def __complexParseFieldToPyut(self, fieldData: str) -> PyutField: """ Can look like this: fieldData: x:int=0 Args: fieldData: Returns: """ noCommentFieldData: str = self.__stripEndOfLineComment(fieldData) fieldAndType: List[str] = noCommentFieldData.split(ReverseEngineerPython2.PYTHON_TYPE_DELIMITER) fieldName: str = fieldAndType[0] vis: PyutVisibilityEnum = self.__determineFieldVisibility(fieldName) fieldName = self.__appropriatelyCleanupName(vis=vis, fieldName=fieldName) pyutField: PyutField = PyutField(name=fieldName, visibility=vis) if len(fieldAndType) > 1: typeAndDefaultValue: List[str] = fieldAndType[1].split(ReverseEngineerPython2.PYTHON_ASSIGNMENT) pyutType: PyutType = PyutType(value=typeAndDefaultValue[0].strip()) pyutField.setType(theType=pyutType) if len(typeAndDefaultValue) > 1: pyutField.setDefaultValue(typeAndDefaultValue[1].strip()) return pyutField
def __addClassFields(self, className, modifiers, fieldType, names_values): """ Add fields to a class Note : Default value can be None. (see names_values) @param String className : Name of the class to be added @param String modifiers : Fields modifiers @param String fieldType : Fields type @param tuple names_values : tuple of (name, default values) """ # Get class fields po: OglClass = self._classes[className] pc: PyutClass = cast(PyutClass, po.pyutObject) classFields = pc.fields # 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 all for (name, value) in names_values: classFields.append(PyutField(name, fieldType, value, visibility))
def _getFields(self, xmlClass: Element) -> PyutFields: """ Extracts fields from a DOM element that represents a UML class Args: xmlClass: The DOM version of a UML class Returns: PyutFields """ pyutFields: PyutFields = cast(PyutFields, []) for element in xmlClass.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_FIELD): xmlField: Element = cast(Element, element) pyutField: PyutField = PyutField() strVis: str = xmlField.getAttribute(PyutXmlConstants.ATTR_VISIBILITY) vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis) pyutField.setVisibility(vis) xmlParam: Element = xmlField.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_PARAM)[0] if xmlParam.hasAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE): pyutField.setDefaultValue(xmlParam.getAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE)) pyutField.setName(xmlParam.getAttribute(PyutXmlConstants.ATTR_NAME)) pyutType: PyutType = PyutType(xmlParam.getAttribute(PyutXmlConstants.ATTR_TYPE)) pyutField.setType(pyutType) pyutFields.append(pyutField) return pyutFields
def testGetPublicFieldPythonCode(self): pyutType: PyutType = PyutType(value='') s: str = self.pyutToPython.generateFieldPythonCode(PyutField("publicField", pyutType, None, PyutVisibilityEnum.PUBLIC)) unExpectedValue: int = -1 actualValue: int = s.find('self.publicField') self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate public method correctly: `{s}`')
def testGetProtectedFieldPythonCode(self): pyutType: PyutType = PyutType(value='') s: str = self.pyutToPython.generateFieldPythonCode(PyutField("protectedField", pyutType, None, PyutVisibilityEnum.PROTECTED)) unExpectedValue: int = -1 actualValue: int = s.find('self._protectedField') self.assertNotEqual(unExpectedValue, actualValue, f'Did not code generate protected field correctly: `{s}`')
def testGetPrivateFieldPythonCode(self): s: str = self.pyutToPython.generateFieldPythonCode( PyutField("privateField", "", None, PyutVisibilityEnum.PRIVATE)) unExpectedValue: int = -1 actualValue: int = s.find('self.__privateField') self.assertNotEqual( unExpectedValue, actualValue, f'Did not code generate private method correctly: `{s}`')
def _getFields(self, Class): """ To extract fields from Class. """ # for class fields allFields = [] for Field in Class.getElementsByTagName("Field"): aField = PyutField() aField.setVisibility(Field.getAttribute('visibility')) Param = Field.getElementsByTagName("Param")[0] if Param.hasAttribute('defaultValue'): aField.setDefaultValue(Param.getAttribute('defaultValue')) aField.setName(Param.getAttribute('name')) aField.setType(Param.getAttribute('type')) allFields.append(aField) return allFields
def __simpleParseFieldToPyut(self, fieldData: str) -> PyutField: pyutField: PyutField = PyutField() noCommentFieldData: str = self.__stripEndOfLineComment(fieldData) fieldAndValue: List[str] = noCommentFieldData.split(ReverseEngineerPython2.PYTHON_ASSIGNMENT) pyutField.name = fieldAndValue[0].strip() pyutField.defaultValue = fieldAndValue[1].strip() return pyutField
def testDeepCopyList(self): originalFields: List[PyutField] = [] for x in range(len(TestPyutField.fieldNames)): field: PyutField = PyutField(name=TestPyutField.fieldNames[x], theFieldType=TestPyutField.fieldTypes[x], defaultValue=TestPyutField.fieldValues[x], visibility=TestPyutField.fieldVisibilities[x] ) originalFields.append(field) self.logger.info(f'originalFields: {originalFields}') doppleGangers: List[PyutField] = deepcopy(originalFields) self.logger.info(f'doppleGangers: {doppleGangers}')
def _getFields(self, Class): """ To extract fields form Class. @since 1.0 @author Deve Roux <*****@*****.**> """ # for class fields allFields = [] for Field in Class.getElementsByTagName("Field"): aField = PyutField() # aField.setVisibility(Field.getAttribute('visibility')) vis: PyutVisibilityEnum = PyutVisibilityEnum(Field.getAttribute('visibility')) aField.setVisibility(vis) Param = Field.getElementsByTagName("Param")[0] if Param.hasAttribute('defaultValue'): aField.setDefaultValue(Param.getAttribute('defaultValue')) aField.setName(Param.getAttribute('name')) aField.setType(Param.getAttribute('type')) allFields.append(aField) return allFields
def __simpleParseFieldToPyut(self, fieldData: str) -> PyutField: pyutField: PyutField = PyutField() noCommentFieldData: str = self.__stripEndOfLineComment(fieldData) fieldAndValue: List[str] = noCommentFieldData.split( ReverseEngineerPython2.PYTHON_ASSIGNMENT) if len(fieldAndValue) == 2: pyutField.name = fieldAndValue[0].strip() pyutField.defaultValue = fieldAndValue[1].strip() else: # might just be a declaration pyutField = self.__declarationOnlyParseToPyut( fieldData=fieldAndValue[0]) return pyutField
def __declarationOnlyParseToPyut(self, fieldData: str) -> PyutField: self.logger.info(f'{fieldData=}') fieldAndType: List[str] = fieldData.split( ReverseEngineerPython2.PYTHON_TYPE_DELIMITER) pyutField: PyutField = PyutField(name=fieldAndType[0]) # # Might be something complex expression as a default value we can't handle it # if len(fieldAndType) > 1: pyutField.type = PyutType(value=fieldAndType[1]) pyutField.visibility = PyutVisibilityEnum.PUBLIC return pyutField
def _getFields(self, elementClass: Element): """ Extract fields from Class. Args: elementClass: Returns: A list of PyutField's """ allFields = [] for Field in elementClass.getElementsByTagName( "Foundation.Core.Attribute"): aField: PyutField = PyutField() # name = Field.getElementsByTagName("Foundation.Core.ModelElement.name")[0].firstChild fieldElements: NodeList = Field.getElementsByTagName( "Foundation.Core.ModelElement.name") self.logger.debug( f'_getFields - {fieldElements=} {fieldElements.length=} type(fieldElements): {type(fieldElements)}' ) fieldElt: Element = fieldElements.item(0) name = fieldElt.firstChild if name.nodeType == name.TEXT_NODE: aField.setName(name.data) # field visibility -- Be verbose for maintainability # visibility = Field.getElementsByTagName ("Foundation.Core.ModelElement.visibility")[0] # aField.setVisibility(self._xmiVisibility2PyutVisibility(visibility.getAttribute('xmi.value'))) visibilityElements: NodeList = Field.getElementsByTagName( "Foundation.Core.ModelElement.visibility") visElt: Element = visibilityElements.item(0) if visElt is None: visStr: str = 'public' else: visStr = visElt.getAttribute('xmi.value') vis: PyutVisibilityEnum = self._xmiVisibility2PyutVisibility( visStr) aField.setVisibility(vis) # default value self._getDefaultValue(Field, aField) # for type self._getTypeId(Field, aField, self.dicoType) allFields.append(aField) return allFields
def _createEnumerationFields(self, pyutClass: PyutClass, enumValues: List[str]): """ TODO: Create a PyutEnumeration at some point For now simulate with a bunch of fields in a class that is `Stereotyped` as Enumeration """ pyutClass.setStereotype(stereotype=XSDParser.ENUMERATION_STEREOTYPE) pyutClass.setShowStereotype(theNewValue=True) for val in enumValues: pyutField: PyutField = PyutField( name=val.upper(), defaultValue=val, visibility=PyutVisibilityEnum.PUBLIC) pyutClass.addField(pyutField)
def _addAttributesToClasses(self): for classAttr in DTDParser.attributes: typedAttr: DTDAttribute = cast(DTDAttribute, classAttr) className: str = typedAttr.elementName treeData: ElementTreeData = self.classTree[className] attrName: str = typedAttr.attributeName attrType: str = typedAttr.attributeType attrValue: str = typedAttr.attributeValue pyutField: PyutField = PyutField(name=attrName, theFieldType=attrType, defaultValue=attrValue, visibility=PyutVisibilityEnum.PUBLIC) self.logger.info(f'pyutField: {pyutField}') pyutClass: PyutClass = treeData.pyutClass pyutClass.addField(pyutField)
def _readFoundationCoreClassifierFeature(self, coreClass, pyutClass): """ Read one Foundation.Core.Class @param coreClass : Foundation.Core.Class element @param pyutClass : PyutClass object to which add features @return 1/0 if the class is abstract or not @author C.Dutoit """ # Get feature xmiFeature = coreClass.getElementsByTagName( "Foundation.Core.Classifier.feature") if len(xmiFeature) == 0: return # Read all feature attribute pyutFields = [] for xmiAttribute in xmiFeature[0].getElementsByTagName( "Foundation.Core.Attribute"): self.logger.info("Attribute ", end=' ') # Read attribute name el = xmiAttribute.getElementsByTagName( "Foundation.Core.ModelElement.name") if len(el) > 0: name = el[0].firstChild.wholeText else: name = "Unnamed_Attribute" self.logger.info(name, end=' ') # Read attribute visibility el = xmiAttribute.getElementsByTagName( "Foundation.Core.ModelElement.visibility") if len(el) > 0: visibility = el[0].getAttribute("xmi.value") else: visibility = "Unvisibilityd_Attribute" self.logger.info("v=", visibility) # Add feature attribute to pyut Fields # name, type, def, vis pyutFields.append(PyutField(name, "", None, visibility)) # Add feature attributes to pyutClass pyutClass.setFields(pyutFields)
def _onFieldAdd(self, event: CommandEvent): """ Add a new field in the list. Args: event: """ field = PyutField() ret = self._callDlgEditField(field) if ret == OK: self._pyutModelCopy.fields.append(field) # Add fields in dialog list self._lstFieldList.Append(str(field)) # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified()
def _pyutFieldToXml(self, pyutField: PyutField, xmlDoc: Document) -> Element: """ Export a PyutField to a miniDom Element Args: pyutField: The PyutField to save xmlDoc: The xml document to update Returns: The new updated element """ root: Element = xmlDoc.createElement( PyutXmlConstants.ELEMENT_MODEL_FIELD) root.appendChild(self._pyutParamToXml(pyutField, xmlDoc)) root.setAttribute(PyutXmlConstants.ATTR_VISIBILITY, str(pyutField.getVisibility())) return root
def testDeepCopyList(self): originalFields: List[PyutField] = [] for x in range(len(TestPyutField.fieldNames)): field: PyutField = PyutField( name=TestPyutField.fieldNames[x], fieldType=TestPyutField.fieldTypes[x], defaultValue=TestPyutField.fieldValues[x], visibility=TestPyutField.fieldVisibilities[x]) originalFields.append(field) self.logger.info(f'originalFields: {originalFields}') doppleGangers: List[PyutField] = deepcopy(originalFields) self.logger.info(f'doppleGangers: {doppleGangers}') for pyutField in doppleGangers: self.assertTrue(isinstance(pyutField.type, PyutType), 'Wrong type copied') self.assertTrue( isinstance(pyutField.visibility, PyutVisibilityEnum), 'Wrong visibility type copied')
def generateFieldPythonCode(self, pyutField: PyutField): """ Generate the Python code for a given field Args: pyutField: The PyutField that is the source of our code generation Returns: Python Code !! """ fieldCode: str = "self." fieldCode = f'{fieldCode}{self.generateVisibilityPrefix(pyutField.getVisibility())}' fieldCode = f'{fieldCode}{pyutField.getName()}: {pyutField.getType()}' value = pyutField.getDefaultValue() if value == '': fieldCode = f'{fieldCode} = None' else: fieldCode = f'{fieldCode} = {value}' fieldCode = f'{fieldCode}\n' return fieldCode
def _addFields(self, className: str, content: List[XsdElement]): """ Has the side effect that it updates the class tree data with the class names of the children Args: className: The class name for which we are adding fields to content: The list of xsd elements that represents the fields """ classTreeData: ElementTreeData = self.classTree[className] pyutClass: PyutClass = classTreeData.pyutClass for contentElement in content: xsdElement: XsdElement = cast(XsdElement, contentElement) self.logger.info( f'xsdElement: {xsdElement} {xsdElement.local_name} {xsdElement.type}' ) defaultValue = xsdElement.default # if defaultValue is None: # defaultValue = '' # else: # self.logger.warning(f'Handle a real default value for a field') xsdType: XsdType = xsdElement.type childClassName: str = xsdElement.local_name pyutField: PyutField = PyutField( name=childClassName, fieldType=xsdType.local_name, defaultValue=defaultValue, visibility=PyutVisibilityEnum.PUBLIC) # # SIDE EFFECT !!!!! # self.updateChildTypes(classTreeData, xsdElement) pyutClass.addField(pyutField) oglClass: OglClass = classTreeData.oglClass oglClass.autoResize()
def _getFields(self, Class): """ To extract fields from Class. @param minidom.Element : Class @return [] with PyutField @since 1.0 @author Deve Roux <*****@*****.**> """ allFields = [] for Field in Class.getElementsByTagName("Foundation.Core.Attribute"): aField = PyutField() # name = Field.getElementsByTagName("Foundation.Core.ModelElement.name")[0].firstChild fieldElts: NodeList = Field.getElementsByTagName("Foundation.Core.ModelElement.name") self.logger.debug(f'_getFields - fieldElts: {fieldElts} fieldElts.length: {fieldElts.length} type(fieldElts): {type(fieldElts)}') fieldElt: Element = fieldElts.item(0) name = fieldElt.firstChild if name.nodeType == name.TEXT_NODE: aField.setName(name.data) # field visibility -- Be verbose for debugability # visibility = Field.getElementsByTagName ("Foundation.Core.ModelElement.visibility")[0] # aField.setVisibility(self._xmiVisibility2PyutVisibility(visibility.getAttribute('xmi.value'))) visElts: NodeList = Field.getElementsByTagName("Foundation.Core.ModelElement.visibility") visElt: Element = visElts.item(0) if visElt is None: visStr: str = 'public' else: visStr: str = visElt.getAttribute('xmi.value') vis: PyutVisibilityEnum = self._xmiVisibility2PyutVisibility(visStr) aField.setVisibility(vis) # default value self._getDefaultValue(Field, aField) # for type self._getTypeId(Field, aField, self.dicoType) allFields.append(aField) return allFields
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()
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