Example #1
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("}")
Example #2
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"}}")
Example #3
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')
Example #4
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')
Example #5
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()
Example #6
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()
Example #7
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()
Example #8
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)
Example #9
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())
Example #10
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('}')
Example #11
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('}')
Example #12
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())
Example #13
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()
Example #14
0
    def writets(self, w: FileWriter) -> None:
        prefix = ''
        if self._tsexport:
            prefix = 'export '

        if self._isabstract:
            prefix += 'abstract '

        extends = ''
        if self._tsbase:
            extends = f" extends {self._tsbase}"

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

        needemptyline = False

        if self._docstring:
            for docline in self._docstring:
                w.line1('// ' + docline.strip())
            needemptyline = True

        # first write out properties
        if self._properties and needemptyline:
            w.blank()
        for prop in self._properties:
            if prop.tsobservable:
                w.blank()
                w.line1(f'@observable')
            if prop.tsreadonly:
                prefix = 'readonly '
            else:
                prefix = 'public '
            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.getTSExpr()[0]

            w.line1(
                f'{prefix}{prop.propname}: {prop.proptype.getTSType()[0]}{assign};'
            )
            needemptyline = True

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

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

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

        w.line0("}")