Source

htsql / src / htsql / core / tr / assemble.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
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
#
# Copyright (c) 2006-2012, Prometheus Research, LLC
#


"""
:mod:`htsql.core.tr.assemble`
=============================

This module implements the assembling process.
"""


from ..util import Printable, Comparable, Record, listof, maybe
from ..adapter import Adapter, adapt, adapt_many
from ..domain import BooleanDomain
from .coerce import coerce
from .flow import (Code, SegmentCode, LiteralCode, FormulaCode, CastCode,
                   RecordCode, AnnihilatorCode, Unit, ColumnUnit, CompoundUnit,
                   CorrelationCode)
from .term import (PreTerm, Term, UnaryTerm, BinaryTerm, TableTerm,
                   ScalarTerm, FilterTerm, JoinTerm, CorrelationTerm,
                   EmbeddingTerm, ProjectionTerm, OrderTerm, SegmentTerm,
                   QueryTerm)
from .frame import (ScalarFrame, TableFrame, NestedFrame,
                    SegmentFrame, QueryFrame,
                    LiteralPhrase, TruePhrase, CastPhrase,
                    ColumnPhrase, ReferencePhrase, EmbeddingPhrase,
                    FormulaPhrase, Anchor, LeadingAnchor)
from .signature import (Signature, IsEqualSig, IsTotallyEqualSig, IsInSig,
                        IsNullSig, NullIfSig, IfNullSig, CompareSig,
                        AndSig, OrSig, NotSig, SortDirectionSig, ToPredicateSig,
                        FromPredicateSig)


class Claim(Comparable, Printable):
    """
    Represents an export request.

    A :class:`Claim` object represents a request to the broker frame
    to export a unit from the target frame.

    The claim indicates that the ``SELECT`` clause of the broker frame
    must contain a phrase that evaluates the unit.

    The target frame must either coincide with the broker frame or
    be a descendant of the broker frame.  When the target and the
    broker coincide, the broker is responsible for evaluating the
    unit value.  Otherwise, the broker imports the unit value from
    one of its subframes.

    Claim objects are compared by-value.  That is, two claim objects
    are equal if their units, brokers, and targets are equal to each
    other.

    `unit` (:class:`htsql.core.tr.flow.Unit`)
        The exported unit.

    `broker` (an integer)
        The tag of the broker term/frame.  The broker frame is expected
        to export a phrase corresponding to the given unit.

    `target` (an integer)
        The tag of the target term/frame.  The target frame is responsible
        for evaluating the unit.  The target term must be a descendant
        of the broker term or coincide with the broker term.
    """

    def __init__(self, unit, broker, target):
        assert isinstance(unit, Unit)
        assert isinstance(broker, int)
        assert isinstance(target, int)
        self.unit = unit
        self.broker = broker
        self.target = target

    def __basis__(self):
        # Claim objects need by-value comparison to avoid assigning
        # multiple claims for the same unit.
        return (self.unit, self.broker, self.target)

    def __str__(self):
        return "(%s)->%s->%s" % (self.unit, self.broker, self.target)


class Gate(object):
    """
    Encapsulates a dispatching context.

    Dispatching context provides information necessary to demand
    and supply unit claims.

    `is_nullable` (Boolean)
        Indicates that the currently assembled frame is going
        to be joined to the parent frame using an outer join.

        This flag affects the `is_nullable` indicator of
        exported phrases.

    `dispatches` (a dictionary `tag -> tag`)
        Maps a descendant term to the immediate child whose subtree contains
        the term.

        The `dispatches` table is used when generating unit claims
        to determine the broker term by the target term.

        See also the `offsprings` attribute of :class:`htsql.core.tr.term.Term`.

    `routes` (a dictionary `Unit | Flow -> tag`)
        Maps a unit to a term capable of evaluating the unit.

        The `routes` table is used when generating unit claims
        to determine the target term by the unit.

        A key of the `routes` table is either a :class:`htsql.core.tr.flow.Unit`
        node or a :class:`htsql.core.tr.flow.Flow` node.  The latter indicates
        that the corresponding term is capable of exporting any primitive
        unit from the given flow.

        See also the `routes` attribute of :class:`htsql.core.tr.term.Term`.

    Note that `dispatches` and `routes` come from `offsprings` and `routes`
    attributes of :class:`htsql.core.tr.term.Term`.  However they do not have to
    come from the same term!  Typically, `dispatches` comes from the term
    which is currently translated to a frame, and `routes` comes either
    from the same term or from one of its direct children.
    """

    def __init__(self, is_nullable, dispatches, routes):
        # Sanity check on the arguments.  We do not perform a costly check
        # on the keys and the values of the mappings since they come directly
        # from term attributes and it is hard to mess them up.
        assert isinstance(is_nullable, bool)
        assert isinstance(dispatches, dict)
        assert isinstance(routes, dict)
        self.is_nullable = is_nullable
        self.dispatches = dispatches
        self.routes = routes


class AssemblingState(object):
    """
    Encapsulates the state of the assembling process.

    State attributes:

    `gate` (:class:`Gate`)
        The current dispatching context.

    `claim_set` (a set of :class:`Claim`)
        All requested unit claims.

    `claims_by_broker` (a mapping `tag -> [Claim]`)
        Unit claims grouped by the broker.

        A key of the mapping is the broker tag.  A value of the mapping
        is a list of :class:`Claim` objects with the same broker.

    `phrases_by_claim` (a mapping `Claim -> [Phrase]`)
        Satisfied claims.

        A key of the mapping is a :class:`Claim` object.  A value of the
        mapping is a list of :class:`htsql.core.tr.frame.ExportPhrase` objects.
    """

    def __init__(self):
        # The stack of previous gates.
        self.gate_stack = []
        # The current gate (dispatching context).
        self.gate = None
        # The set of all unit claims (used for checking for duplicates).
        self.claim_set = None
        # Unit claims grouped by the broker.
        self.claims_by_broker = None
        # Satisfied unit claims.
        self.phrases_by_claim = None
        # Stencils and other composition state.
        self.subterms_by_segment = {}
        self.stencils_by_term = {}
        self.location_by_term = {}
        self.shift_by_term = {}
        self.name_stack = []
        self.name = None
        self.segment_stack = []
        self.segment = None
        self.correlations_stack = []
        self.correlations = {}

    def push_correlations(self, correlations):
        self.correlations_stack.append(self.correlations)
        self.correlations = correlations

    def pop_correlations(self):
        self.correlations = self.correlations_stack.pop()

    def push_name(self, name):
        assert isinstance(name, maybe(unicode))
        self.name_stack.append(self.name)
        self.name = name

    def pop_name(self):
        self.name = self.name_stack.pop()

    def push_segment(self, code):
        assert isinstance(code, SegmentCode)
        term = self.subterms_by_segment[self.segment][code]
        self.segment_stack.append(self.segment)
        self.segment = term
        self.shift_by_term[term] = 0

    def pop_segment(self):
        self.segment = self.segment_stack.pop()

    def save_subterms(self, term, subterms):
        assert isinstance(term, maybe(SegmentTerm))
        assert isinstance(subterms, listof(SegmentTerm))
        term_by_code = dict((subterm.code, subterm)
                            for subterm in subterms)
        self.subterms_by_segment[term] = term_by_code

    def save_location(self, term, location):
        assert isinstance(term, SegmentTerm)
        assert isinstance(location, maybe(int))
        self.location_by_term[term] = location

    def get_location(self):
        return self.location_by_term[self.segment]

    def save_stencils(self, term, stencils):
        assert isinstance(term, SegmentTerm)
        assert isinstance(stencils, listof(listof(int))) and len(stencils) == 3
        self.stencils_by_term[term] = stencils

    def get_code_stencil(self):
        return self.stencils_by_term[self.segment][0]

    def get_superkey_stencil(self):
        return self.stencils_by_term[self.segment][1]

    def get_key_stencil(self):
        return self.stencils_by_term[self.segment][2]

    def get_next_index(self):
        stencil = self.get_code_stencil()
        index = stencil[self.shift_by_term[self.segment]]
        self.shift_by_term[self.segment] += 1
        return index

    def decompose(self, code):
        return Decompose.__invoke__(code, self)

    def set_tree(self, term):
        """
        Initializes the assembling state.

        This method must be called before assembling any frames.

        `term` (:class:`htsql.core.tr.term.SegmentTerm`)
            The term corresponding to the top-level ``SELECT`` statement.
        """
        assert isinstance(term, SegmentTerm)
        assert not self.gate_stack
        # Use the segment term both as the dispatcher and the router.  We
        # set `is_nullable` to `False`, but the value does not really matter
        # since we never export from the segment frame.
        self.gate = Gate(False, term.offsprings, term.routes)
        # Initialize claim containers.
        self.claim_set = set()
        self.claims_by_broker = {}
        self.phrases_by_claim = {}
        # Initialize `claims_by_broker` with an empty list for each node
        # in the term tree.
        self.claims_by_broker[term.tag] = []
        for offspring in term.offsprings:
            self.claims_by_broker[offspring] = []

    def flush(self):
        """
        Clears the assembling state.
        """
        # Revert all attributes to their pristine state.  We assume that
        # `gate_stack` is already empty.
        self.gate = None
        self.claim_set = None
        self.claims_by_broker = None
        self.phrases_by_claim = None
        self.segment_indexes = None
        self.correlations_stack = []
        self.correlations = {}

    def push_gate(self, is_nullable=None, dispatcher=None, router=None):
        """
        Updates the current dispatching context.

        `is_nullable` (Boolean or ``None``)
            Indicates that the currently assembled frame is to be
            attached to the parent frame using an ``OUTER`` join.

            If ``None``, keeps the current value.

            When satisfying the claims directed to the currently
            constructed frame, this flag is used to determine whether
            the exported values are nullable or not.

        `dispatcher` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the dispatcher term.

            If ``None``, keeps the current dispatcher.

            The dispatcher term (more exactly, the `offsprings` table
            of the term) maps a descendant term to the immediate
            child whose subtree contains the term.

            When generating claims, the dispatcher is used to find
            the broker term by the target term.

            Typically, the dispatcher term is the one currently
            translated to a frame node.

        `router` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the router term.

            If ``None``, uses `dispatcher` as the router term.
            If both `dispatcher` and `router` are ``None``,
            keeps the current router.

            The router term (more exactly, the `routes` table of the
            term) maps a unit to a term capable of evaluating the unit.

            When generating claims, the router is used to find
            the target term by the unit.

            Typically, the router term is the one currently translated
            to a frame node or one of its immediate children.
        """
        # If `is_nullable` is not set, keep the current value.
        if is_nullable is None:
            is_nullable = self.gate.is_nullable
        # Extract the dispatching table from the given `dispatcher` term,
        # keeps the current table if `dispatcher` is not specified.
        if dispatcher is not None:
            dispatches = dispatcher.offsprings
        else:
            dispatches = self.gate.dispatches
        # When changing the dispatcher, we always want to change the router
        # as well.  Thus, when `dispatcher` is specified, but `router` is not,
        # we assume that `router` coincides with `dispatcher`.
        if router is None:
            router = dispatcher
        # Extract the routing table from the given `router` term, keeps
        # the current table if `router` is not specified.
        if router is not None:
            routes = router.routes
        else:
            routes = self.gate.routes
        # Save the current gate and install the new one.
        self.gate_stack.append(self.gate)
        self.gate = Gate(is_nullable, dispatches, routes)

    def pop_gate(self):
        """
        Restores the previous dispatching context.
        """
        self.gate = self.gate_stack.pop()

    def assemble(self, term):
        """
        Assembles a frame node for the given term.

        `term` (:class:`htsql.core.tr.term.Term`)
            A term node.
        """
        # Realize and call the `Assemble` adapter.
        return assemble(term, self)

    def appoint(self, unit):
        """
        Generates a claim for the given unit.

        This method finds the target and the broker terms that are
        capable of evaluating the unit and returns the corresponding
        :class:`Claim` object.

        `unit` (:class:`htsql.core.tr.flow.Unit`)
            The unit to make a claim for.
        """
        # To make a claim, we need to find two terms:
        # - the target term, one that is capable of evaluating the unit;
        # - the broker term, an immediate child which contains the target
        #   term (or, possibly coincides with the target term).
        # We use the current routing and dispatching tables to determine
        # the target and the broker terms respectively.
        # Note that it is a responsibility of the caller to ensure that
        # the current routing table contains the given unit.

        ## Extract the (tag of the) target term from the current routing
        ## table.  Recall that `routes` does not keep primitive units directly,
        ## instead a flow node represents all primitive units that belong
        ## to that flow.
        #if unit.is_primitive:
        #    assert unit.flow in self.gate.routes
        #    target = self.gate.routes[unit.flow]
        #if unit.is_compound:
        #    assert unit in self.gate.routes
        #    target = self.gate.routes[unit]
        assert unit in self.gate.routes, (unit, self.gate.routes)
        target = self.gate.routes[unit]
        # Extract the (tag of the) broker term from the current dispatch
        # table.
        # FIXME?: there is a possibility that the target coincides with
        # the current term -- it may happen, for instance, with scalar units.
        # To handle this case properly, we need to dismantle the unit
        # and appoint all its sub-units.  However currently the compiler
        # takes special care to ensure that scalar units are never routed
        # to the term where they are defined, so we do not bother with
        # handling this case here.
        assert target in self.gate.dispatches
        broker = self.gate.dispatches[target]
        # Generate and return a claim object.
        return Claim(unit, broker, target)

    def forward(self, claim):
        """
        Generates a forward claim for the given claim.

        This function takes a claim targeted to one of the current term's
        descendants and returns a new claim dispatched to the current term's
        immediate child.

        `claim` (:class:`Claim`)
            A claim dispatched to the current term.
        """
        # This function is used when a term gets a claim targeted not
        # to the term itself, but to one of its descendants.  In this
        # case, we need to re-dispatch the claim to the immediate child
        # whose subtree contains the target term.
        assert claim.target in self.gate.dispatches
        broker = self.gate.dispatches[claim.target]
        return Claim(claim.unit, broker, claim.target)

    def schedule(self, code, dispatcher=None, router=None):
        """
        Appoints and assigns claims for all units of the given code.

        `code` (:class:`htsql.core.tr.flow.Code`)
            A code object to schedule.

        `dispatcher` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the dispatcher to use when appointing units.

            If ``None``, keeps the current dispatcher.

        `router` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the router to use when appointing units.

            If ``None``, uses `dispacher` as the router term;
            if both are ``None``, keeps the current router.
        """
        # Update the gate to use the given dispatcher and router.
        self.push_gate(dispatcher=dispatcher, router=router)
        # Iterate over all units included to the given code node.
        for unit in code.units:
            # Generate a claim for the unit.
            claim = self.appoint(unit)
            # Assign the claim to the broker.
            self.demand(claim)
        # Restore the original gate.
        self.pop_gate()

    def evaluate_all(self, code, dispatcher=None, router=None):
        """
        Evaluates the given code node.

        Returns the corresponding :class:`htsql.core.tr.frame.Phrase` node.

        It is assumed that the code node was previously scheduled
        with :meth:`schedule` and all the claims were satisfied.

        `code` (:class:`htsql.core.tr.flow.Code`)
            The code node to evaluate.

        `dispatcher` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the dispatcher to use when appointing units.

            If ``None``, keeps the current dispatcher.

        `router` (:class:`htsql.core.tr.term.Term` or ``None``)
            Specifies the router to use when appointing units.

            If ``None`` uses `dispacher` as the router term;
            if both are ``None``, keeps the current router.
        """
        # Update the gate to use the given dispatcher and router.
        self.push_gate(dispatcher=dispatcher, router=router)
        # Realize and call the `Evaluate` adapter.
        phrases = list(Evaluate.__invoke__(code, self))
        # Restore the original gate.
        self.pop_gate()
        # Return the generated phrase.
        return phrases

    def evaluate(self, code, dispatcher=None, router=None):
        phrases = self.evaluate_all(code, dispatcher, router)
        assert len(phrases) == 1
        [phrase] = phrases
        return phrase

    def demand(self, claim):
        """
        Assigns the given claim to the broker.

        `claim` (:class:`Claim`)
            The claim to assign.
        """
        # Check is the claim (remember, they are compared by value) was
        # already assigned.
        if not claim in self.claim_set:
            # Add it to the list of all claims.
            self.claim_set.add(claim)
            # Assign it to the broker.
            self.claims_by_broker[claim.broker].append(claim)

    def supply(self, claim, *phrases):
        """
        Satisfies the claim.

        `claim` (:class:`Claim`)
            The claim to satisfy.

        `phrases` ([:class:`htsql.core.tr.frame.Phrase`])
            The phrases satisfying the claim.
        """
        # A few sanity checks.  Verify that the claim was actually requested.
        assert claim in self.claim_set
        # Verify that the claim was not satisfied already.
        assert claim not in self.phrases_by_claim
        # Save the phrase.
        self.phrases_by_claim[claim] = list(phrases)

    def to_predicate(self, phrase):
        return FormulaPhrase(ToPredicateSig(), phrase.domain,
                             phrase.is_nullable, phrase.expression, op=phrase)

    def from_predicate(self, phrase):
        return FormulaPhrase(FromPredicateSig(), phrase.domain,
                             phrase.is_nullable, phrase.expression, op=phrase)


class Assemble(Adapter):
    """
    Translates a term node to a frame node.

    This is an interface adapter, see subclasses for implementations.

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

        Assemble: (Term, AssemblingState) -> Frame

    The adapter is polymorphic on the `Term` argument.

    `term` (:class:`htsql.core.tr.term.Term`)
        A term node.

    `state` (:class:`AssemblingState`)
        The current state of the assembling process.
    """

    adapt(PreTerm)

    def __init__(self, term, state):
        assert isinstance(term, PreTerm)
        assert isinstance(state, AssemblingState)
        self.term = term
        self.state = state

    def __call__(self):
        # Implement in subclasses.
        raise NotImplementedError("the compile adapter is not implemented"
                                  " for a %r node" % self.term)


class AssembleTerm(Assemble):
    """
    Assembles a frame for a proper term node.

    This adapt :class:`Assemble` for proper term nodes (i.e., not a
    :class:`htsql.core.tr.term.QueryTerm`).

    Attributes:

    `claims` (a list of :class:`Claim`)
        The claims that are dispatched to the term.
    """

    adapt(Term)

    def __init__(self, term, state):
        super(AssembleTerm, self).__init__(term, state)
        # Extract claims dispatched to the given term.
        self.claims = state.claims_by_broker[term.tag]


class AssembleScalar(Assemble):
    """
    Assembles a (scalar) frame for a scalar term.
    """

    adapt(ScalarTerm)

    def __call__(self):
        # A scalar term cannot export anything and thus should never receive
        # any claims.
        assert not self.claims
        # Generate and return a frame node.
        return ScalarFrame(self.term)


class AssembleTable(Assemble):
    """
    Assembles a (table) frame for a table term.
    """

    adapt(TableTerm)

    def __call__(self):
        # The actual table entity.
        table = self.term.table
        # Iterate over and satisfy all the claims.
        for claim in self.claims:
            # Sanity checks.
            assert claim.broker == self.term.tag
            assert claim.target == self.term.tag
            # FIXME: Currently, a table term could only expect claims for
            # column units.  In the future, however, we may wish to allow
            # other kinds of units (for instance, to support pseudo-columns).
            # To handle that, we may need to introduce a new adapter
            # dispatched on the unit type.
            assert claim.unit.is_primitive
            assert isinstance(claim.unit, ColumnUnit)
            # The requested column entity.
            column = claim.unit.column
            # More sanity checks.
            assert column.table == table
            # The exported phrase is nullable if the column itself is nullable,
            # but also if the frame is attached to its parent using an
            # `OUTER JOIN`.
            is_nullable = (column.is_nullable or self.state.gate.is_nullable)
            # Satisfy the claim with a column phrase.
            export = ColumnPhrase(self.term.tag, column, is_nullable,
                                  claim.unit)
            self.state.supply(claim, export)
        # Generate and return a frame node.
        return TableFrame(table, self.term)


class AssembleBranch(Assemble):
    """
    Assembles a branch frame.

    This is a default implementation used by all non-terminal (i.e. unary
    or binary) terms.
    """

    adapt_many(UnaryTerm, BinaryTerm)

    def delegate(self):
        # Review all the given claims.
        for claim in self.claims:
            assert claim.broker == self.term.tag
            # If the claim is not targeted to us directly, we are not
            # responsible for evaluating it.  Just forward it to the
            # next hop.
            if claim.target != self.term.tag:
                next_claim = self.state.forward(claim)
                self.state.demand(next_claim)
            # Otherwise, the frame will evaluate the unit of the claim.
            # Dismantle the unit and submit claims for all of its sub-units.
            else:
                # FIXME: Here we assume that a claim targeted to a non-leaf
                # term is always compound.  This may (or may not) change
                # in the future.
                assert claim.unit.is_compound
                self.state.schedule(claim.unit.code)

    def assemble_include(self):
        # Assemle the `FROM` list; should be overridden in subclasses.
        return []

    def assemble_embed(self):
        # Assemble the embedded frames; override in subclasses.
        # The default implementations assumes there are no embedded subframes.
        return []

    def assemble_select(self):
        # Assemble the `SELECT` clause and satisfy all the claims; may be
        # overridden in subclasses.

        # Note that this method is called after `assemble_include()` and
        # `assemble_embed()`, so any claims requested by `delegate()` should
        # be already satisfied.

        # List of `SELECT` phrases.
        select = []
        # A mapping: `phrase` -> the position of the phrase in the `select`
        # list.  We use it to avoid duplicates in the `SELECT` list.
        index_by_phrase = {}

        # For each of the claims:
        # - generate a phrase corresponding to the unit of the claim;
        # - add the phrase to the `SELECT` list;
        # - satisfy the claim with a reference to the generated phrase.
        for claim in self.claims:

            # Generate a phrase corresponding to the claim.  Check if
            # the claim is not targeted to us directly -- then it was
            # targeted to one of our descendants.
            if claim.target != self.term.tag:
                # Generate a forward claim (again).
                next_claim = self.state.forward(claim)
                # We expect the forward claim to be already satisfied.
                assert next_claim in self.state.phrases_by_claim
                # Get the export phrase that satisfied the claim.
                phrases = self.state.phrases_by_claim[next_claim]
            # Otherwise, the claim is targeted to us and we are responsible
            # for evaluating the unit of the claim.
            else:
                # Since it is a branch term, the unit must be compound.
                # So we evaluate the code expression of the unit.
                phrases = self.state.evaluate_all(claim.unit.code)

            export = []
            for phrase in phrases:
                # Check if the generated phrase is a duplicate.  Even though
                # all claims are unique, different claims may still produce
                # identical phrases.  Therefore an extra check here is necessary.
                if phrase not in index_by_phrase:
                    # So it is not a duplicate: add it to the `SELECT` list.
                    index = len(select)
                    select.append(phrase)
                    index_by_phrase[phrase] = index

                # Generate an export reference to the phrase.
                index = index_by_phrase[phrase]
                domain = phrase.domain
                # The reference is nullable if the referenced phrase itself is
                # nullable or the assembled frame is to be attached using an
                # `OUTER JOIN`.
                is_nullable = (phrase.is_nullable or
                               self.state.gate.is_nullable)
                reference = ReferencePhrase(self.term.tag, index, domain,
                                            is_nullable, claim.unit)
                export.append(reference)
            # Satisfy the claim with the generated reference.
            self.state.supply(claim, *export)

        # It might happen (though with the way the compiler generates the term
        # tree, it is probably impossible) that the frame has no claims
        # dispatched to it and therefore the `SELECT` list is empty.  Since
        # SQL syntax does not permit an empty `SELECT` list, we add a dummy
        # phrase to the list.
        if not select:
            select = [TruePhrase(self.term.expression)]
        # All claims are satisfied; return the generated `SELECT` list.
        return select

    def assemble_where(self):
        # Assemble the `WHERE` clause; could be overridden in subclasses.
        return None

    def assemble_group(self):
        # Assemble the `GROUP BY` clause; could be overridden in subclasses.
        return []

    def assemble_having(self):
        # Assemble the `HAVING` clause; could be overridden in subclasses.
        return None

    def assemble_order(self):
        # Assemble the `ORDER BY` clause; could be overridden in subclasses.
        return []

    def assemble_limit(self):
        # Assemble the `LIMIT` clause; could be overridden in subclasses.
        return None

    def assemble_offset(self):
        # Assemble the `OFFSET` clause; could be overridden in subclasses.
        return None

    def assemble_frame(self, include, embed, select,
                       where, group, having,
                       order, limit, offset):
        # Assemble a frame node with the given clauses; could be overridden
        # in subclasses.
        return NestedFrame(include, embed, select,
                           where, group, having,
                           order, limit, offset, self.term)

    def __call__(self):
        # Review the given claims and dispatch new ones.
        self.delegate()
        # Assemble a `FROM` clause.
        include = self.assemble_include()
        # Assemble all embedded frames.
        embed = self.assemble_embed()
        # Assemble the `SELECT` clause and satisfy the claims.
        select = self.assemble_select()
        # Assemble the remaining clauses of the frame.
        where = self.assemble_where()
        group = self.assemble_group()
        having = self.assemble_having()
        order = self.assemble_order()
        limit = self.assemble_limit()
        offset = self.assemble_offset()
        # Generate and return a frame node.
        return self.assemble_frame(include, embed, select,
                                   where, group, having,
                                   order, limit, offset)


class AssembleUnary(AssembleBranch):
    """
    Assembles a frame for an unary term.

    This is a default implementation used by all unary terms.
    """

    adapt(UnaryTerm)
    # Note that `AssembleUnary` is inherited from `AssembleBranch` (not
    # `Assemble`) to indicate relative priority of these two implementations.

    def assemble_include(self):
        # Assemble the `FROM` list.  All unary terms have just one child,
        # so they could all share the same implementation.

        # Set up the dispatch context for the child term.
        self.state.push_gate(is_nullable=False, dispatcher=self.term.kid)
        # Assemble the frame by the child term.
        frame = self.state.assemble(self.term.kid)
        # Restore the original dispatch context.
        self.state.pop_gate()
        # Generate a `JOIN` clause.  Since it is the first (and the only)
        # subframe, the `JOIN` clause has no join condition.
        anchor = LeadingAnchor(frame)
        # Return a `FROM` list with a single subframe.
        return [anchor]


class AssembleFilter(Assemble):
    """
    Assembles a frame for a filter term.
    """

    adapt(FilterTerm)

    def delegate(self):
        # Call the super `delegate()` to review and forward claims.
        super(AssembleFilter, self).delegate()
        # Appoint and assign claims for the `filter` expression.
        # Note that we route the filter units against the term's child --
        # it could do routing because we injected `filter` to the `kid`
        # term when the filter term was compiled.  (However since the filter
        # term contains all the routes of its child, we could have routed
        # the filter against the parent term with the same effect.)
        self.state.schedule(self.term.filter,
                            router=self.term.kid)

    def assemble_where(self):
        # Assemble a `WHERE` clause.
        # Evaluate the `filter` expression (we expect all its claims
        # to be already satisfied).
        phrase = self.state.evaluate(self.term.filter,
                                     router=self.term.kid)
        return self.state.to_predicate(phrase)


class AssembleOrder(Assemble):
    """
    Assembles a frame for an order term.
    """

    adapt(OrderTerm)

    def delegate(self):
        # Call the super `delegate()` to review and forward claims.
        super(AssembleOrder, self).delegate()
        # Appoint and assign claims for all code expressions in
        # the order list.
        for code, direction in self.term.order:
            self.state.schedule(code, router=self.term.kid)

    def assemble_order(self):
        # Assemble the `ORDER BY` clause.
        # The list of `(phrase, direction)` pairs.
        order = []
        # Evaluate the code expressions in the order list.
        for code, direction in self.term.order:
            # If a code does not have units, it must be a literal or
            # a scalar function, and thus it cannot affect the ordering
            # of the frame rows.  We can safely weed it out.
            if not code.units:
                continue
            phrase = self.state.evaluate(code, router=self.term.kid)
            phrase = FormulaPhrase(SortDirectionSig(direction),
                                   phrase.domain, phrase.is_nullable,
                                   phrase.expression, base=phrase)
            order.append(phrase)
        return order

    def assemble_limit(self):
        # Assemble the `LIMIT` clause.
        return self.term.limit

    def assemble_offset(self):
        # Assemble the `OFFSET` clause.
        return self.term.offset


class AssembleProjection(Assemble):
    """
    Assembles a frame for a projection term.
    """

    adapt(ProjectionTerm)

    def delegate(self):
        # Update the dispatching context to use the routing table
        # of the child term.
        # Note: a projection term is special in that it does not provide
        # all the routes of its child term.  In particular, when evaluating
        # an aggregate expression, all its units must be appointed against
        # the child's routing table.  Only aggregate units target a projection
        # term directly, therefore updating the routing table should not
        # affect evaluation of any other claims.
        self.state.push_gate(router=self.term.kid)
        # Call the super `delegate()` to review and forward claims.
        super(AssembleProjection, self).delegate()
        # Appoint and assign claims for the projection kernel.
        for code in self.term.kernels:
            self.state.schedule(code)
        # Restore the original dispatching context.
        self.state.pop_gate()

    def assemble_select(self):
        # Just like in `delegate()`, we update the dispatching context
        # to use the routing table of the child term.
        self.state.push_gate(router=self.term.kid)
        # Call the super implementation to generate a `SELECT` list.
        select = super(AssembleProjection, self).assemble_select()
        # Restore the original dispatching context.
        self.state.pop_gate()
        return select

    def assemble_group(self):
        # Assemble a `GROUP BY` clause.
        # The list of phrases included to the clause.
        group = []
        # Evaluate all the code expressions in the kernel.
        for code in self.term.kernels:
            # If a code does not have units, it must be a scalar function
            # or a literal, and therefore it cannot affect the projection.
            # We can safely weed it out.
            if not code.units:
                continue
            phrase = self.state.evaluate(code, router=self.term.kid)
            group.append(phrase)
        # It may happen that the kernel of the projection is empty, which
        # means the range of the projection is the scalar flow.  SQL
        # recognizes scalar projections by detecting an aggregate in
        # the `SELECT` list, so, technically, we could keep the `GROUP BY`
        # list empty.  However, when collapsing frames, we must be able
        # to distinguish between projection (scalar or not) and non-projection
        # frames.  To make it easy, we never generate an empty `GROUP BY`
        # list for projection terms.  When the projection kernel is empty,
        # we just add a dummy literal to the list.  This literal will be
        # removed by the reducing process.
        if not group:
            group = [TruePhrase(self.term.expression)]
        return group


class AssembleJoin(Assemble):
    """
    Assembles a frame for a join term.
    """

    adapt(JoinTerm)

    def delegate(self):
        # Call the super `delegate()` to review and forward claims.
        super(AssembleJoin, self).delegate()
        # Appoint and assign claims for the join condition.
        # The join condition is composed of equality expressions
        # of the form: `lop = rop`, where the the operands are
        # exported from the left child and the right child respectively.
        for joint in self.term.joints:
            self.state.schedule(joint.lop, router=self.term.lkid)
            self.state.schedule(joint.rop, router=self.term.rkid)

    def assemble_include(self):
        # Assemble the `FROM` list.
        # Set up the dispatch context for the first child term.
        # Note that currently right joins are never generated
        # by the compiler, so `is_nullable` is always `False`.
        self.state.push_gate(is_nullable=self.term.is_right,
                             dispatcher=self.term.lkid)
        # Assemble a frame for the first child.
        lframe = self.state.assemble(self.term.lkid)
        # Restore the original dispatch context.
        self.state.pop_gate()
        # Generate a `JOIN` clause for the first subframe.
        lanchor = LeadingAnchor(lframe)
        # Set up the dispatch context for the second child term.
        self.state.push_gate(is_nullable=self.term.is_left,
                             dispatcher=self.term.rkid)
        # Assemble a frame for the second child.
        rframe = self.state.assemble(self.term.rkid)
        # Restore the original dispatch context.
        self.state.pop_gate()
        # Generate the join condition, which is a conjunction of equalities
        # of the form: `lop = rop`.  The operands of the equality operator
        # are evaluated against the left subframe and the right subframe
        # respectively.
        equalities = []
        for joint in self.term.joints:
            lop = self.state.evaluate(joint.lop, router=self.term.lkid)
            rop = self.state.evaluate(joint.rop, router=self.term.rkid)
            is_nullable = (lop.is_nullable or rop.is_nullable)
            signature = IsEqualSig(+1)
            equality = FormulaPhrase(signature, coerce(BooleanDomain()),
                                     is_nullable, self.term.expression,
                                     lop=lop, rop=rop)
            equalities.append(equality)
        condition = None
        if equalities:
            is_nullable = any(equality.is_nullable for equality in equalities)
            condition = FormulaPhrase(AndSig(), coerce(BooleanDomain()),
                                      is_nullable, self.term.expression,
                                      ops=equalities)
        elif self.term.is_left or self.term.is_right:
            condition = TruePhrase(self.term.expression)
            condition = self.state.to_predicate(condition)
        # Generate a `JOIN` clause for the second subframe.
        ranchor = Anchor(rframe, condition,
                         self.term.is_left, self.term.is_right)
        # Return the generated `FROM` list.
        return [lanchor, ranchor]


class AssembleEmbedding(Assemble):
    """
    Assembles a frame for an embedding term.
    """

    adapt(EmbeddingTerm)

    def delegate(self):
        # Call the super `delegate()` to review and forward claims.
        super(AssembleEmbedding, self).delegate()

        for code in self.term.correlations:
            self.state.schedule(code, router=self.term.lkid)

    def assemble_include(self):
        # Assemble the `FROM` list.
        # Although embedding is a binary term, only its first child goes
        # to the `FROM` list, so the assembling here practically coincides
        # with the one for a unary term.

        # Set up the dispatch context for the child term.
        self.state.push_gate(is_nullable=False, dispatcher=self.term.lkid)
        # Assemble a frame corresponding to the first child.
        frame = self.state.assemble(self.term.lkid)
        # Restore the original dispatch context.
        self.state.pop_gate()
        # Generate a `JOIN` clause (without any join condition).
        anchor = LeadingAnchor(frame)
        # Return a `FROM` list with a single subframe.
        return [anchor]

    def assemble_embed(self):
        # Assemble the list of embedded frames.

        correlations = {}
        for code in self.term.correlations:
            phrase = self.state.evaluate(code, router=self.term.lkid)
            correlations[code] = phrase
        self.state.push_correlations(correlations)

        # Set up the dispatch context for the embedded term.  An embedded
        # frame is always considered nullable, although it may not be true
        # in some cases.  In practice, nullability of an embedded frame does
        # not affect the translator.
        self.state.push_gate(is_nullable=True, dispatcher=self.term.rkid)
        # Generate a frame for the embedded term.
        frame = self.state.assemble(self.term.rkid)
        # Restore the original dispatch context.
        self.state.pop_gate()
        self.state.pop_correlations()
        # Return a list of subframes embedded to the assembled frame.
        return [frame]


class AssembleCorrelation(Assemble):

    adapt(CorrelationTerm)

    def delegate(self):
        # An embedded frame is special in that its `SELECT` clause could
        # contain only one phrase (corresponding to a correlation unit).
        # It is a responsibility of the compiler to ensure that there is
        # one and only one unit targeted to a correlation term.
        assert len(self.claims) == 1
        # Get the (only) claim.  It must be a compound claim of a correlation
        # unit targeted to the term itself.
        [claim] = self.claims
        assert claim.target == self.term.tag
        assert claim.unit.is_compound
        # Dismantle the unit, appoint and assign its subunits.
        self.state.schedule(claim.unit.code)
        # Note that we do not need to assign the units of `joints`: it is done
        # by our parent, see `AssembleEmbedding.delegate()`.

    def assemble_select(self):
        # Assemble a `SELECT` clause.
        # The (only) claim delegated (and targeted) to the frame.
        [claim] = self.claims
        # All the subunits must be already satisfied, so we could evaluate
        # a phrase corresponding to the claim unit.
        phrase = self.state.evaluate(claim.unit.code)
        # Generate an export phrase and satisfy the claim.
        domain = phrase.domain
        # Values produced by embedded frames are always nullable.
        # FIXME: is it always true? Still, it is safe to assume so, and it is
        # unlikely to significantly degrade the generated SQL.
        is_nullable = True
        export = EmbeddingPhrase(self.term.tag, domain, is_nullable, claim.unit)
        self.state.supply(claim, export)
        # Return the `SELECT` list.
        return [phrase]


class AssembleSegment(Assemble):
    """
    Assembles a frame for a segment term.
    """

    adapt(SegmentTerm)

    def delegate(self):
        # This is a top-level frame, so it can't have claims.
        assert not self.claims
        # Assign all the units in the `SELECT` clause.
        self.state.schedule(self.term.code.code)
        for code in self.term.superkeys:
            self.state.schedule(code)
        if self.term.subtrees:
            for code in self.term.keys:
                self.state.schedule(code)

    def assemble_select(self):
        # Assemble a `SELECT` clause.
        select = []
        stencils = []
        phrase_groups = []
        phrase_groups.append(self.state.evaluate_all(self.term.code.code))
        phrase_groups.append([self.state.evaluate(code)
                              for code in self.term.superkeys])
        if self.term.subtrees:
            phrase_groups.append([self.state.evaluate(code)
                                  for code in self.term.keys])
        else:
            phrase_groups.append([])
        index_by_phrase = {}
        for phrases in phrase_groups:
            stencil = []
            for phrase in phrases:
                if phrase not in index_by_phrase:
                    index = len(select)
                    select.append(phrase)
                    index_by_phrase[phrase] = index
                stencil.append(index_by_phrase[phrase])
            stencils.append(stencil)
        if not select:
            select = [TruePhrase(self.term.code)]
        self.state.save_stencils(self.term, stencils)
        return select

    def assemble_subtrees(self):
        subtrees = []
        duplicates = set()
        for code in self.term.code.code.segments:
            if code in duplicates:
                continue
            duplicates.add(code)
            subterm = self.term.subtrees[code]
            location = len(subtrees)
            self.state.set_tree(subterm)
            self.state.save_location(subterm, location)
            subframe = self.state.assemble(subterm)
            subtrees.append(subframe)
        self.state.save_subterms(self.term,
                                 [frame.term for frame in subtrees])
        return subtrees

    def assemble_frame(self, include, embed, select,
                       where, group, having,
                       order, limit, offset):
        subtrees = self.assemble_subtrees()
        return SegmentFrame(include, embed, select,
                           where, group, having,
                           order, limit, offset,
                           subtrees, self.term)


class AssembleQuery(Assemble):
    """
    Assembles a top-level query frame.
    """

    adapt(QueryTerm)

    def __call__(self):
        # Compile the segment frame.
        segment = None
        compose = None
        if self.term.segment is not None:
            # Initialize the state.
            self.state.set_tree(self.term.segment)
            self.state.save_location(self.term.segment, None)
            self.state.save_subterms(None, [self.term.segment])
            # Compile the segment.
            segment = self.state.assemble(self.term.segment)
            # Generate the compositor.
            self.state.push_name(self.term.binding.profile.tag)
            compose = self.state.decompose(self.term.segment.code)
            # Clean up the state.
            self.state.flush()
        # Generate a frame node.
        return QueryFrame(segment, compose, self.term)


class Evaluate(Adapter):
    """
    Translates a code node to a phrase node.

    This is an interface adapter; see subclasses for implementations.

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

        Evaluate(Code, AssemblingState) -> Phrase

    The adapter is polymorphic on the `Code` argument.

    `code` (:class:`htsql.core.tr.flow.Code`)
        The code node to translate.

    `state` (:class:`AssemblingState`)
        The current state of the assembling process.
    """

    adapt(Code)

    def __init__(self, code, state):
        assert isinstance(code, Code)
        assert isinstance(state, AssemblingState)
        self.code = code
        self.state = state

    def __call__(self):
        # Implement in subclasses.
        raise NotImplementedError("the evaluate adapter is not implemented"
                                  " for a %r node" % self.code)


class EvaluateSegment(Evaluate):

    adapt(SegmentCode)

    def __call__(self):
        # Nested segments are serialized into a separate frame tree.
        return []


class EvaluateLiteral(Evaluate):
    """
    Evaluates a literal code.
    """

    adapt(LiteralCode)

    def __call__(self):
        # Keep all attributes, but switch the class.
        yield LiteralPhrase(self.code.value, self.code.domain, self.code)


class EvaluateCast(Evaluate):
    """
    Evaluates a cast code.
    """

    adapt(CastCode)

    def __call__(self):
        # Evaluate the operand and generate a phrase node.
        # Note that the for some source and target domains, the reducer will
        # retranslate a generic cast phrase to a more specific expression.
        base = self.state.evaluate(self.code.base)
        yield CastPhrase(base, self.code.domain, base.is_nullable, self.code)


class EvaluateRecord(Evaluate):

    adapt(RecordCode)

    def __call__(self):
        for field in self.code.fields:
            for phrase in self.state.evaluate_all(field):
                yield phrase


class EvaluateAnnihilator(Evaluate):

    adapt(AnnihilatorCode)

    def __call__(self):
        yield self.state.evaluate(self.code.indicator)
        for phrase in self.state.evaluate_all(self.code.code):
            yield phrase


class EvaluateCorrelation(Evaluate):

    adapt(CorrelationCode)

    def __call__(self):
        assert self.code.code in self.state.correlations
        # FIXME: is this correct in case of nested correlated subqueries?
        # FIXME: implement decompose?
        yield self.state.correlations[self.code.code]


class EvaluateFormula(Evaluate):
    """
    Evaluates a formula node.

    The evaluation could be specific to the formula signature and is
    implemented by the :class:`EvaluateBySignature` adapter.
    """

    adapt(FormulaCode)

    def __call__(self):
        # Delegate the evaluation to `EvaluteBySignature`.
        return EvaluateBySignature.__invoke__(self.code, self.state)


class EvaluateBySignature(Adapter):
    """
    Evaluates a formula node.

    This is an auxiliary adapter used to evaluate
    :class:`htsql.core.tr.flow.FormulaCode` nodes.  The adapter is polymorphic
    on the formula signature.

    Unless overridden, the adapter evaluates the arguments of the formula
    and generates a new formula phrase with the same signature.

    `code` (:class:`htsql.core.tr.flow.FormulaCode`)
        The formula node to evaluate.

    `state` (:class:`AssemblingState`)
        The current state of the assembling process.

    Aliases:

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

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

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

    adapt(Signature)

    @classmethod
    def __dispatch__(interface, code, *args, **kwds):
        # Override the default dispatch since the adapter is polymorphic
        # on the type of the formula signature, not on the formula itself.
        assert isinstance(code, FormulaCode)
        return (type(code.signature),)

    def __init__(self, code, state):
        assert isinstance(code, FormulaCode)
        assert isinstance(state, AssemblingState)
        self.code = code
        self.state = state
        # Extract commonly used attributes of the node.
        self.signature = code.signature
        self.domain = code.domain
        self.arguments = code.arguments

    def __call__(self):
        # Evaluate the arguments of the formula.
        arguments = self.arguments.map(self.state.evaluate)
        # By default, assume that the formula is null-regular.  The adapter
        # should be overridden for nodes where it is not the case.
        is_nullable = any(cell.is_nullable for cell in arguments.cells())
        # Generate a new formula node.
        yield FormulaPhrase(self.signature,
                            self.domain,
                            is_nullable,
                            self.code,
                            **arguments)


class EvaluateIsEqualBase(EvaluateBySignature):

    adapt_many(IsEqualSig, IsInSig, CompareSig)

    def __call__(self):
        for phrase in super(EvaluateIsEqualBase, self).__call__():
            yield self.state.from_predicate(phrase)


class EvaluateIsTotallyEqualBase(EvaluateBySignature):
    """
    Evaluates the total equality (``==``) operator.
    """

    adapt_many(IsTotallyEqualSig, IsNullSig)

    def __call__(self):
        # Override the default implementation since the total equality
        # operator is not null-regular, and, in fact, always not nullable.
        arguments = self.arguments.map(self.state.evaluate)
        phrase = FormulaPhrase(self.signature, self.domain,
                               False, self.code, **arguments)
        yield self.state.from_predicate(phrase)


class EvaluateNullIf(EvaluateBySignature):
    """
    Evaluates the ``null_if()`` operator.
    """

    adapt(NullIfSig)

    def __call__(self):
        # Override the default implementation since the `null_if()`
        # operator is not null-regular, and, in fact, is always nullable.
        arguments = self.arguments.map(self.state.evaluate)
        yield FormulaPhrase(self.signature, self.domain,
                            True, self.code, **arguments)


class EvaluateIfNull(EvaluateBySignature):
    """
    Evaluates the ``if_null()`` operator.
    """

    adapt(IfNullSig)

    def __call__(self):
        # Override the default implementation since the `null_if()`
        # operator is not null-regular.  It is nullable only if all of
        # its arguments are nullable.
        arguments = self.arguments.map(self.state.evaluate)
        is_nullable = all(cell.is_nullable for cell in arguments.cells())
        yield FormulaPhrase(self.signature, self.domain,
                            is_nullable, self.code, **arguments)


class EvaluateAndOrNot(EvaluateBySignature):

    adapt_many(AndSig, OrSig, NotSig)

    def __call__(self):
        arguments = (self.arguments.map(self.state.evaluate)
                                   .map(self.state.to_predicate))
        is_nullable = any(cell.is_nullable for cell in arguments.cells())
        phrase = FormulaPhrase(self.signature,
                               self.domain,
                               is_nullable,
                               self.code,
                               **arguments)
        yield self.state.from_predicate(phrase)


class EvaluateUnit(Evaluate):
    """
    Evaluates a unit.
    """

    adapt(Unit)

    def __call__(self):
        # Generate a claim for a unit (for the second time).
        claim = self.state.appoint(self.code)
        # We expect the claim to be already satisfied.
        assert claim in self.state.phrases_by_claim
        # Return the export phrase corresponding to the claim.
        return self.state.phrases_by_claim[claim]


class Decompose(Adapter):

    adapt(Code)

    def __init__(self, code, state):
        assert isinstance(code, Code)
        assert isinstance(state, AssemblingState)
        self.code = code
        self.state = state

    def __call__(self):
        index = self.state.get_next_index()
        def compose_value(row, stream, index=index):
            return row[index]
        return compose_value


class DecomposeSegment(Decompose):

    adapt(SegmentCode)

    def __call__(self):
        if self.state.segment is None:
            self.state.push_segment(self.code)
            compose_code = self.state.decompose(self.code.code)
            self.state.pop_segment()
            def compose_root_segment(row, stream, compose_code=compose_code):
                items = []
                for row in stream:
                    items.append(compose_code(row, stream))
                return items
            return compose_root_segment
        else:
            key_stencil = self.state.get_key_stencil()
            self.state.push_segment(self.code)
            location = self.state.get_location()
            superkey_stencil = self.state.get_superkey_stencil()
            compose_code = self.state.decompose(self.code.code)
            self.state.pop_segment()
            def compose_nested_segment(row, stream, compose_code=compose_code,
                                       location=location,
                                       key_stencil=key_stencil,
                                       superkey_stencil=superkey_stencil):
                items = []
                key = stream.get(key_stencil)
                substream = stream.substreams[location]
                for row in substream.slice(superkey_stencil, key):
                    items.append(compose_code(row, substream))
                return items
            return compose_nested_segment


class DecomposeCompound(Decompose):

    adapt(CompoundUnit)

    def __call__(self):
        return self.state.decompose(self.code.code)


class DecomposeRecord(Decompose):

    adapt(RecordCode)

    def __call__(self):
        compose_fields = []
        field_names = []
        for field, profile in zip(self.code.fields,
                                  self.code.domain.fields):
            field_names.append(profile.tag)
            self.state.push_name(profile.tag)
            compose_field = self.state.decompose(field)
            self.state.pop_name()
            compose_fields.append(compose_field)
        record_class = Record.make(self.state.name, field_names)
        def compose_record(row, stream, record_class=record_class,
                           compose_fields=compose_fields):
            return record_class(*[compose_field(row, stream)
                                  for compose_field in compose_fields])
        return compose_record


class DecomposeAnnihilator(Decompose):

    adapt(AnnihilatorCode)

    def __call__(self):
        compose_indicator = self.state.decompose(self.code.indicator)
        compose = self.state.decompose(self.code.code)
        def compose_nullable(row, stream,
                             compose_indicator=compose_indicator,
                             compose=compose):
            value = compose(row, stream)
            if compose_indicator(row, stream) is None:
                return None
            return value
        return compose_nullable


def assemble(term, state=None):
    """
    Compiles a new frame node for the given term.

    Returns a :class:`htsql.core.tr.frame.Frame` instance.

    `term` (:class:`htsql.core.tr.term.Term`)
        A term node.

    `state` (:class:`AssemblingState` or ``None``)
        The assembling state to use.  If not set, a new assembling
        state is instantiated.
    """
    # Instantiate a new assembling state if not given one.
    if state is None:
        state = AssemblingState()
    # Realize and apply the `Assemble` adapter; return the generated frame.
    return Assemble.__invoke__(term, state)