diff --git a/capgen/ccpp_validator.py b/capgen/ccpp_validator.py index f5799679..57c446eb 100755 --- a/capgen/ccpp_validator.py +++ b/capgen/ccpp_validator.py @@ -71,15 +71,17 @@ if _PACKAGE_DIR not in sys.path: sys.path.insert(0, _PACKAGE_DIR) -from metadata.parse_tools import CCPPError, init_log, set_log_level +from metadata.parse_tools import ( + CCPPError, + FREE_FORM_MAX_COLUMNS, + init_log, + set_log_level, +) from metadata.variable_resolver import SchemeStore from metadata.metadata_table import parse_metadata_file _LOGGER = init_log('ccpp_validator') -# Line-length limit (NCAR/ccpp-framework#788) -FREE_FORM_MAX_COLUMNS = 132 - # Severity of a line-length limit violation. Scheme source is CCPP's own # code, so an over-long line is an error. Host source belongs to the host # model, so it warns for now. diff --git a/capgen/generator/fortran_lines.py b/capgen/generator/fortran_lines.py new file mode 100644 index 00000000..536e048d --- /dev/null +++ b/capgen/generator/fortran_lines.py @@ -0,0 +1,560 @@ +"""Line-length wrapping for generated Fortran. + +Free-form Fortran ends at column 132 (``FREE_FORM_MAX_COLUMNS``) and capgen +holds the Fortran it *reads* to that limit (``doc/followups.md`` FU-038). It +has to hold the Fortran it *writes* to a limit too, and until this module +existed it did not: the generated caps carried 58 over-long lines and the +end-to-end harness compiled them only because it passed gfortran's +``-ffree-line-length-none`` -- the very ambiguity the input rule removes. + +The limit used here is the stricter :data:`GENERATED_MAX_COLUMNS`, 120, which +is the ``ColumnLimit`` in this repository's ``.codee-format``. Nothing else +of that format is implemented: matching it in full is a separate project and +waits on a revisit of the Codee style for ccpp-framework (FU-005). Wrapping +to its column limit now simply keeps the caps from being the thing such a +pass would have to reflow. + +Every cap writer goes through :func:`write_fortran` rather than calling +``open_if_changed`` itself. :func:`wrap_fortran_lines` is a pure pass over +the finished line list, so a line already within the limit is emitted +unchanged and wrapping shows up in generated output only where a line would +have overrun. + +Four ways to break a line, tried in this order: + +1. A logical ``if () `` breaks after the condition -- the one + structural break the statement has. Tried first so the action's commas + are not packed onto the condition's line. +2. ``use , only: `` breaks after ``only:``, one symbol per + continuation line. This is the form ``host_cap`` already emits for its + own long import lists, and the one ``.codee-format`` asks for. +3. Any other statement breaks after the commas that lie outside a character + literal, packing as many items per line as fit. A comma break is legal + at any parenthesis depth, so one over-long actual argument wraps the + same way a long argument list does. +4. A piece with no comma to break on but with a character literal across + the limit -- a generated ``errmsg`` is the case that matters -- continues + the literal itself: the line ends with ``&`` and the next resumes with + ``&`` immediately before the rest of the text. Blanks *before* that + leading ``&`` are not part of the literal, so the message is unchanged. + +A trailing comment moves onto its own line above the statement: ``&`` inside +a comment is just another comment character, so a comment cannot be +continued. + +A line none of that can break is a generator bug rather than something to +emit and hope about, so :func:`wrap_fortran_lines` raises ``CCPPError`` +naming the file and what it could not break. +""" + +import logging +import re +from typing import List, Optional, Sequence, Tuple + +from metadata.parse_tools import CCPPError, open_if_changed + +# What capgen wraps its *own* output to. Free-form Fortran ends at 132 +# (``FREE_FORM_MAX_COLUMNS``, which is what the validator checks on input), +# but `.codee-format` sets ``ColumnLimit: 120`` for this repository, so +# generated code is held to the stricter of the two: a cap that is already +# inside 120 columns cannot be the thing a Codee pass has to reflow. The +# rest of that format is a separate project -- see ``doc/followups.md`` +# FU-005. +GENERATED_MAX_COLUMNS = 120 + +# Continuation indent, in spaces added to the statement's own indent. An +# import list lines up two in, matching the host cap's existing long-import +# form; everything else lines up four in, matching the generated call sites. +_USE_CONT_INDENT = 2 +_CODE_CONT_INDENT = 4 + +# ``, only:`` with any spacing. Resolved with the *last* match in the +# statement so ``use, intrinsic :: , only: ...`` splits at the import +# list and not at the ``intrinsic`` attribute. +_ONLY_RE = re.compile(r',[ \t]*only[ \t]*:[ \t]*', re.IGNORECASE) +_USE_RE = re.compile(r'[ \t]*use\b', re.IGNORECASE) + +# The opening parenthesis of a logical ``if () ``. +_IF_RE = re.compile(r'[ \t]*if[ \t]*\(', re.IGNORECASE) + + +def wrap_fortran_lines( + lines: Sequence[str], + path: Optional[str] = None, + limit: int = GENERATED_MAX_COLUMNS, +) -> List[str]: + """Return *lines* with every over-long line broken into continuations. + + Parameters + ---------- + lines : sequence of str + Generated Fortran source lines, without trailing newlines. + path : str, optional + Output path, used only to name the file in an error message. + limit : int + Column limit; defaults to :data:`GENERATED_MAX_COLUMNS`. + + Returns + ------- + list of str + The same lines, with any line past *limit* replaced by the + continuation block that carries the same statement. + + Raises + ------ + CCPPError + If a line is past *limit* and holds no comma and no character + literal to break at. + + Examples + -------- + A line within the limit is returned untouched: + + >>> wrap_fortran_lines([' x = 1']) + [' x = 1'] + + An import list breaks after ``only:``, one symbol per line: + + >>> for line in wrap_fortran_lines( + ... [' use m, only: alpha, beta, gamma'], limit=30 + ... ): + ... print(repr(line)) + ' use m, only: &' + ' alpha, &' + ' beta, &' + ' gamma' + + Anything else packs as many comma-separated items per line as fit: + + >>> for line in wrap_fortran_lines( + ... [' call sub(alpha, beta, gamma, delta)'], limit=30 + ... ): + ... print(repr(line)) + ' call sub(alpha, beta, &' + ' gamma, delta)' + """ + out: List[str] = [] + for line in lines: + if len(line) <= limit: + out.append(line) + else: + out.extend(_wrap_one(line, limit, path)) + return out + + +def write_fortran( + out_path: str, + lines: Sequence[str], + logger: Optional[logging.Logger] = None, +) -> str: + """Wrap *lines* to the free-form limit and write them to *out_path*. + + The write itself is :func:`~metadata.parse_tools.open_if_changed`, so an + unchanged file keeps its mtime. + + Parameters + ---------- + out_path : str + Path of the generated Fortran file. + lines : sequence of str + Source lines, without trailing newlines. + logger : logging.Logger, optional + Passed through to the write helper. + + Returns + ------- + str + *out_path*, for the caller to return on. + """ + wrapped = wrap_fortran_lines(lines, path=out_path) + with open_if_changed(out_path, logger=logger) as fh: + fh.write('\n'.join(wrapped) + '\n') + return out_path + + +######################################################################## +# Internals +######################################################################## + + +def _wrap_one(line: str, limit: int, path: Optional[str]) -> List[str]: + """Return the continuation block for one over-long *line*.""" + indent = line[:len(line) - len(line.lstrip())] + code, comment = _split_comment(line) + code = code.rstrip() + # A statement that was already a continuation keeps its ``&``: strip it + # for the wrapping and put it back on the final line. + trailing_amp = code.endswith('&') + if trailing_amp: + code = code[:-1].rstrip() + + out: List[str] = [] + if comment: + out.extend(_wrap_comment(indent, comment, limit)) + if not code: + return out + out.extend(_wrap_code(indent, code, limit, trailing_amp, path)) + return out + + +def _split_comment(line: str) -> Tuple[str, str]: + """Split *line* at the first ``!`` outside a character literal. + + Returns ``(code, comment)``; *comment* keeps its ``!`` and is empty + when the line carries no comment. + + Examples + -------- + >>> _split_comment(" x = 1 ! why") + (' x = 1 ', '! why') + >>> _split_comment(" msg = 'not ! a comment'") + (" msg = 'not ! a comment'", '') + """ + quote = None + idx = 0 + while idx < len(line): + char = line[idx] + if quote is not None: + if char == quote: + if line[idx + 1:idx + 2] == quote: + idx += 2 # doubled delimiter inside the literal + continue + quote = None + elif char in ("'", '"'): + quote = char + elif char == '!': + return line[:idx], line[idx:] + idx += 1 + return line, '' + + +def _wrap_comment(indent: str, comment: str, limit: int) -> List[str]: + """Return *comment* as one or more full-line comments at *indent*.""" + words = comment.lstrip('!').split() + lines: List[str] = [] + current = '' + for word in words: + candidate = '{} {}'.format(current, word) if current else word + if current and len(indent) + 2 + len(candidate) > limit: + lines.append('{}! {}'.format(indent, current)) + current = word + else: + current = candidate + lines.append('{}! {}'.format(indent, current) if current + else '{}!'.format(indent)) + return lines + + +def _wrap_code( + indent: str, + code: str, + limit: int, + trailing_amp: bool, + path: Optional[str], +) -> List[str]: + """Return the finished continuation lines for one statement.""" + # A logical ``if`` breaks after its condition, which is the one + # structural break such a statement has. Tried first, because the + # action half often carries commas that would otherwise be packed into + # the condition's line. Skipped when the condition alone is the part + # that does not fit, so the comma path can break inside it. + logical_if = _logical_if_split(code) + if logical_if is not None and len(logical_if[0]) + 2 <= limit: + condition, action = logical_if + cont = indent + ' ' * _CODE_CONT_INDENT + rows = [(condition, False)] + rows.extend(_pack(cont, _comma_chunks(cont + action), limit - 2)) + rows = _split_literals(rows, cont, limit, path, code) + return _add_continuations(rows, trailing_amp) + + only = _ONLY_RE.search(code) + if _USE_RE.match(code) and only is not None: + cont = indent + ' ' * _USE_CONT_INDENT + head = code[:only.end()].rstrip() + rows = [(head, False)] + rows.extend((cont + chunk.rstrip(), False) + for chunk in _comma_chunks(code[only.end():])) + else: + cont = indent + ' ' * _CODE_CONT_INDENT + rows = _pack(cont, _comma_chunks(code), limit - 2) + + rows = _split_literals(rows, cont, limit, path, code) + return _add_continuations(rows, trailing_amp) + + +def _logical_if_split(code: str) -> Optional[Tuple[str, str]]: + """Split ``if () `` into its condition and its action. + + Returns ``None`` for anything else, including a block ``if ... then``, + whose body is already on its own lines. + + Examples + -------- + >>> _logical_if_split(' if (allocated(x)) deallocate(x)') + (' if (allocated(x))', 'deallocate(x)') + >>> _logical_if_split(' if (x > 1) then') is None + True + >>> _logical_if_split(' call sub(a)') is None + True + """ + opening = _IF_RE.match(code) + if opening is None: + return None + closing = _matching_paren(code, opening.end() - 1) + if closing is None: + return None + action = code[closing + 1:].strip() + if not action or action.lower() == 'then' or action.lower().startswith('then '): + return None + return code[:closing + 1], action + + +def _matching_paren(code: str, opening: int) -> Optional[int]: + """Return the index closing the parenthesis at *opening*, or ``None``.""" + depth = 0 + quote = None + idx = opening + while idx < len(code): + char = code[idx] + if quote is not None: + if char == quote: + if code[idx + 1:idx + 2] == quote: + idx += 2 + continue + quote = None + elif char in ("'", '"'): + quote = char + elif char == '(': + depth += 1 + elif char == ')': + depth -= 1 + if depth == 0: + return idx + idx += 1 + return None + + +def _comma_chunks(code: str) -> List[str]: + """Split *code* after every comma outside a character literal. + + Each chunk keeps its comma and the blanks that followed it, so + concatenating the chunks reproduces *code* exactly. + + Examples + -------- + >>> _comma_chunks('alpha, beta, gamma') + ['alpha, ', 'beta, ', 'gamma'] + >>> _comma_chunks("f(a, 'x,y')") + ['f(a, ', "'x,y')"] + """ + chunks: List[str] = [] + start = 0 + quote = None + idx = 0 + while idx < len(code): + char = code[idx] + if quote is not None: + if char == quote: + if code[idx + 1:idx + 2] == quote: + idx += 2 + continue + quote = None + elif char in ("'", '"'): + quote = char + elif char == ',': + end = idx + 1 + while end < len(code) and code[end] in ' \t': + end += 1 + chunks.append(code[start:end]) + start = end + idx = end + continue + idx += 1 + if start < len(code): + chunks.append(code[start:]) + return chunks + + +def _pack( + cont: str, + chunks: Sequence[str], + budget: int, +) -> List[Tuple[str, bool]]: + """Greedily fill lines of at most *budget* columns with *chunks*. + + The first chunk carries the statement's own indent, so only the + continuation rows are prefixed with *cont*. + """ + rows: List[Tuple[str, bool]] = [] + current = '' + placed = False + for chunk in chunks: + if placed and len((current + chunk).rstrip()) > budget: + rows.append((current.rstrip(), False)) + current = cont + chunk + else: + current = current + chunk + placed = True + rows.append((current.rstrip(), False)) + return rows + + +def _split_literals( + rows: Sequence[Tuple[str, bool]], + cont: str, + limit: int, + path: Optional[str], + statement: str, +) -> List[Tuple[str, bool]]: + """Break any row still past the limit inside its character literal.""" + out: List[Tuple[str, bool]] = [] + for text, tight in rows: + # A row ending in a tight ``&`` needs one column for it; one that + # takes a ``' &'`` needs two. Charge two throughout: it is the + # safe side and costs at most one column of fill. + if len(text) <= limit - 2: + out.append((text, tight)) + else: + out.extend( + _literal_rows(text, cont, limit, path, statement, tight) + ) + return out + + +def _literal_rows( + text: str, + cont: str, + limit: int, + path: Optional[str], + statement: str, + tight: bool, +) -> List[Tuple[str, bool]]: + """Return the rows for *text*, continuing the literal that overruns. + + The literal straddling the limit is cut into as many pieces as it takes. + Every piece but the last ends with a tight ``&`` and the next opens with + ``&``, so the literal resumes with the character right after it. + """ + quote, open_at = _literal_at(text, limit - 2) + if quote is None: + raise CCPPError(_unbreakable(path, statement, limit)) + close_at = _literal_end(text, open_at, quote) + lead = text[:open_at + 1] # through the opening delimiter + content = text[open_at + 1:close_at] # doubled delimiters intact + trailer = text[close_at:] # closing delimiter and the rest + + rows: List[Tuple[str, bool]] = [] + while True: + if len(lead) + len(content) + len(trailer) <= limit - 2: + rows.append((lead + content + trailer, tight)) + return rows + # One column goes to the tight ``&`` that continues the literal. + room = limit - 1 - len(lead) + cut = _atom_boundary(content, min(room, len(content) - 1), quote) + if cut < 1: + raise CCPPError(_unbreakable(path, statement, limit)) + rows.append((lead + content[:cut], True)) + content = content[cut:] + lead = cont + '&' + + +def _literal_end(text: str, open_at: int, quote: str) -> int: + """Return the index of the delimiter closing the literal at *open_at*.""" + idx = open_at + 1 + while idx < len(text): + if text[idx] == quote: + if text[idx + 1:idx + 2] == quote: + idx += 2 + continue + return idx + idx += 1 + return len(text) + + +def _literal_at(text: str, column: int) -> Tuple[Optional[str], int]: + """Return the delimiter and start index of the literal open at *column*. + + ``(None, -1)`` when *column* is not inside a character literal. + """ + quote = None + open_at = -1 + idx = 0 + while idx < len(text): + char = text[idx] + if quote is not None: + if char == quote: + if text[idx + 1:idx + 2] == quote: + idx += 2 + continue + if idx >= column: + return quote, open_at + quote = None + open_at = -1 + elif char in ("'", '"'): + quote = char + open_at = idx + if quote is not None and idx >= column: + return quote, open_at + idx += 1 + return (quote, open_at) if quote is not None else (None, -1) + + +def _atom_boundary(content: str, cut: int, quote: str) -> int: + """Return the largest safe split index in *content* at or below *cut*. + + A doubled delimiter (``''`` inside a ``'``-quoted literal) is one + character of content and must not be split down the middle. A split + straight after a blank is preferred, so a continued message breaks + between words rather than mid-word. + + Examples + -------- + >>> _atom_boundary('one two three', 9, "'") + 8 + >>> _atom_boundary("a''b", 2, "'") + 1 + """ + stops: List[int] = [] + idx = 0 + while idx < cut: + if content[idx] == quote and content[idx + 1:idx + 2] == quote: + idx += 2 + else: + idx += 1 + if idx <= cut: + stops.append(idx) + if not stops: + return 0 + for stop in reversed(stops): + if content[stop - 1] == ' ': + return stop + return stops[-1] + + +def _add_continuations( + rows: Sequence[Tuple[str, bool]], + trailing_amp: bool, +) -> List[str]: + """Place the continuation markers on a finished set of rows.""" + out: List[str] = [] + for index, (text, tight) in enumerate(rows): + last = index == len(rows) - 1 + if tight: + # The literal is still open: the ``&`` has to hug the text, + # because a blank before it would join the literal. + out.append(text if text.endswith('&') else text + '&') + elif last and not trailing_amp: + out.append(text) + else: + out.append(text + ' &') + return out + + +def _unbreakable(path: Optional[str], statement: str, limit: int) -> str: + """Return the error message for a statement that cannot be wrapped.""" + where = ' in {}'.format(path) if path else '' + return ( + "Generated Fortran line{} is longer than {} columns and has no " + "comma, logical-if condition or character literal to continue at; " + "the emitter has to break it:\n {}".format(where, limit, statement) + ) diff --git a/capgen/generator/group_cap.py b/capgen/generator/group_cap.py index 9b9d9315..fd03c5ef 100644 --- a/capgen/generator/group_cap.py +++ b/capgen/generator/group_cap.py @@ -25,8 +25,9 @@ import os from typing import Dict, List, Optional, Set, Tuple -from metadata.parse_tools import CCPPError, FORTRAN_CONDITIONAL_REGEX, open_if_changed +from metadata.parse_tools import CCPPError, FORTRAN_CONDITIONAL_REGEX from metadata.variable_resolver import HostVarEntry +from generator.fortran_lines import write_fortran from generator.suite_types import _ptr_type_name_for_arg from generator.suite_resolver import ( ResolvedArg, @@ -1439,6 +1440,4 @@ def write_group_cap( suite_name, group_name, resolved_group, host_dict, trace=trace, logger=logger, ) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) diff --git a/capgen/generator/host_cap.py b/capgen/generator/host_cap.py index ba3e5ccf..7ad7caeb 100644 --- a/capgen/generator/host_cap.py +++ b/capgen/generator/host_cap.py @@ -44,9 +44,10 @@ import os from typing import Dict, List, Optional, Set, Tuple -from metadata.parse_tools import CCPPError, open_if_changed +from metadata.parse_tools import CCPPError from metadata.metadata_table import FORTRAN_MAX_IDENT_LEN from metadata.variable_resolver import SchemeStore +from generator.fortran_lines import write_fortran from generator.suite_resolver import ( ResolvedArg, SuiteResolution, @@ -1205,6 +1206,4 @@ def write_host_cap( no_host_introspection=no_host_introspection, trace=trace, ) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) diff --git a/capgen/generator/host_constituents.py b/capgen/generator/host_constituents.py index 934b2471..018fa76d 100644 --- a/capgen/generator/host_constituents.py +++ b/capgen/generator/host_constituents.py @@ -31,7 +31,7 @@ import os from typing import List, Optional, Set, Tuple -from metadata.parse_tools import open_if_changed +from generator.fortran_lines import write_fortran from generator.suite_resolver import SuiteResolution, _index_symbol_name _INDENT = ' ' @@ -711,6 +711,5 @@ def write_host_constituents( if not os.path.isdir(outdir): os.makedirs(outdir, exist_ok=True) path = os.path.join(outdir, 'ccpp_host_constituents.F90') - with open_if_changed(path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') + write_fortran(path, lines, logger=logger) return os.path.abspath(path) diff --git a/capgen/generator/kinds_writer.py b/capgen/generator/kinds_writer.py index c6cbf4dd..e9728181 100644 --- a/capgen/generator/kinds_writer.py +++ b/capgen/generator/kinds_writer.py @@ -46,7 +46,8 @@ import os from typing import Dict, List, Optional, Tuple -from metadata.parse_tools import CCPPError, open_if_changed +from metadata.parse_tools import CCPPError +from generator.fortran_lines import write_fortran _KINDS_FILENAME = 'ccpp_kinds.F90' _KINDS_MODULE = 'ccpp_kinds' @@ -91,9 +92,7 @@ def write_ccpp_kinds( os.makedirs(output_root, exist_ok=True) lines = _generate_ccpp_kinds(kind_types) out_path = os.path.join(output_root, _KINDS_FILENAME) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) ######################################################################## diff --git a/capgen/generator/suite_cap.py b/capgen/generator/suite_cap.py index 75a23c28..4ea11776 100644 --- a/capgen/generator/suite_cap.py +++ b/capgen/generator/suite_cap.py @@ -25,8 +25,9 @@ import os from typing import Dict, List, Optional, Set -from metadata.parse_tools import CCPPError, open_if_changed +from metadata.parse_tools import CCPPError from metadata.variable_resolver import HostVarEntry, SchemeStore +from generator.fortran_lines import write_fortran from generator.suite_resolver import ( ResolvedArg, ResolvedGroup, @@ -1377,6 +1378,4 @@ def write_suite_cap( suite_name, suite_res, scheme_store, host_dict, trace=trace, logger=logger, ) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) diff --git a/capgen/generator/suite_data.py b/capgen/generator/suite_data.py index 1864c37e..b3b38f94 100644 --- a/capgen/generator/suite_data.py +++ b/capgen/generator/suite_data.py @@ -7,6 +7,7 @@ from typing import Dict, List, Optional from metadata.parse_tools import CCPPError, open_if_changed +from generator.fortran_lines import write_fortran from generator.suite_resolver import SuiteVar _INDENT = ' ' @@ -428,9 +429,7 @@ def write_suite_data( out_path = os.path.join(output_root, filename) lines = _generate_suite_data(suite_name, suite_vars, host_dict, ddt_module_map=ddt_module_map) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) def _generate_suite_meta( diff --git a/capgen/generator/suite_types.py b/capgen/generator/suite_types.py index 73c5f6fd..8de986a7 100644 --- a/capgen/generator/suite_types.py +++ b/capgen/generator/suite_types.py @@ -21,7 +21,8 @@ import re from typing import Dict, List, Optional, Set, Tuple -from metadata.parse_tools import CCPPError, open_if_changed +from metadata.parse_tools import CCPPError +from generator.fortran_lines import write_fortran from generator.suite_resolver import SuiteResolution, iter_phase_calls _INDENT = ' ' @@ -510,6 +511,4 @@ def write_suite_types( out_path = os.path.join(output_root, filename) lines = _generate_suite_types(suite_name, combos, ddt_module_map) - with open_if_changed(out_path, logger=logger) as fh: - fh.write('\n'.join(lines) + '\n') - return out_path + return write_fortran(out_path, lines, logger=logger) diff --git a/capgen/metadata/parse_tools/__init__.py b/capgen/metadata/parse_tools/__init__.py index 6994db2e..d2e18b03 100644 --- a/capgen/metadata/parse_tools/__init__.py +++ b/capgen/metadata/parse_tools/__init__.py @@ -26,6 +26,7 @@ FORTRAN_SCALAR_REF_RE, ) from .fortran_conditional import FORTRAN_CONDITIONAL_REGEX +from .fortran_source_form import FREE_FORM_MAX_COLUMNS from .xml_tools import ( read_xml_file, find_schema_version, diff --git a/capgen/metadata/parse_tools/fortran_source_form.py b/capgen/metadata/parse_tools/fortran_source_form.py new file mode 100644 index 00000000..c1843894 --- /dev/null +++ b/capgen/metadata/parse_tools/fortran_source_form.py @@ -0,0 +1,22 @@ +"""Free-form Fortran source-form limits. + +Free-form Fortran source ends at column 132. Past that column a compiler +is free to ignore what it reads, and they differ in what they do: gfortran +truncates with a warning unless ``-ffree-line-length-none`` says otherwise, +Intel truncates, LLVM flang reads the whole line. Capgen therefore has to +treat 132 as a hard limit in both directions, and both read the number from +here: + +- **Input** -- ``ccpp_validator`` checks every Fortran file it is asked to + parse against the limit before parsing it, so capgen never reads text the + compiler will not see (``doc/followups.md`` FU-038). +- **Output** -- the cap writers wrap every emitted line to the limit + (``generator.fortran_lines``), so generated code compiles without a + line-length flag. + +The limit is not configurable: 132 is where the standard's free form ends, +so it is the standard's number rather than a CCPP preference. A group +wanting a stricter limit enforces that with its own linter. +""" + +FREE_FORM_MAX_COLUMNS = 132 diff --git a/end-to-end-tests/CMakeLists.txt b/end-to-end-tests/CMakeLists.txt index 3ea171a8..74bb992f 100644 --- a/end-to-end-tests/CMakeLists.txt +++ b/end-to-end-tests/CMakeLists.txt @@ -19,8 +19,8 @@ if(${CMAKE_Fortran_COMPILER_ID} STREQUAL "GNU") ADD_COMPILE_OPTIONS(-ffpe-trap=zero) ADD_COMPILE_OPTIONS(-finit-real=nan) ADD_COMPILE_OPTIONS(-ggdb) - ADD_COMPILE_OPTIONS(-ffree-line-length-none) ADD_COMPILE_OPTIONS(-cpp) + ADD_COMPILE_OPTIONS(-fimplicit-none) elseif(${CMAKE_Fortran_COMPILER_ID} STREQUAL "Intel") ADD_COMPILE_OPTIONS(-fpe0) ADD_COMPILE_OPTIONS(-warn) @@ -34,6 +34,11 @@ elseif(${CMAKE_Fortran_COMPILER_ID} STREQUAL "IntelLLVM") ADD_COMPILE_OPTIONS(-traceback) ADD_COMPILE_OPTIONS(-debug full) ADD_COMPILE_OPTIONS(-fpp) +elseif (${CMAKE_Fortran_COMPILER_ID} STREQUAL "LLVMFlang") + ADD_COMPILE_OPTIONS(-g2) + ADD_COMPILE_OPTIONS(-fno-omit-frame-pointer) + ADD_COMPILE_OPTIONS(-cpp) + ADD_COMPILE_OPTIONS(-fimplicit-none) elseif (${CMAKE_Fortran_COMPILER_ID} STREQUAL "NVIDIA" OR ${CMAKE_Fortran_COMPILER_ID} STREQUAL "NVHPC") ADD_COMPILE_OPTIONS(-Mnoipa) ADD_COMPILE_OPTIONS(-traceback) diff --git a/end-to-end-tests/advection/test_host.F90 b/end-to-end-tests/advection/test_host.F90 index 67399bbe..75273792 100644 --- a/end-to-end-tests/advection/test_host.F90 +++ b/end-to-end-tests/advection/test_host.F90 @@ -396,7 +396,8 @@ subroutine test_host(retval, test_suites) call ccpp_const_get_index(stdname='dyn_const2_wrt_moist_air', const_index=index_dyn2, errcode=errcode, errmsg=errmsg) call check_errcode(subname // ".index_dyn_const2", errcode, errmsg, & errcode_final) - call ccpp_const_get_index(stdname='dyn_const3_wrt_moist_air_and_condensed_water', const_index=index_dyn3, errcode=errcode, errmsg=errmsg) + call ccpp_const_get_index(stdname='dyn_const3_wrt_moist_air_and_condensed_water', & + const_index=index_dyn3, errcode=errcode, errmsg=errmsg) call check_errcode(subname // ".index_dyn_const3", errcode, errmsg, & errcode_final) diff --git a/end-to-end-tests/advection_auto_clone/test_host.F90 b/end-to-end-tests/advection_auto_clone/test_host.F90 index dd9549d4..cc1d14a9 100644 --- a/end-to-end-tests/advection_auto_clone/test_host.F90 +++ b/end-to-end-tests/advection_auto_clone/test_host.F90 @@ -384,7 +384,8 @@ subroutine test_host(retval, test_suites) call ccpp_const_get_index(stdname='dyn_const2_wrt_moist_air', const_index=index_dyn2, errcode=errcode, errmsg=errmsg) call check_errcode(subname // ".index_dyn_const2", errcode, errmsg, & errcode_final) - call ccpp_const_get_index(stdname='dyn_const3_wrt_moist_air_and_condensed_water', const_index=index_dyn3, errcode=errcode, errmsg=errmsg) + call ccpp_const_get_index(stdname='dyn_const3_wrt_moist_air_and_condensed_water', & + const_index=index_dyn3, errcode=errcode, errmsg=errmsg) call check_errcode(subname // ".index_dyn_const3", errcode, errmsg, & errcode_final) diff --git a/end-to-end-tests/chunked_data/main.F90 b/end-to-end-tests/chunked_data/main.F90 index 36201afe..2d9d9a23 100644 --- a/end-to-end-tests/chunked_data/main.F90 +++ b/end-to-end-tests/chunked_data/main.F90 @@ -56,7 +56,9 @@ program test_chunked_data ! CCPP physics init step ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - call ccpp_physics_init(lb=1, ub=ncols, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_init(lb=1, ub=ncols, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_init:" write(error_unit, '(a)') trim(errmsg) @@ -68,7 +70,9 @@ program test_chunked_data !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !cdata => ccpp_data_domain - call ccpp_physics_timestep_init(lb=1, ub=ncols, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_timestep_init(lb=1, ub=ncols, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_timestep_init:" write(error_unit, '(a)') trim(errmsg) @@ -82,7 +86,9 @@ program test_chunked_data do nchunk = 1, nchunks lb=chunk_begin(nchunk) ub=chunk_end(nchunk) - call ccpp_physics_run(lb=lb, ub=ub, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_run(lb=lb, ub=ub, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a,i3,a)') "An error occurred in ccpp_physics_run for chunk", nchunk, ":" write(error_unit, '(a)') trim(errmsg) @@ -95,7 +101,9 @@ program test_chunked_data !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !cdata => ccpp_data_domain - call ccpp_physics_timestep_final(lb=1, ub=ncols, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_timestep_final(lb=1, ub=ncols, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_timestep_finalize:" write(error_unit, '(a)') trim(errmsg) @@ -107,7 +115,9 @@ program test_chunked_data !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !cdata => ccpp_data_domain - call ccpp_physics_final(lb=1, ub=ncols, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_final(lb=1, ub=ncols, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_finalize:" write(error_unit, '(a)') trim(errmsg) diff --git a/end-to-end-tests/opt_arg/main.F90 b/end-to-end-tests/opt_arg/main.F90 index e0643513..37ff59e7 100644 --- a/end-to-end-tests/opt_arg/main.F90 +++ b/end-to-end-tests/opt_arg/main.F90 @@ -65,7 +65,9 @@ program test_opt_arg ! CCPP physics init step ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - call ccpp_physics_init(lb=1, ub=1, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_init(lb=1, ub=1, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_init:" write(error_unit, '(a)') trim(errmsg) @@ -81,7 +83,9 @@ program test_opt_arg ! CCPP physics timestep init step ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - call ccpp_physics_timestep_init(lb=1, ub=1, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_timestep_init(lb=1, ub=1, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_timestep_init:" write(error_unit, '(a)') trim(errmsg) @@ -97,7 +101,9 @@ program test_opt_arg ! CCPP physics run step ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - call ccpp_physics_run(lb=1, ub=1, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_run(lb=1, ub=1, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_run:" write(error_unit, '(a)') trim(errmsg) @@ -116,7 +122,9 @@ program test_opt_arg deallocate(opt_arg) flag_for_opt_arg = .false. - call ccpp_physics_timestep_final(lb=1, ub=1, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_timestep_final(lb=1, ub=1, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_timestep_final:" write(error_unit, '(a)') trim(errmsg) @@ -131,7 +139,9 @@ program test_opt_arg ! CCPP physics finalize step ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - call ccpp_physics_final(lb=1, ub=1, nthreads=1, nphys_threads=1, thread_num=1, suite_name=trim(ccpp_suite), group_name='all', errmsg=errmsg, errflg=errflg) + call ccpp_physics_final(lb=1, ub=1, nthreads=1, nphys_threads=1, & + thread_num=1, suite_name=trim(ccpp_suite), group_name='all', & + errmsg=errmsg, errflg=errflg) if (errflg/=0) then write(error_unit, '(a)') "An error occurred in ccpp_physics_final:" write(error_unit, '(a)') trim(errmsg) diff --git a/unit-tests/test_fortran_lines.py b/unit-tests/test_fortran_lines.py new file mode 100644 index 00000000..db8c51b3 --- /dev/null +++ b/unit-tests/test_fortran_lines.py @@ -0,0 +1,406 @@ +"""Tests for ``generator.fortran_lines`` — wrapping generated Fortran. + +The property that matters is not the exact layout but that wrapping is +*transparent*: every emitted line fits in 132 columns, and joining the +continuations back up gives the statement the emitter asked for. :func:`_join` +is that inverse and :func:`_same` the comparison, so most tests below are +round-trip tests rather than golden strings. + +A continuation line's indent is whitespace between tokens, so :func:`_same` +compares with runs of blanks *outside* a character literal collapsed. Inside +a literal nothing is collapsed: a continued message has to come back byte for +byte, which is the part a wrapper can silently get wrong. +""" + +import doctest +import os +import tempfile +import unittest + +from metadata.parse_tools import CCPPError, FREE_FORM_MAX_COLUMNS +from generator.fortran_lines import ( + GENERATED_MAX_COLUMNS, + wrap_fortran_lines, + write_fortran, +) + +LIMIT = GENERATED_MAX_COLUMNS + + +def _join(lines): + """Undo free-form continuation, returning the logical lines. + + A line ending in ``&`` continues onto the next. When the next line's + first non-blank character is an ``&`` the blanks before it are not part + of the text — that is the rule that lets a character literal be + continued without gaining or losing a blank. + """ + out = [] + pending = None + for raw in lines: + text = raw.rstrip() + if pending is not None: + stripped = text.lstrip() + if stripped.startswith('&'): + text = stripped[1:] + text = pending + text + pending = None + if text.endswith('&'): + pending = text[:-1] + continue + out.append(text) + if pending is not None: + out.append(pending) + return out + + +def _normalise(line): + """Collapse blank runs outside a character literal; keep literals exact.""" + out = [] + quote = None + idx = 0 + while idx < len(line): + char = line[idx] + if quote is not None: + out.append(char) + if char == quote: + if line[idx + 1:idx + 2] == quote: + out.append(quote) + idx += 2 + continue + quote = None + elif char in ("'", '"'): + quote = char + out.append(char) + elif char in ' \t': + if out and out[-1] != ' ': + out.append(' ') + else: + out.append(char) + idx += 1 + return ''.join(out).strip() + + +def _same(wrapped, original): + """Return ``(joined, expected)`` ready for an equality assertion. + + Both sides go through :func:`_join`, so a fixture that is itself a + continuation line compares against its own joined form rather than + against text that still carries the trailing ampersand. + """ + return ( + [_normalise(line) for line in _join(wrapped)], + [_normalise(line) for line in _join(original)], + ) + + +class TestTheLimitInForce(unittest.TestCase): + """Generated output is held to `.codee-format`'s column limit, which is + stricter than the one the standard sets and the validator checks.""" + + def test_generated_limit_is_the_codee_column_limit(self): + self.assertEqual(GENERATED_MAX_COLUMNS, 120) + + def test_generated_limit_is_stricter_than_the_standard(self): + self.assertLess(GENERATED_MAX_COLUMNS, FREE_FORM_MAX_COLUMNS) + + def test_wrapping_defaults_to_the_generated_limit(self): + # Between the two limits: wrapped under 120, untouched under 132. + line = ' use m, only: ' + ', '.join( + 'symbol_{:02d}'.format(i) for i in range(10) + ) + self.assertGreater(len(line), GENERATED_MAX_COLUMNS) + self.assertLess(len(line), FREE_FORM_MAX_COLUMNS) + self.assertGreater(len(wrap_fortran_lines([line])), 1) + + +class TestLogicalIf(unittest.TestCase): + """A one-line ``if`` breaks after its condition.""" + + def setUp(self): + self.name = 'a_suite_with_a_rather_long_name_dynamic_constituents' + self.line = ' if (allocated({0})) deallocate({0})'.format(self.name) + self.wrapped = wrap_fortran_lines([self.line]) + + def test_fixture_is_over_the_limit(self): + self.assertGreater(len(self.line), LIMIT) + + def test_breaks_after_the_condition(self): + self.assertEqual( + self.wrapped[0], + ' if (allocated({})) &'.format(self.name), + ) + self.assertEqual( + self.wrapped[1], ' deallocate({})'.format(self.name) + ) + + def test_round_trips(self): + self.assertEqual(*_same(self.wrapped, [self.line])) + + def test_block_if_is_left_to_the_comma_path(self): + # ``then`` has no action to move, so the condition's commas are the + # only break points. + line = (' if (' + ' .and. '.join( + 'flag_{:02d}(index_{:02d}, 1)'.format(i, i) for i in range(8) + ) + ') then') + wrapped = wrap_fortran_lines([line]) + self.assertFalse(wrapped[0].rstrip().endswith(') &')) + self.assertEqual(*_same(wrapped, [line])) + + def test_condition_too_long_falls_through_to_commas(self): + line = (' if (check(' + ', '.join( + 'argument_{:02d}'.format(i) for i in range(14) + ) + ')) return') + wrapped = wrap_fortran_lines([line]) + for out in wrapped: + self.assertLessEqual(len(out), LIMIT) + self.assertEqual(*_same(wrapped, [line])) + + +class TestShortLinesUntouched(unittest.TestCase): + """Wrapping only ever touches a line that would overrun.""" + + def test_line_at_the_limit_is_unchanged(self): + line = ' ' + 'x' * (LIMIT - 2) + self.assertEqual(len(line), LIMIT) + self.assertEqual(wrap_fortran_lines([line]), [line]) + + def test_whole_file_unchanged_when_nothing_overruns(self): + lines = ['module m', ' implicit none', 'end module m'] + self.assertEqual(wrap_fortran_lines(lines), lines) + + def test_wrapping_is_idempotent(self): + line = ' use m, only: ' + ', '.join( + 'symbol_number_{:02d}'.format(i) for i in range(20) + ) + once = wrap_fortran_lines([line]) + self.assertEqual(wrap_fortran_lines(once), once) + + +class TestEveryLineFits(unittest.TestCase): + """Each shape the generator actually emits comes back inside 132.""" + + def _check(self, line): + wrapped = wrap_fortran_lines([line]) + self.assertGreater(len(line), LIMIT, 'fixture is not over-long') + for out in wrapped: + self.assertLessEqual( + len(out), LIMIT, + '{} columns: {!r}'.format(len(out), out), + ) + return wrapped + + def test_import_list(self): + self._check( + ' use ccpp_chunked_data_suite_chunked_data_group_cap, only: ' + 'chunked_data_group_init, chunked_data_group_timestep_init, ' + 'chunked_data_group_run, chunked_data_group_timestep_final, ' + 'chunked_data_group_final, chunked_data_group_state_alloc, ' + 'chunked_data_group_state_dealloc' + ) + + def test_call_statement(self): + self._check( + " call ccpp_model_constituents_obj(1)%const_index(" + "index_of_cloud_liquid_dry_mixing_ratio, " + "'cloud_liquid_dry_mixing_ratio', errcode=errcode, " + "errmsg=errmsg)" + ) + + def test_long_error_message(self): + self._check( + " errmsg = 'ccpp_initialize_constituents: constituent " + "''cloud_liquid_dry_mixing_ratio'' is referenced by a scheme " + "but is not in the registered constituent table; check that " + "some scheme''s _register routine or the host_constituents " + "argument to ccpp_register_constituents includes it'" + ) + + def test_statement_with_long_trailing_comment(self): + self._check( + ' effrs(col_start:col_end, pver:1:-1) = ' + '1.0E-6_kind_phys*effrs_inout_l ! type conversion: 8 to ' + 'kind_phys; unit conversion: um to m; vertical flip ' + '(top_at_one mismatch) recorded here' + ) + + def test_one_over_long_actual_argument(self): + self._check( + ' cld_liq_tend=ccpp_model_constituents_obj(1)%' + 'vars_layer_tend(col_start:col_end, 1:pver, ' + 'index_of_cloud_liquid_dry_mixing_ratio_with_a_long_name), &' + ) + + +class TestRoundTrip(unittest.TestCase): + """Joining the continuations reproduces what the emitter asked for.""" + + def test_import_list_round_trips(self): + line = ' use m, only: ' + ', '.join( + 'symbol_number_{:02d}'.format(i) for i in range(20) + ) + self.assertEqual(*_same(wrap_fortran_lines([line]), [line])) + + def test_call_round_trips(self): + line = ' call sub(' + ', '.join( + 'argument_{:02d}=value_{:02d}'.format(i, i) for i in range(12) + ) + ')' + self.assertEqual(*_same(wrap_fortran_lines([line]), [line])) + + def test_literal_content_survives_byte_for_byte(self): + message = ( + 'this message is long enough to need continuing, and it holds ' + "a doubled quote in ''quoted'' text plus a comma, an " + 'exclamation mark! and trailing words to push it past the ' + 'free-form column limit for certain' + ) + line = " errmsg = '{}'".format(message) + self.assertEqual(*_same(wrap_fortran_lines([line]), [line])) + + def test_doubled_quote_is_never_split(self): + # A ``''`` that straddles the cut would otherwise become a closing + # delimiter followed by a stray opening one. + for pad in range(40): + message = 'a' * (LIMIT + pad) + "''" + 'b' * 40 + line = " msg = '{}'".format(message) + wrapped = wrap_fortran_lines([line]) + joined, expected = _same(wrapped, [line]) + self.assertEqual(joined, expected, 'pad={}'.format(pad)) + for out in wrapped: + self.assertLessEqual(len(out), LIMIT, 'pad={}'.format(pad)) + + def test_already_continued_line_keeps_its_ampersand(self): + line = ' argument=' + 'f(' + ', '.join( + 'item_{:02d}'.format(i) for i in range(20) + ) + '), &' + wrapped = wrap_fortran_lines([line]) + self.assertTrue(wrapped[-1].endswith(', &')) + self.assertEqual(*_same(wrapped, [line])) + + +class TestBreakPointsRespectLiterals(unittest.TestCase): + """Commas and exclamation marks inside a literal are just text.""" + + def test_comma_inside_a_literal_is_not_a_break_point(self): + line = " call sub(a, 'one, two, three', " + ', '.join( + 'argument_{:02d}'.format(i) for i in range(12) + ) + ')' + wrapped = wrap_fortran_lines([line]) + # No line may end inside the literal, i.e. at one of its commas. + for out in wrapped: + self.assertFalse(out.rstrip(' &').rstrip().endswith("'one,")) + self.assertFalse(out.rstrip(' &').rstrip().endswith("two,")) + self.assertEqual(*_same(wrapped, [line])) + + def test_exclamation_inside_a_literal_is_not_a_comment(self): + line = " msg = 'not a comment! " + 'x' * LIMIT + "'" + wrapped = wrap_fortran_lines([line]) + self.assertEqual(*_same(wrapped, [line])) + self.assertFalse(any(out.lstrip().startswith('!') for out in wrapped)) + + +class TestImportListStyle(unittest.TestCase): + """The import list takes the form the host cap already emits.""" + + def setUp(self): + self.wrapped = wrap_fortran_lines([ + ' use m, only: ' + ', '.join( + 'symbol_number_{:02d}'.format(i) for i in range(20) + ) + ]) + + def test_head_ends_at_only(self): + self.assertEqual(self.wrapped[0], ' use m, only: &') + + def test_one_symbol_per_continuation_line(self): + for index, out in enumerate(self.wrapped[1:]): + self.assertTrue(out.startswith(' symbol_number_')) + self.assertEqual(out.count(','), 0 if index == 19 else 1) + + def test_intrinsic_use_splits_at_the_import_list(self): + line = (' use, intrinsic :: iso_fortran_env, only: ' + + ', '.join('name_{:03d}'.format(i) for i in range(20))) + wrapped = wrap_fortran_lines([line]) + self.assertEqual( + wrapped[0], ' use, intrinsic :: iso_fortran_env, only: &' + ) + self.assertEqual(*_same(wrapped, [line])) + + +class TestTrailingComment(unittest.TestCase): + """A comment cannot be continued, so it moves above the statement.""" + + def setUp(self): + self.comment = 'unit conversion: um to m ' + 'and more words ' * 8 + self.code = ' x = 1.0E-6_kind_phys*y' + self.wrapped = wrap_fortran_lines( + ['{} ! {}'.format(self.code, self.comment)] + ) + + def test_comment_comes_first(self): + self.assertTrue(self.wrapped[0].lstrip().startswith('!')) + + def test_statement_survives_unchanged(self): + self.assertEqual(self.wrapped[-1], self.code) + + def test_comment_text_is_kept_whole(self): + text = ' '.join( + out.lstrip().lstrip('!').strip() + for out in self.wrapped if out.lstrip().startswith('!') + ) + self.assertEqual(text.split(), self.comment.split()) + + def test_comment_lines_fit(self): + for out in self.wrapped: + self.assertLessEqual(len(out), LIMIT) + + +class TestUnbreakableLineRaises(unittest.TestCase): + """An over-long line with nowhere to break is a generator bug.""" + + def test_raises_naming_the_file(self): + line = ' ' + 'a' * (LIMIT * 2) + with self.assertRaises(CCPPError) as caught: + wrap_fortran_lines([line], path='ccpp_bogus_cap.F90') + message = str(caught.exception) + self.assertIn('ccpp_bogus_cap.F90', message) + self.assertIn(str(LIMIT), message) + + +class TestWriteFortran(unittest.TestCase): + """The writer wraps on the way to disk and keeps no-op semantics.""" + + def setUp(self): + self._tmpdir = tempfile.mkdtemp() + self.path = os.path.join(self._tmpdir, 'ccpp_sample_cap.F90') + self.lines = [ + 'module m', + ' use m2, only: ' + ', '.join( + 'symbol_number_{:02d}'.format(i) for i in range(20) + ), + 'end module m', + ] + + def test_written_file_is_within_the_limit(self): + write_fortran(self.path, self.lines) + with open(self.path) as fh: + written = fh.read().splitlines() + for out in written: + self.assertLessEqual(len(out), LIMIT) + self.assertEqual(*_same(written, self.lines)) + + def test_unchanged_rewrite_is_a_no_op(self): + write_fortran(self.path, self.lines) + before = os.stat(self.path).st_mtime_ns + write_fortran(self.path, self.lines) + self.assertEqual(os.stat(self.path).st_mtime_ns, before) + + +def load_tests(loader, tests, ignore): + import generator.fortran_lines as fl + tests.addTests(doctest.DocTestSuite(fl)) + return tests + + +if __name__ == '__main__': + unittest.main() diff --git a/unit-tests/test_host_cap.py b/unit-tests/test_host_cap.py index 509ef0e8..4a30edbf 100644 --- a/unit-tests/test_host_cap.py +++ b/unit-tests/test_host_cap.py @@ -2,6 +2,7 @@ import doctest import os +import re import tempfile import unittest from unittest.mock import MagicMock @@ -1303,8 +1304,14 @@ def test_write_host_cap_passes_flag_through(self): ) with open(out_path) as fh: text = fh.read() + # Unlike the sibling tests, which read the generator's line list + # directly, this one reads the written file -- where the stub's + # message runs past column 132 and so arrives as a continued + # character literal (``generator.fortran_lines``). Join the + # continuation back up before matching the message. + joined = re.sub(r'&\n\s*&', '', text) self.assertIn('ccpp_physics_suite_variables: ' + self._DISABLED_MSG, - text) + joined) self.assertIn( 'use, intrinsic :: iso_fortran_env, only: error_unit', text, ) diff --git a/unit-tests/test_integration.py b/unit-tests/test_integration.py index decbd160..4d544bd5 100644 --- a/unit-tests/test_integration.py +++ b/unit-tests/test_integration.py @@ -13,6 +13,7 @@ import xml.etree.ElementTree as ET from ccpp_capgen import capgen +from generator.fortran_lines import GENERATED_MAX_COLUMNS _TESTS_DIR = os.path.dirname(__file__) _SAMPLES_DIR = os.path.join(_TESTS_DIR, 'sample_files') @@ -2336,5 +2337,51 @@ def test_meta_with_suite_vars_lists_them(self): self.assertIn('kind = kind_phys', text) +# --------------------------------------------------------------------------- +# Test: generated Fortran respects the free-form column limit +# --------------------------------------------------------------------------- + +class TestGeneratedFortranFitsTheColumnLimit(unittest.TestCase): + """Capgen holds the Fortran it reads to 132 columns (FU-038); it has to + hold the Fortran it writes to a limit too, or the caps need a compiler + flag (``-ffree-line-length-none``) to build. Output goes to the stricter + 120 of `.codee-format`, so a cap is never what a future Codee pass has to + reflow (FU-005). Wrapping happens for every writer in + ``generator.fortran_lines``; this is the invariant it exists to keep.""" + + def _assert_within_limit(self, outdir): + checked = 0 + for name in sorted(os.listdir(outdir)): + if not name.endswith('.F90'): + continue + checked += 1 + with open(os.path.join(outdir, name)) as fh: + for num, line in enumerate(fh.read().splitlines(), 1): + self.assertLessEqual( + len(line.rstrip()), GENERATED_MAX_COLUMNS, + '{}:{} is {} columns:\n{}'.format( + name, num, len(line.rstrip()), line + ), + ) + self.assertGreater(checked, 0, 'no generated Fortran to check') + + def test_simple_suite(self): + with tempfile.TemporaryDirectory() as d: + _run_simple(d) + self._assert_within_limit(d) + + def test_constituents_suite(self): + # The constituent path holds the longest generated lines: the + # per-constituent ``errmsg`` runs past 280 columns unwrapped. + with tempfile.TemporaryDirectory() as d: + _run_with_constituents(d) + self._assert_within_limit(d) + + def test_subcycle_suite(self): + with tempfile.TemporaryDirectory() as d: + _run_subcycle(d) + self._assert_within_limit(d) + + if __name__ == '__main__': unittest.main(verbosity=2)