summaryrefslogtreecommitdiff
path: root/BaseTools/Source/Python/Common/FdfParserLite.py
blob: e9b69ff1b9a92a512c7dc8401e647c1fa0035a20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
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
## @file
# parse FDF file
#
#  Copyright (c) 2007, Intel Corporation
#
#  All rights reserved. This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution.  The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#

##
# Import Modules
#
import re
import os

import CommonDataClass.FdfClass

##define T_CHAR_SPACE                ' '
##define T_CHAR_NULL                 '\0'
##define T_CHAR_CR                   '\r'
##define T_CHAR_TAB                  '\t'
##define T_CHAR_LF                   '\n'
##define T_CHAR_SLASH                '/'
##define T_CHAR_BACKSLASH            '\\'
##define T_CHAR_DOUBLE_QUOTE         '\"'
##define T_CHAR_SINGLE_QUOTE         '\''
##define T_CHAR_STAR                 '*'
##define T_CHAR_HASH                 '#'

(T_CHAR_SPACE, T_CHAR_NULL, T_CHAR_CR, T_CHAR_TAB, T_CHAR_LF, T_CHAR_SLASH, \
T_CHAR_BACKSLASH, T_CHAR_DOUBLE_QUOTE, T_CHAR_SINGLE_QUOTE, T_CHAR_STAR, T_CHAR_HASH) = \
(' ', '\0', '\r', '\t', '\n', '/', '\\', '\"', '\'', '*', '#')

SEPERATOR_TUPLE = ('=', '|', ',', '{', '}') 

IncludeFileList = []
# Macro passed from command line, which has greatest priority and can NOT be overridden by those in FDF
InputMacroDict = {}
# All Macro values when parsing file, not replace existing Macro
AllMacroList = []

def GetRealFileLine (File, Line):
    
    InsertedLines = 0
    for Profile in IncludeFileList:
        if Line >= Profile.InsertStartLineNumber and Line < Profile.InsertStartLineNumber + Profile.InsertAdjust + len(Profile.FileLinesList):
            return (Profile.FileName, Line - Profile.InsertStartLineNumber + 1)
        if Line >= Profile.InsertStartLineNumber + Profile.InsertAdjust + len(Profile.FileLinesList):
            InsertedLines += Profile.InsertAdjust + len(Profile.FileLinesList)
    
    return (File, Line - InsertedLines)

## The exception class that used to report error messages when parsing FDF
#
# Currently the "ToolName" is set to be "FDF Parser".
#
class Warning (Exception):
    ## The constructor
    #
    #   @param  self        The object pointer
    #   @param  Str         The message to record
    #   @param  File        The FDF name
    #   @param  Line        The Line number that error occurs
    #
    def __init__(self, Str, File = None, Line = None):
        
        FileLineTuple = GetRealFileLine(File, Line)
        self.FileName = FileLineTuple[0]
        self.LineNumber = FileLineTuple[1]
        self.message = Str + str(self.LineNumber)
        self.ToolName = 'FDF Parser'
        
## The MACRO class that used to record macro value data when parsing include file
#
#
class MacroProfile :
    ## The constructor
    #
    #   @param  self        The object pointer
    #   @param  FileName    The file that to be parsed
    #
    def __init__(self, FileName, Line):
        self.FileName = FileName        
        self.DefinedAtLine  = Line
        self.MacroName = None
        self.MacroValue = None

## The Include file content class that used to record file data when parsing include file
#
# May raise Exception when opening file.
#
class IncludeFileProfile :
    ## The constructor
    #
    #   @param  self        The object pointer
    #   @param  FileName    The file that to be parsed
    #
    def __init__(self, FileName):
        self.FileName = FileName
        self.FileLinesList = []
        try:
            fsock = open(FileName, "rb", 0)
            try:
                self.FileLinesList = fsock.readlines()
            finally:
                fsock.close()

        except IOError:
            raise Warning("Error when opening file %s" % FileName)
        
        self.InsertStartLineNumber = None
        self.InsertAdjust = 0

## The FDF content class that used to record file data when parsing FDF
#
# May raise Exception when opening file.
#
class FileProfile :
    ## The constructor
    #
    #   @param  self        The object pointer
    #   @param  FileName    The file that to be parsed
    #
    def __init__(self, FileName):
        self.FileLinesList = []
        try:
            fsock = open(FileName, "rb", 0)
            try:
                self.FileLinesList = fsock.readlines()
            finally:
                fsock.close()

        except IOError:
            raise Warning("Error when opening file %s" % FileName)
        
        self.PcdDict = {}
        self.InfList = []
        
        self.PcdFileLineDict = {}
        self.InfFileLineList = []
        
        self.FdDict = {}
        self.FvDict = {}
        self.CapsuleList = []
#        self.VtfList = []
#        self.RuleDict = {}

## The syntax parser for FDF
#
# PreprocessFile method should be called prior to ParseFile
# CycleReferenceCheck method can detect cycles in FDF contents
#
# GetNext*** procedures mean these procedures will get next token first, then make judgement.
# Get*** procedures mean these procedures will make judgement on current token only.
#        
class FdfParser(object):
    ## The constructor
    #
    #   @param  self        The object pointer
    #   @param  FileName    The file that to be parsed
    #
    def __init__(self, FileName):
        self.Profile = FileProfile(FileName)
        self.FileName = FileName
        self.CurrentLineNumber = 1
        self.CurrentOffsetWithinLine = 0
        self.CurrentFdName = None
        self.CurrentFvName = None
        self.__Token = ""
        self.__SkippedChars = ""
        
        self.__WipeOffArea = []

    ## __IsWhiteSpace() method
    #
    #   Whether char at current FileBufferPos is whitespace
    #
    #   @param  self        The object pointer
    #   @param  Char        The char to test
    #   @retval True        The char is a kind of white space
    #   @retval False       The char is NOT a kind of white space
    #
    def __IsWhiteSpace(self, Char):
        if Char in (T_CHAR_NULL, T_CHAR_CR, T_CHAR_SPACE, T_CHAR_TAB, T_CHAR_LF):
            return True
        else:
            return False

    ## __SkipWhiteSpace() method
    #
    #   Skip white spaces from current char, return number of chars skipped
    #
    #   @param  self        The object pointer
    #   @retval Count       The number of chars skipped
    #
    def __SkipWhiteSpace(self):
        Count = 0
        while not self.__EndOfFile():
            Count += 1
            if self.__CurrentChar() in (T_CHAR_NULL, T_CHAR_CR, T_CHAR_LF, T_CHAR_SPACE, T_CHAR_TAB):
                self.__SkippedChars += str(self.__CurrentChar())
                self.__GetOneChar()

            else:
                Count = Count - 1
                return Count

    ## __EndOfFile() method
    #
    #   Judge current buffer pos is at file end
    #
    #   @param  self        The object pointer
    #   @retval True        Current File buffer position is at file end
    #   @retval False       Current File buffer position is NOT at file end
    #
    def __EndOfFile(self):
        NumberOfLines = len(self.Profile.FileLinesList)
        SizeOfLastLine = len(self.Profile.FileLinesList[-1])
        if self.CurrentLineNumber == NumberOfLines and self.CurrentOffsetWithinLine >= SizeOfLastLine - 1:
            return True
        elif self.CurrentLineNumber > NumberOfLines:
            return True
        else:
            return False

    ## __EndOfLine() method
    #
    #   Judge current buffer pos is at line end
    #
    #   @param  self        The object pointer
    #   @retval True        Current File buffer position is at line end
    #   @retval False       Current File buffer position is NOT at line end
    #
    def __EndOfLine(self):
        if self.CurrentLineNumber > len(self.Profile.FileLinesList):
            return True
        SizeOfCurrentLine = len(self.Profile.FileLinesList[self.CurrentLineNumber - 1])
        if self.CurrentOffsetWithinLine >= SizeOfCurrentLine:
            return True
        else:
            return False
    
    ## Rewind() method
    #
    #   Reset file data buffer to the initial state
    #
    #   @param  self        The object pointer
    #
    def Rewind(self):
        self.CurrentLineNumber = 1
        self.CurrentOffsetWithinLine = 0
    
    ## __UndoOneChar() method
    #
    #   Go back one char in the file buffer
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully go back one char
    #   @retval False       Not able to go back one char as file beginning reached
    #    
    def __UndoOneChar(self):
        
        if self.CurrentLineNumber == 1 and self.CurrentOffsetWithinLine == 0:
            return False
        elif self.CurrentOffsetWithinLine == 0:
            self.CurrentLineNumber -= 1
            self.CurrentOffsetWithinLine = len(self.__CurrentLine()) - 1
        else:
            self.CurrentOffsetWithinLine -= 1
        return True
        
    ## __GetOneChar() method
    #
    #   Move forward one char in the file buffer
    #
    #   @param  self        The object pointer
    #  
    def __GetOneChar(self):
        if self.CurrentOffsetWithinLine == len(self.Profile.FileLinesList[self.CurrentLineNumber - 1]) - 1:
            self.CurrentLineNumber += 1
            self.CurrentOffsetWithinLine = 0
        else:
            self.CurrentOffsetWithinLine += 1

    ## __CurrentChar() method
    #
    #   Get the char pointed to by the file buffer pointer
    #
    #   @param  self        The object pointer
    #   @retval Char        Current char
    #  
    def __CurrentChar(self):
        return self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine]
    
    ## __NextChar() method
    #
    #   Get the one char pass the char pointed to by the file buffer pointer
    #
    #   @param  self        The object pointer
    #   @retval Char        Next char
    #
    def __NextChar(self):
        if self.CurrentOffsetWithinLine == len(self.Profile.FileLinesList[self.CurrentLineNumber - 1]) - 1:
            return self.Profile.FileLinesList[self.CurrentLineNumber][0]
        else:
            return self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine + 1]
        
    ## __SetCurrentCharValue() method
    #
    #   Modify the value of current char
    #
    #   @param  self        The object pointer
    #   @param  Value       The new value of current char
    #
    def __SetCurrentCharValue(self, Value):
        self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine] = Value
        
    ## __CurrentLine() method
    #
    #   Get the list that contains current line contents
    #
    #   @param  self        The object pointer
    #   @retval List        current line contents
    #
    def __CurrentLine(self):
        return self.Profile.FileLinesList[self.CurrentLineNumber - 1]
        
    def __StringToList(self):
        self.Profile.FileLinesList = [list(s) for s in self.Profile.FileLinesList]
        self.Profile.FileLinesList[-1].append(' ')

    def __ReplaceMacros(self, Str, File, Line):
        MacroEnd = 0
        while Str.find('$(', MacroEnd) >= 0:
            MacroStart = Str.find('$(', MacroEnd)
            if Str.find(')', MacroStart) > 0:
                MacroEnd = Str.find(')', MacroStart)
                Name = Str[MacroStart + 2 : MacroEnd]
                Value = None
                if Name in InputMacroDict:
                    Value = InputMacroDict[Name]
                   
                else:
                    for Profile in AllMacroList:
                        if Profile.FileName == File and Profile.MacroName == Name and Profile.DefinedAtLine <= Line:
                            Value = Profile.MacroValue
                            
                if Value != None:
                    Str = Str.replace('$(' + Name + ')', Value)
                    MacroEnd = MacroStart + len(Value) 
                
            else:
                raise Warning("Macro not complete At Line ", self.FileName, self.CurrentLineNumber)
        return Str
    
    def __ReplaceFragment(self, StartPos, EndPos, Value = ' '):
        if StartPos[0] == EndPos[0]:
            Offset = StartPos[1]
            while Offset <= EndPos[1]:
                self.Profile.FileLinesList[StartPos[0]][Offset] = Value
                Offset += 1
            return
        
        Offset = StartPos[1]
        while self.Profile.FileLinesList[StartPos[0]][Offset] not in ('\r', '\n'):
            self.Profile.FileLinesList[StartPos[0]][Offset] = Value
            Offset += 1
        
        Line = StartPos[0]
        while Line < EndPos[0]:
            Offset = 0
            while self.Profile.FileLinesList[Line][Offset] not in ('\r', '\n'):
                self.Profile.FileLinesList[Line][Offset] = Value
                Offset += 1
            Line += 1
            
        Offset = 0
        while Offset <= EndPos[1]:
            self.Profile.FileLinesList[EndPos[0]][Offset] = Value
            Offset += 1
            
    
    ## PreprocessFile() method
    #
    #   Preprocess file contents, replace comments with spaces.
    #   In the end, rewind the file buffer pointer to the beginning
    #   BUGBUG: No !include statement processing contained in this procedure
    #   !include statement should be expanded at the same FileLinesList[CurrentLineNumber - 1]
    #
    #   @param  self        The object pointer
    #   
    def PreprocessFile(self):
        
        self.Rewind()
        InComment = False
        DoubleSlashComment = False
        HashComment = False
        # HashComment in quoted string " " is ignored.
        InString = False    
        
        while not self.__EndOfFile():
            
            if self.__CurrentChar() == T_CHAR_DOUBLE_QUOTE and not InComment:
                InString = not InString
            # meet new line, then no longer in a comment for // and '#'
            if self.__CurrentChar() == T_CHAR_LF:
                self.CurrentLineNumber += 1
                self.CurrentOffsetWithinLine = 0
                if InComment and DoubleSlashComment:
                    InComment = False
                    DoubleSlashComment = False
                if InComment and HashComment:
                    InComment = False
                    HashComment = False
            # check for */ comment end
            elif InComment and not DoubleSlashComment and not HashComment and self.__CurrentChar() == T_CHAR_STAR and self.__NextChar() == T_CHAR_SLASH:
                self.__SetCurrentCharValue(T_CHAR_SPACE)
                self.__GetOneChar()
                self.__SetCurrentCharValue(T_CHAR_SPACE)
                self.__GetOneChar()
                InComment = False
            # set comments to spaces
            elif InComment:
                self.__SetCurrentCharValue(T_CHAR_SPACE)
                self.__GetOneChar()
            # check for // comment
            elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_SLASH and not self.__EndOfLine():
                InComment = True
                DoubleSlashComment = True
            # check for '#' comment
            elif self.__CurrentChar() == T_CHAR_HASH and not self.__EndOfLine() and not InString:
                InComment = True
                HashComment = True
            # check for /* comment start
            elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_STAR:
                self.__SetCurrentCharValue( T_CHAR_SPACE)
                self.__GetOneChar()
                self.__SetCurrentCharValue( T_CHAR_SPACE)
                self.__GetOneChar()
                InComment = True
            else:
                self.__GetOneChar()
        
        # restore from ListOfList to ListOfString
        self.Profile.FileLinesList = ["".join(list) for list in self.Profile.FileLinesList]
        self.Rewind()

    ## PreprocessIncludeFile() method
    #
    #   Preprocess file contents, replace !include statements with file contents.
    #   In the end, rewind the file buffer pointer to the beginning
    #
    #   @param  self        The object pointer
    #   
    def PreprocessIncludeFile(self):
        
        while self.__GetNextToken():
            
            if self.__Token == '!include':
                IncludeLine = self.CurrentLineNumber
                IncludeOffset = self.CurrentOffsetWithinLine - len('!include')
                if not self.__GetNextToken():
                    raise Warning("expected include file name At Line ", self.FileName, self.CurrentLineNumber)
                IncFileName = self.__Token
                if not os.path.isabs(IncFileName):
                    if IncFileName.startswith('$(WORKSPACE)'):
                        Str = IncFileName.replace('$(WORKSPACE)', os.environ.get('WORKSPACE'))
                        if os.path.exists(Str):
                            if not os.path.isabs(Str):
                                Str = os.path.abspath(Str)
                        IncFileName = Str
                    else:
                        # file is in the same dir with FDF file
                        FullFdf = self.FileName
                        if not os.path.isabs(self.FileName):
                            FullFdf = os.path.join(os.environ.get('WORKSPACE'), self.FileName)
                
                        IncFileName = os.path.join(os.path.dirname(FullFdf), IncFileName)
                    
                if not os.path.exists(os.path.normpath(IncFileName)):
                    raise Warning("Include file not exists At Line ", self.FileName, self.CurrentLineNumber)
                
                IncFileProfile = IncludeFileProfile(os.path.normpath(IncFileName))
                
                CurrentLine = self.CurrentLineNumber
                CurrentOffset = self.CurrentOffsetWithinLine
                # list index of the insertion, note that line number is 'CurrentLine + 1'
                InsertAtLine = CurrentLine
                IncFileProfile.InsertStartLineNumber = InsertAtLine + 1
                # deal with remaining portions after "!include filename", if exists.
                if self.__GetNextToken():
                    if self.CurrentLineNumber == CurrentLine:
                        RemainingLine = self.__CurrentLine()[CurrentOffset:]
                        self.Profile.FileLinesList.insert(self.CurrentLineNumber, RemainingLine)
                        IncFileProfile.InsertAdjust += 1
                        self.CurrentLineNumber += 1
                        self.CurrentOffsetWithinLine = 0
                
                for Line in IncFileProfile.FileLinesList:
                    self.Profile.FileLinesList.insert(InsertAtLine, Line)
                    self.CurrentLineNumber += 1
                    InsertAtLine += 1    
                
                IncludeFileList.append(IncFileProfile)
                
                # comment out the processed include file statement
                TempList = list(self.Profile.FileLinesList[IncludeLine - 1])
                TempList.insert(IncludeOffset, '#')
                self.Profile.FileLinesList[IncludeLine - 1] = ''.join(TempList)
                
        self.Rewind()

    ## PreprocessIncludeFile() method
    #
    #   Preprocess file contents, replace !include statements with file contents.
    #   In the end, rewind the file buffer pointer to the beginning
    #
    #   @param  self        The object pointer
    #   
    def PreprocessConditionalStatement(self):
        # IfList is a stack of if branches with elements of list [Pos, CondSatisfied, BranchDetermined]
        IfList = []
        while self.__GetNextToken():
            if self.__Token == 'DEFINE':
                DefineLine = self.CurrentLineNumber - 1
                DefineOffset = self.CurrentOffsetWithinLine - len('DEFINE')
                if not self.__GetNextToken():
                    raise Warning("expected Macro name At Line ", self.FileName, self.CurrentLineNumber)
                Macro = self.__Token
                if not self.__IsToken( "="):
                    raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                
                if not self.__GetNextToken():
                    raise Warning("expected value At Line ", self.FileName, self.CurrentLineNumber)
                
                if self.__GetStringData():
                    pass
                Value = self.__Token
                if not Macro in InputMacroDict:
                    FileLineTuple = GetRealFileLine(self.FileName, DefineLine + 1)
                    MacProfile = MacroProfile(FileLineTuple[0], FileLineTuple[1])
                    MacProfile.MacroName = Macro
                    MacProfile.MacroValue = Value
                    AllMacroList.append(MacProfile)
                self.__WipeOffArea.append(((DefineLine, DefineOffset), (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
            
            elif self.__Token in ('!ifdef', '!ifndef', '!if'):
                IfStartPos = (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - len(self.__Token))
                IfList.append([IfStartPos, None, None])
                CondLabel = self.__Token
                
                if not self.__GetNextToken():
                    raise Warning("expected Macro name At Line ", self.FileName, self.CurrentLineNumber)
                MacroName = self.__Token
                NotFlag = False
                if MacroName.startswith('!'):
                    NotFlag = True
                    MacroName = MacroName[1:]

                NotDefineFlag = False
                if CondLabel == '!ifndef':
                    NotDefineFlag = True
                if CondLabel == '!ifdef' or CondLabel == '!ifndef':
                    if NotFlag:
                        raise Warning("'NOT' operation not allowed for Macro name At Line ", self.FileName, self.CurrentLineNumber)
                    
                if CondLabel == '!if':
                        
                    if not self.__GetNextOp():
                        raise Warning("expected !endif At Line ", self.FileName, self.CurrentLineNumber)
                    
                    if self.__Token in ('!=', '==', '>', '<', '>=', '<='):
                        Op = self.__Token
                        if not self.__GetNextToken():
                            raise Warning("expected value At Line ", self.FileName, self.CurrentLineNumber)
                        if self.__GetStringData():
                            pass
                        MacroValue = self.__Token
                        ConditionSatisfied = self.__EvaluateConditional(MacroName, IfList[-1][0][0] + 1, Op, MacroValue)
                        if NotFlag:
                            ConditionSatisfied = not ConditionSatisfied
                        BranchDetermined = ConditionSatisfied
                    else:
                        self.CurrentOffsetWithinLine -= len(self.__Token)                        
                        ConditionSatisfied = self.__EvaluateConditional(MacroName, IfList[-1][0][0] + 1, None, 'Bool')
                        if NotFlag:
                            ConditionSatisfied = not ConditionSatisfied
                        BranchDetermined = ConditionSatisfied
                    IfList[-1] = [IfList[-1][0], ConditionSatisfied, BranchDetermined]
                    if ConditionSatisfied:
                        self.__WipeOffArea.append((IfList[-1][0], (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
                        
                else:
                    ConditionSatisfied = self.__EvaluateConditional(MacroName, IfList[-1][0][0] + 1)
                    if NotDefineFlag:
                        ConditionSatisfied = not ConditionSatisfied
                    BranchDetermined = ConditionSatisfied
                    IfList[-1] = [IfList[-1][0], ConditionSatisfied, BranchDetermined]
                    if ConditionSatisfied:
                        self.__WipeOffArea.append((IfStartPos, (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
                    
            elif self.__Token in ('!elseif', '!else'):
                ElseStartPos = (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - len(self.__Token))
                if len(IfList) <= 0:
                    raise Warning("Missing !if statement At Line ", self.FileName, self.CurrentLineNumber)
                if IfList[-1][1]:
                    IfList[-1] = [ElseStartPos, False, True]
                    self.__WipeOffArea.append((ElseStartPos, (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
                else:
                    self.__WipeOffArea.append((IfList[-1][0], ElseStartPos))
                    IfList[-1] = [ElseStartPos, True, IfList[-1][2]]
                    if self.__Token == '!elseif':
                        if not self.__GetNextToken():
                            raise Warning("expected Macro name At Line ", self.FileName, self.CurrentLineNumber)
                        MacroName = self.__Token
                        NotFlag = False
                        if MacroName.startswith('!'):
                            NotFlag = True
                            MacroName = MacroName[1:]

                        if not self.__GetNextOp():
                            raise Warning("expected !endif At Line ", self.FileName, self.CurrentLineNumber)
                    
                        if self.__Token in ('!=', '==', '>', '<', '>=', '<='):
                            Op = self.__Token
                            if not self.__GetNextToken():
                                raise Warning("expected value At Line ", self.FileName, self.CurrentLineNumber)
                            if self.__GetStringData():
                                pass
                            MacroValue = self.__Token
                            ConditionSatisfied = self.__EvaluateConditional(MacroName, IfList[-1][0][0] + 1, Op, MacroValue)
                            if NotFlag:
                                ConditionSatisfied = not ConditionSatisfied

                        else:
                            self.CurrentOffsetWithinLine -= len(self.__Token)                        
                            ConditionSatisfied = self.__EvaluateConditional(MacroName, IfList[-1][0][0] + 1, None, 'Bool')
                            if NotFlag:
                                ConditionSatisfied = not ConditionSatisfied

                        IfList[-1] = [IfList[-1][0], ConditionSatisfied, IfList[-1][2]]
                    
                    if IfList[-1][1]:
                        if IfList[-1][2]:
                            IfList[-1][1] = False
                        else:
                            IfList[-1][2] = True
                            self.__WipeOffArea.append((IfList[-1][0], (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))

                
            elif self.__Token == '!endif':
                if IfList[-1][1]:
                    self.__WipeOffArea.append(((self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - len('!endif')), (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
                else:
                    self.__WipeOffArea.append((IfList[-1][0], (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
                
                IfList.pop()
                
                    
        if len(IfList) > 0:
            raise Warning("Missing !endif At Line ", self.FileName, self.CurrentLineNumber)
        self.Rewind()

    def __EvaluateConditional(self, Name, Line, Op = None, Value = None):
        
        FileLineTuple = GetRealFileLine(self.FileName, Line)
        if Name in InputMacroDict:
            MacroValue = InputMacroDict[Name]
            if Op == None:
                if Value == 'Bool' and MacroValue == None or MacroValue.upper() == 'FALSE':
                    return False
                return True
            elif Op == '!=':
                if Value != MacroValue:
                    return True
                else:
                    return False
            elif Op == '==':
                if Value == MacroValue:
                    return True
                else:
                    return False
            else:
                if (self.__IsHex(Value) or Value.isdigit()) and (self.__IsHex(MacroValue) or (MacroValue != None and MacroValue.isdigit())):
                    InputVal = long(Value, 0)
                    MacroVal = long(MacroValue, 0)
                    if Op == '>':
                        if MacroVal > InputVal:
                            return True
                        else:
                            return False
                    elif Op == '>=':
                        if MacroVal >= InputVal:
                            return True
                        else:
                            return False
                    elif Op == '<':
                        if MacroVal < InputVal:
                            return True
                        else:
                            return False
                    elif Op == '<=':
                        if MacroVal <= InputVal:
                            return True
                        else:
                            return False
                    else:
                        return False
                else:
                    raise Warning("Value %s is not a number At Line ", self.FileName, Line)
                
        for Profile in AllMacroList:
            if Profile.FileName == FileLineTuple[0] and Profile.MacroName == Name and Profile.DefinedAtLine <= FileLineTuple[1]:
                if Op == None:
                    if Value == 'Bool' and Profile.MacroValue == None or Profile.MacroValue.upper() == 'FALSE':
                        return False
                    return True
                elif Op == '!=':
                    if Value != Profile.MacroValue:
                        return True
                    else:
                        return False
                elif Op == '==':
                    if Value == Profile.MacroValue:
                        return True
                    else:
                        return False
                else:
                    if (self.__IsHex(Value) or Value.isdigit()) and (self.__IsHex(Profile.MacroValue) or (Profile.MacroValue != None and Profile.MacroValue.isdigit())):
                        InputVal = long(Value, 0)
                        MacroVal = long(Profile.MacroValue, 0)
                        if Op == '>':
                            if MacroVal > InputVal:
                                return True
                            else:
                                return False
                        elif Op == '>=':
                            if MacroVal >= InputVal:
                                return True
                            else:
                                return False
                        elif Op == '<':
                            if MacroVal < InputVal:
                                return True
                            else:
                                return False
                        elif Op == '<=':
                            if MacroVal <= InputVal:
                                return True
                            else:
                                return False
                        else:
                            return False
                    else:
                        raise Warning("Value %s is not a number At Line ", self.FileName, Line)
        
        return False

    ## __IsToken() method
    #
    #   Check whether input string is found from current char position along
    #   If found, the string value is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @param  String      The string to search
    #   @param  IgnoreCase  Indicate case sensitive/non-sensitive search, default is case sensitive
    #   @retval True        Successfully find string, file buffer pointer moved forward
    #   @retval False       Not able to find string, file buffer pointer not changed
    #
    def __IsToken(self, String, IgnoreCase = False):
        self.__SkipWhiteSpace()

        # Only consider the same line, no multi-line token allowed
        StartPos = self.CurrentOffsetWithinLine
        index = -1
        if IgnoreCase:
            index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].upper().find(String.upper()) 
        else:
            index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].find(String)
        if index == 0:
            self.CurrentOffsetWithinLine += len(String)
            self.__Token = self.__CurrentLine()[StartPos : self.CurrentOffsetWithinLine]
            return True
        return False

    ## __IsKeyword() method
    #
    #   Check whether input keyword is found from current char position along, whole word only!
    #   If found, the string value is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @param  Keyword     The string to search
    #   @param  IgnoreCase  Indicate case sensitive/non-sensitive search, default is case sensitive
    #   @retval True        Successfully find string, file buffer pointer moved forward
    #   @retval False       Not able to find string, file buffer pointer not changed
    #
    def __IsKeyword(self, KeyWord, IgnoreCase = False):
        self.__SkipWhiteSpace()

        # Only consider the same line, no multi-line token allowed
        StartPos = self.CurrentOffsetWithinLine
        index = -1
        if IgnoreCase:
            index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].upper().find(KeyWord.upper()) 
        else:
            index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].find(KeyWord)
        if index == 0:
            followingChar = self.__CurrentLine()[self.CurrentOffsetWithinLine + len(KeyWord)]
            if not str(followingChar).isspace() and followingChar not in SEPERATOR_TUPLE:
                return False
            self.CurrentOffsetWithinLine += len(KeyWord)
            self.__Token = self.__CurrentLine()[StartPos : self.CurrentOffsetWithinLine]
            return True
        return False

    ## __GetNextWord() method
    #
    #   Get next C name from file lines
    #   If found, the string value is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a C name string, file buffer pointer moved forward
    #   @retval False       Not able to find a C name string, file buffer pointer not changed
    #
    def __GetNextWord(self):
        self.__SkipWhiteSpace()
        if self.__EndOfFile():
            return False
        
        TempChar = self.__CurrentChar()
        StartPos = self.CurrentOffsetWithinLine
        if (TempChar >= 'a' and TempChar <= 'z') or (TempChar >= 'A' and TempChar <= 'Z') or TempChar == '_':
            self.__GetOneChar()
            while not self.__EndOfLine():
                TempChar = self.__CurrentChar()
                if (TempChar >= 'a' and TempChar <= 'z') or (TempChar >= 'A' and TempChar <= 'Z') \
                or (TempChar >= '0' and TempChar <= '9') or TempChar == '_' or TempChar == '-':
                    self.__GetOneChar()
                    
                else:
                    break

            self.__Token = self.__CurrentLine()[StartPos : self.CurrentOffsetWithinLine]
            return True
            
        return False
    
    ## __GetNextToken() method
    #
    #   Get next token unit before a seperator
    #   If found, the string value is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a token unit, file buffer pointer moved forward
    #   @retval False       Not able to find a token unit, file buffer pointer not changed
    #
    def __GetNextToken(self):
        # Skip leading spaces, if exist.
        self.__SkipWhiteSpace()
        if self.__EndOfFile():
            return False
        # Record the token start position, the position of the first non-space char.
        StartPos = self.CurrentOffsetWithinLine
        StartLine = self.CurrentLineNumber
        while not self.__EndOfLine():
            TempChar = self.__CurrentChar()
            # Try to find the end char that is not a space and not in seperator tuple.
            # That is, when we got a space or any char in the tuple, we got the end of token.
            if not str(TempChar).isspace() and TempChar not in SEPERATOR_TUPLE:
                self.__GetOneChar()
            # if we happen to meet a seperator as the first char, we must proceed to get it.
            # That is, we get a token that is a seperator char. nomally it is the boundary of other tokens.
            elif StartPos == self.CurrentOffsetWithinLine and TempChar in SEPERATOR_TUPLE:
                self.__GetOneChar()
                break
            else:
                break
#        else:
#            return False

        EndPos = self.CurrentOffsetWithinLine
        if self.CurrentLineNumber != StartLine:
            EndPos = len(self.Profile.FileLinesList[StartLine-1])
        self.__Token = self.Profile.FileLinesList[StartLine-1][StartPos : EndPos]
        if StartPos != self.CurrentOffsetWithinLine:
            return True
        else:
            return False
    
    def __GetNextOp(self):
        # Skip leading spaces, if exist.
        self.__SkipWhiteSpace()
        if self.__EndOfFile():
            return False
        # Record the token start position, the position of the first non-space char.
        StartPos = self.CurrentOffsetWithinLine
        while not self.__EndOfLine():
            TempChar = self.__CurrentChar()
            # Try to find the end char that is not a space
            if not str(TempChar).isspace():
                self.__GetOneChar()
            else:
                break
        else:
            return False
        
        if StartPos != self.CurrentOffsetWithinLine:
            self.__Token = self.__CurrentLine()[StartPos : self.CurrentOffsetWithinLine]
            return True
        else:
            return False
    ## __GetNextGuid() method
    #
    #   Get next token unit before a seperator
    #   If found, the GUID string is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a registry format GUID, file buffer pointer moved forward
    #   @retval False       Not able to find a registry format GUID, file buffer pointer not changed
    #
    def __GetNextGuid(self):
        
        if not self.__GetNextToken():
            return False
        p = re.compile('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}')
        if p.match(self.__Token) != None:
            return True
        else:
            self.__UndoToken()
            return False

    ## __UndoToken() method
    #
    #   Go back one token unit in file buffer
    #
    #   @param  self        The object pointer
    #
    def __UndoToken(self):
        self.__UndoOneChar()
        while self.__CurrentChar().isspace():
            if not self.__UndoOneChar():
                self.__GetOneChar()
                return
        
        
        StartPos = self.CurrentOffsetWithinLine
        CurrentLine = self.CurrentLineNumber
        while CurrentLine == self.CurrentLineNumber:
            
            TempChar = self.__CurrentChar()
            # Try to find the end char that is not a space and not in seperator tuple.
            # That is, when we got a space or any char in the tuple, we got the end of token.
            if not str(TempChar).isspace() and not TempChar in SEPERATOR_TUPLE:
                if not self.__UndoOneChar():
                    break
            # if we happen to meet a seperator as the first char, we must proceed to get it.
            # That is, we get a token that is a seperator char. nomally it is the boundary of other tokens.
            elif StartPos == self.CurrentOffsetWithinLine and TempChar in SEPERATOR_TUPLE:
                return
            else:
                break
            
        self.__GetOneChar()
    
    ## __HexDigit() method
    #
    #   Whether char input is a Hex data bit
    #
    #   @param  self        The object pointer
    #   @param  TempChar    The char to test
    #   @retval True        The char is a Hex data bit
    #   @retval False       The char is NOT a Hex data bit
    #
    def __HexDigit(self, TempChar):
        if (TempChar >= 'a' and TempChar <= 'f') or (TempChar >= 'A' and TempChar <= 'F') \
                or (TempChar >= '0' and TempChar <= '9'):
                    return True
        else:
            return False
    
    def __IsHex(self, HexStr):
        if not HexStr.upper().startswith("0X"):
            return False
        if len(self.__Token) <= 2:
            return False
        charList = [c for c in HexStr[2 : ] if not self.__HexDigit( c)]
        if len(charList) == 0:
            return True
        else:
            return False    
    ## __GetNextHexNumber() method
    #
    #   Get next HEX data before a seperator
    #   If found, the HEX data is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a HEX data, file buffer pointer moved forward
    #   @retval False       Not able to find a HEX data, file buffer pointer not changed
    #
    def __GetNextHexNumber(self):
        if not self.__GetNextToken():
            return False
        if self.__IsHex(self.__Token):
            return True
        else:
            self.__UndoToken()
            return False
        
    ## __GetNextDecimalNumber() method
    #
    #   Get next decimal data before a seperator
    #   If found, the decimal data is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a decimal data, file buffer pointer moved forward
    #   @retval False       Not able to find a decimal data, file buffer pointer not changed
    #
    def __GetNextDecimalNumber(self):
        if not self.__GetNextToken():
            return False
        if self.__Token.isdigit():
            return True
        else:
            self.__UndoToken()
            return False
    
    ## __GetNextPcdName() method
    #
    #   Get next PCD token space C name and PCD C name pair before a seperator
    #   If found, the decimal data is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval Tuple       PCD C name and PCD token space C name pair 
    #
    def __GetNextPcdName(self):
        if not self.__GetNextWord():
            raise Warning("expected PcdTokenSpaceCName.PcdCName At Line ", self.FileName, self.CurrentLineNumber)
        pcdTokenSpaceCName = self.__Token
        
        if not self.__IsToken( "."):
            raise Warning("expected PcdTokenSpaceCName.PcdCName At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextWord():
            raise Warning("expected PcdTokenSpaceCName.PcdCName At Line ", self.FileName, self.CurrentLineNumber)
        pcdCName = self.__Token
        
        return (pcdCName, pcdTokenSpaceCName) 
            
    ## __GetStringData() method
    #
    #   Get string contents quoted in ""
    #   If found, the decimal data is put into self.__Token
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a string data, file buffer pointer moved forward
    #   @retval False       Not able to find a string data, file buffer pointer not changed
    #    
    def __GetStringData(self):
        if self.__Token.startswith("\"") or self.__Token.startswith("L\""):
            self.__UndoToken()
            self.__SkipToToken("\"")
            currentLineNumber = self.CurrentLineNumber
            
            if not self.__SkipToToken("\""):
                raise Warning("Missing Quote \" for String At Line ", self.FileName, self.CurrentLineNumber)
            if currentLineNumber != self.CurrentLineNumber:
                raise Warning("Missing Quote \" for String At Line ", self.FileName, self.CurrentLineNumber)
            self.__Token = self.__SkippedChars.rstrip('\"')
            return True
        
        elif self.__Token.startswith("\'") or self.__Token.startswith("L\'"):
            self.__UndoToken()
            self.__SkipToToken("\'")
            currentLineNumber = self.CurrentLineNumber
            
            if not self.__SkipToToken("\'"):
                raise Warning("Missing Quote \' for String At Line ", self.FileName, self.CurrentLineNumber)
            if currentLineNumber != self.CurrentLineNumber:
                raise Warning("Missing Quote \' for String At Line ", self.FileName, self.CurrentLineNumber)
            self.__Token = self.__SkippedChars.rstrip('\'')
            return True
        
        else:
            return False
            
    ## __SkipToToken() method
    #
    #   Search forward in file buffer for the string
    #   The skipped chars are put into self.__SkippedChars
    #
    #   @param  self        The object pointer
    #   @param  String      The string to search
    #   @param  IgnoreCase  Indicate case sensitive/non-sensitive search, default is case sensitive
    #   @retval True        Successfully find the string, file buffer pointer moved forward
    #   @retval False       Not able to find the string, file buffer pointer not changed
    #
    def __SkipToToken(self, String, IgnoreCase = False):
        StartPos = self.GetFileBufferPos()
        
        self.__SkippedChars = ""
        while not self.__EndOfFile():
            index = -1
            if IgnoreCase:
                index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].upper().find(String.upper()) 
            else:
                index = self.__CurrentLine()[self.CurrentOffsetWithinLine : ].find(String)
            if index == 0:
                self.CurrentOffsetWithinLine += len(String)
                self.__SkippedChars += String
                return True
            self.__SkippedChars += str(self.__CurrentChar())
            self.__GetOneChar()
            
        self.SetFileBufferPos( StartPos)
        self.__SkippedChars = ""
        return False

    ## GetFileBufferPos() method
    #
    #   Return the tuple of current line and offset within the line
    #
    #   @param  self        The object pointer
    #   @retval Tuple       Line number and offset pair 
    #
    def GetFileBufferPos(self):
        return (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
    
    ## SetFileBufferPos() method
    #
    #   Restore the file buffer position
    #
    #   @param  self        The object pointer
    #   @param  Pos         The new file buffer position
    #
    def SetFileBufferPos(self, Pos):
        (self.CurrentLineNumber, self.CurrentOffsetWithinLine) = Pos
            
    ## ParseFile() method
    #
    #   Parse the file profile buffer to extract fd, fv ... information
    #   Exception will be raised if syntax error found
    #
    #   @param  self        The object pointer
    #
    def ParseFile(self):

        try:
            self.__StringToList()
            self.PreprocessFile()
            self.PreprocessIncludeFile()
            self.__StringToList()
            self.PreprocessFile()
            self.PreprocessConditionalStatement()
            self.__StringToList()
            for Pos in self.__WipeOffArea:
                self.__ReplaceFragment(Pos[0], Pos[1])
            self.Profile.FileLinesList = ["".join(list) for list in self.Profile.FileLinesList]
            
            while self.__GetDefines():
                pass
            
            Index = 0
            while Index < len(self.Profile.FileLinesList):
                FileLineTuple = GetRealFileLine(self.FileName, Index + 1)
                self.Profile.FileLinesList[Index] = self.__ReplaceMacros(self.Profile.FileLinesList[Index], FileLineTuple[0], FileLineTuple[1])
                Index += 1
                
            while self.__GetFd():
                pass

            while self.__GetFv():
                pass

            while self.__GetCapsule():
                pass

#            while self.__GetVtf():
#                pass
#
#            while self.__GetRule():
#                pass
            

        except Warning, X:
            self.__UndoToken()
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            X.message += '\nGot Token: \"%s\" from File %s\n' % (self.__Token, FileLineTuple[0]) + \
                'Previous Token: \"%s\" At line: %d, Offset Within Line: %d\n' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :].rstrip('\n').rstrip('\r'), FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise

    ## __GetDefines() method
    #
    #   Get Defines section contents and store its data into AllMacrosList
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a Defines
    #   @retval False       Not able to find a Defines
    #
    def __GetDefines(self):

        if not self.__GetNextToken():
            return False

        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[DEFINES"):
            if not S.startswith("[FD.") and not S.startswith("[FV.") and not S.startswith("[CAPSULE.") \
                and not S.startswith("[VTF.") and not S.startswith("[RULE.") and not S.startswith("[OPTIONROM."):
                raise Warning("Unknown section or section appear sequence error (The correct sequence should be [DEFINES], [FD.], [FV.], [Capsule.], [VTF.], [Rule.], [OptionRom.])", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False

        self.__UndoToken()
        if not self.__IsToken("[DEFINES", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            #print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
            #        % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("expected [DEFINES", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken( "]"):
            raise Warning("expected ']'", self.FileName, self.CurrentLineNumber)

        while self.__GetNextWord():
            Macro = self.__Token
            
            if not self.__IsToken("="):
                raise Warning("expected '='", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken() or self.__Token.startswith('['):
                raise Warning("expected MACRO value", self.FileName, self.CurrentLineNumber)
            Value = self.__Token
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            MacProfile = MacroProfile(FileLineTuple[0], FileLineTuple[1])
            MacProfile.MacroName = Macro
            MacProfile.MacroValue = Value
            AllMacroList.append(MacProfile)

        return False

    ## __GetFd() method
    #
    #   Get FD section contents and store its data into FD dictionary of self.Profile
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a FD
    #   @retval False       Not able to find a FD
    #
    def __GetFd(self):

        if not self.__GetNextToken():
            return False
        
        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[FD."):
            if not S.startswith("[FV.") and not S.startswith("[CAPSULE.") \
                and not S.startswith("[VTF.") and not S.startswith("[RULE."):
                raise Warning("Unknown section At Line ", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False
        
        self.__UndoToken()
        if not self.__IsToken("[FD.", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("expected [FD.] At Line ", self.FileName, self.CurrentLineNumber)
        
        FdName = self.__GetUiName()
        self.CurrentFdName = FdName.upper()
        
        if not self.__IsToken( "]"):
            raise Warning("expected ']' At Line ", self.FileName, self.CurrentLineNumber)
        
        FdObj = CommonDataClass.FdfClass.FDClassObject()
        FdObj.FdUiName = self.CurrentFdName
        self.Profile.FdDict[self.CurrentFdName] = FdObj
        Status = self.__GetCreateFile(FdObj)
        if not Status:
            raise Warning("FD name error At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetTokenStatements(FdObj):
            return False
        
        self.__GetDefineStatements(FdObj)

        self.__GetSetStatements(FdObj)

        if not self.__GetRegionLayout(FdObj):
            raise Warning("expected region layout At Line ", self.FileName, self.CurrentLineNumber)
            
        while self.__GetRegionLayout(FdObj):
            pass
        return True
    
    ## __GetUiName() method
    #
    #   Return the UI name of a section
    #
    #   @param  self        The object pointer
    #   @retval FdName      UI name
    #
    def __GetUiName(self):
        FdName = ""
        if self.__GetNextWord():
            FdName = self.__Token
            
        return FdName

    ## __GetCreateFile() method
    #
    #   Return the output file name of object
    #
    #   @param  self        The object pointer
    #   @param  Obj         object whose data will be stored in file
    #   @retval FdName      UI name
    #
    def __GetCreateFile(self, Obj):

        if self.__IsKeyword( "CREATE_FILE"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                
            if not self.__GetNextToken():
                raise Warning("expected file name At Line ", self.FileName, self.CurrentLineNumber)
                
            FileName = self.__Token
            Obj.CreateFileName = FileName

        return True

    ## __GetTokenStatements() method
    #
    #   Get token statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom token statement is got
    #   @retval True        Successfully find a token statement
    #   @retval False       Not able to find a token statement
    #
    def __GetTokenStatements(self, Obj):
        if not self.__IsKeyword( "BaseAddress"):
            raise Warning("BaseAddress missing At Line ", self.FileName, self.CurrentLineNumber)
           
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__GetNextHexNumber():
            raise Warning("expected Hex base address At Line ", self.FileName, self.CurrentLineNumber)
            
        Obj.BaseAddress = self.__Token
        
        if self.__IsToken( "|"):
            pcdPair = self.__GetNextPcdName()
            Obj.BaseAddressPcd = pcdPair
            self.Profile.PcdDict[pcdPair] = long(Obj.BaseAddress, 0)
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.PcdFileLineDict[pcdPair] = FileLineTuple
            
        if not self.__IsKeyword( "Size"):
            raise Warning("Size missing At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__GetNextHexNumber():
            raise Warning("expected Hex size At Line ", self.FileName, self.CurrentLineNumber)
            
      
        Obj.Size = long(self.__Token, 0)

        if self.__IsToken( "|"):
            pcdPair = self.__GetNextPcdName()
            Obj.SizePcd = pcdPair
            self.Profile.PcdDict[pcdPair] = Obj.Size
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.PcdFileLineDict[pcdPair] = FileLineTuple
                    
        if not self.__IsKeyword( "ErasePolarity"):
            raise Warning("ErasePolarity missing At Line ", self.FileName, self.CurrentLineNumber)
           
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__GetNextToken():
            raise Warning("expected Erase Polarity At Line ", self.FileName, self.CurrentLineNumber)
            
        if self.__Token != "1" and self.__Token != "0":
            raise Warning("expected 1 or 0 Erase Polarity At Line ", self.FileName, self.CurrentLineNumber)
            
        Obj.ErasePolarity = self.__Token

        Status = self.__GetBlockStatements(Obj)
        return Status
    
    ## __GetAddressStatements() method
    #
    #   Get address statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom address statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetAddressStatements(self, Obj):
        
        if self.__IsKeyword("BsBaseAddress"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextDecimalNumber() and not self.__GetNextHexNumber():
                raise Warning("expected address At Line ", self.FileName, self.CurrentLineNumber)
                
            BsAddress = long(self.__Token, 0)
            Obj.BsBaseAddress = BsAddress
            
        if self.__IsKeyword("RtBaseAddress"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextDecimalNumber() and not self.__GetNextHexNumber():
                raise Warning("expected address At Line ", self.FileName, self.CurrentLineNumber)
                
            RtAddress = long(self.__Token, 0)
            Obj.RtBaseAddress = RtAddress
    
    ## __GetBlockStatements() method
    #
    #   Get block statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom block statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetBlockStatements(self, Obj):
        
        if not self.__GetBlockStatement(Obj):
            #set default block size is 1
            Obj.BlockSizeList.append((1, Obj.Size, None))
            return True

        while self.__GetBlockStatement(Obj):
            pass
        
        for Item in Obj.BlockSizeList:
            if Item[0] == None or Item[1] == None:
                raise Warning("expected block statement for Fd Section", self.FileName, self.CurrentLineNumber)

        return True
    
    ## __GetBlockStatement() method
    #
    #   Get block statement
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom block statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetBlockStatement(self, Obj):
        if not self.__IsKeyword( "BlockSize"):
            return False
        
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__GetNextHexNumber() and not self.__GetNextDecimalNumber():
            raise Warning("expected Hex block size At Line ", self.FileName, self.CurrentLineNumber)

        BlockSize = long(self.__Token, 0)
        BlockSizePcd = None
        if self.__IsToken( "|"):
            PcdPair = self.__GetNextPcdName()
            BlockSizePcd = PcdPair
            self.Profile.PcdDict[PcdPair] = BlockSize
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.PcdFileLineDict[pcdPair] = FileLineTuple
            
        BlockNumber = None
        if self.__IsKeyword( "NumBlocks"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                
            if not self.__GetNextDecimalNumber() and not self.__GetNextHexNumber():
                raise Warning("expected block numbers At Line ", self.FileName, self.CurrentLineNumber)
                
            BlockNumber = long(self.__Token, 0)
        
        Obj.BlockSizeList.append((BlockSize, BlockNumber, BlockSizePcd))
        return True

    ## __GetDefineStatements() method
    #
    #   Get define statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom define statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetDefineStatements(self, Obj):
        while self.__GetDefineStatement( Obj):
            pass
    
    ## __GetDefineStatement() method
    #
    #   Get define statement
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom define statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetDefineStatement(self, Obj):
        if self.__IsKeyword("DEFINE"):
            self.__GetNextToken()
            Macro = self.__Token
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                
            if not self.__GetNextToken():
                raise Warning("expected value At Line ", self.FileName, self.CurrentLineNumber)

            Value = self.__Token
            Macro = '$(' + Macro + ')'
            Obj.DefineVarDict[Macro] = Value
            return True
        
        return False
    
    ## __GetSetStatements() method
    #
    #   Get set statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom set statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetSetStatements(self, Obj):
        while self.__GetSetStatement(Obj):
            pass

    ## __GetSetStatement() method
    #
    #   Get set statement
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom set statement is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetSetStatement(self, Obj):
        if self.__IsKeyword("SET"):
            PcdPair = self.__GetNextPcdName()
            
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                
            if not self.__GetNextToken():
                raise Warning("expected value At Line ", self.FileName, self.CurrentLineNumber)
                
            Value = self.__Token
            if Value.startswith("{"):
                # deal with value with {}
                if not self.__SkipToToken( "}"):
                    raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
                Value += self.__SkippedChars
                
            Obj.SetVarDict[PcdPair] = Value
            self.Profile.PcdDict[PcdPair] = Value
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.PcdFileLineDict[PcdPair] = FileLineTuple
            return True

        return False

    ## __GetRegionLayout() method
    #
    #   Get region layout for FD
    #
    #   @param  self        The object pointer
    #   @param  Fd          for whom region is got
    #   @retval True        Successfully find
    #   @retval False       Not able to find
    #
    def __GetRegionLayout(self, Fd):
        if not self.__GetNextHexNumber():
            return False
        
        RegionObj = CommonDataClass.FdfClass.RegionClassObject()
        RegionObj.Offset = long(self.__Token, 0)
        Fd.RegionList.append(RegionObj)
        
        if not self.__IsToken( "|"):
            raise Warning("expected '|' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextHexNumber():
            raise Warning("expected Region Size At Line ", self.FileName, self.CurrentLineNumber)
        RegionObj.Size = long(self.__Token, 0)
        
        if not self.__GetNextWord():
            return True
        
        if not self.__Token in ("SET", "FV", "FILE", "DATA", "CAPSULE"):
            self.__UndoToken()
            RegionObj.PcdOffset = self.__GetNextPcdName()
            self.Profile.PcdDict[RegionObj.PcdOffset] = RegionObj.Offset + long(Fd.BaseAddress, 0)
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.PcdFileLineDict[RegionObj.PcdOffset] = FileLineTuple
            if self.__IsToken( "|"):
                RegionObj.PcdSize = self.__GetNextPcdName()
                self.Profile.PcdDict[RegionObj.PcdSize] = RegionObj.Size
                FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
                self.Profile.PcdFileLineDict[RegionObj.PcdSize] = FileLineTuple
            
            if not self.__GetNextWord():
                return True

        if self.__Token == "SET":
            self.__UndoToken()
            self.__GetSetStatements( RegionObj)
            if not self.__GetNextWord():
                return True
            
        elif self.__Token == "FV":
            self.__UndoToken()
            self.__GetRegionFvType( RegionObj)

        elif self.__Token == "CAPSULE":
            self.__UndoToken()
            self.__GetRegionCapType( RegionObj)

        elif self.__Token == "FILE":
            self.__UndoToken()
            self.__GetRegionFileType( RegionObj)

        else:
            self.__UndoToken()
            self.__GetRegionDataType( RegionObj)
            
        return True
            
    ## __GetRegionFvType() method
    #
    #   Get region fv data for region
    #
    #   @param  self        The object pointer
    #   @param  RegionObj   for whom region data is got
    #
    def __GetRegionFvType(self, RegionObj):

        if not self.__IsKeyword( "FV"):
            raise Warning("expected Keyword 'FV' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextToken():
            raise Warning("expected FV name At Line ", self.FileName, self.CurrentLineNumber)
        
        RegionObj.RegionType = "FV"
        RegionObj.RegionDataList.append(self.__Token)
        
        while self.__IsKeyword( "FV"):
        
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
            if not self.__GetNextToken():
                raise Warning("expected FV name At Line ", self.FileName, self.CurrentLineNumber)
        
            RegionObj.RegionDataList.append(self.__Token)

    ## __GetRegionCapType() method
    #
    #   Get region capsule data for region
    #
    #   @param  self        The object pointer
    #   @param  RegionObj   for whom region data is got
    #
    def __GetRegionCapType(self, RegionObj):

        if not self.__IsKeyword("CAPSULE"):
            raise Warning("expected Keyword 'CAPSULE' at line", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' at line", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected CAPSULE name at line", self.FileName, self.CurrentLineNumber)

        RegionObj.RegionType = "CAPSULE"
        RegionObj.RegionDataList.append(self.__Token)

        while self.__IsKeyword("CAPSULE"):

            if not self.__IsToken("="):
                raise Warning("expected '=' at line", self.FileName, self.CurrentLineNumber)

            if not self.__GetNextToken():
                raise Warning("expected CAPSULE name at line", self.FileName, self.CurrentLineNumber)

            RegionObj.RegionDataList.append(self.__Token)

    ## __GetRegionFileType() method
    #
    #   Get region file data for region
    #
    #   @param  self        The object pointer
    #   @param  RegionObj   for whom region data is got
    #
    def __GetRegionFileType(self, RegionObj):

        if not self.__IsKeyword( "FILE"):
            raise Warning("expected Keyword 'FILE' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected File name At Line ", self.FileName, self.CurrentLineNumber)

        RegionObj.RegionType = "FILE"
        RegionObj.RegionDataList.append( self.__Token)
        
        while self.__IsKeyword( "FILE"):
        
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
            if not self.__GetNextToken():
                raise Warning("expected FILE name At Line ", self.FileName, self.CurrentLineNumber)
        
            RegionObj.RegionDataList.append(self.__Token)

    ## __GetRegionDataType() method
    #
    #   Get region array data for region
    #
    #   @param  self        The object pointer
    #   @param  RegionObj   for whom region data is got
    #
    def __GetRegionDataType(self, RegionObj):
        
        if not self.__IsKeyword( "DATA"):
            raise Warning("expected Region Data type At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__IsToken( "{"):
            raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextHexNumber():
            raise Warning("expected Hex byte At Line ", self.FileName, self.CurrentLineNumber)
        
        if len(self.__Token) > 4:
            raise Warning("Hex byte(must be 2 digits) too long At Line ", self.FileName, self.CurrentLineNumber)
        
        DataString = self.__Token
        DataString += ","
        
        while self.__IsToken(","):
            if not self.__GetNextHexNumber():
                raise Warning("Invalid Hex number At Line ", self.FileName, self.CurrentLineNumber)
            if len(self.__Token) > 4:
                raise Warning("Hex byte(must be 2 digits) too long At Line ", self.FileName, self.CurrentLineNumber)
            DataString += self.__Token
            DataString += ","
            
        if not self.__IsToken( "}"):
            raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
        
        DataString = DataString.rstrip(",")
        RegionObj.RegionType = "DATA"
        RegionObj.RegionDataList.append( DataString)
        
        while self.__IsKeyword( "DATA"):

            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
            if not self.__IsToken( "{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
        
            if not self.__GetNextHexNumber():
                raise Warning("expected Hex byte At Line ", self.FileName, self.CurrentLineNumber)
        
            if len(self.__Token) > 4:
                raise Warning("Hex byte(must be 2 digits) too long At Line ", self.FileName, self.CurrentLineNumber)
        
            DataString = self.__Token
            DataString += ","
        
            while self.__IsToken(","):
                self.__GetNextHexNumber()
                if len(self.__Token) > 4:
                    raise Warning("Hex byte(must be 2 digits) too long At Line ", self.FileName, self.CurrentLineNumber)
                DataString += self.__Token
                DataString += ","
            
            if not self.__IsToken( "}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
        
            DataString = DataString.rstrip(",")
            RegionObj.RegionDataList.append( DataString)
    
    ## __GetFv() method
    #
    #   Get FV section contents and store its data into FV dictionary of self.Profile
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a FV
    #   @retval False       Not able to find a FV
    #    
    def __GetFv(self):
        if not self.__GetNextToken():
            return False

        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[FV."):
            if not S.startswith("[CAPSULE.") \
                and not S.startswith("[VTF.") and not S.startswith("[RULE."):
                raise Warning("Unknown section or section appear sequence error \n(The correct sequence should be [FD.], [FV.], [Capsule.], [VTF.], [Rule.]) At Line ", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False

        self.__UndoToken()
        if not self.__IsToken("[FV.", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("Unknown Keyword At Line ", self.FileName, self.CurrentLineNumber)
        
        FvName = self.__GetUiName()
        self.CurrentFvName = FvName.upper()
        
        if not self.__IsToken( "]"):
            raise Warning("expected ']' At Line ", self.FileName, self.CurrentLineNumber)
        
        FvObj = CommonDataClass.FdfClass.FvClassObject()
        FvObj.UiFvName = self.CurrentFvName
        self.Profile.FvDict[self.CurrentFvName] = FvObj
        
        Status = self.__GetCreateFile(FvObj)
        if not Status:
            raise Warning("FV name error At Line ", self.FileName, self.CurrentLineNumber)

        self.__GetDefineStatements(FvObj)

        self.__GetAddressStatements(FvObj)
        
        self.__GetBlockStatement(FvObj)

        self.__GetSetStatements(FvObj)

        self.__GetFvAlignment(FvObj)

        self.__GetFvAttributes(FvObj)
        
        self.__GetFvNameGuid(FvObj)

        self.__GetAprioriSection(FvObj, FvObj.DefineVarDict.copy())
        self.__GetAprioriSection(FvObj, FvObj.DefineVarDict.copy())
        
        while True:
            isInf = self.__GetInfStatement(FvObj, MacroDict = FvObj.DefineVarDict.copy())
            isFile = self.__GetFileStatement(FvObj, MacroDict = FvObj.DefineVarDict.copy())
            if not isInf and not isFile:
                break
        
        return True

    ## __GetFvAlignment() method
    #
    #   Get alignment for FV
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom alignment is got
    #   @retval True        Successfully find a alignment statement
    #   @retval False       Not able to find a alignment statement
    #
    def __GetFvAlignment(self, Obj):
        
        if not self.__IsKeyword( "FvAlignment"):
            return False
        
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextToken():
            raise Warning("expected alignment value At Line ", self.FileName, self.CurrentLineNumber)
        
        if self.__Token.upper() not in ("1", "2", "4", "8", "16", "32", "64", "128", "256", "512", \
                                        "1K", "2K", "4K", "8K", "16K", "32K", "64K", "128K", "256K", "512K", \
                                        "1M", "2M", "4M", "8M", "16M", "32M", "64M", "128M", "256M", "512M", \
                                        "1G", "2G"):
            raise Warning("Unknown alignment value At Line ", self.FileName, self.CurrentLineNumber)
        Obj.FvAlignment = self.__Token
        return True
    
    ## __GetFvAttributes() method
    #
    #   Get attributes for FV
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom attribute is got
    #   @retval None
    #
    def __GetFvAttributes(self, FvObj):
        
        while self.__GetNextWord():
            name = self.__Token
            if name not in ("ERASE_POLARITY", "MEMORY_MAPPED", \
                           "STICKY_WRITE", "LOCK_CAP", "LOCK_STATUS", "WRITE_ENABLED_CAP", \
                           "WRITE_DISABLED_CAP", "WRITE_STATUS", "READ_ENABLED_CAP", \
                           "READ_DISABLED_CAP", "READ_STATUS", "READ_LOCK_CAP", \
                           "READ_LOCK_STATUS", "WRITE_LOCK_CAP", "WRITE_LOCK_STATUS", \
                           "WRITE_POLICY_RELIABLE"):
                self.__UndoToken()
                return

            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken() or self.__Token.upper() not in ("TRUE", "FALSE", "1", "0"):
                raise Warning("expected TRUE/FALSE (1/0) At Line ", self.FileName, self.CurrentLineNumber)
            
            FvObj.FvAttributeDict[name] = self.__Token

        return
    
    ## __GetFvNameGuid() method
    #
    #   Get FV GUID for FV
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom GUID is got
    #   @retval None
    #
    def __GetFvNameGuid(self, FvObj):

        if not self.__IsKeyword( "FvNameGuid"):
            return

        if not self.__IsToken( "="):
            raise Warning("expected '='", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextGuid():
            raise Warning("expected FV GUID value", self.FileName, self.CurrentLineNumber)

        FvObj.FvNameGuid = self.__Token

        return

    ## __GetAprioriSection() method
    #
    #   Get token statements
    #
    #   @param  self        The object pointer
    #   @param  FvObj       for whom apriori is got
    #   @param  MacroDict   dictionary used to replace macro
    #   @retval True        Successfully find apriori statement
    #   @retval False       Not able to find apriori statement
    #
    def __GetAprioriSection(self, FvObj, MacroDict = {}):
        
        if not self.__IsKeyword( "APRIORI"):
            return False
        
        if not self.__IsKeyword("PEI") and not self.__IsKeyword("DXE"):
            raise Warning("expected Apriori file type At Line ", self.FileName, self.CurrentLineNumber)
        AprType = self.__Token
        
        if not self.__IsToken( "{"):
            raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
        
        AprSectionObj = CommonDataClass.FdfClass.AprioriSectionClassObject()
        AprSectionObj.AprioriType = AprType
        
        self.__GetDefineStatements(AprSectionObj)
        MacroDict.update(AprSectionObj.DefineVarDict)
        
        while True:
            IsInf = self.__GetInfStatement( AprSectionObj, MacroDict = MacroDict)
            IsFile = self.__GetFileStatement( AprSectionObj)
            if not IsInf and not IsFile:
                break
        
        if not self.__IsToken( "}"):
            raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)

        FvObj.AprioriSectionList.append(AprSectionObj)
        return True

    ## __GetInfStatement() method
    #
    #   Get INF statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom inf statement is got
    #   @param  MacroDict   dictionary used to replace macro
    #   @retval True        Successfully find inf statement
    #   @retval False       Not able to find inf statement
    #
    def __GetInfStatement(self, Obj, ForCapsule = False, MacroDict = {}):

        if not self.__IsKeyword( "INF"):
            return False
        
        ffsInf = CommonDataClass.FdfClass.FfsInfStatementClassObject()
        self.__GetInfOptions( ffsInf)
        
        if not self.__GetNextToken():
            raise Warning("expected INF file path At Line ", self.FileName, self.CurrentLineNumber)
        ffsInf.InfFileName = self.__Token
        
#        if ffsInf.InfFileName.find('$') >= 0:
#            ffsInf.InfFileName = GenFdsGlobalVariable.GenFdsGlobalVariable.MacroExtend(ffsInf.InfFileName, MacroDict)
            
        if not ffsInf.InfFileName in self.Profile.InfList:
            self.Profile.InfList.append(ffsInf.InfFileName)
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            self.Profile.InfFileLineList.append(FileLineTuple)
        
        if self.__IsToken('|'):
            if self.__IsKeyword('RELOCS_STRIPPED'):
                ffsInf.KeepReloc = False
            elif self.__IsKeyword('RELOCS_RETAINED'):
                ffsInf.KeepReloc = True
            else:
                raise Warning("Unknown reloc strip flag At Line ", self.FileName, self.CurrentLineNumber)
        
        if ForCapsule:
            capsuleFfs = CapsuleData.CapsuleFfs()
            capsuleFfs.Ffs = ffsInf
            Obj.CapsuleDataList.append(capsuleFfs)
        else:
            Obj.FfsList.append(ffsInf)
        return True
    
    ## __GetInfOptions() method
    #
    #   Get options for INF
    #
    #   @param  self        The object pointer
    #   @param  FfsInfObj   for whom option is got
    #
    def __GetInfOptions(self, FfsInfObj):
        
        if self.__IsKeyword( "RuleOverride"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected Rule name At Line ", self.FileName, self.CurrentLineNumber)
            FfsInfObj.Rule = self.__Token
            
        if self.__IsKeyword( "VERSION"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected Version At Line ", self.FileName, self.CurrentLineNumber)
            
            if self.__GetStringData():
                FfsInfObj.Version = self.__Token
        
        if self.__IsKeyword( "UI"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected UI name At Line ", self.FileName, self.CurrentLineNumber)
            
            if self.__GetStringData():
                FfsInfObj.Ui = self.__Token

        if self.__IsKeyword( "USE"):
            if not self.__IsToken( "="):
                raise Warning("expected '='", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected ARCH name", self.FileName, self.CurrentLineNumber)
            FfsInfObj.UseArch = self.__Token

                
        if self.__GetNextToken():
            p = re.compile(r'([a-zA-Z0-9\-]+|\$\(TARGET\)|\*)_([a-zA-Z0-9\-]+|\$\(TOOL_CHAIN_TAG\)|\*)_([a-zA-Z0-9\-]+|\$\(ARCH\)|\*)')
            if p.match(self.__Token):
                FfsInfObj.KeyStringList.append(self.__Token)
                if not self.__IsToken(","):
                    return
            else:
                self.__UndoToken()
                return
                
            while self.__GetNextToken():
                if not p.match(self.__Token):
                    raise Warning("expected KeyString \"Target_Tag_Arch\" At Line ", self.FileName, self.CurrentLineNumber)
                FfsInfObj.KeyStringList.append(self.__Token)
    
                if not self.__IsToken(","):
                    break
                
    ## __GetFileStatement() method
    #
    #   Get FILE statements
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom FILE statement is got
    #   @param  MacroDict   dictionary used to replace macro
    #   @retval True        Successfully find FILE statement
    #   @retval False       Not able to find FILE statement
    #
    def __GetFileStatement(self, Obj, ForCapsule = False, MacroDict = {}):

        if not self.__IsKeyword( "FILE"):
            return False
        
        FfsFileObj = CommonDataClass.FdfClass.FileStatementClassObject()
        
        if not self.__GetNextWord():
            raise Warning("expected FFS type At Line ", self.FileName, self.CurrentLineNumber)
        FfsFileObj.FvFileType = self.__Token
        
        if not self.__IsToken( "="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextGuid():
            if not self.__GetNextWord():
                raise Warning("expected File GUID", self.FileName, self.CurrentLineNumber)
            if self.__Token == 'PCD':
                if not self.__IsToken( "("):
                    raise Warning("expected '('", self.FileName, self.CurrentLineNumber)
                PcdPair = self.__GetNextPcdName()
                if not self.__IsToken( ")"):
                    raise Warning("expected ')'", self.FileName, self.CurrentLineNumber)
                self.__Token = 'PCD('+PcdPair[1]+'.'+PcdPair[0]+')'
                
        FfsFileObj.NameGuid = self.__Token
    
        self.__GetFilePart( FfsFileObj, MacroDict.copy())
        
        if ForCapsule:
            capsuleFfs = CapsuleData.CapsuleFfs()
            capsuleFfs.Ffs = FfsFileObj
            Obj.CapsuleDataList.append(capsuleFfs)
        else:
            Obj.FfsList.append(FfsFileObj)
                
        return True
    
    ## __FileCouldHaveRelocFlag() method
    #
    #   Check whether reloc strip flag can be set for a file type.
    #
    #   @param  self        The object pointer
    #   @param  FileType    The file type to check with
    #   @retval True        This type could have relocation strip flag
    #   @retval False       No way to have it
    #
    
    def __FileCouldHaveRelocFlag (self, FileType):
        if FileType in ('SEC', 'PEI_CORE', 'PEIM', 'PEI_DXE_COMBO'):
            return True
        else:
            return False
    
    ## __SectionCouldHaveRelocFlag() method
    #
    #   Check whether reloc strip flag can be set for a section type.
    #
    #   @param  self        The object pointer
    #   @param  SectionType The section type to check with
    #   @retval True        This type could have relocation strip flag
    #   @retval False       No way to have it
    #
    
    def __SectionCouldHaveRelocFlag (self, SectionType):
        if SectionType in ('TE', 'PE32'):
            return True
        else:
            return False
        
    ## __GetFilePart() method
    #
    #   Get components for FILE statement
    #
    #   @param  self        The object pointer
    #   @param  FfsFileObj   for whom component is got
    #   @param  MacroDict   dictionary used to replace macro
    #
    def __GetFilePart(self, FfsFileObj, MacroDict = {}):
        
        self.__GetFileOpts( FfsFileObj)
        
        if not self.__IsToken("{"):
#            if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
#                if self.__FileCouldHaveRelocFlag(FfsFileObj.FvFileType):
#                    if self.__Token == 'RELOCS_STRIPPED':
#                        FfsFileObj.KeepReloc = False
#                    else:
#                        FfsFileObj.KeepReloc = True
#                else:
#                    raise Warning("File type %s could not have reloc strip flag At Line %d" % (FfsFileObj.FvFileType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
#            
#            if not self.__IsToken("{"):
            raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
            
        if not self.__GetNextToken():
            raise Warning("expected File name or section data At Line ", self.FileName, self.CurrentLineNumber)
        
        if self.__Token == "FV":
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected FV name At Line ", self.FileName, self.CurrentLineNumber)
            FfsFileObj.FvName = self.__Token
            
        elif self.__Token == "FD":
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected FD name At Line ", self.FileName, self.CurrentLineNumber)
            FfsFileObj.FdName = self.__Token
            
        elif self.__Token in ("DEFINE", "APRIORI", "SECTION"):
            self.__UndoToken()
            self.__GetSectionData( FfsFileObj, MacroDict)
        else:
            FfsFileObj.FileName = self.__Token
        
        if not self.__IsToken( "}"):
            raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
    
    ## __GetFileOpts() method
    #
    #   Get options for FILE statement
    #
    #   @param  self        The object pointer
    #   @param  FfsFileObj   for whom options is got
    #
    def __GetFileOpts(self, FfsFileObj):
        
        if self.__GetNextToken():
            Pattern = re.compile(r'([a-zA-Z0-9\-]+|\$\(TARGET\)|\*)_([a-zA-Z0-9\-]+|\$\(TOOL_CHAIN_TAG\)|\*)_([a-zA-Z0-9\-]+|\$\(ARCH\)|\*)')
            if Pattern.match(self.__Token):
                FfsFileObj.KeyStringList.append(self.__Token)
                if self.__IsToken(","):
                    while self.__GetNextToken():
                        if not Pattern.match(self.__Token):
                            raise Warning("expected KeyString \"Target_Tag_Arch\" At Line ", self.FileName, self.CurrentLineNumber)
                        FfsFileObj.KeyStringList.append(self.__Token)

                        if not self.__IsToken(","):
                            break
                    
            else:
                self.__UndoToken()

        if self.__IsKeyword( "FIXED", True):
            FfsFileObj.Fixed = True
            
        if self.__IsKeyword( "CHECKSUM", True):
            FfsFileObj.CheckSum = True
            
        if self.__GetAlignment():
            FfsFileObj.Alignment = self.__Token
            
        
    
    ## __GetAlignment() method
    #
    #   Return the alignment value
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find alignment
    #   @retval False       Not able to find alignment
    #
    def __GetAlignment(self):
        if self.__IsKeyword( "Align", True):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken():
                raise Warning("expected alignment value At Line ", self.FileName, self.CurrentLineNumber)
            return True
            
        return False
    
    ## __GetFilePart() method
    #
    #   Get section data for FILE statement
    #
    #   @param  self        The object pointer
    #   @param  FfsFileObj   for whom section is got
    #   @param  MacroDict   dictionary used to replace macro
    #
    def __GetSectionData(self, FfsFileObj, MacroDict = {}):
        Dict = {}
        Dict.update(MacroDict)
        
        self.__GetDefineStatements(FfsFileObj)
        
        Dict.update(FfsFileObj.DefineVarDict)
        self.__GetAprioriSection(FfsFileObj, Dict.copy())
        self.__GetAprioriSection(FfsFileObj, Dict.copy())
        
        while True:
            IsLeafSection = self.__GetLeafSection(FfsFileObj, Dict)
            IsEncapSection = self.__GetEncapsulationSec(FfsFileObj)
            if not IsLeafSection and not IsEncapSection:
                break
         
    ## __GetLeafSection() method
    #
    #   Get leaf section for Obj
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom leaf section is got
    #   @param  MacroDict   dictionary used to replace macro
    #   @retval True        Successfully find section statement
    #   @retval False       Not able to find section statement
    #
    def __GetLeafSection(self, Obj, MacroDict = {}):
        
        OldPos = self.GetFileBufferPos()
        
        if not self.__IsKeyword( "SECTION"):
            if len(Obj.SectionList) == 0:
                raise Warning("expected SECTION At Line ", self.FileName, self.CurrentLineNumber)
            else:
                return False
        
        AlignValue = None
        if self.__GetAlignment():
            if self.__Token not in ("Auto", "8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                raise Warning("Incorrect alignment '%s'" % self.__Token, self.FileName, self.CurrentLineNumber)
            AlignValue = self.__Token
            
        BuildNum = None
        if self.__IsKeyword( "BUILD_NUM"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken():
                raise Warning("expected Build number value At Line ", self.FileName, self.CurrentLineNumber)
            
            BuildNum = self.__Token
            
        if self.__IsKeyword( "VERSION"):
            if AlignValue == 'Auto':
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected version At Line ", self.FileName, self.CurrentLineNumber)
            VerSectionObj = CommonDataClass.FdfClass.VerSectionClassObject()
            VerSectionObj.Alignment = AlignValue
            VerSectionObj.BuildNum = BuildNum
            if self.__GetStringData():
                VerSectionObj.StringData = self.__Token
            else:
                VerSectionObj.FileName = self.__Token
            Obj.SectionList.append(VerSectionObj)

        elif self.__IsKeyword( "UI"):
            if AlignValue == 'Auto':
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextToken():
                raise Warning("expected UI At Line ", self.FileName, self.CurrentLineNumber)
            UiSectionObj = CommonDataClass.FdfClass.UiSectionClassObject()
            UiSectionObj.Alignment = AlignValue
            if self.__GetStringData():
                UiSectionObj.StringData = self.__Token
            else:
                UiSectionObj.FileName = self.__Token
            Obj.SectionList.append(UiSectionObj)
            
        elif self.__IsKeyword( "FV_IMAGE"):
            if AlignValue == 'Auto':
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__GetNextWord():
                raise Warning("expected FV name At Line ", self.FileName, self.CurrentLineNumber)
            
            FvName = self.__Token.upper()
            FvObj = None

            if self.__IsToken( "{"):
                FvObj = Fv.FV()
                FvObj.UiFvName = FvName
                self.__GetDefineStatements(FvObj)
                MacroDict.update(FvObj.DefineVarDict)
                self.__GetBlockStatement(FvObj)
                self.__GetSetStatements(FvObj)
                self.__GetFvAlignment(FvObj)
                self.__GetFvAttributes(FvObj)
                self.__GetAprioriSection(FvObj, MacroDict.copy())
                self.__GetAprioriSection(FvObj, MacroDict.copy())
    
                while True:
                    IsInf = self.__GetInfStatement(FvObj, MacroDict.copy())
                    IsFile = self.__GetFileStatement(FvObj, MacroDict.copy())
                    if not IsInf and not IsFile:
                        break
    
                if not self.__IsToken( "}"):
                    raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            
            FvImageSectionObj = CommonDataClass.FdfClass.FvImageSectionClassObject()
            FvImageSectionObj.Alignment = AlignValue
            if FvObj != None:
                FvImageSectionObj.Fv = FvObj
                FvImageSectionObj.FvName = None
            else:
                FvImageSectionObj.FvName = FvName
                
            Obj.SectionList.append(FvImageSectionObj) 
           
        elif self.__IsKeyword("PEI_DEPEX_EXP") or self.__IsKeyword("DXE_DEPEX_EXP") or self.__IsKeyword("SMM_DEPEX_EXP"):
            if AlignValue == 'Auto':
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            DepexSectionObj = CommonDataClass.FdfClass.DepexSectionClassObject()
            DepexSectionObj.Alignment = AlignValue
            DepexSectionObj.DepexType = self.__Token
            
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__IsToken( "{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
            if not self.__SkipToToken( "}"):
                raise Warning("expected Depex expression ending '}' At Line ", self.FileName, self.CurrentLineNumber)
            
            DepexSectionObj.Expression = self.__SkippedChars.rstrip('}')
            Obj.SectionList.append(DepexSectionObj)
        
        else:
            
            if not self.__GetNextWord():
                raise Warning("expected section type At Line ", self.FileName, self.CurrentLineNumber)
            
            # Encapsulation section appear, UndoToken and return
            if self.__Token == "COMPRESS" or self.__Token == "GUIDED":
                self.SetFileBufferPos(OldPos)
                return False
            
            if self.__Token not in ("COMPAT16", "PE32", "PIC", "TE", "FV_IMAGE", "RAW", "DXE_DEPEX",\
                               "UI", "VERSION", "PEI_DEPEX", "SUBTYPE_GUID", "SMM_DEPEX"):
                raise Warning("Unknown section type '%s'" % self.__Token, self.FileName, self.CurrentLineNumber)
            if AlignValue == 'Auto'and (not self.__Token == 'PE32') and (not self.__Token == 'TE'):
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            # DataSection
            DataSectionObj = CommonDataClass.FdfClass.DataSectionClassObject()
            DataSectionObj.Alignment = AlignValue
            DataSectionObj.SecType = self.__Token
            
            if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
                if self.__FileCouldHaveRelocFlag(Obj.FvFileType) and self.__SectionCouldHaveRelocFlag(DataSectionObj.SecType):
                    if self.__Token == 'RELOCS_STRIPPED':
                        DataSectionObj.KeepReloc = False
                    else:
                        DataSectionObj.KeepReloc = True
                else:
                    raise Warning("File type %s, section type %s, could not have reloc strip flag At Line %d" % (Obj.FvFileType, DataSectionObj.SecType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
            
            if self.__IsToken("="):
                if not self.__GetNextToken():
                    raise Warning("expected section file path At Line ", self.FileName, self.CurrentLineNumber)
                DataSectionObj.SectFileName = self.__Token
            else:
                if not self.__GetCglSection(DataSectionObj):
                    return False
            
            Obj.SectionList.append(DataSectionObj)
            
        return True
            
    ## __GetCglSection() method
    #
    #   Get compressed or GUIDed section for Obj
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom leaf section is got
    #   @param  AlignValue  alignment value for complex section
    #   @retval True        Successfully find section statement
    #   @retval False       Not able to find section statement
    #
    def __GetCglSection(self, Obj, AlignValue = None):
        
        if self.__IsKeyword( "COMPRESS"):
            type = "PI_STD"
            if self.__IsKeyword("PI_STD") or self.__IsKeyword("PI_NONE"):
                type = self.__Token
                
            if not self.__IsToken("{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)

            CompressSectionObj = CommonDataClass.FdfClass.CompressSectionClassObject()
            CompressSectionObj.Alignment = AlignValue
            CompressSectionObj.CompType = type
            # Recursive sections...
            while True:
                IsLeafSection = self.__GetLeafSection(CompressSectionObj)
                IsEncapSection = self.__GetEncapsulationSec(CompressSectionObj)
                if not IsLeafSection and not IsEncapSection:
                    break
            
            
            if not self.__IsToken( "}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            Obj.SectionList.append(CompressSectionObj)
                
#            else:
#               raise Warning("Compress type not known At Line ") 
           
            return True
        
        elif self.__IsKeyword( "GUIDED"):
            GuidValue = None
            if self.__GetNextGuid():
                GuidValue = self.__Token

            AttribDict = self.__GetGuidAttrib()
            if not self.__IsToken("{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
            GuidSectionObj = CommonDataClass.FdfClass.GuidSectionClassObject()
            GuidSectionObj.Alignment = AlignValue
            GuidSectionObj.NameGuid = GuidValue
            GuidSectionObj.SectionType = "GUIDED"
            GuidSectionObj.ProcessRequired = AttribDict["PROCESSING_REQUIRED"]
            GuidSectionObj.AuthStatusValid = AttribDict["AUTH_STATUS_VALID"]
            # Recursive sections...
            while True:
                IsLeafSection = self.__GetLeafSection(GuidSectionObj)
                IsEncapSection = self.__GetEncapsulationSec(GuidSectionObj)
                if not IsLeafSection and not IsEncapSection:
                    break
            
            if not self.__IsToken( "}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            Obj.SectionList.append(GuidSectionObj)
                
            return True
        
        return False

    ## __GetGuidAttri() method
    #
    #   Get attributes for GUID section
    #
    #   @param  self        The object pointer
    #   @retval AttribDict  Dictionary of key-value pair of section attributes
    #
    def __GetGuidAttrib(self):
        
        AttribDict = {}
        AttribDict["PROCESSING_REQUIRED"] = False
        AttribDict["AUTH_STATUS_VALID"] = False
        if self.__IsKeyword("PROCESSING_REQUIRED") or self.__IsKeyword("AUTH_STATUS_VALID"):
            AttribKey = self.__Token

            if not self.__IsToken("="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken() or self.__Token.upper() not in ("TRUE", "FALSE", "1", "0"):
                raise Warning("expected TRUE/FALSE (1/0) At Line ", self.FileName, self.CurrentLineNumber)
            AttribDict[AttribKey] = self.__Token
            
        if self.__IsKeyword("PROCESSING_REQUIRED") or self.__IsKeyword("AUTH_STATUS_VALID"):
            AttribKey = self.__Token

            if not self.__IsToken("="):
                raise Warning("expected '=' At Line ")

            if not self.__GetNextToken() or self.__Token.upper() not in ("TRUE", "FALSE", "1", "0"):
                raise Warning("expected TRUE/FALSE (1/0) At Line ", self.FileName, self.CurrentLineNumber)
            AttribDict[AttribKey] = self.__Token
            
        return AttribDict
            
    ## __GetEncapsulationSec() method
    #
    #   Get encapsulation section for FILE
    #
    #   @param  self        The object pointer
    #   @param  FfsFile     for whom section is got
    #   @retval True        Successfully find section statement
    #   @retval False       Not able to find section statement
    #
    def __GetEncapsulationSec(self, FfsFileObj):        
        
        OldPos = self.GetFileBufferPos()
        if not self.__IsKeyword( "SECTION"):
            if len(FfsFileObj.SectionList) == 0:
                raise Warning("expected SECTION At Line ", self.FileName, self.CurrentLineNumber)
            else:
                return False
        
        AlignValue = None
        if self.__GetAlignment():
            if self.__Token not in ("8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                raise Warning("Incorrect alignment '%s'" % self.__Token, self.FileName, self.CurrentLineNumber)
            AlignValue = self.__Token
            
        if not self.__GetCglSection(FfsFileObj, AlignValue):
            self.SetFileBufferPos(OldPos)
            return False
        else:
            return True

    ## __GetCapsule() method
    #
    #   Get capsule section contents and store its data into capsule list of self.Profile
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a capsule
    #   @retval False       Not able to find a capsule
    #
    def __GetCapsule(self):
        
        if not self.__GetNextToken():
            return False

        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[CAPSULE."):
            if not S.startswith("[VTF.") and not S.startswith("[RULE.") and not S.startswith("[OPTIONROM."):
                raise Warning("Unknown section or section appear sequence error (The correct sequence should be [FD.], [FV.], [Capsule.], [VTF.], [Rule.], [OptionRom.])", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False

        self.__UndoToken()
        if not self.__IsToken("[CAPSULE.", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("expected [Capsule.] At Line ", self.FileName, self.CurrentLineNumber)        
            
        CapsuleObj = CommonDataClass.FdfClass.CapsuleClassObject()

        CapsuleName = self.__GetUiName()
        if not CapsuleName:
            raise Warning("expected capsule name At line ", self.FileName, self.CurrentLineNumber)
        
        CapsuleObj.UiCapsuleName = CapsuleName.upper()
        
        if not self.__IsToken( "]"):
            raise Warning("expected ']' At Line ", self.FileName, self.CurrentLineNumber)
        
        if self.__IsKeyword("CREATE_FILE"):
            if not self.__IsToken( "="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken():
                raise Warning("expected file name At Line ", self.FileName, self.CurrentLineNumber)
            
            CapsuleObj.CreateFile = self.__Token
        
        self.__GetCapsuleStatements(CapsuleObj)
        self.Profile.CapsuleList.append(CapsuleObj)
        return True    
            
    ## __GetCapsuleStatements() method
    #
    #   Get statements for capsule
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom statements are got
    #
    def __GetCapsuleStatements(self, Obj):
        self.__GetCapsuleTokens(Obj)
        self.__GetDefineStatements(Obj)
        self.__GetSetStatements(Obj)
        
        self.__GetCapsuleData(Obj)
                
    ## __GetCapsuleStatements() method
    #
    #   Get token statements for capsule
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom token statements are got
    #
    def __GetCapsuleTokens(self, Obj):
        
        if not self.__IsKeyword("CAPSULE_GUID"):
            raise Warning("expected 'CAPSULE_GUID' At Line ", self.FileName, self.CurrentLineNumber)
        
        while self.__CurrentLine().find("=") != -1:
            NameValue = self.__CurrentLine().split("=")
            Obj.TokensDict[NameValue[0].strip()] = NameValue[1].strip()
            self.CurrentLineNumber += 1
            self.CurrentOffsetWithinLine = 0
    
    ## __GetCapsuleData() method
    #
    #   Get capsule data for capsule
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom capsule data are got
    #
    def __GetCapsuleData(self, Obj):
        
        while True:
            IsInf = self.__GetInfStatement(Obj, True)
            IsFile = self.__GetFileStatement(Obj, True)
            IsFv = self.__GetFvStatement(Obj)
            if not IsInf and not IsFile and not IsFv:
                break
    
    ## __GetFvStatement() method
    #
    #   Get FV for capsule
    #
    #   @param  self        The object pointer
    #   @param  CapsuleObj  for whom FV is got
    #   @retval True        Successfully find a FV statement
    #   @retval False       Not able to find a FV statement
    #
    def __GetFvStatement(self, CapsuleObj):
        
        if not self.__IsKeyword("FV"):
            return False
        
        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextToken():
            raise Warning("expected FV name At Line ", self.FileName, self.CurrentLineNumber)
        
#        CapsuleFv = CapsuleData.CapsuleFv()
#        CapsuleFv.FvName = self.__Token
#        CapsuleObj.CapsuleDataList.append(CapsuleFv)
        return True
    
    ## __GetRule() method
    #
    #   Get Rule section contents and store its data into rule list of self.Profile
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a Rule
    #   @retval False       Not able to find a Rule
    #
    def __GetRule(self):
        
        if not self.__GetNextToken():
            return False

        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[RULE."):
            if not S.startswith("[OPTIONROM."):
                raise Warning("Unknown section or section appear sequence error (The correct sequence should be [FD.], [FV.], [Capsule.], [VTF.], [Rule.], [OptionRom.])", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False
        self.__UndoToken()
        if not self.__IsToken("[Rule.", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("expected [Rule.] At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__SkipToToken("."):
            raise Warning("expected '.' At Line ", self.FileName, self.CurrentLineNumber)
        
        Arch = self.__SkippedChars.rstrip(".")
        if Arch.upper() not in ("IA32", "X64", "IPF", "EBC", "ARM", "COMMON"):
            raise Warning("Unknown Arch '%s'" % Arch, self.FileName, self.CurrentLineNumber)
        
        ModuleType = self.__GetModuleType()
        
        TemplateName = ""
        if self.__IsToken("."):
            if not self.__GetNextWord():
                raise Warning("expected template name At Line ", self.FileName, self.CurrentLineNumber)
            TemplateName = self.__Token
            
        if not self.__IsToken( "]"):
            raise Warning("expected ']' At Line ", self.FileName, self.CurrentLineNumber)
        
        RuleObj = self.__GetRuleFileStatements()
        RuleObj.Arch = Arch.upper()
        RuleObj.ModuleType = ModuleType
        RuleObj.TemplateName = TemplateName
        if TemplateName == '' :
            self.Profile.RuleDict['RULE'             + \
                              '.'                    + \
                              Arch.upper()           + \
                              '.'                    + \
                              ModuleType.upper()     ] = RuleObj
        else :
            self.Profile.RuleDict['RULE'             + \
                              '.'                    + \
                              Arch.upper()           + \
                              '.'                    + \
                              ModuleType.upper()     + \
                              '.'                    + \
                              TemplateName.upper() ] = RuleObj
#        self.Profile.RuleList.append(rule)
        return True
    
    ## __GetModuleType() method
    #
    #   Return the module type
    #
    #   @param  self        The object pointer
    #   @retval string      module type
    #
    def __GetModuleType(self):
        
        if not self.__GetNextWord():
            raise Warning("expected Module type At Line ", self.FileName, self.CurrentLineNumber)
        if self.__Token.upper() not in ("SEC", "PEI_CORE", "PEIM", "DXE_CORE", \
                             "DXE_DRIVER", "DXE_SAL_DRIVER", \
                             "DXE_SMM_DRIVER", "DXE_RUNTIME_DRIVER", \
                             "UEFI_DRIVER", "UEFI_APPLICATION", "USER_DEFINED", "DEFAULT", "BASE", \
                             "SECURITY_CORE", "COMBINED_PEIM_DRIVER", "PIC_PEIM", "RELOCATABLE_PEIM", \
                             "PE32_PEIM", "BS_DRIVER", "RT_DRIVER", "SAL_RT_DRIVER", "APPLICATION", "ACPITABLE", "SMM_CORE"):
            raise Warning("Unknown Module type At line ", self.FileName, self.CurrentLineNumber)
        return self.__Token
    
    ## __GetFileExtension() method
    #
    #   Return the file extension
    #
    #   @param  self        The object pointer
    #   @retval string      file name extension
    #
    def __GetFileExtension(self):
        if not self.__IsToken("."):
                raise Warning("expected '.' At Line ", self.FileName, self.CurrentLineNumber)
            
        Ext = ""
        if self.__GetNextToken():
            Pattern = re.compile(r'([a-zA-Z][a-zA-Z0-9]*)')
            if Pattern.match(self.__Token):
                Ext = self.__Token                            
                return '.' + Ext    
            else:
                raise Warning("Unknown file extension At Line ", self.FileName, self.CurrentLineNumber)
                
        else:
            raise Warning("expected file extension At Line ", self.FileName, self.CurrentLineNumber)
        
    ## __GetRuleFileStatement() method
    #
    #   Get rule contents
    #
    #   @param  self        The object pointer
    #   @retval Rule        Rule object
    #
    def __GetRuleFileStatements(self):
        
        if not self.__IsKeyword("FILE"):
            raise Warning("expected FILE At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__GetNextWord():
            raise Warning("expected FFS type At Line ", self.FileName, self.CurrentLineNumber)
        
        Type = self.__Token.strip().upper()
        if Type not in ("RAW", "FREEFORM", "SEC", "PEI_CORE", "PEIM",\
                             "PEI_DXE_COMBO", "DRIVER", "DXE_CORE", "APPLICATION", "FV_IMAGE", "SMM", "SMM_CORE"):
            raise Warning("Unknown FV type At line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
        
        if not self.__IsKeyword("$(NAMED_GUID)"):
            if not self.__GetNextWord():
                raise Warning("expected $(NAMED_GUID)", self.FileName, self.CurrentLineNumber)
            if self.__Token == 'PCD':
                if not self.__IsToken( "("):
                    raise Warning("expected '('", self.FileName, self.CurrentLineNumber)
                PcdPair = self.__GetNextPcdName()
                if not self.__IsToken( ")"):
                    raise Warning("expected ')'", self.FileName, self.CurrentLineNumber)
                self.__Token = 'PCD('+PcdPair[1]+'.'+PcdPair[0]+')'
            
        NameGuid = self.__Token

        KeepReloc = None
        if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
            if self.__FileCouldHaveRelocFlag(Type):
                if self.__Token == 'RELOCS_STRIPPED':
                    KeepReloc = False
                else:
                    KeepReloc = True
            else:
                raise Warning("File type %s could not have reloc strip flag At Line %d" % (Type, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
        
        KeyStringList = []
        if self.__GetNextToken():
            Pattern = re.compile(r'([a-zA-Z0-9\-]+|\$\(TARGET\)|\*)_([a-zA-Z0-9\-]+|\$\(TOOL_CHAIN_TAG\)|\*)_([a-zA-Z0-9\-]+|\$\(ARCH\)|\*)')
            if Pattern.match(self.__Token):
                KeyStringList.append(self.__Token)
                if self.__IsToken(","):
                    while self.__GetNextToken():
                        if not Pattern.match(self.__Token):
                            raise Warning("expected KeyString \"Target_Tag_Arch\" At Line ", self.FileName, self.CurrentLineNumber)
                        KeyStringList.append(self.__Token)

                        if not self.__IsToken(","):
                            break
                    
            else:
                self.__UndoToken()

        
        Fixed = False
        if self.__IsKeyword("Fixed", True):
            Fixed = True
            
        CheckSum = False
        if self.__IsKeyword("CheckSum", True):
            CheckSum = True
            
        AlignValue = ""
        if self.__GetAlignment():
            if self.__Token not in ("Auto", "8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                raise Warning("Incorrect alignment At Line ", self.FileName, self.CurrentLineNumber)
            AlignValue = self.__Token

        if self.__IsToken("{"):
            # Complex file rule expected
            Rule = RuleComplexFile.RuleComplexFile()
            Rule.FvFileType = Type
            Rule.NameGuid = NameGuid
            Rule.Alignment = AlignValue
            Rule.CheckSum = CheckSum
            Rule.Fixed = Fixed
            Rule.KeyStringList = KeyStringList
            if KeepReloc != None:
                Rule.KeepReloc = KeepReloc
            
            while True:
                IsEncapsulate = self.__GetRuleEncapsulationSection(Rule)
                IsLeaf = self.__GetEfiSection(Rule)
                if not IsEncapsulate and not IsLeaf:
                    break
                
            if not self.__IsToken("}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            
            return Rule
        
        elif self.__IsToken("|"):
            # Ext rule expected
            Ext = self.__GetFileExtension()
            
            Rule = RuleSimpleFile.RuleSimpleFile()

            Rule.FvFileType = Type
            Rule.NameGuid = NameGuid
            Rule.Alignment = AlignValue
            Rule.CheckSum = CheckSum
            Rule.Fixed = Fixed
            Rule.FileExtension = Ext
            Rule.KeyStringList = KeyStringList
            if KeepReloc != None:
                Rule.KeepReloc = KeepReloc
            
            return Rule
            
        else:
            # Simple file rule expected
            if not self.__GetNextWord():
                raise Warning("expected leaf section type At Line ", self.FileName, self.CurrentLineNumber)

            SectionName = self.__Token
        
            if SectionName not in ("COMPAT16", "PE32", "PIC", "TE", "FV_IMAGE", "RAW", "DXE_DEPEX",\
                                    "UI", "PEI_DEPEX", "VERSION", "SUBTYPE_GUID", "SMM_DEPEX"):
                raise Warning("Unknown leaf section name '%s'" % SectionName, self.FileName, self.CurrentLineNumber)


            if self.__IsKeyword("Fixed", True):
                Fixed = True              
    
            if self.__IsKeyword("CheckSum", True):
                CheckSum = True
    
            if self.__GetAlignment():
                if self.__Token not in ("Auto", "8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                    raise Warning("Incorrect alignment At Line ", self.FileName, self.CurrentLineNumber)
                if self.__Token == 'Auto' and (not SectionName == 'PE32') and (not SectionName == 'TE'):
                    raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
                AlignValue = self.__Token
            
            if not self.__GetNextToken():
                raise Warning("expected File name At Line ", self.FileName, self.CurrentLineNumber)
            
            Rule = RuleSimpleFile.RuleSimpleFile()
            Rule.SectionType = SectionName
            Rule.FvFileType = Type
            Rule.NameGuid = NameGuid
            Rule.Alignment = AlignValue
            Rule.CheckSum = CheckSum
            Rule.Fixed = Fixed
            Rule.FileName = self.__Token
            Rule.KeyStringList = KeyStringList
            if KeepReloc != None:
                Rule.KeepReloc = KeepReloc
            return Rule
        
    ## __GetEfiSection() method
    #
    #   Get section list for Rule
    #
    #   @param  self        The object pointer
    #   @param  Obj         for whom section is got
    #   @retval True        Successfully find section statement
    #   @retval False       Not able to find section statement
    #
    def __GetEfiSection(self, Obj):
        
        OldPos = self.GetFileBufferPos()
        if not self.__GetNextWord():
            return False
        SectionName = self.__Token
        
        if SectionName not in ("COMPAT16", "PE32", "PIC", "TE", "FV_IMAGE", "RAW", "DXE_DEPEX",\
                               "UI", "VERSION", "PEI_DEPEX", "GUID", "SMM_DEPEX"):
            self.__UndoToken()
            return False
        
        if SectionName == "FV_IMAGE":
            FvImageSectionObj = FvImageSection.FvImageSection()
            if self.__IsKeyword("FV_IMAGE"):
                pass
            if self.__IsToken( "{"):
                FvObj = Fv.FV()
                self.__GetDefineStatements(FvObj)
                self.__GetBlockStatement(FvObj)
                self.__GetSetStatements(FvObj)
                self.__GetFvAlignment(FvObj)
                self.__GetFvAttributes(FvObj)
                self.__GetAprioriSection(FvObj)
                self.__GetAprioriSection(FvObj)
    
                while True:
                    IsInf = self.__GetInfStatement(FvObj)
                    IsFile = self.__GetFileStatement(FvObj)
                    if not IsInf and not IsFile:
                        break
    
                if not self.__IsToken( "}"):
                    raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
                FvImageSectionObj.Fv = FvObj
                FvImageSectionObj.FvName = None
                
            else:
                if not self.__IsKeyword("FV"):
                    raise Warning("expected 'FV' At Line ", self.FileName, self.CurrentLineNumber)
                FvImageSectionObj.FvFileType = self.__Token
                
                if self.__GetAlignment():
                    if self.__Token not in ("8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                        raise Warning("Incorrect alignment At Line ", self.FileName, self.CurrentLineNumber)
                    FvImageSectionObj.Alignment = self.__Token
                
                if self.__IsToken('|'):
                    FvImageSectionObj.FvFileExtension = self.__GetFileExtension()
                elif self.__GetNextToken():
                    if self.__Token not in ("}", "COMPAT16", "PE32", "PIC", "TE", "FV_IMAGE", "RAW", "DXE_DEPEX",\
                               "UI", "VERSION", "PEI_DEPEX", "GUID", "SMM_DEPEX"):
                        FvImageSectionObj.FvFileName = self.__Token
                    else:
                        self.__UndoToken()
                else:
                    raise Warning("expected FV file name At Line ", self.FileName, self.CurrentLineNumber)
                    
            Obj.SectionList.append(FvImageSectionObj)
            return True
        
        EfiSectionObj = EfiSection.EfiSection()
        EfiSectionObj.SectionType = SectionName
        
        if not self.__GetNextToken():
            raise Warning("expected file type At Line ", self.FileName, self.CurrentLineNumber)
        
        if self.__Token == "STRING":
            if not self.__RuleSectionCouldHaveString(EfiSectionObj.SectionType):
                raise Warning("%s section could NOT have string data At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
            
            if not self.__IsToken('='):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
            
            if not self.__GetNextToken():
                raise Warning("expected Quoted String At Line ", self.FileName, self.CurrentLineNumber)
        
            if self.__GetStringData():
                EfiSectionObj.StringData = self.__Token
            
            if self.__IsKeyword("BUILD_NUM"):
                if not self.__RuleSectionCouldHaveBuildNum(EfiSectionObj.SectionType):
                    raise Warning("%s section could NOT have BUILD_NUM At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
            
                if not self.__IsToken("="):
                    raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                if not self.__GetNextToken():
                    raise Warning("expected Build number At Line ", self.FileName, self.CurrentLineNumber)
                EfiSectionObj.BuildNum = self.__Token
                
        else:
            EfiSectionObj.FileType = self.__Token
            self.__CheckRuleSectionFileType(EfiSectionObj.SectionType, EfiSectionObj.FileType)
            
        if self.__IsKeyword("Optional"):
            if not self.__RuleSectionCouldBeOptional(EfiSectionObj.SectionType):
                raise Warning("%s section could NOT be optional At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
            EfiSectionObj.Optional = True
        
            if self.__IsKeyword("BUILD_NUM"):
                if not self.__RuleSectionCouldHaveBuildNum(EfiSectionObj.SectionType):
                    raise Warning("%s section could NOT have BUILD_NUM At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
                
                if not self.__IsToken("="):
                    raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)
                if not self.__GetNextToken():
                    raise Warning("expected Build number At Line ", self.FileName, self.CurrentLineNumber)
                EfiSectionObj.BuildNum = self.__Token
                
        if self.__GetAlignment():
            if self.__Token not in ("Auto", "8", "16", "32", "64", "128", "512", "1K", "4K", "32K" ,"64K"):
                raise Warning("Incorrect alignment '%s'" % self.__Token, self.FileName, self.CurrentLineNumber)
            if self.__Token == 'Auto' and (not SectionName == 'PE32') and (not SectionName == 'TE'):
                raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber)
            EfiSectionObj.Alignment = self.__Token
        
        if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
            if self.__SectionCouldHaveRelocFlag(EfiSectionObj.SectionType):
                if self.__Token == 'RELOCS_STRIPPED':
                    EfiSectionObj.KeepReloc = False
                else:
                    EfiSectionObj.KeepReloc = True
                if Obj.KeepReloc != None and Obj.KeepReloc != EfiSectionObj.KeepReloc:
                    raise Warning("Section type %s has reloc strip flag conflict with Rule At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
            else:
                raise Warning("Section type %s could not have reloc strip flag At Line %d" % (EfiSectionObj.SectionType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
        
        
        if self.__IsToken('|'):
            EfiSectionObj.FileExtension = self.__GetFileExtension()
        elif self.__GetNextToken():
            if self.__Token not in ("}", "COMPAT16", "PE32", "PIC", "TE", "FV_IMAGE", "RAW", "DXE_DEPEX",\
                       "UI", "VERSION", "PEI_DEPEX", "GUID", "SMM_DEPEX"):
                
                if self.__Token.startswith('PCD'):
                    self.__UndoToken()
                    self.__GetNextWord()
                
                    if self.__Token == 'PCD':
                        if not self.__IsToken( "("):
                            raise Warning("expected '('", self.FileName, self.CurrentLineNumber)
                        PcdPair = self.__GetNextPcdName()
                        if not self.__IsToken( ")"):
                            raise Warning("expected ')'", self.FileName, self.CurrentLineNumber)
                        self.__Token = 'PCD('+PcdPair[1]+'.'+PcdPair[0]+')'
                        
                EfiSectionObj.FileName = self.__Token        
                            
            else:
                self.__UndoToken()
        else:
            raise Warning("expected section file name At Line ", self.FileName, self.CurrentLineNumber)
                
        Obj.SectionList.append(EfiSectionObj)
        return True
        
    ## __RuleSectionCouldBeOptional() method
    #
    #   Get whether a section could be optional
    #
    #   @param  self        The object pointer
    #   @param  SectionType The section type to check
    #   @retval True        section could be optional
    #   @retval False       section never optional
    #
    def __RuleSectionCouldBeOptional(self, SectionType):
        if SectionType in ("DXE_DEPEX", "UI", "VERSION", "PEI_DEPEX", "RAW", "SMM_DEPEX"):
            return True
        else:
            return False
    
    ## __RuleSectionCouldHaveBuildNum() method
    #
    #   Get whether a section could have build number information
    #
    #   @param  self        The object pointer
    #   @param  SectionType The section type to check
    #   @retval True        section could have build number information
    #   @retval False       section never have build number information
    #
    def __RuleSectionCouldHaveBuildNum(self, SectionType):
        if SectionType in ("VERSION"):
            return True
        else:
            return False
    
    ## __RuleSectionCouldHaveString() method
    #
    #   Get whether a section could have string
    #
    #   @param  self        The object pointer
    #   @param  SectionType The section type to check
    #   @retval True        section could have string
    #   @retval False       section never have string
    #
    def __RuleSectionCouldHaveString(self, SectionType):
        if SectionType in ("UI", "VERSION"):
            return True
        else:
            return False
    
    ## __CheckRuleSectionFileType() method
    #
    #   Get whether a section matches a file type
    #
    #   @param  self        The object pointer
    #   @param  SectionType The section type to check
    #   @param  FileType    The file type to check
    #
    def __CheckRuleSectionFileType(self, SectionType, FileType):
        if SectionType == "COMPAT16":
            if FileType not in ("COMPAT16", "SEC_COMPAT16"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "PE32":
            if FileType not in ("PE32", "SEC_PE32"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "PIC":
            if FileType not in ("PIC", "PIC"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "TE":
            if FileType not in ("TE", "SEC_TE"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "RAW":
            if FileType not in ("BIN", "SEC_BIN", "RAW", "ASL", "ACPI"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "DXE_DEPEX" or SectionType == "SMM_DEPEX":
            if FileType not in ("DXE_DEPEX", "SEC_DXE_DEPEX", "SMM_DEPEX"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "UI":
            if FileType not in ("UI", "SEC_UI"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "VERSION":
            if FileType not in ("VERSION", "SEC_VERSION"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "PEI_DEPEX":
            if FileType not in ("PEI_DEPEX", "SEC_PEI_DEPEX"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)
        elif SectionType == "GUID":
            if FileType not in ("PE32", "SEC_GUID"):
                raise Warning("Incorrect section file type At Line ", self.FileName, self.CurrentLineNumber)    
              
    ## __GetRuleEncapsulationSection() method
    #
    #   Get encapsulation section for Rule
    #
    #   @param  self        The object pointer
    #   @param  Rule        for whom section is got
    #   @retval True        Successfully find section statement
    #   @retval False       Not able to find section statement
    #
    def __GetRuleEncapsulationSection(self, Rule):

        if self.__IsKeyword( "COMPRESS"):
            Type = "PI_STD"
            if self.__IsKeyword("PI_STD") or self.__IsKeyword("PI_NONE"):
                Type = self.__Token
                
            if not self.__IsToken("{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)

            CompressSectionObj = CompressSection.CompressSection()
            
            CompressSectionObj.CompType = Type
            # Recursive sections...
            while True:
                IsEncapsulate = self.__GetRuleEncapsulationSection(CompressSectionObj)
                IsLeaf = self.__GetEfiSection(CompressSectionObj)
                if not IsEncapsulate and not IsLeaf:
                    break
            
            if not self.__IsToken( "}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            Rule.SectionList.append(CompressSectionObj)
                
            return True

        elif self.__IsKeyword( "GUIDED"):
            GuidValue = None
            if self.__GetNextGuid():
                GuidValue = self.__Token
            
            if self.__IsKeyword( "$(NAMED_GUID)"):
                GuidValue = self.__Token
                
            AttribDict = self.__GetGuidAttrib()
            
            if not self.__IsToken("{"):
                raise Warning("expected '{' At Line ", self.FileName, self.CurrentLineNumber)
            GuidSectionObj = GuidSection.GuidSection()
            GuidSectionObj.NameGuid = GuidValue
            GuidSectionObj.SectionType = "GUIDED"
            GuidSectionObj.ProcessRequired = AttribDict["PROCESSING_REQUIRED"]
            GuidSectionObj.AuthStatusValid = AttribDict["AUTH_STATUS_VALID"]
            
            # Efi sections...
            while True:
                IsEncapsulate = self.__GetRuleEncapsulationSection(GuidSectionObj)
                IsLeaf = self.__GetEfiSection(GuidSectionObj)
                if not IsEncapsulate and not IsLeaf:
                    break
            
            if not self.__IsToken( "}"):
                raise Warning("expected '}' At Line ", self.FileName, self.CurrentLineNumber)
            Rule.SectionList.append(GuidSectionObj)

            return True

        return False
        
    ## __GetVtf() method
    #
    #   Get VTF section contents and store its data into VTF list of self.Profile
    #
    #   @param  self        The object pointer
    #   @retval True        Successfully find a VTF
    #   @retval False       Not able to find a VTF
    #
    def __GetVtf(self):
        
        if not self.__GetNextToken():
            return False

        S = self.__Token.upper()
        if S.startswith("[") and not S.startswith("[VTF."):
            if not S.startswith("[RULE.") and not S.startswith("[OPTIONROM."):
                raise Warning("Unknown section or section appear sequence error (The correct sequence should be [FD.], [FV.], [Capsule.], [VTF.], [Rule.], [OptionRom.])", self.FileName, self.CurrentLineNumber)
            self.__UndoToken()
            return False

        self.__UndoToken()
        if not self.__IsToken("[VTF.", True):
            FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
            print 'Parsing String: %s in File %s, At line: %d, Offset Within Line: %d' \
                    % (self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine :], FileLineTuple[0], FileLineTuple[1], self.CurrentOffsetWithinLine)
            raise Warning("expected [VTF.] At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__SkipToToken("."):
            raise Warning("expected '.' At Line ", self.FileName, self.CurrentLineNumber)

        Arch = self.__SkippedChars.rstrip(".").upper()
        if Arch not in ("IA32", "X64", "IPF", "ARM"):
            raise Warning("Unknown Arch At line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextWord():
            raise Warning("expected VTF name At Line ", self.FileName, self.CurrentLineNumber)
        Name = self.__Token.upper()

        VtfObj = Vtf.Vtf()
        VtfObj.UiName = Name
        VtfObj.KeyArch = Arch
        
        if self.__IsToken(","):
            if not self.__GetNextWord():
                raise Warning("expected Arch list At Line ", self.FileName, self.CurrentLineNumber)
            if self.__Token.upper() not in ("IA32", "X64", "IPF", "ARM"):
                raise Warning("Unknown Arch At line ", self.FileName, self.CurrentLineNumber)
            VtfObj.ArchList = self.__Token.upper()

        if not self.__IsToken( "]"):
            raise Warning("expected ']' At Line ", self.FileName, self.CurrentLineNumber)
        
        if self.__IsKeyword("IA32_RST_BIN"):
            if not self.__IsToken("="):
                raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

            if not self.__GetNextToken():
                raise Warning("expected Reset file At Line ", self.FileName, self.CurrentLineNumber)

            VtfObj.ResetBin = self.__Token
            
        while self.__GetComponentStatement(VtfObj):
            pass
        
        self.Profile.VtfList.append(VtfObj)
        return True
    
    ## __GetComponentStatement() method
    #
    #   Get components in VTF
    #
    #   @param  self        The object pointer
    #   @param  VtfObj         for whom component is got
    #   @retval True        Successfully find a component
    #   @retval False       Not able to find a component
    #
    def __GetComponentStatement(self, VtfObj):
        
        if not self.__IsKeyword("COMP_NAME"):
            return False
        
        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextWord():
            raise Warning("expected Component Name At Line ", self.FileName, self.CurrentLineNumber)

        CompStatementObj = ComponentStatement.ComponentStatement()
        CompStatementObj.CompName = self.__Token
        
        if not self.__IsKeyword("COMP_LOC"):
            raise Warning("expected COMP_LOC At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        CompStatementObj.CompLoc = ""
        if self.__GetNextWord():
            CompStatementObj.CompLoc = self.__Token
            if self.__IsToken('|'):
                if not self.__GetNextWord():
                    raise Warning("Expected Region Name At Line ", self.FileName, self.CurrentLineNumber)
                
                if self.__Token not in ("F", "N", "S"):    #, "H", "L", "PH", "PL"): not support
                    raise Warning("Unknown location type At line ", self.FileName, self.CurrentLineNumber)
    
                CompStatementObj.FilePos = self.__Token
        else:
            self.CurrentLineNumber += 1
            self.CurrentOffsetWithinLine = 0
        
        if not self.__IsKeyword("COMP_TYPE"):
            raise Warning("expected COMP_TYPE At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected Component type At Line ", self.FileName, self.CurrentLineNumber)
        if self.__Token not in ("FIT", "PAL_B", "PAL_A", "OEM"):
            if not self.__Token.startswith("0x") or len(self.__Token) < 3 or len(self.__Token) > 4 or \
                not self.__HexDigit(self.__Token[2]) or not self.__HexDigit(self.__Token[-1]):
                raise Warning("Unknown location type At line ", self.FileName, self.CurrentLineNumber)
        CompStatementObj.CompType = self.__Token
        
        if not self.__IsKeyword("COMP_VER"):
            raise Warning("expected COMP_VER At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected Component version At Line ", self.FileName, self.CurrentLineNumber)

        Pattern = re.compile('-$|[0-9]{0,1}[0-9]{1}\.[0-9]{0,1}[0-9]{1}')
        if Pattern.match(self.__Token) == None:
            raise Warning("Unknown version format At line ", self.FileName, self.CurrentLineNumber)
        CompStatementObj.CompVer = self.__Token
        
        if not self.__IsKeyword("COMP_CS"):
            raise Warning("expected COMP_CS At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected Component CS At Line ", self.FileName, self.CurrentLineNumber)
        if self.__Token not in ("1", "0"):
            raise Warning("Unknown  Component CS At line ", self.FileName, self.CurrentLineNumber)
        CompStatementObj.CompCs = self.__Token
        
        
        if not self.__IsKeyword("COMP_BIN"):
            raise Warning("expected COMP_BIN At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected Component file At Line ", self.FileName, self.CurrentLineNumber)

        CompStatementObj.CompBin = self.__Token
        
        if not self.__IsKeyword("COMP_SYM"):
            raise Warning("expected COMP_SYM At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__GetNextToken():
            raise Warning("expected Component symbol file At Line ", self.FileName, self.CurrentLineNumber)

        CompStatementObj.CompSym = self.__Token
    
        if not self.__IsKeyword("COMP_SIZE"):
            raise Warning("expected COMP_SIZE At Line ", self.FileName, self.CurrentLineNumber)

        if not self.__IsToken("="):
            raise Warning("expected '=' At Line ", self.FileName, self.CurrentLineNumber)

        if self.__IsToken("-"):
            CompStatementObj.CompSize = self.__Token
        elif self.__GetNextDecimalNumber():
            CompStatementObj.CompSize = self.__Token
        elif self.__GetNextHexNumber():
            CompStatementObj.CompSize = self.__Token
        else:
            raise Warning("Unknown size At line ", self.FileName, self.CurrentLineNumber)
        
        VtfObj.ComponentStatementList.append(CompStatementObj)
        return True
    
    ## __GetFvInFd() method
    #
    #   Get FV list contained in FD
    #
    #   @param  self        The object pointer
    #   @param  FdName      FD name
    #   @retval FvList      list of FV in FD
    #
    def __GetFvInFd (self, FdName):
    
        FvList = []
        if FdName.upper() in self.Profile.FdDict.keys():
            FdObj = self.Profile.FdDict[FdName.upper()]
            for elementRegion in FdObj.RegionList:
                if elementRegion.RegionType == 'FV':
                    for elementRegionData in elementRegion.RegionDataList:
                        if elementRegionData != None and elementRegionData.upper() not in FvList:
                            FvList.append(elementRegionData.upper())
        return FvList
    
    ## __GetReferencedFdFvTuple() method
    #
    #   Get FD and FV list referenced by a FFS file
    #
    #   @param  self        The object pointer
    #   @param  FfsFile     contains sections to be searched
    #   @param  RefFdList   referenced FD by section
    #   @param  RefFvList   referenced FV by section
    #
    def __GetReferencedFdFvTuple(self, FvObj, RefFdList = [], RefFvList = []):
        
        for FfsObj in FvObj.FfsList:
            if isinstance(FfsObj, FfsFileStatement.FileStatement):
                if FfsObj.FvName != None and FfsObj.FvName.upper() not in RefFvList:
                    RefFvList.append(FfsObj.FvName.upper())
                elif FfsObj.FdName != None and FfsObj.FdName.upper() not in RefFdList:
                    RefFdList.append(FfsObj.FdName.upper())
                else:
                    self.__GetReferencedFdFvTupleFromSection(FfsObj, RefFdList, RefFvList)    
    
    ## __GetReferencedFdFvTupleFromSection() method
    #
    #   Get FD and FV list referenced by a FFS section
    #
    #   @param  self        The object pointer
    #   @param  FfsFile     contains sections to be searched
    #   @param  FdList      referenced FD by section
    #   @param  FvList      referenced FV by section
    #
    def __GetReferencedFdFvTupleFromSection(self, FfsFile, FdList = [], FvList = []):
        
        SectionStack = []
        SectionStack.extend(FfsFile.SectionList)
        while SectionStack != []:
            SectionObj = SectionStack.pop()
            if isinstance(SectionObj, FvImageSection.FvImageSection):
                if SectionObj.FvName != None and SectionObj.FvName.upper() not in FvList:
                    FvList.append(SectionObj.FvName.upper())
                if SectionObj.Fv != None and SectionObj.Fv.UiFvName != None and SectionObj.Fv.UiFvName.upper() not in FvList:
                    FvList.append(SectionObj.Fv.UiFvName.upper())
                    self.__GetReferencedFdFvTuple(SectionObj.Fv, FdList, FvList)
            
            if isinstance(SectionObj, CompressSection.CompressSection) or isinstance(SectionObj, GuidSection.GuidSection):
                SectionStack.extend(SectionObj.SectionList)
                          
    ## CycleReferenceCheck() method
    #
    #   Check whether cycle reference exists in FDF
    #
    #   @param  self        The object pointer
    #   @retval True        cycle reference exists
    #   @retval False       Not exists cycle reference
    #
    def CycleReferenceCheck(self):
        
        CycleRefExists = False
        
        try:
            for FvName in self.Profile.FvDict.keys():
                LogStr = "Cycle Reference Checking for FV: %s\n" % FvName
                RefFvStack = []
                RefFvStack.append(FvName)
                FdAnalyzedList = []
                
                while RefFvStack != []:
                    FvNameFromStack = RefFvStack.pop()
                    if FvNameFromStack.upper() in self.Profile.FvDict.keys():
                        FvObj = self.Profile.FvDict[FvNameFromStack.upper()]
                    else:
                        continue
                    
                    RefFdList = []
                    RefFvList = []
                    self.__GetReferencedFdFvTuple(FvObj, RefFdList, RefFvList)
                    
                    for RefFdName in RefFdList:
                        if RefFdName in FdAnalyzedList:
                            continue
                        
                        LogStr += "FD %s is referenced by FV %s\n" % (RefFdName, FvNameFromStack) 
                        FvInFdList = self.__GetFvInFd(RefFdName)
                        if FvInFdList != []:
                            LogStr += "FD %s contains FV: " % RefFdName
                            for FvObj in FvInFdList:
                                LogStr += FvObj
                                LogStr += ' \n'
                                if FvObj not in RefFvStack:
                                    RefFvStack.append(FvObj)
                        
                                if FvName in RefFvStack:
                                    CycleRefExists = True
                                    raise Warning(LogStr)
                        FdAnalyzedList.append(RefFdName)
                                   
                    for RefFvName in RefFvList:
                        LogStr += "FV %s is referenced by FV %s\n" % (RefFvName, FvNameFromStack)
                        if RefFvName not in RefFvStack:
                            RefFvStack.append(RefFvName)
                            
                        if FvName in RefFvStack:
                            CycleRefExists = True
                            raise Warning(LogStr)
        
        except Warning:
            print LogStr
        
        finally:
            return CycleRefExists
        
if __name__ == "__main__":
    parser = FdfParser("..\LakeportX64Pkg.fdf")
    try:
        parser.ParseFile()
        parser.CycleReferenceCheck()
    except Warning, X:
        print X.message
    else:
        print "Success!"