aboutsummaryrefslogtreecommitdiff
path: root/src/smp/macro_processor.py
blob: 68fd726f95cb6f1c4f1887047d4b1e55be8cdd94 (plain) (blame)
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
import smp.builtins
import traceback
import inspect

from typing import Any
from enum import Enum
from io import StringIO
from contextlib import redirect_stdout


class ParserState(Enum):
    NORMAL = 1
    IN_QUOTES = 2
    IN_MACRO = 3
    IN_MACRO_ARGS = 4
    IN_SPECIAL_MACRO = 5
    IN_SPECIAL_MACRO_EXPRESSION = 6
    IN_CODE = 7
    DNL = 8


def macro_is_whitespace_deleting(s: str) -> bool:
    if len(s) == 0:
        return False
    return s[-1] == "_"


def macro_name_clean(macro_name: str) -> str:
    if macro_is_whitespace_deleting(macro_name):
        macro_name = macro_name[:-1]
    return macro_name


def seek(input: str, start: int, target: str) -> int | None:
    """Seek for a value in a string, consider using startswith instead"""
    from warnings import warn

    warn(
        "seek should be considered replaced with str.startswith",
        DeprecationWarning,
        stacklevel=2,
    )
    input_end = len(input)
    target_end = len(target)

    if input_end < start + target_end:
        return None

    i = 0
    while i < len(target):
        if input[start + i] != target[i]:
            return None
        i += 1

    return start + target_end


class MacroProcessor:
    """All currently defined macros in this MacroProcessor"""

    macros: dict[str, Any]
    """ All macro invocations that has happened """
    macro_invocations: list[tuple[str, list[str]]]
    """ Emitted warnings """
    warnings: list[Any]
    """ Global environment for python execution """
    py_global_env: dict
    py_local_env_alt: dict
    py_local_env_current: dict

    special_macros: dict[str, tuple[Any, Any]]

    start_quote: str = '%"'
    end_quote: str = '"%'

    def __init__(self, prefix=""):
        self.macros = dict()
        self.macro_invocations = list()
        self.warnings = list()
        self.py_global_env = dict()
        self.py_local_env_alt = dict()
        self.py_local_env_current = self.macros
        self.indent_level = ""

        self._define_builtins(self.macros, prefix=prefix)
        self._define_builtins(self.py_local_env_alt, prefix=prefix)

    def _define_builtins(self, env, prefix=""):
        env[f"{prefix}macro_processor"] = self
        env[f"{prefix}define"] = smp.builtins.smp_builtin_define
        env[f"{prefix}undefine"] = smp.builtins.smp_builtin_undefine
        env[f"{prefix}define_array"] = smp.builtins.smp_builtin_define_array
        env[f"{prefix}ifdef"] = smp.builtins.smp_builtin_ifdef
        env[f"{prefix}ifndef"] = smp.builtins.smp_builtin_ifndef
        env[f"{prefix}ifeq"] = smp.builtins.smp_builtin_ifeq
        env[f"{prefix}ifneq"] = smp.builtins.smp_builtin_ifneq
        env[f"{prefix}include"] = smp.builtins.smp_builtin_include
        env[f"{prefix}include_verbatim"] = smp.builtins.smp_builtin_include_verbatim
        env[f"{prefix}shell"] = smp.builtins.smp_builtin_shell
        env[f"{prefix}dumpenv"] = smp.builtins.smp_builtin_dumpenv
        env[f"{prefix}eval"] = smp.builtins.smp_builtin_eval
        env[f"{prefix}array_push"] = smp.builtins.smp_builtin_array_push
        env[f"{prefix}array_each"] = smp.builtins.smp_builtin_array_each
        env[f"{prefix}array_size"] = smp.builtins.smp_builtin_array_size
        env[f"{prefix}explode"] = smp.builtins.smp_builtin_explode
        env[f"{prefix}format_time"] = smp.builtins.smp_builtin_format_time
        env[f"{prefix}html_from_markdown"] = smp.builtins.smp_builtin_html_from_markdown
        env[f"{prefix}wodl"] = smp.builtins.smp_builtin_wodl

    def define_macro_string(self, macro_name, macro_value):
        self.define_macro(macro_name, str(macro_value))

    def define_macro(self, macro_name, macro_value):
        self.macros[macro_name] = macro_value

    def expand_macro(self, macro_name: str, args: list[str] = list()) -> str:
        # Ignore trailing underscore in macro name, the parser will pop a space in front if
        # present, but we should ignore it for finding the macro.
        macro_name = macro_name_clean(macro_name)
        if macro_name not in self.macros:
            if len(args) == 0:
                return macro_name
            out = f"{macro_name}("
            for i, arg in enumerate(args):
                out += self.process_input(arg)
                if i < (len(args) - 1):
                    out += ","
            out += ")"
            return out

        # Strip leading whitespace from arguments
        for arg in args:
            arg = arg.strip()

        # Log macro invokation
        # The fact that we are here, does not ensure that the macro is actually expanded into
        # something useful, just that it exists, and was invoked
        self.macro_invocations.append((macro_name, args))

        macro = self.macros.get(macro_name)

        if callable(macro):
            signature = inspect.signature(macro)
            macro_args: list[Any] = []
            if (
                "macro_processor" in signature.parameters
                or "smp" in signature.parameters
            ):
                macro_args.append(self)
            macro_args.extend(args)
            try:
                return str(macro(*macro_args))
            except Exception as e:
                s = f"{macro_name}({','.join([repr(x) for x in args])})"
                self.warnings.append(f"Error expanding macro {s} ({e})")
                return s
        if isinstance(macro, str):
            expanded = macro
            for i, arg in enumerate(args):
                placeholder = f"${i}"
                expanded = macro.replace(placeholder, arg)
            return self.process_input(expanded)
        return f"{repr(macro)}"

    def process_input(self, input: str):
        """
        I also want to add special syntax for "special blocks",
        I am thinking of two main options, either some macro_names are intercepted, _or_ a special kind of macro can exist like
        These will be on a line-basis, so they simply end on newline
        @if <python-expression>

        @else <python-expression>

        @endif

        @for <python-expression>
        @endfor
        """
        output = ""
        state = ParserState.NORMAL
        macro_name = ""
        macro_args = []
        argument = ""
        py_expr = ""

        skip_next_line_ending = False

        # We should keep track of filename, linenumber, and character number on line here
        # So we can give sensible error messages
        # Probably add to python stack trace?

        quote_level = 0
        parens_level = 0

        i = 0
        while i < len(input):
            c = input[i]
            peek = None if i + 1 >= len(input) else input[i + 1]
            # import sys
            # print(f"[{i:4}] {repr(c):4} -> {repr(peek):4} [{state}] = {repr(output)}", file=sys.stderr)

            if state == ParserState.DNL:
                if c == "\n":
                    state = ParserState.NORMAL
            elif state == ParserState.NORMAL:
                if skip_next_line_ending and (c == "\n"):
                    skip_next_line_ending = False
                    i += 1
                    continue

                if c == "%" and peek == "(":
                    state = ParserState.IN_CODE
                    i += 2
                    continue

                if c == "%" and peek == '"':
                    state = ParserState.IN_QUOTES
                    quote_level += 1
                    i += 1
                elif c.isalnum():
                    state = ParserState.IN_MACRO
                    macro_name += c
                else:
                    output += c

            elif state == ParserState.IN_QUOTES:
                if c == "%" and peek == '"':
                    quote_level += 1
                    i += 1
                    output += '%"'
                elif c == '"' and peek == "%":
                    quote_level -= 1
                    if quote_level == 0:
                        state = ParserState.NORMAL
                    else:
                        output += '"%'
                    i += 1
                else:
                    output += c
            elif state == ParserState.IN_MACRO:
                if c.isalnum() or c == "_":
                    macro_name += c
                elif c == "(":
                    parens_level += 1
                    state = ParserState.IN_MACRO_ARGS
                else:
                    if macro_is_whitespace_deleting(macro_name):
                        if output[-1] == " ":
                            output = output[:-1]
                        macro_name = macro_name_clean(macro_name)

                    if macro_name == "SNNL":
                        skip_next_line_ending = c != "\n"
                    elif macro_name == "DNL":
                        if c != "\n":
                            state = ParserState.DNL
                        macro_name = ""
                        i += 1
                        continue
                    else:
                        expanded = self.expand_macro(macro_name)
                        output += expanded
                        output += c
                    macro_name = ""
                    state = ParserState.NORMAL
            elif state == ParserState.IN_MACRO_ARGS:
                if c == "%" and peek == '"':
                    quote_level += 1
                    i += 2
                    argument += '%"'
                    continue
                elif c == '"' and peek == "%":
                    quote_level -= 1
                    i += 2
                    argument += '"%'
                    continue
                elif quote_level > 0:
                    argument += c
                    i += 1
                    continue

                if (c == ")") and (parens_level == 1):
                    if macro_is_whitespace_deleting(macro_name):
                        if output[-1] == " ":
                            output = output[:-1]
                        macro_name = macro_name_clean(macro_name)
                    parens_level = 0
                    macro_args.append(argument.strip())
                    expanded = self.expand_macro(macro_name, macro_args)
                    output += expanded
                    state = ParserState.NORMAL
                    macro_name = ""
                    macro_args = []
                    argument = ""
                elif (c == ",") and (parens_level == 1):
                    macro_args.append(argument.strip())
                    argument = ""
                else:
                    if c == "(":
                        parens_level += 1
                    if c == ")":
                        parens_level -= 1
                    argument += c
            elif state == ParserState.IN_CODE:
                if c == ")" and peek == "%":
                    try:
                        f = StringIO()
                        with redirect_stdout(f):
                            exec(py_expr, self.py_global_env, self.py_local_env_current)
                        s = f.getvalue()
                        if s != "":
                            output += s
                    except Exception:
                        traceback.print_exc()
                    py_expr = ""
                    state = ParserState.NORMAL
                    i += 1
                else:
                    py_expr += c
            i += 1

        # Handle cases where the text ends with a macro without arguments
        if macro_name != "":
            if macro_is_whitespace_deleting(macro_name):
                if output[-1] == " ":
                    output = output[:-1]
                macro_name = macro_name_clean(macro_name)
            output += self.expand_macro(macro_name)
        return output