New URL for NEMO forge!   http://forge.nemo-ocean.eu

Since March 2022 along with NEMO 4.2 release, the code development moved to a self-hosted GitLab.
This present forge is now archived and remained online for history.
fortran.py in utils/developer – NEMO

source: utils/developer/fortran.py @ 11767

Last change on this file since 11767 was 11767, checked in by nicolasmartin, 4 years ago

Modify lexer to recognize all logical operators
Move punctuation rule at the end of 'core' token to make operator rule working on .and., .not. & .or.

File size: 9.6 KB
RevLine 
[11765]1# -*- coding: utf-8 -*-
2"""
3    pygments.lexers.fortran
4    ~~~~~~~~~~~~~~~~~~~~~~~
5
6    Lexers for Fortran languages.
7
8    :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
9    :license: BSD, see LICENSE for details.
10"""
11
12import re
13
14from pygments.lexer import RegexLexer, bygroups, include, words, using, default
15from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
16    Number, Punctuation, Generic
17
18__all__ = ['FortranLexer', 'FortranFixedLexer']
19
20
21class FortranLexer(RegexLexer):
22    """
23    Lexer for FORTRAN 90 code.
24
25    .. versionadded:: 0.10
26    """
27    name = 'Fortran'
28    aliases = ['fortran']
29    filenames = ['*.f03', '*.f90', '*.F03', '*.F90']
30    mimetypes = ['text/x-fortran']
31    flags = re.IGNORECASE | re.MULTILINE
32
33    # Data Types: INTEGER, REAL, COMPLEX, LOGICAL, CHARACTER and DOUBLE PRECISION
34    # Operators: **, *, +, -, /, <, >, <=, >=, ==, /=
35    # Logical (?): NOT, AND, OR, EQV, NEQV
36
37    # Builtins:
38    # http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Table-of-Intrinsic-Functions.html
39
40    tokens = {
41        'root': [
42            (r'^#.*\n', Comment.Preproc),
43            (r'!.*\n', Comment),
44            include('strings'),
45            include('core'),
46            (r'[a-z][\w$]*', Name),
47            include('nums'),
48            (r'[\s]+', Text),
49        ],
50        'core': [
51            # Statements
52            (words((
53                'ABSTRACT', 'ACCEPT', 'ALL', 'ALLSTOP', 'ALLOCATABLE', 'ALLOCATE',
54                'ARRAY', 'ASSIGN', 'ASSOCIATE', 'ASYNCHRONOUS', 'BACKSPACE', 'BIND',
55                'BLOCK', 'BLOCKDATA', 'BYTE', 'CALL', 'CASE', 'CLASS', 'CLOSE',
56                'CODIMENSION', 'COMMON', 'CONCURRRENT', 'CONTIGUOUS', 'CONTAINS',
57                'CONTINUE', 'CRITICAL', 'CYCLE', 'DATA', 'DEALLOCATE', 'DECODE',
[11766]58                'DEFERRED', 'DIMENSION', 'DO', 'ELEMENTAL', 'ELSE', 'ENCODE', 'END', 'ENDIF',
[11765]59                'ENTRY', 'ENUM', 'ENUMERATOR', 'EQUIVALENCE', 'EXIT', 'EXTENDS',
60                'EXTERNAL', 'EXTRINSIC', 'FILE', 'FINAL', 'FORALL', 'FORMAT',
61                'FUNCTION', 'GENERIC', 'GOTO', 'IF', 'IMAGES', 'IMPLICIT',
62                'IMPORT', 'IMPURE', 'INCLUDE', 'INQUIRE', 'INTENT', 'INTERFACE',
63                'INTRINSIC', 'IS', 'LOCK', 'MEMORY', 'MODULE', 'NAMELIST', 'NULLIFY',
64                'NONE', 'NON_INTRINSIC', 'NON_OVERRIDABLE', 'NOPASS', 'OPEN', 'OPTIONAL',
65                'OPTIONS', 'PARAMETER', 'PASS', 'PAUSE', 'POINTER', 'PRINT', 'PRIVATE',
66                'PROGRAM', 'PROCEDURE', 'PROTECTED', 'PUBLIC', 'PURE', 'READ',
67                'RECURSIVE', 'RESULT', 'RETURN', 'REWIND', 'SAVE', 'SELECT', 'SEQUENCE',
68                'STOP', 'SUBMODULE', 'SUBROUTINE', 'SYNC', 'SYNCALL', 'SYNCIMAGES',
69                'SYNCMEMORY', 'TARGET', 'THEN', 'TYPE', 'UNLOCK', 'USE', 'VALUE',
70                'VOLATILE', 'WHERE', 'WRITE', 'WHILE'), prefix=r'\b', suffix=r'\s*\b'),
71             Keyword),
72
73            # Data Types
74            (words((
75                'CHARACTER', 'COMPLEX', 'DOUBLE PRECISION', 'DOUBLE COMPLEX', 'INTEGER',
76                'LOGICAL', 'REAL', 'C_INT', 'C_SHORT', 'C_LONG', 'C_LONG_LONG',
77                'C_SIGNED_CHAR', 'C_SIZE_T', 'C_INT8_T', 'C_INT16_T', 'C_INT32_T',
78                'C_INT64_T', 'C_INT_LEAST8_T', 'C_INT_LEAST16_T', 'C_INT_LEAST32_T',
79                'C_INT_LEAST64_T', 'C_INT_FAST8_T', 'C_INT_FAST16_T', 'C_INT_FAST32_T',
80                'C_INT_FAST64_T', 'C_INTMAX_T', 'C_INTPTR_T', 'C_FLOAT', 'C_DOUBLE',
81                'C_LONG_DOUBLE', 'C_FLOAT_COMPLEX', 'C_DOUBLE_COMPLEX',
82                'C_LONG_DOUBLE_COMPLEX', 'C_BOOL', 'C_CHAR', 'C_PTR', 'C_FUNPTR'),
83                   prefix=r'\b', suffix=r'\s*\b'),
84             Keyword.Type),
85
86            # Operators
87            (r'(\*\*|\*|\+|-|\/|<|>|<=|>=|==|\/=|=)', Operator),
88
89            (r'(::)', Keyword.Declaration),
90
91            # Intrinsics
92            (words((
93                'Abort', 'Abs', 'Access', 'AChar', 'ACos', 'ACosH', 'AdjustL',
94                'AdjustR', 'AImag', 'AInt', 'Alarm', 'All', 'Allocated', 'ALog',
[11766]95                'AMax', 'AMin', 'AMod', 'ANInt', 'Any', 'ASin', 'ASinH',
[11765]96                'Associated', 'ATan', 'ATanH', 'Atomic_Define', 'Atomic_Ref',
97                'BesJ', 'BesJN', 'Bessel_J0', 'Bessel_J1', 'Bessel_JN', 'Bessel_Y0',
98                'Bessel_Y1', 'Bessel_YN', 'BesY', 'BesYN', 'BGE', 'BGT', 'BLE',
99                'BLT', 'Bit_Size', 'BTest', 'CAbs', 'CCos', 'Ceiling', 'CExp',
100                'Char', 'ChDir', 'ChMod', 'CLog', 'Cmplx', 'Command_Argument_Count',
101                'Complex', 'Conjg', 'Cos', 'CosH', 'Count', 'CPU_Time', 'CShift',
102                'CSin', 'CSqRt', 'CTime', 'C_Loc', 'C_Associated',
103                'C_Null_Ptr', 'C_Null_Funptr', 'C_F_Pointer', 'C_F_ProcPointer',
104                'C_Null_Char', 'C_Alert', 'C_Backspace', 'C_Form_Feed', 'C_FunLoc',
105                'C_Sizeof', 'C_New_Line', 'C_Carriage_Return',
106                'C_Horizontal_Tab', 'C_Vertical_Tab', 'DAbs', 'DACos', 'DASin',
107                'DATan', 'Date_and_Time', 'DbesJ', 'DbesJN', 'DbesY',
108                'DbesYN', 'Dble', 'DCos', 'DCosH', 'DDiM', 'DErF',
109                'DErFC', 'DExp', 'Digits', 'DiM', 'DInt', 'DLog', 'DMax',
110                'DMin', 'DMod', 'DNInt', 'Dot_Product', 'DProd', 'DSign', 'DSinH',
111                'DShiftL', 'DShiftR', 'DSin', 'DSqRt', 'DTanH', 'DTan', 'DTime',
112                'EOShift', 'Epsilon', 'ErF', 'ErFC', 'ErFC_Scaled', 'ETime',
113                'Execute_Command_Line', 'Exit', 'Exp', 'Exponent', 'Extends_Type_Of',
114                'FDate', 'FGet', 'FGetC', 'FindLoc', 'Float', 'Floor', 'Flush',
115                'FNum', 'FPutC', 'FPut', 'Fraction', 'FSeek', 'FStat', 'FTell',
116                'Gamma', 'GError', 'GetArg', 'Get_Command', 'Get_Command_Argument',
117                'Get_Environment_Variable', 'GetCWD', 'GetEnv', 'GetGId', 'GetLog',
118                'GetPId', 'GetUId', 'GMTime', 'HostNm', 'Huge', 'Hypot', 'IAbs',
119                'IAChar', 'IAll', 'IAnd', 'IAny', 'IArgC', 'IBClr', 'IBits',
120                'IBSet', 'IChar', 'IDate', 'IDiM', 'IDInt', 'IDNInt', 'IEOr',
121                'IErrNo', 'IFix', 'Imag', 'ImagPart', 'Image_Index', 'Index',
122                'Int', 'IOr', 'IParity', 'IRand', 'IsaTty', 'IShft', 'IShftC',
123                'ISign', 'Iso_C_Binding', 'Is_Contiguous', 'Is_Iostat_End',
124                'Is_Iostat_Eor', 'ITime', 'Kill', 'Kind', 'LBound', 'LCoBound',
125                'Len', 'Len_Trim', 'LGe', 'LGt', 'Link', 'LLe', 'LLt', 'LnBlnk',
126                'Loc', 'Log', 'Log_Gamma', 'Logical', 'Long', 'LShift', 'LStat',
127                'LTime', 'MaskL', 'MaskR', 'MatMul', 'Max', 'MaxExponent',
128                'MaxLoc', 'MaxVal', 'MClock', 'Merge', 'Merge_Bits', 'Move_Alloc',
129                'Min', 'MinExponent', 'MinLoc', 'MinVal', 'Mod', 'Modulo', 'MvBits',
[11766]130                'Nearest', 'New_Line', 'NInt', 'Norm2', 'Null', 'Num_Images',
131                'Pack', 'Parity', 'PError', 'Precision', 'Present', 'Product',
[11765]132                'Radix', 'Rand', 'Random_Number', 'Random_Seed', 'Range', 'Real',
133                'RealPart', 'Rename', 'Repeat', 'Reshape', 'RRSpacing', 'RShift',
134                'Same_Type_As', 'Scale', 'Scan', 'Second', 'Selected_Char_Kind',
135                'Selected_Int_Kind', 'Selected_Real_Kind', 'Set_Exponent', 'Shape',
136                'ShiftA', 'ShiftL', 'ShiftR', 'Short', 'Sign', 'Signal', 'SinH',
137                'Sin', 'Sleep', 'Sngl', 'Spacing', 'Spread', 'SqRt', 'SRand',
138                'Stat', 'Storage_Size', 'Sum', 'SymLnk', 'System', 'System_Clock',
139                'Tan', 'TanH', 'Time', 'This_Image', 'Tiny', 'TrailZ', 'Transfer',
140                'Transpose', 'Trim', 'TtyNam', 'UBound', 'UCoBound', 'UMask',
141                'Unlink', 'Unpack', 'Verify', 'XOr', 'ZAbs', 'ZCos', 'ZExp',
142                'ZLog', 'ZSin', 'ZSqRt'), prefix=r'\b', suffix=r'\s*\b'),
143             Name.Builtin),
144
145            # Booleans
146            (r'\.(true|false)\.', Name.Builtin),
147            # Comparing Operators
148            (r'\.(eq|ne|lt|le|gt|ge|not|and|or|eqv|neqv)\.', Operator.Word),
[11767]149
150            # Punctuation
151            (r'[()\[\],:&%;.]', Punctuation),
[11765]152        ],
153        'strings': [
154            (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
155            (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
156        ],
157
158        'nums': [
159            (r'\d+(?![.e])(_[a-z]\w+)?', Number.Integer),
160            (r'[+-]?\d*\.\d+([ed][-+]?\d+)?(_[a-z]\w+)?', Number.Float),
161            (r'[+-]?\d+\.\d*([ed][-+]?\d+)?(_[a-z]\w+)?', Number.Float),
162            (r'[+-]?\d+(\.\d*)?[ed][-+]?\d+(_[a-z]\w+)?', Number.Float),
163        ],
164    }
165
166
167class FortranFixedLexer(RegexLexer):
168    """
169    Lexer for fixed format Fortran.
170
171    .. versionadded:: 2.1
172    """
173    name = 'FortranFixed'
174    aliases = ['fortranfixed']
175    filenames = ['*.f', '*.F']
176
177    flags = re.IGNORECASE
178
179    def _lex_fortran(self, match, ctx=None):
180        """Lex a line just as free form fortran without line break."""
181        lexer = FortranLexer()
182        text = match.group(0) + "\n"
183        for index, token, value in lexer.get_tokens_unprocessed(text):
184            value = value.replace('\n', '')
185            if value != '':
186                yield index, token, value
187
188    tokens = {
189        'root': [
190            (r'[C*].*\n', Comment),
191            (r'#.*\n', Comment.Preproc),
192            (r' {0,4}!.*\n', Comment),
193            (r'(.{5})', Name.Label, 'cont-char'),
194            (r'.*\n', using(FortranLexer)),
195        ],
196        'cont-char': [
197            (' ', Text, 'code'),
198            ('0', Comment, 'code'),
199            ('.', Generic.Strong, 'code'),
200        ],
201        'code': [
202            (r'(.{66})(.*)(\n)',
203             bygroups(_lex_fortran, Comment, Text), 'root'),
204            (r'(.*)(\n)', bygroups(_lex_fortran, Text), 'root'),
205            default('root'),
206        ]
207    }
Note: See TracBrowser for help on using the repository browser.