Skip to content

Commit 268ccac

Browse files
committed
even more style fixes
1 parent 147e315 commit 268ccac

File tree

4 files changed

+55
-53
lines changed

4 files changed

+55
-53
lines changed

__init__.py

Whitespace-only changes.

fparse_utils.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1+
"""
2+
This is a collection of Fortran parsing utilities.
3+
"""
14
import re
2-
import string
35
from collections import deque
4-
try:
5-
from cStringIO import StringIO
6-
except ImportError:
7-
from io import StringIO
86

97
USE_PARSE_RE = re.compile(
108
r" *use +(?P<module>[a-zA-Z_][a-zA-Z_0-9]*)(?P<only> *, *only *:)? *(?P<imports>.*)$",
119
flags=re.IGNORECASE)
12-
VAR_DECL_RE = re.compile(r" *(?P<type>integer(?: *\* *[0-9]+)?|logical|character(?: *\* *[0-9]+)?|real(?: *\* *[0-9]+)?|complex(?: *\* *[0-9]+)?|type) *(?P<parameters>\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\))? *(?P<attributes>(?: *, *[a-zA-Z_0-9]+(?: *\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\))?)+)? *(?P<dpnt>::)?(?P<vars>[^\n]+)\n?", re.IGNORECASE) # $
10+
11+
# FIXME bad ass regex!
12+
VAR_DECL_RE = re.compile(r" *(?P<type>integer(?: *\* *[0-9]+)?|logical|character(?: *\* *[0-9]+)?|real(?: *\* *[0-9]+)?|complex(?: *\* *[0-9]+)?|type) *(?P<parameters>\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\))? *(?P<attributes>(?: *, *[a-zA-Z_0-9]+(?: *\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\))?)+)? *(?P<dpnt>::)?(?P<vars>[^\n]+)\n?", re.IGNORECASE)
1313

1414
OMP_DIR_RE = re.compile(r"^\s*(!\$omp)", re.IGNORECASE)
1515
OMP_RE = re.compile(r"^\s*(!\$)", re.IGNORECASE)
@@ -75,16 +75,16 @@ def __init__(self, infile):
7575
self.infile = infile
7676
self.line_nr = 0
7777

78-
def nextFortranLine(self):
78+
def next_fortran_line(self):
7979
"""Reads a group of connected lines (connected with &, separated by newline or semicolon)
8080
returns a touple with the joined line, and a list with the original lines.
8181
Doesn't support multiline character constants!
8282
"""
83-
lineRe = re.compile(
84-
# $
83+
# FIXME regex
84+
line_re = re.compile(
8585
r"(?:(?P<preprocessor>#.*\n?)| *(&)?(?P<core>(?:!\$|[^&!\"']+|\"[^\"]*\"|'[^']*')*)(?P<continue>&)? *(?P<comment>!.*)?\n?)",
8686
re.IGNORECASE)
87-
joinedLine = ""
87+
joined_line = ""
8888
comments = []
8989
lines = []
9090
continuation = 0
@@ -109,7 +109,7 @@ def nextFortranLine(self):
109109
omp_indent = 0
110110
is_omp_conditional = False
111111
line_start = pos + 1
112-
if(line_start < len(line)):
112+
if line_start < len(line):
113113
# line + comment
114114
self.line_buffer.append('!$' * is_omp_conditional +
115115
line[line_start:])
@@ -121,35 +121,35 @@ def nextFortranLine(self):
121121
break
122122

123123
lines.append(line)
124-
m = lineRe.match(line)
125-
if not m or m.span()[1] != len(line):
124+
match = line_re.match(line)
125+
if not match or match.span()[1] != len(line):
126126
# FIXME: does not handle line continuation of
127127
# omp conditional fortran statements
128128
# starting with an ampersand.
129129
raise SyntaxError("unexpected line format:" + repr(line))
130-
if m.group("preprocessor"):
130+
if match.group("preprocessor"):
131131
if len(lines) > 1:
132132
raise SyntaxError(
133133
"continuation to a preprocessor line not supported " + repr(line))
134134
comments.append(line)
135135
break
136-
coreAtt = m.group("core")
137-
if OMP_RE.match(coreAtt) and joinedLine.strip():
136+
core_att = match.group("core")
137+
if OMP_RE.match(core_att) and joined_line.strip():
138138
# remove omp '!$' for line continuation
139-
coreAtt = OMP_RE.sub('', coreAtt, count=1).lstrip()
140-
joinedLine = joinedLine.rstrip("\n") + coreAtt
141-
if coreAtt and not coreAtt.isspace():
139+
core_att = OMP_RE.sub('', core_att, count=1).lstrip()
140+
joined_line = joined_line.rstrip("\n") + core_att
141+
if core_att and not core_att.isspace():
142142
continuation = 0
143-
if m.group("continue"):
143+
if match.group("continue"):
144144
continuation = 1
145145
if line.lstrip().startswith('!') and not OMP_RE.search(line):
146146
comments.append(line.rstrip('\n'))
147-
elif m.group("comment"):
148-
comments.append(m.group("comment"))
147+
elif match.group("comment"):
148+
comments.append(match.group("comment"))
149149
else:
150150
comments.append('')
151151
if not continuation:
152152
break
153-
return (joinedLine, comments, lines)
153+
return (joined_line, comments, lines)
154154

155155

fprettify.py

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,12 @@
4242
import sys
4343
import os
4444
import tempfile
45+
import logging
4546
from fparse_utils import (USE_PARSE_RE, VAR_DECL_RE, InputStream,
4647
CharFilter, OMP_RE, OMP_DIR_RE)
47-
import logging
4848

4949

5050
# PY2/PY3 compat wrappers:
51-
5251
try:
5352
any
5453
except NameError:
@@ -162,6 +161,7 @@ def any(iterable):
162161

163162
class FortranSyntaxError(Exception):
164163
"""Exception for unparseable Fortran code"""
164+
165165
def __init__(self, filename, line_nr,
166166
msg=("Syntax error - "
167167
"this formatter can not handle invalid Fortran files.")):
@@ -450,7 +450,7 @@ def inspect_ffile_format(infile, indent_size):
450450
prev_offset = 0
451451
first_indent = -1
452452
while 1:
453-
f_line, _, lines = stream.nextFortranLine()
453+
f_line, _, lines = stream.next_fortran_line()
454454
if not lines:
455455
break
456456

@@ -515,7 +515,7 @@ def format_single_fline(f_line, whitespace, linebreak_pos, ampersand_sep,
515515
line_ftd = line_ftd + char
516516
else:
517517
if (line_ftd and line_ftd[-1] == ' ' and
518-
(not re.search(r'[\w"]', char) and not is_decl)):
518+
(not re.search(r'[\w"]', char) and not is_decl)):
519519
line_ftd = line_ftd[:-1] # remove spaces except between words
520520
line_ftd = line_ftd + line[pos_prev + 1:pos + 1]
521521
pos_prev = pos
@@ -710,6 +710,9 @@ def format_single_fline(f_line, whitespace, linebreak_pos, ampersand_sep,
710710

711711

712712
def reformat_inplace(filename, stdout=False, **kwargs):
713+
"""
714+
reformat a file in place.
715+
"""
713716
if filename == 'stdin':
714717
infile = tempfile.TemporaryFile(mode='r+')
715718
infile.write(sys.stdin.read())
@@ -765,7 +768,7 @@ def reformat_ffile(infile, outfile, indent_size=3, whitespace=2,
765768
in_manual_block = False
766769

767770
while 1:
768-
f_line, comments, lines = stream.nextFortranLine()
771+
f_line, comments, lines = stream.next_fortran_line()
769772
if not lines:
770773
break
771774

@@ -861,9 +864,9 @@ def reformat_ffile(infile, outfile, indent_size=3, whitespace=2,
861864
pre_ampersand = []
862865
ampersand_sep = []
863866
for pos, line in enumerate(lines):
864-
m = re.search(SOL_STR + r'(&\s*)', line)
865-
if m:
866-
pre_ampersand.append(m.group(1))
867+
match = re.search(SOL_STR + r'(&\s*)', line)
868+
if match:
869+
pre_ampersand.append(match.group(1))
867870
sep = len(re.search(r'(\s*)&[\s]*(?:!.*)?$',
868871
lines[pos - 1]).group(1))
869872
ampersand_sep.append(sep)
@@ -972,11 +975,11 @@ def reformat_ffile(infile, outfile, indent_size=3, whitespace=2,
972975
def main(argv=None):
973976
if argv is None:
974977
argv = sys.argv
975-
defaultsDict = {'indent': 3, 'whitespace': 2,
976-
'stdout': 0, 'report-errors': 1,
977-
'debug': 0}
978+
defaults_dict = {'indent': 3, 'whitespace': 2,
979+
'stdout': 0, 'report-errors': 1,
980+
'debug': 0}
978981

979-
usageDesc = ("usage:\n" + argv[0] + """
982+
usage_desc = ("usage:\n" + argv[0] + """
980983
[--indent=3] [--whitespace=2]
981984
[--[no-]stdout] [--[no-]report-errors] file1 [file2 ...]
982985
[--help]
@@ -1006,22 +1009,22 @@ def main(argv=None):
10061009
report warnings and errors
10071010
10081011
Defaults:
1009-
""" + str(defaultsDict))
1012+
""" + str(defaults_dict))
10101013

10111014
if "--help" in argv:
1012-
sys.stderr.write(usageDesc + '\n')
1015+
sys.stderr.write(usage_desc + '\n')
10131016
return 0
10141017
args = []
10151018
for arg in argv[1:]:
1016-
m = re.match(
1019+
match = re.match(
10171020
r"--(no-)?(stdout|report-errors|debug)", arg)
1018-
if m:
1019-
defaultsDict[m.groups()[1]] = not m.groups()[0]
1021+
if match:
1022+
defaults_dict[match.groups()[1]] = not match.groups()[0]
10201023
else:
1021-
m = re.match(
1024+
match = re.match(
10221025
r"--(indent|whitespace)=(.*)", arg)
1023-
if m:
1024-
defaultsDict[m.groups()[0]] = int(m.groups()[1])
1026+
if match:
1027+
defaults_dict[match.groups()[0]] = int(match.groups()[1])
10251028
else:
10261029
if arg.startswith('--'):
10271030
sys.stderr.write('unknown option ' + arg + '\n')
@@ -1035,10 +1038,10 @@ def main(argv=None):
10351038
if not os.path.isfile(filename) and filename != 'stdin':
10361039
sys.stderr.write("file " + filename + " does not exists!\n")
10371040
else:
1038-
stdout = defaultsDict['stdout'] or filename == 'stdin'
1041+
stdout = defaults_dict['stdout'] or filename == 'stdin'
10391042

1040-
if defaultsDict['report-errors']:
1041-
if defaultsDict['debug']:
1043+
if defaults_dict['report-errors']:
1044+
if defaults_dict['debug']:
10421045
level = logging.DEBUG
10431046
else:
10441047
level = logging.INFO
@@ -1048,17 +1051,17 @@ def main(argv=None):
10481051

10491052
logger = logging.getLogger('prettify-logger')
10501053
logger.setLevel(level)
1051-
sh = logging.StreamHandler()
1052-
sh.setLevel(level)
1054+
stream_handler = logging.StreamHandler()
1055+
stream_handler.setLevel(level)
10531056
formatter = logging.Formatter('%(levelname)s - %(message)s')
1054-
sh.setFormatter(formatter)
1055-
logger.addHandler(sh)
1057+
stream_handler.setFormatter(formatter)
1058+
logger.addHandler(stream_handler)
10561059

10571060
try:
10581061
reformat_inplace(filename,
10591062
stdout=stdout,
1060-
indent_size=defaultsDict['indent'],
1061-
whitespace=defaultsDict['whitespace'])
1063+
indent_size=defaults_dict['indent'],
1064+
whitespace=defaults_dict['whitespace'])
10621065
except:
10631066
failure += 1
10641067
import traceback

tests.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
import sys
32
import unittest
43

0 commit comments

Comments
 (0)