aboutsummaryrefslogtreecommitdiff
path: root/muppet/puppet/format/html.py
blob: 9719b534910ec6d72f5fd36be7231a202c236a1b (plain)
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
"""
Reserilaize AST as HTML.

This is mostly an extension of the text formatter, but with some HTML
tags inserted. This is also why the text module is imported.

.. code-block:: html

    <span class="{TYPE}">{BODY}</span>
"""

import re
import logging
from .base import Serializer
from muppet.puppet.ast import (
    PuppetLiteral, PuppetAccess, PuppetBinaryOperator,
    PuppetUnaryOperator, PuppetArray, PuppetCallMethod,
    PuppetCase, PuppetDeclarationParameter,
    PuppetInstanciationParameter, PuppetClass, PuppetConcat,
    PuppetCollect, PuppetIf, PuppetUnless, PuppetKeyword,
    PuppetExportedQuery, PuppetVirtualQuery, PuppetFunction,
    PuppetHash, PuppetHeredoc, PuppetLiteralHeredoc, PuppetVar,
    PuppetLambda,  PuppetQn, PuppetQr, PuppetRegex,
    PuppetResource, PuppetDefine, PuppetString,
    PuppetNumber, PuppetInvoke, PuppetResourceDefaults,
    PuppetResourceOverride, PuppetDeclaration, PuppetSelector,
    PuppetBlock, PuppetNode,
    PuppetCall, PuppetParenthesis, PuppetNop,

    HashEntry,
    # PuppetParseError,
)
import html
from .text import (
    override,
    find_heredoc_delimiter,
    ind,
    string_width,
)


logger = logging.getLogger(__name__)


def span(cls: str, content: str) -> str:
    """Wrap content in a span, and escape content."""
    return f'<span class="{cls}">{html.escape(content)}</span>'


def literal(x: str) -> str:
    """Tag string as a literal."""
    return span("literal", x)


def op(x: str) -> str:
    """Tag string as an operator."""
    return span("op", x)


def keyword(x: str) -> str:
    """Tag string as a keyword."""
    return span("keyword", x)


def var(x: str) -> str:
    """Tag string as a variable."""
    return span("var", x)


def string(x: str) -> str:
    """Tag strings as a string literal."""
    return span("string", x)


def number(x: str) -> str:
    """Tag string as a number literal."""
    return span("number", x)


class HTMLFormatter(Serializer[str]):
    """AST formatter returning source code."""

    @classmethod
    def format_declaration_parameter(
            cls,
            param: PuppetDeclarationParameter,
            indent: int) -> str:
        """Format a single declaration parameter."""
        out: str = ''
        if param.type:
            out += f'{cls.serialize(param.type, indent + 1)} '
        out += var(f'${param.k}')
        if param.v:
            out += f' = {cls.serialize(param.v, indent + 1)}'
        return out

    @classmethod
    def format_declaration_parameters(
            cls,
            lst: list[PuppetDeclarationParameter],
            indent: int) -> str:
        """
        Print declaration parameters.

        This formats the parameters for class, resoruce, and function declarations.
        """
        if not lst:
            return ''

        out = ' (\n'
        for param in lst:
            out += ind(indent + 1) + cls.format_declaration_parameter(param, indent + 1) + ',\n'
        out += ind(indent) + ')'
        return out

    @classmethod
    def serialize_hash_entry(
            cls,
            entry: HashEntry,
            indent: int) -> str:
        """Return a hash entry as a string."""
        return f'{cls.serialize(entry.k, indent + 1)} => {cls.serialize(entry.v, indent + 2)}'

    @override
    @classmethod
    def _puppet_literal(cls, it: PuppetLiteral, indent: int) -> str:
        return literal(it.literal)

    @override
    @classmethod
    def _puppet_access(cls, it: PuppetAccess, indent: int) -> str:
        args = ', '.join(cls.serialize(x, indent) for x in it.args)

        return f'{cls.serialize(it.how, indent)}[{args}]'

    @override
    @classmethod
    def _puppet_binary_operator(cls, it: PuppetBinaryOperator, indent: int) -> str:
        out = cls.serialize(it.lhs, indent)
        out += f' {op(it.op)} '
        out += cls.serialize(it.rhs, indent)
        return out

    @override
    @classmethod
    def _puppet_unary_operator(cls, it: PuppetUnaryOperator, indent: int) -> str:
        return f'{op(it.op)} {cls.serialize(it.x, indent)}'

    @override
    @classmethod
    def _puppet_array(cls, it: PuppetArray, indent: int) -> str:
        if not it.items:
            return '[]'
        else:
            out = '[\n'
            for item in it.items:
                out += ind(indent + 1) + cls.serialize(item, indent + 2) + ',\n'
            out += ind(indent) + ']'
            return out

    @override
    @classmethod
    def _puppet_call(cls, it: PuppetCall, indent: int) -> str:
        args = ', '.join(cls.serialize(x, indent) for x in it.args)
        return f'{cls.serialize(it.func, indent)}({args})'

    @override
    @classmethod
    def _puppet_call_method(cls, it: PuppetCallMethod, indent: int) -> str:
        out: str = cls.serialize(it.func, indent)

        if it.args:
            args = ', '.join(cls.serialize(x, indent) for x in it.args)
            out += f' ({args})'

        if it.block:
            out += cls.serialize(it.block, indent)

        return out

    @override
    @classmethod
    def _puppet_case(cls, it: PuppetCase, indent: int) -> str:
        out: str = f'{keyword("case")} {cls.serialize(it.test, indent)} {{\n'
        for (when, body) in it.cases:
            out += ind(indent + 1)
            out += ', '.join(cls.serialize(x, indent + 1) for x in when)
            out += ': {\n'
            for item in body:
                out += ind(indent + 2) + cls.serialize(item, indent + 2) + '\n'
            out += ind(indent + 1) + '}\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_declaration_parameter(cls, it: PuppetDeclarationParameter, indent: int) -> str:
        out: str = ''
        if it.type:
            out += f'{cls.serialize(it.type, indent + 1)} '
        out += var(f'${it.k}')
        if it.v:
            out += f' = {cls.serialize(it.v, indent + 1)}'
        return out

    @override
    @classmethod
    def _puppet_instanciation_parameter(cls, it: PuppetInstanciationParameter, indent: int) -> str:
        return f'{it.k} {it.arrow} {cls.serialize(it.v, indent)}'

    @override
    @classmethod
    def _puppet_class(cls, it: PuppetClass, indent: int) -> str:
        out: str = f'{keyword("class")} {it.name}'
        if it.params:
            out += cls.format_declaration_parameters(it.params, indent)

        out += ' {\n'
        for form in it.body:
            out += ind(indent+1) + cls.serialize(form, indent+1) + '\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_concat(cls, it: PuppetConcat, indent: int) -> str:
        out = '"'
        for item in it.fragments:
            match item:
                case PuppetString(s):
                    out += s
                case PuppetVar(x):
                    out += var(f"${{{x}}}")
                case puppet:
                    out += f"${{{cls.serialize(puppet, indent)}}}"
        out += '"'
        # Don't escape `out`, since it contains sub-expressions
        return f'<span class="string">{out}</span>'

    @override
    @classmethod
    def _puppet_collect(cls, it: PuppetCollect, indent: int) -> str:
        return f'{cls.serialize(it.type, indent)} {cls.serialize(it.query, indent + 1)}'

    @override
    @classmethod
    def _puppet_if(cls, it: PuppetIf, indent: int) -> str:
        out: str = f'{keyword("if")} {cls.serialize(it.condition, indent)} {{\n'
        for item in it.consequent:
            out += ind(indent+1) + cls.serialize(item, indent+1) + '\n'
        out += ind(indent) + '}'
        if alts := it.alternative:
            # TODO elsif
            out += f' {keyword("else")} {{\n'
            for item in alts:
                out += ind(indent+1) + cls.serialize(item, indent+1) + '\n'
            out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_unless(cls, it: PuppetUnless, indent: int) -> str:
        out: str = f'{keyword("unless")} {cls.serialize(it.condition, indent)} {{\n'
        for item in it.consequent:
            out += ind(indent+1) + cls.serialize(item, indent+1) + '\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_keyword(cls, it: PuppetKeyword, indent: int) -> str:
        return it.name

    @override
    @classmethod
    def _puppet_exported_query(cls, it: PuppetExportedQuery, indent: int) -> str:
        out: str = op('<<|')
        if f := it.filter:
            out += ' ' + cls.serialize(f, indent)
        out += ' ' + op('|>>')
        return out

    @override
    @classmethod
    def _puppet_virtual_query(cls, it: PuppetVirtualQuery, indent: int) -> str:
        out: str = op('<|')
        if f := it.q:
            out += ' ' + cls.serialize(f, indent)
        out += ' ' + op('|>')
        return out

    @override
    @classmethod
    def _puppet_function(cls, it: PuppetFunction, indent: int) -> str:
        out: str = f'{keyword("function")} {it.name}'
        if it.params:
            out += cls.format_declaration_parameters(it.params, indent)

        if ret := it.returns:
            out += f' {op(">>")} {cls.serialize(ret, indent + 1)}'

        out += ' {\n'
        for item in it.body:
            out += ind(indent + 1) + cls.serialize(item, indent + 1) + '\n'
        out += ind(indent) + '}'

        return out

    @override
    @classmethod
    def _puppet_hash(cls, it: PuppetHash, indent: int) -> str:
        if not it.entries:
            return '{}'
        else:
            out: str = '{\n'
            for item in it.entries:
                out += ind(indent + 1)
                out += cls.serialize_hash_entry(item, indent + 1)
                out += ',\n'
            out += ind(indent) + '}'
            return out

    @override
    @classmethod
    def _puppet_heredoc(cls, it: PuppetHeredoc, indent: int) -> str:
        """
        Serialize heredoc with interpolation.

        The esacpes $, r, and t are always added and un-escaped,
        while the rest are left as is, since they work fine in the literal.
        """
        syntax: str = ''
        if it.syntax:
            syntax = f':{it.syntax}'

        # TODO find delimiter
        body = ''
        for frag in it.fragments:
            match frag:
                case PuppetString(s):
                    # \r, \t, \, $
                    e = re.sub('[\r\t\\\\$]', lambda m: {
                        '\r': r'\r',
                        '\t': r'\t',
                        }.get(m[0], '\\' + m[0]), s)
                    body += e
                case PuppetVar(x):
                    body += f'${{{x}}}'
                case p:
                    body += cls.serialize(p, indent + 2)

        # Check if string ends with a newline
        match it.fragments[-1]:
            case PuppetString(s) if s.endswith('\n'):
                eol_marker = ''
                body = body[:-1]
            case _:
                eol_marker = '-'

        # Aligning this to the left column is ugly, but saves us from
        # parsing newlines in the actual string
        return f'@("EOF"{syntax}/$rt)\n{body}\n|{eol_marker} EOF'

    @override
    @classmethod
    def _puppet_literal_heredoc(cls, it: PuppetLiteralHeredoc, indent: int) -> str:
        syntax: str = ''
        if it.syntax:
            syntax = f':{it.syntax}'

        out: str = ''
        if not it.content:
            out += f'@(EOF{syntax})\n'
            out += ind(indent) + '|- EOF'
            return out

        delimiter = find_heredoc_delimiter(it.content)

        out += f'@({delimiter}{syntax})\n'

        lines = it.content.split('\n')
        eol: bool = False
        if lines[-1] == '':
            lines = lines[:-1]  # Remove last
            eol = True

        for line in lines:
            out += ind(indent + 1) + line + '\n'

        out += ind(indent + 1) + '|'

        if not eol:
            out += '-'

        out += ' ' + delimiter

        return out

    @override
    @classmethod
    def _puppet_var(cls, it: PuppetVar, indent: int) -> str:
        return var(f'${it.name}')

    @override
    @classmethod
    def _puppet_lambda(cls, it: PuppetLambda, indent: int) -> str:
        out: str = '|'
        for item in it.params:
            out += 'TODO'
        out += '| {'
        for form in it.body:
            out += ind(indent + 1) + cls.serialize(form, indent + 1)
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_qn(cls, it: PuppetQn, indent: int) -> str:
        return span('qn', it.name)

    @override
    @classmethod
    def _puppet_qr(cls, it: PuppetQr, indent: int) -> str:
        return span('qn', it.name)

    @override
    @classmethod
    def _puppet_regex(cls, it: PuppetRegex, indent: int) -> str:
        return span('regex', f'/{it.s}/')

    @override
    @classmethod
    def _puppet_resource(cls, it: PuppetResource, indent: int) -> str:
        out = f'{cls.serialize(it.type, indent + 1)} {{'
        match it.bodies:
            case [(name, values)]:
                out += f' {cls.serialize(name, indent + 1)}:\n'
                for v in values:
                    out += ind(indent + 1) + cls.serialize(v, indent + 2) + ',\n'
            case bodies:
                out += '\n'
                for (name, values) in bodies:
                    out += f'{ind(indent + 1)}{cls.serialize(name, indent + 1)}:\n'
                    for v in values:
                        out += ind(indent + 2) + cls.serialize(v, indent + 3) + ',\n'
                    out += ind(indent + 2) + ';\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_define(cls, it: PuppetDefine, indent: int) -> str:
        out: str = f'{keyword("define")} {it.name}'
        if params := it.params:
            out += cls.format_declaration_parameters(params, indent)

        out += ' {\n'
        for form in it.body:
            out += ind(indent + 1) + cls.serialize(form, indent + 1) + '\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_string(cls, it: PuppetString, indent: int) -> str:
        # TODO escaping
        return string(f"'{it.s}'")

    @override
    @classmethod
    def _puppet_number(cls, it: PuppetNumber, indent: int) -> str:
        return number(str(it.x))

    @override
    @classmethod
    def _puppet_invoke(cls, it: PuppetInvoke, indent: int) -> str:
        invoker = f'{cls.serialize(it.func, indent)}'
        out: str = invoker
        template: str
        if invoker == keyword('include'):
            template = ' {}'
        else:
            template = '({})'
        out += template.format(', '.join(cls.serialize(x, indent + 1) for x in it.args))
        return out

    @override
    @classmethod
    def _puppet_resource_defaults(cls, it: PuppetResourceDefaults, indent: int) -> str:
        out: str = f'{cls.serialize(it.type, indent)} {{\n'
        for op in it.ops:
            out += ind(indent + 1) + cls.serialize(op, indent + 1) + ',\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_resource_override(cls, it: PuppetResourceOverride, indent: int) -> str:
        out: str = f'{cls.serialize(it.resource, indent)} {{\n'
        for op in it.ops:
            out += ind(indent + 1) + cls.serialize(op, indent + 1) + ',\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_declaration(cls, it: PuppetDeclaration, indent: int) -> str:
        return f'{cls.serialize(it.k, indent)} = {cls.serialize(it.v, indent)}'

    @override
    @classmethod
    def _puppet_selector(cls, it: PuppetSelector, indent: int) -> str:
        out: str = f'{cls.serialize(it.resource, indent)} ? {{\n'
        rendered_cases = [(cls.serialize(test, indent + 1),
                           cls.serialize(body, indent + 2))
                          for (test, body) in it.cases]
        case_width = max(string_width(c[0], indent + 1) for c in rendered_cases)
        for (test, body) in rendered_cases:
            out += ind(indent + 1) + test
            out += ' ' * (case_width - string_width(test, indent + 1))
            out += f' => {body},\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_block(cls, it: PuppetBlock, indent: int) -> str:
        return '\n'.join(cls.serialize(x, indent) for x in it.entries)

    @override
    @classmethod
    def _puppet_node(cls, it: PuppetNode, indent: int) -> str:
        out: str = keyword('node') + ' '
        out += ', '.join(cls.serialize(x, indent) for x in it.matches)
        out += ' {\n'
        for item in it.body:
            out += ind(indent + 1) + cls.serialize(item, indent + 1) + '\n'
        out += ind(indent) + '}'
        return out

    @override
    @classmethod
    def _puppet_parenthesis(cls, it: PuppetParenthesis, indent: int) -> str:
        return f'({cls.serialize(it.form, indent)})'

    @override
    @classmethod
    def _puppet_nop(cls, it: PuppetNop, indent: int) -> str:
        return ''