Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: f3bec1ff4f951461395b153ba32d8b8231ec4a6c (plain)
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
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  Compiles rater XML into JavaScript

  Copyright (C) 2016 LoVullo Associates, Inc.

    This file is part of TAME.

    TAME 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 3 of the License, or
    (at your option) any later version.

    This program 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 this program.  If not, see
    <http://www.gnu.org/licenses/>.

  This stylesheet should be included by whatever is doing the processing and is
  responsible for outputting the generated code in whatever manner is
  appropriate (inline JS, a file, etc).
-->
<stylesheet version="2.0"
            xmlns="http://www.w3.org/1999/XSL/Transform"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:lv="http://www.lovullo.com/rater"
            xmlns:lvp="http://www.lovullo.com"
            xmlns:c="http://www.lovullo.com/calc"
            xmlns:w="http://www.lovullo.com/rater/worksheet"
            xmlns:wc="http://www.lovullo.com/rater/worksheet/compiler"
            xmlns:compiler="http://www.lovullo.com/rater/compiler"
            xmlns:calc-compiler="http://www.lovullo.com/calc/compiler"
            xmlns:preproc="http://www.lovullo.com/rater/preproc"
            xmlns:util="http://www.lovullo.com/util"
            xmlns:ext="http://www.lovullo.com/ext">


<!-- calculation compiler -->
<include href="js-calc.xsl" />

<!-- rating worksheet definition compiler -->
<include href="worksheet.xsl" />

<!-- newline -->
<variable name="compiler:nl" select="'&#10;'" />


<!--
  Generates rater function

  The rater is a single function that may be invoked with a key-value argument
  list and will return a variety of data, including the final premium.

  @param NodeSet pkgs all packages, including rater

  @return compiled JS
-->
<template match="lv:package" mode="compiler:entry">
  <!-- enclose everything in a self-executing function to sandbox our data -->
  <text>( function() { </text>
    <!-- to store debug information for equations (we have to put this out here
         so that functions also have access to it...yes, it's stateful, yes it's
         bullshit, but oh well) -->
    <text>var debug = {};</text>
    <text>var consts = {};</text>
    <text>var params = {};</text>
    <text>var types = {};</text>
    <text>var meta = {};</text>
    <!--
    <value-of select="$compiler:nl" />
    <apply-templates
      select="root(.)//lv:const[ .//lv:item or preproc:iou ]"
      mode="compile" />
    -->

</template>


<template match="lv:package" mode="compiler:entry-rater">
    <!-- the rater itself -->
    <value-of select="$compiler:nl" />
    <text>function rater( arglist, _canterm ) {</text>
      <text>_canterm = ( _canterm == undefined ) ? true : !!_canterm;</text>

      <!-- XXX: fix; clear debug from any previous runs -->
      <text>debug = {};</text>

      <!-- magic constants (N.B. these ones must be re-calculated with each
           call, otherwise the data may be incorrect!) -->
      <value-of select="$compiler:nl" />

      <!-- XXX: Remove this; shouldn't be magic -->
      <text>consts['__DATE_YEAR__'] = ( new Date() ).getFullYear(); </text>

      <!-- clone the object so as not to modify the one that was passed
           (ES5 feature); also adds constants -->
      <text>var args = Object.create( arglist );</text>

      <!-- will store the global params that we ended up requiring -->
      <text>var req_params = {};</text>

      <!-- handle defaults -->
      <text>init_defaults( args, params );</text>

      <!-- perform classifications -->
      <value-of select="$compiler:nl" />
      <text>var classes = rater.classify( args, _canterm );</text>
      <!-- for @external generated clases -->
      <text>var genclasses = {};</text>
</template>

<template match="lv:package" mode="compiler:entry-classifier">
  <!-- allow classification of any arbitrary dataset -->
  <value-of select="$compiler:nl" />
  <text>rater.classify = function( args, _canterm ) {</text>
    <text>_canterm = ( _canterm == undefined ) ? true : !!_canterm;</text>

    <!-- XXX: Remove this; shouldn't be magic -->
    <text>consts['__DATE_YEAR__'] = ( new Date() ).getFullYear(); </text>

    <!-- object into which all classifications will be stored -->
    <text>var classes = {}, genclasses = {}; </text>

    <!-- TODO: We need to do something with this... -->
    <text>var req_params = {}; </text>
</template>

<template match="lv:package" mode="compiler:exit-classifier">
    <text>return classes;</text>
  <text> };</text>

  <!-- TODO: make sure fromMap has actually been compiled -->
  <text>rater.classify.fromMap = function( args_base, _canterm ) { </text>
    <text>var ret = {}; </text>
    <text>rater.fromMap( args_base, function( args ) {</text>
      <text>var classes = rater.classify( args, _canterm ); </text>

      <text>
        for ( var c in classes )
        {
          ret[ c ] = {
            is: !!classes[ c ],
            indexes: args[ rater.classify.classmap[ c ] ]
          };
        }
      </text>
    <text>} );</text>
    <text>return ret;</text>
  <text> }; </text>
</template>

<template match="lv:package" mode="compiler:exit-rater">
  <param name="symbols" as="element( preproc:sym )*" />

      <value-of select="$compiler:nl" />
      <text>return { </text>
        <!-- round the premium (special symbol ___yield) to max of 2 decimal places -->
        <text>premium: ( Math.round( args.___yield * 100 ) / 100 ), </text>
        <text>classes: classes, </text>
        <text>vars: args, </text>
        <text>consts: consts, </text>
        <text>reqParams: req_params, </text>
        <text>debug: debug </text>
      <text>}; </text>
    <text>}</text>

    <!-- make the name of the supplier available -->
    <text>rater.supplier = '</text>
      <value-of select="substring-after( @name, '/' )" />
    <text>'; </text>

    <text>rater.meta = meta;</text>

    <!-- provide classification -> yields mapping -->
    <value-of select="$compiler:nl" />
    <text>rater.classify.classmap = { </text>
      <apply-templates select="." mode="compiler:classifier-yields-map">
        <with-param name="symbols" select="$symbols" />
      </apply-templates>
    <text> }; </text>

    <!-- provide classification descriptions -->
    <value-of select="$compiler:nl" />
    <text>rater.classify.desc = { </text>
    <sequence select="
        compiler:class-desc(
          $symbols[ @type='class' ] )" />
    <text> }; </text>

    <variable name="mapfrom" select="
        preproc:symtable/preproc:sym[
          @type='map'
        ]/preproc:from[
          not(
            @name = parent::preproc:sym
              /preceding-sibling::preproc:sym[
                @type='map'
              ]/preproc:from/@name
          )
        ]
      " />

    <!-- mapped fields (external names) -->
    <text>rater.knownFields = {</text>
      <for-each select="$mapfrom">
        <if test="position() > 1">
          <text>, </text>
        </if>

        <text>'</text>
          <value-of select="@name" />
        <text>': true</text>
      </for-each>
    <text>}</text>

    <!-- common stuff -->
    <call-template name="compiler:static" />

    <!-- the rater has been generated; return it -->
    <text>return rater;</text>
  <text>} )()</text>
</template>


<template match="lv:package" mode="compiler:classifier-yields-map">
  <param name="symbols" />

  <!-- for each cgen symbol (which is the classification @yields), map the
       classification name (the @parent) to the cgen symbol name -->
  <for-each select="$symbols[ @type='cgen' ]">
    <if test="position() > 1">
      <text>,</text>
    </if>

    <text>'</text>
      <value-of select="substring-after( @parent, ':class:' )" />
    <text>':'</text>
      <value-of select="@name" />
    <text>'</text>
  </for-each>
</template>


<function name="compiler:class-desc">
  <param name="syms" as="element( preproc:sym )*" />

  <for-each select="$syms">
    <if test="position() > 1">
      <text>,</text>
    </if>

    <text>'</text>
      <value-of select="substring-after( @name, ':class:' )" />
    <text>':'</text>
      <!-- todo: escape -->
      <value-of select="translate( @desc, &quot;'&quot;, '' )" />
    <text>'</text>
  </for-each>
</function>


<!--
  Compile global parameter list into an object literal

  @return key and value for the given parameter
-->
<template match="lv:param" mode="compile">
  <!-- generate key using param name -->
  <text>params['</text>
  <value-of select="@name" />
  <text>'] = {</text>

  <!-- param properties -->
  <text>type: '</text>
    <value-of select="@type" />
  <text>',</text>

  <text>'default': '</text>
    <value-of select="@default" />
  <text>',</text>

  <text>required: </text>
    <!-- param is required if the attribute is present, not non-empty -->
    <value-of select="string( not( boolean( @default ) ) )" />
  <text>};</text>
</template>


<!--
  Generate value table for unions

  The type of the table will be considered the type of the first enum and each
  enum value table will be combined.

  @return object literal properties containing union data
-->
<template match="lv:typedef/lv:union" mode="compile" priority="5">
  <!-- generate key using type name -->
  <text>types['</text>
  <value-of select="../@name" />
  <text>'] = {</text>

  <!-- its type will be the type of its first enum (all must share the same
       domain) -->
  <text>type: '</text>
    <value-of select=".//lv:enum[1]/@type" />
  <text>',</text>

  <!-- finally, its table of values should consist of every enum it contains -->
  <text>values: {</text>
    <for-each select="./lv:typedef/lv:enum/lv:item">
      <if test="position() > 1">
        <text>,</text>
      </if>

      <apply-templates select="." mode="compile" />
    </for-each>
  <text>}</text>

  <text>};</text>
</template>


<!--
  Generate value table for enums

  @return object literal properties containing enum data
-->
<template match="lv:typedef/lv:enum" mode="compile" priority="5">
  <!-- generate key using type name -->
  <text>types['</text>
  <value-of select="../@name" />
  <text>'] = {</text>

  <!-- domain of all values -->
  <text>type: '</text>
    <value-of select="@type" />
  <text>',</text>

  <!-- table of acceptable values -->
  <text>values: {</text>
    <for-each select="./lv:item">
      <if test="position() > 1">
        <text>,</text>
      </if>

      <apply-templates select="." mode="compile" />
    </for-each>
  <text>}</text>

  <text>};</text>
</template>


<template match="lv:typedef/lv:base-type" mode="compile" priority="5">
  <text>types['</text>
  <value-of select="../@name" />
  <text>'] = {</text>

  <!-- base types are their own type -->
  <text>type: '</text>
    <value-of select="../@name" />
  <text>',</text>

  <text>values:{}</text>

  <text>};</text>
</template>


<template match="lv:typedef/*" mode="compile" priority="1">
  <message terminate="yes">
    <text>[lvc] Unhandled typedef: </text>
    <value-of select="../@name" />
  </message>
</template>


<!--
  Generate enum item value

  @return property representing a specific value
-->
<template match="lv:enum/lv:item" mode="compile">
  <!-- determine enumerated value -->
  <variable name="value">
    <choose>
      <when test="@value">
        <value-of select="@value" />
      </when>

      <!-- default to string value equivalent to name -->
      <otherwise>
        <value-of select="@name" />
      </otherwise>
    </choose>
  </variable>

  <!-- we are only interest in its value; its constant is an internal value -->
  <text>'</text>
  <value-of select="$value" />
  <text>': true</text>
</template>


<!--
  Generate an object containing values of constant sets

  This is done instead of inlining constant values as we do with non-sets since
  the specific index can be determined at runtime.

  @return JS object assignment for constant set values
-->
<template mode="compile" priority="1"
          match="lv:const[ element() or @values ]">
  <text>consts['</text>
    <value-of select="@name" />
  <text>'] = [ </text>

    <!-- matrices -->
    <for-each select="compiler:const-sets( . )[ not( . = '' ) ]">
      <if test="position() > 1">
        <text>, </text>
      </if>

      <text>[ </text>
        <for-each select="compiler:set-items( ., true() )">
          <if test="position() > 1">
            <text>, </text>
          </if>

          <value-of select="." />
        </for-each>
      <text> ]</text>
    </for-each>

    <!-- vectors -->
    <for-each select="compiler:set-items( ., false() )">
      <if test="position() > 1">
        <text>, </text>
      </if>

      <value-of select="." />
    </for-each>

  <text> ]; </text>
</template>


<!--
  Produce sequence of sets

  Sets are used to group together items in a matrix.  A set can be
  defined explicitly (using nodes), or via a GNU Octave or
  MATLAB-style matrix definition.
-->
<function name="compiler:const-sets" as="item()*">
  <param name="const" as="element( lv:const )" />

  <variable name="values-def" as="xs:string?"
            select="$const/@values" />

  <choose>
    <when test="$values-def and contains( $values-def, ';' )">
      <sequence select="tokenize(
                          normalize-space( $values-def ), ';' )" />
    </when>

    <otherwise>
      <sequence select="$const/lv:set" />
    </otherwise>
  </choose>
</function>


<!--
  Produce a sequence of items

  Items represent elements of a vector.  They may be specified
  explicitly using nodes, or via a comma-delimited string.
-->
<function name="compiler:set-items" as="xs:string*">
  <param name="set"          as="item()*" />
  <param name="allow-values" as="xs:boolean" />

  <choose>
    <when test="$set instance of xs:string">
      <sequence select="tokenize(
                          normalize-space( $set ), ',' )" />
    </when>

    <when test="$set/@values and $allow-values">
      <sequence select="tokenize(
                          normalize-space( $set/@values ), ',' )" />
    </when>

    <otherwise>
      <sequence select="$set/lv:item/@value" />
    </otherwise>
  </choose>
</function>


<!--
  Generate code to perform a classification

  Based on the criteria provided by the classification, generate and store the
  result of a boolean expression performing the classification using global
  arguments.

  TODO: Refactor; both @yields and $result-set checks are unneeded; they can be
  combined (@yields as the default, which may or may not exist)

  @return generated classification expression
-->
<template match="lv:classify" mode="compile">
  <param name="noclass" />
  <param name="result-set" />
  <param name="ignores" />

  <variable name="self" select="." />

  <value-of select="$compiler:nl" />

  <if test="not( $noclass )">
    <if test="@preproc:generated='true'">
      <text>gen</text>
    </if>

    <text>classes['</text>
      <value-of select="@as" />
    <text>'] = (function(){var result,tmp; </text>
  </if>

  <!-- locate classification criteria -->
  <variable name="criteria" as="element( lv:match )*"
            select="lv:match[
                      not( $ignores )
                      or not( @on=$ignores/@ref ) ]" />

  <variable name="criteria-syms" as="element( preproc:sym )*"
            select="root(.)/preproc:symtable/preproc:sym[
                      @name = $criteria/@on ]" />

  <variable name="dest">
    <choose>
      <when test="$result-set">
        <value-of select="$result-set" />
      </when>

      <otherwise>
        <text>args['</text>
          <value-of select="@yields" />
        <text>']</text>
      </otherwise>
    </choose>
  </variable>

  <!-- generate boolean value from match expressions -->
  <choose>
    <!-- if classification criteria were provided, then use them -->
    <when test="$criteria">
      <variable name="criteria-scalar" as="element( lv:match )*"
                select="$criteria[
                          @on = $criteria-syms[
                              @dim = '0' ]/@name ]" />

      <variable name="op" as="xs:string"
                select="compiler:match-group-op( $self )" />

      <text></text>
        <!-- first, non-scalar criteria -->
        <apply-templates mode="compile"
                         select="$criteria[
                                   not( @on = $criteria-scalar/@on ) ]">
          <with-param name="result-set" select="$result-set" />
          <with-param name="ignores" select="$ignores" />
          <with-param name="operator" select="$op" />
        </apply-templates>

        <!-- scalars must be matched last -->
        <apply-templates mode="compile"
                         select="$criteria-scalar">
          <with-param name="result-set" select="$result-set" />
          <with-param name="ignores" select="$ignores" />
          <with-param name="operator" select="$op" />
        </apply-templates>
    </when>

    <!-- if no classification criteria, then always true/false -->
    <otherwise>
      <!-- this is only useful if $noclass is *not* set -->
      <if test="not( $noclass )">
        <choose>
          <!-- universal -->
          <when test="not( @any='true' )">
            <text>tmp = true; </text>
          </when>

          <!-- existential -->
          <otherwise>
            <text>tmp = false; </text>
          </otherwise>
        </choose>
      </if>

      <!-- if @yields was provided, then store the value in a variable of their
           choice as well (since cmatch will not be done) -->
      <if test="@yields or $result-set">
        <value-of select="$dest" />
        <choose>
          <!-- universal -->
          <when test="not( @any='true' )">
            <text> = 1;</text>
          </when>

          <!-- existential -->
          <otherwise>
            <text> = 0;</text>
          </otherwise>
        </choose>
      </if>
    </otherwise>
  </choose>

  <text> return tmp;})();</text>

  <!-- support termination on certain classifications (useful for eligibility
       and error conditions) -->
  <if test="@terminate = 'true'">
    <text>if ( _canterm &amp;&amp; </text>

    <if test="@preproc:generated='true'">
      <text>gen</text>
    </if>
    <text>classes['</text>
      <value-of select="@as" />
    <text>'] ) throw Error( '</text>
      <value-of select="@desc" />
    <text>' );</text>

    <value-of select="$compiler:nl" />
  </if>

    <variable name="sym"
      select="root(.)/preproc:symtable/preproc:sym[ @name=$self/@yields ]" />

  <!-- if we are not any type of set, then yield the value of the first
         index (note the $criteria check; see above); note that we do not do
         not( @set ) here, since that may have ill effects as it implies that
         the node is not preprocessed -->
  <!-- TODO: this can be simplified, since @yields is always provided -->
  <if test="$criteria and ( @yields or $result-set ) and ( $sym/@dim='0' )">
    <value-of select="$dest" />
    <text> = </text>
      <value-of select="$dest" />
    <text>[0];</text>

    <value-of select="$compiler:nl" />
  </if>
</template>


<template match="preproc:rate" mode="compile">
  <variable name="yields" select="@ref" />

  <!-- compile the lv:rate block associated with this name -->
  <apply-templates
    select="root(.)//lv:rate[ @yields=$yields ]"
    mode="compile" />
</template>

<template match="preproc:class" mode="compile">
  <variable name="as" select="@ref" />

  <apply-templates
    select="root(.)//lv:classify[ @as=$as ]"
    mode="compile" />
</template>


<!--
  Generate domain checks for require-param nodes

  The resulting code will cause an exception to be thrown if the domain check
  fails.

  FIXME: remove

  @return generated domain check code
-->
<template match="lv:required-param" mode="compile">
  <!--
  <variable name="name" select="@ref" />

  <text>vocalDomainCheck( '</text>
    <value-of select="$name" />
  <text>', '</text>
    <value-of select="root(.)//lv:param[ @name=$name ]/@type" />
  <text>', args['</text>
    <value-of select="$name" />
  <text>'] ); </text>
  -->

  <!-- record that this param was required -->
  <!--
  <text>req_params['</text>
    <value-of select="$name" />
  <text>'] = true; </text>
  -->
</template>


<!--
  Generate code asserting a match

  Siblings are joined by default with ampersands to denote an AND relationship,
  unless overridden.

  @return generated match code
-->
<template match="lv:match" mode="compile" priority="1">
  <!-- default to all matches being required -->
  <param name="operator" select="'&amp;&amp;'" />
  <param name="yields" select="../@yields" />
  <param name="result-set" />

  <variable name="name" select="@on" />

  <text> tmp = </text>

  <variable name="input-raw">
    <choose>
      <!-- if we have assumptions, then we'll be recalculating (rather than
           referencing) an existing classification -->
      <when test="lv:assuming">
        <text>_cassume</text>
      </when>

      <otherwise>
        <text>args['</text>
          <value-of select="translate( @on, &quot;'&quot;, '' )" />
        <text>']</text>
      </otherwise>
    </choose>
  </variable>

  <!-- yields (if not set, generate one so that cmatches still works properly)
       -->
  <variable name="yieldto">
    <choose>
      <!-- if we were given a result set to use, then use it -->
      <when test="$result-set">
        <value-of select="$result-set" />
      </when>

      <!-- store directly into the destination result set -->
      <otherwise>
        <call-template name="compiler:gen-match-yieldto">
          <with-param name="yields" select="$yields" />
        </call-template>
      </otherwise>
    </choose>
  </variable>

  <!-- the input value -->
  <variable name="input">
    <choose>
      <when test="@scalar = 'true'">
        <text>stov( </text>
          <value-of select="$input-raw" />
        <text>, ( ( </text>
          <value-of select="$yieldto" />
        <!-- note that we default to 1 so that there is at least a single
             element (which will be the case of the scalar is the first match)
             in a given classification; the awkward inner [] is to protect
             against potentially undefined values and will hopefully never
             happen, and the length is checked on the inner grouping rather than
             on the outside of the entire expression to ensure that it will
             yield the intended result if yieldto.length === 0 -->
        <text> || [] ).length || 1 ) )</text>
      </when>

      <otherwise>
        <value-of select="$input-raw" />
      </otherwise>
    </choose>
  </variable>

  <if test="lv:assuming">
    <text>(function(){</text>
      <!-- initialize variable (ensuring that the closure we're about to generate
           will properly assign the value rather than encapsulate it) -->
      <text>var </text>
      <value-of select="$input-raw" />
      <text>; </text>

      <!-- generate assumptions and recursively generate the referenced
           classification -->
      <apply-templates select="." mode="compile-match-assumptions">
        <with-param name="result-var" select="$input-raw" />
      </apply-templates>
      <text>; return </text>
  </if>

  <!-- invoke the classification matcher on this input -->
  <text>anyValue( </text>
    <value-of select="$input" />
  <text>, </text>

  <!-- TODO: error if multiple; also, refactor -->
  <choose>
    <when test="@value">
      <variable name="value" select="@value" />
      <variable name="sym"
        select="root(.)/preproc:symtable/preproc:sym[ @name=$value ]" />

      <choose>
        <!-- simple constant -->
        <when test="$sym and @value">
          <value-of select="$sym/@value" />
        </when>

        <!-- value unavailable (XXX: this probably should never happen...) -->
        <when test="$sym and @value">
            <message>
              <text>[jsc] !!! TODO: bad classification match: '</text>
                <value-of select="$value" />
            </message>
        </when>

        <otherwise>
          <text>'</text>
            <!-- TODO: Should we disallow entirely? -->
            <message>
              <text>[jsc] warning: static classification match '</text>
                <value-of select="$value" />
              <text>' in </text>
              <value-of select="ancestor::lv:classify[1]/@as" />
              <text>; use calculation predicate or constant instead</text>
            </message>

            <value-of select="$value" />
          <text>'</text>
        </otherwise>
      </choose>
    </when>

    <when test="@pattern">
      <text>function( val ) { </text>
        <text>return /</text>
          <value-of select="@pattern" />
        <text>/.test( val );</text>
      <text> }</text>
    </when>

    <when test="./c:*">
      <text>function( val, __$$i ) { </text>
        <text>return ( </text>
          <for-each select="./c:*">
            <if test="position() > 1">
              <text disable-output-escaping="yes"> &amp;&amp; </text>
            </if>

            <text>( val </text>
              <apply-templates select="." mode="compile-calc-when" />
            <text> ) </text>
          </for-each>
        <text>);</text>
      <text>}</text>
    </when>

    <otherwise>
      <apply-templates select="." mode="compiler:match-anyof" />
    </otherwise>
  </choose>

  <text>, ( </text>
  <value-of select="$yieldto" />
  <text> || ( </text>
  <value-of select="$yieldto" />
  <text> = [] ) ), </text>

  <!-- if this match is part of a classification that should yield a matrix,
       then force a matrix set -->
  <choose>
    <when test="ancestor::lv:classify/@set = 'matrix'">
      <text>true</text>
    </when>
    <otherwise>
      <text>false</text>
    </otherwise>
  </choose>

  <text>, </text>
  <choose>
    <when test="parent::lv:classify/@any='true'">
      <text>false</text>
    </when>
    <otherwise>
      <text>true</text>
    </otherwise>
  </choose>

  <!-- for debugging -->
  <text>,"</text>
  <value-of select="$input" />
  <text>"</text>

  <!-- end of anyValue() call -->
  <text> ) </text>

  <!-- end of assuming function call -->
  <if test="lv:assuming">
    <text>})()</text>
  </if>

  <text>;</text>

  <text>( debug['</text>
    <value-of select="@_id" />
  <text>'] || ( debug['</text>
    <value-of select="@_id" />
  <text>'] = [] ) ).push( tmp ); </text>


  <text>result = </text>
  <choose>
    <!-- join with operator if not first in set -->
    <when test="position() > 1">
      <text>result </text>
      <value-of select="$operator" />
      <text> tmp;</text>
    </when>

    <otherwise>
      <text>tmp;</text>
    </otherwise>
  </choose>
</template>

<template name="compiler:gen-match-yieldto">
  <param name="yields" />

  <text>args['</text>
    <choose>
      <when test="$yields">
        <value-of select="$yields" />
      </when>

      <otherwise>
        <call-template name="compiler:gen-default-yield">
          <with-param name="name" select="ancestor::lv:classify/@as" />
        </call-template>
      </otherwise>
    </choose>
  <text>']</text>
</template>

<!--
  Handles the special "float" domain

  Rather than the impossible task of calculating all possible floats and
  asserting that the given values is within that set, the obvious task is to
  assert whether or not the value is logically capable of existing in such a
  set based on a definition of such a set.

  See also "integer"
-->
<template match="lv:match[ @anyOf='float' ]" mode="compiler:match-anyof" priority="5">
  <!-- ceil(x) - floor(x) = [ x is not an integer ] -->
  <text>function( val ) {</text>
    <text>return ( typeof +val === 'number' ) </text>
      <text disable-output-escaping="yes">&amp;&amp; </text>
      <!-- note: greater than or equal to, since we want to permit integers as
           well -->
      <text disable-output-escaping="yes">( Math.ceil( val ) >= Math.floor( val ) )</text>
    <text>;</text>
  <text>}</text>
</template>

<!--
  Handles the special "float" domain

  Rather than the impossible task of calculating all possible integers and
  asserting that the given values is within that set, the obvious task is to
  assert whether or not the value is logically capable of existing in such a
  set based on a definition of such a set.

  See also "float"
-->
<template match="lv:match[ @anyOf='integer' ]" mode="compiler:match-anyof" priority="5">
  <!-- ceil(x) - floor(x) = [ x is not an integer ] -->
  <text>function( val ) {</text>
    <text>return ( typeof +val === 'number' ) </text>
      <text disable-output-escaping="yes">&amp;&amp; </text>
      <text>( Math.floor( val ) === Math.ceil( val ) )</text>
    <text>;</text>
  <text>}</text>
</template>

<!--
  Handles matching on an empty set

  This is useful for asserting against fields that may have default values,
  since in such a case an empty value would be permitted.
-->
<template match="lv:match[ @anyOf='empty' ]" mode="compiler:match-anyof" priority="5">
  <!-- ceil(x) - floor(x) = [ x is not an integer ] -->
  <text>function( val ) {</text>
    <text>return ( val === '' ) </text>
      <text>|| ( val === undefined ) || ( val === null )</text>
    <text>;</text>
  <text>}</text>
</template>

<!--
  Uh oh. Hopefully this never happens; will throw an exception if a type is
  defined as a base type (using typedef), but is not handled by the compiler.
-->
<template match="lv:match[ @anyOf=root(.)//lv:typedef[ ./lv:base-type ]/@name ]"
  mode="compiler:match-anyof" priority="3">

  <text>function( val ) {</text>
    <text>throw Error( 'CRITICAL: Unhandled base type: </text>
      <value-of select="@anyOf" />
    <text>' );</text>
  <text>}</text>
</template>

<!--
  Used for user-defined domains
-->
<template match="lv:match[ @anyOf ]" mode="compiler:match-anyof" priority="1">
  <text>types['</text>
    <value-of select="@anyOf" />
  <text>'].values</text>
</template>


<function name="compiler:match-group-op" as="xs:string">
  <param name="class" as="element( lv:classify )" />

  <sequence select="if ( $class/@any = 'true' ) then
                      '||'
                    else
                      '&amp;&amp;'" />
</function>


<!--
  Compiles a function

  Parameters will be converted into actual function parameters. The function
  will return the result of its expression (represented by a calculation in the
  XML).

  @return generated function
-->
<template match="lv:function" mode="compile">
  <value-of select="$compiler:nl" />

  <text>function </text>
    <call-template name="calc-compiler:gen-func-name">
      <with-param name="name" select="@name" />
    </call-template>
  <text>( args </text>

  <!-- add parameters -->
  <for-each select="./lv:param">
    <text>, </text>
    <value-of select="@name" />
  </for-each>

  <text>) {</text>

  <text>return ( </text>
    <!-- begin calculation generation (there should be only one calculation node
         as a child, so only it will be considered) -->
    <apply-templates select="./c:*[1]" mode="compile" />
  <text> );</text>

  <text>} </text>
</template>


<!--
  Compile lv:rate's in such an order that dependencies will be compiled first

  This is important to ensure that premium calculations based on other premiums
  are actually calculated after the premium that they depend on. Having an
  order-dependent document doesn't make sense with the declarative style and is
  especially confusing when including packages.
-->
<template match="lv:package" mode="compile-rates">
  <!-- generate the rate blocks, dependencies first; does not compile classifier
       dependencies, as those will be compiled with the appropriate classifier
       -->
  <apply-templates mode="compile" select="
      ./preproc:rate-deps/preproc:flat/preproc:rate
      |
      ./preproc:rate-deps/preproc:flat/preproc:class[ @external='true' ]
    " />

</template>



<!--
  Generates a premium calculation

  The result of the generated expression, as denoted by a calculation in the
  XML, will be stored in the variable identified by @yields.

  TODO: If another calculation uses the yielded premium in the document before
  this lv:rate block, then this block needs to be compiled *before* the block
  that references is. We don't want to depend on order, as that would not be
  declarative (in this particular scenario, at least).

  @return generated self-executing premium calculation function
-->
<template match="lv:rate" mode="compile">
  <value-of select="$compiler:nl" />

  <!-- see c:ceil/c:floor precision comments in js-calc -->
  <variable name="precision">
    <choose>
      <when test="@precision">
        <value-of select="@precision" />
      </when>

      <otherwise>
        <text>8</text>
      </otherwise>
    </choose>
  </variable>

  <variable name="store">
    <!-- TODO: escape single quotes (even though there should never be any) -->
    <text>args['</text>
      <value-of select="@yields" />
    <text>']</text>
  </variable>

  <!-- store the premium -->
  <value-of select="$store" />
  <text> = </text>

  <text>( function rate_</text>
    <!-- dashes, which may end up in generated code from templates, must be
         removed -->
    <value-of select="translate( @yields, '-', '_' )" />
  <text>() {</text>

  <text>var predmatch = ( </text>
    <apply-templates select="." mode="compile-class-condition" />
  <text> ); </text>

  <!-- set the magic _CMATCH_ var to represent a list of indexes that meet all
       the classifications -->
  <text>consts._CMATCH_ = </text>
    <apply-templates select="." mode="compile-cmatch" />
  <text>;</text>

  <!-- return the result of the calculation for this rate block -->
  <text>return (+( </text>
    <!-- begin calculation generation (there should be only one calculation
         node as a child, so only it will be considered) -->
    <apply-templates select="./c:*[1]" mode="compile" />
  <text> )).toFixed(</text>
    <value-of select="$precision" />
  <text>) * predmatch; } )() </text>

  <text>; </text>
</template>

<template match="lv:rate" mode="compile-class-condition">
  <!-- generate expression for class list (leave the @no check to the cmatch
       algorithm, since we want per-index @no's) -->
  <text>( </text>
    <variable name="class-set" select="./lv:class" />

    <choose>
      <when test="$class-set">
        <for-each select="$class-set">
          <!-- join class expressions with AND operator -->
          <if test="position() > 1">
            <text disable-output-escaping="yes"> &amp;&amp; </text>
          </if>

          <!-- negate if @no -->
          <if test="@no='true'">
            <text>!</text>
          </if>

          <variable name="ref" select="@ref" />

          <if test="
              root(.)/preproc:symtable/preproc:sym[
                @name=concat( ':class:', $ref )
              ]/@preproc:generated='true'
            ">
            <text>gen</text>
          </if>

          <text>classes['</text>
            <value-of select="@ref" />
          <text>']</text>
        </for-each>
      </when>

      <!-- well, we need to output something -->
      <otherwise>
        <text>true</text>
      </otherwise>
    </choose>
  <text> )</text>
</template>


<template match="lv:rate" mode="compile-cmatch">
  <variable name="root" select="root(.)" />

  <!-- generate cmatch call that will generate the cmatch set -->
  <text>cmatch( [</text>
    <for-each select="lv:class[ not( @no='true' ) ]">
      <if test="position() > 1">
        <text>, </text>
      </if>

      <text>args['</text>
        <call-template name="compiler:get-class-yield">
          <with-param name="name" select="@ref" />
          <with-param name="search" select="$root" />
        </call-template>
      <text>']</text>
    </for-each>
  <text>], [</text>
    <for-each select="lv:class[ @no='true' ]">
      <if test="position() > 1">
        <text>, </text>
      </if>

      <text>args['</text>
        <call-template name="compiler:get-class-yield">
          <with-param name="name" select="@ref" />
          <with-param name="search" select="$root" />
        </call-template>
      <text>']</text>
    </for-each>
  <text>] )</text>
</template>


<template name="compiler:get-class-yield">
  <param name="name" />
  <param name="search" />

  <variable name="yields">
    <value-of select="
        root(.)/preproc:symtable/preproc:sym[
          @name=concat( ':class:', $name )
        ]/@yields
      " />
  </variable>

  <choose>
    <when test="$yields != ''">
      <value-of select="$yields" />
    </when>

    <otherwise>
      <call-template name="compiler:gen-default-yield">
        <with-param name="name" select="$name" />
      </call-template>
    </otherwise>
  </choose>
</template>


<template name="compiler:gen-default-yield">
  <param name="name" />

  <!-- a random name that would be invalid to reference from the XML -->
  <text>___$$</text>
  <value-of select="$name" />
  <text>$$</text>
</template>


<!--
  Generates calculation used to yield a final premium

  @return generated expression
-->
<template match="lv:yield" mode="compile">
  <!-- compile yield calculation -->
  <apply-templates select="./c:*[1]" mode="compile" />
</template>



<template match="lv:meta/lv:prop" mode="compile">
  <text>meta['</text>
  <value-of select="@name" />
  <text>'] = </text>

  <call-template name="util:json">
    <with-param name="array">
      <!-- values -->
      <for-each select="lv:value">
        <variable name="name" select="@name" />

        <util:value>
          <!-- TODO: refactor -->
          <value-of select="
            root(.)//lv:const[ @name=$name ]/@value
            , root(.)//lv:item[ @name=$name ]/@value" />
        </util:value>
      </for-each>

      <!-- constants -->
      <for-each select="lv:const">
        <util:value>
          <value-of select="@value" />
        </util:value>
      </for-each>
    </with-param>
  </call-template>

  <text>;</text>
</template>



<template match="lvp:*" mode="compile" priority="1">
  <!-- do nothing with UI nodes -->
</template>
<template match="lvp:*" priority="1">
  <!-- do nothing with UI nodes -->
</template>

<!--
  Static code common to each rater

  This is included here because XSLT cannot, without extension, read plain-text
  files (the included file must be XML). If we separated it into another file,
  we would be doing the same thing as we are doing here.

  @return JavaScript code
-->
<template name="compiler:static">
<text>
<![CDATA[
    var domains = {
        'integer': function( value )
        {
            return ( value == +value );
        },

        'float': function( value )
        {
            return ( value == +value );
        },

        'boolean': function( value )
        {
            return ( ( +value === 1 ) || ( +value === 0 ) );
        },

        'string': function( value )
        {
            // well, everything is a string
            return true;
        }
    };


    function argCheck( args, params )
    {
        var req = {};

        for ( var name in params )
        {
            // if the argument is not required, then we do not yet need to deal
            // with it
            if ( !( params[ name ].required ) )
            {
                continue;
            }

            // first, ensure that required arguments have been provided (note
            // the strict check for .length; this is important, since it won't
            // have a length property if it's not an array, in which case we do
            // not want to trigger an error)
            if ( !( args[ name ] ) || ( args[ name ].length === 0 ) )
            {
                throw Error( "argument required: " + name );
            }

            var value = args[ name ];

            // next, ensure that the argument is within the domain of its type
            vocalDomainCheck( name, params[ name ].type, deepClone( value ) );

            // record that we required this param
            req[ name ] = true;
        }

        return req;
    }


    function vocalDomainCheck( name, domain, value )
    {
        var default_val = ( rater.params[ name ] || {} )['default'];

        if ( !( domainCheck( domain, value, default_val ) ) )
        {
            throw Error(
                "argument '" + name + "' value outside domain of '" +
                domain + "': " + JSON.stringify( value )
            );
        }

        return true;
    }


    function domainCheck( domain, value, default_val )
    {
        var type;

        // if it's an object, then the value is assumed to be an array
        if ( typeof value === 'object' )
        {
            if ( value.length < 1 )
            {
                return true;
            }

            // clone before popping so that we don't wipe out any values that
            // will be used
            value = Array.prototype.slice.call( value );

            // check each value recursively
            return domainCheck( domain, value.pop(), default_val )
                && domainCheck( domain, value, default_val );
        }

        if ( ( ( value === undefined ) || ( value === '' ) )
          && ( default_val !== undefined )
        )
        {
            value = +default_val;
        }

        if ( domains[ domain ] )
        {
            return domains[ domain ]( value );
        }
        else if ( type = types[ domain ] ) /** XXX: types global **/
        {
            // custom type checks are two-fold: ensure that the value is within
            // the domain of its base type and that it is within its list of
            // acceptable values
            return !!( domainCheck( type.type, value )
                && type.values[ value ]
            );
        }

        // no domain found
        return false;
    }


    /**
     * Checks for matches against values for any param value
     *
     * A single successful match will result in a successful classification.
     *
     * For an explanation and formal definition of this algorithm, please see
     * the section entitled "Classification Match (cmatch) Algorithm" in the
     * manual.
     *
     * @param {Array|string} param    value or set of values to check
     * @param {Array|string} values   or set of values to match against
     * @param {Object}       yield_to object to yield into
     * @param {boolean}      clear    when true, AND results; otherwise, OR
     *
     * @return {boolean} true if any match is found, otherwise false
     */
    function anyValue( param, values, yield_to, ismatrix, clear, _id )
    {
        // convert everything to an array if needed (we'll assume all objects to
        // be arrays; Array.isArray() is ES5-only) to make them easier to work
        // with
        if ( ( param === undefined ) || ( param === null ) )
        {
            // according to the specification, an undefined input vector should
            // yield an empty result set, which in turn will be interpreted as
            // false (yield_to is the result vector)
            param = [];
        }
        else if ( typeof param !== 'object' )
        {
            param = [ param ];
        }

        var values_orig = values;
        if ( typeof values !== 'object' )
        {
            // the || 0 here ensures that non-values are treated as 0, as
            // mentioned in the specification
            values = [ values || 0 ];
        }
        else
        {
            var tmp = [];
            for ( var v in values )
            {
                tmp.push( v );
            }

            values = tmp;
        }

        // if no yield var name was provided, we'll just be storing in a
        // temporary array which will be discarded when it goes out of scope
        // (this is the result vector in the specification)
        var store = yield_to || [];

        var i      = param.length,
            found  = false,
            scalar = ( i === 0 ),
            u      = ( store.length === 0 ) ? clear : false;

        while ( i-- )
        {
            // these var names are as they appear in the algorithm---temporary,
            // and value
            var t,
                v = returnOrReduceOr( store[ i ], u );

            // recurse on vectors
            if ( typeof param[ i ] === 'object' )
            {
                var r = deepClone( store[ i ] || [] );
                if ( typeof r !== 'object' )
                {
                    r = [ r ];
                }

                var rfound = !!anyValue( param[ i ], values_orig, r, false, clear, _id );
                found = ( found || rfound );

                if ( ( typeof store[ i ] === 'object' )
                  || ( store[ i ] === undefined )
                )
                {
                    // we do not want to reduce; this is the match that we are
                    // interested in
                    store[ i ] = r;
                    continue;
                }
                else
                {
                    t = returnOrReduceOr( r, clear );
                }
            }
            else
            {
                // we have a scalar, folks!
                scalar = true;
                t = anyPredicate( values, ( param[ i ] || 0 ), i );
            }

            store[ i ] = +( ( clear )
                ? ( v && t )
                : ( v || t )
            );

            // equivalent of "Boolean Classification Match" section of manual
            found = ( found || !!store[ i ] );
        }

        if ( store.length > param.length )
        {
            var sval = ( scalar ) ? anyPredicate( values, param[0] ) : null;
            if ( typeof sval === 'function' )
            {
                // pass the scalar value to the function
                sval = values[0]( param[0] );
            }

            // XXX: review the algorithm; this is a mess
            for ( var k = param.length, l = store.length; k < l; k++ )
            {
                // note that this has the same effect as initializing (in the
                // case of a scalar) the scalar to the length of the store
                var v = +(
                  ( returnOrReduceOr( store[ k ], clear )
                    || ( !clear && ( scalar && sval ) )
                  )
                  && ( !clear || ( scalar && sval ) )
                );

                store[ k ] = ( scalar )
                  ? v
                  : [ v ];

                found = ( found || !!v );
            }
        }

        return found;
    }


    function anyPredicate( preds, value, index )
    {
        for ( var i in preds )
        {
            var p = preds[ i ];

            if ( ( typeof p === 'function' )
              && p( value, index )
            )
            {
                return true;
            }
            // lazy equality intentional
            else if ( p == value )
            {
                return true;
            }
        }

        return false;
    }


    function returnOrReduceOr( arr, c )
    {
        if ( arr === undefined )
        {
            return !!c;
        }
        else if ( !( arr.length ) )
        {
            return arr;
        }

        return reduce( arr, function( a, b )
        {
            return returnOrReduceOr( a, c ) || returnOrReduceOr( b, c );
        } );
    }


    function returnOrReduceAnd( arr, c )
    {
        if ( arr === undefined )
        {
            return !!c;
        }
        else if ( !( arr.length ) )
        {
            return arr;
        }

        return reduce( arr, function( a, b )
        {
            return returnOrReduceAnd( a, c ) && returnOrReduceAnd( b, c );
        } );
    }


    function deepClone( obj )
    {
        var objnew = [];

        // if we were not given an object, then do nothing
        if ( typeof obj !== 'object' )
        {
            return obj;
        }

        for ( var i in obj )
        {
            // deep-clone for matrices
            objnew[ i ] = ( typeof obj[ i ] === 'object' )
              ? deepClone( obj[ i ] )
              : obj[ i ];
        }

        return objnew;
    }


    /**
     * Converts a match set to an integer
     *
     * If the given set is an array, then return a sum of each of its boolean
     * values (if any one is set, then it's 1); otherwise, cast the given
     * value to a number, just in case it's not.
     *
     * This function does not check to ensure that the given set contains valid
     * data.
     *
     * @param {*} match set to convert
     *
     * @return {number} 1 or 0
     */
    function matchSetToInt( match )
    {
        if ( Array.isArray( match ) )
        {
            return reduce( match, function( a, b )
            {
                return a + b;
            } );
        }

        return +match;
    }


    function cmatch( match, nomatch )
    {
        var len    = 0,
            cmatch = [];

        // the length of our set should be the length of the largest set (we
        // will not know this until runtime)
        for ( var i in match )
        {
            // note that this has the consequence of not matching on scalar-only
            // classifications...is this what we want? If not, we need to
            // document a proper solution.
            if ( ( match[ i ] || [] ).length > len )
            {
                len = match[ i ].length;
            }
        }

        for ( var i in nomatch )
        {
            if ( ( nomatch[ i ] || [] ).length > len )
            {
                len = nomatch[ i ].length;
            }
        }

        while ( len-- )
        {
            var fail = false;

            for ( var i in match )
            {
                // if we're dealing with a scalar, then it should be used for
                // every index
                var mdata = ( ( typeof match[ i ] !== 'object' )
                  ? match[ i ]
                  : ( match[ i ] || [] )[ len ]
                );

                if ( !( matchSetToInt( mdata ) ) )
                {
                    fail = true;
                }
            }

            // XXX duplicate code
            for ( var i in nomatch )
            {
                // if we're dealing with a scalar, then it should be used for
                // every index
                var mdata = ( ( typeof nomatch[ i ] !== 'object' )
                  ? nomatch[ i ]
                  : ( nomatch[ i ] || [] )[ len ]
                );

                if ( matchSetToInt( mdata ) !== 0 )
                {
                    fail = true;
                }
            }

            cmatch[ len ] = ( fail ) ? 0 : 1;
        }

        return cmatch;
    }


    /**
     * Return the length of the longest set
     *
     * Provide each set as its own argument.
     *
     * @return number length of longest set
     */
    function longerOf()
    {
        var i   = arguments.length,
            len = 0;
        while ( i-- )
        {
            var thislen = arguments[ i ].length;

            if ( thislen > len )
            {
                len = thislen;
            }
        }

        return len;
    }


    /**
     * Some browsers don't support Array.reduce(), and adding to the prototype
     * causes problems since we cannot make it non-enumerable in those browsers
     * due to broken Object.defineProperty implementations (IE8).
     */
    function reduce( arr, c )
    {
        var ret = arr[ 0 ],
            i = 0, // skip first
            l = arr.length;

        while ( ++i < l )
        {
            ret = c( ret, arr[ i ] );
        }

        // note that this will have the effet of returning the first element if
        // there are none/no more than 1
        return ret;
    }


    /* scalar to vector */
    function stov( s, n )
    {
        // already a vector
        if ( typeof s === 'object' )
        {
            // if the length is only one, then we can pretend that it is a
            // scalar (unless the requested length is one, in which case it is
            // utterly pointless to continue)
            if ( ( n === 1 ) || ( s.length !== 1 ) )
            {
                return s;
            }

            s = s[ 0 ];
        }

        var v = [];
        for ( var i = 0; i < n; i++ )
        {
            v.push( s );
        }

        return v;
    }


    function argreplace( orig, value )
    {
        if ( !( typeof orig === 'object' ) )
        {
            return value;
        }

        // we have an object; recurse
        for ( var i in orig )
        {
            return argreplace( orig[ i ], value );
        }
    }


    function init_defaults( args, params )
    {
        for ( var param in params )
        {
            var val = params[ param ]['default'];
            if ( !val )
            {
                continue;
            }

            args[ param ] = set_defaults( args[ param ], val );
        }
    }


    function set_defaults( input, value )
    {
        // scalar
        if ( !( typeof input === 'object' ) )
        {
            return ( input === '' || input === undefined ) ? value : input;
        }

        // otherwise, assume array
        var i = input.length;
        var ret = [];
        while ( i-- ) {
            ret[i] = ( input[i] === '' ) ? value : input[i];
        }
        return ret;
    }
]]>
</text>
</template>

</stylesheet>