summaryrefslogtreecommitdiffstats
path: root/src/fortrancode.l
blob: c7c4d898b3f5cdc925758b37baa14cf9c468c32c (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
/******************************************************************************
 *
 * Parser for syntax highlighting and references for Fortran90 F subset
 *
 * Copyright (C) by Anke Visser
 * based on the work of Dimitri van Heesch.
 * Copyright (C) 2020 by Dimitri van Heesch.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation under the terms of the GNU General Public License is hereby
 * granted. No representations are made about the suitability of this software
 * for any purpose. It is provided "as is" without express or implied warranty.
 * See the GNU General Public License for more details.
 *
 * Documents produced by Doxygen are derivative works derived from the
 * input used in their production; they are not affected by this license.
 *
 */

/**
 @todo - continuation lines not always recognized
       - merging of use-statements with same module name and different only-names
       - rename part of use-statement
       - links to interface functions
       - references to variables
**/
%option never-interactive
%option case-insensitive
%option reentrant
%option prefix="fortrancodeYY"
%option extra-type="struct fortrancodeYY_state *"
%option noyy_top_state
%top{
#include <stdint.h>
}

%{

/*
 *      includes
 */
#include <stdio.h>
#include <assert.h>
#include <ctype.h>

#include "doxygen.h"
#include "message.h"
#include "outputlist.h"
#include "util.h"
#include "membername.h"
#include "defargs.h"
#include "config.h"
#include "groupdef.h"
#include "classlist.h"
#include "filedef.h"
#include "namespacedef.h"
#include "tooltip.h"
#include "fortrancode.h"
#include "fortranscanner.h"
#include "containers.h"

const int fixedCommentAfter = 72;

// Toggle for some debugging info
//#define DBG_CTX(x) fprintf x
#define DBG_CTX(x) do { } while(0)

#define YY_NO_TOP_STATE 1
#define YY_NO_INPUT 1
#define YY_NO_UNISTD_H 1

#define USE_STATE2STRING 0

/*
 * For fixed formatted code position 6 is of importance (continuation character).
 * The following variables and macros keep track of the column number
 * YY_USER_ACTION is always called for each scan action
 * YY_FTN_RESET   is used to handle end of lines and reset the column counter
 * YY_FTN_REJECT  resets the column counters when a pattern is rejected and thus rescanned.
 */
int yy_old_start = 0;
int yy_my_start  = 0;
int yy_end       = 1;
#define YY_USER_ACTION {yy_old_start = yy_my_start; yy_my_start = yy_end; yy_end += static_cast<int>(yyleng);}
#define YY_FTN_RESET   {yy_old_start = 0; yy_my_start = 0; yy_end = 1;}
#define YY_FTN_REJECT  {yy_end = yy_my_start; yy_my_start = yy_old_start; REJECT;}

//--------------------------------------------------------------------------------

/**
  data of an use-statement
*/
class UseEntry
{
 public:
   QCString module; // just for debug
   std::vector<QCString> onlyNames;   /* entries of the ONLY-part */
};

/**
  module name -> list of ONLY/remote entries
  (module name = name of the module, which can be accessed via use-directive)
*/
class UseMap : public std::map<std::string,UseEntry>
{
};

/**
  Contains names of used modules and names of local variables.
*/
class Scope
{
  public:
    std::vector<QCString> useNames; //!< contains names of used modules
    StringUnorderedSet localVars; //!< contains names of local variables
    StringUnorderedSet externalVars; //!< contains names of external entities
};

/*===================================================================*/
/*
 *      statics
 */

struct fortrancodeYY_state
{
  QCString      docBlock;                   //!< contents of all lines of a documentation block
  QCString      currentModule=QCString();   //!< name of the current enclosing module
  UseMap      useMembers;                   //!< info about used modules
  UseEntry      useEntry;                   //!< current use statement info
  std::vector<Scope>  scopeStack;
  bool          isExternal = false;
  QCString      str=QCString();             //!< contents of fortran string

  CodeOutputInterface * code = 0;

  const char *  inputString = 0;     //!< the code fragment as text
  yy_size_t     inputPosition = 0;   //!< read offset during parsing
  int           inputLines = 0;      //!< number of line in the code fragment
  int           yyLineNr = 0;        //!< current line number
  int           contLineNr = 0;      //!< current, local, line number for continuation determination
  int          *hasContLine = 0;     //!< signals whether or not a line has a continuation line (fixed source form)
  bool          needsTermination = false;
  const Definition *searchCtx = 0;
  bool          collectXRefs = false;
  bool          isFixedForm = false;

  bool          insideBody = false;      //!< inside subprog/program body? => create links
  const char *  currentFontClass = 0;

  bool          exampleBlock = false;
  QCString      exampleName;
  QCString      exampleFile;

  FileDef *     sourceFileDef = 0;
  const Definition * currentDefinition = 0;
  const MemberDef *  currentMemberDef = 0;
  bool          includeCodeFragment = false;

  char          stringStartSymbol = '\0'; // single or double quote
// count in variable declaration to filter out
//  declared from referenced names
  int           bracketCount = 0;

// signal when in type / class /procedure declaration
  int           inTypeDecl = 0;

  bool          endComment = false;
};

#if USE_STATE2STRING
static const char *stateToString(int state);
#endif

static bool getFortranNamespaceDefs(const QCString &mname,
                               NamespaceDef *&cd);
static bool getFortranTypeDefs(const QCString &tname, const QCString &moduleName,
                               ClassDef *&cd, const UseMap &useMap);

//----------------------------------------------------------------------------

static void endFontClass(yyscan_t yyscanner);
static void startFontClass(yyscan_t yyscanner,const char *s);
static void setCurrentDoc(yyscan_t yyscanner,const QCString &anchor);
static void addToSearchIndex(yyscan_t yyscanner,const QCString &text);
static void startCodeLine(yyscan_t yyscanner);
static void endCodeLine(yyscan_t yyscanner);
static void nextCodeLine(yyscan_t yyscanner);
static void codifyLines(yyscan_t yyscanner,const QCString &text);
static void writeMultiLineCodeLink(yyscan_t yyscanner,CodeOutputInterface &ol,
                  Definition *d,const QCString &text);
static bool getGenericProcedureLink(yyscan_t yyscanner,const ClassDef *cd,
                                    const QCString &memberText,
                                    CodeOutputInterface &ol);
static bool getLink(yyscan_t yyscanner,const UseMap &useMap, // map with used modules
                    const QCString &memberText,  // exact member text
                    CodeOutputInterface &ol,
                    const QCString &text);
static void generateLink(yyscan_t yyscanner,CodeOutputInterface &ol, const QCString &lname);
static void generateLink(yyscan_t yyscanner,CodeOutputInterface &ol, const char *lname);
static int countLines(yyscan_t yyscanner);
static void startScope(yyscan_t yyscanner);
static void endScope(yyscan_t yyscanner);
static void addUse(yyscan_t yyscanner,const QCString &moduleName);
static void addLocalVar(yyscan_t yyscanner,const QCString &varName);
static MemberDef *getFortranDefs(yyscan_t yyscanner,const QCString &memberName, const QCString &moduleName,
                                 const UseMap &useMap);
static yy_size_t yyread(yyscan_t yyscanner,char *buf,yy_size_t max_size);


//-------------------------------------------------------------------

static std::mutex g_docCrossReferenceMutex;
static std::mutex g_countFlowKeywordsMutex;

/* -----------------------------------------------------------------*/
#undef  YY_INPUT
#define YY_INPUT(buf,result,max_size) result=yyread(yyscanner,buf,max_size);

%}

IDSYM     [a-z_A-Z0-9]
ID        [a-z_A-Z]+{IDSYM}*
SUBPROG   (subroutine|function)
B         [ \t]
BS        [ \t]*
BS_       [ \t]+
COMMA     {BS},{BS}
ARGS_L0   ("("[^)]*")")
ARGS_L1a  [^()]*"("[^)]*")"[^)]*
ARGS_L1   ("("{ARGS_L1a}*")")
ARGS_L2   "("({ARGS_L0}|[^()]|{ARGS_L1a}|{ARGS_L1})*")"
ARGS      {BS}({ARGS_L0}|{ARGS_L1}|{ARGS_L2})

NUM_TYPE  (complex|integer|logical|real)
LOG_OPER  (\.and\.|\.eq\.|\.eqv\.|\.ge\.|\.gt\.|\.le\.|\.lt\.|\.ne\.|\.neqv\.|\.or\.|\.not\.)
KIND      {ARGS}
CHAR      (CHARACTER{ARGS}?|CHARACTER{BS}"*"({BS}[0-9]+|{ARGS}))
TYPE_SPEC (({NUM_TYPE}({BS}"*"{BS}[0-9]+)?)|({NUM_TYPE}{KIND})|DOUBLE{BS}COMPLEX|DOUBLE{BS}PRECISION|{CHAR}|TYPE|CLASS|PROCEDURE|ENUMERATOR)

INTENT_SPEC intent{BS}"("{BS}(in|out|in{BS}out){BS}")"
ATTR_SPEC (IMPLICIT|ALLOCATABLE|DIMENSION{ARGS}|EXTERNAL|{INTENT_SPEC}|INTRINSIC|OPTIONAL|PARAMETER|POINTER|PROTECTED|PRIVATE|PUBLIC|SAVE|TARGET|(NON_)?RECURSIVE|PURE|IMPURE|ELEMENTAL|VALUE|NOPASS|DEFERRED|CONTIGUOUS|VOLATILE)
ACCESS_SPEC (PROTECTED|PRIVATE|PUBLIC)
/* Assume that attribute statements are almost the same as attributes. */
ATTR_STMT {ATTR_SPEC}|DIMENSION
FLOW      (DO|SELECT|CASE|SELECT{BS}(CASE|TYPE)|WHERE|IF|THEN|ELSE|WHILE|FORALL|ELSEWHERE|ELSEIF|RETURN|CONTINUE|EXIT|GO{BS}TO)
COMMANDS  (FORMAT|CONTAINS|MODULE{BS_}PROCEDURE|WRITE|READ|ALLOCATE|ALLOCATED|ASSOCIATED|PRESENT|DEALLOCATE|NULLIFY|SIZE|INQUIRE|OPEN|CLOSE|FLUSH|DATA|COMMON)
IGNORE    (CALL)
PREFIX    ((NON_)?RECURSIVE{BS_}|IMPURE{BS_}|PURE{BS_}|ELEMENTAL{BS_}){0,4}((NON_)?RECURSIVE|IMPURE|PURE|ELEMENTAL)?0
LANGUAGE_BIND_SPEC BIND{BS}"("{BS}C{BS}(,{BS}NAME{BS}"="{BS}"\""(.*)"\""{BS})?")"

/* |  */

%option noyywrap
%option stack
%option caseless
/*%option debug*/

%x Start
%x SubCall
%x FuncDef
%x ClassName
%x ClassVar
%x Subprog
%x DocBlock
%x Use
%x UseOnly
%x Import
%x Declaration
%x DeclarationBinding
%x DeclContLine
%x Parameterlist
%x String
%x Subprogend

%%
 /*==================================================================*/

 /*-------- ignore ------------------------------------------------------------*/

<Start>{IGNORE}/{BS}"("                   { // do not search keywords, intrinsics... TODO: complete list
                                            codifyLines(yyscanner,yytext);
                                          }
 /*-------- inner construct ---------------------------------------------------*/

<Start>{COMMANDS}/{BS}[,( \t\n]           {  // highlight
                                            /* font class is defined e.g. in doxygen.css */
                                            startFontClass(yyscanner,"keyword");
                                            codifyLines(yyscanner,yytext);
                                            endFontClass(yyscanner);
                                          }
<Start>{FLOW}/{BS}[,( \t\n]               {
                                          if (yyextra->isFixedForm)
                                          {
                                            if ((yy_my_start == 1) && ((yytext[0] == 'c') || (yytext[0] == 'C'))) YY_FTN_REJECT;
                                          }
                                          if (yyextra->currentMemberDef && yyextra->currentMemberDef->isFunction())
                                          {
                                            std::lock_guard<std::mutex> lock(g_countFlowKeywordsMutex);
                                            MemberDefMutable *mdm = toMemberDefMutable(yyextra->currentMemberDef);
                                            if (mdm)
                                            {
                                              mdm->incrementFlowKeyWordCount();
                                            }
                                          }
                                          /* font class is defined e.g. in doxygen.css */
                                          startFontClass(yyscanner,"keywordflow");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>{BS}(CASE|CLASS|TYPE){BS_}(IS|DEFAULT) {
                                          startFontClass(yyscanner,"keywordflow");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>{BS}"end"({BS}{FLOW})/[ \t\n]       { // list is a bit long as not all have possible end
                                          startFontClass(yyscanner,"keywordflow");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>"implicit"{BS}("none"|{TYPE_SPEC})  {
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>^{BS}"namelist"/[/]              {  // Namelist specification
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
 /*-------- use statement -------------------------------------------*/
<Start>"use"{BS_}                       {
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Use);
                                        }
<Use>"ONLY"                             { // TODO: rename
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(UseOnly);
                                        }
<Use>{ID}                               {
                                          QCString tmp(yytext);
                                          tmp = tmp.lower();
                                          yyextra->insideBody=TRUE;
                                          generateLink(yyscanner,*yyextra->code, yytext);
                                          yyextra->insideBody=FALSE;

                                          /* append module name to use dict */
                                          yyextra->useEntry = UseEntry();
                                          yyextra->useEntry.module = tmp;
                                          yyextra->useMembers.insert(std::make_pair(tmp.str(), yyextra->useEntry));
                                          addUse(yyscanner,tmp);
                                        }
<Use,UseOnly,Import>{BS},{BS}           { codifyLines(yyscanner,yytext); }
<UseOnly,Import>{BS}&{BS}"\n"           { codifyLines(yyscanner,yytext);
                                          yyextra->contLineNr++;
                                          YY_FTN_RESET}
<UseOnly>{ID}                           {
                                          QCString tmp(yytext);
                                          tmp = tmp.lower();
                                          yyextra->useEntry.onlyNames.push_back(tmp);
                                          yyextra->insideBody=TRUE;
                                          generateLink(yyscanner,*yyextra->code, yytext);
                                          yyextra->insideBody=FALSE;
                                        }
<Use,UseOnly,Import>"\n"                {
                                          unput(*yytext);
                                          yy_pop_state(yyscanner);
                                          YY_FTN_RESET
                                        }
<*>"import"{BS}/"\n"                    |
<*>"import"{BS_}                        {
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Import);
                                        }
<Import>{ID}                            {
                                          yyextra->insideBody=TRUE;
                                          generateLink(yyscanner,*yyextra->code, yytext);
                                          yyextra->insideBody=FALSE;
                                        }
<Import>("ONLY"|"NONE"|"ALL")           {
                                          startFontClass(yyscanner,"keywordtype");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
 /*-------- fortran module  -----------------------------------------*/
<Start>("block"{BS}"data"|"program"|"module"|"interface")/{BS_}|({COMMA}{ACCESS_SPEC})|\n {  //
                                          startScope(yyscanner);
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(ClassName);
                                          if (!qstricmp(yytext,"module")) yyextra->currentModule="module";
                                        }
<Start>("enum")/{BS_}|{BS}{COMMA}{BS}{LANGUAGE_BIND_SPEC}|\n {  //
                                          startScope(yyscanner);
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(ClassName);
                                        }
<*>{LANGUAGE_BIND_SPEC}                 {  //
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>("type")/{BS_}|({COMMA}({ACCESS_SPEC}|ABSTRACT|EXTENDS))|\n {  //
                                          startScope(yyscanner);
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(ClassName);
                                        }
<ClassName>{ID}                         {
                                          if (yyextra->currentModule == "module")
                                          {
                                            yyextra->currentModule=yytext;
                                            yyextra->currentModule = yyextra->currentModule.lower();
                                          }
                                          generateLink(yyscanner,*yyextra->code,yytext);
                                          yy_pop_state(yyscanner);
                                        }
<ClassName>({ACCESS_SPEC}|ABSTRACT|EXTENDS)/[,:( ] { //| variable declaration
                                          startFontClass(yyscanner,"keyword");
                                          yyextra->code->codify(QCString(yytext));
                                          endFontClass(yyscanner);
                                        }
<ClassName>\n                           { // interface may be without name
                                          yy_pop_state(yyscanner);
                                          YY_FTN_REJECT;
                                        }
<Start>^{BS}"end"({BS_}"enum").*        {
                                          YY_FTN_REJECT;
                                        }
<Start>^{BS}"end"({BS_}"type").*        {
                                          YY_FTN_REJECT;
                                        }
<Start>^{BS}"end"({BS_}"module").*      { // just reset yyextra->currentModule, rest is done in following rule
                                          yyextra->currentModule=0;
                                          YY_FTN_REJECT;
                                        }
 /*-------- subprog definition -------------------------------------*/
<Start>({PREFIX}{BS_})?{TYPE_SPEC}{BS_}({PREFIX}{BS_})?{BS}/{SUBPROG}{BS_}  {   // TYPE_SPEC is for old function style function result
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Start>({PREFIX}{BS_})?{SUBPROG}{BS_}   {  // Fortran subroutine or function found
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Subprog);
                                        }
<Subprog>{ID}                           { // subroutine/function name
                                          DBG_CTX((stderr, "===> start subprogram %s\n", yytext));
                                          startScope(yyscanner);
                                          generateLink(yyscanner,*yyextra->code,yytext);
                                        }
<Subprog>"result"/{BS}"("[^)]*")"       {
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<Subprog>"("[^)]*")"                    { // ignore rest of line
                                          codifyLines(yyscanner,yytext);
                                        }
<Subprog,Subprogend>"\n"                { codifyLines(yyscanner,yytext);
                                          yyextra->contLineNr++;
                                          yy_pop_state(yyscanner);
                                          YY_FTN_RESET
                                        }
<Start>"end"{BS}("block"{BS}"data"|{SUBPROG}|"module"|"program"|"enum"|"type"|"interface")?{BS}     {  // Fortran subroutine or function ends
                                          //cout << "===> end function " << yytext << endl;
                                          endScope(yyscanner);
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Subprogend);
                                        }
<Subprogend>{ID}/{BS}(\n|!|;)           {
                                          generateLink(yyscanner,*yyextra->code,yytext);
                                          yy_pop_state(yyscanner);
                                        }
<Start>"end"{BS}("block"{BS}"data"|{SUBPROG}|"module"|"program"|"enum"|"type"|"interface"){BS}/(\n|!|;) {  // Fortran subroutine or function ends
                                          //cout << "===> end function " << yytext << endl;
                                          endScope(yyscanner);
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
 /*-------- variable declaration ----------------------------------*/
<Start>^{BS}"real"/[,:( ]               { // real is a bit tricky as it is a data type but also a function.
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Declaration);
                                          startFontClass(yyscanner,"keywordtype");
                                          yyextra->code->codify(QCString(yytext));
                                          endFontClass(yyscanner);
                                        }
<Start>{TYPE_SPEC}/[,:( ]               {
                                          QCString typ(yytext);
                                          typ = removeRedundantWhiteSpace(typ.lower());
                                          if (typ.startsWith("real")) YY_FTN_REJECT;
                                          if (typ == "type" || typ == "class" || typ == "procedure") yyextra->inTypeDecl = 1;
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(Declaration);
                                          startFontClass(yyscanner,"keywordtype");
                                          yyextra->code->codify(QCString(yytext));
                                          endFontClass(yyscanner);
                                        }
<Start>{ATTR_SPEC}                      {
                                          if (QCString(yytext) == "external")
                                          {
                                            yy_push_state(YY_START,yyscanner);
                                            BEGIN(Declaration);
                                            yyextra->isExternal = true;
                                          }
                                          startFontClass(yyscanner,"keywordtype");
                                          yyextra->code->codify(QCString(yytext));
                                          endFontClass(yyscanner);
                                        }
<Declaration>({TYPE_SPEC}|{ATTR_SPEC})/[,:( ] { //| variable declaration
                                          if (QCString(yytext) == "external") yyextra->isExternal = true;
                                          startFontClass(yyscanner,"keywordtype");
                                          yyextra->code->codify(QCString(yytext));
                                          endFontClass(yyscanner);
                                        }
<Declaration>{ID}                       { // local var
                                          if (yyextra->isFixedForm && yy_my_start == 1)
                                          {
                                            startFontClass(yyscanner,"comment");
                                            yyextra->code->codify(QCString(yytext));
                                            endFontClass(yyscanner);
                                          }
                                          else if (yyextra->currentMemberDef &&
                                                   ((yyextra->currentMemberDef->isFunction() && (yyextra->currentMemberDef->typeString()!=QCString("subroutine") || yyextra->inTypeDecl)) ||
                                                     yyextra->currentMemberDef->isVariable() || yyextra->currentMemberDef->isEnumValue()
                                                    )
                                                   )
                                          {
                                            generateLink(yyscanner,*yyextra->code, yytext);
                                          }
                                          else
                                          {
                                            yyextra->code->codify(QCString(yytext));
                                            addLocalVar(yyscanner,QCString(yytext));
                                          }
                                        }
<Declaration>{BS}("=>"|"="){BS}         { // Procedure binding
                                          BEGIN(DeclarationBinding);
                                          yyextra->code->codify(QCString(yytext));
                                        }
<DeclarationBinding>{ID}                { // Type bound procedure link
                                          generateLink(yyscanner,*yyextra->code, yytext);
                                          yy_pop_state(yyscanner);
                                        }
<Declaration>[(]                        { // start of array or type / class specification
                                          yyextra->bracketCount++;
                                          yyextra->code->codify(QCString(yytext));
                                        }

<Declaration>[)]                        { // end array specification
                                          yyextra->bracketCount--;
                                          if (!yyextra->bracketCount) yyextra->inTypeDecl = 0;
                                          yyextra->code->codify(QCString(yytext));
                                        }

<Declaration,DeclarationBinding>"&"     { // continuation line
                                          yyextra->code->codify(QCString(yytext));
                                          if (!yyextra->isFixedForm)
                                          {
                                            yy_push_state(YY_START,yyscanner);
                                            BEGIN(DeclContLine);
                                          }
                                        }
<DeclContLine>"\n"                      { // declaration not yet finished
                                          yyextra->contLineNr++;
                                          codifyLines(yyscanner,yytext);
                                          yyextra->bracketCount = 0;
                                          yy_pop_state(yyscanner);
                                          YY_FTN_RESET
                                        }
<Declaration,DeclarationBinding>"\n"    { // end declaration line (?)
                                          if (yyextra->endComment)
                                          {
                                            yyextra->endComment=FALSE;
                                          }
                                          else
                                          {
                                            codifyLines(yyscanner,yytext);
                                          }
                                          yyextra->bracketCount = 0;
                                          yyextra->contLineNr++;
                                          if (!(yyextra->hasContLine && yyextra->hasContLine[yyextra->contLineNr - 1]))
                                          {
                                            yyextra->isExternal = false;
                                            yy_pop_state(yyscanner);
                                          }
                                          YY_FTN_RESET
                                        }

 /*-------- subprog calls  -----------------------------------------*/

<Start>"call"{BS_}                      {
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(SubCall);
                                        }
<SubCall>{ID}                           { // subroutine call
                                          yyextra->insideBody=TRUE;
                                          generateLink(yyscanner,*yyextra->code, yytext);
                                          yyextra->insideBody=FALSE;
                                          yy_pop_state(yyscanner);
                                        }
<Start>{ID}{BS}/"("                     { // function call
                                          if (yyextra->isFixedForm && yy_my_start == 6)
                                          {
                                            // fixed form continuation line
                                            YY_FTN_REJECT;
                                          }
                                          else if (QCString(yytext).stripWhiteSpace().lower() == "type")
                                          {
                                            yy_push_state(YY_START,yyscanner);
                                            BEGIN(Declaration);
                                            startFontClass(yyscanner,"keywordtype");
                                            yyextra->code->codify(QCString(yytext).stripWhiteSpace());
                                            endFontClass(yyscanner);
                                            yyextra->code->codify(QCString(yytext + 4));
                                          }
                                          else
                                          {
                                            yyextra->insideBody=TRUE;
                                            generateLink(yyscanner,*yyextra->code,yytext);
                                            yyextra->insideBody=FALSE;
                                          }
                                        }

 /*-------- comments ---------------------------------------------------*/
<Start,Declaration,DeclarationBinding>\n?{BS}"!>"|"!<"                 { // start comment line or comment block
                                          if (yytext[0] == '\n')
                                          {
                                            yyextra->contLineNr++;
                                            yy_old_start = 0;
                                            yy_my_start = 1;
                                            yy_end = static_cast<int>(yyleng);
                                          }
                                          // Actually we should see if ! on position 6, can be continuation
                                          // but the chance is very unlikely, so no effort to solve it here
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(DocBlock);
                                          yyextra->docBlock=yytext;
                                        }
<Declaration,DeclarationBinding>{BS}"!<"                   { // start comment line or comment block
                                          yy_push_state(YY_START,yyscanner);
                                          BEGIN(DocBlock);
                                          yyextra->docBlock=yytext;
                                        }

<DocBlock>.*                            { // contents of current comment line
                                          yyextra->docBlock+=yytext;
                                        }
<DocBlock>"\n"{BS}("!>"|"!<"|"!!")      { // comment block (next line is also comment line)
                                          yyextra->contLineNr++;
                                          yy_old_start = 0;
                                          yy_my_start = 1;
                                          yy_end = static_cast<int>(yyleng);
                                          // Actually we should see if ! on position 6, can be continuation
                                          // but the chance is very unlikely, so no effort to solve it here
                                          yyextra->docBlock+=yytext;
                                        }
<DocBlock>"\n"                          { // comment block ends at the end of this line
                                          // remove special comment (default config)
                                          yyextra->contLineNr++;
                                          if (Config_getBool(STRIP_CODE_COMMENTS))
                                          {
                                            yyextra->yyLineNr+=((QCString)yyextra->docBlock).contains('\n');
                                            yyextra->yyLineNr+=1;
                                            nextCodeLine(yyscanner);
                                            yyextra->endComment=TRUE;
                                          }
                                          else // do not remove comment
                                          {
                                            startFontClass(yyscanner,"comment");
                                            codifyLines(yyscanner,yyextra->docBlock);
                                            endFontClass(yyscanner);
                                          }
                                          unput(*yytext);
                                          yyextra->contLineNr--;
                                          yy_pop_state(yyscanner);
                                          YY_FTN_RESET
                                        }

<*>"!"[^><\n].*|"!"$                    { // normal comment
                                          if(YY_START == String) YY_FTN_REJECT; // ignore in strings
                                          if (yyextra->isFixedForm && yy_my_start == 6) YY_FTN_REJECT;
                                          startFontClass(yyscanner,"comment");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }

<*>^[Cc*].*                             { // normal comment
                                          if(! yyextra->isFixedForm) YY_FTN_REJECT;

                                          startFontClass(yyscanner,"comment");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<*>"assignment"/{BS}"("{BS}"="{BS}")"   {
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }
<*>"operator"/{BS}"("[^)]*")"           {
                                          startFontClass(yyscanner,"keyword");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                        }

 /*------ preprocessor  --------------------------------------------*/
<Start>"#".*\n                          {
                                          if (yyextra->isFixedForm && yy_my_start == 6) YY_FTN_REJECT;
                                          yyextra->contLineNr++;
                                          startFontClass(yyscanner,"preprocessor");
                                          codifyLines(yyscanner,yytext);
                                          endFontClass(yyscanner);
                                          YY_FTN_RESET
                                        }
 /*------ variable references?  -------------------------------------*/

<Start>"%"{BS}{ID}                      { // ignore references to elements
                                          yyextra->code->codify(QCString(yytext));
                                        }
<Start>{ID}                             {
                                            yyextra->insideBody=TRUE;
                                            generateLink(yyscanner,*yyextra->code, yytext);
                                            yyextra->insideBody=FALSE;
                                        }
 /*------ strings --------------------------------------------------*/
<String>\n                              { // string with \n inside
                                          yyextra->contLineNr++;
                                          yyextra->str+=yytext;
                                          startFontClass(yyscanner,"stringliteral");
                                          codifyLines(yyscanner,yyextra->str);
                                          endFontClass(yyscanner);
                                          yyextra->str = "";
                                          YY_FTN_RESET
                                        }
<String>\"|\'                           { // string ends with next quote without previous backspace
                                          if(yytext[0]!=yyextra->stringStartSymbol) YY_FTN_REJECT; // single vs double quote
                                          yyextra->str+=yytext;
                                          startFontClass(yyscanner,"stringliteral");
                                          codifyLines(yyscanner,yyextra->str);
                                          endFontClass(yyscanner);
                                          yy_pop_state(yyscanner);
                                        }
<String>.                               {yyextra->str+=yytext;}

<*>\"|\'                                { /* string starts */
                                          /* if(YY_START == StrIgnore) YY_FTN_REJECT; // ignore in simple comments */
                                          if (yyextra->isFixedForm && yy_my_start == 6) YY_FTN_REJECT;
                                          yy_push_state(YY_START,yyscanner);
                                          yyextra->stringStartSymbol=yytext[0]; // single or double quote
                                          BEGIN(String);
                                          yyextra->str=yytext;
                                        }
 /*-----------------------------------------------------------------------------*/

<*>\n                                   {
                                          if (yyextra->endComment)
                                          {
                                            yyextra->endComment=FALSE;
                                          }
                                          else
                                          {
                                            codifyLines(yyscanner,yytext);
                                            // comment cannot extend over the end of a line so should always be terminated at the end of the line.
                                            if (yyextra->currentFontClass && !strcmp(yyextra->currentFontClass,"comment")) endFontClass(yyscanner);
                                          }
                                          yyextra->contLineNr++;
                                          YY_FTN_RESET
                                        }
<*>^{BS}"type"{BS}"="                   { yyextra->code->codify(QCString(yytext)); }

<*>[\x80-\xFF]*                         { // keep utf8 characters together...
                                          if (yyextra->isFixedForm && yy_my_start > fixedCommentAfter)
                                          {
                                            startFontClass(yyscanner,"comment");
                                            codifyLines(yyscanner,yytext);
                                          }
                                          else
                                          {
                                            yyextra->code->codify(QCString(yytext));
                                          }
                                        }
<*>.                                    {
                                          if (yyextra->isFixedForm && yy_my_start > fixedCommentAfter)
                                          {
                                            //yy_push_state(YY_START,yyscanner);
                                            //BEGIN(DocBlock);
                                            //yyextra->docBlock=yytext;
                                            startFontClass(yyscanner,"comment");
                                            codifyLines(yyscanner,yytext);
                                          }
                                          else
                                          {
                                            yyextra->code->codify(QCString(yytext));
                                          }
                                        }
<*>{LOG_OPER}                           { // Fortran logical comparison keywords
                                          yyextra->code->codify(QCString(yytext));
                                        }
<*><<EOF>>                              {
                                          if (YY_START == DocBlock) {
                                            if (!Config_getBool(STRIP_CODE_COMMENTS))
                                            {
                                              startFontClass(yyscanner,"comment");
                                              codifyLines(yyscanner,yyextra->docBlock);
                                              endFontClass(yyscanner);
                                            }
                                          }
                                          yyterminate();
                                        }
%%

/*@ ----------------------------------------------------------------------------
 */

static yy_size_t yyread(yyscan_t yyscanner,char *buf,yy_size_t max_size)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  yy_size_t inputPosition = yyextra->inputPosition;
  const char *s = yyextra->inputString + inputPosition;
  yy_size_t c=0;
  while( c < max_size && *s)
  {
    *buf++ = *s++;
    c++;
  }
  yyextra->inputPosition += c;
  return c;
}

static void endFontClass(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (yyextra->currentFontClass)
  {
    yyextra->code->endFontClass();
    yyextra->currentFontClass=0;
  }
}

static void startFontClass(yyscan_t yyscanner,const char *s)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  // if font class is already set don't stop and start it.
  // strcmp does not like null pointers as input.
  if (!yyextra->currentFontClass || !s || strcmp(yyextra->currentFontClass,s))
  {
    endFontClass(yyscanner);
    yyextra->code->startFontClass(QCString(s));
    yyextra->currentFontClass=s;
  }
}

static void setCurrentDoc(yyscan_t yyscanner,const QCString &anchor)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (Doxygen::searchIndex)
  {
    if (yyextra->searchCtx)
    {
      yyextra->code->setCurrentDoc(yyextra->searchCtx,yyextra->searchCtx->anchor(),FALSE);
    }
    else
    {
      yyextra->code->setCurrentDoc(yyextra->sourceFileDef,anchor,TRUE);
    }
  }
}

static void addToSearchIndex(yyscan_t yyscanner,const QCString &text)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (Doxygen::searchIndex)
  {
    yyextra->code->addWord(text,FALSE);
  }
}

/*! start a new line of code, inserting a line number if yyextra->sourceFileDef
 * is TRUE. If a definition starts at the current line, then the line
 * number is linked to the documentation of that definition.
 */
static void startCodeLine(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (yyextra->sourceFileDef)
  {
    //QCString lineNumber,lineAnchor;
    //lineNumber.sprintf("%05d",yyextra->yyLineNr);
    //lineAnchor.sprintf("l%05d",yyextra->yyLineNr);

    const Definition *d = yyextra->sourceFileDef->getSourceDefinition(yyextra->yyLineNr);
    //printf("startCodeLine %d d=%s\n", yyextra->yyLineNr,d ? qPrint(d->name()) : "<null>");
    if (!yyextra->includeCodeFragment && d)
    {
      yyextra->currentDefinition = d;
      yyextra->currentMemberDef = yyextra->sourceFileDef->getSourceMember(yyextra->yyLineNr);
      yyextra->insideBody = FALSE;
      yyextra->endComment = FALSE;
      QCString lineAnchor;
      lineAnchor.sprintf("l%05d",yyextra->yyLineNr);
      if (yyextra->currentMemberDef)
      {
        yyextra->code->writeLineNumber(yyextra->currentMemberDef->getReference(),
                                yyextra->currentMemberDef->getOutputFileBase(),
                                yyextra->currentMemberDef->anchor(),yyextra->yyLineNr);
        setCurrentDoc(yyscanner,lineAnchor);
      }
      else if (d->isLinkableInProject())
      {
        yyextra->code->writeLineNumber(d->getReference(),
                                d->getOutputFileBase(),
                                QCString(),yyextra->yyLineNr);
        setCurrentDoc(yyscanner,lineAnchor);
      }
    }
    else
    {
      yyextra->code->writeLineNumber(QCString(),QCString(),QCString(),yyextra->yyLineNr);
    }
  }
  yyextra->code->startCodeLine(yyextra->sourceFileDef);
  if (yyextra->currentFontClass)
  {
    yyextra->code->startFontClass(QCString(yyextra->currentFontClass));
  }
}


static void endCodeLine(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  endFontClass(yyscanner);
  yyextra->code->endCodeLine();
}

static void nextCodeLine(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  const char * fc = yyextra->currentFontClass;
  endCodeLine(yyscanner);
  if (yyextra->yyLineNr<yyextra->inputLines)
  {
    yyextra->currentFontClass = fc;
    startCodeLine(yyscanner);
  }
}

/*! write a code fragment 'text' that may span multiple lines, inserting
 * line numbers for each line.
 */
static void codifyLines(yyscan_t yyscanner,const QCString &text)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  //printf("codifyLines(%d,\"%s\")\n",yyextra->yyLineNr,text);
  if (text.isEmpty()) return;
  const char *p=text.data(),*sp=p;
  char c;
  bool done=FALSE;
  while (!done)
  {
    sp=p;
    while ((c=*p++) && c!='\n') { }
    if (c=='\n')
    {
      yyextra->yyLineNr++;
      int l = (int)(p-sp-1);
      char *tmp = (char*)malloc(l+1);
      memcpy(tmp,sp,l);
      tmp[l]='\0';
      yyextra->code->codify(QCString(tmp));
      free(tmp);
      nextCodeLine(yyscanner);
    }
    else
    {
      yyextra->code->codify(QCString(sp));
      done=TRUE;
    }
  }
}

/*! writes a link to a fragment \a text that may span multiple lines, inserting
 * line numbers for each line. If \a text contains newlines, the link will be
 * split into multiple links with the same destination, one for each line.
 */
static void writeMultiLineCodeLink(yyscan_t yyscanner,CodeOutputInterface &ol,
                  Definition *d,const QCString &text)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  static bool sourceTooltips = Config_getBool(SOURCE_TOOLTIPS);
  TooltipManager::instance().addTooltip(ol,d);
  QCString ref  = d->getReference();
  QCString file = d->getOutputFileBase();
  QCString anchor = d->anchor();
  QCString tooltip;
  if (!sourceTooltips) // fall back to simple "title" tooltips
  {
    tooltip = d->briefDescriptionAsTooltip();
  }
  bool done=FALSE;
  const char *p=text.data();
  while (!done)
  {
    const char *sp=p;
    char c;
    while ((c=*p++) && c!='\n') { }
    if (c=='\n')
    {
      yyextra->yyLineNr++;
      //printf("writeCodeLink(%s,%s,%s,%s)\n",ref,file,anchor,sp);
      ol.writeCodeLink(ref,file,anchor,QCString(sp,p-sp-1),tooltip);
      nextCodeLine(yyscanner);
    }
    else
    {
      //printf("writeCodeLink(%s,%s,%s,%s)\n",ref,file,anchor,sp);
      ol.writeCodeLink(ref,file,anchor,sp,tooltip);
      done=TRUE;
    }
  }
}
//-------------------------------------------------------------------------------
/**
  searches for definition of a module (Namespace)
  @param mname the name of the module
  @param cd the entry, if found or null
  @returns true, if module is found
*/
static bool getFortranNamespaceDefs(const QCString &mname,
                               NamespaceDef *&cd)
{
  if (mname.isEmpty()) return FALSE; /* empty name => nothing to link */

  // search for module
  if ((cd=Doxygen::namespaceLinkedMap->find(mname))) return TRUE;

  return FALSE;
}
//-------------------------------------------------------------------------------
/**
  searches for definition of a type
  @param tname the name of the type
  @param moduleName name of enclosing module or null, if global entry
  @param cd the entry, if found or null
  @param useMap map of data of USE-statement
  @returns true, if type is found
*/
static bool getFortranTypeDefs(const QCString &tname, const QCString &moduleName,
                               ClassDef *&cd, const UseMap &useMap)
{
  if (tname.isEmpty()) return FALSE; /* empty name => nothing to link */

  //cout << "=== search for type: " << tname << endl;

  // search for type
  if ((cd=Doxygen::classLinkedMap->find(tname)))
  {
    //cout << "=== type found in global module" << endl;
    return TRUE;
  }
  else if (!moduleName.isEmpty() && (cd= Doxygen::classLinkedMap->find(moduleName+"::"+tname)))
  {
    //cout << "=== type found in local module" << endl;
    return TRUE;
  }
  else
  {
    for (const auto &kv : useMap)
    {
      if ((cd= Doxygen::classLinkedMap->find(kv.second.module+"::"+tname)))
      {
        //cout << "===  type found in used module" << endl;
        return TRUE;
      }
    }
  }

  return FALSE;
}

/**
  searches for definition of function memberName
  @param yyscanner the scanner data to be used
  @param memberName the name of the function/variable
  @param moduleName name of enclosing module or null, if global entry
  @param useMap map of data of USE-statement
  @returns MemberDef pointer, if found, or nullptr otherwise
*/
static MemberDef *getFortranDefs(yyscan_t yyscanner,const QCString &memberName, const QCString &moduleName,
                                 const UseMap &useMap)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (memberName.isEmpty()) return nullptr; /* empty name => nothing to link */

  // look in local variables
  for (auto it = yyextra->scopeStack.rbegin(); it!=yyextra->scopeStack.rend(); ++it)
  {
    const Scope &scope = *it;
    std::string lowMemName = memberName.lower().str();
    if (scope.localVars   .find(lowMemName)!=std::end(scope.localVars)     &&  // local var
        scope.externalVars.find(lowMemName)==std::end(scope.externalVars))     // and not external
    {
      return nullptr;
    }
  }

  // search for function
  MemberName *mn = Doxygen::functionNameLinkedMap->find(memberName);
  if (!mn)
  {
    mn = Doxygen::memberNameLinkedMap->find(memberName);
  }

  if (mn) // name is known
  {
    // all found functions with given name
    for (const auto &md : *mn)
    {
      const FileDef  *fd=md->getFileDef();
      const GroupDef *gd=md->getGroupDef();
      const ClassDef *cd=md->getClassDef();

      //cout << "found link with same name: " << fd->fileName() << "  " <<  memberName;
      //if (md->getNamespaceDef() != 0) cout << " in namespace " << md->getNamespaceDef()->name();cout << endl;

      if ((gd && gd->isLinkable()) || (fd && fd->isLinkable()))
      {
        const NamespaceDef *nspace= md->getNamespaceDef();

        if (nspace == 0)
        { // found function in global scope
          if(cd == 0)
          { // Skip if bound to type
            return md.get();
          }
        }
        else if (moduleName == nspace->name())
        { // found in local scope
          return md.get();
        }
        else
        { // else search in used modules
          QCString usedModuleName= nspace->name();
          auto use_it = useMap.find(usedModuleName.str());
          if (use_it!=useMap.end())
          {
            const UseEntry &ue = use_it->second;
            // check if only-list exists and if current entry exists is this list
            if (ue.onlyNames.empty())
            {
              //cout << " found in module " << usedModuleName << " entry " << memberName <<  endl;
              return md.get(); // whole module used
            }
            else
            {
              for ( const auto &name : ue.onlyNames)
              {
                //cout << " search in only: " << usedModuleName << ":: " << memberName << "==" << (*it)<<  endl;
                if (memberName == name)
                {
                  return md.get(); // found in ONLY-part of use list
                }
              }
            }
          }
        }
      } // if linkable
    } // for
  }
  return nullptr;
}

/**
 gets the link to a generic procedure which depends not on the name, but on the parameter list
 @todo implementation
*/
static bool getGenericProcedureLink(yyscan_t yyscanner,const ClassDef *cd,
                                    const QCString &memberText,
                                    CodeOutputInterface &ol)
{
  (void)cd;
  (void)memberText;
  (void)ol;
  return FALSE;
}

static bool getLink(yyscan_t yyscanner,const UseMap &useMap, // dictionary with used modules
                    const QCString &memberText,  // exact member text
                    CodeOutputInterface &ol,
                    const QCString &text)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  MemberDef *md=0;
  QCString memberName= removeRedundantWhiteSpace(memberText);

  if ((md=getFortranDefs(yyscanner,memberName, yyextra->currentModule, useMap)) && md->isLinkable())
  {
    if (md->isVariable() && (md->getLanguage()!=SrcLangExt_Fortran)) return FALSE; // Non Fortran variables aren't handled yet,
                                                                                   // see also linkifyText in util.cpp

    const Definition *d = md->getOuterScope()==Doxygen::globalScope ?
                          md->getBodyDef() : md->getOuterScope();
    if (md->getGroupDef()) d = md->getGroupDef();
    if (d && d->isLinkable())
    {
      if (yyextra->currentDefinition && yyextra->currentMemberDef &&
          md!=yyextra->currentMemberDef && yyextra->insideBody && yyextra->collectXRefs)
      {
        std::lock_guard<std::mutex> lock(g_docCrossReferenceMutex);
        addDocCrossReference(toMemberDefMutable(yyextra->currentMemberDef),toMemberDefMutable(md));
      }
      writeMultiLineCodeLink(yyscanner,ol,md,!text.isEmpty() ? text : memberText);
      addToSearchIndex(yyscanner, !text.isEmpty() ? text : memberText);
      return TRUE;
    }
  }
  return FALSE;
}


static void generateLink(yyscan_t yyscanner,CodeOutputInterface &ol, const QCString &lname)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  ClassDef *cd=0;
  NamespaceDef *nsd=0;
  QCString name = lname;
  name = removeRedundantWhiteSpace(name.lower());

  // check if lowercase lname is a linkable type or interface
  if ( (getFortranTypeDefs(name, yyextra->currentModule, cd, yyextra->useMembers)) && cd->isLinkable() )
  {
    if ( (cd->compoundType() == ClassDef::Class) && // was  Entry::INTERFACE_SEC) &&
         (getGenericProcedureLink(yyscanner, cd, name, ol)) )
    {
      //cout << "=== generic procedure resolved" << endl;
    }
    else
    { // write type or interface link
      writeMultiLineCodeLink(yyscanner, ol,cd,name);
      addToSearchIndex(yyscanner, name);
    }
  }
  // check for module
  else if ( (getFortranNamespaceDefs(name, nsd)) && nsd->isLinkable() )
  { // write module link
    writeMultiLineCodeLink(yyscanner,ol,nsd,name);
    addToSearchIndex(yyscanner,name);
  }
  // check for function/variable
  else if (getLink(yyscanner,yyextra->useMembers, name, ol, name))
  {
    //cout << "=== found link for lowercase " << lname << endl;
  }
  else
  {
    // nothing found, just write out the word
    //startFontClass("charliteral"); //test
    codifyLines(yyscanner,name);
    //endFontClass(yyscanner); //test
    addToSearchIndex(yyscanner,name);
  }
}

static void generateLink(yyscan_t yyscanner,CodeOutputInterface &ol, const char *lname)
{
  generateLink(yyscanner,ol,QCString(lname));
}

/*! counts the number of lines in the input */
static int countLines(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  const char *p=yyextra->inputString;
  char c;
  int count=1;
  while ((c=*p))
  {
    p++ ;
    if (c=='\n') count++;
  }
  if (p>yyextra->inputString && *(p-1)!='\n')
  { // last line does not end with a \n, so we add an extra
    // line and explicitly terminate the line after parsing.
    count++,
    yyextra->needsTermination=TRUE;
  }
  return count;
}

//----------------------------------------------------------------------------
/** start scope */
static void startScope(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  DBG_CTX((stderr, "===> startScope %s",yytext));
  yyextra->scopeStack.push_back(Scope());
}

/** end scope */
static void endScope(yyscan_t yyscanner)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  DBG_CTX((stderr,"===> endScope %s",yytext));
  if (yyextra->scopeStack.empty())
  {
    DBG_CTX((stderr,"WARNING: fortrancode.l: stack empty!\n"));
    return;
  }

  Scope &scope = yyextra->scopeStack.back();
  for ( const auto &name : scope.useNames)
  {
    yyextra->useMembers.erase(name.str());
  }
  yyextra->scopeStack.pop_back();
}

static void addUse(yyscan_t yyscanner,const QCString &moduleName)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (!yyextra->scopeStack.empty())
    yyextra->scopeStack.back().useNames.push_back(moduleName);
}

static void addLocalVar(yyscan_t yyscanner,const QCString &varName)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  if (!yyextra->scopeStack.empty())
  {
    std::string lowVarName = varName.lower().str();
    yyextra->scopeStack.back().localVars.insert(lowVarName);
    if (yyextra->isExternal) yyextra->scopeStack.back().externalVars.insert(lowVarName);
  }
}

/*===================================================================*/


static void checkContLines(yyscan_t yyscanner,const char *s)
{
  struct yyguts_t *yyg = (struct yyguts_t*)yyscanner;
  int numLines = 0;
  int i = 0;
  const char *p = s;

  numLines = 2; // one for element 0, one in case no \n at end
  while (*p)
  {
    if (*p == '\n') numLines++;
    p++;
  }

  yyextra->hasContLine = (int *) malloc((numLines) * sizeof(int));
  for (i = 0; i < numLines; i++)
    yyextra->hasContLine[i] = 0;
  p = prepassFixedForm(s, yyextra->hasContLine);
  yyextra->hasContLine[0] = 0;
}

void parseFortranCode(CodeOutputInterface &od,const char *,const QCString &s,
                  bool exBlock, const char *exName,FileDef *fd,
                  int startLine,int endLine,bool inlineFragment,
                  const MemberDef *,bool,const Definition *searchCtx,
                  bool collectXRefs, FortranFormat format)
{
  //printf("***parseCode() exBlock=%d exName=%s fd=%p\n",exBlock,exName,fd);

  return;
}

//---------------------------------------------------------

struct FortranCodeParser::Private
{
  yyscan_t yyscanner;
  fortrancodeYY_state state;
  FortranFormat format;
};

FortranCodeParser::FortranCodeParser(FortranFormat format) : p(std::make_unique<Private>())
{
  p->format = format;
  fortrancodeYYlex_init_extra(&p->state,&p->yyscanner);
#ifdef FLEX_DEBUG
  fortrancodeYYset_debug(1,p->yyscanner);
#endif
  resetCodeParserState();
}

FortranCodeParser::~FortranCodeParser()
{
  fortrancodeYYlex_destroy(p->yyscanner);
}

void FortranCodeParser::resetCodeParserState()
{
  struct yyguts_t *yyg = (struct yyguts_t*)p->yyscanner;
  yyextra->currentDefinition = 0;
  yyextra->currentMemberDef = 0;
  yyextra->currentFontClass = 0;
  yyextra->needsTermination = FALSE;
  BEGIN( Start );
}

void FortranCodeParser::parseCode(CodeOutputInterface & codeOutIntf,
                   const QCString & scopeName,
                   const QCString & input,
                   SrcLangExt /*lang*/,
                   bool isExampleBlock,
                   const QCString & exampleName,
                   FileDef * fileDef,
                   int startLine,
                   int endLine,
                   bool inlineFragment,
                   const MemberDef *memberDef,
                   bool showLineNumbers,
                   const Definition *searchCtx,
                   bool collectXRefs
                  )
{
  yyscan_t yyscanner = p->yyscanner;
  struct yyguts_t *yyg = (struct yyguts_t*)p->yyscanner;
  //::parseFortranCode(codeOutIntf,scopeName,input,isExampleBlock,exampleName,
  //                   fileDef,startLine,endLine,inlineFragment,memberDef,
  //                   showLineNumbers,searchCtx,collectXRefs,m_format);
  //  parseFortranCode(CodeOutputInterface &od,const char *,const QCString &s,
  //                bool exBlock, const char *exName,FileDef *fd,
  //                int startLine,int endLine,bool inlineFragment,
  //                const MemberDef *,bool,const Definition *searchCtx,
  //                bool collectXRefs, FortranFormat format)
  if (input.isEmpty()) return;
  printlex(yy_flex_debug, TRUE, __FILE__, fileDef ? qPrint(fileDef->fileName()): NULL);
  yyextra->code = &codeOutIntf;
  yyextra->inputString   = input.data();
  yyextra->inputPosition = 0;
  yyextra->isFixedForm = recognizeFixedForm(input,p->format);
  yyextra->contLineNr = 1;
  yyextra->hasContLine = NULL;
  if (yyextra->isFixedForm)
  {
    checkContLines(yyscanner,yyextra->inputString);
  }
  yyextra->currentFontClass = 0;
  yyextra->needsTermination = FALSE;
  yyextra->searchCtx = searchCtx;
  yyextra->collectXRefs = collectXRefs;
  if (startLine!=-1)
    yyextra->yyLineNr    = startLine;
  else
    yyextra->yyLineNr    = 1;

  if (endLine!=-1)
    yyextra->inputLines  = endLine+1;
  else
    yyextra->inputLines  = yyextra->yyLineNr + countLines(yyscanner) - 1;

  yyextra->exampleBlock  = isExampleBlock;
  yyextra->exampleName   = exampleName;
  yyextra->sourceFileDef = fileDef;
  if (isExampleBlock && fileDef==0)
  {
    // create a dummy filedef for the example
    yyextra->sourceFileDef = createFileDef(QCString(),exampleName);
  }
  if (yyextra->sourceFileDef)
  {
    setCurrentDoc(yyscanner,QCString("l00001"));
  }
  yyextra->currentDefinition = 0;
  yyextra->currentMemberDef = 0;
  if (!yyextra->exampleName.isEmpty())
  {
    yyextra->exampleFile = convertNameToFile(yyextra->exampleName+"-example");
  }
  yyextra->includeCodeFragment = inlineFragment;
  startCodeLine(yyscanner);
  fortrancodeYYrestart(0, yyscanner);
  BEGIN( Start );
  fortrancodeYYlex(yyscanner);
  if (yyextra->needsTermination)
  {
    endFontClass(yyscanner);
    yyextra->code->endCodeLine();
  }
  if (isExampleBlock && yyextra->sourceFileDef)
  {
    // delete the temporary file definition used for this example
    delete yyextra->sourceFileDef;
    yyextra->sourceFileDef=0;
  }
  if (yyextra->hasContLine) free(yyextra->hasContLine);
  yyextra->hasContLine = NULL;

  // write the tooltips
  TooltipManager::instance().writeTooltips(codeOutIntf);

  printlex(yy_flex_debug, FALSE, __FILE__, fileDef ? qPrint(fileDef->fileName()): NULL);
}

//---------------------------------------------------------

#if USE_STATE2STRING
#include "fortrancode.l.h"
#endif