File: test_sourceform.py

package info (click to toggle)
ford 7.0.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,000 kB
  • sloc: python: 11,852; f90: 419; javascript: 51; fortran: 45; makefile: 23
file content (2401 lines) | stat: -rw-r--r-- 66,347 bytes parent folder | download
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
from ford.sourceform import (
    FortranSourceFile,
    FortranModule,
    FortranBase,
    parse_type,
    ParsedType,
    line_to_variables,
    GenericSource,
)
from ford.fortran_project import find_used_modules
from ford import ProjectSettings
from ford._markdown import MetaMarkdown

from dataclasses import dataclass, field
from typing import Union, List, Optional
from itertools import chain
from textwrap import dedent

import pytest


class FakeProject:
    def __init__(self, procedures=None):
        self.procedures = procedures or []


@pytest.fixture
def parse_fortran_file(copy_fortran_file):
    def parse_file(data, **kwargs):
        filename = copy_fortran_file(data)
        settings = ProjectSettings(**kwargs)
        return FortranSourceFile(str(filename), settings)

    return parse_file


def test_extends(parse_fortran_file):
    """Check that types can be extended"""

    data = """\
    program foo
    !! base type
    type :: base
    end type base

    !! derived type
    type, extends(base) :: derived
    end type

    !! derived type but capitalised
    type, EXTENDS(base) :: derived_capital
    end type

    end program foo
    """

    fortran_type = parse_fortran_file(data)

    assert len(fortran_type.programs) == 1

    program = fortran_type.programs[0]

    assert len(program.types) == 3
    assert program.types[1].extends == "base"
    assert program.types[2].extends == "base"


def test_type_visibility_attributes(parse_fortran_file):
    """Check that we can set visibility attributes on types, #388"""

    data = """\
    module default_public
      type no_attrs
      end type no_attrs

      type, public :: public_attr
      end type public_attr

      type, private :: private_attr
      end type private_attr

      type, public :: public_attr_private_components
        private
      end type public_attr

      type, private :: private_attr_public_components
        public
      end type private_attr
    end module default_public

    module default_private
      private

      type no_attrs
      end type no_attrs

      type, public :: public_attr
      end type public_attr

      type, private :: private_attr
      end type private_attr

      type, public :: public_attr_private_components
        private
      end type public_attr

      type, private :: private_attr_public_components
        public
      end type private_attr
    end module default_private
    """

    source = parse_fortran_file(data)
    public_no_attrs = source.modules[0].types[0]
    public_public_attr = source.modules[0].types[1]
    public_private_attr = source.modules[0].types[2]
    public_public_attr_components = source.modules[0].types[3]
    public_private_attr_components = source.modules[0].types[4]

    assert public_no_attrs.permission == "public"
    assert public_public_attr.permission == "public"
    assert public_private_attr.permission == "private"
    assert public_public_attr_components.permission == "public"
    assert public_private_attr_components.permission == "private"

    private_no_attrs = source.modules[1].types[0]
    private_public_attr = source.modules[1].types[1]
    private_private_attr = source.modules[1].types[2]
    private_public_attr_components = source.modules[1].types[3]
    private_private_attr_components = source.modules[1].types[4]

    assert private_no_attrs.permission == "private"
    assert private_public_attr.permission == "public"
    assert private_private_attr.permission == "private"
    assert private_public_attr_components.permission == "public"
    assert private_private_attr_components.permission == "private"


def test_submodule_procedure_contains(parse_fortran_file):
    """Check that submodule procedures can have 'contains' statements"""

    data = """\
    module foo_m
      implicit none
      interface
        module subroutine foo()
          implicit none
        end subroutine
      end interface
    end module

    submodule(foo_m) foo_s
      implicit none
    contains
      module procedure foo
      contains
        subroutine bar()
        end subroutine
      end procedure
    end submodule
    """

    fortran_type = parse_fortran_file(data)

    assert len(fortran_type.modules) == 1
    assert len(fortran_type.submodules) == 1
    submodule = fortran_type.submodules[0]
    assert len(submodule.modprocedures) == 1
    module_procedure = submodule.modprocedures[0]
    assert len(module_procedure.subroutines) == 1


def test_backslash_in_character_string(parse_fortran_file):
    """Bad escape crash #296"""

    data = r"""\
    module test_module
    character(len=*),parameter,public:: q = '(?)'
    character(len=*),parameter,public:: a  = '\a'
    character(len=*),parameter,public:: b  = '\b'
    character(len=*),parameter,public:: c  = '\c'
    end module test_module
    """

    source = parse_fortran_file(data)
    module = source.modules[0]

    expected_variables = {"q": r"'(?)'", "a": r"'\a'", "b": r"'\b'", "c": r"'\c'"}

    for variable in module.variables:
        assert variable.initial == expected_variables[variable.name]


def test_sync_images_in_submodule_procedure(parse_fortran_file):
    """Crash on sync images inside module procedure in submodule #237"""

    data = """\
    module stuff
      interface
        module subroutine foo()
        end subroutine
      end interface
    end module

    submodule(stuff) sub_stuff
      implicit none
    contains
      module procedure foo
        sync images(1)
      end procedure
    end submodule
    """

    parse_fortran_file(data)


def test_function_and_subroutine_call_on_same_line(parse_fortran_file):
    """Regex does not check for nested calls #256"""

    data = """\
    program test
    call bar(foo())
    contains
    integer function foo()
    end function foo
    subroutine bar(thing)
      integer, intent(in) :: thing
    end subroutine bar
    end program test
    """

    fortran_file = parse_fortran_file(data)
    program = fortran_file.programs[0]
    assert len(program.calls) == 2
    expected_calls = {"bar", "foo"}
    assert set(call[-1] for call in program.calls) == expected_calls


@pytest.mark.parametrize(
    ["call_segment", "expected"],
    [
        (
            """
            USE m_baz, ONLY: t_bar
            USE m_foo, ONLY: t_baz

            TYPE(t_bar) :: v_bar
            TYPE(t_baz) :: var
            var = v_bar%p_foo()
            """,
            ["p_foo"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar) :: v_bar
            INTEGER :: var
            var = v_bar%v_foo(1)
            """,
            [],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar) :: v_bar
            INTEGER :: var
            var = [v_bar%v_foo(1)]
            """,
            [],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar) :: v_bar
            INTEGER, DIMENSION(:), ALLOCATABLE :: var
            var = v_bar%v_baz%p_baz()
            """,
            ["p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            USE m_foo, ONLY: t_baz

            TYPE(t_bar) :: v_bar
            TYPE(t_baz) :: var
            var = v_bar%t_foo%p_foo()
            """,
            ["p_foo"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            USE m_foo, ONLY: t_baz

            TYPE(t_bar) :: v_bar
            TYPE(t_baz) :: var(1)
            var = [v_bar%t_foo%p_foo()]
            """,
            ["p_foo"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar), DIMENSION(2) :: v_bar
            INTEGER :: var
            var = v_bar(1)%v_baz%v_faz(1)
            """,
            [],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar), DIMENSION(2) :: v_bar
            call v_bar(1)%renamed()
            """,
            ["renamed"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar), DIMENSION(2) :: v_bar
            call v_bar ( 1 ) % p_bar
            """,
            ["p_bar"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar

            TYPE(t_bar) :: v_bar
            call v_bar % p_bar ( v_bar % v_baz % p_baz () )
            """,
            ["p_bar", "p_baz"],
        ),
        (
            """
            USE m_foo, ONLY: t_baz
            USE m_baz, ONLY: p_buz

            TYPE(t_baz) :: var_baz
            call p_buz(var_baz%p_baz())
            """,
            ["p_baz", "p_buz"],
        ),
        (
            """
            USE m_foo, ONLY: t_baz

            TYPE(t_baz) :: var_baz
            write(*,*) var_baz%p_baz()
            """,
            ["p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            ASSOCIATE (tmp => v_bar)
                CALL tmp%p_bar()
            END ASSOCIATE
            """,
            ["p_bar"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            INTEGER, DIMENSION(2) :: var
            ASSOCIATE (tmp => v_bar%v_baz)
                var = tmp%p_baz()
            END ASSOCIATE
            """,
            ["p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            INTEGER :: var
            ASSOCIATE (tmp => v_bar%v_baz)
                ASSOCIATE (tmp2 => tmp%p_baz())
                END ASSOCIATE
            END ASSOCIATE
            """,
            ["p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            INTEGER, DIMENSION(1) :: var_arr
            ASSOCIATE (tmp => v_bar%v_baz)
                ASSOCIATE (tmp => tmp%v_faz)
                    var_arr = tmp
                END ASSOCIATE
                var_arr = tmp%p_baz()
            END ASSOCIATE
            """,
            ["p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            INTEGER :: var = 10
            ASSOCIATE (tmp => var)
                var = tmp
            END ASSOCIATE
            """,
            [],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            ASSOCIATE (tmp => v_bar%p_foo())
                PRINT *, tmp
            END ASSOCIATE
            """,
            ["p_foo"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            INTEGER, DIMENSION(2) :: var_arr
            ASSOCIATE (tmp => v_bar, arr => var_arr)
                CALL tmp%p_bar()
                arr = tmp%v_baz%p_baz()
            END ASSOCIATE
            """,
            ["p_bar", "p_baz"],
        ),
        (
            """
            USE m_baz, ONLY: t_bar
            TYPE(t_bar) :: v_bar
            INTEGER, DIMENSION(2) :: var_arr
            ASSOCIATE (tmp => v_bar)
                ASSOCIATE (tmp2 => tmp%v_baz%p_baz())
                END ASSOCIATE
            END ASSOCIATE
            """,
            ["p_baz"],
        ),
        (
            """
            ASSOCIATE (tmp => p_faz(p_fuz(1)))
            END ASSOCIATE
            """,
            ["p_faz", "p_fuz"],
        ),
        (
            """
            USE m_baz, ONLY: t_unknown_parent
            TYPE(t_unknown_parent)
            call t_unknown_parent%known_method()
            """,
            ["known_method"],
        ),
    ],
)
def test_type_chain_function_and_subroutine_calls(
    parse_fortran_file, call_segment, expected
):
    data = f"""\
    MODULE m_foo
        IMPLICIT NONE
        TYPE :: t_baz
            INTEGER, DIMENSION(:), ALLOCATABLE :: v_faz
        CONTAINS
            PROCEDURE :: p_baz
        END TYPE t_baz

        CONTAINS

        FUNCTION p_baz(self) RESULT(ret_val)
            CLASS(t_baz), INTENT(IN) :: self
            INTEGER, DIMENSION(:), ALLOCATABLE :: ret_val
        END FUNCTION p_baz

    END MODULE m_foo

    MODULE m_bar
        TYPE :: t_foo
            INTEGER, DIMENSION(:), ALLOCATABLE :: v_foo
        CONTAINS
            PROCEDURE :: p_foo
        END TYPE t_foo

        CONTAINS

        FUNCTION p_foo(self) RESULT(ret_val)
            USE m_foo, ONLY: t_baz

            CLASS(t_foo), INTENT(IN) :: self
            TYPE(t_baz) :: ret_val
        END FUNCTION p_foo

    END MODULE m_bar

    MODULE m_baz

        USE m_foo, ONLY: t_baz
        USE m_bar, ONLY: t_foo
        USE unknown_module
        TYPE, EXTENDS(t_foo) :: t_bar
            TYPE(t_baz) :: v_baz
        CONTAINS
            PROCEDURE :: p_bar
            PROCEDURE :: renamed => p_bar
        END TYPE t_bar

        TYPE, EXTENDS(unknown_type) :: t_unknown_parent
        CONTAINS
            PROCEDURE, NOPASS :: known_method
        END TYPE

        CONTAINS

        SUBROUTINE p_bar(self)
            CLASS(t_bar), INTENT(IN) :: self
        END SUBROUTINE p_bar

        SUBROUTINE p_buz(var_int)
            INTEGER, DIMENSION(2), INTENT(IN) :: var_int
        END SUBROUTINE p_buz

        SUBROUTINE known_method()
        END SUBROUTINE

    END MODULE m_baz

    MODULE m_main

        CONTAINS
        
        FUNCTION p_faz(arg) RESULT(ret_val)
            INTEGER, INTENT(IN) :: arg
            INTEGER :: ret_val
        END FUNCTION p_faz

        FUNCTION p_fuz(arg) RESULT(ret_val)
            INTEGER, INTENT(IN) :: arg
            INTEGER :: ret_val
        END FUNCTION p_fuz
        
        SUBROUTINE main
            {call_segment}
        END SUBROUTINE main

    END MODULE m_main
    """

    fortran_file = parse_fortran_file(data)
    fp = FakeProject()
    modules = {module.name: module for module in fortran_file.modules}
    for module in modules.values():
        find_used_modules(module, modules.values(), [], [])

    # correlation order is important
    modules["m_foo"].correlate(fp)
    modules["m_bar"].correlate(fp)
    modules["m_baz"].correlate(fp)
    modules["m_main"].correlate(fp)

    main_subroutines = {sub.name: sub for sub in modules["m_main"].subroutines}
    calls = main_subroutines["main"].calls

    assert len(calls) == len(expected)

    calls_sorted = sorted(calls, key=lambda x: getattr(x, "name", x))
    expected_sorted = sorted(expected)
    for call, expected_name in zip(calls_sorted, expected_sorted):
        assert isinstance(call, FortranBase)

        assert call.name == expected_name


def test_call_in_module_procedure(parse_fortran_file):
    data = """\
    module foo
      type :: nuz
      contains
        procedure :: cor
      end type nuz
      interface
        module subroutine bar()
        end subroutine bar
      end interface
    contains
      function cor(this_) result (ret_val)
        class (nuz), intent(in) :: this_
        real :: ret_val
      end function cor
    end module foo

    submodule(foo) baz
    contains
      module procedure bar
        type (nuz) :: var
        real :: val
        val = var%cor()
      end procedure bar
    end submodule baz
    """
    expected = ["cor"]

    fortran_file = parse_fortran_file(data, display=["public", "protected", "private"])
    fp = FakeProject()
    modules = {
        module.name: module
        for module in chain(fortran_file.modules, fortran_file.submodules)
    }
    for module in modules.values():
        find_used_modules(module, modules.values(), [], [])

    # correlation order is important
    modules["foo"].correlate(fp)
    modules["baz"].correlate(fp)

    main_subroutines = {sub.name: sub for sub in modules["baz"].modprocedures}
    calls = main_subroutines["bar"].calls

    assert len(calls) == len(expected)

    calls_sorted = sorted(calls, key=lambda x: getattr(x, "name", x))
    expected_sorted = sorted(expected)
    for call, expected_name in zip(calls_sorted, expected_sorted):
        assert isinstance(call, FortranBase)

        assert call.name == expected_name


def test_submodule_private_var_call(parse_fortran_file):
    data = """\
    module foo
      type :: nuz
        integer :: var
      end type nuz

      type(nuz), dimension(2), private :: pri_var

      interface
        module subroutine bar()
        end subroutine bar
      end interface
    end module foo

    submodule(foo) baz
    contains
      module procedure bar
        integer :: val
        val = pri_var(1)%var
      end procedure bar
    end submodule baz
    """

    fortran_file = parse_fortran_file(data)
    fp = FakeProject()
    modules = {
        module.name: module
        for module in chain(fortran_file.modules, fortran_file.submodules)
    }
    for module in modules.values():
        find_used_modules(module, modules.values(), [], [])

    # correlation order is important
    modules["foo"].correlate(fp)
    modules["baz"].correlate(fp)

    main_subroutines = {sub.name: sub for sub in modules["baz"].modprocedures}
    calls = main_subroutines["bar"].calls

    assert calls == []


def test_internal_proc_arg_var_call(parse_fortran_file):
    data = """\
    module foo
      type :: nuz
        integer :: var
      end type nuz
      type(nuz), dimension(2), private :: pri_var
    contains
      subroutine bar(nuz_var)
        class(nuz), dimension(2) :: nuz_var
      contains
        subroutine baz
          integer :: val
          val = nuz_var(1)%var
        end subroutine baz
      end subroutine bar
    end module foo
    """

    fortran_file = parse_fortran_file(data)
    fp = FakeProject()
    modules = {module.name: module for module in fortran_file.modules}
    for module in modules.values():
        find_used_modules(module, modules.values(), [], [])

    # correlation order is important
    modules["foo"].correlate(fp)

    calls = modules["foo"].subroutines[0].subroutines[0].calls

    assert calls == []


def test_component_access(parse_fortran_file):
    data = """\
    module mod1
        integer :: anotherVar(20)
        type typeOne
            integer :: ivar(10)
        end type typeOne
        type(typeOne) :: One
    end module mod1

    module mod2
        type typeTwo
            integer :: ivar(10)
        end type typeTwo
        type(typeTwo) :: Two
    end module mod2

    subroutine with_space
        use mod2
        integer :: a
        a = 3
        Two% ivar(:) = a
    end subroutine with_space

    program main
        integer :: i, j
        integer :: zzz(5)

        type typeThree
            integer :: ivar(10)
        end type typeThree
        type(typeThree) :: Three

        call with_space()
        call without_space()
        anotherVar(3) = i
        j = zzz(3)

        Three% ivar(3) = 7
    end program
    """

    fortran_file = parse_fortran_file(data)

    expected_variables = {"i", "j", "zzz", "Three"}
    actual_variables = {var.name for var in fortran_file.programs[0].variables}
    assert actual_variables == expected_variables


def test_format_statement(parse_fortran_file):
    """No function calls in `format` statements are allowed, so don't
    confuse them with format specifiers. Issue #350"""

    data = """\
    program test_format_statement
      implicit none
      write (*, 300)
    300 format (/1X, 44('-'), ' Begin of test2 Calculation ', 33('-')//)
    end program test_format_statement
    """

    fortran_file = parse_fortran_file(data)
    assert fortran_file.programs[0].calls == []


def test_enumerator_with_kind(parse_fortran_file):
    """Checking enumerators with specified kind, issue #293"""

    data = """\
    module some_enums
      use, intrinsic :: iso_fortran_env, only : int32
      enum, bind(c)
        enumerator :: item1, item2
        enumerator :: list1 = 100_int32, list2
        enumerator :: fixed_item1 = 0, fixed_item2
      end enum
    end module some_enums
    """

    fortran_file = parse_fortran_file(data)
    enum = fortran_file.modules[0].enums[0]
    assert enum.variables[0].name == "item1"
    assert enum.variables[0].initial == 0
    assert enum.variables[1].name == "item2"
    assert enum.variables[1].initial == 1
    assert enum.variables[2].name == "list1"
    assert enum.variables[2].initial == "100_int32"
    assert enum.variables[3].name == "list2"
    assert enum.variables[3].initial == 101
    assert enum.variables[4].name == "fixed_item1"
    assert enum.variables[4].initial == "0"
    assert enum.variables[5].name == "fixed_item2"
    assert enum.variables[5].initial == 1


class FakeModule(FortranModule):
    def __init__(
        self, procedures: dict, interfaces: dict, types: dict, variables: dict
    ):
        self.pub_procs = procedures
        self.pub_absints = interfaces
        self.pub_types = types
        self.pub_vars = variables


def test_module_get_used_entities_all():
    mod_procedures = {"subroutine": "some subroutine"}
    mod_interfaces = {"abstract": "interface"}
    mod_types = {"mytype": "some type"}
    mod_variables = {"x": "some var"}

    module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)

    procedures, interfaces, types, variables = module.get_used_entities("")

    assert procedures == mod_procedures
    assert interfaces == mod_interfaces
    assert types == mod_types
    assert variables == mod_variables


def test_module_get_used_entities_some():
    mod_procedures = {"subroutine": "some subroutine"}
    mod_interfaces = {"abstract": "interface"}
    mod_types = {"mytype": "some type"}
    mod_variables = {"x": "some var", "y": "some other var"}

    module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)

    procedures, interfaces, types, variables = module.get_used_entities(
        ", only: x, subroutine"
    )

    assert procedures == mod_procedures
    assert interfaces == {}
    assert types == {}
    assert variables == {"x": mod_variables["x"]}


def test_module_get_used_entities_rename():
    mod_procedures = {"subroutine": "some subroutine"}
    mod_interfaces = {"abstract": "interface"}
    mod_types = {"mytype": "some type"}
    mod_variables = {"x": "some var", "y": "some other var"}

    module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)

    procedures, interfaces, types, variables = module.get_used_entities(
        ", only: x, y => subroutine"
    )

    assert procedures == {"y": mod_procedures["subroutine"]}
    assert interfaces == {}
    assert types == {}
    assert variables == {"x": mod_variables["x"]}


def test_module_default_access(parse_fortran_file):
    data = """\
    module default_access
      ! No access keyword
      integer :: int_public, int_private
      private :: int_private
      real :: real_public
      real, private :: real_private

      type :: type_public
        complex :: component_public
        complex, private :: component_private
      end type type_public

      type :: type_private
        character(len=1) :: string_public
        character(len=1), private :: string_private
      end type type_private

      private :: sub_private, func_private, type_private

    contains
      subroutine sub_public
      end subroutine sub_public

      subroutine sub_private
      end subroutine sub_private

      integer function func_public()
      end function func_public

      integer function func_private()
      end function func_private
    end module default_access
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())

    assert set(fortran_file.modules[0].all_procs.keys()) == {
        "sub_public",
        "func_public",
        "sub_private",
        "func_private",
    }
    assert set(fortran_file.modules[0].pub_procs.keys()) == {
        "sub_public",
        "func_public",
    }
    assert set(fortran_file.modules[0].all_types.keys()) == {
        "type_public",
        "type_private",
    }
    assert set(fortran_file.modules[0].pub_types.keys()) == {
        "type_public",
    }
    assert set(fortran_file.modules[0].all_vars.keys()) == {
        "int_public",
        "int_private",
        "real_public",
        "real_private",
    }
    assert set(fortran_file.modules[0].pub_vars.keys()) == {
        "int_public",
        "real_public",
    }


def test_module_public_access(parse_fortran_file):
    data = """\
    module public_access
      public
      integer :: int_public, int_private
      private :: int_private
      real :: real_public
      real, private :: real_private

      type :: type_public
        complex :: component_public
        complex, private :: component_private
      end type type_public

      type :: type_private
        character(len=1) :: string_public
        character(len=1), private :: string_private
      end type type_private

      private :: sub_private, func_private, type_private

    contains
      subroutine sub_public
      end subroutine sub_public

      subroutine sub_private
      end subroutine sub_private

      integer function func_public()
      end function func_public

      integer function func_private()
      end function func_private
    end module public_access
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())

    assert set(fortran_file.modules[0].all_procs.keys()) == {
        "sub_public",
        "func_public",
        "sub_private",
        "func_private",
    }
    assert set(fortran_file.modules[0].pub_procs.keys()) == {
        "sub_public",
        "func_public",
    }
    assert set(fortran_file.modules[0].all_types.keys()) == {
        "type_public",
        "type_private",
    }
    assert set(fortran_file.modules[0].pub_types.keys()) == {
        "type_public",
    }
    assert set(fortran_file.modules[0].all_vars.keys()) == {
        "int_public",
        "int_private",
        "real_public",
        "real_private",
    }
    assert set(fortran_file.modules[0].pub_vars.keys()) == {
        "int_public",
        "real_public",
    }


def test_module_private_access(parse_fortran_file):
    data = """\
    module private_access
      private
      integer :: int_public, int_private
      public :: int_public
      real :: real_private
      real, public :: real_public

      type :: type_public
        complex :: component_public
        complex, private :: component_private
      end type type_public

      type :: type_private
        character(len=1) :: string_public
        character(len=1), private :: string_private
      end type type_private

      public :: sub_public, func_public, type_public

    contains
      subroutine sub_public
      end subroutine sub_public

      subroutine sub_private
      end subroutine sub_private

      integer function func_public()
      end function func_public

      integer function func_private()
      end function func_private
    end module private_access
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())

    assert set(fortran_file.modules[0].all_procs.keys()) == {
        "sub_public",
        "func_public",
        "sub_private",
        "func_private",
    }
    assert set(fortran_file.modules[0].pub_procs.keys()) == {
        "sub_public",
        "func_public",
    }
    assert set(fortran_file.modules[0].all_types.keys()) == {
        "type_public",
        "type_private",
    }
    assert set(fortran_file.modules[0].pub_types.keys()) == {
        "type_public",
    }
    assert set(fortran_file.modules[0].all_vars.keys()) == {
        "int_public",
        "int_private",
        "real_public",
        "real_private",
    }
    assert set(fortran_file.modules[0].pub_vars.keys()) == {
        "int_public",
        "real_public",
    }


def test_module_procedure_case(parse_fortran_file):
    """Check that submodule procedures in interface blocks are parsed correctly. Issue #353"""
    data = """\
    module a
      implicit none
      interface
        MODULE SUBROUTINE square( x )
          integer, intent(inout):: x
        END SUBROUTINE square
        module subroutine cube( x )
          integer, intent(inout):: x
        end subroutine cube
        MODULE FUNCTION square_func( x )
          integer, intent(in):: x
        END FUNCTION square_func
        module function cube_func( x )
          integer, intent(inout):: x
        end function cube_func
      end interface
    end module a

    submodule (a) b
      implicit none
    contains
      MODULE PROCEDURE square
        x = x * x
      END PROCEDURE square
      module PROCEDURE cube
        x = x * x * x
      END PROCEDURE cube
      MODULE PROCEDURE square_func
        square_func = x * x
      END PROCEDURE square_func
      module procedure cube_func
        cube_func = x * x * x
      end procedure cube_func
    end submodule b
    """

    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    assert len(module.interfaces) == 4
    assert module.interfaces[0].procedure.module
    assert module.interfaces[1].procedure.module
    assert module.interfaces[2].procedure.module
    assert module.interfaces[3].procedure.module


def test_submodule_ancestors(parse_fortran_file):
    """Check that submodule ancestors and parents are correctly identified"""

    data = """\
    module mod_a
    end module mod_a

    submodule (mod_a) mod_b
    end submodule mod_b

    submodule (mod_a) mod_c
    end submodule mod_c

    submodule (mod_a:mod_c) mod_d
    end submodule mod_d
    """

    fortran_file = parse_fortran_file(data)

    mod_b = fortran_file.submodules[0]
    mod_c = fortran_file.submodules[1]
    mod_d = fortran_file.submodules[2]

    assert mod_b.parent_submodule is None
    assert mod_b.ancestor_module == "mod_a"

    assert mod_c.parent_submodule is None
    assert mod_c.ancestor_module == "mod_a"

    assert mod_d.parent_submodule == "mod_c"
    assert mod_d.ancestor_module == "mod_a"


@pytest.mark.parametrize(
    ["variable_decl", "expected"],
    [
        ("integer i", ParsedType("integer", "i")),
        ("integer :: i", ParsedType("integer", ":: i")),
        ("integer ( int32 ) :: i", ParsedType("integer", ":: i", "int32")),
        ("real r", ParsedType("real", "r")),
        ("real(real64) r", ParsedType("real", "r", "real64")),
        ("REAL( KIND  =  8) :: r, x, y", ParsedType("real", ":: r, x, y", "8")),
        ("REAL( 8 ) :: r, x, y", ParsedType("real", ":: r, x, y", "8")),
        ("complex*16 znum", ParsedType("complex", "znum", "16")),
        (
            "character(len=*) :: string",
            ParsedType("character", ":: string", strlen="*"),
        ),
        (
            "character(len=:) :: string",
            ParsedType("character", ":: string", strlen=":"),
        ),
        ("character(12) :: string", ParsedType("character", ":: string", strlen="12")),
        (
            "character(var) :: string",
            ParsedType("character", ":: string", strlen="var"),
        ),
        ("character :: string", ParsedType("character", ":: string", strlen="1")),
        (
            "character(LEN=12) :: string",
            ParsedType("character", ":: string", strlen="12"),
        ),
        (
            "CHARACTER(KIND= kind('0') ,  len =12) :: string",
            ParsedType("character", ":: string", kind='kind("a")', strlen="12"),
        ),
        (
            "CHARACTER(KIND=kanji,  len =12) :: string",
            ParsedType("character", ":: string", kind="kanji", strlen="12"),
        ),
        (
            "CHARACTER(  len =   12,KIND=kanji) :: string",
            ParsedType("character", ":: string", kind="kanji", strlen="12"),
        ),
        (
            "CHARACTER( 12,kanji ) :: string",
            ParsedType("character", ":: string", kind="kanji", strlen="12"),
        ),
        (
            "CHARACTER(  kind=    kanji) :: string",
            ParsedType("character", ":: string", kind="kanji", strlen="1"),
        ),
        ("double PRECISION dp", ParsedType("double precision", "dp")),
        ("DOUBLE   complex dc", ParsedType("double complex", "dc")),
        (
            "type(something) :: thing",
            ParsedType("type", ":: thing", proto=["something", ""]),
        ),
        (
            "type(character(kind=kanji, len=10)) :: thing",
            ParsedType("type", ":: thing", proto=["character", "kind=kanji,len=10"]),
        ),
        (
            "class(foo) :: thing",
            ParsedType("class", ":: thing", proto=["foo", ""]),
        ),
        (
            "procedure(bar) :: thing",
            ParsedType("procedure", ":: thing", proto=["bar", ""]),
        ),
        ("Vec :: vector", ParsedType("vec", ":: vector")),
        ("Mat :: matrix", ParsedType("mat", ":: matrix")),
    ],
)
def test_parse_type(variable_decl, expected):
    # Tokeniser will have previously replaced strings with index into
    # this list
    capture_strings = ['"a"']
    result = parse_type(variable_decl, capture_strings, ["Vec", "Mat"])
    assert result.vartype == expected.vartype
    assert result.kind == expected.kind
    assert result.strlen == expected.strlen
    assert result.proto == expected.proto
    assert result.rest == expected.rest


class FakeSource:
    def __init__(self):
        self.text = iter(["end subroutine", "end module"])

    def __next__(self):
        return next(self.text)

    def pass_back(self, line):
        pass


@dataclass
class FakeParent:
    strings: List[str] = field(default_factory=lambda: ['"Hello"', "'World'"])
    settings: ProjectSettings = field(default_factory=ProjectSettings)
    obj: str = "module"
    parent = None
    display: List[str] = field(default_factory=list)
    _to_be_markdowned: List[FortranBase] = field(default_factory=list)
    doxy_dict = {}


def _make_list_str() -> List[str]:
    """This is just to stop mypy complaining for ``attribs`` below"""
    return []


@dataclass
class FakeVariable:
    name: str
    vartype: str
    parent: Optional[FakeParent] = field(default_factory=FakeParent)
    attribs: Optional[List[str]] = field(default_factory=_make_list_str)
    intent: str = ""
    optional: bool = False
    permission: str = "public"
    parameter: bool = False
    kind: Optional[str] = None
    strlen: Optional[str] = None
    proto: Union[None, str, List[str]] = None
    doc_list: List[str] = field(default_factory=list)
    points: bool = False
    initial: Optional[str] = None


@pytest.mark.parametrize(
    ["line", "expected_variables"],
    [
        ("integer foo", [FakeVariable("foo", "integer")]),
        ("integer :: foo", [FakeVariable("foo", "integer")]),
        (
            "real :: foo, bar",
            [FakeVariable("foo", "real"), FakeVariable("bar", "real")],
        ),
        (
            "real, allocatable :: foo",
            [FakeVariable("foo", "real", attribs=["allocatable"])],
        ),
        (
            "integer, intent ( in  out)::zing",
            [FakeVariable("zing", "integer", intent="inout")],
        ),
        (
            "real(real64), optional, intent(in) :: foo, bar",
            [
                FakeVariable("foo", "real", kind="real64", optional=True, intent="in"),
                FakeVariable("bar", "real", kind="real64", optional=True, intent="in"),
            ],
        ),
        (
            "character ( len = 24 , kind = 4), parameter :: char = '0', far = '1'",
            [
                FakeVariable(
                    "char",
                    "character",
                    strlen="24",
                    kind="4",
                    parameter=True,
                    initial='"Hello"',
                ),
                FakeVariable(
                    "far",
                    "character",
                    strlen="24",
                    kind="4",
                    parameter=True,
                    initial="'World'",
                ),
            ],
        ),
        (
            "procedure(foo) :: bar",
            [FakeVariable("bar", "procedure", proto=["foo", ""])],
        ),
        (
            "type(foo) :: bar = 42",
            [FakeVariable("bar", "type", proto=["foo", ""], initial="42")],
        ),
        (
            "class(foo) :: var1, var2",
            [
                FakeVariable("var1", "class", proto=["foo", ""]),
                FakeVariable("var2", "class", proto=["foo", ""]),
            ],
        ),
        (
            "class(*) :: polymorphic",
            [FakeVariable("polymorphic", "class", proto=["*", ""])],
        ),
    ],
)
def test_line_to_variable(line, expected_variables):
    variables = line_to_variables(FakeSource(), line, "public", FakeParent())
    attributes = expected_variables[0].__dict__
    attributes.pop("parent")

    for variable, expected in zip(variables, expected_variables):
        for attr in attributes:
            variable_attr = getattr(variable, attr)
            expected_attr = getattr(expected, attr)
            assert variable_attr == expected_attr, attr

    if len(expected_variables) > 1:
        for attr in attributes:
            attribute = getattr(variable, attr)
            if not isinstance(attribute, list):
                continue
            proto_ids = [id(getattr(variable, attr)) for variable in variables]
            assert len(proto_ids) == len(set(proto_ids)), attr


def test_markdown_header_bug286(parse_fortran_file):
    """Check that markdown headers work, issue #286"""
    data = """\
    module myModule
    contains
      subroutine printSquare(x)
        !! ## My Header
        !! This should be one section, but the header doesn't work
        integer, intent(in) :: x
        write(*,*) x*x
      end subroutine printSquare
    end module myModule
    """

    fortran_file = parse_fortran_file(data)
    md = MetaMarkdown()

    subroutine = fortran_file.modules[0].subroutines[0]
    subroutine.markdown(md)

    assert subroutine.doc.startswith("<h2>My Header</h2>")


def test_markdown_codeblocks_bug286(parse_fortran_file):
    """Check that markdown codeblocks work, issue #287"""
    data = """\
    module myModule
    contains
      subroutine printSquare(x)
        !! This codeblock should not be inline:
        !! ```
        !! printSquare(4)
        !! ```
        integer, intent(in) :: x
        write(*,*) x*x
      end subroutine printSquare
    end module myModule
    """

    fortran_file = parse_fortran_file(data)
    md = MetaMarkdown()

    subroutine = fortran_file.modules[0].subroutines[0]
    subroutine.markdown(md)

    assert "<code>printSquare(4)" in subroutine.doc
    assert "<div" in subroutine.doc


def test_markdown_meta_reset(parse_fortran_file):
    """Check that markdown metadata is reset between entities"""
    data = """\
    module myModule
      !! version: 0.1.0
    contains
      subroutine printSquare(x)
        !! author: Test name
        integer, intent(in) :: x
        write(*,*) x*x
      end subroutine printSquare
      !> @author Lucie Forrest
      subroutine printCube(x)
        integer, intent(in) :: x
        write(*,*) x*x*x
      end subroutine printCube
    end module myModule
    """

    fortran_file = parse_fortran_file(data)
    md = MetaMarkdown()
    module = fortran_file.modules[0]
    module.markdown(md)
    assert module.meta.version == "0.1.0"
    assert module.subroutines[0].meta.author == "Test name"
    assert module.subroutines[1].meta.author == "Lucie Forrest"


def test_multiline_attributes(parse_fortran_file):
    """Check that specifying attributes over multiple lines works"""

    data = """\
    program prog
      real x
      dimension x(:)
      allocatable x
      integer, allocatable, dimension(:) :: y
      complex z
      allocatable z(:)

      allocate(x(1), y(1), z(1))
    end program prog
    """

    fortran_file = parse_fortran_file(data)
    prog = fortran_file.programs[0]

    for variable in prog.variables:
        assert (
            "allocatable" in variable.attribs
        ), f"Missing 'allocatable' in '{variable}' attributes"
        assert (
            variable.dimension == "(:)" or "dimension(:)" in variable.attribs
        ), f"Wrong dimension for '{variable}'"


def test_markdown_source_meta(parse_fortran_file):
    """Check that specifying 'source' in the procedure meta block is processed"""

    data = """\
    subroutine with_source
    !! source: true
    !!
    !! some docs
    end subroutine with_source
    """

    md = MetaMarkdown()

    fortran_file = parse_fortran_file(data)
    subroutine = fortran_file.subroutines[0]
    subroutine.markdown(md)

    assert subroutine.meta.source is True
    assert "with_source" in subroutine.src


def test_markdown_source_settings(parse_fortran_file):
    """Check that specifying 'source' in the settings works"""

    data = """\
    subroutine with_source
    !! some docs
    end subroutine with_source
    """

    md = MetaMarkdown()
    fortran_file = parse_fortran_file(data, source=True)
    subroutine = fortran_file.subroutines[0]
    subroutine.markdown(md)

    assert subroutine.meta.source is True
    assert "with_source" in subroutine.src


@pytest.mark.parametrize(
    ["snippet", "expected_error", "expected_name"],
    (
        (
            "program foo\n contains\n contains",
            "Multiple CONTAINS",
            "foo",
        ),
        (
            "program foo\n interface bar\n contains",
            "Unexpected CONTAINS",
            "bar",
        ),
        ("end", "END statement", "test.f90"),
        ("program foo\n module procedure bar", "Unexpected MODULE PROCEDURE", "foo"),
        ("program foo\n module bar", "Unexpected MODULE", "foo"),
        (
            "program foo\n submodule (foo) bar \n end program foo",
            "Unexpected SUBMODULE",
            "program 'foo'",
        ),
        ("program foo\n program bar", "Unexpected PROGRAM", "foo"),
        (
            "program foo\n end program foo\n program bar \n end program bar",
            "Multiple PROGRAM",
            "test.f90",
        ),
        (
            "program foo\n subroutine bar \n end subroutine \n end program",
            "Unexpected SUBROUTINE",
            "program 'foo'",
        ),
        (
            "program foo\n integer function bar() \n end function bar\n end program foo",
            "Unexpected FUNCTION",
            "program 'foo'",
        ),
    ),
)
def test_bad_parses(snippet, expected_error, expected_name, parse_fortran_file):
    with pytest.raises(ValueError) as e:
        parse_fortran_file(snippet, dbg=False)

    assert expected_error in e.value.args[0]
    assert expected_name in e.value.args[0]


def test_routine_iterator(parse_fortran_file):
    data = """\
    module foo
      interface
        module subroutine modsub1()
        end subroutine modsub1
        module subroutine modsub2()
        end subroutine modsub2
        module integer function modfunc1()
        end function modfunc1
        module integer function modfunc2()
        end function modfunc2
      end interface
    contains
      subroutine sub1()
      end subroutine sub1
      subroutine sub2()
      end subroutine sub2
      integer function func1()
      end function func1
      integer function func2()
      end function func2
    end module foo

    submodule (foo) bar
    contains
      module subroutine modsub1
      end subroutine modsub1
      module subroutine modsub2
      end subroutine modsub2
      module procedure modfunc1
      end procedure modfunc1
      module procedure modfunc2
      end procedure modfunc2

      subroutine sub3()
      end subroutine sub3
      subroutine sub4()
      end subroutine sub4
      integer function func3()
      end function func3
      integer function func4()
      end function func4
    end submodule bar
    """

    fortran_file = parse_fortran_file(data)

    module = fortran_file.modules[0]
    assert sorted([proc.name for proc in module.routines]) == [
        "func1",
        "func2",
        "sub1",
        "sub2",
    ]

    submodule = fortran_file.submodules[0]
    assert sorted([proc.name for proc in submodule.routines]) == [
        "func3",
        "func4",
        "modfunc1",
        "modfunc2",
        "modsub1",
        "modsub2",
        "sub3",
        "sub4",
    ]


def test_type_component_permissions(parse_fortran_file):
    data = """\
    module default_access
      private
      type :: type_default
        complex :: component_public
        complex, private :: component_private
      contains
        procedure :: sub_public
        procedure, private :: sub_private
      end type type_default

      type, public :: type_public
        public
        complex :: component_public
        complex, private :: component_private
      contains
        public
        procedure :: sub_public
        procedure, private :: sub_private
      end type type_public

      type :: type_private
        private
        character(len=1), public :: string_public
        character(len=1) :: string_private
      contains
        private
        procedure, public :: sub_public
        procedure :: sub_private
      end type type_private

      type :: type_public_private
        public
        character(len=1) :: string_public
        character(len=1), private :: string_private
      contains
        private
        procedure, public :: sub_public
        procedure :: sub_private
      end type type_public_private

      type :: type_private_public
        private
        character(len=1), public :: string_public
        character(len=1) :: string_private
      contains
        public
        procedure :: sub_public
        procedure, private :: sub_private
      end type type_private_public

      public :: type_default, type_private_public, type_public_private
    contains
      subroutine sub_public
      end subroutine sub_public

      subroutine sub_private
      end subroutine sub_private
    end module default_access
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())

    for ftype in fortran_file.modules[0].types:
        assert (
            ftype.variables[0].permission == "public"
        ), f"{ftype.name}::{ftype.variables[0].name}"
        assert (
            ftype.variables[1].permission == "private"
        ), f"{ftype.name}::{ftype.variables[1].name}"
        assert (
            ftype.boundprocs[0].permission == "public"
        ), f"{ftype.name}::{ftype.boundprocs[0].name}"
        assert (
            ftype.boundprocs[1].permission == "private"
        ), f"{ftype.name}::{ftype.boundprocs[1].name}"


def test_variable_formatting(parse_fortran_file):
    data = """\
    module foo_m
      character(kind=kind('a'), len=4), dimension(:, :), allocatable :: multidimension_string
      type :: bar
      end type bar
      type(bar), parameter :: something = bar()
    contains
      type(bar) function quux()
      end function quux
    end module foo_m
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())
    variable0 = fortran_file.modules[0].variables[0]
    variable1 = fortran_file.modules[0].variables[1]

    assert variable0.full_type == "character(kind=kind('a'), len=4)"
    assert (
        variable0.full_declaration
        == "character(kind=kind('a'), len=4), dimension(:, :), allocatable"
    )
    assert variable1.full_type == "type(bar)"
    assert variable1.full_declaration == "type(bar), parameter"

    function = fortran_file.modules[0].functions[0]
    assert function.retvar.full_declaration == "type(bar)"


def test_url(parse_fortran_file):
    data = """\
    program prog_foo
      integer :: int_foo
    contains
      subroutine sub_foo
      end subroutine sub_foo
      function func_foo()
      end function func_foo
    end program prog_foo

    module mod_foo
      real :: real_foo
      interface inter_foo
        module procedure foo1, foo2
      end interface inter_foo
      type :: foo_t
        integer :: int_bar
      end type
      enum, bind(C)
        enumerator :: red = 4, blue = 9
        enumerator :: yellow
      end enum
    contains
      subroutine foo1()
      end subroutine foo1
      subroutine foo2(x)
        integer :: x
      end subroutine foo2
    end module mod_foo

    submodule (mod_foo) submod_foo
    end submodule submod_foo
    """

    fortran_file = parse_fortran_file(data)
    program = fortran_file.programs[0]
    module = fortran_file.modules[0]
    submodule = fortran_file.submodules[0]

    assert program.get_dir() == "program"
    assert module.get_dir() == "module"
    assert submodule.get_dir() == "module"
    assert program.subroutines[0].get_dir() == "proc"
    assert program.functions[0].get_dir() == "proc"
    assert module.subroutines[0].get_dir() == "proc"
    assert module.interfaces[0].get_dir() == "interface"
    assert program.variables[0].get_dir() is None
    assert module.variables[0].get_dir() is None
    assert module.enums[0].get_dir() is None

    assert program.full_url.endswith("program/prog_foo.html")
    assert module.full_url.endswith("module/mod_foo.html")
    assert submodule.full_url.endswith("module/submod_foo.html")
    assert program.subroutines[0].full_url.endswith("proc/sub_foo.html")
    assert program.functions[0].full_url.endswith("proc/func_foo.html")
    assert module.subroutines[0].full_url.endswith("proc/foo1.html")
    assert module.interfaces[0].full_url.endswith("interface/inter_foo.html")
    assert program.variables[0].full_url.endswith(
        "program/prog_foo.html#variable-int_foo"
    )
    assert module.variables[0].full_url.endswith(
        "module/mod_foo.html#variable-real_foo"
    )


def test_single_character_interface(parse_fortran_file):
    data = """\
    module a
      interface b !! some comment
        module procedure c
      end interface b
    end module a
    """
    fortran_file = parse_fortran_file(data)
    assert fortran_file.modules[0].interfaces[0].name == "b"
    assert fortran_file.modules[0].interfaces[0].doc_list == [" some comment"]


def test_module_procedure_in_module(parse_fortran_file):
    data = """\
    module foo_mod
      interface
        module subroutine quaxx
        end subroutine quaxx
      end interface
    contains
      module procedure quaxx
        print*, "implementation"
      end procedure
    end module foo_mod
    """

    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    module.correlate(FakeProject())

    interface = module.interfaces[0]
    assert interface.name == "quaxx"
    modproc = module.modprocedures[0]

    assert interface.procedure.module == modproc
    assert modproc.module == interface


def test_module_interface_same_name_as_interface(parse_fortran_file):
    data = """\
    module foo_m
      interface foo
        module function foo() result(bar)
          logical bar
        end function
      end interface
    contains
      module procedure foo
        bar = .true.
      end procedure
    end module
    """

    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    module.correlate(FakeProject())

    interface = module.interfaces[0]
    assert interface.name == "foo"

    modproc = module.modprocedures[0]
    assert modproc.name == "foo"


def test_procedure_pointer(parse_fortran_file):
    data = """\
    module foo
      abstract interface
        integer pure function unary_f_t(n)
          implicit none
          integer, intent(in) :: n
        end function
      end interface

      private

      procedure(unary_f_t), pointer, public :: unary_f => null()

      interface generic_unary_f
        procedure unary_f
      end interface
    end module
    """

    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    module.correlate(FakeProject())
    assert len(module.interfaces[0].modprocs) == 0
    assert module.interfaces[0].variables[0].name == "unary_f"


def test_block_data(parse_fortran_file):
    data = """\
    block data name
      !! Block data docstring
      common /name/ foo
      !! Common block docstring

      character*31 foo(1024)
      !! Variable docstring

      data foo /'a', 'b', 'c', 'd', 'e', 1019*'0'/
    end
    """

    fortran_file = parse_fortran_file(data)
    blockdata = fortran_file.blockdata[0]

    assert blockdata.name == "name"
    assert blockdata.doc_list[0].strip() == "Block data docstring"
    assert len(blockdata.common) == 1
    assert blockdata.common[0].doc_list[0].strip() == "Common block docstring"
    assert len(blockdata.variables) == 1
    assert blockdata.variables[0].doc_list[0].strip() == "Variable docstring"


def test_subroutine_empty_args(parse_fortran_file):
    data = """\
    subroutine foo (    )
    end subroutine foo
    """

    fortran_file = parse_fortran_file(data)
    subroutine = fortran_file.subroutines[0]
    assert subroutine.args == []


def test_subroutine_whitespace(parse_fortran_file):
    data = """\
    subroutine foo (  a,b,    c,d  )
      integer :: a, b, c, d
    end subroutine foo
    """

    fortran_file = parse_fortran_file(data)
    subroutine = fortran_file.subroutines[0]
    arg_names = [arg.name for arg in subroutine.args]
    assert arg_names == ["a", "b", "c", "d"]


def test_function_empty_args(parse_fortran_file):
    data = """\
    integer function foo (    )
    end function foo
    """

    fortran_file = parse_fortran_file(data)
    function = fortran_file.functions[0]
    assert function.args == []


def test_function_whitespace(parse_fortran_file):
    data = """\
    integer function foo (  a,b,    c,d  )
      integer :: a, b, c, d
    end function foo
    """

    fortran_file = parse_fortran_file(data)
    function = fortran_file.functions[0]
    arg_names = [arg.name for arg in function.args]
    assert arg_names == ["a", "b", "c", "d"]


def test_bind_name_subroutine(parse_fortran_file):
    data = """\
    subroutine init() bind(C, name="c_init")
    end subroutine init
    """

    fortran_file = parse_fortran_file(data)
    subroutine = fortran_file.subroutines[0]

    assert subroutine.bindC == 'C, name="c_init"'


def test_bind_name_function(parse_fortran_file):
    data = """\
    integer function foo() bind(C, name="c_foo")
    end function foo
    """

    fortran_file = parse_fortran_file(data)
    function = fortran_file.functions[0]

    assert function.bindC == 'C, name="c_foo"'


def test_generic_bound_procedure(parse_fortran_file):
    data = """\
    module subdomain_m
      type subdomain_t
      contains
        procedure no_colon
        procedure :: colon
        generic :: operator(+) => no_colon, colon
      end type
      interface
        module function no_colon(lhs, rhs)
          class(subdomain_t), intent(in) :: lhs
          integer, intent(in) :: rhs
          type(subdomain_t) total
        end function
        module function colon(lhs, rhs)
          class(subdomain_t), intent(in) :: lhs, rhs
          type(subdomain_t) total
        end function
      end interface
    end module
    """

    fortran_file = parse_fortran_file(data)
    fortran_type = fortran_file.modules[0].types[0]

    expected_names = sorted(["no_colon", "colon", "operator(+)"])
    bound_proc_names = sorted([proc.name for proc in fortran_type.boundprocs])
    assert bound_proc_names == expected_names


def test_submodule_procedure_calls(parse_fortran_file):
    """Check that calls inside submodule procedures are correctly correlated"""

    data = """\
    module foo_m
      implicit none
      interface
        module function foo1(start, end) result(res)
          integer, intent(in) :: start, end
          integer :: res
        end function
      end interface
    end module

    submodule(foo_m) foo_s
      implicit none
    contains
      integer function bar(start, end)
        integer, intent(in) :: start, end
        bar = end - start
      end function

      module procedure foo1
        res = bar(start, end)
      end procedure
    end submodule
    """

    fortran_file = parse_fortran_file(data)
    fortran_file.modules[0].correlate(FakeProject())
    submodule = fortran_file.submodules[0]
    submodule.correlate(FakeProject())

    assert submodule.modprocedures[0].calls[0] == submodule.functions[0]


def test_namelist(parse_fortran_file):
    data = """\
    module mod_a
      integer :: var_a
    end module mod_a
    module mod_b
      use mod_a
      integer :: var_b
    end module mod_b

    program prog
      integer :: var_c
    contains
      subroutine sub(var_d)
        use mod_b
        integer, intent(in) :: var_d
        integer :: var_e
        namelist /namelist_a/ var_a, var_b, var_c, var_d, var_e
        !! namelist docstring
      end subroutine sub
    end program prog
    """
    fortran_file = parse_fortran_file(data)
    namelist = fortran_file.programs[0].subroutines[0].namelists[0]
    assert namelist.name == "namelist_a"

    expected_names = sorted(["var_a", "var_b", "var_c", "var_d", "var_e"])
    output_names = sorted(namelist.variables)
    assert output_names == expected_names

    assert namelist.doc_list == [" namelist docstring"]


def test_namelist_correlate(parse_fortran_file):
    data = """\
    program prog
      integer :: var_c
    contains
      subroutine sub(var_b)
        integer, intent(in) :: var_b
        integer :: var_a
        namelist /namelist_a/ var_a, var_b, var_c
      end subroutine sub
    end program prog
    """
    fortran_file = parse_fortran_file(data)
    fortran_file.programs[0].correlate(FakeProject())
    namelist = fortran_file.programs[0].subroutines[0].namelists[0]
    expected_names = sorted(["var_a", "var_b", "var_c"])
    output_names = sorted([variables.name for variables in namelist.variables])
    assert output_names == expected_names


def test_generic_source(tmp_path):
    data = """\
    #! docmark
    #* docmark_alt
    #> predocmark
    #| predocmark_alt
    """

    filename = tmp_path / "generic_source.sh"
    filename.write_text(dedent(data))

    settings = ProjectSettings(
        extra_filetypes=[{"extension": "sh", "comment": "#"}],
    )
    source = GenericSource(filename, settings)
    expected_docs = [
        "docmark",
        "docmark_alt",
        "predocmark",
        "predocmark_alt",
    ]

    assert source.doc_list == expected_docs


def test_type_bound_procedure_formatting(parse_fortran_file):
    data = """\
    module ford_example_type_mod
      type, abstract, public :: example_type
      contains
        procedure :: say_hello => example_type_say
        procedure, private, nopass :: say_int
        procedure, private, nopass :: say_real
        generic :: say_number => say_int, say_real
        procedure(say_interface), deferred :: say
        final :: example_type_finalise
      end type example_type

      interface
        subroutine say_interface(self)
          import say_type_base
          class(say_type_base), intent(inout) :: self
        end subroutine say_interface
      end interface

    contains

      subroutine example_type_say(self)
        class(example_type), intent(inout) :: self
      end subroutine example_type_say

      subroutine example_type_finalise(self)
        type(example_type), intent(inout) :: self
      end subroutine example_type_finalise

      subroutine say_int(int)
        integer, intent(in) :: int
      end subroutine say_int

      subroutine say_real(r)
        real, intent(in) :: r
      end subroutine say_real
    end module ford_example_type_mod
    """

    example_type = parse_fortran_file(data).modules[0].types[0]

    assert example_type.boundprocs[0].full_declaration == "procedure, public"
    assert example_type.boundprocs[1].full_declaration == "procedure, private, nopass"
    assert example_type.boundprocs[2].full_declaration == "procedure, private, nopass"
    assert example_type.boundprocs[3].full_declaration == "generic, public"
    assert (
        example_type.boundprocs[4].full_declaration
        == "procedure(say_interface), public, deferred"
    )


def test_type_num_lines(parse_fortran_file):
    data = """\
    module ford_example_type_mod
      type, abstract, public :: example_type
      contains
        procedure :: say_hello => example_type_say
        procedure, private, nopass :: say_int
        procedure, private, nopass :: say_real
        generic :: say_number => say_int, say_real, say_hello
        procedure(say_interface), deferred :: say
      end type example_type
      interface
        subroutine say_interface(self)
          import say_type_base
          class(say_type_base), intent(inout) :: self
        end subroutine say_interface
      end interface
    contains
      subroutine example_type_say(self)
        class(example_type), intent(inout) :: self
      end subroutine example_type_say
      subroutine say_int(int)
        integer, intent(in) :: int
      end subroutine say_int
      subroutine say_real(r)
        real, intent(in) :: r
      end subroutine say_real
    end module ford_example_type_mod
    """

    project = FakeProject()
    module = parse_fortran_file(data).modules[0]
    module.correlate(project)

    example_type = module.types[0]
    assert example_type.num_lines == 8
    assert example_type.num_lines_all == 8 + 9


def test_associate_array(parse_fortran_file):
    data = """\
    subroutine test()
      associate(phi => [1,2], theta => (/ 3, 4 /))
      end associate
    end subroutine test"""

    # Just check we can parse ok
    parse_fortran_file(data)


def test_blocks_with_type(parse_fortran_file):
    data = """\
    module foo
    contains
      subroutine sub1()
        block
          type :: t1
          end type t1
        end block
      end subroutine sub1
    end module foo
    """

    source = parse_fortran_file(data)
    module = source.modules[0]
    assert len(module.subroutines) == 1


def test_no_space_after_character_type(parse_fortran_file):
    data = """\
    CHARACTER(LEN=250)FUNCTION FirstWord( sString ) RESULT( sRes )
        CHARACTER(LEN=250)sString
    END FUNCTION FirstWord
    """

    source = parse_fortran_file(data)
    function = source.functions[0]
    assert function.name.lower() == "firstword"


def test_summary_handling_bug703(parse_fortran_file):
    """Check that `summary` works, PR #703"""
    data = """\
    !> summary: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    !>          Fusce ultrices tortor et felis tempus vehicula.
    !>          Nulla gravida, magna ut pharetra.
    !>
    !> Full description
    module test
    end module myModule
    """

    fortran_file = parse_fortran_file(data)
    md = MetaMarkdown()

    module = fortran_file.modules[0]
    module.markdown(md)

    assert "Lorem ipsum" in module.meta.summary


def test_doxygen_parameters(parse_fortran_file):
    data = """\
    !> @param stuff some comment
    !> Normal Comment
    !> @param[in] stuff_2 Doxygen comment
    !> @param     stuff_3 Comment should not show
    module a
      integer, intent(in) :: stuff
      integer, intent(in) :: stuff_2
      !! FORD comment
    end module a
    module b
      integer, intent(in) :: stuff_3
      !! Should only capture this comment for stuff_3
    end module a
    """
    fortran_file = parse_fortran_file(data)
    module_a = fortran_file.modules[0]
    module_b = fortran_file.modules[1]
    assert module_a.doc_list == [" Normal Comment"]
    # single doxygen comment
    assert module_a.variables[0].doc_list == [" some comment"]
    # doxygen comment and a FORD comment
    assert module_a.variables[1].doc_list == [" FORD comment", " Doxygen comment"]
    # doxygen comments are only shown for comments directly above the subroutine
    assert module_b.variables[0].doc_list == [
        " Should only capture this comment for stuff_3"
    ]


def test_no_doxygen_parameters(parse_fortran_file):
    data = """\
    !> Normal Comment
    !> @param stuff_2 Doxygen comment
    module a
      integer, intent(in) :: stuff
      integer, intent(in) :: stuff_2
      !! FORD comment
    end module a
    module b
      integer, intent(in) :: stuff_3
      !!comment for stuff_3
    end module a
    """
    fortran_file = parse_fortran_file(data, doxygen=False)
    module_a = fortran_file.modules[0]
    module_b = fortran_file.modules[1]
    assert module_a.doc_list == [" Normal Comment", " @param stuff_2 Doxygen comment"]
    assert module_a.variables[0].doc_list == []
    assert module_a.variables[1].doc_list == [" FORD comment"]
    # doxygen comments are only shown for comments directly above the subroutine
    assert module_b.variables[0].doc_list == ["comment for stuff_3"]


def test_doxygen_metadata_translation(parse_fortran_file):
    data = """\
    !> @brief summary bit
    !> Main details
    module a
    end module a
    """
    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    assert module.meta.summary == "summary bit"
    assert module.doc_list == [" Main details"]


def test_doxygen_multiple_metadata(parse_fortran_file):
    data = """\
    !> @brief summary bit
    !> @author Foo Shamaloo
    !> Main details
    !> @version 3.14
    module a
    end module a
    """
    fortran_file = parse_fortran_file(data)
    module = fortran_file.modules[0]
    assert module.meta.summary == "summary bit"
    assert module.meta.author == "Foo Shamaloo"
    assert module.meta.version == "3.14"
    assert module.doc_list == [" Main details"]


def test_doxygen_ok_on_source_file(parse_fortran_file):
    data = """\
    !! @brief Source file
    module a
    end module a
    """
    fortran_file = parse_fortran_file(data)
    assert fortran_file.meta.summary == "Source file"


def test_doxygen_see_link(parse_fortran_file):
    data = """\
    !> @see b
    module a
    end module a
    !> @see a with a description
    module b
    end module b
    """
    fortran_file = parse_fortran_file(data)
    assert fortran_file.modules[1].doc_list[0].strip() == "[[a]] with a description"
    assert fortran_file.modules[0].doc_list[0].strip() == "[[b]]"