~jasper/type_stack_calc

ref: 6aca66fb1a7cf1e10f7dd3263f04537c8ff37590 type_stack_calc/type_stack_calc/unused/if1.py -rw-r--r-- 2.2 KiB
6aca66fb — Jasper den Ouden Apparently `to_c` can already read ahead one, hopefully its this simple... 1 year, 1 month ago
                                                                                
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
#  Copyright (C) 2021 Jasper den Ouden.
#
#  This is free software: you can redistribute it and/or modify
#  it under the terms of the Affero GNU General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

# TODO may remove it, the other seems sufficient..

from type_stack_calc.ib.inbuild import InbuildFunction

def _tp_if(cond, if_t, if_f):
    if cond in (True, False, None):  # Only one-or-the-other.
        return [if_t if cond else if_f]
    else:  # TODO only for objects that can be "falsy".
        return [if_t.smoosh(if_f)]

from type_stack_calc.extractor import Extractor, extract

from type_stack_calc.pe.tmpvar import TmpVar
from type_stack_calc.tp.general import tp_stack

class InbuildIf(InbuildFunction):
    def __init__(self):
        InbuildFunction.__init__(self, 3, _tp_if, name='if')

    def to_c(self, tc, gen):
        wfile, prep = tc[:2]
        wfile(prep + "if(")
        tc.new_context(prep + " "*4, '(').c_1(gen)  # It's an expression.
        wfile(") {")

        body_tc = tc.new_context(prep + "  ", ';')  # bodies with more identation.
        body_tc.c_1(gen)
        wfile(';' + prep + "} else {")
        body_tc.c_1(gen)
        wfile(';' + prep + "}")

    c_seq = ["if(", "){\n", ";\n} else {\n", ";\n}\n"]

    def _extract_lsts(self, ext_fun, gen):
        lsts = ([], [], [])
        for lst in lsts:
            # Continue extractor within, the non-extracted we get,
            #  the extracted can be passed externally.
            Extractor((lst.append, ext_fun)).extract_1(gen)
        return lsts

    def extract(self, extractor, gen, obj):
        # Make a temporary variable for the output of the `if`.
        cond, if_t, if_f = self._extract_lsts(extractor[1], gen)
        tmp = TmpVar('if', tp_stack(obj))
        extractor[1]([tmp.deffer,  # If itself is extracted.
                      self,
                      cond, [tmp.setter, *if_t], [tmp.setter, *if_f]])
        extractor[0](tmp)  # Temporary variable in non-extracted so value there.

    def extract_top(self, extractor, gen, obj):
        # TODO it only has to extract one..
        extractor[0]([self, *self._extract_lsts(extractor[1], gen)])