Source

semantic / semantic.el

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
;;; semantic.el --- Semantic buffer evaluator.

;;; Copyright (C) 1999, 2000, 2001 Eric M. Ludlam

;; Author: Eric M. Ludlam <zappo@gnu.org>
;; Keywords: syntax
;; X-RCS: $Id$

(defvar semantic-version "1.4beta8"
  "Current version of Semantic.")

;; This file is not part of GNU Emacs.

;; Semantic is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
;;
;; API for determining semantic content of a buffer.  The mode using
;; semantic must be a deterministic programming language.
;;
;; The output of a semantic bovine parse is parse tree.  While it is
;; possible to assign actions in the bovine-table in a similar fashion
;; to bison, this is not it's end goal.

;;; History:
;; 

(require 'working)

(defgroup semantic nil
  "Parser Generator/Parser."
  )

;;; Code:

;;; Compatibility
;;
(if (featurep 'xemacs)
    (progn
      (defalias 'semantic-overlay-live-p 'extent-live-p)
      (defalias 'semantic-make-overlay 'make-extent)
      (defalias 'semantic-overlay-put 'set-extent-property)
      (defalias 'semantic-overlay-get 'extent-property)
      (defalias 'semantic-overlay-delete 'delete-extent)
      (defalias 'semantic-overlays-at
        (lambda (pos) (extent-list nil pos pos)))
      (defalias 'semantic-overlays-in 
	(lambda (beg end) (extent-list nil beg end)))
      (defalias 'semantic-overlay-buffer 'extent-buffer)
      (defalias 'semantic-overlay-start 'extent-start-position)
      (defalias 'semantic-overlay-end 'extent-end-position)
      (defalias 'semantic-overlay-next-change 'next-extent-change)
      (defalias 'semantic-overlay-previous-change 'previous-extent-change)
      (defalias 'semantic-overlay-lists
	(lambda () (list (extent-list))))
      (defalias 'semantic-overlay-p 'extentp)
      (defun semantic-read-event ()
        (let ((event (next-command-event)))
          (if (key-press-event-p event)
              (let ((c (event-to-character event)))
                (if (char-equal c (quit-char))
                    (keyboard-quit)
                  c)))
          event))
      )
  (defalias 'semantic-overlay-live-p 'overlay-buffer)
  (defalias 'semantic-make-overlay 'make-overlay)
  (defalias 'semantic-overlay-put 'overlay-put)
  (defalias 'semantic-overlay-get 'overlay-get)
  (defalias 'semantic-overlay-delete 'delete-overlay)
  (defalias 'semantic-overlays-at 'overlays-at)
  (defalias 'semantic-overlays-in 'overlays-in)
  (defalias 'semantic-overlay-buffer 'overlay-buffer)
  (defalias 'semantic-overlay-start 'overlay-start)
  (defalias 'semantic-overlay-end 'overlay-end)
  (defalias 'semantic-overlay-next-change 'next-overlay-change)
  (defalias 'semantic-overlay-previous-change 'previous-overlay-change)
  (defalias 'semantic-overlay-lists 'overlay-lists)
  (defalias 'semantic-overlay-p 'overlayp)
  (defalias 'semantic-read-event 'read-event)
  )

(defvar semantic-edebug nil
  "When non-nil, activate the interactive parsing debugger.
Do not set this yourself.  Call `semantic-bovinate-buffer-debug'.")


(defcustom semantic-dump-parse nil
  "When non-nil, dump parsing information."
  :group 'semantic
  :type 'boolean)

(defvar semantic-toplevel-bovine-table nil
  "Variable that defines how to bovinate top level items in a buffer.
Set this in your major mode to return function and variable semantic
types.

The format of a BOVINE-TABLE is:

 ( ( NONTERMINAL-SYMBOL1 MATCH-LIST1 )
   ( NONTERMINAL-SYMBOL2 MATCH-LIST2 )
   ...
   ( NONTERMINAL-SYMBOLn MATCH-LISTn )
 
Where each NONTERMINAL-SYMBOL is an artificial symbol which can appear
in any child state.  As a starting place, one of the NONTERMINAL-SYMBOLS
must be `bovine-toplevel'.

A MATCH-LIST is a list of possible matches of the form:

 ( STATE-LIST1
   STATE-LIST2
   ...
   STATE-LISTN )

where STATE-LIST is of the form:
  ( TYPE1 [ \"VALUE1\" ] TYPE2 [ \"VALUE2\" ] ... LAMBDA )

where TYPE is one of the returned types of the token stream.
VALUE is a value, or range of values to match against.  For
example, a SYMBOL might need to match \"foo\".  Some TYPES will not
have matching criteria.

LAMBDA is a lambda expression which is evaled with the text of the
type when it is found.  It is passed the list of all buffer text
elements found since the last lambda expression.  It should return a
semantic element (see below.)

For consistency between languages, always use the following symbol
forms.  It is fine to create new symbols, or to exclude some if they
do not exist, however by using these symbols, you can maximize the
number of language-independent programs available for use with your
language.

GENERIC ENTRIES:

 Bovine table entry return elements are up to the table author.  It is
recommended, however, that the following format be used.

 (\"NAME\" type-symbol [\"TYPE\"] ... \"DOCSTRING\" PROPERTIES OVERLAY)

Where type-symbol is the type of return token found, and NAME is it's
name.  If there is any typing information needed to describe this
entry, make that come third.  Next, any additional information follows
the optional type.  The last data entry can be the position in the buffer
of DOCSTRING.  A docstring does not have to exist in the form used by
Emacs Lisp.  It could be the text of a comment appearing just before a
function call, or in line with a variable.

PROPERTIES is a list of additional properties for this token.
PRORPERTIES is not for details of the token.  It is used for
additional tags needed by tools using the parse stream.  For example,
the `dirty' property is used when a given token needs to be reparsed.

PROPERTIES are automatically added to the token by the system when
using BNF, or `semantic-lambda' in the table.

The last element must be OVERLAY.  The OVERLAY is automatically
created by the parsing system.  When programming with BNF, or using
`semantic-lambda', no extra work needs to be done.  If you are
building the parse table yourself, use START and END.

It may seem odd to place NAME in slot 0, and the type-symbol in slot
1, but this turns the returned elements into a list which can be used
by alist based function.  This makes it ideal for passing into generic
sorters, string completion functions, and list searching functions.

In the below entry formats, \"NAME\" is a string which is the name of
the object in question.  It is possible for this to be nil in some
situations, and code dealing with entries should try to be aware of
these situations.

\"TYPE\" is a string representing the type of some objects.  For a
variable, this could very well be another top level token representing
a type nonterminal.

TOP-LEVEL ENTRIES:

 (\"NAME\" variable \"TYPE\" DEFAULT-VALUE EXTRA-SPEC 
         \"DOCSTRING\" PROPERTIES OVERLAY)
   The definition of a variable, or constant.
   DEFAULT-VALUE can be something apropriate such a a string,
                 or list of parsed elements.
   EXTRA-SPEC are details about a variable that are not covered in the TYPE.
             See detail on EXTRA-SPEC after entries section.
   DOCSTRING is optional.

 (\"NAME\" function \"TYPE\" ( ARG-LIST ) EXTRA-SPEC
          \"DOCSTRING\" PROPERTIES OVERLAY)
   A function/procedure definition.
   ARG-LIST is a list of variable definitions.
   DOCSTRING is optional.

 (\"NAME\" type \"TYPE\" ( PART-LIST ) ( PARENTS ) EXTRA-SPEC
          \"DOCSTRING\" PROPERTIES OVERLAY)
   A type definition.
   TYPE of a type could be anything, such as (in C) struct, union, typedef,
        or class.
   PART-LIST is only useful for structs that have multiple individual parts.
            (It is recommended that these be variables, functions or types).
   PARENTS is strictly for classes where there is inheritance.
           See `semantic-token-parent' for a description of this value.   

 (\"FILE\" include SYSTEM \"DOCSTRING\" PROPERTIES OVERLAY)
   In C, an #include statement.  In elisp, a require statement.
   Indicates additional locations of sources or definitions.
   SYSTEM is true if this include is part of a set of system includes.

 (\"NAME\" package DETAIL \"DOCSTRING\" PROPERTIES OVERLAY)
   In Emacs Lisp, a `provide' statement.  DETAIL might be an
   associated file name.  In Java, this is a package statement.

EXTRA-SPEC:

  The EXTRA-SPEC section of variables, functions, and types provide a
location to place language specific details which are not accounted
for by the base token type.  Because there is an arbitrary number of
things that could be associated in the EXTRA-SPEC section, this should
be formatted as an association list.

  Here are some typed extra specifiers that may exist.  Any arbitrary
number of extra specifiers may be created, and specifiers not
documented here are allowed.

  (parent .  \"text\") - Name of a parent type/class.  C++ and CLOS allow
     the creation of a function outside the body of that type/class.

  (dereference .  INT) - Number of levels of dereference.  In C, the number
     of `*' characters indicating pointers.

  (typemodifiers .  \"text\") - Keyword modifiers for a type.  In C, such
     words would include `register', and `volatile'.

  (suffix . \"text\") - Suffix information for a variable.

  (const .  t) - This exists if the variable or return value is constant.

  (throws .  \"text\") - For functions or methods in languages that support
     typed signal throwing.

  (user-visible . t) - For functions in interpreted languages such as Emacs Lisp,
     this signals that a function or variable is user visible.  In Emacs Lisp,
     this means a function is `interactive'.")
(make-variable-buffer-local 'semantic-toplevel-bovine-table)

(defvar semantic-toplevel-bovine-table-source nil
  "The .bnf source file the current table was created from.")
(make-variable-buffer-local 'semantic-toplevel-bovine-table-source)

(defvar semantic-symbol->name-assoc-list
  '((variable . "Variables")
    (function . "Functions")
    (type     . "Types")
    (include  . "Dependencies")
    (package  . "Provides"))
  "Association between symbols returned, and a string.
The string is used to represent a group of objects of the given type.
It is sometimes useful for a language to use a different string
in place of the default, even though that language will still
return a symbol.  For example, Java return's includes, but the
string can be replaced with `Imports'.")
(make-variable-buffer-local 'semantic-symbol->name-assoc-list)

(defvar semantic-case-fold nil
  "Value for `case-fold-search' when parsing.")
(make-variable-buffer-local 'semantic-case-fold)

(defvar semantic-flex-depth 0
  "Default flexing depth.
This specifies how many lists to create tokens in.")
(make-variable-buffer-local 'semantic-flex-depth)

(defvar semantic-ignore-comments t
  "Default comment handling.
t means to strip comments when flexing.  Nil means to keep comments
as part of the token stream.")
(make-variable-buffer-local 'semantic-ignore-comments)

(defvar semantic-expand-nonterminal nil
  "Function to call for each nonterminal production.
Return a list of non-terminals derived from the first argument, or nil
if it does not need to be expanded.
Languages with compound definitions should use this function to expand
from one compound symbol into several.  For example, in C the definition
  int a, b;
is easily parsed into one token.  This function should take this
compound token and turn it into two tokens, one for A, and the other for B.")
(make-variable-buffer-local 'semantic-expand-nonterminal)

(defvar semantic-toplevel-bovine-cache nil
  "A cached copy of a recent bovination, plus state.
If no significant changes have been made (based on the state) then
this is returned instead of re-parsing the buffer.
 
  DO NOT USE THIS VARIABLE IN PROGRAMS.

If you need a token list, use `semantic-bovinate-toplevel'.  If you
need the cached values for some reason, chances are you can, add a
hook to `semantic-after-toplevel-cache-change-hook'.")
(make-variable-buffer-local 'semantic-toplevel-bovine-cache)

(defvar semantic-edits-are-safe nil
  "When non-nil, modifications do not require a reparse.
This prevents tokens from being marked dirty, and it
prevents top level edits from causing a cache check.
Use this when writing programs that could cause a full
reparse, but will not change the tag structure, such
as adding or updating top-level comments.")

(defvar semantic-toplevel-bovine-cache-check nil
  "Non nil if the bovine cache is out of date.
This is tracked with `semantic-change-function'.")
(make-variable-buffer-local 'semantic-toplevel-bovine-cache-check)

(defvar semantic-toplevel-bovine-force-reparse nil
  "Non nil if the next token request forces a reparse.")
(make-variable-buffer-local 'semantic-toplevel-bovine-force-reparse)

(defvar semantic-dirty-tokens nil
  "List of tokens in the current buffer which are dirty.
Dirty functions can then be reparsed, and spliced back into the main list.")
(make-variable-buffer-local 'semantic-dirty-tokens)

(defvar semantic-bovinate-nonterminal-check-obarray nil
  "Obarray of streams already parsed for nonterminal symbols.")
(make-variable-buffer-local 'semantic-bovinate-nonterminal-check-obarray)

(defvar semantic-dirty-token-hooks nil
  "Hooks run after when a token is marked as dirty (edited by the user).
The functions must take TOKEN, START, and END as a parameters.
This hook will only be called once when a token is first made dirty,
subsequent edits will not cause this to run a second time unless that
token is first cleaned.  Any token marked as dirty will
also be called with `semantic-clean-token-hooks', unless a full
reprase is done instead.")

(defvar semantic-clean-token-hooks nil
  "Hooks run after a token is marked as clean (reparsed after user edits.)
The functions must take a TOKEN as a parameter.
Any token sent to this hook will have first been called with
`semantic-dirty-token-hooks'.  This hook is not called for tokens
marked dirty if the buffer is completely reparsed.  In that case, use
`semantic-after-toplevel-bovinate-hook'.")

(defvar semantic-change-hooks nil
  "Hooks run when semantic detects a change in a buffer.
Each hook function must take three arguments, identical to the
common hook `after-change-function'.")

(defvar semantic-bovinate-toplevel-override nil
  "Local variable set by major modes which provide their own bovination.
This function should behave as the function `semantic-bovinate-toplevel'.")
(make-variable-buffer-local 'semantic-bovinate-toplevel-override)

(defvar semantic-after-toplevel-bovinate-hook nil
  "Hooks run after a toplevel token parse.
It is not run if the toplevel parse command is called, and buffer does
not need to be fully reparsed.
For language specific hooks, make sure you define this as a local hook.")

(defvar semantic-after-toplevel-cache-change-hook nil
  "Hooks run after the buffer token list has changed.
This list will change when a buffer is reparsed, or when the token
list in a buffer is cleared.  It is *NOT* called if the current token
list partially reparsed.

Hook functions must take one argument, which is the new list of
tokens associated with this buffer.

For language specific hooks, make sure you define this as a local hook.")

(defvar semantic-before-toplevel-cache-flush-hook nil
  "Hooks run before the toplevel nonterminal cache is flushed.
For language specific hooks, make sure you define this as a local hook.
This hook is called before a corresponding
`semantic-after-toplevel-bovinate-hook' which is also called during a
flush when the cache is given a new value of nil.")

(defvar semantic-reparse-needed-change-hook nil
  "Hooks run when a user edit is detected as needing a reparse.
For language specific hooks, make sure you define this as a local
hook.
Not used yet; part of the next generation reparse mechanism")

(defvar semantic-no-reparse-needed-change-hook nil
  "Hooks run when a user edit is detected as not needing a reparse.
If the hook returns non-nil, then declare that a reparse is needed.
For language specific hooks, make sure you define this as a local
hook.
Not used yet; part of the next generation reparse mechanism.")


;;; Primitive Token access system:
;;
;; These are token level APIs (similar to some APIs in semantic-util)
;; which are required for parsing operations.  Semantic.el should have
;; no dependencies on other semantic files.
;;
;; TFE = Token From End

(defconst semantic-tfe-overlay 1
  "Amount to subtract from the length of the token to get the overlay.")
(defconst semantic-tfe-properties 2
  "Amount to subtract from the length of the token to get the property list.")
(defconst semantic-tfe-docstring 3
  "Amount to subtract from the length of the token to get the doc string.")
(defconst semantic-tfe-number 2
  "The number of required end elements.")

(defmacro semantic-token-token (token)
  "Retrieve from TOKEN the token identifier.
ie, the symbol 'variable, 'function, 'type, or other."
  `(nth 1 ,token))

(defun semantic-token-name (token)
  "Retrieve the name of TOKEN."
  (car token))

(defun semantic-token-docstring (token &optional buffer)
  "Retrieve the documentation of TOKEN.
Optional argument BUFFER indicates where to get the text from.
If not provided, then only the POSITION can be provided."
  (let ((p (nth (- (length token) semantic-tfe-docstring) token)))
    (if (and p buffer)
	(save-excursion
	  (set-buffer buffer)
	  (semantic-flex-text (car (semantic-flex p (1+ p)))))
      p)))

(defmacro semantic-token-properties (token)
  "Retrieve the PROPERTIES part of TOKEN.
The returned item is an ALIST of (KEY . VALUE) pairs."
  `(nth (- (length ,token) semantic-tfe-properties) ,token))

(defmacro semantic-token-properties-cdr (token)
  "Retrieve the cons cell for the PROPERTIES part of TOKEN."
  `(nthcdr (- (length ,token) semantic-tfe-properties) ,token))

(defun semantic-token-put (token key value)
  "For TOKEN, put the property KEY on it with VALUE.
If VALUE is nil, then remove the property from TOKEN."
  (let* ((c (semantic-token-properties-cdr token))
	 (al (car c))
	 (a (assoc key (car c))))
    (if a
	(if value
	    (setcdr a value)
	  (adelete 'al key)
	  (setcar c al))
      (if value
	  (setcar c (cons (cons key value) (car c)))))
    ))

(defun semantic-token-get (token key)
  "For TOKEN, get the value for property KEY."
  (cdr (assoc key (semantic-token-properties token))))

(defmacro semantic-token-overlay (token)
  "Retrieve the OVERLAY part of TOKEN.
The returned item may be an overlay or an unloaded buffer representation."
  `(nth (- (length ,token) semantic-tfe-overlay) ,token))

(defmacro semantic-token-overlay-cdr (token)
  "Retrieve the cons cell containing the OVERLAY part of TOKEN."
  `(nthcdr (- (length ,token) semantic-tfe-overlay) ,token))

(defmacro semantic-token-extent (token)
  "Retrieve the extent (START END) of TOKEN."
  `(let ((o (semantic-token-overlay ,token)))
     (if (semantic-overlay-p o)
	 (list (semantic-overlay-start o) (semantic-overlay-end o))
       (list (aref o 0) (aref o 1)))))

(defun semantic-token-start (token)
  "Retrieve the start location of TOKEN."
  (let ((o (semantic-token-overlay token)))
    (if (semantic-overlay-p o) (semantic-overlay-start o) (aref o 0))))

(defun semantic-token-end (token)
  "Retrieve the end location of TOKEN."
  (let ((o (semantic-token-overlay token)))
    (if (semantic-overlay-p o) (semantic-overlay-end o) (aref o 1))))

(defun semantic-token-buffer (token)
  "Retrieve the buffer TOKEN resides in."
  (let ((o (semantic-token-overlay token)))
    (if (semantic-overlay-p o) (semantic-overlay-buffer o)
      ;; We have no buffer for this token (It's not in Emacs right now.)
      nil)))

(defun semantic-token-p (token)
  "Return non-nil if TOKEN is most likely a semantic token."
  (and (listp token)
       (stringp (car token))
       (car (cdr token))
       (symbolp (car (cdr token)))))

(defun semantic-token-with-position-p (token)
  "Return non-nil if TOKEN is a semantic token with positional information."
  (and (listp token)
       (stringp (car token))
       (symbolp (car (cdr token)))
       (let ((o (semantic-token-overlay token)))
	 (or (semantic-overlay-p o)
	     (arrayp o)))))


;;; Overlay and error stacks.
;;
(defvar semantic-overlay-error-recovery-stack nil
  "List of overlays used during error recovery.")

(defun semantic-overlay-stack-add (o)
  "Add overlay O to the error recovery stack."
  (setq semantic-overlay-error-recovery-stack
	(if (listp o)
	    (append o semantic-overlay-error-recovery-stack)
	  (cons o semantic-overlay-error-recovery-stack))))

(defun semantic-overlay-stack-clear ()
  "Clear the overlay error recovery stack."
  (while semantic-overlay-error-recovery-stack
    (semantic-overlay-delete (car semantic-overlay-error-recovery-stack))
    (setq semantic-overlay-error-recovery-stack
	  (cdr semantic-overlay-error-recovery-stack))))

(defun semantic-delete-overlay-maybe (overlay)
  "Delete OVERLAY if it is a semantic token overlay."
  (if (semantic-overlay-get overlay 'semantic)
      (semantic-overlay-delete overlay)))

;;; Interfacing with the system
;;
(defvar semantic-init-hooks nil
  "*Hooks run when a buffer is initialized with a parsing table.")

(defun semantic-active-p ()
  "Return non-nil if the current buffer was set up for parsing."
  (or semantic-toplevel-bovine-table
      semantic-bovinate-toplevel-override))

(defun semantic-new-buffer-fcn ()
  "Setup Semantic in the current buffer.
Runs `semantic-init-hook' if the major mode is setup to use Semantic."
  (when (semantic-active-p)
    (semantic-clear-toplevel-cache)
    (setq semantic-toplevel-bovine-force-reparse t)
    (run-hooks 'semantic-init-hooks)))

(defvar semantic-changed-mode-buffers nil
  "List of buffers whose `major-mode' has changed recently.")

(defun semantic-post-change-major-mode-function ()
  "`post-command-hook' run when there is a `major-mode' change.
This makes sure semantic-init type stuff can occur."
  (remove-hook 'post-command-hook
               'semantic-post-change-major-mode-function)
  (let (buf)
    (while semantic-changed-mode-buffers
      (setq buf (car semantic-changed-mode-buffers)
            semantic-changed-mode-buffers
            (cdr semantic-changed-mode-buffers))
      (and (buffer-live-p buf)
           (buffer-file-name buf)
           (with-current-buffer buf
             (semantic-new-buffer-fcn))))))

(defun semantic-change-major-mode-hook-function ()
  "Function called in `change-major-mode-hook'."
  (add-to-list 'semantic-changed-mode-buffers (current-buffer))
  (add-hook 'post-command-hook 'semantic-post-change-major-mode-function))

(add-hook 'find-file-hooks
          'semantic-post-change-major-mode-function)
(add-hook 'change-major-mode-hook
          'semantic-change-major-mode-hook-function)

;; Test the above hook.
;;(add-hook 'semantic-init-hooks (lambda () (message "init for semantic")))

(defun semantic-rebovinate-quickly-hook ()
  "For use in a hook.  When only a partial reparse is needed, reparse."
  (condition-case nil
      (if (semantic-bovine-toplevel-partial-reparse-needed-p nil)
	  (semantic-bovinate-toplevel))
    (error nil)))

(if (boundp 'eval-defun-hooks)
    (add-hook 'eval-defun-hooks 'semantic-rebovinate-quickly-hook))

;;; Parsing Commands
;;
(eval-when-compile
  (condition-case nil (require 'pp) (error nil)))

(defun bovinate (&optional clear)
  "Bovinate the current buffer.  Show output in a temp buffer.
Optional argument CLEAR will clear the cache before bovinating."
  (interactive "P")
  (if clear (semantic-clear-toplevel-cache))
  (let ((out (semantic-bovinate-toplevel t)))
    (pop-to-buffer "*BOVINATE*")
    (require 'pp)
    (erase-buffer)
    (insert (pp-to-string out))
    (goto-char (point-min))))

(defun bovinate-debug ()
  "Bovinate the current buffer and run in debug mode."
  (interactive)
  (let ((semantic-edebug t)
	(out (semantic-bovinate-debug-buffer)))
    (pop-to-buffer "*BOVINATE*")
    (require 'pp)
    (erase-buffer)
    (insert (pp-to-string out))))

;;; Parsing functions
;;
(defun semantic-clear-toplevel-cache ()
  "Clear the toplevel bovin cache for the current buffer.
Clearing the cache will force a complete reparse next time a token
stream is requested."
  (interactive)
  (run-hooks 'semantic-before-toplevel-cache-flush-hook)
  (setq semantic-toplevel-bovine-cache nil)
  ;; Nuke all semantic overlays.  This is faster than deleting based
  ;; on our data structure.
  (let ((l (semantic-overlay-lists)))
    (mapcar 'semantic-delete-overlay-maybe (car l))
    (mapcar 'semantic-delete-overlay-maybe (cdr l))
    )
  ;; Clear the dirty tokens... no longer relevant
  (setq semantic-dirty-tokens nil)
  (setq semantic-toplevel-bovine-force-reparse t)
  ;; Remove this hook which tracks if a buffer is up to date or not.
  (remove-hook 'after-change-functions 'semantic-change-function t)
  ;; Old model.  Delete someday.
  ;;(run-hooks 'semantic-after-toplevel-bovinate-hook)
  (run-hook-with-args 'semantic-after-toplevel-cache-change-hook
		      semantic-toplevel-bovine-cache)
  )

(defvar semantic-bovination-working-type 'percent
  "*The type of working message to use when bovinating.
'percent means we are doing a linear parse through the buffer.
'dynamic means we are rebovinating specific tokens.")

(defun semantic-bovine-toplevel-full-reparse-needed-p (&optional checkcache)
  "Return non-nil if the current buffer needs a full reparse.
Optional argument CHECKCACHE indicates if the cache check should be made."
  (or semantic-toplevel-bovine-force-reparse
      (and
       checkcache
       semantic-toplevel-bovine-cache-check)))

(defun semantic-bovine-toplevel-partial-reparse-needed-p (&optional checkcache)
  "Return non-nil if the current buffer needs a partial reparse.
This only returns non-nil if `semantic-bovine-toplevel-full-reparse-needed-p'
returns nil.
Optional argument CHECKCACHE indicates if the cache check should be made
when checking `semantic-bovine-toplevel-full-reparse-needed-p'."
  (and semantic-toplevel-bovine-cache
       semantic-dirty-tokens
       (not (semantic-bovine-toplevel-full-reparse-needed-p checkcache))))

;;;###autoload
(defun semantic-bovinate-toplevel (&optional checkcache)
  "Bovinate the entire current buffer.
If the optional argument CHECKCACHE is non-nil, then make sure the
cached token list is up to date.  If a partial reparse is possible, do
that, otherwise, do a full reparse."
  (cond
   ((and semantic-bovinate-toplevel-override
	 ;; We cannot predict partial reparsing for these parsers.  Let them
	 ;; fend for themselves.  We can, however, handle the main cache for them.
	 (or (semantic-bovine-toplevel-partial-reparse-needed-p checkcache)
	     (semantic-bovine-toplevel-full-reparse-needed-p checkcache)))
    (semantic-clear-toplevel-cache)
    ;; Call a custom function
    (let ((res (funcall semantic-bovinate-toplevel-override checkcache)))
      (semantic-set-toplevel-bovine-cache res))
    ;; Check: The below is not needed because of the -set- command above?
    ;;(run-hooks 'semantic-after-toplevel-bovinate-hook)
    semantic-toplevel-bovine-cache
    )
   ((semantic-bovine-toplevel-partial-reparse-needed-p checkcache)
    ;; We have a cache, and some dirty tokens
    (let ((semantic-bovination-working-type 'dynamic))
      (working-status-forms (buffer-name) "done"
	(while (and semantic-dirty-tokens
		    (not (semantic-bovine-toplevel-full-reparse-needed-p
			  checkcache)))
	  (semantic-rebovinate-token (car semantic-dirty-tokens))
	  (setq semantic-dirty-tokens (cdr semantic-dirty-tokens))
	  (working-dynamic-status))
	(working-dynamic-status t))
      (setq semantic-dirty-tokens nil)
      )
    (if (semantic-bovine-toplevel-full-reparse-needed-p checkcache)
	;; If the partial reparse fails, jump to a full reparse.
	(semantic-bovinate-toplevel checkcache)
      semantic-toplevel-bovine-cache)
    )
   ((semantic-bovine-toplevel-full-reparse-needed-p checkcache)
    (semantic-clear-toplevel-cache)
    ;; Reparse the whole system
    (let ((ss (semantic-flex (point-min) (point-max)))
	  (res nil)
	  (semantic-overlay-error-recovery-stack nil))
      ;; Init a dump
      (if semantic-dump-parse (semantic-dump-buffer-init))
      ;; Parse!
      (working-status-forms (buffer-name) "done"
	(setq res
	      (semantic-bovinate-nonterminals
	       ss 'bovine-toplevel semantic-flex-depth))
	(working-status t))
      (semantic-set-toplevel-bovine-cache (nreverse res))
      semantic-toplevel-bovine-cache))
   (t
    ;; We have a cache with stuff in it, so return it
    semantic-toplevel-bovine-cache
    )))

(defun semantic-set-toplevel-bovine-cache (tokenlist)
  "Set the toplevel bovine cache to TOKENLIST."
  (setq semantic-toplevel-bovine-cache tokenlist
	semantic-toplevel-bovine-cache-check nil
	semantic-toplevel-bovine-force-reparse nil
        semantic-bovinate-nonterminal-check-obarray nil)
  (add-hook 'after-change-functions 'semantic-change-function nil t)
  (run-hook-with-args 'semantic-after-toplevel-cache-change-hook
		      semantic-toplevel-bovine-cache)
  ;; Old Semantic 1.3 hook API.  Maybe useful forever?
  (run-hooks 'semantic-after-toplevel-bovinate-hook)
  )

(defun semantic-change-function (start end length)
  "Provide a mechanism for semantic token management.
Argument START, END, and LENGTH specify the bounds of the change."
  (run-hook-with-args 'semantic-change-hooks start end length))

;;; Force token lists in and out of overlay mode.
;;
(defun semantic-deoverlay-token (token)
  "Convert TOKEN from using an overlay to using an overlay proxy."
  (when (semantic-token-p token)
    (let ((c (semantic-token-overlay-cdr token))
	  a)
      (when (and c (semantic-overlay-p (car c)))
	(setq a (vector (semantic-overlay-start (car c))
			(semantic-overlay-end (car c))))
	(semantic-overlay-delete (car c))
	(setcar c a)
	;; Fix the children of this token.
	;; Semantic-util is required and the end of semantic, so this will
	;; throw a warning
	(semantic-deoverlay-list (semantic-nonterminal-children token)))
      )))

(defun semantic-overlay-token (token)
  "Convert TOKEN from using an overlay proxy to using an overlay."
  (when (semantic-token-p token)
    (let ((c (semantic-token-overlay-cdr token))
	  o)
      (when (and c (vectorp (car c)) (= (length (car c)) 2))
	(setq o (semantic-make-overlay (aref (car c) 0)
				       (aref (car c) 1)
				       (current-buffer)))
	(setcar c o)
	(semantic-overlay-put o 'semantic token)
	;; Fix overlays in children of this token
	;; Semantic-util is required and the end of semantic, so this will
	;; throw a warning
	(semantic-overlay-list (semantic-nonterminal-children token))
	))))

(defun semantic-deoverlay-list (l)
  "Remove overlays from the list L."
  (mapcar 'semantic-deoverlay-token l))

(defun semantic-overlay-list (l)
  "Convert numbers to  overlays from the list L."
  (mapcar 'semantic-overlay-token l))

(defun semantic-deoverlay-cache ()
  "Convert all tokens in the current cache to use overlay proxies."
  (semantic-deoverlay-list (semantic-bovinate-toplevel)))

(defun semantic-overlay-cache ()
  "Convert all tokens in the current cache to use overlays."
  (condition-case nil
      ;; In this unique case, we cannot call the usual toplevel fn.
      ;; because we don't want a reparse, we want the old overlays.
      (semantic-overlay-list semantic-toplevel-bovine-cache)
    ;; Recover when there is an error restoring the cache.
    (error (message "Error recovering token list.")
	   (semantic-clear-toplevel-cache)
	   nil)))

;;; Token parsing utilities
;;
(defun semantic-raw-to-cooked-token (token)
  "Convert TOKEN from a raw state to a cooked state.
The parser returns raw tokens with positional data START/END.
We convert it from that to a cooked state with a property list and an overlay.
Change the token with side effects and returns TOKEN."
  (let* ((result nil)
	 (expandedtokens nil)
	 (ncdr (- (length token) 2))
	 (propcdr (if (natnump ncdr) (nthcdr ncdr token)))
	 (overcdr (cdr propcdr))
	 ;; propcdr is the CDR containing the START from the token.
	 ;; overcdr is the CDR containing the END from the token.
	 ;; PROPCDR will contain the property list after cooking.
	 ;; OVERCDR will contain the overlay after cooking.
	 (o (condition-case nil
		(semantic-make-overlay (car propcdr)
				       (car overcdr)
				       (current-buffer)
				       ;; Examin start/rear
				       ;; advance flags.
				       )
	      (error (debug token)
		     nil))))
    ;; Convert START/END into PROPERTIES/OVERLAY.
    (setcar overcdr o)
    (setcar propcdr nil)
    (semantic-overlay-put o 'semantic token)
    ;; Expand based on local configuration
    (if (not semantic-expand-nonterminal)
	;; no expanders
	(setq result (cons token result))
      ;; Glom generated tokens
      (setq expandedtokens (funcall semantic-expand-nonterminal token))
      (if (not expandedtokens)
	  (progn (setq result (cons token result))
		 (semantic-overlay-stack-add o))
	;; Fixup all overlays, start by deleting the old one
	(let ((tokenloop expandedtokens) o start end)
	  (while tokenloop
	    (setq propcdr (nthcdr (- (length (car tokenloop)) 2)
				   (car tokenloop))
		  overcdr (nthcdr (- (length (car tokenloop)) 1)
				   (car tokenloop))
		  ;; this will support new overlays created by
		  ;; the special function, or recycles
		  start (if (semantic-overlay-live-p (car overcdr))
			    (semantic-overlay-start (car overcdr))
			  start)
		  end (if (semantic-overlay-live-p (car overcdr))
			  (semantic-overlay-end (car overcdr))
			end)
		  o (semantic-make-overlay start end
					   (current-buffer)))
	    (if (semantic-overlay-live-p (car overcdr))
		(semantic-overlay-delete (semantic-token-overlay
					  (car tokenloop))))
	    (semantic-overlay-stack-add o)
	    (setcar propcdr nil)
	    (setcar overcdr o)
	    (semantic-overlay-put o 'semantic (car tokenloop))
	    (setq tokenloop (cdr tokenloop))))
	(setq result (append expandedtokens result))))
    result))

(defun semantic-bovinate-nonterminals (stream nonterm &optional
					      depth returnonerror)
  "Bovinate the entire stream STREAM starting with NONTERM.
DEPTH is optional, and defaults to 0.
Optional argument RETURNONERROR indicates that the parser should exit with
the current results on a parse error."
  (if (not depth) (setq depth semantic-flex-depth))
  (let ((result nil) (case-fold-search semantic-case-fold))
    (while stream
      (let* ((nontermsym
	      (semantic-bovinate-nonterminal
	       stream semantic-toplevel-bovine-table nonterm))
	     (stream-overlays (car (cdr (cdr nontermsym))))
	     (token (car (cdr nontermsym))))
	(if (not nontermsym)
	    (error "Parse error @ %d" (car (cdr (car stream)))))
	(semantic-overlay-stack-add stream-overlays)
	(if token
	    (if (car token)
		(progn
		  (setq result (append (semantic-raw-to-cooked-token token)
				       result))
		  ;; Place the nonterm into the token.
		  (if (not (eq nonterm 'bovine-toplevel))
		      (semantic-token-put token 'reparse-symbol nonterm)))
	      ;; No error in this case, a purposeful nil means don't store
	      ;; anything.
	      )
	  (if returnonerror (setq stream nil))
	  ;;(error "Parse error")
	  )
	;; Designated to ignore.
	(setq stream (car nontermsym)))
      (if stream
	  (if (eq semantic-bovination-working-type 'percent)
	      (working-status (floor
			       (* 100.0 (/ (float (car (cdr (car stream))))
					   (float (point-max))))))
	    (working-dynamic-status))))
    result))

(defun semantic-remove-dirty-children-internal (token dirties)
  "Remove TOKEN children from DIRTIES.
Return the new value of DIRTIES."
  (if dirties
      (let ((children (semantic-nonterminal-children token t))
            child)
        (while (and children dirties)
          (setq child (car children)
                children (cdr children)
                dirties  (semantic-remove-dirty-children-internal
                          child (delq child dirties))))))
  dirties)

(defun semantic-remove-dirty-children (token)
  "Remove TOKEN children from the list of dirty tokens.
This must be done before deoverlaying TOKEN.  At this point (when
called by `semantic-rebovinate-token') TOKEN is the first element of
`semantic-dirty-tokens' so only the rest of `semantic-dirty-tokens' is
considered."
  (setq semantic-dirty-tokens
        (cons (car semantic-dirty-tokens)
              (semantic-remove-dirty-children-internal
               token (cdr semantic-dirty-tokens)))))

(defun semantic-rebovinate-token (token)
  "Use TOKEN for extents, and reparse it, splicing it back into the cache."
  (let* ((flexbits (semantic-flex (semantic-token-start token)
				  (semantic-token-end token)))
	 ;; For embeded tokens (type parts, for example) we need a
	 ;; different symbol.  Come up with a plan to solve this.
	 (nonterminal (or (semantic-token-get token 'reparse-symbol)
			  'bovine-toplevel))
	 (new (condition-case nil
                  (semantic-bovinate-nonterminal
                   flexbits
                   semantic-toplevel-bovine-table
                   nonterminal)
                ;; Trap `read' errors which may temporarily occurs
                ;; when re-parsing a dirty Elisp token.
                (end-of-file 'delay)
                (invalid-read-syntax 'delay)))
	 (cooked nil)
	 )
    (if (eq new 'delay)
        ;; If a `read' error occured during re-parsing of an Elisp
        ;; token just delay rebovination.  Thus features like Semantic
        ;; completion could continue to work until a clean syntax
        ;; state is reached and re-parse succeeds.
        nil
      (setq new (car (cdr new)))
      (if (not new)
          ;; Clever reparse failed, queuing full reparse.
          (setq semantic-toplevel-bovine-cache-check t)
        (setq cooked (semantic-raw-to-cooked-token new))
        (if (not (eq new (car cooked)))
            (if (= (length cooked) 1)
                ;; Cooking did a 1 to 1 replacement.  Use it.
                (setq new (car cooked))
	      ;; If cooking results in multiple things, do a full reparse.
              (setq semantic-toplevel-bovine-cache-check t))))
      ;; Don't do much if we have to do a full recheck.
      (if semantic-toplevel-bovine-cache-check
          nil
        (let ((oo (semantic-token-overlay token))
              (o (semantic-token-overlay new)))
          ;; Copy all properties of the old overlay here.
          ;; I think I can use plists in emacs, but not in XEmacs.
          ;; Ack!
          (semantic-overlay-put o 'face (semantic-overlay-get oo 'face))
          (semantic-overlay-put o 'old-face (semantic-overlay-get oo 'old-face))
          (semantic-overlay-put o 'intangible (semantic-overlay-get oo 'intangible))
          (semantic-overlay-put o 'invisible (semantic-overlay-get oo 'invisible))
          ;; Remove TOKEN children from `semantic-dirty-tokens'
          (semantic-remove-dirty-children token)
          ;; Free the old overlay(s)
          (semantic-deoverlay-token token)
          ;; Recover properties
          (let ((p (semantic-token-properties token)))
            (while p
              (semantic-token-put new (car (car p)) (cdr (car p)))
              (setq p (cdr p))))
          (if (not (eq nonterminal 'bovine-toplevel))
              (semantic-token-put new 'reparse-symbol nonterminal))
          (semantic-token-put new 'dirty nil)
          ;; Splice into the main list.
          (setcdr token (cdr new))
          (setcar token (car new))
	  ;; This important bit is because the CONS cell representing TOKEN
	  ;; is what we need here, even though the whole thing is the same.
          (semantic-overlay-put o 'semantic token)
          ;; Hooks
          (run-hook-with-args 'semantic-clean-token-hooks token)
          )
        ))))


;;; Semantic Bovination
;;
;; Take a semantic token stream, and convert it using the bovinator.
;; The bovinator takes a state table, and converts the token stream
;; into a new semantic stream defined by the bovination table.
;;
(defsubst semantic-bovinate-symbol-nonterminal-p (sym table)
  "Return non-nil if SYM is in TABLE, indicating it is NONTERMINAL."
  ;; sym is always a sym, so assq should be ok.
  (if (assq sym table) t nil))

(defmacro semantic-bovinate-nonterminal-db-nt ()
  "Return the current nonterminal symbol.
Part of the BNF source debugger.  Depends on the existing environment
of `semantic-bovinate-nonterminal'."
  `(if nt-stack
       (car (aref (car nt-stack) 2))
     nonterminal))

(defun semantic-bovinate-nonterminal-check (stream nonterminal)
  "Check if STREAM not already parsed for NONTERMINAL.
If so abort because an infinite recursive parse is suspected."
  (or (vectorp semantic-bovinate-nonterminal-check-obarray)
      (setq semantic-bovinate-nonterminal-check-obarray
            (make-vector 13 nil)))
  (let* ((nt (symbol-name nonterminal))
         (vs (symbol-value
              (intern-soft
               nt semantic-bovinate-nonterminal-check-obarray))))
    (if (memq stream vs)
        ;; Always enter debugger to see the backtrace
        (let ((debug-on-signal t)
              (debug-on-error  t))
          (setq semantic-bovinate-nonterminal-check-obarray nil)
          (error "Infinite recursive parse suspected on %s" nt))
      (set (intern nt semantic-bovinate-nonterminal-check-obarray)
           (cons stream vs)))))

(defun semantic-bovinate-nonterminal (stream table &optional nonterminal)
  "Bovinate STREAM based on the TABLE of nonterminal symbols.
Optional argument NONTERMINAL is the nonterminal symbol to start with.
Use `bovine-toplevel' if it is not provided.
This is the core routine for converting a stream into a table.
Return the list (STREAM SEMANTIC-STREAM OVERLAYS) where STREAM are those
elements of STREAM that have not been used.  SEMANTIC-STREAM is the
list of semantic tokens found.  OVERLAYS is the list of overlays found
so far, to be used in the error recovery stack."
  (if (not nonterminal)
      (setq nonterminal 'bovine-toplevel))

  ;; Try to detect infinite recursive parse when doing a full reparse.
  (or semantic-toplevel-bovine-cache
      (semantic-bovinate-nonterminal-check stream nonterminal))

  (let ((matchlist (cdr (assq nonterminal table)))
	(starting-stream stream)
        (nt-loop  t)             ;non-terminal loop condition
        nt-popup                 ;non-nil if return from nt recursion
        nt-stack                 ;non-terminal recursion stack
        s                        ;Temp Stream Tracker
        lse                      ;Local Semantic Element
        lte                      ;Local matchlist element
        tev                      ;Matchlist entry values from buffer
        val                      ;Value found in buffer.
        cvl                      ;collected values list.
        out                      ;Output
        end                      ;End of match
        result
        semantic-overlay-error-recovery-stack ;part of error recovery
        )
    (while nt-loop
      (catch 'push-non-terminal
        (setq semantic-overlay-error-recovery-stack nil
              nt-popup nil
              end (cdr (cdr (car stream))))
        (while (or nt-loop nt-popup)
          (setq nt-loop nil
                out     nil)
          (while (or nt-popup matchlist)
            (if nt-popup
                ;; End of a non-terminal recursion
                (setq nt-popup nil)
              ;; New matching process
              (setq s   stream           ;init s from stream.
                    cvl nil              ;re-init the collected value list.
                    lte (car matchlist)  ;Get the local matchlist entry.
                    )
              (if (or (byte-code-function-p (car lte))
                      (listp (car lte)))
                  ;; In this case, we have an EMPTY match!  Make stuff
                  ;; up.
                  (setq cvl (list nil))))
            
            (while (and lte
                        (not (byte-code-function-p (car lte)))
                        (not (listp (car lte))))

              ;; BNF SOURCE DEBUGGING!
              (if semantic-edebug
                  (let* ((db-nt   (semantic-bovinate-nonterminal-db-nt))
                         (db-ml   (cdr (assq db-nt table)))
                         (db-mlen (length db-ml))
                         (db-midx (- db-mlen (length matchlist)))
                         (db-tlen (length (nth db-midx db-ml)))
                         (db-tidx (- db-tlen (length lte))))
                    (if (eq 'fail
                            (semantic-bovinate-show
                             (car s) db-nt db-midx db-tidx cvl))
                        (setq lte '(trash 0 . 0)))))
              ;; END BNF SOURCE DEBUGGING!
              
              (cond
               ;; We have a nonterminal symbol.  Recurse inline.
               ((setq nt-loop (assq (car lte) table))
          
                (setq
                 ;; push state into the nt-stack
                 nt-stack (cons (vector matchlist cvl lte stream end
                                        ;; error recovery
                                        semantic-overlay-error-recovery-stack
                                        )
                                nt-stack)
                 ;; new non-terminal matchlist
                 matchlist   (cdr nt-loop)
                 ;; new non-terminal stream
                 stream      s)
               
                (throw 'push-non-terminal t)

                )
               ;; Default case
               (t
                (setq lse (car s)       ;Get the local stream element
                      s   (cdr s))      ;update stream.
                ;; Do the compare
                (if (eq (car lte) (car lse)) ;syntactic match
                    (let ((valdot (cdr lse)))
                      (setq val (semantic-flex-text lse))
                      ;; DEBUG SECTION
                      (if semantic-dump-parse
                          (semantic-dump-detail
                           (if (stringp (car (cdr lte)))
                               (list (car (cdr lte)) (car lte))
                             (list (car lte)))
                           (semantic-bovinate-nonterminal-db-nt)
                           val
                           (if (stringp (car (cdr lte)))
                               (if (string-match (car (cdr lte)) val)
                                   "Term Match" "Term Fail")
                             "Term Type=")))
                      ;; END DEBUG SECTION
                      (setq lte (cdr lte))
                      (if (stringp (car lte))
                          (progn
                            (setq tev (car lte)
                                  lte (cdr lte))
                            (if (string-match tev val)
                                (setq cvl (cons
                                           (if (memq (car lse)
                                                     '(comment semantic-list))
                                               valdot val)
                                           cvl)) ;append this value
                              (semantic-overlay-stack-clear)
                              (setq lte nil cvl nil))) ;clear the entry (exit)
                        (setq cvl (cons
                                   (if (memq (car lse)
                                             '(comment semantic-list))
                                       valdot val) cvl))) ;append unchecked value.
                      (setq end (cdr (cdr lse)))
                      )
                  (if (and semantic-dump-parse nil)
                      (semantic-dump-detail (car lte)
                                            (semantic-bovinate-nonterminal-db-nt)
                                            (semantic-flex-text lse)
                                            "Term Type Fail"))
                  (semantic-overlay-stack-clear)
                  (setq lte nil cvl nil)) ;No more matches, exit
                )))
            (if (not cvl)               ;lte=nil;  there was no match.
                (setq matchlist (cdr matchlist)) ;Move to next matchlist entry
              (let ((start (car (cdr (car stream)))))
                (setq out (cond
                           ((car lte)
                        
                            ;; REMOVE THIS TO USE THE REFERENCE/COMPARE CODE
                            ;;(let ((o (apply (car lte) ;call matchlist fn on values
                            ;;                (nreverse cvl) start (list end))))
                            ;;  (if semantic-bovinate-create-reference
                            ;;      (semantic-bovinate-add-reference o))
                            ;;  (if semantic-bovinate-compare-reference
                            ;;      (semantic-bovinate-compare-against-reference o))
                            ;;  o
                            ;;  )
                            
                            (funcall (car lte) ;call matchlist fn on values
                                     (nreverse cvl) start end))
                           ((and (= (length cvl) 1)
                                 (listp (car cvl))
                                 (not (numberp (car (car cvl)))))
                            (append (car cvl) (list start end)))
                           (t
                            ;;(append (nreverse cvl) (list start end))))
                            ;; MAYBE THE FOLLOWING NEEDS LESS CONS
                            ;; CELLS THAN THE ABOVE?
                            (nreverse (cons end (cons start cvl)))))
                      matchlist nil) ;;generate exit condition
                (if (not end)
                    (setq out nil)))
              ;; Nothin?
              ))
	  (setq result
		(if (eq s starting-stream)
		    (list (cdr s) nil
			  semantic-overlay-error-recovery-stack)
		  (list s out
			semantic-overlay-error-recovery-stack)))
          (if nt-stack
              ;; pop previous state from the nt-stack
              (let ((state (car nt-stack))
                    (ov semantic-overlay-error-recovery-stack))

                (setq nt-popup    t
                      ;; pop actual parser state
                      matchlist   (aref state 0)
                      cvl         (aref state 1)
                      lte         (aref state 2)
                      stream      (aref state 3)
                      end         (aref state 4)
                      ;; pop error recovery state
                      semantic-overlay-error-recovery-stack (aref state 5)
                      ;; update the stack
                      nt-stack    (cdr nt-stack))
                
                (if ov
                    (semantic-overlay-stack-add ov))
                
                (if out
                    (let ((len (length out))
                          (strip (nreverse (cdr (cdr (reverse out))))))
                      (if semantic-dump-parse
                          (semantic-dump-detail (cdr result)
                                                (car lte)
                                                ""
                                                "NonTerm Match"))
                      (setq end (nth (1- len) out) ;reset end to the end of exp
                            cvl (cons strip cvl) ;prepend value of exp
                            lte (cdr lte)) ;update the local table entry
                      )
                  ;; No value means that we need to terminate this
                  ;; match.
                  (semantic-overlay-stack-clear)
                  (setq lte nil cvl nil)) ;No match, exit
                )))))
    result))


;;; Bovine table functions
;;
;; These are functions that can be called from within a bovine table.
;; Most of these have code auto-generated from other construct in the BNF.
(defmacro semantic-lambda (&rest return-val)
  "Create a lambda expression to return a list including RETURN-VAL.
The return list is a lambda expression to be used in a bovine table."
  `(lambda (vals start end)
     (append ,@return-val (list start end))))

(defun semantic-bovinate-from-nonterminal (start end nonterm
						 &optional depth length)
  "Bovinate from within a nonterminal lambda from START to END.
Depends on the existing environment created by `semantic-bovinate-stream'.
Argument NONTERM is the nonterminal symbol to start with.
Optional argument DEPTH is the depth of lists to dive into.
Whan used in a `lambda' of a MATCH-LIST, there is no need to include
a START and END part.
Optional argument LENGTH specifies we are only interested in LENGTH tokens."
  (car-safe (cdr (semantic-bovinate-nonterminal
		  (semantic-flex start end (or depth 1) length)
		  ;; the byte compiler will complain about TABLE
		  table
		  nonterm))))

(defun semantic-bovinate-from-nonterminal-full (start end nonterm
						      &optional depth)
  "Bovinate from within a nonterminal lambda from START to END.
Iterates until all the space between START and END is exhausted.
Depends on the existing environment created by `semantic-bovinate-stream'.
Argument NONTERM is the nonterminal symbol to start with.
If NONTERM is nil, use `bovine-block-toplevel'.
Optional argument DEPTH is the depth of lists to dive into.
Whan used in a `lambda' of a MATCH-LIST, there is no need to include
a START and END part."
  (nreverse
   (semantic-bovinate-nonterminals (semantic-flex start end (or depth 1))
				   nonterm
				   depth)))

(defun semantic-bovinate-region-until-error (start end nonterm &optional depth)
  "Bovinate between START and END starting with NONTERM.
Optinal DEPTH specifies how many levels of parenthesis to enter.
This command will parse until an error is encountered, and return
the list of everything found until that moment.
This is meant for finding variable definitions at the beginning of
code blocks in methods.  If `bovine-inner-scope' can also support
commands, use `semantic-bovinate-from-nonterminal-full'."
  (nreverse
   (semantic-bovinate-nonterminals (semantic-flex start end depth)
				   nonterm
				   depth
				   ;; This says stop on an error.
				   t)))

(defun semantic-bovinate-make-assoc-list (&rest args)
  "Create an association list with ARGS.
Args are of the form (KEY1 VALUE1 ... KEYN VALUEN).
The return value will be of the form: ((KEY1 .  VALUE1) ... (KEYN . VALUEN))
Where KEY is a symbol, and VALUE is the value for that symbol.
If VALUE is nil, then KEY is excluded from the return association list."
  (let ((ret nil))
    (while args
      (let ((value (car-safe (cdr args))))
	(if (and value
		 (or (not (stringp value))
		     (not (string= value "")))
		 (or (not (numberp value))
		     (not (= value 0))))
	    (setq ret (cons (cons (car args) (car (cdr args))) ret)))
	(setq args (cdr (cdr args)))))
    (nreverse ret)))

;;; Debugging in bovine tables
;;
(defun semantic-dump-buffer-init ()
  "Initialize the semantic dump buffer."
  (save-excursion
    (let ((obn (buffer-name)))
      (set-buffer (get-buffer-create "*Semantic Dump*"))
      (erase-buffer)
      (insert "Parse dump of " obn "\n\n")
      (insert (format "%-15s %-15s %10s %s\n\n"
		      "Nonterm" "Comment" "Text" "Context"))
      )))

(defun semantic-dump-detail (lse nonterminal text comment)
  "Dump info about this match.
Argument LSE is the current syntactic element.
Argument NONTERMINAL is the nonterminal matched.
Argument TEXT is the text to match.
Argument COMMENT is additional description."
  (save-excursion
    (set-buffer "*Semantic Dump*")
    (goto-char (point-max))
    (insert (format "%-15S %-15s %10s %S\n" nonterminal comment text lse)))
  )

(defvar semantic-bovinate-debug-table nil
  "A marker where the current table we are debugging is.")

(defun semantic-bovinate-debug-set-table ()
  "Set the table for the next debug to be here."
  (interactive)
  (if (not (eq major-mode 'emacs-lisp-mode))
      (error "Not an Emacs Lisp file"))
  (beginning-of-defun)
  (setq semantic-bovinate-debug-table (point-marker)))

;; We will get warnings in here about semantic-bnf-* fns.
;; We cannot require semantic-bnf due to compile eerrors.
(defun semantic-bovinate-debug-buffer ()
  "Bovinate the current buffer in debug mode."
  (interactive)
  (if (and (not semantic-toplevel-bovine-table-source)
	   (not semantic-bovinate-debug-table))
      (error
       "Call `semantic-bovinate-debug-set-table' from your semantic table"))
  (delete-other-windows)
  (split-window-vertically)
  (if semantic-bovinate-debug-table
      (switch-to-buffer (marker-buffer semantic-bovinate-debug-table))
    (if (not semantic-toplevel-bovine-table-source)
        (error "No debuggable BNF source found"))
    (require 'semantic-bnf)
    (switch-to-buffer (semantic-bnf-find-source-on-load-path
                       semantic-toplevel-bovine-table-source)))
  (other-window 1)
  (semantic-clear-toplevel-cache)
  (let ((semantic-edebug t))
    (semantic-bovinate-toplevel)))

(defun semantic-bovinate-show (lse nonterminal matchlen tokenlen collection)
  "Display some info about the current parse.
Returns 'fail if the user quits, nil otherwise.
LSE is the current listed syntax element.
NONTERMINAL is the current nonterminal being parsed.
MATCHLEN is the number of match lists tried.
TOKENLEN is the number of match tokens tried.
COLLECTION is the list of things collected so far."
  (let* ((semantic-edebug nil)
         (ol1 nil) (ol2 nil) (ret nil)
         (bnf-buffer (semantic-bnf-find-source-on-load-path
                      semantic-toplevel-bovine-table-source)))
    (unwind-protect
	(progn
	  (goto-char (car (cdr lse)))
	  (setq ol1 (semantic-make-overlay (car (cdr lse)) (cdr (cdr lse))))
	  (semantic-overlay-put ol1 'face 'highlight)
	  (goto-char (car (cdr lse)))
	  (if window-system nil (sit-for 1))
	  (other-window 1)
	  (let (s e)
	    (if semantic-bovinate-debug-table
		(progn
		  (set-buffer (marker-buffer semantic-bovinate-debug-table))
		  (goto-char semantic-bovinate-debug-table)
		  (re-search-forward
		   (concat "^\\s-*\\((\\|['`]((\\)\\(" (symbol-name nonterminal)
			   "\\)[ \t\n]+(")
		   nil t)
		  (setq s (match-beginning 2)
			e (match-end 2))
		  (forward-char -2)
		  (forward-list matchlen)
		  (skip-chars-forward " \t\n(")
		  (forward-sexp tokenlen)
		  )
	      ;; The user didn't specify a lisp level table.
	      ;; go to the source...
	      (set-buffer bnf-buffer)
	      (semantic-bnf-find-state-position
	       nonterminal matchlen tokenlen)
	      (save-excursion
		(goto-char (semantic-token-start (semantic-current-nonterminal)))
		(setq s (point)
		      e (progn (forward-sexp 1) (point))))
	      )
	    (setq ol2 (semantic-make-overlay s e))
	    (semantic-overlay-put ol2 'face 'highlight)
	    )
	  (message "%s: %S" lse collection)
	  (let ((e (semantic-read-event)))
	    (cond ((eq e ?f)		;force a failure on this symbol.
		   (setq ret 'fail))
		  (t nil)))
	  (other-window 1)
	  )
      (semantic-overlay-delete ol1)
      (semantic-overlay-delete ol2))
    ret))

;;; Reference Debugging
;;
(defvar semantic-bovinate-create-reference nil
  "Non nil to create a reference.")

(defvar semantic-bovinate-reference-token-list nil
  "A list generated as a referece (assumed valid).
A second pass comares return values against this list.")

(defun semantic-bovinate-add-reference (ref)
  "Add REF to the reference list."
  (setq semantic-bovinate-reference-token-list
	(cons ref semantic-bovinate-reference-token-list)))

(defvar semantic-bovinate-compare-reference nil
  "Non nil to compare against a reference list.")

(defvar semantic-bovinate-reference-temp-list nil
  "List used when doing a compare.")

(defun semantic-bovinate-compare-against-reference (ref)
  "Compare REF against what was returned last time."
  (if (not (equal ref (car semantic-bovinate-reference-temp-list)))
      (let ((debug-on-error t))
	(error "Stop: %d %S != %S"
	       (- (length semantic-bovinate-reference-token-list)
		  (length semantic-bovinate-reference-temp-list))
	       (car semantic-bovinate-reference-temp-list)
	       ref))
    (setq semantic-bovinate-reference-temp-list
	  (cdr semantic-bovinate-reference-temp-list))))
	   
(defun bovinate-create-reference ()
  "Create a reference list."
  (interactive)
  (condition-case nil
      (progn
	(semantic-clear-toplevel-cache)
	(setq semantic-bovinate-create-reference t
	      semantic-bovinate-reference-token-list nil)
	(bovinate)
	(setq semantic-bovinate-reference-token-list
	      (nreverse semantic-bovinate-reference-token-list)))
    (error nil))
  (setq semantic-bovinate-create-reference nil))

(defun bovinate-reference-compare ()
  "Compare the current parsed output to the reference list.
Create a reference with `bovinate-create-reference'."
  (interactive)
  (let ((semantic-bovinate-compare-reference t))
    (semantic-clear-toplevel-cache)
    (setq semantic-bovinate-reference-temp-list
	  semantic-bovinate-reference-token-list)
    (bovinate)))


;;; Semantic Flexing
;;
;; This is a simple scanner which uses the syntax table to generate
;; a stream of simple tokens.
;;
;; A flex element is of the form:
;;  (SYMBOL START . END)
;; Where symbol is the type of thing it is.  START and END mark that
;; objects boundary.

(eval-and-compile (if (not (fboundp 'with-syntax-table))

;; Copied from Emacs 21 for compatibility with released Emacses.
(defmacro with-syntax-table (table &rest body)
  "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
The syntax table of the current buffer is saved, BODY is evaluated, and the
saved table is restored, even in case of an abnormal exit.
Value is what BODY returns."
  (let ((old-table (make-symbol "table"))
	(old-buffer (make-symbol "buffer")))
    `(let ((,old-table (syntax-table))
	   (,old-buffer (current-buffer)))
       (unwind-protect
	   (progn
	     (set-syntax-table (copy-syntax-table ,table))
	     ,@body)
	 (save-current-buffer
	   (set-buffer ,old-buffer)
	   (set-syntax-table ,old-table))))))

))

;;; Keyword Table Handling.
;;
(defvar semantic-flex-keywords-obarray nil
  "Buffer local keyword obarray for the lexical analyzer.
These keywords are matched explicitly, and converted into special symbols.")
(make-variable-buffer-local 'semantic-flex-keywords-obarray)

(defun semantic-flex-make-keyword-table (keywords &optional propertyalist)
  "Convert a list of KEYWORDS into an obarray.
Save the obarry into `semantic-flex-keywords-obarray'.
If optional argument PROPERTYALIST is non nil, then interpret it, and
apply those properties"
  ;; Create the symbol hash table
  (let ((obarray (make-vector 13 nil)))
    ;; fill it with stuff
    (while keywords
      (set (intern (car (car keywords)) obarray)
	   (cdr (car keywords)))
      (setq keywords (cdr keywords)))
    ;; Apply all properties
    (let ((semantic-flex-keywords-obarray obarray))
      (while propertyalist
	(semantic-flex-keyword-put (car (car propertyalist))
				   (nth 1 (car propertyalist))
				   (nth 2 (car propertyalist)))
	(setq propertyalist (cdr propertyalist))))
    obarray))

(defun semantic-flex-keyword-p (text)
  "Return a symbol if TEXT is a keyword in the keyword table.
Return nil if TEXT is not in the symbol table."
  (let ((sym (intern-soft text semantic-flex-keywords-obarray)))
    (if sym (symbol-value sym))))

(defun semantic-flex-keyword-put (text property value)
  "For keyword TEXT, set PROPERTY to have VALUE."
  (let ((sym (intern-soft text semantic-flex-keywords-obarray)))
    (if (not sym) (signal 'wrong-type-argument (list text 'keyword)))
    (put sym property value)))

(defun semantic-flex-keyword-get (text property)
  "For keyword TEXT, get the value of PROPERTY."
  (let ((sym (intern-soft text semantic-flex-keywords-obarray)))
    (if (not sym) (signal 'wrong-type-argument (list text 'keyword)))
    (get sym property)))

;; David Ponce
(defun semantic-flex-map-keywords (fun &optional property)
  "Call function FUN on every semantic keyword.
If optional PROPERTY is non-nil call FUN only on every keyword which
have a PROPERTY value.  FUN receives a semantic keyword as argument."
  (if (arrayp semantic-flex-keywords-obarray)
      (mapatoms
       (function
        (lambda (keyword)
          (and keyword
               (or (null property) (get keyword property))
               (funcall fun keyword))))
       semantic-flex-keywords-obarray)))

;; David Ponce
(defun semantic-flex-keywords (&optional property)
  "Return a list of semantic keywords.
If optional PROPERTY is non-nil return only keyword which have a
PROPERTY value."
  (let (keywords)
    (semantic-flex-map-keywords
     (function
      (lambda (keyword)
        (setq keywords (cons keyword keywords))))
     property)
    keywords))

;;; Lexical Analysis
;;
(defvar semantic-flex-extensions nil
  "Buffer local extensions to the lexical analyzer.
This should contain an alist with a key of a regex and a data element of
a function.  The function should both move point, and return a lexical
token of the form:
  ( TYPE START .  END)
nil is also a valid return.
TYPE can be any type of symbol, as long as it doesn't occur as a
nonterminal in the language definition.")
(make-variable-buffer-local 'semantic-flex-extensions)

(defvar semantic-flex-syntax-modifications nil
  "Updates to the syntax table for this buffer.
These changes are active only while this file is being flexed.
This is a list where each element is of the form:
  (CHAR CLASS)
Where CHAR is the char passed to `modify-syntax-entry',
and CLASS is the string also passed to `modify-syntax-entry' to define
what class of syntax CHAR is.")
(make-variable-buffer-local 'semantic-flex-syntax-modifications)

(defvar semantic-flex-enable-newlines nil
  "When flexing, report 'newlines as syntactic elements.
Useful for languages where the newline is a special case terminator.
Only set this on a per mode basis, not globally.")
(make-variable-buffer-local 'semantic-flex-enable-newlines)

(defun semantic-flex-buffer (&optional depth)
  "Sematically flex the current buffer.
Optional argument DEPTH is the depth to scan into lists."
  (semantic-flex (point-min) (point-max) depth))

(defun semantic-flex (start end &optional depth length)
  "Using the syntax table, do something roughly equivalent to flex.
Semantically check between START and END.  Optional argument DEPTH
indicates at what level to scan over entire lists.
The return value is a token stream.  Each element being a list, such
as (symbol start-expression .  end-expresssion).
END does not mark the end of text scanned, only the end of the beginning
of text scanned.  Thus, if a string extended past END, the end of the
return token will be larger than END.  To truly restrict scanning, using
narrow-to-region'.
The last argument, LENGTH specifies that `semantic-flex' should only return
LENGTH tokens."
  ;(message "Flexing muscles...")
  (if (not semantic-flex-keywords-obarray)
      (setq semantic-flex-keywords-obarray [ nil ]))
  (let ((ts nil)
	(sym nil)
	(pos (point))
	(ep nil)
	(curdepth 0)
	(cs (if comment-start-skip
		(concat "\\(\\s<\\|" comment-start-skip "\\)")
	      (concat "\\(\\s<\\)")))
	(newsyntax (copy-syntax-table (syntax-table)))
	(mods semantic-flex-syntax-modifications)
	;; Use the default depth if it is not specified.
	(depth (or depth semantic-flex-depth)))
    ;; Update the syntax table
    (while mods
      (modify-syntax-entry (car (car mods)) (car (cdr (car mods))) newsyntax)
      (setq mods (cdr mods)))
    (with-syntax-table newsyntax
      (goto-char start)
      (while (and (< (point) end) (or (not length) (<= (length ts) length)))
	(cond (;; catch newlines when needed
	       (and semantic-flex-enable-newlines
		    (looking-at "\\s-*\\(\n\\)"))
	       (setq ep (match-end 1)
		     ts (cons (cons 'newline
				    (cons (match-beginning 1) ep))
			      ts)))
	      ;; special extentions, sometimes includes some whitespace.
	      ((and semantic-flex-extensions
		    (let ((fe semantic-flex-extensions)
			  (r nil))
		      (while fe
			(if (looking-at (car (car fe)))
			    (setq ts (cons (funcall (cdr (car fe))) ts)
				  r t
				  fe nil
				  ep (point)))
			(setq fe (cdr fe)))
		      (if (and r (not (car ts))) (setq ts (cdr ts)))
		      r)))
	      ;; comment end is also EOL for some languages.
	      ((looking-at "\\(\\s-\\|\\s>\\)+"))
	      ;; symbols
	      ((looking-at "\\(\\sw\\|\\s_\\)+")
	       (setq ts (cons (cons
			       ;; Get info on if this is a keyword or not
			       (or (semantic-flex-keyword-p (match-string 0))
				   'symbol)
			       (cons (match-beginning 0) (match-end 0)))
			      ts)))
	      ;; Character quoting characters (ie, \n as newline)
	      ((looking-at "\\s\\+")
	       (setq ts (cons (cons 'charquote
				    (cons (match-beginning 0) (match-end 0)))
			      ts)))
	      ;; Open parens, or semantic-lists.
	      ((looking-at "\\s(")
	       (if (or (not depth) (< curdepth depth))
		   (progn
		     (setq curdepth (1+ curdepth))
		     (setq ts (cons (cons 'open-paren
					  (cons (match-beginning 0) (match-end 0)))
				    ts)))
		 (setq ts (cons
			   (cons 'semantic-list
				 (cons (match-beginning 0)
				       (save-excursion
					 (condition-case nil
					     (forward-list 1)
					   ;; This case makes flex robust
					   ;; to broken lists.
					   (error (goto-char end)))
					 (setq ep (point)))))
				ts))))
	      ;; Close parens
	      ((looking-at "\\s)")
	       (setq ts (cons (cons 'close-paren
				    (cons (match-beginning 0) (match-end 0)))
			      ts))
	       (setq curdepth (1- curdepth)))
	      ;; String initiators
	      ((looking-at "\\s\"")
	       ;; Zing to the end of this string.
	       (setq ts (cons (cons 'string
				    (cons (match-beginning 0)
					  (save-excursion
					    (forward-sexp 1)
					    (setq ep (point)))))
			      ts)))
	      ((looking-at cs)
	       (if semantic-ignore-comments
		   ;; If the language doesn't deal with comments,
		   ;; ignore them here.
		   (let ((comment-start-point (point)))
		     (forward-comment 1)
		     (if (eq (point) comment-start-point)
			 ;; In this case our start-skip string failed
			 ;; to work properly.  Lets try and move over
			 ;; whatever white space we matched to begin
			 ;; with.
			 (skip-syntax-forward "-.'"
					      (save-excursion
						(end-of-line)
						(point)))
		       (forward-comment 1))
		     (if (eq (point) comment-start-point)
			 (error "Strange comment syntax prevents lexical analysis"))
		     (setq ep (point)))
		 ;; Language wants comments, link them together.
		 (if (eq (car (car ts)) 'comment)
		     (setcdr (cdr (car ts)) (save-excursion
					      (forward-comment 1)
					      (setq ep (point))))
		   (setq ts (cons (cons 'comment
					(cons (match-beginning 0)
					      (save-excursion
						(forward-comment 1)
						(setq ep (point)))))
				  ts)))))
	      ((looking-at "\\(\\s.\\|\\s$\\|\\s'\\)")
	       (setq ts (cons (cons 'punctuation
				    (cons (match-beginning 0) (match-end 0)))
			      ts)))
	      (t (error "What is that?")))
	(goto-char (or ep (match-end 0)))
	(setq ep nil)))
    (goto-char pos)
    ;(message "Flexing muscles...done")
    (nreverse ts)))

(defun semantic-flex-text (semobj)
  "Fetch the text associated with the semantic object SEMOBJ."
  (buffer-substring-no-properties (car (cdr semobj)) (cdr (cdr semobj))))

(defun semantic-flex-list (semlist depth)
  "Flex the body of SEMLIST to DEPTH."
  (semantic-flex (car (cdr semlist)) (cdr (cdr semlist)) depth))

(defun semantic-flex-start (semobj)
  "Fetch the start position of the semantic object SEMOBJ."
  (nth 1 semobj))

(defun semantic-flex-end (semobj)
  "Fetch the end position of the semantic object SEMOBJ."
  (cdr (cdr semobj)))

;;; Settings and autoloads
;;
(autoload 'semantic-create-imenu-index "semantic-imenu"
  "Create an imenu index for any buffer which supports Semantic.")
(autoload 'senator-minor-mode "senator"
  "Minor mode for the SEmantic NAvigaTOR." t)
(autoload 'global-semanticdb-minor-mode "semanticdb"
  "Mode saving token lists between sessions." t)

(provide 'semantic)

;;; semantic.el ends here

;; Semantic-util is a part of the semantic API.  Include it last
;; because it depends on semantic.
(require 'semantic-util)
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.