Pure-Fortran is a set of Python tools written by Codex and prompted and tested by me that help modernize and tighten Fortran codebases by adding:
INTENT(...)on dummy argumentsPURE/ELEMENTALon proceduresPRIVATEaccessibility inside modules
The tools are designed for iterative use on real projects: suggest changes, apply safe edits, compile, and roll back if needed.
Large Fortran codebases often evolve without complete interface annotations. Missing intent, missing pure, and broad default public visibility make code harder to reason about and harder for compilers to optimize.
Pure-Fortran focuses on practical improvements that are:
- Conservative: static heuristics avoid aggressive unsafe rewrites.
- Compile-validated: in fix mode, tools can verify that code still compiles.
- Incremental: support iterative passes (
--iterate) to unlock more opportunities as code improves. - Reversible: backups and rollback behavior reduce risk.
Main programs:
xintent.py- suggest/applyintent(in), optionalintent(out), and optionalintent(in out).xpure.py- suggest/applypure, optionally upgrade toelemental, and advisory-suggestimpure elemental.xprivate.py- suggest/apply module-levelprivate :: namerestrictions.xprune.py- compile-validated pruning of likely unused top-level procedures.ximplicit_none.py- suggest/applyimplicit nonein program units.xuse_only.py- suggest/applyuse ..., only: ...imports from broadusestatements.xunset.py- advisory checker for likely use-before-set variables.xunused.py- advisory checker for likely unused set variables/constants, with optional conservative fix mode.xparam.py- advisory checker for variables that can be made named constants (parameter), with optional fix modes.xrepeated_if.py- advisory checker/fixer for consecutive repeated IF conditions.xfunc_print.py- advisory checker/fixer for external output statements inside functions.xnotrim.py- advisory checker/fixer for likely needlesstrim(...)in string equality/inequality comparisons.xoptval.py- advisory checker/fixer for optional-argument defaulting patterns replaceable withstdliboptval(...).xmerge.py- advisory checker/fixer for simpleif/elseassignment blocks replaceable withmerge(...).xdealloc.py- advisory checker for earlydeallocate(...)opportunities, with annotation/fix workflows.xformat.py- advisory checker/fixer for format literals that can be shortened with repeat edit descriptors.xadvance.py- advisory checker for non-advancingwriteloops that can be collapsed.xnames.py- advisory checker for variable/procedure names that collide with Fortran keywords/intrinsics.xkind.py- advisory checker/fixer for hard-coded kind numbers (_8,kind=8, etc.).xalloc_assign.py- advisory checker/fixer for redundantallocate(...)immediately before whole-array assignment.xc2f.py- practical C-to-Fortran transpiler for a supported C subset, with Fortran-oriented cleanup/post-processing passes.xc2f_batch_test.py- batch harness to smoke-testxc2f.pyacross many C files with compile/run reporting.xf2c.py- practical Fortran-to-C transpiler for a supported free-form Fortran subset, with build/run and per-file modes.xp2f.py- practical Python-to-Fortran transpiler for a supported Python subset, with helper-module integration and run/compare options.xp2f_batch.py- batch harness to runxp2f.pyover multiple Python sources/globs with summary reporting.xf2p.py- practical Fortran-to-Python transpiler for a supported free-form Fortran subset, with compile/run comparison modes.xr2f.py- practical R-to-Fortran transpiler for a supported R subset, with helper-module integration and run/compare options.xoct2f.py- practical Octave/MATLAB-to-Fortran transpiler for a supported subset.xlegal.py- lightweight Fortran legality validator (statement/form checks, implicit-none/declaration sanity, duplicate checks).xfix.py- conservative auto-fixer for common structural issues (for example end-name mismatches, duplicate defs/decls, simple paren fixes).xerror_loc.py- annotateerror stopmessages with file/line (and optional scope), with optional condition-value expansion for IF-guarded stops.xcombine_decl.py- coalesce adjacent compatible declarations and contiguouspublic/privatelists.xindent.py- Fortran indentation and long-line wrapping utility with configurable indentation controls.xnamed_arg.py- rewrite procedure calls to use named arguments under conservative rules.xset_array.py- advisory checker for replacing consecutive scalar array-element assignments with one array assignment.xarray.py- advisory checker for simple loops replaceable by array operations (sum/product/countand elementwise forms).xto_loop.py- advisory checker/fixer that reverses selected array operations to explicit loops (for benchmarking/audit round-trips).xroundtrip.py- harness that appliesxarray.py/xto_loop.pyin sequence and compares semantic equivalence of round-tripped code.xbounds.py- advisory checker for likely out-of-bounds indexing/slicing patterns.xone_line_if.py- advisory checker/fixer for collapsible three-line IF blocks (and reverse expansion mode).xlong_lines.py- advisory checker/fixer for overlong Fortran lines via continuation wrapping.xpower.py- advisory checker/fixer for repeated multiplication terms (x*x) that can be written as powers (x**2).xno_variable.py- advisory checker/fixer for single-use local scalar temporaries that can be inlined.xdealloc_tail.py- advisory checker for redundant taildeallocate(...)of local allocatables.xintent_pure.py- pipeline wrapper (intent -> pure -> optional elemental).xintent_pure_private.py- full pipeline wrapper (intent -> pure -> optional elemental -> private).xstrip.py- strip annotations (intent,pure/elemental/impure, or both) for testing.xstrip_implicit_none.py- stripimplicit nonestatements for test-case generation.xstrip_use_only.py- stripuse ..., only: ...back to broadusefor testing.xdecl.py- advisory checker/fixer for declarations missing::.xend_name.py- advisory checker/fixer for plainendstatements, replacing with named forms (end subroutine foo, etc.).xspace.py- advisory checker/fixer for spacing/layout normalization rules.xburkardt.py- infer/applyintent(in/out)from Burkardt-style argument comment blocks.xmodule.py- informational wrapper-checker for procedures outside modules, with compile test via temporary module wrapping.xfree.py- fixed-form (.f) to free-form (.f90) converter with optional compile regression checks.xtest.py- transform regression harness (baseline compile -> transform -> post-compile) over file lists.xcompile.py- compile-only batch harness over file lists with resume/loop controls.xbuild.py- executable-build harness over source-file sets (one set per line in--codes).xarith_if.py- advisory checker/fixer for arithmetic IF (if (expr) l1, l2, l3) with structured rewrites where safe.xassign.py- advisory checker/fixer for legacyASSIGNand assignedGO TO/assignedFORMATpatterns.xassumed_shape.py- advisory checker/fixer to wrap or replace explicit-shape procedures with assumed-shape interfaces/bodies.xassumed_shape_set.py- set-based assumed-shape migration across related source files, including caller rewrite support.xerror.py- summarize warning/error kinds from compile logs (files/lines/hits per diagnostic kind).xcount_goto.py- countgotostatements per file and compare two directories (beforevsafter) with totals/deltas.xdata.py- advisory checker/fixer forDATA-initialized variables that can be promoted to named constants.xdep.py- dependency resolver/build helper for main-program source sets viause-module graph analysis.xdp.py- advisory checker/fixer to migrate defaultrealusage toward a chosen kind parameter (for exampledp).xformat_mismatch.py- advisory checker for likely type/descriptor mismatches inprint/writeformat usage.xformat_statement.py- advisory checker/fixer replacing labeledFORMATstatements with inline or named format strings.xgoto.py- advisory checker/fixer for reduciblegotopatterns, with extraction/report utilities for remaining goto-heavy code.xinit.py- advisory checker/fixer to add explicit variable initialization (with configurable sentinels/NaN and uncertain-only mode).xloop.py- advisory checker/fixer for labeled DO termination modernization (do label ...toend doforms).xmodularize.py- transforms external-procedure program sets to module-based layout and updates main-programuselists.xoptional.py- advisory checker for optional-dummy arguments that may be used without guaranteedpresent(...)guards.xproc_index.py- procedure index/report tool listing discovered procedure names and duplicate definitions across file sets.xselect.py- advisory checker/fixer to rewrite eligible IF/ELSEIF chains asselect case(including ranges/sets).xsubroutine.py- extracts marked code blocks (or auto-selected loops) into new module procedures, with argument/local inference, optional function extraction, and compile/run validation modes.xsort_size.py- sort a file list (such ascodes.txt) by source file size.xoptions.py- list option counts and option names forx*.pyscripts.xrepeat.py- utility helper for repeated harness execution workflows.xdiff.pycompares two versions of a Fortran module and reports structural differences, documented here
Shared support modules:
fortran_scan.py- scanning/parsing helpers, dependency ordering, file selection.fortran_build.py- compile and rollback helpers, git commit helper.fortran_pipeline.py- shared pipeline orchestration used by wrappers.
- Python 3.10+
- Optional but recommended:
gfortran(or another Fortran compiler command) for compile checks - Optional: Git for
--git
Across tools:
- If no file list is provided, tools scan
*.f90and*.F90in the current directory. - File processing order is dependency-aware (least-dependent first).
--excludecan be repeated to skip files by glob.--backup(default in fixing tools) writes.bakfiles before first modification.--compilerenables compile checks; for fix pipelines this is strongly recommended.--gitcommits changed files with an auto-generated message.
Many fixer/checker scripts follow a shared CLI pattern.
--fix: apply edits instead of advisory reporting.--diff: show unified diff for applied edits.--out <file>: with--fix, write transformed output to a separate file (single-input mode).--backup/--no-backup: control.bakbackup creation when editing in place.--exclude <glob>: skip matching files; repeatable.--compiler "<cmd>": run compile validation (baseline/after-fixwhere supported).--verbose: print per-file details and/or full suggestions.--limit <n>: cap number of files processed in a run (where supported).--resume: continue from prior state for harness-style scripts (where supported).--loop,--max-loop: rerun harness cycles with bounded retries (where supported).
Suggests and optionally applies missing intent attributes on dummy arguments.
Core use cases:
- add
intent(in)where argument appears read-only - optionally add
intent(out)with--suggest-intent-out - optionally add
intent(in out)with--suggest-intent-inout - warn about unresolved arguments with
--warn-missing-intent
Typical commands:
python xintent.py
python xintent.py --fix --iterate --compiler "gfortran -o foo.exe"
python xintent.py --fix --infer-by-compile
python xintent.py --fix --iterate --suggest-intent-out --warn-missing-intent --compiler "gfortran -o foo.exe"
python xintent.py --fix --iterate --suggest-intent-inout --warn-missing-intent --compiler "gfortran -o foo.exe"Notes:
- Conservative analysis; ambiguous cases are left unchanged.
--infer-by-compileprovisionally adds remainingintent(in)candidates and keeps only edits that compile.--infer-by-compileimplies--fix; compile command defaults togfortran -c {files}and can be overridden with--compile-cmd(or--compiler).- Handles multi-entity declarations (for example
integer :: i, j) when adding intents. - Detailed inference rules are documented in intent.md and an example of module transformed by
xintent.pyis at intent_example.md.
Suggests and optionally applies pure to procedures not currently marked pure/elemental.
Optional elemental mode:
--suggest-elementalsuggests/upgrades eligiblepureprocedures toelemental.--suggest-impure-elementaladvisories procedures that may be markableimpure elemental(no fix mode).
Typical commands:
python xpure.py
python xpure.py --fix --iterate --compiler "gfortran -o foo.exe"
python xpure.py --fix --iterate --suggest-elemental --compiler "gfortran -o foo.exe"
python xpure.py --suggest-impure-elementalNotes:
- Uses conservative purity checks (calls, assignments, I/O, control statements, etc.).
- Internal I/O is treated differently from external I/O.
- On compile failure after fix, modified files can be rolled back from backups.
--suggest-impure-elementalis advisory-only and cannot be combined with--fix.
Suggests and optionally applies private :: name inside modules.
It considers module entities, including procedures and module-scope declarations (variables/constants/types/procedures).
Typical commands:
python xprivate.py
python xprivate.py --fix --iterate --compiler "gfortran -o foo.exe"Notes:
- Suggest mode is conservative around wildcard imports.
- Fix mode is compile-validated and reverts candidate edits that break compilation.
Pipeline wrapper for:
xintent.py(--fix --iterate)xpure.py(--fix --iterate)- optional
xpure.py --suggest-elemental
Typical command:
python xintent_pure.py --suggest-intent-out --suggest-elemental --compiler "gfortran -o foo.exe"Compile-validated pruning tool that removes likely unused top-level procedures.
By default, it writes a working copy of sources to pruned/ and applies pruning there.
Use --in-place only when you explicitly want to modify the current source tree.
Typical commands:
python xprune.py --compiler "gfortran -o foo.exe"
python xprune.py --compiler "gfortran -o foo.exe" --out-dir pruned_stats
python xprune.py --compiler "gfortran -o foo.exe" --in-placeNotes:
- Pruning is conservative and compile-validated (
baseline,trial,finalcompile passes). - The tool removes accepted procedures and updates matching
publiclists for removed names. - If a trial removal breaks compilation, it is reverted immediately.
Suggests and optionally inserts implicit none in:
- each
program - each
module(inserted beforecontainswhen present) - external procedures outside modules
It intentionally does not add implicit none to procedures contained inside modules, because module-level implicit none already covers them.
Typical commands:
python ximplicit_none.py
python ximplicit_none.py --fix
python ximplicit_none.py --fix --compiler "gfortran -o foo.exe"Suggests and optionally rewrites broad imports such as:
use foo
to explicit imports such as:
use foo, only: func_a, sub_b
Typical commands:
python xuse_only.py
python xuse_only.py --fix
python xuse_only.py --fix --compiler "gfortran -o foo.exe"Notes:
- Conservative analysis across source files using discovered module exports and identifier usage.
- In
--fixmode, compile checks can be used (baselineandafter-fix) with rollback on failure. - Renamed imports (
=>) are handled conservatively and may be skipped.
Full pipeline wrapper for:
- intent
- pure
- optional elemental
- private
Typical command:
python xintent_pure_private.py --suggest-intent-out --suggest-elemental --compiler "gfortran -o foo.exe"Advisory checker for likely use-before-set variables in procedures/program units.
Typical commands:
python xunset.py
python xunset.py stats.f90 --verboseNotes:
- Advisory only (no
--fix). - Conservative static analysis; best used with manual review.
- Tracks partial array initialization with element-level diagnostics (rank 1-3 when extents are inferable).
- Checks allocatable-use state (
allocate/deallocate) and warns on uses while unallocated. - Treats inquiry intrinsics (for example
size,lbound,ubound,shape,kind,rank,allocated) as non-value reads.
Advisory checker for likely unused set variables/constants.
Optional modes:
--fix: apply conservative declaration/assignment removals when safe--warn-dead-store: also report likely dead stores (overwritten-before-read / final unread write)
Typical commands:
python xunused.py
python xunused.py --warn-dead-store --verbose
python xunused.py --fix --backupNotes:
--fixis conservative by design and skips unsafe edits.- Dead-store warnings are advisory and branch-aware for
if/elseflows.
Advisory checker for variables that may be converted to named constants (parameter).
Optional modes:
--fix: conservative auto-fix for single-entity declarations--annotate: insert suggestion comments (or tag changed declarations with--fix)--fix-all: more aggressive auto-fix that may split multi-entity declarations--fix-alloc: allow eligibleallocatablearrays to be promoted toparameter--diff: with fix modes, print unified diffs for changed files
Typical commands:
python xparam.py
python xparam.py foo.f90 --verbose
python xparam.py foo.f90 --fix
python xparam.py foo.f90 --annotate
python xparam.py foo.f90 --fix-all
python xparam.py foo.f90 --fix-all --fix-alloc
python xparam.py foo.f90 --fix --annotate --diffNotes:
- Fix modes create backups before editing (
.bak,.bak1, ...). --fixand--fix-allrun recursively by default (re-analyze and re-apply) until no more variables can be converted.- During fixes, generated
parameterdeclarations are reordered as needed so dependencies are declared before use. - By default,
allocatabledeclarations are excluded; use--fix-allocto opt in. - Full rule details are documented in param.md.
Warns about consecutive lines of code (optionally separated by comments) that test the same if condition.
Optional mode:
--fix: rewrite repeated single-line IF pairs into oneif (...) then ... end ifblock--diff: with--fix, print unified diffs for changed files
Typical commands:
python xrepeated_if.py
python xrepeated_if.py foo.f90 --verbose
python xrepeated_if.py foo.f90 --fix
python xrepeated_if.py foo.f90 --fix --diffWarns when functions contain external output statements (print, write(*,...)).
Fix strategy options (mutually exclusive):
--fix-msg--fix-msg-error-stop--fix-msg-error-stop-block--fix-unit--fix-unit-error-stop--fix-suppress--fix-error-stop--diff: print unified diffs for changed files
Typical commands:
python xfunc_print.py
python xfunc_print.py foo.f90 --verbose
python xfunc_print.py foo.f90 --fix-msg --diff
python xfunc_print.py foo.f90 --fix-msg-error-stop-block --diff
python xfunc_print.py foo.f90 --fix-unit-error-stop --diff
python xfunc_print.py foo.f90 --fix-suppress --diffNotes:
- Fix strategies are intentionally explicit and mutually exclusive.
- Detailed strategy behavior and caveats are documented in func_print.md.
Warns about likely needless trim(...) in string ==//= (.eq./.ne.) comparisons.
Optional modes:
--fix: remove needlesstrim(var)wrappers in high-confidence comparison forms--diff: with--fix, print unified diffs for changed files
Typical commands:
python xnotrim.py
python xnotrim.py foo.f90 --verbose
python xnotrim.py foo.f90 --fix
python xnotrim.py foo.f90 --fix --diffUtility for test preparation by stripping annotations.
Typical commands:
python xstrip.py --strip all
python xstrip.py --strip intent --strip-value
python xstrip.py --strip pureBy default summary output is off; enable with --summary.
Utility to remove implicit none statements for testing ximplicit_none.py.
Typical commands:
python xstrip_implicit_none.py --fix
python xstrip_implicit_none.py foo.f90 --fix --diffUtility to remove only: clauses from use statements for testing xuse_only.py.
Typical commands:
python xstrip_use_only.py --fix
python xstrip_use_only.py foo.f90 --fix --diffAdvisory checker for local allocatables that may be safely deallocated earlier.
Optional modes:
--annotate: insert suggestions from current findings.--fix: convert existing! deallocate (...) !! suggested by xdealloc.pycomments to activedeallocate (...)statements.--annotate --fix: insert activedeallocate (...) !! suggested by xdealloc.pylines directly from findings.
Typical commands:
python xdealloc.py
python xdealloc.py foo.f90 --verbose
python xdealloc.py foo.f90 --annotate
python xdealloc.py foo.f90 --fix
python xdealloc.py foo.f90 --annotate --fixNotes:
- Suggestions are conservative and skip common unsafe cases (for example function result variables, loop-local last uses, near-unit-end structural-only tails).
- Edit modes create backups before modifying files (
.bak,.bak1, ...).
Advisory checker/fixer for shorten-able Fortran format literals in print/write statements.
Optional modes:
--fix: apply conservative rewrites (for example(a,a,a,i0,a,i0,a)->(3a,2(i0,a))).--diff: with--fix, print unified diffs for changed files.
Typical commands:
python xformat.py
python xformat.py foo.f90 --verbose
python xformat.py foo.f90 --fix
python xformat.py foo.f90 --fix --diffNotes:
- Current matching is conservative and focuses on string-literal format specs.
- Fix mode rewrites only unambiguous matches and creates backups before edits.
Advisory checker for simple indexed do loops that perform one non-advancing write(..., advance="no") per iteration and can be collapsed.
Optional mode:
--annotate: add suggestion comments after matching loops:! write (...) ... !! suggested by xadvance.py
Typical commands:
python xadvance.py
python xadvance.py foo.f90 --verbose
python xadvance.py foo.f90 --annotateNotes:
- Suggestions use single-write forms with unlimited-repeat formats when a literal format is available (for example
"(*(1x,f12.6))"). - Array-section output is suggested when possible; otherwise implied-do output is suggested.
--annotatecreates backups before edits.
Advisory checker for runs of consecutive scalar element assignments that can be replaced by one array-constructor assignment.
Optional mode:
--fix: apply suggested rewrites in-place.--annotate: insert suggestion comments after the candidate lines (or tag changed lines with--fix).--diff: with--fix, print unified diffs for changed files.--vector-subscript: also suggest/fix non-consecutive element assignments using vector subscripts.
Typical commands:
python xset_array.py
python xset_array.py foo.f90 --verbose
python xset_array.py foo.f90 --annotate
python xset_array.py foo.f90 --vector-subscript --verbose
python xset_array.py foo.f90 --fix --annotate --diffNotes:
- By default, suggestions use explicit section LHS (for example
x(1:4) = [...]). - When full bounds are clearly covered, suggestions use whole-array LHS (for example
x = [...]). - Detects vectorizable forms such as
f(a(i))and suggestsf(a)/f(a(lo:hi))when safe.
Advisory checker for simple do loops that can be replaced with array operations.
Optional mode:
--fix: apply suggested rewrites in-place.--annotate: insert marked replacement blocks and suggested array-operation lines (or tag changed lines with--fix).--diff: with--fix, print unified diffs for changed files.
Typical commands:
python xarray.py
python xarray.py foo.f90 --verbose
python xarray.py foo.f90 --annotate
python xarray.py foo.f90 --fix --annotate --diffNotes:
- Current conservative patterns include:
- elementwise loops (
c(i)=...), sumreductions,productreductions,- masked
sumreductions, countpatterns,minval/maxvalreductions,minloc/maxlocindex-tracking reductions (strict</>patterns).
- elementwise loops (
- Supports simple strided loops (
do i=lb,ub,step) in supported reduction patterns. - Avoids recurrence-style false positives (for example
y(i)=y(i-1)+...). - Edit modes create backups before edits.
Advisory checker/fixer that rewrites selected array expressions/intrinsics back to explicit loops.
Optional modes:
--fix: apply loopifying rewrites.--out/--out-dir: write transformed sources to a file/directory.--run,--run-both,--run-diff: compile/run transformed and optionally compare outputs.--time-both,--time-reps: benchmark original vs transformed executables.--no-annotate: suppress replacement comments in emitted code.
Typical commands:
python xto_loop.py
python xto_loop.py foo.f90 --out foo_loop.f90 --run-diff
python xto_loop.py src\\*.f90 --out-dir loop_out --compile-bothNotes:
- Intended as a conservative inverse companion to
xarray.py. - Includes residual checks for prohibited array-operation forms in loopified output.
Round-trip harness for semantic regression checks between array-style and loop-style rewrites.
Optional modes:
--direction array-loop|loop-array|both: choose transform order.--tee,--tee-all: print intermediate generated sources.--keep: preserve generated intermediate files/directories.
Typical commands:
python xroundtrip.py foo.f90
python xroundtrip.py foo.f90 --direction both --tee-all
python xroundtrip.py src\\*.f90 --limit 20Notes:
- Reports per-file pass/fail with mismatch details and final transformed path.
- Useful for validating transform reversibility and catching behavioral regressions.
Advisory checker/fixer that inserts explicit initializations (for example NaN/sentinels) to expose uninitialized-variable behavior.
Optional modes:
--fix: apply inserted initialization statements.--uncertain: initialize only variables flagged as uncertain by static analysis.--out/--out-dir: write transformed file(s) to target path(s).--compiler: compile baseline and transformed code for validation.
Typical commands:
python xinit.py foo.f90 --fix
python xinit.py foo.f90 --out temp.f90 --uncertain --compiler "gfortran -c -Wfatal-errors {file}"
python xinit.py src\\*.f90 --out-dir init_out --uncertainNotes:
- Defaults are configurable for integer/real/logical/character initialization values.
- Designed for debugging undefined behavior from unset variables.
Procedure indexing/report tool that scans file sets and reports discovered procedure names, locations, and duplicates.
Optional modes:
- file globs/directories as inputs (including recursive selections where supported),
- duplicate-focused reporting and sorted summaries.
Typical commands:
python xproc_index.py
python xproc_index.py burkardt\\*.f90
python xproc_index.py src --verboseNotes:
- Useful for identifying duplicate helper procedures across large source collections.
- Designed as a lightweight inventory tool for refactoring/modularization workflows.
Extractor that lifts marked code regions (or selected loops) into generated module procedures/functions.
Optional modes:
- marker-driven extraction (
!! begin .../!! end ...) with module/procedure naming, - function/subroutine generation with argument/local inference,
--compiler-cmd,--run,--run-bothvalidation workflows,--inline,--loop-linesautomation helpers.
Typical commands:
python xsubroutine.py foo.f90 --out temp.f90
python xsubroutine.py foo.f90 --compiler-cmd "gfortran {file}" --run-both
python xsubroutine.py foo.f90 --loop-lines 5 --fixNotes:
- Applies structural checks on marker placement and scope boundaries.
- Can infer/insert
purewhere safe and updates caller/use sites.
Advisory checker/fixer for repeated multiplication of the same operand (for example x*x) that can be rewritten as power form (x**2).
Optional modes:
--fix: apply in-place rewrites.--annotate: with--fix, append!! changed by xpower.pyon changed lines.--diff: with--fix, print unified diffs for changed files.
Typical commands:
python xpower.py
python xpower.py foo.f90 --verbose
python xpower.py foo.f90 --fix
python xpower.py foo.f90 --fix --annotate --diffAdvisory checker/fixer for single-use local scalar temporaries that can be inlined.
Optional modes:
--fix: inline safe candidates and remove now-unused declaration entities.--annotate: with--fix, add declaration comments such as!! x, y removed by xno_variable.py.
Typical commands:
python xno_variable.py
python xno_variable.py foo.f90 --verbose
python xno_variable.py foo.f90 --fix
python xno_variable.py foo.f90 --fix --annotate --verboseNotes:
- Includes a safety check that blocks invalid inlining when RHS dependencies are reassigned between temp definition and use (for example swap patterns).
- Fix mode creates backups before edits.
Advisory checker for redundant deallocate(...) statements on local allocatables near program-unit end.
Optional mode:
--annotate: append inline comments such as!! xdealloc_tail.py suggests deleting this line.
Typical commands:
python xdealloc_tail.py
python xdealloc_tail.py foo.f90 --verbose
python xdealloc_tail.py foo.f90 --annotateNotes:
- Focuses on local allocatables and tail-position deallocations with no meaningful trailing work.
--annotatecreates backups before edits.
Advisory checker for identifiers that collide with Fortran keywords or intrinsic names.
Optional mode:
--verbose: print full offending statements/contexts.
Typical commands:
python xnames.py
python xnames.py foo.f90 --verboseNotes:
- Advisory only (no
--fix).
Advisory checker/fixer for hard-coded kind numbers.
Optional modes:
--fix: apply in-place rewrites.--annotate: with--fix, append!! changed by xkind.pyon changed lines.--diff: with--fix, print unified diffs for changed files.
Typical commands:
python xkind.py
python xkind.py foo.f90 --verbose
python xkind.py foo.f90 --fix --annotate --diffNotes:
- Handles suffix kinds (
0_8,1.0_8), selector kinds (kind=8,real(8)), and kind-parameter constants (for exampledp = 8when used in kind selectors). - In module scope, fix mode can introduce module-level
xkind_*named kind constants and rewrite literals/selectors to use them.
Advisory checker/fixer for redundant allocate(...) before assignment-driven allocation opportunities.
Optional modes:
--fix: comment out redundant allocate lines.--annotate: annotate findings; with--fix, append!! commented out by xalloc_assign.py.--diff: with--fix, print unified diffs for changed files.
Typical commands:
python xalloc_assign.py
python xalloc_assign.py foo.f90 --verbose
python xalloc_assign.py foo.f90 --fix --annotate --diffNotes:
- Conservative by design (skips unsafe patterns).
- Handles single-object and multi-object
allocate(...)statements, removing only the redundant objects when possible. - Can rewrite eligible contiguous slice-constructor assignments (for example
a(1:n) = [...]) to whole-array assignment when needed for safe allocate-on-assignment conversion. - When shape would be lost after removing
allocate(var(1)), fix mode can rewrite scalar assignment to singleton constructor form (for examplevar = [0.0_dp]).
Practical transpiler from a supported C subset to compilable free-form Fortran, with conservative cleanup passes.
Usage:
python xc2f.py xfactors.c --out xfactors.f90The C directory has examples of C codes and their translations.
Notes:
- Uses
pycparserAST lowering and emits module/program Fortran structure. - Applies post-processing passes to improve generated Fortran readability and safety (for example declaration/allocate coalescing, redundant-syntax cleanup, constant promotion, and allocation-on-assignment rewrites where safe).
- Supports generation patterns validated on representative examples such as factors/matmul-style C sources.
Batch harness for evaluating how many C sources can be transpiled by xc2f.py and built successfully.
Typical commands:
python xc2f_batch_test.py --root c:\\c\\public_domain\\github\\jburkardt-c --limit 50
python xc2f_batch_test.py --limit 10 --sort-size --out-dir _xc2f_batch_smoke --verboseNotes:
- Can sort by source size to try smaller/easier files first.
- Can skip cases where baseline C build fails.
- Produces per-file status summary and failure diagnostics.
Practical transpiler from a supported free-form Fortran subset to C, with optional build/run checks.
Typical commands:
python xf2c.py foo.f90 --out foo.c
python xf2c.py foo.f90 --run-both
python xf2c.py src\\*.f90 --mode-each --compile-both --summaryNotes:
- Supports single-file and multi-file processing (
--mode each|combined). - Includes options for compile-only and run comparisons (
--compile,--compile-c,--compile-both,--run-both). - Emits C helpers for selected Fortran intrinsics/patterns where needed.
Practical transpiler from a supported Python subset to free-form Fortran.
Typical commands:
python xp2f.py foo.py
python xp2f.py foo.py python.f90 --compile
python xp2f.py foo.py python.f90 --run-both --time-bothNotes:
- Supports helper-module inputs (for example
python.f90) and optional auto-helper resolution. - Includes compile/run workflows and output-diff/timing modes for validation.
Batch harness for running xp2f.py over many Python files/globs.
Typical commands:
python xp2f_batch.py "xfit_mix*.py" --helpers python.f90 --time-both
python xp2f_batch.py src\\*.py --helpers python.f90 --verboseNotes:
- Expands globs, runs cases independently, and prints per-file PASS/FAIL summary.
- Useful for smoke/regression sweeps of transpiler coverage.
Practical transpiler from supported free-form Fortran to Python.
Typical commands:
python xf2p.py foo.f90
python xf2p.py foo.f90 --run-both
python xf2p.py mod.f90 main.f90 --mode-program --runNotes:
- Supports per-file and multi-file program modes.
- Includes run/compile comparison workflows and timing/diff options.
Practical transpiler from a supported R subset to free-form Fortran.
Typical commands:
python xr2f.py foo.r
python xr2f.py foo.r r.f90 --run-both
python xr2f.py foo.r r.f90 --time-bothNotes:
- Supports helper-module inputs (for example
r.f90) for runtime/stat/RNG helpers. - Includes conservative rewrites and run/compare workflows.
Transpiler from a supported Octave/MATLAB-like subset to free-form Fortran.
Typical commands:
python xoct2f.py foo.m
python xoct2f.py foo.m --run-bothNotes:
- Intended for practical numeric-script subsets; unsupported constructs are reported conservatively.
Validator for free-form Fortran source legality using lightweight static checks.
Typical commands:
python xlegal.py foo.f90
python xlegal.py src\\*.f90Notes:
- Reports unrecognized statements and basic structural mismatches.
- Includes implicit-none/declaration sanity checks and duplicate definition/declaration detection.
- Intended as a fast preflight gate for transformation/transpilation workflows.
Conservative auto-fixer for common structural/typo issues detected in Fortran code.
Typical commands:
python xfix.py foo.f90 --out fixed.f90
python xfix.py src\\*.f90 --fixNotes:
- Repairs selected end-statement name mismatches and simple unambiguous parenthesis issues.
- Can remove duplicate procedure definitions (keeping the last) and duplicate declarations (keeping the first), with reporting.
- Complements
xlegal.pyby applying safe automated corrections where possible.
Coalesce adjacent compatible declarations and contiguous public/private lists.
Typical commands:
python xcombine_decl.py foo.f90
python xcombine_decl.py foo.f90 --fix
python xcombine_decl.py src\\*.f90 --fix --max-len 80Indent Fortran sources and wrap long lines with shared formatting rules.
Typical commands:
python xindent.py foo.f90 --fix
python xindent.py foo.f90 --fix --indent 3 --indent-proc --indent-moduleNotes:
- Supports indentation toggles for procedures/modules/programs/contains sections.
Rewrite procedure calls to use named arguments for literals/optional dummies and late positional arguments.
Typical commands:
python xnamed_arg.py foo.f90
python xnamed_arg.py foo.f90 --fix
python xnamed_arg.py code1.f90 code2.f90 --fix --max-positional 3Rewriter for error stop diagnostics:
- Appends source location tags to literal
error stop "..."messages. - Optional
--condition-valuesmode rewrites valid IF-guarded error-stop forms to include values from the condition. - Location tags can include scope context (module/procedure) and line, for example
file.f90::module m::function f::line 42.
Typical commands:
python xerror_loc.py foo.f90
python xerror_loc.py foo.f90 --fix
python xerror_loc.py foo.f90 --condition-values --fix
python xerror_loc.py foo.f90 --out transformed.f90 --run
python xerror_loc.py foo.f90 --run-both --tee-bothNotes:
- Uses shared line-wrapping logic (
fortran_scan.py) with--max-len(default 80). - Conservative by default: skips unsupported/non-literal
error stopforms and suspicious invalid IF patterns. - Supports compile/run and source preview flows via
--run,--run-both,--tee, and--tee-both.
Advisory checker for likely out-of-bounds array index/slice patterns.
Optional mode:
--verbose: print statements and diagnostic details.
Typical commands:
python xbounds.py
python xbounds.py foo.f90 --verboseNotes:
- Advisory only (no
--fix). - Uses conservative guard inference (for example
size(...)checks, alias guards, loop bounds).
Advisory checker/fixer for three-line IF blocks that can be collapsed to one-line IF, with optional reverse expansion.
Optional modes:
--fix: apply rewrite.--annotate: insert suggestion comments.--diff: with edits, print unified diffs.--reverse: operate in reverse (one-line IF -> 3-line block).
Typical commands:
python xone_line_if.py
python xone_line_if.py foo.f90 --verbose
python xone_line_if.py foo.f90 --fix --diff
python xone_line_if.py foo.f90 --reverse --fix --diffAdvisory checker/fixer for lines longer than a configurable maximum (default 100).
Optional modes:
--max-len N: set length threshold (default100).--fix: wrap long lines with continuation (&) where safe.--diff/-diff: with--fix, print unified diffs.--verbose: print full overlong lines.
Typical commands:
python xlong_lines.py
python xlong_lines.py foo.f90 --max-len 100 --verbose
python xlong_lines.py foo.f90 --fix --diffAdvisory checker/fixer for optional-defaulting idioms that can be rewritten with optval(...) from stdlib_optval.
Optional modes:
--fix: apply in-place rewrites and insertuse stdlib_optval, only: optvalwhere needed.--annotate: insert suggestion comments (or add!! changed by xoptval.pyon changed lines with--fix).--diff: with--fix, print unified diffs for changed files.--verbose: print full findings with source context.
Typical commands:
python xoptval.py
python xoptval.py foo.f90 --verbose
python xoptval.py foo.f90 --fix --diff
python xoptval.py foo.f90 --fix --annotate --diffNotes:
- Handles common patterns such as:
x = default; if (present(arg)) x = argif (present(arg)) then; x = arg; else; x = default; end if
- In fix mode, required
use stdlib_optval, only: optvalimport is kept in the module/specification part (beforeimplicit none).
Advisory checker/fixer for simple if/else assignment blocks that can be replaced by merge(...).
Optional modes:
--fix: apply conservative in-place rewrites.--annotate: insert suggestion comments (or add!! changed by xmerge.pyon changed lines with--fix).--diff/-diff: with--fix, print unified diffs for changed files.--verbose: print full suggestions.
Typical commands:
python xmerge.py
python xmerge.py foo.f90 --verbose
python xmerge.py foo.f90 --annotate
python xmerge.py foo.f90 --fix --annotate --diffNotes:
- Matching is intentionally strict: one-statement-per-line, contiguous 5-line
if/else/end ifblocks assigning the same LHS in both branches. - Rewrites are skipped for known unsafe cases, including:
present(...)-guarded optionals referenced in either source expression,- string-literal branch values with unequal character lengths,
- complex branch expressions outside the supported simple-source subset.
Advisory checker/fixer for declaration statements that omit ::.
Typical commands:
python xdecl.py
python xdecl.py foo.f90 --verbose
python xdecl.py foo.f90 --fix --diffAdvisory checker/fixer that replaces plain end with named forms such as end subroutine foo, end function bar, end module m.
Typical commands:
python xend_name.py
python xend_name.py foo.f90 --verbose
python xend_name.py foo.f90 --fix --diffAdvisory checker/fixer for spacing/layout normalization rules (parenthesis spacing, blank-line normalization, procedure separation, and related formatting cleanup).
Typical commands:
python xspace.py
python xspace.py foo.f90 --verbose
python xspace.py foo.f90 --fix --diff
python xspace.py foo.f90 --fix --disable 2,4Reads Burkardt-style argument comment blocks and applies matching intent(in), intent(out), or intent(in out) to declarations.
Typical commands:
python xburkardt.py
python xburkardt.py starpac.f90 --verboseInformational checker: detects procedures outside modules, wraps them into a temporary generated module in temp.f90, and compile-checks the wrapped file.
Typical commands:
python xmodule.py foo.f90
python xmodule.py --codes codes.txt --compile-cmd "gfortran -c {file}"
python xmodule.py c:\fortran\**\*.f90 --verboseConverts fixed-form .f sources to free-form .f90 in the same directory, with optional compile regression checks.
Typical commands:
python xfree.py foo.f
python xfree.py c:\fortran\lapack --recursive --overwrite
python xfree.py c:\fortran\lapack --recursive --overwrite --check --fail-fastTransform harness: copy source to temp.f90, baseline compile, run transform command, post-transform compile, and stop/report on transform or post-compile failure.
Typical commands:
python xtest.py --transform-cmd "python xintent.py --fix"
python xtest.py --transform-cmd "python xpure.py --fix" --compile-cmd "gfortran -c -w -fmax-errors=1 {file}" --codes codes.txt
python xtest.py --transform-cmd "python xintent.py --fix" --resume --loop --max-loop 20Compile-only harness for file lists/globs, with resume/loop controls and optional fast-fail mode.
Typical commands:
python xcompile.py --codes codes.txt
python xcompile.py --codes codes.txt --compile-cmd "gfortran -c -O0 -Wall {file}"
python xcompile.py --codes codes.txt --resume --limit 500
python xcompile.py --codes codes.txt --fast-failParses xcompile.py output logs and summarizes warning/error kinds by file count, source-line count, and total hits.
Typical commands:
python xerror.py
python xerror.py burkardt_errors.txtSorts a newline-delimited source list (for example codes.txt) by file size ascending.
Typical commands:
python xsort_size.py codes.txt
python xsort_size.py codes.txt --output codes_size_sorted.txtReports long-option inventories for x*.py scripts (option count plus names).
Typical commands:
python xoptions.py
python xoptions.py xintent.py xpure.py xarray.pyAdvisory finder for repeated IF conditions and repeated expressions in straight-line blocks.
Typical commands:
python xrepeat.py
python xrepeat.py foo.f90 --verboseBuild-only harness for source-file sets, where each line in --codes is one build set (one or more source files).
It attempts to build an executable for each set and reports failures with resume/silent controls.
Typical commands:
python xbuild.py --codes codes.txt --compile-cmd "gfortran -w -Wfatal-errors {files}"
python xbuild.py --codes c:\python\fortran\burkardt\codes.txt --code-dir c:\python\fortran\burkardt --silent --maxfail 10 --compile-cmd "gfortran -w -Wfatal-errors {files}"
python xbuild.py --codes codes.txt --resume --silent --maxfail 0Notes:
--compile-cmdsupports{files},{file}, and{exe}placeholders.- If
--compile-cmdomits{files}and{file}, all set files are appended automatically. - Defaults:
--state-file xbuild_state.json,--fail-log xbuild_fail.log,--exe-dir build_exe.
If applying all transformations, use this order:
implicit none(ximplicit_none.py)intent(xintent.py)pure(xpure.py)elemental(xpure.py --suggest-elemental)private(xprivate.py)- optional structural cleanup: tighten imports/prune (
xuse_only.py,xprune.py) - final cleanup/audit: unused values/dead stores (
xunused.py)
xintent_pure_private.py implements the intent/pure/elemental/private subset of this sequence.
- Conservative inference: if uncertain, tools usually do not edit.
- Compile checks: use
--compilerso edits are validated. - Backups: keep
.bakfiles unless--no-backupis requested. - Rollback: fix flows attempt restoration when post-edit compilation fails.
These are static heuristics, not full Fortran semantic compilers. Expect some false negatives (and occasional false positives that compile checks catch), especially around:
- indirect/global state effects
- polymorphic dispatch and procedure pointers
- complex host association and interface patterns
- project-specific build systems not represented by a single compiler command
python xintent.py
python xpure.py
python xprivate.py
python ximplicit_none.pypython xprune.py --compiler "gfortran -o foo.exe"This writes pruned sources to pruned/ by default.
python xintent_pure_private.py --suggest-intent-out --suggest-elemental --compiler "gfortran -o foo.exe"--compiler accepts either:
- a command where file paths are appended automatically, or
- a template using
{files}placeholder.
Examples:
--compiler "gfortran -o foo.exe"
--compiler "gfortran -J build/mod -o foo.exe {files}"For tools that modify source, --git can auto-commit changed files with an informative message.
Use this only when your working tree state is ready for automatic commits.
python xintent_pure_private.py --compiler "gfortran -o foo.exe" --suggest-intent-out --suggest-elemental
on the source files in the original directory gave the source code in the revised directory and the terminal
output below.
=== Intent Phase ===
Command: c:\Programs\Python313\python.exe xintent.py kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90 --fix --iterate --max-iter 10 --compiler gfortran -o foo.exe --backup --suggest-intent-out
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): PASS
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
=== Pure Phase ===
Command: c:\Programs\Python313\python.exe xpure.py kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90 --fix --iterate --max-iter 10 --compiler gfortran -o foo.exe --backup
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): PASS
Backup written: util.f90.bak
Applied PURE to 6 procedure declaration(s).
Backup written: stats.f90.bak
Applied PURE to 17 procedure declaration(s).
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Backup written: stats.f90.bak
Applied PURE to 2 procedure declaration(s).
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
Summary of 12 functions and 1 subroutine marked pure in 2 source files:
stats.f90 6 functions: arcoef loglik fit_lnorm fit_laplace hyperb_var hyperb_scale_from_sd
stats.f90 1 subroutine: unpack_params
util.f90 6 functions: arange grid replace rep_vec matrix reverse
=== Elemental Phase ===
Command: c:\Programs\Python313\python.exe xpure.py kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90 --fix --iterate --max-iter 10 --compiler gfortran -o foo.exe --backup --suggest-elemental
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): PASS
Backup written: stats.f90.bak
Applied ELEMENTAL to 18 procedure declaration(s).
Backup written: interpret.f90.bak
Applied ELEMENTAL to 1 procedure declaration(s).
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS
Summary of 19 functions and 0 subroutines marked elemental in 2 source files:
interpret.f90 1 function: lower_str
stats.f90 18 functions: hyperb_pdf_scalar hyperb_int inv_norm besseli0 besseli1 besselk0 besselk1 log1pexp log_beta hyperb_scale_from_sd hyperb_var tcdf betai chisq_cdf gammp gser gcf betacf
=== Private Phase ===
Command: c:\Programs\Python313\python.exe xprivate.py kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90 --fix --iterate --max-iter 10 --compiler gfortran -o foo.exe --backup
Processing order: kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (baseline): PASS
Backup written: constants.f90.bak
Backup written: gnuplot.f90.bak
Backup written: interpret.f90.bak
Backup written: kind.f90.bak
Backup written: qsort.f90.bak
Backup written: random.f90.bak
Backup written: stats.f90.bak
Backup written: util.f90.bak
Compile (after-fix): gfortran -o foo.exe kind.f90 constants.f90 qsort.f90 util.f90 gnuplot.f90 random.f90 stats.f90 interpret.f90 xinterpret.f90
Compile (after-fix): PASS