1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
/*
 * Copyright © 2017, 2018 Christian Persch
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <cstdint>
#include <algorithm>
#include <string>

#include "parser.hh"

namespace bte {

namespace parser {

class Sequence;

class Parser {
public:
        friend class Sequence;

        Parser() noexcept
        {
                bte_parser_init(&m_parser);
        }
        Parser(Parser const&) = delete;
        Parser(Parser&&) = delete;

        ~Parser() noexcept
        {
                bte_parser_deinit(&m_parser);
        }

        Parser& operator=(Parser const&) = delete;
        Parser& operator=(Parser&&) = delete;

        inline int feed(uint32_t raw) noexcept
        {
                return bte_parser_feed(&m_parser, raw);
        }

        inline void reset() noexcept
        {
                bte_parser_reset(&m_parser);
        }

protected:
        bte_parser_t m_parser;
}; // class Parser

class Sequence {
public:

        Sequence() = default;
        Sequence(Sequence const&) = delete;
        Sequence(Sequence&&) = delete;
        ~Sequence() = default;

        Sequence(Parser& parser)
        {
                m_seq = &parser.m_parser.seq;
        }

        typedef int number;

        char* ucs4_to_utf8(gunichar const* str,
                           ssize_t len = -1) const noexcept;

        void print() const noexcept;

        /* type:
         *
         *
         * Returns: the type of the sequence, a value from the BTE_SEQ_* enum
         */
        inline constexpr unsigned int type() const noexcept
        {
                return m_seq->type;
        }

        /* command:
         *
         * Returns: the command the sequence codes for, a value
         *   from the BTE_CMD_* enum, or %BTE_CMD_NONE if the command is
         *   unknown
         */
        inline constexpr unsigned int command() const noexcept
        {
                return m_seq->command;
        }

        /* charset:
         *
         * This is the charset to use in a %BTE_CMD_GnDm, %BTE_CMD_GnDMm,
         * %BTE_CMD_CnD or %BTE_CMD_DOCS command.
         *
         * Returns: the charset, a value from the BTE_CHARSET_* enum.
         */
        inline constexpr unsigned int charset() const noexcept
        {
                return BTE_CHARSET_GET_CHARSET(m_seq->charset);
        }

        /* slot:
         *
         * This is the slot in a %BTE_CMD_GnDm, %BTE_CMD_GnDMm,
         * or %BTE_CMD_CnD command.
         *
         * Returns: the slot, a value from the 0..3 for Gn*, or 0..1 for CnD
         */
        inline constexpr unsigned int slot() const noexcept
        {
                return BTE_CHARSET_GET_SLOT(m_seq->charset);
        }

        /* introducer:
         *
         * This is the character introducing the sequence, if any.
         *
         * Returns: the introducing character
         */
        inline constexpr uint32_t introducer() const noexcept
        {
                return m_seq->introducer;
        }

        /* terminator:
         *
         * This is the character terminating the sequence, or, for a
         * %BTE_SEQ_GRAPHIC sequence, the graphic character.
         *
         * Returns: the terminating character
         */
        inline constexpr uint32_t terminator() const noexcept
        {
                return m_seq->terminator;
        }


        /* is_c1:
         *
         * Whether the sequence was introduced with a C0 or C1 control.
         *
         * Returns: the introducing character
         */
        inline constexpr bool is_c1() const noexcept
        {
                return (introducer() & 0x80) != 0;
        }

        /* intermediates:
         *
         * This is the pintro and intermediate characters in the sequence, if any.
         *
         * Returns: the intermediates
         */
        inline constexpr unsigned int intermediates() const noexcept
        {
                return m_seq->intermediates;
        }

        // FIXMEchpe: upgrade to C++17 and use the u32string_view version below, instead
        /*
         * string:
         *
         * This is the string argument of a DCS or OSC sequence.
         *
         * Returns: the string argument
         */
        inline std::u32string string() const noexcept
        {
                size_t len;
                auto buf = bte_seq_string_get(&m_seq->arg_str, &len);
                return std::u32string(reinterpret_cast<char32_t*>(buf), len);
        }

        #if 0
        /*
         * string:
         *
         * This is the string argument of a DCS or OSC sequence.
         *
         * Returns: the string argument
         */
        inline constexpr std::u32string_view string() const noexcept
        {
                size_t len = 0;
                auto buf = bte_seq_string_get(&m_seq->arg_str, &len);
                return std::u32string_view(buf, len);
        }
        #endif

        /*
         * string:
         *
         * This is the string argument of a DCS or OSC sequence.
         *
         * Returns: the string argument
         */
        std::string string_utf8() const noexcept;

        inline char* string_param() const noexcept
        {
                size_t len = 0;
                auto buf = bte_seq_string_get(&m_seq->arg_str, &len);
                return ucs4_to_utf8(buf, len);
        }

        /* size:
         *
         * Returns: the number of parameters
         */
        inline constexpr unsigned int size() const noexcept
        {
                return m_seq->n_args;
        }


        /* size:
         *
         * Returns: the number of parameter blocks, counting runs of subparameters
         *   as only one parameter
         */
        inline constexpr unsigned int size_final() const noexcept
        {
                return m_seq->n_final_args;
        }

        /* capacity:
         *
         * Returns: the number of parameter blocks, counting runs of subparameters
         *   as only one parameter
         */
        inline constexpr unsigned int capacity() const noexcept
        {
                return G_N_ELEMENTS(m_seq->args);
        }

        /* param:
         * @idx:
         * @default_v: the value to use for default parameters
         *
         * Returns: the value of the parameter at index @idx, or @default_v if
         *   the parameter at this index has default value, or the index
         *   is out of bounds
         */
        inline constexpr int param(unsigned int idx,
                                   int default_v = -1) const noexcept
        {
                return __builtin_expect(idx < size(), 1) ? bte_seq_arg_value(m_seq->args[idx], default_v) : default_v;
        }

        /* param:
         * @idx:
         * @default_v: the value to use for default parameters
         * @min_v: the minimum value
         * @max_v: the maximum value
         *
         * Returns: the value of the parameter at index @idx, or @default_v if
         *   the parameter at this index has default value, or the index
         *   is out of bounds. The returned value is clamped to the
         *   range @min_v..@max_v (or returns min_v, if min_v > max_v).
         */
        inline constexpr int param(unsigned int idx,
                                   int default_v,
                                   int min_v,
                                   int max_v) const noexcept
        {
                auto v = param(idx, default_v);
                // not using std::clamp() since it's not guaranteed that min_v <= max_v
                return std::max(std::min(v, max_v), min_v);
        }

        /* param_nonfinal:
         * @idx:
         *
         * Returns: whether the parameter at @idx is nonfinal, i.e.
         * there are more subparameters after it.
         */
        inline constexpr bool param_nonfinal(unsigned int idx) const noexcept
        {
                return __builtin_expect(idx < size(), 1) ? bte_seq_arg_nonfinal(m_seq->args[idx]) : false;
        }

        /* param_default:
         * @idx:
         *
         * Returns: whether the parameter at @idx has default value
         */
        inline constexpr bool param_default(unsigned int idx) const noexcept
        {
                return __builtin_expect(idx < size(), 1) ? bte_seq_arg_default(m_seq->args[idx]) : true;
        }

        /* next:
         * @idx:
         *
         * Returns: the index of the next parameter block
         */
        inline constexpr unsigned int next(unsigned int idx) const noexcept
        {
                /* Find the final parameter */
                while (param_nonfinal(idx))
                        ++idx;
                /* And return the index after that one */
                return ++idx;
        }

        inline constexpr unsigned int cbegin() const noexcept
        {
                return 0;
        }

        inline constexpr unsigned int cend() const noexcept
        {
                return size();
        }

        /* collect:
         *
         * Collects some final parameters.
         *
         * Returns: %true if the sequence parameter list begins with
         *  a run of final parameters that were collected.
         */
        inline constexpr bool collect(unsigned int start_idx,
                                      std::initializer_list<int*> params,
                                      int default_v = -1) const noexcept
        {
                unsigned int idx = start_idx;
                for (auto i : params) {
                        *i = param(idx, default_v);
                        idx = next(idx);
                }

                return (idx - start_idx) == params.size();
        }

        /* collect1:
         * @idx:
         * @default_v:
         *
         * Collects one final parameter.
         *
         * Returns: the parameter value, or @default_v if the parameter has
         *   default value or is not a final parameter
         */
        inline constexpr int collect1(unsigned int idx,
                                      int default_v = -1) const noexcept
        {
                return __builtin_expect(idx < size(), 1) ? bte_seq_arg_value_final(m_seq->args[idx], default_v) : default_v;
        }

        /* collect1:
         * @idx:
         * @default_v:
         * @min_v:
         * @max_v
         *
         * Collects one final parameter.
         *
         * Returns: the parameter value clamped to the @min_v .. @max_v range (or @min_v,
         * if min_v > max_v),
         *   or @default_v if the parameter has default value or is not a final parameter
         */
        inline constexpr int collect1(unsigned int idx,
                                      int default_v,
                                      int min_v,
                                      int max_v) const noexcept
        {
                int v = __builtin_expect(idx < size(), 1) ? bte_seq_arg_value_final(m_seq->args[idx], default_v) : default_v;
                // not using std::clamp() since it's not guaranteed that min_v <= max_v
                return std::max(std::min(v, max_v), min_v);
        }

        /* collect_subparams:
         *
         * Collects some subparameters.
         *
         * Returns: %true if the sequence parameter list contains enough
         *   subparams at @start_idx
         */
        inline constexpr bool collect_subparams(unsigned int start_idx,
                                                std::initializer_list<int*> params,
                                                int default_v = -1) const noexcept
        {
                unsigned int idx = start_idx;
                for (auto i : params) {
                        *i = param(idx++, default_v);
                }

                return idx <= next(start_idx);
        }

        inline explicit operator bool() const { return m_seq != nullptr; }

        /* This is only used in the test suite */
        bte_seq_t** seq_ptr() { return &m_seq; }

private:
        bte_seq_t* m_seq{nullptr};

        char const* type_string() const;
        char const* command_string() const;
}; // class Sequence

/* Helper classes to unify UTF-32 and UTF-8 versions of SequenceBuilder.
 * ::put will only be called with C1 controls, so it's ok to simplify
 * the UTF-8 version to simply prepend 0xc2.
 */
template<typename C>
class DirectEncoder {
public:
        using string_type = std::basic_string<C>;
        inline void put(string_type& s, C const c) const noexcept
        {
                s.push_back(c);
        }
}; // class DirectEncoder

class UTF8Encoder {
public:
        using string_type = std::basic_string<char>;
        inline void put(string_type& s, unsigned char const c) const noexcept
        {
                s.push_back(0xc2);
                s.push_back(c);
        }
}; // class UTF8Encoder

template<class S, class E = DirectEncoder<typename S::value_type>>
class SequenceBuilder {
public:
        using string_type = S;
        using encoder_type = E;

private:
        bte_seq_t m_seq;
        string_type m_arg_str;
        unsigned char m_intermediates[4];
        unsigned char m_n_intermediates{0};
        unsigned char m_param_intro{0};
        encoder_type m_encoder;

public:
        SequenceBuilder(unsigned int type = BTE_SEQ_NONE)
        {
                memset(&m_seq, 0, sizeof(m_seq));
                set_type(type);
        }

        SequenceBuilder(unsigned int type,
                        uint32_t f)
                : SequenceBuilder(type)
        {
                set_final(f);
        }

        SequenceBuilder(unsigned int type,
                        string_type const& str)
                : SequenceBuilder(type)
        {
                set_string(str);
        }

        SequenceBuilder(unsigned int type,
                        string_type&& str)
                : SequenceBuilder(type)
        {
                set_string(str);
        }

        SequenceBuilder(SequenceBuilder const&) = delete;
        SequenceBuilder(SequenceBuilder&&) = delete;
        ~SequenceBuilder() = default;

        SequenceBuilder& operator= (SequenceBuilder const&) = delete;
        SequenceBuilder& operator= (SequenceBuilder&&) = delete;

        inline constexpr unsigned int type() const noexcept { return m_seq.type; }

        inline void set_type(unsigned int type) noexcept
        {
                m_seq.type = type;
        }

        inline void set_final(uint32_t t) noexcept
        {
                m_seq.terminator = t;
        }

        inline void append_intermediate(unsigned char i) noexcept
        {
                assert(unsigned(m_n_intermediates + 1) <= (sizeof(m_intermediates)/sizeof(m_intermediates[0])));

                m_intermediates[m_n_intermediates++] = i;
        }

        inline void append_intermediates(std::initializer_list<unsigned char> l) noexcept
        {
                assert(m_n_intermediates + l.size() <= (sizeof(m_intermediates)/sizeof(m_intermediates[0])));

                for (uint32_t i : l) {
                        m_intermediates[m_n_intermediates++] = i;
                }
        }

        inline void set_param_intro(unsigned char p) noexcept
        {
                m_param_intro = p;
        }

        inline void append_param(int p) noexcept
        {
                assert(m_seq.n_args + 1 <= (sizeof(m_seq.args) / sizeof(m_seq.args[0])));
                m_seq.args[m_seq.n_args++] = bte_seq_arg_init(std::min(p, 0xffff));
        }

        inline void append_params(std::initializer_list<int> params) noexcept
        {
                assert(m_seq.n_args + params.size() <= (sizeof(m_seq.args) / sizeof(m_seq.args[0])));
                for (int p : params)
                        m_seq.args[m_seq.n_args++] = bte_seq_arg_init(std::min(p, 0xffff));
        }

        inline void append_subparams(std::initializer_list<int> subparams) noexcept
        {
                assert(m_seq.n_args + subparams.size() <= (sizeof(m_seq.args) / sizeof(m_seq.args[0])));
                for (int p : subparams) {
                        int* arg = &m_seq.args[m_seq.n_args++];
                        *arg = bte_seq_arg_init(std::min(p, 0xffff));
                        bte_seq_arg_finish(arg, false);
                }
                bte_seq_arg_refinish(&m_seq.args[m_seq.n_args - 1], true);
        }

        inline void set_string(string_type const& str) noexcept
        {
                m_arg_str = str;
        }

        inline void set_string(string_type&& str) noexcept
        {
                m_arg_str = str;
        }

        enum class Introducer {
                NONE,
                DEFAULT,
                C0,
                C1
        };

        enum class ST {
                NONE,
                DEFAULT,
                C0,
                C1,
                BEL
        };


private:
        void append_introducer_(string_type& s,
                                bool c1 = true) const noexcept
        {
                /* Introducer */
                if (c1) {
                        switch (m_seq.type) {
                        case BTE_SEQ_ESCAPE: m_encoder.put(s, 0x1b); break; // ESC
                        case BTE_SEQ_CSI:    m_encoder.put(s, 0x9b); break; // CSI
                        case BTE_SEQ_DCS:    m_encoder.put(s, 0x90); break; // DCS
                        case BTE_SEQ_OSC:    m_encoder.put(s, 0x9d); break; // OSC
                        case BTE_SEQ_APC:    m_encoder.put(s, 0x9f); break; // APC
                        case BTE_SEQ_PM:     m_encoder.put(s, 0x9e); break; // PM
                        case BTE_SEQ_SOS:    m_encoder.put(s, 0x98); break; // SOS
                        case BTE_SEQ_SCI:    m_encoder.put(s, 0x9a); break; // SCI
                        default: return;
                        }
                } else {
                        s.push_back(0x1B); // ESC
                        switch (m_seq.type) {
                        case BTE_SEQ_ESCAPE:                    break; // nothing more
                        case BTE_SEQ_CSI:    s.push_back(0x5b); break; // [
                        case BTE_SEQ_DCS:    s.push_back(0x50); break; // P
                        case BTE_SEQ_OSC:    s.push_back(0x5d); break; // ]
                        case BTE_SEQ_APC:    s.push_back(0x5f); break; // _
                        case BTE_SEQ_PM:     s.push_back(0x5e); break; // ^
                        case BTE_SEQ_SOS:    s.push_back(0x58); break; // X
                        case BTE_SEQ_SCI:    s.push_back(0x5a); break; // Z
                        default: return;
                        }
                }
        }

        void append_introducer(string_type& s,
                               bool c1 = true,
                               Introducer introducer = Introducer::DEFAULT) const noexcept
        {
                switch (introducer) {
                case Introducer::NONE:
                        break;
                case Introducer::DEFAULT:
                        append_introducer_(s, c1);
                        break;
                case Introducer::C0:
                        append_introducer_(s, false);
                        break;
                case Introducer::C1:
                        append_introducer_(s, true);
                }
        }

        void append_params(string_type& s) const noexcept
        {
                /* Parameters */
                switch (m_seq.type) {
                case BTE_SEQ_CSI:
                case BTE_SEQ_DCS: {

                        if (m_param_intro != 0)
                                s.push_back(m_param_intro);
                        auto n_args = m_seq.n_args;
                        for (unsigned int n = 0; n < n_args; n++) {
                                auto arg = bte_seq_arg_value(m_seq.args[n]);
                                if (n > 0) {
                                        s.push_back(";:"[bte_seq_arg_nonfinal(m_seq.args[n])]);
                                }
                                if (arg >= 0) {
                                        char buf[16];
                                        int l = g_snprintf(buf, sizeof(buf), "%d", arg);
                                        for (int j = 0; j < l; j++)
                                                s.push_back(buf[j]);
                                }
                        }
                        break;
                }
                default:
                        break;
                }
        }

        void append_intermediates_and_final(string_type& s) const noexcept
        {
                /* Intermediates and Final */
                switch (m_seq.type) {
                case BTE_SEQ_ESCAPE:
                case BTE_SEQ_CSI:
                case BTE_SEQ_DCS:
                        for (unsigned char n = 0; n < m_n_intermediates; n++)
                                s.push_back(m_intermediates[n]);
                        [[fallthrough]];
                case BTE_SEQ_SCI:
                        if (m_seq.terminator != 0)
                                s.push_back(m_seq.terminator);
                        break;
                default:
                        break;
                }
        }

        void append_arg_string(string_type& s,
                               bool c1 = false,
                               ssize_t max_arg_str_len = -1,
                               ST st = ST::DEFAULT) const noexcept
        {
                /* String and ST */
                switch (m_seq.type) {
                case BTE_SEQ_DCS:
                case BTE_SEQ_OSC:

                        if (max_arg_str_len < 0)
                                s.append(m_arg_str, 0, max_arg_str_len);
                        else
                                s.append(m_arg_str);

                        switch (st) {
                        case ST::NONE:
                                // omit ST
                                break;
                        case ST::DEFAULT:
                                if (c1) {
                                        m_encoder.put(s, 0x9c); // ST
                                } else {
                                        s.push_back(0x1b); // ESC
                                        s.push_back(0x5c); // BACKSLASH
                                }
                                break;
                        case ST::C0:
                                s.push_back(0x1b); // ESC
                                s.push_back(0x5c); // BACKSLASH
                                break;
                        case ST::C1:
                                m_encoder.put(s, 0x9c); // ST
                                break;
                        case ST::BEL:
                                s.push_back(0x7); // BEL
                                break;
                        default:
                                break;
                        }
                }
        }

public:
        void to_string(string_type& s,
                       bool c1 = false,
                       ssize_t max_arg_str_len = -1,
                       Introducer introducer = Introducer::DEFAULT,
                       ST st = ST::DEFAULT) const noexcept
        {
                append_introducer(s, c1, introducer);
                append_params(s);
                append_intermediates_and_final(s);
                append_arg_string(s, c1, max_arg_str_len, st);
        }

        /* The following are only used in the test suite */
        void reset_params() noexcept
        {
                m_seq.n_args = 0;
        }

        void assert_equal(Sequence const& seq) const noexcept
        {
                g_assert_cmpuint(seq.type(), ==, m_seq.type);<--- syntax error
                g_assert_cmphex(seq.terminator(), ==, m_seq.terminator);
        }

        void assert_equal_full(Sequence const& seq) const noexcept
        {
                assert_equal(seq);

                auto type = seq.type();
                if (type == BTE_SEQ_CSI ||
                    type == BTE_SEQ_DCS) {
                        /* We may get one arg less back, if it's at default */
                        if (m_seq.n_args != seq.size()) {
                                g_assert_cmpuint(m_seq.n_args, ==, seq.size() + 1);
                                g_assert_true(bte_seq_arg_default(m_seq.args[m_seq.n_args - 1]));
                        }
                        for (unsigned int n = 0; n < seq.size(); n++)
                                g_assert_cmpint(bte_seq_arg_value(m_seq.args[n]), ==, seq.param(n));
                }
        }
}; // class SequenceBuilder

using u8SequenceBuilder = SequenceBuilder<std::string, UTF8Encoder>;
using u32SequenceBuilder = SequenceBuilder<std::u32string>;

class ReplyBuilder : public u8SequenceBuilder {
public:
        ReplyBuilder(unsigned int reply,
                     std::initializer_list<int> params)
        {
                switch (reply) {
#define _BTE_REPLY_PARAMS(params) append_params(params);
#define _BTE_REPLY_STRING(str) set_string(str);
#define _BTE_REPLY(cmd,type,final,pintro,intermediate,code) \
                case BTE_REPLY_##cmd: \
                        set_type(BTE_SEQ_##type); \
                        set_final(final); \
                        set_param_intro(BTE_SEQ_PARAMETER_CHAR_##pintro); \
                        if (BTE_SEQ_INTERMEDIATE_CHAR_##intermediate != BTE_SEQ_INTERMEDIATE_CHAR_NONE) \
                                append_intermediate(BTE_SEQ_INTERMEDIATE_CHAR_##intermediate); \
                        code \
                        break;
#include "parser-reply.hh"
#undef _BTE_REPLY
#undef _BTE_REPLY_PARAMS
#undef _BTE_REPLY_STRING
                default:
                        assert(false);
                        break;
                }
                append_params(params);
        }

}; // class ReplyBuilder

class StringTokeniser {
public:
        using string_type = std::string;
        using char_type = std::string::value_type;

private:
        string_type const& m_string;
        char_type m_separator{';'};

public:
        StringTokeniser(string_type& s,
                        char_type separator = ';')
                : m_string{s},
                  m_separator{separator}
        {
        }

        StringTokeniser(string_type&& s,
                        char_type separator = ';')
                : m_string{s},
                  m_separator{separator}
        {
        }

        StringTokeniser(StringTokeniser const&) = delete;
        StringTokeniser(StringTokeniser&&) = delete;
        ~StringTokeniser() = default;

        StringTokeniser& operator=(StringTokeniser const&) = delete;
        StringTokeniser& operator=(StringTokeniser&&) = delete;

        /*
         * const_iterator:
         *
         * InputIterator for string tokens.
         */
        class const_iterator {
        public:
                using difference_type = ptrdiff_t;
                using value_type = string_type;
                using pointer = string_type;
                using reference = string_type;
                using iterator_category = std::input_iterator_tag;
                using size_type = string_type::size_type;

        private:
                string_type const* m_string;
                char_type m_separator{';'};
                string_type::size_type m_position;
                string_type::size_type m_next_separator;

        public:
                const_iterator(string_type const* str,
                               char_type separator,
                               size_type position)
                        : m_string{str},
                          m_separator{separator},
                          m_position{position},
                          m_next_separator{m_string->find(m_separator, m_position)}
                {
                }

                const_iterator(string_type const* str,
                               char_type separator)
                        : m_string{str},
                          m_separator{separator},
                          m_position{string_type::npos},
                          m_next_separator{string_type::npos}
                {
                }

                const_iterator(const_iterator const&) = default;
                const_iterator(const_iterator&& o)
                        : m_string{o.m_string},
                          m_separator{o.m_separator},
                          m_position{o.m_position},
                          m_next_separator{o.m_next_separator}
                {
                }

                ~const_iterator() = default;

                const_iterator& operator=(const_iterator const& o)
                {
                        m_string = o.m_string;
                        m_separator = o.m_separator;
                        m_position = o.m_position;
                        m_next_separator = o.m_next_separator;
                        return *this;
                }

                const_iterator& operator=(const_iterator&& o)
                {
                        m_string = std::move(o.m_string);
                        m_separator = o.m_separator;
                        m_position = o.m_position;
                        m_next_separator = o.m_next_separator;
                        return *this;
                }

                inline bool operator==(const_iterator const& o) const noexcept
                {
                        return m_position == o.m_position;
                }

                inline bool operator!=(const_iterator const& o) const noexcept
                {
                        return m_position != o.m_position;
                }

                inline const_iterator& operator++() noexcept
                {
                        if (m_next_separator != string_type::npos) {
                                m_position = ++m_next_separator;
                                m_next_separator = m_string->find(m_separator, m_position);
                        } else
                                m_position = string_type::npos;

                        return *this;
                }

                /*
                 * number:
                 *
                 * Returns the value of the iterator as a number, or -1
                 *   if the string could not be parsed as a number, or
                 *   the parsed values exceeds the uint16_t range.
                 *
                 * Returns: true if a number was parsed
                 */
                bool number(int& v) const noexcept
                {
                        auto const s = size();
                        if (s == 0) {
                                v = -1;
                                return true;
                        }

                        v = 0;
                        size_type i;
                        for (i = 0; i < s; ++i) {
                                char_type c = (*m_string)[m_position + i];
                                if (c < '0' || c > '9')
                                        return false;

                                v = v * 10 + (c - '0');
                                if (v > 0xffff)
                                        return false;
                        }

                        /* All consumed? */
                        return i == s;
                }

                inline size_type size() const noexcept
                {
                        if (m_next_separator != string_type::npos)
                                return m_next_separator - m_position;
                        else
                                return m_string->size() - m_position;
                }

                inline size_type size_remaining() const noexcept
                {
                        return m_string->size() - m_position;
                }

                inline string_type operator*() const noexcept
                {
                        return m_string->substr(m_position, size());
                }

                /*
                 * string_remaining:
                 *
                 * Returns the whole string left, including possibly more separators.
                 */
                inline string_type string_remaining() const noexcept
                {
                        return m_string->substr(m_position);
                }

                inline void append(string_type& str) const noexcept
                {
                        str.append(m_string->substr(m_position, size()));
                }

                inline void append_remaining(string_type& str) const noexcept
                {
                        str.append(m_string->substr(m_position));
                }

        }; // class const_iterator

        inline const_iterator cbegin(char_type c = ';') const noexcept
        {
                return const_iterator(&m_string, m_separator, 0);
        }

        inline const_iterator cend() const noexcept
        {
                return const_iterator(&m_string, m_separator);
        }

        inline const_iterator begin(char_type c = ';') const noexcept
        {
                return cbegin();
        }

        inline const_iterator end() const noexcept
        {
                return cend();
        }

}; // class StringTokeniser

} // namespace parser

} // namespace bte