Ejemplo n.º 1
0
    def _createProperties(
            self, propName: str,
            setterParams: List[str]) -> Tuple[PyutMethod, PyutMethod]:

        getter: PyutMethod = PyutMethod(name=propName,
                                        visibility=PyutVisibilityEnum.PUBLIC)
        if len(setterParams) == 0:
            setter: PyutMethod = cast(PyutMethod, None)
        else:
            setter = PyutMethod(name=propName,
                                visibility=PyutVisibilityEnum.PUBLIC)

        if setter is not None:
            nameType: str = setterParams[0]
            potentialNameType: List[str] = nameType.split(':')

            if len(potentialNameType) == 2:

                param: PyutParam = PyutParam(
                    name=potentialNameType[0],
                    parameterType=PyutType(value=potentialNameType[1]))
                setter.addParam(param)
                getter.returnType = PyutType(value=potentialNameType[1])
            else:
                param = PyutParam(name=potentialNameType[0])
                setter.addParam(param)

        return setter, getter
Ejemplo n.º 2
0
    def __addClassMethod(self, className, modifiers, returnType, name,
                         lstFields):
        """
        Add a method to a class
        Parameters example:
        ```java
            static private int getName(int a, long b)
            - className = name of the class which own this method
            - static private => modifiers
            - int            => return type
            - getName        => name
            - int a, long b  => lstFields => ["int a", "long b"]
        ```
        Note : Default value can be None. (see names_values)

        Args:
            className:  Name of the class to add
            modifiers:  Method modifiers
            returnType: Method returnType
            name:       Method name
            lstFields:  List of string lstFields : Method fields
        """

        self.__logMessage("Adding method %s for class %s" % (name, className))
        self.__logMessage("(modifiers=%s; returnType=%s)" %
                          (modifiers, returnType))
        # Get class fields
        po: OglClass = self._classes[className]
        pc: PyutClass = cast(PyutClass, po.pyutObject)

        # TODO fix this crazy code to use constructor and catch exception on bad input
        # Get visibility
        if "private" in modifiers:
            visibility: PyutVisibilityEnum = PyutVisibilityEnum.PRIVATE
        elif "protected" in modifiers:
            visibility: PyutVisibilityEnum = PyutVisibilityEnum.PROTECTED
        elif "public" in modifiers:
            visibility: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC
        else:
            visibility: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC

        # Add method
        methods = pc.methods

        if returnType == '\n' or returnType == '' or returnType == 'void' or returnType is None:
            pm = PyutMethod(name, visibility)
        else:
            retType: PyutType = PyutType(returnType)
            pm = PyutMethod(name, visibility, retType)

        for (paramType, name, defaultValue) in lstFields:
            param = PyutParam(name, paramType, defaultValue)
            pm.addParam(param)
        methods.append(pm)
Ejemplo n.º 3
0
    def _generatePyutClasses(self):

        for className in self._classNames():
            pyutClass: PyutClass = PyutClass(name=className)

            pyutClass = self._addFields(pyutClass)

            for methodName in self._methodNames(className):
                pyutMethod: PyutMethod = PyutMethod(name=methodName)
                if methodName[0:2] == "__":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE)
                elif methodName[0] == "_":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED)
                else:
                    pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC)
                pyutMethod = self._addParameters(pyutMethod)
                pyutMethod.sourceCode = self.visitor.methodCode[methodName]

                pyutClass.addMethod(pyutMethod)
            setterProperties: PyutPythonVisitor.Parameters = self.visitor.setterProperties
            getterProperties: PyutPythonVisitor.Parameters = self.visitor.getterProperties
            for propName in self.visitor.propertyNames:

                setterParams: List[str] = setterProperties[propName]
                getterParams: List[str] = getterProperties[propName]
                self.logger.info(f'Processing - {propName=} {setterParams=} {getterParams=}')
                setter, getter = self._createProperties(propName=propName, setterParams=setterParams)
                pyutClass.addMethod(setter)
                pyutClass.addMethod(getter)

            self._pyutClasses[className] = pyutClass
        self.logger.info(f'Generated {len(self._pyutClasses)} classes')
    def generatePyutMethods(self,
                            clmethods: List[classmethod]) -> List[PyutMethod]:

        methods: List[PyutMethod] = []
        for me in clmethods:
            funcName: str = me.__name__
            meth: PyutMethod = PyutMethod(funcName)

            if me is not None:
                args = getfullargspec(me)
                if args[3] is None:
                    firstDefVal = len(args[0])
                else:
                    firstDefVal = len(args[0]) - len(args[3])
                for arg, i in zip(args[0], range(len(args[0]))):
                    # don't add self, it's implied
                    if arg != "self":
                        if i >= firstDefVal:
                            defVal = args[3][i - firstDefVal]
                            if isinstance(defVal, str):
                                defVal = f'"{defVal}"'
                            param = PyutParam(arg, "", str(defVal))
                        else:
                            param = PyutParam(arg)
                        meth.addParam(param)
            methods.append(meth)
            # set the visibility according to naming conventions
            func_name = funcName
            if func_name[-2:] != "__":
                if func_name[0:2] == "__":
                    meth.setVisibility("-")
                elif func_name[0] == "_":
                    meth.setVisibility("#")

        return methods
Ejemplo n.º 5
0
    def _getMethods(self, Class):
        """
        To extract methods from interface.
        """
        # class methods for this current class
        allMethods = []
        for Method in Class.getElementsByTagName("Method"):

            # method name
            aMethod = PyutMethod(Method.getAttribute('name'))

            # method visibility
            aMethod.setVisibility(Method.getAttribute('visibility'))

            # for method return type
            Return = Method.getElementsByTagName("Return")[0]
            aMethod.setReturns(Return.getAttribute('type'))

            # for methods param
            allParams = []
            for Param in Method.getElementsByTagName("Param"):
                allParams.append(self._getParam(Param))

            # setting the params for this method
            aMethod.setParams(allParams)
            # adding this method in all class methods
            allMethods.append(aMethod)

        return allMethods
Ejemplo n.º 6
0
    def _generatePyutClasses(self):

        for className in self._classNames():
            pyutClass: PyutClass = PyutClass(name=className)

            pyutClass = self._addFields(pyutClass)

            for methodName in self._methodNames(className):
                pyutMethod: PyutMethod = PyutMethod(name=methodName)
                if methodName[0:2] == "__":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE)
                elif methodName[0] == "_":
                    pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED)
                else:
                    pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC)
                pyutMethod = self._addParameters(pyutMethod)
                pyutMethod.sourceCode = self.visitor.methodCode[methodName]

                pyutClass.addMethod(pyutMethod)

            setterProperties: Parameters = self.visitor.setterProperties
            getterProperties: Parameters = self.visitor.getterProperties

            pyutClass = self._generatePropertiesAsMethods(
                pyutClass, getterProperties, setterProperties)

            if className in self.visitor.dataClassNames:
                self._createDataClassPropertiesAsFields(
                    pyutClass, self.visitor.dataClassProperties)

            self._pyutClasses[className] = pyutClass
        self.logger.info(f'Generated {len(self._pyutClasses)} classes')
Ejemplo n.º 7
0
    def _generateAMethod(self) -> PyutMethod:
        pyutMethod: PyutMethod = PyutMethod(name='OzzeeElGatoDiablo')

        pyutMethod.sourceCode = SourceCode([
            'weLeft:           bool = True', 'isOzzeeAGoodGato: bool = False',
            'if weLeft is True:', '    isOzzeeAGoodGato = True',
            'return isOzzeeAGoodGato'
        ])
        return pyutMethod
Ejemplo n.º 8
0
    def testGetOneMethodCodePrivate(self):

        pyutType: PyutType = PyutType(value='str')
        publicMethod: PyutMethod = PyutMethod(name='privateMethod', visibility=PyutVisibilityEnum.PRIVATE, returns=pyutType)

        defCode: List[str] = self.pyutToPython.generateASingleMethodsCode(publicMethod, writePass=False)
        self.logger.info(f'Generated definition: {defCode}')
        unExpectedValue: int = -1
        actualValue:     int = defCode.__contains__('def __privateMethod')

        self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate private method correctly: `{defCode}`')
Ejemplo n.º 9
0
    def _getMethods(self, Class):
        """
        Extract a method from a Xmi file from Class part.

        Args:
            Class:  An XML Class

        Returns:  A PyutMethod
        """
        # class methods for this current class
        allMethods = []

        for Method in Class.getElementsByTagName("Foundation.Core.Operation"):

            self.logger.debug(f'_getMethods - Method: {Method}')
            # name = Method.getElementsByTagName("Foundation.Core.ModelElement.name")[0].firstChild
            methodElements: NodeList = Method.getElementsByTagName(
                "Foundation.Core.ModelElement.name")

            self.logger.debug(
                f'_getMethods - {methodElements=}  {methodElements.length=}  type(methodElements): {type(methodElements)}'
            )
            if methodElements.length == 0:
                continue
            elt = methodElements.item(0)
            self.logger.debug(f'_getMethods - elt: {elt}')
            name = elt.firstChild

            if name.nodeType == name.TEXT_NODE:
                aMethod = PyutMethod(name.data)
                self.logger.debug(f'Method name: {name.data}')
                # method visibility
                visibility = Method.getElementsByTagName(
                    "Foundation.Core.ModelElement.visibility")[0]
                # aMethod.setVisibility(self._xmiVisibility2PyutVisibility (visibility.getAttribute('xmi.value')))
                visStr: str = visibility.getAttribute('xmi.value')
                vis: PyutVisibilityEnum = self._xmiVisibility2PyutVisibility(
                    visStr)
                self.logger.debug(f'Method visibility: {vis}')
                aMethod.setVisibility(vis)
                allParams = []
                for Param in Method.getElementsByTagName(
                        "Foundation.Core.Parameter"):
                    pyutParam = self._getParam(Param, aMethod)
                    if pyutParam is not None:
                        allParams.append(pyutParam)

                aMethod.setParams(allParams)

                # adding this method in all class methods
                allMethods.append(aMethod)

        return allMethods
Ejemplo n.º 10
0
    def _generateAMethod(self) -> PyutMethod:
        pyutMethod: PyutMethod = PyutMethod(name='OzzeeElGatoDiablo')

        pyutMethod.sourceCode = SourceCode([
            'weLeft:           bool = True', 'isOzzeeAGoodGato: bool = False',
            'if weLeft is True:', '    isOzzeeAGoodGato = True',
            'return isOzzeeAGoodGato'
        ])
        pyutMethod.modifiers = PyutModifiers(
            [PyutModifier(modifierTypeName='static'),
             PyutModifier('bogus')])
        pyutMethod.returnType = PyutType('str')
        return pyutMethod
Ejemplo n.º 11
0
    def _getMethods(self, xmlClass: Element) -> PyutMethods:
        """
        Converts XML methods to `PyutMethod`s
        Args:
            xmlClass:  A DOM element that is a UML Class

        Returns:
            A list of `PyutMethod`s associated with the class
        """
        allMethods: PyutMethods = cast(PyutMethods, [])
        for xmlMethod in xmlClass.getElementsByTagName(
                PyutXmlConstants.ELEMENT_MODEL_METHOD):

            pyutMethod: PyutMethod = PyutMethod(
                xmlMethod.getAttribute(PyutXmlConstants.ATTR_NAME))

            strVis: str = xmlMethod.getAttribute(
                PyutXmlConstants.ATTR_VISIBILITY)
            vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis)
            pyutMethod.setVisibility(visibility=vis)

            returnElt: Element = xmlMethod.getElementsByTagName(
                PyutXmlConstants.ELEMENT_MODEL_RETURN)[0]
            retTypeStr: str = returnElt.getAttribute(
                PyutXmlConstants.ATTR_TYPE)
            retType: PyutType = PyutType(retTypeStr)
            pyutMethod.setReturns(retType)

            #
            #  Code supports multiple modifiers, but the dialog allows input of only one
            #
            modifiers: NodeList = xmlMethod.getElementsByTagName(
                PyutXmlConstants.ELEMENT_MODEL_MODIFIER)
            for xmlModifier in modifiers:
                xmlModifier: Element = cast(Element, xmlModifier)
                modName: str = xmlModifier.getAttribute(
                    PyutXmlConstants.ATTR_NAME)

                pyutModifier: PyutModifier = PyutModifier(modName)
                pyutMethod.addModifier(pyutModifier)

            methodParameters = []
            for xmlParam in xmlMethod.getElementsByTagName(
                    PyutXmlConstants.ELEMENT_MODEL_PARAM):
                methodParameters.append(self._getParam(xmlParam))

            pyutMethod.setParams(methodParameters)

            allMethods.append(pyutMethod)

        return allMethods
Ejemplo n.º 12
0
    def deserialize(cls, serializedData: str,
                    pyutObject: PyutClassCommon) -> PyutClassCommon:
        """

        Args:
            serializedData:
            pyutObject:

        Returns:  The updated PyutClass or PyutInterface

        """

        classDescription = deTokenize("classDescription", serializedData)

        pyutObject.description = classDescription

        methods = eval(deTokenize("methods", serializedData))

        pyutMethods: List[PyutMethod] = []

        for methodProfile in methods:

            # construction of a method
            methodName: str = methodProfile[0]
            methodVisibility: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(
                methodProfile[1])
            methodReturns: PyutType = PyutType(value=methodProfile[2])

            pyutMethod: PyutMethod = PyutMethod(name=methodName,
                                                visibility=methodVisibility,
                                                returns=methodReturns)

            # deserialize method's parameters;  Get the tuple (name, Type, defaultValue)
            params = eval(methodProfile[3])
            for param in params:
                paramName: str = param[0]
                paramType: PyutType = PyutType(param[1])
                paramDefaultValue: str = param[2]

                # creates and add the param to the method
                pyutParam: PyutParam = PyutParam(
                    name=paramName,
                    parameterType=paramType,
                    defaultValue=paramDefaultValue)
                pyutMethod.addParam(pyutParam)

            pyutMethods.append(pyutMethod)

        pyutObject.methods = pyutMethods
        return pyutObject
Ejemplo n.º 13
0
    def generateMethodsCode(self, pyutClass: PyutClass) -> MethodsCodeType:
        """
        Return a dictionary of method code for a given class

        Args:
            pyutClass:  The data model class for which we have to generate a bunch fo code for

        Returns:
            A bunch of code that is the code for this class; The map key is the method name the
            value is a list of the method code
        """
        clsMethods = cast(PyutToPython.MethodsCodeType, {})
        for pyutMethod in pyutClass.methods:
            # Separation
            txt = ""
            lstCodeMethod = [txt]

            # Get code
            subCode:       List[str] = self.generateASingleMethodsCode(pyutMethod)
            lstCodeMethod += self.indent(subCode)

            clsMethods[pyutMethod.getName()] = lstCodeMethod

        # Add fields
        if len(pyutClass.fields) > 0:
            # Create method __init__ if it does not exist
            if PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR not in clsMethods:
                # Separation
                lstCodeMethod = []

                subCode = self.generateASingleMethodsCode(PyutMethod(PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR), False)

                for el in self.indent(subCode):
                    lstCodeMethod.append(str(el))

                clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR] = lstCodeMethod

            clsInit = clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR]
            for pyutField in pyutClass.fields:
                clsInit.append(self.__indentStr(self.__indentStr(self.generateFieldPythonCode(pyutField))))
            clsInit.append('\n')

        return clsMethods
Ejemplo n.º 14
0
    def _onMethodAdd(self, event: CommandEvent):
        """
        Add a new method in the list.
        Args:
            event:
        """
        # Add fields in PyutClass copy object
        method: PyutMethod = PyutMethod(PyutMethod.DEFAULT_METHOD_NAME)
        ret = self._invokeEditMethodDialog(method)
        if ret == OK:
            self._pyutModelCopy.methods.append(method)
            # Add fields in dialog list
            self._lstMethodList.Append(method.getString())

            # Tell window that its data has been modified
            fileHandling = self._mediator.getFileHandling()
            project = fileHandling.getCurrentProject()
            if project is not None:
                project.setModified()
Ejemplo n.º 15
0
    def createTestMethod(cls, name: str, visibility: PyutVisibilityEnum,
                         returnType: PyutType) -> PyutMethod:

        pyutMethod: PyutMethod = PyutMethod()

        pyutMethod.name = name
        pyutMethod.visibility = visibility
        pyutMethod.returnType = returnType

        pyutParam: PyutParam = PyutParam(
            name=f'param{TestCommandCommon.methodParamNumber}',
            parameterType=PyutType(
                f'Type{TestCommandCommon.methodTypeNumber}'),
            defaultValue='')

        pyutMethod.addParam(pyutParam)

        TestCommandCommon.methodParamNumber += 1
        TestCommandCommon.methodTypeNumber += 1

        return pyutMethod
Ejemplo n.º 16
0
    def read(self, umlObject, file):
        """
        Read data from file

        format:
        ```Python
        class name
        <<stereotype_optional>>
        +method([param[:type]]*)[:type_return]
        +field[:type][=value_initial]
        ```

        for example:

        ParentClass
        +strMethod(strParam : str = bogus) : str
        +intMethod(intParam = 1) : int
        +floatField : float = 1.0
        +booleanField : bool = True

        Args:
            umlObject:
            file:
        """
        className: str = file.readline().strip()
        pyutClass: PyutClass = umlObject.getPyutObject()
        pyutClass.setName(className)

        # process stereotype if present
        nextStereoType: str = file.readline().strip()
        if nextStereoType[0:2] == "<<":
            pyutClass.setStereotype(nextStereoType[2:-2].strip())
            nextStereoType = file.readline().strip()

        methods = []
        fields = []
        pyutClass.methods = methods
        pyutClass.fields = fields

        # process methods and fields
        visValues: List[str] = PyutVisibilityEnum.values()
        while True:
            if nextStereoType == "":
                break

            # search visibility

            if nextStereoType[0] in visValues:
                visStr = nextStereoType[0]
                vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(visStr)
                nextStereoType = nextStereoType[1:]
            else:
                vis: PyutVisibilityEnum = PyutVisibilityEnum.PUBLIC

            pos = nextStereoType.find("(")
            params = []
            if pos != -1:
                # process method
                name = nextStereoType[0:pos].strip()
                nextStereoType = nextStereoType[pos + 1:]
                pos = nextStereoType.find(")")

                # TODO return typ should be PyutType
                returnType: str = ""
                if pos != -1:
                    params = self._findParams(nextStereoType[:pos])
                    nextStereoType = nextStereoType[pos + 1:]
                    pos = nextStereoType.find(":")

                    if pos != -1:
                        returnType = nextStereoType[pos + 1:].strip()
                    else:
                        returnType = ""
                method = PyutMethod(name, vis, returnType)

                method.setParams([PyutParam(x[0], x[1]) for x in params])
                methods.append(method)
            else:
                # process field
                field = self._findParams(nextStereoType)[0]
                if field:
                    fields.append(PyutField(field[0], field[1],
                                            visibility=vis))

            nextStereoType = file.readline().strip()
Ejemplo n.º 17
0
    def deserialize(self, serializedData):
        """
        deserialize the data needed by the destroyed OglLinkedObject.

        Args:
            serializedData: serialized data needed by the command.
        """
        from org.pyut.model.PyutMethod import PyutMethod
        from org.pyut.model.PyutParam import PyutParam
        from org.pyut.model.PyutField import PyutField

        from org.pyut.model.PyutStereotype import PyutStereotype
        from org.pyut.model.PyutModifier import PyutModifier

        # deserialize the data common to all OglObjects
        DelOglLinkedObjectCommand.deserialize(self, serializedData)

        # deserialize properties of the OglClass (first level)
        classDescription = getTokenValue("classDescription", serializedData)
        classStereotypeName = getTokenValue("classStereotypeName",
                                            serializedData)
        classShowStereotype = eval(
            getTokenValue("classShowStereotype", serializedData))
        classShowMethods = eval(
            getTokenValue("classShowMethods", serializedData))
        classShowFields = eval(getTokenValue("classShowFields",
                                             serializedData))

        methods = eval(getTokenValue("methods", serializedData))
        fields = eval(getTokenValue("fields", serializedData))

        # set up the first level properties of the pyutClass
        pyutClass: PyutClass = self._shape.getPyutObject()
        pyutClass.description = classDescription

        if cmp(classStereotypeName, ""):
            pyutStereo = PyutStereotype(classStereotypeName)
            pyutClass.setStereotype(pyutStereo)

        pyutClass.setShowStereotype(classShowStereotype)
        pyutClass.showMethods = classShowMethods
        pyutClass.showFields = classShowFields

        for field in fields:

            fieldName = field[0]
            fieldType = field[1]
            fieldDefaultValue = field[2]
            fieldVisibility = field[3]
            pyutClass.addField(
                PyutField(fieldName, fieldType, fieldDefaultValue,
                          fieldVisibility))

        methodsList = []
        # deserialize methods of the pyutClass
        for methodProfile in methods:

            # construction of a method
            methodName = methodProfile[0]
            methodVisibility = methodProfile[1]
            methodReturns = methodProfile[2]
            method = PyutMethod(methodName, methodVisibility, methodReturns)

            # deserialize method's params so we get a tuple (name, Type, defaultValue)
            params = eval(methodProfile[3])
            for param in params:
                paramName = param[0]

                # construction of the type of the param
                paramType = param[1]
                # pyutType = PyutType(paramType)   Not used
                paramDefaultValue = param[2]

                # creates and add the param to the method
                method.addParam(
                    PyutParam(paramName, paramType, paramDefaultValue))

            # deserialize method's modifiers so we get a list of names
            # that we have to transform into a list of PyutModifiers.
            modifiersNames = eval(methodProfile[4])
            modifiers = []
            for modifierName in modifiersNames:
                modifiers.append(PyutModifier(modifierName))

            # add the modifiers to the method
            method.setModifiers(modifiers)
            # add the method to the list of methods
            methodsList.append(method)

        # add all the methods to the list
        pyutClass.methods = methodsList
Ejemplo n.º 18
0
 def setUp(self):
     self.logger: Logger = TestPyutMethod.clsLogger
     self._pyutMethod: PyutMethod = PyutMethod()