Source

htsql-charset-option / src / htsql / tr / encode.py

Full commit
   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
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
#
# Copyright (c) 2006-2011, Prometheus Research, LLC
# Authors: Clark C. Evans <cce@clarkevans.com>,
#          Kirill Simonov <xi@resolvent.net>
#


"""
:mod:`htsql.tr.encode`
======================

This module implements the encoding process.
"""


from ..adapter import Adapter, adapts, adapts_many
from ..domain import (Domain, UntypedDomain, TupleDomain, BooleanDomain,
                      NumberDomain, IntegerDomain, DecimalDomain, FloatDomain,
                      StringDomain, EnumDomain, DateDomain, TimeDomain,
                      DateTimeDomain, OpaqueDomain)
from .error import EncodeError
from .coerce import coerce
from .binding import (Binding, RootBinding, QueryBinding, SegmentBinding,
                      FreeTableBinding, AttachedTableBinding,
                      QuotientBinding, ComplementBinding, KernelBinding,
                      ColumnBinding, LiteralBinding, SieveBinding,
                      SortBinding, CastBinding, WrapperBinding,
                      DefinitionBinding, AliasBinding,
                      DirectionBinding, FormulaBinding,
                      SelectionBinding, HomeBinding)
from .code import (RootSpace, ScalarSpace,
                   DirectTableSpace, FiberTableSpace,
                   QuotientSpace, ComplementSpace,
                   FilteredSpace, OrderedSpace,
                   QueryExpr, SegmentExpr, LiteralCode, FormulaCode,
                   CastCode, ColumnUnit, ScalarUnit, KernelUnit)
from .signature import Signature, IsNullSig, NullIfSig
import decimal


class EncodingState(object):
    """
    Encapsulates the (mutable) state of the encoding process.

    Currently encoding is a stateless process, but we will likely add
    extra state in the future.  The state is also used to store the
    cache of binding to space and binding to code translations.
    """

    # Indicates whether results of `encode` or `relate` are cached.
    # Caching means that two calls of `encode` (or `relate`) on the
    # same `Binding` instance produce the same object.
    #
    # By default, caching is turned on; however the translator must
    # never rely on that.  That is, the result generated by the
    # translator must not depend on whether caching is enabled or
    # disabled.  This parameter gives us an easy way to check this
    # assumption.  Different results usually mean a bug in comparison
    # by value for code objects.
    with_cache = True

    def __init__(self):
        # A mapping of cached results of `encode()`.
        self.binding_to_code = {}
        # A mapping of cached results of `relate()`.
        self.binding_to_space = {}

    def flush(self):
        """
        Clears the encoding state.
        """
        self.binding_to_code.clear()
        self.binding_to_state.clear()

    def encode(self, binding):
        """
        Encodes the given binding node to a code expression node.

        Returns a :class:`htsql.tr.code.Code` node (in some cases,
        a :class:`htsql.tr.code.Expression` node).

        `binding` (:class:`htsql.tr.binding.Binding`)
            The binding node to encode.
        """
        # When caching is enabled, we check if `binding` was
        # already encoded.  If not, we encode it and save the
        # result.
        if self.with_cache:
            if binding not in self.binding_to_code:
                code = encode(binding, self)
                self.binding_to_code[binding] = code
            return self.binding_to_code[binding]
        # Caching is disabled; return a new instance every time.
        return encode(binding, self)

    def relate(self, binding):
        """
        Encodes the given binding node to a space expression node.

        Returns a :class:`htsql.tr.code.Space` node.

        `binding` (:class:`htsql.tr.binding.Binding`)
            The binding node to encode.
        """
        # When caching is enabled, we check if `binding` was
        # already encoded.  If not, we encode it and save the
        # result.
        if self.with_cache:
            if binding not in self.binding_to_space:
                space = relate(binding, self)
                self.binding_to_space[binding] = space
            return self.binding_to_space[binding]
        # Caching is disabled; return a new instance every time.
        return relate(binding, self)

    def direct(self, binding):
        """
        Extracts a direction modifier from the given binding.

        A direction modifier is set by post-fix ``+`` and ``-`` operators.
        The function returns ``+1`` for the ``+`` modifier (ascending order),
        ``-1`` for the ``-`` modifier (descending order), ``None`` if there
        are no modifiers.

        `binding` (:class:`htsql.tr.binding.Binding`)
            The binding node.
        """
        # FIXME: `Direct` does not really depend on the state, should
        # it still accept it?
        return direct(binding, self)


class EncodeBase(Adapter):
    """
    Applies an encoding adapter to a binding node.

    This is a base class for three encoding adapters: :class:`Encode`,
    :class:`Relate`, :class:`Direct`; it encapsulates methods and
    attributes shared between these adapters.

    The encoding process translates binding nodes to space and code
    nodes.  Space nodes represent ordered sets of rows; code nodes
    represent functions on spaces.  See :class:`htsql.tr.binding.Binding`,
    :class:`htsql.tr.code.Expression`, :class:`htsql.tr.code.Space`,
    :class:`htsql.tr.code.Code` for more details on the respective
    node types.

    `binding` (:class:`htsql.tr.binding.Binding`)
        The binding node to encode.

    `state` (:class:`EncodingState`)
        The current state of the encoding process.
    """

    adapts(Binding)

    def __init__(self, binding, state):
        assert isinstance(binding, Binding)
        assert isinstance(state, EncodingState)
        self.binding = binding
        self.state = state


class Encode(EncodeBase):
    """
    Translates a binding node to a code expression node.

    This is an interface adapter; see subclasses for implementations.

    The :class:`Encode` adapter has the following signature::

        Encode: (Binding, EncodingState) -> Code or Expression

    The adapter is polymorphic on the `Binding` argument.

    See :class:`htsql.tr.binding.Binding`, :class:`htsql.tr.code.Expression`,
    :class:`htsql.tr.code.Code` for detail on the respective nodes.

    This adapter provides non-trivial implementation for binding
    nodes representing HTSQL functions and operators.
    """

    def __call__(self):
        # The default implementation generates an error.
        # FIXME: a better error message?
        raise EncodeError("expected a valid code expression",
                          self.binding.mark)


class Relate(EncodeBase):
    """
    Translates a binding node to a space expression node.

    This is an interface adapter; see subclasses for implementations.

    The :class:`Relate` adapter has the following signature::

        Relate: (Binding, EncodingState) -> Space

    The adapter is polymorphic on the `Binding` argument.

    See :class:`htsql.tr.binding.Binding` and :class:`htsql.tr.code.Space`
    for detail on the respective nodes.

    The adapter provides non-trivial implementations for subclasses
    of :class:`htsql.tr.binding.ChainBinding`; the `base` attributes
    are used to restore the structure of the space.
    """

    def __call__(self):
        # The default implementation generates an error.
        # FIXME: a better error message?
        raise EncodeError("expected a valid space expression",
                          self.binding.mark)


class Direct(EncodeBase):
    """
    Extracts a direction modifier from the given binding.

    A direction modifier is set by post-fix ``+`` and ``-`` operators.
    The function returns ``+1`` for the ``+`` modifier (ascending order),
    ``-1`` for the ``-`` modifier (descending order), ``None`` if there
    are no modifiers.

    This is an interface adapter; see subclasses for implementations.

    The :class:`Direct` adapter has the following signature::

        Direct: (Binding, EncodingState) -> +1 or -1 or None

    The adapter is polymorphic on the `Binding` argument.

    The adapter unwraps binding nodes looking for instances of
    :class:`htsql.tr.binding.DirectionBinding`, which represent
    direction modifiers.
    """

    def __call__(self):
        # The default implementation produces no modifier.
        return None


class EncodeQuery(Encode):
    """
    Encodes the top-level binding node :class:`htsql.tr.binding.QueryBinding`.

    Produces an instance of :class:`htsql.tr.code.QueryExpr`.
    """

    adapts(QueryBinding)

    def __call__(self):
        # Encode the segment node if it is provided.
        segment = None
        if self.binding.segment is not None:
            segment = self.state.encode(self.binding.segment)
        # Construct the expression node.
        return QueryExpr(segment, self.binding)


class EncodeSegment(Encode):
    """
    Encodes a segment binding node :class:`htsql.tr.binding.SegmentBinding`.

    Produces an instance of :class:`htsql.tr.code.SegmentExpr`.
    """

    adapts(SegmentBinding)

    def __call__(self):
        # The list of segment elements.
        elements = []
        # Encode each of the element bindings.
        for binding in self.binding.elements:
            # Encode the node.
            element = self.state.encode(binding)
            elements.append(element)
        if self.binding.base is not None:
            space = self.state.relate(self.binding.base)
        else:
            units = []
            for element in elements:
                units.extend(element.units)
            if not units:
                space = RootSpace(None, self.binding)
            else:
                spaces = []
                for unit in units:
                    if any(space.dominates(unit.space) for space in spaces):
                        continue
                    spaces = [space for space in spaces
                                    if unit.space.dominates(space)]
                    spaces.append(unit.space)
                if len(spaces) > 1:
                    raise EncodeError("invalid segment operand",
                                      self.binding.mark)
                else:
                    space = spaces[0]
        return SegmentExpr(space, elements, self.binding)


class RelateRoot(Relate):
    """
    Translates the root binding node to a space node.

    Returns a scalar space node :class:`htsql.tr.code.RootSpace`.
    """

    adapts(RootBinding)

    def __call__(self):
        # The root binding always originates the scalar space `I`.
        return RootSpace(None, self.binding)


class RelateHome(Relate):

    adapts(HomeBinding)

    def __call__(self):
        base = self.state.relate(self.binding.base)
        return ScalarSpace(base, self.binding)


class RelateFreeTable(Relate):
    """
    Translates a free table binding to a space node.

    Returns a direct table node :class:`htsql.tr.code.DirectTableSpace`.
    """

    adapts(FreeTableBinding)

    def __call__(self):
        # Generate a space node corresponding to the binding base.
        base = self.state.relate(self.binding.base)
        # Produce a direct table space between the base space and
        # the binding table: `base * table`.
        return DirectTableSpace(base, self.binding.table, self.binding)


class RelateAttachedTable(Relate):
    """
    Translates an attached table binding to a space node.

    Returns a fiber table node :class:`htsql.tr.code.FiberTableSpace`.
    """

    adapts(AttachedTableBinding)

    def __call__(self):
        # Generate a space node corresponding to the binding base.
        space = self.state.relate(self.binding.base)
        return FiberTableSpace(space, self.binding.join, self.binding)


class RelateSieve(Relate):
    """
    Translates a sieve binding to a space node.

    Returns a filtered space node :class:`htsql.tr.code.FilteredSpace`.
    """

    adapts(SieveBinding)

    def __call__(self):
        # Generate a space node corresponding to the binding base.
        space = self.state.relate(self.binding.base)
        # Encode the predicate expression.
        filter = self.state.encode(self.binding.filter)
        # Augment the base space with a filter: `base ? filter`.
        return FilteredSpace(space, filter, self.binding)


class DirectSieve(Direct):
    """
    Extracts the direction modifier from a sieve binding.
    """

    adapts(SieveBinding)

    def __call__(self):
        # We delegate the adapter to the binding base, ignoring the filter.
        # FIXME: It is controversal, but matches the `entitle` adapter.
        # Perhaps, we need to add a class attribute `is_passthrough`
        # (or a mixin class `PassthroughBinding`) to indicate bindings
        # that could delegate modifier extraction adapters?
        return self.state.direct(self.binding.base)


class RelateSort(Relate):
    """
    Translates a sort binding to a space node.

    Returns an ordered space node :class:`htsql.tr.code.OrderedSpace`.
    """

    adapts(SortBinding)

    def __call__(self):
        # Generate a space node corresponding to the binding base.
        space = self.state.relate(self.binding.base)
        # A list of pairs `(code, direction)` containing the expressions
        # by which the space is sorted and respective direction indicators.
        order = []
        # Iterate over ordering binding nodes.
        for binding in self.binding.order:
            # Encode the binding.
            code = self.state.encode(binding)
            # Extract the direction modifier; assume `+` if none.
            direction = self.state.direct(binding)
            if direction is None:
                direction = +1
            order.append((code, direction))
        # The slice indicators.
        limit = self.binding.limit
        offset = self.binding.offset
        # Produce an ordered space node over the base space:
        #   `base [e,...;offset:offset+limit]`.
        return OrderedSpace(space, order, limit, offset, self.binding)


class EncodeColumn(Encode):
    """
    Translates a column binding to a code node.

    Returns a column unit node :class:`htsql.tr.code.ColumnUnit`.
    """

    adapts(ColumnBinding)

    def __call__(self):
        # The binding base is translated to the space of the unit node.
        space = self.state.relate(self.binding.base)
        # Generate a column unit node.
        return ColumnUnit(self.binding.column, space, self.binding)


class RelateColumn(Relate):
    """
    Translates a column binding to a space node.

    Returns a fiber table node :class:`htsql.tr.code.FiberTableSpace` or
    raises an error.
    """

    adapts(ColumnBinding)

    def __call__(self):
        # If the column binding has an associated table binding node,
        # delegate the adapter to it.
        if self.binding.link is not None:
            return self.state.relate(self.binding.link)
        # Otherwise, let the parent produce an error message.
        return super(RelateColumn, self).__call__()


class RelateQuotient(Relate):

    adapts(QuotientBinding)

    def __call__(self):
        space = self.state.relate(self.binding.base)
        seed_space = self.state.relate(self.binding.seed)
        if space.spans(seed_space):
            raise EncodeError("a plural operand is required",
                              seed_space.mark)
        if not seed_space.spans(space):
            raise EncodeError("invalid plural operand",
                              seed_space.mark)
        kernel = [self.state.encode(binding)
                  for binding in self.binding.kernel]
        return QuotientSpace(space, seed_space, kernel, self.binding)


class RelateComplement(Relate):

    adapts(ComplementBinding)

    def __call__(self):
        space = self.state.relate(self.binding.base)
        return ComplementSpace(space, self.binding)


class EncodeKernel(Encode):

    adapts(KernelBinding)

    def __call__(self):
        space = self.state.relate(self.binding.base)
        code = space.family.kernel[self.binding.index]
        return KernelUnit(code, space, self.binding)


class EncodeLiteral(Encode):
    """
    Encodes a literal binding.

    Returns a literal code node :class:`htsql.tr.code.LiteralCode`.
    """

    adapts(LiteralBinding)

    def __call__(self):
        # Switch the class from `Binding` to `Code` keeping all attributes.
        return LiteralCode(self.binding.value, self.binding.domain,
                           self.binding)


class EncodeCast(Encode):
    """
    Encodes a cast binding.

    The actual encoding is performed by the :class:`Convert` adapter.
    """

    adapts(CastBinding)

    def __call__(self):
        # Delegate it to the `Convert` adapter.
        convert = Convert(self.binding, self.state)
        return convert()


class DirectCast(Direct):
    """
    Extracts a direction modifier from a cast binding.
    """

    adapts(CastBinding)

    def __call__(self):
        # The adapter is delegated to the binding base; we have to do it
        # because many expressions (including segment elements) are wrapped
        # with implicit cast nodes, which otherwise would mask any decorators.
        return self.state.direct(self.binding.base)


class Convert(Adapter):
    """
    Encodes a cast binding to a code node.

    This is an auxiliary adapter used to encode
    :class:`htsql.tr.binding.CastBinding` nodes.  The adapter is polymorphic
    by the origin and the target domains.

    The purpose of the adapter is multifold.  The :class:`Convert` adapter:

    - verifies that the conversion from the source to the target
      domain is admissible;
    - eliminates redundant conversions;
    - handles conversion from the special types:
      :class:`htsql.domain.UntypedDomain` and :class:`htsql.domain.TupleDomain`;
    - when possible, expresses the cast in terms of other operations; otherwise,
      generates a new :class:`htsql.tr.code.CastCode` node.

    `binding` (:class:`htsql.tr.binding.CastBinding`)
        The binding node to encode.

        Note that the adapter is dispatched on the pair
        `(binding.base.domain, binding.domain)`.

    `state` (:class:`EncodingState`)
        The current state of the encoding process.

    Aliases:

    `base` (:class:`htsql.tr.binding.Binding`)
        An alias for `binding.base`; the operand of the cast expression.

    `domain` (:class:`htsql.domain.Domain`)
        An alias for `binding.domain`; the target domain.
    """

    adapts(Domain, Domain)

    @classmethod
    def dispatch(interface, binding, *args, **kwds):
        # We override the standard extract of the dispatch key, which
        # returns the type of the first argument(s).  For `Convert`,
        # the dispatch key is the pair of the origin and the target domains.
        assert isinstance(binding, CastBinding)
        return (type(binding.base.domain), type(binding.domain))

    def __init__(self, binding, state):
        assert isinstance(binding, CastBinding)
        assert isinstance(state, EncodingState)
        self.binding = binding
        self.base = binding.base
        self.domain = binding.domain
        self.state = state

    def __call__(self):
        # A final check to eliminate conversion when the origin and
        # the target domains are the same.  It is likely no-op since
        # this case should be already handled.
        if self.base.domain == self.domain:
            return self.state.encode(self.base)
        # The default implementation complains that the conversion is
        # not admissible.
        raise EncodeError("inadmissible conversion", self.binding.mark)


class ConvertUntyped(Convert):
    """
    Validates and converts untyped literals.
    """

    adapts(UntypedDomain, Domain)

    def __call__(self):
        # The base binding is of untyped domain, however it does not have
        # to be an instance of `LiteralBinding` since the actual literal node
        # could be wrapped by decorators.  However after we encode the node,
        # the decorators are gone and the result must be a `LiteralCode`.
        # The domain should remain the same too.
        base = self.state.encode(self.base)
        assert isinstance(base, LiteralCode)
        assert isinstance(base.domain, UntypedDomain)
        # Convert the serialized literal value to a Python object; raises
        # a `ValueError` if the literal is not in a valid format.
        try:
            value = self.domain.parse(base.value)
        except ValueError, exc:
            raise EncodeError(str(exc), self.binding.mark)
        # Generate a new literal node with the converted value and
        # the target domain.
        return LiteralCode(value, self.domain, self.binding)


class ConvertToItself(Convert):
    """
    Eliminates redundant conversions.
    """
    adapts_many((BooleanDomain, BooleanDomain),
                (IntegerDomain, IntegerDomain),
                (FloatDomain, FloatDomain),
                (DecimalDomain, DecimalDomain),
                (StringDomain, StringDomain),
                (DateDomain, DateDomain),
                (TimeDomain, TimeDomain),
                (DateTimeDomain, DateTimeDomain))
    # FIXME: do we need `EnumDomain` here?

    def __call__(self):
        # Encode and return the operand of the cast.
        return self.state.encode(self.binding.base)


class ConvertTupleToBoolean(Convert):
    """
    Converts a tuple expression to a conditional expression.
    """

    adapts(TupleDomain, BooleanDomain)

    def __call__(self):
        # When the binding domain is tuple, we assume that the binding
        # represents some space.  In this case, Boolean cast produces
        # an expression which is `FALSE` when the space is empty and
        # `TRUE` otherwise.  The actual expression is:
        #   `!is_null(unit)`,
        # where `unit` is some non-nullable function on the space.

        # Translate the operand to a space node.
        space = self.state.relate(self.base)
        # A `TRUE` literal.
        true_literal = LiteralCode(True, coerce(BooleanDomain()), self.binding)
        # A `TRUE` constant as a function on the space.
        unit = ScalarUnit(true_literal, space, self.binding)
        # Return `!is_null(unit)`.
        return FormulaCode(IsNullSig(-1), coerce(BooleanDomain()),
                           self.binding, op=unit)


class ConvertStringToBoolean(Convert):
    """
    Converts a string expression to a conditional expression.
    """

    adapts(StringDomain, BooleanDomain)

    def __call__(self):
        # A `NULL` value and an empty string are converted to `FALSE`,
        # any other string value is converted to `TRUE`.

        # Encode the operand of the cast.
        code = self.state.encode(self.base)
        # An empty string.
        empty_literal = LiteralCode('', self.base.domain, self.binding)
        # Construct: `null_if(base,'')`.
        code = FormulaCode(NullIfSig(), self.base.domain, self.binding,
                           lop=code, rop=empty_literal)
        # Construct: `!is_null(null_if(base,''))`.
        code = FormulaCode(IsNullSig(-1), self.domain, self.binding,
                           op=code)
        # Return `!is_null(null_if(base,''))`.
        return code


class ConvertToBoolean(Convert):
    """
    Converts an expression of any type to a conditional expression.
    """

    adapts_many((NumberDomain, BooleanDomain),
                (EnumDomain, BooleanDomain),
                (DateDomain, BooleanDomain),
                (TimeDomain, BooleanDomain),
                (DateTimeDomain, BooleanDomain),
                (OpaqueDomain, BooleanDomain))
    # Note: we include the opaque domain here to ensure that any
    # data type could be converted to Boolean.  However this may
    # lead to unintuitive results.

    def __call__(self):
        # A `NULL` value is converted to `FALSE`; any other value is
        # converted to `TRUE`.

        # Construct and return `!is_null(base)`.
        return FormulaCode(IsNullSig(-1), self.domain, self.binding,
                           op=self.state.encode(self.base))


class ConvertToString(Convert):
    """
    Convert an expression to a string.
    """

    adapts_many((BooleanDomain, StringDomain),
                (NumberDomain, StringDomain),
                (EnumDomain, StringDomain),
                (DateDomain, StringDomain),
                (TimeDomain, StringDomain),
                (DateTimeDomain, StringDomain),
                (OpaqueDomain, StringDomain))
    # Note: we assume we could convert any opaque data type to string;
    # it is risky but convenient.

    def __call__(self):
        # We generate a cast code node leaving it to the serializer
        # to specialize on the origin data type.
        return CastCode(self.state.encode(self.base), self.domain,
                        self.binding)


class ConvertToInteger(Convert):
    """
    Convert an expression to an integer value.
    """

    adapts_many((DecimalDomain, IntegerDomain),
                (FloatDomain, IntegerDomain),
                (StringDomain, IntegerDomain))

    def __call__(self):
        # We leave conversion from literal values to the database
        # engine even though we could handle it here because the
        # conversion may be engine-specific.
        return CastCode(self.state.encode(self.base), self.domain,
                        self.binding)


class ConvertToDecimal(Convert):
    """
    Convert an expression to a decimal value.
    """

    adapts_many((IntegerDomain, DecimalDomain),
                (FloatDomain, DecimalDomain),
                (StringDomain, DecimalDomain))

    def __call__(self):
        # Encode the operand of the cast.
        code = self.state.encode(self.base)
        # Handle conversion from an integer literal manually.
        # We do not handle conversion from other literal types
        # because it may be engine-specific.
        if isinstance(code, LiteralCode):
            if isinstance(code.domain, IntegerDomain):
                if code.value is None:
                    return code.clone(domain=self.domain)
                else:
                    value = decimal.Decimal(code.value)
                    return code.clone(value=value, domain=self.domain)
        # For the regular case, generate an appropriate cast node.
        return CastCode(code, self.domain, self.binding)


class ConvertToFloat(Convert):
    """
    Convert an expression to a float value.
    """

    adapts_many((IntegerDomain, FloatDomain),
                (DecimalDomain, FloatDomain),
                (StringDomain, FloatDomain))

    def __call__(self):
        # Encode the operand of the cast.
        code = self.state.encode(self.base)
        # Handle conversion from an integer and decimal literals manually.
        # We do not handle conversion from other literal types because it
        # may be engine-specific.
        if isinstance(code, LiteralCode):
            if isinstance(code.domain, (IntegerDomain, DecimalDomain)):
                if code.value is None:
                    return code.clone(domain=self.domain)
                else:
                    value = float(code.value)
                    return code.clone(value=value, domain=self.domain)
        # For the regular case, generate an appropriate cast node.
        return CastCode(code, self.domain, self.binding)


class ConvertToDate(Convert):
    """
    Convert an expression to a date value.
    """

    adapts_many((StringDomain, DateDomain),
                (DateTimeDomain, DateDomain))

    def __call__(self):
        # We leave conversion from literal values to the database
        # engine even though we could handle it here because the
        # conversion may be engine-specific.
        return CastCode(self.state.encode(self.base), self.domain,
                        self.binding)


class ConvertToTime(Convert):
    """
    Convert an expression to a time value.
    """

    adapts_many((StringDomain, TimeDomain),
                (DateTimeDomain, TimeDomain))

    def __call__(self):
        return CastCode(self.state.encode(self.base), self.domain,
                        self.binding)


class ConvertToDateTime(Convert):
    """
    Convert an expression to a datetime value.
    """

    adapts_many((StringDomain, DateTimeDomain),
                (DateDomain, DateTimeDomain))

    def __call__(self):
        return CastCode(self.state.encode(self.base), self.domain,
                        self.binding)


class EncodeFormula(Encode):
    """
    Translates a formula binding to a code node.

    The translation is specific to the formula signature and is implemented
    by the :class:`EncodeBySignature` adapter.
    """

    adapts(FormulaBinding)

    def __call__(self):
        # Delegate the translation to the `EncodeBySignature` adapter.
        encode = EncodeBySignature(self.binding, self.state)
        return encode()


class RelateFormula(Relate):
    """
    Translates a formula binding to a space node.

    The translation is specific to the formula signature and is implemented
    by the :class:`RelateBySignature` adapter.
    """

    adapts(FormulaBinding)

    def __call__(self):
        # Delegate the translation to the `RelateBySignature` adapter.
        relate = RelateBySignature(self.binding, self.state)
        return relate()


class DirectFormula(Direct):
    """
    Extracts a direction modifier from a formula binding.

    The extration is specific to the formula signature and is implemented
    by the :class:`DirectBySignature` adapter.
    """

    adapts(FormulaBinding)

    def __call__(self):
        # Delegate the extraction to the `DirectBySignature` adapter.
        direct = DirectBySignature(self.binding, self.state)
        return direct()


class EncodeBySignatureBase(Adapter):
    """
    Translates a formula node.

    This is a base class for three encoding adapters:
    :class:`EncodeBySignature`, :class:`RelateBySignature` and
    :class:`DirectBySignature`; it encapsulates methods and attributes
    shared between these adapters.

    The adapter accepts a binding formula node and is polymorphic
    on the formula signature.

    `binding` (:class:`htsql.tr.binding.FormulaBinding`)
        The formula node to encode.

    `state` (:class:`EncodingState`)
        The current state of the encoding process.

    Aliases:

    `signature` (:class:`htsql.tr.signature.Signature`)
        The signature of the formula.

    `domain` (:class:`htsql.tr.domain.Domain`)
        The co-domain of the formula.

    `arguments` (:class:`htsql.tr.signature.Bag`)
        The arguments of the formula.
    """

    adapts(Signature)

    @classmethod
    def dispatch(interface, binding, *args, **kwds):
        # We need to override `dispatch` since the adapter is polymorphic
        # not on the type of the node itself, but on the type of the
        # node signature.
        assert isinstance(binding, FormulaBinding)
        return (type(binding.signature),)

    def __init__(self, binding, state):
        assert isinstance(binding, FormulaBinding)
        assert isinstance(state, EncodingState)
        self.binding = binding
        self.state = state
        # Extract commonly used attributes of the node.
        self.signature = binding.signature
        self.domain = binding.domain
        self.arguments = binding.arguments


class EncodeBySignature(EncodeBySignatureBase):
    """
    Translates a formula binding to a code node.

    This is an auxiliary adapter used to encode
    class:`htsql.tr.binding.FormulaBinding` nodes.  The adapter is
    polymorphic on the formula signature.

    Unless overridden, the adapter encodes the arguments of the formula
    and generates a new formula code with the same signature.
    """

    def __call__(self):
        # Encode the arguments of the formula.
        arguments = self.arguments.map(self.state.encode)
        # Produce a formula code with the same signature.
        return FormulaCode(self.signature,
                           self.domain,
                           self.binding,
                           **arguments)


class RelateBySignature(EncodeBySignatureBase):
    """
    Translates a formula binding to a space node.

    This is an auxiliary adapter used to relate
    class:`htsql.tr.binding.FormulaBinding` nodes.  The adapter is
    polymorphic on the formula signature.

    Unless overridden, the adapter generates an error.
    """

    def __call__(self):
        # Override in subclasses for formulas that generate space nodes.
        raise EncodeError("expected a valid space expression",
                          self.binding.mark)


class DirectBySignature(EncodeBySignatureBase):
    """
    Extracts a direction modifier from a formula node.

    This is an auxiliary adapter used to extract direction modifiers
    from class:`htsql.tr.binding.FormulaBinding` nodes.  The adapter is
    polymorphic on the formula signature.

    Unless overridden, the adapter returns no direction modifier.
    """

    def __call__(self):
        # Override in subclasses for formulas which may export non-trivial
        # direction modifier.
        return None


class EncodeWrapper(Encode):
    """
    Translates a wrapper binding to a code node.
    """

    adapts_many(WrapperBinding,
                DefinitionBinding)

    def __call__(self):
        # Delegate the adapter to the wrapped binding.
        return self.state.encode(self.binding.base)


class RelateWrapper(Relate):
    """
    Translates a wrapper binding to a space node.
    """

    adapts_many(WrapperBinding,
                DefinitionBinding,
                SelectionBinding)

    def __call__(self):
        # Delegate the adapter to the wrapped binding.
        return self.state.relate(self.binding.base)


class DirectWrapper(Direct):
    """
    Extracts a direction modifier from a wrapper binding.
    """

    adapts_many(WrapperBinding,
                DefinitionBinding)

    def __call__(self):
        # Delegate the adapter to the wrapped binding.
        return self.state.direct(self.binding.base)


class EncodeAlias(Encode):

    adapts(AliasBinding)

    def __call__(self):
        return self.state.encode(self.binding.base)


class RelateAlias(Relate):

    adapts(AliasBinding)

    def __call__(self):
        return self.state.relate(self.binding.base)


class DirectAlias(Direct):

    adapts(AliasBinding)

    def __call__(self):
        return self.state.direct(self.binding.base)


class DirectDirection(Direct):
    """
    Extracts a direction modifier from a direction decorator.
    """

    adapts(DirectionBinding)

    def __call__(self):
        # The direction modifier specified by the decorator.
        direction = self.binding.direction
        # Here we handle nested decorators: `++` and `--` are
        # translated to `+`; `+-` and `-+` are translated to `-`.
        base_direction = self.state.direct(self.binding.base)
        if base_direction is not None:
            direction *= base_direction
        # Return the combined direction.
        return direction


def encode(binding, state=None):
    """
    Encodes the given binding to a code expression node.

    Returns a :class:`htsql.tr.code.Code` instance (in some cases,
    a :class:`htsql.tr.code.Expression` instance).

    `binding` (:class:`htsql.tr.binding.Binding`)
        The binding node to encode.

    `state` (:class:`EncodingState` or ``None``)
        The encoding state to use.  If not set, a new encoding state
        is instantiated.
    """
    # Create a new encoding state if necessary.
    if state is None:
        state = EncodingState()
    # Realize and apply the `Encode` adapter.
    encode = Encode(binding, state)
    return encode()


def relate(binding, state=None):
    """
    Encodes the given binding to a space expression node.

    Returns a :class:`htsql.tr.code.Space` instance.

    `binding` (:class:`htsql.tr.binding.Binding`)
        The binding node to encode.

    `state` (:class:`EncodingState` or ``None``)
        The encoding state to use.  If not set, a new encoding state
        is instantiated.
    """
    # Create a new encoding state if necessary.
    if state is None:
        state = EncodingState()
    # Realize and apply the `Relate` adapter.
    relate = Relate(binding, state)
    return relate()


def direct(binding, state=None):
    """
    Extracts a direction modifier from the given binding.

    Returns

    - ``+1`` for the ``+`` modifier (ascending order);
    - ``-1`` for the ``-`` modifier (descending order);
    - ``None`` if there are no modifiers.

    `binding` (:class:`htsql.tr.binding.Binding`)
        The binding node.

    `state` (:class:`EncodingState` or ``None``)
        The encoding state to use.  If not set, a new encoding state
        is instantiated.
    """
    # Create a new encoding state if necessary.
    if state is None:
        state = EncodingState()
    # Realize and apply the `Direct` adapter.
    direct = Direct(binding, state)
    return direct()