Skip to content

Code Generator (code_gen.py)

code_gen

VersionInfo

Bases: object

Encapsulates build and version metadata for the code generator execution.

This class queries the current Git repository state to fetch the HEAD commit hash and checks if there are uncommitted changes, appending metadata to identify the exact codebase state used to generate the output files.

Source code in code/code_gen/code_gen.py
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
class VersionInfo(object):
    """Encapsulates build and version metadata for the code generator execution.

    This class queries the current Git repository state to fetch the HEAD commit
    hash and checks if there are uncommitted changes, appending metadata to
    identify the exact codebase state used to generate the output files.
    """

    def __init__(self, input_raw):
        """Initializes VersionInfo with build date, git hash, and terms metadata.

        Args:
            input_raw (str): The raw input string containing DSL term definitions.
        """
        bd = 'build date: {}'
        bb = 'build base: {}'

        self.build_date = bd.format(datetime.datetime.today().ctime())

        try:
            self.build_base = bb.format(sp.check_output(["git", "rev-parse", "HEAD"]).strip())
        except sp.CalledProcessError:
            self.build_base = "None"

        try:
            sp.check_output("git diff --exit-code".split())
            sp.check_output("git diff --cached --exit-code".split())
            self.off_base = ""
        except sp.CalledProcessError:
            self.off_base = "built with changes not commited"

        tinfo = '''
================================================================================
************************************ terms *************************************
--------------------------------------------------------------------------------
{}
================================================================================
'''

        self.term_info = tinfo.format(input_raw)

    def fparams(self):
        """Formats the collected build parameters into a single string.

        Returns:
            str: Multi-line string summarizing build date, revision, and terms details.
        """
        return "\n".join([self.build_date, self.build_base, self.off_base, self.term_info])

__init__(input_raw)

Initializes VersionInfo with build date, git hash, and terms metadata.

Parameters:

Name Type Description Default
input_raw str

The raw input string containing DSL term definitions.

required
Source code in code/code_gen/code_gen.py
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
    def __init__(self, input_raw):
        """Initializes VersionInfo with build date, git hash, and terms metadata.

        Args:
            input_raw (str): The raw input string containing DSL term definitions.
        """
        bd = 'build date: {}'
        bb = 'build base: {}'

        self.build_date = bd.format(datetime.datetime.today().ctime())

        try:
            self.build_base = bb.format(sp.check_output(["git", "rev-parse", "HEAD"]).strip())
        except sp.CalledProcessError:
            self.build_base = "None"

        try:
            sp.check_output("git diff --exit-code".split())
            sp.check_output("git diff --cached --exit-code".split())
            self.off_base = ""
        except sp.CalledProcessError:
            self.off_base = "built with changes not commited"

        tinfo = '''
================================================================================
************************************ terms *************************************
--------------------------------------------------------------------------------
{}
================================================================================
'''

        self.term_info = tinfo.format(input_raw)

fparams()

Formats the collected build parameters into a single string.

Returns:

Name Type Description
str

Multi-line string summarizing build date, revision, and terms details.

Source code in code/code_gen/code_gen.py
68
69
70
71
72
73
74
def fparams(self):
    """Formats the collected build parameters into a single string.

    Returns:
        str: Multi-line string summarizing build date, revision, and terms details.
    """
    return "\n".join([self.build_date, self.build_base, self.off_base, self.term_info])

build_info(terms_raw)

Generates and prints build information for the current code generation run.

Parameters:

Name Type Description Default
terms_raw str

The raw string contents of the DSL terms specification input file.

required
Source code in code/code_gen/code_gen.py
186
187
188
189
190
191
192
193
def build_info(terms_raw):
    """Generates and prints build information for the current code generation run.

    Args:
        terms_raw (str): The raw string contents of the DSL terms specification input file.
    """
    vinfo = VersionInfo(terms_raw)
    print(vinfo.fparams())

compile_terms(terms_raw)

Parses DSL terms spec and runs it through the five compiler stages.

This function initializes a new CompilationContext and executes the compiler pipeline sequentially: parsing, derivative/fluctuation expansion, SymPy expression simplification, data dependency resolution, and array buffer pooling.

Parameters:

Name Type Description Default
terms_raw str

The raw string contents of the DSL terms specification input file.

required

Returns:

Name Type Description
CompilationContext

The fully compiled and optimized compilation context.

Source code in code/code_gen/code_gen.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def compile_terms(terms_raw):
    """Parses DSL terms spec and runs it through the five compiler stages.

    This function initializes a new `CompilationContext` and executes the compiler pipeline
    sequentially: parsing, derivative/fluctuation expansion, SymPy expression simplification,
    data dependency resolution, and array buffer pooling.

    Args:
        terms_raw (str): The raw string contents of the DSL terms specification input file.

    Returns:
        CompilationContext: The fully compiled and optimized compilation context.
    """
    ctx = CompilationContext()
    ParserStage().execute(terms_raw, ctx)
    DerivativeExpansionStage().execute(ctx)
    SympySimplificationStage().execute(ctx)
    DependencyResolutionStage().execute(ctx)
    SympyOptimizationStage().execute(ctx)
    return ctx

escape_fortran_string(s)

Escapes string content for standard Fortran source formatting.

Converts internal double quotes into double-double quotes and splits the string lines, wrapping them in Fortran concatenation syntax // char(10) // & to respect line length limit.

Parameters:

Name Type Description Default
s str

The raw string to escape.

required

Returns:

Name Type Description
str

The escaped and formatted Fortran string parameter literal.

Source code in code/code_gen/code_gen.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def escape_fortran_string(s):
    """Escapes string content for standard Fortran source formatting.

    Converts internal double quotes into double-double quotes and splits the string lines,
    wrapping them in Fortran concatenation syntax `// char(10) // &` to respect line length limit.

    Args:
        s (str): The raw string to escape.

    Returns:
        str: The escaped and formatted Fortran string parameter literal.
    """
    escaped = s.replace('"', '""')
    lines = escaped.splitlines()
    if not lines:
        return '""'
    formatted_lines = [f'"{line}"' for line in lines]
    return ' // char(10) // &\n    '.join(formatted_lines)

generate_build_info_module(terms_raw)

Generates a complete standard Fortran module containing build info and LaTeX equations.

The generated module contains metadata about the compiler run, including the build base Git hash, and a string representations of the LaTeX equations.

Parameters:

Name Type Description Default
terms_raw str

The raw string contents of the DSL terms specification input file.

required
Source code in code/code_gen/code_gen.py
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
def generate_build_info_module(terms_raw):
    """Generates a complete standard Fortran module containing build info and LaTeX equations.

    The generated module contains metadata about the compiler run, including the build base Git hash,
    and a string representations of the LaTeX equations.

    Args:
        terms_raw (str): The raw string contents of the DSL terms specification input file.
    """
    vinfo = VersionInfo(terms_raw)
    build_info_str = vinfo.fparams()

    ctx = compile_terms(terms_raw)
    latex_str = get_latex_equations_str(ctx)

    fortran_build_info = escape_fortran_string(build_info_str)
    fortran_latex = escape_fortran_string(latex_str)

    fortran_code = f"""module m_build_info
  implicit none
  character(len=*), parameter :: build_info_str = &
    {fortran_build_info}
  character(len=*), parameter :: latex_equations_str = &
    {fortran_latex}
end module m_build_info
"""
    print(fortran_code)

get_latex_equations_str(ctx)

Generates the LaTeX equations dictionary string from the context.

Parameters:

Name Type Description Default
ctx CompilationContext

The compiled context containing the averaged fields.

required

Returns:

Name Type Description
str

A formatted string representing a Python dictionary mapping field names to LaTeX code.

Source code in code/code_gen/code_gen.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def get_latex_equations_str(ctx):
    """Generates the LaTeX equations dictionary string from the context.

    Args:
        ctx (CompilationContext): The compiled context containing the averaged fields.

    Returns:
        str: A formatted string representing a Python dictionary mapping field names to LaTeX code.
    """
    latex_lines = ["{"]
    for avg in ctx.averaged.values():
        latex_lines.append('  "{}" : r"${}$",'.format(avg.name, avg.latex))
    latex_lines.append("}")
    return "\n".join(latex_lines)

test(terms_raw, report=False, latex=False)

Compiles the post-processing term specifications from DSL into targets.

This compiles the Lark AST through all 4 pipeline stages and outputs the resulting Fortran source code via FortranProgramWriter, a LaTeX equation dictionary via LatexWriter, or an IR report via ReportWriter.

Parameters:

Name Type Description Default
terms_raw str

The raw string contents of the DSL terms specification.

required
report bool

If True, prints a JSON-based compilation IR report instead. Defaults to False.

False
latex bool

If True, prints LaTeX equation dictionary instead. Defaults to False.

False
Source code in code/code_gen/code_gen.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def test(terms_raw, report=False, latex=False):
    """Compiles the post-processing term specifications from DSL into targets.

    This compiles the Lark AST through all 4 pipeline stages
    and outputs the resulting Fortran source code via FortranProgramWriter,
    a LaTeX equation dictionary via LatexWriter, or an IR report via ReportWriter.

    Args:
        terms_raw (str): The raw string contents of the DSL terms specification.
        report (bool, optional): If True, prints a JSON-based compilation IR report instead. Defaults to False.
        latex (bool, optional): If True, prints LaTeX equation dictionary instead. Defaults to False.
    """
    ctx = compile_terms(terms_raw)

    if report:
        ReportWriter().write(ctx)
    elif latex:
        LatexWriter().write(ctx)
    else:
        FortranProgramWriter().write(ctx)