Esempio n. 1
0
 def writets(self, w: FileWriter) -> None:
     assert self._ctor is None, "Custom Exception constructor not allowed for TS"
     if self._msg is None:
         assert self._expr is not None
         line = f"throw new Error({self._expr.getPyExpr()[0]})"
     else:
         line = f"throw new Error({self._msg!r})"
     w.line0(line)
Esempio n. 2
0
    def writephp(self, w: FileWriter) -> None:
        w.line0(f'if ({self._expr.getPHPExpr()[0]}) {{')
        for stmt in self._statements:
            stmt.writephp(w.with_more_indent())
        w.line0('}')

        # always put a blank line after a conditional
        w.blank()
Esempio n. 3
0
 def writepy(self, w: FileWriter) -> None:
     w.line0(
         f'for {self._assign.getPyExpr()[0]} in {self._expr.getPyExpr()[0]}:'
     )
     for stmt in self._statements:
         stmt.writepy(w.with_more_indent())
     # always put a blank line after a for loop
     w.blank()
Esempio n. 4
0
 def writepy(self, w: FileWriter) -> None:
     left = self._target.getPyExpr()[0]
     if self._declare and self._declaretype:
         left += ': ' + self._target.getPanType().getQuotedPyType()
     if self._expr is None:
         w.line0(left)
     else:
         w.line0(f'{left} = {self._expr.getPyExpr()[0]}')
Esempio n. 5
0
    def writepy(self, w: FileWriter) -> None:
        w.line0('try:')
        for stmt in self._statements:
            stmt.writepy(w.with_more_indent())

        # catch blocks
        for cb in self._catchblocks:
            # write out catch blocks without increasing indent
            cb.writepy(w)
Esempio n. 6
0
 def writets(self, w: FileWriter) -> None:
     w.line0(
         f'for (let {self._assign.getTSExpr()[0]} of {self._expr.getTSExpr()[0]}) {{'
     )
     for stmt in self._statements:
         stmt.writets(w.with_more_indent())
     w.line0(f'}}')
     # always put a blank line after a for loop
     w.blank()
Esempio n. 7
0
 def writepy(self, w: FileWriter) -> None:
     ctor = 'Exception'
     if self._ctor is not None:
         ctor = self._ctor
     if self._msg is None:
         assert self._expr is not None
         line = f"raise {ctor}({self._expr.getPyExpr()[0]})"
     else:
         line = f"raise {ctor}({self._msg!r})"
     w.line0(line)
Esempio n. 8
0
    def writephp(self, w: FileWriter) -> None:
        phptypes = self._target.getPanType().getPHPTypes()
        if self._declare and self._declaretype:
            w.line0(f"/** @var {phptypes[1]} */")

        left = self._target.getPHPExpr()[0]

        # you can't just make a variable declaration in PHP
        assert self._expr is not None
        w.line0(f'{left} = {self._expr.getPHPExpr()[0]};')
Esempio n. 9
0
 def writephp(self, w: FileWriter) -> None:
     ctor = self._ctor or '\\Exception'
     if self._msg is None:
         assert self._expr is not None
         line = f"throw new {ctor}({self._expr.getPHPExpr()[0]});"
     else:
         # TODO: don't import this here
         from paradox.expressions import _phpstr
         line = f"throw new {ctor}({_phpstr(self._msg)});"
     w.line0(line)
Esempio n. 10
0
 def writepy(self, w: FileWriter) -> None:
     intro = 'except'
     if self.catchexpr:
         intro += ' ' + self.catchexpr
         if self.catchvar:
             intro += ' as ' + self.catchvar
     intro += ':'
     w.line0(intro)
     for stmt in self._statements:
         stmt.writepy(w.with_more_indent())
Esempio n. 11
0
    def writephp(self, w: FileWriter) -> None:
        prefix = ''

        if self._isabstract:
            prefix += 'abstract '

        if self._docstring:
            w.line0('/**')
            for docline in self._docstring:
                w.line0(' * ' + docline.strip())
            w.line0(' */')

        extends = ''
        if len(self._bases):
            assert len(self._bases) <= 1
            extends = ' extends ' + self._bases[0]

        w.line0(f"{prefix}class {self._name}{extends} {{")

        needemptyline = False

        # first write out properties
        for prop in self._properties:
            assign = ''

            # only assign values in the class body if the value is a literal
            if prop.propdefault and isinstance(prop.propdefault, PanLiteral):
                assign = ' = ' + prop.propdefault.getPHPExpr()[0]

            phptypes = prop.proptype.getPHPTypes()
            w.line1(f'/** @var {phptypes[1]} */')
            w.line1(f'public ${prop.propname}{assign};')
            needemptyline = True

        # add an __init__() method to set default values
        constructor = self._getInitSpec("php")
        if constructor:
            if needemptyline:
                w.blank()
            constructor.writephp(w.with_more_indent())
            needemptyline = True

        # all other methods
        for method in self._methods:
            if needemptyline:
                w.blank()
            method.writephp(w.with_more_indent())
            needemptyline = True

        if needemptyline:
            for comment in self._remarks:
                w.line1('// ' + comment)
                w.blank()

        w.line0("}")
Esempio n. 12
0
    def writets(self, w: FileWriter) -> None:
        left = self._target.getTSExpr()[0]
        if self._declare:
            left = f"let {left}"
            if self._declaretype:
                left += ": " + self._target.getPanType().getTSType()[0]

        if self._expr is None:
            w.line0(f'{left};')
        else:
            w.line0(f'{left} = {self._expr.getTSExpr()[0]};')
Esempio n. 13
0
    def writets(self, w: FileWriter) -> None:
        modifiers: List[str] = []

        # TODO: do we need to write some imports?
        if self._isasync:
            assert not self._isconstructor, "async constructor not possible?"
            modifiers.append('async')

        if self._isabstract:
            modifiers.append('abstract')

        if self._isstaticmethod:
            modifiers.append('static')

        # first write out overloads
        assert not len(self._overloads), "TS overloads not supported yet"

        for decoration in self._decorators_ts:
            w.line0(decoration)

        if not len(modifiers):
            modifiers.append('public')

        name = 'constructor' if self._isconstructor else self._name
        w.line0((' '.join(modifiers)) + ' ' + name + "(")

        assert not len(self._kwargs), "TS does not support kwargs"

        # header
        for argname, crosstype, argdefault in self._pargs:
            argstr = argname + ': ' + crosstype.getTSType()[0]
            if argdefault is not None:
                argstr += ' = ' + argdefault.getTSExpr()[0]
            w.line1(argstr + ',')

        rettype: str = "void"
        if self._isconstructor:
            # no return type annotation for a class constructor
            rettype = ""
        else:
            if self._rettype is not None:
                rettype = self._rettype.getTSType()[0]
            if self._isasync:
                rettype = "Promise<" + rettype + ">"

        if self._isabstract:
            assert not len(self._statements)
            w.line0(f"): {rettype};" if rettype else ");")
        else:
            w.line0(f"): {rettype} {{" if rettype else ") {")
            for stmt in self._statements:
                stmt.writets(w.with_more_indent())
            w.line0('}')
Esempio n. 14
0
 def writepy(self, w: FileWriter) -> None:
     # XXX: remember that for Python you almost certainly don't want a bare "except:" as that
     # would catch process signals and such.
     if self._pyclass:
         intro = "except " + self._pyclass
     else:
         intro = "except Exception"
     if self._var:
         intro += ' as ' + self._var.getPyExpr()[0]
     intro += ":"
     w.line0(intro)
     for stmt in self._statements:
         stmt.writepy(w.with_more_indent())
Esempio n. 15
0
    def writepy(self, w: FileWriter) -> None:
        inner = ', '.join(
            [f'{k!r}: {k}' for k, allowomit in self._keys if not allowomit])

        varstr = self._var.getPyExpr()[0]

        w.line0(f'{varstr}: {self._type.getQuotedPyType()} = {{{inner}}}')

        # now do the omittable args
        for k, allowomit in self._keys:
            if allowomit:
                # FIXME: this isn't how we want to do omitted args - we should be doing ellipsis
                expr = pannotomit(PanVar(k, None))
                w.line0(f'if {expr.getPyExpr()[0]}:')
                w.line1(f'{varstr}[{k!r}] = {k}')
Esempio n. 16
0
    def writepy(self, w: FileWriter) -> None:
        havebody = False
        bases = self._bases[:]

        # write out class header
        if self._isabstract:
            bases.append('abc.ABC')
        if self._isdataclass:
            w.line0('@dataclasses.dataclass')

        parents = ', '.join(bases)
        if parents:
            parents = '(' + parents + ')'
        w.line0(f'class {self._name}{parents}:')
        if self._docstring:
            w.line1('"""')
            for docline in self._docstring:
                w.line1(docline.strip())
            w.line1('"""')
            w.blank()
            havebody = True

        # first write out properties
        for prop in self._properties:
            w.line1(f'{prop.propname}: {prop.proptype.getQuotedPyType()}')
        if self._properties:
            w.blank()
            havebody = True

        # add an __init__() method to set default values
        initspec = self._getInitSpec("python")
        if initspec:
            initspec.writepy(w.with_more_indent())
            w.blank()
            havebody = True

        # all other methods
        for method in self._methods:
            method.writepy(w.with_more_indent())
            w.blank()
            havebody = True

        for comment in self._remarks:
            w.line1('# ' + comment)
            w.blank()

        if not havebody:
            w.line1('pass')
Esempio n. 17
0
    def writephp(self, w: FileWriter) -> None:
        modifiers: List[str] = []

        assert not self._isasync, "Async methods not possible for PHP"

        if self._isabstract:
            modifiers.append('abstract')

        if self._isstaticmethod:
            modifiers.append('static')

        # first write out overloads
        assert not len(self._overloads), "Overloads not possible in PHP"

        if self._ismethod:
            modifiers.append('public')

        name = '__construct' if self._isconstructor else self._name
        w.line0((' '.join(modifiers)) + ' function ' + name + "(")

        assert not len(self._kwargs), "PHP does not support kwargs"

        # header
        argnum = 0
        comma = ','
        for argname, crosstype, argdefault in self._pargs:
            argnum += 1
            if argnum == len(self._pargs):
                comma = ''
            argstr = '$' + argname
            phptype = crosstype.getPHPTypes()[0]
            if phptype:
                argstr = phptype + ' ' + argstr
            if argdefault is not None:
                argstr += ' = ' + argdefault.getPHPExpr()[0]
            w.line1(argstr + comma)

        rettype: str = ""
        if not self._isconstructor and self._rettype is not None:
            rettype = self._rettype.getPHPTypes()[0] or ""

        if rettype:
            rettype = ": " + rettype

        if self._isabstract:
            assert not len(self._statements)
            w.line0(f"){rettype};")
        else:
            w.line0(f"){rettype} {{")
            for stmt in self._statements:
                stmt.writephp(w.with_more_indent())
            w.line0('}')
Esempio n. 18
0
    def writephp(self, w: FileWriter) -> None:
        # TODO: don't import this here
        from paradox.expressions import _phpstr

        phptype = self._type.getPHPTypes()[0]
        if phptype:
            w.line0(f'/** @var {phptype} */')

        inner = ', '.join([
            _phpstr(k) + ' => $' + k for k, allowomit in self._keys
            if not allowomit
        ])

        varstr = self._var.getPHPExpr()[0]

        w.line0(f'{varstr} = [{inner}];')

        # now do the omittable args
        for k, allowomit in self._keys:
            raise Exception("omittable args aren't supported by PHP")
Esempio n. 19
0
    def writets(self, w: FileWriter) -> None:
        w.line0(f"try {{")
        for stmt in self._statements:
            stmt.writets(w.with_more_indent())

        assert len(self._catchblocks
                   ), "TryCatchBlock must have at least one Catch block"

        # all catch blocks must be a CatchBlock2 and have the same var name
        catchvar = None
        catchspecific: List[CatchBlock2] = []
        catchall: Optional[CatchBlock2] = None
        for cb in self._catchblocks:
            assert isinstance(cb, CatchBlock2)
            assert cb._var is not None

            # TODO: get rid of this dirty hack
            if catchvar is None:
                catchvar = cb._var._name
            else:
                assert cb._var._name == catchvar

            if cb._tsclass:
                catchspecific.append(cb)
            else:
                catchall = cb
        assert catchvar is not None

        w.line0(f"}} catch ({catchvar}) {{")
        if catchspecific:
            for cb in catchspecific:
                assert isinstance(cb, CatchBlock2)
                w.line1(f"if ({catchvar} instanceof {cb._tsclass}) {{")
                for stmt in cb._statements:
                    stmt.writets(w.with_more_indent().with_more_indent())
            if catchall:
                w.line1(f"}} else {{")
                for stmt in catchall._statements:
                    stmt.writets(w.with_more_indent().with_more_indent())
            # close off the last catch block
            w.line1(f"}}")

            if not catchall:
                # if there was no catch block added to handle any exception types, we need to
                # rethrow the exception
                w.line1(f"throw {catchvar};")
        else:
            assert catchall is not None
            for stmt in catchall._statements:
                stmt.writets(w.with_more_indent())

        w.line0(f"}}")
Esempio n. 20
0
    def writets(self, w: FileWriter) -> None:
        inner = ', '.join(
            [f'{k!r}: {k}' for k, allowomit in self._keys if not allowomit])

        varstr = self._var.getTSExpr()[0]

        w.line0(f'let {varstr}: {self._type.getTSType()[0]} = {{{inner}}};')

        # now do the omittable args
        for k, allowomit in self._keys:
            if allowomit:
                w.line0(f'if (typeof {k} !== "undefined") {{')
                w.line1(f'{varstr}[{k!r}] = {k};')
                w.line0(f'}}')
Esempio n. 21
0
 def writepy(self, w: FileWriter) -> None:
     w.line0(self._expr.getPyExpr()[0])
Esempio n. 22
0
 def writephp(self, w: FileWriter) -> None:
     w.line0(self._expr.getPHPExpr()[0] + ';')
Esempio n. 23
0
 def writephp(self, w: FileWriter) -> None:
     list_, prec = self._list.getPHPExpr()
     if prec.value >= PHPPrecedence.Arrow.value:
         list_ = '(' + list_ + ')'
     w.line0(list_ + '[] = ' + self._value.getPHPExpr()[0] + ';')
Esempio n. 24
0
 def writets(self, w: FileWriter) -> None:
     for stmt in self._lines:
         w.line0(stmt)
Esempio n. 25
0
 def writets(self, w: FileWriter) -> None:
     if self._typescript is None:
         raise Exception("Not implemented in TS")
     w.line0(self._typescript)
Esempio n. 26
0
 def writepy(self, w: FileWriter) -> None:
     if self._python is None:
         raise Exception("Not implemented in Python")
     w.line0(self._python)
Esempio n. 27
0
 def writephp(self, w: FileWriter) -> None:
     if self._php is None:
         raise Exception("Not implemented in PHP")
     w.line0(self._php)
Esempio n. 28
0
 def writephp(self, w: FileWriter) -> None:
     if isinstance(self._expr, PanOmit):
         w.line0('return;')
     else:
         w.line0('return ' + self._expr.getPHPExpr()[0] + ';')
Esempio n. 29
0
    def writepy(self, w: FileWriter) -> None:
        assert not self._isasync, "async FunctionSpec not yet supported in Python"

        # first write out overloads
        for overload in self._overloads:
            overload.writepy(w)

        # blank line
        w.blank()

        # decorators
        if self._isstaticmethod:
            w.line0('@staticmethod')

        for dec in self._decorators_py:
            w.line0(dec)
        if self._isabstract:
            w.line0('@abc.abstractmethod')

        # header
        w.line0(f'def {self._name}(')

        if self._ismethod and not self._isstaticmethod:
            w.line1('self,')

        for argname, crosstype, argdefault in self._pargs:
            argstr = argname + ': ' + crosstype.getQuotedPyType()
            if argdefault is not None:
                argstr += ' = ' + argdefault.getPyExpr()[0]
            w.line1(argstr + ',')
        if len(self._kwargs):
            # mark start of kwargs
            w.line1('*,')
        for argname, argtype, argdefault in self._kwargs:
            argstr = argname
            argstr += ': ' + argtype.getQuotedPyType()
            if argdefault is not None:
                argstr += ' = ' + argdefault.getPyExpr()[0]
            w.line1(argstr + ',')

        if self._rettype is None:
            w.line0(f') -> None:')
        else:
            w.line0(f') -> {self._rettype.getQuotedPyType()}:')

        if self._docstring:
            w.line1('"""')
            for docline in self._docstring:
                w.line1(docline.strip())
            w.line1('"""')
            havebody = True

        havebody = False

        for stmt in self._statements:
            stmt.writepy(w.with_more_indent())
            havebody = True

        if not havebody:
            w.line1('pass')
Esempio n. 30
0
 def writepy(self, w: FileWriter) -> None:
     w.line0(f'if {self._expr.getPyExpr()[0]}:')
     for stmt in self._statements:
         stmt.writepy(w.with_more_indent())
     # always put a blank line after a conditional
     w.blank()