Skip to content

explicit Local/Global for all Instance, Arguments, Hint

Ralf Jung requested to merge ralf/explicit-local-global into master

This applies the script from iris!609 (closed) to std++. I slightly extended the script to also handle Arguments and Hint:

#!/usr/bin/env python3

# Add Local or Global to any unqualified Instance declarations. Tracks whether
# a section is open and adds Global outside any section and Local inside one.

import sys
import re

SECTION_RE = re.compile("""\s*Section\s+(?P<name>\w*).*\..*""")
END_RE = re.compile("""\s*End\s+(?P<name>\w*).*\..*""")
# Do not adjust `Hint Rewrite`, it does not support visibility.
ADJUST_VERNAC_RE = re.compile("""(?P<indent>\s*)(?P<vernac>(Instance|Arguments|Hint (Extern|Constructors|Resolve|Immediate|Mode|Opaque|Transparent|Unfold))\s.*)""")

def qualify_lines(lines):
    """Qualify instances in text given as a list of lines."""
    # tracks the list of sections open
    section_stack = []
    out = []
    for line in lines:
        m = SECTION_RE.match(line)
        if m:
            name = m.group("name")
            section_stack.append(name)
        m = END_RE.match(line)
        if m:
            name = m.group("name")
            # close a section if it's open (name may not match because End is
            # for a module instead)
            if len(section_stack) > 0 and section_stack[-1] == name:
                section_stack.pop()
        m = ADJUST_VERNAC_RE.match(line)
        if m:
            indent = m.group("indent")
            modifier = "Local" if section_stack else "Global"
            vernac = m.group("vernac")
            line = f"{indent}{modifier} {vernac}\n"
        out.append(line)
    if section_stack:
        print(f"oops {section_stack} remaining", file=sys.stderr)
        sys.exit(1)
    return out

for fname in sys.argv[1:]:
    print(f"processing {fname}")
    with open(fname) as f:
        lines = f.readlines()
    with open(fname, "w") as f:
        lines = qualify_lines(lines)
        f.writelines(lines)
Edited by Ralf Jung

Merge request reports