Example #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
    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
Example #3
0
    def __generateParameter(self, currentParamNumber: int, numberOfParameters: int, pyutParam: PyutParam) -> str:
        """

        Args:
            currentParamNumber: The current parameter #
            numberOfParameters: The number of parameters the method has
            pyutParam:          What we are generating code from

        Returns:
            Python code for a single parameter
        """

        paramCode: str = ""

        paramCode = f'{paramCode}{pyutParam.getName()}'

        paramType: PyutType = pyutParam.getType()
        if paramType is not None and paramType.value != '':
            paramCode = f'{paramCode}: {paramType.value}'
        if pyutParam.getDefaultValue() is not None:
            paramCode = f'{paramCode} = {pyutParam.getDefaultValue()}'
        if currentParamNumber < numberOfParameters - 1:
            paramCode = f'{paramCode}, '

        return paramCode
Example #4
0
    def _getParam(self, Param, pyutMethod):
        """
        Extract param from Xmi file from Class part.

        @param   minidom.Element  : Param
        @param   pyutMethod for returned type
        @return  PyutParam

        @since 1.0
        @author Deve Roux <*****@*****.**>
        """
        aParam = PyutParam()

        # param's name
        name = Param.getElementsByTagName("Foundation.Core.ModelElement.name")[0].firstChild
        if name.nodeType == name.TEXT_NODE:
            self.logger.debug(f'Parameter name: {name.data}')
            if name.data[-6:] == "Return" or name.data[-6:] == "return":
                self._getTypeId(Param, pyutMethod, self.dicoReturn)
                return None
            else:
                aParam.setName(name.data)

        # default value
        self._getDefaultValue(Param, aParam)

        # for type
        self._getTypeId(Param, aParam, self.dicoType)

        return aParam
Example #5
0
    def _getParam(self, Param: Element, pyutMethod: PyutMethod):
        """
        Extract param from Xmi file from Class part.

        Args:
            Param:
            pyutMethod:

        Returns: PyutParam
        """
        aParam = PyutParam()

        # param's name
        name = Param.getElementsByTagName(
            "Foundation.Core.ModelElement.name")[0].firstChild
        if name.nodeType == name.TEXT_NODE:
            self.logger.debug(f'Parameter name: {name.data}')
            if name.data[-6:] == "Return" or name.data[-6:] == "return":
                self._getTypeId(Param, pyutMethod, self.dicoReturn)
                return None
            else:
                aParam.setName(name.data)

        # default value
        self._getDefaultValue(Param, aParam)

        # for type
        self._getTypeId(Param, aParam, self.dicoType)

        return aParam
Example #6
0
    def _writeParam(self, file: int, param: PyutParam):
        """
        Writing params to file.

        Args:
            file:   file descriptor
            param:  pyut parameter object to write
        """
        paramType: str = param.getType().__str__()
        paramName: str = param.getName()
        write(file, f'{paramType} {paramName}'.encode())
Example #7
0
    def _makeParameters(self) -> PyutParameters:

        pyutParameter1: PyutParam = PyutParam(name='intParam',
                                              parameterType=PyutType("int"),
                                              defaultValue='0')
        pyutParameter2: PyutParam = PyutParam(name='floatParam',
                                              parameterType=PyutType("float"),
                                              defaultValue='32.0')
        parameters: PyutParameters = PyutParameters(
            [pyutParameter1, pyutParameter2])

        return parameters
Example #8
0
 def _getParam(self, Param):
     aParam = PyutParam()
     if Param.hasAttribute('defaultValue'):
         aParam.setDefaultValue(Param.getAttribute('defaultValue'))
     aParam.setName(Param.getAttribute('name'))
     aParam.setType(Param.getAttribute('type'))
     return aParam
Example #9
0
    def _generateParameters(self, multiParameterNames: str) -> PyutParameters:
        """
        Handles the following 4 cases:
        Simple:                       param
        Typed:                        param: float
        SimpleDefaultValue:           param=0.0
        ComplexTypedAndDefaultValue: param: float = 0.0
        Args:
            multiParameterNames:

        Returns:  A list of PyutParam objects
        """
        parameterNameList: List[str] = multiParameterNames.split(',')
        pyutParams: PyutParameters = PyutParameters([])
        for parameterStr in parameterNameList:
            if ':' in parameterStr and '=' in parameterStr:
                pyutParam: PyutParam = self.__complexTypedAndDefaultValue(
                    parameterStr)
            elif '=' in parameterStr:
                pyutParam = self._simpleDefaultValue(parameterStr)
            elif ':' in parameterStr:
                pyutParam = self._typedParameter(parameterStr)
            else:
                pyutParam = PyutParam(parameterStr)
            pyutParams.append(pyutParam)

        return pyutParams
Example #10
0
    def _typedParameter(self, typedParam: str) -> PyutParam:
        pyutParamAndType: List[str] = typedParam.split(':')
        paramName: str = pyutParamAndType[0]
        paramType: str = pyutParamAndType[1]

        pyutParam: PyutParam = PyutParam(
            name=paramName, parameterType=PyutType(value=paramType))
        return pyutParam
Example #11
0
    def _getParam(self, domElement: Element) -> PyutParam:

        pyutParam: PyutParam = PyutParam(name=domElement.getAttribute('name'), theParameterType=domElement.getAttribute('type'))

        if domElement.hasAttribute('defaultValue'):
            pyutParam.setDefaultValue(domElement.getAttribute('defaultValue'))

        return pyutParam
Example #12
0
    def _simpleDefaultValue(self, simpleDefaultValueParam: str) -> PyutParam:

        pyutParamAndValue: List[str] = simpleDefaultValueParam.split('=')
        paramName: str = pyutParamAndValue[0]
        paramValue: str = pyutParamAndValue[1]

        pyutParam: PyutParam = PyutParam(name=paramName,
                                         defaultValue=paramValue)

        return pyutParam
Example #13
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)
Example #14
0
    def __complexTypedAndDefaultValue(self, complexParam: str) -> PyutParam:

        paramNameType: List[str] = complexParam.split(':')
        paramName: str = paramNameType[0]
        paramTypeValue: List[str] = paramNameType[1].split('=')
        paramType: str = paramTypeValue[0]
        paramValue: str = paramTypeValue[1]

        pyutType: PyutType = PyutType(paramType)
        return PyutParam(name=paramName,
                         parameterType=pyutType,
                         defaultValue=paramValue)
Example #15
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
Example #16
0
    def _onParamAdd(self, event: CommandEvent):
        """
        Add a new parameter to the list

        Args:
            event:
        """
        param: PyutParam = PyutParam()
        ret = self._callDlgEditParam(param)
        if ret == OK:
            self._pyutMethodCopy.getParams().append(param)
            # Add fields in dialog list
            self._lstParams.Append(str(param))
            self._setProjectModified()
Example #17
0
    def _dupParams(self, params):
        """
        Duplicate a list of params, all params are duplicated too.

        @since 1.9
        @author N. Dubois <*****@*****.**>
        """
        dupParams = []
        for i in params:
            param: PyutParam = PyutParam(name=i.getName(),
                                         theParameterType=i.getType(),
                                         defaultValue=i.getDefaultValue())
            dupParams.append(param)
        return dupParams
Example #18
0
    def _pyutParamToXml(self, pyutParam: PyutParam,
                        xmlDoc: Document) -> Element:
        """
        Export a PyutParam to a miniDom Element

        Args:
            pyutParam:  Parameter to save
            xmlDoc:     XML Node

        Returns:
            The new updated element
        """
        root: Element = xmlDoc.createElement(
            PyutXmlConstants.ELEMENT_MODEL_PARAM)

        root.setAttribute(PyutXmlConstants.ATTR_NAME, pyutParam.getName())
        root.setAttribute(PyutXmlConstants.ATTR_TYPE, str(pyutParam.getType()))

        defaultValue = pyutParam.getDefaultValue()
        if defaultValue is not None:
            root.setAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE,
                              defaultValue)

        return root
Example #19
0
    def _getParam(self, domElement: Element) -> PyutParam:
        """

        Args:
            domElement:  The xml element tht is a parameter

        Returns:
            A parameter model object
        """
        pyutParam: PyutParam = PyutParam(name=domElement.getAttribute(PyutXmlConstants.ATTR_NAME),
                                         theParameterType=domElement.getAttribute(PyutXmlConstants.ATTR_TYPE))

        if domElement.hasAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE):
            pyutParam.setDefaultValue(domElement.getAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE))

        return pyutParam
    def _addParameters(self, pyutMethod: PyutMethod) -> PyutMethod:

        methodName: str = pyutMethod.name
        if methodName in self.visitor.parameters:
            parameters: PyutPythonVisitor.Parameters = self.visitor.parameters[methodName]
            for parameter in parameters:
                self.logger.debug(f'parameter: {parameter}')
                paramNameType = parameter.split(':')
                #
                # TODO: account for default values
                #
                if len(paramNameType) == 2:         # Somebody is good and did typing
                    pyutType: PyutType = PyutType(paramNameType[1])
                    pyutParam: PyutParam = PyutParam(name=paramNameType[0], theParameterType=pyutType)
                    pyutMethod.addParam(pyutParam)

        return pyutMethod
Example #21
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
Example #22
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()
Example #23
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