-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxf2p.py
More file actions
5714 lines (5332 loc) · 237 KB
/
Copy pathxf2p.py
File metadata and controls
5714 lines (5332 loc) · 237 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import ast
import sys
import argparse
import subprocess
import shlex
import time
import difflib
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass
from typing import cast
def split_fortran_comment(line: str) -> tuple[str, str]:
in_str = False
quote = ""
out: list[str] = []
for ch in line:
if in_str:
out.append(ch)
if ch == quote:
in_str = False
else:
if ch in ("'", '"'):
in_str = True
quote = ch
out.append(ch)
elif ch == "!":
code = "".join(out).rstrip()
comment = line[len("".join(out)) + 1 :].strip()
return code, comment
else:
out.append(ch)
return "".join(out).rstrip(), ""
@dataclass
class UseSpec:
module: str
only_items: list[str] | None
intrinsic: bool = False
def _replace_identifier_outside_strings(code: str, old: str, new: str) -> str:
out: list[str] = []
i = 0
n = len(code)
in_str = False
quote = ""
pat = re.compile(rf"(?i)\b{re.escape(old)}\b")
while i < n:
ch = code[i]
if in_str:
out.append(ch)
if ch == quote:
in_str = False
i += 1
continue
if ch in ("'", '"'):
in_str = True
quote = ch
out.append(ch)
i += 1
continue
j = i
while j < n and code[j] not in ("'", '"'):
j += 1
out.append(pat.sub(new, code[i:j]))
i = j
return "".join(out)
def _choose_fresh_identifier(src: str, base: str) -> str:
ids: set[str] = set()
for raw in src.splitlines():
code, _comment = split_fortran_comment(raw)
ids.update(m.group(0).lower() for m in re.finditer(r"\b[a-z_]\w*\b", code, re.I))
cand = base
while cand.lower() in ids:
cand += "_"
return cand
def _preprocess_fortran_source(src: str) -> str:
ids: set[str] = set()
for raw in src.splitlines():
code, _comment = split_fortran_comment(raw)
ids.update(m.group(0).lower() for m in re.finditer(r"\b[a-z_]\w*\b", code, re.I))
if "lambda" not in ids:
return src
repl = _choose_fresh_identifier(src, "lambda_")
out_lines: list[str] = []
for raw in src.splitlines():
code, comment = split_fortran_comment(raw)
new_code = _replace_identifier_outside_strings(code, "lambda", repl)
if comment:
if new_code:
out_lines.append(f"{new_code} ! {comment}")
else:
out_lines.append(f"! {comment}")
else:
out_lines.append(new_code)
return "\n".join(out_lines)
def _clean_fortran_code_lines(src: str) -> list[str]:
out: list[str] = []
for raw in src.splitlines():
code, _c = split_fortran_comment(raw)
s = code.strip()
if s:
out.append(s)
return out
def _parse_file_interface(src: str) -> tuple[list[str], list[str], list[UseSpec]]:
"""Return (defined_modules, defined_symbols, use_specs) for one source."""
code_lines = _clean_fortran_code_lines(src)
defs: list[str] = []
mods: list[str] = []
uses: list[UseSpec] = []
in_module = False
in_module_contains = False
for s in code_lines:
sl = s.lower()
# module declarations (skip 'module procedure')
mm = re.match(r"^module\s+([a-z_]\w*)\b", sl, re.I)
if mm and not re.match(r"^module\s+procedure\b", sl, re.I):
mods.append(mm.group(1))
in_module = True
in_module_contains = False
continue
if re.match(r"^end\s+module\b", sl, re.I):
in_module = False
in_module_contains = False
continue
if in_module and sl == "contains":
in_module_contains = True
continue
# type declarations
mt = re.match(r"^type\s*(?:,\s*[^:]*)?::\s*([a-z_]\w*)\b", sl, re.I)
if mt:
defs.append(mt.group(1))
continue
# module declarative-part variables/parameters
if in_module and not in_module_contains:
pd = parse_decl(s)
if pd:
_ftype, attrs, rest = pd
for nm, _shape, _init in parse_decl_items(rest, parse_decl_attr_dimension(attrs)):
defs.append(nm)
continue
td = re.match(r"^type\s*\(\s*([a-z_]\w*)\s*\)\s*(.*?)::\s*(.*)$", s, re.I)
if td:
attrs = td.group(2).strip()
for nm, _shape, _init in parse_decl_items(td.group(3).strip(), parse_decl_attr_dimension(attrs)):
defs.append(nm)
continue
# function declarations
mf = re.match(
r"^(?!\s*end\s+function\b)\s*(?:(?:pure|elemental|recursive)\s+)*(?:\w+(?:\s*\([^)]*\))?\s+)*function\s+([a-z_]\w*)\s*\(",
sl,
re.I,
)
if mf:
defs.append(mf.group(1))
continue
# subroutine declarations
ms = re.match(
r"^(?!\s*end\s+subroutine\b)\s*(?:(?:pure|elemental|recursive)\s+)*subroutine\s+([a-z_]\w*)\s*\(",
sl,
re.I,
)
if ms:
defs.append(ms.group(1))
continue
# use statements
mu = re.match(r"^use\s*(?:,\s*intrinsic\s*)?(?:::)?\s*([a-z_]\w*)\s*(.*)$", sl, re.I)
if mu:
mod = mu.group(1)
tail = mu.group(2).strip()
intrinsic = bool(re.search(r"\bintrinsic\b", sl, re.I))
only_items: list[str] | None = None
mo = re.search(r"\bonly\s*:\s*(.+)$", tail, re.I)
if mo:
only_raw = mo.group(1).strip()
only_items = []
for it in split_args(only_raw):
nm = it.strip()
if not nm:
continue
# For USE renames, keep the local imported name (a => b -> keep a).
if "=>" in nm:
nm = nm.split("=>", 1)[0].strip()
nm = nm.strip()
if re.match(r"^[a-z_]\w*$", nm, re.I):
only_items.append(nm)
uses.append(UseSpec(module=mod, only_items=only_items, intrinsic=intrinsic))
continue
i = 0
n = len(code_lines)
while i < n:
s = code_lines[i].strip()
mgi = re.match(r"^interface(?:\s+([a-z_]\w*))?\s*$", s, re.I)
if not mgi:
i += 1
continue
gname = mgi.group(1)
block: list[str] = []
i += 1
while i < n and not re.match(r"^\s*end\s+interface\b", code_lines[i], re.I):
block.append(code_lines[i].strip())
i += 1
if i < n:
i += 1
if not gname:
continue
has_module_proc = any(re.match(r"^module\s+procedure\b", b, re.I) for b in block)
if has_module_proc:
defs.append(gname)
return unique_preserve(mods), unique_preserve(defs), uses
def _extract_generic_interfaces(lines: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], list[dict[str, list[str]]]]:
"""Extract generic interface blocks that name module procedures."""
filtered: list[tuple[str, str]] = []
generics: list[dict[str, list[str]]] = []
i = 0
n = len(lines)
while i < n:
s = lines[i][0].strip()
m = re.match(r"^interface(?:\s+([a-z_]\w*))?\s*$", s, re.I)
if not m:
filtered.append(lines[i])
i += 1
continue
gname = m.group(1)
block: list[tuple[str, str]] = []
i += 1
while i < n and not re.match(r"^\s*end\s+interface\b", lines[i][0], re.I):
block.append(lines[i])
i += 1
if i < n:
i += 1
procs: list[str] = []
for code, _comment in block:
mm = re.match(r"^\s*module\s+procedure\s+(.+)$", code.strip(), re.I)
if mm:
procs.extend([p.strip() for p in split_args(mm.group(1)) if p.strip()])
if gname and procs:
generics.append({"name": gname, "procedures": unique_preserve(procs)})
else:
filtered.append((s, ""))
filtered.extend(block)
filtered.append(("end interface", ""))
return filtered, generics
def _insert_imports(py_text: str, import_lines: list[str]) -> str:
if not import_lines:
return py_text
lines = py_text.splitlines()
insert_at = 0
while insert_at < len(lines):
s = lines[insert_at].strip()
if s.startswith("import ") or s.startswith("from "):
insert_at += 1
continue
if s == "":
insert_at += 1
break
break
merged = lines[:insert_at] + import_lines + ([""] if import_lines and (insert_at < len(lines) and lines[insert_at].strip() != "") else []) + lines[insert_at:]
return "\n".join(merged).rstrip() + "\n"
def collapse_fortran_continuations(raw_lines: list[tuple[str, str]]) -> list[tuple[str, str]]:
"""Collapse free-form continuation lines joined with trailing/leading '&'."""
out: list[tuple[str, str]] = []
i = 0
n = len(raw_lines)
while i < n:
code, comment = raw_lines[i]
cur_code = code.rstrip()
cur_comment = comment
while cur_code.rstrip().endswith("&"):
cur_code = cur_code.rstrip()
cur_code = cur_code[:-1].rstrip()
i += 1
if i >= n:
break
ncode, ncomment = raw_lines[i]
s = ncode.lstrip()
if s.startswith("&"):
s = s[1:].lstrip()
if cur_code and s:
cur_code = f"{cur_code} {s}"
else:
cur_code = cur_code + s
if ncomment.strip():
if cur_comment.strip():
cur_comment = f"{cur_comment.strip()} | {ncomment.strip()}"
else:
cur_comment = ncomment
out.append((cur_code, cur_comment))
i += 1
return out
def find_matching_paren(text: str, open_pos: int) -> int:
depth = 0
in_str = False
q = ""
for p in range(open_pos, len(text)):
ch = text[p]
if in_str:
if ch == q:
in_str = False
continue
if ch in ("'", '"'):
in_str = True
q = ch
continue
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return p
return -1
def split_args(s: str) -> list[str]:
args: list[str] = []
buf: list[str] = []
pdepth = 0
bdepth = 0
in_str = False
quote = ""
for ch in s:
if in_str:
buf.append(ch)
if ch == quote:
in_str = False
continue
if ch in ("'", '"'):
in_str = True
quote = ch
buf.append(ch)
continue
if ch == "(":
pdepth += 1
buf.append(ch)
continue
if ch == ")":
pdepth = max(0, pdepth - 1)
buf.append(ch)
continue
if ch == "[":
bdepth += 1
buf.append(ch)
continue
if ch == "]":
bdepth = max(0, bdepth - 1)
buf.append(ch)
continue
if ch == "," and pdepth == 0 and bdepth == 0:
arg = "".join(buf).strip()
if arg:
args.append(arg)
buf = []
continue
buf.append(ch)
tail = "".join(buf).strip()
if tail:
args.append(tail)
return args
def split_top_level(s: str, delim: str) -> list[str]:
parts: list[str] = []
buf: list[str] = []
pdepth = 0
bdepth = 0
in_str = False
quote = ""
i = 0
n = len(s)
while i < n:
ch = s[i]
if in_str:
buf.append(ch)
if ch == quote:
in_str = False
i += 1
continue
if ch in ("'", '"'):
in_str = True
quote = ch
buf.append(ch)
i += 1
continue
if ch == '(':
pdepth += 1
buf.append(ch)
i += 1
continue
if ch == ')':
pdepth = max(0, pdepth - 1)
buf.append(ch)
i += 1
continue
if ch == '[':
bdepth += 1
buf.append(ch)
i += 1
continue
if ch == ']':
bdepth = max(0, bdepth - 1)
buf.append(ch)
i += 1
continue
if ch == delim and pdepth == 0 and bdepth == 0:
parts.append(''.join(buf).strip())
buf = []
i += 1
continue
buf.append(ch)
i += 1
tail = ''.join(buf).strip()
if tail or not parts:
parts.append(tail)
return parts
def split_top_level_concat(s: str) -> list[str]:
parts: list[str] = []
buf: list[str] = []
pdepth = 0
bdepth = 0
in_str = False
quote = ""
i = 0
n = len(s)
while i < n:
ch = s[i]
if in_str:
buf.append(ch)
if ch == quote:
in_str = False
i += 1
continue
if ch in ("'", '"'):
in_str = True
quote = ch
buf.append(ch)
i += 1
continue
if ch == '(':
pdepth += 1
buf.append(ch)
i += 1
continue
if ch == ')':
pdepth = max(0, pdepth - 1)
buf.append(ch)
i += 1
continue
if ch == '[':
bdepth += 1
buf.append(ch)
i += 1
continue
if ch == ']':
bdepth = max(0, bdepth - 1)
buf.append(ch)
i += 1
continue
if i + 1 < n and s[i:i + 2] == '//' and pdepth == 0 and bdepth == 0:
parts.append(''.join(buf).strip())
buf = []
i += 2
continue
buf.append(ch)
i += 1
tail = ''.join(buf).strip()
if tail or not parts:
parts.append(tail)
return parts
def _fortran_unquote(s: str) -> str:
if len(s) >= 2 and s[0] == s[-1] and s[0] in ("'", "\""):
q = s[0]
return s[1:-1].replace(q + q, q)
return s
def _is_fortran_string_literal(s: str) -> bool:
s = s.strip()
if len(s) < 2 or s[0] not in ("'", "\""):
return False
q = s[0]
i = 1
n = len(s)
while i < n:
if s[i] == q:
if i + 1 < n and s[i + 1] == q:
i += 2
continue
i += 1
while i < n and s[i].isspace():
i += 1
return i == n
i += 1
return False
def _rewrite_fortran_string_literals(s: str) -> str:
out = []
i = 0
n = len(s)
while i < n:
ch = s[i]
if ch not in ("'", '"'):
out.append(ch)
i += 1
continue
q = ch
j = i + 1
while j < n:
if s[j] == q:
if j + 1 < n and s[j + 1] == q:
j += 2
continue
lit = s[i:j + 1]
out.append(repr(_fortran_unquote(lit)))
i = j + 1
break
j += 1
else:
out.append(ch)
i += 1
return ''.join(out)
def _strip_one_outer_paren(s: str) -> str:
s = s.strip()
if len(s) >= 2 and s[0] == "(" and s[-1] == ")" and find_matching_paren(s, 0) == len(s) - 1:
return s[1:-1].strip()
return s
def _fortran_implied_do_expr(raw: str, translate_expr, arrays_1d: set[str]) -> str | None:
"""Translate an I/O implied-DO item, including nested implied-DOs."""
s = raw.strip()
if not (len(s) >= 2 and s[0] == "(" and s[-1] == ")" and find_matching_paren(s, 0) == len(s) - 1):
return None
inner = s[1:-1].strip()
parts = [p.strip() for p in split_args(inner) if p.strip()]
if len(parts) < 3:
return None
obj_parts: list[str] | None = None
var = lo = hi = step = None
if len(parts) >= 4:
mm = re.fullmatch(r"([a-z_]\w*)\s*=\s*(.+)", parts[-3], re.I)
if mm:
obj_parts = parts[:-3]
var = mm.group(1)
lo = mm.group(2).strip()
hi = parts[-2]
step = parts[-1]
if obj_parts is None:
mm = re.fullmatch(r"([a-z_]\w*)\s*=\s*(.+)", parts[-2], re.I)
if mm:
obj_parts = parts[:-2]
var = mm.group(1)
lo = mm.group(2).strip()
hi = parts[-1]
step = None
if obj_parts is None or not obj_parts or var is None or lo is None or hi is None:
return None
lo_py = translate_expr(lo, arrays_1d)
hi_py = translate_expr(hi, arrays_1d)
if step is None:
step_py = "1"
else:
step_py = translate_expr(step, arrays_1d)
body_parts: list[str] = []
for p in obj_parts:
nested_py = _fortran_implied_do_expr(p, translate_expr, arrays_1d)
if nested_py is not None:
body_parts.append(nested_py)
else:
expr_py = translate_expr(p, arrays_1d)
body_parts.append(f"[{expr_py}]")
if len(body_parts) == 1:
body_py = body_parts[0]
else:
body_py = " + ".join(body_parts)
return f"_xf2p_implied_do(lambda {var}: {body_py}, {lo_py}, {hi_py}, {step_py})"
def _is_recyclable_io_iterable(raw: str, decl_array_types: dict[str, str]) -> bool:
s = raw.strip()
if (
s.startswith('[')
or s.startswith('(/')
or _fortran_implied_do_expr(s, lambda x, _a: x, set()) is not None
or (re.fullmatch(r"[a-z_]\w*", s, flags=re.I) and s.lower() in decl_array_types)
):
return True
concat_parts = split_top_level_concat(s)
if len(concat_parts) > 1:
return any(_is_recyclable_io_iterable(part, decl_array_types) for part in concat_parts)
return False
def _fortran_format_arg_count(fmt_literal: str) -> int | None:
"""Return the number of data items consumed by one pass of a limited format."""
try:
fmt_text = _strip_one_outer_paren(_fortran_unquote(fmt_literal.strip()))
except Exception:
return None
def count_token(tok: str) -> int | None:
tok = tok.strip()
if not tok:
return 0
low = tok.lower()
if tok[0] in ("'", '"') and tok[-1] == tok[0]:
return 0
mm = re.fullmatch(r"\*\((.*)\)", tok, re.I)
if mm:
return None
mm = re.fullmatch(r"(\d+)\((.*)\)", tok, re.I)
if mm:
rep = int(mm.group(1))
inner_total = 0
for sub in split_args(mm.group(2).strip()):
nsub = count_token(sub)
if nsub is None:
return None
inner_total += nsub
return rep * inner_total
mm = re.fullmatch(r"(\d*)/", low)
if mm:
return 0
if low == ":":
return 0
mm = re.fullmatch(r"(\d*)x", low)
if mm:
return 0
mm = re.fullmatch(r"(\d*)a(\d+)?", low)
if mm:
return int(mm.group(1) or "1")
mm = re.fullmatch(r"(\d*)l(\d+)", low)
if mm:
return int(mm.group(1) or "1")
mm = re.fullmatch(r"(\d*)i(\d+)(?:\.\d+)?", low)
if mm:
return int(mm.group(1) or "1")
mm = re.fullmatch(r"(\d*)(es|en|e|d|g|f)(\d+)(?:\.(\d+))?(?:e(\d+))?", low)
if mm:
return int(mm.group(1) or "1")
if tok.startswith("(") and tok.endswith(")") and find_matching_paren(tok, 0) == len(tok) - 1:
total = 0
for sub in split_args(tok[1:-1]):
nsub = count_token(sub)
if nsub is None:
return None
total += nsub
return total
return None
total = 0
for item in split_args(fmt_text):
nitem = count_token(item)
if nitem is None:
return None
total += nitem
return total
def _fortran_format_recycled_expr(fmt_literal: str, iterable_expr: str) -> str | None:
"""Return a Python expression for one-argument finite-format recycling over an iterable."""
if _fortran_format_arg_count(fmt_literal) != 1:
return None
item_expr = _fortran_format_expr(fmt_literal, ["_xf2p_item"])
if item_expr is None:
return None
# For finite format reversion during output, each new cycle starts a new record.
return f"'\\n'.join({item_expr} for _xf2p_item in {iterable_expr})"
def _single_iterable_formatted_arg_plan(fmt_literal: str, raw_args: list[str], decl_array_types: dict[str, str]) -> tuple[int, int] | None:
"""Plan finite-format expansion when exactly one I/O argument is an iterable."""
total = _fortran_format_arg_count(fmt_literal)
if total is None:
return None
iterable_pos = [i for i, raw in enumerate(raw_args) if _is_recyclable_io_iterable(raw, decl_array_types)]
if len(iterable_pos) != 1:
return None
pos = iterable_pos[0]
needed = total - (len(raw_args) - 1)
if needed <= 0:
return None
return pos, needed
def _fortran_format_expr(fmt_literal: str, arg_exprs: list[str]) -> str | None:
"""Return a Python expression for a limited Fortran character format string."""
try:
fmt_text = _strip_one_outer_paren(_fortran_unquote(fmt_literal.strip()))
except Exception:
return None
parts: list[str] = []
arg_i = 0
STOP = "__xf2p_stop__"
def take_arg() -> str | None:
nonlocal arg_i
if arg_i >= len(arg_exprs):
return None
out = arg_exprs[arg_i]
arg_i += 1
return out
def add_token(tok: str) -> str:
nonlocal arg_i
tok = tok.strip()
if not tok:
return "ok"
low = tok.lower()
mm = re.fullmatch(r"\*\((.*)\)", tok, re.I)
if mm:
inner = mm.group(1).strip()
if arg_i >= len(arg_exprs):
return "ok"
iterable = arg_exprs[arg_i]
arg_i += 1
inner_items = split_args(inner)
if ":" in [it.strip().lower() for it in inner_items]:
colon_i = next(i for i, it in enumerate(inner_items) if it.strip().lower() == ":")
left = ",".join(inner_items[:colon_i]).strip()
right = ",".join(inner_items[colon_i + 1:]).strip()
if left and right:
left_n = _fortran_format_arg_count(repr("(" + left + ")"))
right_n = _fortran_format_arg_count(repr("(" + right + ")"))
if left_n == 1 and right_n == 0:
item_expr = _fortran_format_expr(repr("(" + left + ")"), ["_xf2p_item"])
sep_expr = _fortran_format_expr(repr("(" + right + ")"), [])
if item_expr is not None and sep_expr is not None:
parts.append(f"({sep_expr}).join({item_expr} for _xf2p_item in {iterable})")
return "ok"
inner_expr = _fortran_format_expr(repr("(" + inner + ")"), ["_xf2p_item"])
if inner_expr is None:
return "fail"
parts.append(f"''.join({inner_expr} for _xf2p_item in {iterable})")
return "ok"
if tok[0] in ("'", '"') and tok[-1] == tok[0]:
parts.append(repr(_fortran_unquote(tok)))
return "ok"
mm = re.fullmatch(r"(\d+)\((.*)\)", tok, re.I)
if mm:
rep = int(mm.group(1))
inner = mm.group(2).strip()
inner_items = split_args(inner)
for _ in range(rep):
for sub in inner_items:
status = add_token(sub)
if status == "fail":
return "fail"
if status == STOP:
return STOP
return "ok"
mm = re.fullmatch(r"(\d*)/", low)
if mm:
rep = int(mm.group(1) or "1")
parts.append(repr("\n" * rep))
return "ok"
if low == ":":
if arg_i >= len(arg_exprs):
return STOP
return "ok"
mm = re.fullmatch(r"(\d*)x", low)
if mm:
rep = int(mm.group(1) or "1")
if rep == 1:
parts.append(repr(" "))
else:
parts.append(f"{rep}*' '")
return "ok"
mm = re.fullmatch(r"(\d*)a(\d+)?", low)
if mm:
rep = int(mm.group(1) or "1")
width = mm.group(2)
for _ in range(rep):
a = take_arg()
if a is None:
return STOP
if width is None:
parts.append(f"str({a})")
else:
parts.append(f"str({a}).rjust({int(width)})")
return "ok"
mm = re.fullmatch(r"(\d*)l(\d+)", low)
if mm:
rep = int(mm.group(1) or "1")
width = int(mm.group(2))
for _ in range(rep):
a = take_arg()
if a is None:
return STOP
parts.append(f"str(bool({a})).upper().replace('TRUE', 'T').replace('FALSE', 'F').rjust({width})")
return "ok"
mm = re.fullmatch(r"(\d*)i(\d+)(?:\.\d+)?", low)
if mm:
rep = int(mm.group(1) or "1")
width = int(mm.group(2))
for _ in range(rep):
a = take_arg()
if a is None:
return STOP
if width == 0:
parts.append(f"str(int({a}))")
else:
parts.append(f"format(int({a}), '{width}d')")
return "ok"
mm = re.fullmatch(r"(\d*)(es|en|e|d|g|f)(\d+)(?:\.(\d+))?(?:e(\d+))?", low)
if mm:
rep = int(mm.group(1) or "1")
code = mm.group(2)
width = int(mm.group(3))
prec = mm.group(4)
py_code = {"d": "E", "e": "E", "es": "E", "en": "E", "f": "f", "g": "G"}[code]
spec = f"{width}.{int(prec)}{py_code}" if prec is not None else f"{width}{py_code}"
for _ in range(rep):
a = take_arg()
if a is None:
return STOP
parts.append(f"format(float({a}), '{spec}')")
return "ok"
if tok.startswith("(") and tok.endswith(")") and find_matching_paren(tok, 0) == len(tok) - 1:
for sub in split_args(tok[1:-1]):
status = add_token(sub)
if status == "fail":
return "fail"
if status == STOP:
return STOP
return "ok"
return "fail"
items = split_args(fmt_text)
if not items:
return repr("")
for item in items:
status = add_token(item)
if status == "fail":
return None
if status == STOP:
break
if arg_i < len(arg_exprs):
for a in arg_exprs[arg_i:]:
parts.append(f"str({a})")
if not parts:
return repr("")
return " + ".join(parts)
def unique_preserve(items: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for it in items:
key = it.strip().lower()
if key in seen:
continue
seen.add(key)
out.append(it)
return out
def _find_dups_ci(items: list[str]) -> list[str]:
seen: set[str] = set()
dups: list[str] = []
for it in items:
key = it.strip().lower()
if key in seen and key not in dups:
dups.append(key)
seen.add(key)
return dups
_type_scalar_hint = {
"integer": "int",
"real": "np.float64",
"logical": "bool",
"complex": "complex",
"character": "str",
}
_type_default_scalar_value = {
"integer": "0",
"real": "np.float64(0.0)",
"logical": "False",
"complex": "0j",
"character": repr(""),
}
_type_dtype = {
"integer": "np.int_",
"real": "np.float64",
"logical": "np.bool_",
"complex": "np.complex128",
"character": "object",
}
_type_ndarray_hint = {
"integer": "npt.NDArray[np.int_]",
"real": "npt.NDArray[np.float64]",
"logical": "npt.NDArray[np.bool_]",
"complex": "npt.NDArray[np.complex128]",
"character": "npt.NDArray[object]",
}
_type_target_scalar_hint = {
"integer": "npt.NDArray[np.int_]",
"real": "npt.NDArray[np.float64]",
"logical": "npt.NDArray[np.bool_]",
"complex": "npt.NDArray[np.complex128]",
}
_LOCAL_RUNTIME_HELPERS = {
"_f_size",
"_f_spread",
"_f_assign_array",
"mean_1d",
"var_1d",
"argsort_real",
"random_normal_vec",
"random_choice2",
"random_choice_prob",
"random_choice_norep",
}
def infer_function_result_ftype(header: str) -> str | None:
"""Infer scalar Fortran result type from function header when explicit.
Examples:
pure integer function f(...)
real(kind=dp) pure function g(...)
"""
h = header.strip()
m = re.search(r"\b(integer|real|logical|complex)\b(?:\s*\([^)]*\))?\b[^!\n]*\bfunction\b", h, re.I)
if not m:
return None