summaryrefslogtreecommitdiffstats
path: root/BaseTools/Source/Python/Ecc/c.py
blob: 0ebdc1a99605469c6c5f418580e67fa425a1ec54 (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
## @file
# This file is used to be the c coding style checking of ECC tool
#
# Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2020, Arm Limited. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#

from __future__ import print_function
from __future__ import absolute_import
import sys
import Common.LongFilePathOs as os
import re
import string
from Ecc import CodeFragmentCollector
from Ecc import FileProfile
from CommonDataClass import DataClass
from Ecc import Database
from Common import EdkLogger
from Ecc.EccToolError import *
from Ecc import EccGlobalData
from Ecc import MetaDataParser

IncludeFileListDict = {}
AllIncludeFileListDict = {}
IncludePathListDict = {}
ComplexTypeDict = {}
SUDict = {}
IgnoredKeywordList = ['EFI_ERROR']

def GetIgnoredDirListPattern():
    skipList = list(EccGlobalData.gConfig.SkipDirList) + ['.svn']
    DirString = '|'.join(skipList)
    p = re.compile(r'.*[\\/](?:%s)[\\/]?.*' % DirString)
    return p

def GetFuncDeclPattern():
    p = re.compile(r'(?:EFIAPI|EFI_BOOT_SERVICE|EFI_RUNTIME_SERVICE)?\s*[_\w]+\s*\(.*\)$', re.DOTALL)
    return p

def GetArrayPattern():
    p = re.compile(r'[_\w]*\s*[\[.*\]]+')
    return p

def GetTypedefFuncPointerPattern():
    p = re.compile(r'[_\w\s]*\([\w\s]*\*+\s*[_\w]+\s*\)\s*\(.*\)', re.DOTALL)
    return p

def GetDB():
    return EccGlobalData.gDb

def GetConfig():
    return EccGlobalData.gConfig

def PrintErrorMsg(ErrorType, Msg, TableName, ItemId):
    Msg = Msg.replace('\n', '').replace('\r', '')
    MsgPartList = Msg.split()
    Msg = ''
    for Part in MsgPartList:
        Msg += Part
        Msg += ' '
    GetDB().TblReport.Insert(ErrorType, OtherMsg=Msg, BelongsToTable=TableName, BelongsToItem=ItemId)

def GetIdType(Str):
    Type = DataClass.MODEL_UNKNOWN
    Str = Str.replace('#', '# ')
    List = Str.split()
    if len(List) < 2:
        pass
    elif List[1] == 'include':
        Type = DataClass.MODEL_IDENTIFIER_INCLUDE
    elif List[1] == 'define':
        Type = DataClass.MODEL_IDENTIFIER_MACRO_DEFINE
    elif List[1] == 'ifdef':
        Type = DataClass.MODEL_IDENTIFIER_MACRO_IFDEF
    elif List[1] == 'ifndef':
        Type = DataClass.MODEL_IDENTIFIER_MACRO_IFNDEF
    elif List[1] == 'endif':
        Type = DataClass.MODEL_IDENTIFIER_MACRO_ENDIF
    elif List[1] == 'pragma':
        Type = DataClass.MODEL_IDENTIFIER_MACRO_PROGMA
    else:
        Type = DataClass.MODEL_UNKNOWN
    return Type

def SuOccurInTypedef (Su, TdList):
    for Td in TdList:
        if Su.StartPos[0] == Td.StartPos[0] and Su.EndPos[0] == Td.EndPos[0]:
            return True
    return False

def GetIdentifierList():
    IdList = []
    for comment in FileProfile.CommentList:
        IdComment = DataClass.IdentifierClass(-1, '', '', '', comment.Content, DataClass.MODEL_IDENTIFIER_COMMENT, -1, -1, comment.StartPos[0], comment.StartPos[1], comment.EndPos[0], comment.EndPos[1])
        IdList.append(IdComment)

    for pp in FileProfile.PPDirectiveList:
        Type = GetIdType(pp.Content)
        IdPP = DataClass.IdentifierClass(-1, '', '', '', pp.Content, Type, -1, -1, pp.StartPos[0], pp.StartPos[1], pp.EndPos[0], pp.EndPos[1])
        IdList.append(IdPP)

    for pe in FileProfile.PredicateExpressionList:
        IdPE = DataClass.IdentifierClass(-1, '', '', '', pe.Content, DataClass.MODEL_IDENTIFIER_PREDICATE_EXPRESSION, -1, -1, pe.StartPos[0], pe.StartPos[1], pe.EndPos[0], pe.EndPos[1])
        IdList.append(IdPE)

    FuncDeclPattern = GetFuncDeclPattern()
    ArrayPattern = GetArrayPattern()
    for var in FileProfile.VariableDeclarationList:
        DeclText = var.Declarator.lstrip()
        FuncPointerPattern = GetTypedefFuncPointerPattern()
        if FuncPointerPattern.match(DeclText):
            continue
        VarNameStartLine = var.NameStartPos[0]
        VarNameStartColumn = var.NameStartPos[1]
        FirstChar = DeclText[0]
        while not FirstChar.isalpha() and FirstChar != '_':
            if FirstChar == '*':
                var.Modifier += '*'
                VarNameStartColumn += 1
                DeclText = DeclText.lstrip('*')
            elif FirstChar == '\r':
                DeclText = DeclText.lstrip('\r\n').lstrip('\r')
                VarNameStartLine += 1
                VarNameStartColumn = 0
            elif FirstChar == '\n':
                DeclText = DeclText.lstrip('\n')
                VarNameStartLine += 1
                VarNameStartColumn = 0
            elif FirstChar == ' ':
                DeclText = DeclText.lstrip(' ')
                VarNameStartColumn += 1
            elif FirstChar == '\t':
                DeclText = DeclText.lstrip('\t')
                VarNameStartColumn += 8
            else:
                DeclText = DeclText[1:]
                VarNameStartColumn += 1
            FirstChar = DeclText[0]

        var.Declarator = DeclText
        if FuncDeclPattern.match(var.Declarator):
            DeclSplitList = var.Declarator.split('(')
            FuncName = DeclSplitList[0].strip()
            FuncNamePartList = FuncName.split()
            if len(FuncNamePartList) > 1:
                FuncName = FuncNamePartList[-1].strip()
                NameStart = DeclSplitList[0].rfind(FuncName)
                var.Declarator = var.Declarator[NameStart:]
                if NameStart > 0:
                    var.Modifier += ' ' + DeclSplitList[0][0:NameStart]
                    Index = 0
                    PreChar = ''
                    while Index < NameStart:
                        FirstChar = DeclSplitList[0][Index]
                        if DeclSplitList[0][Index:].startswith('EFIAPI'):
                            Index += 6
                            VarNameStartColumn += 6
                            PreChar = ''
                            continue
                        elif FirstChar == '\r':
                            Index += 1
                            VarNameStartLine += 1
                            VarNameStartColumn = 0
                        elif FirstChar == '\n':
                            Index += 1
                            if PreChar != '\r':
                                VarNameStartLine += 1
                                VarNameStartColumn = 0
                        elif FirstChar == ' ':
                            Index += 1
                            VarNameStartColumn += 1
                        elif FirstChar == '\t':
                            Index += 1
                            VarNameStartColumn += 8
                        else:
                            Index += 1
                            VarNameStartColumn += 1
                        PreChar = FirstChar
            IdVar = DataClass.IdentifierClass(-1, var.Modifier, '', var.Declarator, FuncName, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION, -1, -1, var.StartPos[0], var.StartPos[1], VarNameStartLine, VarNameStartColumn)
            IdList.append(IdVar)
            continue

        if var.Declarator.find('{') == -1:
            for decl in var.Declarator.split(','):
                DeclList = decl.split('=')
                Name = DeclList[0].strip()
                if ArrayPattern.match(Name):
                    LSBPos = var.Declarator.find('[')
                    var.Modifier += ' ' + Name[LSBPos:]
                    Name = Name[0:LSBPos]

                IdVar = DataClass.IdentifierClass(-1, var.Modifier, '', Name, (len(DeclList) > 1 and [DeclList[1]]or [''])[0], DataClass.MODEL_IDENTIFIER_VARIABLE, -1, -1, var.StartPos[0], var.StartPos[1], VarNameStartLine, VarNameStartColumn)
                IdList.append(IdVar)
        else:
            DeclList = var.Declarator.split('=')
            Name = DeclList[0].strip()
            if ArrayPattern.match(Name):
                LSBPos = var.Declarator.find('[')
                var.Modifier += ' ' + Name[LSBPos:]
                Name = Name[0:LSBPos]
            IdVar = DataClass.IdentifierClass(-1, var.Modifier, '', Name, (len(DeclList) > 1 and [DeclList[1]]or [''])[0], DataClass.MODEL_IDENTIFIER_VARIABLE, -1, -1, var.StartPos[0], var.StartPos[1], VarNameStartLine, VarNameStartColumn)
            IdList.append(IdVar)

    for enum in FileProfile.EnumerationDefinitionList:
        LBPos = enum.Content.find('{')
        RBPos = enum.Content.find('}')
        Name = enum.Content[4:LBPos].strip()
        Value = enum.Content[LBPos + 1:RBPos]
        IdEnum = DataClass.IdentifierClass(-1, '', '', Name, Value, DataClass.MODEL_IDENTIFIER_ENUMERATE, -1, -1, enum.StartPos[0], enum.StartPos[1], enum.EndPos[0], enum.EndPos[1])
        IdList.append(IdEnum)

    for su in FileProfile.StructUnionDefinitionList:
        if SuOccurInTypedef(su, FileProfile.TypedefDefinitionList):
            continue
        Type = DataClass.MODEL_IDENTIFIER_STRUCTURE
        SkipLen = 6
        if su.Content.startswith('union'):
            Type = DataClass.MODEL_IDENTIFIER_UNION
            SkipLen = 5
        LBPos = su.Content.find('{')
        RBPos = su.Content.find('}')
        if LBPos == -1 or RBPos == -1:
            Name = su.Content[SkipLen:].strip()
            Value = ''
        else:
            Name = su.Content[SkipLen:LBPos].strip()
            Value = su.Content[LBPos:RBPos + 1]
        IdPE = DataClass.IdentifierClass(-1, '', '', Name, Value, Type, -1, -1, su.StartPos[0], su.StartPos[1], su.EndPos[0], su.EndPos[1])
        IdList.append(IdPE)

    TdFuncPointerPattern = GetTypedefFuncPointerPattern()
    for td in FileProfile.TypedefDefinitionList:
        Modifier = ''
        Name = td.ToType
        Value = td.FromType
        if TdFuncPointerPattern.match(td.ToType):
            Modifier = td.FromType
            LBPos = td.ToType.find('(')
            TmpStr = td.ToType[LBPos + 1:].strip()
            StarPos = TmpStr.find('*')
            if StarPos != -1:
                Modifier += ' ' + TmpStr[0:StarPos]
            while TmpStr[StarPos] == '*':
#                Modifier += ' ' + '*'
                StarPos += 1
            TmpStr = TmpStr[StarPos:].strip()
            RBPos = TmpStr.find(')')
            Name = TmpStr[0:RBPos]
            Value = 'FP' + TmpStr[RBPos + 1:]
        else:
            while Name.startswith('*'):
                Value += ' ' + '*'
                Name = Name.lstrip('*').strip()

        if Name.find('[') != -1:
            LBPos = Name.find('[')
            RBPos = Name.rfind(']')
            Value += Name[LBPos : RBPos + 1]
            Name = Name[0 : LBPos]

        IdTd = DataClass.IdentifierClass(-1, Modifier, '', Name, Value, DataClass.MODEL_IDENTIFIER_TYPEDEF, -1, -1, td.StartPos[0], td.StartPos[1], td.EndPos[0], td.EndPos[1])
        IdList.append(IdTd)

    for funcCall in FileProfile.FunctionCallingList:
        IdFC = DataClass.IdentifierClass(-1, '', '', funcCall.FuncName, funcCall.ParamList, DataClass.MODEL_IDENTIFIER_FUNCTION_CALLING, -1, -1, funcCall.StartPos[0], funcCall.StartPos[1], funcCall.EndPos[0], funcCall.EndPos[1])
        IdList.append(IdFC)
    return IdList

def StripNonAlnumChars(Str):
    StrippedStr = ''
    for Char in Str:
        if Char.isalnum() or Char == '_':
            StrippedStr += Char
    return StrippedStr

def GetParamList(FuncDeclarator, FuncNameLine=0, FuncNameOffset=0):
    FuncDeclarator = StripComments(FuncDeclarator)
    ParamIdList = []
    #DeclSplitList = FuncDeclarator.split('(')
    LBPos = FuncDeclarator.find('(')
    #if len(DeclSplitList) < 2:
    if LBPos == -1:
        return ParamIdList
    #FuncName = DeclSplitList[0]
    FuncName = FuncDeclarator[0:LBPos]
    #ParamStr = DeclSplitList[1].rstrip(')')
    ParamStr = FuncDeclarator[LBPos + 1:].rstrip(')')
    LineSkipped = 0
    OffsetSkipped = 0
    TailChar = FuncName[-1]
    while not TailChar.isalpha() and TailChar != '_':

        if TailChar == '\n':
            FuncName = FuncName.rstrip('\r\n').rstrip('\n')
            LineSkipped += 1
            OffsetSkipped = 0
        elif TailChar == '\r':
            FuncName = FuncName.rstrip('\r')
            LineSkipped += 1
            OffsetSkipped = 0
        elif TailChar == ' ':
            FuncName = FuncName.rstrip(' ')
            OffsetSkipped += 1
        elif TailChar == '\t':
            FuncName = FuncName.rstrip('\t')
            OffsetSkipped += 8
        else:
            FuncName = FuncName[:-1]
        TailChar = FuncName[-1]

    OffsetSkipped += 1 #skip '('

    for p in ParamStr.split(','):
        ListP = p.split()
        if len(ListP) == 0:
            continue
        ParamName = ListP[-1]
        DeclText = ParamName.strip()
        RightSpacePos = p.rfind(ParamName)
        ParamModifier = p[0:RightSpacePos]
        if ParamName == 'OPTIONAL':
            if ParamModifier == '':
                ParamModifier += ' ' + 'OPTIONAL'
                DeclText = ''
            else:
                ParamName = ListP[-2]
                DeclText = ParamName.strip()
                RightSpacePos = p.rfind(ParamName)
                ParamModifier = p[0:RightSpacePos]
                ParamModifier += 'OPTIONAL'
        while DeclText.startswith('*'):
            ParamModifier += ' ' + '*'
            DeclText = DeclText.lstrip('*').strip()
        ParamName = DeclText
        # ignore array length if exists.
        LBIndex = ParamName.find('[')
        if LBIndex != -1:
            ParamName = ParamName[0:LBIndex]

        Start = RightSpacePos
        Index = 0
        PreChar = ''
        while Index < Start:
            FirstChar = p[Index]

            if FirstChar == '\r':
                Index += 1
                LineSkipped += 1
                OffsetSkipped = 0
            elif FirstChar == '\n':
                Index += 1
                if PreChar != '\r':
                    LineSkipped += 1
                    OffsetSkipped = 0
            elif FirstChar == ' ':
                Index += 1
                OffsetSkipped += 1
            elif FirstChar == '\t':
                Index += 1
                OffsetSkipped += 8
            else:
                Index += 1
                OffsetSkipped += 1
            PreChar = FirstChar

        ParamBeginLine = FuncNameLine + LineSkipped
        ParamBeginOffset = FuncNameOffset + OffsetSkipped

        Index = Start + len(ParamName)
        PreChar = ''
        while Index < len(p):
            FirstChar = p[Index]

            if FirstChar == '\r':
                Index += 1
                LineSkipped += 1
                OffsetSkipped = 0
            elif FirstChar == '\n':
                Index += 1
                if PreChar != '\r':
                    LineSkipped += 1
                    OffsetSkipped = 0
            elif FirstChar == ' ':
                Index += 1
                OffsetSkipped += 1
            elif FirstChar == '\t':
                Index += 1
                OffsetSkipped += 8
            else:
                Index += 1
                OffsetSkipped += 1
            PreChar = FirstChar

        ParamEndLine = FuncNameLine + LineSkipped
        ParamEndOffset = FuncNameOffset + OffsetSkipped
        if ParamName != '...':
            ParamName = StripNonAlnumChars(ParamName)
        IdParam = DataClass.IdentifierClass(-1, ParamModifier, '', ParamName, '', DataClass.MODEL_IDENTIFIER_PARAMETER, -1, -1, ParamBeginLine, ParamBeginOffset, ParamEndLine, ParamEndOffset)
        ParamIdList.append(IdParam)

        OffsetSkipped += 1 #skip ','

    return ParamIdList

def GetFunctionList():
    FuncObjList = []
    for FuncDef in FileProfile.FunctionDefinitionList:
        ParamIdList = []
        DeclText = FuncDef.Declarator.lstrip()
        FuncNameStartLine = FuncDef.NamePos[0]
        FuncNameStartColumn = FuncDef.NamePos[1]
        FirstChar = DeclText[0]
        while not FirstChar.isalpha() and FirstChar != '_':
            if FirstChar == '*':
                FuncDef.Modifier += '*'
                FuncNameStartColumn += 1
                DeclText = DeclText.lstrip('*')
            elif FirstChar == '\r':
                DeclText = DeclText.lstrip('\r\n').lstrip('\r')
                FuncNameStartLine += 1
                FuncNameStartColumn = 0
            elif FirstChar == '\n':
                DeclText = DeclText.lstrip('\n')
                FuncNameStartLine += 1
                FuncNameStartColumn = 0
            elif FirstChar == ' ':
                DeclText = DeclText.lstrip(' ')
                FuncNameStartColumn += 1
            elif FirstChar == '\t':
                DeclText = DeclText.lstrip('\t')
                FuncNameStartColumn += 8
            else:
                DeclText = DeclText[1:]
                FuncNameStartColumn += 1
            FirstChar = DeclText[0]

        FuncDef.Declarator = DeclText
        DeclSplitList = FuncDef.Declarator.split('(')
        if len(DeclSplitList) < 2:
            continue

        FuncName = DeclSplitList[0]
        FuncNamePartList = FuncName.split()
        if len(FuncNamePartList) > 1:
            FuncName = FuncNamePartList[-1]
            NameStart = DeclSplitList[0].rfind(FuncName)
            if NameStart > 0:
                FuncDef.Modifier += ' ' + DeclSplitList[0][0:NameStart]
                Index = 0
                PreChar = ''
                while Index < NameStart:
                    FirstChar = DeclSplitList[0][Index]
                    if DeclSplitList[0][Index:].startswith('EFIAPI'):
                        Index += 6
                        FuncNameStartColumn += 6
                        PreChar = ''
                        continue
                    elif FirstChar == '\r':
                        Index += 1
                        FuncNameStartLine += 1
                        FuncNameStartColumn = 0
                    elif FirstChar == '\n':
                        Index += 1
                        if PreChar != '\r':
                            FuncNameStartLine += 1
                            FuncNameStartColumn = 0
                    elif FirstChar == ' ':
                        Index += 1
                        FuncNameStartColumn += 1
                    elif FirstChar == '\t':
                        Index += 1
                        FuncNameStartColumn += 8
                    else:
                        Index += 1
                        FuncNameStartColumn += 1
                    PreChar = FirstChar

        FuncObj = DataClass.FunctionClass(-1, FuncDef.Declarator, FuncDef.Modifier, FuncName.strip(), '', FuncDef.StartPos[0], FuncDef.StartPos[1], FuncDef.EndPos[0], FuncDef.EndPos[1], FuncDef.LeftBracePos[0], FuncDef.LeftBracePos[1], -1, ParamIdList, [], FuncNameStartLine, FuncNameStartColumn)
        FuncObjList.append(FuncObj)

    return FuncObjList

def GetFileModificationTimeFromDB(FullFileName):
    TimeValue = 0.0
    Db = GetDB()
    SqlStatement = """ select TimeStamp
                       from File
                       where FullPath = \'%s\'
                   """ % (FullFileName)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        TimeValue = Result[0]
    return TimeValue

def CollectSourceCodeDataIntoDB(RootDir):
    FileObjList = []
    tuple = os.walk(RootDir)
    IgnoredPattern = GetIgnoredDirListPattern()
    ParseErrorFileList = []
    TokenReleaceList = EccGlobalData.gConfig.TokenReleaceList
    TokenReleaceList.extend(['L",\\\""'])

    for dirpath, dirnames, filenames in tuple:
        if IgnoredPattern.match(dirpath.upper()):
            continue

        for Dir in dirnames:
            Dirname = os.path.join(dirpath, Dir)
            if os.path.islink(Dirname):
                Dirname = os.path.realpath(Dirname)
                if os.path.isdir(Dirname):
                    # symlinks to directories are treated as directories
                    dirnames.remove(Dir)
                    dirnames.append(Dirname)

        for f in filenames:
            if f.lower() in EccGlobalData.gConfig.SkipFileList:
                continue
            collector = None
            FullName = os.path.normpath(os.path.join(dirpath, f))
            model = DataClass.MODEL_FILE_OTHERS
            if os.path.splitext(f)[1] in ('.h', '.c'):
                EdkLogger.info("Parsing " + FullName)
                model = f.endswith('c') and DataClass.MODEL_FILE_C or DataClass.MODEL_FILE_H
                collector = CodeFragmentCollector.CodeFragmentCollector(FullName)
                collector.TokenReleaceList = TokenReleaceList
                try:
                    collector.ParseFile()
                except UnicodeError:
                    ParseErrorFileList.append(FullName)
                    collector.CleanFileProfileBuffer()
                    collector.ParseFileWithClearedPPDirective()
#                collector.PrintFragments()
            BaseName = os.path.basename(f)
            DirName = os.path.dirname(FullName)
            Ext = os.path.splitext(f)[1].lstrip('.')
            ModifiedTime = os.path.getmtime(FullName)
            FileObj = DataClass.FileClass(-1, BaseName, Ext, DirName, FullName, model, ModifiedTime, GetFunctionList(), GetIdentifierList(), [])
            FileObjList.append(FileObj)
            if collector:
                collector.CleanFileProfileBuffer()

    if len(ParseErrorFileList) > 0:
        EdkLogger.info("Found unrecoverable error during parsing:\n\t%s\n" % "\n\t".join(ParseErrorFileList))

    Db = GetDB()
    for file in FileObjList:
        if file.ExtName.upper() not in ['INF', 'DEC', 'DSC', 'FDF']:
            Db.InsertOneFile(file)

    Db.UpdateIdentifierBelongsToFunction()

def GetTableID(FullFileName, ErrorMsgList=None):
    if ErrorMsgList is None:
        ErrorMsgList = []

    Db = GetDB()
    SqlStatement = """ select ID
                       from File
                       where FullPath like '%s'
                   """ % FullFileName
    ResultSet = Db.TblFile.Exec(SqlStatement)

    FileID = -1
    for Result in ResultSet:
        if FileID != -1:
            ErrorMsgList.append('Duplicate file ID found in DB for file %s' % FullFileName)
            return - 2
        FileID = Result[0]
    if FileID == -1:
        ErrorMsgList.append('NO file ID found in DB for file %s' % FullFileName)
        return - 1
    return FileID

def GetIncludeFileList(FullFileName):
    if os.path.splitext(FullFileName)[1].upper() not in ('.H'):
        return []
    IFList = IncludeFileListDict.get(FullFileName)
    if IFList is not None:
        return IFList

    FileID = GetTableID(FullFileName)
    if FileID < 0:
        return []

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_INCLUDE)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    IncludeFileListDict[FullFileName] = ResultSet
    return ResultSet

def GetFullPathOfIncludeFile(Str, IncludePathList):
    for IncludePath in IncludePathList:
        FullPath = os.path.join(IncludePath, Str)
        FullPath = os.path.normpath(FullPath)
        if os.path.exists(FullPath):
            return FullPath
    return None

def GetAllIncludeFiles(FullFileName):
    if AllIncludeFileListDict.get(FullFileName) is not None:
        return AllIncludeFileListDict.get(FullFileName)

    FileDirName = os.path.dirname(FullFileName)
    IncludePathList = IncludePathListDict.get(FileDirName)
    if IncludePathList is None:
        IncludePathList = MetaDataParser.GetIncludeListOfFile(EccGlobalData.gWorkspace, FullFileName, GetDB())
        if FileDirName not in IncludePathList:
            IncludePathList.insert(0, FileDirName)
        IncludePathListDict[FileDirName] = IncludePathList
    IncludeFileQueue = []
    for IncludeFile in GetIncludeFileList(FullFileName):
        FileName = IncludeFile[0].lstrip('#').strip()
        FileName = FileName.lstrip('include').strip()
        FileName = FileName.strip('\"')
        FileName = FileName.lstrip('<').rstrip('>').strip()
        FullPath = GetFullPathOfIncludeFile(FileName, IncludePathList)
        if FullPath is not None:
            IncludeFileQueue.append(FullPath)

    i = 0
    while i < len(IncludeFileQueue):
        for IncludeFile in GetIncludeFileList(IncludeFileQueue[i]):
            FileName = IncludeFile[0].lstrip('#').strip()
            FileName = FileName.lstrip('include').strip()
            FileName = FileName.strip('\"')
            FileName = FileName.lstrip('<').rstrip('>').strip()
            FullPath = GetFullPathOfIncludeFile(FileName, IncludePathList)
            if FullPath is not None and FullPath not in IncludeFileQueue:
                IncludeFileQueue.insert(i + 1, FullPath)
        i += 1

    AllIncludeFileListDict[FullFileName] = IncludeFileQueue
    return IncludeFileQueue

def GetPredicateListFromPredicateExpStr(PES):

    PredicateList = []
    i = 0
    PredicateBegin = 0
    #PredicateEnd = 0
    LogicOpPos = -1
    p = GetFuncDeclPattern()
    while i < len(PES) - 1:
        if (PES[i].isalnum() or PES[i] == '_' or PES[i] == '*') and LogicOpPos > PredicateBegin:
            PredicateBegin = i
        if (PES[i] == '&' and PES[i + 1] == '&') or (PES[i] == '|' and PES[i + 1] == '|'):
            LogicOpPos = i
            Exp = PES[PredicateBegin:i].strip()
            # Exp may contain '.' or '->'
            TmpExp = Exp.replace('.', '').replace('->', '')
            if p.match(TmpExp):
                PredicateList.append(Exp)
            else:
                PredicateList.append(Exp.rstrip(';').rstrip(')').strip())
        i += 1

    if PredicateBegin > LogicOpPos:
        while PredicateBegin < len(PES):
            if PES[PredicateBegin].isalnum() or PES[PredicateBegin] == '_' or PES[PredicateBegin] == '*':
                break
            PredicateBegin += 1
        Exp = PES[PredicateBegin:len(PES)].strip()
        # Exp may contain '.' or '->'
        TmpExp = Exp.replace('.', '').replace('->', '')
        if p.match(TmpExp):
            PredicateList.append(Exp)
        else:
            PredicateList.append(Exp.rstrip(';').rstrip(')').strip())
    return PredicateList

def GetCNameList(Lvalue, StarList=[]):
    Lvalue += ' '
    i = 0
    SearchBegin = 0
    VarStart = -1
    VarEnd = -1
    VarList = []

    while SearchBegin < len(Lvalue):
        while i < len(Lvalue):
            if Lvalue[i].isalnum() or Lvalue[i] == '_':
                if VarStart == -1:
                    VarStart = i
                VarEnd = i
                i += 1
            elif VarEnd != -1:
                VarList.append(Lvalue[VarStart:VarEnd + 1])
                i += 1
                break
            else:
                if VarStart == -1 and Lvalue[i] == '*':
                    StarList.append('*')
                i += 1
        if VarEnd == -1:
            break


        DotIndex = Lvalue[VarEnd:].find('.')
        ArrowIndex = Lvalue[VarEnd:].find('->')
        if DotIndex == -1 and ArrowIndex == -1:
            break
        elif DotIndex == -1 and ArrowIndex != -1:
            SearchBegin = VarEnd + ArrowIndex
        elif ArrowIndex == -1 and DotIndex != -1:
            SearchBegin = VarEnd + DotIndex
        else:
            SearchBegin = VarEnd + ((DotIndex < ArrowIndex) and DotIndex or ArrowIndex)

        i = SearchBegin
        VarStart = -1
        VarEnd = -1

    return VarList

def SplitPredicateByOp(Str, Op, IsFuncCalling=False):

    Name = Str.strip()
    Value = None

    if IsFuncCalling:
        Index = 0
        LBFound = False
        UnmatchedLBCount = 0
        while Index < len(Str):
            while not LBFound and Str[Index] != '_' and not Str[Index].isalnum():
                Index += 1

            while not LBFound and (Str[Index].isalnum() or Str[Index] == '_'):
                Index += 1
            # maybe type-cast at the beginning, skip it.
            RemainingStr = Str[Index:].lstrip()
            if RemainingStr.startswith(')') and not LBFound:
                Index += 1
                continue

            if RemainingStr.startswith('(') and not LBFound:
                LBFound = True

            if Str[Index] == '(':
                UnmatchedLBCount += 1
                Index += 1
                continue

            if Str[Index] == ')':
                UnmatchedLBCount -= 1
                Index += 1
                if UnmatchedLBCount == 0:
                    break
                continue

            Index += 1

        if UnmatchedLBCount > 0:
            return [Name]

        IndexInRemainingStr = Str[Index:].find(Op)
        if IndexInRemainingStr == -1:
            return [Name]

        Name = Str[0:Index + IndexInRemainingStr].strip()
        Value = Str[Index + IndexInRemainingStr + len(Op):].strip().strip(')')
        return [Name, Value]

    TmpStr = Str.rstrip(';').rstrip(')')
    while True:
        Index = TmpStr.rfind(Op)
        if Index == -1:
            return [Name]

        if Str[Index - 1].isalnum() or Str[Index - 1].isspace() or Str[Index - 1] == ')' or Str[Index - 1] == ']':
            Name = Str[0:Index].strip()
            Value = Str[Index + len(Op):].strip()
            return [Name, Value]

        TmpStr = Str[0:Index - 1]

def SplitPredicateStr(Str):

    Str = Str.lstrip('(')
    IsFuncCalling = False
    p = GetFuncDeclPattern()
    TmpStr = Str.replace('.', '').replace('->', '')
    if p.match(TmpStr):
        IsFuncCalling = True

    PredPartList = SplitPredicateByOp(Str, '==', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '==']

    PredPartList = SplitPredicateByOp(Str, '!=', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '!=']

    PredPartList = SplitPredicateByOp(Str, '>=', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '>=']

    PredPartList = SplitPredicateByOp(Str, '<=', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '<=']

    PredPartList = SplitPredicateByOp(Str, '>', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '>']

    PredPartList = SplitPredicateByOp(Str, '<', IsFuncCalling)
    if len(PredPartList) > 1:
        return [PredPartList, '<']

    return [[Str, None], None]

def GetFuncContainsPE(ExpLine, ResultSet):
    for Result in ResultSet:
        if Result[0] < ExpLine and Result[1] > ExpLine:
            return Result
    return None

def PatternInModifier(Modifier, SubStr):
    PartList = Modifier.split()
    for Part in PartList:
        if Part == SubStr:
            return True
    return False

def GetDataTypeFromModifier(ModifierStr):
    MList = ModifierStr.split()
    ReturnType = ''
    for M in MList:
        if M in EccGlobalData.gConfig.ModifierSet:
            continue
        # remove array suffix
        if M.startswith('[') or M.endswith(']'):
            continue
        ReturnType += M + ' '

    ReturnType = ReturnType.strip()
    if len(ReturnType) == 0:
        ReturnType = 'VOID'
    return ReturnType

def DiffModifier(Str1, Str2):
    PartList1 = Str1.split()
    PartList2 = Str2.split()
    if PartList1 == PartList2:
        return False
    else:
        return True

def GetTypedefDict(FullFileName):

    Dict = ComplexTypeDict.get(FullFileName)
    if Dict is not None:
        return Dict

    FileID = GetTableID(FullFileName)
    FileTable = 'Identifier' + str(FileID)
    Db = GetDB()
    SqlStatement = """ select Modifier, Name, Value, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_TYPEDEF)
    ResultSet = Db.TblFile.Exec(SqlStatement)

    Dict = {}
    for Result in ResultSet:
        if len(Result[0]) == 0:
            Dict[Result[1]] = Result[2]

    IncludeFileList = GetAllIncludeFiles(FullFileName)
    for F in IncludeFileList:
        FileID = GetTableID(F)
        if FileID < 0:
            continue

        FileTable = 'Identifier' + str(FileID)
        SqlStatement = """ select Modifier, Name, Value, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_TYPEDEF)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            if not Result[2].startswith('FP ('):
                Dict[Result[1]] = Result[2]
            else:
                if len(Result[0]) == 0:
                    Dict[Result[1]] = 'VOID'
                else:
                    Dict[Result[1]] = GetDataTypeFromModifier(Result[0])

    ComplexTypeDict[FullFileName] = Dict
    return Dict

def GetSUDict(FullFileName):

    Dict = SUDict.get(FullFileName)
    if Dict is not None:
        return Dict

    FileID = GetTableID(FullFileName)
    FileTable = 'Identifier' + str(FileID)
    Db = GetDB()
    SqlStatement = """ select Name, Value, ID
                       from %s
                       where Model = %d or Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_STRUCTURE, DataClass.MODEL_IDENTIFIER_UNION)
    ResultSet = Db.TblFile.Exec(SqlStatement)

    Dict = {}
    for Result in ResultSet:
        if len(Result[1]) > 0:
            Dict[Result[0]] = Result[1]

    IncludeFileList = GetAllIncludeFiles(FullFileName)
    for F in IncludeFileList:
        FileID = GetTableID(F)
        if FileID < 0:
            continue

        FileTable = 'Identifier' + str(FileID)
        SqlStatement = """ select Name, Value, ID
                       from %s
                       where Model = %d or Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_STRUCTURE, DataClass.MODEL_IDENTIFIER_UNION)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            if len(Result[1]) > 0:
                Dict[Result[0]] = Result[1]

    SUDict[FullFileName] = Dict
    return Dict

def StripComments(Str):
    Str += '   '
    ListFromStr = list(Str)

    InComment = False
    DoubleSlashComment = False
    Index = 0
    while Index < len(ListFromStr):
        # meet new line, then no longer in a comment for //
        if ListFromStr[Index] == '\n':
            if InComment and DoubleSlashComment:
                InComment = False
                DoubleSlashComment = False
            Index += 1
        # check for */ comment end
        elif InComment and not DoubleSlashComment and ListFromStr[Index] == '*' and ListFromStr[Index + 1] == '/':
            ListFromStr[Index] = ' '
            Index += 1
            ListFromStr[Index] = ' '
            Index += 1
            InComment = False
        # set comments to spaces
        elif InComment:
            ListFromStr[Index] = ' '
            Index += 1
        # check for // comment
        elif ListFromStr[Index] == '/' and ListFromStr[Index + 1] == '/':
            InComment = True
            DoubleSlashComment = True

        # check for /* comment start
        elif ListFromStr[Index] == '/' and ListFromStr[Index + 1] == '*':
            ListFromStr[Index] = ' '
            Index += 1
            ListFromStr[Index] = ' '
            Index += 1
            InComment = True
        else:
            Index += 1

    # restore from List to String
    Str = "".join(ListFromStr)
    Str = Str.rstrip(' ')

    return Str

def GetFinalTypeValue(Type, FieldName, TypedefDict, SUDict):
    Value = TypedefDict.get(Type)
    if Value is None:
        Value = SUDict.get(Type)
    if Value is None:
        return None

    LBPos = Value.find('{')
    while LBPos == -1:
        FTList = Value.split()
        for FT in FTList:
            if FT not in ('struct', 'union'):
                Value = TypedefDict.get(FT)
                if Value is None:
                    Value = SUDict.get(FT)
                break

        if Value is None:
            return None

        LBPos = Value.find('{')

#    RBPos = Value.find('}')
    Fields = Value[LBPos + 1:]
    Fields = StripComments(Fields)
    FieldsList = Fields.split(';')
    for Field in FieldsList:
        Field = Field.strip()
        Index = Field.rfind(FieldName)
        if Index < 1:
            continue
        if not Field[Index - 1].isalnum():
            if Index + len(FieldName) == len(Field):
                Type = GetDataTypeFromModifier(Field[0:Index])
                return Type.strip()
            else:
            # For the condition that the field in struct is an array with [] suffixes...
                if not Field[Index + len(FieldName)].isalnum():
                    Type = GetDataTypeFromModifier(Field[0:Index])
                    return Type.strip()

    return None

def GetRealType(Type, TypedefDict, TargetType=None):
    if TargetType is not None and Type == TargetType:
            return Type
    while TypedefDict.get(Type):
        Type = TypedefDict.get(Type)
        if TargetType is not None and Type == TargetType:
            return Type
    return Type

def GetTypeInfo(RefList, Modifier, FullFileName, TargetType=None):
    TypedefDict = GetTypedefDict(FullFileName)
    SUDict = GetSUDict(FullFileName)
    Type = GetDataTypeFromModifier(Modifier).replace('*', '').strip()

    Type = Type.split()[-1]
    Index = 0
    while Index < len(RefList):
        FieldName = RefList[Index]
        FromType = GetFinalTypeValue(Type, FieldName, TypedefDict, SUDict)
        if FromType is None:
            return None
        # we want to determine the exact type.
        if TargetType is not None:
            Type = FromType.split()[0]
        # we only want to check if it is a pointer
        else:
            Type = FromType
            if Type.find('*') != -1 and Index == len(RefList) - 1:
                return Type
            Type = FromType.split()[0]

        Index += 1

    Type = GetRealType(Type, TypedefDict, TargetType)

    return Type

def GetVarInfo(PredVarList, FuncRecord, FullFileName, IsFuncCall=False, TargetType=None, StarList=None):

    PredVar = PredVarList[0]
    FileID = GetTableID(FullFileName)

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    # search variable in include files

    # it is a function call, search function declarations and definitions
    if IsFuncCall:
        SqlStatement = """ select Modifier, ID
                       from %s
                       where Model = %d and Value = \'%s\'
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION, PredVar)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            Type = GetDataTypeFromModifier(Result[0]).split()[-1]
            TypedefDict = GetTypedefDict(FullFileName)
            Type = GetRealType(Type, TypedefDict, TargetType)
            return Type

        IncludeFileList = GetAllIncludeFiles(FullFileName)
        for F in IncludeFileList:
            FileID = GetTableID(F)
            if FileID < 0:
                continue

            FileTable = 'Identifier' + str(FileID)
            SqlStatement = """ select Modifier, ID
                           from %s
                           where Model = %d and Value = \'%s\'
                       """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION, PredVar)
            ResultSet = Db.TblFile.Exec(SqlStatement)

            for Result in ResultSet:
                Type = GetDataTypeFromModifier(Result[0]).split()[-1]
                TypedefDict = GetTypedefDict(FullFileName)
                Type = GetRealType(Type, TypedefDict, TargetType)
                return Type

        FileID = GetTableID(FullFileName)
        SqlStatement = """ select Modifier, ID
                       from Function
                       where BelongsToFile = %d and Name = \'%s\'
                   """ % (FileID, PredVar)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            Type = GetDataTypeFromModifier(Result[0]).split()[-1]
            TypedefDict = GetTypedefDict(FullFileName)
            Type = GetRealType(Type, TypedefDict, TargetType)
            return Type

        for F in IncludeFileList:
            FileID = GetTableID(F)
            if FileID < 0:
                continue

            FileTable = 'Identifier' + str(FileID)
            SqlStatement = """ select Modifier, ID
                           from Function
                           where BelongsToFile = %d and Name = \'%s\'
                       """ % (FileID, PredVar)
            ResultSet = Db.TblFile.Exec(SqlStatement)

            for Result in ResultSet:
                Type = GetDataTypeFromModifier(Result[0]).split()[-1]
                TypedefDict = GetTypedefDict(FullFileName)
                Type = GetRealType(Type, TypedefDict, TargetType)
                return Type

        return None

    # really variable, search local variable first
    SqlStatement = """ select Modifier, ID
                       from %s
                       where Model = %d and Name = \'%s\' and StartLine >= %d and StartLine <= %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE, PredVar, FuncRecord[0], FuncRecord[1])
    ResultSet = Db.TblFile.Exec(SqlStatement)
    VarFound = False
    for Result in ResultSet:
        if len(PredVarList) > 1:
            Type = GetTypeInfo(PredVarList[1:], Result[0], FullFileName, TargetType)
            return Type
        else:
#            Type = GetDataTypeFromModifier(Result[0]).split()[-1]
            TypeList = GetDataTypeFromModifier(Result[0]).split()
            Type = TypeList[-1]
            if len(TypeList) > 1 and StarList is not None:
                for Star in StarList:
                    Type = Type.strip()
                    Type = Type.rstrip(Star)
                # Get real type after de-reference pointers.
                if len(Type.strip()) == 0:
                    Type = TypeList[-2]
            TypedefDict = GetTypedefDict(FullFileName)
            Type = GetRealType(Type, TypedefDict, TargetType)
            return Type

    # search function parameters second
    ParamList = GetParamList(FuncRecord[2])
    for Param in ParamList:
        if Param.Name.strip() == PredVar:
            if len(PredVarList) > 1:
                Type = GetTypeInfo(PredVarList[1:], Param.Modifier, FullFileName, TargetType)
                return Type
            else:
                TypeList = GetDataTypeFromModifier(Param.Modifier).split()
                Type = TypeList[-1]
                if Type == '*' and len(TypeList) >= 2:
                    Type = TypeList[-2]
                if len(TypeList) > 1 and StarList is not None:
                    for Star in StarList:
                        Type = Type.strip()
                        Type = Type.rstrip(Star)
                    # Get real type after de-reference pointers.
                    if len(Type.strip()) == 0:
                        Type = TypeList[-2]
                TypedefDict = GetTypedefDict(FullFileName)
                Type = GetRealType(Type, TypedefDict, TargetType)
                return Type

    # search global variable next
    SqlStatement = """ select Modifier, ID
           from %s
           where Model = %d and Name = \'%s\' and BelongsToFunction = -1
       """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE, PredVar)
    ResultSet = Db.TblFile.Exec(SqlStatement)

    for Result in ResultSet:
        if len(PredVarList) > 1:
            Type = GetTypeInfo(PredVarList[1:], Result[0], FullFileName, TargetType)
            return Type
        else:
            TypeList = GetDataTypeFromModifier(Result[0]).split()
            Type = TypeList[-1]
            if len(TypeList) > 1 and StarList is not None:
                for Star in StarList:
                    Type = Type.strip()
                    Type = Type.rstrip(Star)
                # Get real type after de-reference pointers.
                if len(Type.strip()) == 0:
                    Type = TypeList[-2]
            TypedefDict = GetTypedefDict(FullFileName)
            Type = GetRealType(Type, TypedefDict, TargetType)
            return Type

    IncludeFileList = GetAllIncludeFiles(FullFileName)
    for F in IncludeFileList:
        FileID = GetTableID(F)
        if FileID < 0:
            continue

        FileTable = 'Identifier' + str(FileID)
        SqlStatement = """ select Modifier, ID
                       from %s
                       where Model = %d and BelongsToFunction = -1 and Name = \'%s\'
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE, PredVar)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            if len(PredVarList) > 1:
                Type = GetTypeInfo(PredVarList[1:], Result[0], FullFileName, TargetType)
                return Type
            else:
                TypeList = GetDataTypeFromModifier(Result[0]).split()
                Type = TypeList[-1]
                if len(TypeList) > 1 and StarList is not None:
                    for Star in StarList:
                        Type = Type.strip()
                        Type = Type.rstrip(Star)
                    # Get real type after de-reference pointers.
                    if len(Type.strip()) == 0:
                        Type = TypeList[-2]
                TypedefDict = GetTypedefDict(FullFileName)
                Type = GetRealType(Type, TypedefDict, TargetType)
                return Type

def GetTypeFromArray(Type, Var):
    Count = Var.count('[')

    while Count > 0:
        Type = Type.strip()
        Type = Type.rstrip('*')
        Count = Count - 1

    return Type

def CheckFuncLayoutReturnType(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Modifier, ID, StartLine, StartColumn, EndLine, Value
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ReturnType = GetDataTypeFromModifier(Result[0])
        TypeStart = ReturnType.split()[0]
        FuncName = Result[5]
        if EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_RETURN_TYPE, FuncName):
            continue
        Result0 = Result[0]
        if Result0.upper().startswith('STATIC'):
            Result0 = Result0[6:].strip()
        Index = Result0.find(TypeStart)
        if Index != 0 or Result[3] != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_RETURN_TYPE, '[%s] Return Type should appear at the start of line' % FuncName, FileTable, Result[1])

        if Result[2] == Result[4]:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_RETURN_TYPE, '[%s] Return Type should appear on its own line' % FuncName, FileTable, Result[1])

    SqlStatement = """ select Modifier, ID, StartLine, StartColumn, FunNameStartLine, Name
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ReturnType = GetDataTypeFromModifier(Result[0])
        TypeStart = ReturnType.split()[0]
        FuncName = Result[5]
        if EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_RETURN_TYPE, FuncName):
            continue
        Result0 = Result[0]
        if Result0.upper().startswith('STATIC'):
            Result0 = Result0[6:].strip()
        Index = Result0.find(TypeStart)
        if Index != 0 or Result[3] != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_RETURN_TYPE, '[%s] Return Type should appear at the start of line' % FuncName, 'Function', Result[1])

def CheckFuncLayoutModifier(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Modifier, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ReturnType = GetDataTypeFromModifier(Result[0])
        TypeStart = ReturnType.split()[0]
        Result0 = Result[0]
        if Result0.upper().startswith('STATIC'):
            Result0 = Result0[6:].strip()
        Index = Result0.find(TypeStart)
        if Index != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_OPTIONAL_FUNCTIONAL_MODIFIER, '', FileTable, Result[1])

    SqlStatement = """ select Modifier, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ReturnType = GetDataTypeFromModifier(Result[0])
        TypeStart = ReturnType.split()[0]
        Result0 = Result[0]
        if Result0.upper().startswith('STATIC'):
            Result0 = Result0[6:].strip()
        Index = Result0.find(TypeStart)
        if Index != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_OPTIONAL_FUNCTIONAL_MODIFIER, '', 'Function', Result[1])

def CheckFuncLayoutName(FullFileName):
    ErrorMsgList = []
    # Parameter variable format pattern.
    Pattern = re.compile(r'^[A-Z]+\S*[a-z]\S*$')
    ParamIgnoreList = ('VOID', '...')
    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Name, ID, EndColumn, Value
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        FuncName = Result[3]
        if EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, FuncName):
            continue
        if Result[2] != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Function name [%s] should appear at the start of a line' % FuncName, FileTable, Result[1])
        ParamList = GetParamList(Result[0])
        if len(ParamList) == 0:
            continue
        StartLine = 0
        for Param in ParamList:
            if Param.StartLine <= StartLine:
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Parameter %s should be in its own line.' % Param.Name, FileTable, Result[1])
            if Param.StartLine - StartLine > 1:
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Empty line appears before Parameter %s.' % Param.Name, FileTable, Result[1])
            if not Pattern.match(Param.Name) and not Param.Name in ParamIgnoreList and not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Param.Name):
                PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, 'Parameter [%s] NOT follow naming convention.' % Param.Name, FileTable, Result[1])
            StartLine = Param.StartLine

        if not Result[0].endswith('\n  )') and not Result[0].endswith('\r  )'):
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, '\')\' should be on a new line and indented two spaces', FileTable, Result[1])

    SqlStatement = """ select Modifier, ID, FunNameStartColumn, Name
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        FuncName = Result[3]
        if EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, FuncName):
            continue
        if Result[2] != 0:
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Function name [%s] should appear at the start of a line' % FuncName, 'Function', Result[1])
        ParamList = GetParamList(Result[0])
        if len(ParamList) == 0:
            continue
        StartLine = 0
        for Param in ParamList:
            if Param.StartLine <= StartLine:
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Parameter %s should be in its own line.' % Param.Name, 'Function', Result[1])
            if Param.StartLine - StartLine > 1:
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, 'Empty line appears before Parameter %s.' % Param.Name, 'Function', Result[1])
            if not Pattern.match(Param.Name) and not Param.Name in ParamIgnoreList and not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Param.Name):
                PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, 'Parameter [%s] NOT follow naming convention.' % Param.Name, FileTable, Result[1])
            StartLine = Param.StartLine
        if not Result[0].endswith('\n  )') and not Result[0].endswith('\r  )'):
            PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, '\')\' should be on a new line and indented two spaces', 'Function', Result[1])

def CheckFuncLayoutPrototype(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    FileTable = 'Identifier' + str(FileID)
    Db = GetDB()
    SqlStatement = """ select Modifier, Header, Name, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return ErrorMsgList

    FuncDefList = []
    for Result in ResultSet:
        FuncDefList.append(Result)

    SqlStatement = """ select Modifier, Name, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    FuncDeclList = []
    for Result in ResultSet:
        FuncDeclList.append(Result)

    UndeclFuncList = []
    for FuncDef in FuncDefList:
        FuncName = FuncDef[2].strip()
        FuncModifier = FuncDef[0]
        FuncDefHeader = FuncDef[1]
        for FuncDecl in FuncDeclList:
            LBPos = FuncDecl[1].find('(')
            DeclName = FuncDecl[1][0:LBPos].strip()
            DeclModifier = FuncDecl[0]
            if DeclName == FuncName:
                if DiffModifier(FuncModifier, DeclModifier) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE, FuncName):
                    PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE, 'Function [%s] modifier different with prototype.' % FuncName, 'Function', FuncDef[3])
                ParamListOfDef = GetParamList(FuncDefHeader)
                ParamListOfDecl = GetParamList(FuncDecl[1])
                if len(ParamListOfDef) != len(ParamListOfDecl) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_2, FuncName):
                    PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_2, 'Parameter number different in function [%s].' % FuncName, 'Function', FuncDef[3])
                    break

                Index = 0
                while Index < len(ParamListOfDef):
                    if DiffModifier(ParamListOfDef[Index].Modifier, ParamListOfDecl[Index].Modifier) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_3, FuncName):
                        PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_3, 'Parameter %s has different modifier with prototype in function [%s].' % (ParamListOfDef[Index].Name, FuncName), 'Function', FuncDef[3])
                    Index += 1
                break
        else:
            UndeclFuncList.append(FuncDef)

    IncludeFileList = GetAllIncludeFiles(FullFileName)
    FuncDeclList = []
    for F in IncludeFileList:
        FileID = GetTableID(F, ErrorMsgList)
        if FileID < 0:
            continue

        FileTable = 'Identifier' + str(FileID)
        SqlStatement = """ select Modifier, Name, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
        ResultSet = Db.TblFile.Exec(SqlStatement)

        for Result in ResultSet:
            FuncDeclList.append(Result)

    for FuncDef in UndeclFuncList:
        FuncName = FuncDef[2].strip()
        FuncModifier = FuncDef[0]
        FuncDefHeader = FuncDef[1]
        for FuncDecl in FuncDeclList:
            LBPos = FuncDecl[1].find('(')
            DeclName = FuncDecl[1][0:LBPos].strip()
            DeclModifier = FuncDecl[0]
            if DeclName == FuncName:
                if DiffModifier(FuncModifier, DeclModifier) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE, FuncName):
                    PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE, 'Function [%s] modifier different with prototype.' % FuncName, 'Function', FuncDef[3])
                ParamListOfDef = GetParamList(FuncDefHeader)
                ParamListOfDecl = GetParamList(FuncDecl[1])
                if len(ParamListOfDef) != len(ParamListOfDecl) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_2, FuncName):
                    PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_2, 'Parameter number different in function [%s].' % FuncName, 'Function', FuncDef[3])
                    break

                Index = 0
                while Index < len(ParamListOfDef):
                    if DiffModifier(ParamListOfDef[Index].Modifier, ParamListOfDecl[Index].Modifier) and not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_3, FuncName):
                        PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_PROTO_TYPE_3, 'Parameter %s has different modifier with prototype in function [%s].' % (ParamListOfDef[Index].Name, FuncName), 'Function', FuncDef[3])
                    Index += 1
                break

def CheckFuncLayoutBody(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    FileTable = 'Identifier' + str(FileID)
    Db = GetDB()
    SqlStatement = """ select BodyStartColumn, EndColumn, ID, Name
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return ErrorMsgList
    for Result in ResultSet:
        if Result[0] != 0:
            if not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_BODY, Result[3]):
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_BODY,
                              'The open brace should be at the very beginning of a line for the function [%s].' % Result[3],
                              'Function', Result[2])
        if Result[1] != 0:
            if not EccGlobalData.gException.IsException(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_BODY, Result[3]):
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_BODY,
                              'The close brace should be at the very beginning of a line for the function [%s].' % Result[3],
                              'Function', Result[2])

def CheckFuncLayoutLocalVariable(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return ErrorMsgList
    FL = []
    for Result in ResultSet:
        FL.append(Result)

    for F in FL:
        SqlStatement = """ select Name, Value, ID, Modifier
                       from %s
                       where Model = %d and BelongsToFunction = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE, F[0])
        ResultSet = Db.TblFile.Exec(SqlStatement)
        if len(ResultSet) == 0:
            continue

        for Result in ResultSet:
            if len(Result[1]) > 0 and 'CONST' not in Result[3] and 'STATIC' not in Result[3]:
                PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_NO_INIT_OF_VARIABLE, 'Variable Name: %s' % Result[0], FileTable, Result[2])

def CheckMemberVariableFormat(Name, Value, FileTable, TdId, ModelId):
    ErrMsgList = []
    # Member variable format pattern.
    Pattern = re.compile(r'^[A-Z]+\S*[a-z]\S*$')

    LBPos = Value.find('{')
    RBPos = Value.rfind('}')
    if LBPos == -1 or RBPos == -1:
        return ErrMsgList

    Fields = Value[LBPos + 1 : RBPos]
    Fields = StripComments(Fields).strip()
    NestPos = Fields.find ('struct')
    if NestPos != -1 and (NestPos + len('struct') < len(Fields)) and ModelId != DataClass.MODEL_IDENTIFIER_UNION:
        if not Fields[NestPos + len('struct') + 1].isalnum():
            if not EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, Name):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, 'Nested struct in [%s].' % (Name), FileTable, TdId)
            return ErrMsgList
    NestPos = Fields.find ('union')
    if NestPos != -1 and (NestPos + len('union') < len(Fields)):
        if not Fields[NestPos + len('union') + 1].isalnum():
            if not EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, Name):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, 'Nested union in [%s].' % (Name), FileTable, TdId)
            return ErrMsgList
    NestPos = Fields.find ('enum')
    if NestPos != -1 and (NestPos + len('enum') < len(Fields)):
        if not Fields[NestPos + len('enum') + 1].isalnum():
            if not EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, Name):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NESTED_STRUCTURE, 'Nested enum in [%s].' % (Name), FileTable, TdId)
            return ErrMsgList

    if ModelId == DataClass.MODEL_IDENTIFIER_ENUMERATE:
        FieldsList = Fields.split(',')
        # deal with enum is pre-assigned a value by function call ( , , , ...)
        QuoteCount = 0
        Index = 0
        RemoveCurrentElement = False
        while Index < len(FieldsList):
            Field = FieldsList[Index]

            if Field.find('(') != -1:
                QuoteCount += 1
                RemoveCurrentElement = True
                Index += 1
                continue

            if Field.find(')') != -1 and QuoteCount > 0:
                QuoteCount -= 1

            if RemoveCurrentElement:
                FieldsList.remove(Field)
                if QuoteCount == 0:
                    RemoveCurrentElement = False
                continue

            if QuoteCount == 0:
                RemoveCurrentElement = False

            Index += 1
    else:
        FieldsList = Fields.split(';')

    for Field in FieldsList:
        Field = Field.strip()
        if Field == '':
            continue
        # For the condition that the field in struct is an array with [] suffixes...
        if Field[-1] == ']':
            LBPos = Field.find('[')
            Field = Field[0:LBPos]
        # For the condition that bit field ": Number"
        if Field.find(':') != -1:
            ColonPos = Field.find(':')
            Field = Field[0:ColonPos]

        Field = Field.strip()
        if Field == '':
            continue
        if Field.startswith("#"):
            continue
        # Enum could directly assign value to variable
        Field = Field.split('=')[0].strip()
        TokenList = Field.split()
        # Remove pointers before variable
        Token = TokenList[-1]
        if Token in ['OPTIONAL']:
            Token = TokenList[-2]
        if not Pattern.match(Token.lstrip('*')):
            ErrMsgList.append(Token.lstrip('*'))

    return ErrMsgList

def CheckDeclTypedefFormat(FullFileName, ModelId):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Name, StartLine, EndLine, ID, Value
                       from %s
                       where Model = %d
                   """ % (FileTable, ModelId)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    ResultList = []
    for Result in ResultSet:
        ResultList.append(Result)

    ErrorType = ERROR_DECLARATION_DATA_TYPE_CHECK_ALL
    if ModelId == DataClass.MODEL_IDENTIFIER_STRUCTURE:
        ErrorType = ERROR_DECLARATION_DATA_TYPE_CHECK_STRUCTURE_DECLARATION
    elif ModelId == DataClass.MODEL_IDENTIFIER_ENUMERATE:
        ErrorType = ERROR_DECLARATION_DATA_TYPE_CHECK_ENUMERATED_TYPE
    elif ModelId == DataClass.MODEL_IDENTIFIER_UNION:
        ErrorType = ERROR_DECLARATION_DATA_TYPE_CHECK_UNION_TYPE

    SqlStatement = """ select Modifier, Name, Value, StartLine, EndLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_TYPEDEF)
    TdSet = Db.TblFile.Exec(SqlStatement)
    TdList = []
    for Td in TdSet:
        TdList.append(Td)
    # Check member variable name format that from typedefs of ONLY this file.
    for Td in TdList:
        Name = Td[1].strip()
        Value = Td[2].strip()
        if Value.startswith('enum'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_ENUMERATE
        elif Value.startswith('struct'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_STRUCTURE
        elif Value.startswith('union'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_UNION
        else:
            continue

        if ValueModelId != ModelId:
            continue
        # Check member variable format.
        ErrMsgList = CheckMemberVariableFormat(Name, Value, FileTable, Td[5], ModelId)
        for ErrMsg in ErrMsgList:
            if EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Name + '.' + ErrMsg):
                continue
            PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, 'Member variable [%s] NOT follow naming convention.' % (Name + '.' + ErrMsg), FileTable, Td[5])

    # First check in current file to see whether struct/union/enum is typedef-ed.
    UntypedefedList = []
    for Result in ResultList:
        # Check member variable format.
        Name = Result[0].strip()
        Value = Result[4].strip()
        if Value.startswith('enum'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_ENUMERATE
        elif Value.startswith('struct'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_STRUCTURE
        elif Value.startswith('union'):
            ValueModelId = DataClass.MODEL_IDENTIFIER_UNION
        else:
            continue

        if ValueModelId != ModelId:
            continue
        ErrMsgList = CheckMemberVariableFormat(Name, Value, FileTable, Result[3], ModelId)
        for ErrMsg in ErrMsgList:
            if EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Result[0] + '.' + ErrMsg):
                continue
            PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, 'Member variable [%s] NOT follow naming convention.' % (Result[0] + '.' + ErrMsg), FileTable, Result[3])
        # Check whether it is typedefed.
        Found = False
        for Td in TdList:
            # skip function pointer
            if len(Td[0]) > 0:
                continue
            if Result[1] >= Td[3] and Td[4] >= Result[2]:
                Found = True
                if not Td[1].isupper():
                    PrintErrorMsg(ErrorType, 'Typedef should be UPPER case', FileTable, Td[5])
            if Result[0] in Td[2].split():
                Found = True
                if not Td[1].isupper():
                    PrintErrorMsg(ErrorType, 'Typedef should be UPPER case', FileTable, Td[5])
            if Found:
                break

        if not Found:
            UntypedefedList.append(Result)
            continue

    if len(UntypedefedList) == 0:
        return

    IncludeFileList = GetAllIncludeFiles(FullFileName)
    TdList = []
    for F in IncludeFileList:
        FileID = GetTableID(F, ErrorMsgList)
        if FileID < 0:
            continue

        IncludeFileTable = 'Identifier' + str(FileID)
        SqlStatement = """ select Modifier, Name, Value, StartLine, EndLine, ID
                       from %s
                       where Model = %d
                   """ % (IncludeFileTable, DataClass.MODEL_IDENTIFIER_TYPEDEF)
        ResultSet = Db.TblFile.Exec(SqlStatement)
        TdList.extend(ResultSet)

    for Result in UntypedefedList:

        # Check whether it is typedefed.
        Found = False
        for Td in TdList:

            if len(Td[0]) > 0:
                continue
            if Result[1] >= Td[3] and Td[4] >= Result[2]:
                Found = True
                if not Td[1].isupper():
                    PrintErrorMsg(ErrorType, 'Typedef should be UPPER case', FileTable, Td[5])
            if Result[0] in Td[2].split():
                Found = True
                if not Td[1].isupper():
                    PrintErrorMsg(ErrorType, 'Typedef should be UPPER case', FileTable, Td[5])
            if Found:
                break

        if not Found:
            PrintErrorMsg(ErrorType, 'No Typedef for %s' % Result[0], FileTable, Result[3])
            continue

def CheckDeclStructTypedef(FullFileName):
    CheckDeclTypedefFormat(FullFileName, DataClass.MODEL_IDENTIFIER_STRUCTURE)

def CheckDeclEnumTypedef(FullFileName):
    CheckDeclTypedefFormat(FullFileName, DataClass.MODEL_IDENTIFIER_ENUMERATE)

def CheckDeclUnionTypedef(FullFileName):
    CheckDeclTypedefFormat(FullFileName, DataClass.MODEL_IDENTIFIER_UNION)

def CheckDeclArgModifier(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Modifier, Name, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    ModifierTuple = ('IN', 'OUT', 'OPTIONAL', 'UNALIGNED')
    MAX_MODIFIER_LENGTH = 100
    for Result in ResultSet:
        for Modifier in ModifierTuple:
            if PatternInModifier(Result[0], Modifier) and len(Result[0]) < MAX_MODIFIER_LENGTH:
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_IN_OUT_MODIFIER, 'Variable Modifier %s' % Result[0], FileTable, Result[2])
                break

    SqlStatement = """ select Modifier, Name, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        for Modifier in ModifierTuple:
            if PatternInModifier(Result[0], Modifier):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_IN_OUT_MODIFIER, 'Return Type Modifier %s' % Result[0], FileTable, Result[2])
                break

    SqlStatement = """ select Modifier, Header, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        for Modifier in ModifierTuple:
            if PatternInModifier(Result[0], Modifier):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_IN_OUT_MODIFIER, 'Return Type Modifier %s' % Result[0], FileTable, Result[2])
                break

def CheckDeclNoUseCType(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Modifier, Name, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    CTypeTuple = ('int', 'unsigned', 'char', 'void', 'long')
    for Result in ResultSet:
        for Type in CTypeTuple:
            if PatternInModifier(Result[0], Type):
                if EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE,
                                                        Result[0] + ' ' + Result[1]):
                    continue
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE,
                              'Invalid variable type (%s) in definition [%s]' % (Type, Result[0] + ' ' + Result[1]),
                              FileTable,
                              Result[2])
                break

    SqlStatement = """ select Modifier, Name, ID, Value
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ParamList = GetParamList(Result[1])
        FuncName = Result[3]
        if EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, FuncName):
            continue
        for Type in CTypeTuple:
            if PatternInModifier(Result[0], Type):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, '%s Return type %s' % (FuncName, Result[0]), FileTable, Result[2])

            for Param in ParamList:
                if PatternInModifier(Param.Modifier, Type):
                    PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, 'Parameter %s' % Param.Name, FileTable, Result[2])

    SqlStatement = """ select Modifier, Header, ID, Name
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        ParamList = GetParamList(Result[1])
        FuncName = Result[3]
        if EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, FuncName):
            continue
        for Type in CTypeTuple:
            if PatternInModifier(Result[0], Type):
                PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, '[%s] Return type %s' % (FuncName, Result[0]), FileTable, Result[2])

            for Param in ParamList:
                if PatternInModifier(Param.Modifier, Type):
                    PrintErrorMsg(ERROR_DECLARATION_DATA_TYPE_CHECK_NO_USE_C_TYPE, 'Parameter %s' % Param.Name, FileTable, Result[2])


def CheckPointerNullComparison(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    # cache the found function return type to accelerate later checking in this file.
    FuncReturnTypeDict = {}

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, StartLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_PREDICATE_EXPRESSION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return
    PSL = []
    for Result in ResultSet:
        PSL.append([Result[0], Result[1], Result[2]])

    SqlStatement = """ select BodyStartLine, EndLine, Header, Modifier, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    FL = []
    for Result in ResultSet:
        FL.append([Result[0], Result[1], Result[2], Result[3], Result[4]])

    p = GetFuncDeclPattern()
    for Str in PSL:
        FuncRecord = GetFuncContainsPE(Str[1], FL)
        if FuncRecord is None:
            continue

        for Exp in GetPredicateListFromPredicateExpStr(Str[0]):
            PredInfo = SplitPredicateStr(Exp)
            if PredInfo[1] is None:
                PredVarStr = PredInfo[0][0].strip()
                IsFuncCall = False
                SearchInCache = False
                # PredVarStr may contain '.' or '->'
                TmpStr = PredVarStr.replace('.', '').replace('->', '')
                if p.match(TmpStr):
                    PredVarStr = PredVarStr[0:PredVarStr.find('(')]
                    SearchInCache = True
                    # Only direct function call using IsFuncCall branch. Multi-level ref. function call is considered a variable.
                    if TmpStr.startswith(PredVarStr):
                        IsFuncCall = True

                if PredVarStr.strip() in IgnoredKeywordList:
                    continue
                StarList = []
                PredVarList = GetCNameList(PredVarStr, StarList)
                # No variable found, maybe value first? like (0 == VarName)
                if len(PredVarList) == 0:
                    continue
                if SearchInCache:
                    Type = FuncReturnTypeDict.get(PredVarStr)
                    if Type is not None:
                        if Type.find('*') != -1 and Type != 'BOOLEAN*':
                            PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_COMPARISON_NULL_TYPE, 'Predicate Expression: %s' % Exp, FileTable, Str[2])
                        continue

                    if PredVarStr in FuncReturnTypeDict:
                        continue

                Type = GetVarInfo(PredVarList, FuncRecord, FullFileName, IsFuncCall, None, StarList)
                if SearchInCache:
                    FuncReturnTypeDict[PredVarStr] = Type
                if Type is None:
                    continue
                Type = GetTypeFromArray(Type, PredVarStr)
                if Type.find('*') != -1 and Type != 'BOOLEAN*':
                    PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_COMPARISON_NULL_TYPE, 'Predicate Expression: %s' % Exp, FileTable, Str[2])

def CheckNonBooleanValueComparison(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    # cache the found function return type to accelerate later checking in this file.
    FuncReturnTypeDict = {}

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, StartLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_PREDICATE_EXPRESSION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return
    PSL = []
    for Result in ResultSet:
        PSL.append([Result[0], Result[1], Result[2]])

    SqlStatement = """ select BodyStartLine, EndLine, Header, Modifier, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    FL = []
    for Result in ResultSet:
        FL.append([Result[0], Result[1], Result[2], Result[3], Result[4]])

    p = GetFuncDeclPattern()
    for Str in PSL:
        FuncRecord = GetFuncContainsPE(Str[1], FL)
        if FuncRecord is None:
            continue

        for Exp in GetPredicateListFromPredicateExpStr(Str[0]):
            PredInfo = SplitPredicateStr(Exp)
            if PredInfo[1] is None:
                PredVarStr = PredInfo[0][0].strip()
                IsFuncCall = False
                SearchInCache = False
                # PredVarStr may contain '.' or '->'
                TmpStr = PredVarStr.replace('.', '').replace('->', '')
                if p.match(TmpStr):
                    PredVarStr = PredVarStr[0:PredVarStr.find('(')]
                    SearchInCache = True
                    # Only direct function call using IsFuncCall branch. Multi-level ref. function call is considered a variable.
                    if TmpStr.startswith(PredVarStr):
                        IsFuncCall = True

                if PredVarStr.strip() in IgnoredKeywordList:
                    continue
                StarList = []
                PredVarList = GetCNameList(PredVarStr, StarList)
                # No variable found, maybe value first? like (0 == VarName)
                if len(PredVarList) == 0:
                    continue

                if SearchInCache:
                    Type = FuncReturnTypeDict.get(PredVarStr)
                    if Type is not None:
                        if Type.find('BOOLEAN') == -1:
                            PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_NO_BOOLEAN_OPERATOR, 'Predicate Expression: %s' % Exp, FileTable, Str[2])
                        continue

                    if PredVarStr in FuncReturnTypeDict:
                        continue
                Type = GetVarInfo(PredVarList, FuncRecord, FullFileName, IsFuncCall, 'BOOLEAN', StarList)
                if SearchInCache:
                    FuncReturnTypeDict[PredVarStr] = Type
                if Type is None:
                    continue
                if Type.find('BOOLEAN') == -1:
                    PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_NO_BOOLEAN_OPERATOR, 'Predicate Expression: %s' % Exp, FileTable, Str[2])


def CheckBooleanValueComparison(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    # cache the found function return type to accelerate later checking in this file.
    FuncReturnTypeDict = {}

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, StartLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_PREDICATE_EXPRESSION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return
    PSL = []
    for Result in ResultSet:
        PSL.append([Result[0], Result[1], Result[2]])

    SqlStatement = """ select BodyStartLine, EndLine, Header, Modifier, ID
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    FL = []
    for Result in ResultSet:
        FL.append([Result[0], Result[1], Result[2], Result[3], Result[4]])

    p = GetFuncDeclPattern()
    for Str in PSL:
        FuncRecord = GetFuncContainsPE(Str[1], FL)
        if FuncRecord is None:
            continue

        for Exp in GetPredicateListFromPredicateExpStr(Str[0]):
            PredInfo = SplitPredicateStr(Exp)
            if PredInfo[1] in ('==', '!=') and PredInfo[0][1] in ('TRUE', 'FALSE'):
                PredVarStr = PredInfo[0][0].strip()
                IsFuncCall = False
                SearchInCache = False
                # PredVarStr may contain '.' or '->'
                TmpStr = PredVarStr.replace('.', '').replace('->', '')
                if p.match(TmpStr):
                    PredVarStr = PredVarStr[0:PredVarStr.find('(')]
                    SearchInCache = True
                    # Only direct function call using IsFuncCall branch. Multi-level ref. function call is considered a variable.
                    if TmpStr.startswith(PredVarStr):
                        IsFuncCall = True

                if PredVarStr.strip() in IgnoredKeywordList:
                    continue
                StarList = []
                PredVarList = GetCNameList(PredVarStr, StarList)
                # No variable found, maybe value first? like (0 == VarName)
                if len(PredVarList) == 0:
                    continue

                if SearchInCache:
                    Type = FuncReturnTypeDict.get(PredVarStr)
                    if Type is not None:
                        if Type.find('BOOLEAN') != -1:
                            PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_BOOLEAN_VALUE, 'Predicate Expression: %s' % Exp, FileTable, Str[2])
                        continue

                    if PredVarStr in FuncReturnTypeDict:
                        continue

                Type = GetVarInfo(PredVarList, FuncRecord, FullFileName, IsFuncCall, 'BOOLEAN', StarList)
                if SearchInCache:
                    FuncReturnTypeDict[PredVarStr] = Type
                if Type is None:
                    continue
                if Type.find('BOOLEAN') != -1:
                    PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_BOOLEAN_VALUE, 'Predicate Expression: %s' % Exp, FileTable, Str[2])


def CheckHeaderFileData(FullFileName, AllTypedefFun=[]):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select ID, Modifier
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_VARIABLE)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        if not Result[1].startswith('extern'):
            for Item in AllTypedefFun:
                if '(%s)' % Result[1] in Item:
                    break
            else:
                PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_DATA, 'Variable definition appears in header file', FileTable, Result[0])

    SqlStatement = """ select ID
                       from Function
                       where BelongsToFile = %d
                   """ % FileID
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_DATA, 'Function definition appears in header file', 'Function', Result[0])

    return ErrorMsgList

def CheckHeaderFileIfndef(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, StartLine
                       from %s
                       where Model = %d order by StartLine
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_MACRO_IFNDEF)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_IFNDEF_STATEMENT_1, '', 'File', FileID)
        return ErrorMsgList
    for Result in ResultSet:
        SqlStatement = """ select Value, EndLine
                       from %s
                       where EndLine < %d
                   """ % (FileTable, Result[1])
        ResultSet = Db.TblFile.Exec(SqlStatement)
        for Result in ResultSet:
            if not Result[0].startswith('/*') and not Result[0].startswith('//'):
                PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_IFNDEF_STATEMENT_2, '', 'File', FileID)
        break

    SqlStatement = """ select Value
                       from %s
                       where StartLine > (select max(EndLine) from %s where Model = %d)
                   """ % (FileTable, FileTable, DataClass.MODEL_IDENTIFIER_MACRO_ENDIF)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        if not Result[0].startswith('/*') and not Result[0].startswith('//'):
            PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_IFNDEF_STATEMENT_3, '', 'File', FileID)
    return ErrorMsgList

def CheckDoxygenCommand(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, ID
                       from %s
                       where Model = %d or Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_COMMENT, DataClass.MODEL_IDENTIFIER_FUNCTION_HEADER)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    DoxygenCommandList = ['bug', 'todo', 'example', 'file', 'attention', 'param', 'post', 'pre', 'retval',
                          'return', 'sa', 'since', 'test', 'note', 'par', 'endcode', 'code']
    for Result in ResultSet:
        CommentStr = Result[0]
        CommentPartList = CommentStr.split()
        for Part in CommentPartList:
            if Part.upper() == 'BUGBUG':
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMAND, 'Bug should be marked with doxygen tag @bug', FileTable, Result[1])
            if Part.upper() == 'TODO':
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMAND, 'ToDo should be marked with doxygen tag @todo', FileTable, Result[1])
            if Part.startswith('@'):
                if EccGlobalData.gException.IsException(ERROR_DOXYGEN_CHECK_COMMAND, Part):
                    continue
                if not Part.replace('@', '').strip():
                    continue
                if Part.lstrip('@') in ['{', '}']:
                    continue
                if Part.lstrip('@').isalpha():
                    if Part.lstrip('@') not in DoxygenCommandList:
                        PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMAND, 'Unknown doxygen command %s' % Part, FileTable, Result[1])
                else:
                    Index = Part.find('[')
                    if Index == -1:
                        PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMAND, 'Unknown doxygen command %s' % Part, FileTable, Result[1])
                    RealCmd = Part[1:Index]
                    if RealCmd not in DoxygenCommandList:
                        PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMAND, 'Unknown doxygen command %s' % Part, FileTable, Result[1])


def CheckDoxygenTripleForwardSlash(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()

    SqlStatement = """ select ID, BodyStartLine, BodyStartColumn, EndLine, EndColumn
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        return

    FuncDefSet = []
    for Result in ResultSet:
        FuncDefSet.append(Result)


    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, ID, StartLine, StartColumn, EndLine, EndColumn
                       from %s
                       where Model = %d

                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_COMMENT)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    CommentSet = []
    try:
        for Result in ResultSet:
            CommentSet.append(Result)
    except:
        print('Unrecognized chars in comment of file %s', FullFileName)


    for Result in CommentSet:
        CommentStr = Result[0]
        StartLine = Result[2]
        StartColumn = Result[3]
        EndLine = Result[4]
        EndColumn = Result[5]
        if not CommentStr.startswith('///<'):
            continue

        Found = False
        for FuncDef in FuncDefSet:
            if StartLine == FuncDef[1] and StartColumn > FuncDef[2] and EndLine == FuncDef[3] and EndColumn < FuncDef[4]:
                Found = True
                break
            if StartLine > FuncDef[1] and EndLine < FuncDef[3]:
                Found = True
                break
            if StartLine == FuncDef[1] and StartColumn > FuncDef[2] and EndLine < FuncDef[3]:
                Found = True
                break
            if StartLine > FuncDef[1] and EndLine == FuncDef[3] and EndColumn < FuncDef[4]:
                Found = True
                break
        if Found:
            PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMENT_FORMAT, '', FileTable, Result[1])


def CheckFileHeaderDoxygenComments(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, ID
                       from %s
                       where Model = %d and (StartLine = 1 or StartLine = 7 or StartLine = 8) and StartColumn = 0
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_COMMENT)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    if len(ResultSet) == 0:
        PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'No File License header appear at the very beginning of file.', 'File', FileID)
        return ErrorMsgList

    NoHeaderCommentStartFlag = True
    NoHeaderCommentEndFlag = True
    NoHeaderCommentPeriodFlag = True
    NoCopyrightFlag = True
    NoLicenseFlag = True
    NoRevReferFlag = True
    NextLineIndex = 0
    for Result in ResultSet:
        FileStartFlag = False
        CommentStrList = []
        CommentStr = Result[0].strip()
        CommentStrListTemp = CommentStr.split('\n')
        if (len(CommentStrListTemp) <= 1):
            # For Mac
            CommentStrListTemp = CommentStr.split('\r')
        # Skip the content before the file  header
        for CommentLine in CommentStrListTemp:
            if CommentLine.strip().startswith('/** @file'):
                FileStartFlag = True
            if FileStartFlag ==  True:
                CommentStrList.append(CommentLine)

        ID = Result[1]
        Index = 0
        if CommentStrList and CommentStrList[0].strip().startswith('/** @file'):
            NoHeaderCommentStartFlag = False
        else:
            continue
        if CommentStrList and CommentStrList[-1].strip().endswith('**/'):
            NoHeaderCommentEndFlag = False
        else:
            continue

        for CommentLine in CommentStrList:
            Index = Index + 1
            NextLineIndex = Index
            if CommentLine.startswith('/** @file'):
                continue
            if CommentLine.startswith('**/'):
                break
            # Check whether C File header Comment content start with two spaces.
            if EccGlobalData.gConfig.HeaderCheckCFileCommentStartSpacesNum == '1' or EccGlobalData.gConfig.HeaderCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
                if CommentLine.startswith('/** @file') == False and CommentLine.startswith('**/') == False and CommentLine.strip() and CommentLine.startswith('  ') == False:
                    PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'File header comment content should start with two spaces at each line', FileTable, ID)

            CommentLine = CommentLine.strip()
            if CommentLine.startswith('Copyright') or ('Copyright' in CommentLine and CommentLine.lower().startswith('(c)')):
                NoCopyrightFlag = False
                if CommentLine.find('All rights reserved') == -1:
                    for Copyright in EccGlobalData.gConfig.Copyright:
                        if CommentLine.find(Copyright) > -1:
                            PrintErrorMsg(ERROR_HEADER_CHECK_FILE, '""All rights reserved"" announcement should be following the ""Copyright"" at the same line', FileTable, ID)
                            break
                if CommentLine.endswith('<BR>') == -1:
                    PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'The ""<BR>"" at the end of the Copyright line is required', FileTable, ID)
                if NextLineIndex < len(CommentStrList) and CommentStrList[NextLineIndex].strip().startswith('Copyright') == False and CommentStrList[NextLineIndex].strip():
                    NoLicenseFlag = False
            if CommentLine.startswith('@par Revision Reference:'):
                NoRevReferFlag = False
                RefListFlag = False
                for RefLine in CommentStrList[NextLineIndex:]:
                    if RefLine.strip() and (NextLineIndex + 1) < len(CommentStrList) and CommentStrList[NextLineIndex+1].strip() and CommentStrList[NextLineIndex+1].strip().startswith('**/') == False:
                        RefListFlag = True
                    if RefLine.strip() == False or RefLine.strip().startswith('**/'):
                        RefListFlag = False
                        break
                    # Check whether C File header Comment's each reference at list should begin with a bullet character.
                    if EccGlobalData.gConfig.HeaderCheckCFileCommentReferenceFormat == '1' or EccGlobalData.gConfig.HeaderCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
                        if RefListFlag == True:
                            if RefLine.strip() and RefLine.strip().startswith('**/') == False and RefLine.startswith('  -') == False:
                                PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'Each reference on a separate line should begin with a bullet character ""-"" ', FileTable, ID)

    if NoHeaderCommentStartFlag:
        PrintErrorMsg(ERROR_DOXYGEN_CHECK_FILE_HEADER, 'File header comment should begin with ""/** @file""', FileTable, ID)
        return
    if NoHeaderCommentEndFlag:
        PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'File header comment should end with ""**/""', FileTable, ID)
        return
    if NoCopyrightFlag:
        PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'File header comment missing the ""Copyright""', FileTable, ID)
    #Check whether C File header Comment have the License immediately after the ""Copyright"" line.
    if EccGlobalData.gConfig.HeaderCheckCFileCommentLicenseFormat == '1' or EccGlobalData.gConfig.HeaderCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
        if NoLicenseFlag:
            PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'File header comment should have the License immediately after the ""Copyright"" line', FileTable, ID)

def CheckFuncHeaderDoxygenComments(FullFileName):
    ErrorMsgList = []

    FileID = GetTableID(FullFileName, ErrorMsgList)
    if FileID < 0:
        return ErrorMsgList

    Db = GetDB()
    FileTable = 'Identifier' + str(FileID)
    SqlStatement = """ select Value, StartLine, EndLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_COMMENT)

    ResultSet = Db.TblFile.Exec(SqlStatement)
    CommentSet = []
    try:
        for Result in ResultSet:
            CommentSet.append(Result)
    except:
        print('Unrecognized chars in comment of file %s', FullFileName)

    # Func Decl check
    SqlStatement = """ select Modifier, Name, StartLine, ID, Value
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_DECLARATION)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        FuncName = Result[4]
        FunctionHeaderComment = CheckCommentImmediatelyPrecedeFunctionHeader(Result[1], Result[2], CommentSet)
        if FunctionHeaderComment:
            CheckFunctionHeaderConsistentWithDoxygenComment(Result[0], Result[1], Result[2], FunctionHeaderComment[0], FunctionHeaderComment[1], ErrorMsgList, FunctionHeaderComment[3], FileTable)
        else:
            if EccGlobalData.gException.IsException(ERROR_HEADER_CHECK_FUNCTION, FuncName):
                continue
            ErrorMsgList.append('Line %d :Function %s has NO comment immediately preceding it.' % (Result[2], Result[1]))
            PrintErrorMsg(ERROR_HEADER_CHECK_FUNCTION, 'Function [%s] has NO comment immediately preceding it.' % (FuncName), FileTable, Result[3])

    # Func Def check
    SqlStatement = """ select Value, StartLine, EndLine, ID
                       from %s
                       where Model = %d
                   """ % (FileTable, DataClass.MODEL_IDENTIFIER_FUNCTION_HEADER)

    ResultSet = Db.TblFile.Exec(SqlStatement)
    CommentSet = []
    try:
        for Result in ResultSet:
            CommentSet.append(Result)
    except:
        print('Unrecognized chars in comment of file %s', FullFileName)

    SqlStatement = """ select Modifier, Header, StartLine, ID, Name
                       from Function
                       where BelongsToFile = %d
                   """ % (FileID)
    ResultSet = Db.TblFile.Exec(SqlStatement)
    for Result in ResultSet:
        FuncName = Result[4]
        FunctionHeaderComment = CheckCommentImmediatelyPrecedeFunctionHeader(Result[1], Result[2], CommentSet)
        if FunctionHeaderComment:
            CheckFunctionHeaderConsistentWithDoxygenComment(Result[0], Result[1], Result[2], FunctionHeaderComment[0], FunctionHeaderComment[1], ErrorMsgList, FunctionHeaderComment[3], FileTable)
        else:
            if EccGlobalData.gException.IsException(ERROR_HEADER_CHECK_FUNCTION, FuncName):
                continue
            ErrorMsgList.append('Line %d :Function [%s] has NO comment immediately preceding it.' % (Result[2], Result[1]))
            PrintErrorMsg(ERROR_HEADER_CHECK_FUNCTION, 'Function [%s] has NO comment immediately preceding it.' % (FuncName), 'Function', Result[3])
    return ErrorMsgList

def CheckCommentImmediatelyPrecedeFunctionHeader(FuncName, FuncStartLine, CommentSet):

    for Comment in CommentSet:
        if Comment[2] == FuncStartLine - 1:
            return Comment
    return None

def GetDoxygenStrFromComment(Str):
    DoxygenStrList = []
    ParamTagList = Str.split('@param')
    if len(ParamTagList) > 1:
        i = 1
        while i < len(ParamTagList):
            DoxygenStrList.append('@param' + ParamTagList[i])
            i += 1

    Str = ParamTagList[0]

    RetvalTagList = ParamTagList[-1].split('@retval')
    if len(RetvalTagList) > 1:
        if len(ParamTagList) > 1:
            DoxygenStrList[-1] = '@param' + RetvalTagList[0]
        i = 1
        while i < len(RetvalTagList):
            DoxygenStrList.append('@retval' + RetvalTagList[i])
            i += 1

    ReturnTagList = RetvalTagList[-1].split('@return')
    if len(ReturnTagList) > 1:
        if len(RetvalTagList) > 1:
            DoxygenStrList[-1] = '@retval' + ReturnTagList[0]
        elif len(ParamTagList) > 1:
            DoxygenStrList[-1] = '@param' + ReturnTagList[0]
        i = 1
        while i < len(ReturnTagList):
            DoxygenStrList.append('@return' + ReturnTagList[i])
            i += 1

    if len(DoxygenStrList) > 0:
        DoxygenStrList[-1] = DoxygenStrList[-1].rstrip('--*/')

    return DoxygenStrList

def CheckGeneralDoxygenCommentLayout(Str, StartLine, ErrorMsgList, CommentId= -1, TableName=''):
    #/** --*/ @retval after @param
    if not Str.startswith('/**'):
        ErrorMsgList.append('Line %d : Comment does NOT have prefix /** ' % StartLine)
        PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'Comment does NOT have prefix /** ', TableName, CommentId)
    if not Str.endswith('**/'):
        ErrorMsgList.append('Line %d : Comment does NOT have tail **/ ' % StartLine)
        PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'Comment does NOT have tail **/ ', TableName, CommentId)
    FirstRetvalIndex = Str.find('@retval')
    LastParamIndex = Str.rfind('@param')
    if (FirstRetvalIndex > 0) and (LastParamIndex > 0) and (FirstRetvalIndex < LastParamIndex):
        ErrorMsgList.append('Line %d : @retval appear before @param ' % StartLine)
        PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'in Comment, @retval appear before @param  ', TableName, CommentId)

def CheckFunctionHeaderConsistentWithDoxygenComment(FuncModifier, FuncHeader, FuncStartLine, CommentStr, CommentStartLine, ErrorMsgList, CommentId= -1, TableName=''):

    ParamList = GetParamList(FuncHeader)
    CheckGeneralDoxygenCommentLayout(CommentStr, CommentStartLine, ErrorMsgList, CommentId, TableName)
    DescriptionStr = CommentStr
    DoxygenStrList = GetDoxygenStrFromComment(DescriptionStr)
    if DescriptionStr.find('.') == -1:
        PrintErrorMsg(ERROR_DOXYGEN_CHECK_COMMENT_DESCRIPTION, 'Comment description should end with period \'.\'', TableName, CommentId)
    DoxygenTagNumber = len(DoxygenStrList)
    ParamNumber = len(ParamList)
    for Param in ParamList:
        if Param.Name.upper() == 'VOID' and ParamNumber == 1:
            ParamNumber -= 1
    Index = 0
    if ParamNumber > 0 and DoxygenTagNumber > 0:
        while Index < ParamNumber and Index < DoxygenTagNumber:
            ParamModifier = ParamList[Index].Modifier
            ParamName = ParamList[Index].Name.strip()
            Tag = DoxygenStrList[Index].strip(' ')
            if (not Tag[-1] == ('\n')) and (not Tag[-1] == ('\r')):
                ErrorMsgList.append('Line %d : in Comment, <%s> does NOT end with new line ' % (CommentStartLine, Tag.replace('\n', '').replace('\r', '')))
                PrintErrorMsg(ERROR_HEADER_CHECK_FUNCTION, 'in Comment, <%s> does NOT end with new line ' % (Tag.replace('\n', '').replace('\r', '')), TableName, CommentId)
            TagPartList = Tag.split()
            if len(TagPartList) < 2:
                ErrorMsgList.append('Line %d : in Comment, <%s> does NOT contain doxygen contents ' % (CommentStartLine, Tag.replace('\n', '').replace('\r', '')))
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'in Comment, <%s> does NOT contain doxygen contents ' % (Tag.replace('\n', '').replace('\r', '')), TableName, CommentId)
                Index += 1
                continue
            LBPos = Tag.find('[')
            RBPos = Tag.find(']')
            ParamToLBContent = Tag[len('@param'):LBPos].strip()
            if LBPos > 0 and len(ParamToLBContent) == 0 and RBPos > LBPos:
                InOutStr = ''
                ModifierPartList = ParamModifier.split()
                for Part in ModifierPartList:
                    if Part.strip() == 'IN':
                        InOutStr += 'in'
                    if Part.strip() == 'OUT':
                        if InOutStr != '':
                            InOutStr += ', out'
                        else:
                            InOutStr = 'out'

                if InOutStr != '':
                    if Tag.find('[' + InOutStr + ']') == -1:
                        if InOutStr != 'in, out':
                            ErrorMsgList.append('Line %d : in Comment, <%s> does NOT have %s ' % (CommentStartLine, (TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), '[' + InOutStr + ']'))
                            PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'in Comment, <%s> does NOT have %s ' % ((TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), '[' + InOutStr + ']'), TableName, CommentId)
                        else:
                            if Tag.find('[in,out]') == -1:
                                ErrorMsgList.append('Line %d : in Comment, <%s> does NOT have %s ' % (CommentStartLine, (TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), '[' + InOutStr + ']'))
                                PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'in Comment, <%s> does NOT have %s ' % ((TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), '[' + InOutStr + ']'), TableName, CommentId)


            if Tag.find(ParamName) == -1 and ParamName != 'VOID' and ParamName != 'void':
                ErrorMsgList.append('Line %d : in Comment, <%s> is NOT consistent with parameter name %s ' % (CommentStartLine, (TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), ParamName))
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'in Comment, <%s> is NOT consistent with parameter name %s ' % ((TagPartList[0] + ' ' + TagPartList[1]).replace('\n', '').replace('\r', ''), ParamName), TableName, CommentId)
            Index += 1

        if Index < ParamNumber:
            ErrorMsgList.append('Line %d : Number of doxygen tags in comment less than number of function parameters' % CommentStartLine)
            PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'Number of doxygen tags in comment less than number of function parameters ', TableName, CommentId)
        # VOID return type, NOT VOID*. VOID* should be matched with a doxygen tag.
        if (FuncModifier.find('VOID') != -1 or FuncModifier.find('void') != -1) and FuncModifier.find('*') == -1:

            # assume we allow a return description tag for void func. return. that's why 'DoxygenTagNumber - 1' is used instead of 'DoxygenTagNumber'
            if Index < DoxygenTagNumber - 1 or (Index < DoxygenTagNumber and DoxygenStrList[Index].startswith('@retval')):
                ErrorMsgList.append('Line %d : VOID return type need NO doxygen tags in comment' % CommentStartLine)
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'VOID return type need no doxygen tags in comment ', TableName, CommentId)
        else:
            if Index < DoxygenTagNumber and not DoxygenStrList[Index].startswith('@retval') and not DoxygenStrList[Index].startswith('@return'):
                ErrorMsgList.append('Line %d : Number of @param doxygen tags in comment does NOT match number of function parameters' % CommentStartLine)
                PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'Number of @param doxygen tags in comment does NOT match number of function parameters ', TableName, CommentId)
    else:
        if ParamNumber == 0 and DoxygenTagNumber != 0 and ((FuncModifier.find('VOID') != -1 or FuncModifier.find('void') != -1) and FuncModifier.find('*') == -1):
            ErrorMsgList.append('Line %d : VOID return type need NO doxygen tags in comment' % CommentStartLine)
            PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'VOID return type need NO doxygen tags in comment ', TableName, CommentId)
        if ParamNumber != 0 and DoxygenTagNumber == 0:
            ErrorMsgList.append('Line %d : No doxygen tags in comment' % CommentStartLine)
            PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'No doxygen tags in comment ', TableName, CommentId)

if __name__ == '__main__':

#    EdkLogger.Initialize()
#    EdkLogger.SetLevel(EdkLogger.QUIET)
#    CollectSourceCodeDataIntoDB(sys.argv[1])
    try:
        test_file = sys.argv[1]
    except IndexError as v:
        print("Usage: %s filename" % sys.argv[0])
        sys.exit(1)
    MsgList = CheckFuncHeaderDoxygenComments(test_file)
    for Msg in MsgList:
        print(Msg)
    print('Done!')