Fossil

Check-in Differences
Login

Check-in Differences

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From trunk To release

2024-06-11
18:44
Update the built-in SQLite to a version from the exists-to-join branch in the SQLite source tree, in order to beta-test the exists-to-join optimization. Fossil uses EXISTS operators in the WHERE clause of queries in many places and is therefore a good test case. ... (Leaf check-in: b58b3051 user: drh tags: trunk)
2024-06-09
10:53
Typo fixes reported in forum post 10167c5f79. ... (check-in: 382a61e3 user: stephan tags: trunk)
2024-04-24
21:25
Fix or disable brittle test cases that were broken by changes in 2.23. ... (check-in: 5ad70808 user: drh tags: branch-2.24)
2024-04-23
13:43
Update the homepage for the 2.24 release. ... (check-in: dee02ab6 user: drh tags: trunk)
13:25
Version 2.24 ... (check-in: 8be0372c user: drh tags: trunk, release, version-2.24)
2024-04-22
16:29
cgi.md: be less specific about the Apache version in which the Content-Length change happened because a new forum post reports that it happens at least as far back as 2.4.41. ... (check-in: 9af5f386 user: stephan tags: trunk)

Changes to VERSION.

1
2.25
|
1
2.24

Changes to extsrc/linenoise.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
#line 1 "utf8.h"
#ifndef UTF8_UTIL_H
#define UTF8_UTIL_H

#ifdef __cplusplus
extern "C" {
#endif

/**
 * UTF-8 utility functions
 *
 * (c) 2010-2019 Steve Bennett <steveb@workware.net.au>
 *
 * See utf8.c for licence details.
 */

#ifndef USE_UTF8
#include <ctype.h>

#define MAX_UTF8_LEN 1

/* No utf-8 support. 1 byte = 1 char */
#define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
#define utf8_strwidth(S, B) utf8_strlen((S), (B))
#define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
#define utf8_index(C, I) (I)
#define utf8_charlen(C) 1
 #define utf8_width(C) 1

#else

#define MAX_UTF8_LEN 4

/**
 * Converts the given unicode codepoint (0 - 0x1fffff) to utf-8
 * and stores the result at 'p'.
 *
 * Returns the number of utf-8 characters
 */
int utf8_fromunicode(char *p, unsigned uc);

/**
 * Returns the length of the utf-8 sequence starting with 'c'.
 *
 * Returns 1-4, or -1 if this is not a valid start byte.
 *
 * Note that charlen=4 is not supported by the rest of the API.
 */
int utf8_charlen(int c);

/**
 * Returns the number of characters in the utf-8
 * string of the given byte length.
 *
 * Any bytes which are not part of an valid utf-8
 * sequence are treated as individual characters.
 *
 * The string *must* be null terminated.
 *
 * Does not support unicode code points > \u1fffff
 */
int utf8_strlen(const char *str, int bytelen);

/**
 * Calculates the display width of the first 'charlen' characters in 'str'.
 * See utf8_width()
 */
int utf8_strwidth(const char *str, int charlen);

/**
 * Returns the byte index of the given character in the utf-8 string.
 *
 * The string *must* be null terminated.
 *
 * This will return the byte length of a utf-8 string
 * if given the char length.
 */
int utf8_index(const char *str, int charindex);

/**
 * Returns the unicode codepoint corresponding to the
 * utf-8 sequence 'str'.
 *
 * Stores the result in *uc and returns the number of bytes
 * consumed.
 *
 * If 'str' is null terminated, then an invalid utf-8 sequence
 * at the end of the string will be returned as individual bytes.
 *
 * If it is not null terminated, the length *must* be checked first.
 *
 * Does not support unicode code points > \u1fffff
 */
int utf8_tounicode(const char *str, int *uc);

/**
 * Returns the width (in characters) of the given unicode codepoint.
 * This is 1 for normal letters and 0 for combining characters and 2 for wide characters.
 */
int utf8_width(int ch);

#endif

#ifdef __cplusplus
}
#endif

#endif
#line 1 "utf8.c"
/**
 * UTF-8 utility functions
 *
 * (c) 2010-2019 Steve Bennett <steveb@workware.net.au>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifndef UTF8_UTIL_H
#include "utf8.h"
#endif

#ifdef USE_UTF8
int utf8_fromunicode(char *p, unsigned uc)
{
    if (uc <= 0x7f) {
        *p = uc;
        return 1;
    }
    else if (uc <= 0x7ff) {
        *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
        *p = 0x80 | (uc & 0x3f);
        return 2;
    }
    else if (uc <= 0xffff) {
        *p++ = 0xe0 | ((uc & 0xf000) >> 12);
        *p++ = 0x80 | ((uc & 0xfc0) >> 6);
        *p = 0x80 | (uc & 0x3f);
        return 3;
    }
    /* Note: We silently truncate to 21 bits here: 0x1fffff */
    else {
        *p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
        *p++ = 0x80 | ((uc & 0x3f000) >> 12);
        *p++ = 0x80 | ((uc & 0xfc0) >> 6);
        *p = 0x80 | (uc & 0x3f);
        return 4;
    }
}

int utf8_charlen(int c)
{
    if ((c & 0x80) == 0) {
        return 1;
    }
    if ((c & 0xe0) == 0xc0) {
        return 2;
    }
    if ((c & 0xf0) == 0xe0) {
        return 3;
    }
    if ((c & 0xf8) == 0xf0) {
        return 4;
    }
    /* Invalid sequence */
    return -1;
}

int utf8_strlen(const char *str, int bytelen)
{
    int charlen = 0;
    if (bytelen < 0) {
        bytelen = strlen(str);
    }
    while (bytelen > 0) {
        int c;
        int l = utf8_tounicode(str, &c);
        charlen++;
        str += l;
        bytelen -= l;
    }
    return charlen;
}

int utf8_strwidth(const char *str, int charlen)
{
    int width = 0;
    while (charlen) {
        int c;
        int l = utf8_tounicode(str, &c);
        width += utf8_width(c);
        str += l;
        charlen--;
    }
    return width;
}

int utf8_index(const char *str, int index)
{
    const char *s = str;
    while (index--) {
        int c;
        s += utf8_tounicode(s, &c);
    }
    return s - str;
}

int utf8_tounicode(const char *str, int *uc)
{
    unsigned const char *s = (unsigned const char *)str;

    if (s[0] < 0xc0) {
        *uc = s[0];
        return 1;
    }
    if (s[0] < 0xe0) {
        if ((s[1] & 0xc0) == 0x80) {
            *uc = ((s[0] & ~0xc0) << 6) | (s[1] & ~0x80);
            if (*uc >= 0x80) {
                return 2;
            }
            /* Otherwise this is an invalid sequence */
        }
    }
    else if (s[0] < 0xf0) {
        if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80)) {
            *uc = ((s[0] & ~0xe0) << 12) | ((s[1] & ~0x80) << 6) | (s[2] & ~0x80);
            if (*uc >= 0x800) {
                return 3;
            }
            /* Otherwise this is an invalid sequence */
        }
    }
    else if (s[0] < 0xf8) {
        if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80) && ((str[3] & 0xc0) == 0x80)) {
            *uc = ((s[0] & ~0xf0) << 18) | ((s[1] & ~0x80) << 12) | ((s[2] & ~0x80) << 6) | (s[3] & ~0x80);
            if (*uc >= 0x10000) {
                return 4;
            }
            /* Otherwise this is an invalid sequence */
        }
    }

    /* Invalid sequence, so just return the byte */
    *uc = *s;
    return 1;
}

struct utf8range {
    int lower;     /* lower inclusive */
    int upper;     /* upper exclusive */
};

/* From http://unicode.org/Public/UNIDATA/UnicodeData.txt */
static const struct utf8range unicode_range_combining[] = {
        { 0x0300, 0x0370 },     { 0x0483, 0x048a },     { 0x0591, 0x05d0 },     { 0x0610, 0x061b },
        { 0x064b, 0x0660 },     { 0x0670, 0x0671 },     { 0x06d6, 0x06dd },     { 0x06df, 0x06e5 },
        { 0x06e7, 0x06ee },     { 0x0711, 0x0712 },     { 0x0730, 0x074d },     { 0x07a6, 0x07b1 },
        { 0x07eb, 0x07f4 },     { 0x0816, 0x0830 },     { 0x0859, 0x085e },     { 0x08d4, 0x0904 },
        { 0x093a, 0x0958 },     { 0x0962, 0x0964 },     { 0x0981, 0x0985 },     { 0x09bc, 0x09ce },
        { 0x09d7, 0x09dc },     { 0x09e2, 0x09e6 },     { 0x0a01, 0x0a05 },     { 0x0a3c, 0x0a59 },
        { 0x0a70, 0x0a72 },     { 0x0a75, 0x0a85 },     { 0x0abc, 0x0ad0 },     { 0x0ae2, 0x0ae6 },
        { 0x0afa, 0x0b05 },     { 0x0b3c, 0x0b5c },     { 0x0b62, 0x0b66 },     { 0x0b82, 0x0b83 },
        { 0x0bbe, 0x0bd0 },     { 0x0bd7, 0x0be6 },     { 0x0c00, 0x0c05 },     { 0x0c3e, 0x0c58 },
        { 0x0c62, 0x0c66 },     { 0x0c81, 0x0c85 },     { 0x0cbc, 0x0cde },     { 0x0ce2, 0x0ce6 },
        { 0x0d00, 0x0d05 },     { 0x0d3b, 0x0d4e },     { 0x0d57, 0x0d58 },     { 0x0d62, 0x0d66 },
        { 0x0d82, 0x0d85 },     { 0x0dca, 0x0de6 },     { 0x0df2, 0x0df4 },     { 0x0e31, 0x0e32 },
        { 0x0e34, 0x0e3f },     { 0x0e47, 0x0e4f },     { 0x0eb1, 0x0eb2 },     { 0x0eb4, 0x0ebd },
        { 0x0ec8, 0x0ed0 },     { 0x0f18, 0x0f1a },     { 0x0f35, 0x0f3a },     { 0x0f3e, 0x0f40 },
        { 0x0f71, 0x0f88 },     { 0x0f8d, 0x0fbe },     { 0x0fc6, 0x0fc7 },     { 0x102b, 0x103f },
        { 0x1056, 0x105a },     { 0x105e, 0x1065 },     { 0x1067, 0x106e },     { 0x1071, 0x1075 },
        { 0x1082, 0x1090 },     { 0x109a, 0x109e },     { 0x135d, 0x1360 },     { 0x1712, 0x1720 },
        { 0x1732, 0x1735 },     { 0x1752, 0x1760 },     { 0x1772, 0x1780 },     { 0x17b4, 0x17d4 },
        { 0x17dd, 0x17e0 },     { 0x180b, 0x180e },     { 0x1885, 0x1887 },     { 0x18a9, 0x18aa },
        { 0x1920, 0x1940 },     { 0x1a17, 0x1a1e },     { 0x1a55, 0x1a80 },     { 0x1ab0, 0x1b05 },
        { 0x1b34, 0x1b45 },     { 0x1b6b, 0x1b74 },     { 0x1b80, 0x1b83 },     { 0x1ba1, 0x1bae },
        { 0x1be6, 0x1bfc },     { 0x1c24, 0x1c3b },     { 0x1cd0, 0x1ce9 },     { 0x1ced, 0x1cee },
        { 0x1cf2, 0x1cf5 },     { 0x1cf7, 0x1d00 },     { 0x1dc0, 0x1e00 },     { 0x20d0, 0x2100 },
        { 0x2cef, 0x2cf2 },     { 0x2d7f, 0x2d80 },     { 0x2de0, 0x2e00 },     { 0x302a, 0x3030 },
        { 0x3099, 0x309b },     { 0xa66f, 0xa67e },     { 0xa69e, 0xa6a0 },     { 0xa6f0, 0xa6f2 },
        { 0xa802, 0xa803 },     { 0xa806, 0xa807 },     { 0xa80b, 0xa80c },     { 0xa823, 0xa828 },
        { 0xa880, 0xa882 },     { 0xa8b4, 0xa8ce },     { 0xa8e0, 0xa8f2 },     { 0xa926, 0xa92e },
        { 0xa947, 0xa95f },     { 0xa980, 0xa984 },     { 0xa9b3, 0xa9c1 },     { 0xa9e5, 0xa9e6 },
        { 0xaa29, 0xaa40 },     { 0xaa43, 0xaa44 },     { 0xaa4c, 0xaa50 },     { 0xaa7b, 0xaa7e },
        { 0xaab0, 0xaab5 },     { 0xaab7, 0xaab9 },     { 0xaabe, 0xaac2 },     { 0xaaeb, 0xaaf0 },
        { 0xaaf5, 0xab01 },     { 0xabe3, 0xabf0 },     { 0xfb1e, 0xfb1f },     { 0xfe00, 0xfe10 },
        { 0xfe20, 0xfe30 },
};

/* From http://unicode.org/Public/UNIDATA/EastAsianWidth.txt */
static const struct utf8range unicode_range_wide[] = {
        { 0x1100, 0x115f },     { 0x231a, 0x231b },     { 0x2329, 0x232a },     { 0x23e9, 0x23ec },
        { 0x23f0, 0x23f0 },     { 0x23f3, 0x23f3 },     { 0x25fd, 0x25fe },     { 0x2614, 0x2615 },
        { 0x2648, 0x2653 },     { 0x267f, 0x267f },     { 0x2693, 0x2693 },     { 0x26a1, 0x26a1 },
        { 0x26aa, 0x26ab },     { 0x26bd, 0x26be },     { 0x26c4, 0x26c5 },     { 0x26ce, 0x26ce },
        { 0x26d4, 0x26d4 },     { 0x26ea, 0x26ea },     { 0x26f2, 0x26f3 },     { 0x26f5, 0x26f5 },
        { 0x26fa, 0x26fa },     { 0x26fd, 0x26fd },     { 0x2705, 0x2705 },     { 0x270a, 0x270b },
        { 0x2728, 0x2728 },     { 0x274c, 0x274c },     { 0x274e, 0x274e },     { 0x2753, 0x2755 },
        { 0x2757, 0x2757 },     { 0x2795, 0x2797 },     { 0x27b0, 0x27b0 },     { 0x27bf, 0x27bf },
        { 0x2b1b, 0x2b1c },     { 0x2b50, 0x2b50 },     { 0x2b55, 0x2b55 },     { 0x2e80, 0x2e99 },
        { 0x2e9b, 0x2ef3 },     { 0x2f00, 0x2fd5 },     { 0x2ff0, 0x2ffb },     { 0x3001, 0x303e },
        { 0x3041, 0x3096 },     { 0x3099, 0x30ff },     { 0x3105, 0x312e },     { 0x3131, 0x318e },
        { 0x3190, 0x31ba },     { 0x31c0, 0x31e3 },     { 0x31f0, 0x321e },     { 0x3220, 0x3247 },
        { 0x3250, 0x32fe },     { 0x3300, 0x4dbf },     { 0x4e00, 0xa48c },     { 0xa490, 0xa4c6 },
        { 0xa960, 0xa97c },     { 0xac00, 0xd7a3 },     { 0xf900, 0xfaff },     { 0xfe10, 0xfe19 },
        { 0xfe30, 0xfe52 },     { 0xfe54, 0xfe66 },     { 0xfe68, 0xfe6b },     { 0x16fe0, 0x16fe1 },
        { 0x17000, 0x187ec },   { 0x18800, 0x18af2 },   { 0x1b000, 0x1b11e },   { 0x1b170, 0x1b2fb },
        { 0x1f004, 0x1f004 },   { 0x1f0cf, 0x1f0cf },   { 0x1f18e, 0x1f18e },   { 0x1f191, 0x1f19a },
        { 0x1f200, 0x1f202 },   { 0x1f210, 0x1f23b },   { 0x1f240, 0x1f248 },   { 0x1f250, 0x1f251 },
        { 0x1f260, 0x1f265 },   { 0x1f300, 0x1f320 },   { 0x1f32d, 0x1f335 },   { 0x1f337, 0x1f37c },
        { 0x1f37e, 0x1f393 },   { 0x1f3a0, 0x1f3ca },   { 0x1f3cf, 0x1f3d3 },   { 0x1f3e0, 0x1f3f0 },
        { 0x1f3f4, 0x1f3f4 },   { 0x1f3f8, 0x1f43e },   { 0x1f440, 0x1f440 },   { 0x1f442, 0x1f4fc },
        { 0x1f4ff, 0x1f53d },   { 0x1f54b, 0x1f54e },   { 0x1f550, 0x1f567 },   { 0x1f57a, 0x1f57a },
        { 0x1f595, 0x1f596 },   { 0x1f5a4, 0x1f5a4 },   { 0x1f5fb, 0x1f64f },   { 0x1f680, 0x1f6c5 },
        { 0x1f6cc, 0x1f6cc },   { 0x1f6d0, 0x1f6d2 },   { 0x1f6eb, 0x1f6ec },   { 0x1f6f4, 0x1f6f8 },
        { 0x1f910, 0x1f93e },   { 0x1f940, 0x1f94c },   { 0x1f950, 0x1f96b },   { 0x1f980, 0x1f997 },
        { 0x1f9c0, 0x1f9c0 },   { 0x1f9d0, 0x1f9e6 },   { 0x20000, 0x2fffd },   { 0x30000, 0x3fffd },
};

#define ARRAYSIZE(A) sizeof(A) / sizeof(*(A))

static int cmp_range(const void *key, const void *cm)
{
    const struct utf8range *range = (const struct utf8range *)cm;
    int ch = *(int *)key;
    if (ch < range->lower) {
        return -1;
    }
    if (ch >= range->upper) {
        return 1;
    }
    return 0;
}

static int utf8_in_range(const struct utf8range *range, int num, int ch)
{
    const struct utf8range *r =
        bsearch(&ch, range, num, sizeof(*range), cmp_range);

    if (r) {
        return 1;
    }
    return 0;
}

int utf8_width(int ch)
{
    /* short circuit for common case */
    if (isascii(ch)) {
        return 1;
    }
    if (utf8_in_range(unicode_range_combining, ARRAYSIZE(unicode_range_combining), ch)) {
        return 0;
    }
    if (utf8_in_range(unicode_range_wide, ARRAYSIZE(unicode_range_wide), ch)) {
        return 2;
    }
    return 1;
}
#endif
#line 1 "stringbuf.h"
#ifndef STRINGBUF_H
#define STRINGBUF_H
/**
 * resizable string buffer
 *
 * (c) 2017-2020 Steve Bennett <steveb@workware.net.au>
 *
 * See utf8.c for licence details.
 */
#ifdef __cplusplus
extern "C" {
#endif

/** @file
 * A stringbuf is a resizing, null terminated string buffer.
 *
 * The buffer is reallocated as necessary.
 *
 * In general it is *not* OK to call these functions with a NULL pointer
 * unless stated otherwise.
 *
 * If USE_UTF8 is defined, supports utf8.
 */

/**
 * The stringbuf structure should not be accessed directly.
 * Use the functions below.
 */
typedef struct {
	int remaining;	/**< Allocated, but unused space */
	int last;		/**< Index of the null terminator (and thus the length of the string) */
#ifdef USE_UTF8
	int chars;		/**< Count of characters */
#endif
	char *data;		/**< Allocated memory containing the string or NULL for empty */
} stringbuf;

/**
 * Allocates and returns a new stringbuf with no elements.
 */
stringbuf *sb_alloc(void);

/**
 * Frees a stringbuf.
 * It is OK to call this with NULL.
 */
void sb_free(stringbuf *sb);

/**
 * Returns an allocated copy of the stringbuf
 */
stringbuf *sb_copy(stringbuf *sb);

/**
 * Returns the byte length of the buffer.
 * 
 * Returns 0 for both a NULL buffer and an empty buffer.
 */
static inline int sb_len(stringbuf *sb) {
	return sb->last;
}

/**
 * Returns the utf8 character length of the buffer.
 * 
 * Returns 0 for both a NULL buffer and an empty buffer.
 */
static inline int sb_chars(stringbuf *sb) {
#ifdef USE_UTF8
	return sb->chars;
#else
	return sb->last;
#endif
}

/**
 * Appends a null terminated string to the stringbuf
 */
void sb_append(stringbuf *sb, const char *str);

/**
 * Like sb_append() except does not require a null terminated string.
 * The length of 'str' is given as 'len'
 *
 * Note that in utf8 mode, characters will *not* be counted correctly
 * if a partial utf8 sequence is added with sb_append_len()
 */
void sb_append_len(stringbuf *sb, const char *str, int len);

/**
 * Returns a pointer to the null terminated string in the buffer.
 *
 * Note this pointer only remains valid until the next modification to the
 * string buffer.
 *
 * The returned pointer can be used to update the buffer in-place
 * as long as care is taken to not overwrite the end of the buffer.
 */
static inline char *sb_str(const stringbuf *sb)
{
	return sb->data;
}

/**
 * Inserts the given string *before* (zero-based) byte 'index' in the stringbuf.
 * If index is past the end of the buffer, the string is appended,
 * just like sb_append()
 */
void sb_insert(stringbuf *sb, int index, const char *str);

/**
 * Delete 'len' bytes in the string at the given index.
 *
 * Any bytes past the end of the buffer are ignored.
 * The buffer remains null terminated.
 *
 * If len is -1, deletes to the end of the buffer.
 */
void sb_delete(stringbuf *sb, int index, int len);

/**
 * Clear to an empty buffer.
 */
void sb_clear(stringbuf *sb);

/**
 * Return an allocated copy of buffer and frees 'sb'.
 *
 * If 'sb' is empty, returns an allocated copy of "".
 */
char *sb_to_string(stringbuf *sb);

#ifdef __cplusplus
}
#endif

#endif
#line 1 "stringbuf.c"
/**
 * resizable string buffer
 *
 * (c) 2017-2020 Steve Bennett <steveb@workware.net.au>
 *
 * See utf8.c for licence details.
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>

#ifndef STRINGBUF_H
#include "stringbuf.h"
#endif
#ifdef USE_UTF8
#ifndef UTF8_UTIL_H
#include "utf8.h"
#endif
#endif

#define SB_INCREMENT 200

stringbuf *sb_alloc(void)
{
	stringbuf *sb = (stringbuf *)malloc(sizeof(*sb));
	sb->remaining = 0;
	sb->last = 0;
#ifdef USE_UTF8
	sb->chars = 0;
#endif
	sb->data = NULL;

	return(sb);
}

void sb_free(stringbuf *sb)
{
	if (sb) {
		free(sb->data);
	}
	free(sb);
}

static void sb_realloc(stringbuf *sb, int newlen)
{
	sb->data = (char *)realloc(sb->data, newlen);
	sb->remaining = newlen - sb->last;
}

void sb_append(stringbuf *sb, const char *str)
{
	sb_append_len(sb, str, strlen(str));
}

void sb_append_len(stringbuf *sb, const char *str, int len)
{
	if (sb->remaining < len + 1) {
		sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
	}
	memcpy(sb->data + sb->last, str, len);
	sb->data[sb->last + len] = 0;

	sb->last += len;
	sb->remaining -= len;
#ifdef USE_UTF8
	sb->chars += utf8_strlen(str, len);
#endif
}

char *sb_to_string(stringbuf *sb)
{
	if (sb->data == NULL) {
		/* Return an allocated empty string, not null */
		return strdup("");
	}
	else {
		/* Just return the data and free the stringbuf structure */
		char *pt = sb->data;
		free(sb);
		return pt;
	}
}

/* Insert and delete operations */

/* Moves up all the data at position 'pos' and beyond by 'len' bytes
 * to make room for new data
 *
 * Note: Does *not* update sb->chars
 */
static void sb_insert_space(stringbuf *sb, int pos, int len)
{
	assert(pos <= sb->last);

	/* Make sure there is enough space */
	if (sb->remaining < len) {
		sb_realloc(sb, sb->last + len + SB_INCREMENT);
	}
	/* Now move it up */
	memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
	sb->last += len;
	sb->remaining -= len;
	/* And null terminate */
	sb->data[sb->last] = 0;
}

/**
 * Move down all the data from pos + len, effectively
 * deleting the data at position 'pos' of length 'len'
 */
static void sb_delete_space(stringbuf *sb, int pos, int len)
{
	assert(pos < sb->last);
	assert(pos + len <= sb->last);

#ifdef USE_UTF8
	sb->chars -= utf8_strlen(sb->data + pos, len);
#endif

	/* Now move it up */
	memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
	sb->last -= len;
	sb->remaining += len;
	/* And null terminate */
	sb->data[sb->last] = 0;
}

void sb_insert(stringbuf *sb, int index, const char *str)
{
	if (index >= sb->last) {
		/* Inserting after the end of the list appends. */
		sb_append(sb, str);
	}
	else {
		int len = strlen(str);

		sb_insert_space(sb, index, len);
		memcpy(sb->data + index, str, len);
#ifdef USE_UTF8
		sb->chars += utf8_strlen(str, len);
#endif
	}
}

/**
 * Delete the bytes at index 'index' for length 'len'
 * Has no effect if the index is past the end of the list.
 */
void sb_delete(stringbuf *sb, int index, int len)
{
	if (index < sb->last) {
		char *pos = sb->data + index;
		if (len < 0) {
			len = sb->last;
		}

		sb_delete_space(sb, pos - sb->data, len);
	}
}

void sb_clear(stringbuf *sb)
{
	if (sb->data) {
		/* Null terminate */
		sb->data[0] = 0;
		sb->last = 0;
#ifdef USE_UTF8
		sb->chars = 0;
#endif
	}
}
#line 1 "linenoise.c"
/* linenoise.c -- guerrilla line editing library against the idea that a
 * line editing lib needs to be 20,000 lines of C code.
 *
 * You can find the latest source code at:
 *
 *   http://github.com/msteveb/linenoise
 *   (forked from http://github.com/antirez/linenoise)
 *
 * Does a number of crazy assumptions that happen to be true in 99.9999% of
 * the 2010 UNIX computers around.
 *
 * ------------------------------------------------------------------------
 *
 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





|
<






|
|
<
































































































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6

7
8
9
10
11
12
13
14

15
16
17
18
19
20
21

























































































































































































































































































































































































































































































































































































































































































































/* linenoise.c -- guerrilla line editing library against the idea that a
 * line editing lib needs to be 20,000 lines of C code.
 *
 * You can find the latest source code at:
 *
 *   http://github.com/antirez/linenoise

 *
 * Does a number of crazy assumptions that happen to be true in 99.9999% of
 * the 2010 UNIX computers around.
 *
 * ------------------------------------------------------------------------
 *
 * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>

 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
739
740
741
742
743
744
745




746
747
748
749
750
751
752
753
754
755
756
757
758


759
760
761
762
763
764
765
766
767
768
769

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801


802





803
804

805
806

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850





851
852
853
854
855
856
857
858


859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963

964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016


1017
1018
1019
1020





1021


1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

1032
1033
1034
1035
1036
1037
1038
1039

1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056

1057
1058
1059
1060

1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109

1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132



1133

1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521



1522
1523
1524
1525

1526
1527
1528






1529
1530

1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541


1542

1543



1544
1545
1546
1547
1548
1549

1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568

1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594

1595
1596
1597
1598
1599
1600


1601
1602
1603
1604
1605



1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621



1622
1623
1624
1625
1626
1627

1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642

1643




1644
1645
1646

1647
1648
1649
1650
1651
1652
1653


1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680




1681
1682
1683
1684
1685
1686

1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720

1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733


1734
1735
1736
1737

1738
1739


1740

1741
1742
1743
1744
1745
1746
1747
1748
1749
1750



1751



1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793

1794
1795
1796
1797
1798
1799
1800

1801


1802



1803

1804
1805


1806
1807


1808
1809
1810
1811
1812
1813


1814
1815
1816
1817
1818
1819
1820
1821

1822
1823


1824
1825
1826
1827
1828
1829
1830
1831



1832





1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853

1854



1855

1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867

1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899

1900
1901
1902
1903

1904


1905
1906
1907

1908
1909
1910


1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921

1922
1923
1924

1925
1926

1927
1928
1929
1930
1931

1932




1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979

1980
1981
1982




1983
1984
1985
1986
1987
1988

1989
1990

1991
1992
1993
1994
1995
1996

1997
1998

1999


2000


2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016

2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031



2032
2033
2034





2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045


2046
2047



2048
2049
2050
2051
2052
2053


2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066

2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083


2084

2085
2086
2087
2088
2089

2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107


2108
2109
2110
2111
2112
2113
2114


2115
2116
2117
2118
2119
2120
2121
2122
2123



2124
2125
2126
2127
2128
2129
2130
2131
2132
2133

2134
2135
2136
2137
2138
2139

2140
2141
2142
2143
2144
2145
2146
2147
2148

2149
2150

2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171


2172
2173
2174
2175
2176
2177
2178
2179
2180
2181

2182
2183
2184
2185

2186
2187

2188
2189
2190

2191
2192
2193
2194
2195
2196

2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216

2217
2218


2219

2220
2221
2222
2223
2224
2225
2226
2227


2228


2229

2230

2231
2232
2233
2234
2235
2236
2237
2238


2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255

2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266


2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284

2285
2286






2287
2288
2289
2290
2291

2292

2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303

2304
2305

2306
2307

2308
2309
2310
2311



2312
2313
2314
2315
2316


2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332


2333
2334
2335
2336
2337
2338
2339
2340

2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384


2385
2386


2387
2388

2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422




2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437




2438
2439
2440







2441





2442



2443
2444

2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455




2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468


2469
2470
2471
2472
2473
2474
2475


2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487







2488
2489
2490
2491
2492
2493

2494
2495
2496
2497
2498
2499
2500
2501
2502


2503


2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518

2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546






2547

2548
2549


2550


2551
2552
2553

2554

2555
2556

2557




2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590

2591


2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622


2623
2624
2625
2626

2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643

2644
2645
2646
2647
2648
2649

2650
2651


2652
2653
2654
2655
2656
2657
2658



2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684

2685
2686
2687
2688
2689
2690
2691
2692

2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705

2706
2707
2708


2709

2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761

2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
 *
 * ------------------------------------------------------------------------
 *
 * References:
 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
 *




 * Bloat:
 * - Completion?
 *
 * Unix/termios
 * ------------
 * List of escape sequences used by this program, we do everything just
 * a few sequences. In order to be so cheap we may have some
 * flickering effect with some slow terminal, but the lesser sequences
 * the more compatible.
 *
 * EL (Erase Line)
 *    Sequence: ESC [ 0 K
 *    Effect: clear from cursor to end of line


 *
 * CUF (CUrsor Forward)
 *    Sequence: ESC [ n C
 *    Effect: moves cursor forward n chars
 *
 * CR (Carriage Return)
 *    Sequence: \r
 *    Effect: moves cursor to column 1
 *
 * The following are used to clear the screen: ESC [ H ESC [ 2 J
 * This is actually composed of two sequences:

 *
 * cursorhome
 *    Sequence: ESC [ H
 *    Effect: moves the cursor to upper left corner
 *
 * ED2 (Clear entire screen)
 *    Sequence: ESC [ 2 J
 *    Effect: clear the whole screen
 *
 * == For highlighting control characters, we also use the following two ==
 * SO (enter StandOut)
 *    Sequence: ESC [ 7 m
 *    Effect: Uses some standout mode such as reverse video
 *
 * SE (Standout End)
 *    Sequence: ESC [ 0 m
 *    Effect: Exit standout mode
 *
 * == Only used if TIOCGWINSZ fails ==
 * DSR/CPR (Report cursor position)
 *    Sequence: ESC [ 6 n
 *    Effect: reports current cursor position as ESC [ NNN ; MMM R
 *
 * == Only used in multiline mode ==
 * CUU (Cursor Up)
 *    Sequence: ESC [ n A
 *    Effect: moves cursor up n chars.
 *
 * CUD (Cursor Down)
 *    Sequence: ESC [ n B
 *    Effect: moves cursor down n chars.
 *


 * win32/console





 * -------------
 * If __MINGW32__ is defined, the win32 console API is used.

 * This could probably be made to work for the msvc compiler too.
 * This support based in part on work by Jon Griffiths.

 */

#ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
#include <windows.h>
#include <fcntl.h>
#define USE_WINCONSOLE
#ifdef __MINGW32__
#define HAVE_UNISTD_H
#endif
#else
#include <termios.h>
#include <sys/ioctl.h>
#include <poll.h>
#define USE_TERMIOS
#define HAVE_UNISTD_H
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>

#if defined(_WIN32) && !defined(__MINGW32__)
/* Microsoft headers don't like old POSIX names */
#define strdup _strdup
#define snprintf _snprintf
#endif

#include "linenoise.h"
#ifndef STRINGBUF_H
#include "stringbuf.h"
#endif
#ifndef UTF8_UTIL_H
#include "utf8.h"
#endif






#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100

/* ctrl('A') -> 0x01 */
#define ctrl(C) ((C) - '@')
/* meta('a') ->  0xe1 */
#define meta(C) ((C) | 0x80)

/* Use -ve numbers here to co-exist with normal unicode chars */


enum {
    SPECIAL_NONE,
    /* don't use -1 here since that indicates error */
    SPECIAL_UP = -20,
    SPECIAL_DOWN = -21,
    SPECIAL_LEFT = -22,
    SPECIAL_RIGHT = -23,
    SPECIAL_DELETE = -24,
    SPECIAL_HOME = -25,
    SPECIAL_END = -26,
    SPECIAL_INSERT = -27,
    SPECIAL_PAGE_UP = -28,
    SPECIAL_PAGE_DOWN = -29,

    /* Some handy names for other special keycodes */
    CHAR_ESCAPE = 27,
    CHAR_DELETE = 127,
};

static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int history_len = 0;
static int history_index = 0;
static char **history = NULL;

/* Structure to contain the status of the current (being edited) line */
struct current {
    stringbuf *buf; /* Current buffer. Always null terminated */
    int pos;    /* Cursor position, measured in chars */
    int cols;   /* Size of the window, in chars */
    int nrows;  /* How many rows are being used in multiline mode (>= 1) */
    int rpos;   /* The current row containing the cursor - multiline mode only */
    int colsright; /* refreshLine() cached cols for insert_char() optimisation */
    int colsleft;  /* refreshLine() cached cols for remove_char() optimisation */
    const char *prompt;
    stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
    stringbuf *output;  /* used only during refreshLine() - output accumulator */
#if defined(USE_TERMIOS)
    int fd;     /* Terminal fd */
#elif defined(USE_WINCONSOLE)
    HANDLE outh; /* Console output handle */
    HANDLE inh; /* Console input handle */
    int rows;   /* Screen rows */
    int x;      /* Current column during output */
    int y;      /* Current row */
#ifdef USE_UTF8
    #define UBUF_MAX_CHARS 132
    WORD ubuf[UBUF_MAX_CHARS + 1];  /* Accumulates utf16 output - one extra for final surrogate pairs */
    int ubuflen;      /* length used in ubuf */
    int ubufcols;     /* how many columns are represented by the chars in ubuf? */
#endif
#endif
};

static int fd_read(struct current *current);
static int getWindowSize(struct current *current);
static void cursorDown(struct current *current, int n);
static void cursorUp(struct current *current, int n);
static void eraseEol(struct current *current);
static void refreshLine(struct current *current);
static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
static void setCursorPos(struct current *current, int x);
static void setOutputHighlight(struct current *current, const int *props, int nprops);
static void set_current(struct current *current, const char *str);

static int fd_isatty(struct current *current)
{
#ifdef USE_TERMIOS
    return isatty(current->fd);
#else
    (void)current;
    return 0;
#endif
}

void linenoiseHistoryFree(void) {
    if (history) {
        int j;

        for (j = 0; j < history_len; j++)
            free(history[j]);
        free(history);
        history = NULL;
        history_len = 0;
    }
}

typedef enum {
    EP_START,   /* looking for ESC */
    EP_ESC,     /* looking for [ */
    EP_DIGITS,  /* parsing digits */
    EP_PROPS,   /* parsing digits or semicolons */
    EP_END,     /* ok */
    EP_ERROR,   /* error */
} ep_state_t;

struct esc_parser {
    ep_state_t state;
    int props[5];   /* properties are stored here */
    int maxprops;   /* size of the props[] array */
    int numprops;   /* number of properties found */
    int termchar;   /* terminator char, or 0 for any alpha */
    int current;    /* current (partial) property value */
};

/**

 * Initialise the escape sequence parser at *parser.
 *
 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
 * char terminates successfully.
 * Run the parser state machine with calls to parseEscapeSequence() for each char.
 */
static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
{
    parser->state = EP_START;
    parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
    parser->numprops = 0;
    parser->current = 0;
    parser->termchar = termchar;
}

/**
 * Pass character 'ch' into the state machine to parse:
 *   'ESC' '[' <digits> (';' <digits>)* <termchar>
 *
 * The first character must be ESC.
 * Returns the current state. The state machine is done when it returns either EP_END
 * or EP_ERROR.
 *
 * On EP_END, the "property/attribute" values can be read from parser->props[]
 * of length parser->numprops.
 */
static int parseEscapeSequence(struct esc_parser *parser, int ch)
{
    switch (parser->state) {
        case EP_START:
            parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
            break;
        case EP_ESC:
            parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
            break;
        case EP_PROPS:
            if (ch == ';') {
                parser->state = EP_DIGITS;
donedigits:
                if (parser->numprops + 1 < parser->maxprops) {
                    parser->props[parser->numprops++] = parser->current;
                    parser->current = 0;
                }
                break;
            }
            /* fall through */
        case EP_DIGITS:
            if (ch >= '0' && ch <= '9') {
                parser->current = parser->current * 10 + (ch - '0');
                parser->state = EP_PROPS;
                break;
            }
            /* must be terminator */


            if (parser->termchar != ch) {
                if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
                    parser->state = EP_ERROR;
                    break;





                }


            }
            parser->state = EP_END;
            goto donedigits;
        case EP_END:
            parser->state = EP_ERROR;
            break;
        case EP_ERROR:
            break;
    }
    return parser->state;

}

/*#define DEBUG_REFRESHLINE*/

#ifdef DEBUG_REFRESHLINE
#define DRL(ARGS...) fprintf(dfh, ARGS)
static FILE *dfh;


static void DRL_CHAR(int ch)
{
    if (ch < ' ') {
        DRL("^%c", ch + '@');
    }
    else if (ch > 127) {
        DRL("\\u%04x", ch);
    }
    else {
        DRL("%c", ch);
    }
}
static void DRL_STR(const char *str)
{
    while (*str) {
        int ch;
        int n = utf8_tounicode(str, &ch);

        str += n;
        DRL_CHAR(ch);
    }
}

#else
#define DRL(...)
#define DRL_CHAR(ch)
#define DRL_STR(str)
#endif

#if defined(USE_WINCONSOLE)
#include "linenoise-win32.c"
#endif

#if defined(USE_TERMIOS)
static void linenoiseAtExit(void);
static struct termios orig_termios; /* in order to restore at exit */
static int rawmode = 0; /* for atexit() function to check if restore is needed*/
static int atexit_registered = 0; /* register atexit just 1 time */

static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};

static int isUnsupportedTerm(void) {
    char *term = getenv("TERM");


    if (term) {
        int j;
        for (j = 0; unsupported_term[j]; j++) {
            if (strcmp(term, unsupported_term[j]) == 0) {
                return 1;
            }
        }
    }
    return 0;
}

static int enableRawMode(struct current *current) {
    struct termios raw;

    current->fd = STDIN_FILENO;
    current->cols = 0;

    if (!isatty(current->fd) || isUnsupportedTerm() ||
        tcgetattr(current->fd, &orig_termios) == -1) {
fatal:
        errno = ENOTTY;
        return -1;
    }

    if (!atexit_registered) {
        atexit(linenoiseAtExit);
        atexit_registered = 1;
    }


    raw = orig_termios;  /* modify the original mode */
    /* input modes: no break, no CR to NL, no parity check, no strip char,
     * no start/stop output control. */
    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    /* output modes - actually, no need to disable post processing */
    /*raw.c_oflag &= ~(OPOST);*/
    /* control modes - set 8 bit chars */
    raw.c_cflag |= (CS8);
    /* local modes - choing off, canonical off, no extended functions,
     * no signal chars (^Z,^C) */
    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    /* control chars - set return condition: min number of bytes and timer.
     * We want read to return every single byte, without timeout. */
    raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */

    /* put terminal in raw mode after flushing */
    if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
        goto fatal;
    }
    rawmode = 1;
    return 0;
}





static void disableRawMode(struct current *current) {
    /* Don't even check the return value as it's too late. */
    if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
        rawmode = 0;
}

/* At exit we'll try to fix the terminal to the initial conditions. */
static void linenoiseAtExit(void) {
    if (rawmode) {
        tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
    }
    linenoiseHistoryFree();
}

/* gcc/glibc insists that we care about the return code of write!
 * Clarification: This means that a void-cast like "(void) (EXPR)"
 * does not work.
 */
#define IGNORE_RC(EXPR) if (EXPR) {}

/**
 * Output bytes directly, or accumulate output (if current->output is set)
 */
static void outputChars(struct current *current, const char *buf, int len)
{
    if (len < 0) {
        len = strlen(buf);
    }
    if (current->output) {
        sb_append_len(current->output, buf, len);
    }
    else {
        IGNORE_RC(write(current->fd, buf, len));
    }
}

/* Like outputChars, but using printf-style formatting
 */
static void outputFormatted(struct current *current, const char *format, ...)
{
    va_list args;
    char buf[64];
    int n;

    va_start(args, format);
    n = vsnprintf(buf, sizeof(buf), format, args);
    /* This will never happen because we are sure to use outputFormatted() only for short sequences */
    assert(n < (int)sizeof(buf));
    va_end(args);
    outputChars(current, buf, n);
}

static void cursorToLeft(struct current *current)
{
    outputChars(current, "\r", -1);
}

static void setOutputHighlight(struct current *current, const int *props, int nprops)
{
    outputChars(current, "\x1b[", -1);
    while (nprops--) {
        outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
        props++;
    }
}

static void eraseEol(struct current *current)
{
    outputChars(current, "\x1b[0K", -1);
}

static void setCursorPos(struct current *current, int x)
{
    if (x == 0) {
        cursorToLeft(current);
    }
    else {
        outputFormatted(current, "\r\x1b[%dC", x);
    }
}

static void cursorUp(struct current *current, int n)
{
    if (n) {
        outputFormatted(current, "\x1b[%dA", n);
    }
}

static void cursorDown(struct current *current, int n)
{
    if (n) {
        outputFormatted(current, "\x1b[%dB", n);
    }
}

void linenoiseClearScreen(void)
{
    IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
}

/**
 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
 *
 * A timeout of -1 means to wait forever.
 *
 * Returns -1 if no char is received within the time or an error occurs.
 */
static int fd_read_char(int fd, int timeout)
{
    struct pollfd p;
    unsigned char c;

    p.fd = fd;
    p.events = POLLIN;

    if (poll(&p, 1, timeout) == 0) {
        /* timeout */
        return -1;
    }
    if (read(fd, &c, 1) != 1) {
        return -1;
    }
    return c;
}

/**
 * Reads a complete utf-8 character
 * and returns the unicode value, or -1 on error.
 */
static int fd_read(struct current *current)
{
#ifdef USE_UTF8
    char buf[MAX_UTF8_LEN];
    int n;
    int i;
    int c;

    if (read(current->fd, &buf[0], 1) != 1) {
        return -1;
    }
    n = utf8_charlen(buf[0]);
    if (n < 1) {
        return -1;
    }
    for (i = 1; i < n; i++) {
        if (read(current->fd, &buf[i], 1) != 1) {
            return -1;
        }
    }
    /* decode and return the character */
    utf8_tounicode(buf, &c);
    return c;
#else
    return fd_read_char(current->fd, -1);
#endif
}


/**
 * Stores the current cursor column in '*cols'.
 * Returns 1 if OK, or 0 if failed to determine cursor pos.
 */
static int queryCursor(struct current *current, int* cols)
{
    struct esc_parser parser;
    int ch;

    /* Should not be buffering this output, it needs to go immediately */
    assert(current->output == NULL);

    /* control sequence - report cursor location */
    outputChars(current, "\x1b[6n", -1);

    /* Parse the response: ESC [ rows ; cols R */
    initParseEscapeSeq(&parser, 'R');
    while ((ch = fd_read_char(current->fd, 100)) > 0) {
        switch (parseEscapeSequence(&parser, ch)) {
            default:
                continue;
            case EP_END:
                if (parser.numprops == 2 && parser.props[1] < 1000) {
                    *cols = parser.props[1];
                    return 1;
                }
                break;
            case EP_ERROR:
                break;
        }
        /* failed */
        break;
    }
    return 0;
}

/**
 * Updates current->cols with the current window size (width)
 */
static int getWindowSize(struct current *current)
{
    struct winsize ws;

    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
        current->cols = ws.ws_col;
        return 0;
    }

    /* Failed to query the window size. Perhaps we are on a serial terminal.
     * Try to query the width by sending the cursor as far to the right
     * and reading back the cursor position.
     * Note that this is only done once per call to linenoise rather than
     * every time the line is refreshed for efficiency reasons.
     *
     * In more detail, we:
     * (a) request current cursor position,
     * (b) move cursor far right,
     * (c) request cursor position again,
     * (d) at last move back to the old position.
     * This gives us the width without messing with the externally
     * visible cursor position.
     */

    if (current->cols == 0) {
        int here;

        /* If anything fails => default 80 */
        current->cols = 80;

        /* (a) */
        if (queryCursor (current, &here)) {
            /* (b) */
            setCursorPos(current, 999);

            /* (c). Note: If (a) succeeded, then (c) should as well.
             * For paranoia we still check and have a fallback action
             * for (d) in case of failure..
             */
            if (queryCursor (current, &current->cols)) {
                /* (d) Reset the cursor back to the original location. */
                if (current->cols > here) {
                    setCursorPos(current, here);
                }
            }
        }
    }

    return 0;
}

/**
 * If CHAR_ESCAPE was received, reads subsequent
 * chars to determine if this is a known special key.
 *
 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
 *
 * If no additional char is received within a short time,
 * CHAR_ESCAPE is returned.
 */
static int check_special(int fd)
{
    int c = fd_read_char(fd, 50);
    int c2;

    if (c < 0) {
        return CHAR_ESCAPE;
    }
    else if (c >= 'a' && c <= 'z') {
        /* esc-a => meta-a */
        return meta(c);
    }

    c2 = fd_read_char(fd, 50);
    if (c2 < 0) {
        return c2;
    }
    if (c == '[' || c == 'O') {
        /* Potential arrow key */
        switch (c2) {
            case 'A':
                return SPECIAL_UP;
            case 'B':
                return SPECIAL_DOWN;
            case 'C':
                return SPECIAL_RIGHT;
            case 'D':
                return SPECIAL_LEFT;
            case 'F':
                return SPECIAL_END;
            case 'H':
                return SPECIAL_HOME;
        }
    }
    if (c == '[' && c2 >= '1' && c2 <= '8') {
        /* extended escape */
        c = fd_read_char(fd, 50);
        if (c == '~') {
            switch (c2) {
                case '2':
                    return SPECIAL_INSERT;
                case '3':
                    return SPECIAL_DELETE;
                case '5':
                    return SPECIAL_PAGE_UP;
                case '6':
                    return SPECIAL_PAGE_DOWN;
                case '7':
                    return SPECIAL_HOME;
                case '8':
                    return SPECIAL_END;
            }
        }
        while (c != -1 && c != '~') {
            /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
            c = fd_read_char(fd, 50);
        }
    }

    return SPECIAL_NONE;
}
#endif

static void clearOutputHighlight(struct current *current)
{
    int nohighlight = 0;
    setOutputHighlight(current, &nohighlight, 1);
}

static void outputControlChar(struct current *current, char ch)
{
    int reverse = 7;
    setOutputHighlight(current, &reverse, 1);
    outputChars(current, "^", 1);
    outputChars(current, &ch, 1);
    clearOutputHighlight(current);
}

#ifndef utf8_getchars
static int utf8_getchars(char *buf, int c)
{
#ifdef USE_UTF8
    return utf8_fromunicode(buf, c);
#else
    *buf = c;
    return 1;
#endif
}
#endif

/**
 * Returns the unicode character at the given offset,
 * or -1 if none.
 */
static int get_char(struct current *current, int pos)
{
    if (pos >= 0 && pos < sb_chars(current->buf)) {
        int c;
        int i = utf8_index(sb_str(current->buf), pos);
        (void)utf8_tounicode(sb_str(current->buf) + i, &c);
        return c;
    }
    return -1;
}

static int char_display_width(int ch)
{
    if (ch < ' ') {
        /* control chars take two positions */
        return 2;
    }
    else {
        return utf8_width(ch);
    }
}

#ifndef NO_COMPLETION
static linenoiseCompletionCallback *completionCallback = NULL;
static void *completionUserdata = NULL;
static int showhints = 1;
static linenoiseHintsCallback *hintsCallback = NULL;
static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
static void *hintsUserdata = NULL;

static void beep(void) {
#ifdef USE_TERMIOS
    fprintf(stderr, "\x7");
    fflush(stderr);
#endif
}




static void freeCompletions(linenoiseCompletions *lc) {
    size_t i;
    for (i = 0; i < lc->len; i++)
        free(lc->cvec[i]);

    free(lc->cvec);
}







static int completeLine(struct current *current) {
    linenoiseCompletions lc = { 0, NULL };

    int c = 0;

    completionCallback(sb_str(current->buf),&lc,completionUserdata);
    if (lc.len == 0) {
        beep();
    } else {
        size_t stop = 0, i = 0;

        while(!stop) {
            /* Show completion or original buffer */
            if (i < lc.len) {


                int chars = utf8_strlen(lc.cvec[i], -1);

                refreshLineAlt(current, current->prompt, lc.cvec[i], chars);



            } else {
                refreshLine(current);
            }

            c = fd_read(current);
            if (c == -1) {

                break;
            }

            switch(c) {
                case '\t': /* tab */
                    i = (i+1) % (lc.len+1);
                    if (i == lc.len) beep();
                    break;
                case CHAR_ESCAPE: /* escape */
                    /* Re-show original buffer */
                    if (i < lc.len) {
                        refreshLine(current);
                    }
                    stop = 1;
                    break;
                default:
                    /* Update buffer and return */
                    if (i < lc.len) {
                        set_current(current,lc.cvec[i]);

                    }
                    stop = 1;
                    break;
            }
        }
    }

    freeCompletions(&lc);
    return c; /* Return last read character */
}

/* Register a callback function to be called for tab-completion.
   Returns the prior callback so that the caller may (if needed)
   restore it when done. */
linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
    linenoiseCompletionCallback * old = completionCallback;
    completionCallback = fn;
    completionUserdata = userdata;
    return old;
}

void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
    lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
    lc->cvec[lc->len++] = strdup(str);
}


void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
{
    hintsCallback = callback;
    hintsUserdata = userdata;
}



void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
{
    freeHintsCallback = callback;
}




#endif


static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
{
    /* We have availcols columns available.
     * If necessary, strip chars off the front of buf until *cursor_pos
     * fits within availcols
     */
    int needcols = 0;
    int pos = 0;
    int new_cursor_pos = *cursor_pos;
    const char *pt = buf;

    DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);




    while (*pt) {
        int ch;
        int n = utf8_tounicode(pt, &ch);
        pt += n;

        needcols += char_display_width(ch);


        /* If we need too many cols, strip
         * chars off the front of buf to make it fit.
         * We keep 3 extra cols to the right of the cursor.
         * 2 for possible wide chars, 1 for the last column that
         * can't be used.
         */
        while (needcols >= availcols - 3) {
            n = utf8_tounicode(buf, &ch);
            buf += n;
            needcols -= char_display_width(ch);
            DRL_CHAR(ch);

            /* and adjust the apparent cursor position */
            new_cursor_pos--;






            if (buf == pt) {
                /* can't remove more than this */
                break;

            }
        }

        if (pos++ == *cursor_pos) {
            break;
        }



    }
    DRL("<snip>");
    DRL_STR(buf);
    DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);

    /* Done, now new_cursor_pos contains the adjusted cursor position
     * and buf points to he adjusted start
     */
    *cursor_pos = new_cursor_pos;
    return buf;
}

static int mlmode = 0;

void linenoiseSetMultiLine(int enableml)
{
    mlmode = enableml;
}

/* Helper of refreshSingleLine() and refreshMultiLine() to show hints
 * to the right of the prompt.
 * Returns 1 if a hint was shown, or 0 if not
 * If 'display' is 0, does no output. Just returns the appropriate return code.
 */
static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
{
    int rc = 0;




    if (showhints && hintsCallback && availcols > 0) {
        int bold = 0;
        int color = -1;
        char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
        if (hint) {
            rc = 1;

            if (display) {
                const char *pt;
                if (bold == 1 && color == -1) color = 37;
                if (bold || color > 0) {
                    int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
                    setOutputHighlight(current, props, 3);
                }
                DRL("<hint bold=%d,color=%d>", bold, color);
                pt = hint;
                while (*pt) {
                    int ch;
                    int n = utf8_tounicode(pt, &ch);
                    int width = char_display_width(ch);

                    if (width >= availcols) {
                        DRL("<hinteol>");
                        break;
                    }
                    DRL_CHAR(ch);

                    availcols -= width;
                    outputChars(current, pt, n);
                    pt += n;
                }
                if (bold || color > 0) {
                    clearOutputHighlight(current);
                }
                /* Call the function to free the hint returned. */
                if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
            }
        }
    }
    return rc;
}


#ifdef USE_TERMIOS
static void refreshStart(struct current *current)
{
    /* We accumulate all output here */
    assert(current->output == NULL);
    current->output = sb_alloc();
}

static void refreshEnd(struct current *current)
{
    /* Output everything at once */
    IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));


    sb_free(current->output);
    current->output = NULL;
}


static void refreshStartChars(struct current *current)
{


    (void)current;

}

static void refreshNewline(struct current *current)
{
    DRL("<nl>");
    outputChars(current, "\n", 1);
}

static void refreshEndChars(struct current *current)
{



    (void)current;



}
#endif

static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
{
    int i;
    const char *pt;
    int displaycol;
    int displayrow;
    int visible;
    int currentpos;
    int notecursor;
    int cursorcol = 0;
    int cursorrow = 0;
    int hint;
    struct esc_parser parser;

#ifdef DEBUG_REFRESHLINE
    dfh = fopen("linenoise.debuglog", "a");
#endif

    /* Should intercept SIGWINCH. For now, just get the size every time */
    getWindowSize(current);

    refreshStart(current);

    DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);

    /* Here is the plan:
     * (a) move the the bottom row, going down the appropriate number of lines
     * (b) move to beginning of line and erase the current line
     * (c) go up one line and do the same, until we have erased up to the first row
     * (d) output the prompt, counting cols and rows, taking into account escape sequences
     * (e) output the buffer, counting cols and rows
     *   (e') when we hit the current pos, save the cursor position
     * (f) move the cursor to the saved cursor position
     * (g) save the current cursor row and number of rows
     */

    /* (a) - The cursor is currently at row rpos */
    cursorDown(current, current->nrows - current->rpos - 1);
    DRL("<cud=%d>", current->nrows - current->rpos - 1);


    /* (b), (c) - Erase lines upwards until we get to the first row */
    for (i = 0; i < current->nrows; i++) {
        if (i) {
            DRL("<cup>");
            cursorUp(current, 1);
        }

        DRL("<clearline>");


        cursorToLeft(current);



        eraseEol(current);

    }
    DRL("\n");



    /* (d) First output the prompt. control sequences don't take up display space */


    pt = prompt;
    displaycol = 0; /* current display column */
    displayrow = 0; /* current display row */
    visible = 1;

    refreshStartChars(current);



    while (*pt) {
        int width;
        int ch;
        int n = utf8_tounicode(pt, &ch);

        if (visible && ch == CHAR_ESCAPE) {
            /* The start of an escape sequence, so not visible */

            visible = 0;
            initParseEscapeSeq(&parser, 'm');


            DRL("<esc-seq-start>");
        }

        if (ch == '\n' || ch == '\r') {
            /* treat both CR and NL the same and force wrap */
            refreshNewline(current);
            displaycol = 0;
            displayrow++;



        }





        else {
            width = visible * utf8_width(ch);

            displaycol += width;
            if (displaycol >= current->cols) {
                /* need to wrap to the next line because of newline or if it doesn't fit
                 * XXX this is a problem in single line mode
                 */
                refreshNewline(current);
                displaycol = width;
                displayrow++;
            }

            DRL_CHAR(ch);
#ifdef USE_WINCONSOLE
            if (visible) {
                outputChars(current, pt, n);
            }
#else
            outputChars(current, pt, n);
#endif

        }



        pt += n;


        if (!visible) {
            switch (parseEscapeSequence(&parser, ch)) {
                case EP_END:
                    visible = 1;
                    setOutputHighlight(current, parser.props, parser.numprops);
                    DRL("<esc-seq-end,numprops=%d>", parser.numprops);
                    break;
                case EP_ERROR:
                    DRL("<esc-seq-err>");
                    visible = 1;
                    break;

            }
        }
    }

    /* Now we are at the first line with all lines erased */
    DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);


    /* (e) output the buffer, counting cols and rows */
    if (mlmode == 0) {
        /* In this mode we may need to trim chars from the start of the buffer until the
         * cursor fits in the window.
         */
        pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
    }
    else {
        pt = buf;
    }

    currentpos = 0;
    notecursor = -1;

    while (*pt) {
        int ch;
        int n = utf8_tounicode(pt, &ch);
        int width = char_display_width(ch);

        if (currentpos == cursor_pos) {
            /* (e') wherever we output this character is where we want the cursor */
            notecursor = 1;
        }


        if (displaycol + width >= current->cols) {
            if (mlmode == 0) {
                /* In single line mode stop once we print as much as we can on one line */
                DRL("<slmode>");

                break;


            }
            /* need to wrap to the next line since it doesn't fit */
            refreshNewline(current);

            displaycol = 0;
            displayrow++;
        }



        if (notecursor == 1) {
            /* (e') Save this position as the current cursor position */
            cursorcol = displaycol;
            cursorrow = displayrow;
            notecursor = 0;
            DRL("<cursor>");
        }

        displaycol += width;


        if (ch < ' ') {
            outputControlChar(current, ch + '@');
        }

        else {
            outputChars(current, pt, n);

        }
        DRL_CHAR(ch);
        if (width != 1) {
            DRL("<w=%d>", width);
        }






        pt += n;
        currentpos++;
    }

    /* If we didn't see the cursor, it is at the current location */
    if (notecursor) {
        DRL("<cursor>");
        cursorcol = displaycol;
        cursorrow = displayrow;
    }

    DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);

    /* (f) show hints */
    hint = refreshShowHints(current, buf, current->cols - displaycol, 1);

    /* Remember how many many cols are available for insert optimisation */
    if (prompt == current->prompt && hint == 0) {
        current->colsright = current->cols - displaycol;
        current->colsleft = displaycol;
    }
    else {
        /* Can't optimise */
        current->colsright = 0;
        current->colsleft = 0;
    }
    DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);

    refreshEndChars(current);

    /* (g) move the cursor to the correct place */
    cursorUp(current, displayrow - cursorrow);
    setCursorPos(current, cursorcol);

    /* (h) Update the number of rows if larger, but never reduce this */
    if (displayrow >= current->nrows) {
        current->nrows = displayrow + 1;
    }
    /* And remember the row that the cursor is on */
    current->rpos = cursorrow;

    refreshEnd(current);

#ifdef DEBUG_REFRESHLINE
    fclose(dfh);
#endif
}


static void refreshLine(struct current *current)
{




    refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
}

static void set_current(struct current *current, const char *str)
{
    sb_clear(current->buf);

    sb_append(current->buf, str);
    current->pos = sb_chars(current->buf);

}

/**
 * Removes the char at 'pos'.
 *
 * Returns 1 if the line needs to be refreshed, 2 if not

 * and 0 if nothing was removed
 */

static int remove_char(struct current *current, int pos)


{


    if (pos >= 0 && pos < sb_chars(current->buf)) {
        int offset = utf8_index(sb_str(current->buf), pos);
        int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
        int rc = 1;

        /* Now we try to optimise in the simple but very common case that:
         * - outputChars() can be used directly (not win32)
         * - we are removing the char at EOL
         * - the buffer is not empty
         * - there are columns available to the left
         * - the char being deleted is not a wide or utf-8 character
         * - no hints are being shown
         */
        if (current->output && current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
#ifdef USE_UTF8
            /* Could implement utf8_prev_len() but simplest just to not optimise this case */

            char last = sb_str(current->buf)[offset];
#else
            char last = 0;
#endif
            if (current->colsleft > 0 && (last & 0x80) == 0) {
                /* Have cols on the left and not a UTF-8 char or continuation */
                /* Yes, can optimise */
                current->colsleft--;
                current->colsright++;
                rc = 2;
            }
        }

        sb_delete(current->buf, offset, nbytes);




        if (current->pos > pos) {
            current->pos--;
        }





        if (rc == 2) {
            if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
                /* A hint needs to be shown, so can't optimise after all */
                rc = 1;
            }
            else {
                /* optimised output */
                outputChars(current, "\b \b", 3);
            }
        }
        return rc;


        return 1;
    }



    return 0;
}

/**
 * Insert 'ch' at position 'pos'
 *


 * Returns 1 if the line needs to be refreshed, 2 if not
 * and 0 if nothing was inserted (no room)
 */
static int insert_char(struct current *current, int pos, int ch)
{
    if (pos >= 0 && pos <= sb_chars(current->buf)) {
        char buf[MAX_UTF8_LEN + 1];
        int offset = utf8_index(sb_str(current->buf), pos);
        int n = utf8_getchars(buf, ch);
        int rc = 1;

        /* null terminate since sb_insert() requires it */
        buf[n] = 0;


        /* Now we try to optimise in the simple but very common case that:
         * - outputChars() can be used directly (not win32)
         * - we are inserting at EOL
         * - there are enough columns available
         * - no hints are being shown
         */
        if (current->output && pos == current->pos && pos == sb_chars(current->buf)) {
            int width = char_display_width(ch);
            if (current->colsright > width) {
                /* Yes, can optimise */
                current->colsright -= width;
                current->colsleft -= width;
                rc = 2;
            }
        }
        sb_insert(current->buf, offset, buf);


        if (current->pos >= pos) {

            current->pos++;
        }
        if (rc == 2) {
            if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
                /* A hint needs to be shown, so can't optimise after all */

                rc = 1;
            }
            else {
                /* optimised output */
                outputChars(current, buf, n);
            }
        }
        return rc;
    }
    return 0;
}

/**
 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
 *
 * This replaces any existing characters in the cut buffer.
 */
static void capture_chars(struct current *current, int pos, int nchars)


{
    if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
        int offset = utf8_index(sb_str(current->buf), pos);
        int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);

        if (nbytes > 0) {
            if (current->capture) {


                sb_clear(current->capture);
            }
            else {
                current->capture = sb_alloc();
            }
            sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
        }
    }
}




/**
 * Removes up to 'n' characters at cursor position 'pos'.
 *
 * Returns 0 if no chars were removed or non-zero otherwise.
 */
static int remove_chars(struct current *current, int pos, int n)
{
    int removed = 0;


    /* First save any chars which will be removed */
    capture_chars(current, pos, n);

    while (n-- && remove_char(current, pos)) {
        removed++;
    }

    return removed;
}
/**
 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
 *
 * Returns 0 if no chars were inserted or non-zero otherwise.
 */
static int insert_chars(struct current *current, int pos, const char *chars)
{

    int inserted = 0;


    while (*chars) {
        int ch;
        int n = utf8_tounicode(chars, &ch);
        if (insert_char(current, pos, ch) == 0) {
            break;
        }
        inserted++;
        pos++;
        chars += n;
    }
    return inserted;
}

static int skip_space_nonspace(struct current *current, int dir, int check_is_space)
{
    int moved = 0;
    int checkoffset = (dir < 0) ? -1 : 0;
    int limit = (dir < 0) ? 0 : sb_chars(current->buf);
    while (current->pos != limit && (get_char(current, current->pos + checkoffset) == ' ') == check_is_space) {
        current->pos += dir;
        moved++;


    }
    return moved;
}

static int skip_space(struct current *current, int dir)
{
    return skip_space_nonspace(current, dir, 1);
}

static int skip_nonspace(struct current *current, int dir)

{
    return skip_space_nonspace(current, dir, 0);
}


static void set_history_index(struct current *current, int new_index)
{

    if (history_len > 1) {
        /* Update the current history entry before to
         * overwrite it with the next one. */

        free(history[history_len - 1 - history_index]);
        history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
        /* Show the new entry */
        history_index = new_index;
        if (history_index < 0) {
            history_index = 0;

        } else if (history_index >= history_len) {
            history_index = history_len - 1;
        } else {
            set_current(current, history[history_len - 1 - history_index]);
            refreshLine(current);
        }
    }
}

/**
 * Returns the keycode to process, or 0 if none.
 */
static int reverseIncrementalSearch(struct current *current)
{
    /* Display the reverse-i-search prompt and process chars */
    char rbuf[50];
    char rprompt[80];
    int rchars = 0;
    int rlen = 0;
    int searchpos = history_len - 1;

    int c;



    rbuf[0] = 0;

    while (1) {
        int n = 0;
        const char *p = NULL;
        int skipsame = 0;
        int searchdir = -1;

        snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
        refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);


        c = fd_read(current);


        if (c == ctrl('H') || c == CHAR_DELETE) {

            if (rchars) {

                int p_ind = utf8_index(rbuf, --rchars);
                rbuf[p_ind] = 0;
                rlen = strlen(rbuf);
            }
            continue;
        }
#ifdef USE_TERMIOS
        if (c == CHAR_ESCAPE) {


            c = check_special(current->fd);
        }
#endif
        if (c == ctrl('R')) {
            /* Search for the previous (earlier) match */
            if (searchpos > 0) {
                searchpos--;
            }
            skipsame = 1;
        }
        else if (c == ctrl('S')) {
            /* Search for the next (later) match */
            if (searchpos < history_len) {
                searchpos++;
            }
            searchdir = 1;
            skipsame = 1;

        }
        else if (c == ctrl('P') || c == SPECIAL_UP) {
            /* Exit Ctrl-R mode and go to the previous history line from the current search pos */
            set_history_index(current, history_len - searchpos);
            c = 0;
            break;
        }
        else if (c == ctrl('N') || c == SPECIAL_DOWN) {
            /* Exit Ctrl-R mode and go to the next history line from the current search pos */
            set_history_index(current, history_len - searchpos - 2);
            c = 0;


            break;
        }
        else if (c >= ' ' && c <= '~') {
            /* >= here to allow for null terminator */
            if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
                continue;
            }

            n = utf8_getchars(rbuf + rlen, c);
            rlen += n;
            rchars++;
            rbuf[rlen] = 0;

            /* Adding a new char resets the search location */
            searchpos = history_len - 1;
        }
        else {
            /* Exit from incremental search mode */

            break;
        }







        /* Now search through the history for a match */
        for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
            p = strstr(history[searchpos], rbuf);
            if (p) {

                /* Found a match */

                if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
                    /* But it is identical, so skip it */
                    continue;
                }
                /* Copy the matching line and set the cursor position */
                history_index = history_len - 1 - searchpos;
                set_current(current,history[searchpos]);
                current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
                break;
            }
        }

        if (!p && n) {
            /* No match, so don't add it */

            rchars--;
            rlen -= n;

            rbuf[rlen] = 0;
        }
    }
    if (c == ctrl('G') || c == ctrl('C')) {



        /* ctrl-g terminates the search with no effect */
        set_current(current, "");
        history_index = 0;
        c = 0;
    }


    else if (c == ctrl('J')) {
        /* ctrl-j terminates the search leaving the buffer in place */
        history_index = 0;
        c = 0;
    }
    /* Go process the char normally */
    refreshLine(current);
    return c;
}

static int linenoiseEdit(struct current *current) {
    history_index = 0;

    refreshLine(current);

    while(1) {


        int c = fd_read(current);

#ifndef NO_COMPLETION
        /* Only autocomplete when the callback is set. It returns < 0 when
         * there was an error reading from fd. Otherwise it will return the
         * character that should be handled next. */
        if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
            c = completeLine(current);

        }
#endif
        if (c == ctrl('R')) {
            /* reverse incremental search will provide an alternative keycode or 0 for none */
            c = reverseIncrementalSearch(current);
            /* go on to process the returned char normally */
        }

#ifdef USE_TERMIOS
        if (c == CHAR_ESCAPE) {   /* escape sequence */
            c = check_special(current->fd);
        }
#endif
        if (c == -1) {
            /* Return on errors */
            return sb_len(current->buf);
        }

        switch(c) {
        case SPECIAL_NONE:
            break;
        case '\r':    /* enter/CR */
        case '\n':    /* LF */
            history_len--;
            free(history[history_len]);
            current->pos = sb_chars(current->buf);
            if (mlmode || hintsCallback) {
                showhints = 0;
                refreshLine(current);
                showhints = 1;
            }
            return sb_len(current->buf);
        case ctrl('C'):     /* ctrl-c */
            errno = EAGAIN;
            return -1;
        case ctrl('Z'):     /* ctrl-z */
#ifdef SIGTSTP
            /* send ourselves SIGSUSP */
            disableRawMode(current);
            raise(SIGTSTP);
            /* and resume */
            enableRawMode(current);
            refreshLine(current);
#endif


            continue;
        case CHAR_DELETE:   /* backspace */


        case ctrl('H'):
            if (remove_char(current, current->pos - 1) == 1) {

                refreshLine(current);
            }
            break;
        case ctrl('D'):     /* ctrl-d */
            if (sb_len(current->buf) == 0) {
                /* Empty line, so EOF */
                history_len--;
                free(history[history_len]);
                return -1;
            }
            /* Otherwise fall through to delete char to right of cursor */
            /* fall-thru */
        case SPECIAL_DELETE:
            if (remove_char(current, current->pos) == 1) {
                refreshLine(current);
            }
            break;
        case SPECIAL_INSERT:
            /* Ignore. Expansion Hook.
             * Future possibility: Toggle Insert/Overwrite Modes
             */
            break;
        case meta('b'):    /* meta-b, move word left */
            if (skip_nonspace(current, -1)) {
                refreshLine(current);
            }
            else if (skip_space(current, -1)) {
                skip_nonspace(current, -1);
                refreshLine(current);
            }
            break;
        case meta('f'):    /* meta-f, move word right */
            if (skip_space(current, 1)) {
                refreshLine(current);




            }
            else if (skip_nonspace(current, 1)) {
                skip_space(current, 1);
                refreshLine(current);
            }
            break;
        case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
            /* eat any spaces on the left */
            {
                int pos = current->pos;
                while (pos > 0 && get_char(current, pos - 1) == ' ') {
                    pos--;
                }

                /* now eat any non-spaces on the left */




                while (pos > 0 && get_char(current, pos - 1) != ' ') {
                    pos--;
                }













                if (remove_chars(current, pos, current->pos - pos)) {



                    refreshLine(current);
                }

            }
            break;
        case ctrl('T'):    /* ctrl-t */
            if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
                /* If cursor is at end, transpose the previous two chars */
                int fixer = (current->pos == sb_chars(current->buf));
                c = get_char(current, current->pos - fixer);
                remove_char(current, current->pos - fixer);
                insert_char(current, current->pos - 1, c);
                refreshLine(current);
            }




            break;
        case ctrl('V'):    /* ctrl-v */
            /* Insert the ^V first */
            if (insert_char(current, current->pos, c)) {
                refreshLine(current);
                /* Now wait for the next char. Can insert anything except \0 */
                c = fd_read(current);

                /* Remove the ^V first */
                remove_char(current, current->pos - 1);
                if (c > 0) {
                    /* Insert the actual char, can't be error or null */
                    insert_char(current, current->pos, c);


                }
                refreshLine(current);
            }
            break;
        case ctrl('B'):
        case SPECIAL_LEFT:
            if (current->pos > 0) {


                current->pos--;
                refreshLine(current);
            }
            break;
        case ctrl('F'):
        case SPECIAL_RIGHT:
            if (current->pos < sb_chars(current->buf)) {
                current->pos++;
                refreshLine(current);
            }
            break;
        case SPECIAL_PAGE_UP: /* move to start of history */







          set_history_index(current, history_len - 1);
          break;
        case SPECIAL_PAGE_DOWN: /* move to 0 == end of history, i.e. current */
          set_history_index(current, 0);
          break;
        case ctrl('P'):

        case SPECIAL_UP:
            set_history_index(current, history_index + 1);
            break;
        case ctrl('N'):
        case SPECIAL_DOWN:
            set_history_index(current, history_index - 1);
            break;
        case ctrl('A'): /* Ctrl+a, go to the start of the line */
        case SPECIAL_HOME:


            current->pos = 0;


            refreshLine(current);
            break;
        case ctrl('E'): /* ctrl+e, go to the end of the line */
        case SPECIAL_END:
            current->pos = sb_chars(current->buf);
            refreshLine(current);
            break;
        case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
            if (remove_chars(current, 0, current->pos)) {
                refreshLine(current);
            }
            break;
        case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
            if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
                refreshLine(current);

            }
            break;
        case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
            if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
                refreshLine(current);
            }
            break;
        case ctrl('L'): /* Ctrl+L, clear screen */
            linenoiseClearScreen();
            /* Force recalc of window size for serial terminals */
            current->cols = 0;
            current->rpos = 0;
            refreshLine(current);
            break;
        default:
            if (c >= meta('a') && c <= meta('z')) {
                /* Don't insert meta chars that are not bound */
                break;
            }
            /* Only tab is allowed without ^V */
            if (c == '\t' || c >= ' ') {
                if (insert_char(current, current->pos, c) == 1) {
                    refreshLine(current);
                }
            }
            break;
        }
    }






    return sb_len(current->buf);

}



int linenoiseColumns(void)


{
    struct current current;
    current.output = NULL;

    enableRawMode (&current);

    getWindowSize (&current);
    disableRawMode (&current);

    return current.cols;




}

/**
 * Reads a line from the file handle (without the trailing NL or CRNL)
 * and returns it in a stringbuf.
 * Returns NULL if no characters are read before EOF or error.
 *
 * Note that the character count will *not* be correct for lines containing
 * utf8 sequences. Do not rely on the character count.
 */
static stringbuf *sb_getline(FILE *fh)
{
    stringbuf *sb = sb_alloc();
    int c;
    int n = 0;

    while ((c = getc(fh)) != EOF) {
        char ch;
        n++;
        if (c == '\r') {
            /* CRLF -> LF */
            continue;
        }
        if (c == '\n' || c == '\r') {
            break;
        }
        ch = c;
        /* ignore the effect of character count for partial utf8 sequences */
        sb_append_len(sb, &ch, 1);
    }
    if (n == 0 || sb->data == NULL) {
        sb_free(sb);
        return NULL;

    }


    return sb;
}

char *linenoiseWithInitial(const char *prompt, const char *initial)
{
    int count;
    struct current current;
    stringbuf *sb;

    memset(&current, 0, sizeof(current));

    if (enableRawMode(&current) == -1) {
        printf("%s", prompt);
        fflush(stdout);
        sb = sb_getline(stdin);
        if (sb && !fd_isatty(&current)) {
            printf("%s\n", sb_str(sb));
            fflush(stdout);
        }
    }
    else {
        current.buf = sb_alloc();
        current.pos = 0;
        current.nrows = 1;
        current.prompt = prompt;

        /* The latest history entry is always our current buffer */
        linenoiseHistoryAdd(initial);
        set_current(&current, initial);

        count = linenoiseEdit(&current);



        disableRawMode(&current);
        printf("\n");


        sb_free(current.capture);
        if (count == -1) {
            sb_free(current.buf);
            return NULL;
        }
        sb = current.buf;
    }
    return sb ? sb_to_string(sb) : NULL;
}

char *linenoise(const char *prompt)
{
    return linenoiseWithInitial(prompt, "");
}

/* Using a circular buffer is smarter, but a bit more complex to handle. */
static int linenoiseHistoryAddAllocated(char *line) {


    if (history_max_len == 0) {
notinserted:
        free(line);
        return 0;
    }

    if (history == NULL) {
        history = (char **)calloc(sizeof(char*), history_max_len);


    }

    /* do not insert duplicate lines into history */
    if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
        goto notinserted;
    }




    if (history_len == history_max_len) {
        free(history[0]);
        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
        history_len--;
    }
    history[history_len] = line;
    history_len++;
    return 1;
}

int linenoiseHistoryAdd(const char *line) {
    return linenoiseHistoryAddAllocated(strdup(line));
}

int linenoiseHistoryGetMaxLen(void) {
    return history_max_len;
}

int linenoiseHistorySetMaxLen(int len) {
    char **newHistory;

    if (len < 1) return 0;
    if (history) {
        int tocopy = history_len;

        newHistory = (char **)calloc(sizeof(char*), len);


        /* If we can't copy everything, free the elements we'll not use. */
        if (len < tocopy) {
            int j;

            for (j = 0; j < tocopy-len; j++) free(history[j]);
            tocopy = len;
        }

        memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
        free(history);
        history = newHistory;
    }
    history_max_len = len;
    if (history_len > history_max_len)
        history_len = history_max_len;
    return 1;
}

/* Save the history in the specified file. On success 0 is returned
 * otherwise -1 is returned. */
int linenoiseHistorySave(const char *filename) {

    FILE *fp = fopen(filename,"w");
    int j;



    if (fp == NULL) return -1;

    for (j = 0; j < history_len; j++) {
        const char *str = history[j];
        /* Need to encode backslash, nl and cr */
        while (*str) {
            if (*str == '\\') {
                fputs("\\\\", fp);
            }
            else if (*str == '\n') {
                fputs("\\n", fp);
            }
            else if (*str == '\r') {
                fputs("\\r", fp);
            }
            else {
                fputc(*str, fp);
            }
            str++;
        }
        fputc('\n', fp);
    }

    fclose(fp);
    return 0;
}

/* Load the history from the specified file.
 *
 * If the file does not exist or can't be opened, no operation is performed
 * and -1 is returned.
 * Otherwise 0 is returned.
 */
int linenoiseHistoryLoad(const char *filename) {
    FILE *fp = fopen(filename,"r");
    stringbuf *sb;

    if (fp == NULL) return -1;

    while ((sb = sb_getline(fp)) != NULL) {
        /* Take the stringbuf and decode backslash escaped values */
        char *buf = sb_to_string(sb);
        char *dest = buf;
        const char *src;

        for (src = buf; *src; src++) {
            char ch = *src;

            if (ch == '\\') {
                src++;
                if (*src == 'n') {
                    ch = '\n';
                }
                else if (*src == 'r') {

                    ch = '\r';
                } else {
                    ch = *src;
                }
            }
            *dest++ = ch;
        }
        *dest = 0;

        linenoiseHistoryAddAllocated(buf);
    }
    fclose(fp);
    return 0;
}

/* Provide access to the history buffer.
 *
 * If 'len' is not NULL, the length is stored in *len.
 */
char **linenoiseHistory(int *len) {
    if (len) {
        *len = history_len;
    }
    return history;
}







>
>
>
>

|

<
<

|




|
|
>
>





|
|
|

|
<
>

|
|
|
<
<
|
<

|
<
|
<

<
<
<
<
<
<
<
<
<
<


|



|

>
>
|
>
>
>
>
>
|
<
>
|
<
>


<
<
<
<
<
<
<
<

|
|
<
<
<
<
<
|
<
|
|
|
|
|
|
|
|
|
<
<
|
|
|
|
|
|
|
<
<
<
<
<

>
>
>
>
>
|
|
|
<
<
<

|
>
>
|
<
<
|
|
|
|
|
|
|
|
|
|
|
|
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
|
|
|
|
|
|
<
|
|
>
|
|
|
|
|
|
<
<
|
<
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
<
<
<
<
<
<
<
|
<
<
<
<
|
<
<
|
<
|
<
|
<
<
<
>
>
|
<
<
<
>
>
>
>
>
|
>
>
|
|
<
|
<
|
<
<
|
<
>
|
|
<
|
<
<
<
|
>
|
<
<
<
<
<
<
<
|
<
|
|
<
<
|
<
<
>
|
<
|
|
>
|
|
<
<
<
|
<
<
<

<
<
<
<
<
|
<
|


>

|
<
|
|
|
|
|
<
<
<
|
|


|
<
<
<
<
<
<
<
<
<




>





|
|










<
|
<


|
>
>
>
|
>
|

|



<
<
<
<
<
<
<
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
|
<
<
<
<
<
|
|
|
<
<
<
<
<
<
|
|
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
|
<
<
|
<
<
<
<
|
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<

<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
|
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
|
<
<
<
<
<
|
<
<
|
|
<


|
|
<
<
|
<
<
<
<
<
|
<
<
<
|
<
<
|
<
|
<
<

<
<
|
<
<
<
<
|
<
<
<
<
<
<
<
|
<
<
<
<
|
<
|
|
<
<
<
<
<
<
<
<
<
|
<
|
<
|
|
<
<
<
|
<
|
|
<
<
|
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
|
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<

<
<
|
|
|
<
<
<
<
<
<
<
|
|
<


<


>
>
>




>
|


>
>
>
>
>
>
|

>
|

|

|






>
>
|
>
|
>
>
>

|


|
|
>
|



|

|

|

|
<
<





|
>











|
<
<
|
<

<
<


<
<
<
<
|
>
|
<
|
<


>
>
|
<
|


>
>
>
|
|
|
|
<
<
<
<
<
<
<
<
<

<
|
>
>
>
|
|
<
|
|
|
>
|
<
<
<
<
<
<
<
<
<
<
<

<
<
>

>
>
>
>
|
|
|
>
|
<
|
|
|
|

>
>
|
<
|
<
|
<
<
<
|
|


|
|
<
<
<

<
<
<
<
<
<
<
<
|
>
>
>
>
|
<
|
|

|
>
|
<
|
|
<
<
<
|
<
|
<
|
<
|
<
|
<
<
|
|
<
<
<
<
<
<
<
|
|
|
|
|
<
|
>
|
<
<
<
<
|
<
<
|
|
<
<
<
>
>
|
|
<
|
>
|
|
>
>
|
>
|
|
<
<
|
<
|

|
<
>
>
>
|
>
>
>
|
|
|
<
<
|
<
<
<
|
|
|
|
|
<
<
|
<
<
<
|
<
<
|
<
|
<
|
<
<
<
<
<
<
<
<
<
<

<
<
<
>
|
<
|
<
<
|
<
>
|
>
>
|
>
>
>
|
>
|
<
>
>

|
>
>
|
<
<
<
|
<
>
>
|
<
<
<
<

<
<
>
|
<
>
>
|
|

<
<
|
<
<
>
>
>
|
>
>
>
>
>
|
<
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
|
<
<
|
>
|
>
>
>
|
>
|
<
<
|
|
<
<
<
<
|
|
|
>
|
|
<
|
<
<
|
|
<
<
<
<
<
<
|
|
<
<
|
|
<
|
|
<
<
<
|
<
<
<
|
|
>
|
|
<
<
>
|
>
>
|
<
<
>
|
<
|
>
>
|
<
<
<
<
<
<
|
|
<
|
>
|
<
<
>
|
<
>
|
<
<
<
|
>
|
>
>
>
>
|
|
<
|
<
<
<
<
<
<
|
<
|
<
<
|
<
|
|
|
<
|
<
<
|
|
<
|
<
|
<
<
<
|
<
<
|
<
<
|
|
|
|
<
<
<
|
>
|
<
|
>
>
>
>
|
|
|
<
|
|
>
|
|
>
|
|
<
<
|
|
>
|
<
>
|
>
>
|
>
>
|
<
|
|
|
<
<
<
<
<
<
<
<
<
<
<
>
<
<
<
<
<
<
<
<
<
<
|
<
|
<
|
>
>
>
|
|
<
>
>
>
>
>
|
<
<
|
<
<
<
<
<
<
|
>
>
|
|
>
>
>
|
|
|
<
<
|
>
>
|
|
<
<
<
|
<
<
<
<
|
<
|
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
>
>
|
>
|
<
<
<
<
>
|
<
|
<
<
|
|
<
|
<
<
|
<
<
|
<
<
|
>
>
|
<
|
<
|
|
|
>
>
|
<
|
<
|
<
|
<
<
>
>
>
|
|
|

|
<
|

|

>
|
|
|
|
|
<
>
|
<
<
<
<
<
<
<
<
>
|
|
>
|
<
<
<
<
|
|
<
|
<
<
<
|
<
|
<
<
<
<
|
<
>
>
|
|
<
|
<
<
<
<
|
|
>
|
<
<
|
>
<
|
>
|
<
|
>
|
<
|
<
|
<
>
|
<
<
<
<

|
<
|
|
<
<
<
<
<
<
<
<
|
|
>
|
|
>
>
|
>
<
|
<
<
<
|
<
<
>
>
|
>
>
|
>
|
>
|
<
|
<
|
|
<
<
>
>
|
|
|
|
<
|
|
<
|
<
<
<
<
<
<
|
|
>
|
<
<
<
<

<
<
<
<
<
>
>

<
<
<
<
<
<
|
<
|
|
|
|
<
|
<
|
<
>

<
>
>
>
>
>
>

|
<
<
|
>
|
>
|
|
|
<
|
<
<
<
|
|
|
>
|
|
>
|
|
>
|
<
<
|
>
>
>
|
|
|
<
<
>
>
|
|
|
<
|
<
<
<
|
|
<
<

|
|
|
>
>
|
|
<
<
<
<
<
|
>
|
<
<
<
<
<
|
|
|
<
<
<
<
<
<
<
<
|
<
<

|
|
<
<
<
<
|
|
<
<
|
|
|
|
<
<
<
<
<
<
<
|
|
>
>
|
|
>
>
|
<
>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
>
>
>
>
|
<
<
<
|
|
<
<
<
<
<
<
|

<
>
>
>
>
|
<
|
>
>
>
>
>
>
>

>
>
>
>
>
|
>
>
>
|
|
>
|
<
<
<
<
<
<
<
<
<
|
>
>
>
>
<
<
<
<
<
<
<

<
<
|
<
<
>
>
|
<
|
<
<
<
|
>
>
|
|
|
<
<
<
<
<
<
|
<
<
>
>
>
>
>
>
>
|
<
|
<
|
|
>
|
|
|
|
|
|
|
<
<
>
>
|
>
>
|
|
<
|
<
|
|
<
<
<

|
<
<
|
>
|
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
<
<
<
>
>
>
>
>
>
|
>
|
|
>
>
|
>
>
|
|
|
>
|
>
|
|
>
|
>
>
>
>
|
|
<
<
<
<
|
|
|
|
<
<
|
<
<
|
<
<
<
<
<
<
<
<
|
|
<
<
<
|
<
<
<
>
|
>
>
|
<
|
<
<
|
<
<

<
|
<
<
|
<
<
<
|
|
|
<
<
<
<
<

<
<
<
|
|
>
>
|
<
<

>
|
|
|
<
<
<
<
<
<
|
<
<
<
<
|
|
|
>

|
<
<
<
|
>

|
>
>


|
|
<
|
|
>
>
>





|




|
<
<
|
<
|
<
|

|





|
>








>
|

|










>
|


>
>

>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
<
|
<
<
<
<
<
<
<
<
|
|
|
<
<
|
|
<
|

|
<
<
<
|
<
>
|
<
<
|
<
|
<
|
|
|



<
<
<
<
<
<
<
<
<
<
<

40
41
42
43
44
45
46
47
48
49
50
51
52
53


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

74
75
76
77
78


79

80
81

82

83










84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

101
102

103
104
105








106
107
108





109

110
111
112
113
114
115
116
117
118


119
120
121
122
123
124
125





126
127
128
129
130
131
132
133
134



135
136
137
138
139


140
141
142
143
144
145
146
147
148
149
150
151


152












































































153
154
155
156
157
158
159
160

161
162
163
164
165
166
167
168
169


170

171
172
173
174













175
176
177







178




179


180

181

182



183
184
185



186
187
188
189
190
191
192
193
194
195

196

197


198

199
200
201

202



203
204
205







206

207
208


209


210
211

212
213
214
215
216



217



218





219

220
221
222
223
224
225

226
227
228
229
230



231
232
233
234
235









236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

258

259
260
261
262
263
264
265
266
267
268
269
270
271
272







273





274








275






276





277
278
279






280
281




282













































283








284


285




286




287











288


289





290









291
292
293








294















295
296



297





298


299
300

301
302
303
304


305





306



307


308

309


310


311




312







313




314

315
316









317

318

319
320



321

322
323


324




325
326










327


















328






329
330
331



















332
333

334





335














336





337


338
339
340







341
342

343
344

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403


404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422


423

424


425
426




427
428
429

430

431
432
433
434
435

436
437
438
439
440
441
442
443
444
445









446

447
448
449
450
451
452

453
454
455
456
457











458


459
460
461
462
463
464
465
466
467
468
469

470
471
472
473
474
475
476
477

478

479



480
481
482
483
484
485



486








487
488
489
490
491
492

493
494
495
496
497
498

499
500



501

502

503

504

505


506
507







508
509
510
511
512

513
514
515




516


517
518



519
520
521
522

523
524
525
526
527
528
529
530
531
532


533

534
535
536

537
538
539
540
541
542
543
544
545
546


547



548
549
550
551
552


553



554


555

556

557










558



559
560

561


562

563
564
565
566
567
568
569
570
571
572
573

574
575
576
577
578
579
580



581

582
583
584




585


586
587

588
589
590
591
592


593


594
595
596
597
598
599
600
601
602
603

604








605





606


607
608
609
610
611
612
613
614
615


616
617




618
619
620
621
622
623

624


625
626






627
628


629
630

631
632



633



634
635
636
637
638


639
640
641
642
643


644
645

646
647
648
649






650
651

652
653
654


655
656

657
658



659
660
661
662
663
664
665
666
667

668






669

670


671

672
673
674

675


676
677

678

679



680


681


682
683
684
685



686
687
688

689
690
691
692
693
694
695
696

697
698
699
700
701
702
703
704


705
706
707
708

709
710
711
712
713
714
715
716

717
718
719











720










721

722

723
724
725
726
727
728

729
730
731
732
733
734


735






736
737
738
739
740
741
742
743
744
745
746


747
748
749
750
751



752




753

754
755
756













757
758

759
760
761
762
763




764
765

766


767
768

769


770


771


772
773
774
775

776

777
778
779
780
781
782

783

784

785


786
787
788
789
790
791
792
793

794
795
796
797
798
799
800
801
802
803

804
805








806
807
808
809
810




811
812

813



814

815




816

817
818
819
820

821




822
823
824
825


826
827

828
829
830

831
832
833

834

835

836
837




838
839

840
841








842
843
844
845
846
847
848
849
850

851



852


853
854
855
856
857
858
859
860
861
862

863

864
865


866
867
868
869
870
871

872
873

874






875
876
877
878




879





880
881
882






883

884
885
886
887

888

889

890
891

892
893
894
895
896
897
898
899


900
901
902
903
904
905
906

907



908
909
910
911
912
913
914
915
916
917
918


919
920
921
922
923
924
925


926
927
928
929
930

931



932
933


934
935
936
937
938
939
940
941





942
943
944





945
946
947








948


949
950
951




952
953


954
955
956
957







958
959
960
961
962
963
964
965
966

967

































968
969
970
971
972
973



974
975






976
977

978
979
980
981
982

983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004









1005
1006
1007
1008
1009







1010


1011


1012
1013
1014

1015



1016
1017
1018
1019
1020
1021






1022


1023
1024
1025
1026
1027
1028
1029
1030

1031

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041


1042
1043
1044
1045
1046
1047
1048

1049

1050
1051



1052
1053


1054
1055
1056




1057












1058




1059




1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090




1091
1092
1093
1094


1095


1096








1097
1098



1099



1100
1101
1102
1103
1104

1105


1106


1107

1108


1109



1110
1111
1112





1113



1114
1115
1116
1117
1118


1119
1120
1121
1122
1123






1124




1125
1126
1127
1128
1129
1130



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140

1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156


1157

1158

1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200



















1201
1202
1203
1204
1205

1206








1207
1208
1209


1210
1211

1212
1213
1214



1215

1216
1217


1218

1219

1220
1221
1222
1223
1224
1225











1226
 *
 * ------------------------------------------------------------------------
 *
 * References:
 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
 *
 * Todo list:
 * - Filter bogus Ctrl+<char> combinations.
 * - Win32 support
 *
 * Bloat:
 * - History search like Ctrl+r in readline?
 *


 * List of escape sequences used by this program, we do everything just
 * with three sequences. In order to be so cheap we may have some
 * flickering effect with some slow terminal, but the lesser sequences
 * the more compatible.
 *
 * EL (Erase Line)
 *    Sequence: ESC [ n K
 *    Effect: if n is 0 or missing, clear from cursor to end of line
 *    Effect: if n is 1, clear from beginning of line to cursor
 *    Effect: if n is 2, clear entire line
 *
 * CUF (CUrsor Forward)
 *    Sequence: ESC [ n C
 *    Effect: moves cursor forward n chars
 *
 * CUB (CUrsor Backward)
 *    Sequence: ESC [ n D
 *    Effect: moves cursor backward n chars
 *
 * The following is used to get the terminal width if getting

 * the width with the TIOCGWINSZ ioctl fails
 *
 * DSR (Device Status Report)
 *    Sequence: ESC [ 6 n
 *    Effect: reports the current cusor position as ESC [ n ; m R


 *            where n is the row and m is the column

 *
 * When multi line mode is enabled, we also use an additional escape

 * sequence. However multi line editing is disabled by default.

 *










 * CUU (Cursor Up)
 *    Sequence: ESC [ n A
 *    Effect: moves cursor up of n chars.
 *
 * CUD (Cursor Down)
 *    Sequence: ESC [ n B
 *    Effect: moves cursor down of n chars.
 *
 * When linenoiseClearScreen() is called, two additional escape sequences
 * are used in order to clear the screen and position the cursor at home
 * position.
 *
 * CUP (Cursor position)
 *    Sequence: ESC [ H
 *    Effect: moves the cursor to upper left corner
 *
 * ED (Erase display)

 *    Sequence: ESC [ 2 J
 *    Effect: clear the whole screen

 *
 */









#include <termios.h>
#include <unistd.h>
#include <stdlib.h>





#include <stdio.h>

#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "linenoise.h"



#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE 4096
static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
static linenoiseCompletionCallback *completionCallback = NULL;
static linenoiseHintsCallback *hintsCallback = NULL;
static linenoiseFreeHintsCallback *freeHintsCallback = NULL;






static struct termios orig_termios; /* In order to restore at exit.*/
static int maskmode = 0; /* Show "***" instead of input. For passwords. */
static int rawmode = 0; /* For atexit() function to check if restore is needed*/
static int mlmode = 0;  /* Multi line mode. Default is single line. */
static int atexit_registered = 0; /* Register atexit just 1 time. */
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int history_len = 0;
static char **history = NULL;




/* The linenoiseState structure represents the state during line editing.
 * We pass this state to functions implementing specific editing
 * functionalities. */
struct linenoiseState {


    int ifd;            /* Terminal stdin file descriptor. */
    int ofd;            /* Terminal stdout file descriptor. */
    char *buf;          /* Edited line buffer. */
    size_t buflen;      /* Edited line buffer size. */
    const char *prompt; /* Prompt to display. */
    size_t plen;        /* Prompt length. */
    size_t pos;         /* Current cursor position. */
    size_t oldpos;      /* Previous refresh cursor position. */
    size_t len;         /* Current edited line length. */
    size_t cols;        /* Number of columns in terminal. */
    size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
    int history_index;  /* The history index we are currently editing. */


};













































































enum KEY_ACTION{
	KEY_NULL = 0,	    /* NULL */
	CTRL_A = 1,         /* Ctrl+a */
	CTRL_B = 2,         /* Ctrl-b */
	CTRL_C = 3,         /* Ctrl-c */
	CTRL_D = 4,         /* Ctrl-d */
	CTRL_E = 5,         /* Ctrl-e */

	CTRL_F = 6,         /* Ctrl-f */
	CTRL_H = 8,         /* Ctrl-h */
	TAB = 9,            /* Tab */
	CTRL_K = 11,        /* Ctrl+k */
	CTRL_L = 12,        /* Ctrl+l */
	ENTER = 13,         /* Enter */
	CTRL_N = 14,        /* Ctrl-n */
	CTRL_P = 16,        /* Ctrl-p */
	CTRL_T = 20,        /* Ctrl-t */


	CTRL_U = 21,        /* Ctrl+u */

	CTRL_W = 23,        /* Ctrl+w */
	ESC = 27,           /* Escape */
	BACKSPACE =  127    /* Backspace */
};














static void linenoiseAtExit(void);
int linenoiseHistoryAdd(const char *line);







static void refreshLine(struct linenoiseState *l);







/* Debugging macro. */

#if 0

FILE *lndebug_fp = NULL;



#define lndebug(...) \
    do { \
        if (lndebug_fp == NULL) { \



            lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
            fprintf(lndebug_fp, \
            "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
            (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
            (int)l->maxrows,old_rows); \
        } \
        fprintf(lndebug_fp, ", " __VA_ARGS__); \
        fflush(lndebug_fp); \
    } while (0)
#else

#define lndebug(fmt, ...)

#endif




/* ======================= Low level terminal handling ====================== */

/* Enable "mask mode". When it is enabled, instead of the input that

 * the user is typing, the terminal will just display a corresponding



 * number of asterisks, like "****". This is useful for passwords and other
 * secrets that should not be displayed. */
void linenoiseMaskModeEnable(void) {







    maskmode = 1;

}



/* Disable mask mode. */


void linenoiseMaskModeDisable(void) {
    maskmode = 0;

}

/* Set if to use or not the multi line mode. */
void linenoiseSetMultiLine(int ml) {
    mlmode = ml;



}









/* Return true if the terminal name is in the list of terminals we know are

 * not able to understand basic escape sequences. */
static int isUnsupportedTerm(void) {
    char *term = getenv("TERM");
    int j;

    if (term == NULL) return 0;

    for (j = 0; unsupported_term[j]; j++)
        if (!strcasecmp(term,unsupported_term[j])) return 1;
    return 0;
}




/* Raw mode: 1960 magic shit. */
static int enableRawMode(int fd) {
    struct termios raw;

    if (!isatty(STDIN_FILENO)) goto fatal;









    if (!atexit_registered) {
        atexit(linenoiseAtExit);
        atexit_registered = 1;
    }
    if (tcgetattr(fd,&orig_termios) == -1) goto fatal;

    raw = orig_termios;  /* modify the original mode */
    /* input modes: no break, no CR to NL, no parity check, no strip char,
     * no start/stop output control. */
    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    /* output modes - disable post processing */
    raw.c_oflag &= ~(OPOST);
    /* control modes - set 8 bit chars */
    raw.c_cflag |= (CS8);
    /* local modes - choing off, canonical off, no extended functions,
     * no signal chars (^Z,^C) */
    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    /* control chars - set return condition: min number of bytes and timer.
     * We want read to return every single byte, without timeout. */
    raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */

    /* put terminal in raw mode after flushing */

    if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;

    rawmode = 1;
    return 0;

fatal:
    errno = ENOTTY;
    return -1;
}

static void disableRawMode(int fd) {
    /* Don't even check the return value as it's too late. */
    if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
        rawmode = 0;
}








/* Use the ESC [6n escape sequence to query the horizontal cursor position





 * and return it. On error -1 is returned, on success the position of the








 * cursor. */






static int getCursorPosition(int ifd, int ofd) {





    char buf[32];
    int cols, rows;
    unsigned int i = 0;







    /* Report cursor location */




    if (write(ofd, "\x1b[6n", 4) != 4) return -1;






















































    /* Read the response: ESC [ rows ; cols R */


    while (i < sizeof(buf)-1) {




        if (read(ifd,buf+i,1) != 1) break;




        if (buf[i] == 'R') break;











        i++;


    }





    buf[i] = '\0';










    /* Parse it. */
    if (buf[0] != ESC || buf[1] != '[') return -1;








    if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;















    return cols;
}









/* Try to get the number of columns in the current terminal, or assume 80


 * if it fails. */
static int getColumns(int ifd, int ofd) {

    struct winsize ws;

    if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
        /* ioctl() failed. Try to query the terminal itself. */


        int start, cols;









        /* Get the initial position so we can restore it later. */


        start = getCursorPosition(ifd,ofd);

        if (start == -1) goto failed;





        /* Go to right margin and get position. */




        if (write(ofd,"\x1b[999C",6) != 6) goto failed;







        cols = getCursorPosition(ifd,ofd);




        if (cols == -1) goto failed;


        /* Restore position. */









        if (cols > start) {

            char seq[32];

            snprintf(seq,32,"\x1b[%dD",cols-start);
            if (write(ofd,seq,strlen(seq)) == -1) {



                /* Can't recover... */

            }
        }


        return cols;




    } else {
        return ws.ws_col;










    }

























failed:
    return 80;
}




















/* Clear the screen. Used to handle ctrl+l */

void linenoiseClearScreen(void) {





    if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {














        /* nothing to do, just to avoid warning. */





    }


}

/* Beep, used for completion when there is nothing to complete or when all







 * the choices were already shown. */
static void linenoiseBeep(void) {

    fprintf(stderr, "\x7");
    fflush(stderr);

}

/* ============================== Completion ================================ */

/* Free a list of completion option populated by linenoiseAddCompletion(). */
static void freeCompletions(linenoiseCompletions *lc) {
    size_t i;
    for (i = 0; i < lc->len; i++)
        free(lc->cvec[i]);
    if (lc->cvec != NULL)
        free(lc->cvec);
}

/* This is an helper function for linenoiseEdit() and is called when the
 * user types the <tab> key in order to complete the string currently in the
 * input.
 *
 * The state of the editing is encapsulated into the pointed linenoiseState
 * structure as described in the structure definition. */
static int completeLine(struct linenoiseState *ls) {
    linenoiseCompletions lc = { 0, NULL };
    int nread, nwritten;
    char c = 0;

    completionCallback(ls->buf,&lc);
    if (lc.len == 0) {
        linenoiseBeep();
    } else {
        size_t stop = 0, i = 0;

        while(!stop) {
            /* Show completion or original buffer */
            if (i < lc.len) {
                struct linenoiseState saved = *ls;

                ls->len = ls->pos = strlen(lc.cvec[i]);
                ls->buf = lc.cvec[i];
                refreshLine(ls);
                ls->len = saved.len;
                ls->pos = saved.pos;
                ls->buf = saved.buf;
            } else {
                refreshLine(ls);
            }

            nread = read(ls->ifd,&c,1);
            if (nread <= 0) {
                freeCompletions(&lc);
                return -1;
            }

            switch(c) {
                case 9: /* tab */
                    i = (i+1) % (lc.len+1);
                    if (i == lc.len) linenoiseBeep();
                    break;
                case 27: /* escape */
                    /* Re-show original buffer */
                    if (i < lc.len) refreshLine(ls);


                    stop = 1;
                    break;
                default:
                    /* Update buffer and return */
                    if (i < lc.len) {
                        nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
                        ls->len = ls->pos = nwritten;
                    }
                    stop = 1;
                    break;
            }
        }
    }

    freeCompletions(&lc);
    return c; /* Return last read character */
}

/* Register a callback function to be called for tab-completion. */


void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {

    completionCallback = fn;


}





/* Register a hits function to be called to show hits to the user at the
 * right of the prompt. */
void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {

    hintsCallback = fn;

}

/* Register a function to free the hints returned by the hints callback
 * registered with linenoiseSetHintsCallback(). */
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {

    freeHintsCallback = fn;
}

/* This function is used by the callback function registered by the user
 * in order to add completion options given the input string when the
 * user typed <tab>. See the example.c source code for a very easy to
 * understand example. */
void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
    size_t len = strlen(str);
    char *copy, **cvec;











    copy = malloc(len+1);
    if (copy == NULL) return;
    memcpy(copy,str,len+1);
    cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
    if (cvec == NULL) {
        free(copy);

        return;
    }
    lc->cvec = cvec;
    lc->cvec[lc->len++] = copy;
}














/* =========================== Line editing ================================= */

/* We define a very simple "append buffer" structure, that is an heap
 * allocated string where we can append to. This is useful in order to
 * write all the escape sequences in a buffer and flush them to the standard
 * output in a single call, to avoid flickering effects. */
struct abuf {
    char *b;
    int len;
};


static void abInit(struct abuf *ab) {
    ab->b = NULL;
    ab->len = 0;
}

static void abAppend(struct abuf *ab, const char *s, int len) {
    char *new = realloc(ab->b,ab->len+len);


    if (new == NULL) return;

    memcpy(new+ab->len,s,len);



    ab->b = new;
    ab->len += len;
}

static void abFree(struct abuf *ab) {
    free(ab->b);



}









/* Helper of refreshSingleLine() and refreshMultiLine() to show hints
 * to the right of the prompt. */
void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
    char seq[64];
    if (hintsCallback && plen+l->len < l->cols) {

        int color = -1, bold = 0;
        char *hint = hintsCallback(l->buf,&color,&bold);
        if (hint) {
            int hintlen = strlen(hint);
            int hintmaxlen = l->cols-(plen+l->len);
            if (hintlen > hintmaxlen) hintlen = hintmaxlen;

            if (bold == 1 && color == -1) color = 37;
            if (color != -1 || bold != 0)



                snprintf(seq,64,"\033[%d;%d;49m",bold,color);

            else

                seq[0] = '\0';

            abAppend(ab,seq,strlen(seq));

            abAppend(ab,hint,hintlen);


            if (color != -1 || bold != 0)
                abAppend(ab,"\033[0m",4);







            /* Call the function to free the hint returned. */
            if (freeHintsCallback) freeHintsCallback(hint);
        }
    }
}


/* Single line low level line refresh.
 *




 * Rewrite the currently edited line accordingly to the buffer content,


 * cursor position, and number of columns of the terminal. */
static void refreshSingleLine(struct linenoiseState *l) {



    char seq[64];
    size_t plen = strlen(l->prompt);
    int fd = l->ofd;
    char *buf = l->buf;

    size_t len = l->len;
    size_t pos = l->pos;
    struct abuf ab;

    while((plen+pos) >= l->cols) {
        buf++;
        len--;
        pos--;
    }
    while (plen+len > l->cols) {


        len--;

    }

    abInit(&ab);

    /* Cursor to left edge */
    snprintf(seq,64,"\r");
    abAppend(&ab,seq,strlen(seq));
    /* Write the prompt and the current buffer content */
    abAppend(&ab,l->prompt,strlen(l->prompt));
    if (maskmode == 1) {
        while (len--) abAppend(&ab,"*",1);
    } else {
        abAppend(&ab,buf,len);
    }


    /* Show hits if any. */



    refreshShowHints(&ab,l,plen);
    /* Erase to right */
    snprintf(seq,64,"\x1b[0K");
    abAppend(&ab,seq,strlen(seq));
    /* Move cursor to original position. */


    snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));



    abAppend(&ab,seq,strlen(seq));


    if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */

    abFree(&ab);

}














/* Multi line low level line refresh.
 *

 * Rewrite the currently edited line accordingly to the buffer content,


 * cursor position, and number of columns of the terminal. */

static void refreshMultiLine(struct linenoiseState *l) {
    char seq[64];
    int plen = strlen(l->prompt);
    int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
    int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
    int rpos2; /* rpos after refresh. */
    int col; /* colum position, zero-based. */
    int old_rows = l->maxrows;
    int fd = l->ofd, j;
    struct abuf ab;


    /* Update maxrows if needed. */
    if (rows > (int)l->maxrows) l->maxrows = rows;

    /* First step: clear all the lines used before. To do so start by
     * going to the last row. */
    abInit(&ab);
    if (old_rows-rpos > 0) {



        lndebug("go down %d", old_rows-rpos);

        snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
        abAppend(&ab,seq,strlen(seq));
    }







    /* Now for every row clear it, go up. */
    for (j = 0; j < old_rows-1; j++) {

        lndebug("clear+up");
        snprintf(seq,64,"\r\x1b[0K\x1b[1A");
        abAppend(&ab,seq,strlen(seq));
    }



    /* Clean the top line. */


    lndebug("clear");
    snprintf(seq,64,"\r\x1b[0K");
    abAppend(&ab,seq,strlen(seq));

    /* Write the prompt and the current buffer content */
    abAppend(&ab,l->prompt,strlen(l->prompt));
    if (maskmode == 1) {
        unsigned int i;
        for (i = 0; i < l->len; i++) abAppend(&ab,"*",1);
    } else {

        abAppend(&ab,l->buf,l->len);








    }








    /* Show hits if any. */
    refreshShowHints(&ab,l,plen);

    /* If we are at the very end of the screen with our prompt, we need to
     * emit a newline and move the prompt to the first column. */
    if (l->pos &&
        l->pos == l->len &&
        (l->pos+plen) % l->cols == 0)
    {


        lndebug("<newline>");
        abAppend(&ab,"\n",1);




        snprintf(seq,64,"\r");
        abAppend(&ab,seq,strlen(seq));
        rows++;
        if (rows > (int)l->maxrows) l->maxrows = rows;
    }


    /* Move cursor to right position. */


    rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
    lndebug("rpos2 %d", rpos2);







    /* Go up till we reach the expected positon. */


    if (rows-rpos2 > 0) {
        lndebug("go-up %d", rows-rpos2);

        snprintf(seq,64,"\x1b[%dA", rows-rpos2);
        abAppend(&ab,seq,strlen(seq));



    }




    /* Set column. */
    col = (plen+(int)l->pos) % (int)l->cols;
    lndebug("set col %d", 1+col);
    if (col)


        snprintf(seq,64,"\r\x1b[%dC", col);
    else
        snprintf(seq,64,"\r");
    abAppend(&ab,seq,strlen(seq));



    lndebug("\n");
    l->oldpos = l->pos;


    if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
    abFree(&ab);
}







/* Calls the two low level functions refreshSingleLine() or

 * refreshMultiLine() according to the selected mode. */
static void refreshLine(struct linenoiseState *l) {
    if (mlmode)


        refreshMultiLine(l);
    else

        refreshSingleLine(l);
}




/* Insert the character 'c' at cursor current position.
 *
 * On error writing to the terminal -1 is returned, otherwise 0. */
int linenoiseEditInsert(struct linenoiseState *l, char c) {
    if (l->len < l->buflen) {
        if (l->len == l->pos) {
            l->buf[l->pos] = c;
            l->pos++;

            l->len++;






            l->buf[l->len] = '\0';

            if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {


                /* Avoid a full update of the line in the

                 * trivial case. */
                char d = (maskmode==1) ? '*' : c;
                if (write(l->ofd,&d,1) == -1) return -1;

            } else {


                refreshLine(l);
            }

        } else {

            memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);



            l->buf[l->pos] = c;


            l->len++;


            l->pos++;
            l->buf[l->len] = '\0';
            refreshLine(l);
        }



    }
    return 0;
}


/* Move cursor on the left. */
void linenoiseEditMoveLeft(struct linenoiseState *l) {
    if (l->pos > 0) {
        l->pos--;
        refreshLine(l);
    }
}


/* Move cursor on the right. */
void linenoiseEditMoveRight(struct linenoiseState *l) {
    if (l->pos != l->len) {
        l->pos++;
        refreshLine(l);
    }
}



/* Move cursor to the start of the line. */
void linenoiseEditMoveHome(struct linenoiseState *l) {
    if (l->pos != 0) {

        l->pos = 0;
        refreshLine(l);
    }
}

/* Move cursor to the end of the line. */
void linenoiseEditMoveEnd(struct linenoiseState *l) {
    if (l->pos != l->len) {

        l->pos = l->len;
        refreshLine(l);
    }











}












/* Substitute the currently edited line with the next or previous history

 * entry as specified by 'dir'. */
#define LINENOISE_HISTORY_NEXT 0
#define LINENOISE_HISTORY_PREV 1
void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
    if (history_len > 1) {
        /* Update the current history entry before to

         * overwrite it with the next one. */
        free(history[history_len - 1 - l->history_index]);
        history[history_len - 1 - l->history_index] = strdup(l->buf);
        /* Show the new entry */
        l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
        if (l->history_index < 0) {


            l->history_index = 0;






            return;
        } else if (l->history_index >= history_len) {
            l->history_index = history_len-1;
            return;
        }
        strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
        l->buf[l->buflen-1] = '\0';
        l->len = l->pos = strlen(l->buf);
        refreshLine(l);
    }
}



/* Delete the character at the right of the cursor without altering the cursor
 * position. Basically this is what happens with the "Delete" keyboard key. */
void linenoiseEditDelete(struct linenoiseState *l) {
    if (l->len > 0 && l->pos < l->len) {



        memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);




        l->len--;

        l->buf[l->len] = '\0';
        refreshLine(l);
    }













}


/* Backspace implementation. */
void linenoiseEditBackspace(struct linenoiseState *l) {
    if (l->pos > 0 && l->len > 0) {
        memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
        l->pos--;




        l->len--;
        l->buf[l->len] = '\0';

        refreshLine(l);


    }
}




/* Delete the previosu word, maintaining the cursor at the start of the


 * current word. */


void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
    size_t old_pos = l->pos;
    size_t diff;


    while (l->pos > 0 && l->buf[l->pos-1] == ' ')

        l->pos--;
    while (l->pos > 0 && l->buf[l->pos-1] != ' ')
        l->pos--;
    diff = old_pos - l->pos;
    memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
    l->len -= diff;

    refreshLine(l);

}




/* This function is the core of the line editing capability of linenoise.
 * It expects 'fd' to be already in "raw mode" so that every key pressed
 * will be returned ASAP to read().
 *
 * The resulting string is put into 'buf' when the user type enter, or
 * when ctrl+d is typed.
 *
 * The function returns the length of the current buffer. */

static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
{
    struct linenoiseState l;

    /* Populate the linenoise state that we pass to functions implementing
     * specific editing functionalities. */
    l.ifd = stdin_fd;
    l.ofd = stdout_fd;
    l.buf = buf;
    l.buflen = buflen;

    l.prompt = prompt;
    l.plen = strlen(prompt);








    l.oldpos = l.pos = 0;
    l.len = 0;
    l.cols = getColumns(stdin_fd, stdout_fd);
    l.maxrows = 0;
    l.history_index = 0;





    /* Buffer starts empty. */

    l.buf[0] = '\0';



    l.buflen--; /* Make sure there is always space for the nulterm */






    /* The latest history entry is always our current buffer, that

     * initially is just an empty string. */
    linenoiseHistoryAdd("");

    if (write(l.ofd,prompt,l.plen) == -1) return -1;

    while(1) {




        char c;
        int nread;
        char seq[3];



        nread = read(l.ifd,&c,1);
        if (nread <= 0) return l.len;


        /* Only autocomplete when the callback is set. It returns < 0 when
         * there was an error reading from fd. Otherwise it will return the

         * character that should be handled next. */
        if (c == 9 && completionCallback != NULL) {
            c = completeLine(&l);

            /* Return on errors */

            if (c < 0) return l.len;

            /* Read next character when 0 */
            if (c == 0) continue;




        }


        switch(c) {
        case ENTER:    /* enter */








            history_len--;
            free(history[history_len]);
            if (mlmode) linenoiseEditMoveEnd(&l);
            if (hintsCallback) {
                /* Force a refresh without hints to leave the previous
                 * line as the user typed it after a newline. */
                linenoiseHintsCallback *hc = hintsCallback;
                hintsCallback = NULL;
                refreshLine(&l);

                hintsCallback = hc;



            }


            return (int)l.len;
        case CTRL_C:     /* ctrl-c */
            errno = EAGAIN;
            return -1;
        case BACKSPACE:   /* backspace */
        case 8:     /* ctrl-h */
            linenoiseEditBackspace(&l);
            break;
        case CTRL_D:     /* ctrl-d, remove char at right of cursor, or if the
                            line is empty, act as end-of-file. */

            if (l.len > 0) {

                linenoiseEditDelete(&l);
            } else {


                history_len--;
                free(history[history_len]);
                return -1;
            }
            break;
        case CTRL_T:    /* ctrl-t, swaps current character with previous. */

            if (l.pos > 0 && l.pos < l.len) {
                int aux = buf[l.pos-1];

                buf[l.pos-1] = buf[l.pos];






                buf[l.pos] = aux;
                if (l.pos != l.len-1) l.pos++;
                refreshLine(&l);
            }




            break;





        case CTRL_B:     /* ctrl-b */
            linenoiseEditMoveLeft(&l);
            break;






        case CTRL_F:     /* ctrl-f */

            linenoiseEditMoveRight(&l);
            break;
        case CTRL_P:    /* ctrl-p */
            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);

            break;

        case CTRL_N:    /* ctrl-n */

            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
            break;

        case ESC:    /* escape sequence */
            /* Read the next two bytes representing the escape sequence.
             * Use two calls to handle slow terminals returning the two
             * chars at different times. */
            if (read(l.ifd,seq,1) == -1) break;
            if (read(l.ifd,seq+1,1) == -1) break;

            /* ESC [ sequences. */


            if (seq[0] == '[') {
                if (seq[1] >= '0' && seq[1] <= '9') {
                    /* Extended escape, read additional byte. */
                    if (read(l.ifd,seq+2,1) == -1) break;
                    if (seq[2] == '~') {
                        switch(seq[1]) {
                        case '3': /* Delete key. */

                            linenoiseEditDelete(&l);



                            break;
                        }
                    }
                } else {
                    switch(seq[1]) {
                    case 'A': /* Up */
                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
                        break;
                    case 'B': /* Down */
                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
                        break;


                    case 'C': /* Right */
                        linenoiseEditMoveRight(&l);
                        break;
                    case 'D': /* Left */
                        linenoiseEditMoveLeft(&l);
                        break;
                    case 'H': /* Home */


                        linenoiseEditMoveHome(&l);
                        break;
                    case 'F': /* End*/
                        linenoiseEditMoveEnd(&l);
                        break;

                    }



                }
            }



            /* ESC O sequences. */
            else if (seq[0] == 'O') {
                switch(seq[1]) {
                case 'H': /* Home */
                    linenoiseEditMoveHome(&l);
                    break;
                case 'F': /* End*/





                    linenoiseEditMoveEnd(&l);
                    break;
                }





            }
            break;
        default:








            if (linenoiseEditInsert(&l,c)) return -1;


            break;
        case CTRL_U: /* Ctrl+u, delete the whole line. */
            buf[0] = '\0';




            l.pos = l.len = 0;
            refreshLine(&l);


            break;
        case CTRL_K: /* Ctrl+k, delete from current to end of line. */
            buf[l.pos] = '\0';
            l.len = l.pos;







            refreshLine(&l);
            break;
        case CTRL_A: /* Ctrl+a, go to the start of the line */
            linenoiseEditMoveHome(&l);
            break;
        case CTRL_E: /* ctrl+e, go to the end of the line */
            linenoiseEditMoveEnd(&l);
            break;
        case CTRL_L: /* ctrl+l, clear screen */

            linenoiseClearScreen();

































            refreshLine(&l);
            break;
        case CTRL_W: /* ctrl+w, delete previous word */
            linenoiseEditDeletePrevWord(&l);
            break;
        }



    }
    return l.len;






}


/* This special mode is used by linenoise in order to print scan codes
 * on screen for debugging / development purposes. It is implemented
 * by the linenoise_example program using the --keycodes option. */
void linenoisePrintKeyCodes(void) {
    char quit[4];


    printf("Linenoise key codes debugging mode.\n"
            "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
    if (enableRawMode(STDIN_FILENO) == -1) return;
    memset(quit,' ',4);
    while(1) {
        char c;
        int nread;

        nread = read(STDIN_FILENO,&c,1);
        if (nread <= 0) continue;
        memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
        quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
        if (memcmp(quit,"quit",sizeof(quit)) == 0) break;

        printf("'%c' %02x (%d) (type quit to exit)\n",
            isprint(c) ? c : '?', (int)c, (int)c);
        printf("\r"); /* Go left edge manually, we are in raw mode. */
        fflush(stdout);
    }
    disableRawMode(STDIN_FILENO);
}










/* This function calls the line editing function linenoiseEdit() using
 * the STDIN file descriptor set in raw mode. */
static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
    int count;










    if (buflen == 0) {


        errno = EINVAL;
        return -1;
    }





    if (enableRawMode(STDIN_FILENO) == -1) return -1;
    count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
    disableRawMode(STDIN_FILENO);
    printf("\n");
    return count;
}









/* This function is called when linenoise() is called with the standard
 * input file descriptor not attached to a TTY. So for example when the
 * program using linenoise is called in pipe or with a file redirected
 * to its standard input. In this case, we want to be able to return the
 * line regardless of its length (by default we are limited to 4k). */
static char *linenoiseNoTTY(void) {
    char *line = NULL;
    size_t len = 0, maxlen = 0;



    while(1) {
        int c;
        if (len == maxlen) {
            char *oldval = line;
            if (maxlen == 0) maxlen = 16;
            maxlen *= 2;
            line = realloc(line,maxlen);
            if (line == NULL) {
                if (oldval) free(oldval);
                return NULL;


            }
        }
        c = fgetc(stdin);
        if (c == EOF || c == '\n') {
            if (c == EOF && len == 0) {
                free(line);
                return NULL;

            } else {

                line[len] = '\0';
                return line;



            }
        } else {


            line[len] = c;
            len++;
        }




    }












}









/* The high level function that is the main API of the linenoise library.
 * This function checks if the terminal has basic capabilities, just checking
 * for a blacklist of stupid terminals, and later either calls the line
 * editing function or uses dummy fgets() so that you will be able to type
 * something even in the most desperate of the conditions. */
char *linenoise(const char *prompt) {
    char buf[LINENOISE_MAX_LINE];
    int count;

    if (!isatty(STDIN_FILENO)) {
        /* Not a tty: read from file / pipe. In this mode we don't want any
         * limit to the line size, so we call a function to handle that. */
        return linenoiseNoTTY();
    } else if (isUnsupportedTerm()) {
        size_t len;

        printf("%s",prompt);
        fflush(stdout);
        if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
        len = strlen(buf);
        while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
            len--;
            buf[len] = '\0';
        }
        return strdup(buf);
    } else {
        count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
        if (count == -1) return NULL;
        return strdup(buf);
    }
}





/* This is just a wrapper the user may want to call in order to make sure
 * the linenoise returned buffer is freed with the same allocator it was
 * created with. Useful when the main program is using an alternative


 * allocator. */


void linenoiseFree(void *ptr) {








    free(ptr);
}







/* ================================ History ================================= */

/* Free the history, but does not reset it. Only used when we have to
 * exit() to avoid memory leaks are reported by valgrind & co. */
static void freeHistory(void) {

    if (history) {


        int j;




        for (j = 0; j < history_len; j++)


            free(history[j]);



        free(history);
    }
}









/* At exit we'll try to fix the terminal to the initial conditions. */
static void linenoiseAtExit(void) {
    disableRawMode(STDIN_FILENO);
    freeHistory();
}



/* This is the API call to add a new entry in the linenoise history.
 * It uses a fixed array of char pointers that are shifted (memmoved)
 * when the history max length is reached in order to remove the older
 * entry and make room for the new one, so it is not exactly suitable for huge






 * histories, but will work well for a few hundred of entries.




 *
 * Using a circular buffer is smarter, but a bit more complex to handle. */
int linenoiseHistoryAdd(const char *line) {
    char *linecopy;

    if (history_max_len == 0) return 0;




    /* Initialization on first call. */
    if (history == NULL) {
        history = malloc(sizeof(char*)*history_max_len);
        if (history == NULL) return 0;
        memset(history,0,(sizeof(char*)*history_max_len));
    }

    /* Don't add duplicated lines. */
    if (history_len && !strcmp(history[history_len-1], line)) return 0;


    /* Add an heap allocated copy of the line in the history.
     * If we reached the max length, remove the older line. */
    linecopy = strdup(line);
    if (!linecopy) return 0;
    if (history_len == history_max_len) {
        free(history[0]);
        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
        history_len--;
    }
    history[history_len] = linecopy;
    history_len++;
    return 1;
}

/* Set the maximum length for the history. This function can be called even


 * if there is already some history, the function will make sure to retain

 * just the latest 'len' elements if the new history length value is smaller

 * than the amount of items already inside the history. */
int linenoiseHistorySetMaxLen(int len) {
    char **new;

    if (len < 1) return 0;
    if (history) {
        int tocopy = history_len;

        new = malloc(sizeof(char*)*len);
        if (new == NULL) return 0;

        /* If we can't copy everything, free the elements we'll not use. */
        if (len < tocopy) {
            int j;

            for (j = 0; j < tocopy-len; j++) free(history[j]);
            tocopy = len;
        }
        memset(new,0,sizeof(char*)*len);
        memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
        free(history);
        history = new;
    }
    history_max_len = len;
    if (history_len > history_max_len)
        history_len = history_max_len;
    return 1;
}

/* Save the history in the specified file. On success 0 is returned
 * otherwise -1 is returned. */
int linenoiseHistorySave(const char *filename) {
    mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
    FILE *fp;
    int j;

    fp = fopen(filename,"w");
    umask(old_umask);
    if (fp == NULL) return -1;
    chmod(filename,S_IRUSR|S_IWUSR);
    for (j = 0; j < history_len; j++)
        fprintf(fp,"%s\n",history[j]);



















    fclose(fp);
    return 0;
}

/* Load the history from the specified file. If the file does not exist

 * zero is returned and no operation is performed.








 *
 * If the file exists and the operation succeeded 0 is returned, otherwise
 * on error -1 is returned. */


int linenoiseHistoryLoad(const char *filename) {
    FILE *fp = fopen(filename,"r");

    char buf[LINENOISE_MAX_LINE];

    if (fp == NULL) return -1;





    while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
        char *p;




        p = strchr(buf,'\r');

        if (!p) p = strchr(buf,'\n');
        if (p) *p = '\0';
        linenoiseHistoryAdd(buf);
    }
    fclose(fp);
    return 0;











}

Changes to extsrc/linenoise.h.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16


/* linenoise.h -- guerrilla line editing library against the idea that a
 * line editing lib needs to be 20,000 lines of C code.
 *
 * See linenoise.c for more information.
 *
 * ------------------------------------------------------------------------
 *
 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
>
>
|
|





|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* linenoise.h -- VERSION 1.0
 *
 * Guerrilla line editing library against the idea that a line editing lib
 * needs to be 20,000 lines of C code.
 *
 * See linenoise.c for more information.
 *
 * ------------------------------------------------------------------------
 *
 * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
 * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#ifndef __LINENOISE_H
#define __LINENOISE_H

#ifdef __cplusplus
extern "C" {
#endif

#ifndef NO_COMPLETION
typedef struct linenoiseCompletions {
  size_t len;
  char **cvec;
} linenoiseCompletions;

/*
 * The callback type for tab completion handlers.
 */
typedef void(linenoiseCompletionCallback)(const char *prefix, linenoiseCompletions *comp, void *userdata);

/*
 * Sets the current tab completion handler and returns the previous one, or NULL
 * if no prior one has been set.
 */
linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *comp, void *userdata);

/*
 * Adds a copy of the given string to the given completion list. The copy is owned
 * by the linenoiseCompletions object.
 */
void linenoiseAddCompletion(linenoiseCompletions *comp, const char *str);

typedef char*(linenoiseHintsCallback)(const char *, int *color, int *bold, void *userdata);
typedef void(linenoiseFreeHintsCallback)(void *hint, void *userdata);

void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata);
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback);

#endif

/*
 * Prompts for input using the given string as the input
 * prompt. Returns when the user has tapped ENTER or (on an empty
 * line) EOF (Ctrl-D on Unix, Ctrl-Z on Windows). Returns either
 * a copy of the entered string (for ENTER) or NULL (on EOF).  The
 * caller owns the returned string and must eventually free() it.
 */
char *linenoise(const char *prompt);

/**
 * Like linenoise() but starts with an initial buffer.
 */

char *linenoiseWithInitial(const char *prompt, const char *initial);

/**
 * Clear the screen.
 */
void linenoiseClearScreen(void);

/*
 * Adds a copy of the given line of the command history.
 */
int linenoiseHistoryAdd(const char *line);

/*
 * Sets the maximum length of the command history, in lines.
 * If the history is currently longer, it will be trimmed,
 * retaining only the most recent entries. If len is 0 or less
 * then this function does nothing.
 */
int linenoiseHistorySetMaxLen(int len);

/*
 * Returns the current maximum length of the history, in lines.
 */
int linenoiseHistoryGetMaxLen(void);

/*
 * Saves the current contents of the history to the given file.
 * Returns 0 on success.
 */
int linenoiseHistorySave(const char *filename);

/*
 * Replaces the current history with the contents
 * of the given file.  Returns 0 on success.
 */
int linenoiseHistoryLoad(const char *filename);

/*
 * Frees all history entries, clearing the history.
 */
void linenoiseHistoryFree(void);

/*
 * Returns a pointer to the list of history entries, writing its
 * length to *len if len is not NULL. The memory is owned by linenoise
 * and must not be freed.
 */
char **linenoiseHistory(int *len);

/*
 * Returns the number of display columns in the current terminal.
 */
int linenoiseColumns(void);

/**
 * Enable or disable multiline mode (disabled by default)
 */
void linenoiseSetMultiLine(int enableml);

#ifdef __cplusplus
}
#endif

#endif /* __LINENOISE_H */







<





<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
>
|
|
|
<

<
<
<
<
<
<
<

|
<
|
<
>
|
|
<
<
<

|
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|






39
40
41
42
43
44
45

46
47
48
49
50



51













52
53
54
55
56
57

58







59
60

61

62
63
64



65
66




67




























68
















69
70
71
72
73
74
75
#ifndef __LINENOISE_H
#define __LINENOISE_H

#ifdef __cplusplus
extern "C" {
#endif


typedef struct linenoiseCompletions {
  size_t len;
  char **cvec;
} linenoiseCompletions;




typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *);













typedef char*(linenoiseHintsCallback)(const char *, int *color, int *bold);
typedef void(linenoiseFreeHintsCallback)(void *);
void linenoiseSetCompletionCallback(linenoiseCompletionCallback *);
void linenoiseSetHintsCallback(linenoiseHintsCallback *);
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *);
void linenoiseAddCompletion(linenoiseCompletions *, const char *);









char *linenoise(const char *prompt);
void linenoiseFree(void *ptr);

int linenoiseHistoryAdd(const char *line);

int linenoiseHistorySetMaxLen(int len);
int linenoiseHistorySave(const char *filename);
int linenoiseHistoryLoad(const char *filename);



void linenoiseClearScreen(void);
void linenoiseSetMultiLine(int ml);




void linenoisePrintKeyCodes(void);




























void linenoiseMaskModeEnable(void);
















void linenoiseMaskModeDisable(void);

#ifdef __cplusplus
}
#endif

#endif /* __LINENOISE_H */

Changes to extsrc/shell.c.

6000
6001
6002
6003
6004
6005
6006
6007
6008
6009


6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
** once prior to any call to seriesColumn() or seriesRowid() or
** seriesEof().
**
** The query plan selected by seriesBestIndex is passed in the idxNum
** parameter.  (idxStr is not used in this implementation.)  idxNum
** is a bitmask showing which constraints are available:
**
**   0x01:    start=VALUE
**   0x02:    stop=VALUE
**   0x04:    step=VALUE


**   0x08:    descending order
**   0x10:    ascending order
**   0x20:    LIMIT  VALUE
**   0x40:    OFFSET  VALUE
**
** This routine should initialize the cursor and position it so that it
** is pointing at the first row, or pointing off the end of the table
** (so that seriesEof() will return true) if the table is empty.
*/
static int seriesFilter(
  sqlite3_vtab_cursor *pVtabCursor,
  int idxNum, const char *idxStrUnused,
  int argc, sqlite3_value **argv
){
  series_cursor *pCur = (series_cursor *)pVtabCursor;
  int i = 0;
  (void)idxStrUnused;
  if( idxNum & 0x01 ){
    pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
  }else{
    pCur->ss.iBase = 0;
  }
  if( idxNum & 0x02 ){
    pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
  }else{
    pCur->ss.iTerm = 0xffffffff;
  }
  if( idxNum & 0x04 ){
    pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
    if( pCur->ss.iStep==0 ){
      pCur->ss.iStep = 1;
    }else if( pCur->ss.iStep<0 ){
      if( (idxNum & 0x10)==0 ) idxNum |= 0x08;
    }
  }else{
    pCur->ss.iStep = 1;
  }
  if( idxNum & 0x20 ){
    sqlite3_int64 iLimit = sqlite3_value_int64(argv[i++]);
    sqlite3_int64 iTerm;
    if( idxNum & 0x40 ){
      sqlite3_int64 iOffset = sqlite3_value_int64(argv[i++]);
      if( iOffset>0 ){
        pCur->ss.iBase += pCur->ss.iStep*iOffset;
      }
    }
    if( iLimit>=0 ){
      iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep;
      if( pCur->ss.iStep<0 ){
        if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
      }else{
        if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
      }
    }
  }
  for(i=0; i<argc; i++){
    if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
      /* If any of the constraints have a NULL value, then return no rows.
      ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
      pCur->ss.iBase = 1;
      pCur->ss.iTerm = 0;
      pCur->ss.iStep = 1;
      break;
    }
  }
  if( idxNum & 0x08 ){
    pCur->ss.isReversing = pCur->ss.iStep > 0;
  }else{
    pCur->ss.isReversing = pCur->ss.iStep < 0;
  }
  setupSequence( &pCur->ss );
  return SQLITE_OK;
}

/*
** SQLite will invoke this method one or more times while planning a query
** that uses the generate_series virtual table.  This routine needs to create
** a query plan for each invocation and compute an estimated cost for that
** plan.
**
** In this implementation idxNum is used to represent the
** query plan.  idxStr is unused.
**
** The query plan is represented by bits in idxNum:
**
**   0x01  start = $value  -- constraint exists
**   0x02  stop = $value   -- constraint exists
**   0x04  step = $value   -- constraint exists
**   0x08  output is in descending order
**   0x10  output is in ascending order
**   0x20  LIMIT $value    -- constraint exists
**   0x40  OFFSET $value   -- constraint exists
*/
static int seriesBestIndex(
  sqlite3_vtab *pVTab,
  sqlite3_index_info *pIdxInfo
){
  int i, j;              /* Loop over constraints */
  int idxNum = 0;        /* The query plan bitmask */
#ifndef ZERO_ARGUMENT_GENERATE_SERIES
  int bStartSeen = 0;    /* EQ constraint seen on the START column */
#endif
  int unusableMask = 0;  /* Mask of unusable constraints */
  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
  int aIdx[5];           /* Constraints on start, stop, step, LIMIT, OFFSET */
  const struct sqlite3_index_constraint *pConstraint;

  /* This implementation assumes that the start, stop, and step columns
  ** are the last three columns in the virtual table. */
  assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
  assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );

  aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = -1;
  pConstraint = pIdxInfo->aConstraint;
  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
    int iCol;    /* 0 for start, 1 for stop, 2 for step */
    int iMask;   /* bitmask for those column */
    int op = pConstraint->op;
    if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
     && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
    ){
      if( pConstraint->usable==0 ){
        /* do nothing */
      }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
        aIdx[3] = i;
        idxNum |= 0x20;
      }else{
        assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
        aIdx[4] = i;
        idxNum |= 0x40;
      }
      continue;
    }
    if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
    iCol = pConstraint->iColumn - SERIES_COLUMN_START;
    assert( iCol>=0 && iCol<=2 );
    iMask = 1 << iCol;
#ifndef ZERO_ARGUMENT_GENERATE_SERIES
    if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
      bStartSeen = 1;
    }
#endif
    if( pConstraint->usable==0 ){
      unusableMask |=  iMask;
      continue;
    }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
      idxNum |= iMask;
      aIdx[iCol] = i;
    }
  }
  if( aIdx[3]==0 ){
    /* Ignore OFFSET if LIMIT is omitted */
    idxNum &= ~0x60;
    aIdx[4] = 0;
  }
  for(i=0; i<5; i++){
    if( (j = aIdx[i])>=0 ){
      pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
      pIdxInfo->aConstraintUsage[j].omit =
         !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
    }
  }
  /* The current generate_column() implementation requires at least one
  ** argument (the START value).  Legacy versions assumed START=0 if the
  ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
  ** to obtain the legacy behavior */
#ifndef ZERO_ARGUMENT_GENERATE_SERIES
  if( !bStartSeen ){
    sqlite3_free(pVTab->zErrMsg);
    pVTab->zErrMsg = sqlite3_mprintf(
        "first argument to \"generate_series()\" missing or unusable");
    return SQLITE_ERROR;
  }
#endif
  if( (unusableMask & ~idxNum)!=0 ){
    /* The start, stop, and step columns are inputs.  Therefore if there
    ** are unusable constraints on any of start, stop, or step then
    ** this plan is unusable */
    return SQLITE_CONSTRAINT;
  }
  if( (idxNum & 0x03)==0x03 ){
    /* Both start= and stop= boundaries are available.  This is the 
    ** the preferred case */
    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
    pIdxInfo->estimatedRows = 1000;
    if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
      if( pIdxInfo->aOrderBy[0].desc ){
        idxNum |= 0x08;
      }else{
        idxNum |= 0x10;
      }
      pIdxInfo->orderByConsumed = 1;
    }
  }else if( (idxNum & 0x21)==0x21 ){
    /* We have start= and LIMIT */
    pIdxInfo->estimatedRows = 2500;
  }else{
    /* If either boundary is missing, we have to generate a huge span
    ** of numbers.  Make this case very expensive so that the query
    ** planner will work hard to avoid it. */
    pIdxInfo->estimatedRows = 2147483647;
  }
  pIdxInfo->idxNum = idxNum;







|
|
|
>
>
|
|
<
<













|




|




|




|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










|



















|
|
|
|
<
<
<







<

<


|







|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




<
<
|
<
<



|




<
<
<
<
<
|


|
<




















|






|

|



<
<
<







6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013


6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046


















6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080



6081
6082
6083
6084
6085
6086
6087

6088

6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
















6104
6105
6106
6107


6108


6109
6110
6111
6112
6113
6114
6115
6116





6117
6118
6119
6120

6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153



6154
6155
6156
6157
6158
6159
6160
** once prior to any call to seriesColumn() or seriesRowid() or
** seriesEof().
**
** The query plan selected by seriesBestIndex is passed in the idxNum
** parameter.  (idxStr is not used in this implementation.)  idxNum
** is a bitmask showing which constraints are available:
**
**    1:    start=VALUE
**    2:    stop=VALUE
**    4:    step=VALUE
**
** Also, if bit 8 is set, that means that the series should be output
** in descending order rather than in ascending order.  If bit 16 is
** set, then output must appear in ascending order.


**
** This routine should initialize the cursor and position it so that it
** is pointing at the first row, or pointing off the end of the table
** (so that seriesEof() will return true) if the table is empty.
*/
static int seriesFilter(
  sqlite3_vtab_cursor *pVtabCursor,
  int idxNum, const char *idxStrUnused,
  int argc, sqlite3_value **argv
){
  series_cursor *pCur = (series_cursor *)pVtabCursor;
  int i = 0;
  (void)idxStrUnused;
  if( idxNum & 1 ){
    pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
  }else{
    pCur->ss.iBase = 0;
  }
  if( idxNum & 2 ){
    pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
  }else{
    pCur->ss.iTerm = 0xffffffff;
  }
  if( idxNum & 4 ){
    pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
    if( pCur->ss.iStep==0 ){
      pCur->ss.iStep = 1;
    }else if( pCur->ss.iStep<0 ){
      if( (idxNum & 16)==0 ) idxNum |= 8;
    }
  }else{
    pCur->ss.iStep = 1;
  }


















  for(i=0; i<argc; i++){
    if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
      /* If any of the constraints have a NULL value, then return no rows.
      ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
      pCur->ss.iBase = 1;
      pCur->ss.iTerm = 0;
      pCur->ss.iStep = 1;
      break;
    }
  }
  if( idxNum & 8 ){
    pCur->ss.isReversing = pCur->ss.iStep > 0;
  }else{
    pCur->ss.isReversing = pCur->ss.iStep < 0;
  }
  setupSequence( &pCur->ss );
  return SQLITE_OK;
}

/*
** SQLite will invoke this method one or more times while planning a query
** that uses the generate_series virtual table.  This routine needs to create
** a query plan for each invocation and compute an estimated cost for that
** plan.
**
** In this implementation idxNum is used to represent the
** query plan.  idxStr is unused.
**
** The query plan is represented by bits in idxNum:
**
**  (1)  start = $value  -- constraint exists
**  (2)  stop = $value   -- constraint exists
**  (4)  step = $value   -- constraint exists
**  (8)  output in descending order



*/
static int seriesBestIndex(
  sqlite3_vtab *pVTab,
  sqlite3_index_info *pIdxInfo
){
  int i, j;              /* Loop over constraints */
  int idxNum = 0;        /* The query plan bitmask */

  int bStartSeen = 0;    /* EQ constraint seen on the START column */

  int unusableMask = 0;  /* Mask of unusable constraints */
  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
  int aIdx[3];           /* Constraints on start, stop, and step */
  const struct sqlite3_index_constraint *pConstraint;

  /* This implementation assumes that the start, stop, and step columns
  ** are the last three columns in the virtual table. */
  assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
  assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );

  aIdx[0] = aIdx[1] = aIdx[2] = -1;
  pConstraint = pIdxInfo->aConstraint;
  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
    int iCol;    /* 0 for start, 1 for stop, 2 for step */
    int iMask;   /* bitmask for those column */
















    if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
    iCol = pConstraint->iColumn - SERIES_COLUMN_START;
    assert( iCol>=0 && iCol<=2 );
    iMask = 1 << iCol;


    if( iCol==0 ) bStartSeen = 1;


    if( pConstraint->usable==0 ){
      unusableMask |=  iMask;
      continue;
    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
      idxNum |= iMask;
      aIdx[iCol] = i;
    }
  }





  for(i=0; i<3; i++){
    if( (j = aIdx[i])>=0 ){
      pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
      pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;

    }
  }
  /* The current generate_column() implementation requires at least one
  ** argument (the START value).  Legacy versions assumed START=0 if the
  ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
  ** to obtain the legacy behavior */
#ifndef ZERO_ARGUMENT_GENERATE_SERIES
  if( !bStartSeen ){
    sqlite3_free(pVTab->zErrMsg);
    pVTab->zErrMsg = sqlite3_mprintf(
        "first argument to \"generate_series()\" missing or unusable");
    return SQLITE_ERROR;
  }
#endif
  if( (unusableMask & ~idxNum)!=0 ){
    /* The start, stop, and step columns are inputs.  Therefore if there
    ** are unusable constraints on any of start, stop, or step then
    ** this plan is unusable */
    return SQLITE_CONSTRAINT;
  }
  if( (idxNum & 3)==3 ){
    /* Both start= and stop= boundaries are available.  This is the 
    ** the preferred case */
    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
    pIdxInfo->estimatedRows = 1000;
    if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
      if( pIdxInfo->aOrderBy[0].desc ){
        idxNum |= 8;
      }else{
        idxNum |= 16;
      }
      pIdxInfo->orderByConsumed = 1;
    }



  }else{
    /* If either boundary is missing, we have to generate a huge span
    ** of numbers.  Make this case very expensive so that the query
    ** planner will work hard to avoid it. */
    pIdxInfo->estimatedRows = 2147483647;
  }
  pIdxInfo->idxNum = idxNum;
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
  mode_t mode,                    /* MODE parameter passed to writefile() */
  sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
){
  if( zFile==0 ) return 1;
#if !defined(_WIN32) && !defined(WIN32)
  if( S_ISLNK(mode) ){
    const char *zTo = (const char*)sqlite3_value_text(pData);
    if( zTo==0 ) return 1;
    unlink(zFile);
    if( symlink(zTo, zFile)<0 ) return 1;
  }else
#endif
  {
    if( S_ISDIR(mode) ){
      if( mkdir(zFile, mode) ){
        /* The mkdir() call to create the directory failed. This might not
        ** be an error though - if there is already a directory at the same







<
<
|







7473
7474
7475
7476
7477
7478
7479


7480
7481
7482
7483
7484
7485
7486
7487
  mode_t mode,                    /* MODE parameter passed to writefile() */
  sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
){
  if( zFile==0 ) return 1;
#if !defined(_WIN32) && !defined(WIN32)
  if( S_ISLNK(mode) ){
    const char *zTo = (const char*)sqlite3_value_text(pData);


    if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
  }else
#endif
  {
    if( S_ISDIR(mode) ){
      if( mkdir(zFile, mode) ){
        /* The mkdir() call to create the directory failed. This might not
        ** be an error though - if there is already a directory at the same
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
    times[0].tv_nsec = times[1].tv_nsec = 0;
    times[0].tv_sec = time(0);
    times[1].tv_sec = mtime;
    if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
      return 1;
    }
#else
    /* Legacy unix. 
    **
    ** Do not use utimes() on a symbolic link - it sees through the link and
    ** modifies the timestamps on the target. Or fails if the target does 
    ** not exist.  */
    if( 0==S_ISLNK(mode) ){
      struct timeval times[2];
      times[0].tv_usec = times[1].tv_usec = 0;
      times[0].tv_sec = time(0);
      times[1].tv_sec = mtime;
      if( utimes(zFile, times) ){
        return 1;
      }
    }
#endif
  }

  return 0;
}








|
<
<
<
<
<
|
|
|
|
|
|
<







7559
7560
7561
7562
7563
7564
7565
7566





7567
7568
7569
7570
7571
7572

7573
7574
7575
7576
7577
7578
7579
    times[0].tv_nsec = times[1].tv_nsec = 0;
    times[0].tv_sec = time(0);
    times[1].tv_sec = mtime;
    if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
      return 1;
    }
#else
    /* Legacy unix */





    struct timeval times[2];
    times[0].tv_usec = times[1].tv_usec = 0;
    times[0].tv_sec = time(0);
    times[1].tv_sec = mtime;
    if( utimes(zFile, times) ){
      return 1;

    }
#endif
  }

  return 0;
}

9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
**    *  Only the "inflate/deflate" (zlib) compression method is supported
*/
/* #include "sqlite3ext.h" */
SQLITE_EXTENSION_INIT1
#include <stdio.h>
#include <string.h>
#include <assert.h>
#ifndef SQLITE_NO_STDINT
#  include <stdint.h>
#endif

#include <zlib.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

#ifndef SQLITE_AMALGAMATION








<
|
<







9346
9347
9348
9349
9350
9351
9352

9353

9354
9355
9356
9357
9358
9359
9360
**    *  Only the "inflate/deflate" (zlib) compression method is supported
*/
/* #include "sqlite3ext.h" */
SQLITE_EXTENSION_INIT1
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include <stdint.h>


#include <zlib.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

#ifndef SQLITE_AMALGAMATION

11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
*/
static void sqlarUncompressFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  uLong nData;
  sqlite3_int64 sz;

  assert( argc==2 );
  sz = sqlite3_value_int(argv[1]);

  if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
    sqlite3_result_value(context, argv[0]);
  }else{
    uLongf szf = sz;
    const Bytef *pData= sqlite3_value_blob(argv[0]);
    Bytef *pOut = sqlite3_malloc(sz);
    if( pOut==0 ){
      sqlite3_result_error_nomem(context);
    }else if( Z_OK!=uncompress(pOut, &szf, pData, nData) ){
      sqlite3_result_error(context, "error in uncompress()", -1);
    }else{
      sqlite3_result_blob(context, pOut, szf, SQLITE_TRANSIENT);
    }
    sqlite3_free(pOut);
  }
}

#ifdef _WIN32








|







<




|


|







11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651

11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
*/
static void sqlarUncompressFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  uLong nData;
  uLongf sz;

  assert( argc==2 );
  sz = sqlite3_value_int(argv[1]);

  if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
    sqlite3_result_value(context, argv[0]);
  }else{

    const Bytef *pData= sqlite3_value_blob(argv[0]);
    Bytef *pOut = sqlite3_malloc(sz);
    if( pOut==0 ){
      sqlite3_result_error_nomem(context);
    }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
      sqlite3_result_error(context, "error in uncompress()", -1);
    }else{
      sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
    }
    sqlite3_free(pOut);
  }
}

#ifdef _WIN32

14068
14069
14070
14071
14072
14073
14074

14075
14076
14077
14078
14079
14080
14081
    sqlite3_free(p);
  }
}

#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */

/************************* End ../ext/expert/sqlite3expert.c ********************/

/************************* Begin ../ext/intck/sqlite3intck.h ******************/
/*
** 2024-02-08
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**







>







14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
    sqlite3_free(p);
  }
}

#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */

/************************* End ../ext/expert/sqlite3expert.c ********************/

/************************* Begin ../ext/intck/sqlite3intck.h ******************/
/*
** 2024-02-08
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
      p->zTestSql = 0;
    }
  }
  return p->zTestSql;
}

/************************* End ../ext/intck/sqlite3intck.c ********************/
/************************* Begin ../ext/misc/stmtrand.c ******************/
/*
** 2024-05-24
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** An SQL function that return pseudo-random non-negative integers.
**
**      SELECT stmtrand(123);
**
** A special feature of this function is that the same sequence of random
** integers is returned for each invocation of the statement.  This makes
** the results repeatable, and hence useful for testing.  The argument is
** an integer which is the seed for the random number sequence.  The seed
** is used by the first invocation of this function only and is ignored
** for all subsequent calls within the same statement.
**
** Resetting a statement (sqlite3_reset()) also resets the random number
** sequence.
*/
/* #include "sqlite3ext.h" */
SQLITE_EXTENSION_INIT1
#include <assert.h>
#include <string.h>

/* State of the pseudo-random number generator */
typedef struct Stmtrand {
  unsigned int x, y;
} Stmtrand;

/* auxdata key */
#define STMTRAND_KEY  (-4418371)

/*
** Function:     stmtrand(SEED)
**
** Return a pseudo-random number.
*/
static void stmtrandFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  Stmtrand *p;

  p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
  if( p==0 ){
    unsigned int seed;
    p = sqlite3_malloc( sizeof(*p) );
    if( p==0 ){
      sqlite3_result_error_nomem(context);
      return;
    }
    if( argc>=1 ){
      seed = (unsigned int)sqlite3_value_int(argv[0]);
    }else{
      seed = 0;
    }
    p->x = seed | 1;
    p->y = seed;
    sqlite3_set_auxdata(context, STMTRAND_KEY, p, sqlite3_free);
    p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
    if( p==0 ){
      sqlite3_result_error_nomem(context);
      return;
    }
  }
  p->x = (p->x>>1) ^ ((1+~(p->x&1)) & 0xd0000001);
  p->y = p->y*1103515245 + 12345;
  sqlite3_result_int(context, (int)((p->x ^ p->y)&0x7fffffff));
}

#ifdef _WIN32

#endif
int sqlite3_stmtrand_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
  SQLITE_EXTENSION_INIT2(pApi);
  (void)pzErrMsg;  /* Unused parameter */
  rc = sqlite3_create_function(db, "stmtrand", 1, SQLITE_UTF8, 0,
                               stmtrandFunc, 0, 0);
  if( rc==SQLITE_OK ){
    rc = sqlite3_create_function(db, "stmtrand", 0, SQLITE_UTF8, 0,
                                 stmtrandFunc, 0, 0);
  }
  return rc;
}

/************************* End ../ext/misc/stmtrand.c ********************/

#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
#define SQLITE_SHELL_HAVE_RECOVER 1
#else
#define SQLITE_SHELL_HAVE_RECOVER 0
#endif
#if SQLITE_SHELL_HAVE_RECOVER







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







15123
15124
15125
15126
15127
15128
15129




































































































15130
15131
15132
15133
15134
15135
15136
      p->zTestSql = 0;
    }
  }
  return p->zTestSql;
}

/************************* End ../ext/intck/sqlite3intck.c ********************/





































































































#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
#define SQLITE_SHELL_HAVE_RECOVER 1
#else
#define SQLITE_SHELL_HAVE_RECOVER 0
#endif
#if SQLITE_SHELL_HAVE_RECOVER
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675

#ifndef SQLITE_OMIT_VIRTUALTABLE

#define DBDATA_PADDING_BYTES 100 

typedef struct DbdataTable DbdataTable;
typedef struct DbdataCursor DbdataCursor;
typedef struct DbdataBuffer DbdataBuffer;

/*
** Buffer type.
*/
struct DbdataBuffer {
  u8 *aBuf;
  sqlite3_int64 nBuf;
};

/* Cursor object */
struct DbdataCursor {
  sqlite3_vtab_cursor base;       /* Base class.  Must be first */
  sqlite3_stmt *pStmt;            /* For fetching database pages */

  int iPgno;                      /* Current page number */
  u8 *aPage;                      /* Buffer containing page */
  int nPage;                      /* Size of aPage[] in bytes */
  int nCell;                      /* Number of cells on aPage[] */
  int iCell;                      /* Current cell number */
  int bOnePage;                   /* True to stop after one page */
  int szDb;
  sqlite3_int64 iRowid;

  /* Only for the sqlite_dbdata table */
  DbdataBuffer rec;
  sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
  sqlite3_int64 nHdr;             /* Size of header in bytes */
  int iField;                     /* Current field number */
  u8 *pHdrPtr;
  u8 *pPtr;
  u32 enc;                        /* Text encoding */
  







<
<
<
<
<
<
<
<
<
















|







15474
15475
15476
15477
15478
15479
15480









15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504

#ifndef SQLITE_OMIT_VIRTUALTABLE

#define DBDATA_PADDING_BYTES 100 

typedef struct DbdataTable DbdataTable;
typedef struct DbdataCursor DbdataCursor;










/* Cursor object */
struct DbdataCursor {
  sqlite3_vtab_cursor base;       /* Base class.  Must be first */
  sqlite3_stmt *pStmt;            /* For fetching database pages */

  int iPgno;                      /* Current page number */
  u8 *aPage;                      /* Buffer containing page */
  int nPage;                      /* Size of aPage[] in bytes */
  int nCell;                      /* Number of cells on aPage[] */
  int iCell;                      /* Current cell number */
  int bOnePage;                   /* True to stop after one page */
  int szDb;
  sqlite3_int64 iRowid;

  /* Only for the sqlite_dbdata table */
  u8 *pRec;                       /* Buffer containing current record */
  sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
  sqlite3_int64 nHdr;             /* Size of header in bytes */
  int iField;                     /* Current field number */
  u8 *pHdrPtr;
  u8 *pPtr;
  u32 enc;                        /* Text encoding */
  
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
#define DBPTR_SCHEMA              \
      "CREATE TABLE x("           \
      "  pgno INTEGER,"           \
      "  child INTEGER,"          \
      "  schema TEXT HIDDEN"      \
      ")"

/*
** Ensure the buffer passed as the first argument is at least nMin bytes
** in size. If an error occurs while attempting to resize the buffer,
** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
*/
static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){
  if( nMin>pBuf->nBuf ){
    sqlite3_int64 nNew = nMin+16384;
    u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew);

    if( aNew==0 ) return SQLITE_NOMEM;
    pBuf->aBuf = aNew;
    pBuf->nBuf = nNew;
  }
  return SQLITE_OK;
}

/*
** Release the allocation managed by buffer pBuf.
*/
static void dbdataBufferFree(DbdataBuffer *pBuf){
  sqlite3_free(pBuf->aBuf);
  memset(pBuf, 0, sizeof(*pBuf));
}

/*
** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual 
** table.
*/
static int dbdataConnect(
  sqlite3 *db,
  void *pAux,







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







15535
15536
15537
15538
15539
15540
15541

























15542
15543
15544
15545
15546
15547
15548
#define DBPTR_SCHEMA              \
      "CREATE TABLE x("           \
      "  pgno INTEGER,"           \
      "  child INTEGER,"          \
      "  schema TEXT HIDDEN"      \
      ")"


























/*
** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual 
** table.
*/
static int dbdataConnect(
  sqlite3 *db,
  void *pAux,
15871
15872
15873
15874
15875
15876
15877

15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
  }
  pCsr->pStmt = 0;
  pCsr->iPgno = 1;
  pCsr->iCell = 0;
  pCsr->iField = 0;
  pCsr->bOnePage = 0;
  sqlite3_free(pCsr->aPage);

  dbdataBufferFree(&pCsr->rec);
  pCsr->aPage = 0;
  pCsr->nRec = 0;
}

/*
** Close an sqlite_dbdata or sqlite_dbptr cursor.
*/
static int dbdataClose(sqlite3_vtab_cursor *pCursor){
  DbdataCursor *pCsr = (DbdataCursor*)pCursor;







>
|

<







15675
15676
15677
15678
15679
15680
15681
15682
15683
15684

15685
15686
15687
15688
15689
15690
15691
  }
  pCsr->pStmt = 0;
  pCsr->iPgno = 1;
  pCsr->iCell = 0;
  pCsr->iField = 0;
  pCsr->bOnePage = 0;
  sqlite3_free(pCsr->aPage);
  sqlite3_free(pCsr->pRec);
  pCsr->pRec = 0;
  pCsr->aPage = 0;

}

/*
** Close an sqlite_dbdata or sqlite_dbptr cursor.
*/
static int dbdataClose(sqlite3_vtab_cursor *pCursor){
  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
static void dbdataValue(
  sqlite3_context *pCtx, 
  u32 enc,
  int eType, 
  u8 *pData,
  sqlite3_int64 nData
){
  if( eType>=0 ){
    if( dbdataValueBytes(eType)<=nData ){
      switch( eType ){
        case 0: 
        case 10: 
        case 11: 
          sqlite3_result_null(pCtx);
          break;
        
        case 8: 
          sqlite3_result_int(pCtx, 0);
          break;
        case 9:
          sqlite3_result_int(pCtx, 1);
          break;
    
        case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
          sqlite3_uint64 v = (signed char)pData[0];
          pData++;
          switch( eType ){
            case 7:
            case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
            case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
            case 4:  v = (v<<8) + pData[0];  pData++;
            case 3:  v = (v<<8) + pData[0];  pData++;
            case 2:  v = (v<<8) + pData[0];  pData++;
          }
    
          if( eType==7 ){
            double r;
            memcpy(&r, &v, sizeof(r));
            sqlite3_result_double(pCtx, r);
          }else{
            sqlite3_result_int64(pCtx, (sqlite3_int64)v);
          }
          break;
        }
    
        default: {
          int n = ((eType-12) / 2);
          if( eType % 2 ){
            switch( enc ){
  #ifndef SQLITE_OMIT_UTF16
              case SQLITE_UTF16BE:
                sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
                break;
              case SQLITE_UTF16LE:
                sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
                break;
  #endif
              default:
                sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
                break;
            }
          }else{
            sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
          }
        }
      }
    }else{
      if( eType==7 ){
        sqlite3_result_double(pCtx, 0.0);
      }else if( eType<7 ){
        sqlite3_result_int(pCtx, 0);
      }else if( eType%2 ){
        sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
      }else{
        sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC);
      }
    }
  }
}

/* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
** a page-size, it returns the maximum number of cells that may be present







<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<







15819
15820
15821
15822
15823
15824
15825

15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881











15882
15883
15884
15885
15886
15887
15888
static void dbdataValue(
  sqlite3_context *pCtx, 
  u32 enc,
  int eType, 
  u8 *pData,
  sqlite3_int64 nData
){

  if( eType>=0 && dbdataValueBytes(eType)<=nData ){
    switch( eType ){
      case 0: 
      case 10: 
      case 11: 
        sqlite3_result_null(pCtx);
        break;
      
      case 8: 
        sqlite3_result_int(pCtx, 0);
        break;
      case 9:
        sqlite3_result_int(pCtx, 1);
        break;
  
      case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
        sqlite3_uint64 v = (signed char)pData[0];
        pData++;
        switch( eType ){
          case 7:
          case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
          case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
          case 4:  v = (v<<8) + pData[0];  pData++;
          case 3:  v = (v<<8) + pData[0];  pData++;
          case 2:  v = (v<<8) + pData[0];  pData++;
        }
  
        if( eType==7 ){
          double r;
          memcpy(&r, &v, sizeof(r));
          sqlite3_result_double(pCtx, r);
        }else{
          sqlite3_result_int64(pCtx, (sqlite3_int64)v);
        }
        break;
      }
  
      default: {
        int n = ((eType-12) / 2);
        if( eType % 2 ){
          switch( enc ){
#ifndef SQLITE_OMIT_UTF16
            case SQLITE_UTF16BE:
              sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
              break;
            case SQLITE_UTF16LE:
              sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
              break;
#endif
            default:
              sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
              break;
          }
        }else{
          sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
        }











      }
    }
  }
}

/* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
** a page-size, it returns the maximum number of cells that may be present
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
        if( pCsr->bOnePage ) return SQLITE_OK;
        pCsr->iPgno++;
      }else{
        return SQLITE_OK;
      }
    }else{
      /* If there is no record loaded, load it now. */
      assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 );
      if( pCsr->nRec==0 ){
        int bHasRowid = 0;
        int nPointer = 0;
        sqlite3_int64 nPayload = 0;
        sqlite3_int64 nHdr = 0;
        int iHdr;
        int U, X;
        int nLocal;







<
|







15937
15938
15939
15940
15941
15942
15943

15944
15945
15946
15947
15948
15949
15950
15951
        if( pCsr->bOnePage ) return SQLITE_OK;
        pCsr->iPgno++;
      }else{
        return SQLITE_OK;
      }
    }else{
      /* If there is no record loaded, load it now. */

      if( pCsr->pRec==0 ){
        int bHasRowid = 0;
        int nPointer = 0;
        sqlite3_int64 nPayload = 0;
        sqlite3_int64 nHdr = 0;
        int iHdr;
        int U, X;
        int nLocal;
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
    
          /* Load the "byte of payload including overflow" field */
          if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
            bNextPage = 1;
          }else{
            iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
            if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
            if( nPayload==0 ) nPayload = 1;
          }
    
          /* If this is a leaf intkey cell, load the rowid */
          if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
          }
    







<







15981
15982
15983
15984
15985
15986
15987

15988
15989
15990
15991
15992
15993
15994
    
          /* Load the "byte of payload including overflow" field */
          if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
            bNextPage = 1;
          }else{
            iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
            if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;

          }
    
          /* If this is a leaf intkey cell, load the rowid */
          if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
          }
    
16225
16226
16227
16228
16229
16230
16231
16232
16233

16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296

16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307

16308
16309
16310
16311
16312
16313
16314
16315
          if( bNextPage || nLocal+iOff>pCsr->nPage ){
            bNextPage = 1;
          }else{

            /* Allocate space for payload. And a bit more to catch small buffer
            ** overruns caused by attempting to read a varint or similar from 
            ** near the end of a corrupt record.  */
            rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES);
            if( rc!=SQLITE_OK ) return rc;

            assert( nPayload!=0 );

            /* Load the nLocal bytes of payload */
            memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal);
            iOff += nLocal;

            /* Load content from overflow pages */
            if( nPayload>nLocal ){
              sqlite3_int64 nRem = nPayload - nLocal;
              u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
              while( nRem>0 ){
                u8 *aOvfl = 0;
                int nOvfl = 0;
                int nCopy;
                rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
                assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
                if( rc!=SQLITE_OK ) return rc;
                if( aOvfl==0 ) break;

                nCopy = U-4;
                if( nCopy>nRem ) nCopy = nRem;
                memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy);
                nRem -= nCopy;

                pgnoOvfl = get_uint32(aOvfl);
                sqlite3_free(aOvfl);
              }
              nPayload -= nRem;
            }
            memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES);
            pCsr->nRec = nPayload;
    
            iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr);
            if( nHdr>nPayload ) nHdr = 0;
            pCsr->nHdr = nHdr;
            pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr];
            pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr];
            pCsr->iField = (bHasRowid ? -1 : 0);
          }
        }
      }else{
        pCsr->iField++;
        if( pCsr->iField>0 ){
          sqlite3_int64 iType;
          if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec] 
           || pCsr->iField>=DBDATA_MX_FIELD
          ){
            bNextPage = 1;
          }else{
            int szField = 0;
            pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
            szField = dbdataValueBytes(iType);
            if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){
              pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec];
            }else{
              pCsr->pPtr += szField;
            }
          }
        }
      }

      if( bNextPage ){
        sqlite3_free(pCsr->aPage);

        pCsr->aPage = 0;
        pCsr->nRec = 0;
        if( pCsr->bOnePage ) return SQLITE_OK;
        pCsr->iPgno++;
      }else{
        if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){
          return SQLITE_OK;
        }

        /* Advance to the next cell. The next iteration of the loop will load
        ** the record and so on. */

        pCsr->nRec = 0;
        pCsr->iCell++;
      }
    }
  }

  assert( !"can't get here" );
  return SQLITE_OK;







|
|
>
|


|

















|





<

<
<

|


|
|







|







|
|









>

|



|





>
|







16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051

16052


16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
          if( bNextPage || nLocal+iOff>pCsr->nPage ){
            bNextPage = 1;
          }else{

            /* Allocate space for payload. And a bit more to catch small buffer
            ** overruns caused by attempting to read a varint or similar from 
            ** near the end of a corrupt record.  */
            pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
            if( pCsr->pRec==0 ) return SQLITE_NOMEM;
            memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
            pCsr->nRec = nPayload;

            /* Load the nLocal bytes of payload */
            memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
            iOff += nLocal;

            /* Load content from overflow pages */
            if( nPayload>nLocal ){
              sqlite3_int64 nRem = nPayload - nLocal;
              u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
              while( nRem>0 ){
                u8 *aOvfl = 0;
                int nOvfl = 0;
                int nCopy;
                rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
                assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
                if( rc!=SQLITE_OK ) return rc;
                if( aOvfl==0 ) break;

                nCopy = U-4;
                if( nCopy>nRem ) nCopy = nRem;
                memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
                nRem -= nCopy;

                pgnoOvfl = get_uint32(aOvfl);
                sqlite3_free(aOvfl);
              }

            }


    
            iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
            if( nHdr>nPayload ) nHdr = 0;
            pCsr->nHdr = nHdr;
            pCsr->pHdrPtr = &pCsr->pRec[iHdr];
            pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
            pCsr->iField = (bHasRowid ? -1 : 0);
          }
        }
      }else{
        pCsr->iField++;
        if( pCsr->iField>0 ){
          sqlite3_int64 iType;
          if( pCsr->pHdrPtr>=&pCsr->pRec[pCsr->nRec] 
           || pCsr->iField>=DBDATA_MX_FIELD
          ){
            bNextPage = 1;
          }else{
            int szField = 0;
            pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
            szField = dbdataValueBytes(iType);
            if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){
              pCsr->pPtr = &pCsr->pRec[pCsr->nRec];
            }else{
              pCsr->pPtr += szField;
            }
          }
        }
      }

      if( bNextPage ){
        sqlite3_free(pCsr->aPage);
        sqlite3_free(pCsr->pRec);
        pCsr->aPage = 0;
        pCsr->pRec = 0;
        if( pCsr->bOnePage ) return SQLITE_OK;
        pCsr->iPgno++;
      }else{
        if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
          return SQLITE_OK;
        }

        /* Advance to the next cell. The next iteration of the loop will load
        ** the record and so on. */
        sqlite3_free(pCsr->pRec);
        pCsr->pRec = 0;
        pCsr->iCell++;
      }
    }
  }

  assert( !"can't get here" );
  return SQLITE_OK;
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
        break;
      case DBDATA_COLUMN_FIELD:
        sqlite3_result_int(ctx, pCsr->iField);
        break;
      case DBDATA_COLUMN_VALUE: {
        if( pCsr->iField<0 ){
          sqlite3_result_int64(ctx, pCsr->iIntkey);
        }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){
          sqlite3_int64 iType;
          dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
          dbdataValue(
              ctx, pCsr->enc, iType, pCsr->pPtr, 
              &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr
          );
        }
        break;
      }
    }
  }
  return SQLITE_OK;







|




|







16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
        break;
      case DBDATA_COLUMN_FIELD:
        sqlite3_result_int(ctx, pCsr->iField);
        break;
      case DBDATA_COLUMN_VALUE: {
        if( pCsr->iField<0 ){
          sqlite3_result_int64(ctx, pCsr->iIntkey);
        }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
          sqlite3_int64 iType;
          dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
          dbdataValue(
              ctx, pCsr->enc, iType, pCsr->pPtr, 
              &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
          );
        }
        break;
      }
    }
  }
  return SQLITE_OK;
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
        if( pArg->autoEQP>=AUTOEQP_trigger ){
          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
        }
        pExplain = pStmt;
        sqlite3_reset(pExplain);
        rc = sqlite3_stmt_explain(pExplain, 2);
        if( rc==SQLITE_OK ){
          bind_prepared_stmt(pArg, pExplain);
          while( sqlite3_step(pExplain)==SQLITE_ROW ){
            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
            int iEqpId = sqlite3_column_int(pExplain, 0);
            int iParentId = sqlite3_column_int(pExplain, 1);
            if( zEQPLine==0 ) zEQPLine = "";
            if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
          }
          eqp_render(pArg, 0);
        }
        if( pArg->autoEQP>=AUTOEQP_full ){
          /* Also do an EXPLAIN for ".eqp full" mode */
          sqlite3_reset(pExplain);
          rc = sqlite3_stmt_explain(pExplain, 1);
          if( rc==SQLITE_OK ){
            pArg->cMode = MODE_Explain;
            assert( sqlite3_stmt_isexplain(pExplain)==1 );
            bind_prepared_stmt(pArg, pExplain);
            explain_data_prepare(pArg, pExplain);
            exec_prepared_stmt(pArg, pExplain);
            explain_data_delete(pArg);
          }
        }
        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);







<

















<







22248
22249
22250
22251
22252
22253
22254

22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271

22272
22273
22274
22275
22276
22277
22278
        if( pArg->autoEQP>=AUTOEQP_trigger ){
          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
        }
        pExplain = pStmt;
        sqlite3_reset(pExplain);
        rc = sqlite3_stmt_explain(pExplain, 2);
        if( rc==SQLITE_OK ){

          while( sqlite3_step(pExplain)==SQLITE_ROW ){
            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
            int iEqpId = sqlite3_column_int(pExplain, 0);
            int iParentId = sqlite3_column_int(pExplain, 1);
            if( zEQPLine==0 ) zEQPLine = "";
            if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
          }
          eqp_render(pArg, 0);
        }
        if( pArg->autoEQP>=AUTOEQP_full ){
          /* Also do an EXPLAIN for ".eqp full" mode */
          sqlite3_reset(pExplain);
          rc = sqlite3_stmt_explain(pExplain, 1);
          if( rc==SQLITE_OK ){
            pArg->cMode = MODE_Explain;
            assert( sqlite3_stmt_isexplain(pExplain)==1 );

            explain_data_prepare(pArg, pExplain);
            exec_prepared_stmt(pArg, pExplain);
            explain_data_delete(pArg);
          }
        }
        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
    }

#ifndef SQLITE_OMIT_LOAD_EXTENSION
    sqlite3_enable_load_extension(p->db, 1);
#endif
    sqlite3_shathree_init(p->db, 0, 0);
    sqlite3_uint_init(p->db, 0, 0);
    sqlite3_stmtrand_init(p->db, 0, 0);
    sqlite3_decimal_init(p->db, 0, 0);
    sqlite3_base64_init(p->db, 0, 0);
    sqlite3_base85_init(p->db, 0, 0);
    sqlite3_regexp_init(p->db, 0, 0);
    sqlite3_ieee_init(p->db, 0, 0);
    sqlite3_series_init(p->db, 0, 0);
#ifndef SQLITE_SHELL_FIDDLE







<







23359
23360
23361
23362
23363
23364
23365

23366
23367
23368
23369
23370
23371
23372
    }

#ifndef SQLITE_OMIT_LOAD_EXTENSION
    sqlite3_enable_load_extension(p->db, 1);
#endif
    sqlite3_shathree_init(p->db, 0, 0);
    sqlite3_uint_init(p->db, 0, 0);

    sqlite3_decimal_init(p->db, 0, 0);
    sqlite3_base64_init(p->db, 0, 0);
    sqlite3_base85_init(p->db, 0, 0);
    sqlite3_regexp_init(p->db, 0, 0);
    sqlite3_ieee_init(p->db, 0, 0);
    sqlite3_series_init(p->db, 0, 0);
#ifndef SQLITE_SHELL_FIDDLE
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
  (void)iEnd;
  rl_attempted_completion_over = 1;
  return rl_completion_matches(zText, readline_completion_generator);
}

#elif HAVE_LINENOISE
/*
** Linenoise completion callback. Note that the 3rd argument is from
** the "msteveb" version of linenoise, not the "antirez" version.
*/
static void linenoise_completion(const char *zLine, linenoiseCompletions *lc,
                                 void *pUserData){
  i64 nLine = strlen(zLine);
  i64 i, iStart;
  sqlite3_stmt *pStmt = 0;
  char *zSql;
  char zBuf[1000];

  UNUSED_PARAMETER(pUserData);
  if( nLine>(i64)sizeof(zBuf)-30 ) return;
  if( zLine[0]=='.' || zLine[0]=='#') return;
  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  if( i==nLine-1 ) return;
  iStart = i+1;
  memcpy(zBuf, zLine, iStart);
  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"







|
<

|
<






<







23512
23513
23514
23515
23516
23517
23518
23519

23520
23521

23522
23523
23524
23525
23526
23527

23528
23529
23530
23531
23532
23533
23534
  (void)iEnd;
  rl_attempted_completion_over = 1;
  return rl_completion_matches(zText, readline_completion_generator);
}

#elif HAVE_LINENOISE
/*
** Linenoise completion callback

*/
static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){

  i64 nLine = strlen(zLine);
  i64 i, iStart;
  sqlite3_stmt *pStmt = 0;
  char *zSql;
  char zBuf[1000];


  if( nLine>(i64)sizeof(zBuf)-30 ) return;
  if( zLine[0]=='.' || zLine[0]=='#') return;
  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  if( i==nLine-1 ) return;
  iStart = i+1;
  memcpy(zBuf, zLine, iStart);
  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
*/
static struct {
  int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
  int iErr;          /* The error code to return on a fault */
  int iCnt;          /* Trigger the fault only if iCnt is already zero */
  int iInterval;     /* Reset iCnt to this value after each fault */
  int eVerbose;      /* When to print output */
  int nHit;          /* Number of hits seen so far */
  int nRepeat;       /* Turn off after this many hits.  0 for never */
  int nSkip;         /* Skip this many before first fault */
} faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};

/*
** This is the fault-sim callback
*/
static int faultsim_callback(int iArg){
  if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
    return SQLITE_OK;
  }
  if( faultsim_state.iCnt ){
    if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
    if( faultsim_state.eVerbose>=2 ){
      oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
    }
    return SQLITE_OK;
  }
  if( faultsim_state.eVerbose>=1 ){
    oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
  }
  faultsim_state.iCnt = faultsim_state.iInterval;
  faultsim_state.nHit++;
  if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
    faultsim_state.iCnt = -1;
  }
  return faultsim_state.iErr;
}

/*
** If an input line begins with "." then invoke this routine to
** process that line.
**







<
<
<
|








|
|









<
<
<
<







25935
25936
25937
25938
25939
25940
25941



25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961




25962
25963
25964
25965
25966
25967
25968
*/
static struct {
  int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
  int iErr;          /* The error code to return on a fault */
  int iCnt;          /* Trigger the fault only if iCnt is already zero */
  int iInterval;     /* Reset iCnt to this value after each fault */
  int eVerbose;      /* When to print output */



} faultsim_state = {-1, 0, 0, 0, 0};

/*
** This is the fault-sim callback
*/
static int faultsim_callback(int iArg){
  if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
    return SQLITE_OK;
  }
  if( faultsim_state.iCnt>0 ){
    faultsim_state.iCnt--;
    if( faultsim_state.eVerbose>=2 ){
      oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
    }
    return SQLITE_OK;
  }
  if( faultsim_state.eVerbose>=1 ){
    oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
  }
  faultsim_state.iCnt = faultsim_state.iInterval;




  return faultsim_state.iErr;
}

/*
** If an input line begins with "." then invoke this routine to
** process that line.
**
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
        sqlite3_free(zRenames);
      }
      assert(dbCols==0);
      if( zColDefs==0 ){
        eputf("%s: empty file\n", sCtx.zFile);
        import_cleanup(&sCtx);
        rc = 1;
        sqlite3_free(zCreate);
        goto meta_command_exit;
      }
      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
      if( zCreate==0 ){
        import_cleanup(&sCtx);
        shell_out_of_memory();
      }







<







26939
26940
26941
26942
26943
26944
26945

26946
26947
26948
26949
26950
26951
26952
        sqlite3_free(zRenames);
      }
      assert(dbCols==0);
      if( zColDefs==0 ){
        eputf("%s: empty file\n", sCtx.zFile);
        import_cleanup(&sCtx);
        rc = 1;

        goto meta_command_exit;
      }
      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
      if( zCreate==0 ){
        import_cleanup(&sCtx);
        shell_out_of_memory();
      }
27189
27190
27191
27192
27193
27194
27195

27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
    }
    zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
                           zTable, zSchema);
    if( zSql==0 ){
      import_cleanup(&sCtx);
      shell_out_of_memory();
    }

    rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    zSql = 0;
    if( rc ){
      if (pStmt) sqlite3_finalize(pStmt);
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      import_cleanup(&sCtx);
      rc = 1;
      goto meta_command_exit;
    }
    if( sqlite3_step(pStmt)==SQLITE_ROW ){
      nCol = sqlite3_column_int(pStmt, 0);
    }else{
      nCol = 0;
    }
    sqlite3_finalize(pStmt);
    pStmt = 0;
    if( nCol==0 ) return 0; /* no columns, no error */

    nByte = 64                 /* space for "INSERT INTO", "VALUES(", ")\0" */
          + (zSchema ? strlen(zSchema)*2 + 2: 0)  /* Quoted schema name */
          + strlen(zTable)*2 + 2                  /* Quoted table name */
          + nCol*2;            /* Space for ",?" for each column */
    zSql = sqlite3_malloc64( nByte );
    if( zSql==0 ){
      import_cleanup(&sCtx);
      shell_out_of_memory();
    }
    if( zSchema ){
      sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", 
                       zSchema, zTable);
    }else{
      sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
    }
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;
    assert( j<nByte );
    if( eVerbose>=2 ){
      oputf("Insert using: %s\n", zSql);
    }
    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    zSql = 0;
    if( rc ){







>


















<
<
<
<
<
|





|


|








<







26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990





26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008

27009
27010
27011
27012
27013
27014
27015
    }
    zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
                           zTable, zSchema);
    if( zSql==0 ){
      import_cleanup(&sCtx);
      shell_out_of_memory();
    }
    nByte = strlen(zSql);    
    rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    zSql = 0;
    if( rc ){
      if (pStmt) sqlite3_finalize(pStmt);
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      import_cleanup(&sCtx);
      rc = 1;
      goto meta_command_exit;
    }
    if( sqlite3_step(pStmt)==SQLITE_ROW ){
      nCol = sqlite3_column_int(pStmt, 0);
    }else{
      nCol = 0;
    }
    sqlite3_finalize(pStmt);
    pStmt = 0;
    if( nCol==0 ) return 0; /* no columns, no error */





    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
    if( zSql==0 ){
      import_cleanup(&sCtx);
      shell_out_of_memory();
    }
    if( zSchema ){
      sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", 
                       zSchema, zTable);
    }else{
      sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
    }
    j = strlen30(zSql);
    for(i=1; i<nCol; i++){
      zSql[j++] = ',';
      zSql[j++] = '?';
    }
    zSql[j++] = ')';
    zSql[j] = 0;

    if( eVerbose>=2 ){
      oputf("Insert using: %s\n", zSql);
    }
    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
    sqlite3_free(zSql);
    zSql = 0;
    if( rc ){
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
    {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
    {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
    {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
    {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
#ifdef YYCOVERAGE
    {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
#endif
    {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,1, "OFFSET  "       },
    {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
    {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
    {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
    {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
    {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
    {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
    {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},







|







28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
    {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
    {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
    {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
    {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
#ifdef YYCOVERAGE
    {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
#endif
    {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
    {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
    {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
    {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
    {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
    {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
    {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
    {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
          isOk = 3;
          for(kk=2; kk<nArg; kk++){
            const char *z = azArg[kk];
            if( z[0]=='-' && z[1]=='-' ) z++;
            if( cli_strcmp(z,"off")==0 ){
              sqlite3_test_control(testctrl, 0);
            }else if( cli_strcmp(z,"on")==0 ){
              faultsim_state.iCnt = faultsim_state.nSkip;
              if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
              faultsim_state.nHit = 0;
              sqlite3_test_control(testctrl, faultsim_callback);
            }else if( cli_strcmp(z,"reset")==0 ){
              faultsim_state.iCnt = faultsim_state.nSkip;
              faultsim_state.nHit = 0;
              sqlite3_test_control(testctrl, faultsim_callback);
            }else if( cli_strcmp(z,"status")==0 ){
              oputf("faultsim.iId:       %d\n", faultsim_state.iId);
              oputf("faultsim.iErr:      %d\n", faultsim_state.iErr);
              oputf("faultsim.iCnt:      %d\n", faultsim_state.iCnt);
              oputf("faultsim.nHit:      %d\n", faultsim_state.nHit);
              oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
              oputf("faultsim.eVerbose:  %d\n", faultsim_state.eVerbose);
              oputf("faultsim.nRepeat:   %d\n", faultsim_state.nRepeat);
              oputf("faultsim.nSkip:     %d\n", faultsim_state.nSkip);
            }else if( cli_strcmp(z,"-v")==0 ){
              if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
            }else if( cli_strcmp(z,"-q")==0 ){
              if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
            }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
              faultsim_state.iId = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
              faultsim_state.iErr = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
              faultsim_state.iInterval = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
              faultsim_state.nRepeat = atoi(azArg[++kk]);
           }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
              faultsim_state.nSkip = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
              bShowHelp = 1;
            }else{
              eputf("Unrecognized fault_install argument: \"%s\"\n",
                  azArg[kk]);
              rc = 1;
              bShowHelp = 1;







|

<


|
<
<




<


<
<










<
<
<
<







29116
29117
29118
29119
29120
29121
29122
29123
29124

29125
29126
29127


29128
29129
29130
29131

29132
29133


29134
29135
29136
29137
29138
29139
29140
29141
29142
29143




29144
29145
29146
29147
29148
29149
29150
          isOk = 3;
          for(kk=2; kk<nArg; kk++){
            const char *z = azArg[kk];
            if( z[0]=='-' && z[1]=='-' ) z++;
            if( cli_strcmp(z,"off")==0 ){
              sqlite3_test_control(testctrl, 0);
            }else if( cli_strcmp(z,"on")==0 ){
              faultsim_state.iCnt = faultsim_state.iInterval;
              if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;

              sqlite3_test_control(testctrl, faultsim_callback);
            }else if( cli_strcmp(z,"reset")==0 ){
              faultsim_state.iCnt = faultsim_state.iInterval;


            }else if( cli_strcmp(z,"status")==0 ){
              oputf("faultsim.iId:       %d\n", faultsim_state.iId);
              oputf("faultsim.iErr:      %d\n", faultsim_state.iErr);
              oputf("faultsim.iCnt:      %d\n", faultsim_state.iCnt);

              oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
              oputf("faultsim.eVerbose:  %d\n", faultsim_state.eVerbose);


            }else if( cli_strcmp(z,"-v")==0 ){
              if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
            }else if( cli_strcmp(z,"-q")==0 ){
              if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
            }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
              faultsim_state.iId = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
              faultsim_state.iErr = atoi(azArg[++kk]);
            }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
              faultsim_state.iInterval = atoi(azArg[++kk]);




            }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
              bShowHelp = 1;
            }else{
              eputf("Unrecognized fault_install argument: \"%s\"\n",
                  azArg[kk]);
              rc = 1;
              bShowHelp = 1;
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
               "   reset             Reset the trigger counter\n"
               "   status            Show current status\n"
               "   -v                Increase verbosity\n"
               "   -q                Decrease verbosity\n"
               "   --errcode N       When triggered, return N as error code\n"
               "   --id ID           Trigger only for the ID specified\n"
               "   --interval N      Trigger only after every N-th call\n"
               "   --repeat N        Turn off after N hits.  0 means never\n"
               "   --skip N          Skip the first N encounters\n"
            );
          }
          break;
        }
      }
    }
    if( isOk==0 && iCtrl>=0 ){







<
<







29160
29161
29162
29163
29164
29165
29166


29167
29168
29169
29170
29171
29172
29173
               "   reset             Reset the trigger counter\n"
               "   status            Show current status\n"
               "   -v                Increase verbosity\n"
               "   -q                Decrease verbosity\n"
               "   --errcode N       When triggered, return N as error code\n"
               "   --id ID           Trigger only for the ID specified\n"
               "   --interval N      Trigger only after every N-th call\n"


            );
          }
          break;
        }
      }
    }
    if( isOk==0 && iCtrl>=0 ){
30957
30958
30959
30960
30961
30962
30963

30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977

30978
30979
30980
30981
30982
30983
30984
30985
30986
    ** command-line inputs, except for the argToSkip argument which contains
    ** the database filename.
    */
    for(i=0; i<nCmd; i++){
      if( azCmd[i][0]=='.' ){
        rc = do_meta_command(azCmd[i], &data);
        if( rc ){

          if( rc==2 ) rc = 0;
          goto shell_main_exit;
        }
      }else{
        open_db(&data, 0);
        echo_group_input(&data, azCmd[i]);
        rc = shell_exec(&data, azCmd[i], &zErrMsg);
        if( zErrMsg || rc ){
          if( zErrMsg!=0 ){
            eputf("Error: %s\n", zErrMsg);
          }else{
            eputf("Error: unable to process SQL: %s\n", azCmd[i]);
          }
          sqlite3_free(zErrMsg);

          if( rc==0 ) rc = 1;
          goto shell_main_exit;
        }
      }
    }
  }else{
    /* Run commands received from standard input
    */
    if( stdin_is_interactive ){







>
|
<












>
|
<







30716
30717
30718
30719
30720
30721
30722
30723
30724

30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738

30739
30740
30741
30742
30743
30744
30745
    ** command-line inputs, except for the argToSkip argument which contains
    ** the database filename.
    */
    for(i=0; i<nCmd; i++){
      if( azCmd[i][0]=='.' ){
        rc = do_meta_command(azCmd[i], &data);
        if( rc ){
          free(azCmd);
          return rc==2 ? 0 : rc;

        }
      }else{
        open_db(&data, 0);
        echo_group_input(&data, azCmd[i]);
        rc = shell_exec(&data, azCmd[i], &zErrMsg);
        if( zErrMsg || rc ){
          if( zErrMsg!=0 ){
            eputf("Error: %s\n", zErrMsg);
          }else{
            eputf("Error: unable to process SQL: %s\n", azCmd[i]);
          }
          sqlite3_free(zErrMsg);
          free(azCmd);
          return rc!=0 ? rc : 1;

        }
      }
    }
  }else{
    /* Run commands received from standard input
    */
    if( stdin_is_interactive ){
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
        }
      }
      if( zHistory ){ shell_read_history(zHistory); }
#if HAVE_READLINE || HAVE_EDITLINE
      rl_attempted_completion_function = readline_completion;
#elif HAVE_LINENOISE
      linenoiseSetCompletionCallback(linenoise_completion, NULL);
#endif
      data.in = 0;
      rc = process_input(&data);
      if( zHistory ){
        shell_stifle_history(2000);
        shell_write_history(zHistory);
        free(zHistory);







|







30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
        }
      }
      if( zHistory ){ shell_read_history(zHistory); }
#if HAVE_READLINE || HAVE_EDITLINE
      rl_attempted_completion_function = readline_completion;
#elif HAVE_LINENOISE
      linenoiseSetCompletionCallback(linenoise_completion);
#endif
      data.in = 0;
      rc = process_input(&data);
      if( zHistory ){
        shell_stifle_history(2000);
        shell_write_history(zHistory);
        free(zHistory);
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
  /* In WASM mode we have to leave the db state in place so that
  ** client code can "push" SQL into it after this call returns. */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( data.expert.pExpert ){
    expertFinish(&data, 1, 0);
  }
#endif
 shell_main_exit:
  free(azCmd);
  set_table_name(&data, 0);
  if( data.db ){
    session_close_all(&data, -1);
    close_db(data.db);
  }
  for(i=0; i<ArraySize(data.aAuxDb); i++){







<







30791
30792
30793
30794
30795
30796
30797

30798
30799
30800
30801
30802
30803
30804
  /* In WASM mode we have to leave the db state in place so that
  ** client code can "push" SQL into it after this call returns. */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( data.expert.pExpert ){
    expertFinish(&data, 1, 0);
  }
#endif

  free(azCmd);
  set_table_name(&data, 0);
  if( data.db ){
    session_close_all(&data, -1);
    close_db(data.db);
  }
  for(i=0; i<ArraySize(data.aAuxDb); i++){
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
  memset(&data, 0, sizeof(data));
#ifdef SQLITE_DEBUG
  if( sqlite3_memory_used()>mem_main_enter ){
    eputf("Memory leaked: %u bytes\n",
          (unsigned int)(sqlite3_memory_used()-mem_main_enter));
  }
#endif
#else /* SQLITE_SHELL_FIDDLE... */
  shell_main_exit:
#endif
  return rc;
}


#ifdef SQLITE_SHELL_FIDDLE
/* Only for emcc experimentation purposes. */
int fiddle_experiment(int a,int b){







|
<
<







30823
30824
30825
30826
30827
30828
30829
30830


30831
30832
30833
30834
30835
30836
30837
  memset(&data, 0, sizeof(data));
#ifdef SQLITE_DEBUG
  if( sqlite3_memory_used()>mem_main_enter ){
    eputf("Memory leaked: %u bytes\n",
          (unsigned int)(sqlite3_memory_used()-mem_main_enter));
  }
#endif
#endif /* !SQLITE_SHELL_FIDDLE */


  return rc;
}


#ifdef SQLITE_SHELL_FIDDLE
/* Only for emcc experimentation purposes. */
int fiddle_experiment(int a,int b){

Changes to extsrc/sqlite3.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.47.0.  By combining all the individual C code files into this
** single large file, the entire code can be compiled as a single translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% or more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
** programs, you need this file and the "sqlite3.h" header file that defines
** the programming interface to the SQLite library.  (If you do not have
** the "sqlite3.h" header file at hand, you will find a copy embedded within
** the text of this file.  Search for "Begin file sqlite3.h" to find the start
** of the embedded sqlite3.h header file.) Additional code files may be needed
** if you want a wrapper to interface SQLite with your choice of programming
** language. The code for the "sqlite3" command-line shell is also in a
** separate file. This file contains only code for the core SQLite library.
**
** The content in this amalgamation comes from Fossil check-in
** 33a3f327855b427ae6ba0057218d043a1417.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
/************** Begin file sqliteInt.h ***************************************/


|

















|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.46.0.  By combining all the individual C code files into this
** single large file, the entire code can be compiled as a single translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% or more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
** programs, you need this file and the "sqlite3.h" header file that defines
** the programming interface to the SQLite library.  (If you do not have
** the "sqlite3.h" header file at hand, you will find a copy embedded within
** the text of this file.  Search for "Begin file sqlite3.h" to find the start
** of the embedded sqlite3.h header file.) Additional code files may be needed
** if you want a wrapper to interface SQLite with your choice of programming
** language. The code for the "sqlite3" command-line shell is also in a
** separate file. This file contains only code for the core SQLite library.
**
** The content in this amalgamation comes from Fossil check-in
** 8c0f69e0e4ae0a446838cc193bfd4395fd25.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
/************** Begin file sqliteInt.h ***************************************/
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.47.0"
#define SQLITE_VERSION_NUMBER 3047000
#define SQLITE_SOURCE_ID      "2024-06-11 18:22:48 33a3f327855b427ae6ba0057218d043a1417bc9d780728f47f23acdd836e1686"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros







|
|
|







455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.46.0"
#define SQLITE_VERSION_NUMBER 3046000
#define SQLITE_SOURCE_ID      "2024-04-18 16:11:01 8c0f69e0e4ae0a446838cc193bfd4395fd251f3c7659b35ac388e5a0a7650a66"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
** <dd>The database is opened [shared cache] disabled, overriding
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
** <dd>The database connection comes up in "extended result code mode".
** In other words, the database behaves as if
** [sqlite3_extended_result_codes(db,1)] were called on the database
** connection as soon as the connection is created. In addition to setting
** the extended result code mode, this flag also causes [sqlite3_open_v2()]
** to return an extended result code.</dd>
**
** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
** <dd>The database filename is not allowed to contain a symbolic link</dd>
** </dl>)^







|
|







3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
** <dd>The database is opened [shared cache] disabled, overriding
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
** <dd>The database connection comes up in "extended result code mode".
** In other words, the database behaves has if
** [sqlite3_extended_result_codes(db,1)] where called on the database
** connection as soon as the connection is created. In addition to setting
** the extended result code mode, this flag also causes [sqlite3_open_v2()]
** to return an extended result code.</dd>
**
** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
** <dd>The database filename is not allowed to contain a symbolic link</dd>
** </dl>)^
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261

10262
10263
10264

10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
** that the query planner does not need the rows to be returned in sorted order
** as long as all rows with the same values in all columns identified by the
** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
** is doing a GROUP BY.
** <li value="2"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
** that the query planner does not need the rows returned in any particular
** order, as long as rows with the same values in all columns identified
** by "aOrderBy" are adjacent.)^  ^(Furthermore, when two or more rows
** contain the same values for all columns identified by "colUsed", all but
** one such row may optionally be omitted from the result.)^

** The virtual table is not required to omit rows that are duplicates
** over the "colUsed" columns, but if the virtual table can do that without
** too much extra effort, it could potentially help the query to run faster.

** This mode is used for a DISTINCT query.
** <li value="3"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the
** virtual table must return rows in the order defined by "aOrderBy" as
** if the sqlite3_vtab_distinct() interface had returned 0.  However if
** two or more rows in the result have the same values for all columns
** identified by "colUsed", then all but one such row may optionally be
** omitted.)^  Like when the return value is 2, the virtual table
** is not required to omit rows that are duplicates over the "colUsed"
** columns, but if the virtual table can do that without
** too much extra effort, it could potentially help the query to run faster.
** This mode is used for queries
** that have both DISTINCT and ORDER BY clauses.
** </ol>
**
** <p>The following table summarizes the conditions under which the
** virtual table is allowed to set the "orderByConsumed" flag based on
** the value returned by sqlite3_vtab_distinct().  This table is a
** restatement of the previous four paragraphs:
**
** <table border=1 cellspacing=0 cellpadding=10 width="90%">
** <tr>
** <td valign="top">sqlite3_vtab_distinct() return value
** <td valign="top">Rows are returned in aOrderBy order
** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent
** <td valign="top">Duplicates over all colUsed columns may be omitted
** <tr><td>0<td>yes<td>yes<td>no
** <tr><td>1<td>no<td>yes<td>no
** <tr><td>2<td>no<td>yes<td>yes
** <tr><td>3<td>yes<td>yes<td>yes
** </table>
**
** ^For the purposes of comparing virtual table output values to see if the
** values are same value for sorting purposes, two NULL values are considered
** to be the same.  In other words, the comparison operator is "IS"
** (or "IS NOT DISTINCT FROM") and not "==".
**
** If a virtual table implementation is unable to meet the requirements
** specified above, then it must not set the "orderByConsumed" flag in the







|
|
|
|
>
|
|
<
>


|
<
|
<
<
|
|
<
<
|



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264

10265
10266
10267
10268

10269


10270
10271


10272
10273
10274
10275

















10276
10277
10278
10279
10280
10281
10282
** that the query planner does not need the rows to be returned in sorted order
** as long as all rows with the same values in all columns identified by the
** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
** is doing a GROUP BY.
** <li value="2"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
** that the query planner does not need the rows returned in any particular
** order, as long as rows with the same values in all "aOrderBy" columns
** are adjacent.)^  ^(Furthermore, only a single row for each particular
** combination of values in the columns identified by the "aOrderBy" field
** needs to be returned.)^  ^It is always ok for two or more rows with the same
** values in all "aOrderBy" columns to be returned, as long as all such rows
** are adjacent.  ^The virtual table may, if it chooses, omit extra rows
** that have the same value for all columns identified by "aOrderBy".

** ^However omitting the extra rows is optional.
** This mode is used for a DISTINCT query.
** <li value="3"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 3, that means

** that the query planner needs only distinct rows but it does need the


** rows to be sorted.)^ ^The virtual table implementation is free to omit
** rows that are identical in all aOrderBy columns, if it wants to, but


** it is not required to omit any rows.  This mode is used for queries
** that have both DISTINCT and ORDER BY clauses.
** </ol>
**

















** ^For the purposes of comparing virtual table output values to see if the
** values are same value for sorting purposes, two NULL values are considered
** to be the same.  In other words, the comparison operator is "IS"
** (or "IS NOT DISTINCT FROM") and not "==".
**
** If a virtual table implementation is unable to meet the requirements
** specified above, then it must not set the "orderByConsumed" flag in the
11141
11142
11143
11144
11145
11146
11147


11148
11149
11150
11151
11152
11153
11154
#ifdef SQLITE_OMIT_FLOATING_POINT
# undef double
#endif

#if defined(__wasi__)
# undef SQLITE_WASI
# define SQLITE_WASI 1


# ifndef SQLITE_OMIT_LOAD_EXTENSION
#  define SQLITE_OMIT_LOAD_EXTENSION
# endif
# ifndef SQLITE_THREADSAFE
#  define SQLITE_THREADSAFE 0
# endif
#endif







>
>







11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
#ifdef SQLITE_OMIT_FLOATING_POINT
# undef double
#endif

#if defined(__wasi__)
# undef SQLITE_WASI
# define SQLITE_WASI 1
# undef SQLITE_OMIT_WAL
# define SQLITE_OMIT_WAL 1/* because it requires shared memory APIs */
# ifndef SQLITE_OMIT_LOAD_EXTENSION
#  define SQLITE_OMIT_LOAD_EXTENSION
# endif
# ifndef SQLITE_THREADSAFE
#  define SQLITE_THREADSAFE 0
# endif
#endif
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
** occurs during processing, this function returns SQLITE_NOMEM.
**
** In all cases, if an error occurs the state of the final contents of the
** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
*/
SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);

/*
** CAPI3REF: Add A Single Change To A Changegroup
** METHOD: sqlite3_changegroup
**
** This function adds the single change currently indicated by the iterator
** passed as the second argument to the changegroup object. The rules for
** adding the change are just as described for [sqlite3changegroup_add()].
**
** If the change is successfully added to the changegroup, SQLITE_OK is
** returned. Otherwise, an SQLite error code is returned.
**
** The iterator must point to a valid entry when this function is called.
** If it does not, SQLITE_ERROR is returned and no change is added to the
** changegroup. Additionally, the iterator must not have been opened with
** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also
** returned.
*/
SQLITE_API int sqlite3changegroup_add_change(
  sqlite3_changegroup*,
  sqlite3_changeset_iter*
);



/*
** CAPI3REF: Obtain A Composite Changeset From A Changegroup
** METHOD: sqlite3_changegroup
**
** Obtain a buffer containing a changeset (or patchset) representing the
** current contents of the changegroup. If the inputs to the changegroup







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







12312
12313
12314
12315
12316
12317
12318
























12319
12320
12321
12322
12323
12324
12325
** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
** occurs during processing, this function returns SQLITE_NOMEM.
**
** In all cases, if an error occurs the state of the final contents of the
** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
*/
SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);

























/*
** CAPI3REF: Obtain A Composite Changeset From A Changegroup
** METHOD: sqlite3_changegroup
**
** Obtain a buffer containing a changeset (or patchset) representing the
** current contents of the changegroup. If the inputs to the changegroup
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658

14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
#define TK_DESC                            39
#define TK_DETACH                          40
#define TK_EACH                            41
#define TK_FAIL                            42
#define TK_OR                              43
#define TK_AND                             44
#define TK_IS                              45
#define TK_ISNOT                           46
#define TK_MATCH                           47
#define TK_LIKE_KW                         48
#define TK_BETWEEN                         49
#define TK_IN                              50
#define TK_ISNULL                          51
#define TK_NOTNULL                         52
#define TK_NE                              53
#define TK_EQ                              54
#define TK_GT                              55
#define TK_LE                              56
#define TK_LT                              57
#define TK_GE                              58
#define TK_ESCAPE                          59
#define TK_ID                              60
#define TK_COLUMNKW                        61
#define TK_DO                              62
#define TK_FOR                             63
#define TK_IGNORE                          64
#define TK_INITIALLY                       65
#define TK_INSTEAD                         66
#define TK_NO                              67
#define TK_KEY                             68
#define TK_OF                              69
#define TK_OFFSET                          70
#define TK_PRAGMA                          71
#define TK_RAISE                           72
#define TK_RECURSIVE                       73
#define TK_REPLACE                         74
#define TK_RESTRICT                        75
#define TK_ROW                             76
#define TK_ROWS                            77
#define TK_TRIGGER                         78
#define TK_VACUUM                          79
#define TK_VIEW                            80
#define TK_VIRTUAL                         81
#define TK_WITH                            82
#define TK_NULLS                           83
#define TK_FIRST                           84
#define TK_LAST                            85
#define TK_CURRENT                         86
#define TK_FOLLOWING                       87
#define TK_PARTITION                       88
#define TK_PRECEDING                       89
#define TK_RANGE                           90
#define TK_UNBOUNDED                       91
#define TK_EXCLUDE                         92
#define TK_GROUPS                          93
#define TK_OTHERS                          94
#define TK_TIES                            95
#define TK_GENERATED                       96
#define TK_ALWAYS                          97
#define TK_MATERIALIZED                    98
#define TK_REINDEX                         99
#define TK_RENAME                         100
#define TK_CTIME_KW                       101
#define TK_ANY                            102
#define TK_BITAND                         103
#define TK_BITOR                          104
#define TK_LSHIFT                         105
#define TK_RSHIFT                         106
#define TK_PLUS                           107
#define TK_MINUS                          108
#define TK_STAR                           109
#define TK_SLASH                          110
#define TK_REM                            111
#define TK_CONCAT                         112
#define TK_PTR                            113
#define TK_COLLATE                        114
#define TK_BITNOT                         115
#define TK_ON                             116
#define TK_INDEXED                        117
#define TK_STRING                         118
#define TK_JOIN_KW                        119
#define TK_CONSTRAINT                     120
#define TK_DEFAULT                        121
#define TK_NULL                           122
#define TK_PRIMARY                        123
#define TK_UNIQUE                         124
#define TK_CHECK                          125
#define TK_REFERENCES                     126
#define TK_AUTOINCR                       127
#define TK_INSERT                         128
#define TK_DELETE                         129
#define TK_UPDATE                         130
#define TK_SET                            131
#define TK_DEFERRABLE                     132
#define TK_FOREIGN                        133
#define TK_DROP                           134
#define TK_UNION                          135
#define TK_ALL                            136
#define TK_EXCEPT                         137
#define TK_INTERSECT                      138
#define TK_SELECT                         139
#define TK_VALUES                         140
#define TK_DISTINCT                       141
#define TK_DOT                            142
#define TK_FROM                           143
#define TK_JOIN                           144
#define TK_USING                          145
#define TK_ORDER                          146
#define TK_GROUP                          147
#define TK_HAVING                         148
#define TK_LIMIT                          149
#define TK_WHERE                          150
#define TK_RETURNING                      151
#define TK_INTO                           152
#define TK_NOTHING                        153
#define TK_FLOAT                          154
#define TK_BLOB                           155
#define TK_INTEGER                        156
#define TK_VARIABLE                       157
#define TK_CASE                           158
#define TK_WHEN                           159
#define TK_THEN                           160
#define TK_ELSE                           161
#define TK_INDEX                          162
#define TK_ALTER                          163
#define TK_ADD                            164
#define TK_WINDOW                         165
#define TK_OVER                           166
#define TK_FILTER                         167
#define TK_COLUMN                         168
#define TK_AGG_FUNCTION                   169
#define TK_AGG_COLUMN                     170
#define TK_TRUEFALSE                      171

#define TK_FUNCTION                       172
#define TK_UPLUS                          173
#define TK_UMINUS                         174
#define TK_TRUTH                          175
#define TK_REGISTER                       176
#define TK_VECTOR                         177
#define TK_SELECT_COLUMN                  178
#define TK_IF_NULL_ROW                    179
#define TK_ASTERISK                       180
#define TK_SPAN                           181







<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>

|
|







14483
14484
14485
14486
14487
14488
14489

14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
#define TK_DESC                            39
#define TK_DETACH                          40
#define TK_EACH                            41
#define TK_FAIL                            42
#define TK_OR                              43
#define TK_AND                             44
#define TK_IS                              45

#define TK_MATCH                           46
#define TK_LIKE_KW                         47
#define TK_BETWEEN                         48
#define TK_IN                              49
#define TK_ISNULL                          50
#define TK_NOTNULL                         51
#define TK_NE                              52
#define TK_EQ                              53
#define TK_GT                              54
#define TK_LE                              55
#define TK_LT                              56
#define TK_GE                              57
#define TK_ESCAPE                          58
#define TK_ID                              59
#define TK_COLUMNKW                        60
#define TK_DO                              61
#define TK_FOR                             62
#define TK_IGNORE                          63
#define TK_INITIALLY                       64
#define TK_INSTEAD                         65
#define TK_NO                              66
#define TK_KEY                             67
#define TK_OF                              68
#define TK_OFFSET                          69
#define TK_PRAGMA                          70
#define TK_RAISE                           71
#define TK_RECURSIVE                       72
#define TK_REPLACE                         73
#define TK_RESTRICT                        74
#define TK_ROW                             75
#define TK_ROWS                            76
#define TK_TRIGGER                         77
#define TK_VACUUM                          78
#define TK_VIEW                            79
#define TK_VIRTUAL                         80
#define TK_WITH                            81
#define TK_NULLS                           82
#define TK_FIRST                           83
#define TK_LAST                            84
#define TK_CURRENT                         85
#define TK_FOLLOWING                       86
#define TK_PARTITION                       87
#define TK_PRECEDING                       88
#define TK_RANGE                           89
#define TK_UNBOUNDED                       90
#define TK_EXCLUDE                         91
#define TK_GROUPS                          92
#define TK_OTHERS                          93
#define TK_TIES                            94
#define TK_GENERATED                       95
#define TK_ALWAYS                          96
#define TK_MATERIALIZED                    97
#define TK_REINDEX                         98
#define TK_RENAME                          99
#define TK_CTIME_KW                       100
#define TK_ANY                            101
#define TK_BITAND                         102
#define TK_BITOR                          103
#define TK_LSHIFT                         104
#define TK_RSHIFT                         105
#define TK_PLUS                           106
#define TK_MINUS                          107
#define TK_STAR                           108
#define TK_SLASH                          109
#define TK_REM                            110
#define TK_CONCAT                         111
#define TK_PTR                            112
#define TK_COLLATE                        113
#define TK_BITNOT                         114
#define TK_ON                             115
#define TK_INDEXED                        116
#define TK_STRING                         117
#define TK_JOIN_KW                        118
#define TK_CONSTRAINT                     119
#define TK_DEFAULT                        120
#define TK_NULL                           121
#define TK_PRIMARY                        122
#define TK_UNIQUE                         123
#define TK_CHECK                          124
#define TK_REFERENCES                     125
#define TK_AUTOINCR                       126
#define TK_INSERT                         127
#define TK_DELETE                         128
#define TK_UPDATE                         129
#define TK_SET                            130
#define TK_DEFERRABLE                     131
#define TK_FOREIGN                        132
#define TK_DROP                           133
#define TK_UNION                          134
#define TK_ALL                            135
#define TK_EXCEPT                         136
#define TK_INTERSECT                      137
#define TK_SELECT                         138
#define TK_VALUES                         139
#define TK_DISTINCT                       140
#define TK_DOT                            141
#define TK_FROM                           142
#define TK_JOIN                           143
#define TK_USING                          144
#define TK_ORDER                          145
#define TK_GROUP                          146
#define TK_HAVING                         147
#define TK_LIMIT                          148
#define TK_WHERE                          149
#define TK_RETURNING                      150
#define TK_INTO                           151
#define TK_NOTHING                        152
#define TK_FLOAT                          153
#define TK_BLOB                           154
#define TK_INTEGER                        155
#define TK_VARIABLE                       156
#define TK_CASE                           157
#define TK_WHEN                           158
#define TK_THEN                           159
#define TK_ELSE                           160
#define TK_INDEX                          161
#define TK_ALTER                          162
#define TK_ADD                            163
#define TK_WINDOW                         164
#define TK_OVER                           165
#define TK_FILTER                         166
#define TK_COLUMN                         167
#define TK_AGG_FUNCTION                   168
#define TK_AGG_COLUMN                     169
#define TK_TRUEFALSE                      170
#define TK_ISNOT                          171
#define TK_FUNCTION                       172
#define TK_UMINUS                         173
#define TK_UPLUS                          174
#define TK_TRUTH                          175
#define TK_REGISTER                       176
#define TK_VECTOR                         177
#define TK_SELECT_COLUMN                  178
#define TK_IF_NULL_ROW                    179
#define TK_ASTERISK                       180
#define TK_SPAN                           181
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
**   0x00002000     Constant propagation
**   0x00004000     Push-down optimization
**   0x00008000     After all FROM-clause analysis
**   0x00010000     Beginning of DELETE/INSERT/UPDATE processing
**   0x00020000     Transform DISTINCT into GROUP BY
**   0x00040000     SELECT tree dump after all code has been generated
**   0x00080000     NOT NULL strength reduction
**   0x00100000     EXISTS-to-JOIN optimization
*/

/*
** Macros for "wheretrace"
*/
SQLITE_PRIVATE u32 sqlite3WhereTrace;
#if defined(SQLITE_DEBUG) \







<







15122
15123
15124
15125
15126
15127
15128

15129
15130
15131
15132
15133
15134
15135
**   0x00002000     Constant propagation
**   0x00004000     Push-down optimization
**   0x00008000     After all FROM-clause analysis
**   0x00010000     Beginning of DELETE/INSERT/UPDATE processing
**   0x00020000     Transform DISTINCT into GROUP BY
**   0x00040000     SELECT tree dump after all code has been generated
**   0x00080000     NOT NULL strength reduction

*/

/*
** Macros for "wheretrace"
*/
SQLITE_PRIVATE u32 sqlite3WhereTrace;
#if defined(SQLITE_DEBUG) \
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674

16675
16676
16677
16678
16679
16680
16681
#define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
#define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
#define OP_IdxGE          45 /* jump, synopsis: key=r[P3@P4]               */
#define OP_RowSetRead     46 /* jump, synopsis: r[P3]=rowset(P1)           */
#define OP_RowSetTest     47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
#define OP_Program        48 /* jump0                                      */
#define OP_FkIfZero       49 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
#define OP_IfPos          50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
#define OP_IsNull         51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
#define OP_NotNull        52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
#define OP_Ne             53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
#define OP_Eq             54 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
#define OP_Gt             55 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
#define OP_Le             56 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
#define OP_Lt             57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
#define OP_Ge             58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
#define OP_ElseEq         59 /* jump, same as TK_ESCAPE                    */

#define OP_IfNotZero      60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
#define OP_DecrJumpZero   61 /* jump, synopsis: if (--r[P1])==0 goto P2    */
#define OP_IncrVacuum     62 /* jump                                       */
#define OP_VNext          63 /* jump                                       */
#define OP_Filter         64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */
#define OP_PureFunc       65 /* synopsis: r[P3]=func(r[P2@NP])             */
#define OP_Function       66 /* synopsis: r[P3]=func(r[P2@NP])             */







<
|
|
|
|
|
|
|
|
|
>







16614
16615
16616
16617
16618
16619
16620

16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
#define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
#define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
#define OP_IdxGE          45 /* jump, synopsis: key=r[P3@P4]               */
#define OP_RowSetRead     46 /* jump, synopsis: r[P3]=rowset(P1)           */
#define OP_RowSetTest     47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
#define OP_Program        48 /* jump0                                      */
#define OP_FkIfZero       49 /* jump, synopsis: if fkctr[P1]==0 goto P2    */

#define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
#define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
#define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
#define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
#define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
#define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
#define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
#define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
#define OP_ElseEq         58 /* jump, same as TK_ESCAPE                    */
#define OP_IfPos          59 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
#define OP_IfNotZero      60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
#define OP_DecrJumpZero   61 /* jump, synopsis: if (--r[P1])==0 goto P2    */
#define OP_IncrVacuum     62 /* jump                                       */
#define OP_VNext          63 /* jump                                       */
#define OP_Filter         64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */
#define OP_PureFunc       65 /* synopsis: r[P3]=func(r[P2@NP])             */
#define OP_Function       66 /* synopsis: r[P3]=func(r[P2@NP])             */
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727

16728

16729
16730
16731
16732
16733

16734
16735
16736
16737
16738
16739
16740
#define OP_TypeCheck      95 /* synopsis: typecheck(r[P1@P2])              */
#define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */
#define OP_MakeRecord     97 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
#define OP_Count          98 /* synopsis: r[P2]=count()                    */
#define OP_ReadCookie     99
#define OP_SetCookie     100
#define OP_ReopenIdx     101 /* synopsis: root=P2 iDb=P3                   */
#define OP_OpenRead      102 /* synopsis: root=P2 iDb=P3                   */
#define OP_BitAnd        103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
#define OP_BitOr         104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
#define OP_ShiftLeft     105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
#define OP_ShiftRight    106 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
#define OP_Add           107 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
#define OP_Subtract      108 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
#define OP_Multiply      109 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
#define OP_Divide        110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
#define OP_Remainder     111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
#define OP_Concat        112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */

#define OP_OpenWrite     113 /* synopsis: root=P2 iDb=P3                   */

#define OP_OpenDup       114
#define OP_BitNot        115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2                       */
#define OP_OpenEphemeral 117 /* synopsis: nColumn=P2                       */
#define OP_String8       118 /* same as TK_STRING, synopsis: r[P2]='P4'    */

#define OP_SorterOpen    119
#define OP_SequenceTest  120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
#define OP_OpenPseudo    121 /* synopsis: P3 columns in r[P2]              */
#define OP_Close         122
#define OP_ColumnsUsed   123
#define OP_SeekScan      124 /* synopsis: Scan-ahead up to P1 rows         */
#define OP_SeekHit       125 /* synopsis: set P2<=seekHit<=P3              */







<
|
|
|
|
|
|
|
|
|
|
>

>
|
<

<
|
>







16666
16667
16668
16669
16670
16671
16672

16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686

16687

16688
16689
16690
16691
16692
16693
16694
16695
16696
#define OP_TypeCheck      95 /* synopsis: typecheck(r[P1@P2])              */
#define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */
#define OP_MakeRecord     97 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
#define OP_Count          98 /* synopsis: r[P2]=count()                    */
#define OP_ReadCookie     99
#define OP_SetCookie     100
#define OP_ReopenIdx     101 /* synopsis: root=P2 iDb=P3                   */

#define OP_BitAnd        102 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
#define OP_BitOr         103 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
#define OP_ShiftLeft     104 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
#define OP_ShiftRight    105 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
#define OP_Add           106 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
#define OP_Subtract      107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
#define OP_Multiply      108 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
#define OP_Divide        109 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
#define OP_Remainder     110 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
#define OP_Concat        111 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
#define OP_OpenRead      112 /* synopsis: root=P2 iDb=P3                   */
#define OP_OpenWrite     113 /* synopsis: root=P2 iDb=P3                   */
#define OP_BitNot        114 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
#define OP_OpenDup       115

#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2                       */

#define OP_String8       117 /* same as TK_STRING, synopsis: r[P2]='P4'    */
#define OP_OpenEphemeral 118 /* synopsis: nColumn=P2                       */
#define OP_SorterOpen    119
#define OP_SequenceTest  120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
#define OP_OpenPseudo    121 /* synopsis: P3 columns in r[P2]              */
#define OP_Close         122
#define OP_ColumnsUsed   123
#define OP_SeekScan      124 /* synopsis: Scan-ahead up to P1 rows         */
#define OP_SeekHit       125 /* synopsis: set P2<=seekHit<=P3              */
16761
16762
16763
16764
16765
16766
16767

16768
16769
16770
16771
16772
16773
16774
16775
16776
#define OP_ResetSorter   146
#define OP_CreateBtree   147 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
#define OP_SqlExec       148
#define OP_ParseSchema   149
#define OP_LoadAnalysis  150
#define OP_DropTable     151
#define OP_DropIndex     152

#define OP_DropTrigger   153
#define OP_Real          154 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
#define OP_IntegrityCk   155
#define OP_RowSetAdd     156 /* synopsis: rowset(P1)=r[P2]                 */
#define OP_Param         157
#define OP_FkCounter     158 /* synopsis: fkctr[P1]+=P2                    */
#define OP_MemMax        159 /* synopsis: r[P1]=max(r[P1],r[P2])           */
#define OP_OffsetLimit   160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
#define OP_AggInverse    161 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */







>
|
<







16717
16718
16719
16720
16721
16722
16723
16724
16725

16726
16727
16728
16729
16730
16731
16732
#define OP_ResetSorter   146
#define OP_CreateBtree   147 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
#define OP_SqlExec       148
#define OP_ParseSchema   149
#define OP_LoadAnalysis  150
#define OP_DropTable     151
#define OP_DropIndex     152
#define OP_Real          153 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
#define OP_DropTrigger   154

#define OP_IntegrityCk   155
#define OP_RowSetAdd     156 /* synopsis: rowset(P1)=r[P2]                 */
#define OP_Param         157
#define OP_FkCounter     158 /* synopsis: fkctr[P1]+=P2                    */
#define OP_MemMax        159 /* synopsis: r[P1]=max(r[P1],r[P2])           */
#define OP_OffsetLimit   160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
#define OP_AggInverse    161 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
#define OPFLG_INITIALIZER {\
/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\
/*   8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\
/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\
/*  24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\
/*  32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\
/*  40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\
/*  48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\
/*  56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\
/*  64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\
/*  72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\
/*  80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\
/*  88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\
/*  96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\
/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
/* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\
/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\
/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\
/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\
/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\
/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\
/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}

/* The resolve3P2Values() routine is able to run faster if it knows
** the value of the largest JUMP opcode.  The smaller the maximum







|
|




|

|




|







16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
#define OPFLG_INITIALIZER {\
/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\
/*   8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\
/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\
/*  24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\
/*  32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\
/*  40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\
/*  48 */ 0x81, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
/*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x03, 0x01, 0x41,\
/*  64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\
/*  72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\
/*  80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\
/*  88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\
/*  96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26, 0x26,\
/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
/* 112 */ 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40, 0x00,\
/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\
/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\
/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\
/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
/* 152 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\
/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}

/* The resolve3P2Values() routine is able to run faster if it knows
** the value of the largest JUMP opcode.  The smaller the maximum
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */
#define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */
#define SQLITE_OnePass        0x08000000 /* Single-pass DELETE and UPDATE */
#define SQLITE_ExistsToJoin   0x10000000 /* The EXISTS-to-JOIN optimization */
#define SQLITE_AllOpts        0xffffffff /* All optimizations */

/*
** Macros for testing whether or not optimizations are enabled or disabled.
*/
#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)







<







17848
17849
17850
17851
17852
17853
17854

17855
17856
17857
17858
17859
17860
17861
#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */
#define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */
#define SQLITE_OnePass        0x08000000 /* Single-pass DELETE and UPDATE */

#define SQLITE_AllOpts        0xffffffff /* All optimizations */

/*
** Macros for testing whether or not optimizations are enabled or disabled.
*/
#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
    unsigned fromDDL :1;       /* Comes from sqlite_schema */
    unsigned isCte :1;         /* This is a CTE */
    unsigned notCte :1;        /* This item may not match a CTE */
    unsigned isUsing :1;       /* u3.pUsing is valid */
    unsigned isOn :1;          /* u3.pOn was once valid and non-NULL */
    unsigned isSynthUsing :1;  /* u3.pUsing is synthesized from NATURAL */
    unsigned isNestedFrom :1;  /* pSelect is a SF_NestedFrom subquery */
    unsigned rowidUsed :1;     /* The ROWID of this table is referenced */
  } fg;
  int iCursor;      /* The VDBE cursor number used to access this table */
  union {
    Expr *pOn;        /* fg.isUsing==0 =>  The ON clause of a join */
    IdList *pUsing;   /* fg.isUsing==1 =>  The USING clause of a join */
  } u3;
  Bitmask colUsed;  /* Bit N set if column N used. Details above for N>62 */







<







19236
19237
19238
19239
19240
19241
19242

19243
19244
19245
19246
19247
19248
19249
    unsigned fromDDL :1;       /* Comes from sqlite_schema */
    unsigned isCte :1;         /* This is a CTE */
    unsigned notCte :1;        /* This item may not match a CTE */
    unsigned isUsing :1;       /* u3.pUsing is valid */
    unsigned isOn :1;          /* u3.pOn was once valid and non-NULL */
    unsigned isSynthUsing :1;  /* u3.pUsing is synthesized from NATURAL */
    unsigned isNestedFrom :1;  /* pSelect is a SF_NestedFrom subquery */

  } fg;
  int iCursor;      /* The VDBE cursor number used to access this table */
  union {
    Expr *pOn;        /* fg.isUsing==0 =>  The ON clause of a join */
    IdList *pUsing;   /* fg.isUsing==1 =>  The USING clause of a join */
  } u3;
  Bitmask colUsed;  /* Bit N set if column N used. Details above for N>62 */
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
#define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
#define WHERE_RIGHT_JOIN       0x1000 /* Processing a RIGHT JOIN */
#define WHERE_KEEP_ALL_JOINS   0x2000 /* Do not do the omit-noop-join opt */
#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
                        /*     0x8000    not currently used */

/* Allowed return values from sqlite3WhereIsDistinct()
*/
#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */







|







19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
#define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
#define WHERE_RIGHT_JOIN       0x1000 /* Processing a RIGHT JOIN */
                        /*     0x2000    not currently used */
#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
                        /*     0x8000    not currently used */

/* Allowed return values from sqlite3WhereIsDistinct()
*/
#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
#define NC_Subquery  0x000040 /* A subquery has been seen */
#define NC_UEList    0x000080 /* True if uNC.pEList is used */
#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
/*                   0x002000 // available for reuse */
#define NC_AllowWin  0x004000 /* Window functions are allowed here */
#define NC_HasWin    0x008000 /* One or more window functions seen */
#define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */
#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
#define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */
#define NC_NoSelect  0x080000 /* Do not descend into sub-selects */
#define NC_Where     0x100000 /* Processing WHERE clause of a SELECT */







|







19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
#define NC_Subquery  0x000040 /* A subquery has been seen */
#define NC_UEList    0x000080 /* True if uNC.pEList is used */
#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
#define NC_Complex   0x002000 /* True if a function or subquery seen */
#define NC_AllowWin  0x004000 /* Window functions are allowed here */
#define NC_HasWin    0x008000 /* One or more window functions seen */
#define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */
#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
#define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */
#define NC_NoSelect  0x080000 /* Do not descend into sub-selects */
#define NC_Where     0x100000 /* Processing WHERE clause of a SELECT */
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
  u8 mayAbort;         /* True if statement may throw an ABORT exception */
  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
  u8 okConstFactor;    /* OK to factor out constants */
  u8 disableLookaside; /* Number of times lookaside has been disabled */
  u8 prepFlags;        /* SQLITE_PREPARE_* flags */
  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
  u8 bHasWith;         /* True if statement contains WITH */
  u8 bHasExists;       /* Has a correlated "EXISTS (SELECT ....)" expression */
#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
#endif
#ifdef SQLITE_DEBUG
  u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */
#endif
  int nRangeReg;       /* Size of the temporary register block */







<







19750
19751
19752
19753
19754
19755
19756

19757
19758
19759
19760
19761
19762
19763
  u8 mayAbort;         /* True if statement may throw an ABORT exception */
  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
  u8 okConstFactor;    /* OK to factor out constants */
  u8 disableLookaside; /* Number of times lookaside has been disabled */
  u8 prepFlags;        /* SQLITE_PREPARE_* flags */
  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
  u8 bHasWith;         /* True if statement contains WITH */

#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
#endif
#ifdef SQLITE_DEBUG
  u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */
#endif
  int nRangeReg;       /* Size of the temporary register block */
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3*,void*);
SQLITE_PRIVATE int sqlite3ExprDeferredDelete(Parse*, Expr*);
SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);







|







20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3*,void*);
SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse*, Expr*);
SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
SQLITE_PRIVATE void sqlite3ExprToRegister(Expr *pExpr, int iReg);
SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
#endif
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);







<







20948
20949
20950
20951
20952
20953
20954

20955
20956
20957
20958
20959
20960
20961
#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);

SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
#endif
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse*,Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
#endif
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*, Parse*);
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);
SQLITE_PRIVATE void sqlite3GenerateRowDelete(
    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);







|







21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse*,Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
#endif
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);
SQLITE_PRIVATE void sqlite3GenerateRowDelete(
    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr);
SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);
SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
#if !defined(SQLITE_OMIT_BLOB_LITERAL)
SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
#endif
SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);

#if defined(SQLITE_NEED_ERR_NAME)
SQLITE_PRIVATE const char *sqlite3ErrName(int);
#endif








<

<







21191
21192
21193
21194
21195
21196
21197

21198

21199
21200
21201
21202
21203
21204
21205
SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr);
SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);
SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);

SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);

SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);

#if defined(SQLITE_NEED_ERR_NAME)
SQLITE_PRIVATE const char *sqlite3ErrName(int);
#endif

24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
  float rLimit;       /* Maximum NNN value for this transform */
  float rXform;       /* Constant used for this transform */
} aXformType[] = {
  /* 0 */ { 6, "second",   4.6427e+14,         1.0  },
  /* 1 */ { 6, "minute",   7.7379e+12,        60.0  },
  /* 2 */ { 4, "hour",     1.2897e+11,      3600.0  },
  /* 3 */ { 3, "day",      5373485.0,      86400.0  },
  /* 4 */ { 5, "month",    176546.0,     2592000.0  },
  /* 5 */ { 4, "year",     14713.0,     31536000.0  },
};

/*
** If the DateTime p is raw number, try to figure out if it is
** a julian day number of a unix timestamp.  Set the p value
** appropriately.
*/







|
|







24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
  float rLimit;       /* Maximum NNN value for this transform */
  float rXform;       /* Constant used for this transform */
} aXformType[] = {
  /* 0 */ { 6, "second",   4.6427e+14,         1.0  },
  /* 1 */ { 6, "minute",   7.7379e+12,        60.0  },
  /* 2 */ { 4, "hour",     1.2897e+11,      3600.0  },
  /* 3 */ { 3, "day",      5373485.0,      86400.0  },
  /* 4 */ { 5, "month",    176546.0,  30.0*86400.0  },
  /* 5 */ { 4, "year",     14713.0,  365.0*86400.0  },
};

/*
** If the DateTime p is raw number, try to figure out if it is
** a julian day number of a unix timestamp.  Set the p value
** appropriately.
*/
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
            sqlite3_str_append(pAccum, ".", 1);
          }
          sqlite3_str_appendall(pAccum, pItem->zName);
        }else if( pItem->zAlias ){
          sqlite3_str_appendall(pAccum, pItem->zAlias);
        }else{
          Select *pSel = pItem->pSelect;
          assert( pSel!=0 ); /* Because of tag-20240424-1 */
          if( pSel->selFlags & SF_NestedFrom ){
            sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
          }else if( pSel->selFlags & SF_MultiValue ){
            assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy );
            sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE",
                                pItem->u1.nRow);
          }else{







|







31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
            sqlite3_str_append(pAccum, ".", 1);
          }
          sqlite3_str_appendall(pAccum, pItem->zName);
        }else if( pItem->zAlias ){
          sqlite3_str_appendall(pAccum, pItem->zAlias);
        }else{
          Select *pSel = pItem->pSelect;
          assert( pSel!=0 );
          if( pSel->selFlags & SF_NestedFrom ){
            sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
          }else if( pSel->selFlags & SF_MultiValue ){
            assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy );
            sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE",
                                pItem->u1.nRow);
          }else{
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
    StrAccum x;
    int n = 0;
    char zLine[1000];
    sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
    x.printfFlags |= SQLITE_PRINTF_INTERNAL;
    sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
    if( pItem->pTab ){
      sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx%s",
           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab,
           pItem->colUsed,
           pItem->fg.rowidUsed ? "+rowid" : "");
    }
    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==(JT_LEFT|JT_RIGHT) ){
      sqlite3_str_appendf(&x, " FULL-OUTER-JOIN");
    }else if( pItem->fg.jointype & JT_LEFT ){
      sqlite3_str_appendf(&x, " LEFT-JOIN");
    }else if( pItem->fg.jointype & JT_RIGHT ){
      sqlite3_str_appendf(&x, " RIGHT-JOIN");







|
|
<
<







32726
32727
32728
32729
32730
32731
32732
32733
32734


32735
32736
32737
32738
32739
32740
32741
    StrAccum x;
    int n = 0;
    char zLine[1000];
    sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
    x.printfFlags |= SQLITE_PRINTF_INTERNAL;
    sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
    if( pItem->pTab ){
      sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);


    }
    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==(JT_LEFT|JT_RIGHT) ){
      sqlite3_str_appendf(&x, " FULL-OUTER-JOIN");
    }else if( pItem->fg.jointype & JT_LEFT ){
      sqlite3_str_appendf(&x, " LEFT-JOIN");
    }else if( pItem->fg.jointype & JT_RIGHT ){
      sqlite3_str_appendf(&x, " RIGHT-JOIN");
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
    if( pItem->pSelect ) n++;
    if( pItem->fg.isTabFunc ) n++;
    if( pItem->fg.isUsing ) n++;
    if( pItem->fg.isUsing ){
      sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING");
    }
    if( pItem->pSelect ){
      sqlite3TreeViewPush(&pView, i+1<pSrc->nSrc);
      if( pItem->pTab ){
        Table *pTab = pItem->pTab;
        sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1);
      }
      assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
      sqlite3TreeViewSelect(pView, pItem->pSelect, (--n)>0);
      sqlite3TreeViewPop(&pView);
    }
    if( pItem->fg.isTabFunc ){
      sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
    }
    sqlite3TreeViewPop(&pView);
  }
}







<






<







32767
32768
32769
32770
32771
32772
32773

32774
32775
32776
32777
32778
32779

32780
32781
32782
32783
32784
32785
32786
    if( pItem->pSelect ) n++;
    if( pItem->fg.isTabFunc ) n++;
    if( pItem->fg.isUsing ) n++;
    if( pItem->fg.isUsing ){
      sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING");
    }
    if( pItem->pSelect ){

      if( pItem->pTab ){
        Table *pTab = pItem->pTab;
        sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1);
      }
      assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
      sqlite3TreeViewSelect(pView, pItem->pSelect, (--n)>0);

    }
    if( pItem->fg.isTabFunc ){
      sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
    }
    sqlite3TreeViewPop(&pView);
  }
}
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
    if( p->pOrderBy ){
      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
    }
    if( p->pLimit ){
      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
      sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
      if( p->pLimit->pRight ){
        sqlite3TreeViewItem(pView, "OFFSET", 0);
        sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
        sqlite3TreeViewPop(&pView);
      }
      sqlite3TreeViewPop(&pView);
    }
    if( p->pPrior ){
      const char *zOp = "UNION";







|







32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
    if( p->pOrderBy ){
      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
    }
    if( p->pLimit ){
      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
      sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
      if( p->pLimit->pRight ){
        sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
        sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
        sqlite3TreeViewPop(&pView);
      }
      sqlite3TreeViewPop(&pView);
    }
    if( p->pPrior ){
      const char *zOp = "UNION";
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
      switch( pExpr->affExpr ){
        case OE_Rollback:   zType = "rollback";  break;
        case OE_Abort:      zType = "abort";     break;
        case OE_Fail:       zType = "fail";      break;
        case OE_Ignore:     zType = "ignore";    break;
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      sqlite3TreeViewLine(pView, "RAISE %s", zType);
      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
      break;
    }
#endif
    case TK_MATCH: {
      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
                          pExpr->iTable, pExpr->iColumn, zFlgs);
      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);







|
<







33348
33349
33350
33351
33352
33353
33354
33355

33356
33357
33358
33359
33360
33361
33362
      switch( pExpr->affExpr ){
        case OE_Rollback:   zType = "rollback";  break;
        case OE_Abort:      zType = "abort";     break;
        case OE_Fail:       zType = "fail";      break;
        case OE_Ignore:     zType = "ignore";    break;
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);

      break;
    }
#endif
    case TK_MATCH: {
      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
                          pExpr->iTable, pExpr->iColumn, zFlgs);
      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932

35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
  return x;
}

/*
** Decode a floating-point value into an approximate decimal
** representation.
**
** If iRound<=0 then round to -iRound significant digits to the
** the left of the decimal point, or to a maximum of mxRound total
** significant digits.

**
** If iRound>0 round to min(iRound,mxRound) significant digits total.
**
** mxRound must be positive.
**
** The significant digits of the decimal representation are
** stored in p->z[] which is a often (but not always) a pointer
** into the middle of p->zBuf[].  There are p->n significant digits.
** The p->z[] array is *not* zero-terminated.
*/
SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
  int i;
  u64 v;
  int e, exp = 0;
  p->isSpecial = 0;
  p->z = p->zBuf;

  assert( mxRound>0 );

  /* Convert negative numbers to positive.  Deal with Infinity, 0.0, and
  ** NaN. */
  if( r<0.0 ){
    p->sign = '-';
    r = -r;
  }else if( r==0.0 ){
    p->sign = '+';







|
<
|
>
|
<
<
<













<
<







35868
35869
35870
35871
35872
35873
35874
35875

35876
35877
35878



35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891


35892
35893
35894
35895
35896
35897
35898
  return x;
}

/*
** Decode a floating-point value into an approximate decimal
** representation.
**
** Round the decimal representation to n significant digits if

** n is positive.  Or round to -n signficant digits after the
** decimal point if n is negative.  No rounding is performed if
** n is zero.



**
** The significant digits of the decimal representation are
** stored in p->z[] which is a often (but not always) a pointer
** into the middle of p->zBuf[].  There are p->n significant digits.
** The p->z[] array is *not* zero-terminated.
*/
SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
  int i;
  u64 v;
  int e, exp = 0;
  p->isSpecial = 0;
  p->z = p->zBuf;



  /* Convert negative numbers to positive.  Deal with Infinity, 0.0, and
  ** NaN. */
  if( r<0.0 ){
    p->sign = '-';
    r = -r;
  }else if( r==0.0 ){
    p->sign = '+';
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247

37248
37249
37250
37251
37252
37253
37254
    /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
    /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
    /*  45 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
    /*  46 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
    /*  47 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
    /*  48 */ "Program"          OpHelp(""),
    /*  49 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
    /*  50 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
    /*  51 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
    /*  52 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
    /*  53 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
    /*  54 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
    /*  55 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
    /*  56 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
    /*  57 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
    /*  58 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
    /*  59 */ "ElseEq"           OpHelp(""),

    /*  60 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
    /*  61 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
    /*  62 */ "IncrVacuum"       OpHelp(""),
    /*  63 */ "VNext"            OpHelp(""),
    /*  64 */ "Filter"           OpHelp("if key(P3@P4) not in filter(P1) goto P2"),
    /*  65 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
    /*  66 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),







<
|
|
|
|
|
|
|
|
|
>







37171
37172
37173
37174
37175
37176
37177

37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
    /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
    /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
    /*  45 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
    /*  46 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
    /*  47 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
    /*  48 */ "Program"          OpHelp(""),
    /*  49 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),

    /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
    /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
    /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
    /*  53 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
    /*  54 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
    /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
    /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
    /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
    /*  58 */ "ElseEq"           OpHelp(""),
    /*  59 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
    /*  60 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
    /*  61 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
    /*  62 */ "IncrVacuum"       OpHelp(""),
    /*  63 */ "VNext"            OpHelp(""),
    /*  64 */ "Filter"           OpHelp("if key(P3@P4) not in filter(P1) goto P2"),
    /*  65 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
    /*  66 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300

37301
37302
37303

37304
37305
37306

37307
37308
37309
37310
37311
37312
37313
    /*  95 */ "TypeCheck"        OpHelp("typecheck(r[P1@P2])"),
    /*  96 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
    /*  97 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
    /*  98 */ "Count"            OpHelp("r[P2]=count()"),
    /*  99 */ "ReadCookie"       OpHelp(""),
    /* 100 */ "SetCookie"        OpHelp(""),
    /* 101 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
    /* 102 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
    /* 103 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
    /* 104 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
    /* 105 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
    /* 106 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
    /* 107 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
    /* 108 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
    /* 109 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
    /* 110 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
    /* 111 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
    /* 112 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),

    /* 113 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
    /* 114 */ "OpenDup"          OpHelp(""),
    /* 115 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),

    /* 116 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
    /* 117 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
    /* 118 */ "String8"          OpHelp("r[P2]='P4'"),

    /* 119 */ "SorterOpen"       OpHelp(""),
    /* 120 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
    /* 121 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
    /* 122 */ "Close"            OpHelp(""),
    /* 123 */ "ColumnsUsed"      OpHelp(""),
    /* 124 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
    /* 125 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),







<
|
|
|
|
|
|
|
|
|
|
>

<
|
>

<
|
>







37223
37224
37225
37226
37227
37228
37229

37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241

37242
37243
37244

37245
37246
37247
37248
37249
37250
37251
37252
37253
    /*  95 */ "TypeCheck"        OpHelp("typecheck(r[P1@P2])"),
    /*  96 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
    /*  97 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
    /*  98 */ "Count"            OpHelp("r[P2]=count()"),
    /*  99 */ "ReadCookie"       OpHelp(""),
    /* 100 */ "SetCookie"        OpHelp(""),
    /* 101 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),

    /* 102 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
    /* 103 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
    /* 104 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
    /* 105 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
    /* 106 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
    /* 107 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
    /* 108 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
    /* 109 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
    /* 110 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
    /* 111 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
    /* 112 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
    /* 113 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),

    /* 114 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
    /* 115 */ "OpenDup"          OpHelp(""),
    /* 116 */ "OpenAutoindex"    OpHelp("nColumn=P2"),

    /* 117 */ "String8"          OpHelp("r[P2]='P4'"),
    /* 118 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
    /* 119 */ "SorterOpen"       OpHelp(""),
    /* 120 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
    /* 121 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
    /* 122 */ "Close"            OpHelp(""),
    /* 123 */ "ColumnsUsed"      OpHelp(""),
    /* 124 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
    /* 125 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
37334
37335
37336
37337
37338
37339
37340
37341
37342

37343
37344
37345
37346
37347
37348
37349
    /* 146 */ "ResetSorter"      OpHelp(""),
    /* 147 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
    /* 148 */ "SqlExec"          OpHelp(""),
    /* 149 */ "ParseSchema"      OpHelp(""),
    /* 150 */ "LoadAnalysis"     OpHelp(""),
    /* 151 */ "DropTable"        OpHelp(""),
    /* 152 */ "DropIndex"        OpHelp(""),
    /* 153 */ "DropTrigger"      OpHelp(""),
    /* 154 */ "Real"             OpHelp("r[P2]=P4"),

    /* 155 */ "IntegrityCk"      OpHelp(""),
    /* 156 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
    /* 157 */ "Param"            OpHelp(""),
    /* 158 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
    /* 159 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
    /* 160 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
    /* 161 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),







<
|
>







37274
37275
37276
37277
37278
37279
37280

37281
37282
37283
37284
37285
37286
37287
37288
37289
    /* 146 */ "ResetSorter"      OpHelp(""),
    /* 147 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
    /* 148 */ "SqlExec"          OpHelp(""),
    /* 149 */ "ParseSchema"      OpHelp(""),
    /* 150 */ "LoadAnalysis"     OpHelp(""),
    /* 151 */ "DropTable"        OpHelp(""),
    /* 152 */ "DropIndex"        OpHelp(""),

    /* 153 */ "Real"             OpHelp("r[P2]=P4"),
    /* 154 */ "DropTrigger"      OpHelp(""),
    /* 155 */ "IntegrityCk"      OpHelp(""),
    /* 156 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
    /* 157 */ "Param"            OpHelp(""),
    /* 158 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
    /* 159 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
    /* 160 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
    /* 161 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
  }else{
    pFile->ctrlFlags |= mask;
  }
}

/* Forward declaration */
static int unixGetTempname(int nBuf, char *zBuf);
#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL)
 static int unixFcntlExternalReader(unixFile*, int*);
#endif

/*
** Information and control of an open file handle.
*/
static int unixFileControl(sqlite3_file *id, int op, void *pArg){







|







42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
  }else{
    pFile->ctrlFlags |= mask;
  }
}

/* Forward declaration */
static int unixGetTempname(int nBuf, char *zBuf);
#ifndef SQLITE_OMIT_WAL
 static int unixFcntlExternalReader(unixFile*, int*);
#endif

/*
** Information and control of an open file handle.
*/
static int unixFileControl(sqlite3_file *id, int op, void *pArg){
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
      return proxyFileControl(id,op,pArg);
    }
#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */

    case SQLITE_FCNTL_EXTERNAL_READER: {
#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL)
      return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
#else
      *(int*)pArg = 0;
      return SQLITE_OK;
#endif
    }
  }







|







42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
      return proxyFileControl(id,op,pArg);
    }
#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */

    case SQLITE_FCNTL_EXTERNAL_READER: {
#ifndef SQLITE_OMIT_WAL
      return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
#else
      *(int*)pArg = 0;
      return SQLITE_OK;
#endif
    }
  }
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
#else
  return (int)sysconf(_SC_PAGESIZE);
#endif
}

#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */

#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL)

/*
** Object used to represent an shared memory buffer.
**
** When multiple threads all reference the same wal-index, each thread
** has its own unixShm object, but they all point to a single instance
** of this unixShmNode object.  In other words, each wal-index is opened







|







42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
#else
  return (int)sysconf(_SC_PAGESIZE);
#endif
}

#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */

#ifndef SQLITE_OMIT_WAL

/*
** Object used to represent an shared memory buffer.
**
** When multiple threads all reference the same wal-index, each thread
** has its own unixShm object, but they all point to a single instance
** of this unixShmNode object.  In other words, each wal-index is opened
78114
78115
78116
78117
78118
78119
78120
78121
78122
78123
78124
78125
78126
78127
78128
78129

  assert( nCell>0 );
  assert( i<iEnd );
  j = get2byte(&aData[hdr+5]);
  if( j>(u32)usableSize ){ j = 0; }
  memcpy(&pTmp[j], &aData[j], usableSize - j);

  assert( pCArray->ixNx[NB*2-1]>i );
  for(k=0; pCArray->ixNx[k]<=i; k++){}
  pSrcEnd = pCArray->apEnd[k];

  pData = pEnd;
  while( 1/*exit by break*/ ){
    u8 *pCell = pCArray->apCell[i];
    u16 sz = pCArray->szCell[i];
    assert( sz>0 );







<
|







78054
78055
78056
78057
78058
78059
78060

78061
78062
78063
78064
78065
78066
78067
78068

  assert( nCell>0 );
  assert( i<iEnd );
  j = get2byte(&aData[hdr+5]);
  if( j>(u32)usableSize ){ j = 0; }
  memcpy(&pTmp[j], &aData[j], usableSize - j);


  for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i; k++){}
  pSrcEnd = pCArray->apEnd[k];

  pData = pEnd;
  while( 1/*exit by break*/ ){
    u8 *pCell = pCArray->apCell[i];
    u16 sz = pCArray->szCell[i];
    assert( sz>0 );
78198
78199
78200
78201
78202
78203
78204
78205
78206
78207
78208
78209
78210
78211
78212
78213
  u8 *aData = pPg->aData;         /* Complete page */
  u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
  int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
  int k;                          /* Current slot in pCArray->apEnd[] */
  u8 *pEnd;                       /* Maximum extent of cell data */
  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
  if( iEnd<=iFirst ) return 0;
  assert( pCArray->ixNx[NB*2-1]>i );
  for(k=0; pCArray->ixNx[k]<=i ; k++){}
  pEnd = pCArray->apEnd[k];
  while( 1 /*Exit by break*/ ){
    int sz, rc;
    u8 *pSlot;
    assert( pCArray->szCell[i]!=0 );
    sz = pCArray->szCell[i];
    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){







<
|







78137
78138
78139
78140
78141
78142
78143

78144
78145
78146
78147
78148
78149
78150
78151
  u8 *aData = pPg->aData;         /* Complete page */
  u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
  int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
  int k;                          /* Current slot in pCArray->apEnd[] */
  u8 *pEnd;                       /* Maximum extent of cell data */
  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
  if( iEnd<=iFirst ) return 0;

  for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i ; k++){}
  pEnd = pCArray->apEnd[k];
  while( 1 /*Exit by break*/ ){
    int sz, rc;
    u8 *pSlot;
    assert( pCArray->szCell[i]!=0 );
    sz = pCArray->szCell[i];
    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
78484
78485
78486
78487
78488
78489
78490
78491
78492
78493
78494
78495
78496
78497
78498
    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
    b.nCell = 1;
    b.pRef = pPage;
    b.apCell = &pCell;
    b.szCell = &szCell;
    b.apEnd[0] = pPage->aDataEnd;
    b.ixNx[0] = 2;
    b.ixNx[NB*2-1] = 0x7fffffff;
    rc = rebuildPage(&b, 0, 1, pNew);
    if( NEVER(rc) ){
      releasePage(pNew);
      return rc;
    }
    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;








<







78422
78423
78424
78425
78426
78427
78428

78429
78430
78431
78432
78433
78434
78435
    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
    b.nCell = 1;
    b.pRef = pPage;
    b.apCell = &pCell;
    b.szCell = &szCell;
    b.apEnd[0] = pPage->aDataEnd;
    b.ixNx[0] = 2;

    rc = rebuildPage(&b, 0, 1, pNew);
    if( NEVER(rc) ){
      releasePage(pNew);
      return rc;
    }
    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;

78720
78721
78722
78723
78724
78725
78726
78727
78728
78729
78730
78731
78732
78733
78734
78735
78736
  u8 *aSpace1;                 /* Space for copies of dividers cells */
  Pgno pgno;                   /* Temp var to store a page number in */
  u8 abDone[NB+2];             /* True after i'th new page is populated */
  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
  CellArray b;                 /* Parsed information on cells being balanced */

  memset(abDone, 0, sizeof(abDone));
  assert( sizeof(b) - sizeof(b.ixNx) == offsetof(CellArray,ixNx) );
  memset(&b, 0, sizeof(b)-sizeof(b.ixNx[0]));
  b.ixNx[NB*2-1] = 0x7fffffff;
  pBt = pParent->pBt;
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );

  /* At this point pParent may have at most one overflow cell. And if
  ** this overflow cell is present, it must be the cell with
  ** index iParentIdx. This scenario comes about when this function







<
|
<







78657
78658
78659
78660
78661
78662
78663

78664

78665
78666
78667
78668
78669
78670
78671
  u8 *aSpace1;                 /* Space for copies of dividers cells */
  Pgno pgno;                   /* Temp var to store a page number in */
  u8 abDone[NB+2];             /* True after i'th new page is populated */
  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
  CellArray b;                 /* Parsed information on cells being balanced */

  memset(abDone, 0, sizeof(abDone));

  memset(&b, 0, sizeof(b));

  pBt = pParent->pBt;
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );

  /* At this point pParent may have at most one overflow cell. And if
  ** this overflow cell is present, it must be the cell with
  ** index iParentIdx. This scenario comes about when this function
79313
79314
79315
79316
79317
79318
79319
79320
79321
79322
79323
79324
79325
79326
79327
79328
        assert(leafCorrection==4);
        sz = pParent->xCellSize(pParent, pCell);
      }
    }
    iOvflSpace += sz;
    assert( sz<=pBt->maxLocal+23 );
    assert( iOvflSpace <= (int)pBt->pageSize );
    assert( b.ixNx[NB*2-1]>j );
    for(k=0; b.ixNx[k]<=j; k++){}
    pSrcEnd = b.apEnd[k];
    if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
      rc = SQLITE_CORRUPT_BKPT;
      goto balance_cleanup;
    }
    rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
    if( rc!=SQLITE_OK ) goto balance_cleanup;







<
|







79248
79249
79250
79251
79252
79253
79254

79255
79256
79257
79258
79259
79260
79261
79262
        assert(leafCorrection==4);
        sz = pParent->xCellSize(pParent, pCell);
      }
    }
    iOvflSpace += sz;
    assert( sz<=pBt->maxLocal+23 );
    assert( iOvflSpace <= (int)pBt->pageSize );

    for(k=0; ALWAYS(k<NB*2) && b.ixNx[k]<=j; k++){}
    pSrcEnd = b.apEnd[k];
    if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
      rc = SQLITE_CORRUPT_BKPT;
      goto balance_cleanup;
    }
    rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
    if( rc!=SQLITE_OK ) goto balance_cleanup;
84741
84742
84743
84744
84745
84746
84747
84748
84749
84750
84751
84752
84753
84754
84755
84756
84757
84758
84759
84760
84761
84762
84763
84764
84765
  sqlite3 *db,                    /* Database handle */
  const void *pRec,               /* Pointer to buffer containing record */
  int nRec,                       /* Size of buffer pRec in bytes */
  int iCol,                       /* Column to extract */
  sqlite3_value **ppVal           /* OUT: Extracted value */
){
  u32 t = 0;                      /* a column type code */
  u32 nHdr;                       /* Size of the header in the record */
  u32 iHdr;                       /* Next unread header byte */
  i64 iField;                     /* Next unread data byte */
  u32 szField = 0;                /* Size of the current data field */
  int i;                          /* Column index */
  u8 *a = (u8*)pRec;              /* Typecast byte array */
  Mem *pMem = *ppVal;             /* Write result into this Mem object */

  assert( iCol>0 );
  iHdr = getVarint32(a, nHdr);
  if( nHdr>(u32)nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  iField = nHdr;
  for(i=0; i<=iCol; i++){
    iHdr += getVarint32(&a[iHdr], t);
    testcase( iHdr==nHdr );
    testcase( iHdr==nHdr+1 );
    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
    szField = sqlite3VdbeSerialTypeLen(t);







|
|
|
|






|







84675
84676
84677
84678
84679
84680
84681
84682
84683
84684
84685
84686
84687
84688
84689
84690
84691
84692
84693
84694
84695
84696
84697
84698
84699
  sqlite3 *db,                    /* Database handle */
  const void *pRec,               /* Pointer to buffer containing record */
  int nRec,                       /* Size of buffer pRec in bytes */
  int iCol,                       /* Column to extract */
  sqlite3_value **ppVal           /* OUT: Extracted value */
){
  u32 t = 0;                      /* a column type code */
  int nHdr;                       /* Size of the header in the record */
  int iHdr;                       /* Next unread header byte */
  int iField;                     /* Next unread data byte */
  int szField = 0;                /* Size of the current data field */
  int i;                          /* Column index */
  u8 *a = (u8*)pRec;              /* Typecast byte array */
  Mem *pMem = *ppVal;             /* Write result into this Mem object */

  assert( iCol>0 );
  iHdr = getVarint32(a, nHdr);
  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  iField = nHdr;
  for(i=0; i<=iCol; i++){
    iHdr += getVarint32(&a[iHdr], t);
    testcase( iHdr==nHdr );
    testcase( iHdr==nHdr+1 );
    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
    szField = sqlite3VdbeSerialTypeLen(t);
88202
88203
88204
88205
88206
88207
88208
88209
88210
88211
88212
88213
88214
88215
88216
          p->nChange = 0;
        }
      }
    }

    /* Check for immediate foreign key violations. */
    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
      (void)sqlite3VdbeCheckFk(p, 0);
    }

    /* If the auto-commit flag is set and this is the only active writer
    ** VM, then we do either a commit or rollback of the current transaction.
    **
    ** Note: This block also runs if one of the special errors handled
    ** above has occurred.







|







88136
88137
88138
88139
88140
88141
88142
88143
88144
88145
88146
88147
88148
88149
88150
          p->nChange = 0;
        }
      }
    }

    /* Check for immediate foreign key violations. */
    if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
      sqlite3VdbeCheckFk(p, 0);
    }

    /* If the auto-commit flag is set and this is the only active writer
    ** VM, then we do either a commit or rollback of the current transaction.
    **
    ** Note: This block also runs if one of the special errors handled
    ** above has occurred.
90183
90184
90185
90186
90187
90188
90189
90190
90191
90192
90193
90194
90195
90196
90197
90198
90199
90200
90201
90202
90203
90204
90205
90206
90207
90208
90209
90210
90211
90212
90213
90214
90215
90216
90217
90218
90219
**
** The returned value must be freed by the caller using sqlite3ValueFree().
*/
SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  assert( iVar>0 );
  if( v ){
    Mem *pMem = &v->aVar[iVar-1];
    assert( (v->db->flags & SQLITE_EnableQPSG)==0
         || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
    if( 0==(pMem->flags & MEM_Null) ){
      sqlite3_value *pRet = sqlite3ValueNew(v->db);
      if( pRet ){
        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
      }
      return pRet;
    }
  }
  return 0;
}

/*
** Configure SQL variable iVar so that binding a new value to it signals
** to sqlite3_reoptimize() that re-preparing the statement may result
** in a better query plan.
*/
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  assert( iVar>0 );
  assert( (v->db->flags & SQLITE_EnableQPSG)==0
       || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
  if( iVar>=32 ){
    v->expmask |= 0x80000000;
  }else{
    v->expmask |= ((u32)1 << (iVar-1));
  }
}








|
<



















|
<







90117
90118
90119
90120
90121
90122
90123
90124

90125
90126
90127
90128
90129
90130
90131
90132
90133
90134
90135
90136
90137
90138
90139
90140
90141
90142
90143
90144

90145
90146
90147
90148
90149
90150
90151
**
** The returned value must be freed by the caller using sqlite3ValueFree().
*/
SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  assert( iVar>0 );
  if( v ){
    Mem *pMem = &v->aVar[iVar-1];
    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );

    if( 0==(pMem->flags & MEM_Null) ){
      sqlite3_value *pRet = sqlite3ValueNew(v->db);
      if( pRet ){
        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
      }
      return pRet;
    }
  }
  return 0;
}

/*
** Configure SQL variable iVar so that binding a new value to it signals
** to sqlite3_reoptimize() that re-preparing the statement may result
** in a better query plan.
*/
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  assert( iVar>0 );
  assert( (v->db->flags & SQLITE_EnableQPSG)==0 );

  if( iVar>=32 ){
    v->expmask |= 0x80000000;
  }else{
    v->expmask |= ((u32)1 << (iVar-1));
  }
}

94337
94338
94339
94340
94341
94342
94343
94344
94345
94346
94347
94348
94349
94350
94351
94352
94353
94354
94355
94356
94357
94358
94359
94360
94361
94362
94363
94364
94365

94366
94367
94368
94369
94370
94371
94372
94373
94374
94375
94376
94377
94378
94379
94380
94381
94382
94383
94384
94385
94386
94387
94388
94389
94390
94391
94392
94393
94394
  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
#endif
  if( (pIn3->flags & MEM_Null)==0 ) break;
  /* Fall through into OP_Halt */
  /* no break */ deliberate_fall_through
}

/* Opcode:  Halt P1 P2 P3 P4 P5
**
** Exit immediately.  All open cursors, etc are closed
** automatically.
**
** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
** For errors, it can be some other value.  If P1!=0 then P2 will determine
** whether or not to rollback the current transaction.  Do not rollback
** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
** then back out all changes that have occurred during this execution of the
** VDBE, but do not rollback the transaction.
**
** If P3 is not zero and P4 is NULL, then P3 is a register that holds the
** text of an error message.
**
** If P3 is zero and P4 is not null then the error message string is held
** in P4.
**
** P5 is a value between 1 and 4, inclusive, then the P4 error message
** string is modified as follows:
**

**    1:  NOT NULL constraint failed: P4
**    2:  UNIQUE constraint failed: P4
**    3:  CHECK constraint failed: P4
**    4:  FOREIGN KEY constraint failed: P4
**
** If P3 is zero and P5 is not zero and P4 is NULL, then everything after
** the ":" is omitted.
**
** There is an implied "Halt 0 0 0" instruction inserted at the very end of
** every program.  So a jump past the last instruction of the program
** is the same as executing Halt.
*/
case OP_Halt: {
  VdbeFrame *pFrame;
  int pcx;

#ifdef SQLITE_DEBUG
  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
#endif
  assert( pOp->p4type==P4_NOTUSED
       || pOp->p4type==P4_STATIC
       || pOp->p4type==P4_DYNAMIC );

  /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
  ** something is wrong with the code generator.  Raise an assertion in order
  ** to bring this to the attention of fuzzers and other testing tools. */
  assert( pOp->p1!=SQLITE_INTERNAL );

  if( p->pFrame && pOp->p1==SQLITE_OK ){







|












<
|

<
<
<
|
<

>





|
|












<
<
<







94269
94270
94271
94272
94273
94274
94275
94276
94277
94278
94279
94280
94281
94282
94283
94284
94285
94286
94287
94288

94289
94290



94291

94292
94293
94294
94295
94296
94297
94298
94299
94300
94301
94302
94303
94304
94305
94306
94307
94308
94309
94310
94311
94312



94313
94314
94315
94316
94317
94318
94319
  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
#endif
  if( (pIn3->flags & MEM_Null)==0 ) break;
  /* Fall through into OP_Halt */
  /* no break */ deliberate_fall_through
}

/* Opcode:  Halt P1 P2 * P4 P5
**
** Exit immediately.  All open cursors, etc are closed
** automatically.
**
** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
** For errors, it can be some other value.  If P1!=0 then P2 will determine
** whether or not to rollback the current transaction.  Do not rollback
** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
** then back out all changes that have occurred during this execution of the
** VDBE, but do not rollback the transaction.
**

** If P4 is not null then it is an error message string.
**



** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.

**
**    0:  (no change)
**    1:  NOT NULL constraint failed: P4
**    2:  UNIQUE constraint failed: P4
**    3:  CHECK constraint failed: P4
**    4:  FOREIGN KEY constraint failed: P4
**
** If P5 is not zero and P4 is NULL, then everything after the ":" is
** omitted.
**
** There is an implied "Halt 0 0 0" instruction inserted at the very end of
** every program.  So a jump past the last instruction of the program
** is the same as executing Halt.
*/
case OP_Halt: {
  VdbeFrame *pFrame;
  int pcx;

#ifdef SQLITE_DEBUG
  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
#endif




  /* A deliberately coded "OP_Halt SQLITE_INTERNAL * * * *" opcode indicates
  ** something is wrong with the code generator.  Raise an assertion in order
  ** to bring this to the attention of fuzzers and other testing tools. */
  assert( pOp->p1!=SQLITE_INTERNAL );

  if( p->pFrame && pOp->p1==SQLITE_OK ){
94411
94412
94413
94414
94415
94416
94417
94418
94419
94420
94421
94422
94423
94424
94425
94426
94427
94428
94429
94430
    pOp = &aOp[pcx];
    break;
  }
  p->rc = pOp->p1;
  p->errorAction = (u8)pOp->p2;
  assert( pOp->p5<=4 );
  if( p->rc ){
    if( pOp->p3>0 && pOp->p4type==P4_NOTUSED ){
      const char *zErr;
      assert( pOp->p3<=(p->nMem + 1 - p->nCursor) );
      zErr = sqlite3ValueText(&aMem[pOp->p3], SQLITE_UTF8);
      sqlite3VdbeError(p, "%s", zErr);
    }else if( pOp->p5 ){
      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
                                             "FOREIGN KEY" };
      testcase( pOp->p5==1 );
      testcase( pOp->p5==2 );
      testcase( pOp->p5==3 );
      testcase( pOp->p5==4 );
      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);







<
<
<
<
<
|







94336
94337
94338
94339
94340
94341
94342





94343
94344
94345
94346
94347
94348
94349
94350
    pOp = &aOp[pcx];
    break;
  }
  p->rc = pOp->p1;
  p->errorAction = (u8)pOp->p2;
  assert( pOp->p5<=4 );
  if( p->rc ){





    if( pOp->p5 ){
      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
                                             "FOREIGN KEY" };
      testcase( pOp->p5==1 );
      testcase( pOp->p5==2 );
      testcase( pOp->p5==3 );
      testcase( pOp->p5==4 );
      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
97459
97460
97461
97462
97463
97464
97465



97466
97467
97468

97469
97470
97471
97472
97473
97474
97475
97476
97477
97478
97479
97480
97481
97482
97483
97484
97485
97486
97487
97488
97489
  if( pOp->opcode==OP_OpenWrite ){
    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
      p->minWriteFileFormat = pDb->pSchema->file_format;
    }



    if( pOp->p5 & OPFLAG_P2ISREG ){
      assert( p2>0 );
      assert( p2<=(u32)(p->nMem+1 - p->nCursor) );

      pIn2 = &aMem[p2];
      assert( memIsValid(pIn2) );
      assert( (pIn2->flags & MEM_Int)!=0 );
      sqlite3VdbeMemIntegerify(pIn2);
      p2 = (int)pIn2->u.i;
      /* The p2 value always comes from a prior OP_CreateBtree opcode and
      ** that opcode will always set the p2 value to 2 or more or else fail.
      ** If there were a failure, the prepared statement would have halted
      ** before reaching this instruction. */
      assert( p2>=2 );
    }
  }else{
    wrFlag = 0;
    assert( (pOp->p5 & OPFLAG_P2ISREG)==0 );
  }
  if( pOp->p4type==P4_KEYINFO ){
    pKeyInfo = pOp->p4.pKeyInfo;
    assert( pKeyInfo->enc==ENC(db) );
    assert( pKeyInfo->db==db );
    nField = pKeyInfo->nAllField;
  }else if( pOp->p4type==P4_INT32 ){







>
>
>
|
|
|
>
|
|
|
|
|
|
|
|
|
|
<
<
<
<







97379
97380
97381
97382
97383
97384
97385
97386
97387
97388
97389
97390
97391
97392
97393
97394
97395
97396
97397
97398
97399
97400
97401
97402




97403
97404
97405
97406
97407
97408
97409
  if( pOp->opcode==OP_OpenWrite ){
    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
      p->minWriteFileFormat = pDb->pSchema->file_format;
    }
  }else{
    wrFlag = 0;
  }
  if( pOp->p5 & OPFLAG_P2ISREG ){
    assert( p2>0 );
    assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
    assert( pOp->opcode==OP_OpenWrite );
    pIn2 = &aMem[p2];
    assert( memIsValid(pIn2) );
    assert( (pIn2->flags & MEM_Int)!=0 );
    sqlite3VdbeMemIntegerify(pIn2);
    p2 = (int)pIn2->u.i;
    /* The p2 value always comes from a prior OP_CreateBtree opcode and
    ** that opcode will always set the p2 value to 2 or more or else fail.
    ** If there were a failure, the prepared statement would have halted
    ** before reaching this instruction. */
    assert( p2>=2 );




  }
  if( pOp->p4type==P4_KEYINFO ){
    pKeyInfo = pOp->p4.pKeyInfo;
    assert( pKeyInfo->enc==ENC(db) );
    assert( pKeyInfo->db==db );
    nField = pKeyInfo->nAllField;
  }else if( pOp->p4type==P4_INT32 ){
97719
97720
97721
97722
97723
97724
97725
97726
97727
97728
97729
97730
97731
97732
97733
97734
**
** A pseudo-table created by this opcode is used to hold a single
** row output from the sorter so that the row can be decomposed into
** individual columns using the OP_Column opcode.  The OP_Column opcode
** is the only cursor opcode that works with a pseudo-table.
**
** P3 is the number of fields in the records that will be stored by
** the pseudo-table.  If P2 is 0 or negative then the pseudo-cursor
** will return NULL for every column.
*/
case OP_OpenPseudo: {
  VdbeCursor *pCx;

  assert( pOp->p1>=0 );
  assert( pOp->p3>=0 );
  pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);







|
<







97639
97640
97641
97642
97643
97644
97645
97646

97647
97648
97649
97650
97651
97652
97653
**
** A pseudo-table created by this opcode is used to hold a single
** row output from the sorter so that the row can be decomposed into
** individual columns using the OP_Column opcode.  The OP_Column opcode
** is the only cursor opcode that works with a pseudo-table.
**
** P3 is the number of fields in the records that will be stored by
** the pseudo-table.

*/
case OP_OpenPseudo: {
  VdbeCursor *pCx;

  assert( pOp->p1>=0 );
  assert( pOp->p3>=0 );
  pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
102138
102139
102140
102141
102142
102143
102144
102145

102146
102147
102148
102149
102150
102151
102152
102153
102154
102155
102156
102157
102158
102159
102160
102161
102162
102163
102164
102165
102166
102167

102168
102169
102170
102171
102172
102173
102174
  }
  break;
}
#endif

/* Opcode: Noop * * * * *
**
** Do nothing.  Continue downward to the next opcode.

*/
/* Opcode: Explain P1 P2 P3 P4 *
**
** This is the same as OP_Noop during normal query execution.  The
** purpose of this opcode is to hold information about the query
** plan for the purpose of EXPLAIN QUERY PLAN output.
**
** The P4 value is human-readable text that describes the query plan
** element.  Something like "SCAN t1" or "SEARCH t2 USING INDEX t2x1".
**
** The P1 value is the ID of the current element and P2 is the parent
** element for the case of nested query plan elements.  If P2 is zero
** then this element is a top-level element.
**
** For loop elements, P3 is the estimated code of each invocation of this
** element.
**
** As with all opcodes, the meanings of the parameters for OP_Explain
** are subject to change from one release to the next.  Applications
** should not attempt to interpret or use any of the information
** contined in the OP_Explain opcode.  The information provided by this
** opcode is intended for testing and debugging use only.

*/
default: {          /* This is really OP_Noop, OP_Explain */
  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );

  break;
}








|
>

|
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
>







102057
102058
102059
102060
102061
102062
102063
102064
102065
102066
102067


102068
102069














102070

102071
102072
102073
102074
102075
102076
102077
102078
  }
  break;
}
#endif

/* Opcode: Noop * * * * *
**
** Do nothing.  This instruction is often useful as a jump
** destination.
*/
/*


** The magic Explain opcode are only inserted when explain==2 (which
** is to say when the EXPLAIN QUERY PLAN syntax is used.)














** This opcode records information from the optimizer.  It is the

** the same as a no-op.  This opcodesnever appears in a real VM program.
*/
default: {          /* This is really OP_Noop, OP_Explain */
  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );

  break;
}

105893
105894
105895
105896
105897
105898
105899
105900
105901
105902
105903
105904
105905
105906
105907
105908
105909
105910
         sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
      }
      break;
    }

#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
    case 9:     /* nexec */
      sqlite3_result_int64(ctx, pOp->nExec);
      break;
    case 10:    /* ncycle */
      sqlite3_result_int64(ctx, pOp->nCycle);
      break;
#else
    case 9:     /* nexec */
    case 10:    /* ncycle */
      sqlite3_result_int(ctx, 0);
      break;
#endif







|


|







105797
105798
105799
105800
105801
105802
105803
105804
105805
105806
105807
105808
105809
105810
105811
105812
105813
105814
         sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
      }
      break;
    }

#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
    case 9:     /* nexec */
      sqlite3_result_int(ctx, pOp->nExec);
      break;
    case 10:    /* ncycle */
      sqlite3_result_int(ctx, pOp->nCycle);
      break;
#else
    case 9:     /* nexec */
    case 10:    /* ncycle */
      sqlite3_result_int(ctx, 0);
      break;
#endif
106989
106990
106991
106992
106993
106994
106995
106996
106997
106998
106999
107000
107001
107002
107003
107004
107005
107006
107007
107008
107009
107010
107011
107012
107013
107014

/*
** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
*/
static SQLITE_NOINLINE int isValidSchemaTableName(
  const char *zTab,         /* Name as it appears in the SQL */
  Table *pTab,              /* The schema table we are trying to match */
  const char *zDb           /* non-NULL if a database qualifier is present */
){
  const char *zLegacy;
  assert( pTab!=0 );
  assert( pTab->tnum==1 );
  if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
  zLegacy = pTab->zName;
  if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
    if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
      return 1;
    }
    if( zDb==0 ) return 0;
    if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
  }else{
    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
  }
  return 0;
}







|










|







106893
106894
106895
106896
106897
106898
106899
106900
106901
106902
106903
106904
106905
106906
106907
106908
106909
106910
106911
106912
106913
106914
106915
106916
106917
106918

/*
** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
*/
static SQLITE_NOINLINE int isValidSchemaTableName(
  const char *zTab,         /* Name as it appears in the SQL */
  Table *pTab,              /* The schema table we are trying to match */
  Schema *pSchema           /* non-NULL if a database qualifier is present */
){
  const char *zLegacy;
  assert( pTab!=0 );
  assert( pTab->tnum==1 );
  if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
  zLegacy = pTab->zName;
  if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
    if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
      return 1;
    }
    if( pSchema==0 ) return 0;
    if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
  }else{
    if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
  }
  return 0;
}
107183
107184
107185
107186
107187
107188
107189
107190
107191
107192
107193
107194
107195
107196
107197
          }
          if( pItem->zAlias!=0 ){
            if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
              continue;
            }
          }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
            if( pTab->tnum!=1 ) continue;
            if( !isValidSchemaTableName(zTab, pTab, zDb) ) continue;
          }
          assert( ExprUseYTab(pExpr) );
          if( IN_RENAME_OBJECT && pItem->zAlias ){
            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
          }
        }
        hCol = sqlite3StrIHash(zCol);







|







107087
107088
107089
107090
107091
107092
107093
107094
107095
107096
107097
107098
107099
107100
107101
          }
          if( pItem->zAlias!=0 ){
            if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
              continue;
            }
          }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
            if( pTab->tnum!=1 ) continue;
            if( !isValidSchemaTableName(zTab, pTab, pSchema) ) continue;
          }
          assert( ExprUseYTab(pExpr) );
          if( IN_RENAME_OBJECT && pItem->zAlias ){
            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
          }
        }
        hCol = sqlite3StrIHash(zCol);
107289
107290
107291
107292
107293
107294
107295
107296
107297
107298
107299
107300
107301
107302
107303
107304
#ifndef SQLITE_OMIT_TRIGGER
      if( pParse->pTriggerTab!=0 ){
        int op = pParse->eTriggerOp;
        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
        if( pParse->bReturning ){
          if( (pNC->ncFlags & NC_UBaseReg)!=0
           && ALWAYS(zTab==0
                     || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
                     || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
          ){
            pExpr->iTable = op!=TK_DELETE;
            pTab = pParse->pTriggerTab;
          }
        }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
          pExpr->iTable = 1;
          pTab = pParse->pTriggerTab;







|
<







107193
107194
107195
107196
107197
107198
107199
107200

107201
107202
107203
107204
107205
107206
107207
#ifndef SQLITE_OMIT_TRIGGER
      if( pParse->pTriggerTab!=0 ){
        int op = pParse->eTriggerOp;
        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
        if( pParse->bReturning ){
          if( (pNC->ncFlags & NC_UBaseReg)!=0
           && ALWAYS(zTab==0
                     || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)

          ){
            pExpr->iTable = op!=TK_DELETE;
            pTab = pParse->pTriggerTab;
          }
        }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
          pExpr->iTable = 1;
          pTab = pParse->pTriggerTab;
107589
107590
107591
107592
107593
107594
107595
107596
107597
107598
107599
107600
107601
107602
107603
107604
107605
107606
107607
107608
  ** if the mask contains extra set bits.  However, it is important to
  ** avoid setting bits beyond the maximum column number of the table.
  ** (See ticket [b92e5e8ec2cdbaa1]).
  **
  ** If a generated column is referenced, set bits for every column
  ** of the table.
  */
  if( pMatch ){
    if( pExpr->iColumn>=0 ){
      pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
    }else{
      pMatch->fg.rowidUsed = 1;
    }
  }

  pExpr->op = eNewExprOp;
lookupname_end:
  if( cnt==1 ){
    assert( pNC!=0 );
#ifndef SQLITE_OMIT_AUTHORIZATION







<
|
|
<
<
<







107492
107493
107494
107495
107496
107497
107498

107499
107500



107501
107502
107503
107504
107505
107506
107507
  ** if the mask contains extra set bits.  However, it is important to
  ** avoid setting bits beyond the maximum column number of the table.
  ** (See ticket [b92e5e8ec2cdbaa1]).
  **
  ** If a generated column is referenced, set bits for every column
  ** of the table.
  */

  if( pExpr->iColumn>=0 && cnt==1 && pMatch!=0 ){
    pMatch->colUsed |= sqlite3ExprColUsed(pExpr);



  }

  pExpr->op = eNewExprOp;
lookupname_end:
  if( cnt==1 ){
    assert( pNC!=0 );
#ifndef SQLITE_OMIT_AUTHORIZATION
108046
108047
108048
108049
108050
108051
108052

108053
108054
108055

108056
108057
108058
108059
108060
108061
108062
#ifndef SQLITE_OMIT_WINDOWFUNC
          pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
#else
          pNC->ncFlags &= ~NC_AllowAgg;
#endif
        }
      }

      else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
        is_agg = 1;
      }

      sqlite3WalkExprList(pWalker, pList);
      if( is_agg ){
        if( pExpr->pLeft ){
          assert( pExpr->pLeft->op==TK_ORDER );
          assert( ExprUseXList(pExpr->pLeft) );
          sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
        }







>
|


>







107945
107946
107947
107948
107949
107950
107951
107952
107953
107954
107955
107956
107957
107958
107959
107960
107961
107962
107963
#ifndef SQLITE_OMIT_WINDOWFUNC
          pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
#else
          pNC->ncFlags &= ~NC_AllowAgg;
#endif
        }
      }
#ifndef SQLITE_OMIT_WINDOWFUNC
      else if( ExprHasProperty(pExpr, EP_WinFunc) ){
        is_agg = 1;
      }
#endif
      sqlite3WalkExprList(pWalker, pList);
      if( is_agg ){
        if( pExpr->pLeft ){
          assert( pExpr->pLeft->op==TK_ORDER );
          assert( ExprUseXList(pExpr->pLeft) );
          sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
        }
108128
108129
108130
108131
108132
108133
108134
108135
108136
108137
108138
108139
108140
108141
108142
        }else{
          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
        }
        assert( pNC->nRef>=nRef );
        if( nRef!=pNC->nRef ){
          ExprSetProperty(pExpr, EP_VarSelect);
          pExpr->x.pSelect->selFlags |= SF_Correlated;
          if( pExpr->op==TK_EXISTS ) pParse->bHasExists = 1;
        }
        pNC->ncFlags |= NC_Subquery;
      }
      break;
    }
    case TK_VARIABLE: {
      testcase( pNC->ncFlags & NC_IsCheck );







<







108029
108030
108031
108032
108033
108034
108035

108036
108037
108038
108039
108040
108041
108042
        }else{
          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
        }
        assert( pNC->nRef>=nRef );
        if( nRef!=pNC->nRef ){
          ExprSetProperty(pExpr, EP_VarSelect);
          pExpr->x.pSelect->selFlags |= SF_Correlated;

        }
        pNC->ncFlags |= NC_Subquery;
      }
      break;
    }
    case TK_VARIABLE: {
      testcase( pNC->ncFlags & NC_IsCheck );
108267
108268
108269
108270
108271
108272
108273
108274
108275
108276
108277
108278
108279
108280
108281
  int i;             /* Loop counter */
  ExprList *pEList;  /* The columns of the result set */
  NameContext nc;    /* Name context for resolving pE */
  sqlite3 *db;       /* Database connection */
  int rc;            /* Return code from subprocedures */
  u8 savedSuppErr;   /* Saved value of db->suppressErr */

  assert( sqlite3ExprIsInteger(pE, &i, 0)==0 );
  pEList = pSelect->pEList;

  /* Resolve all names in the ORDER BY term expression
  */
  memset(&nc, 0, sizeof(nc));
  nc.pParse = pParse;
  nc.pSrcList = pSelect->pSrc;







|







108167
108168
108169
108170
108171
108172
108173
108174
108175
108176
108177
108178
108179
108180
108181
  int i;             /* Loop counter */
  ExprList *pEList;  /* The columns of the result set */
  NameContext nc;    /* Name context for resolving pE */
  sqlite3 *db;       /* Database connection */
  int rc;            /* Return code from subprocedures */
  u8 savedSuppErr;   /* Saved value of db->suppressErr */

  assert( sqlite3ExprIsInteger(pE, &i)==0 );
  pEList = pSelect->pEList;

  /* Resolve all names in the ORDER BY term expression
  */
  memset(&nc, 0, sizeof(nc));
  nc.pParse = pParse;
  nc.pSrcList = pSelect->pSrc;
108366
108367
108368
108369
108370
108371
108372
108373
108374
108375
108376
108377
108378
108379
108380
    assert( pEList!=0 );
    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
      int iCol = -1;
      Expr *pE, *pDup;
      if( pItem->fg.done ) continue;
      pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
      if( NEVER(pE==0) ) continue;
      if( sqlite3ExprIsInteger(pE, &iCol, 0) ){
        if( iCol<=0 || iCol>pEList->nExpr ){
          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
          return 1;
        }
      }else{
        iCol = resolveAsName(pParse, pEList, pE);
        if( iCol==0 ){







|







108266
108267
108268
108269
108270
108271
108272
108273
108274
108275
108276
108277
108278
108279
108280
    assert( pEList!=0 );
    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
      int iCol = -1;
      Expr *pE, *pDup;
      if( pItem->fg.done ) continue;
      pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
      if( NEVER(pE==0) ) continue;
      if( sqlite3ExprIsInteger(pE, &iCol) ){
        if( iCol<=0 || iCol>pEList->nExpr ){
          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
          return 1;
        }
      }else{
        iCol = resolveAsName(pParse, pEList, pE);
        if( iCol==0 ){
108551
108552
108553
108554
108555
108556
108557
108558
108559
108560
108561
108562
108563
108564
108565
        ** a copy of the iCol-th result-set column.  The subsequent call to
        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
        ** copy of the iCol-th result-set expression. */
        pItem->u.x.iOrderByCol = (u16)iCol;
        continue;
      }
    }
    if( sqlite3ExprIsInteger(pE2, &iCol, 0) ){
      /* The ORDER BY term is an integer constant.  Again, set the column
      ** number so that sqlite3ResolveOrderGroupBy() will convert the
      ** order-by term to a copy of the result-set expression */
      if( iCol<1 || iCol>0xffff ){
        resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
        return 1;
      }







|







108451
108452
108453
108454
108455
108456
108457
108458
108459
108460
108461
108462
108463
108464
108465
        ** a copy of the iCol-th result-set column.  The subsequent call to
        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
        ** copy of the iCol-th result-set expression. */
        pItem->u.x.iOrderByCol = (u16)iCol;
        continue;
      }
    }
    if( sqlite3ExprIsInteger(pE2, &iCol) ){
      /* The ORDER BY term is an integer constant.  Again, set the column
      ** number so that sqlite3ResolveOrderGroupBy() will convert the
      ** order-by term to a copy of the result-set expression */
      if( iCol<1 || iCol>0xffff ){
        resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
        return 1;
      }
108654
108655
108656
108657
108658
108659
108660
108661
108662
108663
108664
108665
108666
108667
108668
    }

    /* Recursively resolve names in all subqueries in the FROM clause
    */
    if( pOuterNC ) pOuterNC->nNestedSelect++;
    for(i=0; i<p->pSrc->nSrc; i++){
      SrcItem *pItem = &p->pSrc->a[i];
      assert( pItem->zName!=0 || pItem->pSelect!=0 );/* Test of tag-20240424-1*/
      if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
        int nRef = pOuterNC ? pOuterNC->nRef : 0;
        const char *zSavedContext = pParse->zAuthContext;

        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
        pParse->zAuthContext = zSavedContext;







<







108554
108555
108556
108557
108558
108559
108560

108561
108562
108563
108564
108565
108566
108567
    }

    /* Recursively resolve names in all subqueries in the FROM clause
    */
    if( pOuterNC ) pOuterNC->nNestedSelect++;
    for(i=0; i<p->pSrc->nSrc; i++){
      SrcItem *pItem = &p->pSrc->a[i];

      if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
        int nRef = pOuterNC ? pOuterNC->nRef : 0;
        const char *zSavedContext = pParse->zAuthContext;

        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
        pParse->zAuthContext = zSavedContext;
110414
110415
110416
110417
110418
110419
110420
110421
110422
110423
110424
110425
110426
110427
110428
110429
110430
110431
110432
110433
110434
110435
110436

110437
110438
110439
110440
110441
110442
110443
110444
110445
110446
110447
110448
110449
110450
110451
110452
110453
110454
110455
110456
110457
110458
110459
110460
110461
110462
110463
110464
110465
110466
110467
110468
110469
110470

/*
** Recursively delete an expression tree.
*/
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  assert( p!=0 );
  assert( db!=0 );
exprDeleteRestart:
  assert( !ExprUseUValue(p) || p->u.iValue>=0 );
  assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
  assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
  assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
#ifdef SQLITE_DEBUG
  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
    assert( p->pLeft==0 );
    assert( p->pRight==0 );
    assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
    assert( !ExprUseXList(p) || p->x.pList==0 );
  }
#endif
  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
    /* The Expr.x union is never used at the same time as Expr.pRight */
    assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );

    if( p->pRight ){
      assert( !ExprHasProperty(p, EP_WinFunc) );
      sqlite3ExprDeleteNN(db, p->pRight);
    }else if( ExprUseXSelect(p) ){
      assert( !ExprHasProperty(p, EP_WinFunc) );
      sqlite3SelectDelete(db, p->x.pSelect);
    }else{
      sqlite3ExprListDelete(db, p->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( ExprHasProperty(p, EP_WinFunc) ){
        sqlite3WindowDelete(db, p->y.pWin);
      }
#endif
    }
    if( p->pLeft && p->op!=TK_SELECT_COLUMN ){
      Expr *pLeft = p->pLeft;
      if( !ExprHasProperty(p, EP_Static)
       && !ExprHasProperty(pLeft, EP_Static)
      ){
        /* Avoid unnecessary recursion on unary operators */
        sqlite3DbNNFreeNN(db, p);
        p = pLeft;
        goto exprDeleteRestart;
      }else{
        sqlite3ExprDeleteNN(db, pLeft);
      }
    }
  }
  if( !ExprHasProperty(p, EP_Static) ){
    sqlite3DbNNFreeNN(db, p);
  }
}
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  if( p ) sqlite3ExprDeleteNN(db, p);







<















>














<
<
<
<
<
<
<
<
<
<
<
<
<







110313
110314
110315
110316
110317
110318
110319

110320
110321
110322
110323
110324
110325
110326
110327
110328
110329
110330
110331
110332
110333
110334
110335
110336
110337
110338
110339
110340
110341
110342
110343
110344
110345
110346
110347
110348
110349













110350
110351
110352
110353
110354
110355
110356

/*
** Recursively delete an expression tree.
*/
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  assert( p!=0 );
  assert( db!=0 );

  assert( !ExprUseUValue(p) || p->u.iValue>=0 );
  assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
  assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
  assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
#ifdef SQLITE_DEBUG
  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
    assert( p->pLeft==0 );
    assert( p->pRight==0 );
    assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
    assert( !ExprUseXList(p) || p->x.pList==0 );
  }
#endif
  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
    /* The Expr.x union is never used at the same time as Expr.pRight */
    assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
    if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
    if( p->pRight ){
      assert( !ExprHasProperty(p, EP_WinFunc) );
      sqlite3ExprDeleteNN(db, p->pRight);
    }else if( ExprUseXSelect(p) ){
      assert( !ExprHasProperty(p, EP_WinFunc) );
      sqlite3SelectDelete(db, p->x.pSelect);
    }else{
      sqlite3ExprListDelete(db, p->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( ExprHasProperty(p, EP_WinFunc) ){
        sqlite3WindowDelete(db, p->y.pWin);
      }
#endif
    }













  }
  if( !ExprHasProperty(p, EP_Static) ){
    sqlite3DbNNFreeNN(db, p);
  }
}
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  if( p ) sqlite3ExprDeleteNN(db, p);
110489
110490
110491
110492
110493
110494
110495
110496
110497
110498
110499
110500
110501
110502
110503
110504
110505
110506
110507
/*
** Arrange to cause pExpr to be deleted when the pParse is deleted.
** This is similar to sqlite3ExprDelete() except that the delete is
** deferred until the pParse is deleted.
**
** The pExpr might be deleted immediately on an OOM error.
**
** Return 0 if the delete was successfully deferred.  Return non-zero
** if the delete happened immediately because of an OOM.
*/
SQLITE_PRIVATE int sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
  return 0==sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
}

/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
** expression.
*/
SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
  if( p ){







|
|

|
|







110375
110376
110377
110378
110379
110380
110381
110382
110383
110384
110385
110386
110387
110388
110389
110390
110391
110392
110393
/*
** Arrange to cause pExpr to be deleted when the pParse is deleted.
** This is similar to sqlite3ExprDelete() except that the delete is
** deferred until the pParse is deleted.
**
** The pExpr might be deleted immediately on an OOM error.
**
** The deferred delete is (currently) implemented by adding the
** pExpr to the pParse->pConstExpr list with a register number of 0.
*/
SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
  sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
}

/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
** expression.
*/
SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
  if( p ){
111452
111453
111454
111455
111456
111457
111458
111459
111460
111461
111462
111463
111464
111465
111466
   || pDef->xFinalize!=0
   || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
   || ExprHasProperty(pExpr, EP_WinFunc)
  ){
    pWalker->eCode = 0;
    return WRC_Abort;
  }
  return WRC_Prune;
}


/*
** These routines are Walker callbacks used to check expressions to
** see if they are "constant" for some definition of constant.  The
** Walker.eCode value determines the type of "constant" we are looking







|







111338
111339
111340
111341
111342
111343
111344
111345
111346
111347
111348
111349
111350
111351
111352
   || pDef->xFinalize!=0
   || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
   || ExprHasProperty(pExpr, EP_WinFunc)
  ){
    pWalker->eCode = 0;
    return WRC_Abort;
  }
  return WRC_Continue;
}


/*
** These routines are Walker callbacks used to check expressions to
** see if they are "constant" for some definition of constant.  The
** Walker.eCode value determines the type of "constant" we are looking
111835
111836
111837
111838
111839
111840
111841
111842
111843
111844
111845
111846
111847
111848
111849
111850
111851
111852
111853
111854
111855
111856
111857
111858
111859
111860
111861
111862
111863
111864
111865
111866
111867
111868
111869
111870
111871
111872
111873
111874
111875
111876
111877
111878
111879
111880
111881
111882
111883
111884
111885
111886
111887
111888
111889
111890
111891
111892
111893
111894
111895
111896
111897
111898
#endif

/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue.  If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
**
** If the pParse pointer is provided, then allow the expression p to be
** a parameter (TK_VARIABLE) that is bound to an integer.
** But if pParse is NULL, then p must be a pure integer literal.
*/
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse){
  int rc = 0;
  if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */

  /* If an expression is an integer literal that fits in a signed 32-bit
  ** integer, then the EP_IntValue flag will have already been set */
  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
           || sqlite3GetInt32(p->u.zToken, &rc)==0 );

  if( p->flags & EP_IntValue ){
    *pValue = p->u.iValue;
    return 1;
  }
  switch( p->op ){
    case TK_UPLUS: {
      rc = sqlite3ExprIsInteger(p->pLeft, pValue, 0);
      break;
    }
    case TK_UMINUS: {
      int v = 0;
      if( sqlite3ExprIsInteger(p->pLeft, &v, 0) ){
        assert( ((unsigned int)v)!=0x80000000 );
        *pValue = -v;
        rc = 1;
      }
      break;
    }
    case TK_VARIABLE: {
      sqlite3_value *pVal;
      if( pParse==0 ) break;
      if( NEVER(pParse->pVdbe==0) ) break;
      if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break;
      sqlite3VdbeSetVarmask(pParse->pVdbe, p->iColumn);
      pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn,
                                      SQLITE_AFF_BLOB);
      if( pVal ){
        if( sqlite3_value_type(pVal)==SQLITE_INTEGER ){
          sqlite3_int64 vv = sqlite3_value_int64(pVal);
          if( vv == (vv & 0x7fffffff) ){ /* non-negative numbers only */
            *pValue = (int)vv;
            rc = 1;
          }
        }
        sqlite3ValueFree(pVal);
      }
      break;
    }
    default: break;
  }
  return rc;
}








<
<
<
<

|














|




|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







111721
111722
111723
111724
111725
111726
111727




111728
111729
111730
111731
111732
111733
111734
111735
111736
111737
111738
111739
111740
111741
111742
111743
111744
111745
111746
111747
111748
111749
111750
111751
111752
111753




















111754
111755
111756
111757
111758
111759
111760
#endif

/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue.  If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.




*/
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue){
  int rc = 0;
  if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */

  /* If an expression is an integer literal that fits in a signed 32-bit
  ** integer, then the EP_IntValue flag will have already been set */
  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
           || sqlite3GetInt32(p->u.zToken, &rc)==0 );

  if( p->flags & EP_IntValue ){
    *pValue = p->u.iValue;
    return 1;
  }
  switch( p->op ){
    case TK_UPLUS: {
      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
      break;
    }
    case TK_UMINUS: {
      int v = 0;
      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
        assert( ((unsigned int)v)!=0x80000000 );
        *pValue = -v;
        rc = 1;
      }




















      break;
    }
    default: break;
  }
  return rc;
}

113313
113314
113315
113316
113317
113318
113319
113320
113321
113322
113323
113324
113325
113326
113327
}

/*
** Convert a scalar expression node to a TK_REGISTER referencing
** register iReg.  The caller must ensure that iReg already contains
** the correct value for the expression.
*/
SQLITE_PRIVATE void sqlite3ExprToRegister(Expr *pExpr, int iReg){
  Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
  if( NEVER(p==0) ) return;
  p->op2 = p->op;
  p->op = TK_REGISTER;
  p->iTable = iReg;
  ExprClearProperty(p, EP_Skip);
}







|







113175
113176
113177
113178
113179
113180
113181
113182
113183
113184
113185
113186
113187
113188
113189
}

/*
** Convert a scalar expression node to a TK_REGISTER referencing
** register iReg.  The caller must ensure that iReg already contains
** the correct value for the expression.
*/
static void exprToRegister(Expr *pExpr, int iReg){
  Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
  if( NEVER(p==0) ) return;
  p->op2 = p->op;
  p->op = TK_REGISTER;
  p->iTable = iReg;
  ExprClearProperty(p, EP_Skip);
}
114322
114323
114324
114325
114326
114327
114328
114329
114330
114331
114332
114333
114334
114335
114336
      if( (pX = pExpr->pLeft)!=0 ){
        pDel = sqlite3ExprDup(db, pX, 0);
        if( db->mallocFailed ){
          sqlite3ExprDelete(db, pDel);
          break;
        }
        testcase( pX->op==TK_COLUMN );
        sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
        testcase( regFree1==0 );
        memset(&opCompare, 0, sizeof(opCompare));
        opCompare.op = TK_EQ;
        opCompare.pLeft = pDel;
        pTest = &opCompare;
        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
        ** The value in regFree1 might get SCopy-ed into the file result.







|







114184
114185
114186
114187
114188
114189
114190
114191
114192
114193
114194
114195
114196
114197
114198
      if( (pX = pExpr->pLeft)!=0 ){
        pDel = sqlite3ExprDup(db, pX, 0);
        if( db->mallocFailed ){
          sqlite3ExprDelete(db, pDel);
          break;
        }
        testcase( pX->op==TK_COLUMN );
        exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
        testcase( regFree1==0 );
        memset(&opCompare, 0, sizeof(opCompare));
        opCompare.op = TK_EQ;
        opCompare.pLeft = pDel;
        pTest = &opCompare;
        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
        ** The value in regFree1 might get SCopy-ed into the file result.
114376
114377
114378
114379
114380
114381
114382
114383

114384
114385
114386
114387
114388
114389
114390

114391
114392
114393
114394
114395
114396
114397
        return 0;
      }
      if( pExpr->affExpr==OE_Abort ){
        sqlite3MayAbort(pParse);
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      if( pExpr->affExpr==OE_Ignore ){
        sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);

        VdbeCoverage(v);
      }else{
        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
        sqlite3VdbeAddOp3(v, OP_Halt,
             pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
             pExpr->affExpr, r1);
      }

      break;
    }
#endif
  }
  sqlite3ReleaseTempReg(pParse, regFree1);
  sqlite3ReleaseTempReg(pParse, regFree2);
  return inReg;







|
>


<
|

|

>







114238
114239
114240
114241
114242
114243
114244
114245
114246
114247
114248

114249
114250
114251
114252
114253
114254
114255
114256
114257
114258
114259
114260
        return 0;
      }
      if( pExpr->affExpr==OE_Abort ){
        sqlite3MayAbort(pParse);
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      if( pExpr->affExpr==OE_Ignore ){
        sqlite3VdbeAddOp4(
            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
        VdbeCoverage(v);
      }else{

        sqlite3HaltConstraint(pParse,
             pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
             pExpr->affExpr, pExpr->u.zToken, 0, 0);
      }

      break;
    }
#endif
  }
  sqlite3ReleaseTempReg(pParse, regFree1);
  sqlite3ReleaseTempReg(pParse, regFree2);
  return inReg;
114672
114673
114674
114675
114676
114677
114678
114679
114680
114681
114682
114683
114684
114685
114686
    exprAnd.pRight = &compRight;
    compLeft.op = TK_GE;
    compLeft.pLeft = pDel;
    compLeft.pRight = pExpr->x.pList->a[0].pExpr;
    compRight.op = TK_LE;
    compRight.pLeft = pDel;
    compRight.pRight = pExpr->x.pList->a[1].pExpr;
    sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
    if( xJump ){
      xJump(pParse, &exprAnd, dest, jumpIfNull);
    }else{
      /* Mark the expression is being from the ON or USING clause of a join
      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
      ** it into the Parse.pConstExpr list.  We should use a new bit for this,
      ** for clarity, but we are out of bits in the Expr.flags field so we







|







114535
114536
114537
114538
114539
114540
114541
114542
114543
114544
114545
114546
114547
114548
114549
    exprAnd.pRight = &compRight;
    compLeft.op = TK_GE;
    compLeft.pLeft = pDel;
    compLeft.pRight = pExpr->x.pList->a[0].pExpr;
    compRight.op = TK_LE;
    compRight.pLeft = pDel;
    compRight.pRight = pExpr->x.pList->a[1].pExpr;
    exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
    if( xJump ){
      xJump(pParse, &exprAnd, dest, jumpIfNull);
    }else{
      /* Mark the expression is being from the ON or USING clause of a join
      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
      ** it into the Parse.pConstExpr list.  We should use a new bit for this,
      ** for clarity, but we are out of bits in the Expr.flags field so we
115750
115751
115752
115753
115754
115755
115756
115757
115758

115759
115760
115761
115762
115763
115764
115765
115766
115767
115768

115769
115770
115771
115772
115773
115774
115775
    sqlite3 *db = pParse->db;
    assert( iAgg>=0 );
    if( pExpr->op!=TK_AGG_FUNCTION ){
      if( iAgg<pAggInfo->nColumn
       && pAggInfo->aCol[iAgg].pCExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
          pAggInfo->aCol[iAgg].pCExpr = pExpr;

        }
      }
    }else{
      assert( pExpr->op==TK_AGG_FUNCTION );
      if( ALWAYS(iAgg<pAggInfo->nFunc)
       && pAggInfo->aFunc[iAgg].pFExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
          pAggInfo->aFunc[iAgg].pFExpr = pExpr;

        }
      }
    }
  }
  return WRC_Continue;
}








|

>








|

>







115613
115614
115615
115616
115617
115618
115619
115620
115621
115622
115623
115624
115625
115626
115627
115628
115629
115630
115631
115632
115633
115634
115635
115636
115637
115638
115639
115640
    sqlite3 *db = pParse->db;
    assert( iAgg>=0 );
    if( pExpr->op!=TK_AGG_FUNCTION ){
      if( iAgg<pAggInfo->nColumn
       && pAggInfo->aCol[iAgg].pCExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aCol[iAgg].pCExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }else{
      assert( pExpr->op==TK_AGG_FUNCTION );
      if( ALWAYS(iAgg<pAggInfo->nFunc)
       && pAggInfo->aFunc[iAgg].pFExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aFunc[iAgg].pFExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }
  }
  return WRC_Continue;
}

124352
124353
124354
124355
124356
124357
124358



124359
124360
124361
124362
124363
124364
124365
    /* Test for cycles in generated columns and illegal expressions
    ** in CHECK constraints and in DEFAULT clauses. */
    if( p->tabFlags & TF_HasGenerated ){
      sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
             sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
                   db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
    }



  }

  /* Add the table to the in-memory representation of the database.
  */
  if( db->init.busy ){
    Table *pOld;
    Schema *pSchema = p->pSchema;







>
>
>







124217
124218
124219
124220
124221
124222
124223
124224
124225
124226
124227
124228
124229
124230
124231
124232
124233
    /* Test for cycles in generated columns and illegal expressions
    ** in CHECK constraints and in DEFAULT clauses. */
    if( p->tabFlags & TF_HasGenerated ){
      sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
             sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
                   db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
    }
    sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
           sqlite3MPrintf(db, "PRAGMA \"%w\".integrity_check(%Q)",
                 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
  }

  /* Add the table to the in-memory representation of the database.
  */
  if( db->init.busy ){
    Table *pOld;
    Schema *pSchema = p->pSchema;
124489
124490
124491
124492
124493
124494
124495
124496
124497
124498
124499
124500
124501
124502
124503
124504
124505
  return;
}
#endif /* SQLITE_OMIT_VIEW */

#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW.  Fill in the names of
** the columns of the view in the pTable structure.  Return non-zero if
** there are errors.  If an error is seen an error message is left
** in pParse->zErrMsg.
*/
static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
  Table *pSelTab;   /* A fake table from which we get the result set */
  Select *pSel;     /* Copy of the SELECT that implements the view */
  int nErr = 0;     /* Number of errors encountered */
  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
#ifndef SQLITE_OMIT_VIRTUALTABLE







|
|
<







124357
124358
124359
124360
124361
124362
124363
124364
124365

124366
124367
124368
124369
124370
124371
124372
  return;
}
#endif /* SQLITE_OMIT_VIEW */

#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW.  Fill in the names of
** the columns of the view in the pTable structure.  Return the number
** of errors.  If an error is seen leave an error message in pParse->zErrMsg.

*/
static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
  Table *pSelTab;   /* A fake table from which we get the result set */
  Select *pSel;     /* Copy of the SELECT that implements the view */
  int nErr = 0;     /* Number of errors encountered */
  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
#ifndef SQLITE_OMIT_VIRTUALTABLE
124614
124615
124616
124617
124618
124619
124620
124621
124622
124623
124624
124625
124626
124627
124628
    nErr++;
  }
  pTable->pSchema->schemaFlags |= DB_UnresetViews;
  if( db->mallocFailed ){
    sqlite3DeleteColumnNames(db, pTable);
  }
#endif /* SQLITE_OMIT_VIEW */
  return nErr + pParse->nErr;
}
SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  assert( pTable!=0 );
  if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
  return viewGetColumnNames(pParse, pTable);
}
#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */







|







124481
124482
124483
124484
124485
124486
124487
124488
124489
124490
124491
124492
124493
124494
124495
    nErr++;
  }
  pTable->pSchema->schemaFlags |= DB_UnresetViews;
  if( db->mallocFailed ){
    sqlite3DeleteColumnNames(db, pTable);
  }
#endif /* SQLITE_OMIT_VIEW */
  return nErr;
}
SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  assert( pTable!=0 );
  if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
  return viewGetColumnNames(pParse, pTable);
}
#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
126474
126475
126476
126477
126478
126479
126480
126481
126482
126483
126484
126485
126486
126487
126488
126489
126490
126491
126492
126493
126494
126495
126496
126497
126498

/*
** Append the contents of SrcList p2 to SrcList p1 and return the resulting
** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
** are deleted by this function.
*/
SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
  assert( p1 );
  if( p2 ){
    int nOld = p1->nSrc;
    SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, nOld);
    if( pNew==0 ){
      sqlite3SrcListDelete(pParse->db, p2);
    }else{
      p1 = pNew;
      memcpy(&p1->a[nOld], p2->a, p2->nSrc*sizeof(SrcItem));
      assert( nOld==1 || (p2->nSrc==1 && (p2->a[0].fg.jointype&JT_LTORJ)==0) );
      assert( p1->nSrc>=2 );
      sqlite3DbFree(pParse->db, p2);
      p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
    }
  }
  return p1;
}








|

<
|




|
<
<







126341
126342
126343
126344
126345
126346
126347
126348
126349

126350
126351
126352
126353
126354
126355


126356
126357
126358
126359
126360
126361
126362

/*
** Append the contents of SrcList p2 to SrcList p1 and return the resulting
** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
** are deleted by this function.
*/
SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
  assert( p1 && p1->nSrc==1 );
  if( p2 ){

    SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
    if( pNew==0 ){
      sqlite3SrcListDelete(pParse->db, p2);
    }else{
      p1 = pNew;
      memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));


      sqlite3DbFree(pParse->db, p2);
      p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
    }
  }
  return p1;
}

130915
130916
130917
130918
130919
130920
130921
130922
130923
130924
130925
130926
130927
130928
130929
130930
    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
  if( pGCC ){
    StrAccum *pAccum = &pGCC->str;
    if( pAccum->accError==SQLITE_TOOBIG ){
      sqlite3_result_error_toobig(context);
    }else if( pAccum->accError==SQLITE_NOMEM ){
      sqlite3_result_error_nomem(context);
    }else if( pGCC->nAccum>0 && pAccum->nChar==0 ){
      sqlite3_result_text(context, "", 1, SQLITE_STATIC);
    }else{
      const char *zText = sqlite3_str_value(pAccum);
      sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
    }
  }
}
#else







<
<







130779
130780
130781
130782
130783
130784
130785


130786
130787
130788
130789
130790
130791
130792
    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
  if( pGCC ){
    StrAccum *pAccum = &pGCC->str;
    if( pAccum->accError==SQLITE_TOOBIG ){
      sqlite3_result_error_toobig(context);
    }else if( pAccum->accError==SQLITE_NOMEM ){
      sqlite3_result_error_nomem(context);


    }else{
      const char *zText = sqlite3_str_value(pAccum);
      sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
    }
  }
}
#else
131256
131257
131258
131259
131260
131261
131262
131263
131264
131265
131266
131267
131268
131269
131270
  int y, z;
  char zBuf[100];
  UNUSED_PARAMETER(argc);
  assert( argc==3 );
  x = sqlite3_value_double(argv[0]);
  y = sqlite3_value_int(argv[1]);
  z = sqlite3_value_int(argv[2]);
  if( z<=0 ) z = 1;
  sqlite3FpDecode(&s, x, y, z);
  if( s.isSpecial==2 ){
    sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
  }else{
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
  }
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);







<







131118
131119
131120
131121
131122
131123
131124

131125
131126
131127
131128
131129
131130
131131
  int y, z;
  char zBuf[100];
  UNUSED_PARAMETER(argc);
  assert( argc==3 );
  x = sqlite3_value_double(argv[0]);
  y = sqlite3_value_int(argv[1]);
  z = sqlite3_value_int(argv[2]);

  sqlite3FpDecode(&s, x, y, z);
  if( s.isSpecial==2 ){
    sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
  }else{
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
  }
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
132798
132799
132800
132801
132802
132803
132804
132805
132806
132807
132808
132809
132810
132811
132812
132813
    nFrom = sqlite3Strlen30(zFrom);

    if( action==OE_Restrict ){
      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      SrcList *pSrc;
      Expr *pRaise;

      pRaise = sqlite3Expr(db, TK_STRING, "FOREIGN KEY constraint failed"),
      pRaise = sqlite3PExpr(pParse, TK_RAISE, pRaise, 0);
      if( pRaise ){
        pRaise->affExpr = OE_Abort;
      }
      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
      if( pSrc ){
        assert( pSrc->nSrc==1 );
        pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom);







|
<







132659
132660
132661
132662
132663
132664
132665
132666

132667
132668
132669
132670
132671
132672
132673
    nFrom = sqlite3Strlen30(zFrom);

    if( action==OE_Restrict ){
      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      SrcList *pSrc;
      Expr *pRaise;

      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");

      if( pRaise ){
        pRaise->affExpr = OE_Abort;
      }
      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
      if( pSrc ){
        assert( pSrc->nSrc==1 );
        pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom);
140489
140490
140491
140492
140493
140494
140495
140496
140497
140498
140499
140500
140501
140502
140503

    /* Initialize the VDBE program */
    pParse->nMem = 6;

    /* Set the maximum error count */
    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
    if( zRight ){
      if( sqlite3GetInt32(pValue->z, &mxErr) ){
        if( mxErr<=0 ){
          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
        }
      }else{
        pObjTab = sqlite3LocateTable(pParse, 0, zRight,
                      iDb>=0 ? db->aDb[iDb].zDbSName : 0);
      }







|







140349
140350
140351
140352
140353
140354
140355
140356
140357
140358
140359
140360
140361
140362
140363

    /* Initialize the VDBE program */
    pParse->nMem = 6;

    /* Set the maximum error count */
    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
    if( zRight ){
      if( sqlite3GetInt32(zRight, &mxErr) ){
        if( mxErr<=0 ){
          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
        }
      }else{
        pObjTab = sqlite3LocateTable(pParse, 0, zRight,
                      iDb>=0 ? db->aDb[iDb].zDbSName : 0);
      }
141697
141698
141699
141700
141701
141702
141703
141704
141705
141706
141707
141708
141709
141710
141711
}

/* Clear all content from pragma virtual table cursor. */
static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  int i;
  sqlite3_finalize(pCsr->pPragma);
  pCsr->pPragma = 0;
  pCsr->iRowid = 0;
  for(i=0; i<ArraySize(pCsr->azArg); i++){
    sqlite3_free(pCsr->azArg[i]);
    pCsr->azArg[i] = 0;
  }
}

/* Close a pragma virtual table cursor */







<







141557
141558
141559
141560
141561
141562
141563

141564
141565
141566
141567
141568
141569
141570
}

/* Clear all content from pragma virtual table cursor. */
static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  int i;
  sqlite3_finalize(pCsr->pPragma);
  pCsr->pPragma = 0;

  for(i=0; i<ArraySize(pCsr->azArg); i++){
    sqlite3_free(pCsr->azArg[i]);
    pCsr->azArg[i] = 0;
  }
}

/* Close a pragma virtual table cursor */
142498
142499
142500
142501
142502
142503
142504
142505
142506
142507
142508
142509
142510
142511
142512
142513
142514
142515
142516
142517
142518
**       pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
*/
SQLITE_PRIVATE void *sqlite3ParserAddCleanup(
  Parse *pParse,                      /* Destroy when this Parser finishes */
  void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
  void *pPtr                          /* Pointer to object to be cleaned up */
){
  ParseCleanup *pCleanup;
  if( sqlite3FaultSim(300) ){
    pCleanup = 0;
    sqlite3OomFault(pParse->db);
  }else{
    pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
  }
  if( pCleanup ){
    pCleanup->pNext = pParse->pCleanup;
    pParse->pCleanup = pCleanup;
    pCleanup->pPtr = pPtr;
    pCleanup->xCleanup = xCleanup;
  }else{
    xCleanup(pParse->db, pPtr);







<
<
<
<
<
|
<







142357
142358
142359
142360
142361
142362
142363





142364

142365
142366
142367
142368
142369
142370
142371
**       pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
*/
SQLITE_PRIVATE void *sqlite3ParserAddCleanup(
  Parse *pParse,                      /* Destroy when this Parser finishes */
  void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
  void *pPtr                          /* Pointer to object to be cleaned up */
){





  ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));

  if( pCleanup ){
    pCleanup->pNext = pParse->pCleanup;
    pParse->pCleanup = pCleanup;
    pCleanup->pPtr = pPtr;
    pCleanup->xCleanup = xCleanup;
  }else{
    xCleanup(pParse->db, pPtr);
145277
145278
145279
145280
145281
145282
145283

145284
145285
145286
145287
145288
145289
145290
145291
145292
145293
145294
145295
145296
145297
145298
145299
145300
145301
145302
145303
145304
145305
145306
145307
145308
145309


145310
145311
145312
145313
145314
145315
145316
145317
  CollSeq *pColl;
  int i,j;
  Expr *p;
  struct ExprList_item *a;
  NameContext sNC;

  assert( pSelect!=0 );

  assert( (pSelect->selFlags & SF_Resolved)!=0 );
  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
  if( db->mallocFailed || IN_RENAME_OBJECT ) return;
  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  a = pSelect->pEList->a;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pSrcList = pSelect->pSrc;
  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
    const char *zType;
    i64 n;
    int m = 0;
    Select *pS2 = pSelect;
    pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
    p = a[i].pExpr;
    /* pCol->szEst = ... // Column size est for SELECT tables never used */
    pCol->affinity = sqlite3ExprAffinity(p);
    while( pCol->affinity<=SQLITE_AFF_NONE && pS2->pNext!=0 ){
      m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
      pS2 = pS2->pNext;
      pCol->affinity = sqlite3ExprAffinity(pS2->pEList->a[i].pExpr);
    }
    if( pCol->affinity<=SQLITE_AFF_NONE ){
      pCol->affinity = aff;
    }
    if( pCol->affinity>=SQLITE_AFF_TEXT && (pS2->pNext || pS2!=pSelect) ){


      for(pS2=pS2->pNext; pS2; pS2=pS2->pNext){
        m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
      }
      if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
        pCol->affinity = SQLITE_AFF_BLOB;
      }else
      if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
        pCol->affinity = SQLITE_AFF_BLOB;







>
|










<
<




<
<
<
<
<



|
>
>
|







145130
145131
145132
145133
145134
145135
145136
145137
145138
145139
145140
145141
145142
145143
145144
145145
145146
145147
145148


145149
145150
145151
145152





145153
145154
145155
145156
145157
145158
145159
145160
145161
145162
145163
145164
145165
145166
  CollSeq *pColl;
  int i,j;
  Expr *p;
  struct ExprList_item *a;
  NameContext sNC;

  assert( pSelect!=0 );
  testcase( (pSelect->selFlags & SF_Resolved)==0 );
  assert( (pSelect->selFlags & SF_Resolved)!=0 || IN_RENAME_OBJECT );
  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
  if( db->mallocFailed || IN_RENAME_OBJECT ) return;
  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  a = pSelect->pEList->a;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pSrcList = pSelect->pSrc;
  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
    const char *zType;
    i64 n;


    pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
    p = a[i].pExpr;
    /* pCol->szEst = ... // Column size est for SELECT tables never used */
    pCol->affinity = sqlite3ExprAffinity(p);





    if( pCol->affinity<=SQLITE_AFF_NONE ){
      pCol->affinity = aff;
    }
    if( pCol->affinity>=SQLITE_AFF_TEXT && pSelect->pNext ){
      int m = 0;
      Select *pS2;
      for(m=0, pS2=pSelect->pNext; pS2; pS2=pS2->pNext){
        m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
      }
      if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
        pCol->affinity = SQLITE_AFF_BLOB;
      }else
      if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
        pCol->affinity = SQLITE_AFF_BLOB;
145333
145334
145335
145336
145337
145338
145339
145340
145341
145342
145343
145344
145345
145346
145347
145348
145349
145350
145351
145352
            zType = sqlite3StdType[j];
            break;
          }
        }
      }
    }
    if( zType ){
      const i64 k = sqlite3Strlen30(zType);
      n = sqlite3Strlen30(pCol->zCnName);
      pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2);
      pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
      if( pCol->zCnName ){
        memcpy(&pCol->zCnName[n+1], zType, k+1);
        pCol->colFlags |= COLFLAG_HASTYPE;
      }
    }
    pColl = sqlite3ExprCollSeq(pParse, p);
    if( pColl ){
      assert( pTab->pIndex==0 );
      sqlite3ColumnSetColl(db, pCol, pColl->zName);







|

|


|







145182
145183
145184
145185
145186
145187
145188
145189
145190
145191
145192
145193
145194
145195
145196
145197
145198
145199
145200
145201
            zType = sqlite3StdType[j];
            break;
          }
        }
      }
    }
    if( zType ){
      i64 m = sqlite3Strlen30(zType);
      n = sqlite3Strlen30(pCol->zCnName);
      pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
      pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
      if( pCol->zCnName ){
        memcpy(&pCol->zCnName[n+1], zType, m+1);
        pCol->colFlags |= COLFLAG_HASTYPE;
      }
    }
    pColl = sqlite3ExprCollSeq(pParse, p);
    if( pColl ){
      assert( pTab->pIndex==0 );
      sqlite3ColumnSetColl(db, pCol, pColl->zName);
145445
145446
145447
145448
145449
145450
145451
145452
145453
145454
145455
145456
145457
145458
145459
  */
  if( pLimit ){
    assert( pLimit->op==TK_LIMIT );
    assert( pLimit->pLeft!=0 );
    p->iLimit = iLimit = ++pParse->nMem;
    v = sqlite3GetVdbe(pParse);
    assert( v!=0 );
    if( sqlite3ExprIsInteger(pLimit->pLeft, &n, pParse) ){
      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
      VdbeComment((v, "LIMIT counter"));
      if( n==0 ){
        sqlite3VdbeGoto(v, iBreak);
      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
        p->nSelectRow = sqlite3LogEst((u64)n);
        p->selFlags |= SF_FixedLimit;







|







145294
145295
145296
145297
145298
145299
145300
145301
145302
145303
145304
145305
145306
145307
145308
  */
  if( pLimit ){
    assert( pLimit->op==TK_LIMIT );
    assert( pLimit->pLeft!=0 );
    p->iLimit = iLimit = ++pParse->nMem;
    v = sqlite3GetVdbe(pParse);
    assert( v!=0 );
    if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
      VdbeComment((v, "LIMIT counter"));
      if( n==0 ){
        sqlite3VdbeGoto(v, iBreak);
      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
        p->nSelectRow = sqlite3LogEst((u64)n);
        p->selFlags |= SF_FixedLimit;
145925
145926
145927
145928
145929
145930
145931
145932
145933
145934
145935
145936
145937
145938
145939
        TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
        rc = sqlite3Select(pParse, p, &dest);
        testcase( rc!=SQLITE_OK );
        pDelete = p->pPrior;
        p->pPrior = pPrior;
        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
        if( p->pLimit
         && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse)
         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
        ){
          p->nSelectRow = sqlite3LogEst((u64)nLimit);
        }
        if( addr ){
          sqlite3VdbeJumpHere(v, addr);
        }







|







145774
145775
145776
145777
145778
145779
145780
145781
145782
145783
145784
145785
145786
145787
145788
        TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
        rc = sqlite3Select(pParse, p, &dest);
        testcase( rc!=SQLITE_OK );
        pDelete = p->pPrior;
        p->pPrior = pPrior;
        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
        if( p->pLimit
         && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
        ){
          p->nSelectRow = sqlite3LogEst((u64)nLimit);
        }
        if( addr ){
          sqlite3VdbeJumpHere(v, addr);
        }
149364
149365
149366
149367
149368
149369
149370

149371
149372
149373
149374
149375
149376
149377
149378
  int i;
  SrcList *pTabList;
  SrcItem *pFrom;

  if( p->selFlags & SF_HasTypeInfo ) return;
  p->selFlags |= SF_HasTypeInfo;
  pParse = pWalker->pParse;

  assert( (p->selFlags & SF_Resolved) );
  pTabList = p->pSrc;
  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
    Table *pTab = pFrom->pTab;
    assert( pTab!=0 );
    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
      /* A sub-query in the FROM clause of a SELECT */
      Select *pSel = pFrom->pSelect;







>
|







149213
149214
149215
149216
149217
149218
149219
149220
149221
149222
149223
149224
149225
149226
149227
149228
  int i;
  SrcList *pTabList;
  SrcItem *pFrom;

  if( p->selFlags & SF_HasTypeInfo ) return;
  p->selFlags |= SF_HasTypeInfo;
  pParse = pWalker->pParse;
  testcase( (p->selFlags & SF_Resolved)==0 );
  assert( (p->selFlags & SF_Resolved) || IN_RENAME_OBJECT );
  pTabList = p->pSrc;
  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
    Table *pTab = pFrom->pTab;
    assert( pTab!=0 );
    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
      /* A sub-query in the FROM clause of a SELECT */
      Select *pSel = pFrom->pSelect;
150236
150237
150238
150239
150240
150241
150242
150243
150244
150245
150246
150247
150248
150249
150250
150251
150252
150253
150254
150255
150256
150257
150258
150259
150260
150261
150262
150263
150264
150265
150266
150267
150268
150269
150270
150271
150272
150273
150274
150275
150276
150277
150278
150279
150280
150281
150282
150283
150284
150285
150286
150287
150288
150289
150290
150291
150292
150293
150294
150295
150296
150297
150298
150299
150300
150301
150302
150303
150304
150305
150306
150307
150308
150309
150310
150311
150312
150313
150314
150315
150316
150317
150318
150319
150320
150321
150322
150323
150324
150325
150326
150327
150328
150329
150330
150331
150332
150333
150334
150335
150336
150337
150338
150339
150340
150341
150342
150343
150344
150345
150346
150347
150348
150349
150350
150351
150352
150353
150354
150355
150356
150357
150358
150359
150360
150361
150362
150363
150364
150365
150366
150367
150368
150369
150370
150371
150372
150373
150374
150375
150376
150377
150378
150379
150380
150381
150382
150383
150384
150385
150386
150387
150388
150389
150390
150391
150392
150393
150394
150395
150396
150397
150398
150399
150400
150401
    i--;
    pItem--;
    if( pItem->pSelect!=0 ) return 0;                             /* (1c-i) */
  }
  return 1;
}

/*
** sqlite3WalkExpr() callback used by exprReferencesTable().
*/
static int exprReferencesTableExprCb(Walker *pWalker, Expr *pExpr){
  if( pExpr->op==TK_COLUMN && pExpr->iTable==pWalker->u.iCur ){
    pWalker->eCode = 1;
  }
  return WRC_Continue;
}

/*
** Return true if the expression passed as the first argument refers
** to cursor number iCur. Otherwise return false.
*/
static int exprReferencesTable(Expr *pExpr, int iCur){
  Walker w;
  memset(&w, 0, sizeof(w));
  w.u.iCur = iCur;
  w.xExprCallback = exprReferencesTableExprCb;
  w.xSelectCallback = sqlite3SelectWalkNoop;
  sqlite3WalkExpr(&w, pExpr);
  return w.eCode;
}

/*
** Index pIdx is a UNIQUE index on the table accessed by cursor number
** iCsr. This function returns a mask of the index columns that are
** constrained to match a single, non-NULL value by the WHERE clause
** passed as the 4th argument. For example, if the index is:
**
**      CREATE UNIQUE INDEX idx ON tbl(a, b, c);
**
** and pWhere:
**
**      WHERE a=? AND c=?
**
** then this function returns 5.
*/
static u64 findConstIdxTerms(
  Parse *pParse,
  int iCsr,
  Index *pIdx,
  Expr *pWhere
){
  u64 m = 0;
  if( pWhere->op==TK_AND ){
    m = findConstIdxTerms(pParse, iCsr, pIdx, pWhere->pLeft);
    m |= findConstIdxTerms(pParse, iCsr, pIdx, pWhere->pRight);
  }else if( pWhere->op==TK_EQ ){
    Expr *pLeft = sqlite3ExprSkipCollateAndLikely(pWhere->pLeft);
    Expr *pRight = sqlite3ExprSkipCollateAndLikely(pWhere->pRight);
    if( pRight->op==TK_COLUMN && pRight->iTable==iCsr ){
      SWAP(Expr*, pLeft, pRight);
    }
    if( pLeft->op==TK_COLUMN
     && pLeft->iTable==iCsr
     && exprReferencesTable(pRight, iCsr)==0
    ){
      if( pIdx ){
        int ii;
        for(ii=0; ii<pIdx->nKeyCol; ii++){
          assert( pIdx->azColl[ii] );
          if( pLeft->iColumn==pIdx->aiColumn[ii] ){
            CollSeq *pColl = sqlite3ExprCompareCollSeq(pParse, pWhere);
            if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[ii])==0 ){
              m |= ((u64)1 << ii);
              break;
            }
          }
        }
      }else{
        if( pLeft->iColumn<0 ) m = 1;
      }
    }
  }
  return m;
}

/*
** Argument pWhere is the WHERE clause belonging to SELECT statement p. This
** function attempts to transform expressions of the form:
**
**     EXISTS (SELECT ...)
**
** into joins. For example, given
**
**    CREATE TABLE sailors(sid INTEGER PRIMARY KEY, name TEXT);
**    CREATE TABLE reserves(sid INT, day DATE, PRIMARY KEY(sid, day));
**
**    SELECT name FROM sailors AS S WHERE EXISTS (
**      SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25'
**    );
**
** the SELECT statement may be transformed as follows:
**
**    SELECT name FROM sailors AS S, reserves AS R
**      WHERE S.sid = R.sid AND R.day = '2022-10-25';
*/
static void existsToJoin(Parse *pParse, Select *p, Expr *pWhere){
  if( pWhere && p->pSrc->nSrc>0 && pParse->db->mallocFailed==0 ){
    if( pWhere->op==TK_AND ){
      Expr *pRight = pWhere->pRight;
      existsToJoin(pParse, p, pWhere->pLeft);
      existsToJoin(pParse, p, pRight);
    }
    else if( pWhere->op==TK_EXISTS ){
      Select *pSub = pWhere->x.pSelect;
      if( pSub->pSrc->nSrc==1
       && (pSub->selFlags & (SF_Aggregate|SF_Correlated))==SF_Correlated
       && pSub->pWhere
      ){
        int bTransform = 0;       /* True if EXISTS can be made into join */
        Table *pTab = pSub->pSrc->a[0].pTab;
        int iCsr = pSub->pSrc->a[0].iCursor;
        Index *pIdx;
        if( HasRowid(pTab) && findConstIdxTerms(pParse, iCsr, 0,pSub->pWhere) ){
          bTransform = 1;
        }
        for(pIdx=pTab->pIndex; pIdx && bTransform==0; pIdx=pIdx->pNext){
          if( pIdx->onError && pIdx->nKeyCol<=63 ){
            u64 c = findConstIdxTerms(pParse, iCsr, pIdx, pSub->pWhere);
            if( c==((u64)1 << pIdx->nKeyCol)-1 ){
              bTransform = 1;
            }
          }
        }
        if( bTransform ){
          memset(pWhere, 0, sizeof(*pWhere));
          pWhere->op = TK_INTEGER;
          pWhere->u.iValue = 1;
          ExprSetProperty(pWhere, EP_IntValue);

          assert( p->pWhere!=0 );
          p->pSrc = sqlite3SrcListAppendList(pParse, p->pSrc, pSub->pSrc);
          p->pWhere = sqlite3PExpr(pParse, TK_AND, p->pWhere, pSub->pWhere);

          pSub->pWhere = 0;
          pSub->pSrc = 0;
          sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSub);
#if TREETRACE_ENABLED
          if( sqlite3TreeTrace & 0x100000 ){
            TREETRACE(0x100000,pParse,p,
                      ("After EXISTS-to-JOIN optimization:\n"));
            sqlite3TreeViewSelect(0, p, 0);
          }
#endif
        }
      }
    }
  }
}

/*
** Generate code for the SELECT statement given in the p argument.
**
** The results are returned according to the SelectDest structure.
** See comments in sqliteInt.h for further information.
**
** This routine returns the number of errors.  If any errors are







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







150086
150087
150088
150089
150090
150091
150092
























































































































































150093
150094
150095
150096
150097
150098
150099
    i--;
    pItem--;
    if( pItem->pSelect!=0 ) return 0;                             /* (1c-i) */
  }
  return 1;
}

























































































































































/*
** Generate code for the SELECT statement given in the p argument.
**
** The results are returned according to the SelectDest structure.
** See comments in sqliteInt.h for further information.
**
** This routine returns the number of errors.  If any errors are
150714
150715
150716
150717
150718
150719
150720
150721
150722
150723
150724
150725
150726
150727
150728
150729
150730
150731
150732
150733
150734
    }
#endif
    if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
    return rc;
  }
#endif

  /* If there may be an "EXISTS (SELECT ...)" in the WHERE clause, attempt
  ** to change it into a join.  */
  if( pParse->bHasExists && OptimizationEnabled(db,SQLITE_ExistsToJoin) ){
    existsToJoin(pParse, p, p->pWhere);
    pTabList = p->pSrc;
  }

  /* Do the WHERE-clause constant propagation optimization if this is
  ** a join.  No need to speed time on this operation for non-join queries
  ** as the equivalent optimization will be handled by query planner in
  ** sqlite3WhereBegin().
  */
  if( p->pWhere!=0
   && p->pWhere->op==TK_AND







<
<
<
<
<
<
<







150412
150413
150414
150415
150416
150417
150418







150419
150420
150421
150422
150423
150424
150425
    }
#endif
    if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
    return rc;
  }
#endif








  /* Do the WHERE-clause constant propagation optimization if this is
  ** a join.  No need to speed time on this operation for non-join queries
  ** as the equivalent optimization will be handled by query planner in
  ** sqlite3WhereBegin().
  */
  if( p->pWhere!=0
   && p->pWhere->op==TK_AND
150959
150960
150961
150962
150963
150964
150965
150966
150967
150968
150969
150970
150971
150972
150973
150974
150975
150976
150977
150978
150979
150980
150981
150982
150983
150984
  ** The second form is preferred as a single index (or temp-table) may be
  ** used for both the ORDER BY and DISTINCT processing. As originally
  ** written the query must use a temp-table for at least one of the ORDER
  ** BY and DISTINCT, and an index or separate temp-table for the other.
  */
  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
   && OptimizationEnabled(db, SQLITE_GroupByOrder)
#ifndef SQLITE_OMIT_WINDOWFUNC
   && p->pWin==0
#endif
  ){
    p->selFlags &= ~SF_Distinct;
    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
    if( pGroupBy ){
      for(i=0; i<pGroupBy->nExpr; i++){
        pGroupBy->a[i].u.x.iOrderByCol = i+1;
      }
    }
    p->selFlags |= SF_Aggregate;
    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
    ** original setting of the SF_Distinct flag, not the current setting */
    assert( sDistinct.isTnct );
    sDistinct.isTnct = 2;








<






<
<
<
<
<







150650
150651
150652
150653
150654
150655
150656

150657
150658
150659
150660
150661
150662





150663
150664
150665
150666
150667
150668
150669
  ** The second form is preferred as a single index (or temp-table) may be
  ** used for both the ORDER BY and DISTINCT processing. As originally
  ** written the query must use a temp-table for at least one of the ORDER
  ** BY and DISTINCT, and an index or separate temp-table for the other.
  */
  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0

#ifndef SQLITE_OMIT_WINDOWFUNC
   && p->pWin==0
#endif
  ){
    p->selFlags &= ~SF_Distinct;
    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);





    p->selFlags |= SF_Aggregate;
    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
    ** original setting of the SF_Distinct flag, not the current setting */
    assert( sDistinct.isTnct );
    sDistinct.isTnct = 2;

151433
151434
151435
151436
151437
151438
151439
151440
151441
151442
151443
151444
151445
151446
151447
151448
151449
151450
151451
151452
151453
151454
151455
151456
151457
151458
151459
151460
151461
151462
151463
151464
151465
151466
151467
151468
151469
151470

151471
151472
151473
151474
151475
151476
151477
151478
151479
151480
      */
      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
      if( groupBySort ){
        sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
                          sortOut, sortPTab);
      }
      for(j=0; j<pGroupBy->nExpr; j++){
        int iOrderByCol = pGroupBy->a[j].u.x.iOrderByCol;

        if( groupBySort ){
          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
        }else{
          pAggInfo->directMode = 1;
          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
        }

        if( iOrderByCol ){
          Expr *pX = p->pEList->a[iOrderByCol-1].pExpr;
          Expr *pBase = sqlite3ExprSkipCollateAndLikely(pX);
          if( ALWAYS(pBase!=0) && pBase->op!=TK_AGG_COLUMN ){
            sqlite3ExprToRegister(pX, iAMem+j);
          }
        }
      }
      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
      addr1 = sqlite3VdbeCurrentAddr(v);
      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);

      /* Generate code that runs whenever the GROUP BY changes.
      ** Changes in the GROUP BY are detected by the previous code
      ** block.  If there were no changes, this block is skipped.
      **
      ** This code copies current group by terms in b0,b1,b2,...
      ** over to a0,a1,a2.  It then calls the output subroutine
      ** and resets the aggregate accumulator registers in preparation
      ** for the next GROUP BY batch.
      */

      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
      VdbeComment((v, "output one row"));
      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
      VdbeComment((v, "check abort flag"));
      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
      VdbeComment((v, "reset accumulator"));

      /* Update the aggregate accumulators based on the content of
      ** the current row







<
<






<
<
<
<
<
<
<
<















>


<







151118
151119
151120
151121
151122
151123
151124


151125
151126
151127
151128
151129
151130








151131
151132
151133
151134
151135
151136
151137
151138
151139
151140
151141
151142
151143
151144
151145
151146
151147
151148

151149
151150
151151
151152
151153
151154
151155
      */
      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
      if( groupBySort ){
        sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
                          sortOut, sortPTab);
      }
      for(j=0; j<pGroupBy->nExpr; j++){


        if( groupBySort ){
          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
        }else{
          pAggInfo->directMode = 1;
          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
        }








      }
      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
      addr1 = sqlite3VdbeCurrentAddr(v);
      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);

      /* Generate code that runs whenever the GROUP BY changes.
      ** Changes in the GROUP BY are detected by the previous code
      ** block.  If there were no changes, this block is skipped.
      **
      ** This code copies current group by terms in b0,b1,b2,...
      ** over to a0,a1,a2.  It then calls the output subroutine
      ** and resets the aggregate accumulator registers in preparation
      ** for the next GROUP BY batch.
      */
      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
      VdbeComment((v, "output one row"));

      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
      VdbeComment((v, "check abort flag"));
      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
      VdbeComment((v, "reset accumulator"));

      /* Update the aggregate accumulators based on the content of
      ** the current row
152900
152901
152902
152903
152904
152905
152906
152907
152908
152909
152910
152911
152912
152913
152914
152915
152916
152917
152918
152919
152920
152921
152922
152923
152924
152925
152926
152927
152928
152929
152930
152931
152932
152933
152934
152935
152936
152937
152938
152939
152940
152941
152942
152943
152944
152945
152946
152947
152948
152949
152950
152951
152952
152953
152954
152955
152956
152957
152958
152959
152960
152961
152962
152963
152964
152965
152966
152967
152968
152969
152970
152971
152972
152973
152974
152975
152976
152977
152978
152979
        pItem->fg.eEName = pList->a[i].fg.eEName;
      }
    }
  }
  return pNew;
}

/* If the Expr node is a subquery or an EXISTS operator or an IN operator that
** uses a subquery, and if the subquery is SF_Correlated, then mark the
** expression as EP_VarSelect.
*/
static int sqlite3ReturningSubqueryVarSelect(Walker *NotUsed, Expr *pExpr){
  UNUSED_PARAMETER(NotUsed);
  if( ExprUseXSelect(pExpr)
   && (pExpr->x.pSelect->selFlags & SF_Correlated)!=0
  ){
    testcase( ExprHasProperty(pExpr, EP_VarSelect) );
    ExprSetProperty(pExpr, EP_VarSelect);
  }
  return WRC_Continue;
}


/*
** If the SELECT references the table pWalker->u.pTab, then do two things:
**
**    (1) Mark the SELECT as as SF_Correlated.
**    (2) Set pWalker->eCode to non-zero so that the caller will know
**        that (1) has happened.
*/
static int sqlite3ReturningSubqueryCorrelated(Walker *pWalker, Select *pSelect){
  int i;
  SrcList *pSrc;
  assert( pSelect!=0 );
  pSrc = pSelect->pSrc;
  assert( pSrc!=0 );
  for(i=0; i<pSrc->nSrc; i++){
    if( pSrc->a[i].pTab==pWalker->u.pTab ){
      testcase( pSelect->selFlags & SF_Correlated );
      pSelect->selFlags |= SF_Correlated;
      pWalker->eCode = 1;
      break;
    }
  }
  return WRC_Continue;
}

/*
** Scan the expression list that is the argument to RETURNING looking
** for subqueries that depend on the table which is being modified in the
** statement that is hosting the RETURNING clause (pTab).  Mark all such
** subqueries as SF_Correlated.  If the subqueries are part of an
** expression, mark the expression as EP_VarSelect.
**
** https://sqlite.org/forum/forumpost/2c83569ce8945d39
*/
static void sqlite3ProcessReturningSubqueries(
  ExprList *pEList,
  Table *pTab
){
  Walker w;
  memset(&w, 0, sizeof(w));
  w.xExprCallback = sqlite3ExprWalkNoop;
  w.xSelectCallback = sqlite3ReturningSubqueryCorrelated;
  w.u.pTab = pTab;
  sqlite3WalkExprList(&w, pEList);
  if( w.eCode ){
    w.xExprCallback = sqlite3ReturningSubqueryVarSelect;
    w.xSelectCallback = sqlite3SelectWalkNoop;
    sqlite3WalkExprList(&w, pEList);
  }
}

/*
** Generate code for the RETURNING trigger.  Unlike other triggers
** that invoke a subprogram in the bytecode, the code for RETURNING
** is generated in-line.
*/
static void codeReturningTrigger(
  Parse *pParse,       /* Parse context */







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







152575
152576
152577
152578
152579
152580
152581


































































152582
152583
152584
152585
152586
152587
152588
        pItem->fg.eEName = pList->a[i].fg.eEName;
      }
    }
  }
  return pNew;
}



































































/*
** Generate code for the RETURNING trigger.  Unlike other triggers
** that invoke a subprogram in the bytecode, the code for RETURNING
** is generated in-line.
*/
static void codeReturningTrigger(
  Parse *pParse,       /* Parse context */
153002
153003
153004
153005
153006
153007
153008
153009
153010
153011
153012
153013
153014
153015
153016
  }
  memset(&sSelect, 0, sizeof(sSelect));
  memset(&sFrom, 0, sizeof(sFrom));
  sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
  sSelect.pSrc = &sFrom;
  sFrom.nSrc = 1;
  sFrom.a[0].pTab = pTab;
  sFrom.a[0].zName = pTab->zName; /* tag-20240424-1 */
  sFrom.a[0].iCursor = -1;
  sqlite3SelectPrep(pParse, &sSelect, 0);
  if( pParse->nErr==0 ){
    assert( db->mallocFailed==0 );
    sqlite3GenerateColumnNames(pParse, &sSelect);
  }
  sqlite3ExprListDelete(db, sSelect.pEList);







<







152611
152612
152613
152614
152615
152616
152617

152618
152619
152620
152621
152622
152623
152624
  }
  memset(&sSelect, 0, sizeof(sSelect));
  memset(&sFrom, 0, sizeof(sFrom));
  sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
  sSelect.pSrc = &sFrom;
  sFrom.nSrc = 1;
  sFrom.a[0].pTab = pTab;

  sFrom.a[0].iCursor = -1;
  sqlite3SelectPrep(pParse, &sSelect, 0);
  if( pParse->nErr==0 ){
    assert( db->mallocFailed==0 );
    sqlite3GenerateColumnNames(pParse, &sSelect);
  }
  sqlite3ExprListDelete(db, sSelect.pEList);
153029
153030
153031
153032
153033
153034
153035
153036
153037
153038
153039
153040
153041
153042
153043
    pParse->pTriggerTab = pTab;
    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK
     && ALWAYS(!db->mallocFailed)
    ){
      int i;
      int nCol = pNew->nExpr;
      int reg = pParse->nMem+1;
      sqlite3ProcessReturningSubqueries(pNew, pTab);
      pParse->nMem += nCol+2;
      pReturning->iRetReg = reg;
      for(i=0; i<nCol; i++){
        Expr *pCol = pNew->a[i].pExpr;
        assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
        sqlite3ExprCodeFactorable(pParse, pCol, reg+i);
        if( sqlite3ExprAffinity(pCol)==SQLITE_AFF_REAL ){







<







152637
152638
152639
152640
152641
152642
152643

152644
152645
152646
152647
152648
152649
152650
    pParse->pTriggerTab = pTab;
    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK
     && ALWAYS(!db->mallocFailed)
    ){
      int i;
      int nCol = pNew->nExpr;
      int reg = pParse->nMem+1;

      pParse->nMem += nCol+2;
      pReturning->iRetReg = reg;
      for(i=0; i<nCol; i++){
        Expr *pCol = pNew->a[i].pExpr;
        assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
        sqlite3ExprCodeFactorable(pParse, pCol, reg+i);
        if( sqlite3ExprAffinity(pCol)==SQLITE_AFF_REAL ){
156460
156461
156462
156463
156464
156465
156466
156467
156468
156469
156470
156471
156472
156473
156474
156475
156476
156477
  ** really are "CREATE" and "TABLE".  If this is not the case, then
  ** sqlite3_declare_vtab() is being misused.
  */
  z = (const unsigned char*)zCreateTable;
  for(i=0; aKeyword[i]; i++){
    int tokenType = 0;
    do{ z += sqlite3GetToken(z, &tokenType); }while( tokenType==TK_SPACE );
    if( tokenType!=aKeyword[i] ){
      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "syntax error");
      return SQLITE_ERROR;
    }
  }

  sqlite3_mutex_enter(db->mutex);
  pCtx = db->pVtabCtx;
  if( !pCtx || pCtx->bDeclared ){
    sqlite3Error(db, SQLITE_MISUSE_BKPT);
    sqlite3_mutex_leave(db->mutex);







|
<
<
<







156067
156068
156069
156070
156071
156072
156073
156074



156075
156076
156077
156078
156079
156080
156081
  ** really are "CREATE" and "TABLE".  If this is not the case, then
  ** sqlite3_declare_vtab() is being misused.
  */
  z = (const unsigned char*)zCreateTable;
  for(i=0; aKeyword[i]; i++){
    int tokenType = 0;
    do{ z += sqlite3GetToken(z, &tokenType); }while( tokenType==TK_SPACE );
    if( tokenType!=aKeyword[i] ) return SQLITE_MISUSE_BKPT;



  }

  sqlite3_mutex_enter(db->mutex);
  pCtx = db->pVtabCtx;
  if( !pCtx || pCtx->bDeclared ){
    sqlite3Error(db, SQLITE_MISUSE_BKPT);
    sqlite3_mutex_leave(db->mutex);
157187
157188
157189
157190
157191
157192
157193
157194
157195
157196
157197
157198
157199
157200
157201
157202
  } u;
  u32 wsFlags;          /* WHERE_* flags describing the plan */
  u16 nLTerm;           /* Number of entries in aLTerm[] */
  u16 nSkip;            /* Number of NULL aLTerm[] entries */
  /**** whereLoopXfer() copies fields above ***********************/
# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
  LogEst rStarDelta;    /* Cost delta due to star-schema heuristic.  Not
                        ** initialized unless pWInfo->nOutStarDelta>0 */
  WhereTerm **aLTerm;   /* WhereTerms used */
  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
};

/* This object holds the prerequisites and the cost of running a
** subquery on one operand of an OR operator in the WHERE clause.







<
<







156791
156792
156793
156794
156795
156796
156797


156798
156799
156800
156801
156802
156803
156804
  } u;
  u32 wsFlags;          /* WHERE_* flags describing the plan */
  u16 nLTerm;           /* Number of entries in aLTerm[] */
  u16 nSkip;            /* Number of NULL aLTerm[] entries */
  /**** whereLoopXfer() copies fields above ***********************/
# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */


  WhereTerm **aLTerm;   /* WhereTerms used */
  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
};

/* This object holds the prerequisites and the cost of running a
** subquery on one operand of an OR operator in the WHERE clause.
157511
157512
157513
157514
157515
157516
157517
157518
157519
157520
157521
157522
157523
157524
157525
  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
  unsigned bDeferredSeek :1;   /* Uses OP_DeferredSeek */
  unsigned untestedTerms :1;   /* Not all WHERE terms resolved by outer loop */
  unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
  unsigned sorted :1;          /* True if really sorted (not just grouped) */
  LogEst nOutStarDelta;     /* Artifical nOut reduction for star-query */
  LogEst nRowOut;           /* Estimated number of output rows */
  int iTop;                 /* The very beginning of the WHERE loop */
  int iEndWhere;            /* End of the WHERE clause itself */
  WhereLoop *pLoops;        /* List of all WhereLoop objects */
  WhereMemBlock *pMemToFree;/* Memory to free when this object destroyed */
  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
  WhereClause sWC;          /* Decomposition of the WHERE clause */







<







157113
157114
157115
157116
157117
157118
157119

157120
157121
157122
157123
157124
157125
157126
  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
  unsigned bDeferredSeek :1;   /* Uses OP_DeferredSeek */
  unsigned untestedTerms :1;   /* Not all WHERE terms resolved by outer loop */
  unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
  unsigned sorted :1;          /* True if really sorted (not just grouped) */

  LogEst nRowOut;           /* Estimated number of output rows */
  int iTop;                 /* The very beginning of the WHERE loop */
  int iEndWhere;            /* End of the WHERE clause itself */
  WhereLoop *pLoops;        /* List of all WhereLoop objects */
  WhereMemBlock *pMemToFree;/* Memory to free when this object destroyed */
  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
  WhereClause sWC;          /* Decomposition of the WHERE clause */
157869
157870
157871
157872
157873
157874
157875
157876
157877
157878
157879
157880
157881
157882
157883
157884
    }else{
      sqlite3_str_append(&str, " (~1 row)", 9);
    }
#endif
    zMsg = sqlite3StrAccumFinish(&str);
    sqlite3ExplainBreakpoint("",zMsg);
    ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
                            pParse->addrExplain, pLoop->rRun,
                            zMsg, P4_DYNAMIC);
  }
  return ret;
}

/*
** Add a single OP_Explain opcode that describes a Bloom filter.
**







|
<







157470
157471
157472
157473
157474
157475
157476
157477

157478
157479
157480
157481
157482
157483
157484
    }else{
      sqlite3_str_append(&str, " (~1 row)", 9);
    }
#endif
    zMsg = sqlite3StrAccumFinish(&str);
    sqlite3ExplainBreakpoint("",zMsg);
    ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
                            pParse->addrExplain, 0, zMsg,P4_DYNAMIC);

  }
  return ret;
}

/*
** Add a single OP_Explain opcode that describes a Bloom filter.
**
158112
158113
158114
158115
158116
158117
158118
158119
158120
158121
158122
158123
158124
158125
158126
158127
158128
158129
158130
158131
158132
158133
158134
158135
158136
158137
158138
158139
158140
158141
158142
158143
158144
158145
158146
158147
158148
158149
158150
158151
158152
158153
158154
158155
158156
158157
158158
     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
    ){
      zAff[i] = SQLITE_AFF_BLOB;
    }
  }
}

/*
** The pOrderBy->a[].u.x.iOrderByCol values might be incorrect because
** columns might have been rearranged in the result set.  This routine
** fixes them up.
**
** pEList is the new result set.  The pEList->a[].u.x.iOrderByCol values
** contain the *old* locations of each expression.  This is a temporary
** use of u.x.iOrderByCol, not its intended use.  The caller must reset
** u.x.iOrderByCol back to zero for all entries in pEList before the
** caller returns.
**
** This routine changes pOrderBy->a[].u.x.iOrderByCol values from
** pEList->a[N].u.x.iOrderByCol into N+1.  (The "+1" is because of the 1-based
** indexing used by iOrderByCol.)  Or if no match, iOrderByCol is set to zero.
*/
static void adjustOrderByCol(ExprList *pOrderBy, ExprList *pEList){
  int i, j;
  if( pOrderBy==0 ) return;
  for(i=0; i<pOrderBy->nExpr; i++){
    int t = pOrderBy->a[i].u.x.iOrderByCol;
    if( t==0 ) continue;
    for(j=0; j<pEList->nExpr; j++){
      if( pEList->a[j].u.x.iOrderByCol==t ){
        pOrderBy->a[i].u.x.iOrderByCol = j+1;
        break;
      }
    }
    if( j>=pEList->nExpr ){
      pOrderBy->a[i].u.x.iOrderByCol = 0;
    }
  }
}


/*
** pX is an expression of the form:  (vector) IN (SELECT ...)
** In other words, it is a vector IN operator with a SELECT clause on the
** LHS.  But not all terms in the vector are indexable and the terms might
** not be in the correct order for indexing.
**







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







157712
157713
157714
157715
157716
157717
157718

































157719
157720
157721
157722
157723
157724
157725
     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
    ){
      zAff[i] = SQLITE_AFF_BLOB;
    }
  }
}



































/*
** pX is an expression of the form:  (vector) IN (SELECT ...)
** In other words, it is a vector IN operator with a SELECT clause on the
** LHS.  But not all terms in the vector are indexable and the terms might
** not be in the correct order for indexing.
**
158208
158209
158210
158211
158212
158213
158214
158215
158216
158217
158218
158219
158220
158221
158222
        if( pLoop->aLTerm[i]->pExpr==pX ){
          int iField;
          assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
          iField = pLoop->aLTerm[i]->u.x.iField - 1;
          if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
          pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
          pOrigRhs->a[iField].pExpr = 0;
          if( pRhs ) pRhs->a[pRhs->nExpr-1].u.x.iOrderByCol = iField+1;
          if( pOrigLhs ){
            assert( pOrigLhs->a[iField].pExpr!=0 );
            pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr);
            pOrigLhs->a[iField].pExpr = 0;
          }
        }
      }







<







157775
157776
157777
157778
157779
157780
157781

157782
157783
157784
157785
157786
157787
157788
        if( pLoop->aLTerm[i]->pExpr==pX ){
          int iField;
          assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
          iField = pLoop->aLTerm[i]->u.x.iField - 1;
          if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
          pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
          pOrigRhs->a[iField].pExpr = 0;

          if( pOrigLhs ){
            assert( pOrigLhs->a[iField].pExpr!=0 );
            pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr);
            pOrigLhs->a[iField].pExpr = 0;
          }
        }
      }
158231
158232
158233
158234
158235
158236
158237
158238
158239


158240


158241
158242
158243
158244
158245
158246
158247

158248
158249
158250
158251
158252
158253
158254
158255
158256
158257
158258
158259
158260
158261
158262
158263
158264
158265
158266
158267
158268
158269
158270
158271
158272
158273
158274
158275
158276
158277
158278
158279
158280
158281
158282
158283
158284
158285
158286
158287
158288
158289
158290
158291
158292
158293
158294
158295
158296
158297
158298
158299
158300
158301
158302
158303
158304
158305
158306
158307
158308
158309
158310
158311
158312
158313
158314
158315
158316
158317
158318
158319
158320
158321
158322
158323
158324
158325
158326
158327
158328
158329
158330
158331
158332
158333
158334
158335
158336
158337
158338
158339
158340
158341
158342
158343
158344
158345
158346
158347
158348
158349
158350
158351
158352
158353
158354
158355
158356
158357
158358
158359
158360
158361
158362
158363
158364
158365
158366
158367
158368
158369
158370
158371
158372
158373
158374
158375
158376
158377
158378
158379
158380
158381
158382
158383
158384
158385
158386
158387
158388
158389
158390
158391
158392
158393
158394
158395
158396
158397
158398
158399
158400
158401
158402
158403
158404
158405
158406
158407
158408
        ** single value. Since the parser never creates such a vector, some
        ** of the subroutines do not handle this case.  */
        Expr *p = pLhs->a[0].pExpr;
        pLhs->a[0].pExpr = 0;
        sqlite3ExprDelete(db, pNew->pLeft);
        pNew->pLeft = p;
      }

      /* If either the ORDER BY clause or the GROUP BY clause contains


      ** references to result-set columns, those references might now be


      ** obsolete.  So fix them up.
      */
      assert( pRhs!=0 || db->mallocFailed );
      if( pRhs ){
        adjustOrderByCol(pSelect->pOrderBy, pRhs);
        adjustOrderByCol(pSelect->pGroupBy, pRhs);
        for(i=0; i<pRhs->nExpr; i++) pRhs->a[i].u.x.iOrderByCol = 0;

      }

#if 0
      printf("For indexing, change the IN expr:\n");
      sqlite3TreeViewExpr(0, pX, 0);
      printf("Into:\n");
      sqlite3TreeViewExpr(0, pNew, 0);
#endif
    }
  }
  return pNew;
}


#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code for a single X IN (....) term of the WHERE clause.
**
** This is a special-case of codeEqualityTerm() that works for IN operators
** only.  It is broken out into a subroutine because this case is
** uncommon and by splitting it off into a subroutine, the common case
** runs faster.
**
** The current value for the constraint is left in  register iTarget.
** This routine sets up a loop that will iterate over all values of X.
*/
static SQLITE_NOINLINE void codeINTerm(
  Parse *pParse,      /* The parsing context */
  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  int iEq,            /* Index of the equality term within this level */
  int bRev,           /* True for reverse-order IN operations */
  int iTarget         /* Attempt to leave results in this register */
){
  Expr *pX = pTerm->pExpr;
  int eType = IN_INDEX_NOOP;
  int iTab;
  struct InLoop *pIn;
  WhereLoop *pLoop = pLevel->pWLoop;
  Vdbe *v = pParse->pVdbe;
  int i;
  int nEq = 0;
  int *aiMap = 0;

  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
    && pLoop->u.btree.pIndex!=0
    && pLoop->u.btree.pIndex->aSortOrder[iEq]
  ){
    testcase( iEq==0 );
    testcase( bRev );
    bRev = !bRev;
  }
  assert( pX->op==TK_IN );

  for(i=0; i<iEq; i++){
    if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
      disableTerm(pLevel, pTerm);
      return;
    }
  }
  for(i=iEq;i<pLoop->nLTerm; i++){
    assert( pLoop->aLTerm[i]!=0 );
    if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  }

  iTab = 0;
  if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
    eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
  }else{
    Expr *pExpr = pTerm->pExpr;
    if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){
      sqlite3 *db = pParse->db;
      pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
      if( !db->mallocFailed ){
        aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab);
        pExpr->iTable = iTab;
      }
      sqlite3ExprDelete(db, pX);
    }else{
      int n = sqlite3ExprVectorSize(pX->pLeft);
      aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));
      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
    }
    pX = pExpr;
  }

  if( eType==IN_INDEX_INDEX_DESC ){
    testcase( bRev );
    bRev = !bRev;
  }
  sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  VdbeCoverageIf(v, bRev);
  VdbeCoverageIf(v, !bRev);

  assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  pLoop->wsFlags |= WHERE_IN_ABLE;
  if( pLevel->u.in.nIn==0 ){
    pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  }
  if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
    pLoop->wsFlags |= WHERE_IN_EARLYOUT;
  }

  i = pLevel->u.in.nIn;
  pLevel->u.in.nIn += nEq;
  pLevel->u.in.aInLoop =
     sqlite3WhereRealloc(pTerm->pWC->pWInfo,
                         pLevel->u.in.aInLoop,
                         sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  pIn = pLevel->u.in.aInLoop;
  if( pIn ){
    int iMap = 0;               /* Index in aiMap[] */
    pIn += i;
    for(i=iEq;i<pLoop->nLTerm; i++){
      if( pLoop->aLTerm[i]->pExpr==pX ){
        int iOut = iTarget + i - iEq;
        if( eType==IN_INDEX_ROWID ){
          pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
        }else{
          int iCol = aiMap ? aiMap[iMap++] : 0;
          pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
        }
        sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
        if( i==iEq ){
          pIn->iCur = iTab;
          pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
          if( iEq>0 ){
            pIn->iBase = iTarget - i;
            pIn->nPrefix = i;
          }else{
            pIn->nPrefix = 0;
          }
        }else{
          pIn->eEndLoopOp = OP_Noop;
        }
        pIn++;
      }
    }
    testcase( iEq>0
              && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
              && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
    if( iEq>0
     && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
    ){
      sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
    }
  }else{
    pLevel->u.in.nIn = 0;
  }
  sqlite3DbFree(pParse->db, aiMap);
}
#endif


/*
** Generate code for a single equality term of the WHERE clause.  An equality
** term can be either X=expr or X IN (...).   pTerm is the term to be
** coded.
**
** The current value for the constraint is left in a register, the index







|
|
>
>
|
>
>
|
<
<
<
|
|
|
>













<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







157797
157798
157799
157800
157801
157802
157803
157804
157805
157806
157807
157808
157809
157810
157811



157812
157813
157814
157815
157816
157817
157818
157819
157820
157821
157822
157823
157824
157825
157826
157827
157828













































































































































157829
157830
157831
157832
157833
157834
157835
        ** single value. Since the parser never creates such a vector, some
        ** of the subroutines do not handle this case.  */
        Expr *p = pLhs->a[0].pExpr;
        pLhs->a[0].pExpr = 0;
        sqlite3ExprDelete(db, pNew->pLeft);
        pNew->pLeft = p;
      }
      if( pSelect->pOrderBy ){
        /* If the SELECT statement has an ORDER BY clause, zero the
        ** iOrderByCol variables. These are set to non-zero when an
        ** ORDER BY term exactly matches one of the terms of the
        ** result-set. Since the result-set of the SELECT statement may
        ** have been modified or reordered, these variables are no longer
        ** set correctly.  Since setting them is just an optimization,
        ** it's easiest just to zero them here.  */



        ExprList *pOrderBy = pSelect->pOrderBy;
        for(i=0; i<pOrderBy->nExpr; i++){
          pOrderBy->a[i].u.x.iOrderByCol = 0;
        }
      }

#if 0
      printf("For indexing, change the IN expr:\n");
      sqlite3TreeViewExpr(0, pX, 0);
      printf("Into:\n");
      sqlite3TreeViewExpr(0, pNew, 0);
#endif
    }
  }
  return pNew;
}















































































































































/*
** Generate code for a single equality term of the WHERE clause.  An equality
** term can be either X=expr or X IN (...).   pTerm is the term to be
** coded.
**
** The current value for the constraint is left in a register, the index
158420
158421
158422
158423
158424
158425
158426

158427
158428
158429
158430
158431
158432
158433
158434
158435
158436
158437
















158438
158439
158440

































































































158441
158442
158443
158444
158445
158446
158447
  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  int iEq,            /* Index of the equality term within this level */
  int bRev,           /* True for reverse-order IN operations */
  int iTarget         /* Attempt to leave results in this register */
){
  Expr *pX = pTerm->pExpr;

  int iReg;                  /* Register holding results */

  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  assert( iTarget>0 );
  if( pX->op==TK_EQ || pX->op==TK_IS ){
    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  }else if( pX->op==TK_ISNULL ){
    iReg = iTarget;
    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Null, 0, iReg);
#ifndef SQLITE_OMIT_SUBQUERY
  }else{
















    assert( pX->op==TK_IN );
    iReg = iTarget;
    codeINTerm(pParse, pTerm, pLevel, iEq, bRev, iTarget);

































































































#endif
  }

  /* As an optimization, try to disable the WHERE clause term that is
  ** driving the index as it will always be true.  The correct answer is
  ** obtained regardless, but we might get the answer with fewer CPU cycles
  ** by omitting the term.







>








|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







157847
157848
157849
157850
157851
157852
157853
157854
157855
157856
157857
157858
157859
157860
157861
157862
157863
157864
157865
157866
157867
157868
157869
157870
157871
157872
157873
157874
157875
157876
157877
157878
157879
157880
157881
157882
157883
157884
157885
157886
157887
157888
157889
157890
157891
157892
157893
157894
157895
157896
157897
157898
157899
157900
157901
157902
157903
157904
157905
157906
157907
157908
157909
157910
157911
157912
157913
157914
157915
157916
157917
157918
157919
157920
157921
157922
157923
157924
157925
157926
157927
157928
157929
157930
157931
157932
157933
157934
157935
157936
157937
157938
157939
157940
157941
157942
157943
157944
157945
157946
157947
157948
157949
157950
157951
157952
157953
157954
157955
157956
157957
157958
157959
157960
157961
157962
157963
157964
157965
157966
157967
157968
157969
157970
157971
157972
157973
157974
157975
157976
157977
157978
157979
157980
157981
157982
157983
157984
157985
157986
157987
157988
  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  int iEq,            /* Index of the equality term within this level */
  int bRev,           /* True for reverse-order IN operations */
  int iTarget         /* Attempt to leave results in this register */
){
  Expr *pX = pTerm->pExpr;
  Vdbe *v = pParse->pVdbe;
  int iReg;                  /* Register holding results */

  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  assert( iTarget>0 );
  if( pX->op==TK_EQ || pX->op==TK_IS ){
    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  }else if( pX->op==TK_ISNULL ){
    iReg = iTarget;
    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
#ifndef SQLITE_OMIT_SUBQUERY
  }else{
    int eType = IN_INDEX_NOOP;
    int iTab;
    struct InLoop *pIn;
    WhereLoop *pLoop = pLevel->pWLoop;
    int i;
    int nEq = 0;
    int *aiMap = 0;

    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
      && pLoop->u.btree.pIndex!=0
      && pLoop->u.btree.pIndex->aSortOrder[iEq]
    ){
      testcase( iEq==0 );
      testcase( bRev );
      bRev = !bRev;
    }
    assert( pX->op==TK_IN );
    iReg = iTarget;

    for(i=0; i<iEq; i++){
      if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
        disableTerm(pLevel, pTerm);
        return iTarget;
      }
    }
    for(i=iEq;i<pLoop->nLTerm; i++){
      assert( pLoop->aLTerm[i]!=0 );
      if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
    }

    iTab = 0;
    if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
    }else{
      Expr *pExpr = pTerm->pExpr;
      if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){
        sqlite3 *db = pParse->db;
        pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
        if( !db->mallocFailed ){
          aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
          eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab);
          pExpr->iTable = iTab;
        }
        sqlite3ExprDelete(db, pX);
      }else{
        int n = sqlite3ExprVectorSize(pX->pLeft);
        aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));
        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
      }
      pX = pExpr;
    }

    if( eType==IN_INDEX_INDEX_DESC ){
      testcase( bRev );
      bRev = !bRev;
    }
    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
    VdbeCoverageIf(v, bRev);
    VdbeCoverageIf(v, !bRev);

    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
    pLoop->wsFlags |= WHERE_IN_ABLE;
    if( pLevel->u.in.nIn==0 ){
      pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
    }
    if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
      pLoop->wsFlags |= WHERE_IN_EARLYOUT;
    }

    i = pLevel->u.in.nIn;
    pLevel->u.in.nIn += nEq;
    pLevel->u.in.aInLoop =
       sqlite3WhereRealloc(pTerm->pWC->pWInfo,
                           pLevel->u.in.aInLoop,
                           sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
    pIn = pLevel->u.in.aInLoop;
    if( pIn ){
      int iMap = 0;               /* Index in aiMap[] */
      pIn += i;
      for(i=iEq;i<pLoop->nLTerm; i++){
        if( pLoop->aLTerm[i]->pExpr==pX ){
          int iOut = iReg + i - iEq;
          if( eType==IN_INDEX_ROWID ){
            pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
          }else{
            int iCol = aiMap ? aiMap[iMap++] : 0;
            pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
          }
          sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
          if( i==iEq ){
            pIn->iCur = iTab;
            pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
            if( iEq>0 ){
              pIn->iBase = iReg - i;
              pIn->nPrefix = i;
            }else{
              pIn->nPrefix = 0;
            }
          }else{
            pIn->eEndLoopOp = OP_Noop;
          }
          pIn++;
        }
      }
      testcase( iEq>0
                && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
                && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
      if( iEq>0
       && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
      ){
        sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
      }
    }else{
      pLevel->u.in.nIn = 0;
    }
    sqlite3DbFree(pParse->db, aiMap);
#endif
  }

  /* As an optimization, try to disable the WHERE clause term that is
  ** driving the index as it will always be true.  The correct answer is
  ** obtained regardless, but we might get the answer with fewer CPU cycles
  ** by omitting the term.
159048
159049
159050
159051
159052
159053
159054
159055
159056
159057
159058
159059
159060
159061
159062
159063
159064
159065
159066
159067
159068
159069
159070
159071
159072
159073
159074
159075
159076
159077
159078
159079
159080
159081
159082
      VdbeCoverage(pParse->pVdbe);
    }
    pLevel->regFilter = 0;
    pLevel->addrBrk = 0;
  }
}

/*
** Loop pLoop is a WHERE_INDEXED level that uses at least one IN(...)
** operator. Return true if level pLoop is guaranteed to visit only one
** row for each key generated for the index.
*/
static int whereLoopIsOneRow(WhereLoop *pLoop){
  if( pLoop->u.btree.pIndex->onError
   && pLoop->nSkip==0
   && pLoop->u.btree.nEq==pLoop->u.btree.pIndex->nKeyCol
  ){
    int ii;
    for(ii=0; ii<pLoop->u.btree.nEq; ii++){
      if( pLoop->aLTerm[ii]->eOperator & (WO_IS|WO_ISNULL) ){
        return 0;
      }
    }
    return 1;
  }
  return 0;
}

/*
** Generate code for the start of the iLevel-th loop in the WHERE clause
** implementation described by pWInfo.
*/
SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  Parse *pParse,       /* Parsing context */
  Vdbe *v,             /* Prepared statement under construction */







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







158589
158590
158591
158592
158593
158594
158595





















158596
158597
158598
158599
158600
158601
158602
      VdbeCoverage(pParse->pVdbe);
    }
    pLevel->regFilter = 0;
    pLevel->addrBrk = 0;
  }
}






















/*
** Generate code for the start of the iLevel-th loop in the WHERE clause
** implementation described by pWInfo.
*/
SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  Parse *pParse,       /* Parsing context */
  Vdbe *v,             /* Prepared statement under construction */
159147
159148
159149
159150
159151
159152
159153
159154
159155
159156
159157
159158
159159
159160
159161
  */
  assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
       || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  );
  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
    pLevel->iLeftJoin = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
    VdbeComment((v, "init LEFT JOIN match flag"));
  }

  /* Compute a safe address to jump to if we discover that the table for
  ** this loop is empty and can never contribute content. */
  for(j=iLevel; j>0; j--){
    if( pWInfo->a[j].iLeftJoin ) break;
    if( pWInfo->a[j].pRJ ) break;







|







158667
158668
158669
158670
158671
158672
158673
158674
158675
158676
158677
158678
158679
158680
158681
  */
  assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
       || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  );
  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
    pLevel->iLeftJoin = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
    VdbeComment((v, "init LEFT JOIN no-match flag"));
  }

  /* Compute a safe address to jump to if we discover that the table for
  ** this loop is empty and can never contribute content. */
  for(j=iLevel; j>0; j--){
    if( pWInfo->a[j].iLeftJoin ) break;
    if( pWInfo->a[j].pRJ ) break;
159816
159817
159818
159819
159820
159821
159822
159823
159824
159825
159826
159827
159828
159829
159830
159831
159832
      /* The following assert() is not a requirement, merely an observation:
      ** The OR-optimization doesn't work for the right hand table of
      ** a LEFT JOIN: */
      assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
    }

    /* Record the instruction used to terminate the loop. */
    if( (pLoop->wsFlags & WHERE_ONEROW)
     || (pLevel->u.in.nIn && regBignull==0 && whereLoopIsOneRow(pLoop))
    ){
      pLevel->op = OP_Noop;
    }else if( bRev ){
      pLevel->op = OP_Prev;
    }else{
      pLevel->op = OP_Next;
    }
    pLevel->p1 = iIdxCur;







|
<
<







159336
159337
159338
159339
159340
159341
159342
159343


159344
159345
159346
159347
159348
159349
159350
      /* The following assert() is not a requirement, merely an observation:
      ** The OR-optimization doesn't work for the right hand table of
      ** a LEFT JOIN: */
      assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
    }

    /* Record the instruction used to terminate the loop. */
    if( pLoop->wsFlags & WHERE_ONEROW ){


      pLevel->op = OP_Noop;
    }else if( bRev ){
      pLevel->op = OP_Prev;
    }else{
      pLevel->op = OP_Next;
    }
    pLevel->p1 = iIdxCur;
160473
160474
160475
160476
160477
160478
160479
160480
160481
160482
160483
160484

160485
160486
160487
160488
160489
160490
160491
    pRight = &pWInfo->pTabList->a[pWInfo->a[k].iFrom];
    mAll |= pWInfo->a[k].pWLoop->maskSelf;
    if( pRight->fg.viaCoroutine ){
      sqlite3VdbeAddOp3(
          v, OP_Null, 0, pRight->regResult,
          pRight->regResult + pRight->pSelect->pEList->nExpr-1
      );
    }
    sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
    iIdxCur = pWInfo->a[k].iIdxCur;
    if( iIdxCur ){
      sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);

    }
  }
  if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
    mAll |= pLoop->maskSelf;
    for(k=0; k<pWC->nTerm; k++){
      WhereTerm *pTerm = &pWC->a[k];
      if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0







|
|
|
|
|
>







159991
159992
159993
159994
159995
159996
159997
159998
159999
160000
160001
160002
160003
160004
160005
160006
160007
160008
160009
160010
    pRight = &pWInfo->pTabList->a[pWInfo->a[k].iFrom];
    mAll |= pWInfo->a[k].pWLoop->maskSelf;
    if( pRight->fg.viaCoroutine ){
      sqlite3VdbeAddOp3(
          v, OP_Null, 0, pRight->regResult,
          pRight->regResult + pRight->pSelect->pEList->nExpr-1
      );
    }else{
      sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
      iIdxCur = pWInfo->a[k].iIdxCur;
      if( iIdxCur ){
        sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
      }
    }
  }
  if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
    mAll |= pLoop->maskSelf;
    for(k=0; k<pWC->nTerm; k++){
      WhereTerm *pTerm = &pWC->a[k];
      if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0
160642
160643
160644
160645
160646
160647
160648
160649
160650
160651
160652
160653
160654
160655
160656
160657
160658
160659
160660
160661
** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
*/
static int allowedOp(int op){
  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  assert( TK_GE==TK_EQ+4 );
  assert( TK_IN<TK_EQ );
  assert( TK_IS<TK_EQ );
  assert( TK_ISNULL<TK_EQ );
  if( op>TK_GE ) return 0;
  if( op>=TK_EQ ) return 1;
  return op==TK_IN || op==TK_ISNULL || op==TK_IS;
}

/*
** Commute a comparison operator.  Expressions of the form "X op Y"
** are converted into "Y op X".
*/
static u16 exprCommute(Parse *pParse, Expr *pExpr){







<
<
<
<
<
|







160161
160162
160163
160164
160165
160166
160167





160168
160169
160170
160171
160172
160173
160174
160175
** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
*/
static int allowedOp(int op){
  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  assert( TK_GE==TK_EQ+4 );





  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
}

/*
** Commute a comparison operator.  Expressions of the form "X op Y"
** are converted into "Y op X".
*/
static u16 exprCommute(Parse *pParse, Expr *pExpr){
160680
160681
160682
160683
160684
160685
160686
160687
160688
160689
160690
160691
160692
160693
160694
160695
160696



160697
160698
160699
160700
160701
160702
160703

/*
** Translate from TK_xx operator to WO_xx bitmask.
*/
static u16 operatorMask(int op){
  u16 c;
  assert( allowedOp(op) );
  if( op>=TK_EQ ){
    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
    c = (u16)(WO_EQ<<(op-TK_EQ));
  }else if( op==TK_IN ){
    c = WO_IN;
  }else if( op==TK_ISNULL ){
    c = WO_ISNULL;
  }else{
    assert( op==TK_IS );
    c = WO_IS;



  }
  assert( op!=TK_ISNULL || c==WO_ISNULL );
  assert( op!=TK_IN || c==WO_IN );
  assert( op!=TK_EQ || c==WO_EQ );
  assert( op!=TK_LT || c==WO_LT );
  assert( op!=TK_LE || c==WO_LE );
  assert( op!=TK_GT || c==WO_GT );







<
<
<
|



<
|

>
>
>







160194
160195
160196
160197
160198
160199
160200



160201
160202
160203
160204

160205
160206
160207
160208
160209
160210
160211
160212
160213
160214
160215
160216

/*
** Translate from TK_xx operator to WO_xx bitmask.
*/
static u16 operatorMask(int op){
  u16 c;
  assert( allowedOp(op) );



  if( op==TK_IN ){
    c = WO_IN;
  }else if( op==TK_ISNULL ){
    c = WO_ISNULL;

  }else if( op==TK_IS ){
    c = WO_IS;
  }else{
    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
    c = (u16)(WO_EQ<<(op-TK_EQ));
  }
  assert( op!=TK_ISNULL || c==WO_ISNULL );
  assert( op!=TK_IN || c==WO_IN );
  assert( op!=TK_EQ || c==WO_EQ );
  assert( op!=TK_LT || c==WO_LT );
  assert( op!=TK_LE || c==WO_LE );
  assert( op!=TK_GT || c==WO_GT );
160976
160977
160978
160979
160980
160981
160982
160983
160984
160985
160986
160987
160988
160989
160990
160991
160992
160993
160994
160995
160996
          *peOp2 = i;
          *ppRight = pList->a[1].pExpr;
          *ppLeft = pCol;
          return 1;
        }
      }
    }
  }else if( pExpr->op>=TK_EQ ){
    /* Comparison operators are a common case.  Save a few comparisons for
    ** that common case by terminating early. */
    assert( TK_NE < TK_EQ );
    assert( TK_ISNOT < TK_EQ );
    assert( TK_NOTNULL < TK_EQ );
    return 0;
  }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
    int res = 0;
    Expr *pLeft = pExpr->pLeft;
    Expr *pRight = pExpr->pRight;
    assert( pLeft->op!=TK_COLUMN || (ExprUseYTab(pLeft) && pLeft->y.pTab!=0) );
    if( ExprIsVtab(pLeft) ){
      res++;







<
<
<
<
<
<
<







160489
160490
160491
160492
160493
160494
160495







160496
160497
160498
160499
160500
160501
160502
          *peOp2 = i;
          *ppRight = pList->a[1].pExpr;
          *ppLeft = pCol;
          return 1;
        }
      }
    }







  }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
    int res = 0;
    Expr *pLeft = pExpr->pLeft;
    Expr *pRight = pExpr->pRight;
    assert( pLeft->op!=TK_COLUMN || (ExprUseYTab(pLeft) && pLeft->y.pTab!=0) );
    if( ExprIsVtab(pLeft) ){
      res++;
162124
162125
162126
162127
162128
162129
162130
162131
162132
162133
162134
162135
162136
162137
162138
  int eMatchOp        /* SQLITE_INDEX_CONSTRAINT_LIMIT or _OFFSET */
){
  Parse *pParse = pWC->pWInfo->pParse;
  sqlite3 *db = pParse->db;
  Expr *pNew;
  int iVal = 0;

  if( sqlite3ExprIsInteger(pExpr, &iVal, pParse) && iVal>=0 ){
    Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0);
    if( pVal==0 ) return;
    ExprSetProperty(pVal, EP_IntValue);
    pVal->u.iValue = iVal;
    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
  }else{
    Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0);







|







161630
161631
161632
161633
161634
161635
161636
161637
161638
161639
161640
161641
161642
161643
161644
  int eMatchOp        /* SQLITE_INDEX_CONSTRAINT_LIMIT or _OFFSET */
){
  Parse *pParse = pWC->pWInfo->pParse;
  sqlite3 *db = pParse->db;
  Expr *pNew;
  int iVal = 0;

  if( sqlite3ExprIsInteger(pExpr, &iVal) && iVal>=0 ){
    Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0);
    if( pVal==0 ) return;
    ExprSetProperty(pVal, EP_IntValue);
    pVal->u.iValue = iVal;
    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
  }else{
    Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0);
162192
162193
162194
162195
162196
162197
162198
162199
162200
162201
162202
162203
162204
162205
162206
162207
162208
162209
162210
162211
162212
162213


162214
162215
162216
162217
162218
162219
162220
162221
162222
162223
162224
162225
162226
162227
162228
        /* If this term has child terms, then they are also part of the
        ** pWC->a[] array. So this term can be ignored, as a LIMIT clause
        ** will only be added if each of the child terms passes the
        ** (leftCursor==iCsr) test below.  */
        continue;
      }
      if( pWC->a[ii].leftCursor!=iCsr ) return;
      if( pWC->a[ii].prereqRight!=0 ) return;
    }

    /* Check condition (5). Return early if it is not met. */
    if( pOrderBy ){
      for(ii=0; ii<pOrderBy->nExpr; ii++){
        Expr *pExpr = pOrderBy->a[ii].pExpr;
        if( pExpr->op!=TK_COLUMN ) return;
        if( pExpr->iTable!=iCsr ) return;
        if( pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) return;
      }
    }

    /* All conditions are met. Add the terms to the where-clause object. */
    assert( p->pLimit->op==TK_LIMIT );


    if( p->iOffset!=0 && (p->selFlags & SF_Compound)==0 ){
      whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
                        iCsr, SQLITE_INDEX_CONSTRAINT_OFFSET);
    }
    if( p->iOffset==0 || (p->selFlags & SF_Compound)==0 ){
      whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
                        iCsr, SQLITE_INDEX_CONSTRAINT_LIMIT);
    }
  }
}

/*
** Initialize a preallocated WhereClause structure.
*/
SQLITE_PRIVATE void sqlite3WhereClauseInit(







<














>
>
|



<
<
<
<







161698
161699
161700
161701
161702
161703
161704

161705
161706
161707
161708
161709
161710
161711
161712
161713
161714
161715
161716
161717
161718
161719
161720
161721
161722
161723
161724




161725
161726
161727
161728
161729
161730
161731
        /* If this term has child terms, then they are also part of the
        ** pWC->a[] array. So this term can be ignored, as a LIMIT clause
        ** will only be added if each of the child terms passes the
        ** (leftCursor==iCsr) test below.  */
        continue;
      }
      if( pWC->a[ii].leftCursor!=iCsr ) return;

    }

    /* Check condition (5). Return early if it is not met. */
    if( pOrderBy ){
      for(ii=0; ii<pOrderBy->nExpr; ii++){
        Expr *pExpr = pOrderBy->a[ii].pExpr;
        if( pExpr->op!=TK_COLUMN ) return;
        if( pExpr->iTable!=iCsr ) return;
        if( pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) return;
      }
    }

    /* All conditions are met. Add the terms to the where-clause object. */
    assert( p->pLimit->op==TK_LIMIT );
    whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
                      iCsr, SQLITE_INDEX_CONSTRAINT_LIMIT);
    if( p->iOffset>0 ){
      whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
                        iCsr, SQLITE_INDEX_CONSTRAINT_OFFSET);
    }




  }
}

/*
** Initialize a preallocated WhereClause structure.
*/
SQLITE_PRIVATE void sqlite3WhereClauseInit(
162732
162733
162734
162735
162736
162737
162738
162739
162740
162741
162742
162743
162744
162745
162746
162747
162748
162749
162750
162751
162752
162753
162754
162755
162756
162757
162758
162759
162760
162761
162762
162763
162764
162765
162766
162767
162768
162769
162770
162771
162772
162773
162774
162775
162776
162777
162778
162779
162780
162781
  p = sqlite3ExprSkipCollateAndLikely(p->pRight);
  if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
    return p;
  }
  return 0;
}

/*
** Term pTerm is guaranteed to be a WO_IN term. It may be a component term
** of a vector IN expression of the form "(x, y, ...) IN (SELECT ...)".
** This function checks to see if the term is compatible with an index
** column with affinity idxaff (one of the SQLITE_AFF_XYZ values). If so,
** it returns a pointer to the name of the collation sequence (e.g. "BINARY"
** or "NOCASE") used by the comparison in pTerm. If it is not compatible
** with affinity idxaff, NULL is returned.
*/
static SQLITE_NOINLINE const char *indexInAffinityOk(
  Parse *pParse,
  WhereTerm *pTerm,
  u8 idxaff
){
  Expr *pX = pTerm->pExpr;
  Expr inexpr;

  assert( pTerm->eOperator & WO_IN );

  if( sqlite3ExprIsVector(pX->pLeft) ){
    int iField = pTerm->u.x.iField - 1;
    inexpr.flags = 0;
    inexpr.op = TK_EQ;
    inexpr.pLeft = pX->pLeft->x.pList->a[iField].pExpr;
    assert( ExprUseXSelect(pX) );
    inexpr.pRight = pX->x.pSelect->pEList->a[iField].pExpr;
    pX = &inexpr;
  }

  if( sqlite3IndexAffinityOk(pX, idxaff) ){
    CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
    return pRet ? pRet->zName : sqlite3StrBINARY;
  }
  return 0;
}

/*
** Advance to the next WhereTerm that matches according to the criteria
** established when the pScan object was initialized by whereScanInit().
** Return NULL if there are no more matching WhereTerms.
*/
static WhereTerm *whereScanNext(WhereScan *pScan){
  int iCur;            /* The cursor on the LHS of the term */







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







162235
162236
162237
162238
162239
162240
162241




































162242
162243
162244
162245
162246
162247
162248
  p = sqlite3ExprSkipCollateAndLikely(p->pRight);
  if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
    return p;
  }
  return 0;
}





































/*
** Advance to the next WhereTerm that matches according to the criteria
** established when the pScan object was initialized by whereScanInit().
** Return NULL if there are no more matching WhereTerms.
*/
static WhereTerm *whereScanNext(WhereScan *pScan){
  int iCur;            /* The cursor on the LHS of the term */
162818
162819
162820
162821
162822
162823
162824
162825
162826
162827
162828
162829
162830
162831
162832
162833
162834
162835
162836
162837
162838
162839
162840
162841
162842
162843
162844
162845
162846
162847
162848
162849
              pScan->aiColumn[j] = pX->iColumn;
              pScan->nEquiv++;
            }
          }
          if( (pTerm->eOperator & pScan->opMask)!=0 ){
            /* Verify the affinity and collating sequence match */
            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
              const char *zCollName;
              Parse *pParse = pWC->pWInfo->pParse;
              pX = pTerm->pExpr;

              if( (pTerm->eOperator & WO_IN) ){
                zCollName = indexInAffinityOk(pParse, pTerm, pScan->idxaff);
                if( !zCollName ) continue;
              }else{
                CollSeq *pColl;
                if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
                  continue;
                }
                assert(pX->pLeft);
                pColl = sqlite3ExprCompareCollSeq(pParse, pX);
                zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
              }

              if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
                continue;
              }
            }
            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
             && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
             && pX->op==TK_COLUMN
             && pX->iTable==pScan->aiCur[0]







|


<
<
<
<
<
<
|
|
|
|
|
<
<
|
|







162285
162286
162287
162288
162289
162290
162291
162292
162293
162294






162295
162296
162297
162298
162299


162300
162301
162302
162303
162304
162305
162306
162307
162308
              pScan->aiColumn[j] = pX->iColumn;
              pScan->nEquiv++;
            }
          }
          if( (pTerm->eOperator & pScan->opMask)!=0 ){
            /* Verify the affinity and collating sequence match */
            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
              CollSeq *pColl;
              Parse *pParse = pWC->pWInfo->pParse;
              pX = pTerm->pExpr;






              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
                continue;
              }
              assert(pX->pLeft);
              pColl = sqlite3ExprCompareCollSeq(pParse, pX);


              if( pColl==0 ) pColl = pParse->db->pDfltColl;
              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
                continue;
              }
            }
            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
             && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
             && pX->op==TK_COLUMN
             && pX->iTable==pScan->aiCur[0]
163270
163271
163272
163273
163274
163275
163276
163277
163278
163279
163280
163281
163282
163283
163284
163285
163286
163287
163288
163289
163290
163291
163292
163293
163294
163295
163296
163297
163298
163299
163300
163301
163302
163303
163304
163305
163306
163307
163308
163309
163310
163311
163312
163313
163314
163315
163316
163317
163318
163319
163320
163321
163322
163323
163324
163325
163326
163327
163328
163329
163330
163331
163332
163333
163334
163335
163336
163337
163338
163339
163340
163341
163342
163343
163344
163345
163346
163347
163348
163349
   && ExprHasProperty(pTerm->pExpr, EP_InnerON)
  ){
    return 0;
  }
  return 1;
}

#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
/*
** Return true if column iCol of table pTab seem like it might be a
** good column to use as part of a query-time index.
**
** Current algorithm (subject to improvement!):
**
**   1.   If iCol is already the left-most column of some other index,
**        then return false.
**
**   2.   If iCol is part of an existing index that has an aiRowLogEst of
**        more than 20, then return false.
**
**   3.   If no disqualifying conditions above are found, return true.
*/
static SQLITE_NOINLINE int columnIsGoodIndexCandidate(
  const Table *pTab,
  int iCol
){
  const Index *pIdx;
  for(pIdx = pTab->pIndex; pIdx!=0; pIdx=pIdx->pNext){
    int j;
    for(j=0; j<pIdx->nKeyCol; j++){
       if( pIdx->aiColumn[j]==iCol ){
         if( j==0 ) return 0;
         if( pIdx->hasStat1 && pIdx->aiRowLogEst[j+1]>20 ) return 0;
         break;
       }
    }
  }
  return 1;
}
#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */



#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
/*
** Return TRUE if the WHERE clause term pTerm is of a form where it
** could be used with an index to access pSrc, assuming an appropriate
** index existed.
*/
static int termCanDriveIndex(
  const WhereTerm *pTerm,        /* WHERE clause term to check */
  const SrcItem *pSrc,           /* Table we are trying to access */
  const Bitmask notReady         /* Tables in outer loops of the join */
){
  char aff;
  int leftCol;

  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
  if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
   && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
  ){
    return 0;  /* See https://sqlite.org/forum/forumpost/51e6959f61 */
  }
  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
  leftCol = pTerm->u.x.leftColumn;
  if( leftCol<0 ) return 0;
  aff = pSrc->pTab->aCol[leftCol].affinity;
  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  testcase( pTerm->pExpr->op==TK_IS );
  return columnIsGoodIndexCandidate(pSrc->pTab, leftCol);
}
#endif


#ifndef SQLITE_OMIT_AUTOMATIC_INDEX

#ifdef SQLITE_ENABLE_STMT_SCANSTATUS







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














<
<










|
<
|


|







162729
162730
162731
162732
162733
162734
162735


































162736
162737
162738
162739
162740
162741
162742
162743
162744
162745
162746
162747
162748
162749


162750
162751
162752
162753
162754
162755
162756
162757
162758
162759
162760

162761
162762
162763
162764
162765
162766
162767
162768
162769
162770
162771
   && ExprHasProperty(pTerm->pExpr, EP_InnerON)
  ){
    return 0;
  }
  return 1;
}





































#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
/*
** Return TRUE if the WHERE clause term pTerm is of a form where it
** could be used with an index to access pSrc, assuming an appropriate
** index existed.
*/
static int termCanDriveIndex(
  const WhereTerm *pTerm,        /* WHERE clause term to check */
  const SrcItem *pSrc,           /* Table we are trying to access */
  const Bitmask notReady         /* Tables in outer loops of the join */
){
  char aff;


  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
  if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
   && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
  ){
    return 0;  /* See https://sqlite.org/forum/forumpost/51e6959f61 */
  }
  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
  if( pTerm->u.x.leftColumn<0 ) return 0;

  aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  testcase( pTerm->pExpr->op==TK_IS );
  return 1;
}
#endif


#ifndef SQLITE_OMIT_AUTOMATIC_INDEX

#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
163776
163777
163778
163779
163780
163781
163782
163783
163784
163785
163786
163787
163788
163789
163790
163791
163792
163793
163794
163795
163796
163797
163798
163799
163800
163801
163802
163803
  sqlite3VdbeJumpHere(v, addrOnce);
  pParse->pIdxEpr = saved_pIdxEpr;
  pParse->pIdxPartExpr = saved_pIdxPartExpr;
}


#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Return term iTerm of the WhereClause passed as the first argument. Terms
** are numbered from 0 upwards, starting with the terms in pWC->a[], then
** those in pWC->pOuter->a[] (if any), and so on.
*/
static WhereTerm *termFromWhereClause(WhereClause *pWC, int iTerm){
  WhereClause *p;
  for(p=pWC; p; p=p->pOuter){
    if( iTerm<p->nTerm ) return &p->a[iTerm];
    iTerm -= p->nTerm;
  }
  return 0;
}

/*
** Allocate and populate an sqlite3_index_info structure. It is the
** responsibility of the caller to eventually release the structure
** by passing the pointer returned by this function to freeIndexInfo().
*/
static sqlite3_index_info *allocateIndexInfo(
  WhereInfo *pWInfo,              /* The WHERE clause */







<
<
<
<
<
<
<
<
<
<
<
<
<
<







163198
163199
163200
163201
163202
163203
163204














163205
163206
163207
163208
163209
163210
163211
  sqlite3VdbeJumpHere(v, addrOnce);
  pParse->pIdxEpr = saved_pIdxEpr;
  pParse->pIdxPartExpr = saved_pIdxPartExpr;
}


#ifndef SQLITE_OMIT_VIRTUALTABLE














/*
** Allocate and populate an sqlite3_index_info structure. It is the
** responsibility of the caller to eventually release the structure
** by passing the pointer returned by this function to freeIndexInfo().
*/
static sqlite3_index_info *allocateIndexInfo(
  WhereInfo *pWInfo,              /* The WHERE clause */
163816
163817
163818
163819
163820
163821
163822
163823
163824
163825
163826
163827
163828
163829
163830
163831
163832
163833
163834
163835
163836
163837
163838
163839
163840
163841
163842
163843
163844
163845
163846
163847
163848
163849
163850
163851
163852
163853
163854
163855
163856
163857
163858
163859
163860
163861
163862
163863
163864
  WhereTerm *pTerm;
  int nOrderBy;
  sqlite3_index_info *pIdxInfo;
  u16 mNoOmit = 0;
  const Table *pTab;
  int eDistinct = 0;
  ExprList *pOrderBy = pWInfo->pOrderBy;
  WhereClause *p;

  assert( pSrc!=0 );
  pTab = pSrc->pTab;
  assert( pTab!=0 );
  assert( IsVirtual(pTab) );

  /* Find all WHERE clause constraints referring to this virtual table.
  ** Mark each term with the TERM_OK flag.  Set nTerm to the number of
  ** terms found.
  */
  for(p=pWC, nTerm=0; p; p=p->pOuter){
    for(i=0, pTerm=p->a; i<p->nTerm; i++, pTerm++){
      pTerm->wtFlags &= ~TERM_OK;
      if( pTerm->leftCursor != pSrc->iCursor ) continue;
      if( pTerm->prereqRight & mUnusable ) continue;
      assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
      testcase( pTerm->eOperator & WO_IN );
      testcase( pTerm->eOperator & WO_ISNULL );
      testcase( pTerm->eOperator & WO_IS );
      testcase( pTerm->eOperator & WO_ALL );
      if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
      if( pTerm->wtFlags & TERM_VNULL ) continue;

      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
      assert( pTerm->u.x.leftColumn>=XN_ROWID );
      assert( pTerm->u.x.leftColumn<pTab->nCol );
      if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
          && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
        ){
        continue;
      }
      nTerm++;
      pTerm->wtFlags |= TERM_OK;
    }
  }

  /* If the ORDER BY clause contains only columns in the current
  ** virtual table then allocate space for the aOrderBy part of
  ** the sqlite3_index_info structure.
  */
  nOrderBy = 0;







<










<
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
<







163224
163225
163226
163227
163228
163229
163230

163231
163232
163233
163234
163235
163236
163237
163238
163239
163240

163241
163242
163243
163244
163245
163246
163247
163248
163249
163250
163251
163252
163253
163254
163255
163256
163257
163258
163259
163260
163261
163262

163263
163264
163265
163266
163267
163268
163269
  WhereTerm *pTerm;
  int nOrderBy;
  sqlite3_index_info *pIdxInfo;
  u16 mNoOmit = 0;
  const Table *pTab;
  int eDistinct = 0;
  ExprList *pOrderBy = pWInfo->pOrderBy;


  assert( pSrc!=0 );
  pTab = pSrc->pTab;
  assert( pTab!=0 );
  assert( IsVirtual(pTab) );

  /* Find all WHERE clause constraints referring to this virtual table.
  ** Mark each term with the TERM_OK flag.  Set nTerm to the number of
  ** terms found.
  */

  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
    pTerm->wtFlags &= ~TERM_OK;
    if( pTerm->leftCursor != pSrc->iCursor ) continue;
    if( pTerm->prereqRight & mUnusable ) continue;
    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
    testcase( pTerm->eOperator & WO_IN );
    testcase( pTerm->eOperator & WO_ISNULL );
    testcase( pTerm->eOperator & WO_IS );
    testcase( pTerm->eOperator & WO_ALL );
    if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
    if( pTerm->wtFlags & TERM_VNULL ) continue;

    assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
    assert( pTerm->u.x.leftColumn>=XN_ROWID );
    assert( pTerm->u.x.leftColumn<pTab->nCol );
    if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
     && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
    ){
      continue;
    }
    nTerm++;
    pTerm->wtFlags |= TERM_OK;

  }

  /* If the ORDER BY clause contains only columns in the current
  ** virtual table then allocate space for the aOrderBy part of
  ** the sqlite3_index_info structure.
  */
  nOrderBy = 0;
163900
163901
163902
163903
163904
163905
163906
163907
163908
163909
163910
163911
163912
163913
163914
      }

      /* No matches cause a break out of the loop */
      break;
    }
    if( i==n ){
      nOrderBy = n;
      if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) && !pSrc->fg.rowidUsed ){
        eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
      }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
        eDistinct = 1;
      }
    }
  }








|







163305
163306
163307
163308
163309
163310
163311
163312
163313
163314
163315
163316
163317
163318
163319
      }

      /* No matches cause a break out of the loop */
      break;
    }
    if( i==n ){
      nOrderBy = n;
      if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
        eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
      }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
        eDistinct = 1;
      }
    }
  }

163929
163930
163931
163932
163933
163934
163935
163936
163937
163938
163939
163940
163941
163942
163943
163944
163945
163946
163947
163948
163949
163950
163951
163952
163953
163954
163955
163956
163957
163958
163959
163960
163961
163962
163963
163964
163965
163966
163967
163968
163969
163970
163971
163972
163973
163974
163975
163976
163977
163978
163979
163980
163981
163982
163983
163984
163985
163986
163987
163988
163989
163990
163991
163992
163993
163994
163995
163996
163997
163998
163999
164000
164001
164002
164003
164004
164005
164006
164007
164008
164009
164010
164011
164012
164013
164014
164015
164016
164017
164018
164019
164020
164021
164022
164023
164024
164025
164026
164027
164028
164029
164030
164031
164032
164033
164034
  pIdxInfo->aConstraint = pIdxCons;
  pIdxInfo->aOrderBy = pIdxOrderBy;
  pIdxInfo->aConstraintUsage = pUsage;
  pHidden->pWC = pWC;
  pHidden->pParse = pParse;
  pHidden->eDistinct = eDistinct;
  pHidden->mIn = 0;
  for(p=pWC, i=j=0; p; p=p->pOuter){
    int nLast = i+p->nTerm;;
    for(pTerm=p->a; i<nLast; i++, pTerm++){
      u16 op;
      if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
      pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
      pIdxCons[j].iTermOffset = i;
      op = pTerm->eOperator & WO_ALL;
      if( op==WO_IN ){
        if( (pTerm->wtFlags & TERM_SLICE)==0 ){
          pHidden->mIn |= SMASKBIT32(j);
        }
        op = WO_EQ;
      }
      if( op==WO_AUX ){
        pIdxCons[j].op = pTerm->eMatchOp;
      }else if( op & (WO_ISNULL|WO_IS) ){
        if( op==WO_ISNULL ){
          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
        }else{
          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
        }
      }else{
        pIdxCons[j].op = (u8)op;
        /* The direct assignment in the previous line is possible only because
        ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
        ** following asserts verify this fact. */
        assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
        assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
        assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
        assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
        assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
        assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );

        if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
            && sqlite3ExprIsVector(pTerm->pExpr->pRight)
          ){
          testcase( j!=i );
          if( j<16 ) mNoOmit |= (1 << j);
          if( op==WO_LT ) pIdxCons[j].op = WO_LE;
          if( op==WO_GT ) pIdxCons[j].op = WO_GE;
        }
      }

      j++;
    }
  }
  assert( j==nTerm );
  pIdxInfo->nConstraint = j;
  for(i=j=0; i<nOrderBy; i++){
    Expr *pExpr = pOrderBy->a[i].pExpr;
    if( sqlite3ExprIsConstant(0, pExpr) ) continue;
    assert( pExpr->op==TK_COLUMN
         || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
              && pExpr->iColumn==pExpr->pLeft->iColumn) );
    pIdxOrderBy[j].iColumn = pExpr->iColumn;
    pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
    j++;
  }
  pIdxInfo->nOrderBy = j;

  *pmNoOmit = mNoOmit;
  return pIdxInfo;
}

/*
** Free and zero the sqlite3_index_info.idxStr value if needed.
*/
static void freeIdxStr(sqlite3_index_info *pIdxInfo){
  if( pIdxInfo->needToFreeIdxStr ){
    sqlite3_free(pIdxInfo->idxStr);
    pIdxInfo->idxStr = 0;
    pIdxInfo->needToFreeIdxStr = 0;
  }
}

/*
** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
** and possibly modified by xBestIndex methods.
*/
static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
  HiddenIndexInfo *pHidden;
  int i;
  assert( pIdxInfo!=0 );
  pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  assert( pHidden->pParse!=0 );
  assert( pHidden->pParse->db==db );
  for(i=0; i<pIdxInfo->nConstraint; i++){
    sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
    pHidden->aRhs[i] = 0;
  }
  freeIdxStr(pIdxInfo);
  sqlite3DbFree(db, pIdxInfo);
}

/*
** The table object reference passed as the second argument to this function
** must represent a virtual table. This function invokes the xBestIndex()
** method of the virtual table with the sqlite3_index_info object that







<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
<



















<
<
<
<
<
<
<
<
<
<
<















<







163334
163335
163336
163337
163338
163339
163340


163341
163342
163343
163344
163345
163346
163347
163348
163349
163350
163351
163352
163353
163354
163355
163356
163357
163358
163359
163360
163361
163362
163363
163364
163365
163366
163367
163368
163369
163370
163371
163372
163373
163374
163375
163376
163377
163378
163379
163380
163381
163382
163383

163384
163385
163386
163387
163388
163389
163390
163391
163392
163393
163394
163395
163396
163397
163398
163399
163400
163401
163402











163403
163404
163405
163406
163407
163408
163409
163410
163411
163412
163413
163414
163415
163416
163417

163418
163419
163420
163421
163422
163423
163424
  pIdxInfo->aConstraint = pIdxCons;
  pIdxInfo->aOrderBy = pIdxOrderBy;
  pIdxInfo->aConstraintUsage = pUsage;
  pHidden->pWC = pWC;
  pHidden->pParse = pParse;
  pHidden->eDistinct = eDistinct;
  pHidden->mIn = 0;


  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
    u16 op;
    if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
    pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
    pIdxCons[j].iTermOffset = i;
    op = pTerm->eOperator & WO_ALL;
    if( op==WO_IN ){
      if( (pTerm->wtFlags & TERM_SLICE)==0 ){
        pHidden->mIn |= SMASKBIT32(j);
      }
      op = WO_EQ;
    }
    if( op==WO_AUX ){
      pIdxCons[j].op = pTerm->eMatchOp;
    }else if( op & (WO_ISNULL|WO_IS) ){
      if( op==WO_ISNULL ){
        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
      }else{
        pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
      }
    }else{
      pIdxCons[j].op = (u8)op;
      /* The direct assignment in the previous line is possible only because
      ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
      ** following asserts verify this fact. */
      assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
      assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
      assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
      assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
      assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
      assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );

      if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
       && sqlite3ExprIsVector(pTerm->pExpr->pRight)
      ){
        testcase( j!=i );
        if( j<16 ) mNoOmit |= (1 << j);
        if( op==WO_LT ) pIdxCons[j].op = WO_LE;
        if( op==WO_GT ) pIdxCons[j].op = WO_GE;
      }
    }

    j++;

  }
  assert( j==nTerm );
  pIdxInfo->nConstraint = j;
  for(i=j=0; i<nOrderBy; i++){
    Expr *pExpr = pOrderBy->a[i].pExpr;
    if( sqlite3ExprIsConstant(0, pExpr) ) continue;
    assert( pExpr->op==TK_COLUMN
         || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
              && pExpr->iColumn==pExpr->pLeft->iColumn) );
    pIdxOrderBy[j].iColumn = pExpr->iColumn;
    pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
    j++;
  }
  pIdxInfo->nOrderBy = j;

  *pmNoOmit = mNoOmit;
  return pIdxInfo;
}












/*
** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
** and possibly modified by xBestIndex methods.
*/
static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
  HiddenIndexInfo *pHidden;
  int i;
  assert( pIdxInfo!=0 );
  pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  assert( pHidden->pParse!=0 );
  assert( pHidden->pParse->db==db );
  for(i=0; i<pIdxInfo->nConstraint; i++){
    sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
    pHidden->aRhs[i] = 0;
  }

  sqlite3DbFree(db, pIdxInfo);
}

/*
** The table object reference passed as the second argument to this function
** must represent a virtual table. This function invokes the xBestIndex()
** method of the virtual table with the sqlite3_index_info object that
165372
165373
165374
165375
165376
165377
165378
165379
165380
165381
165382
165383
165384
165385
165386
        pLoop->nOut--;
        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
         && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */
        ){
          Expr *pRight = pTerm->pExpr->pRight;
          int k = 0;
          testcase( pTerm->pExpr->op==TK_IS );
          if( sqlite3ExprIsInteger(pRight, &k, 0) && k>=(-1) && k<=1 ){
            k = 10;
          }else{
            k = 20;
          }
          if( iReduce<k ){
            pTerm->wtFlags |= TERM_HEURTRUTH;
            iReduce = k;







|







164762
164763
164764
164765
164766
164767
164768
164769
164770
164771
164772
164773
164774
164775
164776
        pLoop->nOut--;
        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
         && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */
        ){
          Expr *pRight = pTerm->pExpr->pRight;
          int k = 0;
          testcase( pTerm->pExpr->op==TK_IS );
          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
            k = 10;
          }else{
            k = 20;
          }
          if( iReduce<k ){
            pTerm->wtFlags |= TERM_HEURTRUTH;
            iReduce = k;
165669
165670
165671
165672
165673
165674
165675
165676
165677
165678
165679
165680
165681
165682
165683
      int iCol = pProbe->aiColumn[saved_nEq];
      pNew->wsFlags |= WHERE_COLUMN_EQ;
      assert( saved_nEq==pNew->u.btree.nEq );
      if( iCol==XN_ROWID
       || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
      ){
        if( iCol==XN_ROWID || pProbe->uniqNotNull
         || (pProbe->nKeyCol==1 && pProbe->onError && (eOp & WO_EQ))
        ){
          pNew->wsFlags |= WHERE_ONEROW;
        }else{
          pNew->wsFlags |= WHERE_UNQ_WANTED;
        }
      }
      if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;







|







165059
165060
165061
165062
165063
165064
165065
165066
165067
165068
165069
165070
165071
165072
165073
      int iCol = pProbe->aiColumn[saved_nEq];
      pNew->wsFlags |= WHERE_COLUMN_EQ;
      assert( saved_nEq==pNew->u.btree.nEq );
      if( iCol==XN_ROWID
       || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
      ){
        if( iCol==XN_ROWID || pProbe->uniqNotNull
         || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
        ){
          pNew->wsFlags |= WHERE_ONEROW;
        }else{
          pNew->wsFlags |= WHERE_UNQ_WANTED;
        }
      }
      if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
166556
166557
166558
166559
166560
166561
166562
166563
166564
166565
166566
166567
166568
166569
166570
166571
166572
166573
166574
166575
166576
166577
166578
166579
166580
166581
166582
166583
166584
*/
static int isLimitTerm(WhereTerm *pTerm){
  assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
  return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
      && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
}

/*
** Return true if the first nCons constraints in the pUsage array are
** marked as in-use (have argvIndex>0). False otherwise.
*/
static int allConstraintsUsed(
  struct sqlite3_index_constraint_usage *aUsage,
  int nCons
){
  int ii;
  for(ii=0; ii<nCons; ii++){
    if( aUsage[ii].argvIndex<=0 ) return 0;
  }
  return 1;
}

/*
** Argument pIdxInfo is already populated with all constraints that may
** be used by the virtual table identified by pBuilder->pNew->iTab. This
** function marks a subset of those constraints usable, invokes the
** xBestIndex method and adds the returned plan to pBuilder.
**
** A constraint is marked usable if:







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







165946
165947
165948
165949
165950
165951
165952















165953
165954
165955
165956
165957
165958
165959
*/
static int isLimitTerm(WhereTerm *pTerm){
  assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
  return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
      && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
}
















/*
** Argument pIdxInfo is already populated with all constraints that may
** be used by the virtual table identified by pBuilder->pNew->iTab. This
** function marks a subset of those constraints usable, invokes the
** xBestIndex method and adds the returned plan to pBuilder.
**
** A constraint is marked usable if:
166621
166622
166623
166624
166625
166626
166627
166628
166629
166630
166631
166632
166633
166634
166635
  *pbIn = 0;
  pNew->prereq = mPrereq;

  /* Set the usable flag on the subset of constraints identified by
  ** arguments mUsable and mExclude. */
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  for(i=0; i<nConstraint; i++, pIdxCons++){
    WhereTerm *pTerm = termFromWhereClause(pWC, pIdxCons->iTermOffset);
    pIdxCons->usable = 0;
    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
     && (pTerm->eOperator & mExclude)==0
     && (pbRetryLimit || !isLimitTerm(pTerm))
    ){
      pIdxCons->usable = 1;
    }







|







165996
165997
165998
165999
166000
166001
166002
166003
166004
166005
166006
166007
166008
166009
166010
  *pbIn = 0;
  pNew->prereq = mPrereq;

  /* Set the usable flag on the subset of constraints identified by
  ** arguments mUsable and mExclude. */
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  for(i=0; i<nConstraint; i++, pIdxCons++){
    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
    pIdxCons->usable = 0;
    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
     && (pTerm->eOperator & mExclude)==0
     && (pbRetryLimit || !isLimitTerm(pTerm))
    ){
      pIdxCons->usable = 1;
    }
166652
166653
166654
166655
166656
166657
166658
166659
166660
166661
166662
166663
166664
166665
166666
166667
166668
166669
166670
166671
166672
166673
166674
166675
166676
166677
166678
166679
166680
166681
166682
166683
166684
166685
166686
166687

166688
166689
166690
166691
166692
166693
166694
  if( rc ){
    if( rc==SQLITE_CONSTRAINT ){
      /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
      ** that the particular combination of parameters provided is unusable.
      ** Make no entries in the loop table.
      */
      WHERETRACE(0xffffffff, ("  ^^^^--- non-viable plan rejected!\n"));
      freeIdxStr(pIdxInfo);
      return SQLITE_OK;
    }
    return rc;
  }

  mxTerm = -1;
  assert( pNew->nLSlot>=nConstraint );
  memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
  memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  for(i=0; i<nConstraint; i++, pIdxCons++){
    int iTerm;
    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
      WhereTerm *pTerm;
      int j = pIdxCons->iTermOffset;
      if( iTerm>=nConstraint
       || j<0
       || (pTerm = termFromWhereClause(pWC, j))==0
       || pNew->aLTerm[iTerm]!=0
       || pIdxCons->usable==0
      ){
        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
        freeIdxStr(pIdxInfo);
        return SQLITE_ERROR;
      }
      testcase( iTerm==nConstraint-1 );
      testcase( j==0 );
      testcase( j==pWC->nTerm-1 );

      pNew->prereq |= pTerm->prereqRight;
      assert( iTerm<pNew->nLSlot );
      pNew->aLTerm[iTerm] = pTerm;
      if( iTerm>mxTerm ) mxTerm = iTerm;
      testcase( iTerm==15 );
      testcase( iTerm==16 );
      if( pUsage[i].omit ){







<

















|




|





>







166027
166028
166029
166030
166031
166032
166033

166034
166035
166036
166037
166038
166039
166040
166041
166042
166043
166044
166045
166046
166047
166048
166049
166050
166051
166052
166053
166054
166055
166056
166057
166058
166059
166060
166061
166062
166063
166064
166065
166066
166067
166068
166069
  if( rc ){
    if( rc==SQLITE_CONSTRAINT ){
      /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
      ** that the particular combination of parameters provided is unusable.
      ** Make no entries in the loop table.
      */
      WHERETRACE(0xffffffff, ("  ^^^^--- non-viable plan rejected!\n"));

      return SQLITE_OK;
    }
    return rc;
  }

  mxTerm = -1;
  assert( pNew->nLSlot>=nConstraint );
  memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
  memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  for(i=0; i<nConstraint; i++, pIdxCons++){
    int iTerm;
    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
      WhereTerm *pTerm;
      int j = pIdxCons->iTermOffset;
      if( iTerm>=nConstraint
       || j<0
       || j>=pWC->nTerm
       || pNew->aLTerm[iTerm]!=0
       || pIdxCons->usable==0
      ){
        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
        testcase( pIdxInfo->needToFreeIdxStr );
        return SQLITE_ERROR;
      }
      testcase( iTerm==nConstraint-1 );
      testcase( j==0 );
      testcase( j==pWC->nTerm-1 );
      pTerm = &pWC->a[j];
      pNew->prereq |= pTerm->prereqRight;
      assert( iTerm<pNew->nLSlot );
      pNew->aLTerm[iTerm] = pTerm;
      if( iTerm>mxTerm ) mxTerm = iTerm;
      testcase( iTerm==15 );
      testcase( iTerm==16 );
      if( pUsage[i].omit ){
166711
166712
166713
166714
166715
166716
166717
166718
166719
166720
166721
166722
166723
166724
166725
166726
166727
166728
166729
166730
166731


166732


166733
166734
166735
166736
166737
166738
166739
166740
166741
166742
166743
166744
166745
166746
166747
166748
166749
166750
166751
166752
        ** (2) Multiple outputs from a single IN value will not merge
        ** together.  */
        pIdxInfo->orderByConsumed = 0;
        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
      }

      /* Unless pbRetryLimit is non-NULL, there should be no LIMIT/OFFSET
      ** terms. And if there are any, they should follow all other terms. */
      assert( pbRetryLimit || !isLimitTerm(pTerm) );
      assert( !isLimitTerm(pTerm) || i>=nConstraint-2 );
      assert( !isLimitTerm(pTerm) || i==nConstraint-1 || isLimitTerm(pTerm+1) );

      if( isLimitTerm(pTerm) && (*pbIn || !allConstraintsUsed(pUsage, i)) ){
        /* If there is an IN(...) term handled as an == (separate call to
        ** xFilter for each value on the RHS of the IN) and a LIMIT or
        ** OFFSET term handled as well, the plan is unusable. Similarly,
        ** if there is a LIMIT/OFFSET and there are other unused terms,
        ** the plan cannot be used. In these cases set variable *pbRetryLimit
        ** to true to tell the caller to retry with LIMIT and OFFSET
        ** disabled. */


        freeIdxStr(pIdxInfo);


        *pbRetryLimit = 1;
        return SQLITE_OK;
      }
    }
  }

  pNew->nLTerm = mxTerm+1;
  for(i=0; i<=mxTerm; i++){
    if( pNew->aLTerm[i]==0 ){
      /* The non-zero argvIdx values must be contiguous.  Raise an
      ** error if they are not */
      sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
      freeIdxStr(pIdxInfo);
      return SQLITE_ERROR;
    }
  }
  assert( pNew->nLTerm<=pNew->nLSlot );
  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  pIdxInfo->needToFreeIdxStr = 0;







<
<

<
<
<
|


|
<
<
|
|
>
>
|
>
>












|







166086
166087
166088
166089
166090
166091
166092


166093



166094
166095
166096
166097


166098
166099
166100
166101
166102
166103
166104
166105
166106
166107
166108
166109
166110
166111
166112
166113
166114
166115
166116
166117
166118
166119
166120
166121
166122
166123
166124
        ** (2) Multiple outputs from a single IN value will not merge
        ** together.  */
        pIdxInfo->orderByConsumed = 0;
        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
      }



      assert( pbRetryLimit || !isLimitTerm(pTerm) );



      if( isLimitTerm(pTerm) && *pbIn ){
        /* If there is an IN(...) term handled as an == (separate call to
        ** xFilter for each value on the RHS of the IN) and a LIMIT or
        ** OFFSET term handled as well, the plan is unusable. Set output


        ** variable *pbRetryLimit to true to tell the caller to retry with
        ** LIMIT and OFFSET disabled. */
        if( pIdxInfo->needToFreeIdxStr ){
          sqlite3_free(pIdxInfo->idxStr);
          pIdxInfo->idxStr = 0;
          pIdxInfo->needToFreeIdxStr = 0;
        }
        *pbRetryLimit = 1;
        return SQLITE_OK;
      }
    }
  }

  pNew->nLTerm = mxTerm+1;
  for(i=0; i<=mxTerm; i++){
    if( pNew->aLTerm[i]==0 ){
      /* The non-zero argvIdx values must be contiguous.  Raise an
      ** error if they are not */
      sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
      testcase( pIdxInfo->needToFreeIdxStr );
      return SQLITE_ERROR;
    }
  }
  assert( pNew->nLTerm<=pNew->nLSlot );
  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  pIdxInfo->needToFreeIdxStr = 0;
166793
166794
166795
166796
166797
166798
166799
166800
166801
166802
166803
166804
166805
166806
166807
*/
SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  const char *zRet = 0;
  if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
    CollSeq *pC = 0;
    int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
    Expr *pX = termFromWhereClause(pHidden->pWC, iTerm)->pExpr;
    if( pX->pLeft ){
      pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
    }
    zRet = (pC ? pC->zName : sqlite3StrBINARY);
  }
  return zRet;
}







|







166165
166166
166167
166168
166169
166170
166171
166172
166173
166174
166175
166176
166177
166178
166179
*/
SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  const char *zRet = 0;
  if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
    CollSeq *pC = 0;
    int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
    Expr *pX = pHidden->pWC->a[iTerm].pExpr;
    if( pX->pLeft ){
      pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
    }
    zRet = (pC ? pC->zName : sqlite3StrBINARY);
  }
  return zRet;
}
166839
166840
166841
166842
166843
166844
166845
166846
166847
166848
166849
166850
166851
166852
166853
166854
166855
  HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
  sqlite3_value *pVal = 0;
  int rc = SQLITE_OK;
  if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
    rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
  }else{
    if( pH->aRhs[iCons]==0 ){
      WhereTerm *pTerm = termFromWhereClause(
          pH->pWC, pIdxInfo->aConstraint[iCons].iTermOffset
      );
      rc = sqlite3ValueFromExpr(
          pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
          SQLITE_AFF_BLOB, &pH->aRhs[iCons]
      );
      testcase( rc!=SQLITE_OK );
    }
    pVal = pH->aRhs[iCons];







<
|
<







166211
166212
166213
166214
166215
166216
166217

166218

166219
166220
166221
166222
166223
166224
166225
  HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
  sqlite3_value *pVal = 0;
  int rc = SQLITE_OK;
  if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
    rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
  }else{
    if( pH->aRhs[iCons]==0 ){

      WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];

      rc = sqlite3ValueFromExpr(
          pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
          SQLITE_AFF_BLOB, &pH->aRhs[iCons]
      );
      testcase( rc!=SQLITE_OK );
    }
    pVal = pH->aRhs[iCons];
166997
166998
166999
167000
167001
167002
167003
167004
167005


167006
167007
167008
167009
167010
167011
167012
    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
    ** in the set of terms that apply to the current virtual table.  */
    while( rc==SQLITE_OK ){
      int i;
      Bitmask mNext = ALLBITS;
      assert( mNext>0 );
      for(i=0; i<nConstraint; i++){
        int iTerm = p->aConstraint[i].iTermOffset;
        Bitmask mThis = termFromWhereClause(pWC, iTerm)->prereqRight & ~mPrereq;


        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
      }
      mPrev = mNext;
      if( mNext==ALLBITS ) break;
      if( mNext==mBest || mNext==mBestNoIn ) continue;
      WHERETRACE(0x800, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));







<
|
>
>







166367
166368
166369
166370
166371
166372
166373

166374
166375
166376
166377
166378
166379
166380
166381
166382
166383
    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
    ** in the set of terms that apply to the current virtual table.  */
    while( rc==SQLITE_OK ){
      int i;
      Bitmask mNext = ALLBITS;
      assert( mNext>0 );
      for(i=0; i<nConstraint; i++){

        Bitmask mThis = (
            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
        );
        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
      }
      mPrev = mNext;
      if( mNext==ALLBITS ) break;
      if( mNext==mBest || mNext==mBestNoIn ) continue;
      WHERETRACE(0x800, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
167034
167035
167036
167037
167038
167039
167040

167041
167042
167043
167044
167045
167046
167047
    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
      WHERETRACE(0x800, ("  VirtualOne: all disabled and w/o IN\n"));
      rc = whereLoopAddVirtualOne(
          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
    }
  }


  freeIndexInfo(pParse->db, p);
  WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  return rc;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*







>







166405
166406
166407
166408
166409
166410
166411
166412
166413
166414
166415
166416
166417
166418
166419
    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
      WHERETRACE(0x800, ("  VirtualOne: all disabled and w/o IN\n"));
      rc = whereLoopAddVirtualOne(
          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
    }
  }

  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  freeIndexInfo(pParse->db, p);
  WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  return rc;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

/*
167702
167703
167704
167705
167706
167707
167708
167709
167710
167711
167712
167713
167714
167715
167716
167717
167718
167719
167720
167721
167722
167723
167724
167725
167726
167727
167728
167729
167730
167731
167732
167733
167734
167735
167736
167737
167738
167739
167740
167741
167742
167743
167744
167745
167746
167747
167748
167749
167750
167751
167752
167753
167754
167755
167756
167757
167758
167759
167760
167761
167762
167763
167764
167765
167766
167767
167768
167769
167770
167771
167772
167773
167774
167775
167776
167777
167778
167779
167780
167781
167782
167783
167784
167785
167786
167787
167788
167789
167790
167791
167792
    ** reduces the number of output rows by a factor of 2 */
    if( nRow>10 ){ nRow -= 10;  assert( 10==sqlite3LogEst(2) ); }
  }
  rSortCost += estLog(nRow);
  return rSortCost;
}

/*
** Compute the maximum number of paths in the solver algorithm, for
** queries that have three or more terms in the FROM clause.  Queries with
** two or fewer FROM clause terms are handled by the caller.
**
** Query planning is NP-hard.  We must limit the number of paths at
** each step of the solver search algorithm to avoid exponential behavior.
**
** The value returned is a tuning parameter.  Currently the value is:
**
**     18    for star queries
**     12    otherwise
**
** For the purposes of SQLite, a star-query is defined as a query
** with a large central table that is joined against four or more
** smaller tables.  The central table is called the "fact" table.
** The smaller tables that get joined are "dimension tables".
**
** SIDE EFFECT:  (and really the whole point of this subroutine)
**
** If pWInfo describes a star-query, then the cost on WhereLoops for the
** fact table is reduced.  This heuristic helps keep fact tables in
** outer loops.  Without this heuristic, paths with fact tables in outer
** loops tend to get pruned by the mxChoice limit on the number of paths,
** resulting in poor query plans.  The total amount of heuristic cost
** adjustment is stored in pWInfo->nOutStarDelta and the cost adjustment
** for each WhereLoop is stored in its rStarDelta field.
*/
static int computeMxChoice(WhereInfo *pWInfo, LogEst nRowEst){
  int nLoop = pWInfo->nLevel;    /* Number of terms in the join */
  if( nRowEst==0 && nLoop>=5 ){
    /* Check to see if we are dealing with a star schema and if so, reduce
    ** the cost of fact tables relative to dimension tables, as a heuristic
    ** to help keep the fact tables in outer loops.
    */
    int iLoop;                /* Counter over join terms */
    Bitmask m;                /* Bitmask for current loop */
    assert( pWInfo->nOutStarDelta==0 );
    for(iLoop=0, m=1; iLoop<nLoop; iLoop++, m<<=1){
      WhereLoop *pWLoop;        /* For looping over WhereLoops */
      int nDep = 0;             /* Number of dimension tables */
      LogEst rDelta;            /* Heuristic cost adjustment */
      Bitmask mSeen = 0;        /* Mask of dimension tables */
      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
        if( (pWLoop->prereq & m)!=0 && (pWLoop->maskSelf & mSeen)==0 ){
          nDep++;
          mSeen |= pWLoop->maskSelf;
        }
      }
      if( nDep<=3 ) continue;
      rDelta = 15*(nDep-3);
#ifdef WHERETRACE_ENABLED /* 0x4 */
      if( sqlite3WhereTrace&0x4 ){
         SrcItem *pItem = pWInfo->pTabList->a + iLoop;
         sqlite3DebugPrintf("Fact-table %s: %d dimensions, cost reduced %d\n",
             pItem->zAlias ? pItem->zAlias : pItem->pTab->zName,
             nDep, rDelta);
      }
#endif
      if( pWInfo->nOutStarDelta==0 ){
        for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
          pWLoop->rStarDelta = 0;
        }
      }
      pWInfo->nOutStarDelta += rDelta;
      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
        if( pWLoop->maskSelf==m ){
          pWLoop->rRun -= rDelta;
          pWLoop->nOut -= rDelta;
          pWLoop->rStarDelta = rDelta;
        }
      }
    }
  }
  return pWInfo->nOutStarDelta>0 ? 18 : 12;
}

/*
** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
** attempts to find the lowest cost path that visits each WhereLoop
** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
**
** Assume that the total number of output rows that will need to be sorted
** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







167074
167075
167076
167077
167078
167079
167080













































































167081
167082
167083
167084
167085
167086
167087
    ** reduces the number of output rows by a factor of 2 */
    if( nRow>10 ){ nRow -= 10;  assert( 10==sqlite3LogEst(2) ); }
  }
  rSortCost += estLog(nRow);
  return rSortCost;
}














































































/*
** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
** attempts to find the lowest cost path that visits each WhereLoop
** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
**
** Assume that the total number of output rows that will need to be sorted
** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
167814
167815
167816
167817
167818
167819
167820





167821
167822
167823
167824
167825
167826
167827
167828
167829
167830
167831
167832
167833
167834
167835
167836
167837
167838
167839
167840
167841
167842
167843
167844
167845
167846
  WhereLoop **pX;           /* Used to divy up the pSpace memory */
  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
  char *pSpace;             /* Temporary memory used by this routine */
  int nSpace;               /* Bytes of space allocated at pSpace */

  pParse = pWInfo->pParse;
  nLoop = pWInfo->nLevel;





  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d, nQueryLoop=%d)\n",
                     nRowEst, pParse->nQueryLoop));
  /* TUNING: mxChoice is the maximum number of possible paths to preserve
  ** at each step.  Based on the number of loops in the FROM clause:
  **
  **     nLoop      mxChoice
  **     -----      --------
  **       1            1            // the most common case
  **       2            5
  **       3+        12 or 18        // see computeMxChoice()
  */
  if( nLoop<=1 ){
    mxChoice = 1;
  }else if( nLoop==2 ){
    mxChoice = 5;
  }else{
    mxChoice = computeMxChoice(pWInfo, nRowEst);
  }
  assert( nLoop<=pWInfo->pTabList->nSrc );

  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  ** case the purpose of this call is to estimate the number of rows returned
  ** by the overall query. Once this estimate has been obtained, the caller
  ** will invoke this function a second time, passing the estimate as the
  ** nRowEst parameter.  */
  if( pWInfo->pOrderBy==0 || nRowEst==0 ){







>
>
>
>
>


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







167109
167110
167111
167112
167113
167114
167115
167116
167117
167118
167119
167120
167121
167122

















167123
167124
167125
167126
167127
167128
167129
  WhereLoop **pX;           /* Used to divy up the pSpace memory */
  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
  char *pSpace;             /* Temporary memory used by this routine */
  int nSpace;               /* Bytes of space allocated at pSpace */

  pParse = pWInfo->pParse;
  nLoop = pWInfo->nLevel;
  /* TUNING: For simple queries, only the best path is tracked.
  ** For 2-way joins, the 5 best paths are followed.
  ** For joins of 3 or more tables, track the 10 best paths */
  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  assert( nLoop<=pWInfo->pTabList->nSrc );
  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d, nQueryLoop=%d)\n",
                     nRowEst, pParse->nQueryLoop));


















  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  ** case the purpose of this call is to estimate the number of rows returned
  ** by the overall query. Once this estimate has been obtained, the caller
  ** will invoke this function a second time, passing the estimate as the
  ** nRowEst parameter.  */
  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
167915
167916
167917
167918
167919
167920
167921
167922
167923
167924
167925
167926
167927
167928
167929
167930
167931
167932
          ** index is useful in the outer loop of a correlated subquery. */
          assert( 10==sqlite3LogEst(2) );
          continue;
        }

        /* At this point, pWLoop is a candidate to be the next loop.
        ** Compute its cost */
        rUnsorted = pWLoop->rRun + pFrom->nRow;
        if( pWLoop->rSetup ){
          rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup, rUnsorted);
        }
        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
        nOut = pFrom->nRow + pWLoop->nOut;
        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
        isOrdered = pFrom->isOrdered;
        if( isOrdered<0 ){
          revMask = 0;
          isOrdered = wherePathSatisfiesOrderBy(pWInfo,







<
<
|
<







167198
167199
167200
167201
167202
167203
167204


167205

167206
167207
167208
167209
167210
167211
167212
          ** index is useful in the outer loop of a correlated subquery. */
          assert( 10==sqlite3LogEst(2) );
          continue;
        }

        /* At this point, pWLoop is a candidate to be the next loop.
        ** Compute its cost */


        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);

        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
        nOut = pFrom->nRow + pWLoop->nOut;
        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
        isOrdered = pFrom->isOrdered;
        if( isOrdered<0 ){
          revMask = 0;
          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
167963
167964
167965
167966
167967
167968
167969
167970
167971
167972
167973
167974
167975
167976
167977
        ** that covers the same set of loops and has the same isOrdered
        ** setting as the current path candidate.
        **
        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
        ** of legal values for isOrdered, -1..64.
        */
        testcase( nTo==0 );
        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
          if( pTo->maskLoop==maskNew
           && ((pTo->isOrdered^isOrdered)&0x80)==0
          ){
            testcase( jj==nTo-1 );
            break;
          }







<







167243
167244
167245
167246
167247
167248
167249

167250
167251
167252
167253
167254
167255
167256
        ** that covers the same set of loops and has the same isOrdered
        ** setting as the current path candidate.
        **
        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
        ** of legal values for isOrdered, -1..64.
        */

        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
          if( pTo->maskLoop==maskNew
           && ((pTo->isOrdered^isOrdered)&0x80)==0
          ){
            testcase( jj==nTo-1 );
            break;
          }
168080
168081
168082
168083
168084
168085
168086
168087
168088
168089
168090
168091
168092
168093
168094
168095
168096
168097
168098
168099
168100
168101
168102
168103
168104
168105
168106
168107
168108
168109
168110
168111
168112
168113
168114
168115
          }
        }
      }
    }

#ifdef WHERETRACE_ENABLED  /* >=2 */
    if( sqlite3WhereTrace & 0x02 ){
      LogEst rMin, rFloor = 0;
      int nDone = 0;
      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
      while( nDone<nTo ){
        rMin = 0x7fff;
        for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
          if( pTo->rCost>rFloor && pTo->rCost<rMin ) rMin = pTo->rCost;
        }
        for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
          if( pTo->rCost==rMin ){
            sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
               wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
               pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
            if( pTo->isOrdered>0 ){
              sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
            }else{
              sqlite3DebugPrintf("\n");
            }
            nDone++;
          }
        }
        rFloor = rMin;
      }
    }
#endif

    /* Swap the roles of aFrom and aTo for the next generation */
    pFrom = aTo;
    aTo = aFrom;







<
<

<
<
|
<
<
<
<
|
|
|
|
|
|
|
|
<
<
<
<







167359
167360
167361
167362
167363
167364
167365


167366


167367




167368
167369
167370
167371
167372
167373
167374
167375




167376
167377
167378
167379
167380
167381
167382
          }
        }
      }
    }

#ifdef WHERETRACE_ENABLED  /* >=2 */
    if( sqlite3WhereTrace & 0x02 ){


      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);


      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){




        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
        if( pTo->isOrdered>0 ){
          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
        }else{
          sqlite3DebugPrintf("\n");
        }




      }
    }
#endif

    /* Swap the roles of aFrom and aTo for the next generation */
    pFrom = aTo;
    aTo = aFrom;
168196
168197
168198
168199
168200
168201
168202
168203
168204
168205
168206
168207
168208
168209
168210
      if( nOrder==pWInfo->pOrderBy->nExpr ){
        pWInfo->sorted = 1;
        pWInfo->revMask = revMask;
      }
    }
  }

  pWInfo->nRowOut = pFrom->nRow + pWInfo->nOutStarDelta;

  /* Free temporary memory and return success */
  sqlite3StackFreeNN(pParse->db, pSpace);
  return SQLITE_OK;
}

/*







|







167463
167464
167465
167466
167467
167468
167469
167470
167471
167472
167473
167474
167475
167476
167477
      if( nOrder==pWInfo->pOrderBy->nExpr ){
        pWInfo->sorted = 1;
        pWInfo->revMask = revMask;
      }
    }
  }

  pWInfo->nRowOut = pFrom->nRow;

  /* Free temporary memory and return success */
  sqlite3StackFreeNN(pParse->db, pSpace);
  return SQLITE_OK;
}

/*
168448
168449
168450
168451
168452
168453
168454
168455
168456
168457
168458
168459
168460
168461
168462
168463
168464
168465
**   5) The table must not have an inner-join ON or USING clause if there is
**      a RIGHT JOIN anywhere in the query.  Otherwise the ON/USING clause
**      might move from the right side to the left side of the RIGHT JOIN.
**      Note: Due to (2), this condition can only arise if the table is
**      the right-most table of a subquery that was flattened into the
**      main query and that subquery was the right-hand operand of an
**      inner join that held an ON or USING clause.
**   6) The ORDER BY clause has 63 or fewer terms
**   7) The omit-noop-join optimization is enabled.
**
** Items (1), (6), and (7) are checked by the caller.
**
** For example, given:
**
**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
**







<
<
<
<







167715
167716
167717
167718
167719
167720
167721




167722
167723
167724
167725
167726
167727
167728
**   5) The table must not have an inner-join ON or USING clause if there is
**      a RIGHT JOIN anywhere in the query.  Otherwise the ON/USING clause
**      might move from the right side to the left side of the RIGHT JOIN.
**      Note: Due to (2), this condition can only arise if the table is
**      the right-most table of a subquery that was flattened into the
**      main query and that subquery was the right-hand operand of an
**      inner join that held an ON or USING clause.




**
** For example, given:
**
**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
**
168590
168591
168592
168593
168594
168595
168596
168597
168598
168599
168600
168601
168602
168603
168604
168605
168606
168607
168608
168609
168610
168611
168612
168613
168614
168615
168616
168617
168618
168619
168620
168621
168622
168623
168624
168625
168626
168627
168628
168629
168630
168631
168632
168633
168634
168635
168636
168637
168638
168639
168640
168641
168642
168643
168644
168645
168646
168647
168648
168649
168650
168651
168652
168653
168654
168655
168656
168657
           "-> use Bloom-filter on loop %c because there are ~%.1e "
           "lookups into %s which has only ~%.1e rows\n",
           pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
           (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
      }
    }
    nSearch += pLoop->nOut;
    if( pWInfo->nOutStarDelta ) nSearch += pLoop->rStarDelta;
  }
}

/*
** Expression Node callback for sqlite3ExprCanReturnSubtype().
**
** Only a function call is able to return a subtype.  So if the node
** is not a function call, return WRC_Prune immediately.
**
** A function call is able to return a subtype if it has the
** SQLITE_RESULT_SUBTYPE property.
**
** Assume that every function is able to pass-through a subtype from
** one of its argument (using sqlite3_result_value()).  Most functions
** are not this way, but we don't have a mechanism to distinguish those
** that are from those that are not, so assume they all work this way.
** That means that if one of its arguments is another function and that
** other function is able to return a subtype, then this function is
** able to return a subtype.
*/
static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){
  int n;
  FuncDef *pDef;
  sqlite3 *db;
  if( pExpr->op!=TK_FUNCTION ){
    return WRC_Prune;
  }
  assert( ExprUseXList(pExpr) );
  db = pWalker->pParse->db;
  n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
  pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
  if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
    pWalker->eCode = 1;
    return WRC_Prune;
  }
  return WRC_Continue;
}

/*
** Return TRUE if expression pExpr is able to return a subtype.
**
** A TRUE return does not guarantee that a subtype will be returned.
** It only indicates that a subtype return is possible.  False positives
** are acceptable as they only disable an optimization.  False negatives,
** on the other hand, can lead to incorrect answers.
*/
static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){
  Walker w;
  memset(&w, 0, sizeof(w));
  w.pParse = pParse;
  w.xExprCallback = exprNodeCanReturnSubtype;
  sqlite3WalkExpr(&w, pExpr);
  return w.eCode;
}

/*
** The index pIdx is used by a query and contains one or more expressions.
** In other words pIdx is an index on an expression.  iIdxCur is the cursor
** number for the index and iDataCur is the cursor number for the corresponding
** table.







<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







167853
167854
167855
167856
167857
167858
167859

167860




















































167861
167862
167863
167864
167865
167866
167867
           "-> use Bloom-filter on loop %c because there are ~%.1e "
           "lookups into %s which has only ~%.1e rows\n",
           pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
           (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
      }
    }
    nSearch += pLoop->nOut;

  }




















































}

/*
** The index pIdx is used by a query and contains one or more expressions.
** In other words pIdx is an index on an expression.  iIdxCur is the cursor
** number for the index and iDataCur is the cursor number for the corresponding
** table.
168679
168680
168681
168682
168683
168684
168685
168686
168687
168688
168689







168690

168691
168692
168693
168694
168695
168696
168697
      pExpr = pIdx->aColExpr->a[i].pExpr;
    }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
      pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
    }else{
      continue;
    }
    if( sqlite3ExprIsConstant(0,pExpr) ) continue;
    if( pExpr->op==TK_FUNCTION && sqlite3ExprCanReturnSubtype(pParse,pExpr) ){
      /* Functions that might set a subtype should not be replaced by the
      ** value taken from an expression index since the index omits the
      ** subtype.  https://sqlite.org/forum/forumpost/68d284c86b082c3e */







      continue;

    }
    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
    if( p==0 ) break;
    p->pIENext = pParse->pIdxEpr;
#ifdef WHERETRACE_ENABLED
    if( sqlite3WhereTrace & 0x200 ){
      sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);







|



>
>
>
>
>
>
>
|
>







167889
167890
167891
167892
167893
167894
167895
167896
167897
167898
167899
167900
167901
167902
167903
167904
167905
167906
167907
167908
167909
167910
167911
167912
167913
167914
167915
      pExpr = pIdx->aColExpr->a[i].pExpr;
    }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
      pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
    }else{
      continue;
    }
    if( sqlite3ExprIsConstant(0,pExpr) ) continue;
    if( pExpr->op==TK_FUNCTION ){
      /* Functions that might set a subtype should not be replaced by the
      ** value taken from an expression index since the index omits the
      ** subtype.  https://sqlite.org/forum/forumpost/68d284c86b082c3e */
      int n;
      FuncDef *pDef;
      sqlite3 *db = pParse->db;
      assert( ExprUseXList(pExpr) );
      n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
      pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
      if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
        continue;
      }
    }
    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
    if( p==0 ) break;
    p->pIENext = pParse->pIdxEpr;
#ifdef WHERETRACE_ENABLED
    if( sqlite3WhereTrace & 0x200 ){
      sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
168866
168867
168868
168869
168870
168871
168872
168873
168874
168875
168876
168877
168878
168879
168880
  memset(&sWLB, 0, sizeof(sWLB));

  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  if( pOrderBy && pOrderBy->nExpr>=BMS ){
    pOrderBy = 0;
    wctrlFlags &= ~WHERE_WANT_DISTINCT;
    wctrlFlags |= WHERE_KEEP_ALL_JOINS; /* Disable omit-noop-join opt */
  }

  /* The number of tables in the FROM clause is limited by the number of
  ** bits in a Bitmask
  */
  testcase( pTabList->nSrc==BMS );
  if( pTabList->nSrc>BMS ){







<







168084
168085
168086
168087
168088
168089
168090

168091
168092
168093
168094
168095
168096
168097
  memset(&sWLB, 0, sizeof(sWLB));

  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  if( pOrderBy && pOrderBy->nExpr>=BMS ){
    pOrderBy = 0;
    wctrlFlags &= ~WHERE_WANT_DISTINCT;

  }

  /* The number of tables in the FROM clause is limited by the number of
  ** bits in a Bitmask
  */
  testcase( pTabList->nSrc==BMS );
  if( pTabList->nSrc>BMS ){
169107
169108
169109
169110
169111
169112
169113
169114
169115
169116
169117
169118
169119
169120
169121
#endif
    WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);

    wherePathSolver(pWInfo, 0);
    if( db->mallocFailed ) goto whereBeginError;
    if( pWInfo->pOrderBy ){
       whereInterstageHeuristic(pWInfo);
       wherePathSolver(pWInfo, pWInfo->nRowOut<0 ? 1 : pWInfo->nRowOut+1);
       if( db->mallocFailed ) goto whereBeginError;
    }

    /* TUNING:  Assume that a DISTINCT clause on a subquery reduces
    ** the output size by a factor of 8 (LogEst -30).
    */
    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){







|







168324
168325
168326
168327
168328
168329
168330
168331
168332
168333
168334
168335
168336
168337
168338
#endif
    WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);

    wherePathSolver(pWInfo, 0);
    if( db->mallocFailed ) goto whereBeginError;
    if( pWInfo->pOrderBy ){
       whereInterstageHeuristic(pWInfo);
       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
       if( db->mallocFailed ) goto whereBeginError;
    }

    /* TUNING:  Assume that a DISTINCT clause on a subquery reduces
    ** the output size by a factor of 8 (LogEst -30).
    */
    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
169167
169168
169169
169170
169171
169172
169173
169174
169175
169176
169177
169178
169179
169180
169181
169182
169183
169184
  ** procedure to keep the sqlite3WhereBegin() procedure from becoming
  ** too large.  If sqlite3WhereBegin() becomes too large, that prevents
  ** some C-compiler optimizers from in-lining the
  ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
  ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
  */
  notReady = ~(Bitmask)0;
  if( pWInfo->nLevel>=2       /* Must be a join, or this opt8n is pointless */
   && pResultSet!=0           /* Condition (1) */
   && 0==(wctrlFlags & (WHERE_AGG_DISTINCT|WHERE_KEEP_ALL_JOINS)) /* (1),(6) */
   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)                /* (7) */
  ){
    notReady = whereOmitNoopJoin(pWInfo, notReady);
    nTabList = pWInfo->nLevel;
    assert( nTabList>0 );
  }

  /* Check to see if there are any SEARCH loops that might benefit from







|
|
|
|







168384
168385
168386
168387
168388
168389
168390
168391
168392
168393
168394
168395
168396
168397
168398
168399
168400
168401
  ** procedure to keep the sqlite3WhereBegin() procedure from becoming
  ** too large.  If sqlite3WhereBegin() becomes too large, that prevents
  ** some C-compiler optimizers from in-lining the
  ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
  ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
  */
  notReady = ~(Bitmask)0;
  if( pWInfo->nLevel>=2
   && pResultSet!=0                         /* these two combine to guarantee */
   && 0==(wctrlFlags & WHERE_AGG_DISTINCT)  /* condition (1) above */
   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  ){
    notReady = whereOmitNoopJoin(pWInfo, notReady);
    nTabList = pWInfo->nLevel;
    assert( nTabList>0 );
  }

  /* Check to see if there are any SEARCH loops that might benefit from
169664
169665
169666
169667
169668
169669
169670
169671
169672

169673
169674
169675
169676
169677
169678
169679
        assert( pLevel->iTabCur==pSrc->iCursor );
        if( pSrc->fg.viaCoroutine ){
          int m, n;
          n = pSrc->regResult;
          assert( pSrc->pTab!=0 );
          m = pSrc->pTab->nCol;
          sqlite3VdbeAddOp3(v, OP_Null, 0, n, n+m-1);
        }
        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);

      }
      if( (ws & WHERE_INDEXED)
       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
      ){
        if( ws & WHERE_MULTI_OR ){
          Index *pIx = pLevel->u.pCoveringIdx;
          int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);







|
|
>







168881
168882
168883
168884
168885
168886
168887
168888
168889
168890
168891
168892
168893
168894
168895
168896
168897
        assert( pLevel->iTabCur==pSrc->iCursor );
        if( pSrc->fg.viaCoroutine ){
          int m, n;
          n = pSrc->regResult;
          assert( pSrc->pTab!=0 );
          m = pSrc->pTab->nCol;
          sqlite3VdbeAddOp3(v, OP_Null, 0, n, n+m-1);
        }else{
          sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
        }
      }
      if( (ws & WHERE_INDEXED)
       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
      ){
        if( ws & WHERE_MULTI_OR ){
          Index *pIx = pLevel->u.pCoveringIdx;
          int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
170764
170765
170766
170767
170768
170769
170770
170771
170772
170773
170774
170775
170776
170777
170778
        sqlite3ExprDelete(db, pDup);
        break;
      }
      if( bIntToNull ){
        int iDummy;
        Expr *pSub;
        pSub = sqlite3ExprSkipCollateAndLikely(pDup);
        if( sqlite3ExprIsInteger(pSub, &iDummy, 0) ){
          pSub->op = TK_NULL;
          pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
          pSub->u.zToken = 0;
        }
      }
      pList = sqlite3ExprListAppend(pParse, pList, pDup);
      if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;







|







169982
169983
169984
169985
169986
169987
169988
169989
169990
169991
169992
169993
169994
169995
169996
        sqlite3ExprDelete(db, pDup);
        break;
      }
      if( bIntToNull ){
        int iDummy;
        Expr *pSub;
        pSub = sqlite3ExprSkipCollateAndLikely(pDup);
        if( sqlite3ExprIsInteger(pSub, &iDummy) ){
          pSub->op = TK_NULL;
          pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
          pSub->u.zToken = 0;
        }
      }
      pList = sqlite3ExprListAppend(pParse, pList, pDup);
      if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;
173241
173242
173243
173244
173245
173246
173247
173248
173249
173250
173251
173252
173253
173254
173255
173256
173257
173258
173259
173260
173261
173262
173263
173264
173265
173266
173267
173268
173269
173270
173271
173272
173273
173274
173275
173276
173277
173278
173279
173280
173281
173282
173283
173284
173285
173286
173287
173288
173289
173290
173291
173292
173293
173294
173295
173296
173297
173298
173299
173300
173301
173302
173303
173304
173305
173306
173307
173308
173309
173310
173311
173312
173313
173314
173315
173316
173317
173318
173319
173320
173321
173322
173323
173324
173325
173326
173327
173328
173329
173330
173331
173332
173333
173334
173335
173336
173337
173338
173339
173340
173341
173342
173343
173344
173345
173346
173347
173348
173349
173350
173351
173352
173353
173354
173355
173356
173357
173358
173359
173360
173361
173362
173363
173364
173365
173366
173367
173368
173369
173370
173371
173372
173373

173374
173375
173376
173377
173378
173379
173380
173381
173382
173383
#define TK_DESC                           39
#define TK_DETACH                         40
#define TK_EACH                           41
#define TK_FAIL                           42
#define TK_OR                             43
#define TK_AND                            44
#define TK_IS                             45
#define TK_ISNOT                          46
#define TK_MATCH                          47
#define TK_LIKE_KW                        48
#define TK_BETWEEN                        49
#define TK_IN                             50
#define TK_ISNULL                         51
#define TK_NOTNULL                        52
#define TK_NE                             53
#define TK_EQ                             54
#define TK_GT                             55
#define TK_LE                             56
#define TK_LT                             57
#define TK_GE                             58
#define TK_ESCAPE                         59
#define TK_ID                             60
#define TK_COLUMNKW                       61
#define TK_DO                             62
#define TK_FOR                            63
#define TK_IGNORE                         64
#define TK_INITIALLY                      65
#define TK_INSTEAD                        66
#define TK_NO                             67
#define TK_KEY                            68
#define TK_OF                             69
#define TK_OFFSET                         70
#define TK_PRAGMA                         71
#define TK_RAISE                          72
#define TK_RECURSIVE                      73
#define TK_REPLACE                        74
#define TK_RESTRICT                       75
#define TK_ROW                            76
#define TK_ROWS                           77
#define TK_TRIGGER                        78
#define TK_VACUUM                         79
#define TK_VIEW                           80
#define TK_VIRTUAL                        81
#define TK_WITH                           82
#define TK_NULLS                          83
#define TK_FIRST                          84
#define TK_LAST                           85
#define TK_CURRENT                        86
#define TK_FOLLOWING                      87
#define TK_PARTITION                      88
#define TK_PRECEDING                      89
#define TK_RANGE                          90
#define TK_UNBOUNDED                      91
#define TK_EXCLUDE                        92
#define TK_GROUPS                         93
#define TK_OTHERS                         94
#define TK_TIES                           95
#define TK_GENERATED                      96
#define TK_ALWAYS                         97
#define TK_MATERIALIZED                   98
#define TK_REINDEX                        99
#define TK_RENAME                         100
#define TK_CTIME_KW                       101
#define TK_ANY                            102
#define TK_BITAND                         103
#define TK_BITOR                          104
#define TK_LSHIFT                         105
#define TK_RSHIFT                         106
#define TK_PLUS                           107
#define TK_MINUS                          108
#define TK_STAR                           109
#define TK_SLASH                          110
#define TK_REM                            111
#define TK_CONCAT                         112
#define TK_PTR                            113
#define TK_COLLATE                        114
#define TK_BITNOT                         115
#define TK_ON                             116
#define TK_INDEXED                        117
#define TK_STRING                         118
#define TK_JOIN_KW                        119
#define TK_CONSTRAINT                     120
#define TK_DEFAULT                        121
#define TK_NULL                           122
#define TK_PRIMARY                        123
#define TK_UNIQUE                         124
#define TK_CHECK                          125
#define TK_REFERENCES                     126
#define TK_AUTOINCR                       127
#define TK_INSERT                         128
#define TK_DELETE                         129
#define TK_UPDATE                         130
#define TK_SET                            131
#define TK_DEFERRABLE                     132
#define TK_FOREIGN                        133
#define TK_DROP                           134
#define TK_UNION                          135
#define TK_ALL                            136
#define TK_EXCEPT                         137
#define TK_INTERSECT                      138
#define TK_SELECT                         139
#define TK_VALUES                         140
#define TK_DISTINCT                       141
#define TK_DOT                            142
#define TK_FROM                           143
#define TK_JOIN                           144
#define TK_USING                          145
#define TK_ORDER                          146
#define TK_GROUP                          147
#define TK_HAVING                         148
#define TK_LIMIT                          149
#define TK_WHERE                          150
#define TK_RETURNING                      151
#define TK_INTO                           152
#define TK_NOTHING                        153
#define TK_FLOAT                          154
#define TK_BLOB                           155
#define TK_INTEGER                        156
#define TK_VARIABLE                       157
#define TK_CASE                           158
#define TK_WHEN                           159
#define TK_THEN                           160
#define TK_ELSE                           161
#define TK_INDEX                          162
#define TK_ALTER                          163
#define TK_ADD                            164
#define TK_WINDOW                         165
#define TK_OVER                           166
#define TK_FILTER                         167
#define TK_COLUMN                         168
#define TK_AGG_FUNCTION                   169
#define TK_AGG_COLUMN                     170
#define TK_TRUEFALSE                      171

#define TK_FUNCTION                       172
#define TK_UPLUS                          173
#define TK_UMINUS                         174
#define TK_TRUTH                          175
#define TK_REGISTER                       176
#define TK_VECTOR                         177
#define TK_SELECT_COLUMN                  178
#define TK_IF_NULL_ROW                    179
#define TK_ASTERISK                       180
#define TK_SPAN                           181







<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>

|
|







172459
172460
172461
172462
172463
172464
172465

172466
172467
172468
172469
172470
172471
172472
172473
172474
172475
172476
172477
172478
172479
172480
172481
172482
172483
172484
172485
172486
172487
172488
172489
172490
172491
172492
172493
172494
172495
172496
172497
172498
172499
172500
172501
172502
172503
172504
172505
172506
172507
172508
172509
172510
172511
172512
172513
172514
172515
172516
172517
172518
172519
172520
172521
172522
172523
172524
172525
172526
172527
172528
172529
172530
172531
172532
172533
172534
172535
172536
172537
172538
172539
172540
172541
172542
172543
172544
172545
172546
172547
172548
172549
172550
172551
172552
172553
172554
172555
172556
172557
172558
172559
172560
172561
172562
172563
172564
172565
172566
172567
172568
172569
172570
172571
172572
172573
172574
172575
172576
172577
172578
172579
172580
172581
172582
172583
172584
172585
172586
172587
172588
172589
172590
172591
172592
172593
172594
172595
172596
172597
172598
172599
172600
172601
#define TK_DESC                           39
#define TK_DETACH                         40
#define TK_EACH                           41
#define TK_FAIL                           42
#define TK_OR                             43
#define TK_AND                            44
#define TK_IS                             45

#define TK_MATCH                          46
#define TK_LIKE_KW                        47
#define TK_BETWEEN                        48
#define TK_IN                             49
#define TK_ISNULL                         50
#define TK_NOTNULL                        51
#define TK_NE                             52
#define TK_EQ                             53
#define TK_GT                             54
#define TK_LE                             55
#define TK_LT                             56
#define TK_GE                             57
#define TK_ESCAPE                         58
#define TK_ID                             59
#define TK_COLUMNKW                       60
#define TK_DO                             61
#define TK_FOR                            62
#define TK_IGNORE                         63
#define TK_INITIALLY                      64
#define TK_INSTEAD                        65
#define TK_NO                             66
#define TK_KEY                            67
#define TK_OF                             68
#define TK_OFFSET                         69
#define TK_PRAGMA                         70
#define TK_RAISE                          71
#define TK_RECURSIVE                      72
#define TK_REPLACE                        73
#define TK_RESTRICT                       74
#define TK_ROW                            75
#define TK_ROWS                           76
#define TK_TRIGGER                        77
#define TK_VACUUM                         78
#define TK_VIEW                           79
#define TK_VIRTUAL                        80
#define TK_WITH                           81
#define TK_NULLS                          82
#define TK_FIRST                          83
#define TK_LAST                           84
#define TK_CURRENT                        85
#define TK_FOLLOWING                      86
#define TK_PARTITION                      87
#define TK_PRECEDING                      88
#define TK_RANGE                          89
#define TK_UNBOUNDED                      90
#define TK_EXCLUDE                        91
#define TK_GROUPS                         92
#define TK_OTHERS                         93
#define TK_TIES                           94
#define TK_GENERATED                      95
#define TK_ALWAYS                         96
#define TK_MATERIALIZED                   97
#define TK_REINDEX                        98
#define TK_RENAME                         99
#define TK_CTIME_KW                       100
#define TK_ANY                            101
#define TK_BITAND                         102
#define TK_BITOR                          103
#define TK_LSHIFT                         104
#define TK_RSHIFT                         105
#define TK_PLUS                           106
#define TK_MINUS                          107
#define TK_STAR                           108
#define TK_SLASH                          109
#define TK_REM                            110
#define TK_CONCAT                         111
#define TK_PTR                            112
#define TK_COLLATE                        113
#define TK_BITNOT                         114
#define TK_ON                             115
#define TK_INDEXED                        116
#define TK_STRING                         117
#define TK_JOIN_KW                        118
#define TK_CONSTRAINT                     119
#define TK_DEFAULT                        120
#define TK_NULL                           121
#define TK_PRIMARY                        122
#define TK_UNIQUE                         123
#define TK_CHECK                          124
#define TK_REFERENCES                     125
#define TK_AUTOINCR                       126
#define TK_INSERT                         127
#define TK_DELETE                         128
#define TK_UPDATE                         129
#define TK_SET                            130
#define TK_DEFERRABLE                     131
#define TK_FOREIGN                        132
#define TK_DROP                           133
#define TK_UNION                          134
#define TK_ALL                            135
#define TK_EXCEPT                         136
#define TK_INTERSECT                      137
#define TK_SELECT                         138
#define TK_VALUES                         139
#define TK_DISTINCT                       140
#define TK_DOT                            141
#define TK_FROM                           142
#define TK_JOIN                           143
#define TK_USING                          144
#define TK_ORDER                          145
#define TK_GROUP                          146
#define TK_HAVING                         147
#define TK_LIMIT                          148
#define TK_WHERE                          149
#define TK_RETURNING                      150
#define TK_INTO                           151
#define TK_NOTHING                        152
#define TK_FLOAT                          153
#define TK_BLOB                           154
#define TK_INTEGER                        155
#define TK_VARIABLE                       156
#define TK_CASE                           157
#define TK_WHEN                           158
#define TK_THEN                           159
#define TK_ELSE                           160
#define TK_INDEX                          161
#define TK_ALTER                          162
#define TK_ADD                            163
#define TK_WINDOW                         164
#define TK_OVER                           165
#define TK_FILTER                         166
#define TK_COLUMN                         167
#define TK_AGG_FUNCTION                   168
#define TK_AGG_COLUMN                     169
#define TK_TRUEFALSE                      170
#define TK_ISNOT                          171
#define TK_FUNCTION                       172
#define TK_UMINUS                         173
#define TK_UPLUS                          174
#define TK_TRUTH                          175
#define TK_REGISTER                       176
#define TK_VECTOR                         177
#define TK_SELECT_COLUMN                  178
#define TK_IF_NULL_ROW                    179
#define TK_ASTERISK                       180
#define TK_SPAN                           181
173447
173448
173449
173450
173451
173452
173453
173454
173455
173456
173457
173458
173459
173460
173461
#ifndef INTERFACE
# define INTERFACE 1
#endif
/************* Begin control #defines *****************************************/
#define YYCODETYPE unsigned short int
#define YYNOCODE 322
#define YYACTIONTYPE unsigned short int
#define YYWILDCARD 102
#define sqlite3ParserTOKENTYPE Token
typedef union {
  int yyinit;
  sqlite3ParserTOKENTYPE yy0;
  ExprList* yy14;
  With* yy59;
  Cte* yy67;







|







172665
172666
172667
172668
172669
172670
172671
172672
172673
172674
172675
172676
172677
172678
172679
#ifndef INTERFACE
# define INTERFACE 1
#endif
/************* Begin control #defines *****************************************/
#define YYCODETYPE unsigned short int
#define YYNOCODE 322
#define YYACTIONTYPE unsigned short int
#define YYWILDCARD 101
#define sqlite3ParserTOKENTYPE Token
typedef union {
  int yyinit;
  sqlite3ParserTOKENTYPE yy0;
  ExprList* yy14;
  With* yy59;
  Cte* yy67;
173584
173585
173586
173587
173588
173589
173590
173591
173592
173593
173594
173595
173596
173597
173598
173599
173600
173601
173602
173603
173604
173605
173606
173607
173608
173609
173610
173611
173612
173613
173614
173615
173616
173617
173618
173619
173620



173621
173622
173623
173624
173625
173626
173627
173628
173629
173630
173631
173632
173633
173634
173635
173636
173637
173638
173639
173640
173641
173642
173643
173644
173645
173646
173647
173648
173649

173650
173651
173652
173653
173654
173655
173656
173657

173658
173659
173660
173661
173662
173663
173664
173665
173666
173667
173668
173669
173670
173671
173672

173673
173674
173675
173676
173677
173678
173679
173680
173681
173682
173683
173684
173685
173686
173687
173688
173689
173690
173691
173692
173693
173694
173695
173696
173697
173698
173699
173700
173701
173702
173703
173704
173705
173706
173707
173708
173709
173710
173711
173712
173713
173714
173715
173716
173717
173718
173719
173720
173721
173722
173723
173724
173725
173726
173727
173728
173729
173730
173731
173732
173733
173734
173735


173736

173737
173738
173739
173740
173741
173742
173743
173744
173745
173746
173747
173748
173749
173750
173751
173752
173753
173754
173755
173756
173757
173758
















173759
173760
173761
173762
173763
173764
173765
173766
173767
173768
173769
173770
173771
173772
173773
173774
173775
173776
173777
173778
173779
173780
173781
173782
173783
173784
173785











173786
173787
173788
173789
173790
173791
173792
173793
173794
173795
173796
173797
173798
173799
173800
173801
173802
173803
173804
173805
173806
173807
173808
173809
173810
173811
173812
173813
173814
173815
173816
173817
173818
173819
173820
173821
173822
173823
173824
173825
173826
173827
173828
173829
173830
173831
173832
173833
173834
173835
173836
173837
173838
173839
173840
173841
173842
173843
173844
173845
173846
173847



173848
173849
173850

173851
173852
173853
173854


173855
173856
173857
173858
173859
173860
173861
173862
173863
173864
173865
173866
173867
173868
173869
173870


173871
173872
173873
173874
173875
173876
173877
173878
173879
173880
173881
173882
173883
173884
173885
173886

173887
173888
173889
173890
173891
173892
173893
173894
173895

173896
173897
173898


173899
173900
173901
173902
173903
173904
173905
173906
173907
173908
173909
173910
173911
173912
173913
173914
173915
173916
173917
173918
173919
173920
173921
173922
173923
173924
173925
173926
173927
173928
173929
173930
173931

173932
173933
173934
173935
173936
173937
173938
173939
173940
173941
173942
173943
173944
173945
173946
173947
173948
173949
173950
173951
173952
173953
173954
173955
173956

173957









173958
173959
173960
173961
173962
173963
173964
173965
173966
173967
173968
173969
173970
173971
173972
173973
173974
173975
173976
173977
173978
173979
173980
173981
173982
173983
173984
173985

173986
173987
173988
173989
173990
173991
173992
173993
173994
173995
173996
173997
173998
173999
174000
174001
174002
174003
174004
174005
174006
174007
174008
174009
174010
174011
174012
174013
174014
174015
174016
174017
174018
174019
174020
174021
174022
174023
174024
174025
174026
174027
174028
174029
174030
174031
174032
174033
174034
174035
174036
174037
174038
174039
174040
174041
174042
174043
174044
174045
174046
174047
174048
174049
174050
174051
174052
174053
174054
174055
174056
174057
174058
174059
174060
174061
174062
174063
174064
174065
174066
174067
174068
174069
174070
174071
174072
174073
174074
174075
174076
174077
174078
174079
174080
174081
174082
174083
174084
174085
174086
174087
174088
174089
174090
174091
174092
174093
174094
174095
174096
174097
174098
174099
174100
174101
174102
174103
174104
174105
174106
174107
174108
174109
174110
174111
174112
174113
174114
174115
174116
174117
174118
174119
174120
174121
174122
174123
174124
174125
174126
174127
174128
174129
174130
174131
174132
174133
174134
174135
174136
174137
174138
174139
174140
174141
174142
174143
174144
174145
174146
174147
174148
174149
174150
174151
174152
174153
174154
174155
174156
174157
174158
174159
174160
174161
174162
174163
174164
174165
174166
174167
174168
174169
174170
174171
174172
174173
174174
174175
174176
174177
174178
174179
174180
174181
174182
174183
174184
174185
174186
174187
174188
174189
174190
174191
174192
174193
174194
174195
174196
174197
174198
174199
174200
174201
174202
174203
174204
174205
174206
174207
174208
174209
174210
174211
174212
174213
174214
174215
174216
174217
174218
174219
174220
174221
174222
174223
174224
174225
174226
174227
174228
174229
174230
174231
174232
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
**
*********** Begin parsing tables **********************************************/
#define YY_ACTTAB_COUNT (2207)
static const YYACTIONTYPE yy_action[] = {
 /*     0 */   130,  127,  234,  282,  282, 1328,  576, 1307,  460,  289,
 /*    10 */   289,  576, 1622,  381,  576, 1328,  573,  576,  562,  413,
 /*    20 */  1300, 1542,  573,  481,  562,  524,  460,  459,  558,   82,
 /*    30 */    82,  983,  294,  375,   51,   51,  498,   61,   61,  984,
 /*    40 */    82,   82, 1577,  137,  138,   91,    7, 1228, 1228, 1063,
 /*    50 */  1066, 1053, 1053,  135,  135,  136,  136,  136,  136,  413,
 /*    60 */   288,  288,  182,  288,  288,  481,  536,  288,  288,  130,
 /*    70 */   127,  234,  432,  573,  525,  562,  573,  557,  562, 1290,
 /*    80 */   573,  421,  562,  137,  138,   91,  559, 1228, 1228, 1063,
 /*    90 */  1066, 1053, 1053,  135,  135,  136,  136,  136,  136,  296,
 /*   100 */   460,  398, 1249,  134,  134,  134,  134,  133,  133,  132,
 /*   110 */   132,  132,  131,  128,  451,   44, 1050, 1050, 1064, 1067,
 /*   120 */  1255,    1,    1,  582,    2, 1259,  581, 1174, 1259, 1174,
 /*   130 */   321,  413,  155,  321, 1584,  155,  379,  112,  498, 1341,
 /*   140 */   456,  299, 1341,  134,  134,  134,  134,  133,  133,  132,
 /*   150 */   132,  132,  131,  128,  451,  137,  138,   91, 1105, 1228,
 /*   160 */  1228, 1063, 1066, 1053, 1053,  135,  135,  136,  136,  136,
 /*   170 */   136, 1204,  320,  567,  288,  288,  283,  288,  288,  523,
 /*   180 */   523, 1250,  139, 1541,    7,  214,  503,  573, 1169,  562,
 /*   190 */   573, 1054,  562,  136,  136,  136,  136,  129,  401,  547,
 /*   200 */   487, 1169,  245, 1568, 1169,  245,  133,  133,  132,  132,
 /*   210 */   132,  131,  128,  451,  261,  134,  134,  134,  134,  133,
 /*   220 */   133,  132,  132,  132,  131,  128,  451,  451, 1204, 1205,
 /*   230 */  1204,  130,  127,  234,  455,  413,  182,  455,  130,  127,
 /*   240 */   234,  134,  134,  134,  134,  133,  133,  132,  132,  132,
 /*   250 */   131,  128,  451,  136,  136,  136,  136,  538,  576,  137,
 /*   260 */   138,   91,  261, 1228, 1228, 1063, 1066, 1053, 1053,  135,
 /*   270 */   135,  136,  136,  136,  136,   44,  472,  346, 1204,  472,



 /*   280 */   346,   51,   51,  418,   93,  157,  134,  134,  134,  134,
 /*   290 */   133,  133,  132,  132,  132,  131,  128,  451,  166,  363,
 /*   300 */   298,  134,  134,  134,  134,  133,  133,  132,  132,  132,
 /*   310 */   131,  128,  451, 1293,  461, 1570,  423,  377,  275,  134,
 /*   320 */   134,  134,  134,  133,  133,  132,  132,  132,  131,  128,
 /*   330 */   451,  418,  320,  567, 1292, 1204, 1205, 1204,  257,  413,
 /*   340 */   483,  511,  508,  507,   94,  132,  132,  132,  131,  128,
 /*   350 */   451,  506, 1204,  548,  548,  388,  576,  384,    7,  413,
 /*   360 */   550,  229,  522,  137,  138,   91,  530, 1228, 1228, 1063,
 /*   370 */  1066, 1053, 1053,  135,  135,  136,  136,  136,  136,   51,
 /*   380 */    51, 1582,  380,  137,  138,   91,  331, 1228, 1228, 1063,
 /*   390 */  1066, 1053, 1053,  135,  135,  136,  136,  136,  136,  320,
 /*   400 */   567,  288,  288,  320,  567, 1602,  582,    2, 1259, 1204,
 /*   410 */  1205, 1204, 1628,  321,  573,  155,  562,  576, 1511,  264,
 /*   420 */   231,  520, 1341,  134,  134,  134,  134,  133,  133,  132,
 /*   430 */   132,  132,  131,  128,  451,  519, 1511, 1513, 1333, 1333,
 /*   440 */    82,   82,  498,  134,  134,  134,  134,  133,  133,  132,
 /*   450 */   132,  132,  131,  128,  451, 1435,  257,  288,  288,  511,
 /*   460 */   508,  507,  944, 1568,  413, 1019, 1204,  943,  360,  506,
 /*   470 */   573, 1598,  562,   44,  575,  551,  551,  557, 1107, 1582,
 /*   480 */   544,  576, 1107,   40,  417,  245,  531, 1505,  137,  138,
 /*   490 */    91,  219, 1228, 1228, 1063, 1066, 1053, 1053,  135,  135,
 /*   500 */   136,  136,  136,  136,   81,   81, 1281, 1204,  413,  553,
 /*   510 */  1511,   48,  512,  448,  447,  493,  578,  455,  578,  344,
 /*   520 */    45, 1204, 1233, 1204, 1205, 1204,  428, 1235,  158,  882,
 /*   530 */   320,  567,  137,  138,   91, 1234, 1228, 1228, 1063, 1066,
 /*   540 */  1053, 1053,  135,  135,  136,  136,  136,  136,  134,  134,
 /*   550 */   134,  134,  133,  133,  132,  132,  132,  131,  128,  451,
 /*   560 */  1236,  576, 1236,  329, 1204, 1205, 1204,  387,  492,  403,

 /*   570 */  1040,  382,  489,  123,  568, 1569,    4,  377, 1204, 1205,
 /*   580 */  1204,  570,  570,  570,   82,   82,  882, 1029, 1331, 1331,
 /*   590 */   571, 1028,  134,  134,  134,  134,  133,  133,  132,  132,
 /*   600 */   132,  131,  128,  451,  288,  288, 1281, 1204,  576,  423,
 /*   610 */   576, 1568,  413,  423,  452,  378,  886,  573, 1279,  562,
 /*   620 */    46,  557,  532, 1028, 1028, 1030,  565,  130,  127,  234,
 /*   630 */   556,   82,   82,   82,   82,  479,  137,  138,   91,  462,
 /*   640 */  1228, 1228, 1063, 1066, 1053, 1053,  135,  135,  136,  136,

 /*   650 */   136,  136, 1188,  487, 1506, 1040,  413,    6, 1204,   50,
 /*   660 */   879,  121,  121,  948, 1204, 1205, 1204,  358,  557,  122,
 /*   670 */   316,  452,  577,  452,  535, 1204, 1028,  439,  303,  212,
 /*   680 */   137,  138,   91,  213, 1228, 1228, 1063, 1066, 1053, 1053,
 /*   690 */   135,  135,  136,  136,  136,  136,  134,  134,  134,  134,
 /*   700 */   133,  133,  132,  132,  132,  131,  128,  451, 1028, 1028,
 /*   710 */  1030, 1031,   35,  288,  288, 1204, 1205, 1204, 1040, 1339,
 /*   720 */   533,  123,  568, 1569,    4,  377,  573, 1019,  562,  353,
 /*   730 */  1277,  356, 1204, 1205, 1204, 1029,  488, 1188,  571, 1028,
 /*   740 */   134,  134,  134,  134,  133,  133,  132,  132,  132,  131,
 /*   750 */   128,  451,  576,  343,  288,  288,  449,  449,  449,  971,
 /*   760 */   413, 1627,  452,  911, 1187,  288,  288,  573,  464,  562,
 /*   770 */   238, 1028, 1028, 1030,  565,   82,   82,  498,  573,  411,
 /*   780 */   562,  344,  467,  332,  137,  138,   91,  197, 1228, 1228,
 /*   790 */  1063, 1066, 1053, 1053,  135,  135,  136,  136,  136,  136,

 /*   800 */  1188,  528, 1169, 1040,  413, 1110, 1110,  495, 1041,  121,
 /*   810 */   121, 1204,  317,  540,  862, 1169, 1244,  122, 1169,  452,
 /*   820 */   577,  452, 1340,  198, 1028, 1204,  481,  526,  137,  138,
 /*   830 */    91,  560, 1228, 1228, 1063, 1066, 1053, 1053,  135,  135,
 /*   840 */   136,  136,  136,  136,  134,  134,  134,  134,  133,  133,
 /*   850 */   132,  132,  132,  131,  128,  451, 1028, 1028, 1030, 1031,
 /*   860 */    35, 1204,  288,  288, 1204,  477,  288,  288, 1204, 1205,
 /*   870 */  1204,  539,  481,  437,  470,  573, 1451,  562,  364,  573,
 /*   880 */  1153,  562, 1204, 1205, 1204, 1188,    5,  576,  134,  134,
 /*   890 */   134,  134,  133,  133,  132,  132,  132,  131,  128,  451,
 /*   900 */   221,  214,  302,   96, 1149, 1657,  232, 1657,  413,  392,
 /*   910 */    19,   19, 1024,  949,  406,  373, 1595, 1085, 1204, 1205,
 /*   920 */  1204, 1204, 1205, 1204, 1204,  426, 1149, 1658,  413, 1658,
 /*   930 */  1659,  399,  137,  138,   91,    3, 1228, 1228, 1063, 1066,
 /*   940 */  1053, 1053,  135,  135,  136,  136,  136,  136,  304, 1311,
 /*   950 */   514, 1204,  137,  138,   91, 1498, 1228, 1228, 1063, 1066,
 /*   960 */  1053, 1053,  135,  135,  136,  136,  136,  136,  434,  131,
 /*   970 */   128,  451,  375, 1204,  274,  291,  372,  517,  367,  516,
 /*   980 */   262, 1204, 1205, 1204, 1147,  227,  363,  448,  447, 1435,
 /*   990 */  1568, 1310,  134,  134,  134,  134,  133,  133,  132,  132,
 /*  1000 */   132,  131,  128,  451, 1568,  576, 1147,  487, 1204, 1205,
 /*  1010 */  1204,  442,  134,  134,  134,  134,  133,  133,  132,  132,
 /*  1020 */   132,  131,  128,  451,  386,  576,  485,  576,   19,   19,
 /*  1030 */  1204, 1205, 1204, 1345, 1236,  970, 1236,  574,   47,  936,
 /*  1040 */   936,  473,  413,  431, 1552,  573, 1125,  562,   19,   19,
 /*  1050 */    19,   19,   49,  336,  850,  851,  852,  111, 1368,  315,
 /*  1060 */   429,  576,  413,  433,  341,  306,  137,  138,   91,  115,
 /*  1070 */  1228, 1228, 1063, 1066, 1053, 1053,  135,  135,  136,  136,
 /*  1080 */   136,  136,  576, 1309,   82,   82,  137,  138,   91,  529,
 /*  1090 */  1228, 1228, 1063, 1066, 1053, 1053,  135,  135,  136,  136,
 /*  1100 */   136,  136, 1569,  222,  377,   19,   19,  305, 1126, 1169,
 /*  1110 */   398, 1148,   22,   22,  498,  333, 1569,  335,  377,  576,
 /*  1120 */   438,  445, 1169, 1127,  486, 1169,  134,  134,  134,  134,
 /*  1130 */   133,  133,  132,  132,  132,  131,  128,  451, 1128,  576,
 /*  1140 */   902,  576,  145,  145,    6,  576,  134,  134,  134,  134,
 /*  1150 */   133,  133,  132,  132,  132,  131,  128,  451,  214, 1336,
 /*  1160 */   922,  576,   19,   19,   19,   19, 1282,  419,   19,   19,
 /*  1170 */   923,  412,  515,  141,  576, 1169,  413,  206,  465,  207,
 /*  1180 */   903,  215, 1575,  552,  147,  147,    7,  227, 1169,  411,
 /*  1190 */  1250, 1169,  120,  307,  117,  307,  413,   66,   66,  334,
 /*  1200 */   137,  138,   91,  119, 1228, 1228, 1063, 1066, 1053, 1053,
 /*  1210 */   135,  135,  136,  136,  136,  136,  413,  285,  209,  969,
 /*  1220 */   137,  138,   91,  471, 1228, 1228, 1063, 1066, 1053, 1053,
 /*  1230 */   135,  135,  136,  136,  136,  136,  435,   10, 1450,  267,
 /*  1240 */   137,  126,   91, 1435, 1228, 1228, 1063, 1066, 1053, 1053,
 /*  1250 */   135,  135,  136,  136,  136,  136, 1435, 1435,  410,  409,
 /*  1260 */   134,  134,  134,  134,  133,  133,  132,  132,  132,  131,
 /*  1270 */   128,  451,  576,  969,  576, 1224,  498,  373, 1595, 1554,
 /*  1280 */   134,  134,  134,  134,  133,  133,  132,  132,  132,  131,
 /*  1290 */   128,  451,  532,  457,  576,   82,   82,   82,   82,  111,
 /*  1300 */   134,  134,  134,  134,  133,  133,  132,  132,  132,  131,
 /*  1310 */   128,  451,  109,  233,  430, 1576,  546,   67,   67,    7,
 /*  1320 */   413,  351,  550, 1550,  260,  259,  258,  494,  443,  569,
 /*  1330 */   419,  983,  446, 1224,  450,  545, 1207,  576,  969,  984,
 /*  1340 */   413,  475, 1449, 1574, 1180,  138,   91,    7, 1228, 1228,
 /*  1350 */  1063, 1066, 1053, 1053,  135,  135,  136,  136,  136,  136,
 /*  1360 */    21,   21,  267,  576,  300, 1126,   91,  233, 1228, 1228,
 /*  1370 */  1063, 1066, 1053, 1053,  135,  135,  136,  136,  136,  136,
 /*  1380 */  1127,  373, 1595,  161, 1573,   16,   53,   53,    7,  108,
 /*  1390 */   533,   38,  969,  125, 1207, 1128, 1180,  576, 1224,  123,
 /*  1400 */   568,  893,    4,  324,  134,  134,  134,  134,  133,  133,
 /*  1410 */   132,  132,  132,  131,  128,  451,  571,  564,  534,  576,
 /*  1420 */    68,   68,  576,   39,  134,  134,  134,  134,  133,  133,


 /*  1430 */   132,  132,  132,  131,  128,  451,  576,  160, 1571, 1223,

 /*  1440 */   452,  576,   54,   54,  576,   69,   69,  576, 1366,  576,
 /*  1450 */   420,  184,  565,  463,  297,  576, 1224,  463,  297,   70,
 /*  1460 */    70,  576,   44,  474,   71,   71,  576,   72,   72,  576,
 /*  1470 */    73,   73,   55,   55,  411,  874,  242,  576,   56,   56,
 /*  1480 */   576, 1040,  576,  478,   57,   57,  576,  121,  121,   59,
 /*  1490 */    59,   23,   60,   60,  411,  122,  319,  452,  577,  452,
 /*  1500 */    74,   74, 1028,   75,   75,   76,   76,  411,  290,   20,
 /*  1510 */    20,  108,  287,  231,  553,  123,  568,  325,    4,  320,
 /*  1520 */   567,   97,  218,  944, 1144,  328,  400,  576,  943,  576,
 /*  1530 */  1380,  424,  571,  874, 1028, 1028, 1030, 1031,   35,  293,
 /*  1540 */   534,  576, 1104,  576, 1104,    9,  576,  342,  576,  111,
 /*  1550 */    77,   77,  143,  143,  576,  205,  452,  222, 1379,  889,
 /*  1560 */   576,  901,  900, 1188,  144,  144,   78,   78,  565,   62,
 /*  1570 */    62,   79,   79,  323, 1021,  576,  266,   63,   63,  908,
 /*  1580 */   909, 1589,  542,   80,   80,  576,  371,  541,  123,  568,
 /*  1590 */   480,    4,  266,  482,  244,  266,  370, 1040,   64,   64,
 /*  1600 */   576,  466,  576,  121,  121,  571, 1557,  576,  170,  170,
 /*  1610 */   576,  122,  576,  452,  577,  452,  576,  889, 1028,  576,
 /*  1620 */   165,  576,  111,  171,  171,   87,   87,  337, 1616,  452,
 /*  1630 */    65,   65, 1530,   83,   83,  146,  146,  986,  987,   84,
 /*  1640 */    84,  565,  168,  168,  148,  148, 1092,  347, 1032,  111,
 /*  1650 */  1028, 1028, 1030, 1031,   35,  542, 1103,  576, 1103,  576,
















 /*  1660 */   543,  123,  568,  504,    4,  263,  576,  361, 1529,  111,
 /*  1670 */  1040, 1088,  576,  263,  576,  490,  121,  121,  571, 1188,
 /*  1680 */   142,  142,  169,  169,  122,  576,  452,  577,  452,  162,
 /*  1690 */   162, 1028,  576,  563,  576,  152,  152,  151,  151,  348,
 /*  1700 */  1376,  974,  452,  266, 1092,  942, 1032,  125,  149,  149,
 /*  1710 */   939,  576,  125,  576,  565,  150,  150,   86,   86,  872,
 /*  1720 */   352,  159,  576, 1028, 1028, 1030, 1031,   35,  542,  941,
 /*  1730 */   576,  125,  355,  541,   88,   88,   85,   85,  357,  359,
 /*  1740 */  1324, 1308,  366, 1040,  376,   52,   52,  499, 1389,  121,
 /*  1750 */   121, 1434, 1188,   58,   58, 1362, 1374,  122, 1439,  452,
 /*  1760 */   577,  452, 1289,  167, 1028, 1280,  280, 1268, 1267, 1269,
 /*  1770 */  1609, 1359,  312,  313,   12,  314,  397, 1421,  224, 1416,
 /*  1780 */   295,  237, 1409,  339,  340, 1426,  301,  345,  484,  228,
 /*  1790 */  1371, 1307, 1372, 1370, 1425,  404, 1028, 1028, 1030, 1031,
 /*  1800 */    35, 1601, 1192,  454,  509,  369,  292, 1502,  210, 1501,
 /*  1810 */  1369,  396,  396,  395,  277,  393,  211,  566,  859, 1612,
 /*  1820 */  1244,  123,  568,  391,    4, 1188,  223,  270, 1549, 1547,
 /*  1830 */  1241,  239,  186,  327,  422,   96,  195,  220,  571,  235,
 /*  1840 */   180,  326,  188,  468,  190, 1507,  191,  192,   92,  193,
 /*  1850 */   469,   95, 1422,   13,  502,  247, 1430,  109,  199,  402,
 /*  1860 */   476,  405,  452, 1496, 1428, 1427,   14,  491,  251,  102,
 /*  1870 */   497, 1518,  241,  281,  565,  253,  203,  354,  500,  254,
 /*  1880 */   175, 1270,  407,   43,  350,  518, 1327,  436,  255, 1326,
 /*  1890 */  1325, 1318,  104,  893, 1626,  229,  408,  440, 1625,  441,
 /*  1900 */   240,  310, 1296, 1040,  311, 1317,  527, 1594, 1297,  121,
 /*  1910 */   121,  368, 1295, 1624,  268,  269, 1580,  122, 1579,  452,
 /*  1920 */   577,  452,  374,  444, 1028, 1394, 1393,  140,  553,   90,











 /*  1930 */   568,   11,    4, 1483,  383,  414,  385,  110,  116,  216,
 /*  1940 */   320,  567, 1350,  555,   42,  318,  571,  537, 1349,  389,
 /*  1950 */   390,  579, 1198,  276,  279,  278, 1028, 1028, 1030, 1031,
 /*  1960 */    35,  580,  415, 1265,  458, 1260,  416,  185, 1534,  172,
 /*  1970 */   452, 1535,  173,  156,  308,  846, 1533, 1532,  453,  217,
 /*  1980 */   225,   89,  565,  174,  322, 1188,  226,  236, 1102,  154,
 /*  1990 */  1100,  330,  176,  187, 1223,  189,  925,  338,  243, 1116,
 /*  2000 */   246,  194,  177,  178,  425,  427,   98,   99,  196,  100,
 /*  2010 */   101, 1040,  179, 1119,  248, 1115,  249,  121,  121,   24,
 /*  2020 */   163,  250,  349, 1108,  266,  122, 1238,  452,  577,  452,
 /*  2030 */  1192,  454, 1028,  200,  292,  496,  252,  201,  861,  396,
 /*  2040 */   396,  395,  277,  393,   15,  501,  859,  370,  292,  256,
 /*  2050 */   202,  554,  505,  396,  396,  395,  277,  393,  103,  239,
 /*  2060 */   859,  327,   25,   26, 1028, 1028, 1030, 1031,   35,  326,
 /*  2070 */   362,  510,  891,  239,  365,  327,  513,  904,  105,  309,
 /*  2080 */   164,  181,   27,  326,  106,  521,  107, 1185, 1069, 1155,
 /*  2090 */    17, 1154,  284, 1188,  286,  978,  265,  204,  125, 1171,
 /*  2100 */   241,  230,  972, 1175,   28, 1160,   29, 1179,  175, 1173,
 /*  2110 */    30,   43,   31, 1178,  241,   32,   41,  549,    8,   33,
 /*  2120 */   208,  111,  175, 1083, 1070,   43,  113, 1068,  240,  114,
 /*  2130 */  1072,   34, 1073,  561, 1124,  118,  271,   36,   18, 1194,
 /*  2140 */  1033,  873,  240,  935,  124,   37,  272,  273, 1617,  572,
 /*  2150 */   183,  153,  394, 1193, 1256, 1256, 1256, 1256, 1256, 1256,
 /*  2160 */  1256, 1256, 1256,  414, 1256, 1256, 1256, 1256,  320,  567,
 /*  2170 */  1256, 1256, 1256, 1256, 1256, 1256, 1256,  414, 1256, 1256,
 /*  2180 */  1256, 1256,  320,  567, 1256, 1256, 1256, 1256, 1256, 1256,
 /*  2190 */  1256, 1256,  458, 1256, 1256, 1256, 1256, 1256, 1256, 1256,
 /*  2200 */  1256, 1256, 1256, 1256, 1256, 1256,  458,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */   276,  277,  278,  240,  241,  224,  194,  226,  194,  240,
 /*    10 */   241,  194,  216,  220,  194,  234,  253,  194,  255,   19,
 /*    20 */   224,  297,  253,  194,  255,  205,  212,  213,  205,  217,
 /*    30 */   218,   31,  205,  194,  217,  218,  194,  217,  218,   39,
 /*    40 */   217,  218,  312,   43,   44,   45,  316,   47,   48,   49,
 /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,   58,   19,
 /*    60 */   240,  241,  194,  240,  241,  194,  254,  240,  241,  276,
 /*    70 */   277,  278,  233,  253,  254,  255,  253,  254,  255,  217,
 /*    80 */   253,  239,  255,   43,   44,   45,  263,   47,   48,   49,
 /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,   58,  270,
 /*   100 */   286,   22,   23,  103,  104,  105,  106,  107,  108,  109,
 /*   110 */   110,  111,  112,  113,  114,   82,   47,   48,   49,   50,
 /*   120 */   186,  187,  188,  189,  190,  191,  189,   87,  191,   89,
 /*   130 */   196,   19,  198,  196,  317,  198,  319,   25,  194,  205,
 /*   140 */   298,  270,  205,  103,  104,  105,  106,  107,  108,  109,
 /*   150 */   110,  111,  112,  113,  114,   43,   44,   45,   11,   47,
 /*   160 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   170 */    58,   60,  139,  140,  240,  241,  214,  240,  241,  311,
 /*   180 */   312,  102,   70,  239,  316,  194,   19,  253,   77,  255,
 /*   190 */   253,  122,  255,   55,   56,   57,   58,   59,  207,   88,
 /*   200 */   194,   90,  268,  194,   93,  268,  107,  108,  109,  110,
 /*   210 */   111,  112,  113,  114,   47,  103,  104,  105,  106,  107,
 /*   220 */   108,  109,  110,  111,  112,  113,  114,  114,  117,  118,
 /*   230 */   119,  276,  277,  278,  300,   19,  194,  300,  276,  277,
 /*   240 */   278,  103,  104,  105,  106,  107,  108,  109,  110,  111,
 /*   250 */   112,  113,  114,   55,   56,   57,   58,  146,  194,   43,
 /*   260 */    44,   45,   47,   47,   48,   49,   50,   51,   52,   53,
 /*   270 */    54,   55,   56,   57,   58,   82,  129,  130,   60,  129,
 /*   280 */   130,  217,  218,  116,   68,   25,  103,  104,  105,  106,
 /*   290 */   107,  108,  109,  110,  111,  112,  113,  114,   23,  132,
 /*   300 */   294,  103,  104,  105,  106,  107,  108,  109,  110,  111,
 /*   310 */   112,  113,  114,  217,  121,  306,  194,  308,   26,  103,



 /*   320 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
 /*   330 */   114,  116,  139,  140,  217,  117,  118,  119,  120,   19,
 /*   340 */   194,  123,  124,  125,   24,  109,  110,  111,  112,  113,

 /*   350 */   114,  133,   60,  311,  312,  250,  194,  252,  316,   19,
 /*   360 */   194,  166,  167,   43,   44,   45,  205,   47,   48,   49,
 /*   370 */    50,   51,   52,   53,   54,   55,   56,   57,   58,  217,
 /*   380 */   218,  317,  318,   43,   44,   45,  264,   47,   48,   49,


 /*   390 */    50,   51,   52,   53,   54,   55,   56,   57,   58,  139,
 /*   400 */   140,  240,  241,  139,  140,  188,  189,  190,  191,  117,
 /*   410 */   118,  119,  231,  196,  253,  198,  255,  194,  194,  258,
 /*   420 */   259,  146,  205,  103,  104,  105,  106,  107,  108,  109,
 /*   430 */   110,  111,  112,  113,  114,  109,  212,  213,  236,  237,
 /*   440 */   217,  218,  194,  103,  104,  105,  106,  107,  108,  109,
 /*   450 */   110,  111,  112,  113,  114,  194,  120,  240,  241,  123,
 /*   460 */   124,  125,  136,  194,   19,   74,   60,  141,   23,  133,
 /*   470 */   253,  194,  255,   82,  194,  309,  310,  254,   29,  317,
 /*   480 */   318,  194,   33,   22,  199,  268,  263,  239,   43,   44,
 /*   490 */    45,  151,   47,   48,   49,   50,   51,   52,   53,   54,
 /*   500 */    55,   56,   57,   58,  217,  218,  194,   60,   19,  146,
 /*   510 */   286,  242,   23,  107,  108,   66,  204,  300,  206,  128,
 /*   520 */    73,   60,  116,  117,  118,  119,  265,  121,  165,   60,
 /*   530 */   139,  140,   43,   44,   45,  129,   47,   48,   49,   50,
 /*   540 */    51,   52,   53,   54,   55,   56,   57,   58,  103,  104,


 /*   550 */   105,  106,  107,  108,  109,  110,  111,  112,  113,  114,
 /*   560 */   154,  194,  156,  194,  117,  118,  119,  280,  283,  205,
 /*   570 */   101,  220,  287,   19,   20,  306,   22,  308,  117,  118,
 /*   580 */   119,  211,  212,  213,  217,  218,  117,  118,  236,  237,
 /*   590 */    36,  122,  103,  104,  105,  106,  107,  108,  109,  110,
 /*   600 */   111,  112,  113,  114,  240,  241,  194,   60,  194,  194,
 /*   610 */   194,  194,   19,  194,   60,  194,   23,  253,  206,  255,
 /*   620 */    73,  254,   19,  154,  155,  156,   72,  276,  277,  278,
 /*   630 */   263,  217,  218,  217,  218,  271,   43,   44,   45,  271,
 /*   640 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*   650 */    57,   58,  183,  194,  285,  101,   19,  214,   60,  242,
 /*   660 */    23,  107,  108,  109,  117,  118,  119,   16,  254,  115,
 /*   670 */   254,  117,  118,  119,  194,   60,  122,  263,  205,  264,
 /*   680 */    43,   44,   45,  264,   47,   48,   49,   50,   51,   52,
 /*   690 */    53,   54,   55,   56,   57,   58,  103,  104,  105,  106,
 /*   700 */   107,  108,  109,  110,  111,  112,  113,  114,  154,  155,

 /*   710 */   156,  157,  158,  240,  241,  117,  118,  119,  101,  205,
 /*   720 */   117,   19,   20,  306,   22,  308,  253,   74,  255,   78,
 /*   730 */   205,   80,  117,  118,  119,  118,  293,  183,   36,  122,
 /*   740 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*   750 */   113,  114,  194,  294,  240,  241,  211,  212,  213,  144,
 /*   760 */    19,   23,   60,   25,   23,  240,  241,  253,  245,  255,
 /*   770 */    15,  154,  155,  156,   72,  217,  218,  194,  253,  256,
 /*   780 */   255,  128,  129,  130,   43,   44,   45,   22,   47,   48,
 /*   790 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   58,

 /*   800 */   183,   19,   77,  101,   19,  128,  129,  130,   23,  107,
 /*   810 */   108,   60,  254,   88,   21,   90,   61,  115,   93,  117,
 /*   820 */   118,  119,  239,   22,  122,   60,  194,  205,   43,   44,


 /*   830 */    45,  205,   47,   48,   49,   50,   51,   52,   53,   54,
 /*   840 */    55,   56,   57,   58,  103,  104,  105,  106,  107,  108,
 /*   850 */   109,  110,  111,  112,  113,  114,  154,  155,  156,  157,
 /*   860 */   158,   60,  240,  241,   60,  116,  240,  241,  117,  118,
 /*   870 */   119,  146,  194,   19,   81,  253,  275,  255,   24,  253,
 /*   880 */    98,  255,  117,  118,  119,  183,   22,  194,  103,  104,
 /*   890 */   105,  106,  107,  108,  109,  110,  111,  112,  113,  114,
 /*   900 */   151,  194,  270,  152,   22,   23,  194,   25,   19,  202,
 /*   910 */   217,  218,   23,  109,  207,  314,  315,  124,  117,  118,
 /*   920 */   119,  117,  118,  119,   60,  232,   22,   23,   19,   25,
 /*   930 */   303,  304,   43,   44,   45,   22,   47,   48,   49,   50,
 /*   940 */    51,   52,   53,   54,   55,   56,   57,   58,  270,  227,
 /*   950 */    96,   60,   43,   44,   45,  162,   47,   48,   49,   50,
 /*   960 */    51,   52,   53,   54,   55,   56,   57,   58,  114,  112,
 /*   970 */   113,  114,  194,   60,  120,  121,  122,  123,  124,  125,
 /*   980 */   126,  117,  118,  119,  102,   25,  132,  107,  108,  194,
 /*   990 */   194,  227,  103,  104,  105,  106,  107,  108,  109,  110,
 /*  1000 */   111,  112,  113,  114,  194,  194,  102,  194,  117,  118,
 /*  1010 */   119,  233,  103,  104,  105,  106,  107,  108,  109,  110,
 /*  1020 */   111,  112,  113,  114,  194,  194,   19,  194,  217,  218,
 /*  1030 */   117,  118,  119,  241,  154,  144,  156,  135,  242,  137,
 /*  1040 */   138,  130,   19,  232,  194,  253,   23,  255,  217,  218,
 /*  1050 */   217,  218,  242,   16,    7,    8,    9,   25,  261,  262,
 /*  1060 */   265,  194,   19,  232,  153,  232,   43,   44,   45,  160,
 /*  1070 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*  1080 */    57,   58,  194,  227,  217,  218,   43,   44,   45,  194,
 /*  1090 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*  1100 */    57,   58,  306,  143,  308,  217,  218,  294,   12,   77,
 /*  1110 */    22,   23,  217,  218,  194,   78,  306,   80,  308,  194,
 /*  1120 */   232,  254,   90,   27,  117,   93,  103,  104,  105,  106,
 /*  1130 */   107,  108,  109,  110,  111,  112,  113,  114,   42,  194,
 /*  1140 */    35,  194,  217,  218,  214,  194,  103,  104,  105,  106,
 /*  1150 */   107,  108,  109,  110,  111,  112,  113,  114,  194,  239,

 /*  1160 */    64,  194,  217,  218,  217,  218,  209,  210,  217,  218,
 /*  1170 */    74,  207,   67,   22,  194,   77,   19,  232,  245,  232,
 /*  1180 */    75,   24,  312,  232,  217,  218,  316,   25,   90,  256,
 /*  1190 */   102,   93,  159,  229,  161,  231,   19,  217,  218,  162,
 /*  1200 */    43,   44,   45,  160,   47,   48,   49,   50,   51,   52,
 /*  1210 */    53,   54,   55,   56,   57,   58,   19,   23,  288,   25,
 /*  1220 */    43,   44,   45,  293,   47,   48,   49,   50,   51,   52,
 /*  1230 */    53,   54,   55,   56,   57,   58,  131,   22,  275,   24,
 /*  1240 */    43,   44,   45,  194,   47,   48,   49,   50,   51,   52,
 /*  1250 */    53,   54,   55,   56,   57,   58,  194,  194,  107,  108,
 /*  1260 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*  1270 */   113,  114,  194,   25,  194,   60,  194,  314,  315,  194,
 /*  1280 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*  1290 */   113,  114,   19,  194,  194,  217,  218,  217,  218,   25,
 /*  1300 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*  1310 */   113,  114,  150,  119,  265,  312,   67,  217,  218,  316,
 /*  1320 */    19,  239,  194,  194,  128,  129,  130,  265,  265,  209,
 /*  1330 */   210,   31,  254,  118,  254,   86,   60,  194,  144,   39,
 /*  1340 */    19,  130,  275,  312,   95,   44,   45,  316,   47,   48,
 /*  1350 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   58,
 /*  1360 */   217,  218,   24,  194,  153,   12,   45,  119,   47,   48,
 /*  1370 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   58,
 /*  1380 */    27,  314,  315,   22,  312,   24,  217,  218,  316,  116,
 /*  1390 */   117,   22,  144,   25,  118,   42,  147,  194,   60,   19,
 /*  1400 */    20,  127,   22,  194,  103,  104,  105,  106,  107,  108,

 /*  1410 */   109,  110,  111,  112,  113,  114,   36,   64,  145,  194,









 /*  1420 */   217,  218,  194,   54,  103,  104,  105,  106,  107,  108,
 /*  1430 */   109,  110,  111,  112,  113,  114,  194,   22,  310,   25,
 /*  1440 */    60,  194,  217,  218,  194,  217,  218,  194,  260,  194,
 /*  1450 */   301,  302,   72,  262,  262,  194,  118,  266,  266,  217,
 /*  1460 */   218,  194,   82,  245,  217,  218,  194,  217,  218,  194,
 /*  1470 */   217,  218,  217,  218,  256,   60,   24,  194,  217,  218,
 /*  1480 */   194,  101,  194,  245,  217,  218,  194,  107,  108,  217,
 /*  1490 */   218,   22,  217,  218,  256,  115,  245,  117,  118,  119,
 /*  1500 */   217,  218,  122,  217,  218,  217,  218,  256,   22,  217,
 /*  1510 */   218,  116,  258,  259,  146,   19,   20,  194,   22,  139,
 /*  1520 */   140,  150,  151,  136,   23,  194,   25,  194,  141,  194,
 /*  1530 */   194,   62,   36,  118,  154,  155,  156,  157,  158,  100,
 /*  1540 */   145,  194,  154,  194,  156,   49,  194,   23,  194,   25,
 /*  1550 */   217,  218,  217,  218,  194,  257,   60,  143,  194,   60,
 /*  1560 */   194,  121,  122,  183,  217,  218,  217,  218,   72,  217,
 /*  1570 */   218,  217,  218,  134,   23,  194,   25,  217,  218,    7,
 /*  1580 */     8,  321,   86,  217,  218,  194,  122,   91,   19,   20,
 /*  1590 */    23,   22,   25,   23,  142,   25,  132,  101,  217,  218,
 /*  1600 */   194,  194,  194,  107,  108,   36,  194,  194,  217,  218,
 /*  1610 */   194,  115,  194,  117,  118,  119,  194,  118,  122,  194,
 /*  1620 */    23,  194,   25,  217,  218,  217,  218,  194,  142,   60,
 /*  1630 */   217,  218,  194,  217,  218,  217,  218,   84,   85,  217,
 /*  1640 */   218,   72,  217,  218,  217,  218,   60,   23,   60,   25,
 /*  1650 */   154,  155,  156,  157,  158,   86,  154,  194,  156,  194,
 /*  1660 */    91,   19,   20,   23,   22,   25,  194,   23,  194,   25,
 /*  1670 */   101,   23,  194,   25,  194,  194,  107,  108,   36,  183,
 /*  1680 */   217,  218,  217,  218,  115,  194,  117,  118,  119,  217,
 /*  1690 */   218,  122,  194,  237,  194,  217,  218,  217,  218,  194,

 /*  1700 */   194,   23,   60,   25,  118,   23,  118,   25,  217,  218,
 /*  1710 */    23,  194,   25,  194,   72,  217,  218,  217,  218,   23,
 /*  1720 */   194,   25,  194,  154,  155,  156,  157,  158,   86,   23,
 /*  1730 */   194,   25,  194,   91,  217,  218,  217,  218,  194,  194,
 /*  1740 */   194,  194,  194,  101,  194,  217,  218,  290,  194,  107,
 /*  1750 */   108,  194,  183,  217,  218,  194,  194,  115,  194,  117,
 /*  1760 */   118,  119,  194,  243,  122,  194,  289,  194,  194,  194,
 /*  1770 */   194,  257,  257,  257,  244,  257,  192,  273,  215,  269,
 /*  1780 */   246,  299,  269,  295,  247,  273,  247,  246,  295,  230,
 /*  1790 */   261,  226,  261,  261,  273,  273,  154,  155,  156,  157,
 /*  1800 */   158,    0,    1,    2,  221,  220,    5,  220,  250,  220,
 /*  1810 */   261,   10,   11,   12,   13,   14,  250,  282,   17,  197,
 /*  1820 */    61,   19,   20,  246,   22,  183,  244,  142,  201,  201,
 /*  1830 */    38,   30,  299,   32,  201,  152,   22,  151,   36,  299,
 /*  1840 */    43,   40,  235,   18,  238,  285,  238,  238,  296,  238,
 /*  1850 */   201,  296,  274,  272,   18,  200,  235,  150,  235,  247,
 /*  1860 */   247,  247,   60,  247,  274,  274,  272,  201,  200,  159,
 /*  1870 */    63,  292,   71,  201,   72,  200,   22,  201,  222,  200,
 /*  1880 */    79,  201,  222,   82,  291,  116,  219,   65,  200,  219,
 /*  1890 */   219,  228,   22,  127,  225,  166,  222,   24,  225,  114,
 /*  1900 */    99,  284,  221,  101,  284,  228,  307,  315,  219,  107,
 /*  1910 */   108,  219,  219,  219,  201,   92,  320,  115,  320,  117,
 /*  1920 */   118,  119,  222,   83,  122,  267,  267,  149,  146,   19,
 /*  1930 */    20,   22,   22,  279,  250,  134,  201,  148,  159,  249,
 /*  1940 */   139,  140,  251,  141,   25,  281,   36,  147,  251,  248,
 /*  1950 */   247,  203,   13,  195,    6,  195,  154,  155,  156,  157,
 /*  1960 */   158,  193,  305,  193,  163,  193,  305,  302,  214,  208,
 /*  1970 */    60,  214,  208,  223,  223,    4,  214,  214,    3,   22,
 /*  1980 */   215,  214,   72,  208,  164,  183,  215,   15,   23,   16,
 /*  1990 */    23,  140,  131,  152,   25,  143,   20,   16,   24,    1,
 /*  2000 */   145,  143,  131,  131,   62,   37,   54,   54,  152,   54,
 /*  2010 */    54,  101,  131,  117,   34,    1,  142,  107,  108,   22,
 /*  2020 */     5,  116,  162,   69,   25,  115,   76,  117,  118,  119,
 /*  2030 */     1,    2,  122,   69,    5,   41,  142,  116,   20,   10,
 /*  2040 */    11,   12,   13,   14,   24,   19,   17,  132,    5,  126,
 /*  2050 */    22,  141,   68,   10,   11,   12,   13,   14,   22,   30,
 /*  2060 */    17,   32,   22,   22,  154,  155,  156,  157,  158,   40,
 /*  2070 */    23,   68,   60,   30,   24,   32,   97,   28,   22,   68,
 /*  2080 */    23,   37,   34,   40,  150,   22,   25,   23,   23,   23,
 /*  2090 */    22,   98,   23,  183,   23,  117,   34,   22,   25,   89,
 /*  2100 */    71,  142,  144,   76,   34,   23,   34,   76,   79,   87,
 /*  2110 */    34,   82,   34,   94,   71,   34,   22,   24,   44,   34,
 /*  2120 */    25,   25,   79,   23,   23,   82,  143,   23,   99,  143,
 /*  2130 */    23,   22,   11,   25,   23,   25,   22,   22,   22,    1,
 /*  2140 */    23,   23,   99,  136,   22,   22,  142,  142,  142,   25,
 /*  2150 */    25,   23,   15,    1,  322,  322,  322,  322,  322,  322,
 /*  2160 */   322,  322,  322,  134,  322,  322,  322,  322,  139,  140,
 /*  2170 */   322,  322,  322,  322,  322,  322,  322,  134,  322,  322,
 /*  2180 */   322,  322,  139,  140,  322,  322,  322,  322,  322,  322,
 /*  2190 */   322,  322,  163,  322,  322,  322,  322,  322,  322,  322,
 /*  2200 */   322,  322,  322,  322,  322,  322,  163,  322,  322,  322,
 /*  2210 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2220 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2230 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2240 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2250 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2260 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2270 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2280 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2290 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2300 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2310 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2320 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2330 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2340 */   186,  186,  186,  186,  186,  186,  186,  186,  186,  186,
 /*  2350 */   186,  186,  186,  186,  186,  186,  186,  186,  186,  186,
 /*  2360 */   186,  186,  186,  186,  186,  186,  186,  186,  186,  186,
 /*  2370 */   186,  186,  186,  186,  186,  186,  186,  186,  186,  186,
 /*  2380 */   186,  186,  186,  186,  186,  186,  186,  186,  186,  186,
 /*  2390 */   186,  186,  186,
};
#define YY_SHIFT_COUNT    (582)
#define YY_SHIFT_MIN      (0)
#define YY_SHIFT_MAX      (2152)
static const unsigned short int yy_shift_ofst[] = {
 /*     0 */  2029, 1801, 2043, 1380, 1380,   33,  391, 1496, 1569, 1642,
 /*    10 */   702,  702,  702,  193,   33,   33,   33,   33,   33,    0,
 /*    20 */     0,  216, 1177,  702,  702,  702,  702,  702,  702,  702,
 /*    30 */   702,  702,  702,  702,  702,  702,  702,  702,  406,  406,
 /*    40 */   111,  111,  218,  447,  547,  598,  598,  260,  260,  260,
 /*    50 */   260,   40,  112,  320,  340,  445,  489,  593,  637,  741,
 /*    60 */   785,  889,  909, 1023, 1043, 1157, 1177, 1177, 1177, 1177,
 /*    70 */  1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177,
 /*    80 */  1177, 1177, 1177, 1177, 1197, 1177, 1301, 1321, 1321,  554,
 /*    90 */  1802, 1910,  702,  702,  702,  702,  702,  702,  702,  702,
 /*   100 */   702,  702,  702,  702,  702,  702,  702,  702,  702,  702,
 /*   110 */   702,  702,  702,  702,  702,  702,  702,  702,  702,  702,
 /*   120 */   702,  702,  702,  702,  702,  702,  702,  702,  702,  702,
 /*   130 */   702,  702,  702,  702,  702,  702,  702,  702,  702,  702,
 /*   140 */   702,  702,  138,  198,  198,  198,  198,  198,  198,  198,
 /*   150 */   183,   99,  236,  292,  598,  793,  167,  598,  598,  880,
 /*   160 */   880,  598,  857,  150,  195,  195,  195,  264,  113,  113,
 /*   170 */  2207, 2207,  854,  854,  854,  751,  765,  765,  765,  765,
 /*   180 */  1096, 1096,  725,  292,  882,  904,  598,  598,  598,  598,
 /*   190 */   598,  598,  598,  598,  598,  598,  598,  598,  598,  598,
 /*   200 */   598,  598,  598,  598,  598, 1273, 1032, 1032,  598,  147,
 /*   210 */  1098, 1098,  603,  603, 1276, 1276,  363, 2207, 2207, 2207,
 /*   220 */  2207, 2207, 2207, 2207,  469,  617,  617,  801,  336,  461,
 /*   230 */   804,  864,  615,  891,  913,  598,  598,  598,  598,  598,
 /*   240 */   598,  598,  598,  598,  598,  653,  598,  598,  598,  598,
 /*   250 */   598,  598,  598,  598,  598,  598,  598,  598, 1105, 1105,
 /*   260 */  1105,  598,  598,  598, 1194,  598,  598,  598, 1215, 1249,
 /*   270 */   598, 1353,  598,  598,  598,  598,  598,  598,  598,  598,
 /*   280 */   677,  449,  902, 1338, 1338, 1338, 1338, 1248,  902,  902,
 /*   290 */   326, 1151, 1047,  755,  749, 1371,  960, 1371, 1007, 1162,
 /*   300 */   749,  749, 1162,  749,  960, 1007, 1274,  738,  215, 1300,
 /*   310 */  1300, 1300, 1395, 1395, 1395, 1395, 1368, 1368, 1033, 1414,
 /*   320 */  1387, 1361, 1759, 1759, 1685, 1685, 1792, 1792, 1685, 1683,
 /*   330 */  1686, 1814, 1797, 1825, 1825, 1825, 1825, 1685, 1836, 1707,
 /*   340 */  1686, 1686, 1707, 1814, 1797, 1707, 1797, 1707, 1685, 1836,
 /*   350 */  1710, 1807, 1685, 1836, 1854, 1685, 1836, 1685, 1836, 1854,
 /*   360 */  1769, 1769, 1769, 1822, 1870, 1870, 1854, 1769, 1766, 1769,
 /*   370 */  1822, 1769, 1769, 1729, 1873, 1785, 1785, 1854, 1685, 1823,
 /*   380 */  1823, 1840, 1840, 1778, 1782, 1909, 1685, 1779, 1778, 1789,
 /*   390 */  1800, 1707, 1919, 1939, 1939, 1948, 1948, 1948, 2207, 2207,
 /*   400 */  2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207,
 /*   410 */  2207, 2207, 2207,   69, 1037,   79, 1088,  651, 1196, 1415,
 /*   420 */  1501, 1439, 1369, 1452,  911, 1211, 1524, 1469, 1551, 1567,
 /*   430 */  1570, 1624, 1640, 1644, 1499, 1440, 1572, 1464, 1597,  275,
 /*   440 */   782, 1586, 1648, 1678, 1553, 1682, 1687, 1388, 1502, 1696,
 /*   450 */  1706, 1588, 1486, 1971, 1975, 1957, 1820, 1972, 1973, 1965,
 /*   460 */  1967, 1851, 1841, 1861, 1969, 1969, 1974, 1852, 1976, 1855,
 /*   470 */  1981, 1998, 1858, 1871, 1969, 1872, 1942, 1968, 1969, 1856,
 /*   480 */  1952, 1953, 1955, 1956, 1881, 1896, 1980, 1874, 2014, 2015,
 /*   490 */  1997, 1905, 1860, 1954, 1999, 1964, 1950, 1994, 1894, 1921,
 /*   500 */  2020, 2018, 2026, 1915, 1923, 2028, 1984, 2036, 2040, 2047,
 /*   510 */  2041, 2003, 2012, 2050, 1979, 2049, 2056, 2011, 2044, 2057,
 /*   520 */  2048, 1934, 2063, 2064, 2065, 2061, 2066, 2068, 1993, 1959,
 /*   530 */  2069, 2071, 1978, 2062, 2075, 1958, 2073, 2070, 2072, 2076,
 /*   540 */  2078, 2010, 2027, 2022, 2074, 2031, 2019, 2081, 2082, 2094,
 /*   550 */  2093, 2095, 2096, 2085, 1983, 1986, 2100, 2073, 2101, 2104,
 /*   560 */  2107, 2109, 2108, 2110, 2111, 2114, 2121, 2115, 2116, 2117,
 /*   570 */  2118, 2122, 2123, 2124, 2007, 2004, 2005, 2006, 2125, 2128,
 /*   580 */  2137, 2138, 2152,
};
#define YY_REDUCE_COUNT (412)
#define YY_REDUCE_MIN   (-276)
#define YY_REDUCE_MAX   (1775)
static const short yy_reduce_ofst[] = {
 /*     0 */   -66,  217,  -63, -177, -180,  161,  364,   64, -183,  162,
 /*    10 */   223,  367,  414, -173,  473,  514,  525,  622,  626, -207,
 /*    20 */   351, -276,  -38,  693,  811,  831,  833,  888, -188,  945,
 /*    30 */   947,  416,  558,  951,  867,  287, 1078, 1080, -186,  224,
 /*    40 */  -132,   42,  964,  269,  417,  796,  810, -237, -231, -237,
 /*    50 */  -231,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,
 /*    60 */   -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,
 /*    70 */   -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,
 /*    80 */   -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  895,
 /*    90 */   925,  967,  980, 1100, 1143, 1169, 1203, 1225, 1228, 1242,
 /*   100 */  1247, 1250, 1253, 1255, 1261, 1267, 1272, 1275, 1283, 1286,
 /*   110 */  1288, 1292, 1333, 1335, 1347, 1349, 1352, 1354, 1360, 1366,
 /*   120 */  1381, 1391, 1406, 1408, 1413, 1416, 1418, 1422, 1425, 1427,
 /*   130 */  1463, 1465, 1472, 1478, 1480, 1491, 1498, 1500, 1517, 1519,
 /*   140 */  1528, 1536,  -45,  -45,  -45,  -45,  -45,  -45,  -45,  -45,
 /*   150 */   -45,  -45,  -45,  312, -158,  285, -219,    9,  166,  370,
 /*   160 */   545,  707,  -45,  930,  601,  963, 1067,  792,  -45,  -45,
 /*   170 */   -45,  -45, -204, -204, -204,  369, -171, -129,  632,  678,
 /*   180 */   202,  352, -270,  412,  627,  627,   -9,  122,  415,  419,
 /*   190 */   -56,  248,  583,  920,    6,  261,  459,  795, 1049,  813,
 /*   200 */  1062, 1082, -161,  778, 1063,  797,  870, 1003, 1128,  443,
 /*   210 */  1031, 1072, 1191, 1192,  957, 1120,  105, 1149,  523,  933,
 /*   220 */  1218, 1238, 1254, 1251, -138,   96,  117,  146,  181,  277,
 /*   230 */   280,  421,  480,  712,  830,  850, 1085, 1099, 1129, 1209,
 /*   240 */  1323, 1331, 1336, 1364, 1407,  368, 1412, 1433, 1438, 1474,
 /*   250 */  1481, 1505, 1506, 1526, 1538, 1544, 1545, 1546,  722,  764,
 /*   260 */   856, 1547, 1548, 1550, 1188, 1554, 1557, 1561, 1298, 1260,
 /*   270 */  1562, 1456, 1564,  280, 1568, 1571, 1573, 1574, 1575, 1576,
 /*   280 */  1457, 1477, 1520, 1514, 1515, 1516, 1518, 1188, 1520, 1520,
 /*   290 */  1530, 1563, 1584, 1482, 1504, 1510, 1534, 1513, 1488, 1537,
 /*   300 */  1512, 1521, 1539, 1522, 1541, 1493, 1583, 1559, 1565, 1585,
 /*   310 */  1587, 1589, 1529, 1531, 1532, 1549, 1558, 1566, 1535, 1577,
 /*   320 */  1582, 1622, 1533, 1540, 1627, 1628, 1552, 1555, 1633, 1560,
 /*   330 */  1578, 1581, 1607, 1606, 1608, 1609, 1611, 1649, 1655, 1612,
 /*   340 */  1590, 1591, 1613, 1594, 1621, 1614, 1623, 1616, 1666, 1668,
 /*   350 */  1579, 1593, 1672, 1675, 1656, 1676, 1679, 1680, 1688, 1660,
 /*   360 */  1667, 1670, 1671, 1663, 1669, 1673, 1674, 1689, 1681, 1692,
 /*   370 */  1677, 1693, 1694, 1592, 1599, 1617, 1620, 1700, 1713, 1596,
 /*   380 */  1598, 1658, 1659, 1691, 1684, 1654, 1735, 1664, 1697, 1690,
 /*   390 */  1701, 1703, 1748, 1758, 1760, 1768, 1770, 1772, 1657, 1661,
 /*   400 */  1665, 1761, 1754, 1757, 1762, 1763, 1764, 1750, 1751, 1765,
 /*   410 */  1771, 1767, 1775,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */  1663, 1663, 1663, 1491, 1254, 1367, 1254, 1254, 1254, 1254,
 /*    10 */  1491, 1491, 1491, 1254, 1254, 1254, 1254, 1254, 1254, 1397,
 /*    20 */  1397, 1544, 1287, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*    30 */  1254, 1254, 1254, 1254, 1254, 1490, 1254, 1254, 1254, 1254,
 /*    40 */  1578, 1578, 1254, 1254, 1254, 1254, 1254, 1563, 1562, 1254,
 /*    50 */  1254, 1254, 1406, 1254, 1413, 1254, 1254, 1254, 1254, 1254,
 /*    60 */  1492, 1493, 1254, 1254, 1254, 1254, 1543, 1545, 1508, 1420,
 /*    70 */  1419, 1418, 1417, 1526, 1385, 1411, 1404, 1408, 1487, 1488,
 /*    80 */  1486, 1641, 1493, 1492, 1254, 1407, 1455, 1471, 1454, 1254,
 /*    90 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   100 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   110 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   120 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   130 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   140 */  1254, 1254, 1463, 1470, 1469, 1468, 1477, 1467, 1464, 1457,
 /*   150 */  1456, 1458, 1459, 1278, 1254, 1275, 1329, 1254, 1254, 1254,
 /*   160 */  1254, 1254, 1460, 1287, 1448, 1447, 1446, 1254, 1474, 1461,
 /*   170 */  1473, 1472, 1551, 1615, 1614, 1509, 1254, 1254, 1254, 1254,
 /*   180 */  1254, 1254, 1578, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   190 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   200 */  1254, 1254, 1254, 1254, 1254, 1387, 1578, 1578, 1254, 1287,
 /*   210 */  1578, 1578, 1388, 1388, 1283, 1283, 1391, 1558, 1358, 1358,
 /*   220 */  1358, 1358, 1367, 1358, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   230 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1548,
 /*   240 */  1546, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   250 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   260 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1363, 1254,
 /*   270 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1608,
 /*   280 */  1254, 1521, 1343, 1363, 1363, 1363, 1363, 1365, 1344, 1342,
 /*   290 */  1357, 1288, 1261, 1655, 1423, 1412, 1364, 1412, 1652, 1410,
 /*   300 */  1423, 1423, 1410, 1423, 1364, 1652, 1304, 1630, 1299, 1397,
 /*   310 */  1397, 1397, 1387, 1387, 1387, 1387, 1391, 1391, 1489, 1364,
 /*   320 */  1357, 1254, 1655, 1655, 1373, 1373, 1654, 1654, 1373, 1509,
 /*   330 */  1638, 1432, 1332, 1338, 1338, 1338, 1338, 1373, 1272, 1410,
 /*   340 */  1638, 1638, 1410, 1432, 1332, 1410, 1332, 1410, 1373, 1272,
 /*   350 */  1525, 1649, 1373, 1272, 1499, 1373, 1272, 1373, 1272, 1499,
 /*   360 */  1330, 1330, 1330, 1319, 1254, 1254, 1499, 1330, 1304, 1330,
 /*   370 */  1319, 1330, 1330, 1596, 1254, 1503, 1503, 1499, 1373, 1588,
 /*   380 */  1588, 1400, 1400, 1405, 1391, 1494, 1373, 1254, 1405, 1403,
 /*   390 */  1401, 1410, 1322, 1611, 1611, 1607, 1607, 1607, 1660, 1660,
 /*   400 */  1558, 1623, 1287, 1287, 1287, 1287, 1623, 1306, 1306, 1288,
 /*   410 */  1288, 1287, 1623, 1254, 1254, 1254, 1254, 1254, 1254, 1618,
 /*   420 */  1254, 1553, 1510, 1377, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   430 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   440 */  1564, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   450 */  1254, 1254, 1437, 1254, 1257, 1555, 1254, 1254, 1254, 1254,
 /*   460 */  1254, 1254, 1254, 1254, 1414, 1415, 1378, 1254, 1254, 1254,
 /*   470 */  1254, 1254, 1254, 1254, 1429, 1254, 1254, 1254, 1424, 1254,
 /*   480 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1651, 1254, 1254,
 /*   490 */  1254, 1254, 1254, 1254, 1524, 1523, 1254, 1254, 1375, 1254,
 /*   500 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   510 */  1254, 1254, 1302, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   520 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   530 */  1254, 1254, 1254, 1254, 1254, 1254, 1402, 1254, 1254, 1254,
 /*   540 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   550 */  1254, 1593, 1392, 1254, 1254, 1254, 1254, 1642, 1254, 1254,
 /*   560 */  1254, 1254, 1352, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   570 */  1254, 1254, 1254, 1634, 1346, 1438, 1254, 1441, 1276, 1254,
 /*   580 */  1266, 1254, 1254,
};
/********** End of lemon-generated parsing tables *****************************/

/* The next table maps tokens (terminal symbols) into fallback tokens.
** If a construct like the following:







|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
<
<
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
>
|
|
|
|
|
|
<
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<
|
|
|
>
>
|
>
|
|
|
|
|
|
|
<
|
<
<
|
|
|
<
<
|
<
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
|
<
<
<
|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
|
<
>
>
>
|
<
|
>
|
|
|
|
>
>
|
<
<
|
|
|
|
|
|
|
|
|
<
<
|
|
>
>
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
<
|
|
>
|
|
|
>
>
|
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
|
|
|
>
|
|
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
<
|
|
|
|
>
|
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|











|
<
<
<
<
<
<
<



|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|








|
|
|





|
|
|
|
|

|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|

|

|
|







172802
172803
172804
172805
172806
172807
172808
172809
172810
172811
172812
172813
172814
172815
172816
172817
172818
172819
172820
172821
172822
172823
172824
172825
172826
172827
172828
172829
172830
172831
172832
172833
172834
172835
172836
172837
172838
172839
172840
172841


172842

172843
172844
172845
172846
172847
172848
172849
172850
172851
172852
172853
172854
172855
172856
172857
172858
172859
172860
172861
172862
172863
172864
172865

172866
172867
172868
172869
172870
172871
172872
172873

172874
172875
172876
172877
172878
172879
172880
172881
172882
172883
172884
172885
172886
172887
172888

172889
172890
172891
172892
172893
172894
172895
172896
172897
172898
172899
172900
172901
172902
172903
172904
172905
172906
172907
172908
172909
172910
172911
172912
172913
172914
172915
172916
172917
172918
172919
172920
172921
172922
172923
172924
172925
172926
172927
172928
172929
172930
172931
172932
172933
172934
172935
172936











172937


172938
172939
172940
172941
172942
172943
172944
172945
172946
172947
172948
172949
172950
172951

172952


172953
172954
172955


172956

172957
172958
172959
172960
172961
172962
172963
172964
172965
172966
172967
172968
172969
172970
172971
172972
172973
172974
172975
172976
172977
172978
172979
172980
172981
172982
172983
172984
172985
172986
172987
172988
172989
172990
172991
172992











172993
172994
172995
172996
172997
172998
172999
173000
173001
173002
173003
173004
173005
173006
173007
173008
173009
173010
173011
173012
173013
173014
173015
173016
173017
173018
173019
173020
173021
173022
173023



173024



173025
173026
173027
173028
173029
173030
173031
173032
173033
173034
173035
173036
173037
173038
173039
173040
173041
173042
173043
173044
173045
173046
173047
173048
173049
173050
173051
173052
173053
173054
173055


173056

173057
173058
173059
173060

173061
173062
173063
173064
173065
173066
173067
173068
173069


173070
173071
173072
173073
173074
173075
173076
173077
173078


173079
173080
173081
173082
173083
173084
173085
173086
173087
173088
173089

173090
173091
173092
173093
173094
173095
173096
173097
173098
173099
173100
173101
173102
173103
173104

173105
173106
173107
173108
173109
173110
173111
173112
173113


173114
173115
173116
173117
173118
173119
173120
173121
173122
173123
173124
173125
173126
173127
173128
173129
173130
173131
173132
173133







173134
173135
173136
173137
173138
173139


173140
173141
173142
173143
173144
173145
173146
173147
173148
173149
173150
173151
173152
173153

173154

173155
173156
173157
173158
173159
173160
173161
173162
173163
173164
173165
173166
173167
173168
173169
173170
173171
173172
173173
173174
173175
173176
173177
173178
173179
173180
173181
173182
173183
173184
173185
173186
173187
173188
173189
173190
173191
173192

173193
173194
173195
173196
173197
173198
173199
173200
173201
173202
173203
173204
173205
173206
173207
173208
173209
173210
173211
173212
173213
173214
173215
173216
173217
173218
173219
173220
173221
173222
173223
173224
173225
173226
173227
173228
173229
173230
173231
173232
173233
173234
173235
173236
173237
173238
173239
173240
173241
173242
173243
173244
173245
173246
173247
173248
173249
173250
173251
173252
173253
173254
173255
173256
173257
173258
173259
173260







173261
173262
173263
173264
173265
173266
173267
173268
173269
173270
173271
173272
173273
173274
173275
173276
173277
173278
173279
173280
173281
173282
173283
173284
173285
173286
173287
173288
173289
173290
173291
173292
173293
173294
173295
173296
173297
173298
173299
173300
173301
173302
173303
173304
173305
173306
173307
173308
173309
173310
173311
173312
173313
173314
173315
173316
173317
173318
173319
173320
173321
173322
173323
173324
173325
173326
173327
173328
173329
173330
173331
173332
173333
173334
173335
173336
173337
173338
173339
173340
173341
173342
173343
173344
173345
173346
173347
173348
173349
173350
173351
173352
173353
173354
173355
173356
173357
173358
173359
173360
173361
173362
173363
173364
173365
173366
173367
173368
173369
173370
173371
173372
173373
173374
173375
173376
173377
173378
173379
173380
173381
173382
173383
173384
173385
173386
173387
173388
173389
173390
173391
173392
173393
173394
173395
173396
173397
173398
173399
173400
173401
173402
173403
173404
173405
173406
173407
173408
173409
173410
173411
173412
173413
173414
173415
173416
173417
173418
173419
173420
173421
173422
173423
173424
173425
173426
173427
173428
173429
173430
173431
173432
173433
173434
173435
173436
173437
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
**
*********** Begin parsing tables **********************************************/
#define YY_ACTTAB_COUNT (2142)
static const YYACTIONTYPE yy_action[] = {
 /*     0 */   576,  128,  125,  232, 1622,  549,  576, 1290, 1281,  576,
 /*    10 */   328,  576, 1300,  212,  576,  128,  125,  232,  578,  412,
 /*    20 */   578,  391, 1542,   51,   51,  523,  405, 1293,  529,   51,
 /*    30 */    51,  983,   51,   51,   81,   81, 1107,   61,   61,  984,
 /*    40 */  1107, 1292,  380,  135,  136,   90, 1228, 1228, 1063, 1066,
 /*    50 */  1053, 1053,  133,  133,  134,  134,  134,  134, 1577,  412,
 /*    60 */   287,  287,    7,  287,  287,  422, 1050, 1050, 1064, 1067,
 /*    70 */   289,  556,  492,  573,  524,  561,  573,  497,  561,  482,
 /*    80 */   530,  262,  229,  135,  136,   90, 1228, 1228, 1063, 1066,
 /*    90 */  1053, 1053,  133,  133,  134,  134,  134,  134,  128,  125,
 /*   100 */   232, 1506,  132,  132,  132,  132,  131,  131,  130,  130,
 /*   110 */   130,  129,  126,  450, 1204, 1255,    1,    1,  582,    2,
 /*   120 */  1259, 1571,  420, 1582,  379,  320, 1174,  153, 1174, 1584,
 /*   130 */   412,  378, 1582,  543, 1341,  330,  111,  570,  570,  570,
 /*   140 */   293, 1054,  132,  132,  132,  132,  131,  131,  130,  130,
 /*   150 */   130,  129,  126,  450,  135,  136,   90, 1228, 1228, 1063,
 /*   160 */  1066, 1053, 1053,  133,  133,  134,  134,  134,  134,  287,
 /*   170 */   287, 1204, 1205, 1204,  255,  287,  287,  510,  507,  506,
 /*   180 */   137,  455,  573,  212,  561,  447,  446,  505,  573, 1616,
 /*   190 */   561,  134,  134,  134,  134,  127,  400,  243,  132,  132,
 /*   200 */   132,  132,  131,  131,  130,  130,  130,  129,  126,  450,
 /*   210 */   282,  471,  345,  132,  132,  132,  132,  131,  131,  130,
 /*   220 */   130,  130,  129,  126,  450,  574,  155,  936,  936,  454,
 /*   230 */   227,  521, 1236,  412, 1236,  134,  134,  134,  134,  132,
 /*   240 */   132,  132,  132,  131,  131,  130,  130,  130,  129,  126,
 /*   250 */   450,  130,  130,  130,  129,  126,  450,  135,  136,   90,
 /*   260 */  1228, 1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,
 /*   270 */   134,  134,  128,  125,  232,  450,  576,  412,  397, 1249,
 /*   280 */   180,   92,   93,  132,  132,  132,  132,  131,  131,  130,
 /*   290 */   130,  130,  129,  126,  450,  381,  387, 1204,  383,   81,
 /*   300 */    81,  135,  136,   90, 1228, 1228, 1063, 1066, 1053, 1053,


 /*   310 */   133,  133,  134,  134,  134,  134,  132,  132,  132,  132,

 /*   320 */   131,  131,  130,  130,  130,  129,  126,  450,  131,  131,
 /*   330 */   130,  130,  130,  129,  126,  450,  556, 1204,  302,  319,
 /*   340 */   567,  121,  568,  480,    4,  555, 1149, 1657, 1628, 1657,
 /*   350 */    45,  128,  125,  232, 1204, 1205, 1204, 1250,  571, 1169,
 /*   360 */   132,  132,  132,  132,  131,  131,  130,  130,  130,  129,
 /*   370 */   126,  450, 1169,  287,  287, 1169, 1019,  576,  422, 1019,
 /*   380 */   412,  451, 1602,  582,    2, 1259,  573,   44,  561,   95,
 /*   390 */   320,  110,  153,  565, 1204, 1205, 1204,  522,  522, 1341,
 /*   400 */    81,   81,    7,   44,  135,  136,   90, 1228, 1228, 1063,
 /*   410 */  1066, 1053, 1053,  133,  133,  134,  134,  134,  134,  295,
 /*   420 */  1149, 1658, 1040, 1658, 1204, 1147,  319,  567,  119,  119,
 /*   430 */   343,  466,  331,  343,  287,  287,  120,  556,  451,  577,
 /*   440 */   451, 1169, 1169, 1028,  319,  567,  438,  573,  210,  561,
 /*   450 */  1339, 1451,  546,  531, 1169, 1169, 1598, 1169, 1169,  416,
 /*   460 */   319,  567,  243,  132,  132,  132,  132,  131,  131,  130,
 /*   470 */   130,  130,  129,  126,  450, 1028, 1028, 1030, 1031,   35,
 /*   480 */    44, 1204, 1205, 1204,  472,  287,  287, 1328,  412, 1307,
 /*   490 */   372, 1595,  359,  225,  454, 1204,  195, 1328,  573, 1147,
 /*   500 */   561, 1333, 1333,  274,  576, 1188,  576,  340,   46,  196,
 /*   510 */   537,  217,  135,  136,   90, 1228, 1228, 1063, 1066, 1053,
 /*   520 */  1053,  133,  133,  134,  134,  134,  134,   19,   19,   19,
 /*   530 */    19,  412,  581, 1204, 1259,  511, 1204,  319,  567,  320,
 /*   540 */   944,  153,  425,  491,  430,  943, 1204,  488, 1341, 1450,

 /*   550 */   532, 1277, 1204, 1205, 1204,  135,  136,   90, 1228, 1228,
 /*   560 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
 /*   570 */   575,  132,  132,  132,  132,  131,  131,  130,  130,  130,
 /*   580 */   129,  126,  450,  287,  287,  528,  287,  287,  372, 1595,
 /*   590 */  1204, 1205, 1204, 1204, 1205, 1204,  573,  486,  561,  573,
 /*   600 */   889,  561,  412, 1204, 1205, 1204,  886,   40,   22,   22,
 /*   610 */   220,  243,  525, 1449,  132,  132,  132,  132,  131,  131,
 /*   620 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,

 /*   630 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*   640 */   134,  412,  180,  454, 1204,  879,  255,  287,  287,  510,
 /*   650 */   507,  506,  372, 1595, 1568, 1331, 1331,  576,  889,  505,
 /*   660 */   573,   44,  561,  559, 1207,  135,  136,   90, 1228, 1228,
 /*   670 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
 /*   680 */    81,   81,  422,  576,  377,  132,  132,  132,  132,  131,
 /*   690 */   131,  130,  130,  130,  129,  126,  450,  297,  287,  287,
 /*   700 */   460, 1204, 1205, 1204, 1204,  534,   19,   19,  448,  448,
 /*   710 */   448,  573,  412,  561,  230,  436, 1187,  535,  319,  567,
 /*   720 */   363,  432, 1207, 1435,  132,  132,  132,  132,  131,  131,
 /*   730 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
 /*   740 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*   750 */   134,  412,  211,  949, 1169, 1041, 1110, 1110,  494,  547,
 /*   760 */   547, 1204, 1205, 1204,    7,  539, 1570, 1169,  376,  576,
 /*   770 */  1169,    5, 1204,  486,    3,  135,  136,   90, 1228, 1228,

 /*   780 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
 /*   790 */   576,  513,   19,   19,  427,  132,  132,  132,  132,  131,
 /*   800 */   131,  130,  130,  130,  129,  126,  450,  305, 1204,  433,
 /*   810 */   225, 1204,  385,   19,   19,  273,  290,  371,  516,  366,
 /*   820 */   515,  260,  412,  538, 1568,  549, 1024,  362,  437, 1204,
 /*   830 */  1205, 1204,  902, 1552,  132,  132,  132,  132,  131,  131,
 /*   840 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
 /*   850 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*   860 */   134,  412, 1435,  514, 1281, 1204, 1205, 1204, 1204, 1205,
 /*   870 */  1204,  903,   48,  342, 1568, 1568, 1279, 1627, 1568,  911,
 /*   880 */   576,  129,  126,  450,  110,  135,  136,   90, 1228, 1228,
 /*   890 */  1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,  134,
 /*   900 */   265,  576,  459,   19,   19,  132,  132,  132,  132,  131,
 /*   910 */   131,  130,  130,  130,  129,  126,  450, 1345,  204,  576,
 /*   920 */   459,  458,   50,   47,   19,   19,   49,  434, 1105,  573,
 /*   930 */   497,  561,  412,  428,  108, 1224, 1569, 1554,  376,  205,
 /*   940 */   550,  550,   81,   81,  132,  132,  132,  132,  131,  131,
 /*   950 */   130,  130,  130,  129,  126,  450,  135,  136,   90, 1228,
 /*   960 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*   970 */   134,  480,  576, 1204,  576, 1541,  412, 1435,  969,  315,
 /*   980 */  1659,  398,  284,  497,  969,  893, 1569, 1569,  376,  376,
 /*   990 */  1569,  461,  376, 1224,  459,   80,   80,   81,   81,  497,
 /*  1000 */   374,  114,   90, 1228, 1228, 1063, 1066, 1053, 1053,  133,
 /*  1010 */   133,  134,  134,  134,  134,  132,  132,  132,  132,  131,
 /*  1020 */   131,  130,  130,  130,  129,  126,  450, 1204, 1505,  576,
 /*  1030 */  1204, 1205, 1204, 1366,  316,  486,  281,  281,  497,  431,
 /*  1040 */   557,  288,  288,  402, 1340,  471,  345,  298,  429,  573,
 /*  1050 */   576,  561,   81,   81,  573,  374,  561,  971,  386,  132,
 /*  1060 */   132,  132,  132,  131,  131,  130,  130,  130,  129,  126,
 /*  1070 */   450,  231,  117,   81,   81,  287,  287,  231,  287,  287,
 /*  1080 */   576, 1511,  576, 1336, 1204, 1205, 1204,  139,  573,  556,
 /*  1090 */   561,  573,  412,  561,  441,  456,  969,  213,  558, 1511,
 /*  1100 */  1513, 1550,  969,  143,  143,  145,  145, 1368,  314,  478,
 /*  1110 */   444,  970,  412,  850,  851,  852,  135,  136,   90, 1228,
 /*  1120 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*  1130 */   134,  357,  412,  397, 1148,  304,  135,  136,   90, 1228,
 /*  1140 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*  1150 */   134, 1575,  323,    6,  862,    7,  135,  124,   90, 1228,
 /*  1160 */  1228, 1063, 1066, 1053, 1053,  133,  133,  134,  134,  134,
 /*  1170 */   134,  409,  408, 1511,  212,  132,  132,  132,  132,  131,
 /*  1180 */   131,  130,  130,  130,  129,  126,  450,  411,  118, 1204,
 /*  1190 */   116,   10,  352,  265,  355,  132,  132,  132,  132,  131,
 /*  1200 */   131,  130,  130,  130,  129,  126,  450,  576,  324,  306,
 /*  1210 */   576,  306, 1250,  469,  158,  132,  132,  132,  132,  131,
 /*  1220 */   131,  130,  130,  130,  129,  126,  450,  207, 1224, 1126,
 /*  1230 */    65,   65,  470,   66,   66,  412,  447,  446,  882,  531,
 /*  1240 */   335,  258,  257,  256, 1127, 1233, 1204, 1205, 1204,  327,
 /*  1250 */  1235,  874,  159,  576,   16,  480, 1085, 1040, 1234, 1128,











 /*  1260 */   136,   90, 1228, 1228, 1063, 1066, 1053, 1053,  133,  133,


 /*  1270 */   134,  134,  134,  134, 1029,  576,   81,   81, 1028, 1040,
 /*  1280 */   922,  576,  463, 1236,  576, 1236, 1224,  502,  107, 1435,
 /*  1290 */   923,    6,  576,  410, 1498,  882, 1029,  480,   21,   21,
 /*  1300 */  1028,  332, 1380,  334,   53,   53,  497,   81,   81,  874,
 /*  1310 */  1028, 1028, 1030,  445,  259,   19,   19,  533,  132,  132,
 /*  1320 */   132,  132,  131,  131,  130,  130,  130,  129,  126,  450,
 /*  1330 */   551,  301, 1028, 1028, 1030,  107,  532,  545,  121,  568,
 /*  1340 */  1188,    4, 1126, 1576,  449,  576,  462,    7, 1282,  418,
 /*  1350 */   462,  350, 1435,  576,  518,  571,  544, 1127,  121,  568,
 /*  1360 */   442,    4, 1188,  464,  533, 1180, 1223,    9,   67,   67,
 /*  1370 */   487,  576, 1128,  303,  410,  571,   54,   54,  451,  576,
 /*  1380 */   123,  944,  576,  417,  576,  333,  943, 1379,  576,  236,
 /*  1390 */   565,  576, 1574,  564,   68,   68,    7,  576,  451,  362,
 /*  1400 */   419,  182,   69,   69,  541,   70,   70,   71,   71,  540,

 /*  1410 */   565,   72,   72,  484,   55,   55,  473, 1180,  296, 1040,


 /*  1420 */    56,   56,  296,  493,  541,  119,  119,  410, 1573,  542,
 /*  1430 */   569,  418,    7,  120, 1244,  451,  577,  451,  465, 1040,
 /*  1440 */  1028,  576, 1557,  552,  476,  119,  119,  527,  259,  121,


 /*  1450 */   568,  240,    4,  120,  576,  451,  577,  451,  576,  477,

 /*  1460 */  1028,  576,  156,  576,   57,   57,  571,  576,  286,  229,
 /*  1470 */   410,  336, 1028, 1028, 1030, 1031,   35,   59,   59,  219,
 /*  1480 */   983,   60,   60,  220,   73,   73,   74,   74,  984,  451,
 /*  1490 */    75,   75, 1028, 1028, 1030, 1031,   35,   96,  216,  291,
 /*  1500 */   552,  565, 1188,  318,  395,  395,  394,  276,  392,  576,
 /*  1510 */   485,  859,  474, 1311,  410,  541,  576,  417, 1530, 1144,
 /*  1520 */   540,  399, 1188,  292,  237, 1153,  326,   38,   23,  576,
 /*  1530 */  1040,  576,   20,   20,  325,  299,  119,  119,  164,   76,
 /*  1540 */    76, 1529,  121,  568,  120,    4,  451,  577,  451,  203,
 /*  1550 */   576, 1028,  141,  141,  142,  142,  576,  322,   39,  571,
 /*  1560 */   341, 1021,  110,  264,  239,  901,  900,  423,  242,  908,
 /*  1570 */   909,  370,  173,   77,   77,   43,  479, 1310,  264,   62,
 /*  1580 */    62,  369,  451, 1028, 1028, 1030, 1031,   35, 1601, 1192,
 /*  1590 */   453, 1092,  238,  291,  565,  163, 1309,  110,  395,  395,
 /*  1600 */   394,  276,  392,  986,  987,  859,  481,  346,  264,  110,
 /*  1610 */  1032,  489,  576, 1188,  503, 1088,  261,  261,  237,  576,
 /*  1620 */   326,  121,  568, 1040,    4,  347, 1376,  413,  325,  119,
 /*  1630 */   119,  948,  319,  567,  351,   78,   78,  120,  571,  451,
 /*  1640 */   577,  451,   79,   79, 1028,  354,  356,  576,  360, 1092,
 /*  1650 */   110,  576,  974,  942,  264,  123,  457,  358,  239,  576,
 /*  1660 */   519,  451,  939, 1104,  123, 1104,  173,  576, 1032,   43,
 /*  1670 */    63,   63, 1324,  565,  168,  168, 1028, 1028, 1030, 1031,
 /*  1680 */    35,  576,  169,  169, 1308,  872,  238,  157, 1589,  576,
 /*  1690 */    86,   86,  365,   89,  568,  375,    4, 1103,  941, 1103,
 /*  1700 */   123,  576, 1040, 1389,   64,   64, 1188, 1434,  119,  119,
 /*  1710 */   571,  576,   82,   82,  563,  576,  120,  165,  451,  577,
 /*  1720 */   451,  413, 1362, 1028,  144,  144,  319,  567,  576, 1374,
 /*  1730 */   562,  498,  279,  451,   83,   83, 1439,  576,  166,  166,
 /*  1740 */   576, 1289,  554,  576, 1280,  565,  576,   12,  576, 1268,
 /*  1750 */   457,  146,  146, 1267,  576, 1028, 1028, 1030, 1031,   35,
 /*  1760 */   140,  140, 1269,  167,  167, 1609,  160,  160, 1359,  150,
 /*  1770 */   150,  149,  149,  311, 1040,  576,  312,  147,  147,  313,
 /*  1780 */   119,  119,  222,  235,  576, 1188,  396,  576,  120,  576,
 /*  1790 */   451,  577,  451, 1192,  453, 1028,  508,  291,  148,  148,
 /*  1800 */  1421, 1612,  395,  395,  394,  276,  392,   85,   85,  859,
 /*  1810 */    87,   87,   84,   84,  553,  576,  294,  576, 1426,  338,











 /*  1820 */   339, 1425,  237,  300,  326, 1416, 1409, 1028, 1028, 1030,
 /*  1830 */  1031,   35,  325,  344,  403,  483,  226, 1307,   52,   52,
 /*  1840 */    58,   58,  368, 1371, 1502,  566, 1501,  121,  568,  221,
 /*  1850 */     4,  208,  268,  209,  390, 1244, 1549, 1188, 1372, 1370,
 /*  1860 */  1369, 1547,  239,  184,  571,  233,  421, 1241,   95,  218,
 /*  1870 */   173, 1507,  193,   43,   91,   94,  178,  186,  467,  188,
 /*  1880 */   468, 1422,   13,  189,  190,  191,  501,  451,  245,  108,
 /*  1890 */   238,  401, 1428, 1427, 1430,  475,  404, 1496,  197,  565,
 /*  1900 */    14,  490,  249,  101, 1518,  496,  349,  280,  251,  201,
 /*  1910 */   353,  499,  252,  406, 1270,  253,  517, 1327, 1326,  435,
 /*  1920 */  1325, 1318,  103,  893, 1296,  413,  227,  407, 1040, 1626,
 /*  1930 */   319,  567, 1625, 1297,  119,  119,  439,  367, 1317, 1295,
 /*  1940 */  1624,  526,  120,  440,  451,  577,  451, 1594,  309, 1028,
 /*  1950 */   310,  373,  266,  267,  457, 1580, 1579,  443,  138, 1394,
 /*  1960 */   552, 1393,   11, 1483,  384,  115,  317, 1350,  109,  536,
 /*  1970 */    42,  579,  382,  214, 1349,  388, 1198,  389,  275,  277,
 /*  1980 */   278, 1028, 1028, 1030, 1031,   35,  580, 1265,  414, 1260,
 /*  1990 */   170,  415,  183, 1534, 1535, 1533,  171,  154,  307, 1532,
 /*  2000 */   846,  223,  224,   88,  452,  215,  172,  321,  234, 1102,
 /*  2010 */   152, 1188, 1100,  329,  185,  174, 1223,  925,  187,  241,
 /*  2020 */   337,  244, 1116,  192,  175,  176,  424,  426,   97,  194,
 /*  2030 */    98,   99,  100,  177, 1119, 1115,  246,  247,  161,   24,
 /*  2040 */   248,  348, 1238,  264, 1108,  250,  495,  199,  198,   15,
 /*  2050 */   861,  500,  369,  254,  504,  509,  512,  200,  102,   25,
 /*  2060 */   179,  361,   26,  364,  104,  891,  308,  162,  105,  904,
 /*  2070 */   520,  106, 1185, 1069, 1155,   17,  228,   27, 1154,  283,
 /*  2080 */   285,  263,  978,  202,  972,  123,   28, 1175,   29,   30,
 /*  2090 */  1179, 1171,   31, 1173, 1160,   41,   32,  206,  548,   33,
 /*  2100 */   110, 1178, 1083,    8,  112, 1070,  113, 1068, 1072,   34,
 /*  2110 */  1073,  560, 1125,  269, 1124,  270,   36,   18, 1194, 1033,
 /*  2120 */   873,  151,  122,   37,  393,  271,  272,  572,  181, 1193,



 /*  2130 */  1256, 1256, 1256,  935, 1256, 1256, 1256, 1256, 1256, 1256,



 /*  2140 */  1256, 1617,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */   194,  276,  277,  278,  216,  194,  194,  217,  194,  194,
 /*    10 */   194,  194,  224,  194,  194,  276,  277,  278,  204,   19,
 /*    20 */   206,  202,  297,  217,  218,  205,  207,  217,  205,  217,
 /*    30 */   218,   31,  217,  218,  217,  218,   29,  217,  218,   39,
 /*    40 */    33,  217,  220,   43,   44,   45,   46,   47,   48,   49,
 /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  312,   19,
 /*    60 */   240,  241,  316,  240,  241,  194,   46,   47,   48,   49,
 /*    70 */    22,  254,   65,  253,  254,  255,  253,  194,  255,  194,
 /*    80 */   263,  258,  259,   43,   44,   45,   46,   47,   48,   49,
 /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  276,  277,
 /*   100 */   278,  285,  102,  103,  104,  105,  106,  107,  108,  109,
 /*   110 */   110,  111,  112,  113,   59,  186,  187,  188,  189,  190,
 /*   120 */   191,  310,  239,  317,  318,  196,   86,  198,   88,  317,
 /*   130 */    19,  319,  317,  318,  205,  264,   25,  211,  212,  213,
 /*   140 */   205,  121,  102,  103,  104,  105,  106,  107,  108,  109,
 /*   150 */   110,  111,  112,  113,   43,   44,   45,   46,   47,   48,
 /*   160 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  240,
 /*   170 */   241,  116,  117,  118,  119,  240,  241,  122,  123,  124,
 /*   180 */    69,  298,  253,  194,  255,  106,  107,  132,  253,  141,
 /*   190 */   255,   54,   55,   56,   57,   58,  207,  268,  102,  103,
 /*   200 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
 /*   210 */   214,  128,  129,  102,  103,  104,  105,  106,  107,  108,
 /*   220 */   109,  110,  111,  112,  113,  134,   25,  136,  137,  300,
 /*   230 */   165,  166,  153,   19,  155,   54,   55,   56,   57,  102,
 /*   240 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*   250 */   113,  108,  109,  110,  111,  112,  113,   43,   44,   45,
 /*   260 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
 /*   270 */    56,   57,  276,  277,  278,  113,  194,   19,   22,   23,


 /*   280 */   194,   67,   24,  102,  103,  104,  105,  106,  107,  108,

 /*   290 */   109,  110,  111,  112,  113,  220,  250,   59,  252,  217,
 /*   300 */   218,   43,   44,   45,   46,   47,   48,   49,   50,   51,
 /*   310 */    52,   53,   54,   55,   56,   57,  102,  103,  104,  105,
 /*   320 */   106,  107,  108,  109,  110,  111,  112,  113,  106,  107,

 /*   330 */   108,  109,  110,  111,  112,  113,  254,   59,  205,  138,
 /*   340 */   139,   19,   20,  194,   22,  263,   22,   23,  231,   25,
 /*   350 */    72,  276,  277,  278,  116,  117,  118,  101,   36,   76,
 /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
 /*   370 */   112,  113,   89,  240,  241,   92,   73,  194,  194,   73,
 /*   380 */    19,   59,  188,  189,  190,  191,  253,   81,  255,  151,
 /*   390 */   196,   25,  198,   71,  116,  117,  118,  311,  312,  205,
 /*   400 */   217,  218,  316,   81,   43,   44,   45,   46,   47,   48,
 /*   410 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  270,


 /*   420 */    22,   23,  100,   25,   59,  101,  138,  139,  106,  107,
 /*   430 */   127,  128,  129,  127,  240,  241,  114,  254,  116,  117,
 /*   440 */   118,   76,   76,  121,  138,  139,  263,  253,  264,  255,
 /*   450 */   205,  275,   87,   19,   89,   89,  194,   92,   92,  199,
 /*   460 */   138,  139,  268,  102,  103,  104,  105,  106,  107,  108,
 /*   470 */   109,  110,  111,  112,  113,  153,  154,  155,  156,  157,
 /*   480 */    81,  116,  117,  118,  129,  240,  241,  224,   19,  226,
 /*   490 */   314,  315,   23,   25,  300,   59,   22,  234,  253,  101,
 /*   500 */   255,  236,  237,   26,  194,  183,  194,  152,   72,   22,


 /*   510 */   145,  150,   43,   44,   45,   46,   47,   48,   49,   50,
 /*   520 */    51,   52,   53,   54,   55,   56,   57,  217,  218,  217,
 /*   530 */   218,   19,  189,   59,  191,   23,   59,  138,  139,  196,
 /*   540 */   135,  198,  232,  283,  232,  140,   59,  287,  205,  275,
 /*   550 */   116,  205,  116,  117,  118,   43,   44,   45,   46,   47,
 /*   560 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   570 */   194,  102,  103,  104,  105,  106,  107,  108,  109,  110,
 /*   580 */   111,  112,  113,  240,  241,  194,  240,  241,  314,  315,
 /*   590 */   116,  117,  118,  116,  117,  118,  253,  194,  255,  253,
 /*   600 */    59,  255,   19,  116,  117,  118,   23,   22,  217,  218,
 /*   610 */   142,  268,  205,  275,  102,  103,  104,  105,  106,  107,

 /*   620 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
 /*   630 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*   640 */    57,   19,  194,  300,   59,   23,  119,  240,  241,  122,
 /*   650 */   123,  124,  314,  315,  194,  236,  237,  194,  117,  132,
 /*   660 */   253,   81,  255,  205,   59,   43,   44,   45,   46,   47,
 /*   670 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   680 */   217,  218,  194,  194,  194,  102,  103,  104,  105,  106,
 /*   690 */   107,  108,  109,  110,  111,  112,  113,  294,  240,  241,
 /*   700 */   120,  116,  117,  118,   59,  194,  217,  218,  211,  212,
 /*   710 */   213,  253,   19,  255,  194,   19,   23,  254,  138,  139,
 /*   720 */    24,  232,  117,  194,  102,  103,  104,  105,  106,  107,
 /*   730 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
 /*   740 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*   750 */    57,   19,  264,  108,   76,   23,  127,  128,  129,  311,
 /*   760 */   312,  116,  117,  118,  316,   87,  306,   89,  308,  194,

 /*   770 */    92,   22,   59,  194,   22,   43,   44,   45,   46,   47,
 /*   780 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   790 */   194,   95,  217,  218,  265,  102,  103,  104,  105,  106,
 /*   800 */   107,  108,  109,  110,  111,  112,  113,  232,   59,  113,
 /*   810 */    25,   59,  194,  217,  218,  119,  120,  121,  122,  123,
 /*   820 */   124,  125,   19,  145,  194,  194,   23,  131,  232,  116,
 /*   830 */   117,  118,   35,  194,  102,  103,  104,  105,  106,  107,
 /*   840 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
 /*   850 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,


 /*   860 */    57,   19,  194,   66,  194,  116,  117,  118,  116,  117,
 /*   870 */   118,   74,  242,  294,  194,  194,  206,   23,  194,   25,
 /*   880 */   194,  111,  112,  113,   25,   43,   44,   45,   46,   47,
 /*   890 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   900 */    24,  194,  194,  217,  218,  102,  103,  104,  105,  106,
 /*   910 */   107,  108,  109,  110,  111,  112,  113,  241,  232,  194,
 /*   920 */   212,  213,  242,  242,  217,  218,  242,  130,   11,  253,
 /*   930 */   194,  255,   19,  265,  149,   59,  306,  194,  308,  232,
 /*   940 */   309,  310,  217,  218,  102,  103,  104,  105,  106,  107,
 /*   950 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
 /*   960 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*   970 */    57,  194,  194,   59,  194,  239,   19,  194,   25,  254,
 /*   980 */   303,  304,   23,  194,   25,  126,  306,  306,  308,  308,
 /*   990 */   306,  271,  308,  117,  286,  217,  218,  217,  218,  194,
 /*  1000 */   194,  159,   45,   46,   47,   48,   49,   50,   51,   52,
 /*  1010 */    53,   54,   55,   56,   57,  102,  103,  104,  105,  106,
 /*  1020 */   107,  108,  109,  110,  111,  112,  113,   59,  239,  194,
 /*  1030 */   116,  117,  118,  260,  254,  194,  240,  241,  194,  233,
 /*  1040 */   205,  240,  241,  205,  239,  128,  129,  270,  265,  253,
 /*  1050 */   194,  255,  217,  218,  253,  194,  255,  143,  280,  102,







 /*  1060 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*  1070 */   113,  118,  159,  217,  218,  240,  241,  118,  240,  241,
 /*  1080 */   194,  194,  194,  239,  116,  117,  118,   22,  253,  254,
 /*  1090 */   255,  253,   19,  255,  233,  194,  143,   24,  263,  212,
 /*  1100 */   213,  194,  143,  217,  218,  217,  218,  261,  262,  271,
 /*  1110 */   254,  143,   19,    7,    8,    9,   43,   44,   45,   46,


 /*  1120 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*  1130 */    57,   16,   19,   22,   23,  294,   43,   44,   45,   46,
 /*  1140 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*  1150 */    57,  312,  194,  214,   21,  316,   43,   44,   45,   46,
 /*  1160 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
 /*  1170 */    57,  106,  107,  286,  194,  102,  103,  104,  105,  106,
 /*  1180 */   107,  108,  109,  110,  111,  112,  113,  207,  158,   59,
 /*  1190 */   160,   22,   77,   24,   79,  102,  103,  104,  105,  106,
 /*  1200 */   107,  108,  109,  110,  111,  112,  113,  194,  194,  229,
 /*  1210 */   194,  231,  101,   80,   22,  102,  103,  104,  105,  106,
 /*  1220 */   107,  108,  109,  110,  111,  112,  113,  288,   59,   12,
 /*  1230 */   217,  218,  293,  217,  218,   19,  106,  107,   59,   19,
 /*  1240 */    16,  127,  128,  129,   27,  115,  116,  117,  118,  194,
 /*  1250 */   120,   59,   22,  194,   24,  194,  123,  100,  128,   42,

 /*  1260 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,

 /*  1270 */    54,   55,   56,   57,  117,  194,  217,  218,  121,  100,
 /*  1280 */    63,  194,  245,  153,  194,  155,  117,   19,  115,  194,
 /*  1290 */    73,  214,  194,  256,  161,  116,  117,  194,  217,  218,
 /*  1300 */   121,   77,  194,   79,  217,  218,  194,  217,  218,  117,
 /*  1310 */   153,  154,  155,  254,   46,  217,  218,  144,  102,  103,
 /*  1320 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
 /*  1330 */   232,  270,  153,  154,  155,  115,  116,   66,   19,   20,
 /*  1340 */   183,   22,   12,  312,  254,  194,  262,  316,  209,  210,
 /*  1350 */   266,  239,  194,  194,  108,   36,   85,   27,   19,   20,
 /*  1360 */   265,   22,  183,  245,  144,   94,   25,   48,  217,  218,
 /*  1370 */   293,  194,   42,  270,  256,   36,  217,  218,   59,  194,
 /*  1380 */    25,  135,  194,  115,  194,  161,  140,  194,  194,   15,
 /*  1390 */    71,  194,  312,   63,  217,  218,  316,  194,   59,  131,
 /*  1400 */   301,  302,  217,  218,   85,  217,  218,  217,  218,   90,
 /*  1410 */    71,  217,  218,   19,  217,  218,  245,  146,  262,  100,
 /*  1420 */   217,  218,  266,  265,   85,  106,  107,  256,  312,   90,
 /*  1430 */   209,  210,  316,  114,   60,  116,  117,  118,  194,  100,
 /*  1440 */   121,  194,  194,  145,  115,  106,  107,   19,   46,   19,
 /*  1450 */    20,   24,   22,  114,  194,  116,  117,  118,  194,  245,
 /*  1460 */   121,  194,  164,  194,  217,  218,   36,  194,  258,  259,
 /*  1470 */   256,  194,  153,  154,  155,  156,  157,  217,  218,  150,
 /*  1480 */    31,  217,  218,  142,  217,  218,  217,  218,   39,   59,
 /*  1490 */   217,  218,  153,  154,  155,  156,  157,  149,  150,    5,
 /*  1500 */   145,   71,  183,  245,   10,   11,   12,   13,   14,  194,
 /*  1510 */   116,   17,  129,  227,  256,   85,  194,  115,  194,   23,
 /*  1520 */    90,   25,  183,   99,   30,   97,   32,   22,   22,  194,
 /*  1530 */   100,  194,  217,  218,   40,  152,  106,  107,   23,  217,
 /*  1540 */   218,  194,   19,   20,  114,   22,  116,  117,  118,  257,
 /*  1550 */   194,  121,  217,  218,  217,  218,  194,  133,   53,   36,
 /*  1560 */    23,   23,   25,   25,   70,  120,  121,   61,  141,    7,
 /*  1570 */     8,  121,   78,  217,  218,   81,   23,  227,   25,  217,
 /*  1580 */   218,  131,   59,  153,  154,  155,  156,  157,    0,    1,
 /*  1590 */     2,   59,   98,    5,   71,   23,  227,   25,   10,   11,
 /*  1600 */    12,   13,   14,   83,   84,   17,   23,   23,   25,   25,
 /*  1610 */    59,  194,  194,  183,   23,   23,   25,   25,   30,  194,
 /*  1620 */    32,   19,   20,  100,   22,  194,  194,  133,   40,  106,
 /*  1630 */   107,  108,  138,  139,  194,  217,  218,  114,   36,  116,
 /*  1640 */   117,  118,  217,  218,  121,  194,  194,  194,   23,  117,

 /*  1650 */    25,  194,   23,   23,   25,   25,  162,  194,   70,  194,
 /*  1660 */   145,   59,   23,  153,   25,  155,   78,  194,  117,   81,
 /*  1670 */   217,  218,  194,   71,  217,  218,  153,  154,  155,  156,
 /*  1680 */   157,  194,  217,  218,  194,   23,   98,   25,  321,  194,
 /*  1690 */   217,  218,  194,   19,   20,  194,   22,  153,   23,  155,
 /*  1700 */    25,  194,  100,  194,  217,  218,  183,  194,  106,  107,
 /*  1710 */    36,  194,  217,  218,  237,  194,  114,  243,  116,  117,
 /*  1720 */   118,  133,  194,  121,  217,  218,  138,  139,  194,  194,
 /*  1730 */   194,  290,  289,   59,  217,  218,  194,  194,  217,  218,
 /*  1740 */   194,  194,  140,  194,  194,   71,  194,  244,  194,  194,
 /*  1750 */   162,  217,  218,  194,  194,  153,  154,  155,  156,  157,
 /*  1760 */   217,  218,  194,  217,  218,  194,  217,  218,  257,  217,
 /*  1770 */   218,  217,  218,  257,  100,  194,  257,  217,  218,  257,
 /*  1780 */   106,  107,  215,  299,  194,  183,  192,  194,  114,  194,
 /*  1790 */   116,  117,  118,    1,    2,  121,  221,    5,  217,  218,
 /*  1800 */   273,  197,   10,   11,   12,   13,   14,  217,  218,   17,
 /*  1810 */   217,  218,  217,  218,  140,  194,  246,  194,  273,  295,
 /*  1820 */   247,  273,   30,  247,   32,  269,  269,  153,  154,  155,
 /*  1830 */   156,  157,   40,  246,  273,  295,  230,  226,  217,  218,
 /*  1840 */   217,  218,  220,  261,  220,  282,  220,   19,   20,  244,
 /*  1850 */    22,  250,  141,  250,  246,   60,  201,  183,  261,  261,
 /*  1860 */   261,  201,   70,  299,   36,  299,  201,   38,  151,  150,
 /*  1870 */    78,  285,   22,   81,  296,  296,   43,  235,   18,  238,
 /*  1880 */   201,  274,  272,  238,  238,  238,   18,   59,  200,  149,
 /*  1890 */    98,  247,  274,  274,  235,  247,  247,  247,  235,   71,
 /*  1900 */   272,  201,  200,  158,  292,   62,  291,  201,  200,   22,
 /*  1910 */   201,  222,  200,  222,  201,  200,  115,  219,  219,   64,
 /*  1920 */   219,  228,   22,  126,  221,  133,  165,  222,  100,  225,
 /*  1930 */   138,  139,  225,  219,  106,  107,   24,  219,  228,  219,
 /*  1940 */   219,  307,  114,  113,  116,  117,  118,  315,  284,  121,
 /*  1950 */   284,  222,  201,   91,  162,  320,  320,   82,  148,  267,
 /*  1960 */   145,  267,   22,  279,  201,  158,  281,  251,  147,  146,
 /*  1970 */    25,  203,  250,  249,  251,  248,   13,  247,  195,  195,
 /*  1980 */     6,  153,  154,  155,  156,  157,  193,  193,  305,  193,
 /*  1990 */   208,  305,  302,  214,  214,  214,  208,  223,  223,  214,
 /*  2000 */     4,  215,  215,  214,    3,   22,  208,  163,   15,   23,
 /*  2010 */    16,  183,   23,  139,  151,  130,   25,   20,  142,   24,
 /*  2020 */    16,  144,    1,  142,  130,  130,   61,   37,   53,  151,
 /*  2030 */    53,   53,   53,  130,  116,    1,   34,  141,    5,   22,
 /*  2040 */   115,  161,   75,   25,   68,  141,   41,  115,   68,   24,
 /*  2050 */    20,   19,  131,  125,   67,   67,   96,   22,   22,   22,
 /*  2060 */    37,   23,   22,   24,   22,   59,   67,   23,  149,   28,
 /*  2070 */    22,   25,   23,   23,   23,   22,  141,   34,   97,   23,
 /*  2080 */    23,   34,  116,   22,  143,   25,   34,   75,   34,   34,
 /*  2090 */    75,   88,   34,   86,   23,   22,   34,   25,   24,   34,
 /*  2100 */    25,   93,   23,   44,  142,   23,  142,   23,   23,   22,
 /*  2110 */    11,   25,   23,   25,   23,   22,   22,   22,    1,   23,
 /*  2120 */    23,   23,   22,   22,   15,  141,  141,   25,   25,    1,
 /*  2130 */   322,  322,  322,  135,  322,  322,  322,  322,  322,  322,
 /*  2140 */   322,  141,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2150 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2160 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2170 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2180 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2190 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2200 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2210 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2220 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2230 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2240 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2250 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2260 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2270 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2280 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2290 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2300 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2310 */   322,  322,  322,  322,  322,  322,  322,  322,  322,  322,
 /*  2320 */   322,  322,  322,  322,  322,  322,  322,  322,







};
#define YY_SHIFT_COUNT    (582)
#define YY_SHIFT_MIN      (0)
#define YY_SHIFT_MAX      (2128)
static const unsigned short int yy_shift_ofst[] = {
 /*     0 */  1792, 1588, 1494,  322,  322,  399,  306, 1319, 1339, 1430,
 /*    10 */  1828, 1828, 1828,  580,  399,  399,  399,  399,  399,    0,
 /*    20 */     0,  214, 1093, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*    30 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1130, 1130,
 /*    40 */   365,  365,   55,  278,  436,  713,  713,  201,  201,  201,
 /*    50 */   201,   40,  111,  258,  361,  469,  512,  583,  622,  693,
 /*    60 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
 /*    70 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
 /*    80 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1523, 1602,
 /*    90 */  1674, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*   100 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*   110 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*   120 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*   130 */  1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828, 1828,
 /*   140 */   137,  181,  181,  181,  181,  181,  181,  181,   96,  222,
 /*   150 */   143,  477,  713, 1133, 1268,  713,  713,   79,   79,  713,
 /*   160 */   770,   83,   65,   65,   65,  288,  162,  162, 2142, 2142,
 /*   170 */   696,  696,  696,  238,  474,  474,  474,  474, 1217, 1217,
 /*   180 */   678,  477,  324,  398,  713,  713,  713,  713,  713,  713,
 /*   190 */   713,  713,  713,  713,  713,  713,  713,  713,  713,  713,
 /*   200 */   713,  713,  713, 1220,  366,  366,  713,  917,  283,  283,
 /*   210 */   434,  434,  605,  605, 1298, 2142, 2142, 2142, 2142, 2142,
 /*   220 */  2142, 2142, 1179, 1157, 1157,  487,  527,  585,  645,  749,
 /*   230 */   914,  968,  752,  713,  713,  713,  713,  713,  713,  713,
 /*   240 */   713,  713,  713,  303,  713,  713,  713,  713,  713,  713,
 /*   250 */   713,  713,  713,  713,  713,  713,  797,  797,  797,  713,
 /*   260 */   713,  713,  959,  713,  713,  713, 1169, 1271,  713,  713,
 /*   270 */  1330,  713,  713,  713,  713,  713,  713,  713,  713,  629,
 /*   280 */     7,   91,  876,  876,  876,  876,  953,   91,   91, 1246,
 /*   290 */  1065, 1106, 1374, 1329, 1348,  468, 1348, 1394,  785, 1329,
 /*   300 */  1329,  785, 1329,  468, 1394,  859,  854, 1402, 1449, 1449,
 /*   310 */  1449, 1173, 1173, 1173, 1173, 1355, 1355, 1030, 1341,  405,
 /*   320 */  1230, 1795, 1795, 1711, 1711, 1829, 1829, 1711, 1717, 1719,
 /*   330 */  1850, 1833, 1860, 1860, 1860, 1860, 1711, 1868, 1740, 1719,
 /*   340 */  1719, 1740, 1850, 1833, 1740, 1833, 1740, 1711, 1868, 1745,
 /*   350 */  1843, 1711, 1868, 1887, 1711, 1868, 1711, 1868, 1887, 1801,
 /*   360 */  1801, 1801, 1855, 1900, 1900, 1887, 1801, 1797, 1801, 1855,
 /*   370 */  1801, 1801, 1761, 1912, 1830, 1830, 1887, 1711, 1862, 1862,
 /*   380 */  1875, 1875, 1810, 1815, 1940, 1711, 1807, 1810, 1821, 1823,
 /*   390 */  1740, 1945, 1963, 1963, 1974, 1974, 1974, 2142, 2142, 2142,
 /*   400 */  2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142,
 /*   410 */  2142, 2142,   20, 1224,  256, 1111, 1115, 1114, 1192, 1496,
 /*   420 */  1424, 1505, 1427,  355, 1383, 1537, 1506, 1538, 1553, 1583,
 /*   430 */  1584, 1591, 1625,  541, 1445, 1562, 1450, 1572, 1515, 1428,
 /*   440 */  1532, 1592, 1629, 1520, 1630, 1639, 1510, 1544, 1662, 1675,
 /*   450 */  1551,   48, 1996, 2001, 1983, 1844, 1993, 1994, 1986, 1989,
 /*   460 */  1874, 1863, 1885, 1991, 1991, 1995, 1876, 1997, 1877, 2004,
 /*   470 */  2021, 1881, 1894, 1991, 1895, 1965, 1990, 1991, 1878, 1975,
 /*   480 */  1977, 1978, 1979, 1903, 1918, 2002, 1896, 2034, 2033, 2017,
 /*   490 */  1925, 1880, 1976, 2018, 1980, 1967, 2005, 1904, 1932, 2025,
 /*   500 */  2030, 2032, 1921, 1928, 2035, 1987, 2036, 2037, 2038, 2040,
 /*   510 */  1988, 2006, 2039, 1960, 2041, 2042, 1999, 2023, 2044, 2043,
 /*   520 */  1919, 2048, 2049, 2050, 2046, 2051, 2053, 1981, 1935, 2056,
 /*   530 */  2057, 1966, 2047, 2061, 1941, 2060, 2052, 2054, 2055, 2058,
 /*   540 */  2003, 2012, 2007, 2059, 2015, 2008, 2062, 2071, 2073, 2074,
 /*   550 */  2072, 2075, 2065, 1962, 1964, 2079, 2060, 2082, 2084, 2085,
 /*   560 */  2087, 2086, 2089, 2088, 2091, 2093, 2099, 2094, 2095, 2096,
 /*   570 */  2097, 2100, 2101, 2102, 1998, 1984, 1985, 2000, 2103, 2098,
 /*   580 */  2109, 2117, 2128,
};
#define YY_REDUCE_COUNT (411)
#define YY_REDUCE_MIN   (-275)
#define YY_REDUCE_MAX   (1798)
static const short yy_reduce_ofst[] = {
 /*     0 */   -71,  194,  343,  835, -180, -177,  838, -194, -188, -185,
 /*    10 */  -183,   82,  183,  -65,  133,  245,  346,  407,  458, -178,
 /*    20 */    75, -275,   -4,  310,  312,  489,  575,  596,  463,  686,
 /*    30 */   707,  725,  780, 1098,  856,  778, 1059, 1090,  708,  887,
 /*    40 */    86,  448,  980,  630,  680,  681,  684,  796,  801,  796,
 /*    50 */   801, -261, -261, -261, -261, -261, -261, -261, -261, -261,
 /*    60 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
 /*    70 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
 /*    80 */  -261, -261, -261, -261, -261, -261, -261, -261,  391,  886,
 /*    90 */   888, 1013, 1016, 1081, 1087, 1151, 1159, 1177, 1185, 1188,
 /*   100 */  1190, 1194, 1197, 1203, 1247, 1260, 1264, 1267, 1269, 1273,
 /*   110 */  1315, 1322, 1335, 1337, 1356, 1362, 1418, 1425, 1453, 1457,
 /*   120 */  1465, 1473, 1487, 1495, 1507, 1517, 1521, 1534, 1543, 1546,
 /*   130 */  1549, 1552, 1554, 1560, 1581, 1590, 1593, 1595, 1621, 1623,
 /*   140 */  -261, -261, -261, -261, -261, -261, -261, -261, -261, -261,
 /*   150 */  -261, -186, -117,  260,  263,  460,  631,  -74,  497, -181,
 /*   160 */  -261,  939,  176,  274,  338,  676, -261, -261, -261, -261,
 /*   170 */  -212, -212, -212, -184,  149,  777, 1061, 1103,  265,  419,
 /*   180 */  -254,  670,  677,  677,  -11, -129,  184,  488,  736,  789,
 /*   190 */   805,  844,  403,  529,  579,  668,  783,  841, 1158, 1112,
 /*   200 */   806,  861, 1095,  846,  839, 1031, -189, 1077, 1080, 1116,
 /*   210 */  1084, 1156, 1139, 1221,   46, 1099, 1037, 1118, 1171, 1214,
 /*   220 */  1210, 1258, -210, -190, -176, -115,  117,  262,  376,  490,
 /*   230 */   511,  520,  618,  639,  743,  901,  907,  958, 1014, 1055,
 /*   240 */  1108, 1193, 1244,  720, 1248, 1277, 1324, 1347, 1417, 1431,
 /*   250 */  1432, 1440, 1451, 1452, 1463, 1478, 1286, 1350, 1369, 1490,
 /*   260 */  1498, 1501,  773, 1509, 1513, 1528, 1292, 1367, 1535, 1536,
 /*   270 */  1477, 1542,  376, 1547, 1550, 1555, 1559, 1568, 1571, 1441,
 /*   280 */  1443, 1474, 1511, 1516, 1519, 1522,  773, 1474, 1474, 1503,
 /*   290 */  1567, 1594, 1484, 1527, 1556, 1570, 1557, 1524, 1573, 1545,
 /*   300 */  1548, 1576, 1561, 1587, 1540, 1575, 1606, 1611, 1622, 1624,
 /*   310 */  1626, 1582, 1597, 1598, 1599, 1601, 1603, 1563, 1608, 1605,
 /*   320 */  1604, 1564, 1566, 1655, 1660, 1578, 1579, 1665, 1586, 1607,
 /*   330 */  1610, 1642, 1641, 1645, 1646, 1647, 1679, 1688, 1644, 1618,
 /*   340 */  1619, 1648, 1628, 1659, 1649, 1663, 1650, 1700, 1702, 1612,
 /*   350 */  1615, 1706, 1708, 1689, 1709, 1712, 1713, 1715, 1691, 1698,
 /*   360 */  1699, 1701, 1693, 1704, 1707, 1705, 1714, 1703, 1718, 1710,
 /*   370 */  1720, 1721, 1632, 1634, 1664, 1666, 1729, 1751, 1635, 1636,
 /*   380 */  1692, 1694, 1716, 1722, 1684, 1763, 1685, 1723, 1724, 1727,
 /*   390 */  1730, 1768, 1783, 1784, 1793, 1794, 1796, 1683, 1686, 1690,
 /*   400 */  1782, 1779, 1780, 1781, 1785, 1788, 1774, 1775, 1786, 1787,
 /*   410 */  1789, 1798,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */  1663, 1663, 1663, 1491, 1254, 1367, 1254, 1254, 1254, 1254,
 /*    10 */  1491, 1491, 1491, 1254, 1254, 1254, 1254, 1254, 1254, 1397,
 /*    20 */  1397, 1544, 1287, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*    30 */  1254, 1254, 1254, 1254, 1254, 1490, 1254, 1254, 1254, 1254,
 /*    40 */  1578, 1578, 1254, 1254, 1254, 1254, 1254, 1563, 1562, 1254,
 /*    50 */  1254, 1254, 1406, 1254, 1413, 1254, 1254, 1254, 1254, 1254,
 /*    60 */  1492, 1493, 1254, 1254, 1254, 1543, 1545, 1508, 1420, 1419,
 /*    70 */  1418, 1417, 1526, 1385, 1411, 1404, 1408, 1487, 1488, 1486,
 /*    80 */  1641, 1493, 1492, 1254, 1407, 1455, 1471, 1454, 1254, 1254,
 /*    90 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   100 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   110 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   120 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   130 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   140 */  1463, 1470, 1469, 1468, 1477, 1467, 1464, 1457, 1456, 1458,
 /*   150 */  1459, 1278, 1254, 1275, 1329, 1254, 1254, 1254, 1254, 1254,
 /*   160 */  1460, 1287, 1448, 1447, 1446, 1254, 1474, 1461, 1473, 1472,
 /*   170 */  1551, 1615, 1614, 1509, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   180 */  1578, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   190 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   200 */  1254, 1254, 1254, 1387, 1578, 1578, 1254, 1287, 1578, 1578,
 /*   210 */  1388, 1388, 1283, 1283, 1391, 1558, 1358, 1358, 1358, 1358,
 /*   220 */  1367, 1358, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   230 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1548, 1546, 1254,
 /*   240 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   250 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   260 */  1254, 1254, 1254, 1254, 1254, 1254, 1363, 1254, 1254, 1254,
 /*   270 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1608, 1254,
 /*   280 */  1521, 1343, 1363, 1363, 1363, 1363, 1365, 1344, 1342, 1357,
 /*   290 */  1288, 1261, 1655, 1423, 1412, 1364, 1412, 1652, 1410, 1423,
 /*   300 */  1423, 1410, 1423, 1364, 1652, 1304, 1630, 1299, 1397, 1397,
 /*   310 */  1397, 1387, 1387, 1387, 1387, 1391, 1391, 1489, 1364, 1357,
 /*   320 */  1254, 1655, 1655, 1373, 1373, 1654, 1654, 1373, 1509, 1638,
 /*   330 */  1432, 1332, 1338, 1338, 1338, 1338, 1373, 1272, 1410, 1638,
 /*   340 */  1638, 1410, 1432, 1332, 1410, 1332, 1410, 1373, 1272, 1525,
 /*   350 */  1649, 1373, 1272, 1499, 1373, 1272, 1373, 1272, 1499, 1330,
 /*   360 */  1330, 1330, 1319, 1254, 1254, 1499, 1330, 1304, 1330, 1319,
 /*   370 */  1330, 1330, 1596, 1254, 1503, 1503, 1499, 1373, 1588, 1588,
 /*   380 */  1400, 1400, 1405, 1391, 1494, 1373, 1254, 1405, 1403, 1401,
 /*   390 */  1410, 1322, 1611, 1611, 1607, 1607, 1607, 1660, 1660, 1558,
 /*   400 */  1623, 1287, 1287, 1287, 1287, 1623, 1306, 1306, 1288, 1288,
 /*   410 */  1287, 1623, 1254, 1254, 1254, 1254, 1254, 1254, 1618, 1254,
 /*   420 */  1553, 1510, 1377, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   430 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1564,
 /*   440 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   450 */  1254, 1437, 1254, 1257, 1555, 1254, 1254, 1254, 1254, 1254,
 /*   460 */  1254, 1254, 1254, 1414, 1415, 1378, 1254, 1254, 1254, 1254,
 /*   470 */  1254, 1254, 1254, 1429, 1254, 1254, 1254, 1424, 1254, 1254,
 /*   480 */  1254, 1254, 1254, 1254, 1254, 1254, 1651, 1254, 1254, 1254,
 /*   490 */  1254, 1254, 1254, 1524, 1523, 1254, 1254, 1375, 1254, 1254,
 /*   500 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   510 */  1254, 1302, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   520 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   530 */  1254, 1254, 1254, 1254, 1254, 1402, 1254, 1254, 1254, 1254,
 /*   540 */  1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   550 */  1593, 1392, 1254, 1254, 1254, 1254, 1642, 1254, 1254, 1254,
 /*   560 */  1254, 1352, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254,
 /*   570 */  1254, 1254, 1254, 1634, 1346, 1438, 1254, 1441, 1276, 1254,
 /*   580 */  1266, 1254, 1254,
};
/********** End of lemon-generated parsing tables *****************************/

/* The next table maps tokens (terminal symbols) into fallback tokens.
** If a construct like the following:
174242
174243
174244
174245
174246
174247
174248
174249
174250
174251
174252
174253
174254
174255
174256
174257
174258
174259
174260
174261
174262
174263
174264
174265
174266
174267
174268
174269
174270
174271
174272
174273
174274
174275
174276
174277
174278
174279
174280
174281
174282
174283
174284
174285
174286
174287
174288
174289
174290
174291
174292
174293
174294
174295
174296
174297
174298
174299
174300
174301
174302
174303
174304
174305
174306
174307
174308
174309
174310
174311
174312
174313
174314
174315
174316
174317
174318
174319
174320
174321
174322
174323
174324
174325
174326
174327
174328
174329
174330
174331
174332
174333
174334
174335
174336
174337
174338
174339
174340
174341
174342
174343
174344
174345
174346
174347
174348
174349
174350
174351
174352
174353
174354
174355
** to revert to identifiers if they keyword does not apply in the context where
** it appears.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
    0,  /*          $ => nothing */
    0,  /*       SEMI => nothing */
   60,  /*    EXPLAIN => ID */
   60,  /*      QUERY => ID */
   60,  /*       PLAN => ID */
   60,  /*      BEGIN => ID */
    0,  /* TRANSACTION => nothing */
   60,  /*   DEFERRED => ID */
   60,  /*  IMMEDIATE => ID */
   60,  /*  EXCLUSIVE => ID */
    0,  /*     COMMIT => nothing */
   60,  /*        END => ID */
   60,  /*   ROLLBACK => ID */
   60,  /*  SAVEPOINT => ID */
   60,  /*    RELEASE => ID */
    0,  /*         TO => nothing */
    0,  /*      TABLE => nothing */
    0,  /*     CREATE => nothing */
   60,  /*         IF => ID */
    0,  /*        NOT => nothing */
    0,  /*     EXISTS => nothing */
   60,  /*       TEMP => ID */
    0,  /*         LP => nothing */
    0,  /*         RP => nothing */
    0,  /*         AS => nothing */
    0,  /*      COMMA => nothing */
   60,  /*    WITHOUT => ID */
   60,  /*      ABORT => ID */
   60,  /*     ACTION => ID */
   60,  /*      AFTER => ID */
   60,  /*    ANALYZE => ID */
   60,  /*        ASC => ID */
   60,  /*     ATTACH => ID */
   60,  /*     BEFORE => ID */
   60,  /*         BY => ID */
   60,  /*    CASCADE => ID */
   60,  /*       CAST => ID */
   60,  /*   CONFLICT => ID */
   60,  /*   DATABASE => ID */
   60,  /*       DESC => ID */
   60,  /*     DETACH => ID */
   60,  /*       EACH => ID */
   60,  /*       FAIL => ID */
    0,  /*         OR => nothing */
    0,  /*        AND => nothing */
    0,  /*         IS => nothing */
    0,  /*      ISNOT => nothing */
   60,  /*      MATCH => ID */
   60,  /*    LIKE_KW => ID */
    0,  /*    BETWEEN => nothing */
    0,  /*         IN => nothing */
    0,  /*     ISNULL => nothing */
    0,  /*    NOTNULL => nothing */
    0,  /*         NE => nothing */
    0,  /*         EQ => nothing */
    0,  /*         GT => nothing */
    0,  /*         LE => nothing */
    0,  /*         LT => nothing */
    0,  /*         GE => nothing */
    0,  /*     ESCAPE => nothing */
    0,  /*         ID => nothing */
   60,  /*   COLUMNKW => ID */
   60,  /*         DO => ID */
   60,  /*        FOR => ID */
   60,  /*     IGNORE => ID */
   60,  /*  INITIALLY => ID */
   60,  /*    INSTEAD => ID */
   60,  /*         NO => ID */
   60,  /*        KEY => ID */
   60,  /*         OF => ID */
   60,  /*     OFFSET => ID */
   60,  /*     PRAGMA => ID */
   60,  /*      RAISE => ID */
   60,  /*  RECURSIVE => ID */
   60,  /*    REPLACE => ID */
   60,  /*   RESTRICT => ID */
   60,  /*        ROW => ID */
   60,  /*       ROWS => ID */
   60,  /*    TRIGGER => ID */
   60,  /*     VACUUM => ID */
   60,  /*       VIEW => ID */
   60,  /*    VIRTUAL => ID */
   60,  /*       WITH => ID */
   60,  /*      NULLS => ID */
   60,  /*      FIRST => ID */
   60,  /*       LAST => ID */
   60,  /*    CURRENT => ID */
   60,  /*  FOLLOWING => ID */
   60,  /*  PARTITION => ID */
   60,  /*  PRECEDING => ID */
   60,  /*      RANGE => ID */
   60,  /*  UNBOUNDED => ID */
   60,  /*    EXCLUDE => ID */
   60,  /*     GROUPS => ID */
   60,  /*     OTHERS => ID */
   60,  /*       TIES => ID */
   60,  /*  GENERATED => ID */
   60,  /*     ALWAYS => ID */
   60,  /* MATERIALIZED => ID */
   60,  /*    REINDEX => ID */
   60,  /*     RENAME => ID */
   60,  /*   CTIME_KW => ID */
    0,  /*        ANY => nothing */
    0,  /*     BITAND => nothing */
    0,  /*      BITOR => nothing */
    0,  /*     LSHIFT => nothing */
    0,  /*     RSHIFT => nothing */
    0,  /*       PLUS => nothing */
    0,  /*      MINUS => nothing */







|
|
|
|

|
|
|

|
|
|
|



|


|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



<
|
|












|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







173447
173448
173449
173450
173451
173452
173453
173454
173455
173456
173457
173458
173459
173460
173461
173462
173463
173464
173465
173466
173467
173468
173469
173470
173471
173472
173473
173474
173475
173476
173477
173478
173479
173480
173481
173482
173483
173484
173485
173486
173487
173488
173489
173490
173491
173492
173493
173494
173495
173496
173497

173498
173499
173500
173501
173502
173503
173504
173505
173506
173507
173508
173509
173510
173511
173512
173513
173514
173515
173516
173517
173518
173519
173520
173521
173522
173523
173524
173525
173526
173527
173528
173529
173530
173531
173532
173533
173534
173535
173536
173537
173538
173539
173540
173541
173542
173543
173544
173545
173546
173547
173548
173549
173550
173551
173552
173553
173554
173555
173556
173557
173558
173559
** to revert to identifiers if they keyword does not apply in the context where
** it appears.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
    0,  /*          $ => nothing */
    0,  /*       SEMI => nothing */
   59,  /*    EXPLAIN => ID */
   59,  /*      QUERY => ID */
   59,  /*       PLAN => ID */
   59,  /*      BEGIN => ID */
    0,  /* TRANSACTION => nothing */
   59,  /*   DEFERRED => ID */
   59,  /*  IMMEDIATE => ID */
   59,  /*  EXCLUSIVE => ID */
    0,  /*     COMMIT => nothing */
   59,  /*        END => ID */
   59,  /*   ROLLBACK => ID */
   59,  /*  SAVEPOINT => ID */
   59,  /*    RELEASE => ID */
    0,  /*         TO => nothing */
    0,  /*      TABLE => nothing */
    0,  /*     CREATE => nothing */
   59,  /*         IF => ID */
    0,  /*        NOT => nothing */
    0,  /*     EXISTS => nothing */
   59,  /*       TEMP => ID */
    0,  /*         LP => nothing */
    0,  /*         RP => nothing */
    0,  /*         AS => nothing */
    0,  /*      COMMA => nothing */
   59,  /*    WITHOUT => ID */
   59,  /*      ABORT => ID */
   59,  /*     ACTION => ID */
   59,  /*      AFTER => ID */
   59,  /*    ANALYZE => ID */
   59,  /*        ASC => ID */
   59,  /*     ATTACH => ID */
   59,  /*     BEFORE => ID */
   59,  /*         BY => ID */
   59,  /*    CASCADE => ID */
   59,  /*       CAST => ID */
   59,  /*   CONFLICT => ID */
   59,  /*   DATABASE => ID */
   59,  /*       DESC => ID */
   59,  /*     DETACH => ID */
   59,  /*       EACH => ID */
   59,  /*       FAIL => ID */
    0,  /*         OR => nothing */
    0,  /*        AND => nothing */
    0,  /*         IS => nothing */

   59,  /*      MATCH => ID */
   59,  /*    LIKE_KW => ID */
    0,  /*    BETWEEN => nothing */
    0,  /*         IN => nothing */
    0,  /*     ISNULL => nothing */
    0,  /*    NOTNULL => nothing */
    0,  /*         NE => nothing */
    0,  /*         EQ => nothing */
    0,  /*         GT => nothing */
    0,  /*         LE => nothing */
    0,  /*         LT => nothing */
    0,  /*         GE => nothing */
    0,  /*     ESCAPE => nothing */
    0,  /*         ID => nothing */
   59,  /*   COLUMNKW => ID */
   59,  /*         DO => ID */
   59,  /*        FOR => ID */
   59,  /*     IGNORE => ID */
   59,  /*  INITIALLY => ID */
   59,  /*    INSTEAD => ID */
   59,  /*         NO => ID */
   59,  /*        KEY => ID */
   59,  /*         OF => ID */
   59,  /*     OFFSET => ID */
   59,  /*     PRAGMA => ID */
   59,  /*      RAISE => ID */
   59,  /*  RECURSIVE => ID */
   59,  /*    REPLACE => ID */
   59,  /*   RESTRICT => ID */
   59,  /*        ROW => ID */
   59,  /*       ROWS => ID */
   59,  /*    TRIGGER => ID */
   59,  /*     VACUUM => ID */
   59,  /*       VIEW => ID */
   59,  /*    VIRTUAL => ID */
   59,  /*       WITH => ID */
   59,  /*      NULLS => ID */
   59,  /*      FIRST => ID */
   59,  /*       LAST => ID */
   59,  /*    CURRENT => ID */
   59,  /*  FOLLOWING => ID */
   59,  /*  PARTITION => ID */
   59,  /*  PRECEDING => ID */
   59,  /*      RANGE => ID */
   59,  /*  UNBOUNDED => ID */
   59,  /*    EXCLUDE => ID */
   59,  /*     GROUPS => ID */
   59,  /*     OTHERS => ID */
   59,  /*       TIES => ID */
   59,  /*  GENERATED => ID */
   59,  /*     ALWAYS => ID */
   59,  /* MATERIALIZED => ID */
   59,  /*    REINDEX => ID */
   59,  /*     RENAME => ID */
   59,  /*   CTIME_KW => ID */
    0,  /*        ANY => nothing */
    0,  /*     BITAND => nothing */
    0,  /*      BITOR => nothing */
    0,  /*     LSHIFT => nothing */
    0,  /*     RSHIFT => nothing */
    0,  /*       PLUS => nothing */
    0,  /*      MINUS => nothing */
174412
174413
174414
174415
174416
174417
174418

174419
174420
174421

174422
174423
174424
174425
174426
174427
174428
    0,  /*     WINDOW => nothing */
    0,  /*       OVER => nothing */
    0,  /*     FILTER => nothing */
    0,  /*     COLUMN => nothing */
    0,  /* AGG_FUNCTION => nothing */
    0,  /* AGG_COLUMN => nothing */
    0,  /*  TRUEFALSE => nothing */

    0,  /*   FUNCTION => nothing */
    0,  /*      UPLUS => nothing */
    0,  /*     UMINUS => nothing */

    0,  /*      TRUTH => nothing */
    0,  /*   REGISTER => nothing */
    0,  /*     VECTOR => nothing */
    0,  /* SELECT_COLUMN => nothing */
    0,  /* IF_NULL_ROW => nothing */
    0,  /*   ASTERISK => nothing */
    0,  /*       SPAN => nothing */