summaryrefslogtreecommitdiff
path: root/components/external/espruino/src/jsparse.c
blob: fb7d42a06842857a1d624ca0f3d229ab412bc237 (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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
/*
 * This file is part of Espruino, a JavaScript interpreter for Microcontrollers
 *
 * Copyright (C) 2013 Gordon Williams <[email protected]>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * ----------------------------------------------------------------------------
 * Recursive descent parser for code execution
 * ----------------------------------------------------------------------------
 */
#include "jsparse.h"
#include "jsinteractive.h"
#include "jswrapper.h"

/* Info about execution when Parsing - this saves passing it on the stack
 * for each call */
JsExecInfo execInfo;

// ----------------------------------------------- Forward decls
JsVar *jspeBase();
JsVar *jspeBaseWithComma();
JsVar *jspeBlock();
JsVar *jspeStatement();
// ----------------------------------------------- Utils
#define JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, CLEANUP_CODE, RETURN_VAL) { if (!jslMatch(execInfo.lex,(TOKEN))) { jspSetError(); CLEANUP_CODE; return RETURN_VAL; } }
#define JSP_MATCH_WITH_RETURN(TOKEN, RETURN_VAL) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , RETURN_VAL)
#define JSP_MATCH(TOKEN) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , 0)
#define JSP_SHOULD_EXECUTE (((execInfo.execute)&EXEC_RUN_MASK)==EXEC_YES)
#define JSP_SAVE_EXECUTE() JsExecFlags oldExecute = execInfo.execute
#define JSP_RESTORE_EXECUTE() execInfo.execute = (execInfo.execute&(JsExecFlags)(~EXEC_SAVE_RESTORE_MASK)) | (oldExecute&EXEC_SAVE_RESTORE_MASK);
#define JSP_HAS_ERROR (((execInfo.execute)&EXEC_ERROR_MASK)!=0)

/// if interrupting execution, this is set
bool jspIsInterrupted() {
  return (execInfo.execute & EXEC_INTERRUPTED)!=0;
}

/// if interrupting execution, this is set
void jspSetInterrupted(bool interrupt) {
  if (interrupt)
    execInfo.execute = execInfo.execute | EXEC_INTERRUPTED;
  else
    execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_INTERRUPTED;
}

static inline void jspSetError() {
  execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_YES) | EXEC_ERROR;
}

bool jspHasError() {
  return JSP_HAS_ERROR;
}

///< Same as jsvSetValueOfName, but nice error message
void jspReplaceWith(JsVar *dst, JsVar *src) {
  // If this is an index in an array buffer, write directly into the array buffer
  if (jsvIsArrayBufferName(dst)) {
    JsVarInt idx = jsvGetInteger(dst);
    JsVar *arrayBuffer = jsvLock(dst->firstChild);
    jsvArrayBufferSet(arrayBuffer, idx, src);
    jsvUnLock(arrayBuffer);
    return;
  }
  // if destination isn't there, isn't a 'name', or is used, give an error
  if (!jsvIsName(dst)) {
    jsErrorAt("Unable to assign value to non-reference", execInfo.lex, execInfo.lex->tokenLastEnd);
    jspSetError();
    return;
  }
  jsvSetValueOfName(dst, src);
}

void jspeiInit(JsParse *parse, JsLex *lex) {
  execInfo.parse = parse;
  execInfo.lex = lex;
  execInfo.scopeCount = 0;
  execInfo.execute = EXEC_YES;
}

void jspeiKill() {
  execInfo.parse = 0;
  execInfo.lex = 0;
  assert(execInfo.scopeCount==0);
}

bool jspeiAddScope(JsVarRef scope) {
  if (execInfo.scopeCount >= JSPARSE_MAX_SCOPES) {
    jsError("Maximum number of scopes exceeded");
    jspSetError();
    return false;
  }
  execInfo.scopes[execInfo.scopeCount++] = jsvRefRef(scope);
  return true;
}

void jspeiRemoveScope() {
  if (execInfo.scopeCount <= 0) {
    jsErrorInternal("Too many scopes removed");
    jspSetError();
    return;
  }
  jsvUnRefRef(execInfo.scopes[--execInfo.scopeCount]);
}

JsVar *jspeiFindInScopes(const char *name) {
  int i;
  for (i=execInfo.scopeCount-1;i>=0;i--) {
    JsVar *ref = jsvFindChildFromStringRef(execInfo.scopes[i], name, false);
    if (ref) return ref;
  }
  return jsvFindChildFromString(execInfo.parse->root, name, false);
}

JsVar *jspeiFindOnTop(const char *name, bool createIfNotFound) {
  if (execInfo.scopeCount>0)
    return jsvFindChildFromStringRef(execInfo.scopes[execInfo.scopeCount-1], name, createIfNotFound);
  return jsvFindChildFromString(execInfo.parse->root, name, createIfNotFound);
}
JsVar *jspeiFindNameOnTop(JsVar *childName, bool createIfNotFound) {
  if (execInfo.scopeCount>0)
    return jsvFindChildFromVarRef(execInfo.scopes[execInfo.scopeCount-1], childName, createIfNotFound);
  return jsvFindChildFromVar(execInfo.parse->root, childName, createIfNotFound);
}

/** Here we assume that we have already looked in the parent itself -
 * and are now going down looking at the stuff it inherited */
JsVar *jspeiFindChildFromStringInParents(JsVar *parent, const char *name) {
  if (jsvIsObject(parent)) {
    // If an object, look for an 'inherits' var
    JsVar *inheritsFrom = jsvObjectGetChild(parent, JSPARSE_INHERITS_VAR, 0);

    // if there's no inheritsFrom, just default to 'Object.prototype'
    if (!inheritsFrom) {
      JsVar *obj = jsvObjectGetChild(execInfo.parse->root, "Object", 0);
      if (obj) {
        inheritsFrom = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
        jsvUnLock(obj);
      }
    }

    if (inheritsFrom && inheritsFrom!=parent) {
      // we have what it inherits from (this is ACTUALLY the prototype var)
      // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto
      JsVar *child = jsvFindChildFromString(inheritsFrom, name, false);
      if (!child)
        child = jspeiFindChildFromStringInParents(inheritsFrom, name);
      jsvUnLock(inheritsFrom);
      if (child) return child;
    }
  } else { // Not actually an object - but might be an array/string/etc
    const char *objectName = jswGetBasicObjectName(parent);
    while (objectName) {
      JsVar *objName = jsvFindChildFromString(execInfo.parse->root, objectName, false);
      if (objName) {
        JsVar *result = 0;
        JsVar *obj = jsvSkipNameAndUnLock(objName);
        if (obj) {
          // We have found an object with this name - search for the prototype var
          JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
          if (proto) {
            result = jsvFindChildFromString(proto, name, false);
            jsvUnLock(proto);
          }
          jsvUnLock(obj);
        }
        if (result) return result;
      }
      /* We haven't found anything in the actual object, we should check the 'Object' itself
        eg, we tried 'String', so now we should try 'Object'. Built-in types don't have room for
        a prototype field, so we hard-code it */
      objectName = jswGetBasicObjectPrototypeName(objectName);
    }
  }

  // no luck!
  return 0;
}

JsVar *jspeiGetScopesAsVar() {
  if (execInfo.scopeCount==0) return 0;
  JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  int i;
  for (i=0;i<execInfo.scopeCount;i++) {
      //printf("%d %d\n",i,execInfo.scopes[i]);
      JsVar *scope = jsvLock(execInfo.scopes[i]);
      JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(i), scope);
      jsvUnLock(scope);
      if (!idx) { // out of memort
        jspSetError();
        return arr;
      }
      jsvAddName(arr, idx);
      jsvUnLock(idx);
  }
  //printf("%d\n",arr->firstChild);
  return arr;
}

void jspeiLoadScopesFromVar(JsVar *arr) {
    execInfo.scopeCount = 0;
    //printf("%d\n",arr->firstChild);
    JsVarRef childref = arr->firstChild;
    while (childref) {
      JsVar *child = jsvLock(childref);
      //printf("%d %d %d %d\n",execInfo.scopeCount,childref,child, child->firstChild);
      execInfo.scopes[execInfo.scopeCount] = jsvRefRef(child->firstChild);
      execInfo.scopeCount++;
      childref = child->nextSibling;
      jsvUnLock(child);
    }
}
// -----------------------------------------------
#ifdef ARM
extern int _end;
#endif
bool jspCheckStackPosition() {
#ifdef ARM
  void *frame = __builtin_frame_address(0);
  if ((char*)frame < ((char*)&_end)+1024/*so many bytes leeway*/) {
//   jsiConsolePrintf("frame: %d,end:%d\n",(int)frame,(int)&_end);
    jsErrorAt("Too much recursion - the stack is about to overflow", execInfo.lex, execInfo.lex->tokenStart );
    jspSetInterrupted(true);
    return false;
  }
#endif
  return true;
}


// Set execFlags such that we are not executing
void jspSetNoExecute() {
  execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO;
}

// parse single variable name
bool jspParseVariableName() {
  JSP_MATCH(LEX_ID);
  return true;
}

// parse function with no arguments
bool jspParseEmptyFunction() {
  JSP_MATCH(LEX_ID);
  JSP_MATCH('(');
  if (execInfo.lex->tk != ')')
    jsvUnLock(jspeBase());
  // throw away extra params
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    jsvUnLock(jspeBase());
  }
  JSP_MATCH(')');
  return true;
}

// parse function with a single argument, return its value (no names!)
JsVar *jspParseSingleFunction() {
  JsVar *v = 0;
  JSP_MATCH(LEX_ID);
  JSP_MATCH('(');
  if (execInfo.lex->tk != ')')
    v = jsvSkipNameAndUnLock(jspeBase());
  // throw away extra params
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
    JSP_MATCH_WITH_RETURN(',', v);
    jsvUnLock(jspeBase());
  }
  JSP_MATCH_WITH_RETURN(')', v);
  return v;
}

/// parse function with max 4 arguments (can set arg to 0 to avoid parse). Usually first arg will be 0, but if we DON'T want to skip names on an arg stuff, we can say
bool jspParseFunction(JspSkipFlags skipName, JsVar **a, JsVar **b, JsVar **c, JsVar **d) {
  if (a) *a = 0;
  if (b) *b = 0;
  if (c) *c = 0; 
  if (d) *d = 0;
  JSP_MATCH(LEX_ID);
  JSP_MATCH('(');
  if (a && execInfo.lex->tk != ')') {
    *a = jspeBase();
    if (!(skipName&JSP_NOSKIP_A)) *a = jsvSkipNameAndUnLock(*a);
  }
  if (b && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *b = jspeBase();
    if (!(skipName&JSP_NOSKIP_B)) *b = jsvSkipNameAndUnLock(*b);
  }
  if (c && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *c = jspeBase();
    if (!(skipName&JSP_NOSKIP_C)) *c = jsvSkipNameAndUnLock(*c);
  }
  if (d && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *d = jspeBase();
    if (!(skipName&JSP_NOSKIP_D)) *d = jsvSkipNameAndUnLock(*d);
  }
  // throw away extra params
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    jsvUnLock(jspeBase());
  }
  JSP_MATCH(')');
  return true;
}

/// parse function with max 8 arguments (can set arg to 0 to avoid parse). Usually first arg will be 0, but if we DON'T want to skip names on an arg stuff, we can say
bool jspParseFunction8(JspSkipFlags skipName, JsVar **a, JsVar **b, JsVar **c, JsVar **d, JsVar **e, JsVar **f, JsVar **g, JsVar **h) {
  if (a) *a = 0;
  if (b) *b = 0;
  if (c) *c = 0;
  if (d) *d = 0;
  if (e) *e = 0;
  if (f) *f = 0;
  if (g) *g = 0;
  if (h) *h = 0;
  JSP_MATCH(LEX_ID);
  JSP_MATCH('(');
  if (a && execInfo.lex->tk != ')') {
    *a = jspeBase();
    if (!(skipName&JSP_NOSKIP_A)) *a = jsvSkipNameAndUnLock(*a);
  }
  if (b && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *b = jspeBase();
    if (!(skipName&JSP_NOSKIP_B)) *b = jsvSkipNameAndUnLock(*b);
  }
  if (c && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *c = jspeBase();
    if (!(skipName&JSP_NOSKIP_C)) *c = jsvSkipNameAndUnLock(*c);
  }
  if (d && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *d = jspeBase();
    if (!(skipName&JSP_NOSKIP_D)) *d = jsvSkipNameAndUnLock(*d);
  }
  if (e && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *e = jspeBase();
    if (!(skipName&JSP_NOSKIP_E)) *e = jsvSkipNameAndUnLock(*e);
  }
  if (f && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *f = jspeBase();
    if (!(skipName&JSP_NOSKIP_F)) *f = jsvSkipNameAndUnLock(*f);
  }
  if (g && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *g = jspeBase();
    if (!(skipName&JSP_NOSKIP_G)) *g = jsvSkipNameAndUnLock(*g);
  }
  if (h && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    *h = jspeBase();
    if (!(skipName&JSP_NOSKIP_H)) *h = jsvSkipNameAndUnLock(*h);
  }
  // throw away extra params
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
    JSP_MATCH(',');
    jsvUnLock(jspeBase());
  }
  JSP_MATCH(')');
  return true;
}

/// parse a function with any number of argument, and return an array of de-named aruments
JsVar *jspParseFunctionAsArray() {
  JSP_MATCH(LEX_ID);
  JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  if (!arr) return 0; // out of memory
  JSP_MATCH_WITH_CLEANUP_AND_RETURN('(', jsvUnLock(arr), 0);
  while (!JSP_HAS_ERROR && execInfo.lex->tk!=')' && execInfo.lex->tk!=LEX_EOF) {
    JsVar *arg = jsvSkipNameAndUnLock(jspeBase());
    jsvArrayPushAndUnLock(arr, arg); // even if undefined
    if (execInfo.lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock(arr), 0);
  }
  JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(arr), 0);
  return arr;
}

// ----------------------------------------------

// we return a value so that JSP_MATCH can return 0 if it fails (if we pass 0, we just parse all args)
bool jspeFunctionArguments(JsVar *funcVar) {
  JSP_MATCH('(');
  while (execInfo.lex->tk!=')') {
      if (funcVar) {
        JsVar *param = jsvAddNamedChild(funcVar, 0, jslGetTokenValueAsString(execInfo.lex));
        if (!param) { // out of memory
          jspSetError();
          return false;
        }
        param->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
        jsvUnLock(param);
      }
      JSP_MATCH(LEX_ID);
      if (execInfo.lex->tk!=')') JSP_MATCH(',');
  }
  JSP_MATCH(')');
  return true;
}

bool jspeParseNativeFunction(JsCallback callbackPtr) {
    char funcName[JSLEX_MAX_TOKEN_LENGTH];
    JsVar *funcVar;
    JsVar *base = jsvLockAgain(execInfo.parse->root);
    JSP_MATCH(LEX_R_FUNCTION);
    // not too bothered about speed/memory here as only called on init :)
    strncpy(funcName, jslGetTokenValueAsString(execInfo.lex), JSLEX_MAX_TOKEN_LENGTH);
    JSP_MATCH(LEX_ID);
    /* Check for dots, we might want to do something like function 'String.substring' ... */
    while (execInfo.lex->tk == '.') {
      JsVar *link;
      JSP_MATCH('.');
      link = jsvFindChildFromString(base, funcName, false);
      // if it doesn't exist, make a new object class
      if (!link) {
        JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
        link = jsvAddNamedChild(base, obj, funcName);
        jsvUnLock(obj);
      }
      // set base to the object (not the name)
      jsvUnLock(base);
      base = jsvSkipNameAndUnLock(link);
      // Look for another name
      strncpy(funcName, jslGetTokenValueAsString(execInfo.lex), JSLEX_MAX_TOKEN_LENGTH);
      JSP_MATCH(LEX_ID);
    }
    // So now, base points to an object where we want our function
    funcVar = jsvNewWithFlags(JSV_FUNCTION | JSV_NATIVE);
    if (!funcVar) {
      jsvUnLock(base);
      jspSetError();
      return false; // Out of memory
    }
    funcVar->varData.callback = callbackPtr;
    jspeFunctionArguments(funcVar);

    if (JSP_HAS_ERROR) { // probably out of memory while parsing
      jsvUnLock(base);
      jsvUnLock(funcVar);
      return false;
    }
    // Add the function with its name
    JsVar *funcNameVar = jsvFindChildFromString(base, funcName, true);
    if (funcNameVar) // could be out of memory
      jsvUnLock(jsvSetValueOfName(funcNameVar, funcVar)); // unlocks funcNameVar
    jsvUnLock(base);
    jsvUnLock(funcVar);
    return true;
}

bool jspAddNativeFunction(JsParse *parse, const char *funcDesc, JsCallback callbackPtr) {
    JsVar *fncode = jsvNewFromString(funcDesc);
    if (!fncode) return false; // out of memory!

    JSP_SAVE_EXECUTE();
    JsExecInfo oldExecInfo = execInfo;

    // Set up Lexer

    JsLex lex;
    jslInit(&lex, fncode);
    jsvUnLock(fncode);

    
    jspeiInit(parse, &lex);

    // Parse
    bool success = jspeParseNativeFunction(callbackPtr);
    if (!success) {
      jsError("Parsing Native Function failed!");
      jspSetError();
    }


    // cleanup
    jspeiKill();
    jslKill(&lex);
    JSP_RESTORE_EXECUTE();
    oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
    execInfo = oldExecInfo;

    return success;
}

JsVar *jspeFunctionDefinition() {
  // actually parse a function... We assume that the LEX_FUNCTION and name
  // have already been parsed
  JsVar *funcVar = 0;
  if (JSP_SHOULD_EXECUTE)
    funcVar = jsvNewWithFlags(JSV_FUNCTION);
  // Get arguments save them to the structure
  if (!jspeFunctionArguments(funcVar)) {
    jsvUnLock(funcVar);
    // parse failed
    return 0;
  }
  // Get the code - first parse it so we know where it stops
  JslCharPos funcBegin = execInfo.lex->tokenStart;
  JSP_SAVE_EXECUTE();
  jspSetNoExecute();
  jsvUnLock(jspeBlock());
  JSP_RESTORE_EXECUTE();
  // Then create var and set
  if (JSP_SHOULD_EXECUTE) {
    // code var
    JsVar *funcCodeVar = jsvNewFromLexer(execInfo.lex, funcBegin, (JslCharPos)(execInfo.lex->tokenLastEnd+1));
    jsvUnLock(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME));
    jsvUnLock(funcCodeVar);
    // scope var
    JsVar *funcScopeVar = jspeiGetScopesAsVar();
    if (funcScopeVar) {
      jsvUnLock(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME));
      jsvUnLock(funcScopeVar);
    }
  }
  return funcVar;
}

/* Parse just the brackets of a function - and throw
 * everything away */
bool jspeParseFunctionCallBrackets() {
  JSP_MATCH('(');
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
    jsvUnLock(jspeBase());
    if (execInfo.lex->tk!=')') JSP_MATCH(',');
  }
  if (!JSP_HAS_ERROR) JSP_MATCH(')');
  return 0;
}

/** Handle a function call (assumes we've parsed the function name and we're
 * on the start bracket). 'thisArg' is the value of the 'this' variable when the
 * function is executed (it's usually the parent object)
 *
 * If !isParsing and arg0!=0, argument 0 is set to what is supplied (same with arg1)
 *
 * functionName is used only for error reporting - and can be 0
 */
JsVar *jspeFunctionCall(JsVar *function, JsVar *functionName, JsVar *thisArg, bool isParsing, int argCount, JsVar **argPtr) {
  if (JSP_SHOULD_EXECUTE && !function) {
      jsErrorAt("Function not found! Skipping.", execInfo.lex, execInfo.lex->tokenLastStart );
      jspSetError();
  }

  if (JSP_SHOULD_EXECUTE) jspCheckStackPosition(); // try and ensure that we won't overflow our stack

  if (JSP_SHOULD_EXECUTE && function) {
    JsVar *functionRoot;
    JsVar *functionCode = 0;
    JsVar *returnVarName;
    JsVar *returnVar;
    JsVarRef v;
    if (!jsvIsFunction(function)) {
        char buf[JS_ERROR_BUF_SIZE];
        strncpy(buf, "Expecting a function to call", JS_ERROR_BUF_SIZE);
        const char *name = jswGetBasicObjectName(function);
        if (name) {
          strncat(buf, ", got a ", JS_ERROR_BUF_SIZE);
          strncat(buf, name, JS_ERROR_BUF_SIZE);
        }
        jsErrorAt(buf, execInfo.lex, execInfo.lex->tokenLastStart );
        jspSetError();
        return 0;
    }

    /** Special case - we're parsing and we hit an already-defined function
     * that has no 'code'. This means that we should use jswHandleFunctionCall
     * to try and parse it */
    if (!jsvIsNative(function)) {
      functionCode = jsvFindChildFromString(function, JSPARSE_FUNCTION_CODE_NAME, false);
      if (isParsing && !functionCode) {
        char buf[32];
        jsvGetString(functionName, buf, sizeof(buf));
        JslCharPos pos = execInfo.lex->tokenStart;
        jslSeekTo(execInfo.lex, execInfo.lex->tokenLastStart); // NASTY! because jswHandleFunctionCall expects to parse IDs
        JsVar *res = jswHandleFunctionCall(0, 0, buf);
        // but we didn't find anything - so just carry on...
        if (res!=JSW_HANDLEFUNCTIONCALL_UNHANDLED)
          return res;
        jslSeekTo(execInfo.lex, pos); // NASTY!
      }
    }

    if (isParsing) JSP_MATCH('(');
    // create a new symbol table entry for execution of this function
    // OPT: can we cache this function execution environment + param variables?
    // OPT: Probably when calling a function ONCE, use it, otherwise when recursing, make new?
    functionRoot = jsvNewWithFlags(JSV_FUNCTION);
    if (!functionRoot) { // out of memory
      jspSetError();
      return 0;
    }
    JsVar *oldThisVar = execInfo.thisVar;
    execInfo.thisVar = thisArg;
    if (isParsing) {
      int hadParams = 0;
      // grab in all parameters. We go around this loop until we've run out
      // of named parameters AND we've parsed all the supplied arguments
      v = function->firstChild;
      while (!JSP_HAS_ERROR && (v || execInfo.lex->tk!=')')) {
        JsVar *param = 0;
        if (v) param = jsvLock(v);
        bool paramDefined = jsvIsFunctionParameter(param);
        if (execInfo.lex->tk!=')' || paramDefined) {
          hadParams++;
          JsVar *value = 0;
          // ONLY parse this if it was supplied, otherwise leave 0 (undefined)
          if (execInfo.lex->tk!=')')
            value = jspeBase();
          // and if execute, copy it over
          if (JSP_SHOULD_EXECUTE) {
            value = jsvSkipNameAndUnLock(value);
            JsVar *paramName = paramDefined ? jsvCopy(param) : jsvNewFromEmptyString();
            paramName->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
            JsVar *newValueName = jsvMakeIntoVariableName(paramName, value);
            if (newValueName) { // could be out of memory
              jsvAddName(functionRoot, newValueName);
            } else
              jspSetError();
            jsvUnLock(newValueName);
          }
          jsvUnLock(value);
          if (execInfo.lex->tk!=')') JSP_MATCH(',');
        }
        if (param) {
          v = param->nextSibling;
          jsvUnLock(param);
        }
      }
      JSP_MATCH(')');
    } else if (JSP_SHOULD_EXECUTE && argCount>0) {  // and NOT isParsing
      int args = 0;
      v = function->firstChild;
      while (args<argCount) {
        JsVar *param = v ? jsvLock(v) : 0;
        bool paramDefined = jsvIsFunctionParameter(param);
        JsVar *paramName = paramDefined ? jsvCopy(param) : jsvNewFromEmptyString();
        paramName->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
        JsVar *newValueName = jsvMakeIntoVariableName(paramName, argPtr[args]);
        if (newValueName) // could be out of memory - or maybe just not supplied!
          jsvAddName(functionRoot, newValueName);
        jsvUnLock(newValueName);
        args++;
        if (param) {
          v = param->nextSibling;
          jsvUnLock(param);
        }
      }
    } 
    // setup a return variable
    returnVarName = jsvAddNamedChild(functionRoot, 0, JSPARSE_RETURN_VAR);
    if (!returnVarName) // out of memory
      jspSetError();
    //jsvTrace(jsvGetRef(functionRoot), 5); // debugging

    if (!JSP_HAS_ERROR) {
      if (jsvIsNative(function)) {
        assert(function->varData.callback);
        if (function->varData.callback)
          function->varData.callback(jsvGetRef(functionRoot));
      } else {
        // save old scopes
        JsVarRef oldScopes[JSPARSE_MAX_SCOPES];
        int oldScopeCount;
        int i;
        oldScopeCount = execInfo.scopeCount;
        for (i=0;i<execInfo.scopeCount;i++)
          oldScopes[i] = execInfo.scopes[i];
        // if we have a scope var, load it up. We may not have one if there were no scopes apart from root
        JsVar *functionScope = jsvFindChildFromString(function, JSPARSE_FUNCTION_SCOPE_NAME, false);
        if (functionScope) {
            JsVar *functionScopeVar = jsvLock(functionScope->firstChild);
            //jsvTrace(jsvGetRef(functionScopeVar),5);
            jspeiLoadScopesFromVar(functionScopeVar);
            jsvUnLock(functionScopeVar);
            jsvUnLock(functionScope);
        } else {
            // no scope var defined? We have no scopes at all!
            execInfo.scopeCount = 0;
        }
        // add the function's execute space to the symbol table so we can recurse
        if (jspeiAddScope(jsvGetRef(functionRoot))) {
          /* Adding scope may have failed - we may have descended too deep - so be sure
           * not to pull somebody else's scope off
           */

          /* we just want to execute the block, but something could
           * have messed up and left us with the wrong ScriptLex, so
           * we want to be careful here... */
          if (functionCode) {
            JsLex *oldLex;
            JsVar* functionCodeVar = jsvSkipNameAndUnLock(functionCode);
            JsLex newLex;
            jslInit(&newLex, functionCodeVar);
            jsvUnLock(functionCodeVar);

            oldLex = execInfo.lex;
            execInfo.lex = &newLex;
            JSP_SAVE_EXECUTE();
            jspeBlock();
            bool hasError = JSP_HAS_ERROR;
            JSP_RESTORE_EXECUTE(); // because return will probably have set execute to false
            jslKill(&newLex);
            execInfo.lex = oldLex;
            if (hasError) {
              jsiConsolePrint("in function ");
              if (jsvIsString(functionName)) {
                jsiConsolePrint("\"");
                jsiConsolePrintStringVar(functionName);
                jsiConsolePrint("\" ");
              }
              jsiConsolePrint("called from ");
              if (execInfo.lex)
                jsiConsolePrintPosition(execInfo.lex, execInfo.lex->tokenLastEnd);
              else
                jsiConsolePrint("system\n");
              jspSetError();
            }
          }

          jspeiRemoveScope();
        }

        // Unref old scopes
        for (i=0;i<execInfo.scopeCount;i++)
            jsvUnRefRef(execInfo.scopes[i]);
        // restore function scopes
        for (i=0;i<oldScopeCount;i++)
            execInfo.scopes[i] = oldScopes[i];
        execInfo.scopeCount = oldScopeCount;
      }
    }

    /* Return to old 'this' var. No need to unlock as we never locked before */
    execInfo.thisVar = oldThisVar;

    /* get the real return var before we remove it from our function */
    returnVar = jsvSkipNameAndUnLock(returnVarName);
    if (returnVarName) // could have failed with out of memory
      jsvSetValueOfName(returnVarName, 0); // remove return value (which helps stops circular references)
    jsvUnLock(functionRoot);
    if (returnVar)
      return returnVar;
    else
      return 0;
  } else if (isParsing) { // ---------------------------------- function, but not executing - just parse args and be done
    jspeParseFunctionCallBrackets();
    /* Do not return function, as it will be unlocked! */
    return 0;
  } else return 0;
}

JsVar *jspeFactorSingleId() {
  JsVar *a = JSP_SHOULD_EXECUTE ? jspeiFindInScopes(jslGetTokenValueAsString(execInfo.lex)) : 0;
  if (JSP_SHOULD_EXECUTE && !a) {
    const char *tokenName = jslGetTokenValueAsString(execInfo.lex); // BEWARE - this won't hang around forever!
    /* Special case! We haven't found the variable, so check out
     * and see if it's one of our builtins...  */
    if (jswIsBuiltInObject(tokenName)) {
      JsVar *obj = jspNewBuiltin(tokenName);
      if (obj) { // not out of memory
        a = jsvAddNamedChild(execInfo.parse->root, obj, tokenName);
        jsvUnLock(obj);
      }
    } else {
      a = jswHandleFunctionCall(0, 0, tokenName);
      if (a != JSW_HANDLEFUNCTIONCALL_UNHANDLED)
        return a;
      /* Variable doesn't exist! JavaScript says we should create it
       * (we won't add it here. This is done in the assignment operator)*/
      a = jsvMakeIntoVariableName(jslGetTokenValueAsVar(execInfo.lex), 0);
    }
  }
  JSP_MATCH_WITH_RETURN(LEX_ID, a);

  return a;
}

JsVar *jspeFactorMember(JsVar *a, JsVar **parentResult) {
  /* The parent if we're executing a method call */
  JsVar *parent = 0;

  while (execInfo.lex->tk=='.' || execInfo.lex->tk=='[') {
      if (execInfo.lex->tk == '.') { // ------------------------------------- Record Access
          JSP_MATCH('.');
          if (JSP_SHOULD_EXECUTE) {
            // Note: name will go away when we oarse something else!
            const char *name = jslGetTokenValueAsString(execInfo.lex);

            JsVar *aVar = jsvSkipName(a);
            JsVar *child = 0;
            if (aVar && jswGetBasicObjectName(aVar)) {
              // if we're an object (or pretending to be one)
              if (jsvHasChildren(aVar))
                child = jsvFindChildFromString(aVar, name, false);

              if (!child)
                child = jspeiFindChildFromStringInParents(aVar, name);


              if (child) {
                // it was found - no need for name ptr now, so match!
                JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
              } else { // NOT FOUND...
                /* Check for builtins via separate function
                 * This way we save on RAM for built-ins because all comes out of program code.
                 *
                 * We don't check for prototype vars, so people can overload the built
                 * in functions (eg. Person.prototype.toString). HOWEVER if we did
                 * this for 'this' then we couldn't say 'this.toString()'
                 * */
                if (!jsvIsString(a) || (!jsvIsStringEqual(a, JSPARSE_PROTOTYPE_VAR))) // don't try and use builtins on the prototype var!
                  child = jswHandleFunctionCall(aVar, a/*name*/, name);
                else
                  child = JSW_HANDLEFUNCTIONCALL_UNHANDLED;
                if (child == JSW_HANDLEFUNCTIONCALL_UNHANDLED) {
                  child = 0;
                  // It wasn't handled... We already know this is an object so just add a new child
                  if (jsvIsObject(aVar) || jsvIsFunction(aVar) || jsvIsArray(aVar)) {
                    JsVar *value = 0;
                    if (jsvIsFunction(aVar) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0)
                      value = jsvNewWithFlags(JSV_OBJECT); // prototype is supposed to be an object
                    child = jsvAddNamedChild(aVar, value, name);
                    jsvUnLock(value);
                  } else {
                    // could have been a string...
                    jsErrorAt("Field or method does not already exist, and can't create it on a non-object", execInfo.lex, execInfo.lex->tokenLastEnd);
                    jspSetError();
                  }
                  JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
                }
              }
            } else {
                jsErrorAt("Using '.' operator on non-object", execInfo.lex, execInfo.lex->tokenLastEnd);
                jspSetError();
                JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
            }
            jsvUnLock(parent);
            parent = aVar;
            jsvUnLock(a);
            a = child;
          } else {
            // Not executing, just match
            JSP_MATCH_WITH_RETURN(LEX_ID, a);
          }
      } else if (execInfo.lex->tk == '[') { // ------------------------------------- Array Access
          JsVar *index;
          JSP_MATCH('[');
          index = jspeBase();
          JSP_MATCH_WITH_CLEANUP_AND_RETURN(']', jsvUnLock(parent);jsvUnLock(index);, a);
          if (JSP_SHOULD_EXECUTE) {
            /* Index filtering (bug #19) - if we have an array index A that is:
             is_string(A) && int_to_string(string_to_int(A)) = =A
             then convert it to an integer. Should be too nasty for performance
             as we only do this when accessing an array with a string */
            if (jsvIsString(index) && jsvIsStringNumericStrict(index)) {
              JsVar *v = jsvNewFromInteger(jsvGetInteger(index));
              jsvUnLock(index);
              index = v;
            }

            JsVar *aVar = jsvSkipName(a);
            if (aVar && (jsvIsArrayBuffer(aVar))) {
              // for array buffers, we actually create a NAME, and hand that back - then when we assign (or use SkipName) we pull out the correct data
              JsVar *indexValue = jsvSkipName(index);
              jsvUnLock(a);
              a = jsvMakeIntoVariableName(jsvNewFromInteger(jsvGetInteger(indexValue)), aVar);
              jsvUnLock(indexValue);
              if (a) // turn into an 'array buffer name'
                a->flags = (a->flags & ~(JSV_NAME|JSV_VARTYPEMASK)) | JSV_ARRAYBUFFERNAME;
            } else if (aVar && (jsvIsArray(aVar) || jsvIsObject(aVar) || jsvIsFunction(aVar))) {
                // TODO: If we set to undefined, maybe we should remove the name?
                JsVar *indexValue = jsvSkipName(index);
                if (!jsvIsString(indexValue) && !jsvIsNumeric(indexValue))
                  indexValue = jsvAsString(indexValue, true);
                JsVar *child = jsvFindChildFromVar(aVar, indexValue, true);
                jsvUnLock(indexValue);

                jsvUnLock(parent);
                parent = jsvLockAgain(aVar);
                jsvUnLock(a);
                a = child;
            } else if (aVar && (jsvIsString(aVar))) {
                JsVarInt idx = jsvGetIntegerAndUnLock(jsvSkipName(index));
                JsVar *child = 0;
                if (idx>=0 && idx<(JsVarInt)jsvGetStringLength(aVar)) {
                  char ch = jsvGetCharInString(aVar, (int)idx);
                  child = jsvNewFromEmptyString();
                  if (child) jsvAppendStringBuf(child, &ch, 1);
                }
                jsvUnLock(parent);
                parent = jsvLockAgain(aVar);
                jsvUnLock(a);
                a = child;
            } else {
                jsWarnAt("Variable is not an Array or Object", execInfo.lex, execInfo.lex->tokenLastEnd);
                jsvUnLock(parent);
                parent = 0;
                jsvUnLock(a);
                a = 0;
            }
            jsvUnLock(aVar);
          }
          jsvUnLock(index);
      } else {
        assert(0);
      }
  }

  if (parentResult) *parentResult = parent;
  else jsvUnLock(parent);
  return a;
}

JsVar *jspeFactor();
void jspEnsureIsPrototype(JsVar *prototypeName);

JsVar *jspeConstruct(JsVar *func, JsVar *funcName, bool hasArgs) {
  assert(JSP_SHOULD_EXECUTE);
  if (!jsvIsFunction(func)) {
    jsErrorAt("Constructor should be a function", execInfo.lex, execInfo.lex->tokenLastEnd);
    jspSetError();
    return 0;
  }

  JsVar *thisObj = jsvNewWithFlags(JSV_OBJECT);
  // Make sure the function has a 'prototype' var
  JsVar *prototypeName = jsvFindChildFromString(func, JSPARSE_PROTOTYPE_VAR, true);
  jspEnsureIsPrototype(prototypeName); // make sure it's an object
  jsvUnLock(jsvAddNamedChild(thisObj, prototypeName, JSPARSE_INHERITS_VAR));
  jsvUnLock(prototypeName);

  JsVar *a = jspeFunctionCall(func, funcName, thisObj, hasArgs, 0, 0);

  if (a) {
    jsvUnLock(thisObj);
    thisObj = a;
  } else {
    jsvUnLock(a);
    JsVar *constructor = jsvFindChildFromString(thisObj, JSPARSE_CONSTRUCTOR_VAR, true);
    if (constructor) {
      jsvSetValueOfName(constructor, funcName);
      jsvUnLock(constructor);
    }
  }
  return thisObj;
}

JsVar *jspeFactorFunctionCall() {
  /* The parent if we're executing a method call */
  bool isConstructor = false;
  if (execInfo.lex->tk==LEX_R_NEW) {
    JSP_MATCH(LEX_R_NEW);
    isConstructor = true;

    if (execInfo.lex->tk==LEX_R_NEW) {
      jsError("Nesting 'new' operators is unsupported");
      jspSetError();
      return 0;
    }
  }

  JsVar *parent = 0;
  JsVar *a = jspeFactorMember(jspeFactor(), &parent);

  while (execInfo.lex->tk=='(' || (isConstructor && JSP_SHOULD_EXECUTE)) {
    JsVar *funcName = a;
    JsVar *func = jsvSkipName(funcName);

    /* The constructor function doesn't change parsing, so if we're
     * not executing, just short-cut it. */
    if (isConstructor && JSP_SHOULD_EXECUTE) {
      // If we have '(' parse an argument list, otherwise don't look for any args
      bool parseArgs = execInfo.lex->tk=='(';
      a = jspeConstruct(func, funcName, parseArgs);
      isConstructor = false; // don't treat subsequent brackets as constructors
    } else
      a = jspeFunctionCall(func, funcName, parent, true, 0, 0);

    jsvUnLock(funcName);
    jsvUnLock(func);

    jsvUnLock(parent); parent=0;
    a = jspeFactorMember(a, &parent);
  }

  jsvUnLock(parent);
  return a;
}

JsVar *jspeFactorId() {
  return jspeFactorSingleId();
}


JsVar *jspeFactorObject() {
  if (JSP_SHOULD_EXECUTE) {
    JsVar *contents = jsvNewWithFlags(JSV_OBJECT);
    if (!contents) { // out of memory
      jspSetError();
      return 0;
    }
    /* JSON-style object definition */
    JSP_MATCH_WITH_RETURN('{', contents);
    while (!JSP_HAS_ERROR && execInfo.lex->tk != '}') {
      JsVar *varName = 0;
      if (JSP_SHOULD_EXECUTE) {
        varName = jslGetTokenValueAsVar(execInfo.lex);
        if (!varName) { // out of memory
          return contents;
        }
      }
      // we only allow strings or IDs on the left hand side of an initialisation
      if (execInfo.lex->tk==LEX_STR) {
        JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_STR, jsvUnLock(varName), contents);
      } else {
        JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(varName), contents);
      }
      JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(varName), contents);
      if (JSP_SHOULD_EXECUTE) {
        JsVar *valueVar;
        JsVar *value = jspeBase(); // value can be 0 (could be undefined!)
        valueVar = jsvSkipNameAndUnLock(value);
        varName = jsvMakeIntoVariableName(varName, valueVar);
        jsvAddName(contents, varName);
        jsvUnLock(valueVar);
      }
      jsvUnLock(varName);
      // no need to clean here, as it will definitely be used
      if (execInfo.lex->tk != '}') JSP_MATCH_WITH_RETURN(',', contents);
    }
    JSP_MATCH_WITH_RETURN('}', contents);
    return contents;
  } else {
    // Not executing so do fast skip
    return jspeBlock();
  }
}

JsVar *jspeFactorArray() {
  int idx = 0;
  JsVar *contents = 0;
  if (JSP_SHOULD_EXECUTE) {
    contents = jsvNewWithFlags(JSV_ARRAY);
    if (!contents) { // out of memory
      jspSetError();
      return 0;
    }
  }
  /* JSON-style array */
  JSP_MATCH_WITH_RETURN('[', contents);
  while (!JSP_HAS_ERROR && execInfo.lex->tk != ']') {
    if (JSP_SHOULD_EXECUTE) {
      // OPT: Store array indices as actual ints
      JsVar *a;
      JsVar *aVar;
      JsVar *indexName;
      a = jspeBase();
      aVar = jsvSkipNameAndUnLock(a);
      indexName = jsvMakeIntoVariableName(jsvNewFromInteger(idx),  aVar);
      if (indexName) { // could be out of memory
        jsvAddName(contents, indexName);
        jsvUnLock(indexName);
      }
      jsvUnLock(aVar);
    } else {
      jsvUnLock(jspeBase());
    }
    // no need to clean here, as it will definitely be used
    if (execInfo.lex->tk != ']') JSP_MATCH_WITH_RETURN(',', contents);
    idx++;
  }
  JSP_MATCH_WITH_RETURN(']', contents);
  return contents;
}

void jspEnsureIsPrototype(JsVar *prototypeName) {
  if (!prototypeName) return;
  JsVar *prototypeVar = jsvSkipName(prototypeName);
  if (!jsvIsObject(prototypeVar)) {
    if (!jsvIsUndefined(prototypeVar))
      jsWarn("Prototype is not an Object, so setting it to {}");    
    jsvUnLock(prototypeVar);
    prototypeVar = jsvNewWithFlags(JSV_OBJECT); // prototype is supposed to be an object
    JsVar *lastName = jsvSkipToLastName(prototypeName);
    jsvSetValueOfName(lastName, prototypeVar);
    jsvUnLock(lastName);
  }
  jsvUnLock(prototypeVar);
}

JsVar *jspeFactorTypeOf() {
  JSP_MATCH(LEX_R_TYPEOF);
  JsVar *a = jspeBase();
  JsVar *result = 0;
  if (JSP_SHOULD_EXECUTE) {
    a = jsvSkipNameAndUnLock(a);
    result=jsvNewFromString(jsvGetTypeOf(a));
  }
  jsvUnLock(a);
  return result;
}

JsVar *jspeFactor() {
    if (execInfo.lex->tk=='(') {
        JsVar *a = 0;
        JSP_MATCH('(');
        if (jspCheckStackPosition())
          a = jspeBaseWithComma();
        if (!JSP_HAS_ERROR) JSP_MATCH_WITH_RETURN(')',a);
        return a;
    } else if (execInfo.lex->tk==LEX_R_TRUE) {
        JSP_MATCH(LEX_R_TRUE);
        return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0;
    } else if (execInfo.lex->tk==LEX_R_FALSE) {
        JSP_MATCH(LEX_R_FALSE);
        return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0;
    } else if (execInfo.lex->tk==LEX_R_NULL) {
        JSP_MATCH(LEX_R_NULL);
        return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0;
    } else if (execInfo.lex->tk==LEX_R_UNDEFINED) {
        JSP_MATCH(LEX_R_UNDEFINED);
        return 0;
    } else if (execInfo.lex->tk==LEX_ID) {
      return jspeFactorId();
    } else if (execInfo.lex->tk==LEX_INT) {
        // atol works only on decimals
        // strtol handles 0x12345 as well
        //JsVarInt v = (JsVarInt)atol(jslGetTokenValueAsString(execInfo.lex));
        //JsVarInt v = (JsVarInt)strtol(jslGetTokenValueAsString(execInfo.lex),0,0); // broken on PIC
        if (JSP_SHOULD_EXECUTE) {
          JsVarInt v = stringToInt(jslGetTokenValueAsString(execInfo.lex));
          JSP_MATCH(LEX_INT);
          return jsvNewFromInteger(v);
        } else {
          JSP_MATCH(LEX_INT);
          return 0;
        }
    } else if (execInfo.lex->tk==LEX_FLOAT) {
      if (JSP_SHOULD_EXECUTE) {
        JsVarFloat v = stringToFloat(jslGetTokenValueAsString(execInfo.lex));
        JSP_MATCH(LEX_FLOAT);
        return jsvNewFromFloat(v);
      } else {
        JSP_MATCH(LEX_FLOAT);
        return 0;
      }
    } else if (execInfo.lex->tk==LEX_STR) {
      if (JSP_SHOULD_EXECUTE) {
        JsVar *a = jslGetTokenValueAsVar(execInfo.lex);
        JSP_MATCH_WITH_RETURN(LEX_STR, a);
        return a;
      } else {
        JSP_MATCH(LEX_STR);
        return 0;
      }
    } else if (execInfo.lex->tk=='{') {
      return jspeFactorObject();
    } else if (execInfo.lex->tk=='[') {
        return jspeFactorArray();
    } else if (execInfo.lex->tk==LEX_R_FUNCTION) {
      JSP_MATCH(LEX_R_FUNCTION);
      return jspeFunctionDefinition();
    } else if (execInfo.lex->tk==LEX_R_THIS) {
      JSP_MATCH(LEX_R_THIS);
      return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.parse->root );
    } else if (execInfo.lex->tk==LEX_R_TYPEOF) {
      return jspeFactorTypeOf();
    } else if (execInfo.lex->tk==LEX_R_VOID) {
      JSP_MATCH(LEX_R_VOID);
      jsvUnLock(jspeFactor());
      return 0;
    }
    // Nothing we can do here... just hope it's the end...
    JSP_MATCH(LEX_EOF);
    return 0;
}

__attribute((noinline)) JsVar *__jspePostfix(JsVar *a) {
  while (execInfo.lex->tk==LEX_PLUSPLUS || execInfo.lex->tk==LEX_MINUSMINUS) {
    int op = execInfo.lex->tk;
    JSP_MATCH(execInfo.lex->tk);
    if (JSP_SHOULD_EXECUTE) {
        JsVar *one = jsvNewFromInteger(1);
        JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
        JsVar *oldValue;
        jsvUnLock(one);
        oldValue = jsvSkipName(a); // keep the old value
        // in-place add/subtract
        jspReplaceWith(a, res);
        jsvUnLock(res);
        // but then use the old value
        jsvUnLock(a);
        a = oldValue;
    }
  }
  return a;
}

JsVar *jspePostfix() {
  JsVar *a;
  if (execInfo.lex->tk==LEX_PLUSPLUS || execInfo.lex->tk==LEX_MINUSMINUS) {
      int op = execInfo.lex->tk;
      JSP_MATCH(execInfo.lex->tk);
      a = jspePostfix();
      if (JSP_SHOULD_EXECUTE) {
          JsVar *one = jsvNewFromInteger(1);
          JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
          jsvUnLock(one);
          // in-place add/subtract
          jspReplaceWith(a, res);
          jsvUnLock(res);
      }
  } else
    a = jspeFactorFunctionCall();
  return __jspePostfix(a);
}

JsVar *jspeUnary() {
    if (execInfo.lex->tk=='!' || execInfo.lex->tk=='~' || execInfo.lex->tk=='-' || execInfo.lex->tk=='+') {
      short tk = execInfo.lex->tk;
      JSP_MATCH(execInfo.lex->tk);
      if (!JSP_SHOULD_EXECUTE) {
        return jspePostfix();
      }
      if (tk=='!') { // logical not
        return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnary())));
      } else if (tk=='~') { // bitwise not
        return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnary())));
      } else if (tk=='-') { // unary minus
        return jsvNegateAndUnLock(jspeUnary()); // names already skipped
      }  else if (tk=='+') { // unary plus (convert to number)
        return jsvAsNumber(jspeUnary()); // names already skipped
      }
      assert(0);
      return 0;
    } else
      return jspePostfix();
}

__attribute((noinline)) JsVar *__jspeTerm(JsVar *a) {
    while (execInfo.lex->tk=='*' || execInfo.lex->tk=='/' || execInfo.lex->tk=='%') {
        JsVar *b;
        int op = execInfo.lex->tk;
        JSP_MATCH(execInfo.lex->tk);
        b = jspeUnary();
        if (JSP_SHOULD_EXECUTE) {
          JsVar *res = jsvMathsOpSkipNames(a, b, op);
          jsvUnLock(a); a = res;
        }
        jsvUnLock(b);
    }
    return a;
}

JsVar *jspeTerm() {
    return __jspeTerm(jspeUnary());
}

__attribute((noinline)) JsVar *__jspeExpression(JsVar *a) {
  while (execInfo.lex->tk=='+' || execInfo.lex->tk=='-') {
      int op = execInfo.lex->tk;
      JSP_MATCH(execInfo.lex->tk);
      JsVar *b = jspeTerm();
      if (JSP_SHOULD_EXECUTE) {
          // not in-place, so just replace
        JsVar *res = jsvMathsOpSkipNames(a, b, op);
        jsvUnLock(a); a = res;
      }
      jsvUnLock(b);
  }
  return a;
}


JsVar *jspeExpression() {
    return __jspeExpression(jspeTerm());
}

__attribute((noinline)) JsVar *__jspeShift(JsVar *a) {
  if (execInfo.lex->tk==LEX_LSHIFT || execInfo.lex->tk==LEX_RSHIFT || execInfo.lex->tk==LEX_RSHIFTUNSIGNED) {
    JsVar *b;
    int op = execInfo.lex->tk;
    JSP_MATCH(op);
    b = jspeExpression();
    if (JSP_SHOULD_EXECUTE) {
      JsVar *res = jsvMathsOpSkipNames(a, b, op);
      jsvUnLock(a); a = res;
    }
    jsvUnLock(b);
  }
  return a;
}

JsVar *jspeShift() {
  return __jspeShift(jspeExpression());
}

__attribute((noinline)) JsVar *__jspeCondition(JsVar *a) {
    JsVar *b;
    while (execInfo.lex->tk==LEX_EQUAL || execInfo.lex->tk==LEX_NEQUAL ||
           execInfo.lex->tk==LEX_TYPEEQUAL || execInfo.lex->tk==LEX_NTYPEEQUAL ||
           execInfo.lex->tk==LEX_LEQUAL || execInfo.lex->tk==LEX_GEQUAL ||
           execInfo.lex->tk=='<' || execInfo.lex->tk=='>' ||
           execInfo.lex->tk==LEX_R_INSTANCEOF ||
           (execInfo.lex->tk==LEX_R_IN && !(execInfo.execute&EXEC_FOR_INIT))) {
        int op = execInfo.lex->tk;
        JSP_MATCH(execInfo.lex->tk);
        b = jspeShift();
        if (JSP_SHOULD_EXECUTE) {
          JsVar *res = 0;
          if (op==LEX_R_IN) {
            JsVar *av = jsvSkipName(a);
            JsVar *bv = jsvSkipName(b);
            if (jsvIsArray(bv) || jsvIsObject(bv)) {
              JsVar *varFound = jsvGetArrayIndexOf(bv, av, false/*not exact*/); // ArrayIndexOf will return 0 if not found
              res = jsvNewFromBool(varFound!=0);
              jsvUnLock(varFound);
            } // else it will be undefined
            jsvUnLock(av);
            jsvUnLock(bv);
          } else if (op==LEX_R_INSTANCEOF) {
            bool inst = false;
            JsVar *av = jsvSkipName(a);
            JsVar *bv = jsvSkipName(b);
            if (!jsvIsFunction(bv)) {
              jsErrorAt("Expecting a function on RHS in instanceof check", execInfo.lex, execInfo.lex->tokenLastEnd);
              jspSetError();
            } else {
              if (jsvIsObject(av)) {
                JsVar *constructor = jsvObjectGetChild(av, JSPARSE_CONSTRUCTOR_VAR, 0);
                if (constructor==bv) inst=true;
                else inst = jspIsConstructor(bv,"Object");
                jsvUnLock(constructor);
              } else {
                const char *name = jswGetBasicObjectName(av);
                if (name) {
                  inst = jspIsConstructor(bv, name);
                }
              }
            }
            jsvUnLock(av);
            jsvUnLock(bv);
            res = jsvNewFromBool(inst);
          } else {
            res = jsvMathsOpSkipNames(a, b, op);

          }
          jsvUnLock(a); a = res;
        }
        jsvUnLock(b);
    }
    return a;
}

JsVar *jspeCondition() {
  return __jspeCondition(jspeShift());
}

__attribute((noinline)) JsVar *__jspeLogic(JsVar *a) {
    JsVar *b = 0;
    while (execInfo.lex->tk=='&' || execInfo.lex->tk=='|' || execInfo.lex->tk=='^' || execInfo.lex->tk==LEX_ANDAND || execInfo.lex->tk==LEX_OROR) {
        bool shortCircuit = false;
        bool boolean = false;
        int op = execInfo.lex->tk;
        JSP_MATCH(execInfo.lex->tk);
        
        // if we have short-circuit ops, then if we know the outcome
        // we don't bother to execute the other op. Even if not
        // we need to tell mathsOp it's an & or |
        if (op==LEX_ANDAND) {
            op = '&';
            shortCircuit = !jsvGetBoolAndUnLock(jsvSkipName(a));
            boolean = true;
        } else if (op==LEX_OROR) {
            op = '|';
            shortCircuit = jsvGetBoolAndUnLock(jsvSkipName(a));
            boolean = true;
        }
        
        JSP_SAVE_EXECUTE();
        if (shortCircuit) jspSetNoExecute(); 
        b = jspeCondition();
        if (shortCircuit) JSP_RESTORE_EXECUTE();
        if (JSP_SHOULD_EXECUTE && !shortCircuit) {
            JsVar *res;
            if (boolean) {
              JsVar *newa = jsvNewFromBool(jsvGetBoolAndUnLock(jsvSkipName(a)));
              JsVar *newb = jsvNewFromBool(jsvGetBoolAndUnLock(jsvSkipName(b)));
              jsvUnLock(a); a = newa;
              jsvUnLock(b); b = newb;
            }
            res = jsvMathsOpSkipNames(a, b, op);
            jsvUnLock(a); a = res;
        }
        jsvUnLock(b);
    }
    return a;
}

JsVar *jspeLogic() {
  return __jspeLogic(jspeCondition());
}

__attribute((noinline)) JsVar *__jspeTernary(JsVar *lhs) {
  if (execInfo.lex->tk=='?') {
    JSP_MATCH('?');
    if (!JSP_SHOULD_EXECUTE) {
      // just let lhs pass through
      jsvUnLock(jspeBase());
      JSP_MATCH(':');
      jsvUnLock(jspeBase());
    } else {
      bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs));
      jsvUnLock(lhs);
      if (first) {
        lhs = jspeBase();
        JSP_MATCH(':');
        JSP_SAVE_EXECUTE();
        jspSetNoExecute();
        jsvUnLock(jspeBase());
        JSP_RESTORE_EXECUTE();
      } else {
        JSP_SAVE_EXECUTE();
        jspSetNoExecute();
        jsvUnLock(jspeBase());
        JSP_RESTORE_EXECUTE();
        JSP_MATCH(':');
        lhs = jspeBase();
      }
    }
  }

  return lhs;
}

JsVar *jspeTernary() {
  return __jspeTernary(jspeLogic());
}

__attribute((noinline)) JsVar *__jspeBase(JsVar *lhs) {
    if (execInfo.lex->tk=='=' || execInfo.lex->tk==LEX_PLUSEQUAL || execInfo.lex->tk==LEX_MINUSEQUAL ||
                                 execInfo.lex->tk==LEX_MULEQUAL || execInfo.lex->tk==LEX_DIVEQUAL || execInfo.lex->tk==LEX_MODEQUAL ||
                                 execInfo.lex->tk==LEX_ANDEQUAL || execInfo.lex->tk==LEX_OREQUAL ||
                                 execInfo.lex->tk==LEX_XOREQUAL || execInfo.lex->tk==LEX_RSHIFTEQUAL ||
                                 execInfo.lex->tk==LEX_LSHIFTEQUAL || execInfo.lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
        JsVar *rhs;
        /* If we're assigning to this and we don't have a parent,
         * add it to the symbol table root as per JavaScript. */
        if (JSP_SHOULD_EXECUTE && lhs && !lhs->refs) {
          if (jsvIsName(lhs)/* && jsvGetStringLength(lhs)>0*/) {
            if (!jsvIsArrayBufferName(lhs))
              jsvAddName(execInfo.parse->root, lhs);
          } else // TODO: Why was this here? can it happen?
            jsWarnAt("Trying to assign to an un-named type\n", execInfo.lex, execInfo.lex->tokenLastEnd);
        }

        int op = execInfo.lex->tk;
        JSP_MATCH(execInfo.lex->tk);
        rhs = jspeBase();
        rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
        if (JSP_SHOULD_EXECUTE && lhs) {
            if (op=='=') {
                jspReplaceWith(lhs, rhs);
            } else {
                if (op==LEX_PLUSEQUAL) op='+';
                else if (op==LEX_MINUSEQUAL) op='-';
                else if (op==LEX_MULEQUAL) op='*';
                else if (op==LEX_DIVEQUAL) op='/';
                else if (op==LEX_MODEQUAL) op='%';
                else if (op==LEX_ANDEQUAL) op='&';
                else if (op==LEX_OREQUAL) op='|';
                else if (op==LEX_XOREQUAL) op='^';
                else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
                else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
                else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
                if (op=='+' && jsvIsName(lhs)) {
                  JsVar *currentValue = jsvSkipName(lhs);
                  if (jsvIsString(currentValue) && currentValue->refs==1) {
                    /* A special case for string += where this is the only use of the string,
                     * as we may be able to do a simple append (rather than clone + append)*/
                    JsVar *str = jsvAsString(rhs, false);
                    jsvAppendStringVarComplete(currentValue, str);
                    jsvUnLock(str);
                    op = 0;
                  }
                  jsvUnLock(currentValue);
                }
                if (op) {
                  /* Fallback which does a proper add */
                  JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
                  jspReplaceWith(lhs, res);
                  jsvUnLock(res);
                }
            }
        }
        jsvUnLock(rhs);
    }
    return lhs;
}


JsVar *jspeBase() {
  return __jspeBase(jspeTernary());
}

// jspeBase where ',' is allowed to add multiple expressions
JsVar *jspeBaseWithComma() {
  while (!JSP_HAS_ERROR) {
    JsVar *a = jspeBase();
    if (execInfo.lex->tk!=',') return a;
    // if we get a comma, we just forget this data and parse the next bit...
    jsvUnLock(a);
    JSP_MATCH(',');
  }
  return 0;
}

JsVar *jspeBlock() {
    JSP_MATCH('{');
    if (JSP_SHOULD_EXECUTE) {
      while (execInfo.lex->tk && execInfo.lex->tk!='}') {
        jsvUnLock(jspeStatement());
        if (JSP_HAS_ERROR) {
          if (execInfo.lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) {
            execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED);
            jsiConsolePrint("at ");
            jsiConsolePrintPosition(execInfo.lex, execInfo.lex->tokenLastEnd);
            jsiConsolePrintTokenLineMarker(execInfo.lex, execInfo.lex->tokenLastEnd);
          }
          return 0;
        }
      }
      JSP_MATCH('}');
    } else {
      // fast skip of blocks
      int brackets = 1;
      while (execInfo.lex->tk && brackets) {
        if (execInfo.lex->tk == '{') brackets++;
        if (execInfo.lex->tk == '}') brackets--;
        JSP_MATCH(execInfo.lex->tk);
      }
    }
    return 0;
}

JsVar *jspeBlockOrStatement() {
    if (execInfo.lex->tk=='{') 
       return jspeBlock();
    else {
       JsVar *v = jspeStatement();
       if (execInfo.lex->tk==';') JSP_MATCH(';');
       return v;
    }
}

JsVar *jspeStatementVar() {
  JsVar *lastDefined = 0;
   /* variable creation. TODO - we need a better way of parsing the left
    * hand side. Maybe just have a flag called can_create_var that we
    * set and then we parse as if we're doing a normal equals.*/
   JSP_MATCH(LEX_R_VAR);
   bool hasComma = true; // for first time in loop
   while (hasComma && execInfo.lex->tk == LEX_ID) {
     JsVar *a = 0;
     if (JSP_SHOULD_EXECUTE) {
       a = jspeiFindOnTop(jslGetTokenValueAsString(execInfo.lex), true);
       if (!a) { // out of memory
         jspSetError();
         return lastDefined;
       }
     }
     JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined);
     // now do stuff defined with dots
     while (execInfo.lex->tk == '.') {
         JSP_MATCH_WITH_CLEANUP_AND_RETURN('.', jsvUnLock(a), lastDefined);
         if (JSP_SHOULD_EXECUTE) {
             JsVar *lastA = a;
             a = jsvFindChildFromString(lastA, jslGetTokenValueAsString(execInfo.lex), true);
             jsvUnLock(lastA);
         }
         JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined);
     }
     // sort out initialiser
     if (execInfo.lex->tk == '=') {
         JsVar *var;
         JSP_MATCH_WITH_CLEANUP_AND_RETURN('=', jsvUnLock(a), lastDefined);
         var = jsvSkipNameAndUnLock(jspeBase());
         if (JSP_SHOULD_EXECUTE)
             jspReplaceWith(a, var);
         jsvUnLock(var);
     }
     jsvUnLock(lastDefined);
     lastDefined = a;
     hasComma = execInfo.lex->tk == ',';
     if (hasComma) JSP_MATCH_WITH_RETURN(',', lastDefined);
   }
   return lastDefined;
}

JsVar *jspeStatementIf() {
  bool cond;
  JsVar *var;
  JSP_MATCH(LEX_R_IF);
  JSP_MATCH('(');
  var = jspeBase();
  JSP_MATCH(')');
  cond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(var));
  jsvUnLock(var);

  JSP_SAVE_EXECUTE();
  if (!cond) jspSetNoExecute();
  jsvUnLock(jspeBlockOrStatement());
  if (!cond) JSP_RESTORE_EXECUTE();
  if (execInfo.lex->tk==LEX_R_ELSE) {
      //JSP_MATCH(';'); ???
      JSP_MATCH(LEX_R_ELSE);
      JSP_SAVE_EXECUTE();
      if (cond) jspSetNoExecute();
      jsvUnLock(jspeBlockOrStatement());
      if (cond) JSP_RESTORE_EXECUTE();
  }
  return 0;
}

JsVar *jspeStatementSwitch() {
  JSP_MATCH(LEX_R_SWITCH);
  JSP_MATCH('(');
  JsVar *switchOn = jspeBase();
  JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(switchOn), 0);
  JSP_MATCH_WITH_CLEANUP_AND_RETURN('{', jsvUnLock(switchOn), 0);
  JSP_SAVE_EXECUTE();
  bool execute = JSP_SHOULD_EXECUTE;
  bool hasExecuted = false;
  if (execute) execInfo.execute=EXEC_NO|EXEC_IN_SWITCH;
  while (execInfo.lex->tk==LEX_R_CASE) {
    JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_CASE, jsvUnLock(switchOn), 0);
    JsExecFlags oldFlags = execInfo.execute;
    if (execute) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
    JsVar *test = jspeBase();
    execInfo.execute = oldFlags|EXEC_IN_SWITCH;;
    JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(switchOn);jsvUnLock(test), 0);
    bool cond = false;
    if (execute)
      cond = jsvGetBoolAndUnLock(jsvMathsOpSkipNames(switchOn, test, LEX_EQUAL));
    if (cond) hasExecuted = true;
    jsvUnLock(test);
    if (cond && (execInfo.execute&EXEC_RUN_MASK)==EXEC_NO)
      execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
    while (!JSP_HAS_ERROR && execInfo.lex->tk!=LEX_EOF && execInfo.lex->tk!=LEX_R_CASE && execInfo.lex->tk!=LEX_R_DEFAULT && execInfo.lex->tk!='}')
      jsvUnLock(jspeBlockOrStatement());
  }
  jsvUnLock(switchOn);
  if (execute && (execInfo.execute&EXEC_RUN_MASK)==EXEC_BREAK)
    execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
  JSP_RESTORE_EXECUTE();

  if (execInfo.lex->tk==LEX_R_DEFAULT) {
    JSP_MATCH(LEX_R_DEFAULT);
    JSP_MATCH(':');
    JSP_SAVE_EXECUTE();
    if (hasExecuted) jspSetNoExecute();
    while (!JSP_HAS_ERROR && execInfo.lex->tk!=LEX_EOF && execInfo.lex->tk!='}')
      jsvUnLock(jspeBlockOrStatement());
    JSP_RESTORE_EXECUTE();
  }
  JSP_MATCH('}');
  return 0;
}

JsVar *jspeStatementWhile() {
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
  int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
#endif
  JsVar *cond;
  bool loopCond;
  bool hasHadBreak = false;
  // We do repetition by pulling out the string representing our statement
  // there's definitely some opportunity for optimisation here
  JSP_MATCH(LEX_R_WHILE);
  JSP_MATCH('(');
  JslCharPos whileCondStart = execInfo.lex->tokenStart;
  cond = jspeBase();
  loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
  jsvUnLock(cond);
  JSP_MATCH(')');
  JslCharPos whileBodyStart = execInfo.lex->tokenStart;
  JSP_SAVE_EXECUTE();
  // actually try and execute first bit of while loop (we'll do the rest in the actual loop later)
  if (!loopCond) jspSetNoExecute();
  execInfo.execute |= EXEC_IN_LOOP;
  jsvUnLock(jspeBlockOrStatement());
  JslCharPos whileBodyEnd = execInfo.lex->tokenStart;
  execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  if (execInfo.execute == EXEC_CONTINUE)
    execInfo.execute = EXEC_YES;
  if (execInfo.execute == EXEC_BREAK) {
    execInfo.execute = EXEC_YES;
    hasHadBreak = true; // fail loop condition, so we exit
  }
  if (!loopCond) JSP_RESTORE_EXECUTE();

  while (!hasHadBreak && loopCond
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
         && loopCount-->0
#endif
         ) {
      jslSeekTo(execInfo.lex, whileCondStart);
      cond = jspeBase();
      loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
      jsvUnLock(cond);
      if (loopCond) {
          jslSeekTo(execInfo.lex, whileBodyStart);
          execInfo.execute |= EXEC_IN_LOOP;
          jsvUnLock(jspeBlockOrStatement());
          execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
          if (execInfo.execute == EXEC_CONTINUE)
            execInfo.execute = EXEC_YES;
          if (execInfo.execute == EXEC_BREAK) {
            execInfo.execute = EXEC_YES;
            hasHadBreak = true;
          }
      }
  }
  jslSeekTo(execInfo.lex, whileBodyEnd);
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
  if (loopCount<=0) {
    jsErrorAt("WHILE Loop exceeded the maximum number of iterations (" STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS) ")", execInfo.lex, execInfo.lex->tokenLastEnd);
    jspSetError();
  }
#endif
  return 0;
}

JsVar *jspeStatementFor() {
  JSP_MATCH(LEX_R_FOR);
  JSP_MATCH('(');
  execInfo.execute |= EXEC_FOR_INIT;
  // initialisation
  JsVar *forStatement = 0;
  // we could have 'for (;;)' - so don't munch up our semicolon if that's all we have
  if (execInfo.lex->tk != ';') 
    forStatement = jspeStatement(); 
  execInfo.execute &= (JsExecFlags)~EXEC_FOR_INIT;
  if (execInfo.lex->tk == LEX_R_IN) {
    // for (i in array)
    // where i = jsvUnLock(forStatement);
    if (!jsvIsName(forStatement)) {
      jsvUnLock(forStatement);
      jsErrorAt("FOR a IN b - 'a' must be a variable name", execInfo.lex, execInfo.lex->tokenLastEnd);
      jspSetError();
      return 0;
    }
    bool addedIteratorToScope = false;
    if (JSP_SHOULD_EXECUTE && !forStatement->refs) {
      // if the variable did not exist, add it to the scope
      addedIteratorToScope = true;
      jsvAddName(execInfo.parse->root, forStatement);
    }
    JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_IN, jsvUnLock(forStatement), 0);
    JsVar *array = jsvSkipNameAndUnLock(jspeExpression());
    JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(forStatement);jsvUnLock(array), 0);
    JslCharPos forBodyStart = execInfo.lex->tokenStart;
    JSP_SAVE_EXECUTE();
    jspSetNoExecute();
    execInfo.execute |= EXEC_IN_LOOP;
    jsvUnLock(jspeBlockOrStatement());
    JslCharPos forBodyEnd = execInfo.lex->tokenStart;
    execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
    JSP_RESTORE_EXECUTE();

    if (jsvIsIterable(array)) {
      bool (*checkerFunction)(JsVar*) = 0;
      if (jsvIsFunction(array)) checkerFunction = jsvIsInternalFunctionKey;
      else if (jsvIsObject(array)) checkerFunction = jsvIsInternalObjectKey;
      JsvIterator it;
      jsvIteratorNew(&it, array);
      bool hasHadBreak = false;
      while (JSP_SHOULD_EXECUTE && jsvIteratorHasElement(&it) && !hasHadBreak) {
          JsVar *loopIndexVar = jsvIteratorGetKey(&it);
          bool ignore = false;
          if (checkerFunction && checkerFunction(loopIndexVar))
            ignore = true;
          if (!ignore) {
            JsVar *indexValue = jsvIsName(loopIndexVar) ?
                                  jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) :
                                  loopIndexVar;
            if (indexValue) { // could be out of memory
              assert(!jsvIsName(indexValue) && indexValue->refs==0);
              jsvSetValueOfName(forStatement, indexValue);
              if (indexValue!=loopIndexVar) jsvUnLock(indexValue);
  
              jsvIteratorNext(&it);
 
              jslSeekTo(execInfo.lex, forBodyStart);
              execInfo.execute |= EXEC_IN_LOOP;
              jsvUnLock(jspeBlockOrStatement());
              execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;

              if (execInfo.execute == EXEC_CONTINUE)
                execInfo.execute = EXEC_YES;
              if (execInfo.execute == EXEC_BREAK) {
                execInfo.execute = EXEC_YES;
                hasHadBreak = true;
              }
            }
          } else
            jsvIteratorNext(&it);
          jsvUnLock(loopIndexVar);
      }
      jsvIteratorFree(&it);
    } else {
      jsErrorAt("FOR loop can only iterate over Arrays, Strings or Objects", execInfo.lex, execInfo.lex->tokenLastEnd);
      jspSetError();
    }

    jslSeekTo(execInfo.lex, forBodyEnd);

    if (addedIteratorToScope) {
      jsvRemoveChild(execInfo.parse->root, forStatement);
    }
    jsvUnLock(forStatement);
    jsvUnLock(array);
  } else { // NORMAL FOR LOOP
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
    int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
#endif
    bool loopCond = true;
    bool hasHadBreak = false;

    jsvUnLock(forStatement);
    JSP_MATCH(';');
    JslCharPos forCondStart = execInfo.lex->tokenStart;
    if (execInfo.lex->tk != ';') {
      JsVar *cond = jspeBase(); // condition
      loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
      jsvUnLock(cond);
    }
    JSP_MATCH(';');
    JslCharPos forIterStart = execInfo.lex->tokenStart;
    if (execInfo.lex->tk != ')')  { // we could have 'for (;;)'
      JSP_SAVE_EXECUTE();
      jspSetNoExecute();
      jsvUnLock(jspeBase()); // iterator
      JSP_RESTORE_EXECUTE();
    }
    JSP_MATCH(')');

    JslCharPos forBodyStart = execInfo.lex->tokenStart; // actual for body
    JSP_SAVE_EXECUTE();
    if (!loopCond) jspSetNoExecute();
    execInfo.execute |= EXEC_IN_LOOP;
    jsvUnLock(jspeBlockOrStatement());
    JslCharPos forBodyEnd = execInfo.lex->tokenStart;
    execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
    if (execInfo.execute == EXEC_CONTINUE)
      execInfo.execute = EXEC_YES;
    if (execInfo.execute == EXEC_BREAK) {
      execInfo.execute = EXEC_YES;
      hasHadBreak = true;
    }
    if (!loopCond) JSP_RESTORE_EXECUTE();
    if (loopCond) {
        jslSeekTo(execInfo.lex, forIterStart);
        if (execInfo.lex->tk != ')') jsvUnLock(jspeBase());
    }
    while (!hasHadBreak && JSP_SHOULD_EXECUTE && loopCond
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
           && loopCount-->0
#endif
           ) {
        jslSeekTo(execInfo.lex, forCondStart);
        ;
        if (execInfo.lex->tk == ';') {
          loopCond = true;
        } else {
          JsVar *cond = jspeBase();
          loopCond = jsvGetBoolAndUnLock(jsvSkipName(cond));
          jsvUnLock(cond);
        }
        if (JSP_SHOULD_EXECUTE && loopCond) {
            jslSeekTo(execInfo.lex, forBodyStart);
            execInfo.execute |= EXEC_IN_LOOP;
            jsvUnLock(jspeBlockOrStatement());
            execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
            if (execInfo.execute == EXEC_CONTINUE)
              execInfo.execute = EXEC_YES;
            if (execInfo.execute == EXEC_BREAK) {
              execInfo.execute = EXEC_YES;
              hasHadBreak = true;
            }
        }
        if (JSP_SHOULD_EXECUTE && loopCond) {
            jslSeekTo(execInfo.lex, forIterStart);
            if (execInfo.lex->tk != ')') jsvUnLock(jspeBase());
        }
    }
    jslSeekTo(execInfo.lex, forBodyEnd);
#ifdef JSPARSE_MAX_LOOP_ITERATIONS
    if (loopCount<=0) {
        jsErrorAt("FOR Loop exceeded the maximum number of iterations ("STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS)")", execInfo.lex, execInfo.lex->tokenLastEnd);
        jspSetError();
    }
#endif
  }
  return 0;
}

JsVar *jspeStatementReturn() {
  JsVar *result = 0;
  JSP_MATCH(LEX_R_RETURN);
  if (execInfo.lex->tk != ';') {
    // we only want the value, so skip the name if there was one
    result = jsvSkipNameAndUnLock(jspeBaseWithComma());
  }
  if (JSP_SHOULD_EXECUTE) {
    JsVar *resultVar = jspeiFindOnTop(JSPARSE_RETURN_VAR, false);
    if (resultVar) {
      jspReplaceWith(resultVar, result);
      jsvUnLock(resultVar);
    } else {
      jsErrorAt("RETURN statement, but not in a function.\n", execInfo.lex, execInfo.lex->tokenLastEnd);
      jspSetError();
    }
    jspSetNoExecute(); // Stop anything else in this function executing
  }
  jsvUnLock(result);
  return 0;
}

JsVar *jspeStatementFunctionDecl() {
  JsVar *funcName = 0;
  JsVar *funcVar;
  JSP_MATCH(LEX_R_FUNCTION);
  if (JSP_SHOULD_EXECUTE)
    funcName = jsvMakeIntoVariableName(jsvNewFromString(jslGetTokenValueAsString(execInfo.lex)), 0);
  if (!funcName) { // out of memory
    jspSetError();
    return 0;
  }
  JSP_MATCH(LEX_ID);
  funcVar = jspeFunctionDefinition();
  if (JSP_SHOULD_EXECUTE) {
    // find a function with the same name (or make one)
    // OPT: can Find* use just a JsVar that is a 'name'?
    JsVar *existingFunc = jspeiFindNameOnTop(funcName, true);
    // replace it
    jspReplaceWith(existingFunc, funcVar);
    jsvUnLock(funcName);
    funcName = existingFunc;
  }
  jsvUnLock(funcVar);
  return funcName;
}

JsVar *jspeStatement() {
    if (execInfo.lex->tk==LEX_ID ||
        execInfo.lex->tk==LEX_INT ||
        execInfo.lex->tk==LEX_FLOAT ||
        execInfo.lex->tk==LEX_STR ||
        execInfo.lex->tk==LEX_R_NEW ||
        execInfo.lex->tk==LEX_R_NULL ||
        execInfo.lex->tk==LEX_R_UNDEFINED ||
        execInfo.lex->tk==LEX_R_TRUE ||
        execInfo.lex->tk==LEX_R_FALSE ||
        execInfo.lex->tk==LEX_R_THIS ||
        execInfo.lex->tk==LEX_R_TYPEOF ||
        execInfo.lex->tk==LEX_R_VOID ||
        execInfo.lex->tk==LEX_PLUSPLUS ||
        execInfo.lex->tk==LEX_MINUSMINUS ||
        execInfo.lex->tk=='!' ||
        execInfo.lex->tk=='-' ||
        execInfo.lex->tk=='+' ||
        execInfo.lex->tk=='~' ||
        execInfo.lex->tk=='[' ||
        execInfo.lex->tk=='(') {
        /* Execute a simple statement that only contains basic arithmetic... */
      return jspeBaseWithComma();
    } else if (execInfo.lex->tk=='{') {
        /* A block of code */
        return jspeBlock();
    } else if (execInfo.lex->tk==';') {
        /* Empty statement - to allow things like ;;; */
        JSP_MATCH(';');
        return 0;
    } else if (execInfo.lex->tk==LEX_R_VAR) {
        return jspeStatementVar();
    } else if (execInfo.lex->tk==LEX_R_IF) {
        return jspeStatementIf();
    } else if (execInfo.lex->tk==LEX_R_WHILE) {
        return jspeStatementWhile();
    } else if (execInfo.lex->tk==LEX_R_FOR) {
        return jspeStatementFor();
    } else if (execInfo.lex->tk==LEX_R_RETURN) {
        return jspeStatementReturn();
    } else if (execInfo.lex->tk==LEX_R_FUNCTION) {
        return jspeStatementFunctionDecl();
    } else if (execInfo.lex->tk==LEX_R_CONTINUE) {
      JSP_MATCH(LEX_R_CONTINUE);
      if (JSP_SHOULD_EXECUTE) {
        if (!(execInfo.execute & EXEC_IN_LOOP))
          jsErrorAt("CONTINUE statement outside of FOR or WHILE loop", execInfo.lex, execInfo.lex->tokenLastEnd);
        else
          execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) |  EXEC_CONTINUE;
      }
    } else if (execInfo.lex->tk==LEX_R_BREAK) {
      JSP_MATCH(LEX_R_BREAK);
      if (JSP_SHOULD_EXECUTE) {
        if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH)))
          jsErrorAt("BREAK statement outside of SWITCH, FOR or WHILE loop", execInfo.lex, execInfo.lex->tokenLastEnd);
        else
          execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK;
      }
    } else if (execInfo.lex->tk==LEX_R_SWITCH) {
      return jspeStatementSwitch();
    } else JSP_MATCH(LEX_EOF);
    return 0;
}

// -----------------------------------------------------------------------------
/// Create a new built-in object that jswrapper can use to check for built-in functions
JsVar *jspNewBuiltin(const char *instanceOf) {
  JsVar *objFunc = jsvNewWithFlags(JSV_FUNCTION);
  if (!objFunc) return 0; // out of memory
  // set object data to be object name
  if (strlen(instanceOf)==sizeof(objFunc->varData))
    memcpy(objFunc->varData.str, instanceOf, sizeof(objFunc->varData)); // no trailing zero!
  else
    strncpy(objFunc->varData.str, instanceOf, sizeof(objFunc->varData));
  return objFunc;
}


JsVar *jspNewObject(JsParse *parse, const char *name, const char *instanceOf) {
  JsVar *objFuncName = jsvFindChildFromString(parse->root, instanceOf, true);
  if (!objFuncName) // out of memory
    return 0;

  JsVar *objFunc = jsvSkipName(objFuncName);
  if (!objFunc) {
    objFunc = jspNewBuiltin(instanceOf);
    if (!objFunc) { // out of memory
      jsvUnLock(objFuncName);
      return 0;
    }

    // set up name
    jsvSetValueOfName(objFuncName, objFunc);
  }

  JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true);
  jspEnsureIsPrototype(prototypeName); // make sure it's an object
  jsvUnLock(objFunc);
  if (!prototypeName) { // out of memory
    jsvUnLock(objFuncName);
    return 0;
  }

  JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  if (!obj) { // out of memory
    jsvUnLock(objFuncName);
    jsvUnLock(prototypeName);
    return 0;
  }
  if (name) {
    // set object data to be object name
    strncpy(obj->varData.str, name, sizeof(obj->varData));
  }
  // add inherits/constructor/etc
  jsvUnLock(jsvAddNamedChild(obj, prototypeName, JSPARSE_INHERITS_VAR));
  jsvUnLock(prototypeName);prototypeName=0;
  jsvUnLock(jsvAddNamedChild(obj, objFuncName, JSPARSE_CONSTRUCTOR_VAR));
  jsvUnLock(objFuncName);
  if (name) {
    JsVar *objName = jsvAddNamedChild(parse->root, obj, name);
    jsvUnLock(obj);
    if (!objName) { // out of memory
      return 0;
    }
    return objName;
  } else
    return obj;
}

/** Returns true if the constructor function given is the same as that
 * of the object with the given name. */
bool jspIsConstructor(JsVar *constructor, const char *constructorName) {
  JsVar *objFunc = jsvObjectGetChild(execInfo.parse->root, constructorName, 0);
  if (!objFunc) return false;
  bool isConstructor = objFunc == constructor;
  jsvUnLock(objFunc);
  return isConstructor;
}

// -----------------------------------------------------------------------------

void jspSoftInit(JsParse *parse) {
  parse->root = jsvFindOrCreateRoot();
  // Root now has a lock and a ref
}

/** Is v likely to have been created by this parser? */
bool jspIsCreatedObject(JsParse *parse, JsVar *v) {
  return
      v==parse->root;
}

void jspSoftKill(JsParse *parse) {
  jsvUnLock(parse->root);
  // Root now has just a ref
}

void jspInit(JsParse *parse) {
  jspSoftInit(parse);
}

void jspKill(JsParse *parse) {
  jspSoftKill(parse);
  // Unreffing this should completely kill everything attached to root
  JsVar *r = jsvFindOrCreateRoot();
  jsvUnRef(r);
  jsvUnLock(r);
}



JsVar *jspEvaluateVar(JsParse *parse, JsVar *str, JsVar *scope) {
  JsLex lex;
  JsVar *v = 0;
  JSP_SAVE_EXECUTE();
  JsExecInfo oldExecInfo = execInfo;

  assert(jsvIsString(str));
  jslInit(&lex, str);

  jspeiInit(parse, &lex);
  bool scopeAdded = false;
  if (scope)
    scopeAdded = jspeiAddScope(jsvGetRef(scope));
  while (!JSP_HAS_ERROR && execInfo.lex->tk != LEX_EOF) {
    jsvUnLock(v);
    v = jspeBlockOrStatement();
  }
  // clean up
  if (scopeAdded) jspeiRemoveScope();
  jspeiKill();
  jslKill(&lex);

  // restore state
  JSP_RESTORE_EXECUTE();
  oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
  execInfo = oldExecInfo;

  // It may have returned a reference, but we just want the value...
  if (v) {
    return jsvSkipNameAndUnLock(v);
  }
  // nothing returned
  return 0;
}

JsVar *jspEvaluate(JsParse *parse, const char *str) {
  JsVar *v = 0;

  JsVar *evCode = jsvNewFromString(str);
  if (!jsvIsMemoryFull())
    v = jspEvaluateVar(parse, evCode, 0);
  jsvUnLock(evCode);

  return v;
}

bool jspExecuteFunction(JsParse *parse, JsVar *func, JsVar *parent, int argCount, JsVar **argPtr) {
  JSP_SAVE_EXECUTE();
  JsExecInfo oldExecInfo = execInfo;

  jspeiInit(parse, 0);
  JsVar *resultVar = jspeFunctionCall(func, 0, parent, false, argCount, argPtr);
  bool result = jsvGetBool(resultVar);
  jsvUnLock(resultVar);
  // clean up
  jspeiKill();
  // restore state
  JSP_RESTORE_EXECUTE();
  oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
  execInfo = oldExecInfo;


  return result;
}


/// Evaluate a JavaScript module and return its exports
JsVar *jspEvaluateModule(JsParse *parse, JsVar *moduleContents) {
  assert(jsvIsString(moduleContents));
  JsVar *scope = jsvNewWithFlags(JSV_OBJECT);
  if (!scope) return 0; // out of mem
  JsVar *scopeExports = jsvNewWithFlags(JSV_OBJECT);
  if (!scopeExports) { jsvUnLock(scope); return 0; } // out of mem
  jsvUnLock(jsvAddNamedChild(scope, scopeExports, "exports"));

  jsvUnLock(jspEvaluateVar(parse, moduleContents, scope));

  jsvUnLock(scope);
  return scopeExports;
}