This file is indexed.

/usr/lib/python2.7/dist-packages/z3printer.py is in python-z3 4.4.1-0.3build4.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
############################################
# Copyright (c) 2012 Microsoft Corporation
# 
# Z3 Python interface
#
# Author: Leonardo de Moura (leonardo)
############################################
import sys, io, z3
from z3consts import *
from z3core import *
from ctypes import *

##############################
#
# Configuration
#
##############################

# Z3 operator names to Z3Py
_z3_op_to_str = {
    Z3_OP_TRUE : 'True', Z3_OP_FALSE : 'False', Z3_OP_EQ : '==', Z3_OP_DISTINCT : 'Distinct', 
    Z3_OP_ITE : 'If', Z3_OP_AND : 'And', Z3_OP_OR : 'Or', Z3_OP_IFF : '==', Z3_OP_XOR : 'Xor',
    Z3_OP_NOT : 'Not', Z3_OP_IMPLIES : 'Implies', Z3_OP_IDIV : '/', Z3_OP_MOD : '%',
    Z3_OP_TO_REAL : 'ToReal', Z3_OP_TO_INT : 'ToInt', Z3_OP_POWER : '**', Z3_OP_IS_INT : 'IsInt', 
    Z3_OP_BADD : '+', Z3_OP_BSUB : '-', Z3_OP_BMUL : '*', Z3_OP_BOR : '|', Z3_OP_BAND : '&',
    Z3_OP_BNOT : '~', Z3_OP_BXOR : '^', Z3_OP_BNEG : '-', Z3_OP_BUDIV : 'UDiv', Z3_OP_BSDIV : '/', Z3_OP_BSMOD : '%',
    Z3_OP_BSREM : 'SRem', Z3_OP_BUREM : 'URem', Z3_OP_EXT_ROTATE_LEFT : 'RotateLeft', Z3_OP_EXT_ROTATE_RIGHT : 'RotateRight',
    Z3_OP_SLEQ : '<=', Z3_OP_SLT : '<', Z3_OP_SGEQ : '>=', Z3_OP_SGT : '>',
    Z3_OP_ULEQ : 'ULE', Z3_OP_ULT : 'ULT', Z3_OP_UGEQ : 'UGE', Z3_OP_UGT : 'UGT',
    Z3_OP_SIGN_EXT : 'SignExt', Z3_OP_ZERO_EXT : 'ZeroExt', Z3_OP_REPEAT : 'RepeatBitVec', 
    Z3_OP_BASHR : '>>', Z3_OP_BSHL : '<<', Z3_OP_BLSHR : 'LShR', 
    Z3_OP_CONCAT : 'Concat', Z3_OP_EXTRACT : 'Extract', Z3_OP_BV2INT : 'BV2Int',
    Z3_OP_ARRAY_MAP : 'Map', Z3_OP_SELECT : 'Select', Z3_OP_STORE : 'Store', 
    Z3_OP_CONST_ARRAY : 'K'
    }

# List of infix operators
_z3_infix = [ 
    Z3_OP_EQ, Z3_OP_IFF, Z3_OP_ADD, Z3_OP_SUB, Z3_OP_MUL, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_POWER,
    Z3_OP_LE, Z3_OP_LT, Z3_OP_GE, Z3_OP_GT, Z3_OP_BADD, Z3_OP_BSUB, Z3_OP_BMUL, Z3_OP_BSDIV, Z3_OP_BSMOD, Z3_OP_BOR, Z3_OP_BAND,
    Z3_OP_BXOR, Z3_OP_BSDIV, Z3_OP_SLEQ, Z3_OP_SLT, Z3_OP_SGEQ, Z3_OP_SGT, Z3_OP_BASHR, Z3_OP_BSHL
    ]

_z3_unary = [ Z3_OP_UMINUS, Z3_OP_BNOT, Z3_OP_BNEG ]

# Precedence
_z3_precedence = {
    Z3_OP_POWER : 0,
    Z3_OP_UMINUS : 1, Z3_OP_BNEG : 1, Z3_OP_BNOT : 1, 
    Z3_OP_MUL : 2, Z3_OP_DIV : 2, Z3_OP_IDIV : 2, Z3_OP_MOD : 2, Z3_OP_BMUL : 2, Z3_OP_BSDIV : 2, Z3_OP_BSMOD : 2,
    Z3_OP_ADD : 3, Z3_OP_SUB : 3, Z3_OP_BADD : 3, Z3_OP_BSUB : 3,    
    Z3_OP_BASHR : 4, Z3_OP_BSHL : 4,
    Z3_OP_BAND : 5,
    Z3_OP_BXOR : 6,
    Z3_OP_BOR : 7,
    Z3_OP_LE : 8, Z3_OP_LT : 8, Z3_OP_GE : 8, Z3_OP_GT : 8, Z3_OP_EQ : 8, Z3_OP_SLEQ : 8, Z3_OP_SLT : 8, Z3_OP_SGEQ : 8, Z3_OP_SGT : 8,
    Z3_OP_IFF : 8,
    
    Z3_OP_FPA_NEG : 1,
    Z3_OP_FPA_MUL : 2, Z3_OP_FPA_DIV : 2, Z3_OP_FPA_REM : 2, Z3_OP_FPA_FMA : 2,
    Z3_OP_FPA_ADD: 3, Z3_OP_FPA_SUB : 3,
    Z3_OP_FPA_LE : 8, Z3_OP_FPA_LT : 8, Z3_OP_FPA_GE : 8, Z3_OP_FPA_GT : 8, Z3_OP_FPA_EQ : 8
    }

# FPA operators 
_z3_op_to_fpa_normal_str = {
    Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RoundNearestTiesToEven()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RoundNearestTiesToAway()',
    Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RoundTowardPositive()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RoundTowardNegative()',
    Z3_OP_FPA_RM_TOWARD_ZERO : 'RoundTowardZero()',
    Z3_OP_FPA_PLUS_INF : '+oo', Z3_OP_FPA_MINUS_INF : '-oo',
    Z3_OP_FPA_NAN : 'NaN', Z3_OP_FPA_PLUS_ZERO : 'PZero', Z3_OP_FPA_MINUS_ZERO : 'NZero',
    Z3_OP_FPA_ADD : 'fpAdd', Z3_OP_FPA_SUB : 'fpSub', Z3_OP_FPA_NEG : 'fpNeg', Z3_OP_FPA_MUL : 'fpMul',
    Z3_OP_FPA_DIV : 'fpDiv', Z3_OP_FPA_REM : 'fpRem', Z3_OP_FPA_ABS : 'fpAbs',
    Z3_OP_FPA_MIN : 'fpMin', Z3_OP_FPA_MAX : 'fpMax',
    Z3_OP_FPA_FMA : 'fpFMA', Z3_OP_FPA_SQRT : 'fpSqrt', Z3_OP_FPA_ROUND_TO_INTEGRAL : 'fpRoundToIntegral',

    Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : 'fpLT', Z3_OP_FPA_GT : 'fpGT', Z3_OP_FPA_LE : 'fpLEQ',
    Z3_OP_FPA_GE : 'fpGEQ',

    Z3_OP_FPA_IS_NAN : 'fpIsNaN', Z3_OP_FPA_IS_INF : 'fpIsInf', Z3_OP_FPA_IS_ZERO : 'fpIsZero',
    Z3_OP_FPA_IS_NORMAL : 'fpIsNormal', Z3_OP_FPA_IS_SUBNORMAL : 'fpIsSubnormal',
    Z3_OP_FPA_IS_NEGATIVE : 'fpIsNegative', Z3_OP_FPA_IS_POSITIVE : 'fpIsPositive',
    
    Z3_OP_FPA_FP : 'fpFP', Z3_OP_FPA_TO_FP : 'fpToFP', Z3_OP_FPA_TO_FP_UNSIGNED: 'fpToFPUnsigned',
    Z3_OP_FPA_TO_UBV : 'fpToUBV', Z3_OP_FPA_TO_SBV : 'fpToSBV', Z3_OP_FPA_TO_REAL: 'fpToReal',
    Z3_OP_FPA_TO_IEEE_BV : 'fpToIEEEBV'
    }

_z3_op_to_fpa_pretty_str = {    
    Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RNE()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RNA()',
    Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RTP()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RTN()',
    Z3_OP_FPA_RM_TOWARD_ZERO : 'RTZ()',
    Z3_OP_FPA_PLUS_INF : '+oo', Z3_OP_FPA_MINUS_INF : '-oo',
    Z3_OP_FPA_NAN : 'NaN', Z3_OP_FPA_PLUS_ZERO : '+0.0', Z3_OP_FPA_MINUS_ZERO : '-0.0',
    
    Z3_OP_FPA_ADD : '+', Z3_OP_FPA_SUB : '-', Z3_OP_FPA_MUL : '*', Z3_OP_FPA_DIV : '/', 
    Z3_OP_FPA_REM : '%', Z3_OP_FPA_NEG : '-',
    
    Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : '<', Z3_OP_FPA_GT : '>', Z3_OP_FPA_LE : '<=', Z3_OP_FPA_GE : '>='
}
    
_z3_fpa_infix = [
    Z3_OP_FPA_ADD, Z3_OP_FPA_SUB, Z3_OP_FPA_MUL, Z3_OP_FPA_DIV, Z3_OP_FPA_REM,
    Z3_OP_FPA_LT, Z3_OP_FPA_GT, Z3_OP_FPA_LE, Z3_OP_FPA_GE
]

def _is_assoc(k):
    return k == Z3_OP_BOR or k == Z3_OP_BXOR or k == Z3_OP_BAND or k == Z3_OP_ADD or k == Z3_OP_BADD or k == Z3_OP_MUL or k == Z3_OP_BMUL

def _is_left_assoc(k):
    return _is_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB

def _is_html_assoc(k):
    return k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IFF or _is_assoc(k)

def _is_html_left_assoc(k):
    return _is_html_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB

def _is_add(k):
    return k == Z3_OP_ADD or k == Z3_OP_BADD

def _is_sub(k):
    return k == Z3_OP_SUB or k == Z3_OP_BSUB

import sys
if sys.version < '3':
    import codecs
    def u(x):
        return codecs.unicode_escape_decode(x)[0]
else:
    def u(x):
        return x

_z3_infix_compact = [ Z3_OP_MUL, Z3_OP_BMUL, Z3_OP_POWER, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_BSDIV, Z3_OP_BSMOD ]

_ellipses = '...'

_html_ellipses = '&hellip;'
# Overwrite some of the operators for HTML
_z3_pre_html_op_to_str = { Z3_OP_EQ : '=', Z3_OP_IFF : '=', Z3_OP_NOT : '&not;',
                           Z3_OP_AND : '&and;', Z3_OP_OR : '&or;', Z3_OP_IMPLIES : '&rArr;',
                           Z3_OP_LT : '&lt;', Z3_OP_GT : '&gt;', Z3_OP_LE : '&le;', Z3_OP_GE : '&ge;', 
                           Z3_OP_MUL : '&middot;', 
                           Z3_OP_SLEQ : '&le;', Z3_OP_SLT : '&lt;', Z3_OP_SGEQ : '&ge;', Z3_OP_SGT : '&gt;',
                           Z3_OP_ULEQ : '&le;<sub>u</sub>', Z3_OP_ULT : '&lt;<sub>u</sub>', 
                           Z3_OP_UGEQ : '&ge;<sub>u</sub>', Z3_OP_UGT : '&gt;<sub>u</sub>',
                           Z3_OP_BMUL : '&middot;',
                           Z3_OP_BUDIV : '/<sub>u</sub>', Z3_OP_BUREM : '%<sub>u</sub>', 
                           Z3_OP_BASHR : '&gt;&gt;', Z3_OP_BSHL : '&lt;&lt;',
                           Z3_OP_BLSHR : '&gt;&gt;<sub>u</sub>'
                           }

# Extra operators that are infix/unary for HTML
_z3_html_infix = [ Z3_OP_AND, Z3_OP_OR, Z3_OP_IMPLIES,
                   Z3_OP_ULEQ, Z3_OP_ULT, Z3_OP_UGEQ, Z3_OP_UGT, Z3_OP_BUDIV, Z3_OP_BUREM, Z3_OP_BLSHR
                   ]

_z3_html_unary = [ Z3_OP_NOT ]

# Extra Precedence for HTML
_z3_pre_html_precedence = { Z3_OP_BUDIV : 2, Z3_OP_BUREM : 2,
                            Z3_OP_BLSHR : 4,
                            Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, 
                            Z3_OP_UGEQ : 8, Z3_OP_UGT : 8,
                            Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, 
                            Z3_OP_UGEQ : 8, Z3_OP_UGT : 8,
                            Z3_OP_NOT : 1,
                            Z3_OP_AND : 10,
                            Z3_OP_OR  : 11,
                            Z3_OP_IMPLIES : 12 }

##############################
#
# End of Configuration
#
##############################

def _support_pp(a):
    return isinstance(a, z3.Z3PPObject) or isinstance(a, list) or isinstance(a, tuple)

_infix_map = {}
_unary_map = {}
_infix_compact_map = {}

for _k in _z3_infix:
    _infix_map[_k] = True
for _k in _z3_unary:
    _unary_map[_k] = True
    
for _k in _z3_infix_compact:
    _infix_compact_map[_k] = True

def _is_infix(k):
    global _infix_map
    return _infix_map.get(k, False)

def _is_infix_compact(k):
    global _infix_compact_map
    return _infix_compact_map.get(k, False)

def _is_unary(k):
    global _unary_map
    return _unary_map.get(k, False)

def _op_name(a):
    if isinstance(a, z3.FuncDeclRef):
        f = a
    else:
        f = a.decl()
    k = f.kind()
    n = _z3_op_to_str.get(k, None)
    if n == None:
        return f.name()
    else:
        return n

def _get_precedence(k):
    global _z3_precedence
    return _z3_precedence.get(k, 100000)

_z3_html_op_to_str = {}
for _k in _z3_op_to_str:
    _v = _z3_op_to_str[_k]
    _z3_html_op_to_str[_k] = _v
for _k in _z3_pre_html_op_to_str:
    _v = _z3_pre_html_op_to_str[_k]
    _z3_html_op_to_str[_k] = _v

_z3_html_precedence = {}
for _k in _z3_precedence:
    _v = _z3_precedence[_k]
    _z3_html_precedence[_k] = _v
for _k in _z3_pre_html_precedence:
    _v = _z3_pre_html_precedence[_k]
    _z3_html_precedence[_k] = _v

_html_infix_map = {}
_html_unary_map = {}
for _k in _z3_infix:
    _html_infix_map[_k] = True
for _k in _z3_html_infix:
    _html_infix_map[_k] = True
for _k in _z3_unary:
    _html_unary_map[_k] = True
for _k in _z3_html_unary:
    _html_unary_map[_k] = True

def _is_html_infix(k):
    global _html_infix_map
    return _html_infix_map.get(k, False)

def _is_html_unary(k):
    global _html_unary_map
    return _html_unary_map.get(k, False)

def _html_op_name(a):
    global _z3_html_op_to_str
    if isinstance(a, z3.FuncDeclRef):
        f = a
    else:
        f = a.decl()
    k = f.kind()
    n = _z3_html_op_to_str.get(k, None)
    if n == None:
        sym = Z3_get_decl_name(f.ctx_ref(), f.ast)
        if Z3_get_symbol_kind(f.ctx_ref(), sym) == Z3_INT_SYMBOL:
            return "&#950;<sub>%s</sub>" % Z3_get_symbol_int(f.ctx_ref(), sym)
        else:
            # Sanitize the string
            return f.name()
    else:
        return n

def _get_html_precedence(k):
    global _z3_html_predence
    return _z3_html_precedence.get(k, 100000)

class FormatObject:
    def is_compose(self):
        return False
    def is_choice(self):
        return False
    def is_indent(self):
        return False
    def is_string(self):
        return False
    def is_linebreak(self):
        return False
    def is_nil(self):
        return True
    def children(self):
        return []
    def as_tuple(self):
        return None
    def space_upto_nl(self):
        return (0, False)
    def flat(self):
        return self

class NAryFormatObject(FormatObject):
    def __init__(self, fs):
        assert all([isinstance(a, FormatObject) for a in fs])
        self.children = fs
    def children(self):
        return self.children

class ComposeFormatObject(NAryFormatObject):
    def is_compose(sef):
        return True
    def as_tuple(self):
        return ('compose', [ a.as_tuple() for a in self.children ])
    def space_upto_nl(self):
        r = 0
        for child in self.children:
            s, nl = child.space_upto_nl()
            r = r + s
            if nl:
                return (r, True)
        return (r, False)
    def flat(self):
        return compose([a.flat() for a in self.children ])

class ChoiceFormatObject(NAryFormatObject):
    def is_choice(sef):
        return True
    def as_tuple(self):
        return ('choice', [ a.as_tuple() for a in self.children ])
    def space_upto_nl(self):
        return self.children[0].space_upto_nl()
    def flat(self):
        return self.children[0].flat()

class IndentFormatObject(FormatObject):
    def __init__(self, indent, child):
        assert isinstance(child, FormatObject)
        self.indent = indent
        self.child  = child
    def children(self):
        return [self.child]
    def as_tuple(self):
        return ('indent', self.indent, self.child.as_tuple())
    def space_upto_nl(self):
        return self.child.space_upto_nl()
    def flat(self):
        return indent(self.indent, self.child.flat())
    def is_indent(self):
        return True

class LineBreakFormatObject(FormatObject):
    def __init__(self):
        self.space = ' '
    def is_linebreak(self):
        return True
    def as_tuple(self):
        return '<line-break>'
    def space_upto_nl(self):
        return (0, True)
    def flat(self):
        return to_format(self.space)

class StringFormatObject(FormatObject):
    def __init__(self, string):
        assert isinstance(string, str)
        self.string = string
    def is_string(self):
        return True
    def as_tuple(self):
        return self.string
    def space_upto_nl(self):
        return (getattr(self, 'size', len(self.string)), False)

def fits(f, space_left):
    s, nl = f.space_upto_nl()
    return s <= space_left

def to_format(arg, size=None):
    if isinstance(arg, FormatObject):
        return arg
    else:
        r = StringFormatObject(str(arg))
        if size != None:
            r.size = size
        return r

def compose(*args):
    if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)):
        args = args[0]
    return ComposeFormatObject(args)

def indent(i, arg):
    return IndentFormatObject(i, arg)

def group(arg):
    return ChoiceFormatObject([arg.flat(), arg])

def line_break():
    return LineBreakFormatObject()

def _len(a):
    if isinstance(a, StringFormatObject):
        return getattr(a, 'size', len(a.string))
    else:
        return len(a)

def seq(args, sep=',', space=True):
    nl = line_break()
    if not space:
        nl.space = ''
    r = []
    r.append(args[0])
    num  = len(args)
    for i in range(num - 1):
        r.append(to_format(sep))
        r.append(nl)
        r.append(args[i+1])
    return compose(r)

def seq1(header, args, lp='(', rp=')'):
    return group(compose(to_format(header),
                         to_format(lp),
                         indent(len(lp) + _len(header),
                                seq(args)),
                         to_format(rp)))

def seq2(header, args, i=4, lp='(', rp=')'):
    if len(args) == 0:
        return compose(to_format(header), to_format(lp), to_format(rp))
    else:
        return group(compose(indent(len(lp), compose(to_format(lp), to_format(header))),
                             indent(i, compose(seq(args), to_format(rp)))))

def seq3(args, lp='(', rp=')'):
    if len(args) == 0:
        return compose(to_format(lp), to_format(rp))
    else:
        return group(indent(len(lp), compose(to_format(lp), seq(args), to_format(rp))))

class StopPPException(Exception):
    def __str__(self):
        return 'pp-interrupted'

class PP:
    def __init__(self):
        self.max_lines  = 200
        self.max_width  = 60
        self.bounded    = False
        self.max_indent = 40
        
    def pp_string(self, f, indent):
        if not self.bounded or self.pos <= self.max_width:
            sz = _len(f)
            if self.bounded and self.pos + sz > self.max_width:
                self.out.write(u(_ellipses))
            else:
                self.pos = self.pos + sz
                self.ribbon_pos = self.ribbon_pos + sz
                self.out.write(u(f.string))

    def pp_compose(self, f, indent):
        for c in f.children:
            self.pp(c, indent)

    def pp_choice(self, f, indent):
        space_left = self.max_width - self.pos
        if space_left > 0 and fits(f.children[0], space_left):
            self.pp(f.children[0], indent)
        else:
            self.pp(f.children[1], indent)
    
    def pp_line_break(self, f, indent):
        self.pos = indent
        self.ribbon_pos = 0
        self.line = self.line + 1
        if self.line < self.max_lines: 
            self.out.write(u('\n'))
            for i in range(indent):
                self.out.write(u(' '))
        else:
            self.out.write(u('\n...'))
            raise StopPPException()

    def pp(self, f, indent):
        if f.is_string():
            self.pp_string(f, indent)
        elif f.is_indent():
            self.pp(f.child, min(indent + f.indent, self.max_indent))
        elif f.is_compose():
            self.pp_compose(f, indent)
        elif f.is_choice():
            self.pp_choice(f, indent)
        elif f.is_linebreak():
            self.pp_line_break(f, indent)
        else:
            return

    def __call__(self, out, f):
        try:
            self.pos = 0
            self.ribbon_pos = 0
            self.line = 0
            self.out  = out
            self.pp(f, 0)
        except StopPPException:
            return
    
class Formatter:
    def __init__(self):
        global _ellipses
        self.max_depth           = 20
        self.max_args            = 128
        self.rational_to_decimal = False
        self.precision           = 10
        self.ellipses            = to_format(_ellipses)
        self.max_visited         = 10000
        self.fpa_pretty          = True
    
    def pp_ellipses(self):
        return self.ellipses

    def pp_arrow(self):
        return ' ->'

    def pp_unknown(self):
        return '<unknown>'
        
    def pp_name(self, a):
        return to_format(_op_name(a))

    def is_infix(self, a):
        return _is_infix(a)
    
    def is_unary(self, a):
        return _is_unary(a)

    def get_precedence(self, a):
        return _get_precedence(a)

    def is_infix_compact(self, a):
        return _is_infix_compact(a)

    def is_infix_unary(self, a):
        return self.is_infix(a) or self.is_unary(a) 

    def add_paren(self, a):
        return compose(to_format('('), indent(1, a), to_format(')'))
    
    def pp_sort(self, s):
        if isinstance(s, z3.ArraySortRef):
            return seq1('Array', (self.pp_sort(s.domain()), self.pp_sort(s.range())))
        elif isinstance(s, z3.BitVecSortRef):
            return seq1('BitVec', (to_format(s.size()), ))
        elif isinstance(s, z3.FPSortRef):
            return seq1('FPSort', (to_format(s.ebits()), to_format(s.sbits())))
        else:
            return to_format(s.name())

    def pp_const(self, a):
        return self.pp_name(a)

    def pp_int(self, a):
        return to_format(a.as_string())
        
    def pp_rational(self, a):
        if not self.rational_to_decimal:
            return to_format(a.as_string())
        else:
            return to_format(a.as_decimal(self.precision))

    def pp_algebraic(self, a):
        return to_format(a.as_decimal(self.precision))

    def pp_bv(self, a):
        return to_format(a.as_string())

    def pp_fprm_value(self, a):
        z3._z3_assert(z3.is_fprm_value(a), 'expected FPRMNumRef')
        if self.fpa_pretty and (a.decl().kind() in _z3_op_to_fpa_pretty_str):
            return to_format(_z3_op_to_fpa_pretty_str.get(a.decl().kind()))
        else:
            return to_format(_z3_op_to_fpa_normal_str.get(a.decl().kind()))

    def pp_fp_value(self, a):
        z3._z3_assert(isinstance(a, z3.FPNumRef), 'type mismatch')
        if not self.fpa_pretty:            
            if (a.isNaN()):
                return to_format('NaN')
            elif (a.isInf()):
                if (a.isNegative()):
                    return to_format('-oo')
                else:
                    return to_format('+oo')
            elif (a.isZero()):
                if (a.isNegative()):
                    return to_format('-zero')
                else:
                    return to_format('+zero')
            else:
                z3._z3_assert(z3.is_fp_value(a), 'expecting FP num ast')
                r = []
                sgn = c_int(0)
                sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn))
                sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast)
                exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast)
                r.append(to_format('FPVal('))
                if sgnb and sgn.value != 0:
                    r.append(to_format('-'))
                r.append(to_format(sig))
                r.append(to_format('*(2**'))
                r.append(to_format(exp))
                r.append(to_format(', '))
                r.append(to_format(a.sort()))
                r.append(to_format('))'))
                return compose(r)
        else:
            if (a.isNaN()):
                return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_NAN])
            elif (a.isInf()):
                if (a.isNegative()):
                    return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_INF])
                else:
                    return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_INF])
            elif (a.isZero()):
                if (a.isNegative()):
                    return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_ZERO])
                else:
                    return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_ZERO])
            else:
                z3._z3_assert(z3.is_fp_value(a), 'expecting FP num ast')
                r = []
                sgn = (ctypes.c_int)(0)
                sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn))
                sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast)
                exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast)
                if sgnb and sgn.value != 0:
                    r.append(to_format('-'))
                r.append(to_format(sig))
                if (exp != '0'):
                    r.append(to_format('*(2**'))
                    r.append(to_format(exp))
                    r.append(to_format(')'))                
                return compose(r)


    def pp_fp(self, a, d, xs):
        z3._z3_assert(isinstance(a, z3.FPRef), "type mismatch")
        k = a.decl().kind()
        op = '?'
        if (self.fpa_pretty and k in _z3_op_to_fpa_pretty_str):
            op = _z3_op_to_fpa_pretty_str[k]
        elif k in _z3_op_to_fpa_normal_str:
            op = _z3_op_to_fpa_normal_str[k]
        elif k in _z3_op_to_str:
            op = _z3_op_to_str[k]        

        n = a.num_args()

        if self.fpa_pretty:
            if self.is_infix(k) and n >= 3:            
                rm = a.arg(0)
                if z3.is_fprm_value(rm) and z3._dflt_rm(a.ctx).eq(rm):
                    arg1 = to_format(self.pp_expr(a.arg(1), d+1, xs))
                    arg2 = to_format(self.pp_expr(a.arg(2), d+1, xs))
                    r = []
                    r.append(arg1)
                    r.append(to_format(' '))
                    r.append(to_format(op))
                    r.append(to_format(' '))
                    r.append(arg2)
                    return compose(r)
            elif k == Z3_OP_FPA_NEG:
                return compose([to_format('-') , to_format(self.pp_expr(a.arg(0), d+1, xs))])

        if k in _z3_op_to_fpa_normal_str:
            op = _z3_op_to_fpa_normal_str[k]
        
        r = []        
        r.append(to_format(op))
        if not z3.is_const(a):
            r.append(to_format('('))                        
            first = True
            for c in a.children():                
                if first:
                    first = False
                else:
                    r.append(to_format(', '))
                r.append(self.pp_expr(c, d+1, xs))
            r.append(to_format(')'))
            return compose(r)
        else:
            return to_format(a.as_string())

    def pp_prefix(self, a, d, xs):
        r  = []
        sz = 0
        for child in a.children(): 
            r.append(self.pp_expr(child, d+1, xs))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        return seq1(self.pp_name(a), r)

    def is_assoc(self, k):
        return _is_assoc(k)

    def is_left_assoc(self, k):
        return _is_left_assoc(k)

    def infix_args_core(self, a, d, xs, r):
        sz = len(r)
        k  = a.decl().kind()
        p  = self.get_precedence(k)
        first = True
        for child in a.children():
            child_pp = self.pp_expr(child, d+1, xs)
            child_k = None
            if z3.is_app(child):
                child_k = child.decl().kind()
            if k == child_k and (self.is_assoc(k) or (first and self.is_left_assoc(k))):
                self.infix_args_core(child, d, xs, r)
                sz = len(r)
                if sz > self.max_args:
                    return
            elif self.is_infix_unary(child_k):
                child_p = self.get_precedence(child_k)
                if p > child_p or (_is_add(k) and _is_sub(child_k)) or (_is_sub(k) and first and _is_add(child_k)):
                    r.append(child_pp)
                else: 
                    r.append(self.add_paren(child_pp))
                sz = sz + 1
            elif z3.is_quantifier(child):
                r.append(self.add_paren(child_pp))
            else:
                r.append(child_pp)
                sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                return
            first = False

    def infix_args(self, a, d, xs):
        r = []
        self.infix_args_core(a, d, xs, r)
        return r

    def pp_infix(self, a, d, xs):
        k  = a.decl().kind()
        if self.is_infix_compact(k):
            op = self.pp_name(a)
            return group(seq(self.infix_args(a, d, xs), op, False))
        else:
            op = self.pp_name(a)
            sz = _len(op)
            op.string = ' ' + op.string
            op.size   = sz + 1
            return group(seq(self.infix_args(a, d, xs), op))

    def pp_unary(self, a, d, xs):
        k  = a.decl().kind()
        p  = self.get_precedence(k)
        child    = a.children()[0]
        child_k  = None
        if z3.is_app(child):
            child_k = child.decl().kind()
        child_pp = self.pp_expr(child, d+1, xs)        
        if k != child_k and self.is_infix_unary(child_k):
            child_p = self.get_precedence(child_k)
            if p <= child_p:
                child_pp = self.add_paren(child_pp)
        if z3.is_quantifier(child):
            child_pp = self.add_paren(child_pp)
        name = self.pp_name(a)
        return compose(to_format(name), indent(_len(name), child_pp))

    def pp_power_arg(self, arg, d, xs):
        r = self.pp_expr(arg, d+1, xs)
        k = None
        if z3.is_app(arg):
            k = arg.decl().kind()
        if self.is_infix_unary(k) or (z3.is_rational_value(arg) and arg.denominator_as_long() != 1):
            return self.add_paren(r)
        else:
            return r

    def pp_power(self, a, d, xs):
        arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs)
        arg2_pp = self.pp_power_arg(a.arg(1), d+1, xs)
        return group(seq((arg1_pp, arg2_pp), '**', False))

    def pp_neq(self):
        return to_format("!=")

    def pp_distinct(self, a, d, xs):
        if a.num_args() == 2:
            op = self.pp_neq()
            sz = _len(op)
            op.string = ' ' + op.string
            op.size   = sz + 1
            return group(seq(self.infix_args(a, d, xs), op))
        else:
            return self.pp_prefix(a, d, xs)

    def pp_select(self, a, d, xs):
        if a.num_args() != 2:
            return self.pp_prefix(a, d, xs)
        else:
            arg1_pp = self.pp_expr(a.arg(0), d+1, xs)
            arg2_pp = self.pp_expr(a.arg(1), d+1, xs)
            return compose(arg1_pp, indent(2, compose(to_format('['), arg2_pp, to_format(']'))))

    def pp_unary_param(self, a, d, xs):
        p   = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0)
        arg = self.pp_expr(a.arg(0), d+1, xs)
        return seq1(self.pp_name(a), [ to_format(p), arg ])

    def pp_extract(self, a, d, xs):
        h   = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0)
        l   = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1)
        arg = self.pp_expr(a.arg(0), d+1, xs)
        return seq1(self.pp_name(a), [ to_format(h), to_format(l), arg ])

    def pp_pattern(self, a, d, xs):
        if a.num_args() == 1:
            return self.pp_expr(a.arg(0), d, xs)
        else:
            return seq1('MultiPattern', [ self.pp_expr(arg, d+1, xs) for arg in a.children() ])

    def pp_map(self, a, d, xs):
        r  = []
        sz = 0
        f  = z3.get_map_func(a)
        r.append(to_format(f.name()))
        for child in a.children(): 
            r.append(self.pp_expr(child, d+1, xs))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        return seq1(self.pp_name(a), r)

    def pp_K(self, a, d, xs):
        return seq1(self.pp_name(a), [ self.pp_sort(a.domain()), self.pp_expr(a.arg(0), d+1, xs) ])

    def pp_app(self, a, d, xs):
        if z3.is_int_value(a):
            return self.pp_int(a)
        elif z3.is_rational_value(a):
            return self.pp_rational(a)
        elif z3.is_algebraic_value(a):
            return self.pp_algebraic(a)        
        elif z3.is_bv_value(a):
            return self.pp_bv(a)
        elif z3.is_fprm_value(a):
            return self.pp_fprm_value(a)
        elif z3.is_fp_value(a):
            return self.pp_fp_value(a)
        elif z3.is_fp(a):
            return self.pp_fp(a, d, xs)
        elif z3.is_const(a):
            return self.pp_const(a)
        else:
            f = a.decl()
            k = f.kind()
            if k == Z3_OP_POWER:
                return self.pp_power(a, d, xs)
            elif k == Z3_OP_DISTINCT:
                return self.pp_distinct(a, d, xs)
            elif k == Z3_OP_SELECT:
                return self.pp_select(a, d, xs)
            elif k == Z3_OP_SIGN_EXT or k == Z3_OP_ZERO_EXT or k == Z3_OP_REPEAT:
                return self.pp_unary_param(a, d, xs)
            elif k == Z3_OP_EXTRACT:
                return self.pp_extract(a, d, xs)
            elif k == Z3_OP_ARRAY_MAP:
                return self.pp_map(a, d, xs)
            elif k == Z3_OP_CONST_ARRAY:
                return self.pp_K(a, d, xs)
            elif z3.is_pattern(a):
                return self.pp_pattern(a, d, xs)
            elif self.is_infix(k):
                return self.pp_infix(a, d, xs)
            elif self.is_unary(k):
                return self.pp_unary(a, d, xs)
            else:
                return self.pp_prefix(a, d, xs)

    def pp_var(self, a, d, xs):
        idx = z3.get_var_index(a)
        sz  = len(xs)
        if idx >= sz:
            return seq1('Var', (to_format(idx),))
        else:
            return to_format(xs[sz - idx - 1])
        
    def pp_quantifier(self, a, d, xs):
        ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ]
        new_xs  = xs + ys
        body_pp = self.pp_expr(a.body(), d+1, new_xs)
        if len(ys) == 1:
            ys_pp = ys[0]
        else:
            ys_pp   = seq3(ys, '[', ']')
        if a.is_forall():
            header = 'ForAll'
        else:
            header = 'Exists'
        return seq1(header, (ys_pp, body_pp))

    def pp_expr(self, a, d, xs):
        self.visited = self.visited + 1
        if d > self.max_depth or self.visited > self.max_visited:
            return self.pp_ellipses()
        if z3.is_app(a):
            return self.pp_app(a, d, xs)
        elif z3.is_quantifier(a):
            return self.pp_quantifier(a, d, xs)
        elif z3.is_var(a):
            return self.pp_var(a, d, xs)
        else:
            return to_format(self.pp_unknown())

    def pp_seq_core(self, f, a, d, xs):
        self.visited = self.visited + 1
        if d > self.max_depth or self.visited > self.max_visited:
            return self.pp_ellipses()
        r = []
        sz = 0
        for elem in a:
            r.append(f(elem, d+1, xs))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        return seq3(r, '[', ']')
        
    def pp_seq(self, a, d, xs):
        return self.pp_seq_core(self.pp_expr, a, d, xs)

    def pp_seq_seq(self, a, d, xs):
        return self.pp_seq_core(self.pp_seq, a, d, xs)

    def pp_model(self, m):
        r = []
        sz = 0
        for d in m:
            i = m[d]
            if isinstance(i, z3.FuncInterp):
                i_pp = self.pp_func_interp(i)
            else:
                i_pp = self.pp_expr(i, 0, [])
            name = self.pp_name(d)
            r.append(compose(name, to_format(' = '), indent(_len(name) + 3, i_pp)))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        return seq3(r, '[', ']')

    def pp_func_entry(self, e):
        num = e.num_args()
        if num > 1:
            args = []
            for i in range(num):
                args.append(self.pp_expr(e.arg_value(i), 0, []))
            args_pp = group(seq3(args))
        else:
            args_pp   = self.pp_expr(e.arg_value(0), 0, [])
        value_pp = self.pp_expr(e.value(), 0, []) 
        return group(seq((args_pp, value_pp), self.pp_arrow()))

    def pp_func_interp(self, f):
        r = []
        sz = 0
        num = f.num_entries()
        for i in range(num):
            r.append(self.pp_func_entry(f.entry(i)))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        if sz <= self.max_args:
            else_val = f.else_value()
            if else_val == None:
                else_pp  = to_format('#unspecified')
            else:
                else_pp  = self.pp_expr(else_val, 0, [])
            r.append(group(seq((to_format('else'), else_pp), self.pp_arrow())))
        return seq3(r, '[', ']')

    def pp_list(self, a):
        r = []
        sz = 0
        for elem in a:
            if _support_pp(elem):
                r.append(self.main(elem))
            else:
                r.append(to_format(str(elem)))
            sz = sz + 1
            if sz > self.max_args:
                r.append(self.pp_ellipses())
                break
        if isinstance(a, tuple):
            return seq3(r)
        else:
            return seq3(r, '[', ']')

    def main(self, a):
        if z3.is_expr(a):
            return self.pp_expr(a, 0, [])
        elif z3.is_sort(a):
            return self.pp_sort(a)
        elif z3.is_func_decl(a):
            return self.pp_name(a)
        elif isinstance(a, z3.Goal) or isinstance(a, z3.AstVector):
            return self.pp_seq(a, 0, [])
        elif isinstance(a, z3.Solver):
            return self.pp_seq(a.assertions(), 0, [])
        elif isinstance(a, z3.Fixedpoint):
            return a.sexpr()
        elif isinstance(a, z3.Optimize):
            return a.sexpr()
        elif isinstance(a, z3.ApplyResult):
            return self.pp_seq_seq(a, 0, [])
        elif isinstance(a, z3.ModelRef):
            return self.pp_model(a)
        elif isinstance(a, z3.FuncInterp):
            return self.pp_func_interp(a)
        elif isinstance(a, list) or isinstance(a, tuple):
            return self.pp_list(a)
        else:
            return to_format(self.pp_unknown())

    def __call__(self, a):
        self.visited = 0
        return self.main(a)

class HTMLFormatter(Formatter):
    def __init__(self):
        Formatter.__init__(self)
        global _html_ellipses
        self.ellipses = to_format(_html_ellipses)

    def pp_arrow(self):
        return to_format(' &rarr;', 1)

    def pp_unknown(self):
        return '<b>unknown</b>'
        
    def pp_name(self, a):
        r = _html_op_name(a)
        if r[0] == '&' or r[0] == '/' or r[0] == '%':
            return to_format(r, 1)
        else:
            pos = r.find('__')
            if pos == -1 or pos == 0:
                return to_format(r)
            else:
                sz = len(r)
                if pos + 2 == sz:
                    return to_format(r)
                else:
                    return to_format('%s<sub>%s</sub>' % (r[0:pos], r[pos+2:sz]), sz - 2)

    def is_assoc(self, k):
        return _is_html_assoc(k)

    def is_left_assoc(self, k):
        return _is_html_left_assoc(k)

    def is_infix(self, a):
        return _is_html_infix(a)
    
    def is_unary(self, a):
        return _is_html_unary(a)

    def get_precedence(self, a):
        return _get_html_precedence(a)

    def pp_neq(self):
        return to_format("&ne;")

    def pp_power(self, a, d, xs):
        arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs)
        arg2_pp = self.pp_expr(a.arg(1), d+1, xs)
        return compose(arg1_pp, to_format('<sup>', 1), arg2_pp, to_format('</sup>', 1)) 

    def pp_var(self, a, d, xs):
        idx = z3.get_var_index(a)
        sz  = len(xs)
        if idx >= sz:
            # 957 is the greek letter nu
            return to_format('&#957;<sub>%s</sub>' % idx, 1)
        else:
            return to_format(xs[sz - idx - 1])

    def pp_quantifier(self, a, d, xs):
        ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ]
        new_xs  = xs + ys
        body_pp = self.pp_expr(a.body(), d+1, new_xs)
        ys_pp = group(seq(ys))
        if a.is_forall():
            header = '&forall;'
        else:
            header = '&exist;'
        return group(compose(to_format(header, 1), 
                             indent(1, compose(ys_pp, to_format(' :'), line_break(), body_pp))))


_PP        = PP()
_Formatter = Formatter()

def set_pp_option(k, v):
    if k == 'html_mode':
        if v:
            set_html_mode(True)
        else:
            set_html_mode(False)
        return True
    if k == 'fpa_pretty':
        if v:
            set_fpa_pretty(True)
        else:
            set_fpa_pretty(False)
        return True
    val = getattr(_PP, k, None)
    if val != None:
        z3._z3_assert(type(v) == type(val), "Invalid pretty print option value")
        setattr(_PP, k, v)
        return True
    val = getattr(_Formatter, k, None)
    if val != None:
        z3._z3_assert(type(v) == type(val), "Invalid pretty print option value")
        setattr(_Formatter, k, v)
        return True
    return False

def obj_to_string(a):
    out = io.StringIO()
    _PP(out, _Formatter(a))
    return out.getvalue()

_html_out = None

def set_html_mode(flag=True):
    global _Formatter
    if flag:
        _Formatter = HTMLFormatter()
    else:
        _Formatter = Formatter()

def set_fpa_pretty(flag=True):
    global _Formatter
    global _z3_op_to_str
    _Formatter.fpa_pretty = flag
    if flag:
        for (_k,_v) in _z3_op_to_fpa_pretty_str.items():
            _z3_op_to_str[_k] = _v
        for _k in _z3_fpa_infix:
            _infix_map[_k] = True
    else:
        for (_k,_v) in _z3_op_to_fpa_normal_str.items():
            _z3_op_to_str[_k] = _v
        for _k in _z3_fpa_infix:
            _infix_map[_k] = False

set_fpa_pretty(True)

def in_html_mode():
    return isinstance(_Formatter, HTMLFormatter)

def pp(a):
    if _support_pp(a):
        print(obj_to_string(a))
    else:
        print(a)

def print_matrix(m):
    z3._z3_assert(isinstance(m, list) or isinstance(m, tuple), "matrix expected")
    if not in_html_mode():
        print(obj_to_string(m))
    else:
        print('<table cellpadding="2", cellspacing="0", border="1">')
        for r in m:
            z3._z3_assert(isinstance(r, list) or isinstance(r, tuple), "matrix expected")
            print('<tr>')
            for c in r:
                print('<td>%s</td>' % c)
            print('</tr>')
        print('</table>')
    
def insert_line_breaks(s, width):
    """Break s in lines of size width (approx)"""
    sz = len(s)
    if sz <= width:
        return s
    new_str = io.StringIO()
    w = 0
    for i in range(sz):
        if w > width and s[i] == ' ':
            new_str.write(u('<br />'))
            w = 0
        else:
            new_str.write(u(s[i]))
        w = w + 1
    return new_str.getvalue()