Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SchemaSetCompiler.cs « Schema « Xml « System « System.Xml « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 02ce25bc61ec9efc3dddf30738a039329af24deb (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
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
//------------------------------------------------------------------------------
// <copyright file="Compiler.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>                                                                
//------------------------------------------------------------------------------

namespace System.Xml.Schema {

    using System;
    using System.Collections;
    using System.Globalization;
    using System.Text; 
    using System.Diagnostics;

    internal sealed class Compiler : BaseProcessor {
        string restrictionErrorMsg;
        XmlSchemaObjectTable attributes = new XmlSchemaObjectTable();
        XmlSchemaObjectTable attributeGroups = new XmlSchemaObjectTable();
        XmlSchemaObjectTable elements = new XmlSchemaObjectTable();
        XmlSchemaObjectTable schemaTypes = new XmlSchemaObjectTable();
        XmlSchemaObjectTable groups = new XmlSchemaObjectTable();
        XmlSchemaObjectTable notations = new XmlSchemaObjectTable();
        XmlSchemaObjectTable examplars = new XmlSchemaObjectTable();
        XmlSchemaObjectTable identityConstraints = new XmlSchemaObjectTable();
        Stack complexTypeStack = new Stack();
        Hashtable schemasToCompile = new Hashtable();
        Hashtable importedSchemas = new Hashtable();

        XmlSchema schemaForSchema;

        public Compiler(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchema schemaForSchema, XmlSchemaCompilationSettings compilationSettings) : base(nameTable, null, eventHandler, compilationSettings) {
            this.schemaForSchema = schemaForSchema;
        }

        public bool Execute(XmlSchemaSet schemaSet, SchemaInfo schemaCompiledInfo) {
            Compile();
            if (!HasErrors) {
                Output(schemaCompiledInfo);
                schemaSet.elements = elements;
                schemaSet.attributes = attributes;
                schemaSet.schemaTypes = schemaTypes;
                schemaSet.substitutionGroups = examplars;
            }
            return !HasErrors;
        }
        
        internal void Prepare(XmlSchema schema, bool cleanup) {
            if (schemasToCompile[schema] != null) {
                return;
            }
            schemasToCompile.Add(schema, schema);
            foreach (XmlSchemaElement element in schema.Elements.Values) {
                if (cleanup) {
                    CleanupElement(element);
                }
                AddToTable(elements, element.QualifiedName, element);
            }
            foreach (XmlSchemaAttribute attribute in schema.Attributes.Values) {
                if (cleanup) {
                    CleanupAttribute(attribute);
                }
                AddToTable(attributes, attribute.QualifiedName, attribute);
            }
            foreach (XmlSchemaGroup group in schema.Groups.Values) {
                if (cleanup) {
                    CleanupGroup(group);
                }
                AddToTable(groups, group.QualifiedName, group);
            }
            foreach (XmlSchemaAttributeGroup attributeGroup in schema.AttributeGroups.Values) {
                if (cleanup) {
                    CleanupAttributeGroup(attributeGroup);
                }
                AddToTable(attributeGroups, attributeGroup.QualifiedName, attributeGroup);
            }
            foreach (XmlSchemaType type in schema.SchemaTypes.Values) {
                if (cleanup) {
                    XmlSchemaComplexType ct = type as XmlSchemaComplexType;
                    if (ct != null) {
                        CleanupComplexType(ct);
                    }
                    else {
                        CleanupSimpleType(type as XmlSchemaSimpleType);
                    }
                }
                AddToTable(schemaTypes, type.QualifiedName, type);
            }
            foreach (XmlSchemaNotation notation in schema.Notations.Values) {
                AddToTable(notations, notation.QualifiedName, notation);
            }
            foreach (XmlSchemaIdentityConstraint ic in schema.IdentityConstraints.Values) {
                AddToTable(identityConstraints, ic.QualifiedName, ic);
            }
        }
        
        private void UpdateSForSSimpleTypes() {
            Debug.Assert(schemaForSchema != null);
            XmlSchemaSimpleType[] schemaSimpleTypes = DatatypeImplementation.GetBuiltInTypes();
            XmlSchemaSimpleType builtInType;
            //Using enumToTypeCode array; indexed by XmlTypeCode; Start indexing from 12 since schema types start there and iterate till Length - 2 as the last 2 are xquery types
            int numberOfSchemaTypes = schemaSimpleTypes.Length - 3; //skip last 2 xquery types
            for (int i = 12; i < numberOfSchemaTypes; i++) {
                builtInType = schemaSimpleTypes[i];
                schemaForSchema.SchemaTypes.Replace(builtInType.QualifiedName, builtInType);
                this.schemaTypes.Replace(builtInType.QualifiedName, builtInType);
            }
        }

        private void Output(SchemaInfo schemaInfo) {
            string tns;
            foreach(XmlSchema schema in schemasToCompile.Values) {
                tns = schema.TargetNamespace;
                if (tns == null) {
                    tns = string.Empty;
                }
                schemaInfo.TargetNamespaces[tns] = true;
            }
            foreach (XmlSchemaElement element in elements.Values) {
                schemaInfo.ElementDecls.Add(element.QualifiedName, element.ElementDecl);
            }
            foreach (XmlSchemaAttribute attribute in attributes.Values) {
                schemaInfo.AttributeDecls.Add(attribute.QualifiedName, attribute.AttDef);
            }    
            foreach (XmlSchemaType type in schemaTypes.Values) {
                schemaInfo.ElementDeclsByType.Add(type.QualifiedName, type.ElementDecl);
            }
            foreach (XmlSchemaNotation notation in notations.Values) {
                SchemaNotation no = new SchemaNotation(notation.QualifiedName);
                no.SystemLiteral = notation.System;
                no.Pubid = notation.Public;
                if (!schemaInfo.Notations.ContainsKey(no.Name.Name)) {
                    schemaInfo.Notations.Add(no.Name.Name, no);
                }
            }
           
        }

        internal void ImportAllCompiledSchemas(XmlSchemaSet schemaSet) {
              XmlSchema currentSchema;
              int schemaIndex;
              SortedList schemas = schemaSet.SortedSchemas; 
              for (schemaIndex = 0; schemaIndex < schemas.Count; schemaIndex++) {
                  currentSchema = (XmlSchema)schemas.GetByIndex(schemaIndex);
                  if (currentSchema.IsCompiledBySet) { //Import already compiled schemas
                    Prepare(currentSchema, false);
                  }
              }
        }

        internal bool Compile() {
            schemaTypes.Insert(DatatypeImplementation.QnAnyType, XmlSchemaComplexType.AnyType);
            if (schemaForSchema != null) { //Get our built-in types
                schemaForSchema.SchemaTypes.Replace(DatatypeImplementation.QnAnyType, XmlSchemaComplexType.AnyType);
                UpdateSForSSimpleTypes();
            }

            foreach(XmlSchemaGroup group in groups.Values) {
                CompileGroup(group);
            }
            foreach(XmlSchemaAttributeGroup attributeGroup in attributeGroups.Values) {
                CompileAttributeGroup(attributeGroup);
            }
            foreach (XmlSchemaType type in schemaTypes.Values) {
                XmlSchemaComplexType ct = type as XmlSchemaComplexType;
                if (ct != null) {
                    CompileComplexType(ct);
                }
                else {
                    CompileSimpleType((XmlSchemaSimpleType)type);
                }
            }
            foreach (XmlSchemaElement element in elements.Values) {
                if (element.ElementDecl == null) {
                    CompileElement(element);
                }
            }
            foreach (XmlSchemaAttribute attribute in attributes.Values) {
                if (attribute.AttDef == null) {
                    CompileAttribute(attribute);
                }
            }
            foreach (XmlSchemaIdentityConstraint identityConstraint in identityConstraints.Values) {
                if (identityConstraint.CompiledConstraint == null) {
                    CompileIdentityConstraint(identityConstraint);
                }
            }
            while (this.complexTypeStack.Count > 0) {
                XmlSchemaComplexType type = (XmlSchemaComplexType)complexTypeStack.Pop();
                CompileComplexTypeElements(type);
            }

            ProcessSubstitutionGroups();

            foreach (XmlSchemaType type in schemaTypes.Values) {
                XmlSchemaComplexType localType = type as XmlSchemaComplexType;
                if (localType != null) {
                    CheckParticleDerivation(localType);
                }
            }
            
            foreach (XmlSchemaElement element in elements.Values) {
                XmlSchemaComplexType localComplexType = element.ElementSchemaType as XmlSchemaComplexType;
                if (localComplexType != null && element.SchemaTypeName == XmlQualifiedName.Empty) { // only local schemaTypes
                    CheckParticleDerivation(localComplexType);
                }
            }
            foreach (XmlSchemaGroup group in groups.Values) { //Check particle derivation for redefined groups
                XmlSchemaGroup baseGroup = group.Redefined;
                if (baseGroup != null) {
                    RecursivelyCheckRedefinedGroups(group, baseGroup);
                }
            }

            foreach (XmlSchemaAttributeGroup attributeGroup in attributeGroups.Values) {
                XmlSchemaAttributeGroup baseAttributeGroup = attributeGroup.Redefined;
                if (baseAttributeGroup != null) {
                    RecursivelyCheckRedefinedAttributeGroups(attributeGroup, baseAttributeGroup);
                }
            }
            return !HasErrors;
        }

        private void CleanupAttribute(XmlSchemaAttribute attribute) {
            if (attribute.SchemaType != null) {
                CleanupSimpleType((XmlSchemaSimpleType)attribute.SchemaType);
            }
            attribute.AttDef = null;
        }
        
        private void CleanupAttributeGroup(XmlSchemaAttributeGroup attributeGroup) {
            CleanupAttributes(attributeGroup.Attributes);
            attributeGroup.AttributeUses.Clear();
            attributeGroup.AttributeWildcard = null;
            if (attributeGroup.Redefined != null) {
                CleanupAttributeGroup(attributeGroup.Redefined);
            }
        }
        
        private void CleanupComplexType(XmlSchemaComplexType complexType) {
            if (complexType.QualifiedName == DatatypeImplementation.QnAnyType) { //if it is built-in anyType dont clean it.
                return;
            }
            if (complexType.ContentModel != null) { //simpleContent or complexContent
                if (complexType.ContentModel is XmlSchemaSimpleContent) {
                    XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel;
                    if (simpleContent.Content is XmlSchemaSimpleContentExtension) {
                        XmlSchemaSimpleContentExtension simpleExtension = (XmlSchemaSimpleContentExtension)simpleContent.Content;
                        CleanupAttributes(simpleExtension.Attributes);
                    }
                    else { //simpleContent.Content is XmlSchemaSimpleContentRestriction
                        XmlSchemaSimpleContentRestriction simpleRestriction = (XmlSchemaSimpleContentRestriction)simpleContent.Content;
                        CleanupAttributes(simpleRestriction.Attributes);
                    }
                }
                else { // complexType.ContentModel is XmlSchemaComplexContent
                    XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel;
                    if (complexContent.Content is XmlSchemaComplexContentExtension) {
                        XmlSchemaComplexContentExtension complexExtension = (XmlSchemaComplexContentExtension)complexContent.Content;
                        CleanupParticle(complexExtension.Particle);
                        CleanupAttributes(complexExtension.Attributes);

                    }
                    else { //XmlSchemaComplexContentRestriction
                        XmlSchemaComplexContentRestriction complexRestriction = (XmlSchemaComplexContentRestriction)complexContent.Content;
                        CleanupParticle(complexRestriction.Particle);
                        CleanupAttributes(complexRestriction.Attributes);
                    }
                }
            }
            else { //equals XmlSchemaComplexContent with baseType is anyType
                CleanupParticle(complexType.Particle);
                CleanupAttributes(complexType.Attributes);
            }
            complexType.LocalElements.Clear();
            complexType.AttributeUses.Clear();
            complexType.SetAttributeWildcard(null);
            complexType.SetContentTypeParticle(XmlSchemaParticle.Empty);
            complexType.ElementDecl = null;
            complexType.HasWildCard = false;

            //Clean up the original type if this is a redefined type
            if (complexType.Redefined != null) {
                CleanupComplexType(complexType.Redefined as XmlSchemaComplexType);
            }
        }
        
        private void CleanupSimpleType(XmlSchemaSimpleType simpleType) {
            if (simpleType == XmlSchemaType.GetBuiltInSimpleType(simpleType.TypeCode)) { //If it is a built-in simple type dont clean up
                return;
            }
            simpleType.ElementDecl = null;
            //Clean up the original group if this is a redefined group
            if (simpleType.Redefined != null) {
                CleanupSimpleType(simpleType.Redefined as XmlSchemaSimpleType);
            }
        }
        
        private void CleanupElement(XmlSchemaElement element) {
            if (element.SchemaType != null) {
                XmlSchemaComplexType complexType = element.SchemaType as XmlSchemaComplexType;
                if (complexType != null) {
                    CleanupComplexType(complexType);
                }
                else {
                    CleanupSimpleType((XmlSchemaSimpleType)element.SchemaType);
                }
            }
            for (int i = 0; i < element.Constraints.Count; ++i) {
                ((XmlSchemaIdentityConstraint)element.Constraints[i]).CompiledConstraint = null;
            }
            element.ElementDecl = null;
            element.IsLocalTypeDerivationChecked = false; //clear Local element type derivation check 
        }
        
        private void CleanupAttributes(XmlSchemaObjectCollection attributes) {
            for (int i = 0; i < attributes.Count; ++i) {
                XmlSchemaAttribute attribute = attributes[i] as XmlSchemaAttribute;
                if (attribute != null) {
                    CleanupAttribute(attribute);
                }
            }
        }

        private void CleanupGroup(XmlSchemaGroup group) {
            CleanupParticle(group.Particle);
            group.CanonicalParticle = null;
            //Clean up the original group if this is a redefined group
            if (group.Redefined != null) {
                CleanupGroup(group.Redefined);
            }
        }

        private void CleanupParticle(XmlSchemaParticle particle) {
            XmlSchemaElement element = particle as XmlSchemaElement;
            if (element != null) {
                CleanupElement(element);
                return;
            }

            XmlSchemaGroupBase groupBase = particle as XmlSchemaGroupBase;
            if (groupBase != null) {
                for (int i = 0; i < groupBase.Items.Count; ++i) {
                    CleanupParticle((XmlSchemaParticle)groupBase.Items[i]);
                }
            }
        }

        private void ProcessSubstitutionGroups() {
            foreach (XmlSchemaElement element in this.elements.Values) {
                if (!element.SubstitutionGroup.IsEmpty) {
                    XmlSchemaElement headElement = this.elements[element.SubstitutionGroup] as XmlSchemaElement;
                    if (headElement == null) {
                        SendValidationEvent(Res.Sch_NoExamplar, element);
                        continue;
                    }
                    //Check derivation of member's type against head's type
                    if (!XmlSchemaType.IsDerivedFrom(element.ElementSchemaType, headElement.ElementSchemaType, headElement.FinalResolved)) {
                        SendValidationEvent(Res.Sch_InvalidSubstitutionMember, (element.QualifiedName).ToString(), (headElement.QualifiedName).ToString(), element);
                    }

                    //Create substitutionGroup
                    XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)this.examplars[element.SubstitutionGroup];
                    if (substitutionGroup == null) {
                        substitutionGroup = new XmlSchemaSubstitutionGroup();
                        substitutionGroup.Examplar = element.SubstitutionGroup;
                        examplars.Add(element.SubstitutionGroup, substitutionGroup);
                    }
                    ArrayList members = substitutionGroup.Members;
                    if (!members.Contains(element)) { //Members might contain element if the same schema is included and imported through different paths. Imp, hence will be added to set directly
                        members.Add(element);
                    }
                }
            }

            //Check the subst groups that we just built
            foreach (XmlSchemaSubstitutionGroup substitutionGroup in examplars.Values) {
                CompileSubstitutionGroup(substitutionGroup);
            }
        }

        private void CompileSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGroup) {
            if (substitutionGroup.IsProcessing && substitutionGroup.Members.Count > 0) {
                SendValidationEvent(Res.Sch_SubstitutionCircularRef, (XmlSchemaElement)substitutionGroup.Members[0]);
                return;
            }
            XmlSchemaElement examplar = (XmlSchemaElement)elements[substitutionGroup.Examplar];
            Debug.Assert(examplar != null); //Headelement presence is checked while building subst groups
            if (substitutionGroup.Members.Contains(examplar)) {// already checked
                return;
            }
            substitutionGroup.IsProcessing = true;
            try {
                if (examplar.FinalResolved == XmlSchemaDerivationMethod.All) {
                    SendValidationEvent(Res.Sch_InvalidExamplar, examplar);
                }
                //Build transitive members
                ArrayList newMembers = null;
                for (int i = 0; i < substitutionGroup.Members.Count; ++i) {
                    XmlSchemaElement element = (XmlSchemaElement)substitutionGroup.Members[i];
                    //Chain to other head's that are members of this head's substGroup
                    if ((element.ElementDecl.Block & XmlSchemaDerivationMethod.Substitution) == 0) { //Chain only if substitution is not blocked
                        XmlSchemaSubstitutionGroup g = (XmlSchemaSubstitutionGroup)examplars[element.QualifiedName];
                        if (g != null) {
                            CompileSubstitutionGroup(g);
                            for (int j = 0; j < g.Members.Count; ++j) {
                                if (g.Members[j] != element) { //Exclude the head
                                    if (newMembers == null) {
                                        newMembers = new ArrayList();
                                    }
                                    newMembers.Add(g.Members[j]);
                                }
                            }
                        }
                    }
                }
                if (newMembers != null) {
                    for (int i = 0; i < newMembers.Count; ++i) {
                        substitutionGroup.Members.Add(newMembers[i]);
                    }
                }
                substitutionGroup.Members.Add(examplar); // Compiled mark
            }
            finally {
                substitutionGroup.IsProcessing = false;              
            }
        }

        private void RecursivelyCheckRedefinedGroups(XmlSchemaGroup redefinedGroup, XmlSchemaGroup baseGroup) {
            if (baseGroup.Redefined != null) {
                RecursivelyCheckRedefinedGroups(baseGroup, baseGroup.Redefined);
            }
            if (redefinedGroup.SelfReferenceCount == 0) {
                if (baseGroup.CanonicalParticle == null) {
                    baseGroup.CanonicalParticle = CannonicalizeParticle(baseGroup.Particle, true);
                }
                if (redefinedGroup.CanonicalParticle == null) {
                    redefinedGroup.CanonicalParticle = CannonicalizeParticle(redefinedGroup.Particle, true);
                }
                CompileParticleElements(redefinedGroup.CanonicalParticle);
                CompileParticleElements(baseGroup.CanonicalParticle);
                CheckParticleDerivation(redefinedGroup.CanonicalParticle, baseGroup.CanonicalParticle);
            }
        }

        private void RecursivelyCheckRedefinedAttributeGroups(XmlSchemaAttributeGroup attributeGroup, XmlSchemaAttributeGroup baseAttributeGroup) {
            if (baseAttributeGroup.Redefined != null) {
                RecursivelyCheckRedefinedAttributeGroups(baseAttributeGroup, baseAttributeGroup.Redefined);
            }
            if (attributeGroup.SelfReferenceCount == 0) {
                CompileAttributeGroup(baseAttributeGroup);
                CompileAttributeGroup(attributeGroup);
                CheckAtrributeGroupRestriction(baseAttributeGroup, attributeGroup);
            }
        }

        private void CompileGroup(XmlSchemaGroup group) {
            if (group.IsProcessing) {
                SendValidationEvent(Res.Sch_GroupCircularRef, group);
                group.CanonicalParticle = XmlSchemaParticle.Empty;
            } 
            else {
                group.IsProcessing = true;
                if (group.CanonicalParticle == null) { 
                    group.CanonicalParticle = CannonicalizeParticle(group.Particle, true); 
                }
                Debug.Assert(group.CanonicalParticle != null);
                group.IsProcessing = false; //Not enclosung in try -finally as cannonicalizeParticle will not throw exception
            }
        }

        private void CompileSimpleType(XmlSchemaSimpleType simpleType) {
            if (simpleType.IsProcessing) {
                throw new XmlSchemaException(Res.Sch_TypeCircularRef, simpleType);
            }
            if (simpleType.ElementDecl != null) { // already compiled
                return;
            }
            simpleType.IsProcessing = true;
            try {
                if (simpleType.Content is XmlSchemaSimpleTypeList) {
                    XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content;
                    XmlSchemaDatatype datatype;
                    simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType); 
                    if (list.ItemTypeName.IsEmpty) {
                        CompileSimpleType(list.ItemType);
                        list.BaseItemType = list.ItemType;
                        datatype = list.ItemType.Datatype;
                    }
                    else {
                        XmlSchemaSimpleType type = GetSimpleType(list.ItemTypeName);
                        if (type != null) {
                            if ((type.FinalResolved & XmlSchemaDerivationMethod.List) != 0) {
                                SendValidationEvent(Res.Sch_BaseFinalList, simpleType);
                            }
                            list.BaseItemType = type;
                            datatype = type.Datatype;
                        }
                        else {
                            throw new XmlSchemaException(Res.Sch_UndeclaredSimpleType, list.ItemTypeName.ToString(), list);   
                        }
                    }
                    simpleType.SetDatatype(datatype.DeriveByList(simpleType));
                    simpleType.SetDerivedBy(XmlSchemaDerivationMethod.List);
                }
                else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) {
                    XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content;
                    XmlSchemaDatatype datatype;
                    if (restriction.BaseTypeName.IsEmpty) {
                        CompileSimpleType(restriction.BaseType);
                        simpleType.SetBaseSchemaType(restriction.BaseType);
                        datatype = restriction.BaseType.Datatype;
                    }
                    else if (simpleType.Redefined != null && restriction.BaseTypeName == simpleType.Redefined.QualifiedName) {
                        CompileSimpleType((XmlSchemaSimpleType)simpleType.Redefined);
                        simpleType.SetBaseSchemaType(simpleType.Redefined.BaseXmlSchemaType);
                        datatype = simpleType.Redefined.Datatype;
                    }
                    else {
                        if (restriction.BaseTypeName.Equals(DatatypeImplementation.QnAnySimpleType)) {
                            XmlSchema parentSchema = Preprocessor.GetParentSchema(simpleType);
                            if (parentSchema.TargetNamespace != XmlSchema.Namespace) { //If it is not SForS, then error
                                throw new XmlSchemaException(Res.Sch_InvalidSimpleTypeRestriction, restriction.BaseTypeName.ToString(), simpleType);   
                            }
                        }
                        XmlSchemaSimpleType type = GetSimpleType(restriction.BaseTypeName);
                        if (type != null) {
                            if ((type.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) {
                                SendValidationEvent(Res.Sch_BaseFinalRestriction, simpleType);
                            }
                            simpleType.SetBaseSchemaType(type);
                            datatype = type.Datatype;
                        }
                        else {
                            throw new XmlSchemaException(Res.Sch_UndeclaredSimpleType, restriction.BaseTypeName.ToString(), restriction);   
                        }
                    }
                    simpleType.SetDatatype(datatype.DeriveByRestriction(restriction.Facets, NameTable, simpleType));
                    simpleType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction);
                }
                else { //simpleType.Content is XmlSchemaSimpleTypeUnion
                    XmlSchemaSimpleType[] baseTypes = CompileBaseMemberTypes(simpleType);
                    simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType);
                    simpleType.SetDatatype(XmlSchemaDatatype.DeriveByUnion(baseTypes, simpleType));
                    simpleType.SetDerivedBy(XmlSchemaDerivationMethod.Union);
                }
            } 
            catch (XmlSchemaException e) {
                if (e.SourceSchemaObject == null) {
                    e.SetSource(simpleType);
                }
                SendValidationEvent(e);
                simpleType.SetDatatype(DatatypeImplementation.AnySimpleType.Datatype);
            } 
            finally {
                SchemaElementDecl decl = new SchemaElementDecl();
                decl.ContentValidator = ContentValidator.TextOnly;
                decl.SchemaType = simpleType;
                decl.Datatype = simpleType.Datatype;
                simpleType.ElementDecl = decl;
                simpleType.IsProcessing = false;
            }
        }

        private XmlSchemaSimpleType[] CompileBaseMemberTypes(XmlSchemaSimpleType simpleType) {
            XmlSchemaSimpleType unionMember;
            ArrayList memberTypeDefinitions = new ArrayList();

            XmlSchemaSimpleTypeUnion mainUnion = (XmlSchemaSimpleTypeUnion)simpleType.Content;

            XmlQualifiedName[] mainMemberTypes = mainUnion.MemberTypes;
            if (mainMemberTypes != null) {
                for (int i = 0; i < mainMemberTypes.Length; ++i) {
                    unionMember = GetSimpleType(mainMemberTypes[i]);
                    if (unionMember != null) {
                        if (unionMember.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { //union of union
                            CheckUnionType(unionMember, memberTypeDefinitions, simpleType);
                        }
                        else { //its list or atomic
                            memberTypeDefinitions.Add(unionMember);
                        }
                        //Check derivation method of the member that is referenced
                        if ((unionMember.FinalResolved & XmlSchemaDerivationMethod.Union) != 0) {
                            SendValidationEvent(Res.Sch_BaseFinalUnion, simpleType);
                        }
                    }
                    else {
                        throw new XmlSchemaException(Res.Sch_UndeclaredSimpleType, mainMemberTypes[i].ToString(), mainUnion);   
                    }
                }
            }

            //Now add the baseTypes that are defined inside the union itself
            XmlSchemaObjectCollection mainBaseTypes = mainUnion.BaseTypes; //
            if (mainBaseTypes != null) {
                for (int i = 0; i < mainBaseTypes.Count; ++i) {
                    XmlSchemaSimpleType st = (XmlSchemaSimpleType)mainBaseTypes[i];
                    CompileSimpleType(st);
                    if (st.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { //union of union
                        CheckUnionType(st, memberTypeDefinitions, simpleType);
                    }
                    else {  //its list or atomic
                        memberTypeDefinitions.Add(st);
                    }
                }
            }
            //set all types
            mainUnion.SetBaseMemberTypes(memberTypeDefinitions.ToArray(typeof(XmlSchemaSimpleType)) as XmlSchemaSimpleType[]);
            return mainUnion.BaseMemberTypes;
        }

        private void CheckUnionType(XmlSchemaSimpleType unionMember, ArrayList memberTypeDefinitions, XmlSchemaSimpleType parentType) {
            XmlSchemaDatatype unionDatatype = unionMember.Datatype;
            if (unionMember.DerivedBy == XmlSchemaDerivationMethod.Restriction && (unionDatatype.HasLexicalFacets || unionDatatype.HasValueFacets) ) {
                SendValidationEvent(Res.Sch_UnionFromUnion, parentType);
            }
            else {
                Datatype_union uniondt = unionMember.Datatype as Datatype_union;
                memberTypeDefinitions.AddRange(uniondt.BaseMemberTypes);
            }
        }

        private void CompileComplexType(XmlSchemaComplexType complexType) {
            if (complexType.ElementDecl != null) { //already compiled
                return;
            }
            if (complexType.IsProcessing) {
                SendValidationEvent(Res.Sch_TypeCircularRef, complexType);
                return;
            }
            complexType.IsProcessing = true;
            try {
                if (complexType.ContentModel != null) { //simpleContent or complexContent
                    if (complexType.ContentModel is XmlSchemaSimpleContent) {
                        XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel;
                        complexType.SetContentType(XmlSchemaContentType.TextOnly);
                        if (simpleContent.Content is XmlSchemaSimpleContentExtension) {
                            CompileSimpleContentExtension(complexType, (XmlSchemaSimpleContentExtension)simpleContent.Content);
                        }
                        else { //simpleContent.Content is XmlSchemaSimpleContentRestriction
                            CompileSimpleContentRestriction(complexType, (XmlSchemaSimpleContentRestriction)simpleContent.Content);
                        }
                    }
                    else { // complexType.ContentModel is XmlSchemaComplexContent
                        XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel;
                        if (complexContent.Content is XmlSchemaComplexContentExtension) {
                            CompileComplexContentExtension(complexType, complexContent, (XmlSchemaComplexContentExtension)complexContent.Content);
                        }
                        else { // complexContent.Content is XmlSchemaComplexContentRestriction
                            CompileComplexContentRestriction(complexType, complexContent, (XmlSchemaComplexContentRestriction)complexContent.Content);
                        }
                    }
                }
                else { //equals XmlSchemaComplexContent with baseType is anyType
                        complexType.SetBaseSchemaType(XmlSchemaComplexType.AnyType);
                        CompileLocalAttributes(XmlSchemaComplexType.AnyType, complexType, complexType.Attributes, complexType.AnyAttribute, XmlSchemaDerivationMethod.Restriction);
                        complexType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction);
                        complexType.SetContentTypeParticle(CompileContentTypeParticle(complexType.Particle));
                        complexType.SetContentType(GetSchemaContentType(complexType, null, complexType.ContentTypeParticle));
                }
                if (complexType.ContainsIdAttribute(true)) {
                    SendValidationEvent(Res.Sch_TwoIdAttrUses, complexType);
                }
                SchemaElementDecl decl = new SchemaElementDecl();
                decl.ContentValidator = CompileComplexContent(complexType);
                decl.SchemaType = complexType;
                decl.IsAbstract = complexType.IsAbstract;
                decl.Datatype = complexType.Datatype;
                decl.Block = complexType.BlockResolved;
                decl.AnyAttribute = complexType.AttributeWildcard;
                foreach(XmlSchemaAttribute attribute in complexType.AttributeUses.Values) {
                    if (attribute.Use == XmlSchemaUse.Prohibited) {
                        if (!decl.ProhibitedAttributes.ContainsKey(attribute.QualifiedName)) {
                            decl.ProhibitedAttributes.Add(attribute.QualifiedName, attribute.QualifiedName);
                        }
                    }
                    else {
                        if (!decl.AttDefs.ContainsKey(attribute.QualifiedName) && attribute.AttDef != null && attribute.AttDef.Name != XmlQualifiedName.Empty && attribute.AttDef != SchemaAttDef.Empty) {
                            decl.AddAttDef(attribute.AttDef);
                        }
                    }
                }
                complexType.ElementDecl = decl;
            }
            finally {
                complexType.IsProcessing = false;
            }
        }


        private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, XmlSchemaSimpleContentExtension simpleExtension) {
            XmlSchemaComplexType baseType = null;
            if (complexType.Redefined != null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) {
                baseType = (XmlSchemaComplexType)complexType.Redefined;
                CompileComplexType(baseType);
                complexType.SetBaseSchemaType(baseType);
                complexType.SetDatatype(baseType.Datatype);
            }
            else {
                XmlSchemaType bto = GetAnySchemaType(simpleExtension.BaseTypeName);
                if (bto == null) {
                    SendValidationEvent(Res.Sch_UndeclaredType, simpleExtension.BaseTypeName.ToString(), simpleExtension);   
                } 
                else {
                    complexType.SetBaseSchemaType(bto);
                    complexType.SetDatatype(bto.Datatype);
                }
                baseType = bto as XmlSchemaComplexType;
            }
            if (baseType != null) {
                if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Extension) != 0) {
                    SendValidationEvent(Res.Sch_BaseFinalExtension, complexType);
                }
                if (baseType.ContentType != XmlSchemaContentType.TextOnly) {
                    SendValidationEvent(Res.Sch_NotSimpleContent, complexType);
                }
            } 
            complexType.SetDerivedBy(XmlSchemaDerivationMethod.Extension);
            CompileLocalAttributes(baseType, complexType, simpleExtension.Attributes, simpleExtension.AnyAttribute, XmlSchemaDerivationMethod.Extension);
        }

        private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, XmlSchemaSimpleContentRestriction simpleRestriction) {
            XmlSchemaComplexType baseType = null;
            XmlSchemaDatatype datatype = null;
            if (complexType.Redefined != null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) {
                baseType = (XmlSchemaComplexType)complexType.Redefined;
                CompileComplexType(baseType);
                datatype = baseType.Datatype;
            }
            else {
                baseType = GetComplexType(simpleRestriction.BaseTypeName);
                if (baseType == null) {
                    SendValidationEvent(Res.Sch_UndefBaseRestriction, simpleRestriction.BaseTypeName.ToString(), simpleRestriction);
                    return;
                }
                if (baseType.ContentType == XmlSchemaContentType.TextOnly) {
                    if (simpleRestriction.BaseType == null) { 
                        datatype = baseType.Datatype; 
                        //There is a 

                    }
                    else {
                        CompileSimpleType(simpleRestriction.BaseType);
                        if(!XmlSchemaType.IsDerivedFromDatatype(simpleRestriction.BaseType.Datatype, baseType.Datatype, XmlSchemaDerivationMethod.None)) {
                           SendValidationEvent(Res.Sch_DerivedNotFromBase, simpleRestriction);
                        }
                        datatype = simpleRestriction.BaseType.Datatype;
                    }
                }
                else if (baseType.ContentType == XmlSchemaContentType.Mixed && baseType.ElementDecl.ContentValidator.IsEmptiable) {
                    if (simpleRestriction.BaseType != null) {
                        CompileSimpleType(simpleRestriction.BaseType);
                        complexType.SetBaseSchemaType(simpleRestriction.BaseType);
                        datatype = simpleRestriction.BaseType.Datatype;
                    }
                    else {
                        SendValidationEvent(Res.Sch_NeedSimpleTypeChild, simpleRestriction);
                    }
                }
                else {
                    SendValidationEvent(Res.Sch_NotSimpleContent, complexType);
                }
            }
            if (baseType != null && baseType.ElementDecl != null) {
                if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) {
                    SendValidationEvent(Res.Sch_BaseFinalRestriction, complexType);
                }
            }
            if (baseType != null) {
                complexType.SetBaseSchemaType(baseType);
            }
            if (datatype != null) {
                try {
                    complexType.SetDatatype(datatype.DeriveByRestriction(simpleRestriction.Facets, NameTable, complexType));
                }
                catch (XmlSchemaException e) {
                    if (e.SourceSchemaObject == null) {
                        e.SetSource(complexType);
                    }
                    SendValidationEvent(e);
                    complexType.SetDatatype(DatatypeImplementation.AnySimpleType.Datatype);
                } 
            }
            complexType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction);
            CompileLocalAttributes(baseType, complexType, simpleRestriction.Attributes, simpleRestriction.AnyAttribute, XmlSchemaDerivationMethod.Restriction);
        }

        private void CompileComplexContentExtension(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentExtension complexExtension) {
            XmlSchemaComplexType baseType = null;
            if (complexType.Redefined != null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) {
                baseType = (XmlSchemaComplexType)complexType.Redefined;
                CompileComplexType(baseType);
            }
            else {
                baseType = GetComplexType(complexExtension.BaseTypeName);
                if (baseType == null) {
                    SendValidationEvent(Res.Sch_UndefBaseExtension, complexExtension.BaseTypeName.ToString(), complexExtension);   
                    return;
                }
            }
            if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Extension) != 0) {
                SendValidationEvent(Res.Sch_BaseFinalExtension, complexType);
            }
            CompileLocalAttributes(baseType, complexType, complexExtension.Attributes, complexExtension.AnyAttribute, XmlSchemaDerivationMethod.Extension);

            XmlSchemaParticle baseParticle = baseType.ContentTypeParticle;
            XmlSchemaParticle extendedParticle = CannonicalizeParticle(complexExtension.Particle, true);
            if (baseParticle != XmlSchemaParticle.Empty) {
                if (extendedParticle != XmlSchemaParticle.Empty) {
                    XmlSchemaSequence compiledParticle = new XmlSchemaSequence();
                    compiledParticle.Items.Add(baseParticle);
                    compiledParticle.Items.Add(extendedParticle);
                    complexType.SetContentTypeParticle(CompileContentTypeParticle(compiledParticle));
                }
                else {
                    complexType.SetContentTypeParticle(baseParticle);
                }
            }
            else {
                complexType.SetContentTypeParticle(extendedParticle);
            }
            XmlSchemaContentType contentType = GetSchemaContentType(complexType, complexContent, extendedParticle);
            if (contentType == XmlSchemaContentType.Empty) { //Derived content type is empty, Get ContentType from base
                contentType = baseType.ContentType;
                // In case of a simple base type (content type is TextOnly) the derived type
                //   will be the same as the base type. So set the same content type and then also
                //   set the same data type.
                if (contentType == XmlSchemaContentType.TextOnly) {
                    complexType.SetDatatype(baseType.Datatype);
                }
            }
            complexType.SetContentType(contentType);

            if (baseType.ContentType != XmlSchemaContentType.Empty && complexType.ContentType != baseType.ContentType) { //If base is empty, do not check
                SendValidationEvent(Res.Sch_DifContentType, complexType);
                return;
            }
            complexType.SetBaseSchemaType(baseType);
            complexType.SetDerivedBy(XmlSchemaDerivationMethod.Extension);
        }

        private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentRestriction complexRestriction) {
            XmlSchemaComplexType baseType = null;
            if (complexType.Redefined != null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) {
                baseType = (XmlSchemaComplexType)complexType.Redefined;
                CompileComplexType(baseType);
            }
            else {
                baseType = GetComplexType(complexRestriction.BaseTypeName);
                if (baseType == null) {
                    SendValidationEvent(Res.Sch_UndefBaseRestriction, complexRestriction.BaseTypeName.ToString(), complexRestriction);   
                    return;
                }
            } 
            complexType.SetBaseSchemaType(baseType);
            if ((baseType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) {
                SendValidationEvent(Res.Sch_BaseFinalRestriction, complexType);
            }
            CompileLocalAttributes(baseType, complexType, complexRestriction.Attributes, complexRestriction.AnyAttribute, XmlSchemaDerivationMethod.Restriction);
            
            complexType.SetContentTypeParticle(CompileContentTypeParticle(complexRestriction.Particle));
            XmlSchemaContentType derivedContentType = GetSchemaContentType(complexType, complexContent, complexType.ContentTypeParticle);
            complexType.SetContentType(derivedContentType);
            switch(derivedContentType) {
                case XmlSchemaContentType.Empty:
                    if (baseType.ElementDecl != null && !baseType.ElementDecl.ContentValidator.IsEmptiable) { //base is either TextOnly or its ElementOnly/Mixed and not emptiable 
                        SendValidationEvent(Res.Sch_InvalidContentRestrictionDetailed, Res.GetString(Res.Sch_InvalidBaseToEmpty), complexType);
                    }
                break;

                case XmlSchemaContentType.Mixed:
                    if (baseType.ContentType != XmlSchemaContentType.Mixed) {
                        SendValidationEvent(Res.Sch_InvalidContentRestrictionDetailed, Res.GetString(Res.Sch_InvalidBaseToMixed), complexType);
                    }
                break;
            }
            complexType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction);
        }

        private void CheckParticleDerivation(XmlSchemaComplexType complexType) {
            XmlSchemaComplexType baseType = complexType.BaseXmlSchemaType as XmlSchemaComplexType;
            restrictionErrorMsg = null;
            if (baseType != null && baseType != XmlSchemaComplexType.AnyType && complexType.DerivedBy == XmlSchemaDerivationMethod.Restriction) {
                XmlSchemaParticle derivedParticle = CannonicalizePointlessRoot(complexType.ContentTypeParticle);
                XmlSchemaParticle baseParticle = CannonicalizePointlessRoot(baseType.ContentTypeParticle);
                if (!IsValidRestriction(derivedParticle, baseParticle)) {
#if DEBUG
                    if(complexType.ContentTypeParticle != null && baseType.ContentTypeParticle != null) {
                        string position = string.Empty;
                        if (complexType.SourceUri != null) {
                            position = " in " + complexType.SourceUri + "(" + complexType.LineNumber + ", " + complexType.LinePosition + ")";
                        }
                        Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "Invalid complexType content restriction" + position);
                        Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Base    " + DumpContentModel(baseType.ContentTypeParticle));
                        Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Derived " + DumpContentModel(complexType.ContentTypeParticle));
                    }
#endif
                    if (restrictionErrorMsg != null) {
                        SendValidationEvent(Res.Sch_InvalidParticleRestrictionDetailed, restrictionErrorMsg, complexType);
                    }
                    else {
                        SendValidationEvent(Res.Sch_InvalidParticleRestriction, complexType);
                    }
                }
            }
            else if (baseType == XmlSchemaComplexType.AnyType) { //The complex type itself is not explicitly derived by restriction but it could have local elements which have anonymous types that are derived by restriction
                foreach(XmlSchemaElement localElement in complexType.LocalElements.Values) {
                    if (localElement.IsLocalTypeDerivationChecked) { //Element already checked
                        continue;
                    }
                    XmlSchemaComplexType localComplexType = localElement.ElementSchemaType as XmlSchemaComplexType;
                    if (localComplexType != null && localElement.SchemaTypeName == XmlQualifiedName.Empty && localElement.RefName == XmlQualifiedName.Empty) { //Only local elements
                        localElement.IsLocalTypeDerivationChecked = true; //Not clearing this flag after recursion to make sure this check is not repeated for multiple references of the same local element (through group refs)
                        CheckParticleDerivation(localComplexType);
                    }
                }
            }
        }

        private void CheckParticleDerivation(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) {
            restrictionErrorMsg = null;
            derivedParticle = CannonicalizePointlessRoot(derivedParticle);
            baseParticle = CannonicalizePointlessRoot(baseParticle);
            if (!IsValidRestriction(derivedParticle, baseParticle)) {
                if (restrictionErrorMsg != null) {
                    SendValidationEvent(Res.Sch_InvalidParticleRestrictionDetailed, restrictionErrorMsg, derivedParticle);
                }
                else {
                    SendValidationEvent(Res.Sch_InvalidParticleRestriction, derivedParticle);
                }
            }
        }

        private XmlSchemaParticle CompileContentTypeParticle(XmlSchemaParticle particle) {
            XmlSchemaParticle ctp = CannonicalizeParticle(particle, true);
            XmlSchemaChoice choice = ctp as XmlSchemaChoice;
            if (choice != null && choice.Items.Count == 0) {
                if (choice.MinOccurs != decimal.Zero) {
                    SendValidationEvent(Res.Sch_EmptyChoice, choice, XmlSeverityType.Warning);
                }
                return XmlSchemaParticle.Empty;
            }
            return ctp;
        }

        private XmlSchemaParticle CannonicalizeParticle(XmlSchemaParticle particle, bool root) {
            if (particle == null || particle.IsEmpty) {
                return XmlSchemaParticle.Empty;
            }
            else if (particle is XmlSchemaElement) {
                //return CannonicalizeElement((XmlSchemaElement)particle, substitution);
                return particle;
            }
            else if (particle is XmlSchemaGroupRef) {
                return CannonicalizeGroupRef((XmlSchemaGroupRef)particle, root);
            }
            else if (particle is XmlSchemaAll) {
                return CannonicalizeAll((XmlSchemaAll)particle, root);
            }
            else if (particle is XmlSchemaChoice) {
                return CannonicalizeChoice((XmlSchemaChoice)particle, root);
            }
            else if (particle is XmlSchemaSequence) {
                return CannonicalizeSequence((XmlSchemaSequence)particle, root);
            }
            else {
                return particle;
            }
        }

        private XmlSchemaParticle CannonicalizeElement(XmlSchemaElement element) {
            if (!element.RefName.IsEmpty && (element.ElementDecl.Block & XmlSchemaDerivationMethod.Substitution) == 0) {
                XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)examplars[element.QualifiedName];
                if (substitutionGroup == null) {
                    return element;
                }
                else {
                    XmlSchemaChoice choice = new XmlSchemaChoice(); 
                    for (int i = 0; i < substitutionGroup.Members.Count; ++i) {
                        choice.Items.Add((XmlSchemaElement)substitutionGroup.Members[i]);
                    }
                    choice.MinOccurs = element.MinOccurs;
                    choice.MaxOccurs = element.MaxOccurs;
                    CopyPosition(choice, element, false);
                    return choice;
                }
            }
            else {
                return element;
            }
        }
        
        private XmlSchemaParticle CannonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool root) {
            XmlSchemaGroup group;
            if (groupRef.Redefined != null) {
                group = groupRef.Redefined;
            }
            else {
                group = (XmlSchemaGroup)groups[groupRef.RefName];
            }
            if (group == null) {
                SendValidationEvent(Res.Sch_UndefGroupRef, groupRef.RefName.ToString(), groupRef);
                return XmlSchemaParticle.Empty;
            }
            if (group.CanonicalParticle == null) {
                CompileGroup(group);
            }
            if (group.CanonicalParticle == XmlSchemaParticle.Empty) {
                return XmlSchemaParticle.Empty;
            }
            XmlSchemaGroupBase groupBase = (XmlSchemaGroupBase)group.CanonicalParticle;
            if (groupBase is XmlSchemaAll) {
                if (!root) {
                    SendValidationEvent(Res.Sch_AllRefNotRoot, "", groupRef);
                    return XmlSchemaParticle.Empty;
                }
                if (groupRef.MinOccurs > decimal.One || groupRef.MaxOccurs != decimal.One) {
                    SendValidationEvent(Res.Sch_AllRefMinMax, groupRef);
                    return XmlSchemaParticle.Empty;
                }
            }
            else if (groupBase is XmlSchemaChoice && groupBase.Items.Count == 0) {
                if (groupRef.MinOccurs != decimal.Zero) {
                    SendValidationEvent(Res.Sch_EmptyChoice, groupRef, XmlSeverityType.Warning);
                }
                return XmlSchemaParticle.Empty;
            }
            XmlSchemaGroupBase groupRefBase = (
                (groupBase is XmlSchemaSequence) ? (XmlSchemaGroupBase)new XmlSchemaSequence() :
                (groupBase is XmlSchemaChoice)   ? (XmlSchemaGroupBase)new XmlSchemaChoice() :
                                                   (XmlSchemaGroupBase)new XmlSchemaAll()
            );
            groupRefBase.MinOccurs = groupRef.MinOccurs;
            groupRefBase.MaxOccurs = groupRef.MaxOccurs;
            CopyPosition(groupRefBase, groupRef, true);

            for (int i = 0; i < groupBase.Items.Count; ++i) {
                groupRefBase.Items.Add(groupBase.Items[i]);
            }
            groupRef.SetParticle(groupRefBase);
            return groupRefBase;
        }

        private XmlSchemaParticle CannonicalizeAll(XmlSchemaAll all, bool root) {
            if (all.Items.Count > 0) {
                XmlSchemaAll newAll = new XmlSchemaAll();
                newAll.MinOccurs = all.MinOccurs;
                newAll.MaxOccurs = all.MaxOccurs;
                CopyPosition(newAll, all, true);
                for (int i = 0; i < all.Items.Count; ++i) {
                    XmlSchemaParticle p = CannonicalizeParticle((XmlSchemaElement)all.Items[i], false);
                    if (p != XmlSchemaParticle.Empty) {
                        newAll.Items.Add(p);
                    }
                }
                all = newAll;
            }
            if (all.Items.Count == 0) {
                return XmlSchemaParticle.Empty;
            }
            else if (!root) {
                SendValidationEvent(Res.Sch_NotAllAlone, all);
                return XmlSchemaParticle.Empty;
            }
            else {
                return all;
            }
        }
        
        private XmlSchemaParticle CannonicalizeChoice(XmlSchemaChoice choice, bool root) {
            XmlSchemaChoice oldChoice = choice;
            if (choice.Items.Count > 0) {
                XmlSchemaChoice newChoice = new XmlSchemaChoice();
                newChoice.MinOccurs = choice.MinOccurs;
                newChoice.MaxOccurs = choice.MaxOccurs;
                CopyPosition(newChoice, choice, true);
                for (int i = 0; i < choice.Items.Count; ++i) {
                    XmlSchemaParticle p1 = CannonicalizeParticle((XmlSchemaParticle)choice.Items[i], false);
                    if (p1 != XmlSchemaParticle.Empty) {
                        if (p1.MinOccurs == decimal.One && p1.MaxOccurs == decimal.One && p1 is XmlSchemaChoice) {
                            XmlSchemaChoice p1Choice = p1 as XmlSchemaChoice;
                            for (int j = 0; j < p1Choice.Items.Count; ++j) {
                                newChoice.Items.Add(p1Choice.Items[j]);
                            }
                        }
                        else {
                            newChoice.Items.Add(p1);
                        }
                    }
                }
                choice = newChoice;
            }
            if (!root && choice.Items.Count == 0) {
                if (choice.MinOccurs != decimal.Zero) {
                    SendValidationEvent(Res.Sch_EmptyChoice, oldChoice, XmlSeverityType.Warning);
                }
                return XmlSchemaParticle.Empty;
            }
            else if (!root && choice.Items.Count == 1 && choice.MinOccurs == decimal.One && choice.MaxOccurs == decimal.One) {
                return (XmlSchemaParticle)choice.Items[0];
            }
            else {
                return choice;
            }
        }

        private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool root) {
            if (sequence.Items.Count > 0) {
                XmlSchemaSequence newSequence = new XmlSchemaSequence();
                newSequence.MinOccurs = sequence.MinOccurs;
                newSequence.MaxOccurs = sequence.MaxOccurs;
                CopyPosition(newSequence, sequence, true);
                for (int i = 0; i < sequence.Items.Count; ++i) {
                    XmlSchemaParticle p1 = CannonicalizeParticle((XmlSchemaParticle)sequence.Items[i], false);
                    if (p1 != XmlSchemaParticle.Empty) {
                        XmlSchemaSequence p1Sequence = p1 as XmlSchemaSequence;
                        if (p1.MinOccurs == decimal.One && p1.MaxOccurs == decimal.One && p1Sequence != null) {
                            for (int j = 0; j < p1Sequence.Items.Count; ++j) {
                                newSequence.Items.Add(p1Sequence.Items[j]);
                            }
                        }
                        else {
                            newSequence.Items.Add(p1);
                        }
                    }
                }
                sequence = newSequence;
            }
            if (sequence.Items.Count == 0) {
                return XmlSchemaParticle.Empty;
            }
            else if (!root && sequence.Items.Count == 1 && sequence.MinOccurs == decimal.One && sequence.MaxOccurs == decimal.One) {
                    return (XmlSchemaParticle)sequence.Items[0];
            }
            else {
                return sequence;
            }
        }
        
        private XmlSchemaParticle CannonicalizePointlessRoot(XmlSchemaParticle particle) {
            if (particle == null) {
                return null;
            }
            XmlSchemaSequence xss;
            XmlSchemaChoice xsc;
            XmlSchemaAll xsa;
            decimal one = decimal.One;

            if ( (xss = (particle as XmlSchemaSequence)) != null ) {
                XmlSchemaObjectCollection items = xss.Items;
                int count = items.Count;
                if (count == 1) {
                    if (xss.MinOccurs == one && xss.MaxOccurs == one) {
                        return (XmlSchemaParticle)items[0];
                    }
                }
            }
            else if ( (xsc = (particle as XmlSchemaChoice)) != null ) {
                XmlSchemaObjectCollection items = xsc.Items;
                int count = items.Count;

                if (count == 1) {
                    if (xsc.MinOccurs == one && xsc.MaxOccurs == one) {
                        return (XmlSchemaParticle)items[0];
                    }
                }
                else if (count == 0) {
                    return XmlSchemaParticle.Empty;
                }
            }
            else if ( (xsa = (particle as XmlSchemaAll)) != null ) {
                XmlSchemaObjectCollection items = xsa.Items;
                int count = items.Count;

                if (count == 1) {
                    if (xsa.MinOccurs == one && xsa.MaxOccurs == one) {
                        return (XmlSchemaParticle)items[0];
                    }
                }
            }

            return particle;
        }

        private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) {
            if (derivedParticle == baseParticle) {
                return true;
            }
            else if (derivedParticle == null || derivedParticle == XmlSchemaParticle.Empty) {
                return IsParticleEmptiable(baseParticle);
            }
            else if (baseParticle == null || baseParticle == XmlSchemaParticle.Empty) {
                return false;
            }
            if (derivedParticle is XmlSchemaElement) { //check for derived element being head of substitutionGroup
                XmlSchemaElement derivedElem = (XmlSchemaElement)derivedParticle;
                derivedParticle = CannonicalizeElement(derivedElem);
            }
            if (baseParticle is XmlSchemaElement) {
                XmlSchemaElement baseElem = (XmlSchemaElement)baseParticle;
                XmlSchemaParticle newBaseParticle;
                newBaseParticle = CannonicalizeElement(baseElem);
                if (newBaseParticle is XmlSchemaChoice) { //Base Element is subs grp head.
                    return IsValidRestriction(derivedParticle, newBaseParticle);
                }
                else if (derivedParticle is XmlSchemaElement) {
                    return IsElementFromElement((XmlSchemaElement)derivedParticle, baseElem);
                }
                else {
                    restrictionErrorMsg = Res.GetString(Res.Sch_ForbiddenDerivedParticleForElem);
                    return false;
                }
            }
            else if (baseParticle is XmlSchemaAny) {
                if (derivedParticle is XmlSchemaElement) {
                    return IsElementFromAny((XmlSchemaElement)derivedParticle, (XmlSchemaAny)baseParticle);
                }
                else if (derivedParticle is XmlSchemaAny) {
                    return IsAnyFromAny((XmlSchemaAny)derivedParticle, (XmlSchemaAny)baseParticle);
                }
                else {
                    return IsGroupBaseFromAny((XmlSchemaGroupBase)derivedParticle, (XmlSchemaAny)baseParticle);
                }
            }
            else if (baseParticle is XmlSchemaAll) {
                if (derivedParticle is XmlSchemaElement) {
                    return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle);
                }
                else if (derivedParticle is XmlSchemaAll) {
                    if(IsGroupBaseFromGroupBase((XmlSchemaGroupBase)derivedParticle, (XmlSchemaGroupBase)baseParticle, true)) {
                        return true;    
                    }
                }
                else if (derivedParticle is XmlSchemaSequence) {
                    if(IsSequenceFromAll((XmlSchemaSequence)derivedParticle, (XmlSchemaAll)baseParticle)) {
                        return true;
                    }
                    restrictionErrorMsg = Res.GetString(Res.Sch_SeqFromAll, derivedParticle.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedParticle.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseParticle.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseParticle.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
                }
                else if (derivedParticle is XmlSchemaChoice || derivedParticle is XmlSchemaAny) {
                    restrictionErrorMsg = Res.GetString(Res.Sch_ForbiddenDerivedParticleForAll);
                }
                return false;
            }
            else if (baseParticle is XmlSchemaChoice ) {
                if (derivedParticle is XmlSchemaElement) {
                    return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase) baseParticle);
                }
                else if (derivedParticle is XmlSchemaChoice) {
                    XmlSchemaChoice baseChoice = baseParticle as XmlSchemaChoice;
                    XmlSchemaChoice derivedChoice = derivedParticle as XmlSchemaChoice;

                    if (baseChoice.Parent == null || derivedChoice.Parent == null) { //using parent property to indicate this choice was created on the fly for substitutionGroup
                        return IsChoiceFromChoiceSubstGroup(derivedChoice, baseChoice);
                    }
                    if(IsGroupBaseFromGroupBase(derivedChoice, baseChoice, false)) {
                        return true;
                    }
                }
                else if (derivedParticle is XmlSchemaSequence) {
                    if(IsSequenceFromChoice((XmlSchemaSequence)derivedParticle, (XmlSchemaChoice) baseParticle)) {
                        return true;
                    }
                    restrictionErrorMsg = Res.GetString(Res.Sch_SeqFromChoice, derivedParticle.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedParticle.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseParticle.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseParticle.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
                }
                else {
                    restrictionErrorMsg = Res.GetString(Res.Sch_ForbiddenDerivedParticleForChoice); 
                }
                return false;
            }
            else if (baseParticle is XmlSchemaSequence) {
                if (derivedParticle is XmlSchemaElement) {
                    return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle);
                }
                else if (derivedParticle is XmlSchemaSequence || (derivedParticle is XmlSchemaAll && ((XmlSchemaGroupBase)derivedParticle).Items.Count ==1)) {
                    if (IsGroupBaseFromGroupBase((XmlSchemaGroupBase)derivedParticle, (XmlSchemaGroupBase)baseParticle, true)) {
                        return true;    
                    }
                }
                else {
                    restrictionErrorMsg = Res.GetString(Res.Sch_ForbiddenDerivedParticleForSeq); 
                }
                return false;
            }
            else {
                Debug.Assert(false);
            }

            return false;
        }

        private bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElement baseElement) {
            // In case of elements the block value '#all' is 100% equivalent to the value of 'substitution restriction extension'.
            // Since below we perform a logical operation on the bit fields we need to convert the #all (0xFF)
            //   to the equivalent set of substitution, restriction and extension, so that the operation works as expected.
            // (The goal of the (derived | base) == derived is to fail if the derived is not a bitwise superset of base)
            XmlSchemaDerivationMethod baseEffectiveBlock =
                baseElement.ElementDecl.Block == XmlSchemaDerivationMethod.All ?
                    XmlSchemaDerivationMethod.Substitution | XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension :
                    baseElement.ElementDecl.Block;
            XmlSchemaDerivationMethod derivedEffectiveBlock =
                derivedElement.ElementDecl.Block == XmlSchemaDerivationMethod.All ?
                    XmlSchemaDerivationMethod.Substitution | XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension :
                    derivedElement.ElementDecl.Block;

            if(! ((derivedElement.QualifiedName == baseElement.QualifiedName) &&
                 (baseElement.IsNillable || !derivedElement.IsNillable) &&
                 IsValidOccurrenceRangeRestriction(derivedElement, baseElement) &&
                 (baseElement.FixedValue == null || IsFixedEqual(baseElement.ElementDecl, derivedElement.ElementDecl) ) &&
                 ((derivedEffectiveBlock | baseEffectiveBlock) == derivedEffectiveBlock) &&
                 (derivedElement.ElementSchemaType != null) && (baseElement.ElementSchemaType != null) &&
                 XmlSchemaType.IsDerivedFrom(derivedElement.ElementSchemaType, baseElement.ElementSchemaType, ~(XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union))) ) {
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromElement, derivedElement.QualifiedName, baseElement.QualifiedName);    
                return false;
            }
            return true;
        }

        private bool IsElementFromAny(XmlSchemaElement derivedElement, XmlSchemaAny baseAny) {
            if (!baseAny.Allows(derivedElement.QualifiedName)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromAnyRule1, derivedElement.QualifiedName.ToString());
                return false;
            }
            if (!IsValidOccurrenceRangeRestriction(derivedElement, baseAny)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromAnyRule2, derivedElement.QualifiedName.ToString());
                return false;
            }
            return true;
        }

        private bool IsAnyFromAny(XmlSchemaAny derivedAny, XmlSchemaAny baseAny) {
            if (!IsValidOccurrenceRangeRestriction(derivedAny, baseAny)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_AnyFromAnyRule1);
                return false;
            }
            if (!NamespaceList.IsSubset(derivedAny.NamespaceList, baseAny.NamespaceList)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_AnyFromAnyRule2);
                return false;
            }
            if ((int)derivedAny.ProcessContentsCorrect < (int)baseAny.ProcessContentsCorrect) {
                restrictionErrorMsg = Res.GetString(Res.Sch_AnyFromAnyRule3);
                return false;
            }
            return true;
        }

        private bool IsGroupBaseFromAny(XmlSchemaGroupBase derivedGroupBase, XmlSchemaAny baseAny) {
            decimal minOccurs, maxOccurs;
            CalculateEffectiveTotalRange(derivedGroupBase, out minOccurs, out maxOccurs);
            if (!IsValidOccurrenceRangeRestriction(minOccurs, maxOccurs, baseAny.MinOccurs, baseAny.MaxOccurs)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseFromAny2, derivedGroupBase.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedGroupBase.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseAny.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseAny.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
                return false;
            }
            // eliminate occurrance range check
            string minOccursAny = baseAny.MinOccursString;
            baseAny.MinOccurs = decimal.Zero;
            for (int i = 0; i < derivedGroupBase.Items.Count; ++i) {
                if (!IsValidRestriction((XmlSchemaParticle)derivedGroupBase.Items[i], baseAny)) {
                    restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseFromAny1);
                    baseAny.MinOccursString = minOccursAny;
                    return false;
                }
            }
            baseAny.MinOccursString = minOccursAny;
            return true;
        }
  
#if Microsoft      
        private bool IsElementFromGroupBase(XmlSchemaElement derivedElement, XmlSchemaGroupBase baseGroupBase,  bool skipEmptableOnly) {
            if (!IsRangeSimple(baseGroupBase.MinOccurs, baseGroupBase.MaxOccurs) || !IsRangeSimple(derivedElement.MinOccurs, derivedElement.MaxOccurs)) {
                return IsElementFromGroupBase(derivedElement, baseGroupBase); //SPEC COMPLIANT
            }
            else {
                //Base partilce's and Derived Element's range is simple
                //If all particles in baseParticle also have simple ranges, then can use our algorithm
                //So that we dont break common cases that we used to accept earlier 
                //Example Choice -> Element
                if (IsElementFromGroupBaseHack(derivedElement, baseGroupBase, skipEmptableOnly)) {
                    return true;
                }
                else { //Fall back to regular checking
                    return IsElementFromGroupBase(derivedElement, baseGroupBase);
                }
            }
        }

        private bool IsElementFromGroupBaseHack(XmlSchemaElement derivedElement, XmlSchemaGroupBase baseGroupBase,  bool skipEmptableOnly) {
            bool isMatched = false;

            foreach(XmlSchemaParticle baseParticle in baseGroupBase.Items) {
                if (!isMatched && IsRangeSimple(baseParticle.MinOccurs, baseParticle.MaxOccurs)) {
                    string minOccursElement = baseParticle.MinOccursString;
                    string maxOccursElement = baseParticle.MaxOccursString;
                    baseParticle.MinOccurs *= baseGroupBase.MinOccurs;
                    if ( baseParticle.MaxOccurs != decimal.MaxValue) {
                        if (baseGroupBase.MaxOccurs == decimal.MaxValue)
                             baseParticle.MaxOccurs = decimal.MaxValue;
                        else 
                             baseParticle.MaxOccurs *= baseGroupBase.MaxOccurs;
                    }
                    isMatched  = IsValidRestriction(derivedElement, baseParticle);
                    baseParticle.MinOccursString = minOccursElement;
                    baseParticle.MaxOccursString = maxOccursElement;
                }
                if (!isMatched && skipEmptableOnly && !IsParticleEmptiable(baseParticle)) {
                    return false;
                }
            }
            return isMatched;
        }
#endif        
        private bool IsElementFromGroupBase(XmlSchemaElement derivedElement, XmlSchemaGroupBase baseGroupBase) {
            if (baseGroupBase is XmlSchemaSequence) {
                XmlSchemaSequence virtualSeq = new XmlSchemaSequence();
                virtualSeq.MinOccurs = 1;
                virtualSeq.MaxOccurs = 1;
                virtualSeq.Items.Add(derivedElement);
                if (IsGroupBaseFromGroupBase((XmlSchemaGroupBase)virtualSeq, baseGroupBase, true)) {
                    return true;
                }
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromGroupBase1, derivedElement.QualifiedName.ToString(), derivedElement.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedElement.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
            }
            else if (baseGroupBase is XmlSchemaChoice) {
                XmlSchemaChoice virtualChoice = new XmlSchemaChoice();
                virtualChoice.MinOccurs = 1;
                virtualChoice.MaxOccurs = 1;
                virtualChoice.Items.Add(derivedElement);
                if (IsGroupBaseFromGroupBase((XmlSchemaGroupBase)virtualChoice, baseGroupBase, false)) {
                    return true;
                }
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromGroupBase2, derivedElement.QualifiedName.ToString(), derivedElement.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedElement.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
            }
            else if (baseGroupBase is XmlSchemaAll) {
                XmlSchemaAll virtualAll = new XmlSchemaAll();
                virtualAll.MinOccurs = 1;
                virtualAll.MaxOccurs = 1;
                virtualAll.Items.Add(derivedElement);
                if (IsGroupBaseFromGroupBase((XmlSchemaGroupBase)virtualAll, baseGroupBase, true)) {
                    return true;
                }
                restrictionErrorMsg = Res.GetString(Res.Sch_ElementFromGroupBase3, derivedElement.QualifiedName.ToString(), derivedElement.LineNumber.ToString(NumberFormatInfo.InvariantInfo), derivedElement.LinePosition.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LineNumber.ToString(NumberFormatInfo.InvariantInfo), baseGroupBase.LinePosition.ToString(NumberFormatInfo.InvariantInfo));
            }
            return false;
        }
        
        private bool IsChoiceFromChoiceSubstGroup(XmlSchemaChoice derivedChoice, XmlSchemaChoice baseChoice) {
            if (!IsValidOccurrenceRangeRestriction(derivedChoice, baseChoice)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseRestRangeInvalid);
                return false;
            }
            for (int i = 0; i < derivedChoice.Items.Count; ++i) {
                if (GetMappingParticle((XmlSchemaParticle)derivedChoice.Items[i], baseChoice.Items) < 0) {
                    return false;
                }
            }
            return true;
        }

        private bool IsGroupBaseFromGroupBase(XmlSchemaGroupBase derivedGroupBase, XmlSchemaGroupBase baseGroupBase,  bool skipEmptableOnly) {
            if (!IsValidOccurrenceRangeRestriction(derivedGroupBase, baseGroupBase)) {
                restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseRestRangeInvalid);
                return false;
            }
            if (derivedGroupBase.Items.Count > baseGroupBase.Items.Count) {
                restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseRestNoMap);
                return false;
            }
            int count = 0;
            for (int i = 0; i < baseGroupBase.Items.Count; ++i) {
                XmlSchemaParticle baseParticle = (XmlSchemaParticle)baseGroupBase.Items[i];
                if ((count < derivedGroupBase.Items.Count)
                        && IsValidRestriction((XmlSchemaParticle)derivedGroupBase.Items[count], baseParticle)) {
                    count ++;
                }
                else if (skipEmptableOnly && !IsParticleEmptiable(baseParticle)) {
                    if (restrictionErrorMsg == null) { //If restriction failed on previous check, do not overwrite error 
                        restrictionErrorMsg = Res.GetString(Res.Sch_GroupBaseRestNotEmptiable);
                    }
                    return false;
                }
            }
            if (count < derivedGroupBase.Items.Count) {
                return false;
            }
            return true;
        }

        private bool IsSequenceFromAll(XmlSchemaSequence derivedSequence, XmlSchemaAll baseAll) {
            if (!IsValidOccurrenceRangeRestriction(derivedSequence, baseAll) || derivedSequence.Items.Count > baseAll.Items.Count) {
                return false;
            }
            BitSet map = new BitSet(baseAll.Items.Count);
            for (int j = 0; j < derivedSequence.Items.Count; ++j) {
                int i = GetMappingParticle((XmlSchemaParticle)derivedSequence.Items[j], baseAll.Items);
                if (i >= 0) {
                    if (map[i]) {
                        return false;
                    }
                    else {
                        map.Set(i);
                    }
                }
                else {
                    return false;
                }
            }
            for (int i = 0; i < baseAll.Items.Count; i++) {
                if (!map[i] && !IsParticleEmptiable((XmlSchemaParticle)baseAll.Items[i])) {
                    return false;
                }
            }
            return true;
        }

        private bool IsSequenceFromChoice(XmlSchemaSequence derivedSequence, XmlSchemaChoice baseChoice) {
            decimal minOccurs, maxOccurs;
            minOccurs = derivedSequence.MinOccurs * derivedSequence.Items.Count;
            if (derivedSequence.MaxOccurs == decimal.MaxValue) {
                maxOccurs = decimal.MaxValue;
            }
            else {
                maxOccurs = derivedSequence.MaxOccurs * derivedSequence.Items.Count;
            }
            if (!IsValidOccurrenceRangeRestriction(minOccurs, maxOccurs, baseChoice.MinOccurs, baseChoice.MaxOccurs) || derivedSequence.Items.Count > baseChoice.Items.Count) {
                return false;
            }
            for (int i = 0; i < derivedSequence.Items.Count; ++i) {
                if (GetMappingParticle((XmlSchemaParticle)derivedSequence.Items[i], baseChoice.Items) < 0)
                    return false;
            }
            return true;
        }

        private bool IsValidOccurrenceRangeRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) {
            return IsValidOccurrenceRangeRestriction(derivedParticle.MinOccurs, derivedParticle.MaxOccurs, baseParticle.MinOccurs, baseParticle.MaxOccurs);
        }

        private bool IsValidOccurrenceRangeRestriction(decimal minOccurs, decimal maxOccurs, decimal baseMinOccurs, decimal baseMaxOccurs) {
            return (baseMinOccurs <= minOccurs) && (maxOccurs <= baseMaxOccurs);
        }

        private int GetMappingParticle(XmlSchemaParticle particle, XmlSchemaObjectCollection collection) {
            for (int i = 0; i < collection.Count; i++) {
                if (IsValidRestriction(particle, (XmlSchemaParticle)collection[i]))
                    return i;
            }
            return -1;
        }

        private bool IsParticleEmptiable(XmlSchemaParticle particle) {
            decimal minOccurs, maxOccurs;
            CalculateEffectiveTotalRange(particle, out minOccurs, out maxOccurs);
            return minOccurs == decimal.Zero;
        }

        private void CalculateEffectiveTotalRange(XmlSchemaParticle particle, out decimal minOccurs, out decimal maxOccurs) {
            XmlSchemaChoice choice = particle as XmlSchemaChoice;

            if (particle is XmlSchemaElement || particle is XmlSchemaAny) {
                minOccurs = particle.MinOccurs;
                maxOccurs = particle.MaxOccurs;
            }
            else if (choice != null) {
                if (choice.Items.Count == 0) {
                    minOccurs = maxOccurs = decimal.Zero;
                }
                else {
                    minOccurs = decimal.MaxValue; 
                    maxOccurs = decimal.Zero;
                    for (int i = 0; i < choice.Items.Count; ++i) {
                        decimal min, max;
                        CalculateEffectiveTotalRange((XmlSchemaParticle)choice.Items[i], out min, out max);
                        if (min < minOccurs) {
                            minOccurs = min;
                        }
                        if (max > maxOccurs) {
                            maxOccurs = max;
                        }
                    }
                    minOccurs *= particle.MinOccurs;
                    if (maxOccurs != decimal.MaxValue) {
                        if (particle.MaxOccurs == decimal.MaxValue)
                            maxOccurs = decimal.MaxValue;
                        else 
                            maxOccurs *= particle.MaxOccurs;
                    }
                }
            }
            else {
                XmlSchemaObjectCollection collection = ((XmlSchemaGroupBase)particle).Items;
                if (collection.Count == 0) {
                    minOccurs = maxOccurs = decimal.Zero;
                }
                else {
                    minOccurs = 0;
                    maxOccurs = 0;
                    for (int i = 0; i < collection.Count; ++i) {
                        decimal min, max;
                        CalculateEffectiveTotalRange((XmlSchemaParticle)collection[i], out min, out max);
                        minOccurs += min;
                        if (maxOccurs != decimal.MaxValue) {
                            if (max == decimal.MaxValue)
                                maxOccurs = decimal.MaxValue;
                            else 
                                maxOccurs += max;
                        }
                    }
                    minOccurs *= particle.MinOccurs;
                    if (maxOccurs != decimal.MaxValue) {
                        if (particle.MaxOccurs == decimal.MaxValue)
                            maxOccurs = decimal.MaxValue;
                        else 
                            maxOccurs *= particle.MaxOccurs;
                    }
                }
            }
        }

        private void PushComplexType(XmlSchemaComplexType complexType) {
            this.complexTypeStack.Push(complexType);
        }

        private XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaParticle particle) {
            if ((complexContent != null && complexContent.IsMixed) ||
                (complexContent == null && complexType.IsMixed)) {
                return XmlSchemaContentType.Mixed;      
            }
            else if (particle != null && !particle.IsEmpty) {
                return XmlSchemaContentType.ElementOnly;
            }
            else {
                return XmlSchemaContentType.Empty;                            
            }
        }

        private void CompileAttributeGroup(XmlSchemaAttributeGroup attributeGroup) {
            if (attributeGroup.IsProcessing) {
                SendValidationEvent(Res.Sch_AttributeGroupCircularRef, attributeGroup);
                return;
            }
            if (attributeGroup.AttributeUses.Count > 0) {// already checked
                return;
            }
            attributeGroup.IsProcessing = true;
            XmlSchemaAnyAttribute anyAttribute = attributeGroup.AnyAttribute;

            try {
                for (int i = 0; i < attributeGroup.Attributes.Count; ++i) {
                    XmlSchemaAttribute attr = attributeGroup.Attributes[i] as XmlSchemaAttribute;
                    if (attr != null) {
                        if (attr.Use == XmlSchemaUse.Prohibited) {
                            continue;
                        }
                        CompileAttribute(attr);
                        if (attributeGroup.AttributeUses[attr.QualifiedName] == null) {
                            attributeGroup.AttributeUses.Add(attr.QualifiedName, attr);
                        }
                        else  {
                            SendValidationEvent(Res.Sch_DupAttributeUse, attr.QualifiedName.ToString(), attr);
                        }
                    }
                    else { // XmlSchemaAttributeGroupRef
                        XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributeGroup.Attributes[i];
                        XmlSchemaAttributeGroup attributeGroupResolved;
                        if (attributeGroup.Redefined != null && attributeGroupRef.RefName == attributeGroup.Redefined.QualifiedName) {
                            attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroup.Redefined;
                        }
                        else {
                            attributeGroupResolved = (XmlSchemaAttributeGroup)attributeGroups[attributeGroupRef.RefName];
                        }
                        if (attributeGroupResolved != null) {
                            CompileAttributeGroup(attributeGroupResolved);
                            foreach (XmlSchemaAttribute attribute in attributeGroupResolved.AttributeUses.Values) {
                                if (attributeGroup.AttributeUses[attribute.QualifiedName] == null) {
                                    attributeGroup.AttributeUses.Add(attribute.QualifiedName, attribute);
                                }
                                else {
                                    SendValidationEvent(Res.Sch_DupAttributeUse, attribute.QualifiedName.ToString(), attribute);
                                }
                            }
                            anyAttribute = CompileAnyAttributeIntersection(anyAttribute, attributeGroupResolved.AttributeWildcard);
                        }
                        else {
                            SendValidationEvent(Res.Sch_UndefAttributeGroupRef, attributeGroupRef.RefName.ToString(), attributeGroupRef);
                        }
                    }
                }          
                attributeGroup.AttributeWildcard = anyAttribute;
            }
            finally {
                attributeGroup.IsProcessing = false;
            }
        }

        private void CompileLocalAttributes(XmlSchemaComplexType baseType, XmlSchemaComplexType derivedType, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlSchemaDerivationMethod derivedBy) {
            XmlSchemaAnyAttribute baseAttributeWildcard = baseType != null ? baseType.AttributeWildcard : null;  
            for (int i = 0; i < attributes.Count; ++i) {
                XmlSchemaAttribute attr = attributes[i] as XmlSchemaAttribute;
                if (attr != null) {
                    if (attr.Use != XmlSchemaUse.Prohibited) {
                        CompileAttribute(attr);
                    }
                    if (attr.Use != XmlSchemaUse.Prohibited || 
                        (attr.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) {

                        if (derivedType.AttributeUses[attr.QualifiedName] == null) {
                            derivedType.AttributeUses.Add(attr.QualifiedName, attr);
                        }
                        else  {
                            SendValidationEvent(Res.Sch_DupAttributeUse, attr.QualifiedName.ToString(), attr);
                        }
                    }
                    else {
                        SendValidationEvent(Res.Sch_AttributeIgnored, attr.QualifiedName.ToString(), attr, XmlSeverityType.Warning);
                    }

                }
                else { // is XmlSchemaAttributeGroupRef
                    XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef) attributes[i];
                    XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)attributeGroups[attributeGroupRef.RefName];
                    if (attributeGroup != null) {
                        CompileAttributeGroup(attributeGroup);
                        foreach (XmlSchemaAttribute attribute in attributeGroup.AttributeUses.Values) {
                          if (attribute.Use != XmlSchemaUse.Prohibited || 
                             (attribute.Use == XmlSchemaUse.Prohibited && derivedBy == XmlSchemaDerivationMethod.Restriction && baseType != XmlSchemaComplexType.AnyType)) {
                            if (derivedType.AttributeUses[attribute.QualifiedName] == null) {
                                derivedType.AttributeUses.Add(attribute.QualifiedName, attribute);
                            }
                            else {
                                SendValidationEvent(Res.Sch_DupAttributeUse, attribute.QualifiedName.ToString(), attributeGroupRef);
                            }
                          }
                          else {
                            SendValidationEvent(Res.Sch_AttributeIgnored, attribute.QualifiedName.ToString(), attribute, XmlSeverityType.Warning);
                          }

                        }
                        anyAttribute = CompileAnyAttributeIntersection(anyAttribute, attributeGroup.AttributeWildcard);
                    }
                    else {
                        SendValidationEvent(Res.Sch_UndefAttributeGroupRef, attributeGroupRef.RefName.ToString(), attributeGroupRef);
                    }
                }
            }

            // check derivation rules
            if (baseType != null) {
                if (derivedBy == XmlSchemaDerivationMethod.Extension) {
                    derivedType.SetAttributeWildcard(CompileAnyAttributeUnion(anyAttribute, baseAttributeWildcard));
                    foreach(XmlSchemaAttribute attributeBase in baseType.AttributeUses.Values) {
                        XmlSchemaAttribute attribute = (XmlSchemaAttribute)derivedType.AttributeUses[attributeBase.QualifiedName];
                        if (attribute == null) {
                            derivedType.AttributeUses.Add(attributeBase.QualifiedName, attributeBase);
                        }
                        else {
                            Debug.Assert(attribute.Use != XmlSchemaUse.Prohibited);
                            if (attributeBase.Use != XmlSchemaUse.Prohibited && attribute.AttributeSchemaType != attributeBase.AttributeSchemaType) { //Extension allows previously prohibited attributes to be re-added, 
                                SendValidationEvent(Res.Sch_InvalidAttributeExtension, attribute);
                            }
                        }
                    }
                }
                else {  // derivedBy == XmlSchemaDerivationMethod.Restriction
                    // Schema Component Constraint: Derivation Valid (Restriction, Complex)
                    if ((anyAttribute != null) && (baseAttributeWildcard == null || !XmlSchemaAnyAttribute.IsSubset(anyAttribute, baseAttributeWildcard) || !IsProcessContentsRestricted(baseType, anyAttribute, baseAttributeWildcard)) ) {
                        SendValidationEvent(Res.Sch_InvalidAnyAttributeRestriction, derivedType);
                    }
                    else {
                        derivedType.SetAttributeWildcard(anyAttribute); //complete wildcard
                    }

                    // Add form the base
                    foreach(XmlSchemaAttribute attributeBase in baseType.AttributeUses.Values) {
                        XmlSchemaAttribute attribute = (XmlSchemaAttribute)derivedType.AttributeUses[attributeBase.QualifiedName];
                        if (attribute == null) {
                            derivedType.AttributeUses.Add(attributeBase.QualifiedName, attributeBase);
                        } 
                        else {
                            if (attributeBase.Use == XmlSchemaUse.Prohibited && attribute.Use != XmlSchemaUse.Prohibited) {
#if DEBUG
                                string position = string.Empty;
                                if (derivedType.SourceUri != null) {
                                    position = " in " + derivedType.SourceUri + "(" + derivedType.LineNumber + ", " + derivedType.LinePosition + ")";
                                }
                                Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "Invalid complexType attributes restriction" + position);
                                Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Base    " + DumpAttributes(baseType.AttributeUses, baseType.AttributeWildcard));
                                Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Derived " + DumpAttributes(derivedType.AttributeUses, derivedType.AttributeWildcard));
#endif
                                SendValidationEvent(Res.Sch_AttributeRestrictionProhibited, attribute);
                            } 
                            else if (attributeBase.Use == XmlSchemaUse.Required && (attribute.Use != XmlSchemaUse.Required)) { //If base is required, derived should also be required
                                SendValidationEvent(Res.Sch_AttributeUseInvalid, attribute);
                            }
                            else if (attribute.Use == XmlSchemaUse.Prohibited) {
                                continue;
                            }
                            else if (attributeBase.AttributeSchemaType == null || attribute.AttributeSchemaType == null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) {
                                SendValidationEvent(Res.Sch_AttributeRestrictionInvalid, attribute);
                            }
                            else if (!IsFixedEqual(attributeBase.AttDef, attribute.AttDef)) {
                                SendValidationEvent(Res.Sch_AttributeFixedInvalid, attribute);
                            }
                        }
                    }

                    // Check additional ones are valid restriction of base's wildcard
                    foreach(XmlSchemaAttribute attribute in derivedType.AttributeUses.Values) {
                        XmlSchemaAttribute attributeBase = (XmlSchemaAttribute)baseType.AttributeUses[attribute.QualifiedName];
                        if (attributeBase != null) {
                            continue;
                        }
                        if (baseAttributeWildcard == null || !baseAttributeWildcard.Allows(attribute.QualifiedName)) {
#if DEBUG
                            string position = string.Empty;
                            if (derivedType.SourceUri != null) {
                                position = " in " + derivedType.SourceUri + "(" + derivedType.LineNumber + ", " + derivedType.LinePosition + ")";
                            }
                            Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "Invalid complexType attributes restriction" + position);
                            Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Base    " + DumpAttributes(baseType.AttributeUses, baseType.AttributeWildcard));
                            Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceError, "     Derived " + DumpAttributes(derivedType.AttributeUses, derivedType.AttributeWildcard));
#endif
                            SendValidationEvent(Res.Sch_AttributeRestrictionInvalidFromWildcard, attribute);
                        }
                    }
                }
            } 
            else {
                derivedType.SetAttributeWildcard(anyAttribute);
            }
       }

        private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttributeGroup, XmlSchemaAttributeGroup derivedAttributeGroup) {
            XmlSchemaAnyAttribute baseAnyAtt = baseAttributeGroup.AttributeWildcard;
            XmlSchemaAnyAttribute derivedAnyAtt = derivedAttributeGroup.AttributeWildcard;

            if ((derivedAnyAtt != null) && (baseAnyAtt == null || !XmlSchemaAnyAttribute.IsSubset(derivedAnyAtt, baseAnyAtt) || !IsProcessContentsRestricted(null, derivedAnyAtt, baseAnyAtt))) {
                SendValidationEvent(Res.Sch_InvalidAnyAttributeRestriction, derivedAttributeGroup);
            }
            foreach(XmlSchemaAttribute attributeBase in baseAttributeGroup.AttributeUses.Values) {
                XmlSchemaAttribute attribute = (XmlSchemaAttribute)derivedAttributeGroup.AttributeUses[attributeBase.QualifiedName];
                if (attribute != null) {
                    if (attributeBase.Use == XmlSchemaUse.Prohibited && attribute.Use != XmlSchemaUse.Prohibited) {
                        SendValidationEvent(Res.Sch_AttributeRestrictionProhibited, attribute);
                    } 
                    else if (attributeBase.Use == XmlSchemaUse.Required && attribute.Use != XmlSchemaUse.Required) {
                        SendValidationEvent(Res.Sch_AttributeUseInvalid, attribute);
                    }
                    else if (attribute.Use == XmlSchemaUse.Prohibited) { //If derived att is prohibited, continue
                        continue;
                    }
                    else if (attributeBase.AttributeSchemaType == null || attribute.AttributeSchemaType == null || !XmlSchemaType.IsDerivedFrom(attribute.AttributeSchemaType, attributeBase.AttributeSchemaType, XmlSchemaDerivationMethod.Empty)) {
                        SendValidationEvent(Res.Sch_AttributeRestrictionInvalid, attribute);
                    }
                    else if (!IsFixedEqual(attributeBase.AttDef, attribute.AttDef)) {
                        SendValidationEvent(Res.Sch_AttributeFixedInvalid, attribute);
                    }    
                }
                else if (attributeBase.Use == XmlSchemaUse.Required) {
                    SendValidationEvent(Res.Sch_NoDerivedAttribute, attributeBase.QualifiedName.ToString(), baseAttributeGroup.QualifiedName.ToString(), derivedAttributeGroup);
                }
            }
            // Check additional ones are valid restriction of base's wildcard
            foreach(XmlSchemaAttribute attribute in derivedAttributeGroup.AttributeUses.Values) {
                XmlSchemaAttribute attributeBase = (XmlSchemaAttribute)baseAttributeGroup.AttributeUses[attribute.QualifiedName];
                if (attributeBase != null) {
                    continue;
                }
                if (baseAnyAtt == null || !baseAnyAtt.Allows(attribute.QualifiedName)) {
                    SendValidationEvent(Res.Sch_AttributeRestrictionInvalidFromWildcard, attribute);
                }
            }
        }

#if DEBUG
        private string DumpAttributes(XmlSchemaObjectTable attributeUses, XmlSchemaAnyAttribute attributeWildcard) {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            bool first = true;
            foreach (XmlSchemaAttribute attribute in attributeUses.Values) {
                if (attribute.Use != XmlSchemaUse.Prohibited) {
                    if (first) {
                        first = false;
                    }
                    else {
                        sb.Append(" ");
                    }
                    sb.Append(attribute.QualifiedName.Name);       
                    if (attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) {
                        sb.Append("?");                                                                  
                    }
                }
            }
            if (attributeWildcard != null) {
                if (attributeUses.Count != 0) {
                    sb.Append(" ");                                                                  
                }
                sb.Append("<");
                sb.Append(attributeWildcard.NamespaceList.ToString());
                sb.Append(">");
            }
            sb.Append("] - [");
            first = true;
            foreach (XmlSchemaAttribute attribute in attributeUses.Values) {
                if (attribute.Use == XmlSchemaUse.Prohibited) {
                    if (first) {
                        first = false;
                    }
                    else {
                        sb.Append(" ");
                    }
                    sb.Append(attribute.QualifiedName.Name);       
                }
            }
            sb.Append("]");
            return sb.ToString();
        }
#endif

        private bool IsProcessContentsRestricted(XmlSchemaComplexType baseType, XmlSchemaAnyAttribute derivedAttributeWildcard, XmlSchemaAnyAttribute baseAttributeWildcard) {
            if (baseType == XmlSchemaComplexType.AnyType) {
                return true;
            }
            if ((int)derivedAttributeWildcard.ProcessContentsCorrect >= (int)baseAttributeWildcard.ProcessContentsCorrect) {
                return true;
            }
            return false;
        }

        private XmlSchemaAnyAttribute CompileAnyAttributeUnion(XmlSchemaAnyAttribute a, XmlSchemaAnyAttribute b) {
            if (a == null) {
                return b;
            }
            else if (b == null) {
                return a;
            }
            else {
                XmlSchemaAnyAttribute attribute = XmlSchemaAnyAttribute.Union(a, b, false); //false is for v1Compatd
                if (attribute == null) {
                    SendValidationEvent(Res.Sch_UnexpressibleAnyAttribute, a);
                }
                return attribute;
            }

        }

        private XmlSchemaAnyAttribute CompileAnyAttributeIntersection(XmlSchemaAnyAttribute a, XmlSchemaAnyAttribute b) {
            if (a == null) {
                return b;
            }
            else if (b == null) {
                return a;
            }
            else {
                XmlSchemaAnyAttribute attribute = XmlSchemaAnyAttribute.Intersection(a, b, false); //false is for v1Compat
                if (attribute == null) {
                    SendValidationEvent(Res.Sch_UnexpressibleAnyAttribute, a);
                }
                return attribute;
            }
        }

         private void CompileAttribute(XmlSchemaAttribute xa) {
            if (xa.IsProcessing) {
                SendValidationEvent(Res.Sch_AttributeCircularRef, xa);
                return;
            }
            if (xa.AttDef != null) { //already compiled?
                return;
            }
            xa.IsProcessing = true;
            SchemaAttDef decl = null;
            try {
                if (!xa.RefName.IsEmpty) {
                    XmlSchemaAttribute a = (XmlSchemaAttribute)attributes[xa.RefName];
                    if (a == null) {
                        throw new XmlSchemaException(Res.Sch_UndeclaredAttribute, xa.RefName.ToString(), xa);
                    }     
                    CompileAttribute(a);
                    if (a.AttDef == null) {
                        throw new XmlSchemaException(Res.Sch_RefInvalidAttribute, xa.RefName.ToString(), xa);
                    }
                    decl = a.AttDef.Clone();
                    XmlSchemaDatatype datatype = decl.Datatype;

                    if (datatype != null) {
                        if (a.FixedValue == null && a.DefaultValue == null) {
                            SetDefaultFixed(xa, decl);
                        }
                        else if (a.FixedValue != null) {
                            if (xa.DefaultValue != null) {
                                throw new XmlSchemaException(Res.Sch_FixedDefaultInRef, xa.RefName.ToString(), xa);
                            }
                            else if (xa.FixedValue != null ) {
                                object refFixedValue = datatype.ParseValue(xa.FixedValue, NameTable, new SchemaNamespaceManager(xa), true);
                                if ( !datatype.IsEqual(decl.DefaultValueTyped, refFixedValue)) {
                                    throw new XmlSchemaException(Res.Sch_FixedInRef, xa.RefName.ToString(), xa);
                                }
                            }
                        }
                    }
                    xa.SetAttributeType(a.AttributeSchemaType);
                }
                else {
                    decl = new SchemaAttDef(xa.QualifiedName);
                    if (xa.SchemaType != null) {
                        CompileSimpleType(xa.SchemaType);
                        xa.SetAttributeType(xa.SchemaType);
                        decl.SchemaType = xa.SchemaType;
                        decl.Datatype = xa.SchemaType.Datatype;
                    }
                    else if (!xa.SchemaTypeName.IsEmpty) {
                        XmlSchemaSimpleType simpleType = GetSimpleType(xa.SchemaTypeName);
                        if (simpleType != null) {
                            xa.SetAttributeType(simpleType);
                            decl.Datatype = simpleType.Datatype;
                            decl.SchemaType = simpleType;
                        }
                        else {
                            throw new XmlSchemaException(Res.Sch_UndeclaredSimpleType, xa.SchemaTypeName.ToString(), xa);   
                        }
                    }
                    else {
                        decl.SchemaType = DatatypeImplementation.AnySimpleType;
                        decl.Datatype = DatatypeImplementation.AnySimpleType.Datatype;
                        xa.SetAttributeType(DatatypeImplementation.AnySimpleType);
                    }
                    //} //Removed this here since the following should be done only if RefName is Empty
                    if (decl.Datatype != null) {
                        decl.Datatype.VerifySchemaValid(notations, xa);
                    }
                    SetDefaultFixed(xa, decl);
                } //End of Else for !RefName.IsEmpty

                decl.SchemaAttribute = xa; //So this is available for PSVI
                xa.AttDef = decl;
            } 
            catch (XmlSchemaException e) {
                if (e.SourceSchemaObject == null) {
                    e.SetSource(xa);
                }
                SendValidationEvent(e);
                xa.AttDef = SchemaAttDef.Empty;
            } 
            finally {
                xa.IsProcessing = false;
            }
        }
        
        private void SetDefaultFixed(XmlSchemaAttribute xa, SchemaAttDef decl) {
            if (xa.DefaultValue != null || xa.FixedValue != null) {
                if (xa.DefaultValue != null) {
                    decl.Presence = SchemaDeclBase.Use.Default; 
                    decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.DefaultValue;
                }
                else {
                    if (xa.Use == XmlSchemaUse.Required) {
                        decl.Presence = SchemaDeclBase.Use.RequiredFixed;
                    }
                    else {
                        decl.Presence = SchemaDeclBase.Use.Fixed; 
                    }
                    decl.DefaultValueRaw = decl.DefaultValueExpanded = xa.FixedValue;
                }
                if(decl.Datatype != null) {
                    if (decl.Datatype.TypeCode == XmlTypeCode.Id) {
                        SendValidationEvent(Res.Sch_DefaultIdValue, xa);
                    }
                    else {
                        decl.DefaultValueTyped = decl.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xa), true);
                    }
                }
            }
            else {
                switch (xa.Use) {
                    case XmlSchemaUse.None: 
                    case XmlSchemaUse.Optional: 
                        decl.Presence = SchemaDeclBase.Use.Implied; 
                        break;
                    case XmlSchemaUse.Required: 
                        decl.Presence = SchemaDeclBase.Use.Required; 
                        break;
                    case XmlSchemaUse.Prohibited:
                        break;
                }
            }
        }

        private void CompileIdentityConstraint (XmlSchemaIdentityConstraint xi) { 
            if (xi.IsProcessing) {
                xi.CompiledConstraint = CompiledIdentityConstraint.Empty;       
                SendValidationEvent(Res.Sch_IdentityConstraintCircularRef, xi);
                return;
            }

            if (xi.CompiledConstraint != null) {
                return;
            }
            
            xi.IsProcessing = true;
            CompiledIdentityConstraint compic = null;
            try {
                SchemaNamespaceManager xnmgr = new SchemaNamespaceManager(xi);
                compic = new CompiledIdentityConstraint(xi, xnmgr);
                if (xi is XmlSchemaKeyref) {
                    XmlSchemaIdentityConstraint ic = (XmlSchemaIdentityConstraint)this.identityConstraints[((XmlSchemaKeyref)xi).Refer];
                    if (ic == null) {
                        throw new XmlSchemaException(Res.Sch_UndeclaredIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi);
                    }     
                    CompileIdentityConstraint(ic);
                    if (ic.CompiledConstraint == null) {
                        throw new XmlSchemaException(Res.Sch_RefInvalidIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi);
                    }
                    // keyref has the different cardinality with the key it referred
                    if (ic.Fields.Count != xi.Fields.Count) {
                        throw new XmlSchemaException(Res.Sch_RefInvalidCardin, xi.QualifiedName.ToString(), xi);
                    }
                    // keyref can only refer to key/unique
                    if (ic.CompiledConstraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref) {
                        throw new XmlSchemaException(Res.Sch_ReftoKeyref, xi.QualifiedName.ToString(), xi);
                    }
                }
                xi.CompiledConstraint = compic;
            }
            catch (XmlSchemaException e) {
                if (e.SourceSchemaObject == null) {
                    e.SetSource(xi);
                }
                SendValidationEvent(e);
                xi.CompiledConstraint = CompiledIdentityConstraint.Empty;       
                // empty is better than null here, stop quickly when circle referencing
            } 
            finally {
                xi.IsProcessing = false;
            }

        }

        private void CompileElement(XmlSchemaElement xe) {
            if (xe.IsProcessing) {
                SendValidationEvent(Res.Sch_ElementCircularRef, xe);
                return;
            }
            if (xe.ElementDecl != null) {
                return;
            }
            xe.IsProcessing = true;
            SchemaElementDecl decl = null;
            try {
                if (!xe.RefName.IsEmpty) {
                    XmlSchemaElement e = (XmlSchemaElement)elements[xe.RefName];
                    if (e == null) {
                        throw new XmlSchemaException(Res.Sch_UndeclaredElement, xe.RefName.ToString(), xe);
                    }  
                    CompileElement(e);
                    if (e.ElementDecl == null) {
                        throw new XmlSchemaException(Res.Sch_RefInvalidElement, xe.RefName.ToString(), xe);
                    }
                    xe.SetElementType(e.ElementSchemaType);
                    decl = e.ElementDecl.Clone();
                }
                else {
                    if (xe.SchemaType != null) {
                        xe.SetElementType(xe.SchemaType);
                    }
                    else if (!xe.SchemaTypeName.IsEmpty) {
                        xe.SetElementType(GetAnySchemaType(xe.SchemaTypeName));
                        if (xe.ElementSchemaType == null) {
                            throw new XmlSchemaException(Res.Sch_UndeclaredType, xe.SchemaTypeName.ToString(), xe);   
                        }
                    }
                    else  if (!xe.SubstitutionGroup.IsEmpty) {
                        XmlSchemaElement examplar = (XmlSchemaElement)elements[xe.SubstitutionGroup];
                        if (examplar == null) {
                            throw new XmlSchemaException(Res.Sch_UndeclaredEquivClass, xe.SubstitutionGroup.Name.ToString(CultureInfo.InvariantCulture), xe);   
                        }
                        if (examplar.IsProcessing) { //Circular subst group; already detected by now
                            return;
                        }
                        CompileElement(examplar);
                        if (examplar.ElementDecl == null) { //If head is invalid, fall back to AnyType
                            xe.SetElementType(XmlSchemaComplexType.AnyType);
                            decl = XmlSchemaComplexType.AnyType.ElementDecl.Clone();
                        }
                        else {
                            xe.SetElementType(examplar.ElementSchemaType);
                            decl = examplar.ElementDecl.Clone();
                        }
                    }
                    else {
                        xe.SetElementType(XmlSchemaComplexType.AnyType);
                        decl = XmlSchemaComplexType.AnyType.ElementDecl.Clone();
                    }
            
                    if (decl == null) {
                        Debug.Assert(xe.ElementSchemaType != null);
                        if (xe.ElementSchemaType is XmlSchemaComplexType) {
                            XmlSchemaComplexType complexType = (XmlSchemaComplexType)xe.ElementSchemaType;
                            CompileComplexType(complexType);
                            if (complexType.ElementDecl != null) {
                                decl = complexType.ElementDecl.Clone();
//                                decl.LocalElements = complexType.LocalElementDecls;
                            }
                        } 
                        else if (xe.ElementSchemaType is XmlSchemaSimpleType) {
                            XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)xe.ElementSchemaType;
                            CompileSimpleType(simpleType);
                            if (simpleType.ElementDecl != null) {
                                decl = simpleType.ElementDecl.Clone();
                            }
                        } 
                    }
                    Debug.Assert(decl != null);
                    decl.Name = xe.QualifiedName;
                    decl.IsAbstract = xe.IsAbstract;
                    XmlSchemaComplexType ct = xe.ElementSchemaType as XmlSchemaComplexType;
                    if (ct != null) {
                        decl.IsAbstract |= ct.IsAbstract; 
                    }
                    decl.IsNillable = xe.IsNillable;
                    decl.Block |= xe.BlockResolved;
                }
                if (decl.Datatype != null) {
                    decl.Datatype.VerifySchemaValid(notations, xe);
                }

                if (xe.DefaultValue != null || xe.FixedValue != null) {
                    if (decl.ContentValidator != null) {
                        if (decl.ContentValidator.ContentType == XmlSchemaContentType.TextOnly || (decl.ContentValidator.ContentType == XmlSchemaContentType.Mixed && decl.ContentValidator.IsEmptiable)) {
                            if (xe.DefaultValue != null) {
                                decl.Presence = SchemaDeclBase.Use.Default; 
                                decl.DefaultValueRaw = xe.DefaultValue;
                            }
                            else {
                                decl.Presence = SchemaDeclBase.Use.Fixed; 
                                decl.DefaultValueRaw = xe.FixedValue;
                            }
                            if (decl.Datatype != null) {
                                if (decl.Datatype.TypeCode == XmlTypeCode.Id) {
                                    SendValidationEvent(Res.Sch_DefaultIdValue, xe);
                                }
                                else {
                                    decl.DefaultValueTyped = decl.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xe), true);
                                }
                            }
                            else { //Mixed with emptiable particle
                                decl.DefaultValueTyped = DatatypeImplementation.AnySimpleType.Datatype.ParseValue(decl.DefaultValueRaw, NameTable, new SchemaNamespaceManager(xe));
                            }
                        }
                        else {
                            throw new XmlSchemaException(Res.Sch_ElementCannotHaveValue, xe);
                        }
                    }
                }
                if (xe.HasConstraints) {
                    XmlSchemaObjectCollection constraints = xe.Constraints;
                    CompiledIdentityConstraint[] compiledConstraints = new CompiledIdentityConstraint[constraints.Count];
                    int idx = 0;
                    for (int i = 0; i < constraints.Count; ++i) {
                        XmlSchemaIdentityConstraint constraint = (XmlSchemaIdentityConstraint)constraints[i];
                        CompileIdentityConstraint(constraint);
                        compiledConstraints[idx ++] = constraint.CompiledConstraint;
                    }
                    decl.Constraints = compiledConstraints;
                }
                decl.SchemaElement = xe; //So this is available for PSVI
                xe.ElementDecl = decl;
            } 
            catch (XmlSchemaException e) {
                if (e.SourceSchemaObject == null) {
                    e.SetSource(xe);
                }
                SendValidationEvent(e);
                xe.ElementDecl = SchemaElementDecl.Empty;
            } 
            finally {
                xe.IsProcessing = false;
            }
        }

        private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) {
            if (complexType.ContentType == XmlSchemaContentType.Empty) {
                return ContentValidator.Empty;
            }
            else if (complexType.ContentType == XmlSchemaContentType.TextOnly) {
                return ContentValidator.TextOnly;
            }
            XmlSchemaParticle particle = complexType.ContentTypeParticle;
            if (particle == null || particle == XmlSchemaParticle.Empty) {
                if (complexType.ContentType == XmlSchemaContentType.ElementOnly) {
                    return ContentValidator.Empty;
                }
                else {
                    return ContentValidator.Mixed;
                }
            }
            PushComplexType(complexType);
            if (particle is XmlSchemaAll) {
                XmlSchemaAll all = (XmlSchemaAll)particle;
                AllElementsContentValidator contentValidator = new AllElementsContentValidator(complexType.ContentType, all.Items.Count, all.MinOccurs == decimal.Zero);
                for (int i = 0; i < all.Items.Count; ++i) {
                    XmlSchemaElement localElement = (XmlSchemaElement)all.Items[i];
                    if (!contentValidator.AddElement(localElement.QualifiedName, localElement, localElement.MinOccurs == decimal.Zero)) {
                       SendValidationEvent(Res.Sch_DupElement, localElement.QualifiedName.ToString(), localElement);
                    }
                }
                return contentValidator;
            }
            else {
                ParticleContentValidator contentValidator = new ParticleContentValidator(complexType.ContentType, CompilationSettings.EnableUpaCheck);
#if DEBUG
                string name = complexType.Name != null ? complexType.Name : string.Empty;
                Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceVerbose, "CompileComplexContent: "+ name  + DumpContentModel(particle));
#endif
                try {
                    contentValidator.Start();
                    complexType.HasWildCard = BuildParticleContentModel(contentValidator, particle);
                    return contentValidator.Finish(true);                         
                }
                catch(UpaException e) {
                    if (e.Particle1 is XmlSchemaElement) {
                        if (e.Particle2 is XmlSchemaElement) {
                            SendValidationEvent(Res.Sch_NonDeterministic, ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaElement)e.Particle2);
                        }
                        else {
                            SendValidationEvent(Res.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle2).ResolvedNamespace, ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaAny)e.Particle2);
                        }
                    }
                    else {
                        if (e.Particle2 is XmlSchemaElement) {
                            SendValidationEvent(Res.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle1).ResolvedNamespace, ((XmlSchemaElement)e.Particle2).QualifiedName.ToString(), (XmlSchemaElement)e.Particle2);
                        }
                        else {
                            SendValidationEvent(Res.Sch_NonDeterministicAnyAny, ((XmlSchemaAny)e.Particle1).ResolvedNamespace, ((XmlSchemaAny)e.Particle2).ResolvedNamespace, (XmlSchemaAny)e.Particle2);
                        }
                    }
                    return XmlSchemaComplexType.AnyTypeContentValidator;
                }
                catch(NotSupportedException) {
                    SendValidationEvent(Res.Sch_ComplexContentModel, complexType, XmlSeverityType.Warning);
                    return XmlSchemaComplexType.AnyTypeContentValidator;
                }
            }
        }

#if DEBUG
        private string DumpContentModel(XmlSchemaParticle particle) {
            StringBuilder sb = new StringBuilder();
            DumpContentModelTo(sb, particle);
            return sb.ToString();
        }

        private void DumpContentModelTo(StringBuilder sb, XmlSchemaParticle particle) {
            if (particle is XmlSchemaElement) {
                sb.Append(((XmlSchemaElement)particle).QualifiedName);       
            }
            else if (particle is XmlSchemaAny) {
                sb.Append("<");
                sb.Append(((XmlSchemaAny)particle).NamespaceList.ToString());
                sb.Append(">");
            }
            else if (particle is XmlSchemaAll) {
                XmlSchemaAll all = (XmlSchemaAll)particle;
                sb.Append("[");       
                bool first = true;
                for (int i = 0; i < all.Items.Count; ++i) {
                    XmlSchemaElement localElement = (XmlSchemaElement)all.Items[i];
                    if (first) {
                        first = false;
                    }
                    else {
                        sb.Append(", ");
                    }
                    sb.Append(localElement.QualifiedName.Name);       
                    if (localElement.MinOccurs == decimal.Zero) {
                        sb.Append("?");                                                                  
                    }
                }    
                sb.Append("]");                                
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaGroupBase gb = (XmlSchemaGroupBase)particle;
                sb.Append("(");
                string delimeter = (particle is XmlSchemaChoice) ? " | " : ", ";
                bool first = true;
                for (int i = 0; i < gb.Items.Count; ++i) {
                    if (first) {
                        first = false;
                    }
                    else {
                        sb.Append(delimeter);
                    }
                    DumpContentModelTo(sb, (XmlSchemaParticle)gb.Items[i]);
                }
                sb.Append(")");
            } else {
                Debug.Assert(particle == XmlSchemaParticle.Empty);
                sb.Append("<>");
            }
            if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.One) {
                // nothing
            }
            else if (particle.MinOccurs == decimal.Zero && particle.MaxOccurs == decimal.One) {
                sb.Append("?");
            }
            else if (particle.MinOccurs == decimal.Zero && particle.MaxOccurs == decimal.MaxValue) {
                sb.Append("*");
            }
            else if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.MaxValue) {
                sb.Append("+");
            }
            else {
                sb.Append("{" + particle.MinOccurs.ToString(NumberFormatInfo.InvariantInfo) +", " + particle.MaxOccurs.ToString(NumberFormatInfo.InvariantInfo) + "}");
            }
        }
#endif

        private bool BuildParticleContentModel(ParticleContentValidator contentValidator, XmlSchemaParticle particle) {
            bool hasWildCard = false;
            if (particle is XmlSchemaElement) {
                XmlSchemaElement element = (XmlSchemaElement)particle;
                contentValidator.AddName(element.QualifiedName, element);       
             }
            else if (particle is XmlSchemaAny) {
                hasWildCard = true;
                XmlSchemaAny any = (XmlSchemaAny)particle;
                contentValidator.AddNamespaceList(any.NamespaceList, any);
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items;
                bool isChoice = particle is XmlSchemaChoice;
                contentValidator.OpenGroup();
                bool first = true;
                for (int i = 0; i < particles.Count; ++i) {
                    Debug.Assert(!((XmlSchemaParticle)particles[i]).IsEmpty);
                    if (first) {
                        first = false;
                    }
                    else if (isChoice) {
                        contentValidator.AddChoice();  
                    }
                    else {
                        contentValidator.AddSequence();
                    }
                    hasWildCard = BuildParticleContentModel(contentValidator, (XmlSchemaParticle)particles[i]);
                }
                contentValidator.CloseGroup();
            }
            else {
                Debug.Assert(false);
            }
            if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.One) {
                // nothing
            }
            else if (particle.MinOccurs == decimal.Zero && particle.MaxOccurs == decimal.One) {
                contentValidator.AddQMark();
            }
            else if (particle.MinOccurs == decimal.Zero && particle.MaxOccurs == decimal.MaxValue) {
                contentValidator.AddStar();
            }
            else if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.MaxValue) {
                contentValidator.AddPlus();
            }
            else {
                contentValidator.AddLeafRange(particle.MinOccurs, particle.MaxOccurs);
            }
            return hasWildCard;
        }

        private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchemaParticle particle) {
            if (particle is XmlSchemaElement) {
                XmlSchemaElement localElement = (XmlSchemaElement)particle;
                CompileElement(localElement); 
                if (complexType.LocalElements[localElement.QualifiedName] == null) {
                    complexType.LocalElements.Add(localElement.QualifiedName, localElement);
                }
                else {
                    XmlSchemaElement element = (XmlSchemaElement)complexType.LocalElements[localElement.QualifiedName];
                    if (element.ElementSchemaType != localElement.ElementSchemaType) {
                        SendValidationEvent(Res.Sch_ElementTypeCollision, particle);
                    }
                }                 
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items;
                for (int i = 0; i < particles.Count; ++i) {
                    CompileParticleElements(complexType, (XmlSchemaParticle)particles[i]);
                }
            }
        }

        private void CompileParticleElements(XmlSchemaParticle particle) { //For checking redefined group particle derivation
            if (particle is XmlSchemaElement) {
                XmlSchemaElement localElement = (XmlSchemaElement)particle;
                CompileElement(localElement);
            }
            else if (particle is XmlSchemaGroupBase) {
                XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items;
                for (int i = 0; i < particles.Count; ++i) {
                    CompileParticleElements((XmlSchemaParticle)particles[i]);
                }
            }
        }

        private void CompileComplexTypeElements(XmlSchemaComplexType complexType) {
            if (complexType.IsProcessing) {
                SendValidationEvent(Res.Sch_TypeCircularRef, complexType);
                return;
            }
            complexType.IsProcessing = true;
            try {
                if (complexType.ContentTypeParticle != XmlSchemaParticle.Empty) {
                    CompileParticleElements(complexType, complexType.ContentTypeParticle);
                }
            }
            finally {
                complexType.IsProcessing = false;
            }
        }

        private XmlSchemaSimpleType GetSimpleType(XmlQualifiedName name) {
            XmlSchemaSimpleType type = schemaTypes[name] as XmlSchemaSimpleType;
            if (type != null) {
                CompileSimpleType(type);
            }
            else {
                type = DatatypeImplementation.GetSimpleTypeFromXsdType(name);
            }
            return type;
        }

        private XmlSchemaComplexType GetComplexType(XmlQualifiedName name) {
            XmlSchemaComplexType type = schemaTypes[name] as XmlSchemaComplexType;
            if (type != null) {
                CompileComplexType(type);
            }
            return type;
        }

         private XmlSchemaType GetAnySchemaType(XmlQualifiedName name) {
                XmlSchemaType type = (XmlSchemaType)schemaTypes[name];
                if (type != null) {
                    if (type is XmlSchemaComplexType) {
                        CompileComplexType((XmlSchemaComplexType)type);
                    }
                    else {
                        CompileSimpleType((XmlSchemaSimpleType)type);  
                    }
                    return type;
                }
                else { //Its is a built-in simpleType
                    XmlSchemaSimpleType simpleType = DatatypeImplementation.GetSimpleTypeFromXsdType(name);
                    return simpleType;
                }
        }

         private void CopyPosition(XmlSchemaAnnotated to, XmlSchemaAnnotated from, bool copyParent) {
             to.SourceUri = from.SourceUri;
             to.LinePosition = from.LinePosition;
             to.LineNumber = from.LineNumber;
             to.SetUnhandledAttributes(from.UnhandledAttributes);
             if (copyParent) {
                to.Parent = from.Parent;
             }
         }

         private bool IsFixedEqual(SchemaDeclBase baseDecl, SchemaDeclBase derivedDecl) {
            
            if (baseDecl.Presence == SchemaDeclBase.Use.Fixed || baseDecl.Presence == SchemaDeclBase.Use.RequiredFixed) {
                object baseFixedValue = baseDecl.DefaultValueTyped;
                object derivedFixedValue = derivedDecl.DefaultValueTyped;

                Debug.Assert(baseFixedValue != null);
                if (derivedDecl.Presence != SchemaDeclBase.Use.Fixed && derivedDecl.Presence != SchemaDeclBase.Use.RequiredFixed) {
                    return false;
                }
                Debug.Assert(derivedFixedValue != null);
                XmlSchemaDatatype baseDatatype = baseDecl.Datatype;
                XmlSchemaDatatype derivedDatatype = derivedDecl.Datatype;

                if (baseDatatype.Variety == XmlSchemaDatatypeVariety.Union) {
                    if (derivedDatatype.Variety == XmlSchemaDatatypeVariety.Union) {
                        if ( !derivedDatatype.IsEqual(baseFixedValue, derivedFixedValue) ) {
                            return false;
                        }
                    }
                    else { //Base is union and derived is member of union
                        XsdSimpleValue simpleFixedValue = baseDecl.DefaultValueTyped as XsdSimpleValue;
                        Debug.Assert(simpleFixedValue != null);
                        XmlSchemaDatatype memberType = simpleFixedValue.XmlType.Datatype;
                        if (!memberType.IsComparable(derivedDatatype) || !derivedDatatype.IsEqual(simpleFixedValue.TypedValue, derivedFixedValue)) { //base type {Union of long & string}, derived type {int}
                            return false;
                        }
                    }
                }
                else if (!derivedDatatype.IsEqual(baseFixedValue, derivedFixedValue)) {
                    return false;
                }
            }
            return true;
         }
    };

} // namespace System.Xml