trac-gviz / trac-dev / gviz / tracgviz / gvizql.py

   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
#!/usr/bin/env python

# Copyright 2009-2011 Olemis Lang <olemis at gmail.com>
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

r"""Basic features needed to support Google Visualization Query Language
(aka. GVizQL).

Copyright 2009-2011 Olemis Lang <olemis at gmail.com>
Licensed under the Apache License, Version 2.0 
"""
__author__ = 'Olemis Lang'

__all__ = 'prepare_ql_data', 'GVizQLClauseHandler', 'GVizQLParser', \
          'defaultParser'
__metaclass__ = type

from ast import literal_eval
from datetime import datetime
from itertools import islice, izip
import logging
import operator
from pygments.lexer import RegexLexer
from pygments.filter import Filter
from pygments.token import *
from re import compile
from weakref import proxy

from tracgviz.api import DataTable
from tracgviz.util.parsing import OperatorPrecedenceParser,  \
    InvalidParserConfiguration

#------------------------------------------------------
#   GVizQL clause handlers 
#------------------------------------------------------

class GVizQLClauseType(type):
  r"""Keep track of all GVizQL clause handlers installed in the 
  system, syntax order ...

  >>> ','.join(ct.get_props('keyw') for ct in GVizQLClauseType.iterparse())
  'select,from,where,group by,pivot,order by,limit,offset,label,format,options'

  ... as well as evaluation order.

  >>> ','.join(ct.get_props('keyw') for ct in GVizQLClauseType.itereval())
  'from,group by,pivot,where,order by,offset,limit,select,format,options,label'
  """
  CLAUSE_CACHE = dict()
  SYNTAX_ORDER = list()
  EVAL_ORDER = list()
  PROPS = ('idx_syntax', 'idx_eval', 'keyw')

  def __new__(cls, name, bases, suite):
    r"""Keep track of all GVizQL clause handlers installed in the 
    system, as well as evaluation order.
    """
    try:
      abstract = suite['__abstract__']
      del suite['__abstract__']
    except KeyError:
      abstract = False

    @classmethod
    def get_props(cls, propnm):
      try:
        return self._PROPS[propnm]
      except KeyError, exc:
        raise ValueError('Unsupported property %s', exc.message)
    suite['get_props'] = get_props

    self = super(GVizQLClauseType, cls).__new__(cls, name, bases, suite)
    if not abstract:
      cnm = self.get_props('keyw')
      GVizQLClauseType.CLAUSE_CACHE[cnm] = self
      GVizQLClauseType.SYNTAX_ORDER.append(self)
      GVizQLClauseType.SYNTAX_ORDER.sort(None, \
                                    lambda x: x.get_props('idx_syntax'))
      GVizQLClauseType.EVAL_ORDER.append(self)
      GVizQLClauseType.EVAL_ORDER.sort(None, \
                                    lambda x: x.get_props('idx_eval'))
    return self

  @staticmethod
  def itereval():
    r"""Iterate over GVizQL clause handlers following evaluation order.
    """
    return iter(GVizQLClauseType.EVAL_ORDER)

  @staticmethod
  def iterparse():
    r"""Iterate over GVizQL clause handlers following syntax order.
    """
    return iter(GVizQLClauseType.SYNTAX_ORDER)

  @staticmethod
  def clauses():
    r"""Retrieved all the keywords identifying different clauses 
    supported in the system.
    """
    return GVizQLClauseType.CLAUSE_CACHE.keys()

class GVizQLClauseHandler:
  r"""Objects used to define syntax and retrieve items inside a 
  clause. It's also responsible of performing the transformations 
  dictated by this clause on a data set.

  Instances of this class have to override the following fields:
    - `_PROPS` :      a static dictionary containing the following keys
      * `idx_eval`      a number indicating the relative order of 
                        this clause at evaluation time.
      * `idx_syntax`    a number indicating the relative syntantic 
                        order of this clause.
      * `keyw`          the keyword introducing (i.e. identifying) 
                        this clause.
    - `transform` :   override this method in order to apply the 
                      transformations specified by the client  in the 
                      corresponding clause to the input result set.
  """
  __metaclass__ = GVizQLClauseType
  __abstract__ = True

  ERR_MSG = "Unable to evaluate %(clause)s clause. " \
      "Either the whole clause or an specific feature " \
      "is not supported yet."

  def unsupported(self, **vals):
    r"""Indicate that this clause is not supported yet.
    """
    vals['clause'] = self.get_props('keyw').upper()
    msg = self.ERR_MSG % vals
    raise GVizUnsupportedQueryOp(msg)

  def transform(self, schema, data):
    r"""Transform the result set as dictated by the clause included 
    in the GViz QL expression provided by the client. This 
    transformation *SHOULD* be performed by using iterators.

    Note: Default behavior is to indicate that the clause is not 
    supported.
    """
    self.unsupported()

  # Internal methods

  @staticmethod
  def _column_accessor(schema):
    r"""Functor returning a callable providing access to the values in 
    a given row of the result set by column name.
    """
    schcols = dict([col[0], i] for i, col in enumerate(schema))

    def get_col_value(row, colnm):
      try:
        return row[schcols[colnm]]
      except KeyError:
        raise GVizRuntimeError("Unknown column " + colnm + ".")

    return get_col_value

  @staticmethod
  def _schema_accessor(schema):
    r"""Functor returning a callable providing access to columns schema 
    by column name.
    """
    schcols = dict([col[0], i] for i, col in enumerate(schema))

    def get_col_schema(colnm):
      try:
        return schema[schcols[colnm]]
      except KeyError:
        raise GVizRuntimeError("Unknown column " + colnm + ".")

    return get_col_schema

  @staticmethod
  def _resolve_schema(expr, get_col_schema):
    r"""Determine the new schema obtained after transforming base result set
    by appying an arithmetic or boolean expression.
    """
    return expr['schema'](get_col_schema) if expr['is_schema_callable'] \
        else expr['schema']

  @staticmethod
  def _eval_expr(row, expr, get_col_value):
    r"""Evaluate an arithmetic or boolean expression against a row
    in the data set. Accessor function might be needed to access row values
    by column name.
    """
    return expr['eval'](row, get_col_value) if expr['is_eval_callable'] \
        else expr['eval']

class GVizSelectClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 0, 'idx_eval': 7, 'keyw' : 'select'}
  KEYWORDS = ('select',)

  def __init__(self, seq):
    r"""Initialize SELECT clause handler with the sequence of expressions
    specified in input GViz QL statement.
    """
    if seq == '*':
      seq = None
    elif not isinstance(seq, Sequence):
      seq = Sequence([seq])
    self.cols_mapping = seq
    logging.debug("Select list %s", seq)
    self.cols = [self._resolve_schema(c, lambda colnm: (colnm, None))[0] 
        for c in self.cols_mapping ] if seq is not None else None

  def transform(self, schema, data):
    r"""Arrange and transform values considering the given expressions list.
    """
    cols = self.cols_mapping
    if not cols:
      return schema, data
    else:
      get_col_value = self._column_accessor(schema)
      get_col_schema = self._schema_accessor(schema)
      new_schema = [self._resolve_schema(c, get_col_schema) \
          for c in self.cols_mapping]
      new_data = ( [self._eval_expr(row, c, get_col_value) \
              for c in self.cols_mapping] for row in data )
      return new_schema, new_data

class GVizFromClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 1, 'idx_eval': 0, 'keyw' : 'from'}
  KEYWORDS = ('from',)

  def __init__(self, name):
    r"""Always fail with deprecation message.

    FROM clause is deprecated and has been removed from the language.
    """
    self.basetable = name['schema'](lambda colnm: (colnm, None))[0]

  def transform(self, schema, data):
    r"""Notify that base table has not been processed by data source. 
    This is made this way since it may hide a bug in the underlying 
    data source implementation.

    FROM clause is deprecated and has been removed from the language.
    """
    raise GVizInvalidQuery("The from clause has been eliminated" \
        " from the language.")

class GVizWhereClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 2, 'idx_eval': 3, 'keyw' : 'where'}
  KEYWORDS = ('where',)

  def __init__(self, expr):
    r"""Initialize clause instance with a boolean expression evaluated
    in order to filter rows in the result set.
    """
    if expr['is_schema_callable'] or expr['schema'][1] != 'boolean':
      raise GVizInvalidQuery("Syntax error: Boolean expression expected " \
          "in where clause." + 
          (" Got %s" % (expr['schema'][1])) if not expr['is_schema_callable']
              else '')
    self.expr = expr
    self.filter = self._resolve_schema(expr, lambda colnm: (colnm, None))[0]

  def transform(self, schema, data):
    r"""Filter rows that do not satisfy target predicate.
    """
    get_col_value = self._column_accessor(schema)
    new_data = ( row for row in data \
        if bool(self._eval_expr(row, self.expr, get_col_value)) )
    return (schema, new_data)

class GVizGroupByClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 3, 'idx_eval': 1, 'keyw' : 'group by'}
  KEYWORDS = ('group', 'by')

  def __init__(self, seq):
    r"""Initialize this clause with a sequence of expressions specifying
    how to group multiple rows in the base data set.
    """
    if not isinstance(seq, Sequence):
      seq = Sequence([seq])
    self.groups_def = seq
    self.aggregate = [self._resolve_schema(c, lambda colnm: (colnm, None))[0] 
        for c in self.groups_def ]

  def transform(self, schema, data):
    r"""Create groups.
    """
    self.unsupported()

class GVizPivotClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 4, 'idx_eval': 2, 'keyw' : 'pivot'}
  KEYWORDS = ('pivot',)

  def __init__(self, seq):
    r"""Initialize this clause with the expressions transforming values into
    new columns.
    """
    if not isinstance(seq, Sequence):
      seq = Sequence([seq])
    self.pivot_def = seq
    self.pivot = [self._resolve_schema(c, lambda colnm: (colnm, None))[0] 
        for c in self.pivot_def ]

  def transform(self, schema, data):
    r"""Create new columns from data.
    """
    self.unsupported()

class GVizOrderByClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 5, 'idx_eval': 4, 'keyw' : 'order by'}
  KEYWORDS = ['asc', 'desc', 'order', 'by']

  def __init__(self, seq):
    r"""Initialize this clause with expressions used to sort base result set.
    """
    if isinstance(seq, tuple):
      seq = Sequence([seq])
    elif isinstance(seq, dict):
      seq = Sequence([(seq, True)])
    self.order_def = [c if isinstance(c, tuple) else (c, True) for c in seq]
    self.sort = [(self._resolve_schema(c, lambda colnm: (colnm, None))[0], is_asc) 
        for c, is_asc in self.order_def ]

  def transform(self, schema, data):
    r"""Sort rows in base result set by evaluating target expressions.
    """
    self.unsupported()

class GVizLimitClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 6, 'idx_eval': 6, 'keyw' : 'limit'}
  KEYWORDS = ('limit',)

  def __init__(self, number):
    r"""Initialize this clause with an integet value
    """
    self.cnt = number

  def transform(self, schema, data):
    r"""Retrieve no more than `cnt` items.
    """
    return schema, islice(data, self.cnt)

class GVizOffsetClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 7, 'idx_eval': 5, 'keyw' : 'offset'}
  KEYWORDS = ('offset',)

  def __init__(self, number):
    r"""Initialize this clause with an integet value
    """
    self.skip = number

  def transform(self, schema, data):
    r"""Skip the number of items determined by `skip` attribute.
    """
    return schema, islice(data, self.skip, None)

class GVizLabelClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 8, 'idx_eval': 10, 'keyw' : 'label'}
  KEYWORDS = ('label',)

  def __init__(self, seq):
    r"""Initialize this clause with a sequence of formatting expressions
    """
    if not isinstance(seq, Sequence):
      seq = Sequence([seq])
    self.labels = seq

  def transform(self, schema, data):
    r"""(Add | modify) the schema in order to (include | update) 
    column labels.

    Note: The process is not aborted if a label for a missing column 
          is specified.
    """
    labels = dict(self.labels)
    new_schema = [col[0] in labels and col[:2] + (labels[col[0]],) or col \
                    for col in schema]
    return new_schema, data

class GVizFormatClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 9, 'idx_eval': 8, 'keyw' : 'format'}
  KEYWORDS = ('format',)

  def __init__(self, seq):
    r"""Initialize this clause with a sequence of formatting expressions
    """
    if not isinstance(seq, Sequence):
      seq = Sequence([seq])
    self.fmt = seq

  def transform(self, schema, data):
    r"""Annotate result set with formatted values.
    """
    self.unsupported()

class GVizOptionsClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 10, 'idx_eval': 9, 'keyw' : 'options'}
  KEYWORDS = ('options',)

  def __init__(self, seq):
    r"""Initialize this clause with a list of option names.
    """
    if not isinstance(seq, Sequence):
      get_col_schema = lambda _colnm: (_colnm, None)
      seq = seq['schema'](get_col_schema)[0]
      seq = Sequence([seq])
    self.opts = seq

  def transform(self, schema, data):
    r"""Condition the result set according to options.
    """
    self.unsupported()

#------------------------------------------------------
#   GVizQL parsing and compilation
#------------------------------------------------------

class GVizQLParser(RegexLexer):
  r"""Objects used to parse GVizQL expressions. 
  """
  GVIZ_QL_KEYWS = [k for ct in GVizQLClauseType.iterparse() \
                        for k in ct.KEYWORDS]
  GVIZ_QL_OPS = 'and,or,is,not,contains,starts with,ends with,matches,' \
        'like'.split(',')
  GVIZ_QL_FUNCS = 'max min count avg sum'.split()
  GVIZ_QL_CPREF = 'date datetime timeofday timestamp'.split()
  GVIZ_QL_CONST = 'true false null'.split()
  GVIZ_QL_TOKENS = {                # Keywords generated in update_syntax
                                    # Identifiers generated in update_syntax
        'int' : '(?:\d+)',          # Integer numbers
        'str' : r"""(?:(?:\'[^']*\')|(?:\"[^"]*\"))""", # Strings
        'number' : '(?:+|-)\d*(?:\.\d+)?',              # Numbers
        'bool' : '(?:true|false)',  # Boolean constants
        'date' : '(?:true|false)',
      }
  tokens = {
        'root' : [
            (r'[(,)]', Punctuation),
            (r'(?:<=)|(?:>=)|(?:!=)|(?:<>)', Operator),
            (r'[-+*/<>=]', Operator),
            (r'(?=date\s)', Whitespace, 'date'),
            (r'(?=timeofday\s)', Whitespace, 'tod'),
            (r'(?=(?:datetime|timestamp)\s)', Whitespace, 'dt'),
            (r'`(?:\w|\s)+`', Name.Variable),
            (r'`.*`', Generic.Error),
            (r'`[^`]*(?=$)', Generic.Error),
            (r'\d*\.\d+(?=[^a-zA-Z_])', Number),
            (r'\d+(?=[^a-zA-Z_])', Number.Integer),
            (r'(?:\d*\.)?\d+(?:[a-zA-Z_]\w*)', Generic.Error),
            (r'(?=\w)', Whitespace, 'alpha'),
            (r'(?:\d+)(?=[.a-zA-Z_])', Generic.Error),
            (r"\'[^']*\'", String.Single),
            (r'\"[^"]*\"', String.Double),
            (r"\'[^']*(?=$)", Generic.Error),
            (r'\"[^"]*(?=$)', Generic.Error),
            (r'\s+', Whitespace),
            (r'.', Generic.Error),
          ],
        'date' : [
            (r"date\s+\'\d{4}-\d{1,2}-\d{1,2}\'", Literal.Date, '#pop'),
            (r'date\s+\"\d{4}-\d{1,2}-\d{1,2}\"', Literal.Date, '#pop'),
            (r"date\s+", Generic.Error, '#pop')
          ],
        'tod' : [
            (r"timeofday\s+\'\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{1-3})?\'", \
                Literal.Date, '#pop'),
            (r'timeofday\s+\"\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{1-3})?\"', \
                Literal.Date, '#pop'),
            (r"timeofday\s+", Generic.Error, '#pop')
          ],
        'dt' : [
            (r'(?:datetime|timestamp)\s+\"\d{4}-\d{1,2}-\d{1,2}\ ' \
             r'\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{3})?\"', \
                Literal.Date, '#pop'),
            (r"(?:datetime|timestamp)\s+\'\d{4}-\d{1,2}-\d{1,2}\ " \
             r"\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{3})?\'", \
                Literal.Date, '#pop'),
            (r"(?:datetime|timestamp)\s+", Generic.Error, '#pop')
          ],
        'alpha' : [
            (r'(?:%s)(?=\s|$)' % '|'.join(GVIZ_QL_CONST), \
                Keyword.Constant, '#pop'),
            (r'(?:(?:%s)|(?:is\ not))(?=\s)' % '|'.join(GVIZ_QL_OPS), \
                Operator.Word, '#pop'),
            ('(?:%s)(?=\W)' % '|'.join(GVizQLClauseType.clauses()), \
                Keyword.Reserved, '#pop'), 
            ('(?:%s)(?=\W)' % '|'.join(GVIZ_QL_KEYWS), 
                Keyword, '#pop'), 
            ('(?:%s)(?=\W)' % '|'.join(GVIZ_QL_FUNCS), 
                Name.Builtin, '#pop'), 
            (r'[a-zA-Z]\w*(?=\()', Name.Function, '#pop'),
            (r'[a-zA-Z]\w*', Name.Variable, '#pop'),
          ],
      }

  from tracgviz.grammar import GVIZ_GRAMMAR_PRECEDENCE, GVIZ_QL_START_STATE, \
      GVIZ_GRAMMAR_PRODUCTIONS

  def __init__(self, *args, **kwds):
    super(GVizQLParser, self).__init__(*args, **kwds)
    self.noisy = True
    self.parser = OperatorPrecedenceParser()
    self.parser.start_state = self.GVIZ_QL_START_STATE
    self.parser.precedence = self.GVIZ_GRAMMAR_PRECEDENCE
    self.parser.productions_tree = self.GVIZ_GRAMMAR_PRODUCTIONS

  def parse(self, tq):
    r"""Parse a GVizQL expression.

    @param tq                       the GViz QL expression.
    @return                         an instance of GVizQLExpression 
    @throw GVizInvalidQuery         if a syntax error or other error 
                                    is detected in the input string.
    @throw GVizUnsupportedQueryOp   if the GViz QL query expression 
                                    contains a clause or feature 
                                    that's not supported yet.
    """
    tkns = iter(self.get_tokens(tq))

    builder = GVizQLExpressionBuilder(self.parser)
    try:
      result = self.parser.parse(tkns, on_reduce=builder.dispatch, \
          on_accept=builder.handle_gvizql)
    except SyntaxError, exc:
      raise GVizInvalidQuery(exc)
    return result

  def get_tokens(self, tq):
    try:
      self._ctx = ctx = GVizQLParsingContext()
      self.filters.append(ctx)
      strm = super(GVizQLParser, self).get_tokens(tq)
      ctx.stream = strm
      ctx.parser = self
      for x in strm:
        yield x
    finally:
      self.filters = []
      self._ctx = None

class GVizQLParsingContext():
  r"""Used to store global information generated at parsing time. 
  The parser adds the following fields to this object:

    - stream : The token stream being processed.
    - parser : The object that's actually parsing the GViz QL expression.
  """
  def __init__(self):
    for attr in 'parser stream'.split():
      setattr(self, attr, None)
    self._last = (None, None)

  OPERATOR_OVERRIDES = {
      '*' : Operator.Arithmetic,
      '+' : Operator.Arithmetic,
      '-' : Operator.Arithmetic,
      '/' : Operator.Arithmetic,
      '<=' : Operator.Comparison,
      '<' : Operator.Comparison,
      '>' : Operator.Comparison,
      '>=' : Operator.Comparison,
      '=' : Operator.Comparison,
      '!=' : Operator.Comparison,
      '<>' : Operator.Comparison,
      'is' : Operator.Word.Comparison,
      'is not' : Operator.Word.Comparison,
      'and' : Operator.Word.Boolean,
      'or' : Operator.Word.Boolean,
      'not' : Operator.Word.Boolean,
      'contains' : Operator.Word.Comparison,
      'starts with' : Operator.Word.Comparison,
      'ends with' : Operator.Word.Comparison,
      'matches' : Operator.Word.Comparison,
      'like' : Operator.Word.Comparison,
    }

  def filter(self, p, stream):
    r""" Store lookahead token.
    """
    self.parser = p
    self._last = (None, None)
    for t in stream:
      if t[0] is Generic.Error :
        if p.noisy :
          raise GVizInvalidQuery("Invalid token %s " % t[1:])
      elif t[0] is not Whitespace:

        # Artificial whitespace between SQL clauses
        if t[0] in Keyword.Reserved and self._last != (None, None):
          yield (Whitespace, ' ')

        if self._last == (Keyword.Reserved, 'select') and \
            t == (Operator, '*'):
          t = Name.Other, '*'
        elif t[0] is Name.Variable and t[1] in GVizQLParser.GVIZ_QL_CONST:
          # FIXME: Constants are sometimes matched as variables . Bizarre !
          t = (Keyword.Constant, t[1])
        elif t[0] in Operator and t[1] in self.OPERATOR_OVERRIDES:
          t = (self.OPERATOR_OVERRIDES[t[1]], t[1])
      elif t[1].endswith('\n'):
        t = (Whitespace, '\n')
      else:
        continue
      self._last = t
      yield t

  @property
  def last_token():
    return self._last

class GVizQLExpression:
  r"""Compiled GVizQL expression.
  """
  def __init__(self):
    r"""Initialize a compiled GVizQL expression.
    """
    self._handlers = dict()
    self._attrmap = dict()

  def _add_handler(self, ch):
    r"""Add a clause handler to this expression object. Bind the 
    handler's attributes to lazy arguments.
    """
    clause_nm = ch.__class__.get_props('keyw')
    self._handlers[clause_nm] = ch
    for attrnm in ch.__dict__ :
      self._attrmap[attrnm] = clause_nm

  def __getattr__(self, attrnm):
    try:
      return getattr(self._handlers[self._attrmap[attrnm]], attrnm)
    except :
      raise AttributeError("'%s' object has no attribute '%s'" % \
                                (self.__class__.__name__, attrnm))

  def itereval(self):
    r"""Iterate over the clause handlers present in this expression 
    following evaluation precedence.
    """
    for ct in GVizQLClauseType.itereval():
      ch = self._handlers.get(ct.get_props('keyw'))
      if ch is not None :
        yield ch

  def transform(self, schema, data):
    r"""Transform the result set as determined by the GVizQL 
    expression directives and clauses.
    """
    for ch in self.itereval():
      schema, data = ch.transform(schema, data)
    return schema, data

#------------------------------------------------------
#   Helper functions
#------------------------------------------------------

def prepare_ql_data(provider, tq, req, **params):
  r"""Prepare the data and schema to be supplied to an instance of 
  gviz_api.DataTable as determined by a GVizQL expression. This is 
  accomplished by wrapping the original data with multiple iterators.

  @param provider   an instance of `IGVizDataProvider` interface 
                    responsible for providing the base result set 
                    (i.e. primary information) subsequently modified 
                    by the application of the GVizQL expression.
  @param tq         the GVizQL expression.
  @param req        an object encapsulating the HTTP request/response 
                    pair.
  @param params     further parameters supported by `provider`.
  @return           a binary tuple. The first item is the schema 
                    describing the column names, data types, and 
                    labels, as well as data structures from where 
                    data will be retrieved. The second is the actual 
                    data resulting from the application of the query 
                    (quite often in the form of iterators).
  """
  sch = provider.get_data_schema.im_func.func_code
  sch_args = (sch.co_argcount > 1) and (req,) or ()
  if not tq:
    sch = provider.get_data_schema(*sch_args)
    data = provider.get_data(req, None, **params)
    return (sch, data)
  else:
    tq = GVizQLParser().parse(tq)
    sch = provider.get_data_schema(*sch_args)
    data = provider.get_data(req, tq, **params)
    table = DataTable(sch)
    # FIXME : Optimize memory
    table.LoadData(data)
    sch = [(col['id'], col['type']) + \
        ( (col['label'],) if col.get('label') else () ) \
        for col in table.columns]
    data_seq = ( tuple(row.get(col['id']) for col in table.columns) \
        for row in table._PreparedData() )
        
    return tq.transform(sch, data_seq)

class Sequence(list):
  pass

class GVizQLExpressionBuilder:
  r"""Stub class responsible for handling parser callback invocations 
  in order to build instances of `GVizQLExpression`.
  """
  def __init__(self, parser, scalar_funcs=None, agg_funcs=None):
    self.parser = parser
    if scalar_funcs is None:
      scalar_funcs = self._default_scalar_funcs()
    if agg_funcs is None:
      agg_funcs = self._default_aggregate_funcs()
    self.scalar_funcs = scalar_funcs
    self.agg_funcs = agg_funcs
    self.now = None

  @classmethod
  def _default_scalar_funcs(cls):
    from tracgviz import scalar
    return dict([nm, getattr(scalar, nm)] for nm in scalar.__all__)

  @classmethod
  def _default_aggregate_funcs(cls):
    from tracgviz import aggregate
    return dict([nm, getattr(aggregate, nm)] for nm in aggregate.__all__)

  def dispatch(self, prod_id, *args):
    try:
      handler = getattr(self, 'handle_' + prod_id)
    except AttributeError:
      raise InvalidParserConfiguration(self.parser, 
          'Unknown production ' + prod_id)
    else:
      result = handler(*args)
      if isinstance(result, dict):
        result['production'] = prod_id
      return result

  # Special markers 

  Sequence = Sequence

  @property
  def SyntaxError(self):
    return GVizInvalidQuery

  # Grammar production handlers

  def handle_number(self, value):
    if value[0] in Number.Integer:
      _value = int(value[1])
    else:
      _value = float(value[1])
    return dict(
        eval=_value, 
        schema=(value[1], 'number'), 
        is_eval_callable=False,
        is_schema_callable=False
      )

  def handle_var(self, name):
    colnm = name[1]
    if colnm.startswith('`'):
      colnm = colnm[1:-1]
    return dict(
        eval=lambda row, getvalue: getvalue(row, colnm) , 
        schema=lambda get_col_schema: get_col_schema(colnm),
        is_eval_callable=True,
        is_schema_callable=True)

  def handle_str(self, value):
    return dict(
        eval=literal_eval(value[1]), 
        schema=(value[1], 'string'),
        is_eval_callable=False,
        is_schema_callable=False)

  def handle_date(self, value):
    try:
      kind, _value = value[1].split()
      _value = literal_eval(_value)
      f, fmtstr = {
          'date' : (datetime.date, '%Y-%m-%d'),
          'timeofday' : (datetime.time, '%H:%M:%S'),
          'datetime' : (lambda x: x, '%Y-%m-%d %H:%M:%S'),
        }.get(kind)
      if not kind:
        raise self.SyntaxError('Invalid date literal %s' % value[1])
      _value = datetime.strptime(_value, fmtstr)
    except ValueError:
      raise self.SyntaxError('Invalid date literal %s' % value[1])
    return dict(
        eval=f(_value), 
        schema=(value[1], kind), 
        is_eval_callable=False,
        is_schema_callable=False)

  def handle_const(self, value):
    try:
      _value = {
          'true' : True,
          'false' : False,
          'null' : None
        }.get(value[1])
    except KeyError:
      raise self.SyntaxError('Unexpected constant %s' % (value[1],))
    return dict(
        eval=_value, 
        schema=(value[1], 'boolean' if value[1] != 'null' else None), 
        is_eval_callable=False,
        is_schema_callable=False
      )

  def handle_seq(self, seq, _, expr):
    _seq = seq[1]
    _expr = expr[1]
    if isinstance(_seq, self.Sequence):
      _seq.append(_expr)
    else:
      _seq = self.Sequence([_seq, _expr])
    return _seq

  def _unsupported(self, *args):
    raise NotImplementedError('Feature not supported ... yet')

  def handle_bfunc(self, funcnm, _, colnm, __):
    funcnm = funcnm[1]
    colnm = colnm[1]
    col_schema = colnm['schema'](lambda colnm: (colnm, None) )
    try:
      f = self.agg_funcs[funcnm]
    except KeyError:
      raise LookupError('Unknown aggregation function %s' % (funcnm,))
    return_type = getattr(f, 'return_type', None)
    func_label = '%s(%s)' % (funcnm, col_schema[0])
    return dict(
        eval=self._unsupported, 
        schema=(func_label, return_type) if return_type else 
            lambda get_col_schema: (func_label, get_col_schema(col_schema[0])[1]),
        is_eval_callable=True,
        is_schema_callable=not bool(return_type)
      )

  def handle_func(self, funcnm, _, __):
    funcnm = funcnm[1]
    try:
      f = self.scalar_funcs[funcnm]
      return_type = r.return_type
    except KeyError:
      raise LookupError('Unknown scalar function %s' % (funcnm,))
    except AttributeError:
      raise GVizRuntimeError('Unknown return tyoe for scalar function %s' % \
          funcnm)
    if funcnm == 'now':
      # Unique time measurement
      if self.now is None:
        self.now = f()
      return dict(
          eval=self.now, 
          schema=('now()', return_type), 
          is_eval_callable=False,
          is_schema_callable=False
        )
    else:
      return dict(
          eval=lambda *args: f(), 
          schema=('%s()' % (funcnm,), return_type),
          is_eval_callable=True,
          is_schema_callable=False
        )

  def handle_funcargs(self, funcnm, _, seq, __):
    funcnm = funcnm[1]
    seq = seq[1]
    if not isinstance(seq, self.Sequence):
      seq = self.Sequence([seq])
    try:
      f = self.scalar_funcs[funcnm]
      return_type = f.return_type
    except KeyError:
      raise LookupError('Unknown scalar function %s' % (funcnm,))
    except AttributeError:
      raise GVizRuntimeError('Unknown return tyoe for scalar function %s' % \
          funcnm)

    # GViz QL scalar functions (except `now`) are deterministic however ...
    is_eval_callable, eval_func = self._eval_expr(f, seq, 
        getattr(f, 'deterministic', True))
    return dict(
        eval=eval_func, 
        schema=(self._function_label(funcnm, seq), return_type),
        is_eval_callable=is_eval_callable,
        is_schema_callable=False
      )

  def handle_par(self, _, expr, __):
    expr = expr[1]
    expr_schema = expr['schema']

    def par_expr_schema(get_col_schema):
      label, return_type = expr_schema(get_col_schema)
      return '(%s)' % (label,) , return_type

    return dict(
        eval=expr['eval'],
        schema=('(%s)' % expr_schema[0], expr_schema[1]) \
            if not expr['is_schema_callable'] else par_expr_schema,
        is_eval_callable=expr['is_eval_callable'],
        is_schema_callable=expr['is_schema_callable']
      )

  handle_boolpar = handle_par

  def _handle_binary_op(self, lexpr, op, rexpr):
    op = op[1]
    lexpr = lexpr[1]
    rexpr = rexpr[1]

    f = {
        '+' : 'add', '-' : 'sub', '*' : 'mul', # '/' : 'div',
        'and' : 'and_', 'or' : 'or_',
        '<=' : 'le', '<' : 'lt', '>' : 'gt', '>=' : 'ge', 
        '=' : 'eq', '!=' : 'ne', '<>' : 'ne', 
        'is' : 'is_', 'is not' : 'is_not', 
        'contains' : 'contains',
      }.get(op)
    if f is not None:
      _f = getattr(operator, f)
      if op in '+-*/':
        f = lambda a,b: None if a is None or b is None else _f(a,b)
      else:
        f = _f
    else:
      from re import match
      from fnmatch import fnmatch

      def div(a, b):
        if a is None or b is None:
          return None
        try:
          return operator.div(float(a), b)
        except ZeroDivisionError:
          return None

      def match_like(a, b):
        if a is None or b is None:
          return None
        pattern = b.replace('*', '[*]').replace('?', '[?]') \
            .replace('%', '*').replace('_', '?')
        return fnmatch(a, pattern)

      f = {
          '/' : div, 
          'starts with' : lambda a, b : a.startswith(b),
          'ends with' : lambda a, b : a.endswith(b),
          'matches' : lambda a, b: bool(match('^%s$' % (b,), a)),
          'like' : match_like,
        }.get(op)

      if f is None:
        raise self.SyntaxError('Unknown operator ' + op)

    is_eval_callable, eval_func = self._eval_expr(f, [lexpr, rexpr])
    return_type = 'number' if op in '-+*/' else 'boolean'
    if lexpr['is_schema_callable']:
      lschema = lexpr['schema'](lambda colnm : (colnm, None))
    else:
      lschema = lexpr['schema']
    if rexpr['is_schema_callable']:
      rschema = rexpr['schema'](lambda colnm : (colnm, None))
    else:
      rschema = rexpr['schema']
    return dict(
        eval=eval_func,
        schema=('%s %s %s' % (lschema[0], op, rschema[0]), return_type),
        is_eval_callable=is_eval_callable,
        is_schema_callable=False
      )

  handle_sum = handle_sub = handle_mult = handle_div = handle_strcmp = \
      handle_cmp = handle_orexp = handle_boolexp = _handle_binary_op

  def handle_not(self, _, expr):
    expr = expr[1]
    not_label='not ' + expr['label']
    if expr.get('is_eval_callable'):
      f = expr['eval']
      return dict(
          eval=lambda *args: not bool(f(*args)), 
          label=(not_label, 'boolean'), 
          is_eval_callable=True,
          is_schema_callable=False
        )
    else:
      return dict(
          eval=not bool(f), 
          schema=(not_label, 'boolean'), 
          is_eval_callable=False,
          is_schema_callable=False)

  def _handle_explicit_order(self, expr, direction):
    return (expr[1], direction[1] == 'asc')

  handle_orderasc = handle_orderdsc = _handle_explicit_order

  # FIXME: This method never gets called
  def handle_orderseq(self, orderdef, _, neworder):
    orderdef = orderdef[1]
    neworder = neworder[1]
    if not isinstance(neworder, tuple):
      # Default order = asc
      neworder = (neworder, True)
    if isinstance(orderdef, self.Sequence):
      orderdef.append(neworder)
      logging.debug('Appending sort expressions %s | %s', orderdef, neworder)
    else:
      if not isinstance(orderdef, tuple):
        # Default order = asc
        orderdef = (orderdef, True)
      logging.debug('Merging sort expressions %s | %s', orderdef, neworder)
      orderdef = self.Sequence([orderdef, neworder])
    return orderdef

  def handle_lblexpr(self, colnm, label):
    return (colnm[1], literal_eval(label[1]))

  def handle_lblseq(self, labels, _, label_expr):
    labels = labels[1]
    label_expr = label_expr[1]
    if isinstance(labels, self.Sequence):
      labels.append(label_expr)
    else:
      labels = self.Sequence([labels, label_expr])
    return labels

  def handle_column(self, colnm):
    return colnm[1]['schema'](lambda _colnm: (_colnm, None))[0]

  def handle_colseq(self, colseq, _, colnm):
    colseq = colseq[1]
    colnm = colnm[1]
    get_col_schema = lambda _colnm: (_colnm, None)
    if isinstance(colseq, self.Sequence):
      colnm = colnm['schema'](get_col_schema)[0]
      colseq.append(colnm)
    else:
      colseq = colseq['schema'](get_col_schema)[0]
      colnm = colnm['schema'](get_col_schema)[0]
      colseq = self.Sequence([colseq, colnm])
    return colseq

  def _handle_number_clause(self, keyword, number):
    keyword = keyword[1]
    try:
      if number[0] not in Number.Integer:
        raise ValueError()
      number = int(number[1])
    except ValueError:
      raise self.SyntaxError('Integer number expected in clause %s . Got %s' %
          (keyword, number[1]) )
    clause_type = GVizQLClauseType.CLAUSE_CACHE[keyword]
    ch = clause_type(number)
    return ch

  handle_limit = handle_offset = _handle_number_clause

  def _handle_complex_clause(self, keyword, body):
    keyword = keyword[1]
    clause_type = GVizQLClauseType.CLAUSE_CACHE[keyword]
    ch = clause_type(body[1])
    return ch

  handle_select = handle_selall = handle_where = handle_groupby = \
      handle_pivot = handle_orderby = handle_label = handle_format = \
      handle_options = handle_from = _handle_complex_clause

  def handle_body(self, expr_or_clause, _=None, newclause=None):
    if isinstance(expr_or_clause, tuple):
      expr_or_clause = expr_or_clause[1]
    if isinstance(expr_or_clause, GVizQLExpression) :
      gviz_expr = expr_or_clause 
    else:
      gviz_expr = GVizQLExpression()
      gviz_expr._add_handler(expr_or_clause)
    if newclause is not None:
      gviz_expr._add_handler(newclause[1])
    return gviz_expr

  handle_gvizql = handle_body

  # Internal methods

  def _function_label(self, funcnm, seq):
    return '%s(%s)' % (funcnm, 
        ', '.join(x['schema'][0] if not x['is_schema_callable'] \
            else x['schema'](lambda colnm: (colnm, None))[0] \
            for x in seq))

  def _eval_expr(self, f, seq, deterministic=True):
    r"""Functor computing evaluation function for a compound statement.

    : param f :       function or callable transforming values in
                      sub-statements values according to the particular
                      semantics of the target non-terminal state
                      e.g. `sum` for production E -> E + T
    : param seq :     a sequence of dictionaries containing the definition of
                      the values and transformations to evaluate 
                      sub-expressions.
    : param deterministic : a boolean flag indicating whether f is 
                      deterministic (i.e. will always output the same result
                      for the same inputs) e.g. `sum` is deterministic
                      whereas `datetime.datetime.now` and `random.random` 
                      are not.
    : return :        a binary tuple of the form `(is_eval_callable, value)`
                      where `is_eval_callable` indicates whether `value`
                      is a constant result (e.g. like in `upper('foo')` )
                      or a callable object.
    """
    expand = set(i for i, x in enumerate(seq) if x.get('is_eval_callable'))
    values = [x['eval'] for x in seq]
    if not expand:
      if deterministic:
        # A constant or a function applied to a constant e.g. upper("foo")
        # ... so it becomes a constant as well ;)
        return False, f(*values)
      else:
        return True, lambda *args: f(*values)
    else:
      return True, lambda *args: f(*[v(*args) if i in expand else v \
              for i,v in enumerate(values)]),

#------------------------------------------------------
#   Global Testing
#------------------------------------------------------

from testing.test_gvizql import __test__, TEST_DATA_GVIZSCHEMA, \
                            TEST_DATA_GVIZDATA
def test_suite():
  from doctest import ELLIPSIS, NORMALIZE_WHITESPACE, REPORT_UDIFF
  from unittest import defaultTestLoader
  from string import whitespace
  import sys

  from tracgviz.api import GVizInvalidQuery
  from tracgviz.testing.dutest import MultiTestLoader, DocTestLoader

  logging.basicConfig(level=logging.DEBUG, filename='./.test.log', filemode='wb')

  def parse(expr, *attrs, **kwds):
    # Test lexical analysis
    print "*****\n* Tokens\n*****"
    newline = False
    p = GVizQLParser()
    p.noisy = False
    for tkn, val in p.get_tokens(expr):
      if tkn is not Whitespace:
        if newline:
          print
        else:
          newline = True
        print tkn, val,
    if not (tkn is Whitespace and val == '\n'):  # Check for EOL token.
      raise AssertionError('Expected : %s , %r \n\nGot : %s , %r' % \
                                  (Whitespace, u'\n', tkn, val))
    if attrs :
      # Test parsing and compilation
      print
      print "*****\n* Parsing\n*****",
      from api import GVizUnsupportedQueryOp
      try:
        expr = p.parse(expr)
      except GVizUnsupportedQueryOp :
        print '\nNotSupported  :(',
      except (GVizInvalidQuery, GVizRuntimeError), exc :
        print 
        print unicode(exc)
      else:
        for attrnm in attrs :
          print
          print getattr(expr, attrnm),
        # Test evaluation and transformations on result sets
        print
        print "*****\n* Result\n*****",
        try:
          schema, data = expr.transform(TEST_DATA_GVIZSCHEMA, \
                                        TEST_DATA_GVIZDATA)
        except Exception, exc:
          print
          print exc.__class__.__name__, ' : ', unicode(exc),
        else:
          print
          print "= Columns =",
          if isinstance(schema, dict):
            def iter_schema():
              return ((k,) + v for k, v in schema.iteritems())
          else:
            iter_schema = lambda : schema
          for col in iter_schema() :
            print
            print col[0], col[1],
            try :
              print col[2],
            except IndexError :
              pass
          print 
          try:
            for row in data :
              print "= Row ="
              for val, col in izip(row, iter_schema()):
                print '  ', col[0], '=', val
          except (GVizInvalidQuery, GVizRuntimeError, NotImplementedError), exc:
            print 
            print exc.__class__.__name__, ' : ', unicode(exc)
            

  l = MultiTestLoader([defaultTestLoader, \
                        DocTestLoader(
                            extraglobs=dict(parse=parse),
                            optionflags=ELLIPSIS \
                                        | NORMALIZE_WHITESPACE \
                                        | REPORT_UDIFF \
                          )])
  return l.loadTestsFromModule(sys.modules[__name__])

# Imports introducing circular reference with tracgviz.api

from tracgviz.api import GVizUnsupportedQueryOp, GVizInvalidQuery, \
    GVizRuntimeError
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.