lfortran / lfortran/lfortran

`lfortran fmt` should use line continuation for long lines

Open
#327 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

fmt
Dominant language
C++
Stars
1.2k
Forks
271
Avg merge
1d 2h
Merged PRs (30d)
173

Description

Original issue: https://gitlab.com/lfortran/lfortran/-/issues/340

A user defined maximum line length (say 80) should be respected by correctly inserting line continuation & character. A quick way to achieve that is by:

diff --git a/src/lfortran/ast_to_src.cpp b/src/lfortran/ast_to_src.cpp
index 27452f23..3a4805e4 100644
--- a/src/lfortran/ast_to_src.cpp
+++ b/src/lfortran/ast_to_src.cpp
@@ -877,10 +877,20 @@ public:
             }
             if (x.n_syms > 0) {
                 r.append(" :: ");
+                int column = r.size();
                 for (size_t i=0; i<x.n_syms; i++) {
                     visit_var_sym(x.m_syms[i]);
+                    if (column + s.size() > 75) {
+                        r += " &\n";
+                        r += indent + "    ";
+                        column = indent.size() + 4;
+                    }
                     r += s;
-                    if (i < x.n_syms-1) r.append(", ");
+                    column += s.size();
+                    if (i < x.n_syms-1) {
+                        r.append(", ");
+                        column += 2;
+                    }
                 }
             }
         }

But it seems quite messy and error prone. A cleaner (perhaps a bit slower) approach would be for the visit methods to not return a string in s but rather a list of tokens (a list of strings), a token can be a new line and an indentation also. Then could have a class that handles converting this list of tokens into a string, which would keep track of indentation and the current column and insert continuation character & appropriately.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the formatter implementation in src/lfortran/ast_to_src.cpp and trace how the lfortran fmt command assembles output strings and indentation. Compare the proposed line-length handling with the cleaner token-based design described in the issue. Done means user-defined maximum line lengths are respected with valid Fortran continuation characters without breaking formatted output.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, fortran
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.