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
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
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Generic;
using Microsoft.Management.Infrastructure.Serialization;
using Microsoft.PowerShell.Commands;

using static Microsoft.PowerShell.SecureStringHelper;

namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
    /// <summary>
    /// </summary>
    [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
        Justification = "Needed Internal use only")]
    public static class DscRemoteOperationsClass
    {
        /// <summary>
        /// Convert Cim Instance representing Resource desired state to Powershell Class Object.
        /// </summary>
        public static object ConvertCimInstanceToObject(Type targetType, CimInstance instance, string moduleName)
        {
            var className = instance.CimClass.CimSystemProperties.ClassName;
            object targetObject = null;
            string errorMessage;

            using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powerShell.AddScript("param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } ");
                powerShell.AddArgument(targetType);
                powerShell.AddArgument(moduleName);

                Collection<PSObject> psExecutionResult = powerShell.Invoke();
                if (psExecutionResult.Count == 1)
                {
                    targetObject = psExecutionResult[0].BaseObject;
                }
                else
                {
                    Exception innerException = null;
                    if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0)
                    {
                        innerException = powerShell.Streams.Error[0].Exception;
                    }

                    errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InstantiatePSClassObjectFailed, className);
                    var invalidOperationException = new InvalidOperationException(errorMessage, innerException);
                    throw invalidOperationException;
                }
            }

            foreach (var property in instance.CimInstanceProperties)
            {
                if (property.Value != null)
                {
                    MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance);

                    // verify property exists in corresponding class type
                    if (memberInfo == null
                        || memberInfo.Length > 1
                        || (memberInfo[0] is not PropertyInfo && memberInfo[0] is not FieldInfo))
                    {
                        errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.PropertyNotDeclaredInPSClass, new object[] { property.Name, className });
                        var invalidOperationException = new InvalidOperationException(errorMessage);
                        throw invalidOperationException;
                    }

                    var member = memberInfo[0];
                    var memberType = (member is FieldInfo)
                        ? ((FieldInfo)member).FieldType
                        : ((PropertyInfo)member).PropertyType;

                    object targetValue = null;
                    switch (property.CimType)
                    {
                        case CimType.Instance:
                            {
                                var cimPropertyInstance = property.Value as CimInstance;
                                if (cimPropertyInstance != null &&
                                    cimPropertyInstance.CimClass != null &&
                                    cimPropertyInstance.CimClass.CimSystemProperties != null &&
                                    string.Equals(
                                        cimPropertyInstance.CimClass.CimSystemProperties.ClassName,
                                        "MSFT_Credential", StringComparison.OrdinalIgnoreCase))
                                {
                                    targetValue = ConvertCimInstancePsCredential(moduleName, cimPropertyInstance);
                                }
                                else
                                {
                                    targetValue = ConvertCimInstanceToObject(memberType, cimPropertyInstance, moduleName);
                                }

                                if (targetValue == null)
                                {
                                    return null;
                                }
                            }

                            break;
                        case CimType.InstanceArray:
                            {
                                if (memberType == typeof(Hashtable))
                                {
                                    targetValue = ConvertCimInstanceHashtable(moduleName, (CimInstance[])property.Value);
                                }
                                else
                                {
                                    var instanceArray = (CimInstance[])property.Value;
                                    if (!memberType.IsArray)
                                    {
                                        errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ExpectArrayTypeOfPropertyInPSClass, new object[] { property.Name, className });
                                        var invalidOperationException = new InvalidOperationException(errorMessage);
                                        throw invalidOperationException;
                                    }

                                    var elementType = memberType.GetElementType();
                                    var targetArray = Array.CreateInstance(elementType, instanceArray.Length);
                                    for (int i = 0; i < instanceArray.Length; i++)
                                    {
                                        var obj = ConvertCimInstanceToObject(elementType, instanceArray[i], moduleName);
                                        if (obj == null)
                                        {
                                            return null;
                                        }

                                        targetArray.SetValue(obj, i);
                                    }

                                    targetValue = targetArray;
                                }
                            }

                            break;
                        default:
                            targetValue = LanguagePrimitives.ConvertTo(property.Value, memberType, CultureInfo.InvariantCulture);
                            break;
                    }

                    if (targetValue == null)
                    {
                        errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ConvertCimPropertyToObjectPropertyFailed, new object[] { property.Name, className });
                        var invalidOperationException = new InvalidOperationException(errorMessage);
                        throw invalidOperationException;
                    }

                    if (member is FieldInfo)
                    {
                        ((FieldInfo)member).SetValue(targetObject, targetValue);
                    }

                    if (member is PropertyInfo)
                    {
                        ((PropertyInfo)member).SetValue(targetObject, targetValue);
                    }
                }
            }

            return targetObject;
        }

        /// <summary>
        /// Convert hashtable from Ciminstance to hashtable primitive type.
        /// </summary>
        /// <param name="providerName"></param>
        /// <param name="arrayInstance"></param>
        /// <returns></returns>
        private static object ConvertCimInstanceHashtable(string providerName, CimInstance[] arrayInstance)
        {
            var result = new Hashtable();
            string errorMessage;

            try
            {
                foreach (var keyValuePair in arrayInstance)
                {
                    var key = keyValuePair.CimInstanceProperties["Key"];
                    var value = keyValuePair.CimInstanceProperties["Value"];

                    if (key == null || value == null)
                    {
                        errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
                        var invalidOperationException = new InvalidOperationException(errorMessage);
                        throw invalidOperationException;
                    }

                    result.Add(LanguagePrimitives.ConvertTo<string>(key.Value), LanguagePrimitives.ConvertTo<string>(value.Value));
                }
            }
            catch (Exception exception)
            {
                errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
                var invalidOperationException = new InvalidOperationException(errorMessage, exception);
                throw invalidOperationException;
            }

            return result;
        }
        /// <summary>
        /// Convert CIM instance to PS Credential.
        /// </summary>
        /// <param name="providerName"></param>
        /// <param name="propertyInstance"></param>
        /// <returns></returns>
        private static object ConvertCimInstancePsCredential(string providerName, CimInstance propertyInstance)
        {
            string errorMessage;
            string userName;
            string plainPassWord;

            try
            {
                userName = propertyInstance.CimInstanceProperties["UserName"].Value as string;
                if (string.IsNullOrEmpty(userName))
                {
                    errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
                    var invalidOperationException = new InvalidOperationException(errorMessage);
                    throw invalidOperationException;
                }
            }
            catch (CimException exception)
            {
                errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
                var invalidOperationException = new InvalidOperationException(errorMessage, exception);
                throw invalidOperationException;
            }

            try
            {
                plainPassWord = propertyInstance.CimInstanceProperties["PassWord"].Value as string;

                // In future we might receive password in an encrypted format. Make sure we add
                // the decryption login in this method.
                if (string.IsNullOrEmpty(plainPassWord))
                {
                    errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
                    var invalidOperationException = new InvalidOperationException(errorMessage);
                    throw invalidOperationException;
                }
            }
            catch (CimException exception)
            {
                errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
                var invalidOperationException = new InvalidOperationException(errorMessage, exception);
                throw invalidOperationException;
            }

            SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord);

            password.MakeReadOnly();
            return new PSCredential(userName, password);
        }
    }
}

namespace Microsoft.PowerShell.DesiredStateConfiguration
{
    /// <summary>
    /// To make it easier to specify -ConfigurationData parameter, we add an ArgumentTransformationAttribute here.
    /// When the input data is of type string and is valid path to a file that can be converted to hashtable, we do
    /// the conversion and return the converted value. Otherwise, we just return the input data.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class ArgumentToConfigurationDataTransformationAttribute : ArgumentTransformationAttribute
    {
        /// <summary>
        /// Convert a file of ConfigurationData into a hashtable.
        /// </summary>
        /// <param name="engineIntrinsics"></param>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
        {
            var configDataPath = inputData as string;
            if (string.IsNullOrEmpty(configDataPath))
            {
                return inputData;
            }

            if (engineIntrinsics == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics));
            }

            return PsUtils.EvaluatePowerShellDataFileAsModuleManifest(
                      "ConfigurationData",
                      configDataPath,
                      engineIntrinsics.SessionState.Internal.ExecutionContext,
                      skipPathValidation: false);
        }
    }

    /// <summary>
    /// <para>
    /// Represents a communication channel to a CIM server.
    /// </para>
    /// <para>
    /// This is the main entry point of the Microsoft.Management.Infrastructure API.
    /// All CIM operations are represented as methods of this class.
    /// </para>
    /// </summary>
    internal class CimDSCParser
    {
        private readonly CimMofDeserializer _deserializer;
        private readonly CimMofDeserializer.OnClassNeeded _onClassNeeded;

        /// <summary>
        /// </summary>
        internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded)
        {
            _deserializer = CimMofDeserializer.Create();
            _onClassNeeded = onClassNeeded;
        }

        /// <summary>
        /// </summary>
        internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded, Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption validationOptions)
        {
            _deserializer = CimMofDeserializer.Create();
            _deserializer.SchemaValidationOption = validationOptions;
            _onClassNeeded = onClassNeeded;
        }

        /// <summary>
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things.  Wrapping those 2 things in a class will result in a more, not less complexity")]
        internal List<CimInstance> ParseInstanceMof(string filePath)
        {
            uint offset = 0;
            var buffer = GetFileContent(filePath);
            try
            {
                var result = new List<CimInstance>(_deserializer.DeserializeInstances(buffer, ref offset, _onClassNeeded, null));
                return result;
            }
            catch (CimException exception)
            {
                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                    exception, ParserStrings.CimDeserializationError, filePath);

                e.SetErrorId("CimDeserializationError");
                throw e;
            }
        }

        /// <summary>
        /// Read file content to byte array.
        /// </summary>
        /// <param name="fullFilePath"></param>
        /// <returns></returns>
        internal static byte[] GetFileContent(string fullFilePath)
        {
            if (string.IsNullOrEmpty(fullFilePath))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(fullFilePath));
            }

            if (!File.Exists(fullFilePath))
            {
                var errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileNotFound, fullFilePath);
                throw PSTraceSource.NewArgumentException(nameof(fullFilePath), errorMessage);
            }

            using (FileStream fs = File.OpenRead(fullFilePath))
            {
                var bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                return bytes;
            }
        }

        internal List<CimClass> ParseSchemaMofFileBuffer(string mof)
        {
            uint offset = 0;
#if UNIX
            // OMI only supports UTF-8 without BOM
            var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
#else
            // This is what we traditionally use with Windows
            // DSC asked to keep it UTF-32 for Windows
            var encoding = new UnicodeEncoding();
#endif

            var buffer = encoding.GetBytes(mof);

            var result = new List<CimClass>(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
            return result;
        }

        /// <summary>
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things.  Wrapping those 2 things in a class will result in a more, not less complexity")]
        internal List<CimClass> ParseSchemaMof(string filePath)
        {
            uint offset = 0;
            var buffer = GetFileContent(filePath);
            try
            {
                string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath);
                int dotIndex = fileNameDefiningClass.IndexOf('.');
                if (dotIndex != -1)
                {
                    fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex);
                }

                var result = new List<CimClass>(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
                foreach (CimClass c in result)
                {
                    string superClassName = c.CimSuperClassName;
                    string className = c.CimSystemProperties.ClassName;
                    if ((superClassName != null) && (superClassName.Equals("OMI_BaseResource", StringComparison.OrdinalIgnoreCase)))
                    {
                        // Get the name of the file without schema.mof extension
                        if (!(className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase)))
                        {
                            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass);
                            throw e;
                        }
                    }
                }

                return result;
            }
            catch (CimException exception)
            {
                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                    exception, ParserStrings.CimDeserializationError, filePath);

                e.SetErrorId("CimDeserializationError");
                throw e;
            }
        }

        /// <summary>
        /// Make sure that the instance conforms to the schema.
        /// </summary>
        /// <param name="classText"></param>
        internal void ValidateInstanceText(string classText)
        {
            uint offset = 0;
            byte[] bytes = null;

            if (Platform.IsLinux || Platform.IsMacOS)
            {
                bytes = System.Text.Encoding.UTF8.GetBytes(classText);
            }
            else
            {
                bytes = System.Text.Encoding.Unicode.GetBytes(classText);
            }

            _deserializer.DeserializeInstances(bytes, ref offset, _onClassNeeded, null);
        }
    }
}

namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
    /// <summary>
    /// </summary>
    [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
        Justification = "Needed Internal use only")]
    internal class DscClassCacheEntry
    {
        /// <summary>
        /// Store the RunAs Credentials that this DSC resource will use.
        /// </summary>
        public DSCResourceRunAsCredential DscResRunAsCred;

        /// <summary>
        /// If we have implicitly imported this resource, we will set this field to true. This will
        /// only happen to InBox resources.
        /// </summary>
        public bool IsImportedImplicitly;

        /// <summary>
        /// A CimClass instance for this resource.
        /// </summary>
        public Microsoft.Management.Infrastructure.CimClass CimClassInstance;

        /// <summary>
        /// Initializes variables with default values.
        /// </summary>
        public DscClassCacheEntry() : this(DSCResourceRunAsCredential.Default, false, null) { }

        /// <summary>
        /// Initializes all values.
        /// </summary>
        /// <param name="aDSCResourceRunAsCredential"></param>
        /// <param name="aIsImportedImplicitly"></param>
        /// <param name="aCimClassInstance"></param>
        public DscClassCacheEntry(DSCResourceRunAsCredential aDSCResourceRunAsCredential, bool aIsImportedImplicitly, Microsoft.Management.Infrastructure.CimClass aCimClassInstance)
        {
            DscResRunAsCred = aDSCResourceRunAsCredential;
            IsImportedImplicitly = aIsImportedImplicitly;
            CimClassInstance = aCimClassInstance;
        }
    }

    /// <summary>
    /// </summary>
    [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
        Justification = "Needed Internal use only")]
    public static class DscClassCache
    {
        private const string InboxDscResourceModulePath = "WindowsPowershell\\v1.0\\Modules\\PsDesiredStateConfiguration";

        private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache");

        // Constants for items in the module qualified name (Module\Version\ClassName)
        private const int IndexModuleName = 0;
        private const int IndexModuleVersion = 1;
        private const int IndexClassName = 2;
        private const int IndexFriendlyName = 3;

        // Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1
        private static readonly string[] s_hiddenResourceList =
        {
            "MSFT_BaseConfigurationProviderRegistration",
            "MSFT_CimConfigurationProviderRegistration",
            "MSFT_PSConfigurationProviderRegistration",
        };

        // Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1)
        private static readonly HashSet<string> s_hiddenResourceCache =
            new(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase);

        // a collection to hold current importing script based resource file
        // this prevent circular importing case when the script resource existing in the same module with resources it import-dscresource
        private static readonly HashSet<string> s_currentImportingScriptFiles = new(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// DSC class cache for this runspace.
        /// Cache stores the DSCRunAsBehavior, cim class and boolean to indicate if an Inbox resource has been implicitly imported.
        /// </summary>
        private static Dictionary<string, DscClassCacheEntry> ClassCache
        {
            get
            {
                t_classCache ??= new Dictionary<string, DscClassCacheEntry>(StringComparer.OrdinalIgnoreCase);

                return t_classCache;
            }
        }

        [ThreadStatic]
        private static Dictionary<string, DscClassCacheEntry> t_classCache;

        /// <summary>
        /// DSC classname to source module mapper.
        /// </summary>
        private static Dictionary<string, Tuple<string, Version>> ByClassModuleCache
        {
            get
            {
                t_byClassModuleCache ??= new Dictionary<string, Tuple<string, Version>>(StringComparer.OrdinalIgnoreCase);

                return t_byClassModuleCache;
            }
        }

        [ThreadStatic]
        private static Dictionary<string, Tuple<string, Version>> t_byClassModuleCache;

        /// <summary>
        /// DSC filename to defined class mapper.
        /// </summary>
        private static Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>> ByFileClassCache
        {
            get
            {
                t_byFileClassCache ??= new Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>>(StringComparer.OrdinalIgnoreCase);

                return t_byFileClassCache;
            }
        }

        [ThreadStatic]
        private static Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>> t_byFileClassCache;

        /// <summary>
        /// Filenames from which we have imported script dynamic keywords.
        /// </summary>
        private static HashSet<string> ScriptKeywordFileCache
        {
            get
            {
                t_scriptKeywordFileCache ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);

                return t_scriptKeywordFileCache;
            }
        }

        [ThreadStatic]
        private static HashSet<string> t_scriptKeywordFileCache;

        /// <summary>
        /// Default ModuleName and ModuleVersion to use.
        /// </summary>
        private static readonly Tuple<string, Version> s_defaultModuleInfoForResource =
            new("PSDesiredStateConfiguration", new Version("1.1"));

        /// <summary>
        /// Default ModuleName and ModuleVersion to use for meta configuration resources.
        /// </summary>
        internal static readonly Tuple<string, Version> DefaultModuleInfoForMetaConfigResource =
            new("PSDesiredStateConfigurationEngine", new Version("2.0"));

        /// <summary>
        /// A set of dynamic keywords that can be used in both configuration and meta configuration.
        /// </summary>
        internal static readonly HashSet<string> SystemResourceNames =
            new(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" };

        /// <summary>
        /// When this property is set to true, DSC Cache will cache multiple versions of a resource.
        /// That means it will cache duplicate resource classes (class names for a resource in two different module versions are same).
        /// NOTE: This property should be set to false for DSC compiler related methods/functionality, such as Import-DscResource,
        ///       because the Mof serializer does not support deserialization of classes with different versions.
        /// </summary>
        [ThreadStatic]
        private static bool t_cacheResourcesFromMultipleModuleVersions;

        private static bool CacheResourcesFromMultipleModuleVersions
        {
            get
            {
                return t_cacheResourcesFromMultipleModuleVersions;
            }

            set
            {
                t_cacheResourcesFromMultipleModuleVersions = value;
            }
        }

        /// <summary>
        /// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
        /// </summary>
        public static void Initialize()
        {
            Initialize(null, null);
        }

        /// <summary>
        /// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
        /// </summary>
        /// <param name="errors">Collection of any errors encountered during initialization.</param>
        /// <param name="modulePathList">List of module path from where DSC PS modules will be loaded.</param>
        public static void Initialize(Collection<Exception> errors, List<string> modulePathList)
        {
            s_tracer.WriteLine("Initializing DSC class cache force={0}");

            if (Platform.IsLinux || Platform.IsMacOS)
            {
                //
                // Load the base schema files.
                //
                ClearCache();
                var dscConfigurationDirectory = Environment.GetEnvironmentVariable("DSC_HOME") ??
                                                "/etc/opt/omi/conf/dsc/configuration";

                if (!Directory.Exists(dscConfigurationDirectory))
                {
                    throw new DirectoryNotFoundException("Unable to find DSC schema store at " + dscConfigurationDirectory + ". Please ensure PS DSC for Linux is installed.");
                }

                var resourceBaseFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/BaseResource.schema.mof");
                ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);

                var metaConfigFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/MSFT_DSCMetaConfiguration.mof");
                ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);

                var allResourceRoots = new string[] { dscConfigurationDirectory };

                //
                // Load all of the system resource schema files, searching
                //
                string resources;
                foreach (var resourceRoot in allResourceRoots)
                {
                    resources = Path.Combine(resourceRoot, "schema");
                    if (!Directory.Exists(resources))
                    {
                        continue;
                    }

                    foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
                    {
                        ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
                    }
                }

                // Linux DSC Modules are installed to the dscConfigurationDirectory, so no need to load them.
            }
            else
            {
                // DSC SxS scenario
                var configSystemPath = Utils.DefaultPowerShellAppBase;
                var systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
                var inboxModulePath = "Modules\\PSDesiredStateConfiguration";

                if (!Directory.Exists(systemResourceRoot))
                {
                    configSystemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                    systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
                    inboxModulePath = InboxDscResourceModulePath;
                }

                var programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!");
                var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration");
                Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist");
                var allResourceRoots = new string[] { systemResourceRoot, customResourceRoot };
                //
                // Load the base schema files.
                //
                ClearCache();
                var resourceBaseFile = Path.Combine(systemResourceRoot, "BaseRegistration\\BaseResource.schema.mof");
                ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);

                var metaConfigFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_DSCMetaConfiguration.mof");
                ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);

                var metaConfigExtensionFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_MetaConfigurationExtensionClasses.schema.mof");
                ImportClasses(metaConfigExtensionFile, DefaultModuleInfoForMetaConfigResource, errors);

                //
                // Load all of the system resource schema files, searching
                //
                string resources;
                foreach (var resourceRoot in allResourceRoots)
                {
                    resources = Path.Combine(resourceRoot, "Schema");
                    if (!Directory.Exists(resources))
                    {
                        continue;
                    }

                    foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
                    {
                        ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
                    }
                }

                // Load Regular and DSC PS modules
                bool importInBoxResourcesImplicitly = false;
                List<string> modulePaths = new();
                if (modulePathList == null || modulePathList.Count == 0)
                {
                    modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath));
                    importInBoxResourcesImplicitly = true;
                }
                else
                {
                    foreach (string moduleFolderPath in modulePathList)
                    {
                        if (!Directory.Exists(moduleFolderPath))
                        {
                            continue;
                        }

                        foreach (string moduleDir in Directory.EnumerateDirectories(moduleFolderPath))
                        {
                            modulePaths.Add(moduleDir);
                        }
                    }
                }

                LoadDSCResourceIntoCache(errors, modulePaths, importInBoxResourcesImplicitly);
            }
        }

        /// <summary>
        /// Load DSC resources into Cache from moduleFolderPath.
        /// </summary>
        /// <param name="errors">Collection of any errors encountered during initialization.</param>
        /// <param name="modulePathList">Module path from where DSC PS modules will be loaded.</param>
        /// <param name="importInBoxResourcesImplicitly">
        /// if module is inbox.
        /// </param>
        private static void LoadDSCResourceIntoCache(Collection<Exception> errors, List<string> modulePathList, bool importInBoxResourcesImplicitly)
        {
            foreach (string moduleDir in modulePathList)
            {
                if (!Directory.Exists(moduleDir))
                {
                    continue;
                }

                var dscResourcesPath = Path.Combine(moduleDir, "DscResources");
                if (Directory.Exists(dscResourcesPath))
                {
                    foreach (string resourceDir in Directory.EnumerateDirectories(dscResourcesPath))
                    {
                        IEnumerable<string> schemaFiles = Directory.EnumerateFiles(resourceDir, "*.schema.mof");
                        if (!schemaFiles.Any())
                        {
                            continue;
                        }

                        Tuple<string, Version> moduleInfo = GetModuleInfoHelper(moduleDir, importInBoxResourcesImplicitly, isPsProviderModule: false);
                        if (moduleInfo == null)
                        {
                            continue;
                        }

                        foreach (string schemaFile in schemaFiles)
                        {
                            ImportClasses(schemaFile, moduleInfo, errors, importInBoxResourcesImplicitly);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Get the module name and module version.
        /// </summary>
        /// <param name="moduleFolderPath">
        /// Path to the module folder
        /// </param>
        /// <param name="importInBoxResourcesImplicitly">
        /// if module is inbox and we are importing resources implicitly
        /// </param>
        /// <param name="isPsProviderModule">
        /// Indicate a internal DSC module
        /// </param>
        /// <returns></returns>
        private static Tuple<string, Version> GetModuleInfoHelper(string moduleFolderPath, bool importInBoxResourcesImplicitly, bool isPsProviderModule)
        {
            string moduleName = "PsDesiredStateConfiguration";
            if (!importInBoxResourcesImplicitly)
            {
                moduleName = Path.GetFileName(moduleFolderPath);
            }

            string manifestPath = Path.Combine(moduleFolderPath, moduleName + ".psd1");
            s_tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath);

            if (!File.Exists(manifestPath))
            {
                if (isPsProviderModule)
                {
                    // Some internal PSProviders do not come with a .psd1 file, such
                    // as MSFT_LogResource. We don't report error in this case.
                    return new Tuple<string, Version>(moduleName, new Version("1.0"));
                }
                else
                {
                    s_tracer.WriteLine("DSC GetModuleVersion: Manifest file '{0}' not exist.", manifestPath);
                    return null;
                }
            }

            try
            {
                Hashtable dataFileSetting =
                    PsUtils.GetModuleManifestProperties(
                        manifestPath,
                        PsUtils.ManifestModuleVersionPropertyName);

                object versionValue = dataFileSetting["ModuleVersion"];
                if (versionValue != null)
                {
                    Version moduleVersion;
                    if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion))
                    {
                        return new Tuple<string, Version>(moduleName, moduleVersion);
                    }
                    else
                    {
                        s_tracer.WriteLine(
                            "DSC GetModuleVersion: ModuleVersion value '{0}' cannot be converted to System.Version. Skip the module '{1}'.",
                            versionValue, moduleName);
                    }
                }
                else
                {
                    s_tracer.WriteLine(
                        "DSC GetModuleVersion: Manifest file '{0}' does not contain ModuleVersion. Skip the module '{1}'.",
                        manifestPath, moduleName);
                }
            }
            catch (PSInvalidOperationException ex)
            {
                s_tracer.WriteLine(
                    "DSC GetModuleVersion: Error evaluating module manifest file '{0}', with error '{1}'. Skip the module '{2}'.",
                    manifestPath, ex, moduleName);
            }

            return null;
        }

        // Callback implementation...
        private static CimClass MyClassCallback(string serverName, string namespaceName, string className)
        {
            foreach (KeyValuePair<string, DscClassCacheEntry> cimClass in ClassCache)
            {
                string cachedClassName = cimClass.Key.Split('\\')[IndexClassName];
                if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase))
                {
                    return cimClass.Value.CimClassInstance;
                }
            }

            return null;
        }

        /// <summary>
        /// Reads CIM MOF schema file and returns classes defined in it.
        /// This is used MOF->PSClass conversion tool.
        /// </summary>
        /// <param name="mofPath">
        /// Path to CIM MOF schema file for reading.
        /// </param>
        /// <returns>List of classes from MOF schema file.</returns>
        public static List<CimClass> ReadCimSchemaMof(string mofPath)
        {
            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
            return parser.ParseSchemaMof(mofPath);
        }

        /// <summary>
        /// Import CIM classes from the given file.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="moduleInfo"></param>
        /// <param name="errors"></param>
        /// <param name="importInBoxResourcesImplicitly"></param>
        /// <returns></returns>
        public static List<CimClass> ImportClasses(string path, Tuple<string, Version> moduleInfo, Collection<Exception> errors, bool importInBoxResourcesImplicitly = false)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path);

            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);

            List<CimClass> classes = null;
            try
            {
                classes = parser.ParseSchemaMof(path);
            }
            catch (PSInvalidOperationException e)
            {
                // Ignore modules with invalid schemas.
                s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'.  Skipping file.", path, e);
                errors?.Add(e);
            }

            if (classes != null)
            {
                foreach (var c in classes)
                {
                    // Only add the class once...
                    var className = c.CimSystemProperties.ClassName;
                    string alias = GetFriendlyName(c);
                    var friendlyName = string.IsNullOrEmpty(alias) ? className : alias;
                    string moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleInfo.Item1, moduleInfo.Item2.ToString(), className, friendlyName);
                    DscClassCacheEntry cimClassInfo;

                    if (ClassCache.TryGetValue(moduleQualifiedResourceName, out cimClassInfo))
                    {
                        CimClass cimClass = cimClassInfo.CimClassInstance;

                        // If this is a nested object and we already have exactly same nested object, we will
                        // allow sharing of nested objects.
                        if (!IsSameNestedObject(cimClass, c))
                        {
                            var files = string.Join(',', GetFileDefiningClass(className));
                            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                ParserStrings.DuplicateCimClassDefinition, className, path, files);

                            e.SetErrorId("DuplicateCimClassDefinition");
                            errors?.Add(e);
                        }
                    }

                    if (s_hiddenResourceCache.Contains(className))
                    {
                        continue;
                    }

                    if (!CacheResourcesFromMultipleModuleVersions)
                    {
                        // Find & remove the previous version of the resource.
                        List<KeyValuePair<string, DscClassCacheEntry>> resourceList = FindResourceInCache(moduleInfo.Item1, className, friendlyName);
                        if (resourceList.Count > 0 && !string.IsNullOrEmpty(resourceList[0].Key))
                        {
                            ClassCache.Remove(resourceList[0].Key);

                            // keyword is already defined and it is a Inbox resource, remove it
                            if (DynamicKeyword.ContainsKeyword(friendlyName) && resourceList[0].Value.IsImportedImplicitly)
                            {
                                DynamicKeyword.RemoveKeyword(friendlyName);
                            }
                        }
                    }

                    ClassCache[moduleQualifiedResourceName] = new DscClassCacheEntry(DSCResourceRunAsCredential.Default, importInBoxResourcesImplicitly, c);
                    ByClassModuleCache[className] = moduleInfo;
                }

                var sb = new System.Text.StringBuilder();
                foreach (var c in classes)
                {
                    sb.Append(c.CimSystemProperties.ClassName);
                    sb.Append(',');
                }

                s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added the following classes to the cache: {1}", path, sb.ToString());
            }
            else
            {
                s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added no classes to the cache.");
            }

            ByFileClassCache[path] = classes;
            return classes;
        }

        /// <summary>
        /// Get text from SecureString.
        /// </summary>
        /// <param name="value">Value of SecureString.</param>
        /// <returns>Decoded string.</returns>
        public static string GetStringFromSecureString(SecureString value)
        {
            string passwordValueToAdd = string.Empty;

            if (value != null)
            {
                IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(value);
                passwordValueToAdd = Marshal.PtrToStringUni(ptr);
                Marshal.ZeroFreeCoTaskMemUnicode(ptr);
            }

            return passwordValueToAdd;
        }

        /// <summary>
        /// Clear out the existing collection of CIM classes and associated keywords.
        /// </summary>
        public static void ClearCache()
        {
            s_tracer.WriteLine("DSC class: clearing the cache and associated keywords.");
            ClassCache.Clear();
            ByClassModuleCache.Clear();
            ByFileClassCache.Clear();
            ScriptKeywordFileCache.Clear();
            CacheResourcesFromMultipleModuleVersions = false;
        }

        /// <summary>
        /// Returns module qualified resource name in "Module\Version\Class" format.
        /// </summary>
        /// <param name="moduleName"></param>
        /// <param name="moduleVersion"></param>
        /// <param name="className"></param>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        private static string GetModuleQualifiedResourceName(string moduleName, string moduleVersion, string className, string resourceName)
        {
            return string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{moduleVersion}\\{className}\\{resourceName}");
        }

        /// <summary>
        /// Finds resources in the that which matches the specified class and module name.
        /// </summary>
        /// <param name="moduleName">Module name.</param>
        /// <param name="className">Resource type name.</param>
        /// <param name="resourceName">Resource friendly name.</param>
        /// <returns>List of found resources in the form of Dictionary{moduleQualifiedName, cimClass}, otherwise empty list.</returns>
        private static List<KeyValuePair<string, DscClassCacheEntry>> FindResourceInCache(string moduleName, string className, string resourceName)
        {
            return (from cacheEntry in ClassCache
                    let splittedName = cacheEntry.Key.Split('\\')
                    let cachedClassName = splittedName[IndexClassName]
                    let cachedModuleName = splittedName[IndexModuleName]
                    let cachedResourceName = splittedName[IndexFriendlyName]
                    where (string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase)
                    || (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)
                        && string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase)))
                    select cacheEntry).ToList();
        }

        /// <summary>
        /// </summary>
        /// <returns></returns>
        private static List<DscClassCacheEntry> GetCachedClasses()
        {
            return ClassCache.Values.ToList();
        }

        /// <summary>
        /// Find cached cim classes defined under specified module.
        /// </summary>
        /// <param name="module"></param>
        /// <returns>List of cached cim classes.</returns>
        public static List<Microsoft.Management.Infrastructure.CimClass> GetCachedClassesForModule(PSModuleInfo module)
        {
            List<Microsoft.Management.Infrastructure.CimClass> cachedClasses = new();
            var moduleQualifiedName = string.Create(CultureInfo.InvariantCulture, $"{module.Name}\\{module.Version}");
            foreach (var dscClassCacheEntry in ClassCache)
            {
                if (dscClassCacheEntry.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase))
                {
                    cachedClasses.Add(dscClassCacheEntry.Value.CimClassInstance);
                }
            }

            return cachedClasses;
        }

        /// <summary>
        /// Get the file that defined this class.
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public static List<string> GetFileDefiningClass(string className)
        {
            List<string> files = new();
            foreach (var pair in ByFileClassCache)
            {
                var file = pair.Key;
                var classList = pair.Value;
                if (classList != null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null)
                {
                    files.Add(file);
                }
            }

            return files;
        }

        /// <summary>
        /// Get a list of files from which classes have been loaded.
        /// </summary>
        /// <returns></returns>
        public static string[] GetLoadedFiles()
        {
            return ByFileClassCache.Keys.ToArray();
        }

        /// <summary>
        /// Returns the classes that we loaded from the specified file name.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static List<CimClass> GetCachedClassByFileName(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(fileName));
            }

            List<CimClass> listCimClass;
            ByFileClassCache.TryGetValue(fileName, out listCimClass);
            return listCimClass;
        }

        /// <summary>
        /// Returns the classes associated with the specified module name.
        /// Per PowerShell the module name is the base name of the schema file.
        /// </summary>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public static List<CimClass> GetCachedClassByModuleName(string moduleName)
        {
            if (string.IsNullOrWhiteSpace(moduleName))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(moduleName));
            }

            var moduleFileName = moduleName + ".schema.mof";
            return (from filename in ByFileClassCache.Keys where string.Equals(Path.GetFileName(filename), moduleFileName, StringComparison.OrdinalIgnoreCase) select GetCachedClassByFileName(filename)).FirstOrDefault();
        }

        /// <summary>
        /// Routine used to load a set of CIM instances from a .mof file using the
        /// current set of cached classes for schema validation.
        /// </summary>
        /// <param name="path">The file to load the classes from.</param>
        /// <returns></returns>
        public static List<CimInstance> ImportInstances(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);

            return parser.ParseInstanceMof(path);
        }

        /// <summary>
        /// Routine used to load a set of CIM instances from a .mof file using the
        /// current set of cached classes for schema validation.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="schemaValidationOption"></param>
        /// <returns></returns>
        public static List<CimInstance> ImportInstances(string path, int schemaValidationOption)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            if (schemaValidationOption < (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Default ||
                schemaValidationOption > (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Ignore)
            {
                throw new IndexOutOfRangeException("schemaValidationOption");
            }

            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback, (Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption)schemaValidationOption);

            return parser.ParseInstanceMof(path);
        }

        /// <summary>
        /// A routine that validates a string containing MOF instances against the
        /// current set of cached classes.
        /// </summary>
        /// <param name="instanceText"></param>
        public static void ValidateInstanceText(string instanceText)
        {
            if (string.IsNullOrEmpty(instanceText))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(instanceText));
            }

            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);

            parser.ValidateInstanceText(instanceText);
        }

        private static string GetFriendlyName(CimClass cimClass)
        {
            try
            {
                var aliasQualifier = cimClass.CimClassQualifiers["FriendlyName"];
                if (aliasQualifier != null)
                {
                    return aliasQualifier.Value as string;
                }
            }
            catch (Microsoft.Management.Infrastructure.CimException)
            {
                // exception means no DSCAlias
            }

            return null;
        }

        /// <summary>
        /// Method to get the cached classes in the form of DynamicKeyword.
        /// </summary>
        public static Collection<DynamicKeyword> GetCachedKeywords()
        {
            Collection<DynamicKeyword> keywords = new();

            foreach (KeyValuePair<string, DscClassCacheEntry> cachedClass in ClassCache)
            {
                string[] splittedName = cachedClass.Key.Split('\\');
                string moduleName = splittedName[IndexModuleName];
                string moduleVersion = splittedName[IndexModuleVersion];

                var keyword = CreateKeywordFromCimClass(moduleName, Version.Parse(moduleVersion), cachedClass.Value.CimClassInstance, null, cachedClass.Value.DscResRunAsCred);
                if (keyword != null)
                {
                    keywords.Add(keyword);
                }
            }

            return keywords;
        }

        /// <summary>
        /// A method to generate a keyword from a CIM class object and register it to DynamicKeyword table.
        /// </summary>
        /// <param name="moduleName"></param>
        /// <param name="moduleVersion"></param>
        /// <param name="cimClass"></param>
        /// <param name="functionsToDefine">If true, don't define the keywords, just create the functions.</param>
        /// <param name="runAsBehavior">To Specify RunAsBehavior of the class.</param>
        private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary<string, ScriptBlock> functionsToDefine, DSCResourceRunAsCredential runAsBehavior)
        {
            var keyword = CreateKeywordFromCimClass(moduleName, moduleVersion, cimClass, functionsToDefine, runAsBehavior);
            if (keyword == null)
            {
                return;
            }

            // keyword is already defined and we don't allow redefine it
            if (!CacheResourcesFromMultipleModuleVersions && DynamicKeyword.ContainsKeyword(keyword.Keyword))
            {
                var oldKeyword = DynamicKeyword.GetKeyword(keyword.Keyword);
                if (oldKeyword.ImplementingModule == null ||
                    !oldKeyword.ImplementingModule.Equals(moduleName, StringComparison.OrdinalIgnoreCase) || oldKeyword.ImplementingModuleVersion != moduleVersion)
                {
                    var e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateKeywordDefinition, keyword.Keyword);
                    e.SetErrorId("DuplicateKeywordDefinition");
                    throw e;
                }
            }
            // Add the dynamic keyword to the table
            DynamicKeyword.AddKeyword(keyword);

            // And now define the driver functions in the current scope...
            if (functionsToDefine != null)
            {
                functionsToDefine[moduleName + "\\" + keyword.Keyword] = CimKeywordImplementationFunction;
            }
        }

        /// <summary>
        /// A method to generate a keyword from a CIM class object. This is used for DSC.
        /// </summary>
        /// <param name="moduleName"></param>
        /// <param name="moduleVersion"></param>
        /// <param name="cimClass"></param>
        /// <param name="functionsToDefine">If true, don't define the keywords, just create the functions.</param>
        /// <param name="runAsBehavior">To specify RunAs behavior of the class.</param>
        private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary<string, ScriptBlock> functionsToDefine, DSCResourceRunAsCredential runAsBehavior)
        {
            var resourceName = cimClass.CimSystemProperties.ClassName;
            string alias = GetFriendlyName(cimClass);
            var keywordString = string.IsNullOrEmpty(alias) ? resourceName : alias;

            //
            // Skip all of the base, meta, registration and other classes that are not intended to be used directly by a script author
            //
            if (keywordString.StartsWith("OMI_Base", StringComparison.OrdinalIgnoreCase) ||
                (keywordString.StartsWith("OMI_", StringComparison.OrdinalIgnoreCase) && keywordString.IndexOf("Registration", 4, StringComparison.OrdinalIgnoreCase) >= 0))
            {
                return null;
            }

            var keyword = new DynamicKeyword()
            {
                BodyMode = DynamicKeywordBodyMode.Hashtable,
                Keyword = keywordString,
                ResourceName = resourceName,
                ImplementingModule = moduleName,
                ImplementingModuleVersion = moduleVersion,
                SemanticCheck = CheckMandatoryPropertiesPresent
            };

            // If it's one of reserved dynamic keyword, mark it
            if (IsReservedDynamicKeyword(keywordString))
            {
                keyword.IsReservedKeyword = true;
            }

            // see if it's a resource type i.e. it inherits from OMI_BaseResource
            bool isResourceType = false;
            for (var classToCheck = cimClass; !string.IsNullOrEmpty(classToCheck.CimSuperClassName); classToCheck = classToCheck.CimSuperClass)
            {
                if (string.Equals("OMI_BaseResource", classToCheck.CimSuperClassName, StringComparison.OrdinalIgnoreCase) || string.Equals("OMI_MetaConfigurationResource", classToCheck.CimSuperClassName, StringComparison.OrdinalIgnoreCase))
                {
                    isResourceType = true;
                    break;
                }
            }

            // If it's a resource type, then a resource name is required.
            keyword.NameMode = isResourceType ? DynamicKeywordNameMode.NameRequired : DynamicKeywordNameMode.NoName;

            //
            // Add the settable properties to the keyword object
            //
            foreach (var prop in cimClass.CimClassProperties)
            {
                // If the property is marked as readonly, skip it...
                if ((prop.Flags & Microsoft.Management.Infrastructure.CimFlags.ReadOnly) == Microsoft.Management.Infrastructure.CimFlags.ReadOnly)
                {
                    continue;
                }

                try
                {
                    // If the property has the Read qualifier, also skip it.
                    if (prop.Qualifiers["Read"] != null)
                    {
                        continue;
                    }
                }
                catch (Microsoft.Management.Infrastructure.CimException)
                {
                    // Cim exception means Read wasn't found so continue...
                }

                // If it's one of our magic properties, skip it
                if (IsMagicProperty(prop.Name))
                {
                    continue;
                }

                if (runAsBehavior == DSCResourceRunAsCredential.NotSupported)
                {
                    if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase))
                    {
                        // skip adding PsDscRunAsCredential to the dynamic word for the dsc resource.
                        continue;
                    }
                }
                // If it's one of our reserved properties, save it for error reporting
                if (IsReservedProperty(prop.Name))
                {
                    keyword.HasReservedProperties = true;
                    continue;
                }

                // Otherwise, add it to the Keyword List.
                var keyProp = new System.Management.Automation.Language.DynamicKeywordProperty();
                keyProp.Name = prop.Name;

                // Set the mandatory flag if appropriate
                if ((prop.Flags & Microsoft.Management.Infrastructure.CimFlags.Key) == Microsoft.Management.Infrastructure.CimFlags.Key)
                {
                    keyProp.Mandatory = true;
                    keyProp.IsKey = true;
                }

                // Copy the type name string. If it's an embedded instance, need to grab it from the ReferenceClassName
                bool referenceClassNameIsNullOrEmpty = string.IsNullOrEmpty(prop.ReferenceClassName);
                if (prop.CimType == CimType.Instance && !referenceClassNameIsNullOrEmpty)
                {
                    keyProp.TypeConstraint = prop.ReferenceClassName;
                }
                else if (prop.CimType == CimType.InstanceArray && !referenceClassNameIsNullOrEmpty)
                {
                    keyProp.TypeConstraint = prop.ReferenceClassName + "[]";
                }
                else
                {
                    keyProp.TypeConstraint = prop.CimType.ToString();
                }

                string[] valueMap = null;
                foreach (var qualifier in prop.Qualifiers)
                {
                    // Check to see if there is a Values attribute and save the list of allowed values if so.
                    if (string.Equals(qualifier.Name, "Values", StringComparison.OrdinalIgnoreCase) && qualifier.CimType == Microsoft.Management.Infrastructure.CimType.StringArray)
                    {
                        keyProp.Values.AddRange((string[])qualifier.Value);
                    }

                    // Check to see if there is a ValueMap attribute and save the list of allowed values if so.
                    if (string.Equals(qualifier.Name, "ValueMap", StringComparison.OrdinalIgnoreCase) && qualifier.CimType == Microsoft.Management.Infrastructure.CimType.StringArray)
                    {
                        valueMap = (string[])qualifier.Value;
                    }

                    // Check to see if this property has the Required qualifier associated with it.
                    if (string.Equals(qualifier.Name, "Required", StringComparison.OrdinalIgnoreCase) &&
                        qualifier.CimType == Microsoft.Management.Infrastructure.CimType.Boolean &&
                            (bool)qualifier.Value)
                    {
                        keyProp.Mandatory = true;
                    }

                    // set the property to mandatory is specified for the resource.
                    if (runAsBehavior == DSCResourceRunAsCredential.Mandatory)
                    {
                        if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase))
                        {
                            keyProp.Mandatory = true;
                        }
                    }
                }

                if (valueMap != null && keyProp.Values.Count > 0)
                {
                    if (valueMap.Length != keyProp.Values.Count)
                    {
                        s_tracer.WriteLine(
                            "DSC CreateDynamicKeywordFromClass: the count of values for qualifier 'Values' and 'ValueMap' doesn't match. count of 'Values': {0}, count of 'ValueMap': {1}. Skip the keyword '{2}'.",
                            keyProp.Values.Count, valueMap.Length, keyword.Keyword);
                        return null;
                    }

                    for (int index = 0; index < valueMap.Length; index++)
                    {
                        string key = keyProp.Values[index];
                        string value = valueMap[index];

                        if (keyProp.ValueMap.ContainsKey(key))
                        {
                            s_tracer.WriteLine(
                                "DSC CreateDynamicKeywordFromClass: same string value '{0}' appears more than once in qualifier 'Values'. Skip the keyword '{1}'.",
                                key, keyword.Keyword);
                            return null;
                        }

                        keyProp.ValueMap.Add(key, value);
                    }
                }

                keyword.Properties.Add(prop.Name, keyProp);
            }

            // update specific keyword with range constraints
            UpdateKnownRestriction(keyword);

            return keyword;

            static bool IsMagicProperty(string propertyName) =>
                string.Equals(propertyName, "ResourceId", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(propertyName, "SourceInfo", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(propertyName, "ModuleName", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(propertyName, "ModuleVersion", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(propertyName, "ConfigurationName", StringComparison.OrdinalIgnoreCase);

            static bool IsReservedDynamicKeyword(string keyword) =>
                string.Equals(keyword, "Synchronization", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(keyword, "Certificate", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(keyword, "IIS", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(keyword, "SQL", StringComparison.OrdinalIgnoreCase);

            static bool IsReservedProperty(string name) =>
                string.Equals(name, "Require", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(name, "Trigger", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(name, "Notify", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(name, "Before", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(name, "After", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(name, "Subscribe", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Update range restriction for meta configuration keywords
        /// the restrictions are for
        /// ConfigurationModeFrequency: 15-44640
        /// RefreshFrequency: 30-44640.
        /// </summary>
        /// <param name="keyword"></param>
        private static void UpdateKnownRestriction(DynamicKeyword keyword)
        {
            if (
                string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2",
                    StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfiguration",
                    StringComparison.OrdinalIgnoreCase))
            {
                if (keyword.Properties["RefreshFrequencyMins"] != null)
                {
                    keyword.Properties["RefreshFrequencyMins"].Range = new Tuple<int, int>(30, 44640);
                }

                if (keyword.Properties["ConfigurationModeFrequencyMins"] != null)
                {
                    keyword.Properties["ConfigurationModeFrequencyMins"].Range = new Tuple<int, int>(15, 44640);
                }

                if (keyword.Properties["DebugMode"] != null)
                {
                    keyword.Properties["DebugMode"].Values.Remove("ResourceScriptBreakAll");
                    keyword.Properties["DebugMode"].ValueMap.Remove("ResourceScriptBreakAll");
                }
            }
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        public static void LoadDefaultCimKeywords()
        {
            LoadDefaultCimKeywords(null, null, null, false);
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        /// <param name="modulePathList">List of module path from where DSC PS modules will be loaded.</param>
        public static void LoadDefaultCimKeywords(List<string> modulePathList)
        {
            LoadDefaultCimKeywords(null, null, modulePathList, false);
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        /// <param name="errors">Collection of any errors encountered while loading keywords.</param>
        public static void LoadDefaultCimKeywords(Collection<Exception> errors)
        {
            LoadDefaultCimKeywords(null, errors, null, false);
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        /// <param name="functionsToDefine">A dictionary to add the defined functions to, may be null.</param>
        public static void LoadDefaultCimKeywords(Dictionary<string, ScriptBlock> functionsToDefine)
        {
            LoadDefaultCimKeywords(functionsToDefine, null, null, false);
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        /// <param name="errors">Collection of any errors encountered while loading keywords.</param>
        /// <param name="cacheResourcesFromMultipleModuleVersions">Allow caching the resources from multiple versions of modules.</param>
        public static void LoadDefaultCimKeywords(Collection<Exception> errors, bool cacheResourcesFromMultipleModuleVersions)
        {
            LoadDefaultCimKeywords(null, errors, null, cacheResourcesFromMultipleModuleVersions);
        }

        /// <summary>
        /// Load the default system CIM classes and create the corresponding keywords.
        /// </summary>
        /// <param name="functionsToDefine">A dictionary to add the defined functions to, may be null.</param>
        /// <param name="errors">Collection of any errors encountered while loading keywords.</param>
        /// <param name="modulePathList">List of module path from where DSC PS modules will be loaded.</param>
        /// <param name="cacheResourcesFromMultipleModuleVersions">Allow caching the resources from multiple versions of modules.</param>
        private static void LoadDefaultCimKeywords(Dictionary<string, ScriptBlock> functionsToDefine, Collection<Exception> errors,
                                                   List<string> modulePathList, bool cacheResourcesFromMultipleModuleVersions)
        {
            DynamicKeyword.Reset();
            Initialize(errors, modulePathList);

            // Initialize->ClearCache resets CacheResourcesFromMultipleModuleVersions to false,
            // workaround is to set it after Initialize method call.
            // Initialize method imports all the Inbox resources and internal classes which belongs to only one version
            // of the module, so it is ok if this property is not set during cache initialization.
            CacheResourcesFromMultipleModuleVersions = cacheResourcesFromMultipleModuleVersions;

            foreach (var cimClass in GetCachedClasses())
            {
                var className = cimClass.CimClassInstance.CimSystemProperties.ClassName;
                var moduleInfo = ByClassModuleCache[className];
                CreateAndRegisterKeywordFromCimClass(moduleInfo.Item1, moduleInfo.Item2, cimClass.CimClassInstance, functionsToDefine, cimClass.DscResRunAsCred);
            }

            // And add the Node keyword definitions
            if (!DynamicKeyword.ContainsKeyword("Node"))
            {
                // Implement dispatch to the Node keyword.
                var nodeKeyword = new DynamicKeyword()
                {
                    BodyMode = DynamicKeywordBodyMode.ScriptBlock,
                    ImplementingModule = s_defaultModuleInfoForResource.Item1,
                    ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2,
                    NameMode = DynamicKeywordNameMode.NameRequired,
                    Keyword = "Node",
                };
                DynamicKeyword.AddKeyword(nodeKeyword);
            }

            // And add the Import-DscResource keyword definitions
            if (!DynamicKeyword.ContainsKeyword("Import-DscResource"))
            {
                // Implement dispatch to the Node keyword.
                var nodeKeyword = new DynamicKeyword()
                {
                    BodyMode = DynamicKeywordBodyMode.Command,
                    ImplementingModule = s_defaultModuleInfoForResource.Item1,
                    ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2,
                    NameMode = DynamicKeywordNameMode.NoName,
                    Keyword = "Import-DscResource",
                    MetaStatement = true,
                    PostParse = ImportResourcePostParse,
                    SemanticCheck = ImportResourceCheckSemantics
                };
                DynamicKeyword.AddKeyword(nodeKeyword);
            }
        }

        // This function is called after parsing the Import-DscResource keyword and it's arguments, but before parsing
        // anything else.
        //
        //
        private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst kwAst)
        {
            var elements = Ast.CopyElements(kwAst.CommandElements);

            Diagnostics.Assert(elements[0] is StringConstantExpressionAst &&
                               ((StringConstantExpressionAst)elements[0]).Value.Equals("Import-DscResource", StringComparison.OrdinalIgnoreCase),
                               "Incorrect ast for expected keyword");
            var commandAst = new CommandAst(kwAst.Extent, elements, TokenKind.Unknown, null);

            const string nameParam = "Name";
            const string moduleNameParam = "ModuleName";
            const string moduleVersionParam = "ModuleVersion";

            StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false);

            var errorList = new List<ParseError>();
            foreach (var bindingException in bindingResult.BindingExceptions.Values)
            {
                errorList.Add(new ParseError(bindingException.CommandElement.Extent,
                                             "ParameterBindingException",
                                             bindingException.BindingException.Message));
            }

            ParameterBindingResult moduleNameBindingResult = null;
            ParameterBindingResult resourceNameBindingResult = null;
            ParameterBindingResult moduleVersionBindingResult = null;

            foreach (var binding in bindingResult.BoundParameters)
            {
                // Error case when positional parameter values are specified
                var boundParameterName = binding.Key;
                var parameterBindingResult = binding.Value;
                if (boundParameterName.All(char.IsDigit))
                {
                    errorList.Add(new ParseError(parameterBindingResult.Value.Extent,
                                                 "ImportDscResourcePositionalParamsNotSupported",
                                                 string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourcePositionalParamsNotSupported)));
                    continue;
                }

                if (nameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
                {
                    resourceNameBindingResult = parameterBindingResult;
                }
                else if (moduleNameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
                {
                    moduleNameBindingResult = parameterBindingResult;
                }
                else if (moduleVersionParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
                {
                    moduleVersionBindingResult = parameterBindingResult;
                }
                else
                {
                    errorList.Add(new ParseError(parameterBindingResult.Value.Extent,
                                                 "ImportDscResourceNeedParams",
                                                 string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
                }
            }

            if (errorList.Count == 0 && moduleNameBindingResult == null && resourceNameBindingResult == null)
            {
                errorList.Add(new ParseError(kwAst.Extent,
                                             "ImportDscResourceNeedParams",
                                             string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
            }

            // Check here if Version is specified but modulename is not specified
            if (moduleVersionBindingResult != null && moduleNameBindingResult == null)
            {
                // only add this error again to the error list if resources is not null
                // if resources and modules are both null we have already added this error in collection
                // we do not want to do this twice. since we are giving same error ImportDscResourceNeedParams in both cases
                // once we have different error messages for 2 scenarios we can remove this check
                if (resourceNameBindingResult != null)
                {
                    errorList.Add(new ParseError(kwAst.Extent,
                                                 "ImportDscResourceNeedModuleNameWithModuleVersion",
                                                 string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
                }
            }

            string[] resourceNames = null;
            if (resourceNameBindingResult != null)
            {
                object resourceName = null;
                if (!IsConstantValueVisitor.IsConstant(resourceNameBindingResult.Value, out resourceName, true, true) ||
                    !LanguagePrimitives.TryConvertTo(resourceName, out resourceNames))
                {
                    errorList.Add(new ParseError(resourceNameBindingResult.Value.Extent,
                                                 "RequiresInvalidStringArgument",
                                                 string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, nameParam)));
                }
            }

            System.Version moduleVersion = null;
            if (moduleVersionBindingResult != null)
            {
                object moduleVer = null;
                if (!IsConstantValueVisitor.IsConstant(moduleVersionBindingResult.Value, out moduleVer, true, true))
                {
                    errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent,
                                                 "RequiresArgumentMustBeConstant",
                                                 ParserStrings.RequiresArgumentMustBeConstant));
                }

                if (moduleVer is double)
                {
                    // this happens in case -ModuleVersion 1.0, then use extent text for that.
                    // The better way to do it would be define static binding API against CommandInfo, that holds information about parameter types.
                    // This way, we can avoid this ugly special-casing and say that -ModuleVersion has type [System.Version].
                    moduleVer = moduleVersionBindingResult.Value.Extent.Text;
                }

                if (!LanguagePrimitives.TryConvertTo(moduleVer, out moduleVersion))
                {
                    errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent,
                                                 "RequiresVersionInvalid",
                                                 ParserStrings.RequiresVersionInvalid));
                }
            }

            ModuleSpecification[] moduleSpecifications = null;
            if (moduleNameBindingResult != null)
            {
                object moduleName = null;
                if (!IsConstantValueVisitor.IsConstant(moduleNameBindingResult.Value, out moduleName, true, true))
                {
                    errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
                                                 "RequiresArgumentMustBeConstant",
                                                 ParserStrings.RequiresArgumentMustBeConstant));
                }

                if (LanguagePrimitives.TryConvertTo(moduleName, out moduleSpecifications))
                {
                    // if resourceNames are specified then we can not specify multiple modules name
                    if (moduleSpecifications != null && moduleSpecifications.Length > 1 && resourceNames != null)
                    {
                        errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
                                                     "ImportDscResourceMultipleModulesNotSupportedWithName",
                                                     string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceMultipleModulesNotSupportedWithName)));
                    }

                    // if moduleversion is specified then we can not specify multiple modules name
                    if (moduleSpecifications != null && moduleSpecifications.Length > 1 && moduleVersion != null)
                    {
                        errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
                                                     "ImportDscResourceMultipleModulesNotSupportedWithVersion",
                                                     string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
                    }

                    // if moduleversion is specified then we can not specify another version in modulespecification object of ModuleName
                    if (moduleSpecifications != null && (moduleSpecifications[0].Version != null || moduleSpecifications[0].MaximumVersion != null) && moduleVersion != null)
                    {
                        errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
                                                     "ImportDscResourceMultipleModuleVersionsNotSupported",
                                                     string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
                    }

                    // If moduleVersion is specified we have only one module Name in valid scenario
                    // So update it's version property in module specification object that will be used to load modules
                    if (moduleSpecifications != null && moduleSpecifications[0].Version == null && moduleSpecifications[0].MaximumVersion == null && moduleVersion != null)
                    {
                        moduleSpecifications[0].Version = moduleVersion;
                    }
                }
                else
                {
                    errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
                                                 "RequiresInvalidStringArgument",
                                                 string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, moduleNameParam)));
                }
            }

            if (errorList.Count == 0)
            {
                // No errors, try to load the resources
                LoadResourcesFromModule(kwAst.Extent, moduleSpecifications, resourceNames, errorList);
            }

            return errorList.ToArray();
        }

        // This function performs semantic checks for Import-DscResource
        private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatementAst kwAst)
        {
            List<ParseError> errorList = null;

            var keywordAst = Ast.GetAncestorAst<DynamicKeywordStatementAst>(kwAst.Parent);
            while (keywordAst != null)
            {
                if (keywordAst.Keyword.Keyword.Equals("Node"))
                {
                    errorList ??= new List<ParseError>();

                    errorList.Add(new ParseError(kwAst.Extent,
                                         "ImportDscResourceInsideNode",
                                         string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceInsideNode)));
                    break;
                }

                keywordAst = Ast.GetAncestorAst<DynamicKeywordStatementAst>(keywordAst.Parent);
            }

            if (errorList != null)
            {
                return errorList.ToArray();
            }
            else
            {
                return null;
            }
        }

        // This function performs semantic checks for all DSC Resources keywords.
        private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatementAst kwAst)
        {
            HashSet<string> mandatoryPropertiesNames = new(StringComparer.OrdinalIgnoreCase);
            foreach (var pair in kwAst.Keyword.Properties)
            {
                if (pair.Value.Mandatory)
                {
                    mandatoryPropertiesNames.Add(pair.Key);
                }
            }

            // by design mandatoryPropertiesNames are not empty at this point:
            // every resource must have at least one Key property.

            HashtableAst hashtableAst = null;
            foreach (var ast in kwAst.CommandElements)
            {
                hashtableAst = ast as HashtableAst;
                if (hashtableAst != null)
                {
                    break;
                }
            }

            if (hashtableAst == null)
            {
                // nothing to validate
                return null;
            }

            foreach (var pair in hashtableAst.KeyValuePairs)
            {
                object evalResultObject;
                if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false))
                {
                    if (evalResultObject is string presentName)
                    {
                        if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0)
                        {
                            // optimization, once all mandatory properties are specified, we can safely exit.
                            return null;
                        }
                    }
                }
            }

            if (mandatoryPropertiesNames.Count > 0)
            {
                ParseError[] errors = new ParseError[mandatoryPropertiesNames.Count];
                var extent = kwAst.CommandElements[0].Extent;
                int i = 0;
                foreach (string name in mandatoryPropertiesNames)
                {
                    errors[i] = new ParseError(extent, "MissingValueForMandatoryProperty",
                        string.Format(CultureInfo.CurrentCulture, ParserStrings.MissingValueForMandatoryProperty,
                                    kwAst.Keyword.Keyword, kwAst.Keyword.Properties.First(
                                        p => StringComparer.OrdinalIgnoreCase.Equals(p.Value.Name, name)).Value.TypeConstraint, name));
                    i++;
                }

                return errors;
            }

            return null;
        }

        /// <summary>
        /// Load DSC resources from specified module.
        /// </summary>
        /// <param name="scriptExtent">Script statement loading the module, can be null.</param>
        /// <param name="moduleSpecifications">Module information, can be null.</param>
        /// <param name="resourceNames">Name of the resource to be loaded from module.</param>
        /// <param name="errorList">List of errors reported by the method.</param>
        public static void LoadResourcesFromModule(IScriptExtent scriptExtent,
                                                           ModuleSpecification[] moduleSpecifications,
                                                           string[] resourceNames,
                                                           List<ParseError> errorList)
        {
            // get all required modules
            var modules = new Collection<PSModuleInfo>();
            if (moduleSpecifications != null)
            {
                foreach (var moduleToImport in moduleSpecifications)
                {
                    bool foundModule = false;
                    var moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(moduleToImport);

                    if (moduleInfos.Count >= 1 && (moduleToImport.Version != null || moduleToImport.Guid != null))
                    {
                        foreach (var psModuleInfo in moduleInfos)
                        {
                            if ((moduleToImport.Guid.HasValue && moduleToImport.Guid.Equals(psModuleInfo.Guid)) ||
                                (moduleToImport.Version != null &&
                                 moduleToImport.Version.Equals(psModuleInfo.Version)))
                            {
                                modules.Add(psModuleInfo);
                                foundModule = true;
                                break;
                            }
                        }
                    }
                    else if (moduleInfos.Count == 1)
                    {
                        modules.Add(moduleInfos[0]);
                        foundModule = true;
                    }

                    if (!foundModule)
                    {
                        if (moduleInfos.Count > 1)
                        {
                            errorList.Add(new ParseError(scriptExtent,
                                                         "MultipleModuleEntriesFoundDuringParse",
                                                         string.Format(CultureInfo.CurrentCulture,
                                                                       ParserStrings.MultipleModuleEntriesFoundDuringParse,
                                                                       moduleToImport.Name)));
                        }
                        else
                        {
                            string moduleString = moduleToImport.Version == null
                                ? moduleToImport.Name
                                : string.Create(CultureInfo.CurrentCulture, $"<{moduleToImport.Name}, {moduleToImport.Version}>");

                            errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse",
                                string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString)));
                        }

                        return;
                    }
                }
            }
            else if (resourceNames != null)
            {
                // Lookup the required resources under available PowerShell modules when modulename is not specified
                using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
                {
                    powerShell.AddCommand("Get-Module");
                    powerShell.AddParameter("ListAvailable");
                    modules = powerShell.Invoke<PSModuleInfo>();
                }
            }

            // When ModuleName only specified, we need to import all resources from that module
            var resourcesToImport = new List<string>();
            if (resourceNames == null || resourceNames.Length == 0)
            {
                resourcesToImport.Add("*");
            }
            else
            {
                resourcesToImport.AddRange(resourceNames);
            }

            foreach (var moduleInfo in modules)
            {
                var dscResourcesPath = Path.Combine(moduleInfo.ModuleBase, "DscResources");

                var resourcesFound = new List<string>();
                LoadPowerShellClassResourcesFromModule(moduleInfo, moduleInfo, resourcesToImport, resourcesFound, errorList, null, true, scriptExtent);

                if (Directory.Exists(dscResourcesPath))
                {
                    foreach (var resourceToImport in resourcesToImport)
                    {
                        bool foundResources = false;
                        foreach (var resourceDir in Directory.EnumerateDirectories(dscResourcesPath, resourceToImport))
                        {
                            var resourceName = Path.GetFileName(resourceDir);

                            bool foundCimSchema = false;
                            bool foundScriptSchema = false;
                            string schemaMofFilePath = string.Empty;

                            try
                            {
                                foundCimSchema = ImportCimKeywordsFromModule(moduleInfo, resourceName, out schemaMofFilePath);
                            }
                            catch (FileNotFoundException)
                            {
                                errorList.Add(new ParseError(scriptExtent,
                                                             "SchemaFileNotFound",
                                                             string.Format(CultureInfo.CurrentCulture, ParserStrings.SchemaFileNotFound, schemaMofFilePath)));
                            }
                            catch (PSInvalidOperationException e)
                            {
                                errorList.Add(new ParseError(scriptExtent,
                                                            e.ErrorRecord.FullyQualifiedErrorId,
                                                            e.Message));
                            }
                            catch (Exception e)
                            {
                                errorList.Add(new ParseError(scriptExtent,
                                                             "ExceptionParsingMOFFile",
                                                             string.Format(CultureInfo.CurrentCulture, ParserStrings.ExceptionParsingMOFFile, schemaMofFilePath, e.Message)));
                            }

                            var schemaScriptFilePath = string.Empty;

                            try
                            {
                                foundScriptSchema = ImportScriptKeywordsFromModule(moduleInfo, resourceName, out schemaScriptFilePath);
                            }
                            catch (FileNotFoundException)
                            {
                                errorList.Add(new ParseError(scriptExtent,
                                                             "SchemaFileNotFound",
                                                             string.Format(CultureInfo.CurrentCulture, ParserStrings.SchemaFileNotFound, schemaScriptFilePath)));
                            }
                            catch (Exception e)
                            {
                                // This shouldn't happen so just report the error as is
                                errorList.Add(new ParseError(scriptExtent,
                                                             "UnexpectedParseError",
                                                             string.Format(CultureInfo.CurrentCulture, e.ToString())));
                            }

                            if (foundCimSchema || foundScriptSchema)
                            {
                                foundResources = true;
                            }
                        }

                        //
                        // resourceToImport may be the friendly name of the DSC resource
                        //
                        if (!foundResources)
                        {
                            try
                            {
                                foundResources = ImportCimKeywordsFromModule(moduleInfo, resourceToImport, out _);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        // resource name without wildcard (*) should be imported only once
                        if (!resourceToImport.Contains('*') && foundResources)
                        {
                            resourcesFound.Add(resourceToImport);
                        }
                    }
                }

                foreach (var resource in resourcesFound)
                {
                    resourcesToImport.Remove(resource);
                }

                if (resourcesToImport.Count == 0)
                {
                    break;
                }
            }

            if (resourcesToImport.Count > 0)
            {
                foreach (var resourceNameToImport in resourcesToImport)
                {
                    if (!resourceNameToImport.Contains('*'))
                    {
                        errorList.Add(new ParseError(scriptExtent,
                                                     "DscResourcesNotFoundDuringParsing",
                                                     string.Format(CultureInfo.CurrentCulture, ParserStrings.DscResourcesNotFoundDuringParsing, resourceNameToImport)));
                    }
                }
            }
        }

        private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryModuleInfo, PSModuleInfo moduleInfo, ICollection<string> resourcesToImport, ICollection<string> resourcesFound,
            List<ParseError> errorList,
            Dictionary<string, ScriptBlock> functionsToDefine = null,
            bool recurse = true,
            IScriptExtent extent = null)
        {
            if (primaryModuleInfo._declaredDscResourceExports == null || primaryModuleInfo._declaredDscResourceExports.Count == 0)
            {
                return;
            }

            if (moduleInfo.ModuleType == ModuleType.Binary)
            {
#if CORECLR
                throw PSTraceSource.NewArgumentException("isConfiguration", ParserStrings.ConfigurationNotSupportedInPowerShellCore);
#else
                ResolveEventHandler reh = (sender, args) => CurrentDomain_ReflectionOnlyAssemblyResolve(sender, args, moduleInfo);

                try
                {
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += reh;
                    var assembly = moduleInfo.ImplementingAssembly;
                    if (assembly == null && moduleInfo.Path != null)
                    {
                        try
                        {
                            var path = moduleInfo.Path;

                            if (moduleInfo.RootModule != null && !Path.GetExtension(moduleInfo.Path).Equals(".dll", StringComparison.OrdinalIgnoreCase))
                            {
                                path = moduleInfo.ModuleBase + "\\" + moduleInfo.RootModule;
                            }

                            assembly = Assembly.ReflectionOnlyLoadFrom(path);
                        }
                        catch { }
                    }

                    // Ignore the module if we can't find the assembly.
                    if (assembly != null)
                    {
                        ImportKeywordsFromAssembly(moduleInfo, resourcesToImport, resourcesFound, functionsToDefine, assembly);
                    }
                }
                finally
                {
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= reh;
                }
#endif
            }
            else
            {
                string scriptPath = null;
                // handle RootModule and nestedModule together
                if (moduleInfo.RootModule != null)
                {
                    scriptPath = Path.Combine(moduleInfo.ModuleBase, moduleInfo.RootModule);
                }
                else if (moduleInfo.Path != null)
                {
                    scriptPath = moduleInfo.Path;
                }

                ImportKeywordsFromScriptFile(scriptPath, primaryModuleInfo, resourcesToImport, resourcesFound, functionsToDefine, errorList, extent);
            }

            if (moduleInfo.NestedModules != null && recurse)
            {
                foreach (var nestedModule in moduleInfo.NestedModules)
                {
                    LoadPowerShellClassResourcesFromModule(primaryModuleInfo, nestedModule, resourcesToImport, resourcesFound, errorList, functionsToDefine, recurse: false, extent: extent);
                }
            }
        }

#if !CORECLR
        private static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args, PSModuleInfo moduleInfo)
        {
            AssemblyName name = new AssemblyName(args.Name);

            if (moduleInfo != null && !string.IsNullOrEmpty(moduleInfo.Path))
            {
                string asmToCheck = Path.GetDirectoryName(moduleInfo.Path) + "\\" + name.Name + ".dll";
                if (File.Exists(asmToCheck))
                {
                    return Assembly.ReflectionOnlyLoadFrom(asmToCheck);
                }

                asmToCheck = Path.GetDirectoryName(moduleInfo.Path) + "\\" + name.Name + ".exe";
                if (File.Exists(asmToCheck))
                {
                    return Assembly.ReflectionOnlyLoadFrom(asmToCheck);
                }
            }

            return Assembly.ReflectionOnlyLoad(args.Name);
        }
#endif

        /// <summary>
        /// </summary>
        /// <param name="moduleInfo"></param>
        /// <param name="resourcesToImport"></param>
        /// <param name="functionsToDefine"></param>
        /// <returns>The list of resources imported from this module.</returns>
        public static List<string> ImportClassResourcesFromModule(PSModuleInfo moduleInfo, ICollection<string> resourcesToImport, Dictionary<string, ScriptBlock> functionsToDefine)
        {
            var resourcesImported = new List<string>();
            LoadPowerShellClassResourcesFromModule(moduleInfo, moduleInfo, resourcesToImport, resourcesImported, null, functionsToDefine);
            return resourcesImported;
        }

        internal static string GenerateMofForAst(TypeDefinitionAst typeAst)
        {
            var embeddedInstanceTypes = new List<object>();
            var sb = new StringBuilder();

            GenerateMofForAst(typeAst, sb, embeddedInstanceTypes);
            var visitedInstances = new List<object>();
            visitedInstances.Add(typeAst);
            ProcessEmbeddedInstanceTypes(embeddedInstanceTypes, visitedInstances, sb);

            return sb.ToString();
        }

        internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List<object> embeddedInstanceTypes, ref string[] enumNames)
        {
            TypeName propTypeName;
            if (typeName is ArrayTypeName arrayTypeName)
            {
                isArrayType = true;
                propTypeName = arrayTypeName.ElementType as TypeName;
            }
            else
            {
                isArrayType = false;
                propTypeName = typeName as TypeName;
            }

            if (propTypeName == null || propTypeName._typeDefinitionAst == null)
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.InvariantCulture,
                    ParserStrings.UnsupportedPropertyTypeOfDSCResourceClass,
                    memberName,
                    typeName.FullName,
                    typeName));
            }

            if (propTypeName._typeDefinitionAst.IsEnum)
            {
                enumNames = propTypeName._typeDefinitionAst.Members.Select(static m => m.Name).ToArray();
                isArrayType = false;
                embeddedInstanceType = null;
                return "string";
            }

            if (!embeddedInstanceTypes.Contains(propTypeName._typeDefinitionAst))
            {
                embeddedInstanceTypes.Add(propTypeName._typeDefinitionAst);
            }

            // The type is obviously not a string, but in the mof, we represent
            // it as string (really, embeddedinstance of the class type)
            embeddedInstanceType = propTypeName.Name.Replace('.', '_');
            return "string";
        }

        private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List<object> embeddedInstanceTypes)
        {
            var className = typeAst.Name;
            sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}");

            if (typeAst.Attributes.Any(static a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)))
            {
                sb.Append(" : OMI_BaseResource");
            }

            sb.Append("\n{\n");

            ProcessMembers(sb, embeddedInstanceTypes, typeAst, className);

            Queue<object> bases = new();
            foreach (var b in typeAst.BaseTypes)
            {
                bases.Enqueue(b);
            }

            while (bases.Count > 0)
            {
                var b = bases.Dequeue();

                if (b is TypeConstraintAst tc)
                {
                    b = tc.TypeName.GetReflectionType();
                    if (b == null)
                    {
                        if (tc.TypeName is TypeName td && td._typeDefinitionAst != null)
                        {
                            ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className);
                            foreach (var b1 in td._typeDefinitionAst.BaseTypes)
                            {
                                bases.Enqueue(b1);
                            }
                        }

                        continue;
                    }
                }

                var type = b as Type;
                if (type != null)
                {
                    ProcessMembers(type, sb, embeddedInstanceTypes, className);
                    var t = type.BaseType;
                    if (t != null)
                    {
                        bases.Enqueue(t);
                    }
                }
            }

            sb.Append("};");
        }

        /// <summary>
        /// Gets the line no for DSC Class Resource Get/Set/Test methods.
        /// </summary>
        /// <param name="typeDefinitionAst"></param>
        /// <param name="methodsLinePosition"></param>
        private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitionAst, out Dictionary<string, int> methodsLinePosition)
        {
            const string getMethodName = "Get";
            const string setMethodName = "Set";
            const string testMethodName = "Test";

            methodsLinePosition = new Dictionary<string, int>();
            foreach (var member in typeDefinitionAst.Members)
            {
                if (member is FunctionMemberAst functionMemberAst)
                {
                    if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase))
                    {
                        methodsLinePosition[getMethodName] = functionMemberAst.NameExtent.StartLineNumber;
                    }
                    else if (functionMemberAst.Name.Equals(setMethodName, StringComparison.OrdinalIgnoreCase))
                    {
                        methodsLinePosition[setMethodName] = functionMemberAst.NameExtent.StartLineNumber;
                    }
                    else if (functionMemberAst.Name.Equals(testMethodName, StringComparison.OrdinalIgnoreCase))
                    {
                        methodsLinePosition[testMethodName] = functionMemberAst.NameExtent.StartLineNumber;
                    }
                }
            }

            // All 3 methods (Get/Set/Test) position should be found.
            return (methodsLinePosition.Count == 3);
        }

        /// <summary>
        /// Gets the line no for DSC Class Resource Get/Set/Test methods.
        /// </summary>
        /// <param name="moduleInfo"></param>
        /// <param name="resourceName"></param>
        /// <param name="resourceMethodsLinePosition"></param>
        /// <param name="resourceFilePath"></param>
        public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, string resourceName, out Dictionary<string, int> resourceMethodsLinePosition, out string resourceFilePath)
        {
            resourceMethodsLinePosition = null;
            resourceFilePath = string.Empty;
            if (moduleInfo == null || string.IsNullOrEmpty(resourceName))
            {
                return false;
            }

            IEnumerable<Ast> resourceDefinitions;
            List<string> moduleFiles = new();
            if (moduleInfo.RootModule != null)
            {
                moduleFiles.Add(moduleInfo.Path);
            }

            if (moduleInfo.NestedModules != null)
            {
                foreach (var nestedModule in moduleInfo.NestedModules.Where(static m => !string.IsNullOrEmpty(m.Path)))
                {
                    moduleFiles.Add(nestedModule.Path);
                }
            }

            foreach (string moduleFile in moduleFiles)
            {
                if (GetResourceDefinitionsFromModule(moduleFile, out resourceDefinitions, null, null))
                {
                    foreach (var r in resourceDefinitions)
                    {
                        var resourceDefnAst = (TypeDefinitionAst)r;
                        if (!resourceName.Equals(resourceDefnAst.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        if (GetResourceMethodsLineNumber(resourceDefnAst, out resourceMethodsLinePosition))
                        {
                            resourceFilePath = moduleFile;
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        private static void ProcessMembers(StringBuilder sb, List<object> embeddedInstanceTypes, TypeDefinitionAst typeDefinitionAst, string className)
        {
            foreach (var member in typeDefinitionAst.Members)
            {
                if (member is not PropertyMemberAst property || property.IsStatic ||
                    property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute)))
                {
                    continue;
                }

                var memberType = property.PropertyType == null
                    ? typeof(object)
                    : property.PropertyType.TypeName.GetReflectionType();

                var attributes = new List<object>();
                for (int i = 0; i < property.Attributes.Count; i++)
                {
                    attributes.Add(property.Attributes[i].GetAttribute());
                }

                string mofType;
                bool isArrayType;
                string embeddedInstanceType;
                string[] enumNames = null;

                if (memberType != null)
                {
                    // TODO - validate type and name
                    mofType = MapTypeToMofType(memberType, member.Name, className, out isArrayType,
                        out embeddedInstanceType,
                        embeddedInstanceTypes);
                    if (memberType.IsEnum)
                    {
                        enumNames = Enum.GetNames(memberType);
                    }
                }
                else
                {
                    // PropertyType can't be null, we used typeof(object) above in that case so we don't get here.
                    mofType = MapTypeNameToMofType(property.PropertyType.TypeName, member.Name, className,
                        out isArrayType,
                        out embeddedInstanceType, embeddedInstanceTypes, ref enumNames);
                }

                string mofAttr = MapAttributesToMof(enumNames, attributes, embeddedInstanceType);
                string arrayAffix = isArrayType ? "[]" : string.Empty;

                sb.Append(
                    CultureInfo.InvariantCulture,
                    $"    {mofAttr}{mofType} {member.Name}{arrayAffix};\n");
            }
        }

        /// <summary>
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="resourceDefinitions"></param>
        /// <param name="errorList"></param>
        /// <param name="extent"></param>
        /// <returns></returns>
        private static bool GetResourceDefinitionsFromModule(string fileName, out IEnumerable<Ast> resourceDefinitions, List<ParseError> errorList, IScriptExtent extent)
        {
            resourceDefinitions = null;

            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }

            if (!".psm1".Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase) &&
                !".ps1".Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // If script dynamic keywords has already been loaded from the file, don't load them again.
            // The ScriptKeywordFile cache is always initialized from scratch by the top-level
            // configuration statement so within a single compile, things shouldn't change.
            if (!File.Exists(fileName) || ScriptKeywordFileCache.Contains(fileName))
            {
                return false;
            }

            // BUGBUG - need to fix up how the module gets set.
            Token[] tokens;
            ParseError[] errors;
            var ast = Parser.ParseFile(fileName, out tokens, out errors);

            if (errors != null && errors.Length > 0)
            {
                if (errorList != null && extent != null)
                {
                    List<string> errorMessages = new();
                    foreach (var error in errors)
                    {
                        errorMessages.Add(error.ToString());
                    }

                    errorList.Add(new ParseError(extent, "FailToParseModuleScriptFile",
                        string.Format(CultureInfo.CurrentCulture, ParserStrings.FailToParseModuleScriptFile, fileName, string.Join(Environment.NewLine, errorMessages))));
                }

                return false;
            }

            resourceDefinitions = ast.FindAll(n =>
            {
                if (n is TypeDefinitionAst typeAst)
                {
                    for (int i = 0; i < typeAst.Attributes.Count; i++)
                    {
                        var a = typeAst.Attributes[i];
                        if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }, false);

            return true;
        }

        /// <summary>
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="module"></param>
        /// <param name="resourcesToImport"></param>
        /// <param name="resourcesFound"></param>
        /// <param name="functionsToDefine"></param>
        /// <param name="errorList"></param>
        /// <param name="extent"></param>
        /// <returns></returns>
        private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo module, ICollection<string> resourcesToImport, ICollection<string> resourcesFound, Dictionary<string, ScriptBlock> functionsToDefine, List<ParseError> errorList, IScriptExtent extent)
        {
            IEnumerable<Ast> resourceDefinitions;
            if (!GetResourceDefinitionsFromModule(fileName, out resourceDefinitions, errorList, extent))
            {
                return false;
            }

            var result = false;
            var parser = new CimDSCParser(MyClassCallback);

            const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            IEnumerable<WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(module._declaredDscResourceExports, wildcardOptions);

            foreach (var r in resourceDefinitions)
            {
                result = true;
                var resourceDefnAst = (TypeDefinitionAst)r;

                if (!SessionStateUtilities.MatchesAnyWildcardPattern(resourceDefnAst.Name, patternList, true))
                {
                    continue;
                }

                bool skip = true;
                foreach (var toImport in resourcesToImport)
                {
                    if ((WildcardPattern.Get(toImport, WildcardOptions.IgnoreCase)).IsMatch(resourceDefnAst.Name))
                    {
                        skip = false;
                        break;
                    }
                }

                if (skip)
                {
                    continue;
                }

                // Parse the Resource Attribute to see if RunAs behavior is specified for the resource.
                DSCResourceRunAsCredential runAsBehavior = DSCResourceRunAsCredential.Default;
                foreach (var attr in resourceDefnAst.Attributes)
                {
                    if (attr.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))
                    {
                        foreach (var na in attr.NamedArguments)
                        {
                            if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase) && attr.GetAttribute() is DscResourceAttribute dscResourceAttribute)
                            {
                                runAsBehavior = dscResourceAttribute.RunAsCredential;
                            }
                        }
                    }
                }

                var mof = GenerateMofForAst(resourceDefnAst);

                ProcessMofForDynamicKeywords(module, resourcesFound, functionsToDefine, parser, mof, runAsBehavior);
            }

            return result;
        }

        private static readonly Dictionary<Type, string> s_mapPrimitiveDotNetTypeToMof = new()
        {
            { typeof(sbyte), "sint8" },
            { typeof(byte), "uint8"},
            { typeof(short), "sint16"},
            { typeof(ushort), "uint16"},
            { typeof(int), "sint32"},
            { typeof(uint), "uint32"},
            { typeof(long), "sint64"},
            { typeof(ulong), "uint64" },
            { typeof(float), "real32"},
            { typeof(double), "real64"},
            { typeof(bool), "boolean"},
            { typeof(string), "string" },
            { typeof(DateTime), "datetime" },
            { typeof(PSCredential), "string" },
            { typeof(char), "char16" },
        };

        private static bool AreQualifiersSame(CimReadOnlyKeyedCollection<CimQualifier> oldQualifier, CimReadOnlyKeyedCollection<CimQualifier> newQualifiers)
        {
            if (oldQualifier.Count != newQualifiers.Count)
            {
                return false;
            }

            foreach (var qual in oldQualifier)
            {
                // Find the qualifier in new class
                var newQual = newQualifiers[qual.Name];
                if (newQual == null)
                {
                    return false;
                }

                if ((qual.CimType != newQual.CimType) ||
                    (qual.Flags != newQual.Flags))
                {
                    return false;
                }

                if ((qual.Value == null && newQual.Value != null) ||
                    (qual.Value != null && newQual.Value == null) ||
                    (qual.Value != null && newQual.Value != null &&
                        !string.Equals(qual.Value.ToString(), newQual.Value.ToString(), StringComparison.OrdinalIgnoreCase)
                    )
                  )
                {
                    return false;
                }
            }

            return true;
        }

        private static bool ArePropertiesSame(CimReadOnlyKeyedCollection<CimPropertyDeclaration> oldProperties, CimReadOnlyKeyedCollection<CimPropertyDeclaration> newProperties)
        {
            if (oldProperties.Count != newProperties.Count)
            {
                return false;
            }

            foreach (var prop in oldProperties)
            {
                // Find the property in new class
                var newProp = newProperties[prop.Name];
                if (newProp == null)
                {
                    return false;
                }
                // flags and type should match
                if ((prop.CimType != newProp.CimType) ||
                    (prop.Flags != newProp.Flags))
                {
                    return false;
                }

                if (!AreQualifiersSame(prop.Qualifiers, newProp.Qualifiers))
                {
                    return false;
                }
            }

            return true;
        }

        private static bool IsSameNestedObject(CimClass oldClass, CimClass newClass)
        {
            // #1 both the classes should be nested class and not DSC resource
            if ((oldClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", oldClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase)) ||
                (newClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", newClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase)))
            {
                return false;
            }
            // #2 qualifier count, names, values and types should be same
            if (!AreQualifiersSame(oldClass.CimClassQualifiers, newClass.CimClassQualifiers))
            {
                return false;
            }

            // #3 property count, names, values, qualifiers and types should be same
            if (!ArePropertiesSame(oldClass.CimClassProperties, newClass.CimClassProperties))
            {
                return false;
            }

            return true;
        }

        internal static string MapTypeToMofType(Type type, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List<object> embeddedInstanceTypes)
        {
            isArrayType = false;
            if (type.IsValueType)
            {
                type = Nullable.GetUnderlyingType(type) ?? type;
            }

            if (type.IsEnum)
            {
                embeddedInstanceType = null;
                return "string";
            }

            if (type == typeof(Hashtable))
            {
                // Hashtable is obviously not an array, but in the mof, we represent
                // it as string[] (really, embeddedinstance of MSFT_KeyValuePair), but
                // we need an array to hold each entry in the hashtable.
                isArrayType = true;
                embeddedInstanceType = "MSFT_KeyValuePair";
                return "string";
            }

            if (type == typeof(PSCredential))
            {
                embeddedInstanceType = "MSFT_Credential";
                return "string";
            }

            if (type.IsArray)
            {
                isArrayType = true;
                bool temp;
                var elementType = type.GetElementType();
                if (!elementType.IsArray)
                    return MapTypeToMofType(type.GetElementType(), memberName, className, out temp, out embeddedInstanceType, embeddedInstanceTypes);
            }
            else
            {
                string cimType;
                if (s_mapPrimitiveDotNetTypeToMof.TryGetValue(type, out cimType))
                {
                    embeddedInstanceType = null;
                    return cimType;
                }
            }

            bool supported = false;
            bool missingDefaultConstructor = false;
            if (type.IsValueType)
            {
                if (s_mapPrimitiveDotNetTypeToMof.ContainsKey(type))
                {
                    supported = true;
                }
            }
            else if (!type.IsAbstract)
            {
                // Must have default constructor, at least 1 public property/field, and no base classes
                if (type.GetConstructor(Type.EmptyTypes) == null)
                {
                    missingDefaultConstructor = true;
                }
                else if (type.BaseType == typeof(object) &&
                    (type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Length > 0 ||
                         type.GetFields(BindingFlags.Instance | BindingFlags.Public).Length > 0))
                {
                    supported = true;
                }
            }

            if (supported)
            {
                if (!embeddedInstanceTypes.Contains(type))
                {
                    embeddedInstanceTypes.Add(type);
                }

                // The type is obviously not a string, but in the mof, we represent
                // it as string (really, embeddedinstance of the class type)
                embeddedInstanceType = type.FullName.Replace('.', '_');
                return "string";
            }

            if (missingDefaultConstructor)
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.InvariantCulture,
                    ParserStrings.DscResourceMissingDefaultConstructor,
                    type.Name));
            }
            else
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.InvariantCulture,
                    ParserStrings.UnsupportedPropertyTypeOfDSCResourceClass,
                    memberName,
                    type.Name,
                    className));
            }
        }

        private static string MapAttributesToMof(string[] enumNames, IEnumerable<object> customAttributes, string embeddedInstanceType)
        {
            var sb = new StringBuilder();

            sb.Append('[');
            bool needComma = false;
            foreach (var attr in customAttributes)
            {
                if (attr is DscPropertyAttribute dscProperty)
                {
                    if (dscProperty.Key)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0}key", needComma ? ", " : string.Empty);
                        needComma = true;
                    }

                    if (dscProperty.Mandatory)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0}required", needComma ? ", " : string.Empty);
                        needComma = true;
                    }

                    if (dscProperty.NotConfigurable)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0}read", needComma ? ", " : string.Empty);
                        needComma = true;
                    }

                    continue;
                }

                if (attr is ValidateSetAttribute validateSet)
                {
                    bool valueMapComma = false;
                    StringBuilder sbValues = new(", Values{");
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty);
                    needComma = true;

                    foreach (var value in validateSet.ValidValues)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value);
                        sbValues.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value);
                        valueMapComma = true;
                    }

                    sb.Append('}');
                    sb.Append(sbValues);
                    sb.Append('}');
                }
            }

            // Default is write - skipped if we already have some attributes
            if (sb.Length == 1)
            {
                sb.Append("write");
                needComma = true;
            }

            if (enumNames != null)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty);
                needComma = false;
                foreach (var name in enumNames)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name);
                    needComma = true;
                }

                sb.Append("}, Values{");
                needComma = false;
                foreach (var name in enumNames)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name);
                    needComma = true;
                }

                sb.Append('}');
            }
            else if (embeddedInstanceType != null)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0}EmbeddedInstance(\"{1}\")", needComma ? ", " : string.Empty, embeddedInstanceType);
            }

            sb.Append(']');
            return sb.ToString();
        }

        /// <summary>
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GenerateMofForType(Type type)
        {
            var embeddedInstanceTypes = new List<object>();
            var sb = new StringBuilder();

            GenerateMofForType(type, sb, embeddedInstanceTypes);
            var visitedInstances = new List<object>();
            visitedInstances.Add(type);
            ProcessEmbeddedInstanceTypes(embeddedInstanceTypes, visitedInstances, sb);

            return sb.ToString();
        }

        private static void ProcessEmbeddedInstanceTypes(List<object> embeddedInstanceTypes, List<object> visitedInstances, StringBuilder sb)
        {
            StringBuilder nestedSb = null;

            while (embeddedInstanceTypes.Count > 0)
            {
                if (nestedSb == null)
                {
                    nestedSb = new StringBuilder();
                }
                else
                {
                    nestedSb.Clear();
                }

                var batchedTypes = embeddedInstanceTypes.Where(x => !visitedInstances.Contains(x)).ToArray();
                embeddedInstanceTypes.Clear();

                for (int i = batchedTypes.Length - 1; i >= 0; i--)
                {
                    visitedInstances.Add(batchedTypes[i]);
                    var type = batchedTypes[i] as Type;
                    if (type != null)
                    {
                        GenerateMofForType(type, nestedSb, embeddedInstanceTypes);
                    }
                    else
                    {
                        GenerateMofForAst((TypeDefinitionAst)batchedTypes[i], nestedSb, embeddedInstanceTypes);
                    }

                    nestedSb.Append('\n');
                }

                sb.Insert(0, nestedSb.ToString());
            }
        }

        private static void GenerateMofForType(Type type, StringBuilder sb, List<object> embeddedInstanceTypes)
        {
            var className = type.Name;
            // Friendly name is required by module validator to verify resource instance against the exclusive resource name list.
            sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}");

            if (type.GetCustomAttributes<DscResourceAttribute>().Any())
            {
                sb.Append(" : OMI_BaseResource");
            }

            sb.Append("\n{\n");

            ProcessMembers(type, sb, embeddedInstanceTypes, className);
            sb.Append("};");
        }

        private static void ProcessMembers(Type type, StringBuilder sb, List<object> embeddedInstanceTypes, string className)
        {
            foreach (var member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public).Where(static m => m is PropertyInfo || m is FieldInfo))
            {
                if (member.CustomAttributes.All(static cad => cad.AttributeType != typeof(DscPropertyAttribute)))
                {
                    continue;
                }

                Type memberType;
                var propertyInfo = member as PropertyInfo;
                if (propertyInfo == null)
                {
                    var fieldInfo = (FieldInfo)member;
                    memberType = fieldInfo.FieldType;
                }
                else
                {
                    if (propertyInfo.GetSetMethod() == null)
                    {
                        continue;
                    }

                    memberType = propertyInfo.PropertyType;
                }

                // TODO - validate type and name
                string mofType = MapTypeToMofType(
                    memberType,
                    member.Name,
                    className,
                    out bool isArrayType,
                    out string embeddedInstanceType,
                    embeddedInstanceTypes);

                var enumNames = memberType.IsEnum ? Enum.GetNames(memberType) : null;
                string mofAttr = MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType);
                string arrayAffix = isArrayType ? "[]" : string.Empty;

                sb.Append(
                    CultureInfo.InvariantCulture,
                    $"    {mofAttr}{mofType} {member.Name}{arrayAffix};\n");
            }
        }

        private static bool ImportKeywordsFromAssembly(PSModuleInfo module,
                                                       ICollection<string> resourcesToImport,
                                                       ICollection<string> resourcesFound,
                                                       Dictionary<string, ScriptBlock> functionsToDefine,
                                                       Assembly assembly)
        {
            bool result = false;

            var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);

            IEnumerable<Type> resourceDefinitions =
                assembly.GetTypes().Where(static t => t.GetCustomAttributes<DscResourceAttribute>().Any());

            foreach (var r in resourceDefinitions)
            {
                result = true;
                bool skip = true;

                foreach (var toImport in resourcesToImport)
                {
                    if ((WildcardPattern.Get(toImport, WildcardOptions.IgnoreCase)).IsMatch(r.Name))
                    {
                        skip = false;
                        break;
                    }
                }

                if (skip)
                {
                    continue;
                }

                var mof = GenerateMofForType(r);

                ProcessMofForDynamicKeywords(module, resourcesFound, functionsToDefine, parser, mof, DSCResourceRunAsCredential.Default);
            }

            return result;
        }

        private static void ProcessMofForDynamicKeywords(PSModuleInfo module, ICollection<string> resourcesFound,
            Dictionary<string, ScriptBlock> functionsToDefine, CimDSCParser parser, string mof, DSCResourceRunAsCredential runAsBehavior)
        {
            foreach (var c in parser.ParseSchemaMofFileBuffer(mof))
            {
                var className = c.CimSystemProperties.ClassName;
                string alias = GetFriendlyName(c);
                var friendlyName = string.IsNullOrEmpty(alias) ? className : alias;
                if (!CacheResourcesFromMultipleModuleVersions)
                {
                    // Find & remove the previous version of the resource.
                    List<KeyValuePair<string, DscClassCacheEntry>> resourceList = FindResourceInCache(module.Name, className, friendlyName);

                    if (resourceList.Count > 0 && !string.IsNullOrEmpty(resourceList[0].Key))
                    {
                        ClassCache.Remove(resourceList[0].Key);

                        // keyword is already defined and it is a Inbox resource, remove it
                        if (DynamicKeyword.ContainsKeyword(friendlyName) && resourceList[0].Value.IsImportedImplicitly)
                        {
                            DynamicKeyword.RemoveKeyword(friendlyName);
                        }
                    }
                }

                var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className, friendlyName);
                ClassCache[moduleQualifiedResourceName] = new DscClassCacheEntry(runAsBehavior, false, c);
                ByClassModuleCache[className] = new Tuple<string, Version>(module.Name, module.Version);
                resourcesFound.Add(className);
                CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, runAsBehavior);
            }
        }

        /// <summary>
        /// Import the CIM functions from a module...
        /// </summary>
        /// <param name="module"></param>
        /// <param name="resourceName"></param>
        /// <param name="schemaFilePath">Full path of the loaded schema file...</param>
        /// <returns></returns>
        public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath)
        {
            return ImportCimKeywordsFromModule(module, resourceName, out schemaFilePath, null);
        }

        /// <summary>
        /// Import the CIM functions from a module...
        /// </summary>
        /// <param name="module"></param>
        /// <param name="resourceName"></param>
        /// <param name="schemaFilePath">Full path of the loaded schema file...</param>
        /// <param name="functionsToDefine"></param>
        /// <returns></returns>
        public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath, Dictionary<string, ScriptBlock> functionsToDefine)
        {
            return ImportCimKeywordsFromModule(module, resourceName, out schemaFilePath, functionsToDefine, null);
        }

        /// <summary>
        /// Import the CIM functions from a module...
        /// </summary>
        /// <param name="module"></param>
        /// <param name="resourceName"></param>
        /// <param name="schemaFilePath">Full path of the loaded schema file...</param>
        /// <param name="functionsToDefine"></param>
        /// <param name="errors">Error reported during deserialization.</param>
        /// <returns></returns>
        public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath, Dictionary<string, ScriptBlock> functionsToDefine, Collection<Exception> errors)
        {
            if (module == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(module));
            }

            if (resourceName == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(resourceName));
            }

            string dscResourcesPath = Path.Combine(module.ModuleBase, "DscResources");
            schemaFilePath = Path.Combine(Path.Combine(dscResourcesPath, resourceName), resourceName + ".schema.mof");

            if (File.Exists(schemaFilePath))
            {
                // If the file has already been loaded, don't load it again.
                // The class cache is always initialized from scratch by the top-level
                // configuration statement so within a single compile, things shouldn't
                // change.
                var classes = GetCachedClassByFileName(schemaFilePath) ?? ImportClasses(schemaFilePath, new Tuple<string, Version>(module.Name, module.Version), errors);
                if (classes != null)
                {
                    foreach (var c in classes)
                    {
                        CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, DSCResourceRunAsCredential.Default);
                        ClearImplicitlyImportedFlagFromResourceInClassCache(module, c);
                    }
                }

                return true;
            }
            else if (Directory.Exists(dscResourcesPath))
            {
                //
                // Cannot find the schema file, then resourceName may be a friendly name,
                // try to search all DscResources' schemas under DscResources folder
                //
                try
                {
                    foreach (var directory in Directory.EnumerateDirectories(dscResourcesPath))
                    {
                        IEnumerable<string> schemaFiles = Directory.EnumerateFiles(directory, "*.schema.mof", SearchOption.TopDirectoryOnly);
                        string tempSchemaFilepath = schemaFiles.FirstOrDefault();

                        Debug.Assert(schemaFiles.Count() == 1, "A valid DSCResource module can have only one schema mof file");

                        if (tempSchemaFilepath is not null)
                        {
                            var classes = GetCachedClassByFileName(tempSchemaFilepath) ?? ImportClasses(tempSchemaFilepath, new Tuple<string, Version>(module.Name, module.Version), errors);
                            if (classes != null)
                            {
                                //
                                // search if class's friendly name is the given resourceName
                                //
                                foreach (var c in classes)
                                {
                                    var alias = GetFriendlyName(c);
                                    if (string.Equals(alias, resourceName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, DSCResourceRunAsCredential.Default);
                                        ClearImplicitlyImportedFlagFromResourceInClassCache(module, c);
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    //
                    // silent in case of exception
                    //
                }
            }

            return false;
        }

        /// <summary>
        /// Clear the 'IsImportedImplicitly' flag when explicitly importing a resource.
        /// </summary>
        /// <param name="module"></param>
        /// <param name="cimClass"></param>
        private static void ClearImplicitlyImportedFlagFromResourceInClassCache(PSModuleInfo module, CimClass cimClass)
        {
            var className = cimClass.CimSystemProperties.ClassName;
            var alias = GetFriendlyName(cimClass);
            var friendlyName = string.IsNullOrEmpty(alias) ? className : alias;
            var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className, friendlyName);
            ClassCache[moduleQualifiedResourceName].IsImportedImplicitly = false;
        }

        /// <summary>
        /// Imports configuration keywords from a .psm1 file.
        /// </summary>
        /// <param name="module"></param>
        /// <param name="resourceName"></param>
        /// <param name="schemaFilePath"></param>
        public static bool ImportScriptKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath)
        {
            return ImportScriptKeywordsFromModule(module, resourceName, out schemaFilePath, null);
        }

        /// <summary>
        /// Imports configuration keywords from a .psm1 file.
        /// </summary>
        /// <param name="module"></param>
        /// <param name="resourceName"></param>
        /// <param name="schemaFilePath"></param>
        /// <param name="functionsToDefine"></param>
        public static bool ImportScriptKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath, Dictionary<string, ScriptBlock> functionsToDefine)
        {
            if (module == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(module));
            }

            if (resourceName == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(resourceName));
            }

            schemaFilePath = Path.Combine(Path.Combine(Path.Combine(module.ModuleBase, "DscResources"), resourceName), resourceName + ".Schema.psm1");

            if (File.Exists(schemaFilePath) && !s_currentImportingScriptFiles.Contains(schemaFilePath))
            {
                // If script dynamic keywords has already been loaded from the file, don't load them again.
                // The ScriptKeywordFile cache is always initialized from scratch by the top-level
                // configuration statement so within a single compile, things shouldn't change.
                if (!ScriptKeywordFileCache.Contains(schemaFilePath))
                {
                    // Parsing the file is all that needs to be done to add the keywords
                    // BUGBUG - need to fix up how the module gets set.
                    // BUGBUG - should fail somehow if errors is not empty
                    Token[] tokens; ParseError[] errors;
                    s_currentImportingScriptFiles.Add(schemaFilePath);
                    Parser.ParseFile(schemaFilePath, out tokens, out errors);
                    s_currentImportingScriptFiles.Remove(schemaFilePath);
                    ScriptKeywordFileCache.Add(schemaFilePath);
                }

                return true;
            }

            return false;
        }

        /// <summary>
        /// Returns an error record to use in the case of a malformed resource reference in the DependsOn list.
        /// </summary>
        /// <param name="badDependsOnReference">The malformed resource.</param>
        /// <param name="definingResource">The referencing resource instance.</param>
        /// <returns></returns>
        public static ErrorRecord GetBadlyFormedRequiredResourceIdErrorRecord(string badDependsOnReference, string definingResource)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.GetBadlyFormedRequiredResourceId, badDependsOnReference, definingResource);

            e.SetErrorId("GetBadlyFormedRequiredResourceId");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of a malformed resource reference in the exclusive resources list.
        /// </summary>
        /// <param name="badExclusiveResourcereference">The malformed resource.</param>
        /// <param name="definingResource">The referencing resource instance.</param>
        /// <returns></returns>
        public static ErrorRecord GetBadlyFormedExclusiveResourceIdErrorRecord(string badExclusiveResourcereference, string definingResource)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.GetBadlyFormedExclusiveResourceId, badExclusiveResourcereference, definingResource);

            e.SetErrorId("GetBadlyFormedExclusiveResourceId");
            return e.ErrorRecord;
        }

        /// <summary>
        /// If a partial configuration is in 'Pull' Mode, it needs a configuration source.
        /// </summary>
        /// <param name="resourceId"></param>
        /// <returns></returns>
        public static ErrorRecord GetPullModeNeedConfigurationSource(string resourceId)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.GetPullModeNeedConfigurationSource, resourceId);

            e.SetErrorId("GetPullModeNeedConfigurationSource");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Refresh Mode can not be Disabled for the Partial Configurations.
        /// </summary>
        /// <param name="resourceId"></param>
        /// <returns></returns>
        public static ErrorRecord DisabledRefreshModeNotValidForPartialConfig(string resourceId)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.DisabledRefreshModeNotValidForPartialConfig, resourceId);

            e.SetErrorId("DisabledRefreshModeNotValidForPartialConfig");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of a malformed resource reference in the DependsOn list.
        /// </summary>
        /// <param name="duplicateResourceId">The duplicate resource identifier.</param>
        /// <param name="nodeName">The node being defined.</param>
        /// <returns>The error record to use.</returns>
        public static ErrorRecord DuplicateResourceIdInNodeStatementErrorRecord(string duplicateResourceId, string nodeName)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.DuplicateResourceIdInNodeStatement, duplicateResourceId, nodeName);

            e.SetErrorId("DuplicateResourceIdInNodeStatement");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of a configuration name is invalid.
        /// </summary>
        /// <param name="configurationName"></param>
        /// <returns></returns>
        public static ErrorRecord InvalidConfigurationNameErrorRecord(string configurationName)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.InvalidConfigurationName, configurationName);

            e.SetErrorId("InvalidConfigurationName");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of the given value for a property is invalid.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <param name="keywordName"></param>
        /// <param name="validValues"></param>
        /// <returns></returns>
        public static ErrorRecord InvalidValueForPropertyErrorRecord(string propertyName, string value, string keywordName, string validValues)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.InvalidValueForProperty, value, propertyName, keywordName, validValues);

            e.SetErrorId("InvalidValueForProperty");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in case the given property is not valid LocalConfigurationManager property.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="validProperties"></param>
        /// <returns></returns>
        public static ErrorRecord InvalidLocalConfigurationManagerPropertyErrorRecord(string propertyName, string validProperties)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.InvalidLocalConfigurationManagerProperty, propertyName, validProperties);

            e.SetErrorId("InvalidLocalConfigurationManagerProperty");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of the given value for a property is not supported.
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <param name="keywordName"></param>
        /// <param name="validValues"></param>
        /// <returns></returns>
        public static ErrorRecord UnsupportedValueForPropertyErrorRecord(string propertyName, string value, string keywordName, string validValues)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.UnsupportedValueForProperty, value, propertyName, keywordName, validValues);

            e.SetErrorId("UnsupportedValueForProperty");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of no value is provided for a mandatory property.
        /// </summary>
        /// <param name="keywordName"></param>
        /// <param name="typeName"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static ErrorRecord MissingValueForMandatoryPropertyErrorRecord(string keywordName, string typeName, string propertyName)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.MissingValueForMandatoryProperty, keywordName, typeName, propertyName);

            e.SetErrorId("MissingValueForMandatoryProperty");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use in the case of more than one values are provided for DebugMode property.
        /// </summary>
        /// <returns></returns>
        public static ErrorRecord DebugModeShouldHaveOneValue()
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.DebugModeShouldHaveOneValue);

            e.SetErrorId("DebugModeShouldHaveOneValue");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Return an error to indicate a value is out of range for a dynamic keyword property.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="name"></param>
        /// <param name="providedValue"></param>
        /// <param name="lower"></param>
        /// <param name="upper"></param>
        /// <returns></returns>
        public static ErrorRecord ValueNotInRangeErrorRecord(string property, string name, int providedValue, int lower, int upper)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                ParserStrings.ValueNotInRange, property, name, providedValue, lower, upper);

            e.SetErrorId("ValueNotInRange");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Returns an error record to use when composite resource and its resource instances both has PsDscRunAsCredentials value.
        /// </summary>
        /// <param name="resourceId">ResourceId of resource.</param>
        /// <returns></returns>
        public static ErrorRecord PsDscRunAsCredentialMergeErrorForCompositeResources(string resourceId)
        {
            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                 ParserStrings.PsDscRunAsCredentialMergeErrorForCompositeResources, resourceId);

            e.SetErrorId("PsDscRunAsCredentialMergeErrorForCompositeResources");
            return e.ErrorRecord;
        }

        /// <summary>
        /// Routine to format a usage string from keyword. The resulting string should look like:
        ///        User [string] #ResourceName
        ///        {
        ///            UserName = [string]
        ///            [ Description = [string] ]
        ///            [ Disabled = [bool] ]
        ///            [ Ensure = [string] { Absent | Present }  ]
        ///            [ Force = [bool] ]
        ///            [ FullName = [string] ]
        ///            [ Password = [PSCredential] ]
        ///            [ PasswordChangeNotAllowed = [bool] ]
        ///            [ PasswordChangeRequired = [bool] ]
        ///            [ PasswordNeverExpires = [bool] ]
        ///            [ DependsOn = [string[]] ]
        ///        }
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static string GetDSCResourceUsageString(DynamicKeyword keyword)
        {
            StringBuilder usageString;
            switch (keyword.NameMode)
            {
                // Name must be present and simple non-empty bare word
                case DynamicKeywordNameMode.SimpleNameRequired:
                    usageString = new StringBuilder(keyword.Keyword + " [string] # Resource Name");
                    break;

                // Name must be present but can also be an expression
                case DynamicKeywordNameMode.NameRequired:
                    usageString = new StringBuilder(keyword.Keyword + " [string[]] # Name List");
                    break;

                // Name may be optionally present, but if it is present, it must be a non-empty bare word.
                case DynamicKeywordNameMode.SimpleOptionalName:
                    usageString = new StringBuilder(keyword.Keyword + " [ [string] ] # Optional Name");
                    break;

                // Name may be optionally present, expression or bare word
                case DynamicKeywordNameMode.OptionalName:
                    usageString = new StringBuilder(keyword.Keyword + " [ [string[]] ] # Optional NameList");
                    break;

                // Does not take a name
                default:
                    usageString = new StringBuilder(keyword.Keyword);
                    break;
            }

            usageString.Append("\n{\n");

            bool listKeyProperties = true;
            while (true)
            {
                foreach (var prop in keyword.Properties.OrderBy(static ob => ob.Key))
                {
                    if (string.Equals(prop.Key, "ResourceId", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var propVal = prop.Value;
                    if (listKeyProperties && propVal.IsKey || !listKeyProperties && !propVal.IsKey)
                    {
                        usageString.Append(propVal.Mandatory ? "    " : "    [ ");
                        usageString.Append(prop.Key);
                        usageString.Append(" = ");
                        usageString.Append(FormatCimPropertyType(propVal, !propVal.Mandatory));
                    }
                }

                if (listKeyProperties)
                {
                    listKeyProperties = false;
                }
                else
                {
                    break;
                }
            }

            usageString.Append('}');

            return usageString.ToString();
        }

        /// <summary>
        /// Format the type name of a CIM property in a presentable way.
        /// </summary>
        /// <param name="prop"></param>
        /// <param name="isOptionalProperty"></param>
        /// <returns></returns>
        private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty)
        {
            string cimTypeName = prop.TypeConstraint;
            StringBuilder formattedTypeString = new();

            if (string.Equals(cimTypeName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase))
            {
                formattedTypeString.Append("[PSCredential]");
            }
            else if (string.Equals(cimTypeName, "MSFT_KeyValuePair", StringComparison.OrdinalIgnoreCase) || string.Equals(cimTypeName, "MSFT_KeyValuePair[]", StringComparison.OrdinalIgnoreCase))
            {
                formattedTypeString.Append("[Hashtable]");
            }
            else
            {
                string convertedTypeString = System.Management.Automation.LanguagePrimitives.ConvertTypeNameToPSTypeName(cimTypeName);
                if (!string.IsNullOrEmpty(convertedTypeString) && !string.Equals(convertedTypeString, "[]", StringComparison.OrdinalIgnoreCase))
                {
                    formattedTypeString.Append(convertedTypeString);
                }
                else
                {
                    formattedTypeString.Append("[" + cimTypeName + "]");
                }
            }

            // Do the property values map
            if (prop.ValueMap != null && prop.ValueMap.Count > 0)
            {
                formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.Order()) + " }");
            }

            // We prepend optional property with "[" so close out it here. This way it is shown with [ ] to indication optional
            if (isOptionalProperty)
            {
                formattedTypeString.Append(']');
            }

            formattedTypeString.Append('\n');

            return formattedTypeString;
        }

        /// <summary>
        /// The scriptblock that implements the CIM keyword functionality.
        /// </summary>
        private static ScriptBlock CimKeywordImplementationFunction
        {
            get
            {
                // The scriptblock cache will handle mutual exclusion
                return s_cimKeywordImplementationFunction ??= ScriptBlock.Create(CimKeywordImplementationFunctionText);
            }
        }

        private static ScriptBlock s_cimKeywordImplementationFunction;

        private const string CimKeywordImplementationFunctionText = @"
    param (
        [Parameter(Mandatory)]
            $KeywordData,
        [Parameter(Mandatory)]
            $Name,
        [Parameter(Mandatory)]
        [Hashtable]
            $Value,
        [Parameter(Mandatory)]
            $SourceMetadata
    )

# walk the call stack to get at all of the enclosing configuration resource IDs
    $stackedConfigs = @(Get-PSCallStack |
        where { ($null -ne $_.InvocationInfo.MyCommand) -and ($_.InvocationInfo.MyCommand.CommandType -eq 'Configuration') })
# keep all but the top-most
    $stackedConfigs = $stackedConfigs[0..(@($stackedConfigs).Length - 2)]
# and build the complex resource ID suffix.
    $complexResourceQualifier = ( $stackedConfigs | ForEach-Object { '[' + $_.Command + ']' + $_.InvocationInfo.BoundParameters['InstanceName'] } ) -join '::'

#
# Utility function used to validate that the DependsOn arguments are well-formed.
# The function also adds them to the define nodes resource collection.
# in the case of resources generated inside a script resource, this routine
# will also fix up the DependsOn references to '[Type]Instance::[OuterType]::OuterInstance
#
    function Test-DependsOn
    {

# make sure the references are well-formed
        $updatedDependsOn = foreach ($DependsOnVar in $value['DependsOn']) {
# match [ResourceType]ResourceName. ResourceName should starts with [a-z_0-9] followed by [a-z_0-9\p{Zs}\.\\-]*
            if ($DependsOnVar -notmatch '^\[[a-z]\w*\][a-z_0-9][a-z_0-9\p{Zs}\.\\-]*$')
            {
                Update-ConfigurationErrorCount
                Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::GetBadlyFormedRequiredResourceIdErrorRecord($DependsOnVar, $resourceId))
            }

# Fix up DependsOn for nested names
            if ($MyTypeName -and $typeName -ne $MyTypeName -and $InstanceName)
            {
                ""$DependsOnVar::$complexResourceQualifier""
            }
            else
            {
                $DependsOnVar
            }
        }

        $value['DependsOn']= $updatedDependsOn

        if($null -ne $DependsOn)
        {
#
# Combine DependsOn with dependson from outer composite resource
# which is set as local variable $DependsOn at the composite resource context
#
            $value['DependsOn']= @($value['DependsOn']) + $DependsOn
        }

# Save the resource id in a per-node dictionary to do cross validation at the end
        Set-NodeResources $resourceId @( $value['DependsOn'])

# Remove depends on because it need to be fixed up for composite resources
# We do it in ValidateNodeResource and Update-Depends on in configuration/Node function
        $value.Remove('DependsOn')
    }

# A copy of the value object with correctly-cased property names
    $canonicalizedValue = @{}

    $typeName = $keywordData.ResourceName # CIM type
    $keywordName = $keywordData.Keyword   # user-friendly alias that is used in scripts
    $keyValues = ''
    $debugPrefix = ""   ${TypeName}:"" # set up a debug prefix string that makes it easier to track what's happening.

    Write-Debug ""${debugPrefix} RESOURCE PROCESSING STARTED [KeywordName='$keywordName'] Function='$($myinvocation.Invocationname)']""

# Check whether it's an old style metaconfig
    $OldMetaConfig = $false
    if ((-not $IsMetaConfig) -and ($keywordName -ieq 'LocalConfigurationManager')) {
        $OldMetaConfig = $true
    }

# Check to see if it's a resource keyword. If so add the meta-properties to the canonical property collection.
    $resourceId = $null
# todo: need to include configuration managers and partial configuration
    if (($keywordData.Properties.Keys -contains 'DependsOn') -or (($KeywordData.ImplementingModule -ieq 'PSDesiredStateConfigurationEngine') -and ($KeywordData.NameMode -eq [System.Management.Automation.Language.DynamicKeywordNameMode]::NameRequired)))
    {

        $resourceId = ""[$keywordName]$name""
        if ($MyTypeName -and $keywordName -ne $MyTypeName -and $InstanceName)
        {
            $resourceId += ""::$complexResourceQualifier""
        }

        Write-Debug ""${debugPrefix} ResourceID = $resourceId""

# copy the meta-properties
        $canonicalizedValue['ResourceID'] = $resourceId
        $canonicalizedValue['SourceInfo'] = $SourceMetadata
        if(-not $IsMetaConfig)
        {
            $canonicalizedValue['ModuleName'] = $keywordData.ImplementingModule
            $canonicalizedValue['ModuleVersion'] = $keywordData.ImplementingModuleVersion -as [string]
        }

# see if there is already a resource with this ID.
        if (Test-NodeResources $resourceId)
        {
            Update-ConfigurationErrorCount
            Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::DuplicateResourceIdInNodeStatementErrorRecord($resourceId, (Get-PSCurrentConfigurationNode)))
        }
        else
        {
# If there are prerequisite resources, validate that the references are well-formed strings
# This routine also adds the resource to the global node resources table.
            Test-DependsOn

# Check if PsDscRunCredential is being specified as Arguments to Configuration
        if($null -ne $PsDscRunAsCredential)
        {
# Check if resource is also trying to set the value for RunAsCred
# In that case we will generate error during compilation, this is merge error
        if($null -ne $value['PsDscRunAsCredential'])
        {
            Update-ConfigurationErrorCount
            Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::PsDscRunAsCredentialMergeErrorForCompositeResources($resourceId))
        }
# Set the Value of RunAsCred to that of outer configuration
        else
        {
            $value['PsDscRunAsCredential'] = $PsDscRunAsCredential
        }
    }

# Save the resource id in a per-node dictionary to do cross validation at the end
            if($keywordData.ImplementingModule -ieq ""PSDesiredStateConfigurationEngine"")
            {
#$keywordName is PartialConfiguration
                if($keywordName -eq 'PartialConfiguration')
                {
# RefreshMode is 'Pull' and .ConfigurationSource is empty
                    if($value['RefreshMode'] -eq 'Pull' -and -not $value['ConfigurationSource'])
                    {
                        Update-ConfigurationErrorCount
                        Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::GetPullModeNeedConfigurationSource($resourceId))
                    }

# Verify that RefreshMode is not Disabled for Partial configuration
                    if($value['RefreshMode'] -eq 'Disabled')
                    {
                        Update-ConfigurationErrorCount
                        Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::DisabledRefreshModeNotValidForPartialConfig($resourceId))
                    }

                    if($null -ne $value['ConfigurationSource'])
                    {
                        Set-NodeManager $resourceId $value['ConfigurationSource']
                    }

                    if($null -ne $value['ResourceModuleSource'])
                    {
                        Set-NodeResourceSource $resourceId $value['ResourceModuleSource']
                    }
                }

                if($null -ne $value['ExclusiveResources'])
                {
# make sure the references are well-formed
                    foreach ($ExclusiveResource in $value['ExclusiveResources']) {
                        if (($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*\\[a-z][a-z_0-9]*$') -and ($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*$') -and ($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*\\\*$'))
                        {
                            Update-ConfigurationErrorCount
                            Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::GetBadlyFormedExclusiveResourceIdErrorRecord($ExclusiveResource, $resourceId))
                        }
                    }

# Save the resource id in a per-node dictionary to do cross validation at the end
# Validate resource exist
# Also update the resource reference from module\friendlyname to module\name
                    $value['ExclusiveResources'] = @(Set-NodeExclusiveResources $resourceId @( $value['ExclusiveResources'] ))
                }
            }
        }
    }
    else
    {
        Write-Debug ""${debugPrefix} TYPE IS NOT AS DSC RESOURCE""
    }

#
# Copy the user-supplied values into a new collection with canonicalized property names
#
    foreach ($key in $keywordData.Properties.Keys)
    {
        Write-Debug ""${debugPrefix} Processing property '$key' [""

        if ($value.Contains($key))
        {
            if ($OldMetaConfig -and (-not ($V1MetaConfigPropertyList -contains $key)))
            {
                Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::InvalidLocalConfigurationManagerPropertyErrorRecord($key, ($V1MetaConfigPropertyList -join ', ')))
                Update-ConfigurationErrorCount
            }
# see if there is a list of allowed values for this property (similar to an enum)
            $allowedValues = $keywordData.Properties[$key].Values
# If there is and user-provided value is not in that list, write an error.
            if ($allowedValues)
            {
                if(($null -eq $value[$key]) -and ($allowedValues -notcontains $value[$key]))
                {
                    Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::InvalidValueForPropertyErrorRecord($key, ""$($value[$key])"", $keywordData.Keyword, ($allowedValues -join ', ')))
                    Update-ConfigurationErrorCount
                }
                else
                {
                    $notAllowedValue=$null
                    foreach($v in $value[$key])
                    {
                        if($allowedValues -notcontains $v)
                        {
                            $notAllowedValue +=$v.ToString() + ', '
                        }
                    }

                    if($notAllowedValue)
                    {
                        $notAllowedValue = $notAllowedValue.Substring(0, $notAllowedValue.Length -2)
                        Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::UnsupportedValueForPropertyErrorRecord($key, $notAllowedValue, $keywordData.Keyword, ($allowedValues -join ', ')))
                        Update-ConfigurationErrorCount
                    }
                }
            }

# see if a value range is defined for this property
            $allowedRange = $keywordData.Properties[$key].Range
            if($allowedRange)
            {
                $castedValue = $value[$key] -as [int]
                if((($castedValue -is [int]) -and (($castedValue -lt  $keywordData.Properties[$key].Range.Item1) -or ($castedValue -gt $keywordData.Properties[$key].Range.Item2))) -or ($null -eq $castedValue))
                {
                    Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::ValueNotInRangeErrorRecord($key, $keywordName, $value[$key],  $keywordData.Properties[$key].Range.Item1,  $keywordData.Properties[$key].Range.Item2))
                    Update-ConfigurationErrorCount
                }
            }

            Write-Debug ""${debugPrefix}        Canonicalized property '$key' = '$($value[$key])'""

            if ($keywordData.Properties[$key].IsKey)
            {
                if($null -eq $value[$key])
                {
                    $keyValues += ""::__NULL__""
                }
                else
                {
                    $keyValues += ""::"" + $value[$key]
                }
            }

# see if ValueMap is also defined for this property (actual values)
            $allowedValueMap = $keywordData.Properties[$key].ValueMap
#if it is and the ValueMap contains the user-provided value as a key, use the actual value
            if ($allowedValueMap -and $allowedValueMap.ContainsKey($value[$key]))
            {
                $canonicalizedValue[$key] = $allowedValueMap[$value[$key]]
            }
            else
            {
                $canonicalizedValue[$key] = $value[$key]
            }
        }
        elseif ($keywordData.Properties[$key].Mandatory)
        {
# If the property was mandatory but the user didn't provide a value, write and error.
            Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::MissingValueForMandatoryPropertyErrorRecord($keywordData.Keyword, $keywordData.Properties[$key].TypeConstraint, $Key))
            Update-ConfigurationErrorCount
        }

        Write-Debug ""${debugPrefix}    Processing completed '$key' ]""
    }

    if($keyValues)
    {
        $keyValues = $keyValues.Substring(2) # Remove the leading '::'
        Add-NodeKeys $keyValues $keywordName
        Test-ConflictingResources $keywordName $canonicalizedValue $keywordData
    }

# update OMI_ConfigurationDocument
    if($IsMetaConfig)
    {
        if($keywordData.ResourceName -eq 'OMI_ConfigurationDocument')
        {
            if($(Get-PSMetaConfigurationProcessed))
            {
                $PSMetaConfigDocumentInstVersionInfo = Get-PSMetaConfigDocumentInstVersionInfo
                $canonicalizedValue['MinimumCompatibleVersion']=$PSMetaConfigDocumentInstVersionInfo['MinimumCompatibleVersion']
            }
            else
            {
                Set-PSMetaConfigDocInsProcessedBeforeMeta
                $canonicalizedValue['MinimumCompatibleVersion']='1.0.0'
            }
        }

        if(($keywordData.ResourceName -eq 'MSFT_WebDownloadManager') `
            -or ($keywordData.ResourceName -eq 'MSFT_FileDownloadManager') `
            -or ($keywordData.ResourceName -eq 'MSFT_WebResourceManager') `
            -or ($keywordData.ResourceName -eq 'MSFT_FileResourceManager') `
            -or ($keywordData.ResourceName -eq 'MSFT_WebReportManager') `
            -or ($keywordData.ResourceName -eq 'MSFT_SignatureValidation') `
            -or ($keywordData.ResourceName -eq 'MSFT_PartialConfiguration'))
        {
            Set-PSMetaConfigVersionInfoV2
        }
    }
    elseif($keywordData.ResourceName -eq 'OMI_ConfigurationDocument')
    {
        $canonicalizedValue['MinimumCompatibleVersion']='1.0.0'
        $canonicalizedValue['CompatibleVersionAdditionalProperties']=@('Omi_BaseResource:ConfigurationName')
    }

    if(($keywordData.ResourceName -eq 'MSFT_DSCMetaConfiguration') -or ($keywordData.ResourceName -eq 'MSFT_DSCMetaConfigurationV2'))
    {
        if($canonicalizedValue['DebugMode'] -and @($canonicalizedValue['DebugMode']).Length -gt 1)
        {
# we only allow one value for debug mode now.
            Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::DebugModeShouldHaveOneValue())
            Update-ConfigurationErrorCount
        }
    }

# Generate the MOF text for this resource instance.
# when generate mof text for OMI_ConfigurationDocument we handle below two cases:
# 1. we will add versioning related property based on meta configuration instance already process
# 2. we update the existing OMI_ConfigurationDocument instance if it already exists when process meta configuration instance
    $aliasId = ConvertTo-MOFInstance $keywordName $canonicalizedValue

# If a OMI_ConfigurationDocument is executed outside of a node statement, it becomes the default
# for all nodes that don't have an explicit OMI_ConfigurationDocument declaration
    if ($keywordData.ResourceName -eq 'OMI_ConfigurationDocument' -and -not (Get-PSCurrentConfigurationNode))
    {
        $data = Get-MoFInstanceText $aliasId
        Write-Debug ""${debugPrefix} DEFINING DEFAULT CONFIGURATION DOCUMENT: $data""
        Set-PSDefaultConfigurationDocument $data
    }

    Write-Debug ""${debugPrefix} MOF alias for this resource is '$aliasId'""

# always return the aliasId so the generated file will be well-formed if not valid
    $aliasId

    Write-Debug ""${debugPrefix} RESOURCE PROCESSING COMPLETED. TOTAL ERROR COUNT: $(Get-ConfigurationErrorCount)""

    ";
    }
}