id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
749,514
|
advancedcodegenerator.cpp
|
KDE_umbrello/umbrello/codegenerators/advancedcodegenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "advancedcodegenerator.h"
#include "classifier.h"
#include "classifiercodedocument.h"
#include "codeviewerdialog.h"
#include "uml.h"
#include "umldoc.h"
/**
* Constructor
*/
AdvancedCodeGenerator::AdvancedCodeGenerator()
{
}
/**
* Destructor
*/
AdvancedCodeGenerator::~AdvancedCodeGenerator()
{
}
/**
* Get the editing dialog for this code document.
*/
CodeViewerDialog * AdvancedCodeGenerator::getCodeViewerDialog(QWidget* parent, CodeDocument *doc,
Settings::CodeViewerState & state)
{
return new CodeViewerDialog(parent, doc, state);
}
/**
* This function checks for adding objects to the UMLDocument.
*/
void AdvancedCodeGenerator::checkAddUMLObject(UMLObject * obj)
{
if (!obj) {
return;
}
UMLClassifier * c = obj->asUMLClassifier();
if (c) {
CodeDocument * cDoc = newClassifierCodeDocument(c);
addCodeDocument(cDoc);
}
}
/**
* This function checks for removing objects from the UMLDocument.
*/
void AdvancedCodeGenerator::checkRemoveUMLObject(UMLObject * obj)
{
if (!obj) {
return;
}
UMLClassifier * c = obj->asUMLClassifier();
if (c) {
ClassifierCodeDocument * cDoc = (ClassifierCodeDocument*) findCodeDocumentByClassifier(c);
if (cDoc) {
removeCodeDocument(cDoc);
}
}
}
/**
* Initialize this code generator from its parent UMLDoc. When this is called,
* it will (re-)generate the list of code documents for this project (generator)
* by checking for new objects/attributes which have been added or changed in the
* document. One or more CodeDocuments will be created/overwritten/amended as is
* appropriate for the given language.
* <p>ClassifierCodeDocument
* In this 'generic' version a ClassifierCodeDocument will exist for each and
* every classifier that exists in our UMLDoc. IF when this is called, a code document
* doesn't exist for the given classifier, then we will created and add a new code
* document to our generator.
* <p>
* IF you want to add non-classifier related code documents at this step,
* you will need to overload this method in the appropriate
* code generatator (see JavaCodeGenerator for an example of this).
*/
void AdvancedCodeGenerator::initFromParentDocument()
{
// Walk through the document converting classifiers into
// classifier code documents as needed (e.g only if doesn't exist)
UMLClassifierList concepts = m_document->classesAndInterfaces();
for(UMLClassifier *c : concepts) {
// Doesn't exist? Then build one.
CodeDocument * codeDoc = findCodeDocumentByClassifier(c);
if (!codeDoc) {
codeDoc = newClassifierCodeDocument(c);
addCodeDocument(codeDoc); // this will also add a unique tag to the code document
}
}
}
/**
* Connect additional slots.
* To be called after constructing the code generator.
*/
void AdvancedCodeGenerator::connectSlots()
{
connect(m_document, SIGNAL(sigObjectCreated(UMLObject*)),
this, SLOT(checkAddUMLObject(UMLObject*)));
connect(m_document, SIGNAL(sigObjectRemoved(UMLObject*)),
this, SLOT(checkRemoveUMLObject(UMLObject*)));
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
connect(commonPolicy, SIGNAL(modifiedCodeContent()),
this, SLOT(syncCodeToDocument()));
}
| 3,582
|
C++
|
.cpp
| 105
| 30.257143
| 98
| 0.729582
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,515
|
xmlelementcodeblock.cpp
|
KDE_umbrello/umbrello/codegenerators/xml/xmlelementcodeblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "xmlelementcodeblock.h"
// local includes
#include "attribute.h"
#include "codedocument.h"
#include "uml.h"
#include "xmlcodecomment.h"
// qt includes
#include <QXmlStreamWriter>
XMLElementCodeBlock::XMLElementCodeBlock (CodeDocument * parentDoc, const QString & nodeName, const QString & comment)
: HierarchicalCodeBlock(parentDoc)
{
init(parentDoc, nodeName, comment);
}
XMLElementCodeBlock::~XMLElementCodeBlock ()
{
}
/**
* Save the XMI representation of this object
*/
void XMLElementCodeBlock::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("xmlelementblock"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
/**
* load params from the appropriate XMI element node.
*/
void XMLElementCodeBlock::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
/**
* Set attributes of the node that represents this class
* in the XMI document.
*/
void XMLElementCodeBlock::setAttributesOnNode (QXmlStreamWriter& writer)
{
// superclass call
HierarchicalCodeBlock::setAttributesOnNode(writer);
// now set local attributes/fields
writer.writeAttribute(QStringLiteral("nodeName"), getNodeName());
}
/**
* Set the class attributes of this object from
* the passed element node.
*/
void XMLElementCodeBlock::setAttributesFromNode (QDomElement & root)
{
// superclass call
HierarchicalCodeBlock::setAttributesFromNode(root);
// now set local attributes
setNodeName(root.attribute(QStringLiteral("nodeName"), QStringLiteral("UNKNOWN")));
}
void XMLElementCodeBlock::setNodeName (const QString &name)
{
m_nodeName = name;
}
QString XMLElementCodeBlock::getNodeName ()
{
return m_nodeName;
}
void XMLElementCodeBlock::addAttribute (UMLAttribute * at)
{
m_attList.append(at);
}
UMLAttributeList * XMLElementCodeBlock::getAttributeList()
{
return & m_attList;
}
/**
* Update the start and end text for this ownedhierarchicalcodeblock.
*/
void XMLElementCodeBlock::updateContent ()
{
QString endLine = getNewLineEndingChars();
QString nodeName = getNodeName();
// Now update START/ENDING Text
QString startText = QLatin1Char('<') + nodeName;
QString endText;
UMLAttributeList * alist = getAttributeList();
for (UMLAttribute *at : *alist)
{
if(at->getInitialValue().isEmpty())
logWarn0("XMLElementCodeBlock : cant print out attribute that lacks an initial value");
else {
startText.append(QStringLiteral(" ") + at->name() + QStringLiteral("=\""));
startText.append(at->getInitialValue() + QStringLiteral("\""));
}
}
// now set close of starting/ending node, the style depending on whether we have child text or not
if(getTextBlockList()->count())
{
startText.append(QStringLiteral(">"));
endText = QStringLiteral("</") + nodeName + QLatin1Char('>');
} else {
startText.append(QStringLiteral("/>"));
endText = QString();
}
setStartText(startText);
setEndText(endText);
}
void XMLElementCodeBlock::init (CodeDocument *parentDoc, const QString &nodeName, const QString &comment)
{
setComment(new XMLCodeComment(parentDoc));
getComment()->setText(comment);
m_nodeName = nodeName;
updateContent();
}
| 3,562
|
C++
|
.cpp
| 115
| 27.373913
| 118
| 0.732164
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,516
|
xmlschemawriter.cpp
|
KDE_umbrello/umbrello/codegenerators/xml/xmlschemawriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "xmlschemawriter.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
/**
* Constructor, initialises a couple of variables
*/
XMLSchemaWriter::XMLSchemaWriter()
{
packageNamespaceTag = QString::fromLatin1("tns");
packageNamespaceURI = QString::fromLatin1("http://foo.example.com/");
schemaNamespaceTag = QString::fromLatin1("xs");
schemaNamespaceURI = QString::fromLatin1("http://www.w3.org/2001/XMLSchema");
}
/**
* Destructor, empty.
*/
XMLSchemaWriter::~XMLSchemaWriter()
{
}
/**
* Returns "XMLSchema".
*/
Uml::ProgrammingLanguage::Enum XMLSchemaWriter::language() const
{
return Uml::ProgrammingLanguage::XMLSchema;
}
/**
* Call this method to generate XMLschema code for a UMLClassifier.
* @param c the class to generate code for
*/
void XMLSchemaWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("XMLSchemaWriter::writeClass: Cannot write class of NULL classifier");
return;
}
// find an appropriate name for our file
QString fileName = findFileName(c,QStringLiteral(".xsd"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
// check that we may open that file for writing
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream xs(&file);
// set package namespace tag appropriately
if (!c->package().isEmpty())
packageNamespaceTag = c->package();
// START WRITING
// 0. FIRST THING: open the xml processing instruction. This MUST be
// the first thing in the file
xs << "<?xml version=\"1.0\"?>" << m_endl;
// 1. create the header
QString headerText = getHeadingFile(QStringLiteral(".xsd"));
if (!headerText.isEmpty()) {
headerText.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
headerText.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
}
if (!headerText.isEmpty())
xs << headerText << m_endl;
// 2. Open schema element node with appropriate namespace decl
xs << "<" << makeSchemaTag(QStringLiteral("schema"));
// common namespaces we know will be in the file..
xs << " targetNamespace=\"" << packageNamespaceURI << packageNamespaceTag << "\"" << m_endl;
xs << " xmlns:" << schemaNamespaceTag << "=\"" << schemaNamespaceURI << "\"";
xs << " xmlns:" << packageNamespaceTag << "=\"" << packageNamespaceURI << packageNamespaceTag << "\"";
xs << ">" << m_endl; // close opening declaration
m_indentLevel++;
// 3? IMPORT statements -- do we need to do anything here? I suppose if
// our document has more than one package, which is possible, we are missing
// the correct import statements. Leave that for later at this time.
/*
//only import classes in a different package as this class
UMLPackageList imports;
findObjectsRelated(c, imports);
for (UMLPackage *con = imports.first(); con ; con = imports.next())
if (con->getPackage() != c->getPackage())
xs << "import " << con->getPackage() << "." << cleanName(con->getName()) << ";" << m_endl;
*/
// 4. BODY of the schema.
// start the writing by sending this classifier, the "root" for this particular
// schema, to writeClassifier method, which will subsequently call itself on all
// related classifiers and thus populate the schema.
writeClassifier(c, xs);
// 5. What remains is to make the root node declaration
xs << m_endl;
writeElementDecl(getElementName(c), getElementTypeName(c), xs);
// 6. Finished: now we may close schema decl
m_indentLevel--;
xs << indent() << "</" << makeSchemaTag(QStringLiteral("schema")) << ">" << m_endl; // finished.. close schema node
// tidy up. no dangling open files please..
file.close();
// bookkeeping for code generation
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(file.fileName());
// need to clear HERE, NOT in the destructor because we want each
// schema that we write to have all related classes.
writtenClassifiers.clear();
}
/**
* Write an element declaration.
*/
void XMLSchemaWriter::writeElementDecl(const QString &elementName, const QString &elementTypeName, QTextStream &xs)
{
if (forceDoc())
writeComment(elementName + QStringLiteral(" is the root element, declared here."), xs);
xs << indent() << "<" << makeSchemaTag(QStringLiteral("element"))
<< " name=\"" << elementName << "\""
<< " type=\"" << makePackageTag(elementTypeName) << "\""
<< "/>" << m_endl;
}
/**
* Writes classifier's documentation then guts.
*/
void XMLSchemaWriter::writeClassifier(UMLClassifier *c, QTextStream &xs)
{
// NO doing this 2 or more times.
if (hasBeenWritten(c))
return;
xs << m_endl;
// write documentation for class, if any, first
if (forceDoc() || !c->doc().isEmpty())
writeComment(c->doc(), xs);
if (c->isAbstract() || c->isInterface())
writeAbstractClassifier(c, xs); // if it is an interface or abstract class
else
writeConcreteClassifier(c, xs);
}
/**
* Find all attributes for this classifier.
*/
UMLAttributeList XMLSchemaWriter::findAttributes(UMLClassifier *c)
{
// sort attributes by Scope
UMLAttributeList attribs;
if (!c->isInterface()) {
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute *at : atl) {
switch(at->visibility())
{
case Uml::Visibility::Public:
case Uml::Visibility::Protected:
attribs.append(at);
break;
case Uml::Visibility::Private:
// DO NOTHING! no way to print in the schema
break;
default:
break;
}
}
}
return attribs;
}
// We have to do 2 things with abstract classifiers (e.g. abstract classes and interfaces)
// which is to:
// 1) declare it as a complexType so it may be inherited (I can see an option here: to NOT write
// this complexType declaration IF the classifier itself isnt inherited by or is inheriting
// from anything because no other element will use this complexType).
// 2) Create a group so that elements, which obey the abstract class /interface may be placed in
// aggregation with other elements (again, and option here to NOT write the group if no other
// element use the interface in element aggregation)
//
void XMLSchemaWriter::writeAbstractClassifier (UMLClassifier *c, QTextStream &xs)
{
// preparations
UMLClassifierList subclasses = c->findSubClassConcepts(); // list of what inherits from us
UMLClassifierList superclasses = c->findSuperClassConcepts(); // list of what we inherit from
// write the main declaration
writeConcreteClassifier (c, xs);
writeGroupClassifierDecl (c, subclasses, xs);
markAsWritten(c);
// now go back and make sure all sub-classing nodes are declared
if (subclasses.count() > 0)
{
QString elementName = getElementName(c);
UMLAttributeList attribs = findAttributes(c);
QStringList attribGroups = findAttributeGroups(c);
writeAttributeGroupDecl(elementName, attribs, xs);
// now write out inheriting classes, as needed
for (UMLClassifier * classifier : subclasses)
writeClassifier(classifier, xs);
}
// write out any superclasses as needed
for (UMLClassifier *classifier : superclasses)
writeClassifier(classifier, xs);
}
/**
* Write a \<group\> declaration for this classifier. Used for interfaces to classes with
* inheriting children.
*/
void XMLSchemaWriter::writeGroupClassifierDecl (UMLClassifier *c,
UMLClassifierList subclasses,
QTextStream &xs)
{
// name of class, subclassing classifiers
QString elementTypeName = getElementGroupTypeName(c);
// start Writing node but only if it has subclasses? Nah..right now put in empty group
xs << indent() << "<" << makeSchemaTag(QStringLiteral("group")) << " name=\"" << elementTypeName << "\">" << m_endl;
m_indentLevel++;
xs << indent() << "<" << makeSchemaTag(QStringLiteral("choice")) << ">" << m_endl;
m_indentLevel++;
for (UMLClassifier *classifier : subclasses) {
writeAssociationRoleDecl(classifier, QStringLiteral("1"), xs);
}
m_indentLevel--;
xs << indent() << "</" << makeSchemaTag(QStringLiteral("choice")) << ">" << m_endl;
m_indentLevel--;
// finish node
xs << indent() << "</" << makeSchemaTag(QStringLiteral("group")) << ">" << m_endl;
}
/**
* Write a \<complexType\> declaration for this classifier.
*/
void XMLSchemaWriter::writeComplexTypeClassifierDecl (UMLClassifier *c,
UMLAssociationList associations,
UMLAssociationList aggregations,
UMLAssociationList compositions,
UMLClassifierList superclasses,
QTextStream &xs)
{
// Preparations
//
// sort attributes by Scope
UMLAttributeList attribs = findAttributes(c);
QStringList attribGroups = findAttributeGroups(c);
// test for relevant associations
bool hasAssociations = determineIfHasChildNodes(c);
bool hasSuperclass = superclasses.count()> 0;
bool hasAttributes = attribs.count() > 0 || attribGroups.count() > 0;
// START WRITING
// start body of element
QString elementTypeName = getElementTypeName(c);
xs << indent() << "<" << makeSchemaTag(QStringLiteral("complexType")) << " name=\"" << elementTypeName << "\"";
if (hasAssociations || hasAttributes || hasSuperclass)
{
xs << ">" << m_endl;
m_indentLevel++;
if (hasSuperclass)
{
QString superClassName = getElementTypeName(superclasses.first());
xs << indent() << "<" << makeSchemaTag(QStringLiteral("complexContent")) << ">" << m_endl;
//PROBLEM: we only treat ONE superclass for inheritance.. bah.
m_indentLevel++;
xs << indent() << "<" << makeSchemaTag(QStringLiteral("extension")) << " base=\"" << makePackageTag(superClassName)
<<"\"";
if (hasAssociations || hasAttributes)
xs << ">" << m_endl;
else
xs << "/>" << m_endl;
m_indentLevel++;
}
if (hasAssociations)
{
// Child Elements (from most associations)
//
bool didFirstOne = false;
didFirstOne = writeAssociationDecls(associations, true, didFirstOne, c->id(), xs);
didFirstOne = writeAssociationDecls(aggregations, false, didFirstOne, c->id(), xs);
didFirstOne = writeAssociationDecls(compositions, false, didFirstOne, c->id(), xs);
if (didFirstOne) {
m_indentLevel--;
xs << indent() << "</" << makeSchemaTag(QStringLiteral("sequence")) << ">" << m_endl;
}
}
// ATTRIBUTES
//
if (hasAttributes)
{
writeAttributeDecls(attribs, xs);
for (int i= 0; i < attribGroups.count(); ++i) {
xs << indent() << "<" << makeSchemaTag(QStringLiteral("attributeGroup")) << " ref=\""
<< makePackageTag(attribGroups[i]) << "\"/>" << m_endl;
}
}
if (hasSuperclass)
{
m_indentLevel--;
if (hasAssociations || hasAttributes)
xs << indent() << "</" << makeSchemaTag(QStringLiteral("extension")) << ">" << m_endl;
m_indentLevel--;
xs << indent() << "</" << makeSchemaTag(QStringLiteral("complexContent")) << ">" << m_endl;
}
// close this element decl
m_indentLevel--;
xs << indent() << "</" << makeSchemaTag(QStringLiteral("complexType")) << ">" << m_endl;
} else
xs << "/>" << m_endl; // empty node. just close this element decl
}
void XMLSchemaWriter::writeConcreteClassifier (UMLClassifier *c, QTextStream &xs)
{
// preparations.. gather information about this classifier
//
UMLClassifierList superclasses = c->findSuperClassConcepts(); // list of what inherits from us
UMLClassifierList subclasses = c->findSubClassConcepts(); // list of what we inherit from
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
// BAD! only way to get "general" associations.
UMLAssociationList associations = c->getSpecificAssocs(Uml::AssociationType::Association);
// write the main declaration
writeComplexTypeClassifierDecl(c, associations, aggregations, compositions, superclasses, xs);
markAsWritten(c);
// Now write out any child def's
writeChildObjsInAssociation(c, associations, xs);
writeChildObjsInAssociation(c, aggregations, xs);
writeChildObjsInAssociation(c, compositions, xs);
// write out any superclasses as needed
for (UMLClassifier *classifier : superclasses)
writeClassifier(classifier, xs);
// write out any subclasses as needed
for (UMLClassifier *classifier : subclasses)
writeClassifier(classifier, xs);
}
/**
* Discover the string name of all the attribute groups (which are child nodes)
* of this classifier (err.. element).
* These exist for abstract classes only (which become xs:group nodes).
*/
QStringList XMLSchemaWriter::findAttributeGroups (UMLClassifier *c)
{
// we need to look for any class we inherit from. IF these
// have attributes, then we need to notice
QStringList list;
UMLClassifierList superclasses = c->findSuperClassConcepts(); // list of what inherits from us
for (UMLClassifier *classifier : superclasses)
{
if (classifier->isAbstract())
{
// only classes have attributes..
if (!classifier->isInterface()) {
UMLAttributeList attribs = c->getAttributeList();
if (attribs.count() > 0)
list.append(getElementName(classifier) + QStringLiteral("AttribGroupType"));
}
}
}
return list;
}
/**
* Find if the classifier would have any Child elements.
*/
bool XMLSchemaWriter::determineIfHasChildNodes(UMLClassifier *c)
{
UMLObjectList aggList = findChildObjsInAssociations (c, c->getAggregations());
UMLObjectList compList = findChildObjsInAssociations (c, c->getCompositions());
UMLAssociationList associations = c->getSpecificAssocs(Uml::AssociationType::Association); // BAD! only way to get "general" associations.
UMLObjectList assocList = findChildObjsInAssociations (c, associations);
return aggList.count() > 0 || compList.count() > 0 || assocList.count() > 0;
}
/**
* Find all the child objects in this association and make sure they get
* written out (if they havent already been).
*/
void XMLSchemaWriter::writeChildObjsInAssociation (UMLClassifier *c,
UMLAssociationList assoc,
QTextStream &xs)
{
UMLObjectList list = findChildObjsInAssociations (c, assoc);
for (UMLObject* obj : list) {
UMLClassifier * thisClassifier = obj->asUMLClassifier();
if (thisClassifier)
writeClassifier(thisClassifier, xs);
}
}
/**
* Quick check to see if we have written the declaration for this classifier yet.
*/
bool XMLSchemaWriter::hasBeenWritten(UMLClassifier *c)
{
if (writtenClassifiers.contains(c))
return true;
else
return false;
}
/**
* Mark a classifier as written, so it is not repeatedly re-declared in the schema.
*/
void XMLSchemaWriter::markAsWritten(UMLClassifier *c)
{
writtenClassifiers.append(c);
}
/**
* Writes the Attribute declarations.
* @param attribs List of attributes
* @param xs text stream
*/
void XMLSchemaWriter::writeAttributeDecls(UMLAttributeList &attribs, QTextStream &xs)
{
for (UMLAttribute* at : attribs) {
writeAttributeDecl(at, xs);
}
}
/**
* Write an element attribute.
*/
void XMLSchemaWriter::writeAttributeDecl(UMLAttribute *attrib, QTextStream &xs)
{
QString documentation = attrib->doc();
QString typeName = fixTypeName(attrib->getTypeName());
bool isStatic = attrib->isStatic();
QString initialValue = fixInitialStringDeclValue(attrib->getInitialValue(), typeName);
if (!documentation.isEmpty())
writeComment(documentation, xs);
xs << indent() << "<" << makeSchemaTag(QStringLiteral("attribute"))
<< " name=\"" << cleanName(attrib->name()) << "\""
<< " type=\"" << typeName << "\"";
// default value?
if (!initialValue.isEmpty())
{
// IF it is static, then we use "fixed", otherwise, we use "default" decl.
// For the default decl, we _must_ use "optional" decl
if (isStatic)
xs << " use=\"required\" fixed=\"" << initialValue << "\"";
else
xs << " use=\"optional\" default=\"" << initialValue << "\"";
}
// finish decl
xs << "/>" << m_endl;
}
/**
* Find all attributes that belong in group.
*/
void XMLSchemaWriter::writeAttributeGroupDecl (const QString &elementName, UMLAttributeList &attribs, QTextStream &xs)
{
if (attribs.count()> 0) {
// write a little documentation
writeComment(QStringLiteral("attributes for element ") + elementName, xs);
// open attribute group
xs << indent() << "<" << makeSchemaTag(QStringLiteral("attributeGroup")) << " name=\"" << elementName << "AttribGroupType" << "\">" << m_endl;
m_indentLevel++;
for (UMLAttribute *at : attribs)
{
writeAttributeDecl(at, xs);
}
m_indentLevel--;
// close attrib group node
xs << indent() << "</" << makeSchemaTag(QStringLiteral("attributeGroup")) << ">" << m_endl;
}
}
/**
* Writes a comment.
*/
void XMLSchemaWriter::writeComment(const QString &comment, QTextStream &xs)
{
// in the case we have several line comment..
// NOTE: this part of the method has the problem of adopting UNIX newline,
// need to resolve for using with MAC/WinDoze eventually I assume
QString indnt = indent();
xs << indnt << "<!-- ";
if (comment.contains(QRegularExpression(QStringLiteral("\n")))) {
xs << m_endl;
QStringList lines = comment.split(QLatin1Char('\n'));
for (int i= 0; i < lines.count(); i++)
xs << indnt << " " << lines[i] << m_endl;
xs << indnt << "-->" << m_endl;
} else {
// this should be more fancy in the future, breaking it up into 80 char
// lines so that it doesn't look too bad
xs << comment << " -->" << m_endl;
}
}
/**
* Searches a list of associations for appropriate ones to write out as attributes.
* This works well for compositions, aggregations and self-associations but will
* not work right for plain associations between 2 different classes.
* all that matters here is roleA, the role served by the children of this class
* in any composition or aggregation association. In full associations, I have only
* considered the case of "self" association, so it shouldn't matter if we use role A or
* B to find the child class as long as we don't use BOTH roles. I bet this will fail
* badly for someone using a plain association between 2 different classes. THAT should
* be done, but isnt yet (this is why I have left role b code in for now). -b.t.
*/
bool XMLSchemaWriter::writeAssociationDecls(UMLAssociationList associations,
bool noRoleNameOK, bool didFirstOne, Uml::ID::Type id, QTextStream &xs)
{
if (!associations.isEmpty())
{
bool printRoleA = false, printRoleB = false;
for (UMLAssociation *a : associations)
{
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id && a->visibility(Uml::RoleType::B) != Uml::Visibility::Private)
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id && a->visibility(Uml::RoleType::A) != Uml::Visibility::Private)
printRoleA = true;
// First: we insert documentation for association IF it has either role
// AND some documentation (!)
if ((printRoleA || printRoleB) && !(a->doc().isEmpty()))
writeComment(a->doc(), xs);
// opening for sequence
if (!didFirstOne && (printRoleA || printRoleB))
{
didFirstOne = true;
xs << indent() << "<" << makeSchemaTag(QStringLiteral("sequence")) << ">" << m_endl;
m_indentLevel++;
}
// print RoleB decl
/*
// As mentioned in the header comment for this method: this block of code is
// commented out for now as it will only be needed if/when plain associations
// between different classes are to be treated
if (printRoleB)
{
UMLClassifier *classifierB = a->getObjectB()->asUMLClassifier();;
if (classifierB) {
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared
if (!a->getRoleNameB().isEmpty() || noRoleNameOK)
writeAssociationRoleDecl(classifierB, a->getMultiB(), xs);
}
}
*/
// print RoleA decl
if (printRoleA)
{
UMLClassifier *classifierA = a->getObject(Uml::RoleType::A)->asUMLClassifier();
if (classifierA) {
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared
if (!a->getRoleName(Uml::RoleType::A).isEmpty() || noRoleNameOK)
writeAssociationRoleDecl(classifierA, a->getMultiplicity(Uml::RoleType::A), xs);
}
}
}
}
return didFirstOne;
}
/**
* Find and return a list of child UMLObjects pointed to by the associations
* in this UMLClassifier.
*/
UMLObjectList XMLSchemaWriter::findChildObjsInAssociations (UMLClassifier *c, UMLAssociationList associations)
{
Uml::ID::Type id = c->id();
UMLObjectList list;
for (UMLAssociation *a : associations)
{
if (a->getObjectId(Uml::RoleType::A) == id
&& a->visibility(Uml::RoleType::B) != Uml::Visibility::Private
&& !a->getRoleName(Uml::RoleType::B).isEmpty()
)
list.append(a->getObject(Uml::RoleType::B));
if (a->getObjectId(Uml::RoleType::B) == id
&& a->visibility(Uml::RoleType::A) != Uml::Visibility::Private
&& !a->getRoleName(Uml::RoleType::A).isEmpty()
)
list.append(a->getObject(Uml::RoleType::A));
}
return list;
}
/**
* Writes out an association as an attribute using Vector
*/
void XMLSchemaWriter::writeAssociationRoleDecl(UMLClassifier *c, const QString &multi, QTextStream &xs)
{
bool isAbstract = c->isAbstract();
bool isInterface = c->isInterface();
QString elementName = getElementName(c);
QString doc = c->doc();
if (!doc.isEmpty())
writeComment(doc, xs);
// Min/Max Occurs is based on whether it is this a single element
// or a List (maxoccurs>1). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
QString minOccurs = QStringLiteral("0");
QString maxOccurs = QStringLiteral("unbounded");
if (multi.isEmpty())
{
// in this case, association will only specify ONE element can exist
// as a child
minOccurs = QStringLiteral("1");
maxOccurs = QStringLiteral("1");
}
else
{
QStringList values = multi.split(QRegularExpression(QStringLiteral("[^\\d{1,}|\\*]")));
// could use some improvement here.. for sequences like "0..1, 3..5, 10" we
// don't capture the whole "richness" of the multi. Instead we translate it
// now to minOccurs="0" maxOccurs="10"
if (values.count() > 0)
{
// populate both with the actual value as long as our value isnt an asterix
// In that case, use special value (from above)
if (values[0].contains(QRegularExpression(QStringLiteral("\\d{1,}"))))
minOccurs = values[0]; // use first number in sequence
if (values[values.count()-1].contains(QRegularExpression(QStringLiteral("\\d{1,}"))))
maxOccurs = values[values.count()-1]; // use only last number in sequence
}
}
// Now declare the class in the association as an element or group.
//
// In a semi-arbitrary way, we have decided to make abstract classes into
// "groups" and concrete classes into "complexTypes".
//
// This is because about the only thing you can do with an abstract
// class (err. node) is inherit from it with a "concrete" element. Therefore,
// in this manner, we need a group node for abstract classes to lay out the child
// element choices so that the child, concrete class may be plugged into whatever spot
// it parent could go. The tradeoff is that "group" nodes may not be extended, so the
// choices that you lay out here are it (e.g. no more nodes may inherit" from this group)
//
// The flipside for concrete classes is that we want to use them as elements in our document.
// Unfortunately, about all you can do with complexTypes in terms of inheritance, is to
// use these as the basis for a new node type. This is NOT full inheritance because the new
// class (err. element node) wont be able to go into the document where it parent went without
// you heavily editing the schema.
//
// Therefore, IF a group is abstract, but has no inheriting sub-classes, there are no choices, and it is nigh
// on pointless to declare it as a group, in this special case, abstract classes get declared
// as complexTypes.
//
// Of course, in OO methodology, you should be able to inherit from
// any class, but schema just don't allow use to have full inheritance using either groups
// or complexTypes. Thus we have taken a middle rode. If someone wants to key me into a
// better way to represent this, I'd be happy to listen. =b.t.
//
// UPDATE: partial solution to the above: as of 13-Mar-2003 we now write BOTH a complexType
// AND a group declaration for interfaces AND classes which are inherited from.
//
if ((isAbstract || isInterface) && c->findSubClassConcepts().count() > 0)
xs << indent() << "<" << makeSchemaTag(QStringLiteral("group"))
<<" ref=\"" << makePackageTag(getElementGroupTypeName(c)) << "\"";
else
xs << indent() << "<" << makeSchemaTag(QStringLiteral("element"))
<<" name=\"" << getElementName(c) << "\""
<<" type=\"" << makePackageTag(getElementTypeName(c)) << "\"";
// min/max occurs
if (minOccurs != QStringLiteral("1"))
xs << " minOccurs=\"" << minOccurs << "\"";
if (maxOccurs != QStringLiteral("1"))
xs << " maxOccurs=\"" << maxOccurs << "\"";
// tidy up the node
xs << "/>" << m_endl;
}
/**
* Replaces `string' with `String' and `bool' with `boolean'
* IF the type is "string" we need to declare it as
* the XMLSchema Object "String" (there is no string primitive in XMLSchema).
* Same thing again for "bool" to "boolean".
*/
QString XMLSchemaWriter::fixTypeName(const QString& string)
{
// string.replace(QRegularExpression(QStringLiteral("^string$"), schemaNamespaceTag + ":string"));
// string.replace(QRegularExpression(QStringLiteral("^bool$"), schemaNamespaceTag + ":boolean"));
return schemaNamespaceTag + QLatin1Char(':') + string;
}
/**
* Check that initial values of strings DON'T have quotes around them
* (we get double quoting then)!!
*/
QString XMLSchemaWriter::fixInitialStringDeclValue(QString value, const QString &type)
{
// check for strings only
if (!value.isEmpty() && type == QStringLiteral("xs:string")) {
if (!value.startsWith(QLatin1Char('"')))
value.remove(0, 1);
if (!value.endsWith(QLatin1Char('"')))
value.remove(value.length(), 1);
}
return value;
}
/**
* Find the element node name for this classifier.
*/
QString XMLSchemaWriter::getElementName(UMLClassifier *c)
{
return cleanName(c->name());
}
/**
* Find the element node "type" name. Used in the "complexType" which
* might define that element node.
*/
QString XMLSchemaWriter::getElementTypeName(UMLClassifier *c)
{
QString elementName = getElementName(c);
return elementName + QStringLiteral("ComplexType");
}
/**
* Find the group node "type" name. Used for elements which define an interface/are abstract.
*/
QString XMLSchemaWriter::getElementGroupTypeName(UMLClassifier *c)
{
QString elementName = getElementName(c);
return elementName + QStringLiteral("GroupType");
}
/**
* Construct an element tag with the package namespace.
*/
QString XMLSchemaWriter::makePackageTag (QString tagName)
{
tagName.prepend(packageNamespaceTag + QLatin1Char(':'));
return tagName;
}
/**
* Construct an element tag with the schema namespace.
*/
QString XMLSchemaWriter::makeSchemaTag (QString tagName)
{
tagName.prepend(schemaNamespaceTag + QLatin1Char(':'));
return tagName;
}
/**
* Get list of reserved keywords.
*/
QStringList XMLSchemaWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("ATTLIST")
<< QStringLiteral("CDATA")
<< QStringLiteral("DOCTYPE")
<< QStringLiteral("ELEMENT")
<< QStringLiteral("ENTITIES")
<< QStringLiteral("ENTITY")
<< QStringLiteral("ID")
<< QStringLiteral("IDREF")
<< QStringLiteral("IDREFS")
<< QStringLiteral("NMTOKEN")
<< QStringLiteral("NMTOKENS")
<< QStringLiteral("NOTATION")
<< QStringLiteral("PUBLIC")
<< QStringLiteral("SHORTREF")
<< QStringLiteral("SYSTEM")
<< QStringLiteral("USEMAP");
}
return keywords;
}
| 30,998
|
C++
|
.cpp
| 746
| 35.121984
| 150
| 0.647602
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,517
|
xmlcodecomment.cpp
|
KDE_umbrello/umbrello/codegenerators/xml/xmlcodecomment.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "xmlcodecomment.h"
XMLCodeComment::XMLCodeComment (CodeDocument * doc, const QString & text)
: CodeComment (doc, text)
{
}
XMLCodeComment::~XMLCodeComment ()
{
}
QString XMLCodeComment::toString () const
{
QString output;
// simple output method
if (getWriteOutText())
{
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
output.append(indent + QStringLiteral("<!-- "));
if (!body.isEmpty()) {
output.append(formatMultiLineText (body, indent, endLine));
}
output.append(indent + QStringLiteral("-->") + endLine);
}
return output;
}
| 923
|
C++
|
.cpp
| 30
| 26
| 92
| 0.683973
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,518
|
jswriter.cpp
|
KDE_umbrello/umbrello/codegenerators/js/jswriter.cpp
|
/*
SPDX-FileCopyrightText: 2003 Alexander Blum <blum@kewbee.de>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "jswriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <QRegularExpression>
#include <QTextStream>
JSWriter::JSWriter()
{
}
JSWriter::~JSWriter()
{
}
/**
* Call this method to generate Actionscript code for a UMLClassifier.
* @param c the class you want to generate code for
*/
void JSWriter::writeClass(UMLClassifier *c)
{
if (!c)
{
logWarn0("JSWriter::writeClass: Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());
QString fileName = c->name().toLower();
//find an appropriate name for our file
fileName = findFileName(c, QStringLiteral(".js"));
if (fileName.isEmpty())
{
Q_EMIT codeGenerated(c, false);
return;
}
QFile filejs;
if (!openFile(filejs, fileName))
{
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream js(&filejs);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".js"));
if (!str.isEmpty())
{
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filejs.fileName());
js << str << m_endl;
}
//write includes
UMLPackageList includes;
findObjectsRelated(c, includes);
for (UMLPackage* conc : includes) {
QString headerName = findFileName(conc, QStringLiteral(".js"));
if (!headerName.isEmpty())
{
js << "#include \"" << headerName << "\"" << m_endl;
}
}
js << m_endl;
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty())
{
js << m_endl << "/**" << m_endl;
js << " * class " << classname << m_endl;
js << formatDoc(c->doc(), QStringLiteral(" * "));
js << " */" << m_endl << m_endl;
}
//check if class is abstract and / or has abstract methods
if (c->isAbstract() && !hasAbstractOps(c))
js << "/******************************* Abstract Class ****************************" << m_endl << " "
<< classname << " does not have any pure virtual methods, but its author" << m_endl
<< " defined it as an abstract class, so you should not use it directly." << m_endl
<< " Inherit from it instead and create only objects from the derived classes" << m_endl
<< "*****************************************************************************/" << m_endl << m_endl;
js << classname << " = function ()" << m_endl;
js << "{" << m_endl;
js << m_indentation << "this._init ();" << m_endl;
js << "}" << m_endl;
js << m_endl;
UMLClassifierList superclasses = c->getSuperClasses();
for (UMLClassifier *obj : superclasses) {
js << classname << ".prototype = new " << cleanName(obj->name()) << " ();" << m_endl;
}
js << m_endl;
if (! c->isInterface()) {
UMLAttributeList atl = c->getAttributeList();
js << "/**" << m_endl;
QString temp = QStringLiteral("_init sets all ") + classname + QStringLiteral(" attributes to their default value.")
+ QStringLiteral(" Make sure to call this method within your class constructor");
js << formatDoc(temp, QStringLiteral(" * "));
js << " */" << m_endl;
js << classname << ".prototype._init = function ()" << m_endl;
js << "{" << m_endl;
for (UMLAttribute *at : atl) {
if (forceDoc() || !at->doc().isEmpty())
{
js << m_indentation << "/**" << m_endl
<< formatDoc(at->doc(), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
if (!at->getInitialValue().isEmpty())
{
js << m_indentation << "this.m_" << cleanName(at->name()) << " = " << at->getInitialValue() << ";" << m_endl;
}
else
{
js << m_indentation << "this.m_" << cleanName(at->name()) << " = \"\";" << m_endl;
}
}
}
//associations
UMLAssociationList aggregations = c->getAggregations();
if (forceSections() || !aggregations.isEmpty())
{
js << m_endl << m_indentation << "/**Aggregations: */" << m_endl;
writeAssociation(classname, aggregations, js);
}
UMLAssociationList compositions = c->getCompositions();
if (forceSections() || !compositions.isEmpty())
{
js << m_endl << m_indentation << "/**Compositions: */" << m_endl;
writeAssociation(classname, compositions, js);
}
js << m_endl;
js << "}" << m_endl;
js << m_endl;
//operations
UMLOperationList ops(c->getOpList());
writeOperations(classname, &ops, js);
js << m_endl;
//finish file
//close files and notfiy we are done
filejs.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(filejs.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write a list of associations.
* @param classname the name of the class
* @param assocList the list of associations
* @param js output stream for the JS file
*/
void JSWriter::writeAssociation(QString& classname, UMLAssociationList& assocList, QTextStream &js)
{
for (UMLAssociation *a : assocList) {
// association side
Uml::RoleType::Enum role = (a->getObject(Uml::RoleType::A)->name() == classname ? Uml::RoleType::B : Uml::RoleType::A);
QString roleName(cleanName(a->getRoleName(role)));
if (!roleName.isEmpty()) {
// association doc
if (forceDoc() || !a->doc().isEmpty())
{
js << m_indentation << "/**" << m_endl
<< formatDoc(a->doc(), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
// role doc
if (forceDoc() || !a->getRoleDoc(role).isEmpty())
{
js << m_indentation << "/**" << m_endl
<< formatDoc(a->getRoleDoc(role), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
bool okCvt;
int nMulti = a->getMultiplicity(role).toInt(&okCvt, 10);
bool isNotMulti = a->getMultiplicity(role).isEmpty() || (okCvt && nMulti == 1);
QString typeName(cleanName(a->getObject(role)->name()));
if (isNotMulti)
js << m_indentation << "this.m_" << roleName << " = new " << typeName << "();" << m_endl;
else
js << m_indentation << "this.m_" << roleName << " = new Array();" << m_endl;
// role visibility
}
}
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param js output stream for the JS file
*/
void JSWriter::writeOperations(QString classname, UMLOperationList *opList, QTextStream &js)
{
for (UMLOperation* op : *opList)
{
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for (UMLAttribute* at : atl)
writeDoc |= !at->doc().isEmpty();
if (writeDoc) //write method documentation
{
js << "/**" << m_endl << formatDoc(op->doc(), QStringLiteral(" * "));
for (UMLAttribute* at : atl) //write parameter documentation
{
if (forceDoc() || !at->doc().isEmpty())
{
js << " * @param " << cleanName(at->name()) << m_endl;
js << formatDoc(at->doc(), QStringLiteral(" * "));
}
}//end for : write parameter documentation
js << " */" << m_endl;
}//end if : write method documentation
js << classname << ".prototype." << cleanName(op->name()) << " = function " << "(";
int i = atl.count();
int j=0;
for (UMLAttribute* at : atl) {
js << cleanName(at->name())
<< (!(at->getInitialValue().isEmpty()) ? QStringLiteral(" = ") + at->getInitialValue() : QString())
<< ((j < i-1) ? QStringLiteral(", ") : QString());
j++;
}
js << ")" << m_endl << "{" << m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
js << m_indentation << m_endl;
}
else {
js << formatSourceCode(sourceCode, m_indentation);
}
js << "}" << m_endl;
js << m_endl << m_endl;
}//end for
}
/**
* Returns "JavaScript".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum JSWriter::language() const
{
return Uml::ProgrammingLanguage::JavaScript;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList JSWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("break")
<< QStringLiteral("case")
<< QStringLiteral("const")
<< QStringLiteral("continue")
<< QStringLiteral("default")
<< QStringLiteral("else")
<< QStringLiteral("false")
<< QStringLiteral("for")
<< QStringLiteral("function")
<< QStringLiteral("if")
<< QStringLiteral("in")
<< QStringLiteral("new")
<< QStringLiteral("return")
<< QStringLiteral("switch")
<< QStringLiteral("this")
<< QStringLiteral("true")
<< QStringLiteral("var")
<< QStringLiteral("while")
<< QStringLiteral("with");
}
return keywords;
}
| 10,521
|
C++
|
.cpp
| 277
| 30.223827
| 127
| 0.538047
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,519
|
sqlwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/sql/sqlwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Nikolaus Gradwohl <guru@local-guru.net>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "sqlwriter.h"
#include "association.h"
#include "attribute.h"
#include "checkconstraint.h"
#include "classifier.h"
#include "debug_utils.h"
#include "enum.h"
#include "entity.h"
#include "foreignkeyconstraint.h"
#include "model_utils.h"
#include "operation.h"
#include "uniqueconstraint.h"
#include "umlentityattributelist.h"
#include "umlclassifierlistitemlist.h"
#include "uml.h" // only needed for log{Warn,Error}
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QList>
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"access",
"add",
"all",
"alter",
"analyze",
"and",
"any",
"as",
"asc",
"audit",
"begin",
"between",
"boolean",
"by",
"char",
"character",
"check",
"cluster",
"column",
"comment",
"commit",
"compress",
"connect",
"create",
"current",
"cursor",
"date",
"decimal",
"default",
"delete",
"desc",
"distinct",
"drop",
"else",
"elsif",
"end",
"escape",
"exception",
"exclusive",
"execute",
"exists",
"explain",
"false",
"file",
"float",
"for",
"from",
"function",
"grant",
"group",
"having",
"identified",
"if",
"immediate",
"in",
"increment",
"index",
"initial",
"insert",
"integer",
"intersect",
"into",
"is",
"level",
"like",
"lock",
"long",
"loop",
"maxextents",
"minus",
"mlslabel",
"mode",
"modify",
"noaudit",
"nocompress",
"not",
"nowait",
"null",
"number",
"of",
"offline",
"on",
"online",
"option",
"or",
"order",
"out",
"pctfree",
"prior",
"privileges",
"procedure",
"public",
"raw",
"rename",
"resource",
"return",
"revoke",
"rollback",
"row",
"rowid",
"rowlabel",
"rownum",
"rows",
"savepoint",
"select",
"session",
"set",
"share",
"size",
"smallint",
"some",
"start",
"successful",
"synonym",
"sysdate",
"table",
"then",
"to",
"trigger",
"true",
"truncate",
"type",
"uid",
"union",
"unique",
"update",
"user",
"using",
"validate",
"values",
"varchar",
"varchar2",
"varray",
"view",
"whenever",
"where",
"with",
nullptr
};
SQLWriter::SQLWriter()
: m_pEntity(nullptr)
{
}
SQLWriter::~SQLWriter()
{
}
/**
* Call this method to generate sql code for a UMLClassifier.
* @param c the class to generate code for
*/
void SQLWriter::writeClass(UMLClassifier *c)
{
UMLEntity* e = c->asUMLEntity();
if (!e) {
logError2("SQLWriter::writeClass: Invalid cast from '%1' to UMLEntity* %2",
c->name(), c->baseTypeStr());
return;
}
m_pEntity = e;
QString entityname = cleanName(m_pEntity->name());
//find an appropriate name for our file
QString fileName = findFileName(m_pEntity, QStringLiteral(".sql"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(m_pEntity, false);
return;
}
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(m_pEntity, false);
return;
}
//Start generating the code!!
QTextStream sql(&file);
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".sql"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
sql << str << m_endl;
}
//Write class Documentation if there is something or if force option
if (forceDoc() || !m_pEntity->doc().isEmpty()) {
sql << m_endl << "--" << m_endl;
sql << "-- TABLE: " << entityname << m_endl;
sql << formatDoc(m_pEntity->doc(),QStringLiteral("-- "));
sql << "-- " << m_endl << m_endl;
}
// write all entity attributes
UMLEntityAttributeList entAttList = m_pEntity->getEntityAttributes();
if (language() == Uml::ProgrammingLanguage::PostgreSQL) {
for(UMLEntityAttribute *at : entAttList) {
if (at->getType()->baseType() == UMLObject::ot_Enum) {
const UMLEnum *_enum = at->getType()->asUMLEnum();
if (m_enumsGenerated.contains(at->getTypeName()))
continue;
m_enumsGenerated.append(at->getTypeName());
sql << "CREATE TYPE " << at->getTypeName() << " AS ENUM (";
QString delimiter(QStringLiteral(""));
UMLClassifierListItemList enumLiterals = _enum->getFilteredList(UMLObject::ot_EnumLiteral);
for(UMLClassifierListItem* enumLiteral : enumLiterals) {
sql << delimiter << "'" << enumLiteral->name() << "'";
delimiter = QStringLiteral(", ");
}
sql << ");\n";
}
}
}
sql << "CREATE TABLE " << entityname << " (";
printEntityAttributes(sql, entAttList);
sql << m_endl << ");" << m_endl;
// auto increments
UMLEntityAttributeList autoIncrementList;
for(UMLEntityAttribute* entAtt : entAttList) {
autoIncrementList.append(entAtt);
}
printAutoIncrements(sql, autoIncrementList);
// write all unique constraint (including primary key)
UMLClassifierListItemList constrList = m_pEntity->getFilteredList(UMLObject::ot_UniqueConstraint);
printUniqueConstraints(sql, constrList);
// write all foreign key constraints
constrList = m_pEntity->getFilteredList(UMLObject::ot_ForeignKeyConstraint);
printForeignKeyConstraints(sql, constrList);
// write all check constraints
constrList = m_pEntity->getFilteredList(UMLObject::ot_CheckConstraint);
printCheckConstraints(sql, constrList);
// write all other indexes
for(UMLEntityAttribute* ea : entAttList) {
if (ea->indexType() != UMLEntityAttribute::Index)
continue;
UMLEntityAttributeList tempList;
tempList.append(ea);
printIndex(sql, m_pEntity, tempList);
tempList.clear();
}
QMap<UMLAssociation*, UMLAssociation*> constraintMap; // so we don't repeat constraint
UMLAssociationList relationships = m_pEntity->getRelationships();
if (forceSections() || !relationships.isEmpty()) {
for(UMLAssociation* a: relationships) {
UMLObject *objA = a->getObject(Uml::RoleType::A);
UMLObject *objB = a->getObject(Uml::RoleType::B);
if (objA->id() == m_pEntity->id() && objB->id() != m_pEntity->id())
continue;
constraintMap[a] = a;
}
}
QMap<UMLAssociation*, UMLAssociation*>::Iterator itor = constraintMap.begin();
for (; itor != constraintMap.end(); ++itor) {
UMLAssociation* a = itor.value();
sql << "ALTER TABLE " << entityname
<< " ADD CONSTRAINT " << a->name() << " FOREIGN KEY ("
<< a->getRoleName(Uml::RoleType::B) << ") REFERENCES "
<< a->getObject(Uml::RoleType::A)->name()
<< " (" << a->getRoleName(Uml::RoleType::A) << ");" << m_endl;
}
file.close();
Q_EMIT codeGenerated(m_pEntity, true);
Q_EMIT showGeneratedFile(file.fileName());
}
/**
* Returns "SQL".
*/
Uml::ProgrammingLanguage::Enum SQLWriter::language() const
{
return Uml::ProgrammingLanguage::SQL;
}
/**
* Reimplement method from CodeGenerator.
*/
QStringList SQLWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("blob"));
l.append(QStringLiteral("bigint"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("date"));
l.append(QStringLiteral("datetime"));
l.append(QStringLiteral("decimal"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("enum"));
l.append(QStringLiteral("longblob"));
l.append(QStringLiteral("longtext"));
l.append(QStringLiteral("mediumblob"));
l.append(QStringLiteral("mediumint"));
l.append(QStringLiteral("mediumtext"));
l.append(QStringLiteral("set"));
l.append(QStringLiteral("smallint"));
l.append(QStringLiteral("text"));
l.append(QStringLiteral("time"));
l.append(QStringLiteral("timestamp"));
l.append(QStringLiteral("tinyblob"));
l.append(QStringLiteral("tinyint"));
l.append(QStringLiteral("tinytext"));
l.append(QStringLiteral("varchar"));
l.append(QStringLiteral("year"));
return l;
}
/**
* Get list of reserved keywords.
*/
QStringList SQLWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
/**
* Prints out attributes as columns in the table.
* @param sql the stream we should print to
* @param entityAttributeList the attributes to be printed
*/
void SQLWriter::printEntityAttributes(QTextStream& sql, UMLEntityAttributeList entityAttributeList)
{
QString attrDoc;
bool first = true;
for(UMLEntityAttribute* at : entityAttributeList) {
// print, after attribute
if (first) {
first = false;
} else {
sql <<",";
}
// print documentation/comment of last attribute at end of line
if (attrDoc.isEmpty() == false) {
sql << " -- " << attrDoc << m_endl;
} else {
sql << m_endl;
}
// write the attribute name
sql << m_indentation << cleanName(at->name()) ;
// the datatype
if (language() == Uml::ProgrammingLanguage::MySQL &&
at->getType() && at->getType()->baseType() == UMLObject::ot_Enum) {
const UMLEnum *_enum = at->getType()->asUMLEnum();
sql << " ENUM(";
QString delimiter(QStringLiteral(""));
UMLClassifierListItemList enumLiterals = _enum->getFilteredList(UMLObject::ot_EnumLiteral);
for (UMLClassifierListItem* enumLiteral : enumLiterals) {
sql << delimiter << "'" << enumLiteral->name() << "'";
delimiter = QStringLiteral(", ");
}
sql << ')';
} else
sql << ' ' << at->getTypeName();
// the length (if there's some value)
QString lengthStr = at->getValues().trimmed();
bool ok;
uint length = lengthStr.toUInt(&ok);
if (ok) {
sql << '(' << length << ')';
}
// write the attributes (unsigned, zerofill etc)
QString attributes = at->getAttributes().trimmed();
if (!attributes.isEmpty()) {
sql << ' ' << attributes;
}
if (!at->getNull()) {
sql << " NOT NULL ";
}
// write any default values
if (!at->getInitialValue().isEmpty()) {
if (at->getType()->baseType() == UMLObject::ot_Enum) {
sql << QStringLiteral(" DEFAULT '") << at->getInitialValue() << QStringLiteral("'");
} else {
sql << QStringLiteral(" DEFAULT ") + at->getInitialValue();
}
}
// now get documentation/comment of current attribute
attrDoc = at->doc();
}
}
/**
* Prints out unique constraints (including primary key) as "ALTER TABLE" statements.
* @param sql the stream we should print to
* @param constrList the unique constraints to be printed
*/
void SQLWriter::printUniqueConstraints(QTextStream& sql, UMLClassifierListItemList constrList)
{
for(UMLClassifierListItem* cli : constrList) {
const UMLUniqueConstraint* uuc = cli->asUMLUniqueConstraint();
if (!uuc) {
logError2("SQLWriter::printUniqueConstraints: Invalid cast from '%1' to UMLUniqueConstraint* %2",
cli->name(), cli->baseTypeStr());
return;
}
sql << m_endl;
UMLEntityAttributeList attList = uuc->getEntityAttributeList();
// print documentation
sql << "-- " << uuc->doc();
sql << m_endl;
sql << "ALTER TABLE " << cleanName(m_pEntity->name())
<<" ADD CONSTRAINT " << cleanName(uuc->name());
if (m_pEntity->isPrimaryKey(uuc))
sql << " PRIMARY KEY ";
else
sql << " UNIQUE ";
sql << '(';
bool first = true;
for(UMLEntityAttribute* entAtt : attList) {
if (first)
first = false;
else
sql << ",";
sql << cleanName(entAtt->name());
}
sql << ");";
sql << m_endl;
}
}
/**
* Prints out foreign key constraints as "ALTER TABLE" statements.
* @param sql the stream we should print to
* @param constrList the foreignkey constraints to be printed
*/
void SQLWriter::printForeignKeyConstraints(QTextStream& sql, UMLClassifierListItemList constrList)
{
for(UMLClassifierListItem* cli : constrList) {
UMLForeignKeyConstraint* fkc = cli->asUMLForeignKeyConstraint();
if (!fkc) {
logError2("SQLWriter::printForeignKeyConstraints: Invalid cast from '%1' to UMLForeignKeyConstraint* %2",
cli->name(), cli->baseTypeStr());
return;
}
sql << m_endl;
QMap<UMLEntityAttribute*, UMLEntityAttribute*> attributeMap;
attributeMap = fkc->getEntityAttributePairs();
// print documentation
sql << "-- " << fkc->doc();
sql << m_endl;
sql << "ALTER TABLE " << cleanName(m_pEntity->name())
<<" ADD CONSTRAINT " << cleanName(fkc->name());
sql << " FOREIGN KEY (";
QList<UMLEntityAttribute*> entAttList = attributeMap.keys();
bool first = true;
// the local attributes which refer the attributes of the referenced entity
for(UMLEntityAttribute* entAtt : entAttList) {
if (first)
first = false;
else
sql << ',';
sql << cleanName(entAtt->name());
}
sql << ')';
sql << " REFERENCES ";
UMLEntity* referencedEntity = fkc->getReferencedEntity();
sql << cleanName(referencedEntity->name());
sql << '(';
QList<UMLEntityAttribute*> refEntAttList = attributeMap.values();
first = true;
// the attributes of the referenced entity which are being referenced
for(UMLEntityAttribute* refEntAtt : refEntAttList) {
if (first)
first = false;
else
sql << ',';
sql << cleanName(refEntAtt->name());
}
sql << ')';
UMLForeignKeyConstraint::UpdateDeleteAction updateAction, deleteAction;
updateAction = fkc->getUpdateAction();
deleteAction = fkc->getDeleteAction();
sql << " ON UPDATE " << Model_Utils::updateDeleteActionToString(updateAction);
sql << " ON DELETE " << Model_Utils::updateDeleteActionToString(deleteAction);
sql << ';';
sql << m_endl;
}
}
/**
* Prints out Indexes as "CREATE INDEX " statements.
* @param sql The Stream we should print to
* @param ent The Entity's attributes on which we want to create an Index
* @param entAttList The list of entityattributes to create an index upon
*/
void SQLWriter::printIndex(QTextStream& sql, UMLEntity* ent, UMLEntityAttributeList entAttList)
{
sql << m_endl;
sql << "CREATE INDEX ";
// we don;t have any name, so we just merge the names of all attributes along with their entity name
sql << cleanName(ent->name()) << '_';
for(UMLEntityAttribute* entAtt : entAttList) {
sql << cleanName(entAtt->name()) << '_';
}
sql << "index ";
sql << " ON " << cleanName(ent->name()) << '(';
bool first = true;
for (UMLEntityAttribute* entAtt : entAttList) {
if (first)
first = false;
else
sql << ',';
sql << cleanName(entAtt->name());
}
sql << ");";
sql << m_endl;
}
/**
* Handles AutoIncrements.
* The derived classes provide the actual body.
* @param sql The Stream we should print to
* @param entAttList The List of Entity Attributes that we want to auto increment
*/
void SQLWriter::printAutoIncrements(QTextStream& sql, UMLEntityAttributeList entAttList)
{
Q_UNUSED(sql); Q_UNUSED(entAttList);
// defer to derived classes
}
/**
* Prints out Check Constraints as "ALTER TABLE" statements.
* @param sql The stream we should print to
* @param constrList The checkConstraints to be printed
*/
void SQLWriter::printCheckConstraints(QTextStream& sql, UMLClassifierListItemList constrList)
{
for(UMLClassifierListItem* cli : constrList) {
const UMLCheckConstraint* chConstr = cli->asUMLCheckConstraint();
if (!chConstr) {
logError2("SQLWriter::printCheckConstraints: Invalid cast from '%1' to UMLCheckConstraint* %2",
cli->name(), cli->baseTypeStr());
return;
}
sql << m_endl;
// print documentation
sql << "-- " << chConstr->doc();
sql << m_endl;
sql << "ALTER TABLE " << cleanName(m_pEntity->name())
<<" ADD CONSTRAINT " << cleanName(chConstr->name())
<<" CHECK (" << chConstr->getCheckCondition()
<<");";
sql << m_endl;
}
}
| 17,811
|
C++
|
.cpp
| 563
| 25.015986
| 116
| 0.59972
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,520
|
postgresqlwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/sql/postgresqlwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "postgresqlwriter.h"
#include "entity.h"
#include "umlentityattributelist.h"
#include <KLocalizedString>
#include <QList>
#include <QTextStream>
PostgreSQLWriter::PostgreSQLWriter()
{
}
PostgreSQLWriter::~PostgreSQLWriter()
{
}
/**
* Returns "PostgreSQL".
*/
Uml::ProgrammingLanguage::Enum PostgreSQLWriter::language() const
{
return Uml::ProgrammingLanguage::PostgreSQL;
}
/**
* Reimplement method from CodeGenerator.
*/
QStringList PostgreSQLWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("bigint"));
l.append(QStringLiteral("bigserial"));
l.append(QStringLiteral("bit"));
l.append(QStringLiteral("bit varying"));
l.append(QStringLiteral("boolean"));
l.append(QStringLiteral("box"));
l.append(QStringLiteral("bytea"));
l.append(QStringLiteral("character varying"));
l.append(QStringLiteral("character"));
l.append(QStringLiteral("cidr"));
l.append(QStringLiteral("circle"));
l.append(QStringLiteral("date"));
l.append(QStringLiteral("decimal"));
l.append(QStringLiteral("double precision"));
l.append(QStringLiteral("inet"));
l.append(QStringLiteral("integer"));
l.append(QStringLiteral("interval"));
l.append(QStringLiteral("line"));
l.append(QStringLiteral("lseg"));
l.append(QStringLiteral("macaddr"));
l.append(QStringLiteral("money"));
l.append(QStringLiteral("numeric"));
l.append(QStringLiteral("path"));
l.append(QStringLiteral("point"));
l.append(QStringLiteral("polygon"));
l.append(QStringLiteral("real"));
l.append(QStringLiteral("serial"));
l.append(QStringLiteral("smallint"));
l.append(QStringLiteral("time without time zone"));
l.append(QStringLiteral("time with time zone"));
l.append(QStringLiteral("timestamp without time zone"));
l.append(QStringLiteral("timestamp with time zone"));
return l;
}
/**
* Reimplement printAutoIncrement statements from Base Class for PostgreSQL
*/
void PostgreSQLWriter::printAutoIncrements(QTextStream& sql, UMLEntityAttributeList entAttList)
{
// rules
// postgres has no such thing as auto increment
// instead it uses sequences. For simulating auto increment, set default value of
// each attribute to the nextval() of its very own sequence
for(UMLEntityAttribute* ea : entAttList) {
if (!ea->getAutoIncrement()) {
continue;
}
QString sequenceName;
// we keep the sequence name as entityName + '_' + entityAttributeName + '_seq'
sequenceName = m_pEntity->name() + QLatin1Char('_') + ea->name() + QStringLiteral("_seq");
// we assume the sequence count starts with 1 and interval is 1 too
// change the values when we start supporting different start values and
// interval values
sql<<"CREATE SEQUENCE "<<cleanName(sequenceName)
<<" START 1 INCREMENT 1 ;";
sql<<m_endl;
// alter the table column (set not null)
sql<<"ALTER TABLE "<<cleanName(m_pEntity->name())
<<" ALTER COLUMN "<<cleanName(ea->name())
<<" SET NOT 0;";
sql<<m_endl;
// alter the table column
sql<<"ALTER TABLE "<<cleanName(m_pEntity->name())
<<" ALTER COLUMN "<<cleanName(ea->name())
<<" SET DEFAULT nextval('"<<cleanName(sequenceName)
<<"');";
sql<<m_endl;
}
}
| 3,564
|
C++
|
.cpp
| 98
| 31.22449
| 98
| 0.682346
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,521
|
mysqlwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/sql/mysqlwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "mysqlwriter.h"
#include "entity.h"
#include "entityattribute.h"
#include "foreignkeyconstraint.h"
#include "umlclassifierlistitemlist.h"
#include "umlentityattributelist.h"
#include <KLocalizedString>
#include <QList>
#include <QTextStream>
MySQLWriter::MySQLWriter()
{
}
MySQLWriter::~MySQLWriter()
{
}
/**
* Returns "MySQL".
*/
Uml::ProgrammingLanguage::Enum MySQLWriter::language() const
{
return Uml::ProgrammingLanguage::MySQL;
}
/**
* Reimplement method from CodeGenerator.
*/
QStringList MySQLWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("ascii"));
l.append(QStringLiteral("bigint"));
l.append(QStringLiteral("bit"));
l.append(QStringLiteral("binary"));
l.append(QStringLiteral("blob"));
l.append(QStringLiteral("bool"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("charset"));
l.append(QStringLiteral("date"));
l.append(QStringLiteral("datetime"));
l.append(QStringLiteral("decimal"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("enum"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("integer"));
l.append(QStringLiteral("longblob"));
l.append(QStringLiteral("longtext"));
l.append(QStringLiteral("mediumblob"));
l.append(QStringLiteral("mediumint"));
l.append(QStringLiteral("mediumtext"));
l.append(QStringLiteral("serial"));
l.append(QStringLiteral("set"));
l.append(QStringLiteral("smallint"));
l.append(QStringLiteral("timestamp"));
l.append(QStringLiteral("time"));
l.append(QStringLiteral("tinyblob"));
l.append(QStringLiteral("tinyint"));
l.append(QStringLiteral("tinytext"));
l.append(QStringLiteral("text"));
l.append(QStringLiteral("unicode"));
l.append(QStringLiteral("varbinary"));
l.append(QStringLiteral("varchar"));
return l;
}
/**
* Reimplemented method from SQLWriter.
*/
void MySQLWriter::printForeignKeyConstraints(QTextStream& sql, UMLClassifierListItemList constrList)
{
// we need to create an index on the referenced attributes before we can create a foreign key constraint in MySQL
for(UMLClassifierListItem* cli : constrList) {
UMLForeignKeyConstraint* fkc = cli->asUMLForeignKeyConstraint();
QMap<UMLEntityAttribute*, UMLEntityAttribute*> attributeMap = fkc->getEntityAttributePairs();
// get the attributes
QList<UMLEntityAttribute*> eaList = attributeMap.keys();
// convert to UMLEntityAttributeList
UMLEntityAttributeList refAttList;
for(UMLEntityAttribute* ea : eaList) {
refAttList.append(ea);
}
// create an index on them
SQLWriter::printIndex(sql, m_pEntity, refAttList);
}
SQLWriter::printForeignKeyConstraints(sql, constrList);
}
/**
* Reimplement printAutoIncrements from Base Class for MySQL
*/
void MySQLWriter::printAutoIncrements(QTextStream& sql, const UMLEntityAttributeList entAttList)
{
// rules
// only one attribute can have an auto increment in a table in MySQL
// and that attribute should have an index on it :/
// get the first attribute of list with auto increment
UMLEntityAttribute *autoIncrementEntAtt = nullptr;
for(UMLEntityAttribute* ea : entAttList) {
if (ea->getAutoIncrement()) {
autoIncrementEntAtt = ea;
break;
}
}
if (autoIncrementEntAtt == nullptr) {
return;
}
// create an index on this attribute
UMLEntityAttributeList indexList;
indexList.append(autoIncrementEntAtt);
printIndex(sql, m_pEntity, indexList);
// now alter the table and this column to add the auto increment
sql << "ALTER TABLE " << cleanName(m_pEntity->name())
<< " CHANGE " << cleanName(autoIncrementEntAtt->name())
<< " " << cleanName(autoIncrementEntAtt->name())
<< " " << cleanName(autoIncrementEntAtt->getTypeName())
<< " " << cleanName(autoIncrementEntAtt->getAttributes())
<< " " << " NOT NULL AUTO_INCREMENT ;";
sql << m_endl;
// we don't support start values currently, but when we do, uncomment the following
//sql << " ALTER TABLE " << cleanName(m_pEntity->getName())
// <<" AUTO_INCREMENT = " << theValue;
//sql << m_endl;
}
/**
* Reimplemented from Base Class to print warning.
*/
void MySQLWriter::printCheckConstraints(QTextStream& sql, UMLClassifierListItemList constrList)
{
sql << m_endl;
sql << "-- CHECK Constraints are not supported in Mysql (as of version 5.x)";
sql << m_endl;
sql << "-- But it'll parse the statements without error ";
sql << m_endl;
// call base class
SQLWriter::printCheckConstraints(sql, constrList);
}
| 4,897
|
C++
|
.cpp
| 136
| 31.433824
| 117
| 0.702514
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,522
|
pascalwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/pascal/pascalwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "pascalwriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "classifierlistitem.h"
#include "debug_utils.h"
#include "enum.h"
#include "folder.h"
#include "operation.h"
#include "template.h"
#include "uml.h"
#include "umlclassifierlistitemlist.h"
#include "umldoc.h"
#include "umltemplatelist.h"
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
const QString PascalWriter::defaultPackageSuffix = QStringLiteral("_Holder");
/**
* Basic Constructor.
*/
PascalWriter::PascalWriter()
: SimpleCodeGenerator()
{
}
/**
* Empty Destructor.
*/
PascalWriter::~PascalWriter()
{
}
/**
* Returns "Pascal".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum PascalWriter::language() const
{
return Uml::ProgrammingLanguage::Pascal;
}
/**
*
*/
bool PascalWriter::isOOClass(const UMLClassifier *c)
{
UMLObject::ObjectType ot = c->baseType();
if (ot == UMLObject::ot_Interface)
return true;
if (ot == UMLObject::ot_Enum || ot == UMLObject::ot_Datatype)
return false;
if (ot != UMLObject::ot_Class) {
logWarn1("PascalWriter::isOOClass: unknown object type %1", UMLObject::toString(ot));
return false;
}
QString stype = c->stereotype();
if (stype == QStringLiteral("CORBAConstant") || stype == QStringLiteral("CORBATypedef") ||
stype == QStringLiteral("CORBAStruct") || stype == QStringLiteral("CORBAUnion"))
return false;
// CORBAValue, CORBAInterface, and all empty/unknown stereotypes are
// assumed to be OO classes.
return true;
}
QString PascalWriter::qualifiedName(UMLPackage *p, bool withType, bool byValue)
{
UMLPackage *umlPkg = p->umlPackage();
QString className = cleanName(p->name());
QString retval;
if (umlPkg == UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical))
umlPkg = nullptr;
const UMLClassifier *c = p->asUMLClassifier();
if (umlPkg == nullptr) {
retval = className;
if (c == nullptr || !isOOClass(c))
retval.append(defaultPackageSuffix);
} else {
retval = umlPkg->fullyQualifiedName(QStringLiteral("."));
if (c && isOOClass(c)) {
retval.append(QStringLiteral("."));
retval.append(className);
}
}
if (! withType)
return retval;
if (c && isOOClass(c)) {
retval.append(QStringLiteral(".Object"));
if (! byValue)
retval.append(QStringLiteral("_Ptr"));
} else {
retval.append(QStringLiteral("."));
retval.append(className);
}
return retval;
}
void PascalWriter::computeAssocTypeAndRole
(UMLAssociation *a, QString& typeName, QString& roleName)
{
roleName = a->getRoleName(Uml::RoleType::A);
if (roleName.isEmpty()) {
if (a->getMultiplicity(Uml::RoleType::A).isEmpty()) {
roleName = QStringLiteral("M_");
roleName.append(typeName);
} else {
roleName = typeName;
roleName.append(QStringLiteral("_Vector"));
}
}
const UMLClassifier* c = a->getObject(Uml::RoleType::A)->asUMLClassifier();
if (c == nullptr)
return;
typeName = cleanName(c->name());
if (! a->getMultiplicity(Uml::RoleType::A).isEmpty())
typeName.append(QStringLiteral("_Array_Access"));
}
/**
* Call this method to generate Pascal code for a UMLClassifier.
* @param c the class to generate code for
*/
void PascalWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("PascalWriter::writeClass: Cannot write class of NULL classifier");
return;
}
const bool isClass = !c->isInterface();
QString classname = cleanName(c->name());
QString fileName = qualifiedName(c).toLower();
fileName.replace(QLatin1Char('.'), QLatin1Char('-'));
//find an appropriate name for our file
fileName = overwritableName(c, fileName, QStringLiteral(".pas"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
// Start generating the code.
QTextStream pas(&file);
//try to find a heading file(license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".pas"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
pas << str << Qt::endl;
}
QString unit = qualifiedName(c);
pas << "unit " << unit << ";" << m_endl << m_endl;
pas << "INTERFACE" << m_endl << m_endl;
// Use referenced classes.
UMLPackageList imports;
findObjectsRelated(c, imports);
if (imports.count()) {
pas << "uses" << m_endl;
bool first = true;
for(UMLPackage* con : imports) {
if (!con->isUMLDatatype()) {
if (first)
first = false;
else
pas << "," << m_endl;
pas << " " << qualifiedName(con);
}
}
pas << ";" << m_endl << m_endl;
}
pas << "type" << m_endl;
m_indentLevel++;
if (c->baseType() == UMLObject::ot_Enum) {
const UMLEnum *ue = c->asUMLEnum();
UMLClassifierListItemList litList = ue->getFilteredList(UMLObject::ot_EnumLiteral);
uint i = 0;
pas << indent() << classname << " = (" << m_endl;
m_indentLevel++;
for(UMLClassifierListItem *lit : litList) {
QString enumLiteral = cleanName(lit->name());
pas << indent() << enumLiteral;
if (++i < (uint)litList.count())
pas << "," << m_endl;
}
m_indentLevel--;
pas << ");" << m_endl << m_endl;
m_indentLevel--;
pas << "end." << m_endl << m_endl;
return;
}
UMLAttributeList atl = c->getAttributeList();
if (! isOOClass(c)) {
QString stype = c->stereotype();
if (stype == QStringLiteral("CORBAConstant")) {
pas << indent() << "// " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else if(stype == QStringLiteral("CORBAStruct")) {
if (isClass) {
pas << indent() << classname << " = record" << m_endl;
m_indentLevel++;
for(UMLAttribute* at : atl) {
QString name = cleanName(at->name());
QString typeName = at->getTypeName();
pas << indent() << name << " : " << typeName;
QString initialVal = at->getInitialValue();
if (!initialVal.isEmpty())
pas << " := " << initialVal;
pas << ";" << m_endl;
}
m_indentLevel--;
pas << "end;" << m_endl << m_endl;
}
} else if(stype == QStringLiteral("CORBAUnion")) {
pas << indent() << "// " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else if(stype == QStringLiteral("CORBATypedef")) {
pas << indent() << "// " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else {
pas << indent() << "// " << stype << ": Unknown stereotype" << m_endl << m_endl;
}
m_indentLevel--;
pas << indent() << "end." << m_endl << m_endl;
return;
}
// Write class Documentation if non-empty or if force option set.
if (forceDoc() || !c->doc().isEmpty()) {
pas << "//" << m_endl;
pas << "// class " << classname << Qt::endl;
pas << formatDoc(c->doc(), QStringLiteral("// "));
pas << m_endl;
}
UMLClassifierList superclasses = c->getSuperClasses();
pas << indent() << classname << " = object";
if (!superclasses.isEmpty()) {
// FIXME: Multiple inheritance is not yet supported
UMLClassifier* parent = superclasses.first();
pas << "(" << qualifiedName(parent) << ")";
}
pas << m_endl;
UMLAttributeList atpub = c->getAttributeList(Uml::Visibility::Public);
if (isClass && (forceSections() || atpub.count())) {
pas << indent() << "// Public attributes:" << m_endl;
for(UMLAttribute* at : atpub) {
// if (at->getStatic())
// continue;
pas << indent() << cleanName(at->name()) << " : "
<< at->getTypeName();
if (at && !at->getInitialValue().isEmpty())
pas << " := " << at->getInitialValue();
pas << ";" << m_endl;
}
}
//bool haveAttrs = (isClass && atl.count());
// Generate public operations.
UMLOperationList opl(c->getOpList());
UMLOperationList oppub;
for(UMLOperation* op : opl) {
if (op->visibility() == Uml::Visibility::Public)
oppub.append(op);
}
if (forceSections() || oppub.count())
pas << indent() << "// Public methods:" << m_endl << m_endl;
for(UMLOperation* op : oppub)
writeOperation(op, pas);
UMLAttributeList atprot = c->getAttributeList(Uml::Visibility::Protected);
if (atprot.count()) {
pas << "protected" << m_endl << m_endl;
for(UMLAttribute* at : atprot) {
// if (at->getStatic())
// continue;
pas << indent() << cleanName(at->name()) << " : "
<< at->getTypeName();
if (!at->getInitialValue().isEmpty())
pas << " := " << at->getInitialValue();
pas << ";" << m_endl;
}
pas << m_endl;
}
UMLAttributeList atpriv = c->getAttributeList(Uml::Visibility::Private);
if (atpriv.count()) {
pas << "private" << m_endl << m_endl;
for(UMLAttribute* at : atpriv) {
if (at) {
pas << indent() << cleanName(at->name()) << " : "
<< at->getTypeName();
// if (at->getStatic())
// continue;
if (!at->getInitialValue().isEmpty())
pas << " := " << at->getInitialValue();
pas << ";" << m_endl;
}
}
pas << m_endl;
}
pas << indent() << "end;" << m_endl << m_endl;
pas << indent() << "P" << classname << " = ^" << classname <<";" << m_endl << m_endl;
m_indentLevel--;
pas << "end;" << m_endl << m_endl;
file.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(file.fileName());
}
/**
* Write one operation.
* @param op the class for which we are generating code
* @param pas the stream associated with the output file
* @param is_comment specifying true generates the operation as commented out
*/
void PascalWriter::writeOperation(UMLOperation *op, QTextStream &pas, bool is_comment)
{
if (op->isStatic()) {
pas << "// TODO: generate status method " << op->name() << m_endl;
return;
}
UMLAttributeList atl = op->getParmList();
QString rettype = op->getTypeName();
bool use_procedure = (rettype.isEmpty() || rettype == QStringLiteral("void"));
pas << indent();
if (is_comment)
pas << "// ";
if (use_procedure)
pas << "procedure ";
else
pas << "function ";
pas << cleanName(op->name()) << " ";
if (atl.count()) {
pas << "(" << m_endl;
uint i = 0;
m_indentLevel++;
for(UMLAttribute *at : atl) {
pas << indent();
if (is_comment)
pas << "// ";
pas << cleanName(at->name()) << " : ";
Uml::ParameterDirection::Enum pk = at->getParmKind();
if (pk != Uml::ParameterDirection::In)
pas << "var ";
pas << at->getTypeName();
if (! at->getInitialValue().isEmpty())
pas << " := " << at->getInitialValue();
if (++i < (uint)atl.count())
pas << ";" << m_endl;
}
m_indentLevel--;
pas << ")";
}
if (! use_procedure)
pas << " : " << rettype << ";";
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
pas << " virtual; abstract;" << m_endl << m_endl;
// TBH, we make the methods abstract here because we don't have the means
// for generating meaningful implementations.
}
else {
pas << m_endl;
pas << indent() << "begin" << m_endl;
m_indentLevel++;
pas << formatSourceCode(sourceCode, indent());
m_indentLevel--;
pas << indent() << "end;" << m_endl << m_endl;
}
}
/**
* Returns the default datatypes in a list.
* @return the list of default datatypes
*/
QStringList PascalWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("AnsiString"));
l.append(QStringLiteral("Boolean"));
l.append(QStringLiteral("Byte"));
l.append(QStringLiteral("ByteBool"));
l.append(QStringLiteral("Cardinal"));
l.append(QStringLiteral("Character"));
l.append(QStringLiteral("Currency"));
l.append(QStringLiteral("Double"));
l.append(QStringLiteral("Extended"));
l.append(QStringLiteral("Int64"));
l.append(QStringLiteral("Integer"));
l.append(QStringLiteral("Longint"));
l.append(QStringLiteral("LongBool"));
l.append(QStringLiteral("Longword"));
l.append(QStringLiteral("QWord"));
l.append(QStringLiteral("Real"));
l.append(QStringLiteral("Shortint"));
l.append(QStringLiteral("ShortString"));
l.append(QStringLiteral("Single"));
l.append(QStringLiteral("Smallint"));
l.append(QStringLiteral("String"));
l.append(QStringLiteral("WideString"));
l.append(QStringLiteral("Word"));
return l;
}
/**
* Check whether the given string is a reserved word for the
* language of this code generator.
* @param rPossiblyReservedKeyword the string to check
*/
bool PascalWriter::isReservedKeyword(const QString & rPossiblyReservedKeyword)
{
const QStringList keywords = reservedKeywords();
QStringList::ConstIterator it;
for (it = keywords.begin(); it != keywords.end(); ++it)
if ((*it).toLower() == rPossiblyReservedKeyword.toLower())
return true;
return false;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList PascalWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords.append(QStringLiteral("absolute"));
keywords.append(QStringLiteral("abstract"));
keywords.append(QStringLiteral("and"));
keywords.append(QStringLiteral("array"));
keywords.append(QStringLiteral("as"));
keywords.append(QStringLiteral("asm"));
keywords.append(QStringLiteral("assembler"));
keywords.append(QStringLiteral("automated"));
keywords.append(QStringLiteral("begin"));
keywords.append(QStringLiteral("case"));
keywords.append(QStringLiteral("cdecl"));
keywords.append(QStringLiteral("class"));
keywords.append(QStringLiteral("const"));
keywords.append(QStringLiteral("constructor"));
keywords.append(QStringLiteral("contains"));
keywords.append(QStringLiteral("default"));
keywords.append(QStringLiteral("deprecated"));
keywords.append(QStringLiteral("destructor"));
keywords.append(QStringLiteral("dispid"));
keywords.append(QStringLiteral("dispinterface"));
keywords.append(QStringLiteral("div"));
keywords.append(QStringLiteral("do"));
keywords.append(QStringLiteral("downto"));
keywords.append(QStringLiteral("dynamic"));
keywords.append(QStringLiteral("else"));
keywords.append(QStringLiteral("end"));
keywords.append(QStringLiteral("except"));
keywords.append(QStringLiteral("export"));
keywords.append(QStringLiteral("exports"));
keywords.append(QStringLiteral("external"));
keywords.append(QStringLiteral("far"));
keywords.append(QStringLiteral("file"));
keywords.append(QStringLiteral("final"));
keywords.append(QStringLiteral("finalization"));
keywords.append(QStringLiteral("finally"));
keywords.append(QStringLiteral("for"));
keywords.append(QStringLiteral("forward"));
keywords.append(QStringLiteral("function"));
keywords.append(QStringLiteral("goto"));
keywords.append(QStringLiteral("if"));
keywords.append(QStringLiteral("implementation"));
keywords.append(QStringLiteral("implements"));
keywords.append(QStringLiteral("in"));
keywords.append(QStringLiteral("index"));
keywords.append(QStringLiteral("inherited"));
keywords.append(QStringLiteral("initialization"));
keywords.append(QStringLiteral("inline"));
keywords.append(QStringLiteral("inline"));
keywords.append(QStringLiteral("interface"));
keywords.append(QStringLiteral("is"));
keywords.append(QStringLiteral("label"));
keywords.append(QStringLiteral("library"));
keywords.append(QStringLiteral("library"));
keywords.append(QStringLiteral("local"));
keywords.append(QStringLiteral("message"));
keywords.append(QStringLiteral("mod"));
keywords.append(QStringLiteral("name"));
keywords.append(QStringLiteral("near"));
keywords.append(QStringLiteral("nil"));
keywords.append(QStringLiteral("nodefault"));
keywords.append(QStringLiteral("not"));
keywords.append(QStringLiteral("object"));
keywords.append(QStringLiteral("of"));
keywords.append(QStringLiteral("or"));
keywords.append(QStringLiteral("out"));
keywords.append(QStringLiteral("overload"));
keywords.append(QStringLiteral("override"));
keywords.append(QStringLiteral("package"));
keywords.append(QStringLiteral("packed"));
keywords.append(QStringLiteral("pascal"));
keywords.append(QStringLiteral("platform"));
keywords.append(QStringLiteral("private"));
keywords.append(QStringLiteral("procedure"));
keywords.append(QStringLiteral("program"));
keywords.append(QStringLiteral("property"));
keywords.append(QStringLiteral("protected"));
keywords.append(QStringLiteral("public"));
keywords.append(QStringLiteral("published"));
keywords.append(QStringLiteral("raise"));
keywords.append(QStringLiteral("read"));
keywords.append(QStringLiteral("readonly"));
keywords.append(QStringLiteral("record"));
keywords.append(QStringLiteral("register"));
keywords.append(QStringLiteral("reintroduce"));
keywords.append(QStringLiteral("repeat"));
keywords.append(QStringLiteral("requires"));
keywords.append(QStringLiteral("resident"));
keywords.append(QStringLiteral("resourcestring"));
keywords.append(QStringLiteral("safecall"));
keywords.append(QStringLiteral("sealed"));
keywords.append(QStringLiteral("set"));
keywords.append(QStringLiteral("shl"));
keywords.append(QStringLiteral("shr"));
keywords.append(QStringLiteral("static"));
keywords.append(QStringLiteral("stdcall"));
keywords.append(QStringLiteral("stored"));
keywords.append(QStringLiteral("string"));
keywords.append(QStringLiteral("then"));
keywords.append(QStringLiteral("threadvar"));
keywords.append(QStringLiteral("to"));
keywords.append(QStringLiteral("try"));
keywords.append(QStringLiteral("type"));
keywords.append(QStringLiteral("unit"));
keywords.append(QStringLiteral("unsafe"));
keywords.append(QStringLiteral("until"));
keywords.append(QStringLiteral("uses"));
keywords.append(QStringLiteral("var"));
keywords.append(QStringLiteral("varargs"));
keywords.append(QStringLiteral("virtual"));
keywords.append(QStringLiteral("while"));
keywords.append(QStringLiteral("with"));
keywords.append(QStringLiteral("write"));
keywords.append(QStringLiteral("writeonly"));
keywords.append(QStringLiteral("xor"));
}
return keywords;
}
| 20,642
|
C++
|
.cpp
| 535
| 31.04486
| 95
| 0.603949
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,523
|
valawriter.cpp
|
KDE_umbrello/umbrello/codegenerators/vala/valawriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2009-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
//
// C++ Implementation: valawriter
//
#include "valawriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "folder.h"
#include "operation.h"
#include "uml.h"
#include "umldoc.h"
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while",
nullptr
};
/**
* Constructor.
*/
ValaWriter::ValaWriter()
: SimpleCodeGenerator(),
m_unnamedRoles(0)
{
}
/**
* Destructor.
*/
ValaWriter::~ValaWriter()
{
}
/**
* Get list of predefined data types.
* @return the list of default data types
*/
QStringList ValaWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("bool"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("uchar"));
l.append(QStringLiteral("unichar"));
l.append(QStringLiteral("int"));
l.append(QStringLiteral("int8"));
l.append(QStringLiteral("int16"));
l.append(QStringLiteral("int32"));
l.append(QStringLiteral("int64"));
l.append(QStringLiteral("uint"));
l.append(QStringLiteral("uint8"));
l.append(QStringLiteral("uint16"));
l.append(QStringLiteral("uint32"));
l.append(QStringLiteral("uint64"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("ulong"));
l.append(QStringLiteral("short"));
l.append(QStringLiteral("ushort"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("struct"));
l.append(QStringLiteral("enum"));
l.append(QStringLiteral("string"));
l.append(QStringLiteral("bool[]"));
l.append(QStringLiteral("char[]"));
l.append(QStringLiteral("uchar[]"));
l.append(QStringLiteral("unichar[]"));
l.append(QStringLiteral("int[]"));
l.append(QStringLiteral("int8[]"));
l.append(QStringLiteral("int16[]"));
l.append(QStringLiteral("int32[]"));
l.append(QStringLiteral("int64[]"));
l.append(QStringLiteral("uint[]"));
l.append(QStringLiteral("uint8[]"));
l.append(QStringLiteral("uint16[]"));
l.append(QStringLiteral("uint32[]"));
l.append(QStringLiteral("uint64[]"));
l.append(QStringLiteral("long[]"));
l.append(QStringLiteral("ulong[]"));
l.append(QStringLiteral("short[]"));
l.append(QStringLiteral("ushort[]"));
l.append(QStringLiteral("float[]"));
l.append(QStringLiteral("double[]"));
l.append(QStringLiteral("struct[]"));
l.append(QStringLiteral("enum[]"));
l.append(QStringLiteral("string[]"));
return l;
}
/**
* Call this method to generate Vala code for a UMLClassifier
* @param c the class you want to generate code for.
*/
void ValaWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("ValaWriter::writeClassL Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".vala"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile filecs;
if (!openFile(filecs, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream cs(&filecs);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".vala"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filecs.fileName());
cs << str << m_endl;
}
UMLDoc *umldoc = UMLApp::app()->document();
UMLFolder *logicalView = umldoc->rootFolder(Uml::ModelType::Logical);
// write generic includes
//cs << "using GLib;" << m_endl;
//cs << "using System.Text;" << m_endl;
//cs << "using System.Collections;" << m_endl;
cs << "using GLib;" << m_endl << m_endl;
//write includes and namespace
UMLPackage *container = c->umlPackage();
if (container == logicalView) {
container = nullptr;
}
UMLPackageList includes;
findObjectsRelated(c, includes);
m_seenIncludes.clear();
//m_seenIncludes.append(logicalView);
if (includes.count()) {
for (UMLPackage* p : includes) {
UMLClassifier *cl = p->asUMLClassifier();
if (cl) {
p = cl->umlPackage();
}
if (p != logicalView && m_seenIncludes.indexOf(p) == -1 && p != container) {
cs << "using " << p->fullyQualifiedName(QStringLiteral(".")) << ";" << m_endl;
m_seenIncludes.append(p);
}
}
cs << m_endl;
}
m_container_indent = QString();
if (container) {
cs << "namespace " << container->fullyQualifiedName(QStringLiteral(".")) << m_endl;
cs << "{" << m_endl << m_endl;
m_container_indent = m_indentation;
m_seenIncludes.append(container);
}
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty()) {
cs << m_container_indent << "/**" << m_endl;
if (c->doc().isEmpty()) {
cs << formatDoc(c->doc(), m_container_indent + QStringLiteral(" * TODO: Add documentation here."));
}
else {
cs << formatDoc(c->doc(), m_container_indent + m_indentation + QStringLiteral(" * "));
}
cs << m_container_indent << " */" << m_endl ;
}
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
UMLAssociationList realizations = c->getRealizations();
bool isInterface = c->isInterface();
m_unnamedRoles = 1;
cs << m_container_indent << "public ";
//check if it is an interface or regular class
if (isInterface) {
cs << "interface " << classname;
}
else {
//check if class is abstract and / or has abstract methods
if (c->isAbstract() || c->hasAbstractOps()) {
cs << "abstract ";
}
cs << "class " << classname << (superclasses.count() > 0 ? QStringLiteral(" : ") : QString());
// write baseclass, ignore interfaces, write error on multiple inheritance
if (superclasses.count() > 0) {
int supers = 0;
for (UMLClassifier* obj : superclasses) {
if (!obj->isInterface()) {
if (supers > 0) {
cs << " // AND ";
}
cs << cleanName(obj->name());
supers++;
}
}
if (supers > 1) {
cs << m_endl << "//WARNING: Vala does not support multiple inheritance but there is more than 1 superclass defined in your UML model!" << m_endl;
}
}
//check for realizations
UMLAssociationList realizations = c->getRealizations();
if (!realizations.isEmpty()) {
for (UMLAssociation* a : realizations) {
UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::RoleType::B);
if(real != c) {
// write list of realizations
cs << ", " << real->name();
}
}
}
}
cs << m_endl << m_container_indent << '{' << m_endl;
//associations
if (forceSections() || !aggregations.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "//region Aggregations" << m_endl << m_endl;
writeAssociatedAttributes(aggregations, c, cs);
cs << m_endl << m_container_indent << m_indentation << "//endregion" << m_endl;
}
//compositions
if (forceSections() || !compositions.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "//region Compositions" << m_endl << m_endl;
writeAssociatedAttributes(compositions, c, cs);
cs << m_endl << m_container_indent << m_indentation << "//endregion" << m_endl;
}
//attributes
// FIXME: Vala allows Properties in interface!
if (!isInterface) {
writeAttributes(c, cs);
}
//operations
writeOperations(c, cs);
//finish file
cs << m_endl << m_container_indent << "}" << m_endl << m_endl; // close class
if (container) {
cs << "} // end of namespace "
<< container->fullyQualifiedName(QStringLiteral(".")) << m_endl << m_endl;
}
//close files and notfiy we are done
filecs.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(filecs.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param cs output stream
*/
void ValaWriter::writeOperations(UMLClassifier *c, QTextStream &cs)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
bool isInterface = c->isInterface();
bool generateErrorStub = true;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for (UMLOperation* op : opl) {
switch (op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
// write realizations (recursive)
UMLAssociationList realizations = c->getRealizations();
if (!isInterface && !realizations.isEmpty()) {
writeRealizationsRecursive(c, &realizations, cs);
}
// write public operations
if (forceSections() || !oppub.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "//region Public methods" << m_endl << m_endl;
writeOperations(oppub, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
}
// write protected operations
if (forceSections() || !opprot.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "//region Protected methods" << m_endl << m_endl;
writeOperations(opprot, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
}
// write private operations
if (forceSections() || !oppriv.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "//region Private methods" << m_endl << m_endl;
writeOperations(oppriv, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
}
// write superclasses abstract methods
UMLClassifierList superclasses = c->getSuperClasses();
if (!isInterface && !c->isAbstract() && !c->hasAbstractOps() && superclasses.count() > 0) {
writeOverridesRecursive(&superclasses, cs);
}
}
/**
* Write superclasses' abstract methods.
* @param superclasses List of superclasses to start recursing on
* @param cs output stream
*/
void ValaWriter::writeOverridesRecursive(UMLClassifierList *superclasses, QTextStream &cs)
{
// oplist for implemented abstract operations
UMLOperationList opabstract;
for (UMLClassifier* obj : *superclasses) {
if (!obj->isInterface() && obj->hasAbstractOps()) {
// collect abstract ops
UMLOperationList opl(obj->getOpList());
for (UMLOperation* op : opl) {
if (op->isAbstract()) {
opabstract.append(op);
}
}
// write abstract implementations
cs << m_endl << m_container_indent << m_indentation << "//region " << obj->name() << " members" << m_endl << m_endl;
writeOperations(opabstract, cs, false, true, true);
cs << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
opabstract.clear();
}
// Recurse to parent superclasses
UMLClassifierList superRecursive = obj->getSuperClasses();
UMLClassifierList *superRecursivePtr =& superRecursive;
if (superRecursivePtr->count() > 0) {
writeOverridesRecursive(superRecursivePtr, cs);
}
}
}
/**
* Write realizations of a class and recurse to parent classes.
* @param currentClass class to start with
* @param realizations realizations of this class
* @param cs output stream
*/
void ValaWriter::writeRealizationsRecursive(UMLClassifier *currentClass, UMLAssociationList *realizations, QTextStream &cs)
{
for (UMLAssociationListIt alit(*realizations); alit.hasNext();) {
UMLAssociation *a = alit.next();
// we know it is a classifier if it is in the list
UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::RoleType::B);
//FIXME: Interfaces realize themselves without this condition!?
if (real == currentClass) {
continue;
}
// collect operations of one realization
UMLOperationList opreal = real->getOpList();
// write realizations
cs << m_endl << m_container_indent << m_indentation << "//region " << real->name() << " members" << m_endl << m_endl;
writeOperations(opreal, cs, false, false, true);
cs << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
// Recurse to parent realizations
UMLAssociationList parentReal = real->getRealizations();
if (!parentReal.isEmpty()) {
writeRealizationsRecursive(real, &parentReal, cs);
}
}
}
/**
* Write a list of class operations.
* @param opList the list of operations
* @param cs output stream
* @param isInterface indicates if the operation is an interface member
* @param isOverride implementation of an inherited abstract function
* @param generateErrorStub true generates a comment "The method or operation is not implemented"
*/
void ValaWriter::writeOperations(UMLOperationList opList,
QTextStream &cs, bool isInterface /* = false */,
bool isOverride /* = false */,
bool generateErrorStub /* = false */)
{
for (UMLOperation* op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for (UMLAttribute* at : atl) {
writeDoc |= !at->doc().isEmpty();
}
//write method documentation
if (writeDoc && !isOverride) {
cs << m_container_indent << m_indentation << "/**" << m_endl;
if (op->doc().isEmpty()) {
cs << formatDoc(op->doc(), m_container_indent + m_indentation + QStringLiteral(" * TODO: Add documentation here. "));
}
else {
cs << formatDoc(op->doc(), m_container_indent + m_indentation + QStringLiteral(" * "));
}
//write parameter documentation
for (UMLAttribute* at : atl) {
if (forceDoc() || !at->doc().isEmpty()) {
cs << m_container_indent << m_indentation << " * @param " << cleanName(at->name());
QString doc = formatDoc(at->doc(), QString());
//removing newlines from parameter doc
doc.replace(QLatin1Char('\n'), QLatin1Char(' '));
doc.remove(QLatin1Char('\r'));
doc.remove(QRegularExpression(QStringLiteral(" $")));
cs << doc << m_endl;
}
}
// FIXME: "returns" should contain documentation, not type.
cs << m_container_indent << m_indentation << " * @return ";
if (! op->getTypeName().isEmpty()) {
cs << makeLocalTypeName(op);
}
cs << m_endl;
cs << m_container_indent << m_indentation << " */" << m_endl;
}
// method visibility
cs << m_container_indent << m_indentation;
if (!isInterface) {
if (!isOverride) {
if (op->isAbstract()) {
cs << "abstract ";
}
cs << Uml::Visibility::toString(op->visibility()) << " ";
if (op->isStatic()) {
cs << "static ";
}
}
else {
// method overriding an abstract parent
cs << Uml::Visibility::toString(op->visibility()) << " override ";
if (op->isStatic()) {
cs << "static ";
}
}
}
// return type (unless constructor, destructor)
if (!op->isLifeOperation()) {
if (op->getTypeName().isEmpty()) {
cs << "void ";
}
else {
cs << makeLocalTypeName(op) << " ";
}
}
// method name
cs << cleanName(op->name()) << "(";
// method parameters
int i= atl.count();
int j=0;
for (UMLAttributeListIt atlIt(atl); atlIt.hasNext(); ++j) {
UMLAttribute* at = atlIt.next();
cs << makeLocalTypeName(at) << " " << cleanName(at->name());
// no initial values in Vala
//<< (!(at->getInitialValue().isEmpty()) ?
// (QStringLiteral(" = ")+at->getInitialValue()) :
// QString())
cs << ((j < i-1) ? QStringLiteral(", ") : QString());
}
cs << ")";
//FIXME: how to control generation of error stub?
if (!isInterface && (!op->isAbstract() || isOverride)) {
cs << m_endl << m_container_indent << m_indentation << "{" << m_endl;
// write source code of operation else throw not implemented exception
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
if (generateErrorStub) {
cs << m_container_indent << m_indentation << m_indentation;
cs << "//TODO: The method or operation is not implemented." << m_endl;
if (!op->getTypeName().isEmpty()) {
cs << m_container_indent << m_indentation << m_indentation;
cs << "return 0; "<< m_endl;
}
}
}
else {
cs << formatSourceCode(sourceCode, m_container_indent + m_indentation + m_indentation);
}
cs << m_container_indent << m_indentation << "}" << m_endl;
}
else {
cs << ';' << m_endl;
}
cs << m_endl;
}
}
/**
* Write all the attributes of a class.
* @param c the class we are generating code for
* @param cs output stream
*/
void ValaWriter::writeAttributes(UMLClassifier *c, QTextStream &cs)
{
UMLAttributeList atpub, atprot, atpriv, atdefval;
//sort attributes by scope and see if they have a default value
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty())
atdefval.append(at);
switch (at->visibility()) {
case Uml::Visibility::Public:
atpub.append(at);
break;
case Uml::Visibility::Protected:
atprot.append(at);
break;
case Uml::Visibility::Private:
atpriv.append(at);
break;
default:
break;
}
}
if (forceSections() || atl.count()) {
cs << m_endl << m_container_indent << m_indentation << "//region Attributes" << m_endl << m_endl;
}
// write public attributes
if (forceSections() || atpub.count()) {
writeAttributes(atpub, cs);
}
// write protected attributes
if (forceSections() || atprot.count()) {
writeAttributes(atprot, cs);
}
// write private attributes
if (forceSections() || atpriv.count()) {
writeAttributes(atpriv, cs);
}
if (forceSections() || atl.count()) {
cs << m_endl << m_container_indent << m_indentation << "//endregion" << m_endl << m_endl;
}
}
/**
* Write a list of class attributes.
* @param atList the list of attributes
* @param cs output stream
*/
void ValaWriter::writeAttributes(UMLAttributeList &atList, QTextStream &cs)
{
for (UMLAttribute* at : atList) {
bool asProperty = true;
if (at->visibility() == Uml::Visibility::Private) {
asProperty = false;
}
writeAttribute(at->doc(), at->visibility(), at->isStatic(),
makeLocalTypeName(at), at->name(), at->getInitialValue(), asProperty, cs);
cs << m_endl;
} // end for
return;
}
/**
* Write attributes from associated objects (compositions, aggregations).
* @param associated list of associated objects
* @param c currently written class, to see association direction
* @param cs output stream
*/
void ValaWriter::writeAssociatedAttributes(UMLAssociationList &associated, UMLClassifier *c, QTextStream &cs)
{
for (UMLAssociation *a : associated) {
if (c != a->getObject(Uml::RoleType::A)) { // we need to be at the A side
continue;
}
UMLObject *o = a->getObject(Uml::RoleType::B);
if (o == nullptr) {
logError0("ValaWriter::writeAssociatedAttributes: composition role B object is NULL");
continue;
}
// Take name and documentation from Role, take type name from the referenced object
QString roleName = cleanName(a->getRoleName(Uml::RoleType::B));
QString typeName = cleanName(o->name());
if (roleName.isEmpty()) {
roleName = QString::fromLatin1("UnnamedRoleB_%1").arg(m_unnamedRoles++);
}
QString roleDoc = a->getRoleDoc(Uml::RoleType::B);
//FIXME:is this simple condition enough?
if (a->getMultiplicity(Uml::RoleType::B).isEmpty() || a->getMultiplicity(Uml::RoleType::B) == QStringLiteral("1")) {
// normal attribute
writeAttribute(roleDoc, a->visibility(Uml::RoleType::B), false, typeName, roleName, QString(), (a->visibility(Uml::RoleType::B) != Uml::Visibility::Private), cs);
}
else {
// array
roleDoc += QStringLiteral("\n(Array of ") + typeName + QLatin1Char(')');
writeAttribute(roleDoc, a->visibility(Uml::RoleType::B), false, QStringLiteral("ArrayList"), roleName, QString(), (a->visibility(Uml::RoleType::B) != Uml::Visibility::Private), cs);
}
}
}
/**
* Write a single attribute to the output stream.
* @param doc attribute documentation
* @param visibility attribute visibility
* @param isStatic static attribute
* @param typeName class/type of the attribute
* @param name name of the attribute
* @param initialValue initial value given to the attribute at declaration
* @param asProperty true writes as property (get/set), false writes single line variable
* @param cs output stream
*/
void ValaWriter::writeAttribute(const QString& doc,
Uml::Visibility::Enum visibility,
bool isStatic,
const QString& typeName,
const QString& name,
const QString& initialValue,
bool asProperty,
QTextStream &cs)
{
if (forceDoc() || !doc.isEmpty()) {
cs << m_container_indent << m_indentation << "/**" << m_endl;
if (doc.isEmpty()) {
cs << formatDoc(doc, m_container_indent + m_indentation + QStringLiteral(" * TODO: Add documentation here."));
}
else {
cs << formatDoc(doc, m_container_indent + m_indentation + QStringLiteral(" * "));
}
cs << m_container_indent << m_indentation << " */" << m_endl;
}
cs << m_container_indent << m_indentation;
cs << Uml::Visibility::toString(visibility) << " ";
if (isStatic) {
cs << "static ";
}
//Variable type with/without namespace path
cs << typeName << " ";
cs << cleanName(name);
// FIXME: may need a GUI switch to not generate as Property?
// Generate as Property if not private
if (asProperty) {
cs << m_endl;
cs << m_container_indent << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "get" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << m_indentation << "return m_" << cleanName(name) << ";" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "set" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << m_indentation << "m_" << cleanName(name) << " = value;" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << "private ";
if (isStatic) {
cs << "static ";
}
cs << typeName << " m_" << cleanName(name);
}
if (!initialValue.isEmpty()) {
cs << " = " << initialValue;
}
cs << ";" << m_endl << m_endl;
}
/**
* Find the type in used namespaces, if namespace found return short name, complete otherwise.
* @param cl Operation or Attribute to check type
* @return the local type name
*/
QString ValaWriter::makeLocalTypeName(UMLClassifierListItem *cl)
{
UMLClassifier *c = cl->getType();
if (c) {
UMLPackage *p = c->umlPackage();
if (m_seenIncludes.indexOf(p) != -1) {
return c->name();
}
}
return cl->getTypeName();
}
/**
* Returns "Vala".
* @return programming language id
*/
Uml::ProgrammingLanguage::Enum ValaWriter::language() const
{
return Uml::ProgrammingLanguage::Vala;
}
/**
* Get list of reserved keywords.
* @return list of reserved keywords
*/
QStringList ValaWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 28,258
|
C++
|
.cpp
| 762
| 29.299213
| 193
| 0.577461
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,524
|
phpwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/php/phpwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Heiko Nardmann <h.nardmann@secunet.de>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "phpwriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"abs",
"acos",
"acosh",
"add",
"addAction",
"addColor",
"addcslashes",
"addEntry",
"addFill",
"add_namespace",
"addShape",
"addslashes",
"addstring",
"addString",
"aggregate",
"aggregate_info",
"aggregate_methods",
"aggregate_methods_by_list",
"aggregate_methods_by_regexp",
"aggregate_properties",
"aggregate_properties_by_list",
"aggregate_properties_by_regexp",
"aggregation_info",
"align",
"apache_child_terminate",
"apache_lookup_uri",
"apache_note",
"apache_request_headers",
"apache_response_headers",
"apache_setenv",
"append_child",
"append_sibling",
"array",
"array_change_key_case",
"array_chunk",
"array_count_values",
"array_diff",
"array_diff_assoc",
"array_fill",
"array_filter",
"array_flip",
"array_intersect",
"array_intersect_assoc",
"array_key_exists",
"array_keys",
"array_map",
"array_merge",
"array_merge_recursive",
"array_multisort",
"array_pad",
"array_pop",
"array_push",
"array_rand",
"array_reduce",
"array_reverse",
"array_search",
"array_shift",
"array_slice",
"array_splice",
"array_sum",
"array_unique",
"array_unshift",
"array_values",
"array_walk",
"arsort",
"ascii2ebcdic",
"asin",
"asinh",
"asort",
"aspell_check",
"aspell_new",
"aspell_suggest",
"assert",
"assert_options",
"assign",
"atan",
"atan2",
"atanh",
"attreditable",
"attributes",
"base64_decode",
"base64_encode",
"base_convert",
"basename",
"bcadd",
"bccomp",
"bcdiv",
"bcmod",
"bcmul",
"bcpow",
"bcpowmod",
"bcscale",
"bcsqrt",
"bcsub",
"bin2hex",
"bindec",
"bindtextdomain",
"bind_textdomain_codeset",
"bool",
"break",
"bzclose",
"bzcompress",
"bzdecompress",
"bzerrno",
"bzerror",
"bzerrstr",
"bzflush",
"bzopen",
"bzread",
"bzwrite",
"cal_days_in_month",
"cal_from_jd",
"cal_info",
"call_user_func",
"call_user_func_array",
"call_user_method",
"call_user_method_array",
"cal_to_jd",
"ccvs_add",
"ccvs_auth",
"ccvs_command",
"ccvs_count",
"ccvs_delete",
"ccvs_done",
"ccvs_init",
"ccvs_lookup",
"ccvs_new",
"ccvs_report",
"ccvs_return",
"ccvs_reverse",
"ccvs_sale",
"ccvs_status",
"ccvs_textvalue",
"ccvs_void",
"ceil",
"chdir",
"checkdate",
"checkdnsrr",
"checkin",
"checkout",
"chgrp",
"child_nodes",
"children",
"chmod",
"chop",
"chown",
"chr",
"chroot",
"chunk_split",
"class",
"class_exists",
"clearstatcache",
"clone_node",
"closedir",
"closelog",
"com_addref",
"com_get",
"com_invoke",
"com_isenum",
"com_load",
"com_load_typelib",
"compact",
"com_propget",
"com_propput",
"com_propset",
"com_release",
"com_set",
"connection_aborted",
"connection_status",
"connection_timeout",
"constant",
"content",
"continue",
"convert_cyr_string",
"_COOKIE",
"copy",
"cos",
"cosh",
"count",
"count_chars",
"cpdf_add_annotation",
"cpdf_add_outline",
"cpdf_arc",
"cpdf_begin_text",
"cpdf_circle",
"cpdf_clip",
"cpdf_close",
"cpdf_closepath",
"cpdf_closepath_fill_stroke",
"cpdf_closepath_stroke",
"cpdf_continue_text",
"cpdf_curveto",
"cpdf_end_text",
"cpdf_fill",
"cpdf_fill_stroke",
"cpdf_finalize",
"cpdf_finalize_page",
"cpdf_global_set_document_limits",
"cpdf_import_jpeg",
"cpdf_lineto",
"cpdf_moveto",
"cpdf_newpath",
"cpdf_open",
"cpdf_output_buffer",
"cpdf_page_init",
"cpdf_place_inline_image",
"cpdf_rect",
"cpdf_restore",
"cpdf_rlineto",
"cpdf_rmoveto",
"cpdf_rotate",
"cpdf_rotate_text",
"cpdf_save",
"cpdf_save_to_file",
"cpdf_scale",
"cpdf_set_action_url",
"cpdf_set_char_spacing",
"cpdf_set_creator",
"cpdf_set_current_page",
"cpdf_setdash",
"cpdf_setflat",
"cpdf_set_font",
"cpdf_set_font_directories",
"cpdf_set_font_map_file",
"cpdf_setgray",
"cpdf_setgray_fill",
"cpdf_setgray_stroke",
"cpdf_set_horiz_scaling",
"cpdf_set_keywords",
"cpdf_set_leading",
"cpdf_setlinecap",
"cpdf_setlinejoin",
"cpdf_setlinewidth",
"cpdf_setmiterlimit",
"cpdf_set_page_animation",
"cpdf_setrgbcolor",
"cpdf_setrgbcolor_fill",
"cpdf_setrgbcolor_stroke",
"cpdf_set_subject",
"cpdf_set_text_matrix",
"cpdf_set_text_pos",
"cpdf_set_text_rendering",
"cpdf_set_text_rise",
"cpdf_set_title",
"cpdf_set_viewer_preferences",
"cpdf_set_word_spacing",
"cpdf_show",
"cpdf_show_xy",
"cpdf_stringwidth",
"cpdf_stroke",
"cpdf_text",
"cpdf_translate",
"crack_check",
"crack_closedict",
"crack_getlastmessage",
"crack_opendict",
"crc32",
"create_attribute",
"create_cdata_section",
"create_comment",
"create_element",
"create_element_ns",
"create_entity_reference",
"create_function",
"create_processing_instruction",
"create_text_node",
"crypt",
"ctype_alnum",
"ctype_alpha",
"ctype_cntrl",
"ctype_digit",
"ctype_graph",
"ctype_lower",
"ctype_print",
"ctype_punct",
"ctype_space",
"ctype_upper",
"ctype_xdigit",
"curl_close",
"curl_errno",
"curl_error",
"curl_exec",
"curl_getinfo",
"curl_init",
"curl_setopt",
"curl_version",
"current",
"cybercash_base64_decode",
"cybercash_base64_encode",
"cybercash_decr",
"cybercash_encr",
"cybermut_creerformulairecm",
"cybermut_creerreponsecm",
"cybermut_testmac",
"cyrus_authenticate",
"cyrus_bind",
"cyrus_close",
"cyrus_connect",
"cyrus_query",
"cyrus_unbind",
"data",
"date",
"dba_close",
"dba_delete",
"dba_exists",
"dba_fetch",
"dba_firstkey",
"dba_handlers",
"dba_insert",
"dba_list",
"dba_nextkey",
"dba_open",
"dba_optimize",
"dba_popen",
"dba_replace",
"dbase_add_record",
"dbase_close",
"dbase_create",
"dbase_delete_record",
"dbase_get_record",
"dbase_get_record_with_names",
"dbase_numfields",
"dbase_numrecords",
"dbase_open",
"dbase_pack",
"dbase_replace_record",
"dba_sync",
"dblist",
"dbmclose",
"dbmdelete",
"dbmexists",
"dbmfetch",
"dbmfirstkey",
"dbminsert",
"dbmnextkey",
"dbmopen",
"dbmreplace",
"dbplus_add",
"dbplus_aql",
"dbplus_chdir",
"dbplus_close",
"dbplus_curr",
"dbplus_errcode",
"dbplus_errno",
"dbplus_find",
"dbplus_first",
"dbplus_flush",
"dbplus_freealllocks",
"dbplus_freelock",
"dbplus_freerlocks",
"dbplus_getlock",
"dbplus_getunique",
"dbplus_info",
"dbplus_last",
"dbplus_lockrel",
"dbplus_next",
"dbplus_open",
"dbplus_prev",
"dbplus_rchperm",
"dbplus_rcreate",
"dbplus_rcrtexact",
"dbplus_rcrtlike",
"dbplus_resolve",
"dbplus_restorepos",
"dbplus_rkeys",
"dbplus_ropen",
"dbplus_rquery",
"dbplus_rrename",
"dbplus_rsecindex",
"dbplus_runlink",
"dbplus_rzap",
"dbplus_savepos",
"dbplus_setindex",
"dbplus_setindexbynumber",
"dbplus_sql",
"dbplus_tcl",
"dbplus_tremove",
"dbplus_undo",
"dbplus_undoprepare",
"dbplus_unlockrel",
"dbplus_unselect",
"dbplus_update",
"dbplus_xlockrel",
"dbplus_xunlockrel",
"dbstat",
"dbx_close",
"dbx_compare",
"dbx_connect",
"dbx_error",
"dbx_escape_string",
"dbx_query",
"dbx_sort",
"dcgettext",
"dcngettext",
"dcstat",
"deaggregate",
"debug_backtrace",
"debugger_off",
"debugger_on",
"decbin",
"dechex",
"declare",
"decoct",
"DEFAULT_INCLUDE_PATH",
"define",
"defined",
"define_syslog_variables",
"deg2rad",
"delete",
"description",
"dgettext",
"die",
"dio_close",
"dio_fcntl",
"dio_open",
"dio_read",
"dio_seek",
"dio_stat",
"dio_tcsetattr",
"dio_truncate",
"dio_write",
"dir",
"dirname",
"disk_free_space",
"diskfreespace",
"disk_total_space",
"dl",
"dngettext",
"dns_check_record",
"dns_get_mx",
"dns_get_record",
"do",
"doctype",
"document_element",
"DOCUMENT_ROOT",
"domxml_new_doc",
"domxml_open_file",
"domxml_open_mem",
"domxml_version",
"domxml_xmltree",
"domxml_xslt_stylesheet",
"domxml_xslt_stylesheet_doc",
"domxml_xslt_stylesheet_file",
"dotnet_load",
"doubleval",
"drawCurve",
"drawCurveTo",
"drawLine",
"drawLineTo",
"dstanchors",
"dstofsrcanchors",
"dump_file",
"dump_mem",
"dump_node",
"each",
"E_ALL",
"easter_date",
"easter_days",
"ebcdic2ascii",
"echo",
"E_COMPILE_ERROR",
"E_COMPILE_WARNING",
"E_CORE_ERROR",
"E_CORE_WARNING",
"E_ERROR",
"else",
"elseif",
"empty",
"end",
"endfor",
"endforeach",
"endif",
"endswitch",
"endwhile",
"E_NOTICE",
"entities",
"_ENV",
"E_PARSE",
"ereg",
"eregi",
"eregi_replace",
"ereg_replace",
"error_log",
"error_reporting",
"escapeshellarg",
"escapeshellcmd",
"E_USER_ERROR",
"E_USER_NOTICE",
"E_USER_WARNING",
"eval",
"E_WARNING",
"exec",
"exif_imagetype",
"exif_read_data",
"exif_thumbnail",
"exit",
"exp",
"explode",
"expm1",
"extension_loaded",
"extract",
"ezmlm_hash",
"FALSE",
"fbsql_affected_rows",
"fbsql_autocommit",
"fbsql_change_user",
"fbsql_close",
"fbsql_commit",
"fbsql_connect",
"fbsql_create_blob",
"fbsql_create_clob",
"fbsql_create_db",
"fbsql_database",
"fbsql_database_password",
"fbsql_data_seek",
"fbsql_db_query",
"fbsql_db_status",
"fbsql_drop_db",
"fbsql_errno",
"fbsql_error",
"fbsql_fetch_array",
"fbsql_fetch_assoc",
"fbsql_fetch_field",
"fbsql_fetch_lengths",
"fbsql_fetch_object",
"fbsql_fetch_row",
"fbsql_field_flags",
"fbsql_field_len",
"fbsql_field_name",
"fbsql_field_seek",
"fbsql_field_table",
"fbsql_field_type",
"fbsql_free_result",
"fbsql_get_autostart_info",
"fbsql_hostname",
"fbsql_insert_id",
"fbsql_list_dbs",
"fbsql_list_fields",
"fbsql_list_tables",
"fbsql_next_result",
"fbsql_num_fields",
"fbsql_num_rows",
"fbsql_password",
"fbsql_pconnect",
"fbsql_query",
"fbsql_read_blob",
"fbsql_read_clob",
"fbsql_result",
"fbsql_rollback",
"fbsql_select_db",
"fbsql_set_lob_mode",
"fbsql_set_transaction",
"fbsql_start_db",
"fbsql_stop_db",
"fbsql_tablename",
"fbsql_username",
"fbsql_warnings",
"fclose",
"fdf_add_doc_javascript",
"fdf_add_template",
"fdf_close",
"fdf_create",
"fdf_errno",
"fdf_error",
"fdf_get_ap",
"fdf_get_attachment",
"fdf_get_encoding",
"fdf_get_file",
"fdf_get_status",
"fdf_get_value",
"fdf_get_version",
"fdf_header",
"fdf_next_field_name",
"fdf_open",
"fdf_open_string",
"fdf_save",
"fdf_save_string",
"fdf_set_ap",
"fdf_set_encoding",
"fdf_set_file",
"fdf_set_flags",
"fdf_set_javascript_action",
"fdf_set_opt",
"fdf_set_status",
"fdf_set_submit_form_action",
"fdf_set_target_frame",
"fdf_set_value",
"fdf_set_version",
"feof",
"fflush",
"fgetc",
"fgetcsv",
"fgets",
"fgetss",
"file",
"__FILE__",
"fileatime",
"filectime",
"file_exists",
"file_get_contents",
"filegroup",
"fileinode",
"filemtime",
"fileowner",
"fileperms",
"filepro",
"filepro_fieldcount",
"filepro_fieldname",
"filepro_fieldtype",
"filepro_fieldwidth",
"filepro_retrieve",
"filepro_rowcount",
"_FILES",
"filesize",
"filetype",
"find",
"first_child",
"floatval",
"flock",
"floor",
"flush",
"fmod",
"fnmatch",
"fopen",
"for",
"foreach",
"fpassthru",
"fprintf",
"fputs",
"fread",
"frenchtojd",
"fribidi_log2vis",
"fscanf",
"fseek",
"fsockopen",
"fstat",
"ftell",
"ftok",
"ftp_cdup",
"ftp_chdir",
"ftp_close",
"ftp_connect",
"ftp_delete",
"ftp_exec",
"ftp_fget",
"ftp_fput",
"ftp_get",
"ftp_get_option",
"ftp_login",
"ftp_mdtm",
"ftp_mkdir",
"ftp_nb_continue",
"ftp_nb_fget",
"ftp_nb_fput",
"ftp_nb_get",
"ftp_nb_put",
"ftp_nlist",
"ftp_pasv",
"ftp_put",
"ftp_pwd",
"ftp_quit",
"ftp_rawlist",
"ftp_rename",
"ftp_rmdir",
"ftp_set_option",
"ftp_site",
"ftp_size",
"ftp_ssl_connect",
"ftp_systype",
"ftruncate",
"ftstat",
"func_get_arg",
"func_get_args",
"func_num_args",
"function",
"function_exists",
"fwrite",
"GATEWAY_INTERFACE",
"gd_info",
"_GET",
"getallheaders",
"get_attribute",
"get_attribute_node",
"get_browser",
"get_cfg_var",
"get_class",
"get_class_methods",
"get_class_vars",
"get_content",
"get_current_user",
"getcwd",
"getdate",
"get_declared_classes",
"get_defined_constants",
"get_defined_functions",
"get_defined_vars",
"get_element_by_id",
"get_elements_by_tagname",
"getenv",
"get_extension_funcs",
"getHeight",
"gethostbyaddr",
"gethostbyname",
"gethostbynamel",
"get_html_translation_table",
"getimagesize",
"get_included_files",
"get_include_path",
"getlastmod",
"get_loaded_extensions",
"get_magic_quotes_gpc",
"get_magic_quotes_runtime",
"get_meta_tags",
"getmxrr",
"getmygid",
"getmyinode",
"getmypid",
"getmyuid",
"get_object_vars",
"getopt",
"get_parent_class",
"getprotobyname",
"getprotobynumber",
"getrandmax",
"get_required_files",
"get_resource_type",
"getrusage",
"getservbyname",
"getservbyport",
"getshape1",
"getshape2",
"gettext",
"gettimeofday",
"gettype",
"getwidth",
"getWidth",
"glob",
"global",
"GLOBALS",
"gmdate",
"gmmktime",
"gmp_abs",
"gmp_add",
"gmp_and",
"gmp_clrbit",
"gmp_cmp",
"gmp_com",
"gmp_div",
"gmp_divexact",
"gmp_div_q",
"gmp_div_qr",
"gmp_div_r",
"gmp_fact",
"gmp_gcd",
"gmp_gcdext",
"gmp_hamdist",
"gmp_init",
"gmp_intval",
"gmp_invert",
"gmp_jacobi",
"gmp_legendre",
"gmp_mod",
"gmp_mul",
"gmp_neg",
"gmp_or",
"gmp_perfect_square",
"gmp_popcount",
"gmp_pow",
"gmp_powm",
"gmp_prob_prime",
"gmp_random",
"gmp_scan0",
"gmp_scan1",
"gmp_setbit",
"gmp_sign",
"gmp_sqrt",
"gmp_sqrtrm",
"gmp_strval",
"gmp_sub",
"gmp_xor",
"gmstrftime",
"gregoriantojd",
"gzclose",
"gzcompress",
"gzdeflate",
"gzencode",
"gzeof",
"gzfile",
"gzgetc",
"gzgets",
"gzgetss",
"gzinflate",
"gzopen",
"gzpassthru",
"gzputs",
"gzread",
"gzrewind",
"gzseek",
"gztell",
"gzuncompress",
"gzwrite",
"has_attribute",
"has_attributess",
"has_child_nodes",
"header",
"headers_sent",
"hebrev",
"hebrevc",
"hexdec",
"highlight_file",
"highlight_string",
"html_dump_mem",
"htmlentities",
"html_entity_decode",
"htmlspecialchars",
"HTTP_ACCEPT",
"HTTP_ACCEPT_CHARSET",
"HTTP_ACCEPT_LANGUAGE",
"HTTP_CONNECTION",
"HTTP_COOKIE_VARS",
"HTTP_ENCODING",
"HTTP_ENV_VARS",
"HTTP_GET_VARS",
"HTTP_HOST",
"HTTP_POST_FILES",
"HTTP_POST_VARS",
"HTTP_RAW_POST_DATA",
"HTTP_REFERER",
"HTTP_SERVER_VARS",
"HTTP_SESSION_VARS",
"HTTP_STATE_VARS",
"HTTP_USER_AGENT",
"hw_api_attribute",
"hw_api_content",
"hwapi_hgcsp",
"hw_api_object",
"hw_Array2Objrec",
"hw_changeobject",
"hw_Children",
"hw_ChildrenObj",
"hw_Close",
"hw_Connect",
"hw_connection_info",
"hw_Cp",
"hw_Deleteobject",
"hw_DocByAnchor",
"hw_DocByAnchorObj",
"hw_Document_Attributes",
"hw_Document_BodyTag",
"hw_Document_Content",
"hw_Document_SetContent",
"hw_Document_Size",
"hw_dummy",
"hw_EditText",
"hw_Error",
"hw_ErrorMsg",
"hw_Free_Document",
"hw_GetAnchors",
"hw_GetAnchorsObj",
"hw_GetAndLock",
"hw_GetChildColl",
"hw_GetChildCollObj",
"hw_GetChildDocColl",
"hw_GetChildDocCollObj",
"hw_GetObject",
"hw_GetObjectByQuery",
"hw_GetObjectByQueryColl",
"hw_GetObjectByQueryCollObj",
"hw_GetObjectByQueryObj",
"hw_GetParents",
"hw_GetParentsObj",
"hw_getrellink",
"hw_GetRemote",
"hw_GetRemoteChildren",
"hw_GetSrcByDestObj",
"hw_GetText",
"hw_getusername",
"hw_Identify",
"hw_InCollections",
"hw_Info",
"hw_InsColl",
"hw_InsDoc",
"hw_insertanchors",
"hw_InsertDocument",
"hw_InsertObject",
"hw_mapid",
"hw_Modifyobject",
"hw_Mv",
"hw_New_Document",
"hw_Objrec2Array",
"hw_Output_Document",
"hw_pConnect",
"hw_PipeDocument",
"hw_Root",
"hw_setlinkroot",
"hw_stat",
"hwstat",
"hw_Unlock",
"hw_Who",
"hypot",
"ibase_blob_add",
"ibase_blob_cancel",
"ibase_blob_close",
"ibase_blob_create",
"ibase_blob_echo",
"ibase_blob_get",
"ibase_blob_import",
"ibase_blob_info",
"ibase_blob_open",
"ibase_close",
"ibase_commit",
"ibase_connect",
"ibase_errmsg",
"ibase_execute",
"ibase_fetch_object",
"ibase_fetch_row",
"ibase_field_info",
"ibase_free_query",
"ibase_free_result",
"ibase_num_fields",
"ibase_pconnect",
"ibase_prepare",
"ibase_query",
"ibase_rollback",
"ibase_timefmt",
"ibase_trans",
"iconv",
"iconv_get_encoding",
"iconv_set_encoding",
"identify",
"if",
"ifx_affected_rows",
"ifx_blobinfile_mode",
"ifx_byteasvarchar",
"ifx_close",
"ifx_connect",
"ifx_copy_blob",
"ifx_create_blob",
"ifx_create_char",
"ifx_do",
"ifx_error",
"ifx_errormsg",
"ifx_fetch_row",
"ifx_fieldproperties",
"ifx_fieldtypes",
"ifx_free_blob",
"ifx_free_char",
"ifx_free_result",
"ifx_get_blob",
"ifx_get_char",
"ifx_getsqlca",
"ifx_htmltbl_result",
"ifx_nullformat",
"ifx_num_fields",
"ifx_num_rows",
"ifx_pconnect",
"ifx_prepare",
"ifx_query",
"ifx_textasvarchar",
"ifx_update_blob",
"ifx_update_char",
"ifxus_close_slob",
"ifxus_create_slob",
"ifxus_free_slob",
"ifxus_open_slob",
"ifxus_read_slob",
"ifxus_seek_slob",
"ifxus_tell_slob",
"ifxus_write_slob",
"ignore_user_abort",
"image2wbmp",
"imagealphablending",
"imagearc",
"imagechar",
"imagecharup",
"imagecolorallocate",
"imagecolorallocatealpha",
"imagecolorat",
"imagecolorclosest",
"imagecolorclosestalpha",
"imagecolorclosesthwb",
"imagecolordeallocate",
"imagecolorexact",
"imagecolorexactalpha",
"imagecolorresolve",
"imagecolorresolvealpha",
"imagecolorset",
"imagecolorsforindex",
"imagecolorstotal",
"imagecolortransparent",
"imagecopy",
"imagecopymerge",
"imagecopymergegray",
"imagecopyresampled",
"imagecopyresized",
"imagecreate",
"imagecreatefromgd",
"imagecreatefromgd2",
"imagecreatefromgd2part",
"imagecreatefromgif",
"imagecreatefromjpeg",
"imagecreatefrompng",
"imagecreatefromstring",
"imagecreatefromwbmp",
"imagecreatefromxbm",
"imagecreatefromxpm",
"imagecreatetruecolor",
"imagedashedline",
"imagedestroy",
"imageellipse",
"imagefill",
"imagefilledarc",
"imagefilledellipse",
"imagefilledpolygon",
"imagefilledrectangle",
"imagefilltoborder",
"imagefontheight",
"imagefontwidth",
"imageftbbox",
"imagefttext",
"imagegammacorrect",
"imagegd",
"imagegd2",
"imagegif",
"imageinterlace",
"imagejpeg",
"imageline",
"imageloadfont",
"imagepalettecopy",
"imagepng",
"imagepolygon",
"imagepsbbox",
"imagepscopyfont",
"imagepsencodefont",
"imagepsextendfont",
"imagepsfreefont",
"imagepsloadfont",
"imagepsslantfont",
"imagepstext",
"imagerectangle",
"imagerotate",
"imagesetbrush",
"imagesetpixel",
"imagesetstyle",
"imagesetthickness",
"imagesettile",
"imagestring",
"imagestringup",
"imagesx",
"imagesy",
"imagetruecolortopalette",
"imagettfbbox",
"imagettftext",
"imagetypes",
"image_type_to_mime_type",
"imagewbmp",
"imap_8bit",
"imap_alerts",
"imap_append",
"imap_base64",
"imap_binary",
"imap_body",
"imap_bodystruct",
"imap_check",
"imap_clearflag_full",
"imap_close",
"imap_createmailbox",
"imap_delete",
"imap_deletemailbox",
"imap_errors",
"imap_expunge",
"imap_fetchbody",
"imap_fetchheader",
"imap_fetch_overview",
"imap_fetchstructure",
"imap_getmailboxes",
"imap_get_quota",
"imap_get_quotaroot",
"imap_getsubscribed",
"imap_header",
"imap_headerinfo",
"imap_headers",
"imap_last_error",
"imap_list",
"imap_listmailbox",
"imap_listscan",
"imap_listsubscribed",
"imap_lsub",
"imap_mail",
"imap_mailboxmsginfo",
"imap_mail_compose",
"imap_mail_copy",
"imap_mail_move",
"imap_mime_header_decode",
"imap_msgno",
"imap_num_msg",
"imap_num_recent",
"imap_open",
"imap_ping",
"imap_qprint",
"imap_renamemailbox",
"imap_reopen",
"imap_rfc822_parse_adrlist",
"imap_rfc822_parse_headers",
"imap_rfc822_write_address",
"imap_scanmailbox",
"imap_search",
"imap_setacl",
"imap_setflag_full",
"imap_set_quota",
"imap_sort",
"imap_status",
"imap_subscribe",
"imap_thread",
"imap_uid",
"imap_undelete",
"imap_unsubscribe",
"imap_utf7_decode",
"imap_utf7_encode",
"imap_utf8",
"implode",
"import_request_variables",
"in_array",
"include",
"include_once",
"info",
"ingres_autocommit",
"ingres_close",
"ingres_commit",
"ingres_connect",
"ingres_fetch_array",
"ingres_fetch_object",
"ingres_fetch_row",
"ingres_field_length",
"ingres_field_name",
"ingres_field_nullable",
"ingres_field_precision",
"ingres_field_scale",
"ingres_field_type",
"ingres_num_fields",
"ingres_num_rows",
"ingres_pconnect",
"ingres_query",
"ingres_rollback",
"ini_alter",
"ini_get",
"ini_get_all",
"ini_restore",
"ini_set",
"insert",
"insertanchor",
"insert_before",
"insertcollection",
"insertdocument",
"int",
"internal_subset",
"intval",
"ip2long",
"iptcembed",
"iptcparse",
"ircg_channel_mode",
"ircg_disconnect",
"ircg_fetch_error_msg",
"ircg_get_username",
"ircg_html_encode",
"ircg_ignore_add",
"ircg_ignore_del",
"ircg_is_conn_alive",
"ircg_join",
"ircg_kick",
"ircg_lookup_format_messages",
"ircg_msg",
"ircg_nick",
"ircg_nickname_escape",
"ircg_nickname_unescape",
"ircg_notice",
"ircg_part",
"ircg_pconnect",
"ircg_register_format_messages",
"ircg_set_current",
"ircg_set_file",
"ircg_set_on_die",
"ircg_topic",
"ircg_whois",
"is_a",
"is_array",
"is_blank_node",
"is_bool",
"is_callable",
"is_dir",
"is_double",
"is_executable",
"is_file",
"is_finite",
"is_float",
"is_infinite",
"is_int",
"is_integer",
"is_link",
"is_long",
"is_nan",
"is_null",
"is_numeric",
"is_object",
"is_readable",
"is_real",
"is_resource",
"is_scalar",
"isset",
"is_string",
"is_subclass_of",
"is_uploaded_file",
"is_writable",
"is_writeable",
"java_last_exception_clear",
"java_last_exception_get",
"jddayofweek",
"jdmonthname",
"jdtofrench",
"jdtogregorian",
"jdtojewish",
"jdtojulian",
"jdtounix",
"jewishtojd",
"join",
"jpeg2wbmp",
"juliantojd",
"key",
"krsort",
"ksort",
"langdepvalue",
"last_child",
"lcg_value",
"ldap_8859_to_t61",
"ldap_add",
"ldap_bind",
"ldap_close",
"ldap_compare",
"ldap_connect",
"ldap_count_entries",
"ldap_delete",
"ldap_dn2ufn",
"ldap_err2str",
"ldap_errno",
"ldap_error",
"ldap_explode_dn",
"ldap_first_attribute",
"ldap_first_entry",
"ldap_first_reference",
"ldap_free_result",
"ldap_get_attributes",
"ldap_get_dn",
"ldap_get_entries",
"ldap_get_option",
"ldap_get_values",
"ldap_get_values_len",
"ldap_list",
"ldap_mod_add",
"ldap_mod_del",
"ldap_modify",
"ldap_mod_replace",
"ldap_next_attribute",
"ldap_next_entry",
"ldap_next_reference",
"ldap_parse_reference",
"ldap_parse_result",
"ldap_read",
"ldap_rename",
"ldap_search",
"ldap_set_option",
"ldap_set_rebind_proc",
"ldap_sort",
"ldap_start_tls",
"ldap_t61_to_8859",
"ldap_unbind",
"levenshtein",
"__LINE__",
"link",
"linkinfo",
"list",
"localeconv",
"localtime",
"lock",
"log",
"log10",
"log1p",
"long2ip",
"lstat",
"ltrim",
"mail",
"mailparse_determine_best_xfer_encoding",
"mailparse_msg_create",
"mailparse_msg_extract_part",
"mailparse_msg_extract_part_file",
"mailparse_msg_free",
"mailparse_msg_get_part",
"mailparse_msg_get_part_data",
"mailparse_msg_get_structure",
"mailparse_msg_parse",
"mailparse_msg_parse_file",
"mailparse_rfc822_parse_addresses",
"mailparse_stream_encode",
"mailparse_uudecode_all",
"main",
"max",
"mb_convert_case",
"mb_convert_encoding",
"mb_convert_kana",
"mb_convert_variables",
"mb_decode_mimeheader",
"mb_decode_numericentity",
"mb_detect_encoding",
"mb_detect_order",
"mb_encode_mimeheader",
"mb_encode_numericentity",
"mb_ereg",
"mb_eregi",
"mb_eregi_replace",
"mb_ereg_match",
"mb_ereg_replace",
"mb_ereg_search",
"mb_ereg_search_getpos",
"mb_ereg_search_getregs",
"mb_ereg_search_init",
"mb_ereg_search_pos",
"mb_ereg_search_regs",
"mb_ereg_search_setpos",
"mb_get_info",
"mb_http_input",
"mb_http_output",
"mb_internal_encoding",
"mb_language",
"mb_output_handler",
"mb_parse_str",
"mb_preferred_mime_name",
"mb_regex_encoding",
"mb_regex_set_options",
"mb_send_mail",
"mb_split",
"mb_strcut",
"mb_strimwidth",
"mb_strlen",
"mb_strpos",
"mb_strrpos",
"mb_strtolower",
"mb_strtoupper",
"mb_strwidth",
"mb_substitute_character",
"mb_substr",
"mb_substr_count",
"mcal_append_event",
"mcal_close",
"mcal_create_calendar",
"mcal_date_compare",
"mcal_date_valid",
"mcal_day_of_week",
"mcal_day_of_year",
"mcal_days_in_month",
"mcal_delete_calendar",
"mcal_delete_event",
"mcal_event_add_attribute",
"mcal_event_init",
"mcal_event_set_alarm",
"mcal_event_set_category",
"mcal_event_set_class",
"mcal_event_set_description",
"mcal_event_set_end",
"mcal_event_set_recur_daily",
"mcal_event_set_recur_monthly_mday",
"mcal_event_set_recur_monthly_wday",
"mcal_event_set_recur_none",
"mcal_event_set_recur_weekly",
"mcal_event_set_recur_yearly",
"mcal_event_set_start",
"mcal_event_set_title",
"mcal_expunge",
"mcal_fetch_current_stream_event",
"mcal_fetch_event",
"mcal_is_leap_year",
"mcal_list_alarms",
"mcal_list_events",
"mcal_next_recurrence",
"mcal_open",
"mcal_popen",
"mcal_rename_calendar",
"mcal_reopen",
"mcal_snooze",
"mcal_store_event",
"mcal_time_valid",
"mcal_week_of_year",
"mcrypt_cbc",
"mcrypt_cfb",
"mcrypt_create_iv",
"mcrypt_decrypt",
"mcrypt_ecb",
"mcrypt_enc_get_algorithms_name",
"mcrypt_enc_get_block_size",
"mcrypt_enc_get_iv_size",
"mcrypt_enc_get_key_size",
"mcrypt_enc_get_modes_name",
"mcrypt_enc_get_supported_key_sizes",
"mcrypt_enc_is_block_algorithm",
"mcrypt_enc_is_block_algorithm_mode",
"mcrypt_enc_is_block_mode",
"mcrypt_encrypt",
"mcrypt_enc_self_test",
"mcrypt_generic",
"mcrypt_generic_deinit",
"mcrypt_generic_end",
"mcrypt_generic_init",
"mcrypt_get_block_size",
"mcrypt_get_cipher_name",
"mcrypt_get_iv_size",
"mcrypt_get_key_size",
"mcrypt_list_algorithms",
"mcrypt_list_modes",
"mcrypt_module_close",
"mcrypt_module_get_algo_block_size",
"mcrypt_module_get_algo_key_size",
"mcrypt_module_get_supported_key_sizes",
"mcrypt_module_is_block_algorithm",
"mcrypt_module_is_block_algorithm_mode",
"mcrypt_module_is_block_mode",
"mcrypt_module_open",
"mcrypt_module_self_test",
"mcrypt_ofb",
"mcve_adduser",
"mcve_adduserarg",
"mcve_bt",
"mcve_checkstatus",
"mcve_chkpwd",
"mcve_chngpwd",
"mcve_completeauthorizations",
"mcve_connect",
"mcve_connectionerror",
"mcve_deleteresponse",
"mcve_deletetrans",
"mcve_deleteusersetup",
"mcve_deluser",
"mcve_destroyconn",
"mcve_destroyengine",
"mcve_disableuser",
"mcve_edituser",
"mcve_enableuser",
"mcve_force",
"mcve_getcell",
"mcve_getcellbynum",
"mcve_getcommadelimited",
"mcve_getheader",
"mcve_getuserarg",
"mcve_getuserparam",
"mcve_gft",
"mcve_gl",
"mcve_gut",
"mcve_initconn",
"mcve_initengine",
"mcve_initusersetup",
"mcve_iscommadelimited",
"mcve_liststats",
"mcve_listusers",
"mcve_maxconntimeout",
"mcve_monitor",
"mcve_numcolumns",
"mcve_numrows",
"mcve_override",
"mcve_parsecommadelimited",
"mcve_ping",
"mcve_preauth",
"mcve_preauthcompletion",
"mcve_qc",
"mcve_responseparam",
"mcve_return",
"mcve_returncode",
"mcve_returnstatus",
"mcve_sale",
"mcve_setblocking",
"mcve_setdropfile",
"mcve_setip",
"mcve_setssl",
"mcve_settimeout",
"mcve_settle",
"mcve_text_avs",
"mcve_text_code",
"mcve_text_cv",
"mcve_transactionauth",
"mcve_transactionavs",
"mcve_transactionbatch",
"mcve_transactioncv",
"mcve_transactionid",
"mcve_transactionitem",
"mcve_transactionssent",
"mcve_transactiontext",
"mcve_transinqueue",
"mcve_transnew",
"mcve_transparam",
"mcve_transsend",
"mcve_ub",
"mcve_uwait",
"mcve_verifyconnection",
"mcve_verifysslcert",
"mcve_void",
"md5",
"md5_file",
"mdecrypt_generic",
"memory_get_usage",
"metaphone",
"method_exists",
"mhash",
"mhash_count",
"mhash_get_block_size",
"mhash_get_hash_name",
"mhash_keygen_s2k",
"microtime",
"mime_content_type",
"mimetype",
"min",
"ming_setcubicthreshold",
"ming_setscale",
"ming_useswfversion",
"mkdir",
"mktime",
"money_format",
"move",
"movePen",
"movePenTo",
"moveTo",
"move_uploaded_file",
"msession_connect",
"msession_count",
"msession_create",
"msession_destroy",
"msession_disconnect",
"msession_find",
"msession_get",
"msession_get_array",
"msession_getdata",
"msession_inc",
"msession_list",
"msession_listvar",
"msession_lock",
"msession_plugin",
"msession_randstr",
"msession_set",
"msession_set_array",
"msession_setdata",
"msession_timeout",
"msession_uniq",
"msession_unlock",
"msg_get_queue",
"msg_receive",
"msg_remove_queue",
"msg_send",
"msg_set_queue",
"msg_stat_queue",
"msql",
"msql_affected_rows",
"msql_close",
"msql_connect",
"msql_create_db",
"msql_createdb",
"msql_data_seek",
"msql_dbname",
"msql_drop_db",
"msql_dropdb",
"msql_error",
"msql_fetch_array",
"msql_fetch_field",
"msql_fetch_object",
"msql_fetch_row",
"msql_fieldflags",
"msql_fieldlen",
"msql_fieldname",
"msql_field_seek",
"msql_fieldtable",
"msql_fieldtype",
"msql_free_result",
"msql_freeresult",
"msql_list_dbs",
"msql_listdbs",
"msql_list_fields",
"msql_listfields",
"msql_list_tables",
"msql_listtables",
"msql_num_fields",
"msql_numfields",
"msql_num_rows",
"msql_numrows",
"msql_pconnect",
"msql_query",
"msql_regcase",
"msql_result",
"msql_select_db",
"msql_selectdb",
"msql_tablename",
"mssql_bind",
"mssql_close",
"mssql_connect",
"mssql_data_seek",
"mssql_execute",
"mssql_fetch_array",
"mssql_fetch_assoc",
"mssql_fetch_batch",
"mssql_fetch_field",
"mssql_fetch_object",
"mssql_fetch_row",
"mssql_field_length",
"mssql_field_name",
"mssql_field_seek",
"mssql_field_type",
"mssql_free_result",
"mssql_free_statement",
"mssql_get_last_message",
"mssql_guid_string",
"mssql_init",
"mssql_min_error_severity",
"mssql_min_message_severity",
"mssql_next_result",
"mssql_num_fields",
"mssql_num_rows",
"mssql_pconnect",
"mssql_query",
"mssql_result",
"mssql_rows_affected",
"mssql_select_db",
"mt_getrandmax",
"mt_rand",
"mt_srand",
"multColor",
"muscat_close",
"muscat_get",
"muscat_give",
"muscat_setup",
"muscat_setup_net",
"mysql_affected_rows",
"mysql_change_user",
"mysql_client_encoding",
"mysql_close",
"mysql_connect",
"mysql_create_db",
"mysql_data_seek",
"mysql_db_name",
"mysql_db_query",
"mysql_drop_db",
"mysql_errno",
"mysql_error",
"mysql_escape_string",
"mysql_fetch_array",
"mysql_fetch_assoc",
"mysql_fetch_field",
"mysql_fetch_lengths",
"mysql_fetch_object",
"mysql_fetch_row",
"mysql_field_flags",
"mysql_field_len",
"mysql_field_name",
"mysql_field_seek",
"mysql_field_table",
"mysql_field_type",
"mysql_free_result",
"mysql_get_client_info",
"mysql_get_host_info",
"mysql_get_proto_info",
"mysql_get_server_info",
"mysql_info",
"mysql_insert_id",
"mysql_list_dbs",
"mysql_list_fields",
"mysql_list_processes",
"mysql_list_tables",
"mysql_num_fields",
"mysql_num_rows",
"mysql_pconnect",
"mysql_ping",
"mysql_query",
"mysql_real_escape_string",
"mysql_result",
"mysql_select_db",
"mysql_stat",
"mysql_tablename",
"mysql_thread_id",
"mysql_unbuffered_query",
"name",
"natcasesort",
"natsort",
"ncurses_addch",
"ncurses_addchnstr",
"ncurses_addchstr",
"ncurses_addnstr",
"ncurses_addstr",
"ncurses_assume_default_colors",
"ncurses_attroff",
"ncurses_attron",
"ncurses_attrset",
"ncurses_baudrate",
"ncurses_beep",
"ncurses_bkgd",
"ncurses_bkgdset",
"ncurses_border",
"ncurses_can_change_color",
"ncurses_cbreak",
"ncurses_clear",
"ncurses_clrtobot",
"ncurses_clrtoeol",
"ncurses_color_set",
"ncurses_curs_set",
"ncurses_define_key",
"ncurses_def_prog_mode",
"ncurses_def_shell_mode",
"ncurses_delay_output",
"ncurses_delch",
"ncurses_deleteln",
"ncurses_delwin",
"ncurses_doupdate",
"ncurses_echo",
"ncurses_echochar",
"ncurses_end",
"ncurses_erase",
"ncurses_erasechar",
"ncurses_filter",
"ncurses_flash",
"ncurses_flushinp",
"ncurses_getch",
"ncurses_getmouse",
"ncurses_halfdelay",
"ncurses_has_colors",
"ncurses_has_ic",
"ncurses_has_il",
"ncurses_has_key",
"ncurses_hline",
"ncurses_inch",
"ncurses_init",
"ncurses_init_color",
"ncurses_init_pair",
"ncurses_insch",
"ncurses_insdelln",
"ncurses_insertln",
"ncurses_insstr",
"ncurses_instr",
"ncurses_isendwin",
"ncurses_keyok",
"ncurses_killchar",
"ncurses_longname",
"ncurses_mouseinterval",
"ncurses_mousemask",
"ncurses_move",
"ncurses_mvaddch",
"ncurses_mvaddchnstr",
"ncurses_mvaddchstr",
"ncurses_mvaddnstr",
"ncurses_mvaddstr",
"ncurses_mvcur",
"ncurses_mvdelch",
"ncurses_mvgetch",
"ncurses_mvhline",
"ncurses_mvinch",
"ncurses_mvvline",
"ncurses_mvwaddstr",
"ncurses_napms",
"ncurses_newwin",
"ncurses_nl",
"ncurses_nocbreak",
"ncurses_noecho",
"ncurses_nonl",
"ncurses_noqiflush",
"ncurses_noraw",
"ncurses_putp",
"ncurses_qiflush",
"ncurses_raw",
"ncurses_refresh",
"ncurses_resetty",
"ncurses_savetty",
"ncurses_scr_dump",
"ncurses_scr_init",
"ncurses_scrl",
"ncurses_scr_restore",
"ncurses_scr_set",
"ncurses_slk_attr",
"ncurses_slk_attroff",
"ncurses_slk_attron",
"ncurses_slk_attrset",
"ncurses_slk_clear",
"ncurses_slk_color",
"ncurses_slk_init",
"ncurses_slk_noutrefresh",
"ncurses_slk_refresh",
"ncurses_slk_restore",
"ncurses_slk_touch",
"ncurses_standend",
"ncurses_standout",
"ncurses_start_color",
"ncurses_termattrs",
"ncurses_termname",
"ncurses_timeout",
"ncurses_typeahead",
"ncurses_ungetch",
"ncurses_ungetmouse",
"ncurses_use_default_colors",
"ncurses_use_env",
"ncurses_use_extended_names",
"ncurses_vidattr",
"ncurses_vline",
"ncurses_wrefresh",
"new",
"next",
"nextframe",
"next_sibling",
"ngettext",
"nl2br",
"nl_langinfo",
"node_name",
"node_type",
"node_value",
"notations",
"notes_body",
"notes_copy_db",
"notes_create_db",
"notes_create_note",
"notes_drop_db",
"notes_find_note",
"notes_header_info",
"notes_list_msgs",
"notes_mark_read",
"notes_mark_unread",
"notes_nav_create",
"notes_search",
"notes_unread",
"notes_version",
"NULL",
"number_format",
"ob_clean",
"ob_end_clean",
"ob_end_flush",
"ob_flush",
"ob_get_contents",
"ob_get_length",
"ob_get_level",
"ob_get_status",
"ob_gzhandler",
"ob_iconv_handler",
"ob_implicit_flush",
"object",
"objectbyanchor",
"ob_start",
"ocibindbyname",
"ocicancel",
"OCICollAppend",
"ocicollassign",
"ocicollassignelem",
"ocicollgetelem",
"ocicollmax",
"ocicollsize",
"ocicolltrim",
"ocicolumnisnull",
"ocicolumnname",
"ocicolumnprecision",
"ocicolumnscale",
"ocicolumnsize",
"ocicolumntype",
"ocicolumntyperaw",
"ocicommit",
"ocidefinebyname",
"ocierror",
"ociexecute",
"ocifetch",
"ocifetchinto",
"ocifetchstatement",
"ocifreecollection",
"ocifreecursor",
"OCIFreeDesc",
"ocifreestatement",
"ociinternaldebug",
"ociloadlob",
"ocilogoff",
"ocilogon",
"ocinewcollection",
"ocinewcursor",
"ocinewdescriptor",
"ocinlogon",
"ocinumcols",
"ociparse",
"ociplogon",
"ociresult",
"ocirollback",
"ocirowcount",
"ocisavelob",
"ocisavelobfile",
"ociserverversion",
"ocisetprefetch",
"ocistatementtype",
"ociwritelobtofile",
"octdec",
"odbc_autocommit",
"odbc_binmode",
"odbc_close",
"odbc_close_all",
"odbc_columnprivileges",
"odbc_columns",
"odbc_commit",
"odbc_connect",
"odbc_cursor",
"odbc_data_source",
"odbc_do",
"odbc_error",
"odbc_errormsg",
"odbc_exec",
"odbc_execute",
"odbc_fetch_array",
"odbc_fetch_into",
"odbc_fetch_object",
"odbc_fetch_row",
"odbc_field_len",
"odbc_field_name",
"odbc_field_num",
"odbc_field_precision",
"odbc_field_scale",
"odbc_field_type",
"odbc_foreignkeys",
"odbc_free_result",
"odbc_gettypeinfo",
"odbc_longreadlen",
"odbc_next_result",
"odbc_num_fields",
"odbc_num_rows",
"odbc_pconnect",
"odbc_prepare",
"odbc_primarykeys",
"odbc_procedurecolumns",
"odbc_procedures",
"odbc_result",
"odbc_result_all",
"odbc_rollback",
"odbc_setoption",
"odbc_specialcolumns",
"odbc_statistics",
"odbc_tableprivileges",
"odbc_tables",
"opendir",
"openlog",
"openssl_csr_export",
"openssl_csr_export_to_file",
"openssl_csr_new",
"openssl_csr_sign",
"openssl_error_string",
"openssl_free_key",
"openssl_get_privatekey",
"openssl_get_publickey",
"openssl_open",
"openssl_pkcs7_decrypt",
"openssl_pkcs7_encrypt",
"openssl_pkcs7_sign",
"openssl_pkcs7_verify",
"openssl_pkey_export",
"openssl_pkey_export_to_file",
"openssl_pkey_get_private",
"openssl_pkey_get_public",
"openssl_pkey_new",
"openssl_private_decrypt",
"openssl_private_encrypt",
"openssl_public_decrypt",
"openssl_public_encrypt",
"openssl_seal",
"openssl_sign",
"openssl_verify",
"openssl_x509_check_private_key",
"openssl_x509_checkpurpose",
"openssl_x509_export",
"openssl_x509_export_to_file",
"openssl_x509_free",
"openssl_x509_parse",
"openssl_x509_read",
"ora_bind",
"ora_close",
"ora_columnname",
"ora_columnsize",
"ora_columntype",
"ora_commit",
"ora_commitoff",
"ora_commiton",
"ora_do",
"ora_error",
"ora_errorcode",
"ora_exec",
"ora_fetch",
"ora_fetch_into",
"ora_getcolumn",
"ora_logoff",
"ora_logon",
"ora_numcols",
"ora_numrows",
"ora_open",
"ora_parse",
"ora_plogon",
"ora_rollback",
"ord",
"output",
"overload",
"ovrimos_close",
"ovrimos_commit",
"ovrimos_connect",
"ovrimos_cursor",
"ovrimos_exec",
"ovrimos_execute",
"ovrimos_fetch_into",
"ovrimos_fetch_row",
"ovrimos_field_len",
"ovrimos_field_name",
"ovrimos_field_num",
"ovrimos_field_type",
"ovrimos_free_result",
"ovrimos_longreadlen",
"ovrimos_num_fields",
"ovrimos_num_rows",
"ovrimos_prepare",
"ovrimos_result",
"ovrimos_result_all",
"ovrimos_rollback",
"owner_document",
"pack",
"parent_node",
"parents",
"parse_ini_file",
"parse_str",
"parse_url",
"passthru",
"pathinfo",
"PATH_TRANSLATED",
"pclose",
"pcntl_exec",
"pcntl_fork",
"pcntl_signal",
"pcntl_waitpid",
"pcntl_wexitstatus",
"pcntl_wifexited",
"pcntl_wifsignaled",
"pcntl_wifstopped",
"pcntl_wstopsig",
"pcntl_wtermsig",
"pdf_add_annotation",
"pdf_add_bookmark",
"pdf_add_launchlink",
"pdf_add_locallink",
"pdf_add_note",
"pdf_add_outline",
"pdf_add_pdflink",
"pdf_add_thumbnail",
"pdf_add_weblink",
"pdf_arc",
"pdf_arcn",
"pdf_attach_file",
"pdf_begin_page",
"pdf_begin_pattern",
"pdf_begin_template",
"pdf_circle",
"pdf_clip",
"pdf_close",
"pdf_close_image",
"pdf_closepath",
"pdf_closepath_fill_stroke",
"pdf_closepath_stroke",
"pdf_close_pdi",
"pdf_close_pdi_page",
"pdf_concat",
"pdf_continue_text",
"pdf_curveto",
"pdf_delete",
"pdf_end_page",
"pdf_endpath",
"pdf_end_pattern",
"pdf_end_template",
"pdf_fill",
"pdf_fill_stroke",
"pdf_findfont",
"pdf_get_buffer",
"pdf_get_font",
"pdf_get_fontname",
"pdf_get_fontsize",
"pdf_get_image_height",
"pdf_get_image_width",
"pdf_get_majorversion",
"pdf_get_minorversion",
"pdf_get_parameter",
"pdf_get_pdi_parameter",
"pdf_get_pdi_value",
"pdf_get_value",
"pdf_initgraphics",
"pdf_lineto",
"pdf_makespotcolor",
"pdf_moveto",
"pdf_new",
"pdf_open",
"pdf_open_CCITT",
"pdf_open_file",
"pdf_open_gif",
"pdf_open_image",
"pdf_open_image_file",
"pdf_open_jpeg",
"pdf_open_memory_image",
"pdf_open_pdi",
"pdf_open_pdi_page",
"pdf_open_png",
"pdf_open_tiff",
"pdf_place_image",
"pdf_place_pdi_page",
"pdf_rect",
"pdf_restore",
"pdf_rotate",
"pdf_save",
"pdf_scale",
"pdf_set_border_color",
"pdf_set_border_dash",
"pdf_set_border_style",
"pdf_set_char_spacing",
"pdf_setcolor",
"pdf_setdash",
"pdf_set_duration",
"pdf_setflat",
"pdf_set_font",
"pdf_setfont",
"pdf_setgray",
"pdf_setgray_fill",
"pdf_setgray_stroke",
"pdf_set_horiz_scaling",
"pdf_set_info",
"pdf_set_info_author",
"pdf_set_info_creator",
"pdf_set_info_keywords",
"pdf_set_info_subject",
"pdf_set_info_title",
"pdf_set_leading",
"pdf_setlinecap",
"pdf_setlinejoin",
"pdf_setlinewidth",
"pdf_setmatrix",
"pdf_setmiterlimit",
"pdf_set_parameter",
"pdf_setpolydash",
"pdf_setrgbcolor",
"pdf_setrgbcolor_fill",
"pdf_setrgbcolor_stroke",
"pdf_set_text_matrix",
"pdf_set_text_pos",
"pdf_set_text_rendering",
"pdf_set_text_rise",
"pdf_set_value",
"pdf_set_word_spacing",
"pdf_show",
"pdf_show_boxed",
"pdf_show_xy",
"pdf_skew",
"pdf_stringwidth",
"pdf_stroke",
"pdf_translate",
"PEAR_EXTENSION_DIR",
"PEAR_INSTALL_DIR",
"pfpro_cleanup",
"pfpro_init",
"pfpro_process",
"pfpro_process_raw",
"pfpro_version",
"pfsockopen",
"pg_affected_rows",
"pg_cancel_query",
"pg_client_encoding",
"pg_close",
"pg_connect",
"pg_connection_busy",
"pg_connection_reset",
"pg_connection_status",
"pg_convert",
"pg_copy_from",
"pg_copy_to",
"pg_dbname",
"pg_delete",
"pg_end_copy",
"pg_escape_bytea",
"pg_escape_string",
"pg_fetch_all",
"pg_fetch_array",
"pg_fetch_assoc",
"pg_fetch_object",
"pg_fetch_result",
"pg_fetch_row",
"pg_field_is_null",
"pg_field_name",
"pg_field_num",
"pg_field_prtlen",
"pg_field_size",
"pg_field_type",
"pg_free_result",
"pg_get_notify",
"pg_get_pid",
"pg_get_result",
"pg_host",
"pg_insert",
"pg_last_error",
"pg_last_notice",
"pg_last_oid",
"pg_lo_close",
"pg_lo_create",
"pg_lo_export",
"pg_lo_import",
"pg_lo_open",
"pg_lo_read",
"pg_lo_read_all",
"pg_lo_seek",
"pg_lo_tell",
"pg_lo_unlink",
"pg_lo_write",
"pg_meta_data",
"pg_num_fields",
"pg_num_rows",
"pg_options",
"pg_pconnect",
"pg_ping",
"pg_port",
"pg_put_line",
"pg_query",
"pg_result_error",
"pg_result_seek",
"pg_result_status",
"pg_select",
"pg_send_query",
"pg_set_client_encoding",
"pg_trace",
"pg_tty",
"pg_unescape_bytea",
"pg_untrace",
"pg_update",
"PHP_BINDIR",
"PHP_CONFIG_FILE_PATH",
"phpcredits",
"PHP_DATADIR",
"PHP_ERRMSG",
"PHP_EXTENSION_DIR",
"phpinfo",
"php_ini_scanned_files",
"PHP_LIBDIR",
"PHP_LOCALSTATEDIR",
"php_logo_guid",
"PHP_OS",
"PHP_OUTPUT_HANDLER_CONT",
"PHP_OUTPUT_HANDLER_END",
"PHP_OUTPUT_HANDLER_START",
"php_sapi_name",
"PHP_SELF",
"PHP_SYSCONFDIR",
"php_uname",
"phpversion",
"PHP_VERSION",
"pi",
"png2wbmp",
"popen",
"pos",
"posix_ctermid",
"posix_getcwd",
"posix_getegid",
"posix_geteuid",
"posix_getgid",
"posix_getgrgid",
"posix_getgrnam",
"posix_getgroups",
"posix_getlogin",
"posix_getpgid",
"posix_getpgrp",
"posix_getpid",
"posix_getppid",
"posix_getpwnam",
"posix_getpwuid",
"posix_getrlimit",
"posix_getsid",
"posix_getuid",
"posix_isatty",
"posix_kill",
"posix_mkfifo",
"posix_setegid",
"posix_seteuid",
"posix_setgid",
"posix_setpgid",
"posix_setsid",
"posix_setuid",
"posix_times",
"posix_ttyname",
"posix_uname",
"_POST",
"pow",
"prefix",
"preg_grep",
"preg_match",
"preg_match_all",
"preg_quote",
"preg_replace",
"preg_replace_callback",
"preg_split",
"prev",
"previous_sibling",
"print",
"printer_abort",
"printer_close",
"printer_create_brush",
"printer_create_dc",
"printer_create_font",
"printer_create_pen",
"printer_delete_brush",
"printer_delete_dc",
"printer_delete_font",
"printer_delete_pen",
"printer_draw_bmp",
"printer_draw_chord",
"printer_draw_elipse",
"printer_draw_line",
"printer_draw_pie",
"printer_draw_rectangle",
"printer_draw_roundrect",
"printer_draw_text",
"printer_end_doc",
"printer_end_page",
"printer_get_option",
"printer_list",
"printer_logical_fontheight",
"printer_open",
"printer_select_brush",
"printer_select_font",
"printer_select_pen",
"printer_set_option",
"printer_start_doc",
"printer_start_page",
"printer_write",
"printf",
"print_r",
"private",
"proc_close",
"process",
"proc_open",
"protected",
"pspell_add_to_personal",
"pspell_add_to_session",
"pspell_check",
"pspell_clear_session",
"pspell_config_create",
"pspell_config_ignore",
"pspell_config_mode",
"pspell_config_personal",
"pspell_config_repl",
"pspell_config_runtogether",
"pspell_config_save_repl",
"pspell_new",
"pspell_new_config",
"pspell_new_personal",
"pspell_save_wordlist",
"pspell_store_replacement",
"pspell_suggest",
"public",
"public_id",
"putenv",
"qdom_error",
"qdom_tree",
"QUERY_STRING",
"quoted_printable_decode",
"quotemeta",
"rad2deg",
"rand",
"range",
"rawurldecode",
"rawurlencode",
"read",
"readdir",
"read_exif_data",
"readfile",
"readgzfile",
"readline",
"readline_add_history",
"readline_clear_history",
"readline_completion_function",
"readline_info",
"readline_list_history",
"readline_read_history",
"readline_write_history",
"readlink",
"realpath",
"reason",
"recode",
"recode_file",
"recode_string",
"register_shutdown_function",
"register_tick_function",
"REMOTE_ADDR",
"REMOTE_PORT",
"remove",
"remove_attribute",
"remove_child",
"rename",
"replace",
"replace_child",
"replace_node",
"_REQUEST",
"REQUEST_METHOD",
"REQUEST_URI",
"require",
"require_once",
"reset",
"restore_error_handler",
"restore_include_path",
"result_dump_file",
"result_dump_mem",
"return",
"rewind",
"rewinddir",
"rmdir",
"Rotate",
"rotateTo",
"round",
"rsort",
"rtrim",
"save",
"scale",
"scaleTo",
"SCRIPT_FILENAME",
"SCRIPT_NAME",
"sem_acquire",
"sem_get",
"sem_release",
"sem_remove",
"serialize",
"_SERVER",
"SERVER_ADMIN",
"SERVER_NAME",
"SERVER_PORT",
"SERVER_PROTOCOL",
"SERVER_SIGNATURE",
"SERVER_SOFTWARE",
"sesam_affected_rows",
"sesam_commit",
"sesam_connect",
"sesam_diagnostic",
"sesam_disconnect",
"sesam_errormsg",
"sesam_execimm",
"sesam_fetch_array",
"sesam_fetch_result",
"sesam_fetch_row",
"sesam_field_array",
"sesam_field_name",
"sesam_free_result",
"sesam_num_fields",
"sesam_query",
"sesam_rollback",
"sesam_seek_row",
"sesam_settransaction",
"_SESSION",
"session_cache_expire",
"session_cache_limiter",
"session_decode",
"session_destroy",
"session_encode",
"session_get_cookie_params",
"session_id",
"session_is_registered",
"session_module_name",
"session_name",
"session_readonly",
"session_register",
"session_save_path",
"session_set_cookie_params",
"session_set_save_handler",
"session_start",
"session_unregister",
"session_unset",
"session_write_close",
"setAction",
"set_attribute",
"setbackground",
"setbounds",
"setcolor",
"setColor",
"setcommitedversion",
"set_content",
"setcookie",
"setDepth",
"setdimension",
"setdown",
"set_error_handler",
"set_file_buffer",
"setFont",
"setframes",
"setHeight",
"setHit",
"set_include_path",
"setindentation",
"setLeftFill",
"setLeftMargin",
"setLine",
"setLineSpacing",
"setlocale",
"set_magic_quotes_runtime",
"setMargins",
"set_name",
"setname",
"setName",
"set_namespace",
"setOver",
"setrate",
"setRatio",
"setRightFill",
"setrightMargin",
"setSpacing",
"set_time_limit",
"settype",
"setUp",
"sha1",
"sha1_file",
"shell_exec",
"shm_attach",
"shm_detach",
"shm_get_var",
"shmop_close",
"shmop_delete",
"shmop_open",
"shmop_read",
"shmop_size",
"shmop_write",
"shm_put_var",
"shm_remove",
"shm_remove_var",
"show_source",
"shuffle",
"similar_text",
"sin",
"sinh",
"sizeof",
"skewX",
"skewXTo",
"skewY",
"skewYTo",
"sleep",
"snmpget",
"snmp_get_quick_print",
"snmprealwalk",
"snmpset",
"snmp_set_quick_print",
"snmpwalk",
"snmpwalkoid",
"socket_accept",
"socket_bind",
"socket_clear_error",
"socket_close",
"socket_connect",
"socket_create",
"socket_create_listen",
"socket_create_pair",
"socket_get_option",
"socket_getpeername",
"socket_getsockname",
"socket_get_status",
"socket_iovec_add",
"socket_iovec_alloc",
"socket_iovec_delete",
"socket_iovec_fetch",
"socket_iovec_free",
"socket_iovec_set",
"socket_last_error",
"socket_listen",
"socket_read",
"socket_readv",
"socket_recv",
"socket_recvfrom",
"socket_recvmsg",
"socket_select",
"socket_send",
"socket_sendmsg",
"socket_sendto",
"socket_set_blocking",
"socket_set_nonblock",
"socket_set_option",
"socket_set_timeout",
"socket_shutdown",
"socket_strerror",
"socket_write",
"socket_writev",
"sort",
"soundex",
"specified",
"split",
"spliti",
"sprintf",
"sql_regcase",
"sqrt",
"srand",
"srcanchors",
"srcsofdst",
"sscanf",
"stat",
"static",
"stdClass",
"strcasecmp",
"strchr",
"strcmp",
"strcoll",
"strcspn",
"stream_context_create",
"stream_context_get_options",
"stream_context_set_option",
"stream_context_set_params",
"stream_filter_append",
"stream_filter_prepend",
"stream_get_filters",
"stream_get_meta_data",
"stream_get_wrappers",
"streammp3",
"stream_register_filter",
"stream_register_wrapper",
"stream_select",
"stream_set_blocking",
"stream_set_timeout",
"stream_set_write_buffer",
"strftime",
"stripcslashes",
"stripslashes",
"strip_tags",
"stristr",
"strlen",
"strnatcasecmp",
"strnatcmp",
"strncasecmp",
"strncmp",
"str_pad",
"strpos",
"strrchr",
"str_repeat",
"str_replace",
"strrev",
"str_rot13",
"strrpos",
"str_shuffle",
"strspn",
"strstr",
"strtok",
"strtolower",
"strtotime",
"strtoupper",
"strtr",
"strval",
"str_word_count",
"substr",
"substr_count",
"substr_replace",
"SWFAction",
"swf_actiongeturl",
"swf_actiongotoframe",
"swf_actiongotolabel",
"swf_actionnextframe",
"swf_actionplay",
"swf_actionprevframe",
"swf_actionsettarget",
"swf_actionstop",
"swf_actiontogglequality",
"swf_actionwaitforframe",
"swf_addbuttonrecord",
"swf_addcolor",
"SWFBitmap",
"SWFbutton",
"swfbutton_keypress",
"swf_closefile",
"swf_definebitmap",
"swf_definefont",
"swf_defineline",
"swf_definepoly",
"swf_definerect",
"swf_definetext",
"SWFDisplayItem",
"swf_endbutton",
"swf_enddoaction",
"swf_endshape",
"swf_endsymbol",
"SWFFill",
"SWFFont",
"swf_fontsize",
"swf_fontslant",
"swf_fonttracking",
"swf_getbitmapinfo",
"swf_getfontinfo",
"swf_getframe",
"SWFGradient",
"swf_labelframe",
"swf_lookat",
"swf_modifyobject",
"SWFMorph",
"SWFMovie",
"swf_mulcolor",
"swf_nextid",
"swf_oncondition",
"swf_openfile",
"swf_ortho",
"swf_ortho2",
"swf_perspective",
"swf_placeobject",
"swf_polarview",
"swf_popmatrix",
"swf_posround",
"swf_pushmatrix",
"swf_removeobject",
"swf_rotate",
"swf_scale",
"swf_setfont",
"swf_setframe",
"SWFShape",
"swf_shapearc",
"swf_shapecurveto",
"swf_shapecurveto3",
"swf_shapefillbitmapclip",
"swf_shapefillbitmaptile",
"swf_shapefilloff",
"swf_shapefillsolid",
"swf_shapelinesolid",
"swf_shapelineto",
"swf_shapemoveto",
"swf_showframe",
"SWFSprite",
"swf_startbutton",
"swf_startdoaction",
"swf_startshape",
"swf_startsymbol",
"SWFText",
"SWFTextField",
"swf_textwidth",
"swf_translate",
"swf_viewport",
"switch",
"sybase_affected_rows",
"sybase_close",
"sybase_connect",
"sybase_data_seek",
"sybase_fetch_array",
"sybase_fetch_field",
"sybase_fetch_object",
"sybase_fetch_row",
"sybase_field_seek",
"sybase_free_result",
"sybase_get_last_message",
"sybase_min_client_severity",
"sybase_min_error_severity",
"sybase_min_message_severity",
"sybase_min_server_severity",
"sybase_num_fields",
"sybase_num_rows",
"sybase_pconnect",
"sybase_query",
"sybase_result",
"sybase_select_db",
"symlink",
"syslog",
"system",
"system_id",
"tagname",
"tan",
"tanh",
"target",
"tempnam",
"textdomain",
"time",
"title",
"tmpfile",
"token_get_all",
"token_name",
"touch",
"trigger_error",
"trim",
"TRUE",
"type",
"uasort",
"ucfirst",
"ucwords",
"udm_add_search_limit",
"udm_alloc_agent",
"udm_api_version",
"udm_cat_list",
"udm_cat_path",
"udm_check_charset",
"udm_check_stored",
"udm_clear_search_limits",
"udm_close_stored",
"udm_crc32",
"udm_errno",
"udm_error",
"udm_find",
"udm_free_agent",
"udm_free_ispell_data",
"udm_free_res",
"udm_get_doc_count",
"udm_get_res_field",
"udm_get_res_param",
"udm_load_ispell_data",
"udm_open_stored",
"udm_set_agent_param",
"uksort",
"umask",
"uniqid",
"unixtojd",
"unlink",
"unlink_node",
"unlock",
"unpack",
"unregister_tick_function",
"unserialize",
"unset",
"urldecode",
"urlencode",
"user",
"user_error",
"userlist",
"usleep",
"usort",
"utf8_decode",
"utf8_encode",
"value",
"values",
"var",
"var_dump",
"var_export",
"version_compare",
"virtual",
"vpopmail_add_alias_domain",
"vpopmail_add_alias_domain_ex",
"vpopmail_add_domain",
"vpopmail_add_domain_ex",
"vpopmail_add_user",
"vpopmail_alias_add",
"vpopmail_alias_del",
"vpopmail_alias_del_domain",
"vpopmail_alias_get",
"vpopmail_alias_get_all",
"vpopmail_auth_user",
"vpopmail_del_domain",
"vpopmail_del_domain_ex",
"vpopmail_del_user",
"vpopmail_error",
"vpopmail_passwd",
"vpopmail_set_user_quota",
"vprintf",
"vsprintf",
"w32api_deftype",
"w32api_init_dtype",
"w32api_invoke_function",
"w32api_register_function",
"w32api_set_call_method",
"wddx_add_vars",
"wddx_deserialize",
"wddx_packet_end",
"wddx_packet_start",
"wddx_serialize_value",
"wddx_serialize_vars",
"while",
"wordwrap",
"xinclude",
"xml_error_string",
"xml_get_current_byte_index",
"xml_get_current_column_number",
"xml_get_current_line_number",
"xml_get_error_code",
"xml_parse",
"xml_parse_into_struct",
"xml_parser_create",
"xml_parser_create_ns",
"xml_parser_free",
"xml_parser_get_option",
"xml_parser_set_option",
"xmlrpc_decode",
"xmlrpc_decode_request",
"xmlrpc_encode",
"xmlrpc_encode_request",
"xmlrpc_get_type",
"xmlrpc_parse_method_descriptions",
"xmlrpc_server_add_introspection_data",
"xmlrpc_server_call_method",
"xmlrpc_server_create",
"xmlrpc_server_destroy",
"xmlrpc_server_register_introspection_callback",
"xmlrpc_server_register_method",
"xmlrpc_set_type",
"xml_set_character_data_handler",
"xml_set_default_handler",
"xml_set_element_handler",
"xml_set_end_namespace_decl_handler",
"xml_set_external_entity_ref_handler",
"xml_set_notation_decl_handler",
"xml_set_object",
"xml_set_processing_instruction_handler",
"xml_set_start_namespace_decl_handler",
"xml_set_unparsed_entity_decl_handler",
"xpath_eval",
"xpath_eval_expression",
"xpath_new_context",
"xptr_eval",
"xptr_new_context",
"xslt_create",
"xslt_errno",
"xslt_error",
"xslt_free",
"xslt_output_process",
"xslt_set_base",
"xslt_set_encoding",
"xslt_set_error_handler",
"xslt_set_log",
"xslt_set_sax_handler",
"xslt_set_sax_handlers",
"xslt_set_scheme_handler",
"xslt_set_scheme_handlers",
"yaz_addinfo",
"yaz_ccl_conf",
"yaz_ccl_parse",
"yaz_close",
"yaz_connect",
"yaz_database",
"yaz_element",
"yaz_errno",
"yaz_error",
"yaz_get_option",
"yaz_hits",
"yaz_itemorder",
"yaz_present",
"yaz_range",
"yaz_record",
"yaz_scan",
"yaz_scan_result",
"yaz_schema",
"yaz_search",
"yaz_set_option",
"yaz_sort",
"yaz_syntax",
"yaz_wait",
"yp_all",
"yp_cat",
"yp_errno",
"yp_err_string",
"yp_first",
"yp_get_default_domain",
"yp_master",
"yp_match",
"yp_next",
"yp_order",
"zend_logo_guid",
"zend_version",
"zend_version",
"zip_close",
"zip_entry_close",
"zip_entry_compressedsize",
"zip_entry_compressionmethod",
"zip_entry_filesize",
"zip_entry_name",
"zip_entry_open",
"zip_entry_read",
"zip_open",
"zip_read",
nullptr
};
PhpWriter::PhpWriter()
{
}
PhpWriter::~PhpWriter()
{
}
/**
* Call this method to generate Php code for a UMLClassifier.
* @param c the class you want to generate code for.
*/
void PhpWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("PhpWriter::writeClass: Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".php"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile filephp;
if (!openFile(filephp, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream php(&filephp);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".php"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filephp.fileName());
php << str << m_endl;
}
//write includes
UMLPackageList includes;
findObjectsRelated(c, includes);
for(UMLPackage* conc : includes) {
QString headerName = findFileName(conc, QStringLiteral(".php"));
if (headerName.isEmpty()) {
php << "include '" << headerName << "';" << m_endl;
}
}
php << m_endl;
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty()) {
php << m_endl << "/**" << m_endl;
php << " * class " << classname << m_endl;
php << formatDoc(c->doc(), QStringLiteral(" * "));
php << " */" << m_endl ;
}
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
//check if class is abstract and / or has abstract methods
//FG if(c->getAbstract() && !hasAbstractOps(c))
if (c->isAbstract())
php << "/******************************* Abstract Class ****************************" << m_endl << " "
<< classname << " does not have any pure virtual methods, but its author" << m_endl
<< " defined it as an abstract class, so you should not use it directly." << m_endl
<< " Inherit from it instead and create only objects from the derived classes" << m_endl
<< "*****************************************************************************/" << m_endl << m_endl;
php << "class " << classname << (superclasses.count() > 0 ? QStringLiteral(" extends ") : QString());
for(UMLClassifier *obj : superclasses) {
php << cleanName(obj->name());
}
php << m_endl << "{" << m_endl;
//associations
if (forceSections() || !aggregations.isEmpty()) {
php << m_endl << m_indentation << "/** Aggregations: */" << m_endl;
for(UMLAssociation* a : aggregations) {
php << m_endl;
//maybe we should parse the string here and take multiplicity into account to decide
//which container to use.
//:UNUSED: UMLObject *o = a->getObject(Uml::RoleType::A);
//:UNUSED: QString typeName = cleanName(o->name());
if (a->getMultiplicity(Uml::RoleType::A).isEmpty()) {
php << m_indentation << "var $m_" << ";" << m_endl;
} else {
php << m_indentation << "var $m_" << "Vector = array();" << m_endl;
}
}//end for
}
if (forceSections() || !compositions.isEmpty()) {
php << m_endl << m_indentation << "/** Compositions: */" << m_endl;
for(UMLAssociation* a : compositions) {
// see comment on Aggregation about multiplicity...
//:UNUSED: UMLObject *o = a->getObject(Uml::RoleType::A);
//:UNUSED: QString typeName = cleanName(o->name());
if (a->getMultiplicity(Uml::RoleType::A).isEmpty()) {
php << m_indentation << "var $m_" << ";" << m_endl;
} else {
php << m_indentation << "var $m_" << "Vector = array();" << m_endl;
}
}
}
const bool isClass = !c->isInterface();
//attributes
if (isClass)
writeAttributes(c, php);
//operations
writeOperations(c, php);
if (isClass && hasDefaultValueAttr(c)) {
UMLAttributeList atl = c->getAttributeList();
php << m_endl;
php << m_indentation << "/**" << m_endl;
QString temp = QStringLiteral("initAttributes sets all ") + classname + QStringLiteral(" attributes to its default value.")
+ QStringLiteral(" Make sure to call this method within your class constructor");
php << formatDoc(temp, m_indentation + QStringLiteral(" * "));
php << m_indentation << " */" << m_endl;
php << m_indentation << "function " << "initAttributes()" << m_endl;
php << m_indentation << "{" << m_endl;
for(UMLAttribute* at: atl) {
if (!at->getInitialValue().isEmpty()) {
php << m_indentation << m_indentation << "$this->" << cleanName(at->name()) << " = " <<
at->getInitialValue() << ";" << m_endl;
}
}
php << m_indentation << "}" << m_endl;
}
php << m_endl;
//finish file
php << m_endl << "} // end of " << classname << m_endl;
php << "?>" << m_endl;
//close files and notfiy we are done
filephp.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(filephp.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param php output stream for the PHP file
*/
void PhpWriter::writeOperations(UMLClassifier *c, QTextStream &php)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for(UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
QString classname(cleanName(c->name()));
//write operations to file
if (forceSections() || !oppub.isEmpty()) {
php << m_endl;
writeOperations(classname, oppub, php);
}
if (forceSections() || !opprot.isEmpty()) {
php << m_endl;
writeOperations(classname, opprot, php);
}
if (forceSections() || !oppriv.isEmpty()) {
php << m_endl;
writeOperations(classname, oppriv, php);
}
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param php output stream for the PHP file
*/
void PhpWriter::writeOperations(const QString& classname,
UMLOperationList &opList,
QTextStream &php)
{
Q_UNUSED(classname);
for(UMLOperation* op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for(UMLAttribute* at : atl)
writeDoc |= !at->doc().isEmpty();
if (writeDoc) //write method documentation
{
php << m_indentation << "/**" << m_endl << formatDoc(op->doc(), m_indentation + QStringLiteral(" * "));
php << m_indentation << " *" << m_endl;
for (UMLAttribute* at : atl) //write parameter documentation
{
if (forceDoc() || !at->doc().isEmpty()) {
php << m_indentation << " * @param " << at->getTypeName() << " " << cleanName(at->name());
php << " " << formatDoc(at->doc(), QString());
}
}//end for : write parameter documentation
php << m_indentation << " * @return " << op->getTypeName() << m_endl;
if (op->isAbstract()) php << m_indentation << " * @abstract" << m_endl;
if (op->isStatic()) php << m_indentation << " * @static" << m_endl;
switch(op->visibility()) {
case Uml::Visibility::Public:
php << m_indentation << " * @access public" << m_endl;
break;
case Uml::Visibility::Protected:
php << m_indentation << " * @access protected" << m_endl;
break;
case Uml::Visibility::Private:
php << m_indentation << " * @access private" << m_endl;
break;
default:
break;
}
php << m_indentation << " */" << m_endl;
}//end if : write method documentation
php << m_indentation << "function " << cleanName(op->name()) << "(";
int i= atl.count();
int j=0;
for(UMLAttribute* at : atl) {
php << " $" << cleanName(at->name())
<< (!(at->getInitialValue().isEmpty()) ?
QStringLiteral(" = ") + at->getInitialValue() : QString())
<< ((j < i-1) ? QStringLiteral(", ") : QString());
j++;
}
php <<")" << m_endl;
php << m_indentation << "{" << m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
php << m_indentation << m_indentation << m_endl;
}
else {
php << formatSourceCode(sourceCode, m_indentation + m_indentation);
}
php << m_indentation << "} // end of member function " << cleanName(op->name()) << m_endl;
php << m_endl;
}//end for
}
/**
* Write all the attributes of a class.
* @param c the class we are generating code for
* @param php output stream for the PHP file
*/
void PhpWriter::writeAttributes(UMLClassifier *c, QTextStream &php)
{
UMLAttributeList atpub, atprot, atpriv, atdefval;
//sort attributes by scope and see if they have a default value
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty())
atdefval.append(at);
switch(at->visibility()) {
case Uml::Visibility::Public:
atpub.append(at);
break;
case Uml::Visibility::Protected:
atprot.append(at);
break;
case Uml::Visibility::Private:
atpriv.append(at);
break;
default:
break;
}
}
if (forceSections() || atl.count())
php << m_endl << m_indentation << " /*** Attributes: ***/" << m_endl << m_endl;
if (forceSections() || atpub.count()) {
writeAttributes(atpub, php);
}
if (forceSections() || atprot.count()) {
writeAttributes(atprot, php);
}
if (forceSections() || atpriv.count()) {
writeAttributes(atpriv, php);
}
}
/**
* Write a list of class attributes.
* @param atList the list of attributes
* @param php output stream for the PHP file
*/
void PhpWriter::writeAttributes(UMLAttributeList &atList, QTextStream &php)
{
for(UMLAttribute *at : atList) {
if (forceDoc() || !at->doc().isEmpty()) {
php << m_indentation << "/**" << m_endl << formatDoc(at->doc(), m_indentation + QStringLiteral(" * "));
switch(at->visibility()) {
case Uml::Visibility::Public:
php << m_indentation << " * @access public" << m_endl;
break;
case Uml::Visibility::Protected:
php << m_indentation << " * @access protected" << m_endl;
break;
case Uml::Visibility::Private:
php << m_indentation << " * @access private" << m_endl;
break;
default:
break;
}
php << m_indentation << " */" << m_endl;
}
php << m_indentation << "var " << "$" << cleanName(at->name()) << ";" << m_endl;
} // end for
return;
}
/**
* Returns "PHP".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum PhpWriter::language() const
{
return Uml::ProgrammingLanguage::PHP;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList PhpWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i)
keywords.append(QLatin1String(reserved_words[i]));
}
return keywords;
}
| 76,887
|
C++
|
.cpp
| 3,306
| 17.931639
| 131
| 0.58833
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,525
|
php5writer.cpp
|
KDE_umbrello/umbrello/codegenerators/php/php5writer.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Heiko Nardmann <h.nardmann@secunet.de>
SPDX-FileCopyrightText: 2004 Thorsten Kunz <tk AT bytecrash DOT net>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "php5writer.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h" // only needed for log{Warn,Error}
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"abs",
"abstract",
"acos",
"acosh",
"add",
"addAction",
"addColor",
"addEntry",
"addFill",
"addShape",
"addString",
"add_namespace",
"addcslashes",
"addslashes",
"addstring",
"aggregate",
"aggregate_info",
"aggregate_methods",
"aggregate_methods_by_list",
"aggregate_methods_by_regexp",
"aggregate_properties",
"aggregate_properties_by_list",
"aggregate_properties_by_regexp",
"aggregation_info",
"align",
"apache_child_terminate",
"apache_lookup_uri",
"apache_note",
"apache_request_headers",
"apache_response_headers",
"apache_setenv",
"append_child",
"append_sibling",
"array",
"array_change_key_case",
"array_chunk",
"array_count_values",
"array_diff",
"array_diff_assoc",
"array_fill",
"array_filter",
"array_flip",
"array_intersect",
"array_intersect_assoc",
"array_key_exists",
"array_keys",
"array_map",
"array_merge",
"array_merge_recursive",
"array_multisort",
"array_pad",
"array_pop",
"array_push",
"array_rand",
"array_reduce",
"array_reverse",
"array_search",
"array_shift",
"array_slice",
"array_splice",
"array_sum",
"array_unique",
"array_unshift",
"array_values",
"array_walk",
"arsort",
"ascii2ebcdic",
"asin",
"asinh",
"asort",
"aspell_check",
"aspell_new",
"aspell_suggest",
"assert",
"assert_options",
"assign",
"atan",
"atan2",
"atanh",
"attreditable",
"attributes",
"base64_decode",
"base64_encode",
"base_convert",
"basename",
"bcadd",
"bccomp",
"bcdiv",
"bcmod",
"bcmul",
"bcpow",
"bcpowmod",
"bcscale",
"bcsqrt",
"bcsub",
"bin2hex",
"bindec",
"bindtextdomain",
"bind_textdomain_codeset",
"bool",
"break",
"bzclose",
"bzcompress",
"bzdecompress",
"bzerrno",
"bzerror",
"bzerrstr",
"bzflush",
"bzopen",
"bzread",
"bzwrite",
"cal_days_in_month",
"cal_from_jd",
"cal_info",
"call_user_func",
"call_user_func_array",
"call_user_method",
"call_user_method_array",
"cal_to_jd",
"ccvs_add",
"ccvs_auth",
"ccvs_command",
"ccvs_count",
"ccvs_delete",
"ccvs_done",
"ccvs_init",
"ccvs_lookup",
"ccvs_new",
"ccvs_report",
"ccvs_return",
"ccvs_reverse",
"ccvs_sale",
"ccvs_status",
"ccvs_textvalue",
"ccvs_void",
"ceil",
"chdir",
"checkdate",
"checkdnsrr",
"checkin",
"checkout",
"chgrp",
"child_nodes",
"children",
"chmod",
"chop",
"chown",
"chr",
"chroot",
"chunk_split",
"class",
"class_exists",
"clearstatcache",
"clone_node",
"closedir",
"closelog",
"com_addref",
"com_get",
"com_invoke",
"com_isenum",
"com_load",
"com_load_typelib",
"compact",
"com_propget",
"com_propput",
"com_propset",
"com_release",
"com_set",
"connection_aborted",
"connection_status",
"connection_timeout",
"constant",
"content",
"continue",
"convert_cyr_string",
"_COOKIE",
"copy",
"cos",
"cosh",
"count",
"count_chars",
"cpdf_add_annotation",
"cpdf_add_outline",
"cpdf_arc",
"cpdf_begin_text",
"cpdf_circle",
"cpdf_clip",
"cpdf_close",
"cpdf_closepath",
"cpdf_closepath_fill_stroke",
"cpdf_closepath_stroke",
"cpdf_continue_text",
"cpdf_curveto",
"cpdf_end_text",
"cpdf_fill",
"cpdf_fill_stroke",
"cpdf_finalize",
"cpdf_finalize_page",
"cpdf_global_set_document_limits",
"cpdf_import_jpeg",
"cpdf_lineto",
"cpdf_moveto",
"cpdf_newpath",
"cpdf_open",
"cpdf_output_buffer",
"cpdf_page_init",
"cpdf_place_inline_image",
"cpdf_rect",
"cpdf_restore",
"cpdf_rlineto",
"cpdf_rmoveto",
"cpdf_rotate",
"cpdf_rotate_text",
"cpdf_save",
"cpdf_save_to_file",
"cpdf_scale",
"cpdf_set_action_url",
"cpdf_set_char_spacing",
"cpdf_set_creator",
"cpdf_set_current_page",
"cpdf_setdash",
"cpdf_setflat",
"cpdf_set_font",
"cpdf_set_font_directories",
"cpdf_set_font_map_file",
"cpdf_setgray",
"cpdf_setgray_fill",
"cpdf_setgray_stroke",
"cpdf_set_horiz_scaling",
"cpdf_set_keywords",
"cpdf_set_leading",
"cpdf_setlinecap",
"cpdf_setlinejoin",
"cpdf_setlinewidth",
"cpdf_setmiterlimit",
"cpdf_set_page_animation",
"cpdf_setrgbcolor",
"cpdf_setrgbcolor_fill",
"cpdf_setrgbcolor_stroke",
"cpdf_set_subject",
"cpdf_set_text_matrix",
"cpdf_set_text_pos",
"cpdf_set_text_rendering",
"cpdf_set_text_rise",
"cpdf_set_title",
"cpdf_set_viewer_preferences",
"cpdf_set_word_spacing",
"cpdf_show",
"cpdf_show_xy",
"cpdf_stringwidth",
"cpdf_stroke",
"cpdf_text",
"cpdf_translate",
"crack_check",
"crack_closedict",
"crack_getlastmessage",
"crack_opendict",
"crc32",
"create_attribute",
"create_cdata_section",
"create_comment",
"create_element",
"create_element_ns",
"create_entity_reference",
"create_function",
"create_processing_instruction",
"create_text_node",
"crypt",
"ctype_alnum",
"ctype_alpha",
"ctype_cntrl",
"ctype_digit",
"ctype_graph",
"ctype_lower",
"ctype_print",
"ctype_punct",
"ctype_space",
"ctype_upper",
"ctype_xdigit",
"curl_close",
"curl_errno",
"curl_error",
"curl_exec",
"curl_getinfo",
"curl_init",
"curl_setopt",
"curl_version",
"current",
"cybercash_base64_decode",
"cybercash_base64_encode",
"cybercash_decr",
"cybercash_encr",
"cybermut_creerformulairecm",
"cybermut_creerreponsecm",
"cybermut_testmac",
"cyrus_authenticate",
"cyrus_bind",
"cyrus_close",
"cyrus_connect",
"cyrus_query",
"cyrus_unbind",
"data",
"date",
"dba_close",
"dba_delete",
"dba_exists",
"dba_fetch",
"dba_firstkey",
"dba_handlers",
"dba_insert",
"dba_list",
"dba_nextkey",
"dba_open",
"dba_optimize",
"dba_popen",
"dba_replace",
"dbase_add_record",
"dbase_close",
"dbase_create",
"dbase_delete_record",
"dbase_get_record",
"dbase_get_record_with_names",
"dbase_numfields",
"dbase_numrecords",
"dbase_open",
"dbase_pack",
"dbase_replace_record",
"dba_sync",
"dblist",
"dbmclose",
"dbmdelete",
"dbmexists",
"dbmfetch",
"dbmfirstkey",
"dbminsert",
"dbmnextkey",
"dbmopen",
"dbmreplace",
"dbplus_add",
"dbplus_aql",
"dbplus_chdir",
"dbplus_close",
"dbplus_curr",
"dbplus_errcode",
"dbplus_errno",
"dbplus_find",
"dbplus_first",
"dbplus_flush",
"dbplus_freealllocks",
"dbplus_freelock",
"dbplus_freerlocks",
"dbplus_getlock",
"dbplus_getunique",
"dbplus_info",
"dbplus_last",
"dbplus_lockrel",
"dbplus_next",
"dbplus_open",
"dbplus_prev",
"dbplus_rchperm",
"dbplus_rcreate",
"dbplus_rcrtexact",
"dbplus_rcrtlike",
"dbplus_resolve",
"dbplus_restorepos",
"dbplus_rkeys",
"dbplus_ropen",
"dbplus_rquery",
"dbplus_rrename",
"dbplus_rsecindex",
"dbplus_runlink",
"dbplus_rzap",
"dbplus_savepos",
"dbplus_setindex",
"dbplus_setindexbynumber",
"dbplus_sql",
"dbplus_tcl",
"dbplus_tremove",
"dbplus_undo",
"dbplus_undoprepare",
"dbplus_unlockrel",
"dbplus_unselect",
"dbplus_update",
"dbplus_xlockrel",
"dbplus_xunlockrel",
"dbstat",
"dbx_close",
"dbx_compare",
"dbx_connect",
"dbx_error",
"dbx_escape_string",
"dbx_query",
"dbx_sort",
"dcgettext",
"dcngettext",
"dcstat",
"deaggregate",
"debug_backtrace",
"debugger_off",
"debugger_on",
"decbin",
"dechex",
"declare",
"decoct",
"DEFAULT_INCLUDE_PATH",
"define",
"defined",
"define_syslog_variables",
"deg2rad",
"delete",
"description",
"dgettext",
"die",
"dio_close",
"dio_fcntl",
"dio_open",
"dio_read",
"dio_seek",
"dio_stat",
"dio_tcsetattr",
"dio_truncate",
"dio_write",
"dir",
"dirname",
"disk_free_space",
"diskfreespace",
"disk_total_space",
"dl",
"dngettext",
"dns_check_record",
"dns_get_mx",
"dns_get_record",
"do",
"doctype",
"document_element",
"DOCUMENT_ROOT",
"domxml_new_doc",
"domxml_open_file",
"domxml_open_mem",
"domxml_version",
"domxml_xmltree",
"domxml_xslt_stylesheet",
"domxml_xslt_stylesheet_doc",
"domxml_xslt_stylesheet_file",
"dotnet_load",
"doubleval",
"drawCurve",
"drawCurveTo",
"drawLine",
"drawLineTo",
"dstanchors",
"dstofsrcanchors",
"dump_file",
"dump_mem",
"dump_node",
"each",
"E_ALL",
"easter_date",
"easter_days",
"ebcdic2ascii",
"echo",
"E_COMPILE_ERROR",
"E_COMPILE_WARNING",
"E_CORE_ERROR",
"E_CORE_WARNING",
"E_ERROR",
"else",
"elseif",
"empty",
"end",
"endfor",
"endforeach",
"endif",
"endswitch",
"endwhile",
"E_NOTICE",
"entities",
"_ENV",
"E_PARSE",
"ereg",
"eregi",
"eregi_replace",
"ereg_replace",
"error_log",
"error_reporting",
"escapeshellarg",
"escapeshellcmd",
"E_USER_ERROR",
"E_USER_NOTICE",
"E_USER_WARNING",
"eval",
"E_WARNING",
"exec",
"exif_imagetype",
"exif_read_data",
"exif_thumbnail",
"exit",
"exp",
"explode",
"expm1",
"extension_loaded",
"extract",
"ezmlm_hash",
"FALSE",
"fbsql_affected_rows",
"fbsql_autocommit",
"fbsql_change_user",
"fbsql_close",
"fbsql_commit",
"fbsql_connect",
"fbsql_create_blob",
"fbsql_create_clob",
"fbsql_create_db",
"fbsql_database",
"fbsql_database_password",
"fbsql_data_seek",
"fbsql_db_query",
"fbsql_db_status",
"fbsql_drop_db",
"fbsql_errno",
"fbsql_error",
"fbsql_fetch_array",
"fbsql_fetch_assoc",
"fbsql_fetch_field",
"fbsql_fetch_lengths",
"fbsql_fetch_object",
"fbsql_fetch_row",
"fbsql_field_flags",
"fbsql_field_len",
"fbsql_field_name",
"fbsql_field_seek",
"fbsql_field_table",
"fbsql_field_type",
"fbsql_free_result",
"fbsql_get_autostart_info",
"fbsql_hostname",
"fbsql_insert_id",
"fbsql_list_dbs",
"fbsql_list_fields",
"fbsql_list_tables",
"fbsql_next_result",
"fbsql_num_fields",
"fbsql_num_rows",
"fbsql_password",
"fbsql_pconnect",
"fbsql_query",
"fbsql_read_blob",
"fbsql_read_clob",
"fbsql_result",
"fbsql_rollback",
"fbsql_select_db",
"fbsql_set_lob_mode",
"fbsql_set_transaction",
"fbsql_start_db",
"fbsql_stop_db",
"fbsql_tablename",
"fbsql_username",
"fbsql_warnings",
"fclose",
"fdf_add_doc_javascript",
"fdf_add_template",
"fdf_close",
"fdf_create",
"fdf_errno",
"fdf_error",
"fdf_get_ap",
"fdf_get_attachment",
"fdf_get_encoding",
"fdf_get_file",
"fdf_get_status",
"fdf_get_value",
"fdf_get_version",
"fdf_header",
"fdf_next_field_name",
"fdf_open",
"fdf_open_string",
"fdf_save",
"fdf_save_string",
"fdf_set_ap",
"fdf_set_encoding",
"fdf_set_file",
"fdf_set_flags",
"fdf_set_javascript_action",
"fdf_set_opt",
"fdf_set_status",
"fdf_set_submit_form_action",
"fdf_set_target_frame",
"fdf_set_value",
"fdf_set_version",
"feof",
"fflush",
"fgetc",
"fgetcsv",
"fgets",
"fgetss",
"file",
"__FILE__",
"fileatime",
"filectime",
"file_exists",
"file_get_contents",
"filegroup",
"fileinode",
"filemtime",
"fileowner",
"fileperms",
"filepro",
"filepro_fieldcount",
"filepro_fieldname",
"filepro_fieldtype",
"filepro_fieldwidth",
"filepro_retrieve",
"filepro_rowcount",
"_FILES",
"filesize",
"filetype",
"find",
"first_child",
"floatval",
"flock",
"floor",
"flush",
"fmod",
"fnmatch",
"fopen",
"for",
"foreach",
"fpassthru",
"fprintf",
"fputs",
"fread",
"frenchtojd",
"fribidi_log2vis",
"fscanf",
"fseek",
"fsockopen",
"fstat",
"ftell",
"ftok",
"ftp_cdup",
"ftp_chdir",
"ftp_close",
"ftp_connect",
"ftp_delete",
"ftp_exec",
"ftp_fget",
"ftp_fput",
"ftp_get",
"ftp_get_option",
"ftp_login",
"ftp_mdtm",
"ftp_mkdir",
"ftp_nb_continue",
"ftp_nb_fget",
"ftp_nb_fput",
"ftp_nb_get",
"ftp_nb_put",
"ftp_nlist",
"ftp_pasv",
"ftp_put",
"ftp_pwd",
"ftp_quit",
"ftp_rawlist",
"ftp_rename",
"ftp_rmdir",
"ftp_set_option",
"ftp_site",
"ftp_size",
"ftp_ssl_connect",
"ftp_systype",
"ftruncate",
"ftstat",
"func_get_arg",
"func_get_args",
"func_num_args",
"function",
"function_exists",
"fwrite",
"GATEWAY_INTERFACE",
"gd_info",
"_GET",
"getallheaders",
"get_attribute",
"get_attribute_node",
"get_browser",
"get_cfg_var",
"get_class",
"get_class_methods",
"get_class_vars",
"get_content",
"get_current_user",
"getcwd",
"getdate",
"get_declared_classes",
"get_defined_constants",
"get_defined_functions",
"get_defined_vars",
"get_element_by_id",
"get_elements_by_tagname",
"getenv",
"get_extension_funcs",
"getHeight",
"gethostbyaddr",
"gethostbyname",
"gethostbynamel",
"get_html_translation_table",
"getimagesize",
"get_included_files",
"get_include_path",
"getlastmod",
"get_loaded_extensions",
"get_magic_quotes_gpc",
"get_magic_quotes_runtime",
"get_meta_tags",
"getmxrr",
"getmygid",
"getmyinode",
"getmypid",
"getmyuid",
"get_object_vars",
"getopt",
"get_parent_class",
"getprotobyname",
"getprotobynumber",
"getrandmax",
"get_required_files",
"get_resource_type",
"getrusage",
"getservbyname",
"getservbyport",
"getshape1",
"getshape2",
"gettext",
"gettimeofday",
"gettype",
"getwidth",
"getWidth",
"glob",
"global",
"GLOBALS",
"gmdate",
"gmmktime",
"gmp_abs",
"gmp_add",
"gmp_and",
"gmp_clrbit",
"gmp_cmp",
"gmp_com",
"gmp_div",
"gmp_divexact",
"gmp_div_q",
"gmp_div_qr",
"gmp_div_r",
"gmp_fact",
"gmp_gcd",
"gmp_gcdext",
"gmp_hamdist",
"gmp_init",
"gmp_intval",
"gmp_invert",
"gmp_jacobi",
"gmp_legendre",
"gmp_mod",
"gmp_mul",
"gmp_neg",
"gmp_or",
"gmp_perfect_square",
"gmp_popcount",
"gmp_pow",
"gmp_powm",
"gmp_prob_prime",
"gmp_random",
"gmp_scan0",
"gmp_scan1",
"gmp_setbit",
"gmp_sign",
"gmp_sqrt",
"gmp_sqrtrm",
"gmp_strval",
"gmp_sub",
"gmp_xor",
"gmstrftime",
"gregoriantojd",
"gzclose",
"gzcompress",
"gzdeflate",
"gzencode",
"gzeof",
"gzfile",
"gzgetc",
"gzgets",
"gzgetss",
"gzinflate",
"gzopen",
"gzpassthru",
"gzputs",
"gzread",
"gzrewind",
"gzseek",
"gztell",
"gzuncompress",
"gzwrite",
"has_attribute",
"has_attributess",
"has_child_nodes",
"header",
"headers_sent",
"hebrev",
"hebrevc",
"hexdec",
"highlight_file",
"highlight_string",
"html_dump_mem",
"htmlentities",
"html_entity_decode",
"htmlspecialchars",
"HTTP_ACCEPT",
"HTTP_ACCEPT_CHARSET",
"HTTP_ACCEPT_LANGUAGE",
"HTTP_CONNECTION",
"HTTP_COOKIE_VARS",
"HTTP_ENCODING",
"HTTP_ENV_VARS",
"HTTP_GET_VARS",
"HTTP_HOST",
"HTTP_POST_FILES",
"HTTP_POST_VARS",
"HTTP_RAW_POST_DATA",
"HTTP_REFERER",
"HTTP_SERVER_VARS",
"HTTP_SESSION_VARS",
"HTTP_STATE_VARS",
"HTTP_USER_AGENT",
"hw_api_attribute",
"hw_api_content",
"hwapi_hgcsp",
"hw_api_object",
"hw_Array2Objrec",
"hw_changeobject",
"hw_Children",
"hw_ChildrenObj",
"hw_Close",
"hw_Connect",
"hw_connection_info",
"hw_Cp",
"hw_Deleteobject",
"hw_DocByAnchor",
"hw_DocByAnchorObj",
"hw_Document_Attributes",
"hw_Document_BodyTag",
"hw_Document_Content",
"hw_Document_SetContent",
"hw_Document_Size",
"hw_dummy",
"hw_EditText",
"hw_Error",
"hw_ErrorMsg",
"hw_Free_Document",
"hw_GetAnchors",
"hw_GetAnchorsObj",
"hw_GetAndLock",
"hw_GetChildColl",
"hw_GetChildCollObj",
"hw_GetChildDocColl",
"hw_GetChildDocCollObj",
"hw_GetObject",
"hw_GetObjectByQuery",
"hw_GetObjectByQueryColl",
"hw_GetObjectByQueryCollObj",
"hw_GetObjectByQueryObj",
"hw_GetParents",
"hw_GetParentsObj",
"hw_getrellink",
"hw_GetRemote",
"hw_GetRemoteChildren",
"hw_GetSrcByDestObj",
"hw_GetText",
"hw_getusername",
"hw_Identify",
"hw_InCollections",
"hw_Info",
"hw_InsColl",
"hw_InsDoc",
"hw_insertanchors",
"hw_InsertDocument",
"hw_InsertObject",
"hw_mapid",
"hw_Modifyobject",
"hw_Mv",
"hw_New_Document",
"hw_Objrec2Array",
"hw_Output_Document",
"hw_pConnect",
"hw_PipeDocument",
"hw_Root",
"hw_setlinkroot",
"hw_stat",
"hwstat",
"hw_Unlock",
"hw_Who",
"hypot",
"ibase_blob_add",
"ibase_blob_cancel",
"ibase_blob_close",
"ibase_blob_create",
"ibase_blob_echo",
"ibase_blob_get",
"ibase_blob_import",
"ibase_blob_info",
"ibase_blob_open",
"ibase_close",
"ibase_commit",
"ibase_connect",
"ibase_errmsg",
"ibase_execute",
"ibase_fetch_object",
"ibase_fetch_row",
"ibase_field_info",
"ibase_free_query",
"ibase_free_result",
"ibase_num_fields",
"ibase_pconnect",
"ibase_prepare",
"ibase_query",
"ibase_rollback",
"ibase_timefmt",
"ibase_trans",
"iconv",
"iconv_get_encoding",
"iconv_set_encoding",
"identify",
"if",
"ifx_affected_rows",
"ifx_blobinfile_mode",
"ifx_byteasvarchar",
"ifx_close",
"ifx_connect",
"ifx_copy_blob",
"ifx_create_blob",
"ifx_create_char",
"ifx_do",
"ifx_error",
"ifx_errormsg",
"ifx_fetch_row",
"ifx_fieldproperties",
"ifx_fieldtypes",
"ifx_free_blob",
"ifx_free_char",
"ifx_free_result",
"ifx_get_blob",
"ifx_get_char",
"ifx_getsqlca",
"ifx_htmltbl_result",
"ifx_nullformat",
"ifx_num_fields",
"ifx_num_rows",
"ifx_pconnect",
"ifx_prepare",
"ifx_query",
"ifx_textasvarchar",
"ifx_update_blob",
"ifx_update_char",
"ifxus_close_slob",
"ifxus_create_slob",
"ifxus_free_slob",
"ifxus_open_slob",
"ifxus_read_slob",
"ifxus_seek_slob",
"ifxus_tell_slob",
"ifxus_write_slob",
"ignore_user_abort",
"image2wbmp",
"imagealphablending",
"imagearc",
"imagechar",
"imagecharup",
"imagecolorallocate",
"imagecolorallocatealpha",
"imagecolorat",
"imagecolorclosest",
"imagecolorclosestalpha",
"imagecolorclosesthwb",
"imagecolordeallocate",
"imagecolorexact",
"imagecolorexactalpha",
"imagecolorresolve",
"imagecolorresolvealpha",
"imagecolorset",
"imagecolorsforindex",
"imagecolorstotal",
"imagecolortransparent",
"imagecopy",
"imagecopymerge",
"imagecopymergegray",
"imagecopyresampled",
"imagecopyresized",
"imagecreate",
"imagecreatefromgd",
"imagecreatefromgd2",
"imagecreatefromgd2part",
"imagecreatefromgif",
"imagecreatefromjpeg",
"imagecreatefrompng",
"imagecreatefromstring",
"imagecreatefromwbmp",
"imagecreatefromxbm",
"imagecreatefromxpm",
"imagecreatetruecolor",
"imagedashedline",
"imagedestroy",
"imageellipse",
"imagefill",
"imagefilledarc",
"imagefilledellipse",
"imagefilledpolygon",
"imagefilledrectangle",
"imagefilltoborder",
"imagefontheight",
"imagefontwidth",
"imageftbbox",
"imagefttext",
"imagegammacorrect",
"imagegd",
"imagegd2",
"imagegif",
"imageinterlace",
"imagejpeg",
"imageline",
"imageloadfont",
"imagepalettecopy",
"imagepng",
"imagepolygon",
"imagepsbbox",
"imagepscopyfont",
"imagepsencodefont",
"imagepsextendfont",
"imagepsfreefont",
"imagepsloadfont",
"imagepsslantfont",
"imagepstext",
"imagerectangle",
"imagerotate",
"imagesetbrush",
"imagesetpixel",
"imagesetstyle",
"imagesetthickness",
"imagesettile",
"imagestring",
"imagestringup",
"imagesx",
"imagesy",
"imagetruecolortopalette",
"imagettfbbox",
"imagettftext",
"imagetypes",
"image_type_to_mime_type",
"imagewbmp",
"imap_8bit",
"imap_alerts",
"imap_append",
"imap_base64",
"imap_binary",
"imap_body",
"imap_bodystruct",
"imap_check",
"imap_clearflag_full",
"imap_close",
"imap_createmailbox",
"imap_delete",
"imap_deletemailbox",
"imap_errors",
"imap_expunge",
"imap_fetchbody",
"imap_fetchheader",
"imap_fetch_overview",
"imap_fetchstructure",
"imap_getmailboxes",
"imap_get_quota",
"imap_get_quotaroot",
"imap_getsubscribed",
"imap_header",
"imap_headerinfo",
"imap_headers",
"imap_last_error",
"imap_list",
"imap_listmailbox",
"imap_listscan",
"imap_listsubscribed",
"imap_lsub",
"imap_mail",
"imap_mailboxmsginfo",
"imap_mail_compose",
"imap_mail_copy",
"imap_mail_move",
"imap_mime_header_decode",
"imap_msgno",
"imap_num_msg",
"imap_num_recent",
"imap_open",
"imap_ping",
"imap_qprint",
"imap_renamemailbox",
"imap_reopen",
"imap_rfc822_parse_adrlist",
"imap_rfc822_parse_headers",
"imap_rfc822_write_address",
"imap_scanmailbox",
"imap_search",
"imap_setacl",
"imap_setflag_full",
"imap_set_quota",
"imap_sort",
"imap_status",
"imap_subscribe",
"imap_thread",
"imap_uid",
"imap_undelete",
"imap_unsubscribe",
"imap_utf7_decode",
"imap_utf7_encode",
"imap_utf8",
"implements",
"implode",
"import_request_variables",
"in_array",
"include",
"include_once",
"info",
"ingres_autocommit",
"ingres_close",
"ingres_commit",
"ingres_connect",
"ingres_fetch_array",
"ingres_fetch_object",
"ingres_fetch_row",
"ingres_field_length",
"ingres_field_name",
"ingres_field_nullable",
"ingres_field_precision",
"ingres_field_scale",
"ingres_field_type",
"ingres_num_fields",
"ingres_num_rows",
"ingres_pconnect",
"ingres_query",
"ingres_rollback",
"ini_alter",
"ini_get",
"ini_get_all",
"ini_restore",
"ini_set",
"insert",
"insertanchor",
"insert_before",
"insertcollection",
"insertdocument",
"int",
"interface",
"internal_subset",
"intval",
"ip2long",
"iptcembed",
"iptcparse",
"ircg_channel_mode",
"ircg_disconnect",
"ircg_fetch_error_msg",
"ircg_get_username",
"ircg_html_encode",
"ircg_ignore_add",
"ircg_ignore_del",
"ircg_is_conn_alive",
"ircg_join",
"ircg_kick",
"ircg_lookup_format_messages",
"ircg_msg",
"ircg_nick",
"ircg_nickname_escape",
"ircg_nickname_unescape",
"ircg_notice",
"ircg_part",
"ircg_pconnect",
"ircg_register_format_messages",
"ircg_set_current",
"ircg_set_file",
"ircg_set_on_die",
"ircg_topic",
"ircg_whois",
"is_a",
"is_array",
"is_blank_node",
"is_bool",
"is_callable",
"is_dir",
"is_double",
"is_executable",
"is_file",
"is_finite",
"is_float",
"is_infinite",
"is_int",
"is_integer",
"is_link",
"is_long",
"is_nan",
"is_null",
"is_numeric",
"is_object",
"is_readable",
"is_real",
"is_resource",
"is_scalar",
"isset",
"is_string",
"is_subclass_of",
"is_uploaded_file",
"is_writable",
"is_writeable",
"java_last_exception_clear",
"java_last_exception_get",
"jddayofweek",
"jdmonthname",
"jdtofrench",
"jdtogregorian",
"jdtojewish",
"jdtojulian",
"jdtounix",
"jewishtojd",
"join",
"jpeg2wbmp",
"juliantojd",
"key",
"krsort",
"ksort",
"langdepvalue",
"last_child",
"lcg_value",
"ldap_8859_to_t61",
"ldap_add",
"ldap_bind",
"ldap_close",
"ldap_compare",
"ldap_connect",
"ldap_count_entries",
"ldap_delete",
"ldap_dn2ufn",
"ldap_err2str",
"ldap_errno",
"ldap_error",
"ldap_explode_dn",
"ldap_first_attribute",
"ldap_first_entry",
"ldap_first_reference",
"ldap_free_result",
"ldap_get_attributes",
"ldap_get_dn",
"ldap_get_entries",
"ldap_get_option",
"ldap_get_values",
"ldap_get_values_len",
"ldap_list",
"ldap_mod_add",
"ldap_mod_del",
"ldap_modify",
"ldap_mod_replace",
"ldap_next_attribute",
"ldap_next_entry",
"ldap_next_reference",
"ldap_parse_reference",
"ldap_parse_result",
"ldap_read",
"ldap_rename",
"ldap_search",
"ldap_set_option",
"ldap_set_rebind_proc",
"ldap_sort",
"ldap_start_tls",
"ldap_t61_to_8859",
"ldap_unbind",
"levenshtein",
"__LINE__",
"link",
"linkinfo",
"list",
"localeconv",
"localtime",
"lock",
"log",
"log10",
"log1p",
"long2ip",
"lstat",
"ltrim",
"mail",
"mailparse_determine_best_xfer_encoding",
"mailparse_msg_create",
"mailparse_msg_extract_part",
"mailparse_msg_extract_part_file",
"mailparse_msg_free",
"mailparse_msg_get_part",
"mailparse_msg_get_part_data",
"mailparse_msg_get_structure",
"mailparse_msg_parse",
"mailparse_msg_parse_file",
"mailparse_rfc822_parse_addresses",
"mailparse_stream_encode",
"mailparse_uudecode_all",
"main",
"max",
"mb_convert_case",
"mb_convert_encoding",
"mb_convert_kana",
"mb_convert_variables",
"mb_decode_mimeheader",
"mb_decode_numericentity",
"mb_detect_encoding",
"mb_detect_order",
"mb_encode_mimeheader",
"mb_encode_numericentity",
"mb_ereg",
"mb_eregi",
"mb_eregi_replace",
"mb_ereg_match",
"mb_ereg_replace",
"mb_ereg_search",
"mb_ereg_search_getpos",
"mb_ereg_search_getregs",
"mb_ereg_search_init",
"mb_ereg_search_pos",
"mb_ereg_search_regs",
"mb_ereg_search_setpos",
"mb_get_info",
"mb_http_input",
"mb_http_output",
"mb_internal_encoding",
"mb_language",
"mb_output_handler",
"mb_parse_str",
"mb_preferred_mime_name",
"mb_regex_encoding",
"mb_regex_set_options",
"mb_send_mail",
"mb_split",
"mb_strcut",
"mb_strimwidth",
"mb_strlen",
"mb_strpos",
"mb_strrpos",
"mb_strtolower",
"mb_strtoupper",
"mb_strwidth",
"mb_substitute_character",
"mb_substr",
"mb_substr_count",
"mcal_append_event",
"mcal_close",
"mcal_create_calendar",
"mcal_date_compare",
"mcal_date_valid",
"mcal_day_of_week",
"mcal_day_of_year",
"mcal_days_in_month",
"mcal_delete_calendar",
"mcal_delete_event",
"mcal_event_add_attribute",
"mcal_event_init",
"mcal_event_set_alarm",
"mcal_event_set_category",
"mcal_event_set_class",
"mcal_event_set_description",
"mcal_event_set_end",
"mcal_event_set_recur_daily",
"mcal_event_set_recur_monthly_mday",
"mcal_event_set_recur_monthly_wday",
"mcal_event_set_recur_none",
"mcal_event_set_recur_weekly",
"mcal_event_set_recur_yearly",
"mcal_event_set_start",
"mcal_event_set_title",
"mcal_expunge",
"mcal_fetch_current_stream_event",
"mcal_fetch_event",
"mcal_is_leap_year",
"mcal_list_alarms",
"mcal_list_events",
"mcal_next_recurrence",
"mcal_open",
"mcal_popen",
"mcal_rename_calendar",
"mcal_reopen",
"mcal_snooze",
"mcal_store_event",
"mcal_time_valid",
"mcal_week_of_year",
"mcrypt_cbc",
"mcrypt_cfb",
"mcrypt_create_iv",
"mcrypt_decrypt",
"mcrypt_ecb",
"mcrypt_enc_get_algorithms_name",
"mcrypt_enc_get_block_size",
"mcrypt_enc_get_iv_size",
"mcrypt_enc_get_key_size",
"mcrypt_enc_get_modes_name",
"mcrypt_enc_get_supported_key_sizes",
"mcrypt_enc_is_block_algorithm",
"mcrypt_enc_is_block_algorithm_mode",
"mcrypt_enc_is_block_mode",
"mcrypt_encrypt",
"mcrypt_enc_self_test",
"mcrypt_generic",
"mcrypt_generic_deinit",
"mcrypt_generic_end",
"mcrypt_generic_init",
"mcrypt_get_block_size",
"mcrypt_get_cipher_name",
"mcrypt_get_iv_size",
"mcrypt_get_key_size",
"mcrypt_list_algorithms",
"mcrypt_list_modes",
"mcrypt_module_close",
"mcrypt_module_get_algo_block_size",
"mcrypt_module_get_algo_key_size",
"mcrypt_module_get_supported_key_sizes",
"mcrypt_module_is_block_algorithm",
"mcrypt_module_is_block_algorithm_mode",
"mcrypt_module_is_block_mode",
"mcrypt_module_open",
"mcrypt_module_self_test",
"mcrypt_ofb",
"mcve_adduser",
"mcve_adduserarg",
"mcve_bt",
"mcve_checkstatus",
"mcve_chkpwd",
"mcve_chngpwd",
"mcve_completeauthorizations",
"mcve_connect",
"mcve_connectionerror",
"mcve_deleteresponse",
"mcve_deletetrans",
"mcve_deleteusersetup",
"mcve_deluser",
"mcve_destroyconn",
"mcve_destroyengine",
"mcve_disableuser",
"mcve_edituser",
"mcve_enableuser",
"mcve_force",
"mcve_getcell",
"mcve_getcellbynum",
"mcve_getcommadelimited",
"mcve_getheader",
"mcve_getuserarg",
"mcve_getuserparam",
"mcve_gft",
"mcve_gl",
"mcve_gut",
"mcve_initconn",
"mcve_initengine",
"mcve_initusersetup",
"mcve_iscommadelimited",
"mcve_liststats",
"mcve_listusers",
"mcve_maxconntimeout",
"mcve_monitor",
"mcve_numcolumns",
"mcve_numrows",
"mcve_override",
"mcve_parsecommadelimited",
"mcve_ping",
"mcve_preauth",
"mcve_preauthcompletion",
"mcve_qc",
"mcve_responseparam",
"mcve_return",
"mcve_returncode",
"mcve_returnstatus",
"mcve_sale",
"mcve_setblocking",
"mcve_setdropfile",
"mcve_setip",
"mcve_setssl",
"mcve_settimeout",
"mcve_settle",
"mcve_text_avs",
"mcve_text_code",
"mcve_text_cv",
"mcve_transactionauth",
"mcve_transactionavs",
"mcve_transactionbatch",
"mcve_transactioncv",
"mcve_transactionid",
"mcve_transactionitem",
"mcve_transactionssent",
"mcve_transactiontext",
"mcve_transinqueue",
"mcve_transnew",
"mcve_transparam",
"mcve_transsend",
"mcve_ub",
"mcve_uwait",
"mcve_verifyconnection",
"mcve_verifysslcert",
"mcve_void",
"md5",
"md5_file",
"mdecrypt_generic",
"memory_get_usage",
"metaphone",
"method_exists",
"mhash",
"mhash_count",
"mhash_get_block_size",
"mhash_get_hash_name",
"mhash_keygen_s2k",
"microtime",
"mime_content_type",
"mimetype",
"min",
"ming_setcubicthreshold",
"ming_setscale",
"ming_useswfversion",
"mkdir",
"mktime",
"money_format",
"move",
"movePen",
"movePenTo",
"moveTo",
"move_uploaded_file",
"msession_connect",
"msession_count",
"msession_create",
"msession_destroy",
"msession_disconnect",
"msession_find",
"msession_get",
"msession_get_array",
"msession_getdata",
"msession_inc",
"msession_list",
"msession_listvar",
"msession_lock",
"msession_plugin",
"msession_randstr",
"msession_set",
"msession_set_array",
"msession_setdata",
"msession_timeout",
"msession_uniq",
"msession_unlock",
"msg_get_queue",
"msg_receive",
"msg_remove_queue",
"msg_send",
"msg_set_queue",
"msg_stat_queue",
"msql",
"msql_affected_rows",
"msql_close",
"msql_connect",
"msql_create_db",
"msql_createdb",
"msql_data_seek",
"msql_dbname",
"msql_drop_db",
"msql_dropdb",
"msql_error",
"msql_fetch_array",
"msql_fetch_field",
"msql_fetch_object",
"msql_fetch_row",
"msql_fieldflags",
"msql_fieldlen",
"msql_fieldname",
"msql_field_seek",
"msql_fieldtable",
"msql_fieldtype",
"msql_free_result",
"msql_freeresult",
"msql_list_dbs",
"msql_listdbs",
"msql_list_fields",
"msql_listfields",
"msql_list_tables",
"msql_listtables",
"msql_num_fields",
"msql_numfields",
"msql_num_rows",
"msql_numrows",
"msql_pconnect",
"msql_query",
"msql_regcase",
"msql_result",
"msql_select_db",
"msql_selectdb",
"msql_tablename",
"mssql_bind",
"mssql_close",
"mssql_connect",
"mssql_data_seek",
"mssql_execute",
"mssql_fetch_array",
"mssql_fetch_assoc",
"mssql_fetch_batch",
"mssql_fetch_field",
"mssql_fetch_object",
"mssql_fetch_row",
"mssql_field_length",
"mssql_field_name",
"mssql_field_seek",
"mssql_field_type",
"mssql_free_result",
"mssql_free_statement",
"mssql_get_last_message",
"mssql_guid_string",
"mssql_init",
"mssql_min_error_severity",
"mssql_min_message_severity",
"mssql_next_result",
"mssql_num_fields",
"mssql_num_rows",
"mssql_pconnect",
"mssql_query",
"mssql_result",
"mssql_rows_affected",
"mssql_select_db",
"mt_getrandmax",
"mt_rand",
"mt_srand",
"multColor",
"muscat_close",
"muscat_get",
"muscat_give",
"muscat_setup",
"muscat_setup_net",
"mysql_affected_rows",
"mysql_change_user",
"mysql_client_encoding",
"mysql_close",
"mysql_connect",
"mysql_create_db",
"mysql_data_seek",
"mysql_db_name",
"mysql_db_query",
"mysql_drop_db",
"mysql_errno",
"mysql_error",
"mysql_escape_string",
"mysql_fetch_array",
"mysql_fetch_assoc",
"mysql_fetch_field",
"mysql_fetch_lengths",
"mysql_fetch_object",
"mysql_fetch_row",
"mysql_field_flags",
"mysql_field_len",
"mysql_field_name",
"mysql_field_seek",
"mysql_field_table",
"mysql_field_type",
"mysql_free_result",
"mysql_get_client_info",
"mysql_get_host_info",
"mysql_get_proto_info",
"mysql_get_server_info",
"mysql_info",
"mysql_insert_id",
"mysql_list_dbs",
"mysql_list_fields",
"mysql_list_processes",
"mysql_list_tables",
"mysql_num_fields",
"mysql_num_rows",
"mysql_pconnect",
"mysql_ping",
"mysql_query",
"mysql_real_escape_string",
"mysql_result",
"mysql_select_db",
"mysql_stat",
"mysql_tablename",
"mysql_thread_id",
"mysql_unbuffered_query",
"name",
"natcasesort",
"natsort",
"ncurses_addch",
"ncurses_addchnstr",
"ncurses_addchstr",
"ncurses_addnstr",
"ncurses_addstr",
"ncurses_assume_default_colors",
"ncurses_attroff",
"ncurses_attron",
"ncurses_attrset",
"ncurses_baudrate",
"ncurses_beep",
"ncurses_bkgd",
"ncurses_bkgdset",
"ncurses_border",
"ncurses_can_change_color",
"ncurses_cbreak",
"ncurses_clear",
"ncurses_clrtobot",
"ncurses_clrtoeol",
"ncurses_color_set",
"ncurses_curs_set",
"ncurses_define_key",
"ncurses_def_prog_mode",
"ncurses_def_shell_mode",
"ncurses_delay_output",
"ncurses_delch",
"ncurses_deleteln",
"ncurses_delwin",
"ncurses_doupdate",
"ncurses_echo",
"ncurses_echochar",
"ncurses_end",
"ncurses_erase",
"ncurses_erasechar",
"ncurses_filter",
"ncurses_flash",
"ncurses_flushinp",
"ncurses_getch",
"ncurses_getmouse",
"ncurses_halfdelay",
"ncurses_has_colors",
"ncurses_has_ic",
"ncurses_has_il",
"ncurses_has_key",
"ncurses_hline",
"ncurses_inch",
"ncurses_init",
"ncurses_init_color",
"ncurses_init_pair",
"ncurses_insch",
"ncurses_insdelln",
"ncurses_insertln",
"ncurses_insstr",
"ncurses_instr",
"ncurses_isendwin",
"ncurses_keyok",
"ncurses_killchar",
"ncurses_longname",
"ncurses_mouseinterval",
"ncurses_mousemask",
"ncurses_move",
"ncurses_mvaddch",
"ncurses_mvaddchnstr",
"ncurses_mvaddchstr",
"ncurses_mvaddnstr",
"ncurses_mvaddstr",
"ncurses_mvcur",
"ncurses_mvdelch",
"ncurses_mvgetch",
"ncurses_mvhline",
"ncurses_mvinch",
"ncurses_mvvline",
"ncurses_mvwaddstr",
"ncurses_napms",
"ncurses_newwin",
"ncurses_nl",
"ncurses_nocbreak",
"ncurses_noecho",
"ncurses_nonl",
"ncurses_noqiflush",
"ncurses_noraw",
"ncurses_putp",
"ncurses_qiflush",
"ncurses_raw",
"ncurses_refresh",
"ncurses_resetty",
"ncurses_savetty",
"ncurses_scr_dump",
"ncurses_scr_init",
"ncurses_scrl",
"ncurses_scr_restore",
"ncurses_scr_set",
"ncurses_slk_attr",
"ncurses_slk_attroff",
"ncurses_slk_attron",
"ncurses_slk_attrset",
"ncurses_slk_clear",
"ncurses_slk_color",
"ncurses_slk_init",
"ncurses_slk_noutrefresh",
"ncurses_slk_refresh",
"ncurses_slk_restore",
"ncurses_slk_touch",
"ncurses_standend",
"ncurses_standout",
"ncurses_start_color",
"ncurses_termattrs",
"ncurses_termname",
"ncurses_timeout",
"ncurses_typeahead",
"ncurses_ungetch",
"ncurses_ungetmouse",
"ncurses_use_default_colors",
"ncurses_use_env",
"ncurses_use_extended_names",
"ncurses_vidattr",
"ncurses_vline",
"ncurses_wrefresh",
"new",
"next",
"nextframe",
"next_sibling",
"ngettext",
"nl2br",
"nl_langinfo",
"node_name",
"node_type",
"node_value",
"notations",
"notes_body",
"notes_copy_db",
"notes_create_db",
"notes_create_note",
"notes_drop_db",
"notes_find_note",
"notes_header_info",
"notes_list_msgs",
"notes_mark_read",
"notes_mark_unread",
"notes_nav_create",
"notes_search",
"notes_unread",
"notes_version",
"NULL",
"number_format",
"ob_clean",
"ob_end_clean",
"ob_end_flush",
"ob_flush",
"ob_get_contents",
"ob_get_length",
"ob_get_level",
"ob_get_status",
"ob_gzhandler",
"ob_iconv_handler",
"ob_implicit_flush",
"object",
"objectbyanchor",
"ob_start",
"ocibindbyname",
"ocicancel",
"OCICollAppend",
"ocicollassign",
"ocicollassignelem",
"ocicollgetelem",
"ocicollmax",
"ocicollsize",
"ocicolltrim",
"ocicolumnisnull",
"ocicolumnname",
"ocicolumnprecision",
"ocicolumnscale",
"ocicolumnsize",
"ocicolumntype",
"ocicolumntyperaw",
"ocicommit",
"ocidefinebyname",
"ocierror",
"ociexecute",
"ocifetch",
"ocifetchinto",
"ocifetchstatement",
"ocifreecollection",
"ocifreecursor",
"OCIFreeDesc",
"ocifreestatement",
"ociinternaldebug",
"ociloadlob",
"ocilogoff",
"ocilogon",
"ocinewcollection",
"ocinewcursor",
"ocinewdescriptor",
"ocinlogon",
"ocinumcols",
"ociparse",
"ociplogon",
"ociresult",
"ocirollback",
"ocirowcount",
"ocisavelob",
"ocisavelobfile",
"ociserverversion",
"ocisetprefetch",
"ocistatementtype",
"ociwritelobtofile",
"octdec",
"odbc_autocommit",
"odbc_binmode",
"odbc_close",
"odbc_close_all",
"odbc_columnprivileges",
"odbc_columns",
"odbc_commit",
"odbc_connect",
"odbc_cursor",
"odbc_data_source",
"odbc_do",
"odbc_error",
"odbc_errormsg",
"odbc_exec",
"odbc_execute",
"odbc_fetch_array",
"odbc_fetch_into",
"odbc_fetch_object",
"odbc_fetch_row",
"odbc_field_len",
"odbc_field_name",
"odbc_field_num",
"odbc_field_precision",
"odbc_field_scale",
"odbc_field_type",
"odbc_foreignkeys",
"odbc_free_result",
"odbc_gettypeinfo",
"odbc_longreadlen",
"odbc_next_result",
"odbc_num_fields",
"odbc_num_rows",
"odbc_pconnect",
"odbc_prepare",
"odbc_primarykeys",
"odbc_procedurecolumns",
"odbc_procedures",
"odbc_result",
"odbc_result_all",
"odbc_rollback",
"odbc_setoption",
"odbc_specialcolumns",
"odbc_statistics",
"odbc_tableprivileges",
"odbc_tables",
"opendir",
"openlog",
"openssl_csr_export",
"openssl_csr_export_to_file",
"openssl_csr_new",
"openssl_csr_sign",
"openssl_error_string",
"openssl_free_key",
"openssl_get_privatekey",
"openssl_get_publickey",
"openssl_open",
"openssl_pkcs7_decrypt",
"openssl_pkcs7_encrypt",
"openssl_pkcs7_sign",
"openssl_pkcs7_verify",
"openssl_pkey_export",
"openssl_pkey_export_to_file",
"openssl_pkey_get_private",
"openssl_pkey_get_public",
"openssl_pkey_new",
"openssl_private_decrypt",
"openssl_private_encrypt",
"openssl_public_decrypt",
"openssl_public_encrypt",
"openssl_seal",
"openssl_sign",
"openssl_verify",
"openssl_x509_check_private_key",
"openssl_x509_checkpurpose",
"openssl_x509_export",
"openssl_x509_export_to_file",
"openssl_x509_free",
"openssl_x509_parse",
"openssl_x509_read",
"ora_bind",
"ora_close",
"ora_columnname",
"ora_columnsize",
"ora_columntype",
"ora_commit",
"ora_commitoff",
"ora_commiton",
"ora_do",
"ora_error",
"ora_errorcode",
"ora_exec",
"ora_fetch",
"ora_fetch_into",
"ora_getcolumn",
"ora_logoff",
"ora_logon",
"ora_numcols",
"ora_numrows",
"ora_open",
"ora_parse",
"ora_plogon",
"ora_rollback",
"ord",
"output",
"overload",
"ovrimos_close",
"ovrimos_commit",
"ovrimos_connect",
"ovrimos_cursor",
"ovrimos_exec",
"ovrimos_execute",
"ovrimos_fetch_into",
"ovrimos_fetch_row",
"ovrimos_field_len",
"ovrimos_field_name",
"ovrimos_field_num",
"ovrimos_field_type",
"ovrimos_free_result",
"ovrimos_longreadlen",
"ovrimos_num_fields",
"ovrimos_num_rows",
"ovrimos_prepare",
"ovrimos_result",
"ovrimos_result_all",
"ovrimos_rollback",
"owner_document",
"pack",
"parent_node",
"parents",
"parse_ini_file",
"parse_str",
"parse_url",
"passthru",
"pathinfo",
"PATH_TRANSLATED",
"pclose",
"pcntl_exec",
"pcntl_fork",
"pcntl_signal",
"pcntl_waitpid",
"pcntl_wexitstatus",
"pcntl_wifexited",
"pcntl_wifsignaled",
"pcntl_wifstopped",
"pcntl_wstopsig",
"pcntl_wtermsig",
"pdf_add_annotation",
"pdf_add_bookmark",
"pdf_add_launchlink",
"pdf_add_locallink",
"pdf_add_note",
"pdf_add_outline",
"pdf_add_pdflink",
"pdf_add_thumbnail",
"pdf_add_weblink",
"pdf_arc",
"pdf_arcn",
"pdf_attach_file",
"pdf_begin_page",
"pdf_begin_pattern",
"pdf_begin_template",
"pdf_circle",
"pdf_clip",
"pdf_close",
"pdf_close_image",
"pdf_closepath",
"pdf_closepath_fill_stroke",
"pdf_closepath_stroke",
"pdf_close_pdi",
"pdf_close_pdi_page",
"pdf_concat",
"pdf_continue_text",
"pdf_curveto",
"pdf_delete",
"pdf_end_page",
"pdf_endpath",
"pdf_end_pattern",
"pdf_end_template",
"pdf_fill",
"pdf_fill_stroke",
"pdf_findfont",
"pdf_get_buffer",
"pdf_get_font",
"pdf_get_fontname",
"pdf_get_fontsize",
"pdf_get_image_height",
"pdf_get_image_width",
"pdf_get_majorversion",
"pdf_get_minorversion",
"pdf_get_parameter",
"pdf_get_pdi_parameter",
"pdf_get_pdi_value",
"pdf_get_value",
"pdf_initgraphics",
"pdf_lineto",
"pdf_makespotcolor",
"pdf_moveto",
"pdf_new",
"pdf_open",
"pdf_open_CCITT",
"pdf_open_file",
"pdf_open_gif",
"pdf_open_image",
"pdf_open_image_file",
"pdf_open_jpeg",
"pdf_open_memory_image",
"pdf_open_pdi",
"pdf_open_pdi_page",
"pdf_open_png",
"pdf_open_tiff",
"pdf_place_image",
"pdf_place_pdi_page",
"pdf_rect",
"pdf_restore",
"pdf_rotate",
"pdf_save",
"pdf_scale",
"pdf_set_border_color",
"pdf_set_border_dash",
"pdf_set_border_style",
"pdf_set_char_spacing",
"pdf_setcolor",
"pdf_setdash",
"pdf_set_duration",
"pdf_setflat",
"pdf_set_font",
"pdf_setfont",
"pdf_setgray",
"pdf_setgray_fill",
"pdf_setgray_stroke",
"pdf_set_horiz_scaling",
"pdf_set_info",
"pdf_set_info_author",
"pdf_set_info_creator",
"pdf_set_info_keywords",
"pdf_set_info_subject",
"pdf_set_info_title",
"pdf_set_leading",
"pdf_setlinecap",
"pdf_setlinejoin",
"pdf_setlinewidth",
"pdf_setmatrix",
"pdf_setmiterlimit",
"pdf_set_parameter",
"pdf_setpolydash",
"pdf_setrgbcolor",
"pdf_setrgbcolor_fill",
"pdf_setrgbcolor_stroke",
"pdf_set_text_matrix",
"pdf_set_text_pos",
"pdf_set_text_rendering",
"pdf_set_text_rise",
"pdf_set_value",
"pdf_set_word_spacing",
"pdf_show",
"pdf_show_boxed",
"pdf_show_xy",
"pdf_skew",
"pdf_stringwidth",
"pdf_stroke",
"pdf_translate",
"PEAR_EXTENSION_DIR",
"PEAR_INSTALL_DIR",
"pfpro_cleanup",
"pfpro_init",
"pfpro_process",
"pfpro_process_raw",
"pfpro_version",
"pfsockopen",
"pg_affected_rows",
"pg_cancel_query",
"pg_client_encoding",
"pg_close",
"pg_connect",
"pg_connection_busy",
"pg_connection_reset",
"pg_connection_status",
"pg_convert",
"pg_copy_from",
"pg_copy_to",
"pg_dbname",
"pg_delete",
"pg_end_copy",
"pg_escape_bytea",
"pg_escape_string",
"pg_fetch_all",
"pg_fetch_array",
"pg_fetch_assoc",
"pg_fetch_object",
"pg_fetch_result",
"pg_fetch_row",
"pg_field_is_null",
"pg_field_name",
"pg_field_num",
"pg_field_prtlen",
"pg_field_size",
"pg_field_type",
"pg_free_result",
"pg_get_notify",
"pg_get_pid",
"pg_get_result",
"pg_host",
"pg_insert",
"pg_last_error",
"pg_last_notice",
"pg_last_oid",
"pg_lo_close",
"pg_lo_create",
"pg_lo_export",
"pg_lo_import",
"pg_lo_open",
"pg_lo_read",
"pg_lo_read_all",
"pg_lo_seek",
"pg_lo_tell",
"pg_lo_unlink",
"pg_lo_write",
"pg_meta_data",
"pg_num_fields",
"pg_num_rows",
"pg_options",
"pg_pconnect",
"pg_ping",
"pg_port",
"pg_put_line",
"pg_query",
"pg_result_error",
"pg_result_seek",
"pg_result_status",
"pg_select",
"pg_send_query",
"pg_set_client_encoding",
"pg_trace",
"pg_tty",
"pg_unescape_bytea",
"pg_untrace",
"pg_update",
"PHP_BINDIR",
"PHP_CONFIG_FILE_PATH",
"phpcredits",
"PHP_DATADIR",
"PHP_ERRMSG",
"PHP_EXTENSION_DIR",
"phpinfo",
"php_ini_scanned_files",
"PHP_LIBDIR",
"PHP_LOCALSTATEDIR",
"php_logo_guid",
"PHP_OS",
"PHP_OUTPUT_HANDLER_CONT",
"PHP_OUTPUT_HANDLER_END",
"PHP_OUTPUT_HANDLER_START",
"php_sapi_name",
"PHP_SELF",
"PHP_SYSCONFDIR",
"php_uname",
"phpversion",
"PHP_VERSION",
"pi",
"png2wbmp",
"popen",
"pos",
"posix_ctermid",
"posix_getcwd",
"posix_getegid",
"posix_geteuid",
"posix_getgid",
"posix_getgrgid",
"posix_getgrnam",
"posix_getgroups",
"posix_getlogin",
"posix_getpgid",
"posix_getpgrp",
"posix_getpid",
"posix_getppid",
"posix_getpwnam",
"posix_getpwuid",
"posix_getrlimit",
"posix_getsid",
"posix_getuid",
"posix_isatty",
"posix_kill",
"posix_mkfifo",
"posix_setegid",
"posix_seteuid",
"posix_setgid",
"posix_setpgid",
"posix_setsid",
"posix_setuid",
"posix_times",
"posix_ttyname",
"posix_uname",
"_POST",
"pow",
"prefix",
"preg_grep",
"preg_match",
"preg_match_all",
"preg_quote",
"preg_replace",
"preg_replace_callback",
"preg_split",
"prev",
"previous_sibling",
"print",
"printer_abort",
"printer_close",
"printer_create_brush",
"printer_create_dc",
"printer_create_font",
"printer_create_pen",
"printer_delete_brush",
"printer_delete_dc",
"printer_delete_font",
"printer_delete_pen",
"printer_draw_bmp",
"printer_draw_chord",
"printer_draw_elipse",
"printer_draw_line",
"printer_draw_pie",
"printer_draw_rectangle",
"printer_draw_roundrect",
"printer_draw_text",
"printer_end_doc",
"printer_end_page",
"printer_get_option",
"printer_list",
"printer_logical_fontheight",
"printer_open",
"printer_select_brush",
"printer_select_font",
"printer_select_pen",
"printer_set_option",
"printer_start_doc",
"printer_start_page",
"printer_write",
"printf",
"print_r",
"private",
"proc_close",
"process",
"proc_open",
"protected",
"pspell_add_to_personal",
"pspell_add_to_session",
"pspell_check",
"pspell_clear_session",
"pspell_config_create",
"pspell_config_ignore",
"pspell_config_mode",
"pspell_config_personal",
"pspell_config_repl",
"pspell_config_runtogether",
"pspell_config_save_repl",
"pspell_new",
"pspell_new_config",
"pspell_new_personal",
"pspell_save_wordlist",
"pspell_store_replacement",
"pspell_suggest",
"public",
"public_id",
"putenv",
"qdom_error",
"qdom_tree",
"QUERY_STRING",
"quoted_printable_decode",
"quotemeta",
"rad2deg",
"rand",
"range",
"rawurldecode",
"rawurlencode",
"read",
"readdir",
"read_exif_data",
"readfile",
"readgzfile",
"readline",
"readline_add_history",
"readline_clear_history",
"readline_completion_function",
"readline_info",
"readline_list_history",
"readline_read_history",
"readline_write_history",
"readlink",
"realpath",
"reason",
"recode",
"recode_file",
"recode_string",
"register_shutdown_function",
"register_tick_function",
"REMOTE_ADDR",
"REMOTE_PORT",
"remove",
"remove_attribute",
"remove_child",
"rename",
"replace",
"replace_child",
"replace_node",
"_REQUEST",
"REQUEST_METHOD",
"REQUEST_URI",
"require",
"require_once",
"reset",
"restore_error_handler",
"restore_include_path",
"result_dump_file",
"result_dump_mem",
"return",
"rewind",
"rewinddir",
"rmdir",
"Rotate",
"rotateTo",
"round",
"rsort",
"rtrim",
"save",
"scale",
"scaleTo",
"SCRIPT_FILENAME",
"SCRIPT_NAME",
"sem_acquire",
"sem_get",
"sem_release",
"sem_remove",
"serialize",
"_SERVER",
"SERVER_ADMIN",
"SERVER_NAME",
"SERVER_PORT",
"SERVER_PROTOCOL",
"SERVER_SIGNATURE",
"SERVER_SOFTWARE",
"sesam_affected_rows",
"sesam_commit",
"sesam_connect",
"sesam_diagnostic",
"sesam_disconnect",
"sesam_errormsg",
"sesam_execimm",
"sesam_fetch_array",
"sesam_fetch_result",
"sesam_fetch_row",
"sesam_field_array",
"sesam_field_name",
"sesam_free_result",
"sesam_num_fields",
"sesam_query",
"sesam_rollback",
"sesam_seek_row",
"sesam_settransaction",
"_SESSION",
"session_cache_expire",
"session_cache_limiter",
"session_decode",
"session_destroy",
"session_encode",
"session_get_cookie_params",
"session_id",
"session_is_registered",
"session_module_name",
"session_name",
"session_readonly",
"session_register",
"session_save_path",
"session_set_cookie_params",
"session_set_save_handler",
"session_start",
"session_unregister",
"session_unset",
"session_write_close",
"setAction",
"set_attribute",
"setbackground",
"setbounds",
"setcolor",
"setColor",
"setcommitedversion",
"set_content",
"setcookie",
"setDepth",
"setdimension",
"setdown",
"set_error_handler",
"set_file_buffer",
"setFont",
"setframes",
"setHeight",
"setHit",
"set_include_path",
"setindentation",
"setLeftFill",
"setLeftMargin",
"setLine",
"setLineSpacing",
"setlocale",
"set_magic_quotes_runtime",
"setMargins",
"set_name",
"setname",
"setName",
"set_namespace",
"setOver",
"setrate",
"setRatio",
"setRightFill",
"setrightMargin",
"setSpacing",
"set_time_limit",
"settype",
"setUp",
"sha1",
"sha1_file",
"shell_exec",
"shm_attach",
"shm_detach",
"shm_get_var",
"shmop_close",
"shmop_delete",
"shmop_open",
"shmop_read",
"shmop_size",
"shmop_write",
"shm_put_var",
"shm_remove",
"shm_remove_var",
"show_source",
"shuffle",
"similar_text",
"sin",
"sinh",
"sizeof",
"skewX",
"skewXTo",
"skewY",
"skewYTo",
"sleep",
"snmpget",
"snmp_get_quick_print",
"snmprealwalk",
"snmpset",
"snmp_set_quick_print",
"snmpwalk",
"snmpwalkoid",
"socket_accept",
"socket_bind",
"socket_clear_error",
"socket_close",
"socket_connect",
"socket_create",
"socket_create_listen",
"socket_create_pair",
"socket_get_option",
"socket_getpeername",
"socket_getsockname",
"socket_get_status",
"socket_iovec_add",
"socket_iovec_alloc",
"socket_iovec_delete",
"socket_iovec_fetch",
"socket_iovec_free",
"socket_iovec_set",
"socket_last_error",
"socket_listen",
"socket_read",
"socket_readv",
"socket_recv",
"socket_recvfrom",
"socket_recvmsg",
"socket_select",
"socket_send",
"socket_sendmsg",
"socket_sendto",
"socket_set_blocking",
"socket_set_nonblock",
"socket_set_option",
"socket_set_timeout",
"socket_shutdown",
"socket_strerror",
"socket_write",
"socket_writev",
"sort",
"soundex",
"specified",
"split",
"spliti",
"sprintf",
"sql_regcase",
"sqrt",
"srand",
"srcanchors",
"srcsofdst",
"sscanf",
"stat",
"static",
"stdClass",
"strcasecmp",
"strchr",
"strcmp",
"strcoll",
"strcspn",
"stream_context_create",
"stream_context_get_options",
"stream_context_set_option",
"stream_context_set_params",
"stream_filter_append",
"stream_filter_prepend",
"stream_get_filters",
"stream_get_meta_data",
"stream_get_wrappers",
"streammp3",
"stream_register_filter",
"stream_register_wrapper",
"stream_select",
"stream_set_blocking",
"stream_set_timeout",
"stream_set_write_buffer",
"strftime",
"stripcslashes",
"stripslashes",
"strip_tags",
"stristr",
"strlen",
"strnatcasecmp",
"strnatcmp",
"strncasecmp",
"strncmp",
"str_pad",
"strpos",
"strrchr",
"str_repeat",
"str_replace",
"strrev",
"str_rot13",
"strrpos",
"str_shuffle",
"strspn",
"strstr",
"strtok",
"strtolower",
"strtotime",
"strtoupper",
"strtr",
"strval",
"str_word_count",
"substr",
"substr_count",
"substr_replace",
"SWFAction",
"swf_actiongeturl",
"swf_actiongotoframe",
"swf_actiongotolabel",
"swf_actionnextframe",
"swf_actionplay",
"swf_actionprevframe",
"swf_actionsettarget",
"swf_actionstop",
"swf_actiontogglequality",
"swf_actionwaitforframe",
"swf_addbuttonrecord",
"swf_addcolor",
"SWFBitmap",
"SWFbutton",
"swfbutton_keypress",
"swf_closefile",
"swf_definebitmap",
"swf_definefont",
"swf_defineline",
"swf_definepoly",
"swf_definerect",
"swf_definetext",
"SWFDisplayItem",
"swf_endbutton",
"swf_enddoaction",
"swf_endshape",
"swf_endsymbol",
"SWFFill",
"SWFFont",
"swf_fontsize",
"swf_fontslant",
"swf_fonttracking",
"swf_getbitmapinfo",
"swf_getfontinfo",
"swf_getframe",
"SWFGradient",
"swf_labelframe",
"swf_lookat",
"swf_modifyobject",
"SWFMorph",
"SWFMovie",
"swf_mulcolor",
"swf_nextid",
"swf_oncondition",
"swf_openfile",
"swf_ortho",
"swf_ortho2",
"swf_perspective",
"swf_placeobject",
"swf_polarview",
"swf_popmatrix",
"swf_posround",
"swf_pushmatrix",
"swf_removeobject",
"swf_rotate",
"swf_scale",
"swf_setfont",
"swf_setframe",
"SWFShape",
"swf_shapearc",
"swf_shapecurveto",
"swf_shapecurveto3",
"swf_shapefillbitmapclip",
"swf_shapefillbitmaptile",
"swf_shapefilloff",
"swf_shapefillsolid",
"swf_shapelinesolid",
"swf_shapelineto",
"swf_shapemoveto",
"swf_showframe",
"SWFSprite",
"swf_startbutton",
"swf_startdoaction",
"swf_startshape",
"swf_startsymbol",
"SWFText",
"SWFTextField",
"swf_textwidth",
"swf_translate",
"swf_viewport",
"switch",
"sybase_affected_rows",
"sybase_close",
"sybase_connect",
"sybase_data_seek",
"sybase_fetch_array",
"sybase_fetch_field",
"sybase_fetch_object",
"sybase_fetch_row",
"sybase_field_seek",
"sybase_free_result",
"sybase_get_last_message",
"sybase_min_client_severity",
"sybase_min_error_severity",
"sybase_min_message_severity",
"sybase_min_server_severity",
"sybase_num_fields",
"sybase_num_rows",
"sybase_pconnect",
"sybase_query",
"sybase_result",
"sybase_select_db",
"symlink",
"syslog",
"system",
"system_id",
"tagname",
"tan",
"tanh",
"target",
"tempnam",
"textdomain",
"time",
"title",
"tmpfile",
"token_get_all",
"token_name",
"touch",
"trigger_error",
"trim",
"TRUE",
"type",
"uasort",
"ucfirst",
"ucwords",
"udm_add_search_limit",
"udm_alloc_agent",
"udm_api_version",
"udm_cat_list",
"udm_cat_path",
"udm_check_charset",
"udm_check_stored",
"udm_clear_search_limits",
"udm_close_stored",
"udm_crc32",
"udm_errno",
"udm_error",
"udm_find",
"udm_free_agent",
"udm_free_ispell_data",
"udm_free_res",
"udm_get_doc_count",
"udm_get_res_field",
"udm_get_res_param",
"udm_load_ispell_data",
"udm_open_stored",
"udm_set_agent_param",
"uksort",
"umask",
"uniqid",
"unixtojd",
"unlink",
"unlink_node",
"unlock",
"unpack",
"unregister_tick_function",
"unserialize",
"unset",
"urldecode",
"urlencode",
"user",
"user_error",
"userlist",
"usleep",
"usort",
"utf8_decode",
"utf8_encode",
"value",
"values",
"var",
"var_dump",
"var_export",
"version_compare",
"virtual",
"vpopmail_add_alias_domain",
"vpopmail_add_alias_domain_ex",
"vpopmail_add_domain",
"vpopmail_add_domain_ex",
"vpopmail_add_user",
"vpopmail_alias_add",
"vpopmail_alias_del",
"vpopmail_alias_del_domain",
"vpopmail_alias_get",
"vpopmail_alias_get_all",
"vpopmail_auth_user",
"vpopmail_del_domain",
"vpopmail_del_domain_ex",
"vpopmail_del_user",
"vpopmail_error",
"vpopmail_passwd",
"vpopmail_set_user_quota",
"vprintf",
"vsprintf",
"w32api_deftype",
"w32api_init_dtype",
"w32api_invoke_function",
"w32api_register_function",
"w32api_set_call_method",
"wddx_add_vars",
"wddx_deserialize",
"wddx_packet_end",
"wddx_packet_start",
"wddx_serialize_value",
"wddx_serialize_vars",
"while",
"wordwrap",
"xinclude",
"xml_error_string",
"xml_get_current_byte_index",
"xml_get_current_column_number",
"xml_get_current_line_number",
"xml_get_error_code",
"xml_parse",
"xml_parse_into_struct",
"xml_parser_create",
"xml_parser_create_ns",
"xml_parser_free",
"xml_parser_get_option",
"xml_parser_set_option",
"xmlrpc_decode",
"xmlrpc_decode_request",
"xmlrpc_encode",
"xmlrpc_encode_request",
"xmlrpc_get_type",
"xmlrpc_parse_method_descriptions",
"xmlrpc_server_add_introspection_data",
"xmlrpc_server_call_method",
"xmlrpc_server_create",
"xmlrpc_server_destroy",
"xmlrpc_server_register_introspection_callback",
"xmlrpc_server_register_method",
"xmlrpc_set_type",
"xml_set_character_data_handler",
"xml_set_default_handler",
"xml_set_element_handler",
"xml_set_end_namespace_decl_handler",
"xml_set_external_entity_ref_handler",
"xml_set_notation_decl_handler",
"xml_set_object",
"xml_set_processing_instruction_handler",
"xml_set_start_namespace_decl_handler",
"xml_set_unparsed_entity_decl_handler",
"xpath_eval",
"xpath_eval_expression",
"xpath_new_context",
"xptr_eval",
"xptr_new_context",
"xslt_create",
"xslt_errno",
"xslt_error",
"xslt_free",
"xslt_output_process",
"xslt_set_base",
"xslt_set_encoding",
"xslt_set_error_handler",
"xslt_set_log",
"xslt_set_sax_handler",
"xslt_set_sax_handlers",
"xslt_set_scheme_handler",
"xslt_set_scheme_handlers",
"yaz_addinfo",
"yaz_ccl_conf",
"yaz_ccl_parse",
"yaz_close",
"yaz_connect",
"yaz_database",
"yaz_element",
"yaz_errno",
"yaz_error",
"yaz_get_option",
"yaz_hits",
"yaz_itemorder",
"yaz_present",
"yaz_range",
"yaz_record",
"yaz_scan",
"yaz_scan_result",
"yaz_schema",
"yaz_search",
"yaz_set_option",
"yaz_sort",
"yaz_syntax",
"yaz_wait",
"yp_all",
"yp_cat",
"yp_errno",
"yp_err_string",
"yp_first",
"yp_get_default_domain",
"yp_master",
"yp_match",
"yp_next",
"yp_order",
"zend_logo_guid",
"zend_version",
"zend_version",
"zip_close",
"zip_entry_close",
"zip_entry_compressedsize",
"zip_entry_compressionmethod",
"zip_entry_filesize",
"zip_entry_name",
"zip_entry_open",
"zip_entry_read",
"zip_open",
"zip_read",
nullptr
};
Php5Writer::Php5Writer()
{
}
Php5Writer::~Php5Writer()
{
}
/**
* Call this method to generate Php code for a UMLClassifier.
* @param c the class you want to generate code for.
*/
void Php5Writer::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("Php5Writer::writeClass: Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".php"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile filephp;
if (!openFile(filephp, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream php(&filephp);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".php"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filephp.fileName());
php<<str<<m_endl;
} else {
php << "<?php" << m_endl;
}
//write includes
UMLPackageList includes;
findObjectsRelated(c, includes);
for(UMLPackage* conc : includes) {
QString headerName = findFileName(conc, QStringLiteral(".php"));
if (!headerName.isEmpty()) {
php << "require_once '" << headerName << "';" << m_endl;
}
}
php << m_endl;
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty()) {
php << m_endl << "/**" << m_endl;
php << " * class " << classname << m_endl;
php << formatDoc(c->doc(), QStringLiteral(" * "));
php << " */" << m_endl ;
}
UMLClassifierList superclasses = c->getSuperClasses(false);
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
UMLAssociationList realizations = c->getRealizations();
bool isInterface = c->isInterface();
//check if it is an interface or regular class
if (isInterface) {
php << "interface " << classname;
} else {
//check if class is abstract and / or has abstract methods
if (c->isAbstract())
php << "abstract ";
php << "class " << classname << (superclasses.count() > 0 ? QStringLiteral(" extends ") : QString());
if (superclasses.count() > 0) {
//php5 does not support multiple inheritance so only use the first one and print a warning if more are used
UMLClassifier *obj = superclasses.first();
php << cleanName(obj->name());
if (superclasses.count() > 1)
php << m_indentation << "//WARNING: PHP5 does not support multiple inheritance but there is more than 1 superclass defined in your UML model!";
}
//check for realizations
if (!realizations.isEmpty()) {
int rc = realizations.count();
int ri = rc;
for(UMLAssociation* a : realizations) {
UMLObject *o = a->getObject(Uml::RoleType::B);
QString typeName = cleanName(o->name());
if (ri == rc)
php << m_endl << m_indentation << m_indentation << m_indentation << "implements ";
php << typeName << (--rc == 0 ? QString() : QStringLiteral(", "));
}
}
}
php << m_endl << '{' << m_endl;
//associations
if (forceSections() || !aggregations.isEmpty()) {
php<< m_endl << m_indentation << "/** Aggregations: */" << m_endl;
for(UMLAssociation* a : aggregations) {
php<< m_endl;
//maybe we should parse the string here and take multiplicity into account to decide
//which container to use.
UMLObject *o = a->getObject(Uml::RoleType::A);
if (o == nullptr) {
logError0("Php5Writer::writeClass: aggregation role A object is NULL");
continue;
}
//:UNUSED: QString typeName = cleanName(o->name());
if (a->getMultiplicity(Uml::RoleType::A).isEmpty()) {
php << m_indentation << "var $m_" << ';' << m_endl;
} else {
php << m_indentation << "var $m_" << "Vector = array();" << m_endl;
}
}//end for
}
if (forceSections() || !compositions.isEmpty()) {
php<< m_endl << m_indentation << "/** Compositions: */" << m_endl;
for(UMLAssociation* a : compositions) {
// see comment on Aggregation about multiplicity...
UMLObject *o = a->getObject(Uml::RoleType::A);
if (o == nullptr) {
logError0("Php5Writer::writeClass: composition role A object is NULL");
continue;
}
//:UNUSED: QString typeName = cleanName(o->name());
if (a->getMultiplicity(Uml::RoleType::A).isEmpty()) {
php << m_indentation << "var $m_" << ';' << m_endl;
} else {
php << m_indentation << "var $m_" << "Vector = array();" << m_endl;
}
}
}
//attributes
if (!isInterface)
writeAttributes(c, php);
//operations
writeOperations(c, php);
php << m_endl;
//finish file
php << m_endl << "} // end of " << classname << m_endl;
php << "?>" << m_endl;
//close files and notfiy we are done
filephp.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(filephp.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param php output stream for the PHP file
*/
void Php5Writer::writeOperations(UMLClassifier *c, QTextStream &php)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
bool isInterface = c->isInterface();
bool generateErrorStub = false;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for(UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
QString classname(cleanName(c->name()));
//write operations to file
if (forceSections() || !oppub.isEmpty()) {
php << m_endl;
writeOperations(classname, oppub, php, isInterface, generateErrorStub);
}
if (forceSections() || !opprot.isEmpty()) {
php << m_endl;
writeOperations(classname, opprot, php, isInterface, generateErrorStub);
}
if (forceSections() || !oppriv.isEmpty()) {
php << m_endl;
writeOperations(classname, oppriv, php, isInterface, generateErrorStub);
}
// build an oplist for all of the realized operations
UMLOperationList opreal;
// go through each of the realizations, taking each op
UMLAssociationList realizations = c->getRealizations();
if (!realizations.isEmpty()) {
for(UMLAssociation* a : realizations) {
// we know its a classifier if its in the list
UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::RoleType::B);
// exclude realizations to self
if (real == c)
continue;
UMLOperationList opl(real->getOpList());
for(UMLOperation *op : opl) {
opreal.append(op);
}
}
}
// write out all the realizations operations
writeOperations(classname, opreal, php, false, true);
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param php output stream for the PHP file
* @param isInterface indicates if the operation is an interface member
* @param generateErrorStub true generates trigger_error("Implement " . __FUNCTION__)
*/
void Php5Writer::writeOperations(const QString & classname, UMLOperationList &opList,
QTextStream &php, bool isInterface /* = false */,
bool generateErrorStub /* = false */)
{
Q_UNUSED(classname);
for(UMLOperation *op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for(UMLAttribute* at : atl)
writeDoc |= !at->doc().isEmpty();
if (writeDoc) //write method documentation
{
php << m_indentation << "/**" << m_endl <<formatDoc(op->doc(), m_indentation + QStringLiteral(" * "));
php << m_indentation << " *" << m_endl;
for(UMLAttribute* at : atl) //write parameter documentation
{
if (forceDoc() || !at->doc().isEmpty()) {
php << m_indentation << " * @param " << at->getTypeName() << ' ' << cleanName(at->name());
php << ' ' << formatDoc(at->doc(), QString()) << m_endl;
}
}//end for : write parameter documentation
QString str = op->getTypeName();
if (str.isEmpty()) {
str = QStringLiteral("void");
}
php << m_indentation << " * @return " << str << m_endl;
if (op->isAbstract()) php << m_indentation << " * @abstract" << m_endl;
if (op->isStatic()) php << m_indentation << " * @static" << m_endl;
switch(op->visibility()) {
case Uml::Visibility::Public:
php << m_indentation << " * @access public" << m_endl;
break;
case Uml::Visibility::Protected:
php << m_indentation << " * @access protected" << m_endl;
break;
case Uml::Visibility::Private:
php << m_indentation << " * @access private" << m_endl;
break;
default:
break;
}
php << m_indentation << " */" << m_endl;
}//end if : write method documentation
php << m_indentation;
if (op->isAbstract())
php << "abstract ";
switch(op->visibility()) {
case Uml::Visibility::Public:
php << "public ";
break;
case Uml::Visibility::Protected:
php << "protected ";
break;
case Uml::Visibility::Private:
php << "private ";
break;
default:
break;
}
if (op->isStatic())
php << "static ";
php << "function " << cleanName(op->name()) << "(";
int i= atl.count();
int j=0;
for(UMLAttribute* at : atl) {
php << " $" << cleanName(at->name())
<< (!(at->getInitialValue().isEmpty()) ?
(QStringLiteral(" = ") + at->getInitialValue()) : QString())
<< ((j < i-1) ? QStringLiteral(", ") : QString());
j++;
}
php << ")";
if (!isInterface && !op->isAbstract()) {
php << " {" << m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
if (generateErrorStub) {
php << m_indentation << m_indentation << "trigger_error(\"Implement \" . __FUNCTION__);" << m_endl;
}
}
else {
php << formatSourceCode(sourceCode, m_indentation + m_indentation);
}
php << m_indentation << "} // end of member function " << cleanName(op->name()) << m_endl;
}
else {
php << ';' << m_endl;
}
php << m_endl;
}//end for
}
/**
* Write all the attributes of a class.
* @param c the class we are generating code for
* @param php output stream for the PHP file
*/
void Php5Writer::writeAttributes(UMLClassifier *c, QTextStream &php)
{
UMLAttributeList atpub, atprot, atpriv, atdefval;
//sort attributes by scope and see if they have a default value
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty())
atdefval.append(at);
switch(at->visibility()) {
case Uml::Visibility::Public:
atpub.append(at);
break;
case Uml::Visibility::Protected:
atprot.append(at);
break;
case Uml::Visibility::Private:
atpriv.append(at);
break;
default:
break;
}
}
if (forceSections() || atl.count())
php<< m_endl << m_indentation << " /*** Attributes: ***/" << m_endl <<m_endl;
if (forceSections() || atpub.count()) {
writeAttributes(atpub, php);
}
if (forceSections() || atprot.count()) {
writeAttributes(atprot, php);
}
if (forceSections() || atpriv.count()) {
writeAttributes(atpriv, php);
}
}
/**
* Write a list of class attributes.
* @param atList the list of attributes
* @param php output stream for the PHP file
*/
void Php5Writer::writeAttributes(UMLAttributeList &atList, QTextStream &php)
{
for(UMLAttribute *at : atList) {
bool isStatic = at->isStatic();
if (forceDoc() || !at->doc().isEmpty()) {
php << m_indentation << "/**" << m_endl << formatDoc(at->doc(), m_indentation + QStringLiteral(" * "));
if (isStatic) php << m_indentation << " * @static" << m_endl;
switch(at->visibility()) {
case Uml::Visibility::Public:
php << m_indentation << " * @access public" << m_endl;
break;
case Uml::Visibility::Protected:
php << m_indentation << " * @access protected" << m_endl;
break;
case Uml::Visibility::Private:
php << m_indentation << " * @access private" << m_endl;
break;
default:
break;
}
php << m_indentation << " */" << m_endl;
}
php << m_indentation;
switch(at->visibility()) {
case Uml::Visibility::Public:
php << "public ";
break;
case Uml::Visibility::Protected:
php << "protected ";
break;
case Uml::Visibility::Private:
php << "private ";
break;
default:
break;
}
if (isStatic) php << "static ";
php << "$" << cleanName(at->name());
if (!at->getInitialValue().isEmpty())
php << " = " << at->getInitialValue();
php << ";" << m_endl << m_endl;
} // end for
return;
}
/**
* Returns "PHP".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum Php5Writer::language() const
{
return Uml::ProgrammingLanguage::PHP5;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList Php5Writer::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 79,709
|
C++
|
.cpp
| 3,392
| 18.007665
| 159
| 0.58701
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,526
|
perlwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/perl/perlwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 David Hugh-Jones <hughjonesd@yahoo.co.uk>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "perlwriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h"
#include <QDateTime>
#include <QDir>
#include <QRegularExpression>
#include <QString>
#include <QTextStream>
static const char *reserved_words[] = {
"abs",
"accept",
"alarm",
"and",
"atan2",
"BEGIN",
"bind",
"binmode",
"bless",
"byte",
"caller",
"carp",
"chdir",
"chmod",
"chomp",
"chop",
"chown",
"chr",
"chroot",
"close",
"closedir",
"cmp",
"confess",
"connect",
"continue",
"cos",
"croak",
"crypt",
"dbmclose",
"dbmopen",
"defined",
"delete",
"die",
"do",
"dump",
"each",
"else",
"elsif",
"END",
"endgrent",
"endhostent",
"endnetent",
"endprotoent",
"endpwent",
"endservent",
"eof",
"eq",
"eval",
"exec",
"exists",
"exit",
"exp",
"fcntl",
"fileno",
"flock",
"for",
"foreach",
"fork",
"format",
"formline",
"ge",
"getc",
"getgrent",
"getgrgid",
"getgrnam",
"gethostbyaddr",
"gethostbyname",
"gethostent",
"getlogin",
"getnetbyaddr",
"getnetbyname",
"getnetent",
"getpeername",
"getpgrp",
"getppid",
"getpriority",
"getprotobyname",
"getprotobynumber",
"getprotoent",
"getpwent",
"getpwnam",
"getpwuid",
"getservbyname",
"getservbyport",
"getservent",
"getsockname",
"getsockopt",
"glob",
"gmtime",
"goto",
"grep",
"gt",
"hex",
"if",
"import",
"index",
"int",
"integer",
"ioctl",
"join",
"keys",
"kill",
"last",
"lc",
"lcfirst",
"le",
"length",
"lib",
"link",
"listen",
"local",
"localtime",
"lock",
"log",
"lstat",
"lt",
"map",
"mkdir",
"msgctl",
"msgget",
"msgrcv",
"msgsnd",
"my",
"ne",
"new",
"next",
"no",
"not",
"oct",
"open",
"opendir",
"or",
"ord",
"our",
"pack",
"package",
"pipe",
"pop",
"pos",
"print",
"printf",
"prototype",
"push",
"quotemeta",
"rand",
"read",
"readdir",
"readline",
"readlink",
"readpipe",
"recv",
"redo",
"ref",
"rename",
"require",
"reset",
"return",
"reverse",
"rewinddir",
"rindex",
"rmdir",
"scalar",
"seek",
"seekdir",
"select",
"semctl",
"semget",
"semop",
"send",
"setgrent",
"sethostent",
"setnetent",
"setpgrp",
"setpriority",
"setprotoent",
"setpwent",
"setservent",
"setsockopt",
"shift",
"shmctl",
"shmget",
"shmread",
"shmwrite",
"shutdown",
"sigtrap",
"sin",
"sleep",
"socket",
"socketpair",
"sort",
"splice",
"split",
"sprintf",
"sqrt",
"srand",
"stat",
"strict",
"study",
"sub",
"subs",
"substr",
"switch",
"symlink",
"syscall",
"sysopen",
"sysread",
"sysseek",
"system",
"syswrite",
"tell",
"telldir",
"tie",
"tied",
"time",
"times",
"truncate",
"uc",
"ucfirst",
"umask",
"undef",
"unless",
"unlink",
"unpack",
"unshift",
"untie",
"until",
"use",
"utf8",
"utime",
"values",
"vars",
"vec",
"wait",
"waitpid",
"wantarray",
"warn",
"warnings",
"while",
"write",
"xor",
nullptr
};
PerlWriter::PerlWriter()
{
}
PerlWriter::~PerlWriter()
{
}
bool PerlWriter::GetUseStatements(UMLClassifier *c, QString &Ret,
QString &ThisPkgName)
{
if (!c){
return(false);
}
UMLPackageList includes;
findObjectsRelated(c, includes);
QString AV = QChar(QLatin1Char('@'));
QString SV = QChar(QLatin1Char('$'));
QString HV = QChar(QLatin1Char('%'));
for (UMLPackage* conc : includes) {
if (conc->isUMLDatatype())
continue;
QString neatName = cleanName(conc->name());
if (neatName != AV && neatName != SV && neatName != HV) {
QString OtherPkgName = conc->package(QStringLiteral("."));
OtherPkgName.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("::"));
QString OtherName = OtherPkgName + QStringLiteral("::") + cleanName(conc->name());
// Only print out the use statement if the other package isn't the
// same as the one we are working on. (This happens for the
// "Singleton" design pattern.)
if (OtherName != ThisPkgName){
Ret += QStringLiteral("use ");
Ret += OtherName;
Ret += QLatin1Char(';');
Ret += m_endl;
}
}
}
UMLClassifierList superclasses = c->getSuperClasses();
if (superclasses.count()) {
Ret += m_endl;
Ret += QStringLiteral("use base qw(");
for(UMLClassifier *obj : superclasses) {
QString packageName = obj->package(QStringLiteral("."));
packageName.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("::"));
Ret += packageName + QStringLiteral("::") + cleanName(obj->name()) + QLatin1Char(' ');
}
Ret += QStringLiteral(");") + m_endl;
}
return(true);
}
/**
* Call this method to generate Perl code for a UMLClassifier.
* @param c the class you want to generate code for
*/
void PerlWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("PerlWriter::writeClass: Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());// this is fine: cleanName is "::-clean"
QString packageName = c->package(QStringLiteral("."));
QString fileName;
// Replace all white spaces with blanks
packageName = packageName.simplified();
// Replace all blanks with underscore
packageName.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
// Replace all dots (".") with double colon scope resolution operators
// ("::")
packageName.replace(QRegularExpression(QStringLiteral("\\.")), QStringLiteral("::"));
// Store complete package name
QString ThisPkgName = packageName + QStringLiteral("::") + classname;
fileName = findFileName(c, QStringLiteral(".pm"));
// the above lower-cases my nice class names. That is bad.
// correct solution: refactor,
// split massive findFileName up, reimplement
// parts here
// actual solution: shameful ".pm" hack in codegenerator
CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy();
QString curDir = pol->getOutputDirectory().absolutePath();
if (fileName.contains(QStringLiteral("::"))) {
// create new directories for each level
QString newDir;
newDir = curDir;
QString fragment = fileName;
QDir* existing = new QDir (curDir);
QRegularExpression regEx(QStringLiteral("(.*)(::)"));
QRegularExpressionMatch regMat = regEx.match(fragment);
while (fragment.indexOf(regEx) > -1) {
newDir = regMat.captured(1);
fragment.remove(0, (regMat.capturedStart(2) + 2)); // get round strange minimal matching bug
existing->setPath(curDir + QLatin1Char('/') + newDir);
if (! existing->exists()) {
existing->setPath(curDir);
if (! existing->mkdir(newDir)) {
Q_EMIT codeGenerated(c, false);
return;
}
}
curDir += QLatin1Char('/') + newDir;
}
fileName = fragment + QStringLiteral(".pm");
}
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QString oldDir = pol->getOutputDirectory().absolutePath();
pol->setOutputDirectory(curDir);
QFile fileperl;
if (!openFile(fileperl, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream perl(&fileperl);
pol->setOutputDirectory(oldDir);
//======================================================================
// Start generating the code!!
//======================================================================
// try to find a heading file (license, comments, etc)
QString str;
bool bPackageDeclared = false;
bool bUseStmsWritten = false;
str = getHeadingFile(QStringLiteral(".pm")); // what this mean?
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), fileperl.fileName());
str.replace(QRegularExpression(QStringLiteral("%year%")), QDate::currentDate().toString(QStringLiteral("yyyy")));
str.replace(QRegularExpression(QStringLiteral("%date%")), QDate::currentDate().toString());
str.replace(QRegularExpression(QStringLiteral("%time%")), QTime::currentTime().toString());
str.replace(QRegularExpression(QStringLiteral("%package-name%")), ThisPkgName);
if(str.indexOf(QRegularExpression(QStringLiteral("%PACKAGE-DECLARE%")))){
str.replace(QRegularExpression(QStringLiteral("%PACKAGE-DECLARE%")),
QStringLiteral("package ") + ThisPkgName + QLatin1Char(';')
+ m_endl + m_endl
+ QStringLiteral("#UML_MODELER_BEGIN_PERSONAL_VARS_") + classname
+ m_endl + m_endl
+ QStringLiteral("#UML_MODELER_END_PERSONAL_VARS_") + classname
+ m_endl
);
bPackageDeclared = true;
}
if (str.indexOf(QRegularExpression(QStringLiteral("%USE-STATEMENTS%")))){
QString UseStms;
if(GetUseStatements(c, UseStms, ThisPkgName)){
str.replace(QRegularExpression(QStringLiteral("%USE-STATEMENTS%")), UseStms);
bUseStmsWritten = true;
}
}
perl << str << m_endl;
}
// if the package wasn't declared above during keyword substitution,
// add it now. (At the end of the file.)
if (! bPackageDeclared){
perl << m_endl << m_endl << "package " <<ThisPkgName << ";" << m_endl
<< m_endl;
//write includes
perl << m_endl << "#UML_MODELER_BEGIN_PERSONAL_VARS_" << classname
<< m_endl ;
perl << m_endl << "#UML_MODELER_END_PERSONAL_VARS_" << classname
<< m_endl << m_endl ;
}
if (! bUseStmsWritten){
QString UseStms;
if (GetUseStatements(c, UseStms, ThisPkgName)){
perl << UseStms << m_endl;
}
}
perl << m_endl;
// Do we really need these for anything???
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
//Write class Documentation
if (forceDoc() || !c->doc().isEmpty()) {
perl << m_endl << "=head1";
perl << " " << classname.toUpper() << m_endl << m_endl;
perl << c->doc();
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
}
//check if class is abstract and / or has abstract methods
if (c->isAbstract())
perl << "=head1 ABSTRACT CLASS" << m_endl << m_endl << "=cut" << m_endl;
//attributes
if (! c->isInterface())
writeAttributes(c, perl); // keep for documentation's sake
//operations
writeOperations(c, perl);
perl << m_endl;
//finish file
//perl << m_endl << m_endl << "=cut" << m_endl;
perl << m_endl << m_endl << "return 1;" << m_endl;
//close files and notify we are done
fileperl.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(fileperl.fileName());
}
/**
* Returns "Perl".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum PerlWriter::language() const
{
return Uml::ProgrammingLanguage::Perl;
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param perl output stream for the Perl file
*/
void PerlWriter::writeOperations(UMLClassifier *c, QTextStream &perl)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
//keep this for documentation only!
UMLOperationList opl(c->getOpList());
for(UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
QString classname(cleanName(c->name()));
//write operations to file
if (forceSections() || !oppub.isEmpty()) {
perl << m_endl << "=head1 PUBLIC METHODS" << m_endl << m_endl ;
writeOperations(classname, oppub, perl);
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
}
if (forceSections() || !opprot.isEmpty()) {
perl << m_endl << "=head1 METHODS FOR SUBCLASSING" << m_endl << m_endl ;
//perl << "=pod " << m_endl << m_endl << "=head3 " ;
writeOperations(classname, opprot, perl);
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
}
if (forceSections() || !oppriv.isEmpty()) {
perl << m_endl << "=head1 PRIVATE METHODS" << m_endl << m_endl ;
//perl << "=pod " << m_endl << m_endl << "=head3 " ;
writeOperations(classname, oppriv, perl);
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
}
// moved here for perl
if (!c->isInterface() && hasDefaultValueAttr(c)) {
UMLAttributeList atl = c->getAttributeList();
perl << m_endl;
perl << m_endl << "=head2 _init" << m_endl << m_endl << m_endl;
perl << "_init sets all " << classname << " attributes to their default values unless already set" << m_endl << m_endl << "=cut" << m_endl << m_endl;
perl << "sub _init {" << m_endl << m_indentation << "my $self = shift;" << m_endl << m_endl;
for(UMLAttribute *at : atl) {
if (!at->getInitialValue().isEmpty())
perl << m_indentation << "defined $self->{" << cleanName(at->name()) << "}"
<< " or $self->{" << cleanName(at->name()) << "} = "
<< at->getInitialValue() << ";" << m_endl;
}
perl << " }" << m_endl;
}
perl << m_endl << m_endl;
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param perl output stream for the Perl file
*/
void PerlWriter::writeOperations(const QString &classname, UMLOperationList &opList, QTextStream &perl)
{
Q_UNUSED(classname);
for(UMLOperation* op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for(UMLAttribute* at : atl)
writeDoc |= !at->doc().isEmpty();
if (writeDoc) //write method documentation
{
perl << "=pod " << m_endl << m_endl << "=head3 " ;
perl << cleanName(op->name()) << m_endl << m_endl;
perl << " Parameters :" << m_endl ;
//write parameter documentation
for(UMLAttribute* at : atl) {
if (forceDoc() || !at->doc().isEmpty()) {
perl << " "
<< cleanName(at->name()) << " : "
<< at->getTypeName() << " : "
<< at->doc()
<< m_endl;
}
}//end for : write parameter documentation
perl << m_endl;
perl << " Return : " << m_endl;
perl << " " << op->getTypeName();
perl << m_endl << m_endl;
perl << " Description : " << m_endl;
perl << " " << op->doc();
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
}//end if : write method documentation
perl << "sub " << cleanName(op->name()) << m_endl << "{" << m_endl;
perl << " my($self";
bool bStartPrinted = false;
//write parameters
for(UMLAttribute* at : atl) {
if (!bStartPrinted) {
bStartPrinted = true;
perl << "," << m_endl;
}
perl << " $" << cleanName(at->name()) << ", # "
<< at->getTypeName() << " : " << at->doc() << m_endl;
}
perl << " ) = @_;" << m_endl;
perl << "#UML_MODELER_BEGIN_PERSONAL_CODE_" << cleanName(op->name()) << m_endl;
QString sourceCode = op->getSourceCode();
if (!sourceCode.isEmpty()) {
perl << formatSourceCode(sourceCode, m_indentation);
}
perl << "#UML_MODELER_END_PERSONAL_CODE_" << cleanName(op->name()) << m_endl;
perl << "}" << m_endl;
perl << m_endl << m_endl;
}//end for
}
/**
* Write all the attributes of a class.
* @param c the class we are generating code for
* @param perl output stream for the Perl file
*/
void PerlWriter::writeAttributes(UMLClassifier *c, QTextStream &perl)
{
UMLAttributeList atpub, atprot, atpriv, atdefval;
//sort attributes by scope and see if they have a default value
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty())
atdefval.append(at);
switch(at->visibility()) {
case Uml::Visibility::Public:
atpub.append(at);
break;
case Uml::Visibility::Protected:
atprot.append(at);
break;
case Uml::Visibility::Private:
atpriv.append(at);
break;
default:
break;
}
}
if (forceSections() || atpub.count()) {
writeAttributes(atpub, perl);
}
/* not needed as writeAttributes only writes documentation
if (forceSections() || atprot.count()) {
writeAttributes(atprot, perl);
}
if (forceSections() || atpriv.count()) {
writeAttributes(atpriv, perl);
}
*/
}
/**
* Write a list of class attributes.
* @param atList the list of attributes
* @param perl output stream for the Perl file
*/
void PerlWriter::writeAttributes(UMLAttributeList &atList, QTextStream &perl)
{
perl << m_endl << "=head1 PUBLIC ATTRIBUTES" << m_endl << m_endl;
perl << "=pod " << m_endl << m_endl ;
for(UMLAttribute *at : atList) {
if (forceDoc() || !at->doc().isEmpty())
{
perl << "=head3 " << cleanName(at->name()) << m_endl << m_endl ;
perl << " Description : " << at->doc() << m_endl << m_endl;
}
} // end for
perl << m_endl << m_endl << "=cut" << m_endl << m_endl;
return;
}
/**
* Get list of default datatypes.
* @return the list of default datatypes
*/
QStringList PerlWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("$"));
l.append(QStringLiteral("@"));
l.append(QStringLiteral("%"));
return l;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList PerlWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 19,697
|
C++
|
.cpp
| 673
| 23.48737
| 157
| 0.572529
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,527
|
pythonwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/python/pythonwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Vincent Decorges <vincent.decorges@eivd.ch>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "pythonwriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "umlattributelist.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextCodec>
#include <QTextStream>
static const char *reserved_words[] = {
"abs",
"and",
"apply",
"ArithmeticError",
"assert",
"AssertionError",
"AttributeError",
"break",
"buffer",
"callable",
"chr",
"class",
"classmethod",
"cmp",
"coerce",
"compile",
"complex",
"continue",
"def",
"del",
"delattr",
"DeprecationWarning",
"dict",
"dir",
"divmod",
"elif",
"Ellipsis",
"else",
"EnvironmentError",
"EOFError",
"eval",
"except",
"Exception",
"exec",
"execfile",
"file",
"filter",
"finally",
"float",
"FloatingPointError",
"for",
"from",
"getattr",
"global",
"globals",
"hasattr",
"hash",
"hex",
"id",
"if",
"import",
"__import__",
"ImportError",
"in",
"IndentationError",
"IndexError",
"input",
"int",
"intern",
"IOError",
"is",
"isinstance",
"issubclass",
"iter",
"KeyboardInterrupt",
"KeyError",
"lambda",
"len",
"list",
"locals",
"long",
"LookupError",
"map",
"max",
"MemoryError",
"min",
"NameError",
"None",
"not",
"NotImplemented",
"NotImplementedError",
"object",
"oct",
"open",
"or",
"ord",
"OSError",
"OverflowError",
"OverflowWarning",
"pass",
"pow",
"print",
"property",
"raise",
"range",
"raw_input",
"reduce",
"ReferenceError",
"reload",
"repr",
"return",
"round",
"RuntimeError",
"RuntimeWarning",
"setattr",
"slice",
"StandardError",
"staticmethod",
"StopIteration",
"str",
"super",
"SyntaxError",
"SyntaxWarning",
"SystemError",
"SystemExit",
"TabError",
"try",
"tuple",
"type",
"TypeError",
"UnboundLocalError",
"unichr",
"unicode",
"UnicodeError",
"UserWarning",
"ValueError",
"vars",
"Warning",
"while",
"WindowsError",
"xrange",
"yield",
"ZeroDivisionError",
"zip",
nullptr
};
PythonWriter::PythonWriter() : m_bNeedPass(true)
{
}
PythonWriter::~PythonWriter()
{
}
/**
* Call this method to generate C++ code for a UMLClassifier.
* @param c the class you want to generate code for
*/
void PythonWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("PythonWriter::writeClass: Cannot write class of NULL classifier!");
return;
}
QString classname = cleanName(c->name());
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
m_bNeedPass = true;
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".py"));
// Do not generate files for classes that has a container
if (hasContainer(fileName)) {
Q_EMIT codeGenerated(c, CodeGenerator::Skipped);
return;
}
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile fileh;
if (!openFile(fileh, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream h(&fileh);
h.setCodec("UTF-8");
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".py"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), fileh.fileName());
h<<str<<m_endl;
}
// generate import statement for superclasses and take packages into account
str = cleanName(c->name());
QString pkg = cleanName(c->package());
if (!pkg.isEmpty())
str.prepend(pkg + QLatin1Char('.'));
QStringList includesList = QStringList(str); //save imported classes
int i = superclasses.count();
for(UMLClassifier *classifier : superclasses) {
str = cleanName(classifier->name());
pkg = cleanName(classifier->package());
if (!pkg.isEmpty())
str.prepend(pkg + QLatin1Char('.'));
includesList.append(str);
h << "from " << str << " import *" << m_endl;
i--;
}
//write includes and take namespaces into account
UMLPackageList includes;
findObjectsRelated(c, includes);
for(UMLPackage* conc : includes) {
QString headerName = findFileName(conc, QStringLiteral(".py"));
if (!headerName.isEmpty()) {
headerName.remove(QRegularExpression(QStringLiteral(".py$")));
str = findIncludeFromType(headerName.replace(QLatin1Char('/'), QLatin1Char('.')));
// not yet imported
if (includesList.indexOf(str) < 0) {
includesList.append(str);
h << "from " << str << " import *" << m_endl;
}
}
}
h << m_endl;
h << "class " << classname;
if (superclasses.count()) {
h << QStringLiteral("(");
h << cleanName(superclasses.front()->name());
for (auto superclass = std::next(std::begin(superclasses)); superclass != std::end(superclasses); superclass++) {
h << QStringLiteral(", ") << cleanName((*superclass)->name());
}
h << QStringLiteral(")");
}
h << ":" << m_endl << m_endl;
if (forceDoc() || !c->doc().isEmpty()) {
h << m_indentation << "\"\"\"" << m_endl;
if (!c->doc().isEmpty()) {
h << formatDoc(c->doc(), m_indentation + QLatin1Char(' ')) << m_endl;
h << m_endl;
}
h << m_indentation << ":version:" << m_endl;
h << m_indentation << ":author:" << m_endl;
h << m_indentation << "\"\"\"" << m_endl << m_endl;
m_bNeedPass = false;
}
// attributes
writeAttributes(c->getAttributeList(), h);
//operations
writeOperations(c, h);
if (m_bNeedPass)
h << m_indentation << "pass" << m_endl;
//finish files
h << m_endl << m_endl;
//close files and notfiy we are done
fileh.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(fileh.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all attributes for a given class.
* @param atList the attribute list we are generating code for
* @param py output stream for the header file
*/
void PythonWriter::writeAttributes(UMLAttributeList atList, QTextStream &py)
{
if (!forceDoc() || atList.count() == 0)
return;
py << m_indentation << "\"\"\" ATTRIBUTES" << m_endl << m_endl;
for(UMLAttribute *at : atList) {
if (!at->doc().isEmpty()) {
py << formatDoc(at->doc(), m_indentation + QLatin1Char(' ')) << m_endl;
py << m_endl;
}
Uml::Visibility::Enum vis = at->visibility();
py << m_indentation << cleanName(at->name()) << " ("
<< Uml::Visibility::toString(vis) << ")" << m_endl << m_endl ;
} // end for
py << m_indentation << "\"\"\"" << m_endl << m_endl;
}
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param h output stream for the header file
*/
void PythonWriter::writeOperations(UMLClassifier *c, QTextStream &h)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for(UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
QString classname(cleanName(c->name()));
//write operations to file
if(forceSections() || !oppub.isEmpty()) {
writeOperations(classname, oppub, h, Uml::Visibility::Public);
}
if(forceSections() || !opprot.isEmpty()) {
writeOperations(classname, opprot, h, Uml::Visibility::Protected);
}
if(forceSections() || !oppriv.isEmpty()) {
writeOperations(classname, oppriv, h, Uml::Visibility::Private);
}
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param h output stream for the header file
* @param access visibility identifier
*/
void PythonWriter::writeOperations(const QString& classname, UMLOperationList &opList,
QTextStream &h, Uml::Visibility::Enum access)
{
Q_UNUSED(classname);
QString sAccess;
switch (access)
{
case Uml::Visibility::Public:
sAccess = QString();
break;
case Uml::Visibility::Private:
sAccess = QStringLiteral("__");
break;
case Uml::Visibility::Protected:
sAccess = QStringLiteral("_");
break;
default:
break;
}
for(UMLOperation* op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for(UMLAttribute* at : atl)
writeDoc |= !at->doc().isEmpty();
h << m_indentation << "def "<< sAccess + cleanName(op->name()) << "(self";
int j=0;
for(UMLAttribute* at : atl) {
h << ", " << cleanName(at->name()) << ": " << PythonWriter::fixTypeName(at->getTypeName())
<< (!(at->getInitialValue().isEmpty()) ?
(QStringLiteral(" = ") + at->getInitialValue()) : QString());
j++;
}
h << "):" << m_endl;
if (writeDoc) //write method documentation
{
h << m_indentation << m_indentation << "\"\"\"" << m_endl;
h << formatDoc(op->doc(), m_indentation + m_indentation + QLatin1Char(' ')) << m_endl;
for(UMLAttribute* at : atl) //write parameter documentation
{
if(forceDoc() || !at->doc().isEmpty()) {
h<<m_indentation<<m_indentation<<"@param "<<at->getTypeName()<<
" " << cleanName(at->name());
h<<" : "<<at->doc()<<m_endl;
}
}//end for : write parameter documentation
h << m_indentation << m_indentation << "@return " << op->getTypeName() << " :" << m_endl;
h << m_indentation << m_indentation << "@author" << m_endl;
h << m_indentation << m_indentation << "\"\"\"" << m_endl;
}
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
h << m_indentation << m_indentation << "pass" << m_endl << m_endl;
}
else {
h << formatSourceCode(sourceCode, m_indentation + m_indentation) << m_endl << m_endl;
}
m_bNeedPass = false;
}//end for
}
/**
* Check if type is a container
* @param string type that will be used
* @return true if is a container
*/
bool PythonWriter::hasContainer(const QString &string)
{
return string.contains(QStringLiteral("<")) && string.contains(QStringLiteral(">"));
}
/**
* Fix types to be compatible with Python
* @param string type as defined in model
* @return fixed type
*/
QString PythonWriter::fixTypeName(const QString &string)
{
if (string == QStringLiteral("string")) {
return QStringLiteral("str");
}
QRegularExpression re(QStringLiteral("^vector<(.*)>$"));
QRegularExpressionMatch reMat = re.match(string);
if (string.indexOf(re) >= 0) {
const QString listOf(QStringLiteral("List[%1]"));
return listOf.arg(fixTypeName(reMat.captured(1)));
}
return string;
}
QString PythonWriter::findIncludeFromType(const QString &string)
{
const QString fixedTypeName = fixTypeName(string);
QRegularExpression re(QStringLiteral("^(Any|Dict|List|Tuple)\\["));
if (fixedTypeName.indexOf(re) >= 0) {
return QStringLiteral("typing");
}
return string;
}
/**
* Return the programming language identifier.
* @return programming language id
*/
Uml::ProgrammingLanguage::Enum PythonWriter::language() const
{
return Uml::ProgrammingLanguage::Python;
}
/**
* Reimplementation of method from class CodeGenerator
*/
QStringList PythonWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("array"));
l.append(QStringLiteral("bool"));
l.append(QStringLiteral("tuple"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("int"));
l.append(QStringLiteral("list"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("dict"));
l.append(QStringLiteral("object"));
l.append(QStringLiteral("set"));
l.append(QStringLiteral("str"));
return l;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList PythonWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 14,229
|
C++
|
.cpp
| 478
| 23.864017
| 121
| 0.588682
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,528
|
csharpwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/csharp/csharpwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "csharpwriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "folder.h"
#include "operation.h"
#include "uml.h"
#include "umldoc.h"
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while",
nullptr
};
CSharpWriter::CSharpWriter()
: SimpleCodeGenerator(),
m_unnamedRoles(0)
{
}
CSharpWriter::~CSharpWriter()
{
}
/**
* Get list of predefined data types.
*/
QStringList CSharpWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("bool"));
l.append(QStringLiteral("byte"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("decimal"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("dynamic"));
l.append(QStringLiteral("fixed"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("int"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("nint"));
l.append(QStringLiteral("nuint"));
l.append(QStringLiteral("object"));
l.append(QStringLiteral("sbyte"));
l.append(QStringLiteral("short"));
l.append(QStringLiteral("string"));
l.append(QStringLiteral("uint"));
l.append(QStringLiteral("ulong"));
l.append(QStringLiteral("ushort"));
l.append(QStringLiteral("bool[]"));
l.append(QStringLiteral("byte[]"));
l.append(QStringLiteral("char[]"));
l.append(QStringLiteral("decimal[]"));
l.append(QStringLiteral("double[]"));
l.append(QStringLiteral("dynamic[]"));
l.append(QStringLiteral("fixed[]"));
l.append(QStringLiteral("float[]"));
l.append(QStringLiteral("int[]"));
l.append(QStringLiteral("long[]"));
l.append(QStringLiteral("nint[]"));
l.append(QStringLiteral("nuint[]"));
l.append(QStringLiteral("object[]"));
l.append(QStringLiteral("sbyte[]"));
l.append(QStringLiteral("short[]"));
l.append(QStringLiteral("string[]"));
l.append(QStringLiteral("uint[]"));
l.append(QStringLiteral("ulong[]"));
l.append(QStringLiteral("ushort[]"));
return l;
}
/**
* Call this method to generate Php code for a UMLClassifier
* @param c the class you want to generate code for.
*/
void CSharpWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("CSharpWriter::writeClass: Cannot write class of NULL classifier");
return;
}
QString classname = cleanName(c->name());
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".cs"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile filecs;
if (!openFile(filecs, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream cs(&filecs);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".cs"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filecs.fileName());
cs << str << m_endl;
}
UMLDoc *umldoc = UMLApp::app()->document();
UMLFolder *logicalView = umldoc->rootFolder(Uml::ModelType::Logical);
// write generic includes
cs << "using System;" << m_endl;
cs << "using System.Text;" << m_endl;
cs << "using System.Collections;" << m_endl;
cs << "using System.Collections.Generic;" << m_endl << m_endl;
//write includes and namespace
UMLPackage *container = c->umlPackage();
if (container == logicalView)
container = nullptr;
UMLPackageList includes;
findObjectsRelated(c, includes);
m_seenIncludes.clear();
//m_seenIncludes.append(logicalView);
if (includes.count()) {
for(UMLPackage* p : includes) {
UMLClassifier *cl = p->asUMLClassifier();
if (cl)
p = cl->umlPackage();
if (p != logicalView && m_seenIncludes.indexOf(p) == -1 && p != container) {
cs << "using " << p->fullyQualifiedName(QStringLiteral(".")) << ";" << m_endl;
m_seenIncludes.append(p);
}
}
cs << m_endl;
}
m_container_indent = QString();
if (container) {
cs << "namespace " << container->fullyQualifiedName(QStringLiteral(".")) << m_endl;
cs << "{" << m_endl << m_endl;
m_container_indent = m_indentation;
m_seenIncludes.append(container);
}
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty()) {
cs << m_container_indent << "/// <summary>" << m_endl;
cs << formatDoc(c->doc(), m_container_indent + QStringLiteral("/// "));
cs << m_container_indent << "/// </summary>" << m_endl ;
}
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
UMLAssociationList realizations = c->getRealizations();
bool isInterface = c->isInterface();
m_unnamedRoles = 1;
cs << m_container_indent << "public ";
//check if it is an interface or regular class
if (isInterface) {
cs << "interface " << classname;
} else {
//check if class is abstract and / or has abstract methods
if (c->isAbstract() || c->hasAbstractOps())
cs << "abstract ";
cs << "class " << classname << (superclasses.count() > 0 ? QStringLiteral(" : ") : QString());
// write baseclass, ignore interfaces, write error on multiple inheritance
if (superclasses.count() > 0) {
int supers = 0;
for(UMLClassifier* obj : superclasses) {
if (!obj->isInterface()) {
if (supers > 0) {
cs << " // AND ";
}
cs << cleanName(obj->name());
supers++;
}
}
if (supers > 1) {
cs << m_endl << "//WARNING: C# does not support multiple inheritance but there is more than 1 superclass defined in your UML model!" << m_endl;
}
}
//check for realizations
UMLAssociationList realizations = c->getRealizations();
if (!realizations.isEmpty()) {
for(UMLAssociation* a : realizations) {
UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::RoleType::B);
if(real != c) {
// write list of realizations
cs << ", " << real->name();
}
}
}
}
cs << m_endl << m_container_indent << '{' << m_endl;
//associations
if (forceSections() || !aggregations.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "#region Aggregations" << m_endl << m_endl;
writeAssociatedAttributes(aggregations, c, cs);
cs << m_endl << m_container_indent << m_indentation << "#endregion" << m_endl;
}
//compositions
if (forceSections() || !compositions.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "#region Compositions" << m_endl << m_endl;
writeAssociatedAttributes(compositions, c, cs);
cs << m_endl << m_container_indent << m_indentation << "#endregion" << m_endl;
}
//attributes
// FIXME: C# allows Properties in interface!
if (!isInterface)
writeAttributes(c, cs);
//operations
writeOperations(c, cs);
//finish file
cs << m_endl << m_container_indent << "}" << m_endl << m_endl; // close class
if (container) {
cs << "} // end of namespace "
<< container->fullyQualifiedName(QStringLiteral(".")) << m_endl << m_endl;
}
//close files and notfiy we are done
filecs.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(filecs.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param cs output stream
*/
void CSharpWriter::writeOperations(UMLClassifier *c, QTextStream &cs)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
bool isInterface = c->isInterface();
bool generateErrorStub = true;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for(UMLOperation* op : opl) {
switch (op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
// write realizations (recursive)
UMLAssociationList realizations = c->getRealizations();
if (!isInterface && !realizations.isEmpty()) {
writeRealizationsRecursive(c, &realizations, cs);
}
// write public operations
if (forceSections() || !oppub.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "#region Public methods" << m_endl << m_endl;
writeOperations(oppub, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
}
// write protected operations
if (forceSections() || !opprot.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "#region Protected methods" << m_endl << m_endl;
writeOperations(opprot, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
}
// write private operations
if (forceSections() || !oppriv.isEmpty()) {
cs << m_endl << m_container_indent << m_indentation << "#region Private methods" << m_endl << m_endl;
writeOperations(oppriv, cs, isInterface, false, generateErrorStub);
cs << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
}
// write superclasses abstract methods
UMLClassifierList superclasses = c->getSuperClasses();
if (!isInterface && !c->isAbstract() && !c->hasAbstractOps()
&& superclasses.count() > 0) {
writeOverridesRecursive(&superclasses, cs);
}
}
/**
* Write superclasses' abstract methods.
* @param superclasses List of superclasses to start recursing on
* @param cs output stream
*/
void CSharpWriter::writeOverridesRecursive(UMLClassifierList *superclasses, QTextStream &cs)
{
// oplist for implemented abstract operations
UMLOperationList opabstract;
for(UMLClassifier* obj : *superclasses) {
if (!obj->isInterface() && obj->hasAbstractOps()) {
// collect abstract ops
UMLOperationList opl(obj->getOpList());
for(UMLOperation* op : opl) {
if (op->isAbstract()) {
opabstract.append(op);
}
}
// write abstract implementations
cs << m_endl << m_container_indent << m_indentation << "#region " << obj->name() << " members" << m_endl << m_endl;
writeOperations(opabstract, cs, false, true, true);
cs << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
opabstract.clear();
}
// Recurse to parent superclasses
UMLClassifierList superRecursive = obj->getSuperClasses();
UMLClassifierList *superRecursivePtr =& superRecursive;
if (superRecursivePtr->count() > 0) {
writeOverridesRecursive(superRecursivePtr, cs);
}
}
}
/**
* Write realizations of a class and recurse to parent classes.
* @param currentClass class to start with
* @param realizations realizations of this class
* @param cs output stream
*/
void CSharpWriter::writeRealizationsRecursive(UMLClassifier *currentClass, UMLAssociationList *realizations, QTextStream &cs)
{
for (UMLAssociationListIt alit(*realizations); alit.hasNext();) {
UMLAssociation *a = alit.next();
// we know it is a classifier if it is in the list
UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::RoleType::B);
//FIXME: Interfaces realize themselves without this condition!?
if (real == currentClass)
continue;
// collect operations of one realization
UMLOperationList opreal = real->getOpList();
// write realizations
cs << m_endl << m_container_indent << m_indentation << "#region " << real->name() << " members" << m_endl << m_endl;
writeOperations(opreal, cs, false, false, true);
cs << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
// Recurse to parent realizations
UMLAssociationList parentReal = real->getRealizations();
if (!parentReal.isEmpty()) {
writeRealizationsRecursive(real, &parentReal, cs);
}
}
}
/**
* Write a list of class operations.
* @param opList the list of operations
* @param cs output stream
* @param isInterface indicates if the operation is an interface member
* @param isOverride implementation of an inherited abstract function
* @param generateErrorStub flag whether an exception should be thrown
*/
void CSharpWriter::writeOperations(UMLOperationList opList,
QTextStream &cs, bool isInterface /* = false */,
bool isOverride /* = false */,
bool generateErrorStub /* = false */)
{
for(UMLOperation* op : opList) {
UMLAttributeList atl = op->getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for(UMLAttribute* at : atl) {
writeDoc |= !at->doc().isEmpty();
}
//write method documentation
if (writeDoc && !isOverride)
{
cs << m_container_indent << m_indentation << "/// <summary>" << m_endl;
cs << formatDoc(op->doc(), m_container_indent + m_indentation + QStringLiteral("/// "));
cs << m_container_indent << m_indentation << "/// </summary>" << m_endl;
//write parameter documentation
for(UMLAttribute* at : atl) {
if (forceDoc() || !at->doc().isEmpty()) {
cs << m_container_indent << m_indentation << "/// <param name=\"" << cleanName(at->name()) << "\">";
//removing newlines from parameter doc
QString doc(formatDoc(at->doc(), QString()));
doc.replace(QLatin1Char('\n'), QLatin1Char(' '));
doc.remove(QLatin1Char('\r'));
doc.remove(QRegularExpression(QStringLiteral(" $")));
cs << doc;
cs << "</param>" << m_endl;
}
}
// FIXME: "returns" should contain documentation, not type.
cs << m_container_indent << m_indentation << "/// <returns>";
if (! op->getTypeName().isEmpty()) {
cs << makeLocalTypeName(op);
}
cs << "</returns>" << m_endl;
}
// method visibility
cs << m_container_indent << m_indentation;
if (!isInterface) {
if (!isOverride) {
if (op->isAbstract()) cs << "abstract ";
cs << Uml::Visibility::toString(op->visibility()) << " ";
if (op->isStatic()) cs << "static ";
}
else {
// method overriding an abstract parent
cs << Uml::Visibility::toString(op->visibility()) << " override ";
if (op->isStatic()) cs << "static ";
}
}
// return type (unless constructor, destructor)
if (!op->isLifeOperation()) {
if (op->getTypeName().isEmpty()) {
cs << "void ";
}
else {
cs << makeLocalTypeName(op) << " ";
}
}
// method name
cs << cleanName(op->name()) << "(";
// method parameters
int i= atl.count();
int j=0;
for (UMLAttributeListIt atlIt(atl); atlIt.hasNext(); ++j) {
UMLAttribute* at = atlIt.next();
cs << makeLocalTypeName(at) << " " << cleanName(at->name());
// no initial values in C#
//<< (!(at->getInitialValue().isEmpty()) ?
// (QStringLiteral(" = ")+at->getInitialValue()) :
// QString())
cs << ((j < i-1) ? QStringLiteral(", ") : QString());
}
cs << ")";
//FIXME: how to control generation of error stub?
if (!isInterface && (!op->isAbstract() || isOverride)) {
cs << m_endl << m_container_indent << m_indentation << "{" << m_endl;
// write source code of operation else throw not implemented exception
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
if (generateErrorStub) {
cs << m_container_indent << m_indentation << m_indentation;
cs << "throw new Exception(\"The method or operation is not implemented.\");" << m_endl;
}
}
else {
cs << formatSourceCode(sourceCode, m_container_indent + m_indentation + m_indentation);
}
cs << m_container_indent << m_indentation << "}" << m_endl;
}
else {
cs << ';' << m_endl;
}
cs << m_endl;
}
}
/**
* Write all the attributes of a class.
* @param c the class we are generating code for
* @param cs output stream
*/
void CSharpWriter::writeAttributes(UMLClassifier *c, QTextStream &cs)
{
UMLAttributeList atpub, atprot, atpriv, atdefval;
//sort attributes by scope and see if they have a default value
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty())
atdefval.append(at);
switch (at->visibility()) {
case Uml::Visibility::Public:
atpub.append(at);
break;
case Uml::Visibility::Protected:
atprot.append(at);
break;
case Uml::Visibility::Private:
atpriv.append(at);
break;
default:
break;
}
}
if (forceSections() || atl.count())
cs << m_endl << m_container_indent << m_indentation << "#region Attributes" << m_endl << m_endl;
// write public attributes
if (forceSections() || atpub.count()) {
writeAttributes(atpub, cs);
}
// write protected attributes
if (forceSections() || atprot.count()) {
writeAttributes(atprot, cs);
}
// write private attributes
if (forceSections() || atpriv.count()) {
writeAttributes(atpriv, cs);
}
if (forceSections() || atl.count())
cs << m_endl << m_container_indent << m_indentation << "#endregion" << m_endl << m_endl;
}
/**
* Write a list of class attributes.
* @param atList the list of attributes
* @param cs output stream
*/
void CSharpWriter::writeAttributes(UMLAttributeList &atList, QTextStream &cs)
{
for(UMLAttribute* at : atList) {
bool asProperty = true;
if (at->visibility() == Uml::Visibility::Private) {
asProperty = false;
}
writeAttribute(at->doc(), at->visibility(), at->isStatic(),
makeLocalTypeName(at), at->name(), at->getInitialValue(), asProperty, cs);
cs << m_endl;
} // end for
return;
}
/**
* Write attributes from associated objects (compositions, aggregations).
* @param associated list of associated objects
* @param c currently written class, to see association direction
* @param cs output stream
*/
void CSharpWriter::writeAssociatedAttributes(UMLAssociationList &associated, UMLClassifier *c, QTextStream &cs)
{
for(UMLAssociation *a : associated) {
if (c != a->getObject(Uml::RoleType::A)) // we need to be at the A side
continue;
UMLObject *o = a->getObject(Uml::RoleType::B);
if (o == nullptr) {
logError0("composition role B object is NULL");
continue;
}
// Take name and documentation from Role, take type name from the referenced object
QString roleName = cleanName(a->getRoleName(Uml::RoleType::B));
QString typeName = cleanName(o->name());
if (roleName.isEmpty()) {
roleName = QString::fromLatin1("UnnamedRoleB_%1").arg(m_unnamedRoles++);
}
QString roleDoc = a->getRoleDoc(Uml::RoleType::B);
//FIXME:is this simple condition enough?
if (a->getMultiplicity(Uml::RoleType::B).isEmpty() || a->getMultiplicity(Uml::RoleType::B) == QStringLiteral("1")) {
// normal attribute
writeAttribute(roleDoc, a->visibility(Uml::RoleType::B), false, typeName, roleName, QString(), (a->visibility(Uml::RoleType::B) != Uml::Visibility::Private), cs);
} else {
// array
roleDoc += QStringLiteral("\n(Array of ") + typeName + QLatin1Char(')');
writeAttribute(roleDoc, a->visibility(Uml::RoleType::B), false, QStringLiteral("ArrayList"), roleName, QString(), (a->visibility(Uml::RoleType::B) != Uml::Visibility::Private), cs);
}
}
}
/**
* Write a single attribute to the output stream.
* @param doc attribute documentation
* @param visibility attribute visibility
* @param isStatic static attribute
* @param typeName class/type of the attribute
* @param name name of the attribute
* @param initialValue initial value given to the attribute at declaration
* @param asProperty true writes as property (get/set), false writes single line variable
* @param cs output stream
*/
void CSharpWriter::writeAttribute(const QString& doc,
Uml::Visibility::Enum visibility,
bool isStatic,
const QString& typeName,
const QString& name,
const QString& initialValue,
bool asProperty,
QTextStream &cs)
{
if (forceDoc() || !doc.isEmpty()) {
cs << m_container_indent << m_indentation << "/// <summary>" << m_endl;
cs << formatDoc(doc, m_container_indent + m_indentation + QStringLiteral("/// "));
cs << m_container_indent << m_indentation << "/// </summary>" << m_endl;
}
cs << m_container_indent << m_indentation;
cs << Uml::Visibility::toString(visibility) << " ";
if (isStatic) cs << "static ";
//Variable type with/without namespace path
cs << typeName << " ";
cs << cleanName(name);
// FIXME: may need a GUI switch to not generate as Property?
// Generate as Property if not private
if (asProperty)
{
cs << m_endl;
cs << m_container_indent << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "get" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << m_indentation << "return m_" << cleanName(name) << ";" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "set" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "{" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << m_indentation << "m_" << cleanName(name) << " = value;" << m_endl;
cs << m_container_indent << m_indentation << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << "}" << m_endl;
cs << m_container_indent << m_indentation << "private ";
if (isStatic) cs << "static ";
cs << typeName << " m_" << cleanName(name);
}
if (!initialValue.isEmpty())
cs << " = " << initialValue;
cs << ";" << m_endl << m_endl;
}
/**
* Find the type in used namespaces, if namespace found return short name, complete otherwise.
* @param cl Operation or Attribute to check type
*/
QString CSharpWriter::makeLocalTypeName(UMLClassifierListItem *cl)
{
UMLClassifier *c = cl->getType();
if (c) {
UMLPackage *p = c->umlPackage();
if (m_seenIncludes.indexOf(p) != -1) {
return c->name();
}
}
return cl->getTypeName();
}
/**
* Returns "C#".
*/
Uml::ProgrammingLanguage::Enum CSharpWriter::language() const
{
return Uml::ProgrammingLanguage::CSharp;
}
/**
* Get list of reserved keywords.
*/
QStringList CSharpWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 26,771
|
C++
|
.cpp
| 705
| 30.273759
| 193
| 0.583484
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,529
|
cppcodegenerationform.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodegenerationform.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodegenerationform.h"
// kde includes
#include <KLocalizedString>
#include <kcombobox.h>
#include <KMessageBox>
// qt includes
#include <QFileDialog>
#include <QLabel>
#include <QListWidget>
/**
* Constructor.
* @param parent the parent of this widget
* @param name the object name
*/
CPPCodeGenerationForm::CPPCodeGenerationForm(QWidget *parent, const char *name)
: QWidget(parent)
{
setObjectName(QLatin1String(name));
setupUi(this);
Qt::ItemFlags flags = Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
m_optionPackageIsANamespace =
new QListWidgetItem(i18n("Package is a namespace"), ui_generalOptionsListWidget);
m_optionPackageIsANamespace->setFlags(flags);
m_optionVirtualDestructors =
new QListWidgetItem(i18n("Virtual destructors"), ui_generalOptionsListWidget);
m_optionVirtualDestructors->setFlags(flags);
m_optionGenerateEmptyConstructors =
new QListWidgetItem(i18n("Generate empty constructors"), ui_generalOptionsListWidget);
m_optionGenerateEmptyConstructors->setFlags(flags);
m_optionGenerateAccessorMethods =
new QListWidgetItem(i18n("Generate accessor methods"), ui_generalOptionsListWidget);
m_optionGenerateAccessorMethods->setFlags(flags);
m_optionOperationsAreInline =
new QListWidgetItem(i18n("Operations are inline"), ui_generalOptionsListWidget);
m_optionOperationsAreInline->setFlags(flags);
m_optionAccessorsAreInline =
new QListWidgetItem(i18n("Accessors are inline"), ui_generalOptionsListWidget);
m_optionAccessorsAreInline->setFlags(flags);
m_optionAccessorsArePublic =
new QListWidgetItem(i18n("Accessors are public"), ui_generalOptionsListWidget);
m_optionAccessorsArePublic->setFlags(flags);
m_optionGetterWithGetPrefix =
new QListWidgetItem(i18n("Create getters with 'get' prefix"), ui_generalOptionsListWidget);
m_optionGetterWithGetPrefix->setFlags(flags);
m_optionRemovePrefixFromAccessorMethodName =
new QListWidgetItem(i18n("Remove prefix '[a-zA-Z]_' from accessor method names"), ui_generalOptionsListWidget);
m_optionRemovePrefixFromAccessorMethodName->setFlags(flags);
m_optionAccessorMethodsStartWithUpperCase =
new QListWidgetItem(i18n("Accessor methods start with capital letters"), ui_generalOptionsListWidget);
m_optionAccessorMethodsStartWithUpperCase->setFlags(flags);
m_optionDocToolTag =
new QListWidgetItem(i18n("Use '\\' as documentation tag instead of '@'"), ui_generalOptionsListWidget);
m_optionDocToolTag->setFlags(flags);
connect(ui_generalOptionsListWidget,
SIGNAL(itemClicked(QListWidgetItem*)), this,
SLOT(generalOptionsListWidgetClicked(QListWidgetItem*)));
connect(ui_browseListButton, &QPushButton::clicked, this, &CPPCodeGenerationForm::browseClicked);
connect(ui_browseStringButton, &QPushButton::clicked, this, &CPPCodeGenerationForm::browseClicked);
/*
Commenting this out due to runtime error,
QObject::connect: No such slot CPPCodeGenerationForm::editClassMemberPrefixDoubleClicked(QListWidgetItem*)
in umbrello/codegenerators/cpp/cppcodegenerationform.cpp:87
QObject::connect: (sender name: 'ui_generalOptionsListWidget')
QObject::connect: (receiver name: 'CPPCodeGenerationFormBase')
connect(ui_generalOptionsListWidget,
SIGNAL(itemDoubleClicked(QListWidgetItem*)), this,
SLOT(editClassMemberPrefixDoubleClicked(QListWidgetItem*)));
*/
}
/**
* Destructor.
*/
CPPCodeGenerationForm::~CPPCodeGenerationForm()
{
}
/**
* Slot for clicking on the browse buttons.
*/
void CPPCodeGenerationForm::browseClicked()
{
QString button = sender()->objectName();
QString file = QFileDialog::getOpenFileName(this, QStringLiteral("Get Header File"), QString(), QStringLiteral("*.h"));
if (file.isEmpty()) {
return;
}
if (button == QStringLiteral("m_browseStringButton")) {
// search for match in history list, if absent, then add it
ui_stringIncludeFileHistoryCombo->setCurrentItem(file, true);
}
else if (button == QStringLiteral("m_browseListButton")) {
// search for match in history list, if absent, then add it
ui_listIncludeFileHistoryCombo->setCurrentItem(file, true);
}
}
/**
* Slot for clicking in the list widget.
* @param pSender the sender of the signal, the item in the list
*/
void CPPCodeGenerationForm::generalOptionsListWidgetClicked(QListWidgetItem *pSender)
{
// operations are inline and accessors are operations :)
if (m_optionOperationsAreInline->checkState() == Qt::Checked &&
m_optionGenerateAccessorMethods->checkState() == Qt::Checked) {
m_optionAccessorsAreInline->setCheckState(Qt::Checked);
}
if (pSender == m_optionPackageIsANamespace) {
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionPackageIsANamespace");
#endif
return;
}
if (pSender == m_optionVirtualDestructors) {
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionVirtualDestructors");
#endif
return;
}
if (pSender == m_optionGenerateEmptyConstructors) {
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionVirtualDestructors");
#endif
return;
}
if (pSender == m_optionGenerateAccessorMethods) {
bool dontGenerateAccessorMethods =
(m_optionGenerateAccessorMethods->checkState() == Qt::Unchecked);
m_optionAccessorsAreInline->setHidden(dontGenerateAccessorMethods);
m_optionAccessorsArePublic->setHidden(dontGenerateAccessorMethods);
m_optionGetterWithGetPrefix->setHidden(dontGenerateAccessorMethods);
m_optionRemovePrefixFromAccessorMethodName->setHidden(dontGenerateAccessorMethods);
m_optionAccessorMethodsStartWithUpperCase->setHidden(dontGenerateAccessorMethods);
// reset the value if needed
if (dontGenerateAccessorMethods) {
m_optionAccessorsAreInline->setCheckState(Qt::Unchecked);
m_optionAccessorsArePublic->setCheckState(Qt::Unchecked);
m_optionGetterWithGetPrefix->setCheckState(Qt::Unchecked);
m_optionRemovePrefixFromAccessorMethodName->setCheckState(Qt::Unchecked);
m_optionAccessorMethodsStartWithUpperCase->setHidden(Qt::Unchecked);
}
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionGenerateAccessorMethods");
#endif
return;
}
if (pSender == m_optionOperationsAreInline) {
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionOperationsAreInline");
#endif
return;
}
if (pSender == m_optionAccessorsAreInline) {
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"sender=m_optionAccessorsAreInline");
#endif
return;
}
#if 0
KMessageBox::error(0, "CPPCodeGenerationForm::generalOptionsListViewClicked(): "
"unknown sender");
#endif
return;
}
/**
* Set the display state of option "Package Is Namespace".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setPackageIsANamespace(bool bFlag)
{
m_optionPackageIsANamespace->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of option "Virtual Destructors".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setVirtualDestructors(bool bFlag)
{
m_optionVirtualDestructors->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of option "Generate Empty Constructors".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setGenerateEmptyConstructors(bool bFlag)
{
m_optionGenerateEmptyConstructors->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of option "Generate Accessor Methods".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setGenerateAccessorMethods(bool bFlag)
{
m_optionGenerateAccessorMethods->setCheckState(toCheckState(bFlag));
// initial settings
m_optionAccessorsAreInline->setHidden(m_optionGenerateAccessorMethods->checkState() == Qt::Unchecked);
m_optionAccessorsArePublic->setHidden(m_optionGenerateAccessorMethods->checkState() == Qt::Unchecked);
// reset the value if needed
if (m_optionGenerateAccessorMethods->checkState() == Qt::Unchecked) {
m_optionAccessorsAreInline->setCheckState(Qt::Unchecked);
m_optionAccessorsArePublic->setCheckState(Qt::Unchecked);
}
}
/**
* Set the display state of option "Operations Are Inline".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setOperationsAreInline(bool bFlag)
{
m_optionOperationsAreInline->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of option "Accessors Are Inline".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setAccessorsAreInline(bool bFlag)
{
m_optionAccessorsAreInline->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of option "Accessors Are Public".
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setAccessorsArePublic(bool bFlag)
{
m_optionAccessorsArePublic->setCheckState(toCheckState(bFlag));
}
/**
* Set the display state of the related checkbox
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setGetterWithoutGetPrefix(bool bFlag)
{
m_optionGetterWithGetPrefix->setCheckState(toCheckState(toCheckState(bFlag)));
}
/**
* Set the display state of the related checkbox
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setRemovePrefixFromAccessorMethodName(bool bFlag)
{
m_optionRemovePrefixFromAccessorMethodName->setCheckState(toCheckState(toCheckState(bFlag)));
}
/**
* Set the display state of the related checkbox
* @param bFlag the flag to set
*/
void CPPCodeGenerationForm::setAccessorMethodsStartWithUpperCase(bool bFlag)
{
m_optionAccessorMethodsStartWithUpperCase->setCheckState(toCheckState(toCheckState(bFlag)));
}
/**
* Set the doc display state of option "Doc Tool Tag".
* @param value the value of the tag
*/
void CPPCodeGenerationForm::setDocToolTag(const QString &value)
{
m_optionDocToolTag->setCheckState(toCheckState(value == QStringLiteral("\\")));
}
/**
* Set the class member prefix
* @param value the value to set
*/
void CPPCodeGenerationForm::setClassMemberPrefix(const QString &value)
{
ui_classMemberPrefixEdit->setText(value);
}
/**
* Get the display state of option "Package Is Namespace".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getPackageIsANamespace()
{
return m_optionPackageIsANamespace->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Virtual Destructors".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getVirtualDestructors()
{
return m_optionVirtualDestructors->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Generate Empty Constructors".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getGenerateEmptyConstructors()
{
return m_optionGenerateEmptyConstructors->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Generate Accessor Methods".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getGenerateAccessorMethods()
{
return m_optionGenerateAccessorMethods->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Operations Are Inline".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getOperationsAreInline()
{
return m_optionOperationsAreInline->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Accessors Are Inline".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getAccessorsAreInline()
{
return m_optionAccessorsAreInline->checkState() == Qt::Checked;
}
/**
* Get the display state of option "Accessors Are Public".
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getAccessorsArePublic()
{
return m_optionAccessorsArePublic->checkState() == Qt::Checked;
}
/**
* Get the display state of the related option
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getGettersWithGetPrefix()
{
return m_optionGetterWithGetPrefix->checkState() == Qt::Checked;
}
/**
* Get the display state of the related option
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getRemovePrefixFromAccessorMethodName()
{
return m_optionRemovePrefixFromAccessorMethodName->checkState() == Qt::Checked;
}
/**
* Get the display state of the related option
* @return the state of the flag
*/
bool CPPCodeGenerationForm::getAccessorMethodsStartWithUpperCase()
{
return m_optionAccessorMethodsStartWithUpperCase->checkState() == Qt::Checked;
}
/**
* Get the display state of the related option
* @return the state of the flag
*/
QString CPPCodeGenerationForm::getDocToolTag()
{
return m_optionDocToolTag->checkState() == Qt::Checked ? QStringLiteral("\\") : QStringLiteral("@");
}
/**
* Get the class member prefix
* @return value
*/
QString CPPCodeGenerationForm::getClassMemberPrefix()
{
return ui_classMemberPrefixEdit->text();
}
/**
* Conversion utility (static) from bool to Qt::CheckState.
* @param value the value to be converted
* @return the check state
*/
Qt::CheckState CPPCodeGenerationForm::toCheckState(bool value)
{
if (value) {
return Qt::Checked;
}
else {
return Qt::Unchecked;
}
}
| 14,092
|
C++
|
.cpp
| 387
| 32.268734
| 123
| 0.742932
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,530
|
cppwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas
<brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors
<umbrello-devel@kde.org>
*/
// own header
#include "cppwriter.h"
// app includes
#include "association.h"
#include "classifier.h"
#include "codegen_utils.h"
#include "datatype.h"
#include "debug_utils.h"
#include "model_utils.h"
#include "uml.h"
#include "umldoc.h"
#include "operation.h"
#include "template.h"
#include "umltemplatelist.h"
#include "umlclassifierlistitemlist.h"
#include "classifierlistitem.h"
#include "codegenerationpolicy.h"
#include "enumliteral.h"
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
// 3-14-2003: this code developed from the javawriter with parts of the
// original cppwriter by Luis De la Parra Blum
/**
* Constructor, initialises a couple of variables.
*/
CppWriter::CppWriter()
: m_stringIncludeRequired(false)
{
// Probably we could resolve this better through the use of templates,
// but it is a quick n dirty fix for the time being.. until codegeneration
// template system is in place.
// You can insert code here. 3 general variables exist: "%VARNAME%"
// allows you to specify where the vector variable should be in your code,
// and "%ITEMCLASS%", if needed, where the class of the item is declared.
VECTOR_METHOD_APPEND = QStringLiteral("%VARNAME%.push_back(add_object);"); // for std::vector
VECTOR_METHOD_REMOVE = QString(QStringLiteral("int i, size = %VARNAME%.size();\nfor (i = 0; i < size; ++i) {\n\t%ITEMCLASS% item = %VARNAME%.at(i);\n\tif(item == remove_object) {\n\t\t%1<%ITEMCLASS%>::iterator it = %VARNAME%.begin() + i;\n\t\t%VARNAME%.erase(it);\n\t\treturn;\n\t}\n }")).arg(policyExt()->getVectorClassName()); // for std::vector
VECTOR_METHOD_INIT.clear(); // nothing to be done
/*
VECTOR_METHOD_APPEND = QStringLiteral("%VARNAME%.append(&add_object);"); // Qt lib implementation
VECTOR_METHOD_REMOVE = QStringLiteral("%VARNAME%.removeRef(&remove_object);"); // Qt lib implementation
VECTOR_METHOD_INIT = QStringLiteral("%VARNAME%.setAutoDelete(false);"); // Qt library
*/
OBJECT_METHOD_INIT = QStringLiteral("%VARNAME% = new %ITEMCLASS%();"); // Qt library
// boolean config params
INLINE_ASSOCIATION_METHODS = false;
}
/**
* Destructor, empty.
*/
CppWriter::~CppWriter()
{
}
/**
* Returns "C++".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum CppWriter::language() const
{
return Uml::ProgrammingLanguage::Cpp;
}
/**
* Return the policy object.
*/
CPPCodeGenerationPolicy *CppWriter::policyExt()
{
return static_cast<CPPCodeGenerationPolicy*>(UMLApp::app()->policyExt());
}
/**
* Call this method to generate cpp code for a UMLClassifier.
* @param c the class to generate code for
*/
void CppWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("CppWriter::writeClass: Cannot write class of NULL classifier!");
return;
}
QFile fileh, filecpp;
// find an appropriate name for our file
fileName_ = findFileName(c, QStringLiteral(".h"));
if (fileName_.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
className_ = cleanName(c->name());
if (c->visibility() != Uml::Visibility::Implementation) {
if (!openFile(fileh, fileName_)) {
Q_EMIT codeGenerated(c, false);
return;
}
// write Header file
writeHeaderFile(c, fileh);
fileh.close();
}
// Determine whether the implementation file is required.
// (It is not required if the class is an enumeration.)
bool need_impl = true;
if (c->baseType() == UMLObject::ot_Enum || c->isInterface()) {
need_impl = false;
}
if (need_impl) {
fileName_.replace(QRegularExpression(QStringLiteral(".h$")), QStringLiteral(".cpp"));
if (!openFile(filecpp, fileName_)) {
Q_EMIT codeGenerated(c, false);
return;
}
// write Source file
writeSourceFile(c, filecpp);
filecpp.close();
}
Q_EMIT codeGenerated(c, true);
}
/**
* Write the header file for this classifier.
*/
void CppWriter::writeHeaderFile (UMLClassifier *c, QFile &file)
{
// open stream for writing
QTextStream h(&file);
// write header blurb
QString str = getHeadingFile(QStringLiteral(".h"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName_ + QStringLiteral(".h"));
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
h << str<< m_endl;
}
// Write the hash define stuff to prevent multiple parsing/inclusion of header
QString hashDefine = className_.toUpper().simplified().replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
writeBlankLine(h);
h << "#ifndef "<< hashDefine << "_H" << m_endl;
h << "#define "<< hashDefine << "_H" << m_endl;
h << m_endl;
QString s;
QTextStream t(&s);
writeClassDecl(c, t);
writeIncludes(c, h);
h << s;
// last thing..close our hashdefine
h << m_endl << "#endif // " << hashDefine << "_H" << m_endl;
}
void CppWriter::writeHeaderAccessorMethodDecl(UMLClassifier *c, Uml::Visibility::Enum permitScope, QTextStream &stream)
{
// attributes
writeHeaderAttributeAccessorMethods(c, permitScope, true, stream); // write static attributes first
writeHeaderAttributeAccessorMethods(c, permitScope, false, stream);
// associations
writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), permitScope,
true, INLINE_ASSOCIATION_METHODS, true, c->id(), stream);
writeAssociationMethods(c->getUniAssociationToBeImplemented(), permitScope,
true, INLINE_ASSOCIATION_METHODS, true, c->id(), stream);
writeAssociationMethods(c->getAggregations(), permitScope,
true, INLINE_ASSOCIATION_METHODS, true, c->id(), stream);
writeAssociationMethods(c->getCompositions(), permitScope,
true, INLINE_ASSOCIATION_METHODS, false, c->id(), stream);
writeBlankLine(stream);
}
/**
* Write out fields and operations for this class selected on a particular
* visibility.
*/
void CppWriter::writeHeaderFieldDecl(UMLClassifier *c, Uml::Visibility::Enum permitScope, QTextStream &stream)
{
// attributes
writeAttributeDecls(c, permitScope, true, stream); // write static attributes first
writeAttributeDecls(c, permitScope, false, stream);
// associations
writeAssociationDecls(c->getSpecificAssocs(Uml::AssociationType::Association), permitScope, c->id(), stream);
writeAssociationDecls(c->getUniAssociationToBeImplemented(), permitScope, c->id(), stream);
writeAssociationDecls(c->getAggregations(), permitScope, c->id(), stream);
writeAssociationDecls(c->getCompositions(), permitScope, c->id(), stream);
}
/**
* Write the source code body file for this classifier.
*/
void CppWriter::writeSourceFile(UMLClassifier *c, QFile &file)
{
// open stream for writing
QTextStream cpp (&file);
// set the starting indentation at zero
m_indentLevel = 0;
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".cpp"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName_ + QStringLiteral(".cpp"));
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
cpp << str << m_endl;
}
// IMPORT statements
// Q: Why all utils? Isnt just List and Vector the only classes we are using?
// Our import *should* also look at operations, and check that objects being
// used arent in another package (and thus need to be explicitly imported here).
cpp << "#include \"" << className_ << ".h\"" << m_endl;
writeBlankLine(cpp);
if (c->visibility() == Uml::Visibility::Implementation) {
writeClassDecl(c, cpp);
}
// Start body of class
// Constructors: anything we more we need to do here ?
//
if (!c->isInterface())
writeConstructorMethods(c, cpp);
// METHODS
//
// write comment for section IF needed
QString indnt = indent();
if (forceSections() || c->hasAccessorMethods() || c->hasOperationMethods()) {
writeComment(QStringLiteral("Methods"), indnt, cpp);
writeBlankLine(cpp);
writeBlankLine(cpp);
}
// write comment for sub-section IF needed
if (forceSections() || c->hasAccessorMethods()) {
writeComment(QStringLiteral("Accessor methods"), indnt, cpp);
writeBlankLine(cpp);
writeBlankLine(cpp);
}
// Accessor methods for attributes
const bool bInlineAccessors = policyExt()->getAccessorsAreInline();
if (!bInlineAccessors && c->hasAttributes()) {
writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Public), Uml::Visibility::Public, false, true, !bInlineAccessors, cpp);
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Public), Uml::Visibility::Public, false, false, !bInlineAccessors, cpp);
writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Protected), Uml::Visibility::Protected, false, true, !bInlineAccessors, cpp);
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Protected), Uml::Visibility::Protected, false, false, !bInlineAccessors, cpp);
writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Private), Uml::Visibility::Private, false, true, !bInlineAccessors, cpp);
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Private), Uml::Visibility::Private, false, false, !bInlineAccessors, cpp);
}
// accessor methods for associations
// public
writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Public, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Public, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getAggregations(), Uml::Visibility::Public, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getCompositions(), Uml::Visibility::Public, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
// protected
writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Protected, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Protected, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getAggregations(), Uml::Visibility::Protected, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getCompositions(), Uml::Visibility::Protected, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
// private
writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Private, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Private, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getAggregations(), Uml::Visibility::Private, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeAssociationMethods(c->getCompositions(), Uml::Visibility::Private, false,
!INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
writeBlankLine(cpp);
// Other operation methods -- all other operations are now written
//
// write comment for sub-section IF needed
if (forceSections() || c->hasOperationMethods()) {
writeComment(QStringLiteral("Other methods"), indnt, cpp);
writeBlankLine(cpp);
writeBlankLine(cpp);
}
if (!policyExt()->getOperationsAreInline()) {
writeOperations(c, false, Uml::Visibility::Public, cpp);
writeOperations(c, false, Uml::Visibility::Protected, cpp);
writeOperations(c, false, Uml::Visibility::Private, cpp);
}
// Yep, bringing up the back of the bus, our initialization method for attributes
writeInitAttributeMethod(c, cpp);
writeBlankLine(cpp);
}
/**
* write includes
* @param c uml classifier
* @param stream text stream
*/
void CppWriter::writeIncludes(UMLClassifier *c, QTextStream &stream)
{
UMLClassifierList superclasses = c->getSuperClasses();
for(UMLClassifier* classifier : superclasses) {
QString headerName = findFileName(classifier, QStringLiteral(".h"));
if (!headerName.isEmpty()) {
stream << "#include \"" << headerName << "\"" << m_endl;
}
}
if (superclasses.size() > 0)
writeBlankLine(stream);
if (m_stringIncludeRequired)
stream << "#include " << policyExt()->getStringClassNameInclude() << m_endl;
if (c->hasVectorFields())
stream << "#include " << policyExt()->getVectorClassNameInclude() << m_endl;
if (m_stringIncludeRequired || c->hasVectorFields())
writeBlankLine(stream);
}
/**
* Writes class's documentation to the class header
* "public abstract class Foo extents {".
*/
void CppWriter::writeClassDecl(UMLClassifier *c, QTextStream &cpp)
{
if (c->hasAssociations())
{
// write all includes we need to include other classes, that arent us.
printAssociationIncludeDecl (c->getSpecificAssocs(Uml::AssociationType::Association), c->id(), cpp);
printAssociationIncludeDecl (c->getUniAssociationToBeImplemented(), c->id(), cpp);
printAssociationIncludeDecl (c->getAggregations(), c->id(), cpp);
printAssociationIncludeDecl (c->getCompositions(), c->id(), cpp);
writeBlankLine(cpp);
}
for(UMLClassifier* classifier : c->getSuperClasses()) {
if (classifier->package()!=c->package() && !classifier->package().isEmpty()) {
cpp << "using " << cleanName(classifier->package()) << "::" << cleanName(classifier->name()) << ";" << m_endl;
}
}
if (!c->package().isEmpty() && policyExt()->getPackageIsNamespace())
cpp << m_endl << "namespace " << cleanName(c->package()) << " {" << m_endl << m_endl;
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty()) {
writeDocumentation(QString(), QStringLiteral("class ") + className_, c->doc(), cpp);
writeBlankLine(cpp);
}
// Up the indent level to one.
// Do this _after_ call to writeDocumentation() because the class documentation
// shall not be indented.
m_indentLevel = 1;
//check if class is abstract and / or has abstract methods
if ((c->isAbstract() || c->isInterface())
&& !hasAbstractOps(c))
cpp << "/******************************* Abstract Class ****************************" << m_endl
<< className_ << " does not have any pure virtual methods, but its author" << m_endl
<< " defined it as an abstract class, so you should not use it directly." << m_endl
<< " Inherit from it instead and create only objects from the derived classes" << m_endl
<< "*****************************************************************************/" << m_endl << m_endl;
if (c->baseType() == UMLObject::ot_Enum) {
UMLClassifierListItemList litList = c->getFilteredList(UMLObject::ot_EnumLiteral);
uint i = 0;
cpp << "enum " << className_ << " {" << m_endl;
for(UMLClassifierListItem* lit : litList) {
UMLEnumLiteral *el = static_cast<UMLEnumLiteral *>(lit);
QString enumLiteral = cleanName(lit->name());
cpp << indent() << enumLiteral;
if (!el->value().isEmpty())
cpp << " = " << el->value();
if (++i < (uint)litList.count())
cpp << ",";
cpp << m_endl;
}
cpp << m_endl << "};" << m_endl; // end of class header
if (!c->package().isEmpty() && policyExt()->getPackageIsNamespace())
cpp << "} // end of package namespace" << m_endl;
return;
}
// Generate template parameters.
UMLTemplateList template_params = c->getTemplateList();
if (template_params.count()) {
cpp << "template<";
for (UMLTemplateListIt tlit(template_params); tlit.hasNext();) {
UMLTemplate* t = tlit.next();
QString formalName = t->name();
QString typeName = t->getTypeName();
cpp << typeName << " " << formalName;
if (tlit.hasNext()) {
tlit.next();
cpp << ", ";
}
}
cpp << ">" << m_endl;
}
cpp << "class " << className_;
uint numOfSuperClasses = c->getSuperClasses().count();
if (numOfSuperClasses > 0)
cpp << " : ";
uint i = 0;
for(UMLClassifier* superClass : c->getSuperClasses()) {
i++;
if (superClass->isAbstract() || superClass->isInterface())
cpp << "virtual ";
cpp << "public " << cleanName(superClass->name());
if (i < numOfSuperClasses)
cpp << ", ";
}
cpp << m_endl << "{" << m_endl; // begin the body of the class
//
// write out field and operations decl grouped by visibility
//
QString s;
QTextStream tmp(&s);
// PUBLIC attribs/methods
writeDataTypes(c, Uml::Visibility::Public, tmp);
// for public: constructors are first ops we print out
if (!c->isInterface())
writeConstructorDecls(tmp);
writeHeaderFieldDecl(c, Uml::Visibility::Public, tmp);
writeHeaderAccessorMethodDecl(c, Uml::Visibility::Public, tmp);
writeOperations(c, true, Uml::Visibility::Public, tmp);
s = s.trimmed();
if (!s.isEmpty()) {
cpp << "public:" << m_endl << indent() << s << m_endl << m_endl;
}
s.clear();
// PROTECTED attribs/methods
writeDataTypes(c, Uml::Visibility::Protected, tmp);
writeHeaderFieldDecl(c, Uml::Visibility::Protected, tmp);
writeHeaderAccessorMethodDecl(c, Uml::Visibility::Protected, tmp);
writeOperations(c, true, Uml::Visibility::Protected, tmp);
s = s.trimmed();
if (!s.isEmpty()) {
cpp << "protected:" << m_endl << indent() << s << m_endl << m_endl;
}
s.clear();
// PRIVATE attribs/methods
writeDataTypes(c, Uml::Visibility::Private, tmp);
writeHeaderFieldDecl(c, Uml::Visibility::Private, tmp);
writeHeaderAccessorMethodDecl(c, Uml::Visibility::Private, tmp);
writeOperations(c, true, Uml::Visibility::Private, tmp);
writeInitAttributeDecl(c, tmp); // this is always private, used by constructors to initialize class
s = s.trimmed();
if (!s.isEmpty()) {
cpp << "private:" << m_endl << indent() << s << m_endl;
}
// end of class header
cpp << m_endl << "};" << m_endl;
// end of class namespace, if any
if (!c->package().isEmpty() && policyExt()->getPackageIsNamespace())
cpp << "} // end of package namespace" << m_endl;
}
/**
* Writes the attribute declarations.
* @param c the classifier
* @param visibility the visibility of the attribs to print out
* @param writeStatic whether to write static or non-static attributes out
* @param stream text stream
*/
void CppWriter::writeAttributeDecls (UMLClassifier *c, Uml::Visibility::Enum visibility, bool writeStatic, QTextStream &stream)
{
if (c->isInterface())
return;
UMLAttributeList list;
if (writeStatic)
list = c->getAttributeListStatic(visibility);
else
list = c->getAttributeList(visibility);
//write documentation
if (forceSections() || list.count() > 0)
{
QString strVis = Codegen_Utils::capitalizeFirstLetter(Uml::Visibility::toString(visibility));
QString strStatic = writeStatic ? QStringLiteral("Static ") : QString();
writeComment(strStatic + strVis + QStringLiteral(" attributes"), indent(), stream);
writeBlankLine(stream);
writeBlankLine(stream);
}
if (list.count() > 0) {
// write attrib declarations now
// bool isFirstAttrib = true;
QString documentation;
for(UMLAttribute* at : list) {
// bool noPriorDocExists = documentation.isEmpty();
documentation = at->doc();
// add a line for code clarity IF PRIOR attrib has comment on it
// OR this line has documentation
// if (!isFirstAttrib && (!documentation.isEmpty()||!noPriorDocExists))
// writeBlankLine(stream);
// isFirstAttrib = false;
QString varName = getAttributeVariableName(at);
QString staticValue = at->isStatic() ? QStringLiteral("static ") : QString();
QString typeName = fixTypeName(at->getTypeName());
int i = typeName.indexOf(QLatin1Char('['));
if (i > -1) {
varName += typeName.mid(i);
typeName = typeName.left(i);
}
if (!documentation.isEmpty())
writeComment(documentation, indent(), stream);
stream << indent() << staticValue << typeName << " " << varName << ";" << m_endl;
}
/*
if (list.count() > 0)
writeBlankLine(stream);
*/
}
}
void CppWriter::writeHeaderAttributeAccessorMethods (UMLClassifier *c, Uml::Visibility::Enum visibility, bool writeStatic, QTextStream &stream)
{
// check the current policy about generate accessors as public
UMLAttributeList list;
if (writeStatic)
list = c->getAttributeListStatic(visibility);
else
list = c->getAttributeList(visibility);
// write accessor methods for attribs we found
// if getAccessorsArePublic policy is true, all attribute accessors are public.
const Uml::Visibility::Enum vis = policyExt()->getAccessorsArePublic() ? Uml::Visibility::Public : visibility;
writeAttributeMethods(list, vis, true, writeStatic, policyExt()->getAccessorsAreInline(), stream);
}
/**
* This is for writing *source* or *header* file attribute methods.
* Calls @ref writeSingleAttributeAccessorMethods() on each of the attributes in attribs list.
*/
void CppWriter::writeAttributeMethods(UMLAttributeList attribs,
Uml::Visibility::Enum visibility, bool isHeaderMethod,
bool isStatic,
bool writeMethodBody, QTextStream &stream)
{
if (!policyExt()->getAutoGenerateAccessors())
return;
if (forceSections() || attribs.count() > 0)
{
QString strVis = Codegen_Utils::capitalizeFirstLetter(Uml::Visibility::toString(visibility));
QString strStatic = (isStatic ? QStringLiteral(" static") : QString());
writeBlankLine(stream);
writeComment(strVis + strStatic + QStringLiteral(" attribute accessor methods"), indent(), stream);
writeBlankLine(stream);
writeBlankLine(stream);
}
// return now if NO attributes to work on
if (attribs.count() == 0)
return;
for(UMLAttribute* at : attribs) {
QString varName = getAttributeVariableName(at);
QString methodBaseName = getAttributeMethodBaseName(cleanName(at->name()));
methodBaseName = methodBaseName.trimmed();
writeSingleAttributeAccessorMethods(at->getTypeName(), varName,
methodBaseName, at->doc(), Uml::Changeability::Changeable, isHeaderMethod,
at->isStatic(), writeMethodBody, stream);
}
}
/**
* Writes a general comment.
*/
void CppWriter::writeComment(const QString &comment, const QString &myIndent, QTextStream &cpp)
{
CodeGenerationPolicy::CommentStyle const cStyle = UMLApp::app()->commonPolicy()->getCommentStyle();
QString commentHeadingStr;
QString intermediateLinePrefixStr;
QString commentFooterStr;
if (cStyle == CodeGenerationPolicy::MultiLine) {
commentHeadingStr = QStringLiteral("/* ");
intermediateLinePrefixStr = QStringLiteral(" * ");
commentFooterStr = QStringLiteral(" */");
} else if (cStyle == CodeGenerationPolicy::SingleLine) {
commentHeadingStr = QStringLiteral("// ");
intermediateLinePrefixStr = commentHeadingStr;
}
cpp << formatFullDocBlock(comment, myIndent + commentHeadingStr,
myIndent + commentFooterStr, myIndent + intermediateLinePrefixStr);
}
/**
* Writes a documentation comment.
*/
void CppWriter::writeDocumentation(QString header, QString body, QString end, QTextStream &cpp)
{
CodeGenerationPolicy::CommentStyle const cStyle = UMLApp::app()->commonPolicy()->getCommentStyle();
QString commentHeadingStr;
QString intermediateLinePrefixStr;
QString commentFooterStr;
if (cStyle == CodeGenerationPolicy::MultiLine) {
commentHeadingStr = QStringLiteral("/** ");
intermediateLinePrefixStr = QStringLiteral(" * ");
commentFooterStr = QStringLiteral(" */");
} else if (cStyle == CodeGenerationPolicy::SingleLine) {
commentHeadingStr = QStringLiteral("/// ");
intermediateLinePrefixStr = commentHeadingStr;
}
writeBlankLine(cpp);
QString indnt = indent();
cpp << indnt << commentHeadingStr << m_endl;
if (!header.isEmpty())
cpp << formatDoc(header, indnt + intermediateLinePrefixStr);
if (!body.isEmpty())
cpp << formatDoc(body, indnt + intermediateLinePrefixStr);
if (!end.isEmpty()) {
QStringList lines = end.split(QLatin1Char('\n'));
for (int i = 0; i < lines.count(); ++i) {
cpp << indnt << intermediateLinePrefixStr << lines[i] << m_endl;
}
}
if (!commentFooterStr.isEmpty()) {
cpp << indnt << commentFooterStr << m_endl;
}
}
/**
* Searches a list of associations for appropriate ones to write out as attributes.
*/
void CppWriter::writeAssociationDecls(UMLAssociationList associations, Uml::Visibility::Enum permitScope, Uml::ID::Type id, QTextStream &h)
{
if (forceSections() || !associations.isEmpty())
{
bool printRoleA = false, printRoleB = false;
for(UMLAssociation *a : associations)
{
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id && !a->getRoleName(Uml::RoleType::B).isEmpty())
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id && !a->getRoleName(Uml::RoleType::A).isEmpty())
printRoleA = true;
// First: we insert documentation for association IF it has either role AND some documentation (!)
if ((printRoleA || printRoleB) && !(a->doc().isEmpty()))
writeComment(a->doc(), indent(), h);
// print RoleB decl
if (printRoleB && a->visibility(Uml::RoleType::B) == permitScope)
{
QString fieldClassName = cleanName(umlObjectName(a->getObject(Uml::RoleType::B)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::B), a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B), h);
}
// print RoleA decl
if (printRoleA && a->visibility(Uml::RoleType::A) == permitScope)
{
QString fieldClassName = cleanName(umlObjectName(a->getObject(Uml::RoleType::A)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::A), a->getMultiplicity(Uml::RoleType::A), a->getRoleDoc(Uml::RoleType::A), h);
}
// reset for next association in our loop
printRoleA = false;
printRoleB = false;
}
}
}
/**
* Writes out an association as an attribute using Vector.
*/
void CppWriter::writeAssociationRoleDecl(QString fieldClassName, QString roleName, QString multi,
QString doc, QTextStream &stream)
{
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared in the code
if (roleName.isEmpty())
return;
QString indnt = indent();
// always put space between this and prior decl, if any
writeBlankLine(stream);
if (!doc.isEmpty())
writeComment(doc, indnt, stream);
// declare the association based on whether it is this a single variable
// or a List (Vector). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$"))))
{
QString fieldVarName = QStringLiteral("m_") + roleName.toLower();
// record this for later consideration of initialization IF the
// multi value requires 1 of these objects
if (ObjectFieldVariables.indexOf(fieldVarName) == -1 &&
multi.contains(QRegularExpression(QStringLiteral("^1$"))))
{
// ugh. UGLY. Storing variable name and its class in pairs.
ObjectFieldVariables.append(fieldVarName);
ObjectFieldVariables.append(fieldClassName);
}
stream << indnt << fieldClassName << " * " << fieldVarName << ";" << m_endl;
}
else
{
QString fieldVarName = QStringLiteral("m_") + roleName.toLower() + QStringLiteral("Vector");
// record unique occurrences for later when we want to check
// for initialization of this vector
if (VectorFieldVariables.indexOf(fieldVarName) == -1)
VectorFieldVariables.append(fieldVarName);
stream << indnt << policyExt()->getVectorClassName() << "<" << fieldClassName << "*";
stream << "> " << fieldVarName << ";" << m_endl;
}
}
/**
* Calls @ref writeAssociationRoleMethod() on each of the associations in the given list
* for either source or header files.
*/
void CppWriter::writeAssociationMethods (UMLAssociationList associations,
Uml::Visibility::Enum permitVisib,
bool isHeaderMethod,
bool writeMethodBody,
bool writePointerVar,
Uml::ID::Type myID, QTextStream &stream)
{
if (forceSections() || !associations.isEmpty())
{
for (UMLAssociation *a : associations)
{
// insert the methods to access the role of the other
// class in the code of this one
if (a->getObjectId(Uml::RoleType::A) == myID && a->visibility(Uml::RoleType::B) == permitVisib)
{
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::B).isEmpty()) {
QString fieldClassName = umlObjectName(a->getObject(Uml::RoleType::B)) + (writePointerVar ? QStringLiteral(" *") : QString());
writeAssociationRoleMethod(fieldClassName,
isHeaderMethod,
writeMethodBody,
a->getRoleName(Uml::RoleType::B),
a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B),
a->changeability(Uml::RoleType::B), stream);
}
}
if (a->getObjectId(Uml::RoleType::B) == myID && a->visibility(Uml::RoleType::A) == permitVisib)
{
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::A).isEmpty()) {
QString fieldClassName = umlObjectName(a->getObject(Uml::RoleType::A)) + (writePointerVar ? QStringLiteral(" *") : QString());
writeAssociationRoleMethod(fieldClassName,
isHeaderMethod,
writeMethodBody,
a->getRoleName(Uml::RoleType::A),
a->getMultiplicity(Uml::RoleType::A),
a->getRoleDoc(Uml::RoleType::A),
a->changeability(Uml::RoleType::A),
stream);
}
}
}
}
}
/**
* Calls @ref writeSingleAttributeAccessorMethods() or @ref
* writeVectorAttributeAccessorMethods() on the association
* role.
*/
void CppWriter::writeAssociationRoleMethod (const QString &fieldClassName,
bool isHeaderMethod,
bool writeMethodBody,
const QString &roleName, const QString &multi,
const QString &description, Uml::Changeability::Enum change,
QTextStream &stream)
{
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$"))))
{
QString fieldVarName = QStringLiteral("m_") + roleName.toLower();
writeSingleAttributeAccessorMethods(fieldClassName, fieldVarName, roleName,
description, change, isHeaderMethod, false, writeMethodBody, stream);
}
else
{
QString fieldVarName = QStringLiteral("m_") + roleName.toLower() + QStringLiteral("Vector");
writeVectorAttributeAccessorMethods(fieldClassName, fieldVarName, roleName,
description, change, isHeaderMethod, writeMethodBody, stream);
}
}
/**
* Writes addFoo() and removeFoo() accessor methods for the Vector attribute.
*/
void CppWriter::writeVectorAttributeAccessorMethods (
const QString &fieldClassName, const QString &fieldVarName,
const QString &fieldName, const QString &description,
Uml::Changeability::Enum changeType,
bool isHeaderMethod,
bool writeMethodBody,
QTextStream &stream)
{
QString className = fixTypeName(fieldClassName);
QString fldName = Codegen_Utils::capitalizeFirstLetter(fieldName);
QString indnt = indent();
// ONLY IF changeability is NOT Frozen
if (changeType != Uml::Changeability::Frozen)
{
writeDocumentation(QStringLiteral("Add a ") + fldName + QStringLiteral(" object to the ") + fieldVarName + QStringLiteral(" List"), description, QString(), stream);
stream << indnt << QStringLiteral("void ");
if (!isHeaderMethod)
stream << className_ << "::";
stream << "add" << fldName << " (" << className << " add_object)";
if (writeMethodBody) {
QString method = VECTOR_METHOD_APPEND;
method.replace(QRegularExpression(QStringLiteral("%VARNAME%")), fieldVarName);
method.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), policyExt()->getVectorClassName());
method.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), className);
stream << indnt << " {" << m_endl;
m_indentLevel++;
printTextAsSeparateLinesWithIndent(method, indent(), stream);
m_indentLevel--;
stream << indnt << "}" << m_endl;
} else
stream << ";" << m_endl;
}
// ONLY IF changeability is Changeable
if (changeType == Uml::Changeability::Changeable)
{
writeDocumentation(QStringLiteral("Remove a ") + fldName + QStringLiteral(" object from ") + fieldVarName + QStringLiteral(" List"),
description, QString(), stream);
stream << indnt << "void ";
if (!isHeaderMethod)
stream << className_ << "::";
stream << "remove" << fldName << " (" << className << " remove_object)";
if (writeMethodBody) {
QString method = VECTOR_METHOD_REMOVE;
method.replace(QRegularExpression(QStringLiteral("%VARNAME%")), fieldVarName);
method.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), policyExt()->getVectorClassName());
method.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), className);
stream << indnt << " {" << m_endl;
m_indentLevel++;
printTextAsSeparateLinesWithIndent(method, indent(), stream);
m_indentLevel--;
stream << indnt << "}" << m_endl;
} else
stream << ";" << m_endl;
}
// always allow getting the list of stuff
QString returnVarName = policyExt()->getVectorClassName() + QLatin1Char('<') + className + QLatin1Char('>');
writeDocumentation(QStringLiteral("Get the list of ") + fldName + QStringLiteral(" objects held by ") + fieldVarName,
description,
policyExt()->getDocToolTag() + QStringLiteral("return ") + returnVarName + QStringLiteral(" list of ") + fldName + QStringLiteral(" objects held by ") + fieldVarName,
stream);
stream << indnt << returnVarName << " ";
if (!isHeaderMethod)
stream << className_ << "::";
stream << "get" << fldName << "List()";
if (writeMethodBody) {
stream << indnt << " {" << m_endl;
m_indentLevel++;
stream << indent() << "return " << fieldVarName << ";" << m_endl;
m_indentLevel--;
stream << indnt << "}" << m_endl;
}
else {
stream << ";" << m_endl;
}
}
/**
* Writes getFoo() and setFoo() accessor methods for the attribute.
*/
void CppWriter::writeSingleAttributeAccessorMethods(
const QString& fieldClassName, const QString& fieldVarName,
const QString& fieldName, const QString &description,
Uml::Changeability::Enum change,
bool isHeaderMethod,
bool isStatic,
bool writeMethodBody,
QTextStream &stream)
{
// DON'T write this IF it is a source method AND writeMethodBody is "false"
if (!isHeaderMethod && !writeMethodBody)
return;
QString className = fixTypeName(fieldClassName);
QString indnt = indent();
QString varName = QStringLiteral("value");
QString fullVarName = varName;
int i = className.indexOf(QLatin1Char('['));
bool isArrayType = false;
if (i > -1) {
fullVarName += className.mid(i);
className = className.left(i);
isArrayType = true;
}
QString fldName = fieldName;
if (policyExt()->getAccessorMethodsStartWithUpperCase())
fldName = Codegen_Utils::capitalizeFirstLetter(fieldName);
// set method
if (change == Uml::Changeability::Changeable) {
writeDocumentation(QStringLiteral("Set the value of ") + fieldVarName, description, policyExt()->getDocToolTag() + QString(QStringLiteral("param %1 the new value of ")).arg(varName) + fieldVarName, stream);
stream << indnt << "void ";
if (!isHeaderMethod)
stream << className_ << "::";
stream << "set" << fldName << "(" << className << " " << fullVarName << ")";
if (writeMethodBody) {
stream << m_endl << indnt << "{" << m_endl;
m_indentLevel++;
stream << indent();
m_indentLevel--;
if (isStatic)
stream << className_ << "::";
if (isArrayType)
stream << "*" << fieldVarName << " = *" << varName << ";" << m_endl;
else
stream << fieldVarName << " = " << fullVarName << ";" << m_endl;
stream << indnt << "}" << m_endl;
} else
stream << ";" << m_endl;
}
if (i > -1)
className += QStringLiteral("*");
// get method
writeDocumentation(QStringLiteral("Get the value of ") + fieldVarName, description, policyExt()->getDocToolTag() + QStringLiteral("return the value of ") + fieldVarName, stream);
stream << indnt << className << " ";
if (!isHeaderMethod)
stream << className_ << "::";
if (policyExt()->getGetterWithGetPrefix())
stream << "get" << fldName << "()";
else
stream << fieldName << "()";
if (writeMethodBody) {
stream << m_endl << indnt << "{" << m_endl;
m_indentLevel++;
stream << indent() << "return ";
m_indentLevel--;
if (isStatic)
stream << className_ << "::";
stream << fieldVarName << ";" << m_endl;
stream << indnt << "}";
} else
stream << ";" << m_endl;
writeBlankLine(stream);
}
/**
* Writes the comment and class constructor declaration or methods.
* Note:
* One day, this should print out non-empty constructor operations too.
*/
void CppWriter::writeConstructorDecls(QTextStream &stream)
{
const bool generateEmptyConstructors =
UMLApp::app()->commonPolicy()->getAutoGenerateConstructors();
if (forceSections() || generateEmptyConstructors)
{
writeComment(QStringLiteral("Constructors/Destructors"), indent(), stream);
writeBlankLine(stream);
writeBlankLine(stream);
}
if (!generateEmptyConstructors)
return;
writeDocumentation(QString(), QStringLiteral("Empty Constructor"), QString(), stream);
stream << indent() << className_ << "();" << m_endl;
writeDocumentation(QString(), QStringLiteral("Empty Destructor"), QString(), stream);
stream << indent();
stream << "virtual ~" << className_ << "();" << m_endl;
writeBlankLine(stream);
}
/**
* If needed, write out the declaration for the method to initialize attributes of our class.
*/
void CppWriter::writeInitAttributeDecl(UMLClassifier * c, QTextStream &stream)
{
if (UMLApp::app()->commonPolicy()->getAutoGenerateConstructors() &&
c->hasAttributes())
stream << indent() << "void initAttributes();" << m_endl;
}
/**
* If needed, write out the method to initialize attributes of our class.
*/
void CppWriter::writeInitAttributeMethod(UMLClassifier * c, QTextStream &stream)
{
// only need to do this under certain conditions
if (!UMLApp::app()->commonPolicy()->getAutoGenerateConstructors() ||
!c->hasAttributes())
return;
QString indnt = indent();
stream << indnt << "void " << className_ << "::" << "initAttributes()" << m_endl
<< "{" << m_endl;
m_indentLevel++;
// first, initiation of fields derived from attributes
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute* at : atl) {
if (!at->getInitialValue().isEmpty()) {
QString varName = getAttributeVariableName(at);
stream << indent() << varName << " = " << at->getInitialValue() << ";" << m_endl;
}
}
// Now initialize the association related fields (e.g. vectors)
if (!VECTOR_METHOD_INIT.isEmpty()) {
QStringList::Iterator it;
for (it = VectorFieldVariables.begin(); it != VectorFieldVariables.end(); ++it) {
QString fieldVarName = *it;
QString method = VECTOR_METHOD_INIT;
method.replace(QRegularExpression(QStringLiteral("%VARNAME%")), fieldVarName);
method.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), policyExt()->getVectorClassName());
stream << indent() << method << m_endl;
}
}
if (!OBJECT_METHOD_INIT.isEmpty()) {
QStringList::Iterator it;
for (it = ObjectFieldVariables.begin(); it != ObjectFieldVariables.end(); ++it) {
QString fieldVarName = *it;
it++;
QString fieldClassName = *it;
QString method = OBJECT_METHOD_INIT;
method.replace(QRegularExpression(QStringLiteral("%VARNAME%")), fieldVarName);
method.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), fieldClassName);
stream << indent() << method << m_endl;
}
}
// clean up
ObjectFieldVariables.clear(); // shouldn't be needed?
VectorFieldVariables.clear(); // shouldn't be needed?
m_indentLevel--;
stream << indnt << "}" << m_endl;
}
// one day, this should print out non-empty constructor operations too.
void CppWriter::writeConstructorMethods(UMLClassifier * c, QTextStream &stream)
{
const bool generateEmptyConstructors =
UMLApp::app()->commonPolicy()->getAutoGenerateConstructors();
if (forceSections() || generateEmptyConstructors) {
writeComment(QStringLiteral("Constructors/Destructors"), indent(), stream);
writeBlankLine(stream);
writeBlankLine(stream);
}
if (!generateEmptyConstructors)
return;
// empty constructor
QString indnt = indent();
stream << indent() << className_ << "::" << className_ << "()" << m_endl
<< indent() << "{" << m_endl;
m_indentLevel++;
if (c->hasAttributes())
stream << indent() << "initAttributes();" << m_endl;
m_indentLevel--;
stream << indent() << "}" << m_endl;
writeBlankLine(stream);
// empty destructor
stream << indent() << className_ << "::~" << className_ << "()" << m_endl
<< indent() << "{" << m_endl
<< indent() << "}" << m_endl;
writeBlankLine(stream);
}
/**
* Write all datatypes for a given class.
* @param c the class for which we are generating code
* @param permitScope what type of method to write (by Scope)
* @param stream QTextStream serialization target
*/
void CppWriter::writeDataTypes(UMLClassifier *c, Uml::Visibility::Enum permitScope, QTextStream &stream)
{
for (UMLObject* o : c->containedObjects()) {
uIgnoreZeroPointer(o);
if (o->visibility() != permitScope)
continue;
if (!o->isUMLDatatype())
continue;
const UMLDatatype *d = o->asUMLDatatype();
if (d && d->isReference() && d->originType()) {
stream << indent() << "typedef " << d->originType()->name() << " " << d->name() << ";" << m_endl;
}
}
}
/**
* Replaces `string' with STRING_TYPENAME.
*/
QString CppWriter::fixTypeName(const QString &string)
{
if (string.isEmpty())
return QStringLiteral("void");
if (string == QStringLiteral("string")) {
m_stringIncludeRequired = true;
return policyExt()->getStringClassName();
}
return string;
}
/**
* Write all ooperations for a given class.
* @param c the class for which we are generating code
* @param isHeaderMethod true when writing to a header file, false for body file
* @param permitScope what type of method to write (by Scope)
* @param cpp the stream associated with the output file
*/
void CppWriter::writeOperations(UMLClassifier *c, bool isHeaderMethod,
Uml::Visibility::Enum permitScope, QTextStream &cpp)
{
UMLOperationList oplist;
//sort operations by scope first and see if there are abstract methods
UMLOperationList inputlist = c->getOpList();
for (UMLOperation* op : inputlist) {
if (op->visibility() == permitScope) {
oplist.append(op);
}
}
// do people REALLY want these comments? Hmm.
/*
if (forceSections() || oppub.count())
{
writeComment(QStringLiteral("public operations"), indent(), cpp);
writeBlankLine(cpp);
}
*/
writeOperations(c, oplist, isHeaderMethod, cpp);
}
/**
* Write a list of operations for a given class.
* Writes operation in either header or source file.
* @param c the class for which we are generating code
* @param oplist the list of operations you want to write
* @param isHeaderMethod true when writing to a header file, false for body file
* @param cpp the stream associated with the output file
*/
void CppWriter::writeOperations(UMLClassifier *c, UMLOperationList &oplist, bool isHeaderMethod, QTextStream &cpp)
{
const bool generateEmptyConstructors =
UMLApp::app()->commonPolicy()->getAutoGenerateConstructors();
// generate method decl for each operation given
for (UMLOperation* op : oplist) {
QString doc; // buffer for documentation
QString methodReturnType;
UMLAttributeList atl = op->getParmList(); // method parameters
if (op->isConstructorOperation()) {
if (generateEmptyConstructors && atl.count() == 0)
continue; // it's already been written, see writeConstructor{Decls, Methods}
} else if (op->isDestructorOperation()) {
if (generateEmptyConstructors)
continue; // it's already been written, see writeConstructor{Decls, Methods}
} else {
methodReturnType = fixTypeName(op->getTypeName());
if (methodReturnType != QStringLiteral("void"))
doc += policyExt()->getDocToolTag() + QStringLiteral("return ") + methodReturnType + QLatin1Char('\n');
}
QString str;
if (op->isAbstract() || c->isInterface()) {
if (isHeaderMethod) {
// declare abstract method as 'virtual'
str += QStringLiteral("virtual ");
}
}
// static declaration for header file
if (isHeaderMethod && op->isStatic())
str += QStringLiteral("static ");
// returntype of method
str += methodReturnType + QLatin1Char(' ');
if (!isHeaderMethod)
str += className_ + QStringLiteral("::");
str += cleanName(op->name()) + QStringLiteral("(");
// generate parameters
uint j = 0;
for (UMLAttributeListIt atlIt(atl); atlIt.hasNext() ; ++j) {
UMLAttribute* at = atlIt.next();
QString typeName = fixTypeName(at->getTypeName());
QString atName = cleanName(at->name());
QString atNameType = atName;
int i = typeName.indexOf(QLatin1Char('['));
if (i > -1) {
atNameType += typeName.mid(i);
typeName = typeName.left(i);
}
str += typeName + QLatin1Char(' ') + atName;
const QString initVal = at->getInitialValue();
if (! initVal.isEmpty())
str += QStringLiteral(" = ") + initVal;
if (j < (uint)(atl.count() - 1))
str += QStringLiteral(", ");
doc += policyExt()->getDocToolTag() + QStringLiteral("param ") + atName + QLatin1Char(' ') + at->doc() + m_endl;
}
doc = doc.remove(doc.size() - 1, 1); // remove last '\n' of comment
str += QLatin1Char(')');
if (op->getConst())
str += QStringLiteral(" const");
if (op->getOverride())
str += QStringLiteral(" override");
if (isHeaderMethod && op->isAbstract()) {
str += QStringLiteral(" = 0;");
}
// method body : only gets IF it is not in a header
else if (isHeaderMethod && !policyExt()->getOperationsAreInline()) {
str += QLatin1Char(';'); // terminate now
}
else {
str += m_endl + indent() + QLatin1Char('{') + m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
// empty method body - TODO: throw exception
}
else {
str += formatSourceCode(sourceCode, indent() + indent());
}
str += indent() + QLatin1Char('}');
}
// write it out
writeDocumentation(QString(), op->doc(), doc, cpp);
cpp << indent() << str << m_endl;
writeBlankLine(cpp);
}
}
/**
* Intelligently print out header include/forward decl. for associated classes.
* Note:
* To prevent circular including when both classifiers on either end
* of an association have roles we need to have forward declaration of
* the other class...but only IF it is not THIS class (as could happen
* in self-association relationship).
*/
void CppWriter::printAssociationIncludeDecl(UMLAssociationList list, Uml::ID::Type myId, QTextStream &stream)
{
for (UMLAssociation *a : list) {
UMLClassifier *current = nullptr;
bool isFirstClass = true;
// only use OTHER classes (e.g. we don't need to write includes for ourselves!!
// AND only IF the roleName is defined, otherwise, it is not meant to be noticed.
if (a->getObjectId(Uml::RoleType::A) == myId && !a->getRoleName(Uml::RoleType::B).isEmpty()) {
current = a->getObject(Uml::RoleType::B)->asUMLClassifier();
} else if (a->getObjectId(Uml::RoleType::B) == myId && !a->getRoleName(Uml::RoleType::A).isEmpty()) {
current = a->getObject(Uml::RoleType::A)->asUMLClassifier();
isFirstClass = false;
}
// as header doc for this method indicates, we need to be a bit sophisticated on
// how to declare some associations.
if (current) {
if (!isFirstClass && !a->getRoleName(Uml::RoleType::A).isEmpty() && !a->getRoleName(Uml::RoleType::B).isEmpty())
stream << "class " << current->name() << ";" << m_endl; // special case: use forward declaration
else
stream << "#include \"" << current->name() << ".h\"" << m_endl; // just the include statement
}
}
}
/**
* Check that initial values of strings have quotes around them.
*/
QString CppWriter::fixInitialStringDeclValue(const QString &value, const QString &type)
{
QString val = value;
// check for strings only
if (!val.isEmpty() && type == policyExt()->getStringClassName()) {
if (!val.startsWith(QLatin1Char('"')))
val.prepend(QLatin1Char('"'));
if (!val.endsWith(QLatin1Char('"')))
val.append(QLatin1Char('"'));
}
return val;
}
/**
* Returns the name of the given object (if it exists).
* Note:
* Methods like this _shouldn't_ be needed IF we properly did things thruought the code.
*/
QString CppWriter::umlObjectName(UMLObject *obj)
{
return (obj ? obj->name() : QStringLiteral("NULL"));
}
/**
* Write a blank line.
*/
void CppWriter::writeBlankLine(QTextStream &stream)
{
stream << m_endl;
}
/**
* Utility method to break up a block of text, which has embedded newline chars,
* and print them to a stream as separate lines of text, indented as directed.
*/
void CppWriter::printTextAsSeparateLinesWithIndent(const QString &text, const QString &indent, QTextStream &stream)
{
if (text.isEmpty()) {
return;
}
QStringList lines = text.split(QLatin1Char('\n'));
for (int i= 0; i < lines.count(); ++i) {
stream << indent << lines[i] << m_endl;
}
}
/**
* Determine what the variable name of this attribute should be.
*/
QString CppWriter::getAttributeVariableName(UMLAttribute *at)
{
QString fieldName;
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
if (policy && !policy->getClassMemberPrefix().isEmpty())
fieldName = policy->getClassMemberPrefix() + cleanName(at->name());
else
fieldName = cleanName(at->name());
return fieldName;
}
QString CppWriter::getAttributeMethodBaseName(const QString &fieldName)
{
QString fldName = fieldName;
if (policyExt()->getRemovePrefixFromAccessorMethods())
fldName.replace(QRegularExpression(QStringLiteral("^[a-zA-Z]_")), QStringLiteral(""));
return fldName;
}
/**
* Add C++ primitives as datatypes.
* @return the list of default datatypes
*/
QStringList CppWriter::defaultDatatypes() const
{
return Codegen_Utils::cppDatatypes();
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList CppWriter::reservedKeywords() const
{
return Codegen_Utils::reservedCppKeywords();
}
| 56,601
|
C++
|
.cpp
| 1,275
| 36.63451
| 351
| 0.624871
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,531
|
cppsourcecodeoperation.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppsourcecodeoperation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppsourcecodeoperation.h"
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppsourcecodedocument.h"
#include "cppcodedocumentation.h"
#include "uml.h"
CPPSourceCodeOperation::CPPSourceCodeOperation(CPPSourceCodeDocument * doc, UMLOperation *parent, const QString & body, const QString & comment)
: CodeOperation (doc, parent, body, comment)
{
// lets not go with the default comment and instead use
// full-blown cpp documentation object instead
setComment(new CPPCodeDocumentation(doc));
// these things never change..
setOverallIndentationLevel(0);
setEndMethodText(QStringLiteral("}"));
}
CPPSourceCodeOperation::~CPPSourceCodeOperation()
{
}
void CPPSourceCodeOperation::updateContent()
{
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
Q_ASSERT(policy);
bool isInlineMethod = policy->getOperationsAreInline();
if (!isInlineMethod) {
setText(QString()); // change whatever it is to ""
}
}
void CPPSourceCodeOperation::updateMethodDeclaration()
{
CPPSourceCodeDocument * doc = dynamic_cast<CPPSourceCodeDocument*>(getParentDocument());
Q_ASSERT(doc);
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
Q_ASSERT(policy);
UMLClassifier * c = doc->getParentClassifier();
UMLOperation * o = getParentOperation();
bool isInterface = doc->parentIsInterface();
bool isInlineMethod = policy->getOperationsAreInline();
// first, the comment on the operation
QString comment = o->doc();
getComment()->setText(comment);
QString returnType = o->getTypeName();
QString methodName = o->name();
QString paramStr;
QString className = CodeGenerator::cleanName(c->name());
// assemble parameters
UMLAttributeList list = getParentOperation()->getParmList();
int nrofParam = list.count();
int paramNum = 0;
for(UMLAttribute* parm : list) {
QString rType = parm->getTypeName();
QString paramName = parm->name();
paramStr += rType + QLatin1Char(' ') + paramName;
paramNum++;
if (paramNum != nrofParam)
paramStr += QStringLiteral(", ");
}
// no return type for constructors/destructors
if (o->isLifeOperation())
returnType = QString();
// if an operation isn't a constructor/destructor and it has no return type
// this operation should be void
else if (returnType.isEmpty())
returnType = QString(QStringLiteral("void"));
QString startText = returnType + QLatin1Char(' ');
// if a property has a friend stereotype, the operation should
// not be a class name
if (o->stereotype() != QStringLiteral("friend"))
startText += className + QStringLiteral("::");
startText += methodName + QStringLiteral(" (") + paramStr + QLatin1Char(')');
if (o->getConst())
startText += QStringLiteral(" const");
if (o->getOverride())
startText += QStringLiteral(" override");
startText += QStringLiteral(" {");
setStartMethodText(startText);
// Only write this out if it is a child of an interface OR is abstract.
// and it is not inline
if (isInterface || o->isAbstract() || isInlineMethod)
{
setWriteOutText(false);
} else {
setWriteOutText(true);
}
}
| 3,697
|
C++
|
.cpp
| 92
| 35.141304
| 144
| 0.700139
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,532
|
cppcodegenerator.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodegenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodegenerator.h"
// app includes
#include "cppcodedocumentation.h"
#include "cppcodegenerationpolicy.h"
#include "cppsourcecodedocument.h"
#include "cppheadercodedocument.h"
#include "codegen_utils.h"
#include "codeviewerdialog.h"
#include "codedocumentlist.h"
#include "uml.h"
// kde includes
#include <kconfig.h>
// qt includes
const bool CPPCodeGenerator::DEFAULT_BUILD_MAKEFILE = false;
/**
* Basic Constructor.
*/
CPPCodeGenerator::CPPCodeGenerator()
: AdvancedCodeGenerator(),
m_createMakefile(false)
{
UMLApp::app()->setPolicyExt(new CPPCodeGenerationPolicy());
// load Classifier documents from parent document
//initFromParentDocument();
connectSlots();
}
/**
* Destructor.
*/
CPPCodeGenerator::~CPPCodeGenerator()
{
// destroy all separately owned codedocuments (e.g. header docs)
qDeleteAll(m_headercodedocumentVector);
m_headercodedocumentVector.clear();
}
/**
* Returns language identifier. In this case "Cpp".
* @return language identifier
*/
Uml::ProgrammingLanguage::Enum CPPCodeGenerator::language() const
{
return Uml::ProgrammingLanguage::Cpp;
}
/**
* Set the value of m_createMakefile
* @param buildIt the new value to set for creating makefile
*/
void CPPCodeGenerator::setCreateProjectMakefile(bool buildIt)
{
m_createMakefile = buildIt;
CodeDocument * antDoc = findCodeDocumentByID(QLatin1String(CPPMakefileCodeDocument::DOCUMENT_ID_VALUE));
if (antDoc) {
antDoc->setWriteOutCode(buildIt);
}
}
/**
* Get the value of m_createMakefile
* @return the value of m_createMakefile
*/
bool CPPCodeGenerator::getCreateProjectMakefile()
{
return m_createMakefile;
}
/**
* Add a header CodeDocument object from m_headercodedocumentVector List
* @param doc the header code document
* @return success status
*/
bool CPPCodeGenerator::addHeaderCodeDocument(CPPHeaderCodeDocument * doc)
{
QString tag = doc->ID();
// assign a tag if one doesn't already exist
if (tag.isEmpty()) {
tag = QStringLiteral("cppheader")+Uml::ID::toString(doc->getParentClassifier()->id());
doc->setID(tag);
}
if (m_codeDocumentDictionary.contains(tag))
return false; // return false, we already have some object with this tag in the list
else
m_codeDocumentDictionary.insert(tag, doc);
m_headercodedocumentVector.append(doc);
return true;
}
/**
* Remove a header CodeDocument object from m_headercodedocumentVector List
*/
bool CPPCodeGenerator::removeHeaderCodeDocument(CPPHeaderCodeDocument * remove_object)
{
QString tag = remove_object->ID();
if (!(tag.isEmpty()))
m_codeDocumentDictionary.remove(tag);
else
return false;
m_headercodedocumentVector.removeAll(remove_object);
return true;
}
/**
* Get the editing dialog for this code document.
* In the C++ version, we need to make both source and header files as well
* as the makefile available.
* @param parent the parent widget
* @param doc the code document
* @param state the code viewer state
* @return the code viewer dialog object
*/
CodeViewerDialog * CPPCodeGenerator::getCodeViewerDialog(QWidget* parent, CodeDocument *doc,
Settings::CodeViewerState & state)
{
ClassifierCodeDocument * cdoc = dynamic_cast<ClassifierCodeDocument*>(doc);
if (!cdoc)
// bah..not a classcode document?? then just use vanilla version
return AdvancedCodeGenerator::getCodeViewerDialog(parent, doc, state);
else {
// build with passed (source) code document
CodeViewerDialog *dialog;
// use classifier to find appropriate header document
UMLClassifier * c = cdoc->getParentClassifier();
CPPHeaderCodeDocument * hdoc = findHeaderCodeDocumentByClassifier(c);
if (hdoc) {
// if we have a header document..build with that
dialog = new CodeViewerDialog(parent, hdoc, state);
dialog->addCodeDocument(doc);
}
else {
// shouldn't happen, but lets try to gracefully deliver something.
dialog = new CodeViewerDialog(parent, doc, state);
}
// add in makefile if available and desired
if (getCreateProjectMakefile()) {
dialog->addCodeDocument(findCodeDocumentByID(QLatin1String(CPPMakefileCodeDocument::DOCUMENT_ID_VALUE)));
}
return dialog;
}
}
/**
* Change the following dataTypes to the ones the user really
* wants in their code. Not yet complete.
* @param name type name
* @return clean name
*/
QString CPPCodeGenerator::fixTypeName(const QString &name)
{
return cleanName(name);
}
/**
* Save the XMI representation of this object.
* Special method needed so that we write out the header code documents.
* @param writer QXmlStreamWriter serialization target
*/
void CPPCodeGenerator::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("codegenerator"));
writer.writeAttribute(QStringLiteral("language"), QStringLiteral("C++"));
const CodeDocumentList * docList = getCodeDocumentList();
CodeDocumentList::ConstIterator it = docList->begin();
CodeDocumentList::ConstIterator end = docList->end();
for (; it != end; ++it)
(*it)->saveToXMI(writer);
CodeDocumentList::Iterator it2 = m_headercodedocumentVector.begin();
CodeDocumentList::Iterator end2 = m_headercodedocumentVector.end();
for (; it2 != end2; ++it2)
(*it2)->saveToXMI(writer);
writer.writeEndElement();
}
/**
* Force a synchronize of this code generator, and its present contents, to that of the parent UMLDocument.
* "UserGenerated" code will be preserved, but Autogenerated contents will be updated/replaced
* or removed as is apppropriate.
* Need to override parent method because we have header documents to consider too.
*/
void CPPCodeGenerator::syncCodeToDocument()
{
const CodeDocumentList * docList = getCodeDocumentList();
CodeDocumentList::ConstIterator it = docList->begin();
CodeDocumentList::ConstIterator end = docList->end();
for (; it != end; ++it) {
(*it)->synchronize();
}
CodeDocumentList::Iterator it2 = m_headercodedocumentVector.begin();
CodeDocumentList::Iterator end2 = m_headercodedocumentVector.end();
for (; it2 != end2; ++it2) {
(*it2)->synchronize();
}
}
/**
* Write out all code documents to file as appropriate.
*/
void CPPCodeGenerator::writeCodeToFile()
{
// write all source documents (incl. Makefile)
writeListedCodeDocsToFile(getCodeDocumentList());
// write all header documents
writeListedCodeDocsToFile(&m_headercodedocumentVector);
}
/**
* this method is here to provide class wizard the
* ability to write out only those classes which
* are selected by the user.
* overridden because we need to be able to generate code for
* both the header and source documents
*/
void CPPCodeGenerator::writeCodeToFile(UMLClassifierList & concepts)
{
CodeDocumentList docs;
for(UMLClassifier* classifier : concepts) {
CodeDocument * doc = findCodeDocumentByClassifier(classifier);
if(doc)
docs.append(doc);
CodeDocument * hdoc = findHeaderCodeDocumentByClassifier(classifier);
if(hdoc)
docs.append(hdoc);
}
writeListedCodeDocsToFile(&docs);
}
/**
* Find a cppheadercodedocument by the given classifier.
* @param classifier UML classifier
* @return CPPHeaderCodeDocument object
*/
CPPHeaderCodeDocument * CPPCodeGenerator::findHeaderCodeDocumentByClassifier(UMLClassifier * classifier)
{
CodeDocument * doc = findCodeDocumentByID(QStringLiteral("cppheader")+Uml::ID::toString(classifier->id()));
return dynamic_cast<CPPHeaderCodeDocument*>(doc);
}
/**
* Generate classifier code document (source document version).
* @param classifier the classifier for which the CodeDocument is to be created
* @return created ClassifierCodeDocument object
*/
CodeDocument * CPPCodeGenerator::newClassifierCodeDocument(UMLClassifier * classifier)
{
ClassifierCodeDocument *doc = new CPPSourceCodeDocument(classifier);
doc->initCodeClassFields();
return doc;
}
/**
* Generate header classifier code document.
* @param classifier the classifier for which the CodeDocument is to be created
* @return created CPPHeaderCodeDocument object
*/
CPPHeaderCodeDocument * CPPCodeGenerator::newHeaderClassifierCodeDocument(UMLClassifier * classifier)
{
CPPHeaderCodeDocument *doc = new CPPHeaderCodeDocument(classifier);
doc->initCodeClassFields();
return doc;
}
/**
* Create a new CPPMakefileCodeDocument.
* @return CPPMakefileCodeDocument object
*/
CPPMakefileCodeDocument * CPPCodeGenerator::newMakefileCodeDocument()
{
return new CPPMakefileCodeDocument();
}
/**
* Overloaded so that we may have both source and header documents for each
* classifier.
*/
void CPPCodeGenerator::initFromParentDocument()
{
// Walk through the document converting classifiers into
// classifier code documents as needed (e.g only if doesn't exist)
UMLClassifierList concepts = UMLApp::app()->document()->classesAndInterfaces();
for(UMLClassifier* c : concepts) {
// Doesn't exist? Then build one.
CodeDocument * codeDoc = findCodeDocumentByClassifier(c);
if (!codeDoc)
{
codeDoc = newClassifierCodeDocument(c);
codeDoc->synchronize();
addCodeDocument(codeDoc); // this will also add a unique tag to the code document
}
CPPHeaderCodeDocument * hcodeDoc = findHeaderCodeDocumentByClassifier(c);
if (!hcodeDoc)
{
hcodeDoc = newHeaderClassifierCodeDocument(c);
hcodeDoc->synchronize();
addHeaderCodeDocument(hcodeDoc); // this will also add a unique tag to the code document
}
}
}
/**
* Check for adding objects to the UMLDocument.
* They are need to be overridden here because unlike in the Java (or most other lang)
* we add 2 types of classifiercodedocument per classifier,
* e.g. a "source" and a "header" document.
* Need to worry about adding both source, and header documents for each classifier.
* @param obj the UML object
*/
void CPPCodeGenerator::checkAddUMLObject(UMLObject * obj)
{
if (!obj)
return;
// if the obj being created is a native data type
// there's no reason to create a .h/.cpp file
if (isReservedKeyword(obj->name()))
return;
UMLClassifier * c = obj->asUMLClassifier();
if(c) {
CodeDocument * cDoc = newClassifierCodeDocument(c);
CPPHeaderCodeDocument * hcodeDoc = newHeaderClassifierCodeDocument(c);
addCodeDocument(cDoc);
addHeaderCodeDocument(hcodeDoc); // this will also add a unique tag to the code document
}
}
/**
* Check for removing objects to the UMLDocument.
* they are need to be overridden here because unlike in the Java (or most other lang)
* we add 2 types of classifiercodedocument per classifier,
* e.g. a "source" and a "header" document.
* Need to worry about removing both source, and header documents for each classifier.
* @param obj the UML object
*/
void CPPCodeGenerator::checkRemoveUMLObject(UMLObject * obj)
{
if (!obj)
return;
UMLClassifier * c = obj->asUMLClassifier();
if(c) {
// source
ClassifierCodeDocument * cDoc = (ClassifierCodeDocument*) findCodeDocumentByClassifier(c);
if (cDoc)
removeCodeDocument(cDoc);
// header
CPPHeaderCodeDocument * hcodeDoc = findHeaderCodeDocumentByClassifier(c);
if (hcodeDoc)
removeHeaderCodeDocument(hcodeDoc);
}
}
/**
* Add C++ primitives as datatypes.
* @return a string list of C++ datatypes
*/
QStringList CPPCodeGenerator::defaultDatatypes() const
{
return Codegen_Utils::cppDatatypes();
}
/**
* Get list of reserved keywords.
* @return a string list with reserve keywords of this language
*/
QStringList CPPCodeGenerator::reservedKeywords() const
{
return Codegen_Utils::reservedCppKeywords();
}
/**
* Add the default stereotypes for c++ (constructor, int etc)
*/
void CPPCodeGenerator::createDefaultStereotypes()
{
Codegen_Utils::createCppStereotypes();
}
| 12,593
|
C++
|
.cpp
| 358
| 31.039106
| 117
| 0.723946
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,533
|
cppcodeclassfield.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodeclassfield.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodeclassfield.h"
// local includes
#include "attribute.h"
#include "classifiercodedocument.h"
#include "codegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
CPPCodeClassField::CPPCodeClassField (ClassifierCodeDocument * parentDoc, UMLRole * role)
: CodeClassField(parentDoc, role)
{
}
CPPCodeClassField::CPPCodeClassField (ClassifierCodeDocument * parentDoc, UMLAttribute * attrib)
: CodeClassField(parentDoc, attrib)
{
}
CPPCodeClassField::~CPPCodeClassField ()
{
}
QString CPPCodeClassField::getFieldName()
{
if (parentIsAttribute())
{
UMLAttribute * at = (UMLAttribute*) getParentObject();
return cleanName(at->name());
}
else
{
UMLRole * role = (UMLRole*) getParentObject();
QString roleName = role->name();
if(fieldIsSingleValue()) {
return roleName.replace(0, 1, roleName.left(1).toLower());
} else {
return roleName.toLower() + QStringLiteral("Vector");
}
}
}
QString CPPCodeClassField::getListFieldClassName ()
{
CodeGenPolicyExt * p = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy *policy = dynamic_cast<CPPCodeGenerationPolicy*>(p);
return policy->getVectorClassName();
}
QString CPPCodeClassField::getInitialValue()
{
if (parentIsAttribute())
{
const UMLAttribute * at = getParentObject()->asUMLAttribute();
if (at) {
return fixInitialStringDeclValue(at->getInitialValue(), getTypeName());
} else {
logError0("parent object is not a UMLAttribute");
return QString();
}
}
else
{
if(fieldIsSingleValue()) {
// FIX : IF the multiplicity is "1" then we should init a new object here, if its 0 or 1,
// then we can just return 'empty' string (minor problem).
return QString();
} else {
return QStringLiteral(" new ") + getListFieldClassName() + QStringLiteral("()");
}
}
}
| 2,334
|
C++
|
.cpp
| 74
| 26.243243
| 101
| 0.671111
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,534
|
cppheaderclassdeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppheaderclassdeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppheaderclassdeclarationblock.h"
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppcodedocumentation.h"
#include "model_utils.h"
#include "uml.h"
CPPHeaderClassDeclarationBlock::CPPHeaderClassDeclarationBlock
(CPPHeaderCodeDocument * parentDoc, const QString &startText, const QString &endText, const QString &comment)
: OwnedHierarchicalCodeBlock(parentDoc->getParentClassifier(), parentDoc, startText, endText, comment)
{
init(parentDoc, comment);
}
CPPHeaderClassDeclarationBlock::~CPPHeaderClassDeclarationBlock ()
{
}
/**
* load params from the appropriate XMI element node.
*/
void CPPHeaderClassDeclarationBlock::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
/** set the class attributes from a passed object
*/
void CPPHeaderClassDeclarationBlock::setAttributesFromObject (TextBlock * obj)
{
HierarchicalCodeBlock::setAttributesFromObject(obj);
}
/**
* Save the XMI representation of this object
*/
void CPPHeaderClassDeclarationBlock::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("cppheaderclassdeclarationblock"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
/**
* update the start and end text for this hierarchicalcodeblock.
*/
void CPPHeaderClassDeclarationBlock::updateContent ()
{
CPPHeaderCodeDocument *parentDoc = dynamic_cast<CPPHeaderCodeDocument*>(getParentDocument());
UMLClassifier *c = parentDoc->getParentClassifier();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
bool isInterface = parentDoc->parentIsInterface(); // a little shortcut
QString CPPHeaderClassName = CodeGenerator::cleanName(c->name());
bool forceDoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
// COMMENT
//check if class is abstract.. it should have abstract methods
if(!isInterface && c->isAbstract() && !c->hasAbstractOps())
{
getComment()->setText(QStringLiteral("******************************* Abstract Class ****************************") + endLine
+ CPPHeaderClassName + QStringLiteral(" does not have any pure virtual methods, but its author") + endLine
+ QStringLiteral(" defined it as an abstract class, so you should not use it directly.") + endLine
+ QStringLiteral(" Inherit from it instead and create only objects from the derived classes") + endLine
+ QStringLiteral("*****************************************************************************"));
} else {
if(isInterface)
getComment()->setText(QStringLiteral("Interface ") + CPPHeaderClassName + endLine + c->doc());
else
getComment()->setText(QStringLiteral("Class ") + CPPHeaderClassName + endLine + c->doc());
}
if(forceDoc || !c->doc().isEmpty())
getComment()->setWriteOutText(true);
else
getComment()->setWriteOutText(false);
// Now set START/ENDING Text
QString startText;
/*
*/
/*
if(parentDoc->parentIsInterface())
startText.append(QStringLiteral("interface "));
else
*/
startText.append(QStringLiteral("class "));
startText.append(CPPHeaderClassName);
// write inheritances out
UMLClassifierList superclasses = c->findSuperClassConcepts();
int nrof_superclasses = superclasses.count();
// write out inheritance
int i = 0;
if(nrof_superclasses >0)
startText.append(QStringLiteral(" : "));
for(UMLClassifier* classifier : superclasses) {
startText.append(Uml::Visibility::toString(classifier->visibility()) + QLatin1Char(' ') +
CodeGenerator::cleanName(classifier->name()));
if(i != (nrof_superclasses-1))
startText.append(QStringLiteral(", "));
i++;
}
// Set the header and end text for the hier.codeblock
setStartText(startText + QStringLiteral(" {"));
// setEndText(QStringLiteral("}")); // not needed
}
void CPPHeaderClassDeclarationBlock::init (CPPHeaderCodeDocument *parentDoc, const QString &comment)
{
setComment(new CPPCodeDocumentation(parentDoc));
getComment()->setText(comment);
setEndText(QStringLiteral("};"));
}
| 4,558
|
C++
|
.cpp
| 107
| 36.981308
| 136
| 0.687528
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,535
|
cppcodecomment.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodecomment.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodecomment.h"
// qt includes
#include <QRegularExpression>
CPPCodeComment::CPPCodeComment (CodeDocument * doc, const QString & text)
: CodeComment (doc, text)
{
}
CPPCodeComment::~CPPCodeComment ()
{
}
void CPPCodeComment::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("cppcodecomment"));
setAttributesOnNode(writer); // as we added no additional fields to this class we may
// just use parent TextBlock method
writer.writeEndElement();
}
QString CPPCodeComment::toString () const
{
QString output;
// simple output method
if(getWriteOutText())
{
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
output.append(formatMultiLineText (getText() + endLine, indent + QStringLiteral("// "), endLine));
}
return output;
}
QString CPPCodeComment::getNewEditorLine (int amount)
{
QString line = getIndentationString(amount) + QStringLiteral("// ");
return line;
}
QString CPPCodeComment::unformatText (const QString & text, const QString & indent)
{
// remove leading or trailing comment stuff
QString mytext = TextBlock::unformatText(text, indent);
// now leading slashes
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
| 1,576
|
C++
|
.cpp
| 48
| 29.229167
| 106
| 0.736634
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,536
|
cppmakecodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppmakecodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppcodegenerator.h"
#include <QRegularExpression>
const char * CPPMakefileCodeDocument::DOCUMENT_ID_VALUE = "Makefile_DOC";
CPPMakefileCodeDocument::CPPMakefileCodeDocument ()
{
setFileName(QStringLiteral("Makefile")); // default name
setFileExtension(QString());
setID(QLatin1String(DOCUMENT_ID_VALUE)); // default id tag for this type of document
}
CPPMakefileCodeDocument::~CPPMakefileCodeDocument ()
{
}
// we add in our code blocks that describe how to generate
// the project here...
void CPPMakefileCodeDocument::updateContent()
{
// FIX : fill in content
}
/**
* @return QString
*/
QString CPPMakefileCodeDocument::toString () const
{
return QStringLiteral("# cpp make build document");
}
// We overwritten by CPP language implementation to get lowercase path
QString CPPMakefileCodeDocument::getPath () const
{
QString path = getPackage();
// Replace all white spaces with blanks
path = path.simplified();
// Replace all blanks with underscore
path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
path.replace(QRegularExpression(QStringLiteral("\\.")),QStringLiteral("/"));
path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/"));
path = path.toLower();
return path;
}
| 1,530
|
C++
|
.cpp
| 43
| 32.627907
| 92
| 0.750849
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,537
|
cppcodedocumentation.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodedocumentation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodedocumentation.h"
// app includes
#include "codedocument.h"
#include "codegenerator.h"
#include "codegenerationpolicy.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
CPPCodeDocumentation::CPPCodeDocumentation(CodeDocument * doc, const QString & text)
: CodeComment(doc, text)
{
}
CPPCodeDocumentation::~CPPCodeDocumentation()
{
}
/**
* Save the XMI representation of this object
*/
void CPPCodeDocumentation::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("cppcodedocumentation"));
setAttributesOnNode(writer); // as we added no additional fields to this class we may
// just use parent TextBlock method
writer.writeEndElement();
}
/**
* @return QString
*/
QString CPPCodeDocumentation::toString() const
{
QString output;
// simple output method
if(getWriteOutText())
{
bool useDoubleDashOutput = true;
// need to figure out output type from cpp policy
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
useDoubleDashOutput = false;
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
if(useDoubleDashOutput)
{
if(!body.isEmpty())
output.append(formatMultiLineText (body, indent + QStringLiteral("// "), endLine));
} else {
output.append(indent + QStringLiteral("/**") + endLine);
output.append(formatMultiLineText (body, indent + QStringLiteral(" * "), endLine));
output.append(indent + QStringLiteral(" */") + endLine);
}
}
return output;
}
QString CPPCodeDocumentation::getNewEditorLine(int amount)
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return getIndentationString(amount) + QStringLiteral(" * ");
else
return getIndentationString(amount) + QStringLiteral("// ");
}
int CPPCodeDocumentation::firstEditableLine()
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return 1;
return 0;
}
int CPPCodeDocumentation::lastEditableLine()
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
return -1; // very last line is NOT editable
}
return 0;
}
/** UnFormat a long text string. Typically, this means removing
* the indentation (linePrefix) and/or newline chars from each line.
*/
QString CPPCodeDocumentation::unformatText(const QString & text, const QString & indent)
{
QString mytext = TextBlock::unformatText(text, indent);
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
// remove leading or trailing comment stuff
mytext.remove(QRegularExpression(QLatin1Char('^') + indent));
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\*\\*\\s*\n?")));
mytext.remove(QRegularExpression(QStringLiteral("\\s*\\*\\/\\s*\n?$")));
mytext.remove(QRegularExpression(QStringLiteral("^\\s*\\*\\s*")));
} else
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
| 3,673
|
C++
|
.cpp
| 102
| 31.264706
| 99
| 0.697243
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,538
|
cppcodegenerationpolicy.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodegenerationpolicy.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodegenerationpolicy.h"
// app includes
#include "cppcodegenerationpolicypage.h"
#include "uml.h"
#include "umbrellosettings.h"
#include "optionstate.h"
// kde includes
#include <kconfig.h>
// qt includes
#include <QRegularExpression>
const char * CPPCodeGenerationPolicy::DEFAULT_VECTOR_METHOD_APPEND = "%VARNAME%.push_back(value);";
const char * CPPCodeGenerationPolicy::DEFAULT_VECTOR_METHOD_REMOVE = "int size = %VARNAME%.size();\nfor (int i = 0; i < size; ++i) {\n\t%ITEMCLASS% item = %VARNAME%.at(i);\n\tif(item == value) {\n\t\tvector<%ITEMCLASS%>::iterator it = %VARNAME%.begin() + i;\n\t\t%VARNAME%.erase(it);\n\t\treturn;\n\t}\n }";
const char * CPPCodeGenerationPolicy::DEFAULT_VECTOR_METHOD_INIT = " "; // nothing to do in std::vector krazy:exclude=doublequote_chars
const char * CPPCodeGenerationPolicy::DEFAULT_OBJECT_METHOD_INIT = "%VARNAME% = new %ITEMCLASS%();";
/**
* Constructor.
*/
CPPCodeGenerationPolicy::CPPCodeGenerationPolicy()
{
init();
}
/**
* Destructor.
*/
CPPCodeGenerationPolicy::~CPPCodeGenerationPolicy()
{
}
/**
* Set the value of publicAccessors
* @param var the new value
*/
void CPPCodeGenerationPolicy::setAccessorsArePublic(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.publicAccessors = var;
// @todo we should probably use an own signal for this
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_publicAccessors
* @return the boolean value of m_publicAccessors
*/
bool CPPCodeGenerationPolicy::getAccessorsArePublic()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.publicAccessors;
}
/**
* Set the value of m_inlineAccessors
* @param var the new value
*/
void CPPCodeGenerationPolicy::setAccessorsAreInline(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.inlineAccessors = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_inlineAccessors.
* @return the boolean value of m_inlineAccessors
*/
bool CPPCodeGenerationPolicy::getAccessorsAreInline()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.inlineAccessors;
}
/**
* Set the value of m_inlineOperations.
* @param var the new value
*/
void CPPCodeGenerationPolicy::setOperationsAreInline(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.inlineOps = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_inlineOperations.
* @return the boolean value of m_inlineOperations
*/
bool CPPCodeGenerationPolicy::getOperationsAreInline()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.inlineOps;
}
/**
* Set the value of m_virtualDestructors.
* @param var the new value
*/
void CPPCodeGenerationPolicy::setDestructorsAreVirtual(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.virtualDestructors = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_virtualDestructors.
* @return the boolean value of m_virtualDestructors
*/
bool CPPCodeGenerationPolicy::getDestructorsAreVirtual()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.virtualDestructors;
}
void CPPCodeGenerationPolicy::setGetterWithGetPrefix(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.getterWithGetPrefix = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
bool CPPCodeGenerationPolicy::getGetterWithGetPrefix()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.getterWithGetPrefix;
}
void CPPCodeGenerationPolicy::setRemovePrefixFromAccessorMethods(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.removePrefixFromAccessorMethods = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
bool CPPCodeGenerationPolicy::getRemovePrefixFromAccessorMethods()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.removePrefixFromAccessorMethods;
}
void CPPCodeGenerationPolicy::setAccessorMethodsStartWithUpperCase(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.accessorMethodsStartWithUpperCase = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
bool CPPCodeGenerationPolicy::getAccessorMethodsStartWithUpperCase()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.accessorMethodsStartWithUpperCase;
}
/**
* Set the value of m_packageIsNamespace.
* @param var the new value
*/
void CPPCodeGenerationPolicy::setPackageIsNamespace(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.packageIsNamespace = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_packageIsNamespace.
* @return the boolean value of m_packageIsNamespace
*/
bool CPPCodeGenerationPolicy::getPackageIsNamespace()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.packageIsNamespace;
}
/**
* Set the value of m_autoGenerateAccessors.
* @param var the new value
*/
void CPPCodeGenerationPolicy::setAutoGenerateAccessors(bool var)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.autoGenAccessors = var;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Get the value of m_autoGenerateAccessors.
* @return the boolean value of m_autoGenerateAccessors
*/
bool CPPCodeGenerationPolicy::getAutoGenerateAccessors()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.autoGenAccessors;
}
QString CPPCodeGenerationPolicy::getStringClassName()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.stringClassName;
}
QString CPPCodeGenerationPolicy::getStringClassNameInclude()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.stringClassNameInclude;
}
QString CPPCodeGenerationPolicy::getVectorClassName()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName;
}
QString CPPCodeGenerationPolicy::getVectorClassNameInclude()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassNameInclude;
}
void CPPCodeGenerationPolicy::setStringClassName(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.stringClassName = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
void CPPCodeGenerationPolicy::setStringClassNameInclude(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.stringClassNameInclude = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
void CPPCodeGenerationPolicy::setVectorClassName(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
void CPPCodeGenerationPolicy::setVectorClassNameInclude(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassNameInclude = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
void CPPCodeGenerationPolicy::setClassMemberPrefix(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.classMemberPrefix = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
QString CPPCodeGenerationPolicy::getClassMemberPrefix()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.classMemberPrefix;
}
void CPPCodeGenerationPolicy::setDocToolTag(const QString &value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.docToolTag = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
QString CPPCodeGenerationPolicy::getDocToolTag()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.docToolTag;
}
/**
* Determine if the string include is global.
* @return value of flag
*/
bool CPPCodeGenerationPolicy::stringIncludeIsGlobal()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.stringIncludeIsGlobal;
}
/**
* Determine if the vector include is global.
* @return value of flag
*/
bool CPPCodeGenerationPolicy::vectorIncludeIsGlobal()
{
return Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorIncludeIsGlobal;
}
/**
* Set flag whether string include is global.
* @param value the value of the flag
*/
void CPPCodeGenerationPolicy::setStringIncludeIsGlobal(bool value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.stringIncludeIsGlobal = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Set flag whether vector include is global.
* @param value the value of the flag
*/
void CPPCodeGenerationPolicy::setVectorIncludeIsGlobal(bool value)
{
Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorIncludeIsGlobal = value;
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
QString CPPCodeGenerationPolicy::getVectorMethodAppend(const QString & variableName, const QString & itemClassName)
{
QString value = m_vectorMethodAppendBase;
if(!variableName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%VARNAME%")), variableName);
value.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName);
if(!itemClassName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), itemClassName);
return value;
}
QString CPPCodeGenerationPolicy::getVectorMethodRemove(const QString & variableName, const QString & itemClassName)
{
QString value = m_vectorMethodRemoveBase;
if(!variableName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%VARNAME%")), variableName);
value.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName);
if(!itemClassName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), itemClassName);
return value;
}
QString CPPCodeGenerationPolicy::getVectorMethodInit(const QString & variableName, const QString & itemClassName)
{
QString value = m_vectorMethodInitBase;
if(!variableName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%VARNAME%")), variableName);
value.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName);
if(!itemClassName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), itemClassName);
return value;
}
/**
* Be somewhat flexible about how new object classes are initialized.
* Not sure if this should be user configureable. For now, it is not.
* @param variableName variable name
* @param itemClassName item class name
* @return object method init string
*/
QString CPPCodeGenerationPolicy::getObjectMethodInit(const QString & variableName, const QString & itemClassName)
{
QString value = m_objectMethodInitBase;
if(!variableName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%VARNAME%")), variableName);
value.replace(QRegularExpression(QStringLiteral("%VECTORTYPENAME%")), Settings::optionState().codeGenerationState.cppCodeGenerationState.vectorClassName);
if(!itemClassName.isEmpty())
value.replace(QRegularExpression(QStringLiteral("%ITEMCLASS%")), itemClassName);
return value;
}
/**
* Set the defaults for this code generator from the passed generator.
* @param cppclone code generation policy object for cloning
* @param emitUpdateSignal flag whether to emit update signal
*/
void CPPCodeGenerationPolicy::setDefaults(CPPCodeGenerationPolicy * cppclone, bool emitUpdateSignal)
{
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
{
setAutoGenerateAccessors(cppclone->getAutoGenerateAccessors());
setAccessorsAreInline(cppclone->getAccessorsAreInline());
setOperationsAreInline(cppclone->getOperationsAreInline());
setDestructorsAreVirtual(cppclone->getDestructorsAreVirtual());
setGetterWithGetPrefix(cppclone->getGetterWithGetPrefix());
setRemovePrefixFromAccessorMethods(cppclone->getRemovePrefixFromAccessorMethods());
setAccessorMethodsStartWithUpperCase(cppclone->getAccessorMethodsStartWithUpperCase());
setPackageIsNamespace(cppclone->getPackageIsNamespace());
setStringClassName(cppclone->getStringClassName());
setStringClassNameInclude(cppclone->getStringClassNameInclude());
setStringIncludeIsGlobal(cppclone->stringIncludeIsGlobal());
setVectorClassName(cppclone->getVectorClassName());
setVectorClassNameInclude(cppclone->getVectorClassNameInclude());
setVectorIncludeIsGlobal(cppclone->vectorIncludeIsGlobal());
setDocToolTag(cppclone->getDocToolTag());
setClassMemberPrefix(cppclone->getClassMemberPrefix());
}
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Set the defaults from a config file for this code generator from the passed KConfig pointer.
* @param emitUpdateSignal flag whether to emit update signal
*/
void CPPCodeGenerationPolicy::setDefaults(bool emitUpdateSignal)
{
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
setAutoGenerateAccessors(UmbrelloSettings::autoGenAccessors());
setAccessorsAreInline(UmbrelloSettings::inlineAccessors());
setAccessorsArePublic(UmbrelloSettings::publicAccessors());
setOperationsAreInline(UmbrelloSettings::inlineOps());
setDestructorsAreVirtual(UmbrelloSettings::virtualDestructors());
setGetterWithGetPrefix(UmbrelloSettings::getterWithGetPrefix());
setRemovePrefixFromAccessorMethods(UmbrelloSettings::removePrefixFromAccessorMethods());
setAccessorMethodsStartWithUpperCase(UmbrelloSettings::accessorMethodsStartWithUpperCase());
setPackageIsNamespace(UmbrelloSettings::packageIsNamespace());
setStringClassName(UmbrelloSettings::stringClassName());
setStringClassNameInclude(UmbrelloSettings::stringClassNameInclude());
setStringIncludeIsGlobal(UmbrelloSettings::stringIncludeIsGlobal());
setVectorClassName(UmbrelloSettings::vectorClassName());
setVectorClassNameInclude(UmbrelloSettings::vectorClassNameInclude());
setVectorIncludeIsGlobal(UmbrelloSettings::vectorIncludeIsGlobal());
setDocToolTag(UmbrelloSettings::docToolTag());
setClassMemberPrefix(UmbrelloSettings::classMemberPrefix());
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
UMLApp::app()->commonPolicy()->emitModifiedCodeContentSig();
}
/**
* Create a new dialog interface for this object.
* @param parent the parent widget
* @param name the name of the page
* @return dialog object
*/
CodeGenerationPolicyPage * CPPCodeGenerationPolicy::createPage(QWidget *parent, const char *name)
{
return new CPPCodeGenerationPolicyPage(parent, name, this);
}
/**
* Initialisation routine.
*/
void CPPCodeGenerationPolicy::init()
{
blockSignals(true);
m_vectorMethodAppendBase = QLatin1String(DEFAULT_VECTOR_METHOD_APPEND);
m_vectorMethodRemoveBase = QLatin1String(DEFAULT_VECTOR_METHOD_REMOVE);
m_vectorMethodInitBase = QLatin1String(DEFAULT_VECTOR_METHOD_INIT);
m_objectMethodInitBase = QLatin1String(DEFAULT_OBJECT_METHOD_INIT);
Settings::OptionState optionState = Settings::optionState();
setAutoGenerateAccessors(optionState.codeGenerationState.cppCodeGenerationState.autoGenAccessors);
setAccessorsAreInline(optionState.codeGenerationState.cppCodeGenerationState.inlineAccessors);
setAccessorsArePublic(optionState.codeGenerationState.cppCodeGenerationState.publicAccessors);
setOperationsAreInline(optionState.codeGenerationState.cppCodeGenerationState.inlineOps);
setDestructorsAreVirtual(optionState.codeGenerationState.cppCodeGenerationState.virtualDestructors);
setGetterWithGetPrefix(optionState.codeGenerationState.cppCodeGenerationState.getterWithGetPrefix);
setRemovePrefixFromAccessorMethods(optionState.codeGenerationState.cppCodeGenerationState.removePrefixFromAccessorMethods);
setAccessorMethodsStartWithUpperCase(optionState.codeGenerationState.cppCodeGenerationState.accessorMethodsStartWithUpperCase);
setPackageIsNamespace(optionState.codeGenerationState.cppCodeGenerationState.packageIsNamespace);
setStringClassName(optionState.codeGenerationState.cppCodeGenerationState.stringClassName);
setStringClassNameInclude(optionState.codeGenerationState.cppCodeGenerationState.stringClassNameInclude);
setStringIncludeIsGlobal(optionState.codeGenerationState.cppCodeGenerationState.stringIncludeIsGlobal);
setVectorClassName(optionState.codeGenerationState.cppCodeGenerationState.vectorClassName);
setVectorClassNameInclude(optionState.codeGenerationState.cppCodeGenerationState.vectorClassNameInclude);
setVectorIncludeIsGlobal(optionState.codeGenerationState.cppCodeGenerationState.vectorIncludeIsGlobal);
setDocToolTag(optionState.codeGenerationState.cppCodeGenerationState.docToolTag);
setClassMemberPrefix(optionState.codeGenerationState.cppCodeGenerationState.classMemberPrefix);
blockSignals(false);
}
| 18,324
|
C++
|
.cpp
| 400
| 42.63
| 307
| 0.808761
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,539
|
cppcodegenerationpolicypage.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppcodegenerationpolicypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppcodegenerationpolicypage.h"
// app includes
#include "debug_utils.h"
#include "uml.h"
// kde includes
#include <KLocalizedString>
#include <kcombobox.h>
// qt includes
#include <QCheckBox>
#include <QLabel>
DEBUG_REGISTER(CPPCodeGenerationPolicyPage)
CPPCodeGenerationPolicyPage::CPPCodeGenerationPolicyPage(QWidget *parent, const char *name, CPPCodeGenerationPolicy * policy)
: CodeGenerationPolicyPage(parent, name, policy)
{
CodeGenerationPolicy *common = UMLApp::app()->commonPolicy();
QVBoxLayout* vboxLayout = new QVBoxLayout(this);
form = new CPPCodeGenerationForm(this);
form->ui_selectCommentStyle->setCurrentIndex((int)(common->getCommentStyle()));
form->setPackageIsANamespace(policy->getPackageIsNamespace());
form->setVirtualDestructors(policy->getDestructorsAreVirtual());
form->setGenerateAccessorMethods(policy->getAutoGenerateAccessors());
form->setGenerateEmptyConstructors(common->getAutoGenerateConstructors());
form->setOperationsAreInline(policy->getOperationsAreInline());
form->setAccessorsAreInline(policy->getAccessorsAreInline());
form->setAccessorsArePublic(policy->getAccessorsArePublic());
form->setGetterWithoutGetPrefix(policy->getGetterWithGetPrefix());
form->setRemovePrefixFromAccessorMethodName(policy->getRemovePrefixFromAccessorMethods());
form->setAccessorMethodsStartWithUpperCase(policy->getAccessorMethodsStartWithUpperCase());
form->setDocToolTag(policy->getDocToolTag());
form->setClassMemberPrefix(policy->getClassMemberPrefix());
form->ui_stringClassHCombo->setCurrentItem(policy->getStringClassName(), true);
form->ui_listClassHCombo->setCurrentItem(policy->getVectorClassName(), true);
form->ui_stringIncludeFileHistoryCombo->setCurrentItem(policy->getStringClassNameInclude(), true);
form->ui_listIncludeFileHistoryCombo->setCurrentItem(policy->getVectorClassNameInclude(), true);
form->ui_globalStringCheckBox->setChecked(policy->stringIncludeIsGlobal());
form->ui_globalListCheckBox->setChecked(policy->vectorIncludeIsGlobal());
vboxLayout->addWidget(form);
}
CPPCodeGenerationPolicyPage::~CPPCodeGenerationPolicyPage()
{
}
void CPPCodeGenerationPolicyPage::apply()
{
CodeGenerationPolicy *common = UMLApp::app()->commonPolicy();
// now do our cpp-specific configs
CPPCodeGenerationPolicy * parent = (CPPCodeGenerationPolicy*) m_parentPolicy;
// block signals so that we don't generate too many sync signals for child code
// documents
parent->blockSignals(true);
common->setCommentStyle((CodeGenerationPolicy::CommentStyle) form->ui_selectCommentStyle->currentIndex());
common->setAutoGenerateConstructors(form->getGenerateEmptyConstructors());
parent->setAutoGenerateAccessors(form->getGenerateAccessorMethods());
bool accMethodGen = form->getGenerateAccessorMethods();
logDebug1("CPPCodeGenerationPolicyPage::apply: form->getGenerateAccessorMethods returns %1", accMethodGen);
parent->setDestructorsAreVirtual(form->getVirtualDestructors());
parent->setPackageIsNamespace(form->getPackageIsANamespace());
parent->setAccessorsAreInline(form->getAccessorsAreInline());
parent->setOperationsAreInline(form->getOperationsAreInline());
parent->setAccessorsArePublic(form->getAccessorsArePublic());
parent->setGetterWithGetPrefix(form->getGettersWithGetPrefix());
parent->setRemovePrefixFromAccessorMethods(form->getRemovePrefixFromAccessorMethodName());
parent->setAccessorMethodsStartWithUpperCase(form->getAccessorMethodsStartWithUpperCase());
parent->setStringClassName(form->ui_stringClassHCombo->currentText());
parent->setStringClassNameInclude(form->ui_stringIncludeFileHistoryCombo->currentText());
parent->setStringIncludeIsGlobal(form->ui_globalStringCheckBox->isChecked());
parent->setVectorClassName(form->ui_listClassHCombo->currentText());
parent->setVectorClassNameInclude(form->ui_listIncludeFileHistoryCombo->currentText());
parent->setVectorIncludeIsGlobal(form->ui_globalListCheckBox->isChecked());
parent->setDocToolTag(form->getDocToolTag());
parent->setClassMemberPrefix(form->getClassMemberPrefix());
parent->blockSignals(false);
// now send out modified code content signal
common->emitModifiedCodeContentSig();
}
| 4,576
|
C++
|
.cpp
| 80
| 53.05
| 125
| 0.799776
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,540
|
cppsourcecodeaccessormethod.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppsourcecodeaccessormethod.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppsourcecodeaccessormethod.h"
// local includes
#include "attribute.h"
#include "classifiercodedocument.h"
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppcodeclassfield.h"
#include "cppcodedocumentation.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
CPPSourceCodeAccessorMethod::CPPSourceCodeAccessorMethod(CodeClassField * field, CodeAccessorMethod::AccessorType type)
: CodeAccessorMethod(field)
{
setType(type);
setEndMethodText(QStringLiteral("}"));
}
void CPPSourceCodeAccessorMethod::update()
{
updateMethodDeclaration();
updateContent();
}
CPPSourceCodeAccessorMethod::~CPPSourceCodeAccessorMethod()
{
}
// we basically want to update the body of this method
void CPPSourceCodeAccessorMethod::updateContent()
{
CodeClassField * parentField = getParentClassField();
CPPCodeClassField * cppfield = dynamic_cast<CPPCodeClassField*>(parentField);
// Check for dynamic casting failure!
if(cppfield == nullptr)
{
logError0("cppfield: invalid dynamic cast");
return;
}
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
// Check for dynamic casting failure!
if(policy == nullptr)
{
logError0("policy: invalid dynamic cast");
return;
}
bool isInlineMethod = policy->getAccessorsAreInline();
QString variableName = cppfield->getFieldName();
QString itemClassName = cppfield->getTypeName();
QString text;
if(isInlineMethod) {
switch(getType()) {
case CodeAccessorMethod::ADD:
text = policy->getVectorMethodAppend(variableName, itemClassName);
break;
case CodeAccessorMethod::REMOVE:
text = policy->getVectorMethodRemove(variableName, itemClassName);
break;
case CodeAccessorMethod::SET:
text = variableName + QStringLiteral(" = value;");
break;
case CodeAccessorMethod::LIST:
case CodeAccessorMethod::GET:
default:
text = QStringLiteral("return ") + variableName + QLatin1Char(';');
break;
}
}
setText(text);
}
// we basically want to update the start text of this method
void CPPSourceCodeAccessorMethod::updateMethodDeclaration()
{
CodeClassField * parentField = getParentClassField();
ClassifierCodeDocument * doc = parentField->getParentDocument();
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
// Check for dynamic casting failure!
if (policy == nullptr)
{
logError0("policy: invalid dynamic cast");
return;
}
CPPCodeClassField * cppfield = dynamic_cast<CPPCodeClassField*>(parentField);
// Check for dynamic casting failure!
if (cppfield == nullptr)
{
logError0("cppfield: invalid dynamic cast");
return;
}
UMLClassifier * c = doc->getParentClassifier();
bool isInlineMethod = policy->getAccessorsAreInline();
QString tag = policy->getDocToolTag();
QString vectorClassName = policy->getVectorClassName();
QString fieldName = cppfield->getFieldName();
QString fieldType = cppfield->getTypeName();
QString objectType = cppfield->getListObjectType();
if(objectType.isEmpty())
objectType = fieldName;
QString methodReturnType(QStringLiteral("void"));
QString methodName; // QStringLiteral("get") + cppdoc->capitalizeFirstLetter(fieldName);
QString methodParams = QChar(QLatin1Char(' ')); // QStringLiteral("get") + cppdoc->capitalizeFirstLetter(fieldName);
QString headerText;
QString className = CodeGenerator::cleanName(c->name());
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
switch(getType()) {
case CodeAccessorMethod::ADD:
methodName = QStringLiteral("add_") + fieldType;
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Add a ") + fieldName + QStringLiteral(" object to the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return void");
break;
case CodeAccessorMethod::REMOVE:
methodName = QStringLiteral("remove_") + fieldType;
methodParams = objectType + QStringLiteral(" value ");
methodReturnType = QStringLiteral("void");
headerText = QStringLiteral("Remove a ") + fieldName + QStringLiteral(" object from the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return void");
break;
case CodeAccessorMethod::LIST:
methodName = QStringLiteral("get_") + fieldType + QStringLiteral("_list");
methodReturnType = vectorClassName;
headerText = QStringLiteral("Get the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return ") + vectorClassName + QStringLiteral("with list of objects");
break;
case CodeAccessorMethod::SET:
methodName = QStringLiteral("set_") + fieldName;
methodParams = fieldType + QStringLiteral(" value ");
methodReturnType = QStringLiteral("void");
headerText = QStringLiteral("Set the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("param value the value of ") + fieldName;
break;
case CodeAccessorMethod::GET:
default:
methodName = QStringLiteral("get_") + fieldName;
methodReturnType = fieldType;
headerText = QStringLiteral("Get the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return the value of ") + fieldName;
break;
}
// set header
CPPCodeDocumentation * header = new CPPCodeDocumentation(doc);
if(!getParentObject()->doc().isEmpty())
header->setText(headerText);
setComment(header);
// set start method text (EndText never changes)
setStartMethodText(methodReturnType + QLatin1Char(' ') + className + QStringLiteral("::") + methodName + QStringLiteral(" (") + methodParams + QLatin1Char(')') + QStringLiteral(" {"));
setOverallIndentationLevel(0);
// these ONLY appear if they arent inline
if(isInlineMethod)
setWriteOutText(false);
}
| 6,776
|
C++
|
.cpp
| 153
| 38.431373
| 225
| 0.70185
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,541
|
cppheadercodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppheadercodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppheadercodedocument.h"
// local includes
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppcodedocumentation.h"
#include "cppheadercodeaccessormethod.h"
#include "cppheadercodeoperation.h"
#include "cppheaderclassdeclarationblock.h"
#include "cppheadercodeclassfielddeclarationblock.h"
#include "debug_utils.h"
#include "umlpackagelist.h"
#include "package.h"
#include "umlclassifierlistitemlist.h"
#include "classifierlistitem.h"
#include "enum.h"
#include "uml.h"
// qt includes
/**
* Constructor.
*/
CPPHeaderCodeDocument::CPPHeaderCodeDocument(UMLClassifier* classifier)
: ClassifierCodeDocument(classifier)
{
setFileExtension(QStringLiteral(".h"));
//initCodeClassFields(); // this is dubious because it calls down to
// CodeGenFactory::newCodeClassField(this)
// but "this" is still in construction at that time.
m_classDeclCodeBlock = nullptr;
m_publicBlock = nullptr;
m_protectedBlock = nullptr;
m_privateBlock = nullptr;
m_namespaceBlock = nullptr;
m_pubConstructorBlock = nullptr;
m_protConstructorBlock = nullptr;
m_privConstructorBlock = nullptr;
m_pubOperationsBlock = nullptr;
m_privOperationsBlock = nullptr;
m_protOperationsBlock = nullptr;
// this will call updateContent() as well as other things that sync our document.
//synchronize();
}
/**
* Destructor.
*/
CPPHeaderCodeDocument::~CPPHeaderCodeDocument()
{
resetTextBlocks();
}
CPPHeaderClassDeclarationBlock * CPPHeaderCodeDocument::getClassDecl()
{
if(!m_classDeclCodeBlock) {
m_classDeclCodeBlock = new CPPHeaderClassDeclarationBlock (this); // was deleted before our load
m_classDeclCodeBlock->updateContent();
m_classDeclCodeBlock->setTag(QStringLiteral("classDeclarationBlock"));
}
return m_classDeclCodeBlock;
}
// Sigh. NOT optimal. The only reason that we need to have this
// is so we can create the CPPHeaderClassDeclarationBlock.
// would be better if we could create a handler interface that each
// codeblock used so all we have to do here is add the handler
void CPPHeaderCodeDocument::loadChildTextBlocksFromNode (QDomElement & root)
{
QDomNode tnode = root.firstChild();
QDomElement telement = tnode.toElement();
bool loadCheckForChildrenOK = false;
while(!telement.isNull()) {
QString nodeName = telement.tagName();
if(nodeName == QStringLiteral("textblocks")) {
QDomNode node = telement.firstChild();
QDomElement element = node.toElement();
// if there is nothing to begin with, then we don't worry about it
loadCheckForChildrenOK = element.isNull() ? true : false;
while(!element.isNull()) {
QString name = element.tagName();
if(name == QStringLiteral("codecomment")) {
CodeComment * block = new CPPCodeDocumentation(this);
block->loadFromXMI(element);
if(!addTextBlock(block))
{
logError0("CPPHeaderCodeDocument: Unable to add codeComment");
delete block;
} else
loadCheckForChildrenOK= true;
} else
if(name == QStringLiteral("codeaccessormethod") ||
name == QStringLiteral("ccfdeclarationcodeblock")) {
QString acctag = element.attribute(QStringLiteral("tag"));
// search for our method in the
TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
if(!tb || !addTextBlock(tb))
{
logError0("CPPHeaderCodeDocument: Unable to add codeclassfield child method");
// DON'T delete
} else
loadCheckForChildrenOK= true;
} else
if(name == QStringLiteral("codeblock")) {
CodeBlock * block = newCodeBlock();
block->loadFromXMI(element);
if(!addTextBlock(block))
{
logError0("CPPHeaderCodeDocument: Unable to add codeBlock");
delete block;
} else
loadCheckForChildrenOK= true;
} else
if(name == QStringLiteral("codeblockwithcomments")) {
CodeBlockWithComments * block = newCodeBlockWithComments();
block->loadFromXMI(element);
if(!addTextBlock(block))
{
logError0("CPPHeaderCodeDocument: Unable to add codeBlockwithcomments");
delete block;
} else
loadCheckForChildrenOK= true;
} else
if(name == QStringLiteral("header")) {
// do nothing.. this is treated elsewhere
} else
if(name == QStringLiteral("hierarchicalcodeblock")) {
HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
block->loadFromXMI(element);
if(!addTextBlock(block))
{
logError0("CPPHeaderCodeDocument: Unable to add hierarchicalcodeBlock");
delete block;
} else
loadCheckForChildrenOK= true;
} else
if(name == QStringLiteral("codeoperation")) {
// find the code operation by id
QString id = element.attribute(QStringLiteral("parent_id"),QStringLiteral("-1"));
UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
UMLOperation * op = obj->asUMLOperation();
if(op) {
CodeOperation * block = new CPPHeaderCodeOperation(this, op);
block->updateMethodDeclaration();
block->updateContent();
block->loadFromXMI(element);
if(addTextBlock(block))
loadCheckForChildrenOK= true;
else
{
logError0("CPPHeaderCodeDocument: Unable to add codeoperation");
block->deleteLater();
}
} else
logError0("CPPHeaderCodeDocument: Unable to find operation create codeoperation");
}
else
if(name == QStringLiteral("cppheaderclassdeclarationblock"))
{
CPPHeaderClassDeclarationBlock * block = getClassDecl();
block->loadFromXMI(element);
// normally this would be populated by the following syncToparent
// call, but we cant wait for it, so lets just do it now.
m_namespaceBlock = getHierarchicalCodeBlock(QStringLiteral("namespace"), QStringLiteral("Namespace"), 0);
if(!m_namespaceBlock || !m_namespaceBlock->addTextBlock(block))
{
logError0("Error:cant add class declaration codeblock");
// DON'T delete/release block
// block->release();
} else
loadCheckForChildrenOK= true;
}
// only needed for extreme debugging conditions (E.g. making new codeclassdocument loader)
//else
//uDebug()<<" LoadFromXMI: Got strange tag in text block stack:"<<name<<", ignoring";
node = element.nextSibling();
element = node.toElement();
}
break;
}
tnode = telement.nextSibling();
telement = tnode.toElement();
}
if(!loadCheckForChildrenOK)
{
logWarn1("loadChildBlocks : unable to initialize any child blocks in doc: %1", getFileName());
}
}
void CPPHeaderCodeDocument::resetTextBlocks()
{
// all special pointers need to be zero'd out.
if (m_classDeclCodeBlock) {
delete m_classDeclCodeBlock;
m_classDeclCodeBlock = nullptr;
}
if (m_publicBlock) {
delete m_publicBlock;
m_publicBlock = nullptr;
}
if (m_protectedBlock) {
delete m_protectedBlock;
m_protectedBlock = nullptr;
}
if (m_privateBlock) {
delete m_privateBlock;
m_privateBlock = nullptr;
}
if (m_namespaceBlock) {
delete m_namespaceBlock;
m_namespaceBlock = nullptr;
}
if (m_pubConstructorBlock) {
delete m_pubConstructorBlock;
m_pubConstructorBlock = nullptr;
}
if (m_protConstructorBlock) {
delete m_protConstructorBlock;
m_protConstructorBlock = nullptr;
}
if (m_privConstructorBlock) {
delete m_privConstructorBlock;
m_privConstructorBlock = nullptr;
}
if (m_pubOperationsBlock) {
delete m_pubOperationsBlock;
m_pubOperationsBlock = nullptr;
}
if (m_privOperationsBlock) {
delete m_privOperationsBlock;
m_privOperationsBlock = nullptr;
}
if (m_protOperationsBlock) {
delete m_protOperationsBlock;
m_protOperationsBlock = nullptr;
}
// now do the traditional release of child text blocks
ClassifierCodeDocument::resetTextBlocks();
}
/**
* Add a code operation to this cpp classifier code document.
* In the vanilla version, we just tack all operations on the end
* of the document.
* @param op the code operation
* @return bool which is true IF the code operation was added successfully
*/
bool CPPHeaderCodeDocument::addCodeOperation(CodeOperation* op)
{
if (op == nullptr) {
logWarn0("CPPHeaderCodeDocument::addCodeOperation: CodeOperation is null!");
return false;
}
Uml::Visibility::Enum scope = op->getParentOperation()->visibility();
if(!op->getParentOperation()->isLifeOperation())
{
switch (scope) {
default:
case Uml::Visibility::Public:
return (m_pubOperationsBlock == nullptr ? false : m_pubOperationsBlock->addTextBlock(op));
break;
case Uml::Visibility::Protected:
return (m_protOperationsBlock == nullptr ? false : m_protOperationsBlock->addTextBlock(op));
break;
case Uml::Visibility::Private:
return (m_privOperationsBlock == nullptr ? false : m_privOperationsBlock->addTextBlock(op));
break;
}
} else {
switch (scope) {
default:
case Uml::Visibility::Public:
return (m_pubConstructorBlock == nullptr ? false : m_pubConstructorBlock->addTextBlock(op));
break;
case Uml::Visibility::Protected:
return (m_protConstructorBlock == nullptr ? false : m_protConstructorBlock->addTextBlock(op));
break;
case Uml::Visibility::Private:
return (m_privConstructorBlock == nullptr ? false : m_privConstructorBlock->addTextBlock(op));
break;
}
}
}
/**
* Save the XMI representation of this object
* @return bool status of save
*/
/*
void CPPHeaderCodeDocument::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeEmptyStartElement();
setAttributesOnNode(writer);
writer.writeEndElement();
}
*/
// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we reasonably will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void CPPHeaderCodeDocument::updateContent()
{
// Gather info on the various fields and parent objects of this class...
UMLClassifier * c = getParentClassifier();
Q_ASSERT(c != nullptr);
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
// first, set the global flag on whether or not to show classfield info
const CodeClassFieldList * cfList = getCodeClassFieldList();
CodeClassFieldList::const_iterator it = cfList->begin();
CodeClassFieldList::const_iterator end = cfList->end();
for(; it != end; ++it)
(*it)->setWriteOutMethods(policy->getAutoGenerateAccessors());
// attribute-based ClassFields
// we do it this way to have the static fields sorted out from regular ones
CodeClassFieldList staticPublicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Public);
CodeClassFieldList publicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Public);
CodeClassFieldList staticProtectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Protected);
CodeClassFieldList protectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Protected);
CodeClassFieldList staticPrivateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Private);
CodeClassFieldList privateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Private);
// association-based ClassFields
// don't care if they are static or not..all are lumped together
CodeClassFieldList publicPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Public);
CodeClassFieldList publicAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Public);
CodeClassFieldList publicCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Public);
CodeClassFieldList protPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Protected);
CodeClassFieldList protAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Protected);
CodeClassFieldList protCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Protected);
CodeClassFieldList privPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Private);
CodeClassFieldList privAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Private);
CodeClassFieldList privCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Private);
bool hasOperationMethods = false;
UMLOperationList list = c->getOpList();
hasOperationMethods = ! list.isEmpty();
bool hasNamespace = false;
bool isEnumeration = false;
bool isInterface = parentIsInterface();
bool hasclassFields = hasClassFields();
bool forcedoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
UMLClassifierList superclasses = c->findSuperClassConcepts();
// START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
//
// Write the hash define stuff to prevent multiple parsing/inclusion of header
QString cppClassName = CodeGenerator::cleanName(c->name());
QString hashDefine = CodeGenerator::cleanName(c->name().toUpper().simplified());
QString defText = QStringLiteral("#ifndef ") + hashDefine + QStringLiteral("_H") + endLine + QStringLiteral("#define ") + hashDefine + QStringLiteral("_H");
addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("hashDefBlock"), defText, QString(), 0, false);
// INCLUDE CODEBLOCK
//
// Q: Why all utils? Isnt just List and Vector the only classes we are using?
// A: doesn't matter at all; its more readable to just include '*' and cpp compilers
// don't slow down or anything. (TZ)
QString includeStatement;
bool stringGlobal = policy->stringIncludeIsGlobal();
QString sStartBrak = stringGlobal ? QStringLiteral("<") : QStringLiteral("\"");
QString sEndBrak = stringGlobal ? QStringLiteral(">") : QStringLiteral("\"");
includeStatement.append(QStringLiteral("#include ") + sStartBrak + policy->getStringClassNameInclude() + sEndBrak + endLine);
if (hasObjectVectorClassFields())
{
bool vecGlobal = policy->vectorIncludeIsGlobal();
QString vStartBrak = vecGlobal ? QStringLiteral("<") : QStringLiteral("\"");
QString vEndBrak = vecGlobal ? QStringLiteral(">") : QStringLiteral("\"");
QString value =QStringLiteral("#include ") + vStartBrak + policy->getVectorClassNameInclude() + vEndBrak;
includeStatement.append(value + endLine);
}
//only include classes in a different package from this class
UMLPackageList includes;
QMap<UMLPackage *, QString> packageMap; // so we don't repeat packages
CodeGenerator::findObjectsRelated(c, includes);
for(UMLPackage* con : includes) {
if (!con->isUMLDatatype() && !packageMap.contains(con)) {
packageMap.insert(con, con->package());
if(con != getParentClassifier())
includeStatement.append(QStringLiteral("#include \"") + CodeGenerator::cleanName(con->name().toLower()) + QStringLiteral(".h\"") + endLine);
}
}
// now, add/update the includes codeblock
CodeBlockWithComments * inclBlock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("includes"), includeStatement, QString(), 0, false);
if(includeStatement.isEmpty() && inclBlock->contentType() == CodeBlock::AutoGenerated)
inclBlock->setWriteOutText(false);
else
inclBlock->setWriteOutText(true);
// Using
QString usingStatement;
for(UMLClassifier* classifier : superclasses) {
if(classifier->package()!=c->package() && !classifier->package().isEmpty()) {
usingStatement.append(QStringLiteral("using ") + CodeGenerator::cleanName(c->package()) + QStringLiteral("::") + cleanName(c->name()) + QLatin1Char(';') + endLine);
}
}
CodeBlockWithComments * usingBlock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("using"), usingStatement, QString(), 0, false);
if(usingStatement.isEmpty() && usingBlock->contentType() == CodeBlock::AutoGenerated)
usingBlock->setWriteOutText(false);
else
usingBlock->setWriteOutText(true);
// namespace
// This needs special treatment. We cant use "nowriteouttext" for this, as
// that will prevent the class declaration from being written. Instead, we
// check if "hasNamspace" is true or not, and then indent the remaining code
// appropriately as well as set the start/end text of this namespace block.
if (c->umlPackage() && policy->getPackageIsNamespace())
hasNamespace = true;
else
hasNamespace = false;
// set start/end text of namespace block
m_namespaceBlock = getHierarchicalCodeBlock(QStringLiteral("namespace"), QStringLiteral("Namespace"), 0);
if(hasNamespace) {
UMLPackageList pkgList = c->packages();
QString pkgs;
for(UMLPackage *pkg: pkgList) {
pkgs += QStringLiteral("namespace ") + CodeGenerator::cleanName(pkg->name()) + QStringLiteral(" { ");
}
m_namespaceBlock->setStartText(pkgs);
QString closingBraces;
for(UMLPackage *pkg: pkgList) {
closingBraces += QStringLiteral("} ");
}
m_namespaceBlock->setEndText(closingBraces);
m_namespaceBlock->getComment()->setWriteOutText(true);
} else {
m_namespaceBlock->setStartText(QString());
m_namespaceBlock->setEndText(QString());
m_namespaceBlock->getComment()->setWriteOutText(false);
}
// Enum types for include
if (!isInterface) {
QString enumStatement;
QString indent = UMLApp::app()->commonPolicy()->getIndentation();
const UMLEnum* e = c->asUMLEnum();
if (e) {
enumStatement.append(indent + QStringLiteral("enum ") + cppClassName + QStringLiteral(" {") + endLine);
// populate
UMLClassifierListItemList ell = e->getFilteredList(UMLObject::ot_EnumLiteral);
for (UMLClassifierListItemListIt elit(ell) ; elit.hasNext() ;) {
UMLClassifierListItem* el = elit.next();
enumStatement.append(indent + indent);
enumStatement.append(CodeGenerator::cleanName(el->name()));
if (elit.hasNext()) {
el=elit.next();
enumStatement.append(QStringLiteral(", ") + endLine);
} else {
break;
}
enumStatement.append(endLine);
}
enumStatement.append(indent + QStringLiteral("};"));
isEnumeration = true;
}
m_namespaceBlock->addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("enums"), enumStatement, QString(), 0, false);
}
// CLASS DECLARATION BLOCK
//
// add the class declaration block to the namespace block.
CPPHeaderClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl();
m_namespaceBlock->addTextBlock(myClassDeclCodeBlock); // note: wont add if already present
// Is this really true?? hmm..
if(isEnumeration)
myClassDeclCodeBlock->setWriteOutText(false); // not written out IF its an enumeration class
else
myClassDeclCodeBlock->setWriteOutText(true);
//
// Main Sub-Blocks
//
// declare public, protected and private methods, attributes (fields).
// set the start text ONLY if this is the first time we created the objects.
bool createdPublicBlock = m_publicBlock == nullptr ? true : false;
m_publicBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("publicBlock"),QStringLiteral("Public stuff"), 0);
if (createdPublicBlock)
m_publicBlock->setStartText(QStringLiteral("public:"));
bool createdProtBlock = m_protectedBlock == nullptr ? true : false;
m_protectedBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("protectedBlock"),QStringLiteral("Protected stuff"), 0);
if(createdProtBlock)
m_protectedBlock->setStartText(QStringLiteral("protected:"));
bool createdPrivBlock = m_privateBlock == nullptr ? true : false;
m_privateBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("privateBlock"),QStringLiteral("Private stuff"), 0);
if(createdPrivBlock)
m_privateBlock->setStartText(QStringLiteral("private:"));
//
// * CLASS FIELD declaration section
//
// setup/get/create the field declaration code block
//
// public fields: Update the comment: we only set comment to appear under the following conditions
HierarchicalCodeBlock * publicFieldDeclBlock = m_publicBlock->getHierarchicalCodeBlock(QStringLiteral("publicFieldsDecl"), QStringLiteral("Fields"), 1);
CodeComment * pubFcomment = publicFieldDeclBlock->getComment();
if (!forcedoc && !hasclassFields)
pubFcomment->setWriteOutText(false);
else
pubFcomment->setWriteOutText(true);
// protected fields: Update the comment: we only set comment to appear under the following conditions
HierarchicalCodeBlock * protectedFieldDeclBlock = m_protectedBlock->getHierarchicalCodeBlock(QStringLiteral("protectedFieldsDecl"), QStringLiteral("Fields"), 1);
CodeComment * protFcomment = protectedFieldDeclBlock->getComment();
if (!forcedoc && !hasclassFields)
protFcomment->setWriteOutText(false);
else
protFcomment->setWriteOutText(true);
// private fields: Update the comment: we only set comment to appear under the following conditions
HierarchicalCodeBlock * privateFieldDeclBlock = m_privateBlock->getHierarchicalCodeBlock(QStringLiteral("privateFieldsDecl"), QStringLiteral("Fields"), 1);
CodeComment * privFcomment = privateFieldDeclBlock->getComment();
if (!forcedoc && !hasclassFields)
privFcomment->setWriteOutText(false);
else
privFcomment->setWriteOutText(true);
// now actually declare the fields within the appropriate HCodeBlock
//
// public
declareClassFields(staticPublicAttribClassFields, publicFieldDeclBlock);
declareClassFields(publicAttribClassFields, publicFieldDeclBlock);
declareClassFields(publicPlainAssocClassFields, publicFieldDeclBlock);
declareClassFields(publicAggregationClassFields, publicFieldDeclBlock);
declareClassFields(publicCompositionClassFields, publicFieldDeclBlock);
// protected
declareClassFields(staticProtectedAttribClassFields, protectedFieldDeclBlock);
declareClassFields(protectedAttribClassFields, protectedFieldDeclBlock);
declareClassFields(protPlainAssocClassFields, protectedFieldDeclBlock);
declareClassFields(protAggregationClassFields, protectedFieldDeclBlock);
declareClassFields(protCompositionClassFields, protectedFieldDeclBlock);
// private
declareClassFields(staticPrivateAttribClassFields, privateFieldDeclBlock);
declareClassFields(privateAttribClassFields, privateFieldDeclBlock);
declareClassFields(privPlainAssocClassFields, privateFieldDeclBlock);
declareClassFields(privAggregationClassFields, privateFieldDeclBlock);
declareClassFields(privCompositionClassFields, privateFieldDeclBlock);
//
// METHODS section
//
// get/create the method codeblock
// public methods
HierarchicalCodeBlock * pubMethodsBlock = m_publicBlock->getHierarchicalCodeBlock(QStringLiteral("pubMethodsBlock"), QString(), 1);
CodeComment * pubMethodsComment = pubMethodsBlock->getComment();
// set conditions for showing this comment
if (!forcedoc && !hasclassFields && !hasOperationMethods)
pubMethodsComment->setWriteOutText(false);
else
pubMethodsComment->setWriteOutText(true);
// protected methods
HierarchicalCodeBlock * protMethodsBlock = m_protectedBlock->getHierarchicalCodeBlock(QStringLiteral("protMethodsBlock"), QString(), 1);
CodeComment * protMethodsComment = protMethodsBlock->getComment();
// set conditions for showing this comment
if (!forcedoc && !hasclassFields && !hasOperationMethods)
protMethodsComment->setWriteOutText(false);
else
protMethodsComment->setWriteOutText(true);
// private methods
HierarchicalCodeBlock * privMethodsBlock = m_privateBlock->getHierarchicalCodeBlock(QStringLiteral("privMethodsBlock"), QString(), 1);
CodeComment * privMethodsComment = privMethodsBlock->getComment();
// set conditions for showing this comment
if (!forcedoc && !hasclassFields && !hasOperationMethods)
privMethodsComment->setWriteOutText(false);
else
privMethodsComment->setWriteOutText(true);
// METHODS sub-section : constructor methods
//
CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy();
// setup/get/create the constructor codeblocks
// public
m_pubConstructorBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * pubConstComment = m_pubConstructorBlock->getComment();
if (!forcedoc && (isInterface || !pol->getAutoGenerateConstructors()))
pubConstComment->setWriteOutText(false);
else
pubConstComment->setWriteOutText(true);
// protected
m_protConstructorBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * protConstComment = m_protConstructorBlock->getComment();
if (!forcedoc && (isInterface || !pol->getAutoGenerateConstructors()))
protConstComment->setWriteOutText(false);
else
protConstComment->setWriteOutText(true);
// private
m_privConstructorBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * privConstComment = m_privConstructorBlock->getComment();
if (!forcedoc && (isInterface || !pol->getAutoGenerateConstructors()))
privConstComment->setWriteOutText(false);
else
privConstComment->setWriteOutText(true);
// add/get the empty constructor. I guess since there is no
// meta-data to state what the scope of this method is, we will make it
// "public" as a default. This might present problems if the user wants
// to move the block into the "private" or "protected" blocks.
QString emptyConstStatement = cppClassName + QStringLiteral(" () { }");
// search for this first in the entire document. IF not present, put
// it in the public constructor method block
TextBlock * emptyConstTb = findTextBlockByTag(QStringLiteral("emptyconstructor"), true);
CodeBlockWithComments * emptyConstBlock = dynamic_cast<CodeBlockWithComments*>(emptyConstTb);
if(!emptyConstBlock)
emptyConstBlock = m_pubConstructorBlock->addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("emptyconstructor"), emptyConstStatement, QStringLiteral("Empty Constructor"), 1, false);
// Now, as an additional condition we only show the empty constructor block
// IF it was desired to be shown
if(!isInterface && pol->getAutoGenerateConstructors())
emptyConstBlock->setWriteOutText(true);
else
emptyConstBlock->setWriteOutText(false);
// METHODS subsection : ACCESSOR METHODS
//
// get/create the accessor codeblock
// public
HierarchicalCodeBlock * pubAccessorBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * pubAccessComment = pubAccessorBlock->getComment();
if (!forcedoc && !hasclassFields)
pubAccessComment->setWriteOutText(false);
else
pubAccessComment->setWriteOutText(true);
// protected
HierarchicalCodeBlock * protAccessorBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * protAccessComment = protAccessorBlock->getComment();
if (!forcedoc && !hasclassFields)
protAccessComment->setWriteOutText(false);
else
protAccessComment->setWriteOutText(true);
// private
HierarchicalCodeBlock * privAccessorBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * privAccessComment = privAccessorBlock->getComment();
// We've to copy the private accessorMethods to the public block
if (!forcedoc && !hasclassFields)
privAccessComment->setWriteOutText(false);
else
privAccessComment->setWriteOutText(true);
// now, 2 sub-sub sections in accessor block
// add/update accessor methods for attributes
HierarchicalCodeBlock * pubStaticAccessors = pubAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("pubStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * pubRegularAccessors = pubAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("pubRegularAccessorMethods"), QString(), 1);
pubStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
pubRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
HierarchicalCodeBlock * protStaticAccessors = protAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("protStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * protRegularAccessors = protAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("protRegularAccessorMethods"), QString(), 1);
protStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
protRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
HierarchicalCodeBlock * privStaticAccessors = privAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("privStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * privRegularAccessors = privAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("privRegularAccessorMethods"), QString(), 1);
privStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
privRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
// now add in accessors as appropriate
// public stuff
pubStaticAccessors->addCodeClassFieldMethods(staticPublicAttribClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicAttribClassFields);
// generate accessors as public
if (policy && policy->getAccessorsArePublic())
{
pubRegularAccessors->addCodeClassFieldMethods(privateAttribClassFields);
pubRegularAccessors->addCodeClassFieldMethods(protectedAttribClassFields);
}
pubRegularAccessors->addCodeClassFieldMethods(publicPlainAssocClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicAggregationClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicCompositionClassFields);
// protected stuff
protStaticAccessors->addCodeClassFieldMethods(staticProtectedAttribClassFields);
// accessors are public so we don't have to create it here
if (policy && !policy->getAccessorsArePublic())
protRegularAccessors->addCodeClassFieldMethods(protectedAttribClassFields);
protRegularAccessors->addCodeClassFieldMethods(protPlainAssocClassFields);
protRegularAccessors->addCodeClassFieldMethods(protAggregationClassFields);
protRegularAccessors->addCodeClassFieldMethods(protCompositionClassFields);
// private stuff
privStaticAccessors->addCodeClassFieldMethods(staticPrivateAttribClassFields);
// accessors are public so we don't have to create it here
if (policy && !policy->getAccessorsArePublic())
privRegularAccessors->addCodeClassFieldMethods(privateAttribClassFields);
privRegularAccessors->addCodeClassFieldMethods(privPlainAssocClassFields);
privRegularAccessors->addCodeClassFieldMethods(privAggregationClassFields);
privRegularAccessors->addCodeClassFieldMethods(privCompositionClassFields);
// METHODS subsection : Operation methods (e.g. methods derive from operations but which arent constructors)
//
// setup/get/create the operations codeblock
// public
m_pubOperationsBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * pubOcomment = m_pubOperationsBlock->getComment();
if (!forcedoc && !hasOperationMethods)
pubOcomment->setWriteOutText(false);
else
pubOcomment->setWriteOutText(true);
//protected
m_protOperationsBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * protOcomment = m_protOperationsBlock->getComment();
if (!forcedoc && !hasOperationMethods)
protOcomment->setWriteOutText(false);
else
protOcomment->setWriteOutText(true);
//private
m_privOperationsBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * privOcomment = m_privOperationsBlock->getComment();
if (!forcedoc && !hasOperationMethods)
privOcomment->setWriteOutText(false);
else
privOcomment->setWriteOutText(true);
// Operations
//
// nothing to do here.. "updateOperations" in parent class puts things
// in the right place using the "addCodeOperation" method we defined in this class
// FINISH up with hash def block close
QString defTextEnd = QStringLiteral("#endif //") + hashDefine + QStringLiteral("_H");
addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("hashDefBlockEnd"), defTextEnd, QString(), 0, false);
}
| 38,908
|
C++
|
.cpp
| 706
| 44.754958
| 192
| 0.676537
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,542
|
cppheadercodeaccessormethod.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppheadercodeaccessormethod.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppheadercodeaccessormethod.h"
// local includes
#include "attribute.h"
#include "classifiercodedocument.h"
#include "cppcodegenerator.h"
#include "cppsourcecodedocument.h"
#include "cppcodegenerationpolicy.h"
#include "cppcodeclassfield.h"
#include "cppcodedocumentation.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
CPPHeaderCodeAccessorMethod::CPPHeaderCodeAccessorMethod(CodeClassField * field, CodeAccessorMethod::AccessorType type)
: CodeAccessorMethod(field)
{
setType(type);
}
void CPPHeaderCodeAccessorMethod::update()
{
updateMethodDeclaration();
updateContent();
}
CPPHeaderCodeAccessorMethod::~CPPHeaderCodeAccessorMethod()
{
}
// we basically want to update the body of this method
void CPPHeaderCodeAccessorMethod::updateContent()
{
CodeClassField * parentField = getParentClassField();
CPPCodeClassField * cppfield = dynamic_cast<CPPCodeClassField*>(parentField);
// Check for dynamic casting failure!
if (cppfield == nullptr)
{
logError0("cppfield: invalid dynamic cast");
return;
}
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
// Check for dynamic casting failure!
if (policy == nullptr)
{
logError0("policy: invalid dynamic cast");
return;
}
bool isInlineMethod = policy->getAccessorsAreInline();
// Uml::Visibility scope = parentField->getVisibility();
QString variableName = cppfield->getFieldName();
QString itemClassName = cppfield->getTypeName();
QString text;
if(isInlineMethod) {
switch(getType()) {
case CodeAccessorMethod::ADD:
text = policy->getVectorMethodAppend(variableName, itemClassName);
break;
case CodeAccessorMethod::REMOVE:
text = policy->getVectorMethodRemove(variableName, itemClassName);
break;
case CodeAccessorMethod::SET:
text = variableName + QStringLiteral(" = value;");
break;
case CodeAccessorMethod::LIST:
case CodeAccessorMethod::GET:
default:
text = QStringLiteral("return ") + variableName + QLatin1Char(';');
break;
}
}
setText(text);
}
// we basically want to update the start text of this method
void CPPHeaderCodeAccessorMethod::updateMethodDeclaration()
{
CodeClassField * parentField = getParentClassField();
ClassifierCodeDocument * doc = parentField->getParentDocument();
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
CPPCodeClassField * cppfield = dynamic_cast<CPPCodeClassField*>(parentField);
bool isInlineMethod = policy->getAccessorsAreInline();
QString tag = policy->getDocToolTag();
QString classMemberPrefix = policy->getClassMemberPrefix();
QString vectorClassName = policy->getVectorClassName();
QString fieldName = classMemberPrefix + cppfield->getFieldName();
QString fieldType = cppfield->getTypeName();
QString objectType = cppfield->getListObjectType();
if(objectType.isEmpty())
objectType = fieldName;
QString methodReturnType = QStringLiteral("void");
QString methodName; // QStringLiteral("get") + cppdoc->capitalizeFirstLetter(fieldName);
QString methodParams = QChar(QLatin1Char(' ')); // QStringLiteral("get") + cppdoc->capitalizeFirstLetter(fieldName);
QString headerText;
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
switch(getType()) {
case CodeAccessorMethod::ADD:
methodName = QStringLiteral("add_") + fieldType;
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Add a ") + fieldName + QStringLiteral(" object to the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return void");
break;
case CodeAccessorMethod::REMOVE:
methodName = QStringLiteral("remove_") + fieldType;
methodParams = objectType + QStringLiteral(" value ");
methodReturnType = QStringLiteral("void");
headerText = QStringLiteral("Remove a ") + fieldName + QStringLiteral(" object from the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return void");
break;
case CodeAccessorMethod::LIST:
methodName = QStringLiteral("get_") + fieldType + QStringLiteral("_list");
methodReturnType = vectorClassName;
headerText = QStringLiteral("Get the ") + fieldName + QStringLiteral("List") + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return ") + vectorClassName + QStringLiteral("with list of objects");
break;
case CodeAccessorMethod::SET:
methodName = QStringLiteral("set_") + fieldName;
methodParams = fieldType + QStringLiteral(" value ");
methodReturnType = QStringLiteral("void");
headerText = QStringLiteral("Set the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("param value the value of ") + fieldName;
break;
case CodeAccessorMethod::GET:
default:
methodName = QStringLiteral("get_") + fieldName;
methodReturnType = fieldType;
headerText = QStringLiteral("Get the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + tag + QStringLiteral("return the value of ") + fieldName;
break;
}
// set header
CPPCodeDocumentation * header = new CPPCodeDocumentation(doc);
if(!getParentObject()->doc().isEmpty())
header->setText(headerText);
setComment(header);
// set start/end method text
QString startText = methodReturnType + QLatin1Char(' ') + methodName + QStringLiteral(" (") + methodParams + QLatin1Char(')');
if (isInlineMethod)
startText += QStringLiteral(" {");
else
startText += QLatin1Char(';');
QString endText = (isInlineMethod ? QStringLiteral("}") : QString());
setStartMethodText(startText);
setEndMethodText(endText);
setOverallIndentationLevel(1);
}
| 6,574
|
C++
|
.cpp
| 145
| 39.586207
| 225
| 0.706525
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,543
|
cppheadercodeoperation.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppheadercodeoperation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppheadercodeoperation.h"
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppheadercodedocument.h"
#include "cppcodedocumentation.h"
#include "uml.h"
CPPHeaderCodeOperation::CPPHeaderCodeOperation
(CPPHeaderCodeDocument * doc, UMLOperation *parent, const QString & body, const QString & comment)
: CodeOperation (doc, parent, body, comment)
{
// lets not go with the default comment and instead use
// full-blown cpp documentation object instead
setComment(new CPPCodeDocumentation(doc));
// these things never change..
setOverallIndentationLevel(1);
setText(QString());
setStartMethodText(QString());
setEndMethodText(QString());
}
CPPHeaderCodeOperation::~CPPHeaderCodeOperation()
{
}
// we basically just want to know whether or not to print out
// the body of the operation.
// In C++ if the operations are inline, then we DO print out
// the body text.
void CPPHeaderCodeOperation::updateContent()
{
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
bool isInlineMethod = policy->getOperationsAreInline();
if(isInlineMethod)
setText(QString()); // change whatever it is to "";
}
// we basically want to update the doc and start text of this method
void CPPHeaderCodeOperation::updateMethodDeclaration()
{
ClassifierCodeDocument *ccd = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());
Q_ASSERT(ccd);
bool isInterface = ccd->parentIsInterface();
UMLOperation * o = getParentOperation();
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
Q_ASSERT(policy);
bool isInlineMethod = policy->getOperationsAreInline();
QString tag = policy->getDocToolTag();
QString endLine = getNewLineEndingChars();
// first, the comment on the operation, IF its autogenerated/empty
QString comment = o->doc();
if(comment.isEmpty() && contentType() == CodeBlock::AutoGenerated)
{
UMLAttributeList parameters = o->getParmList();
for(UMLAttribute* currentAtt : parameters) {
comment += endLine + tag + QStringLiteral("param ") + currentAtt->name() + QLatin1Char(' ');
comment += currentAtt->doc();
}
getComment()->setText(comment);
}
// no return type for constructors
QString methodReturnType = o->getTypeName();
QString methodName = o->name();
QString paramStr;
// assemble parameters
UMLAttributeList list = getParentOperation()->getParmList();
int nrofParam = list.count();
int paramNum = 0;
for(UMLAttribute* parm : list) {
QString rType = parm->getTypeName();
QString paramName = parm->name();
QString initialValue = parm->getInitialValue();
paramStr += rType + QLatin1Char(' ') + paramName;
if(!initialValue.isEmpty())
paramStr += QLatin1Char('=') + initialValue;
paramNum++;
if (paramNum != nrofParam)
paramStr += QStringLiteral(", ");
}
// if an operation isn't a constructor or a destructor and it has no return type
if (o->isLifeOperation()) // constructor/destructor has no type
methodReturnType = QString();
else if (methodReturnType.isEmpty()) // this operation should be 'void'
methodReturnType = QString(QStringLiteral("void"));
// set start/end method text
QString prototype = methodReturnType + QLatin1Char(' ') + methodName + QStringLiteral(" (") + paramStr + QLatin1Char(')');
QString startText;
QString endText;
applyStereotypes (prototype, o, isInlineMethod, isInterface, startText, endText);
setStartMethodText(prototype + startText);
setEndMethodText(endText);
}
int CPPHeaderCodeOperation::lastEditableLine()
{
ClassifierCodeDocument * doc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());
UMLOperation * o = getParentOperation();
if(doc->parentIsInterface() || o->isAbstract())
return -1; // very last line is NOT editable as its a one-line declaration w/ no body in
// an interface.
return 0;
}
void CPPHeaderCodeOperation::applyStereotypes (QString& prototype, UMLOperation * pOp,
bool inlinePolicy, bool interface,
QString& start, QString& end)
{
// if the class is an interface, all methods will be declared as pure
// virtual functions
start = (inlinePolicy ? QStringLiteral(" {") : QStringLiteral(";"));
end = (inlinePolicy ? QStringLiteral("}") : QString());
if (pOp->getConst())
prototype += QStringLiteral(" const");
if (pOp->getOverride())
prototype += QStringLiteral(" override");
if (interface || pOp->isAbstract()) {
// constructor can't be virtual or abstract
if (!pOp->isLifeOperation()) {
prototype = QStringLiteral("virtual ") + prototype + QStringLiteral(" = 0");
if (inlinePolicy) {
start = QLatin1Char(';');
end = QString();
}
}
} // constructors could not be declared as static
else if (pOp->isStatic() && !pOp->isLifeOperation()) {
prototype = QStringLiteral("static ") + prototype;
}
// apply the stereotypes
if (!pOp->stereotype().isEmpty()) {
if ((pOp->stereotype() == QStringLiteral("friend")) || (pOp->stereotype(false) == QStringLiteral("virtual"))) {
if (!pOp->isLifeOperation() && !(interface || pOp->isAbstract()) && !pOp->isStatic())
prototype = pOp->stereotype() + QLatin1Char(' ') + prototype;
}
}
}
| 5,999
|
C++
|
.cpp
| 137
| 37.540146
| 126
| 0.673634
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,544
|
cppsourcecodeclassfielddeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppsourcecodeclassfielddeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppsourcecodeclassfielddeclarationblock.h"
#include "cppcodeclassfield.h"
#include "debug_utils.h"
#include "model_utils.h"
#include "uml.h" // only needed for log{Warn,Error}
CPPSourceCodeClassFieldDeclarationBlock::CPPSourceCodeClassFieldDeclarationBlock (CodeClassField * parent)
: CodeClassFieldDeclarationBlock (parent)
{
setOverallIndentationLevel(1);
}
CPPSourceCodeClassFieldDeclarationBlock::~CPPSourceCodeClassFieldDeclarationBlock ()
{
}
void CPPSourceCodeClassFieldDeclarationBlock::updateContent()
{
CodeClassField * cf = getParentClassField();
CPPCodeClassField * jcf = dynamic_cast<CPPCodeClassField*>(cf);
// Check for dynamic casting failure!
if (jcf == nullptr)
{
logError0("jcf: invalid dynamic cast");
return;
}
// Set the comment
QString notes = getParentObject()->doc();
getComment()->setText(notes);
// Set the body
QString staticValue = getParentObject()->isStatic() ? QStringLiteral("static ") : QString();
QString scopeStr = Uml::Visibility::toString(getParentObject()->visibility());
QString typeName = jcf->getTypeName();
QString fieldName = jcf->getFieldName();
QString initialV = jcf->getInitialValue();
QString body = staticValue+scopeStr + QLatin1Char(' ') + typeName + QLatin1Char(' ') + fieldName;
if (!initialV.isEmpty())
body.append(QStringLiteral(" = ") + initialV);
setText(body + QLatin1Char(';'));
}
| 1,697
|
C++
|
.cpp
| 42
| 36.166667
| 106
| 0.733414
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,545
|
cppsourcecodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppsourcecodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
/**
* We carve the CPP document up into 2 documents, "source" and "header".
* The sections of each are as follows:
* - header
* - includes
* - constructor methods
* - all other methods
*/
// own header
#include "cppsourcecodedocument.h"
// app includes
#include "cppcodegenerator.h"
#include "cppcodegenerationpolicy.h"
#include "cppcodedocumentation.h"
#include "cppcodeclassfield.h"
#include "cppsourcecodeclassfielddeclarationblock.h"
#include "debug_utils.h"
#include "uml.h"
// qt includes
CPPSourceCodeDocument::CPPSourceCodeDocument (UMLClassifier * classifier)
: ClassifierCodeDocument (classifier)
{
setFileExtension(QStringLiteral(".cpp"));
m_methodsBlock = nullptr;
m_constructorBlock = nullptr;
/* We cannot call any virtual initialization functions here because
the object is still under construction and the C++ dispatch table
is not yet set up.
Full initialization is done in CodeGenFactory::newCodeOperation()
*/
}
CPPSourceCodeDocument::~CPPSourceCodeDocument()
{
}
bool CPPSourceCodeDocument::addCodeOperation (CodeOperation * op)
{
bool retval = false;
if (op->getParentOperation()->isLifeOperation()) {
if (m_constructorBlock)
retval = m_constructorBlock->addTextBlock(op);
else
logError0("m_constructorBlock is NULL");
} else {
if (m_methodsBlock)
retval = m_methodsBlock->addTextBlock(op);
else
logError0("m_methodsBlock is NULL");
}
return retval;
}
void CPPSourceCodeDocument::resetTextBlocks()
{
// all special pointers need to be zero'd out.
m_methodsBlock = nullptr;
m_constructorBlock = nullptr;
// now do the traditional release of child text blocks
ClassifierCodeDocument::resetTextBlocks();
}
void CPPSourceCodeDocument::updateContent()
{
// Gather info on the various fields and parent objects of this class...
//UMLClassifier * c = getParentClassifier();
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
// first, set the global flag on whether or not to show classfield info
const CodeClassFieldList * cfList = getCodeClassFieldList();
CodeClassFieldList::const_iterator it = cfList->begin();
CodeClassFieldList::const_iterator end = cfList->end();
for(; it != end; ++it)
(*it)->setWriteOutMethods(policy->getAutoGenerateAccessors());
// attribute-based ClassFields
// we do it this way to have the static fields sorted out from regular ones
CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true);
CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false);
// association-based ClassFields
// don't care if they are static or not..all are lumped together
CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation);
CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation);
CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition);
// START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
// INCLUDE CODEBLOCK
QString includeStatement;
// Include own header file
QString myOwnName(getParentClassifier()->name());
includeStatement.append(QStringLiteral("#include \"") + CodeGenerator::cleanName(myOwnName.toLower()) + QStringLiteral(".h\"") + endLine);
CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("includes"), includeStatement, QString(), 0, false);
iblock->setWriteOutText(true);
// After the includes we have just 2 big blocks basically, the "constructor" block and the
// block for the rest of our methods (operations + accessors)
m_constructorBlock = getHierarchicalCodeBlock(QStringLiteral("constructionMethodsBlock"), QStringLiteral("Constructors/Destructors"), 0);
m_methodsBlock = getHierarchicalCodeBlock(QStringLiteral("otherMethodsBlock"), QStringLiteral("Methods"), 0);
// add accessors to the methods block
m_methodsBlock->addCodeClassFieldMethods(staticAttribClassFields);
m_methodsBlock->addCodeClassFieldMethods(attribClassFields);
m_methodsBlock->addCodeClassFieldMethods(plainAssocClassFields);
m_methodsBlock->addCodeClassFieldMethods(aggregationClassFields);
m_methodsBlock->addCodeClassFieldMethods(compositionClassFields);
// constructors and other operations are handled by the "addCodeOperation" method above.
}
| 4,965
|
C++
|
.cpp
| 105
| 42.752381
| 143
| 0.758528
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,546
|
cppheadercodeclassfielddeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/cpp/cppheadercodeclassfielddeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "cppheadercodeclassfielddeclarationblock.h"
#include "cppcodeclassfield.h"
#include "cppheadercodedocument.h"
#include "debug_utils.h"
#include "uml.h" // only needed for log{Warn,Error}
CPPHeaderCodeClassFieldDeclarationBlock::CPPHeaderCodeClassFieldDeclarationBlock (CodeClassField * parent)
: CodeClassFieldDeclarationBlock (parent)
{
setOverallIndentationLevel(1);
}
CPPHeaderCodeClassFieldDeclarationBlock::~CPPHeaderCodeClassFieldDeclarationBlock ()
{
}
void CPPHeaderCodeClassFieldDeclarationBlock::updateContent()
{
UMLObject *umlparent = CodeClassFieldDeclarationBlock::getParentObject();
if (umlparent == nullptr) {
return;
}
CodeClassField * cf = getParentClassField();
CPPCodeClassField * hcppcf = dynamic_cast<CPPCodeClassField*>(cf);
// Check for dynamic casting failure!
if (hcppcf == nullptr)
{
logError0("hcppcf: invalid dynamic cast");
return;
}
// Set the comment
QString notes = umlparent->doc();
getComment()->setText(notes);
if (notes.isEmpty())
getComment()->setWriteOutText(false);
else
getComment()->setWriteOutText(true);
// Set the body
QString staticValue = umlparent->isStatic() ? QStringLiteral("static ") : QString();
QString typeName = hcppcf->getTypeName();
QString fieldName = hcppcf->getFieldName();
// Ugh. Sloppy exception.
if (!cf->parentIsAttribute() && !cf->fieldIsSingleValue())
typeName = hcppcf->getListFieldClassName();
QString body = staticValue + QLatin1Char(' ') + typeName + QLatin1Char(' ') + fieldName + QLatin1Char(';');
setText(body);
}
| 1,882
|
C++
|
.cpp
| 49
| 33.877551
| 111
| 0.728571
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,547
|
aswriter.cpp
|
KDE_umbrello/umbrello/codegenerators/as/aswriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Alexander Blum <blum@kewbee.de>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "aswriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "uml.h" // Only needed for logWarn
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"abs",
"acos",
"add",
"addListener",
"addProperty",
"align",
"_alpha",
"and",
"appendChild",
"apply",
"Array",
"asin",
"atan",
"atan2",
"attachMovie",
"attachSound",
"attributes",
"autoSize",
"background",
"backgroundColor",
"BACKSPACE",
"beginFill",
"beginGradientFill",
"blockIndent",
"bold",
"Boolean",
"border",
"borderColor",
"bottomScroll",
"break",
"bullet",
"call",
"callee",
"caller",
"capabilities",
"CAPSLOCK",
"case",
"ceil",
"charAt",
"charCodeAt",
"childNodes",
"chr",
"clear",
"clearInterval",
"cloneNode",
"close",
"color",
"Color",
"comment",
"concat",
"connect",
"contentType",
"continue",
"CONTROL",
"cos",
"createElement",
"createEmptyMovieClip",
"createTextField",
"createTextNode",
"_currentframe",
"curveTo",
"Date",
"default",
"delete",
"DELETEKEY",
"do",
"docTypeDecl",
"DOWN",
"_droptarget",
"duplicateMovieClip",
"duration",
"E",
"else",
"embedFonts",
"enabled",
"END",
"endFill",
"endinitclip",
"ENTER",
"eq",
"escape",
"ESCAPE",
"eval",
"evaluate",
"exp",
"false",
"firstChild",
"floor",
"focusEnabled",
"_focusrect",
"font",
"for",
"_framesloaded",
"fromCharCode",
"fscommand",
"function",
"ge",
"get",
"getAscii",
"getBeginIndex",
"getBounds",
"getBytesLoaded",
"getBytesTotal",
"getCaretIndex",
"getCode",
"getDate",
"getDay",
"getDepth",
"getEndIndex",
"getFocus",
"getFontList",
"getFullYear",
"getHours",
"getMilliseconds",
"getMinutes",
"getMonth",
"getNewTextFormat",
"getPan",
"getProperty",
"getRGB",
"getSeconds",
"getTextExtent",
"getTextFormat",
"getTime",
"getTimer",
"getTimezoneOffset",
"getTransform",
"getURL",
"getUTCDate",
"getUTCDay",
"getUTCFullYear",
"getUTCHours",
"getUTCMilliseconds",
"getUTCMinutes",
"getUTCMonth",
"getUTCSeconds",
"getVersion",
"getVolume",
"getYear",
"_global",
"globalToLocal",
"goto",
"gotoAndPlay",
"gotoAndStop",
"gt",
"hasAccessibility",
"hasAudio",
"hasAudioEncoder",
"hasChildNodes",
"hasMP3",
"hasVideoEncoder",
"height",
"_height",
"hide",
"_highquality",
"hitArea",
"hitTest",
"HOME",
"hscroll",
"html",
"htmlText",
"if",
"ifFrameLoaded",
"ignoreWhite",
"in",
"include",
"indent",
"indexOf",
"initclip",
"INSERT",
"insertBefore",
"install",
"instanceof",
"int",
"isActive",
"isDown",
"isFinite",
"isNaN",
"isToggled",
"italic",
"join",
"lastChild",
"lastIndexOf",
"le",
"leading",
"LEFT",
"leftMargin",
"length",
"_level",
"lineStyle",
"lineTo",
"list",
"LN10",
"LN2",
"load",
"loaded",
"loadMovie",
"loadMovieNum",
"loadSound",
"loadVariables",
"loadVariablesNum",
"LoadVars",
"localToGlobal",
"log",
"LOG10E",
"LOG2E",
"max",
"maxChars",
"maxhscroll",
"maxscroll",
"MAX_VALUE",
"mbchr",
"mblength",
"mbord",
"mbsubstring",
"method",
"min",
"MIN_VALUE",
"moveTo",
"multiline",
"_name",
"NaN",
"ne",
"NEGATIVE_INFINITY",
"new",
"newline",
"nextFrame",
"nextScene",
"nextSibling",
"nodeName",
"nodeType",
"nodeValue",
"not",
"null",
"Number",
"Object",
"on",
"onChanged",
"onClipEvent",
"onClose",
"onConnect",
"onData",
"onDragOut",
"onDragOver",
"onEnterFrame",
"onKeyDown",
"onKeyUp",
"onKillFocus",
"onLoad",
"onMouseDown",
"onMouseMove",
"onMouseUp",
"onPress",
"onRelease",
"onReleaseOutside",
"onResize",
"onRollOut",
"onRollOver",
"onScroller",
"onSetFocus",
"onSoundComplete",
"onUnload",
"onUpdate",
"onXML",
"or",
"ord",
"_parent",
"parentNode",
"parseFloat",
"parseInt",
"parseXML",
"password",
"PGDN",
"PGUP",
"PI",
"pixelAspectRatio",
"play",
"pop",
"position",
"POSITIVE_INFINITY",
"pow",
"prevFrame",
"previousSibling",
"prevScene",
"print",
"printAsBitmap",
"printAsBitmapNum",
"printNum",
"__proto__",
"prototype",
"push",
"_quality",
"random",
"registerClass",
"removeListener",
"removeMovieClip",
"removeNode",
"removeTextField",
"replaceSel",
"restrict",
"return",
"reverse",
"RIGHT",
"rightMargin",
"_root",
"_rotation",
"round",
"scaleMode",
"screenColor",
"screenDPI",
"screenResolutionX",
"screenResolutionY",
"scroll",
"selectable",
"send",
"sendAndLoad",
"set",
"setDate",
"setFocus",
"setFullYear",
"setHours",
"setInterval",
"setMask",
"setMilliseconds",
"setMinutes",
"setMonth",
"setNewTextFormat",
"setPan",
"setProperty",
"setRGB",
"setSeconds",
"setSelection",
"setTextFormat",
"setTime",
"setTransform",
"setUTCDate",
"setUTCFullYear",
"setUTCHours",
"setUTCMilliseconds",
"setUTCMinutes",
"setUTCMonth",
"setUTCSeconds",
"setVolume",
"setYear",
"shift",
"SHIFT",
"show",
"showMenu",
"sin",
"size",
"slice",
"sort",
"sortOn",
"Sound",
"_soundbuftime",
"SPACE",
"splice",
"split",
"sqrt",
"SQRT1_2",
"SQRT2",
"start",
"startDrag",
"status",
"stop",
"stopAllSounds",
"stopDrag",
"String",
"substr",
"substring",
"super",
"swapDepths",
"switch",
"TAB",
"tabChildren",
"tabEnabled",
"tabIndex",
"tabStops",
"tan",
"target",
"_target",
"targetPath",
"tellTarget",
"text",
"textColor",
"TextFormat",
"textHeight",
"textWidth",
"this",
"toggleHighQuality",
"toLowerCase",
"toString",
"_totalframes",
"toUpperCase",
"trace",
"trackAsMenu",
"true",
"type",
"typeof",
"undefined",
"underline",
"unescape",
"uninstall",
"unloadMovie",
"unloadMovieNum",
"unshift",
"unwatch",
"UP",
"updateAfterEvent",
"url",
"_url",
"useHandCursor",
"UTC",
"valueOf",
"var",
"variable",
"_visible",
"void",
"watch",
"while",
"width",
"_width",
"with",
"wordWrap",
"_x",
"XML",
"xmlDecl",
"XMLSocket",
"_xmouse",
"_xscale",
"_y",
"_ymouse",
nullptr
};
/**
* Constructor.
*/
ASWriter::ASWriter()
{
}
/**
* Destructor.
*/
ASWriter::~ASWriter()
{
}
/**
* Call this method to generate Actionscript code for a UMLClassifier.
* @param c the class you want to generate code for
*/
void ASWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("ASWriter::writeClass: Cannot write class of NULL classifier!");
return;
}
QString classname = cleanName(c->name());
QString fileName = c->name().toLower();
//find an appropriate name for our file
fileName = findFileName(c, QStringLiteral(".as"));
if (fileName.isEmpty())
{
Q_EMIT codeGenerated(c, false);
return;
}
QFile fileas;
if (!openFile(fileas, fileName))
{
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream as(&fileas);
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".as"));
if (!str.isEmpty())
{
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName + QStringLiteral(".as"));
str.replace(QRegularExpression(QStringLiteral("%filepath%")), fileas.fileName());
as << str << m_endl;
}
//write includes
UMLPackageList includes;
findObjectsRelated(c, includes);
for (UMLPackage* conc: includes) {
QString headerName = findFileName(conc, QStringLiteral(".as"));
if (!headerName.isEmpty())
{
as << "#include \"" << findFileName(conc, QStringLiteral(".as")) << "\"" << m_endl;
}
}
as << m_endl;
//Write class Documentation if there is something or if force option
if (forceDoc() || !c->doc().isEmpty())
{
as << m_endl << "/**" << m_endl;
as << " * class " << classname << m_endl;
as << formatDoc(c->doc(), QStringLiteral(" * "));
as << " */" << m_endl << m_endl;
}
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
//check if class is abstract and / or has abstract methods
if (c->isAbstract() && !hasAbstractOps(c))
as << "/******************************* Abstract Class ****************************" << m_endl << " "
<< classname << " does not have any pure virtual methods, but its author" << m_endl
<< " defined it as an abstract class, so you should not use it directly." << m_endl
<< " Inherit from it instead and create only objects from the derived classes" << m_endl
<< "*****************************************************************************/" << m_endl << m_endl;
as << classname << " = function ()" << m_endl;
as << "{" << m_endl;
as << m_indentation << "this._init ();" << m_endl;
as << "}" << m_endl;
as << m_endl;
for (UMLClassifier* obj: superclasses) {
as << classname << ".prototype = new " << cleanName(obj->name()) << " ();" << m_endl;
}
as << m_endl;
const bool isClass = !c->isInterface();
if (isClass) {
UMLAttributeList atl = c->getAttributeList();
as << "/**" << m_endl;
QString temp = QStringLiteral("_init sets all ") + classname +
QStringLiteral(" attributes to their default values. ") +
QStringLiteral("Make sure to call this method within your class constructor");
as << formatDoc(temp, QStringLiteral(" * "));
as << " */" << m_endl;
as << classname << ".prototype._init = function ()" << m_endl;
as << "{" << m_endl;
for (UMLAttribute* at: atl) {
if (forceDoc() || !at->doc().isEmpty())
{
as << m_indentation << "/**" << m_endl
<< formatDoc(at->doc(), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
if (!at->getInitialValue().isEmpty())
{
as << m_indentation << "this.m_" << cleanName(at->name()) << " = " << at->getInitialValue() << ";" << m_endl;
}
else
{
as << m_indentation << "this.m_" << cleanName(at->name()) << " = \"\";" << m_endl;
}
}
}
//associations
if (forceSections() || !aggregations.isEmpty())
{
as << m_endl << m_indentation << "/**Aggregations: */" << m_endl;
writeAssociation(classname, aggregations, as);
}
if (forceSections() || !compositions.isEmpty())
{
as << m_endl << m_indentation << "/**Compositions: */" << m_endl;
writeAssociation(classname, compositions, as);
}
as << m_endl;
as << m_indentation << "/**Protected: */" << m_endl;
if (isClass) {
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute* at: atl) {
if (at->visibility() == Uml::Visibility::Protected) {
as << m_indentation << "ASSetPropFlags (this, \"" << cleanName(at->name()) << "\", 1);" << m_endl;
}
}
}
UMLOperationList opList(c->getOpList());
for (UMLOperation* op: opList) {
if (op->visibility() == Uml::Visibility::Protected) {
as << m_indentation << "ASSetPropFlags (this, \"" << cleanName(op->name()) << "\", 1);" << m_endl;
}
}
as << m_endl;
as << m_indentation << "/**Private: */" << m_endl;
if (isClass) {
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute* at: atl) {
if (at->visibility() == Uml::Visibility::Private) {
as << m_indentation << "ASSetPropFlags (this, \"" << cleanName(at->name()) << "\", 7);" << m_endl;
}
}
}
for (UMLOperation* op: opList) {
if (op->visibility() == Uml::Visibility::Protected) {
as << m_indentation << "ASSetPropFlags (this, \"" << cleanName(op->name()) << "\", 7);" << m_endl;
}
}
as << "}" << m_endl;
as << m_endl;
//operations
UMLOperationList ops(c->getOpList());
writeOperations(classname, &ops, as);
as << m_endl;
//finish file
//close files and notfiy we are done
fileas.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(fileas.fileName());
}
////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
/**
* Write a list of associations.
*
* @param classname the name of the class
* @param assocList the list of associations
* @param as output stream for the AS file
*/
void ASWriter::writeAssociation(QString& classname, UMLAssociationList& assocList, QTextStream &as)
{
for (UMLAssociation *a: assocList)
{
// association side
Uml::RoleType::Enum role = a->getObject(Uml::RoleType::A)->name() == classname ? Uml::RoleType::B : Uml::RoleType::A;
QString roleName(cleanName(a->getRoleName(role)));
if (!roleName.isEmpty()) {
// association doc
if (forceDoc() || !a->doc().isEmpty()) {
as << m_indentation << "/**" << m_endl
<< formatDoc(a->doc(), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
// role doc
if (forceDoc() || !a->getRoleDoc(role).isEmpty()) {
as << m_indentation << "/**" << m_endl
<< formatDoc(a->getRoleDoc(role), m_indentation + QStringLiteral(" * "))
<< m_indentation << " */" << m_endl;
}
bool okCvt;
int nMulti = a->getMultiplicity(role).toInt(&okCvt, 10);
bool isNotMulti = a->getMultiplicity(role).isEmpty() || (okCvt && nMulti == 1);
QString typeName(cleanName(a->getObject(role)->name()));
if (isNotMulti)
as << m_indentation << "this.m_" << roleName << " = new " << typeName << "();" << m_endl;
else
as << m_indentation << "this.m_" << roleName << " = new Array();" << m_endl;
// role visibility
if (a->visibility(role) == Uml::Visibility::Private)
{
as << m_indentation << "ASSetPropFlags (this, \"m_" << roleName << "\", 7);" << m_endl;
}
else if (a->visibility(role)== Uml::Visibility::Protected)
{
as << m_indentation << "ASSetPropFlags (this, \"m_" << roleName << "\", 1);" << m_endl;
}
}
}
}
/**
* Write a list of class operations.
*
* @param classname the name of the class
* @param opList the list of operations
* @param as output stream for the AS file
*/
void ASWriter::writeOperations(QString classname, UMLOperationList *opList, QTextStream &as)
{
UMLAttributeList atl;
for (UMLOperation* op: *opList) {
atl = op -> getParmList();
//write method doc if we have doc || if at least one of the params has doc
bool writeDoc = forceDoc() || !op->doc().isEmpty();
for (UMLAttribute* at: atl) {
writeDoc |= !at->doc().isEmpty();
}
if (writeDoc) //write method documentation
{
as << "/**" << m_endl << formatDoc(op->doc(), QStringLiteral(" * "));
for (UMLAttribute* at: atl) {
if (forceDoc() || !at->doc().isEmpty()) {
as << " * @param " << cleanName(at->name()) << m_endl;
as << formatDoc(at->doc(), QStringLiteral(" * "));
}
}//end for : write parameter documentation
as << " */" << m_endl;
}//end if : write method documentation
as << classname << ".prototype." << cleanName(op->name()) << " = function " << "(";
int i= atl.count();
int j=0;
for (UMLAttributeListIt atlIt(atl); atlIt.hasNext(); ++j) {
UMLAttribute* at = atlIt.next();
as << cleanName(at->name())
<< (!(at->getInitialValue().isEmpty()) ? (QStringLiteral(" = ") + at->getInitialValue()) : QString())
<< ((j < i-1) ? QStringLiteral(", ") : QString());
}
as << ")" << m_endl << "{" << m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
as << m_indentation << m_endl;
}
else {
as << formatSourceCode(sourceCode, m_indentation);
}
as << "}" << m_endl;
as << m_endl << m_endl;
}//end for
}
/**
* Returns "ActionScript".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum ASWriter::language() const
{
return Uml::ProgrammingLanguage::ActionScript;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList ASWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 18,725
|
C++
|
.cpp
| 740
| 19.264865
| 125
| 0.535025
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,548
|
tclwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/tcl/tclwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Rene Meyer <rene.meyer@sturmit.de>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "tclwriter.h"
// app includes
#include "association.h"
#include "classifier.h"
#include "classifierlistitem.h"
#include "codegen_utils.h"
#include "debug_utils.h"
#include "model_utils.h"
#include "operation.h"
#include "template.h"
#include "umltemplatelist.h"
#include "umlclassifierlistitemlist.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
static const char *reserved_words[] = {
"body",
"break",
"case",
"class",
"common",
"concat",
"configbody",
"constructor",
"continue",
"default",
"destructor",
"else",
"elseif",
"for",
"foreach",
"global",
"if",
"incr",
"lappend",
"lindex",
"list",
"llength",
"load",
"lrange",
"lreplace",
"method",
"namespace",
"private",
"proc",
"protected",
"public",
"return",
"set",
"source",
"switch",
"then",
"upvar",
"variable",
"virtual",
"while",
nullptr
};
/**
* Constructor, initialises a couple of variables.
*/
TclWriter::TclWriter()
: mStream(nullptr)
{
}
/**
* Destructor, empty.
*/
TclWriter::~TclWriter()
{
}
/**
* Returns "Tcl".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum TclWriter::language() const
{
return Uml::ProgrammingLanguage::Tcl;
}
/**
* Call this method to generate tcl code for a UMLClassifier.
* @param c the class to generate code for
*/
void TclWriter::writeClass(UMLClassifier * c)
{
if (!c) {
logWarn0("TclWriter::writeClass: Cannot write class of NULL classifier");
return;
}
QFile fileh, filetcl;
// find an appropriate name for our file
fileName_ = findFileName(c, QStringLiteral(".tcl"));
if (fileName_.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
if (!openFile(fileh, fileName_)) {
Q_EMIT codeGenerated(c, false);
return;
}
// preparations
className_ = cleanName(c->name());
if (!c->package().isEmpty()) {
mNamespace = QStringLiteral("::") + cleanName(c->package());
mClassGlobal = mNamespace + QStringLiteral("::") + className_;
} else {
mNamespace = QStringLiteral("::");
mClassGlobal = QStringLiteral("::") + className_;
}
// write Header file
writeHeaderFile(c, fileh);
fileh.close();
// Determine whether the implementation file is required.
// (It is not required if the class is an enumeration.)
bool need_impl = true;
if (!c->isInterface()) {
if (c->baseType() == UMLObject::ot_Enum)
need_impl = false;
}
if (need_impl) {
if (!openFile(filetcl, fileName_ + QStringLiteral("body"))) {
Q_EMIT codeGenerated(c, false);
return;
}
// write Source file
writeSourceFile(c, filetcl);
filetcl.close();
}
// emit done code
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(fileh.fileName());
if (need_impl) {
Q_EMIT showGeneratedFile(filetcl.fileName());
}
}
/**
* Write the header file for this classifier.
*/
void TclWriter::writeHeaderFile(UMLClassifier * c, QFile & fileh)
{
// open stream for writing
QTextStream stream(&fileh);
mStream = &stream;
// reset the indent level
m_indentLevel = 0;
// write header blurb
QString str = getHeadingFile(QStringLiteral(".tcl"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName_);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), fileh.fileName());
writeCode(str);
}
// set current namespace
writeCode(QStringLiteral("namespace eval ") + mNamespace + QStringLiteral(" {"));
m_indentLevel++;
// check on already existing
writeComm(QStringLiteral("Do not load twice"));
writeCode(QStringLiteral("if {[namespace exist ") + className_ + QStringLiteral("]} return"));
// source used superclass files
UMLClassifierList superclasses = c->getSuperClasses();
if (superclasses.count() > 0) {
writeComm
(QStringLiteral("Source found and used class files and import class command if necessary"));
for(UMLClassifier * classifier : superclasses) {
writeUse(classifier);
}
}
// write all "source" we need to include other classes, that arent us.
if (c->hasAssociations()) {
writeAssociationIncl(c->getSpecificAssocs(Uml::AssociationType::Association), c->id(),
QStringLiteral("Associations"));
writeAssociationIncl(c->getAggregations(), c->id(),
QStringLiteral("Aggregations"));
writeAssociationIncl(c->getCompositions(), c->id(),
QStringLiteral("Compositions"));
}
//Write class Documentation
writeDocu(QStringLiteral("\n@class\t") + className_ + m_endl + c->doc());
//check if class is abstract and / or has abstract methods
if ((c->isAbstract() || c->isInterface())
&& !hasAbstractOps(c)) {
writeComm(QStringLiteral("TODO abstract class") + className_ +
QStringLiteral("\nInherit from it and create only objects from the derived classes"));
}
// check on enum classes
if (!c->isInterface()) {
// use tcl-list for enum's
if (c->baseType() == UMLObject::ot_Enum) {
UMLClassifierListItemList litList =
c->getFilteredList(UMLObject::ot_EnumLiteral);
writeCode(QStringLiteral("set enum_") + className_ + QStringLiteral(" [list\\"));
m_indentLevel++;
for(UMLClassifierListItem * lit : litList) {
QString enumLiteral = cleanName(lit->name());
writeCode(enumLiteral + QStringLiteral("\\"));
}
m_indentLevel--;
writeCode(QStringLiteral("];# end of enum"));
m_indentLevel--;
writeCode(QStringLiteral("};# end of namespace"));
return;
}
}
// Generate template parameters.
UMLTemplateList template_params = c->getTemplateList();
if (template_params.count()) {
writeCode(QStringLiteral("#TODO template<"));
for(UMLTemplate * t : template_params) {
QString formalName = t->name();
QString typeName = t->getTypeName();
writeCode(typeName + QStringLiteral("# ") + formalName);
}
}
// start my own class
writeCode(QStringLiteral("class ") + className_ + QStringLiteral(" {"));
m_indentLevel++;
if (c->getSuperClasses().count() > 0) {
QString code = QStringLiteral("inherit");
for(UMLClassifier * superClass : c->getSuperClasses()) {
/*
if (superClass->getAbstract() || superClass->isInterface())
stream << indent() << QStringLiteral("virtual ");
*/
if (superClass->package().isEmpty()) {
code += QStringLiteral(" ::") + cleanName(superClass->name());
} else {
code +=
QStringLiteral(" ::") + cleanName(superClass->package()) + QStringLiteral("::") +
cleanName(superClass->name());
}
}
writeCode(code);
}
//
//declarations of operations
//
// write out field and operations decl grouped by visibility
//
// PUBLIC attribs/methods
// for public: constructors are first ops we print out
if (!c->isInterface()) {
writeConstructorHeader();
writeDestructorHeader();
}
// attributes
writeAttributeDecl(c, Uml::Visibility::Public, true); // write static attributes first
writeAttributeDecl(c, Uml::Visibility::Public, false);
// associations
writeAssociationDecl(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Public, c->id(),
QStringLiteral("Associations"));
writeAssociationDecl(c->getAggregations(), Uml::Visibility::Public, c->id(),
QStringLiteral("Aggregations"));
writeAssociationDecl(c->getCompositions(), Uml::Visibility::Public, c->id(),
QStringLiteral("Compositions"));
//TODO writeHeaderAccessorMethodDecl(c, Uml::Visibility::Public, stream);
writeOperationHeader(c, Uml::Visibility::Public);
// PROTECTED attribs/methods
//
// attributes
writeAttributeDecl(c, Uml::Visibility::Protected, true); // write static attributes first
writeAttributeDecl(c, Uml::Visibility::Protected, false);
// associations
writeAssociationDecl(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Protected,
c->id(), QStringLiteral("Association"));
writeAssociationDecl(c->getAggregations(), Uml::Visibility::Protected,
c->id(), QStringLiteral("Aggregation"));
writeAssociationDecl(c->getCompositions(), Uml::Visibility::Protected,
c->id(), QStringLiteral("Composition"));
//TODO writeHeaderAccessorMethodDecl(c, Uml::Visibility::Protected, stream);
writeOperationHeader(c, Uml::Visibility::Protected);
// PRIVATE attribs/methods
//
// attributes
writeAttributeDecl(c, Uml::Visibility::Private, true); // write static attributes first
writeAttributeDecl(c, Uml::Visibility::Private, false);
// associations
writeAssociationDecl(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Private,
c->id(), QStringLiteral("Associations"));
writeAssociationDecl(c->getAggregations(), Uml::Visibility::Private, c->id(),
QStringLiteral("Aggregations"));
writeAssociationDecl(c->getCompositions(), Uml::Visibility::Private, c->id(),
QStringLiteral("Compositions"));
//TODO writeHeaderAccessorMethodDecl(c, Uml::Visibility::Public, stream);
writeOperationHeader(c, Uml::Visibility::Private);
writeInitAttributeHeader(c); // this is always private, used by constructors to initialize class
// end of class header
m_indentLevel--;
writeCode(QStringLiteral("};# end of class"));
// end of class namespace, if any
m_indentLevel--;
writeCode(QStringLiteral("};# end of namespace"));
}
/**
* Write the source code body file for this classifier.
*/
void TclWriter::writeSourceFile(UMLClassifier * c, QFile & filetcl)
{
// open stream for writing
QTextStream stream(&filetcl);
mStream = &stream;
// set the starting indentation at zero
m_indentLevel = 0;
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".tclbody"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName_ + QStringLiteral("body"));
str.replace(QRegularExpression(QStringLiteral("%filepath%")), filetcl.fileName());
writeCode(str);
}
// Start body of class
// constructors are first ops we print out
if (!c->isInterface()) {
writeConstructorSource(c);
writeDestructorSource();
}
// Public attributes have in tcl a configbody method
writeAttributeSource(c);
// Association access functions
writeAssociationSource(c->getSpecificAssocs(Uml::AssociationType::Association), c->id());
writeAssociationSource(c->getAggregations(), c->id());
writeAssociationSource(c->getCompositions(), c->id());
// Procedures and methods
writeOperationSource(c, Uml::Visibility::Public);
writeOperationSource(c, Uml::Visibility::Protected);
writeOperationSource(c, Uml::Visibility::Private);
// Yep, bringing up the back of the bus, our initialization method for attributes
writeInitAttributeSource(c);
}
/**
* Write the source code text.
*/
void TclWriter::writeCode(const QString &text)
{
*mStream << indent() << text << m_endl;
}
/**
* Write comment text.
*/
void TclWriter::writeComm(const QString &text)
{
QStringList lines = text.split(QRegularExpression(QStringLiteral("\n")));
for (int i = 0; i < lines.count(); ++i) {
*mStream << indent() << QStringLiteral("# ") << lines[i] << m_endl;
}
}
/**
* Write documentation text.
*/
void TclWriter::writeDocu(const QString &text)
{
QStringList lines = text.split(QRegularExpression(QStringLiteral("\n")));
for (int i = 0; i < lines.count(); ++i) {
*mStream << indent() << QStringLiteral("## ") << lines[i] << m_endl;
}
}
// To prevent circular including when both classifiers on either end
// of an association have roles we need to have forward declaration of
// the other class...but only IF it is not THIS class (as could happen
// in self-association relationship).
void TclWriter::writeAssociationIncl(UMLAssociationList list, Uml::ID::Type myId,
const QString &type)
{
for(UMLAssociation * a : list) {
UMLClassifier *classifier = nullptr;
writeComm(m_endl + type + m_endl + a->toString() + m_endl + a->doc());
// only use OTHER classes (e.g. we don't need to write includes for ourselves!!
// AND only IF the roleName is defined, otherwise, it is not meant to be noticed.
if (a->getObjectId(Uml::RoleType::A) == myId && !a->getRoleName(Uml::RoleType::B).isEmpty()) {
classifier = a->getObject(Uml::RoleType::B)->asUMLClassifier();
if (classifier == nullptr)
continue;
writeUse(classifier);
} else if (a->getObjectId(Uml::RoleType::B) == myId
&& !a->getRoleName(Uml::RoleType::A).isEmpty()) {
classifier = a->getObject(Uml::RoleType::A)->asUMLClassifier();
if (classifier == nullptr)
continue;
if (classifier->package().isEmpty())
writeCode(QStringLiteral("namespace eval ") + cleanName(classifier->name()) +
QStringLiteral(" {}"));
} else {
// CHECK: This crashes (classifier still NULL from above)
/*
writeCode(QStringLiteral("namespace eval ") + cleanName(classifier->getPackage()) +
QStringLiteral("::") + cleanName(classifier->getName()) + QStringLiteral(" {}"));
*/
}
}
}
void TclWriter::writeUse(UMLClassifier * c)
{
QString myNs;
if (!c->package().isEmpty()) {
myNs = cleanName(c->package());
}
// if different package
if (QString(QStringLiteral("::") + myNs) != mNamespace) {
if (c->package().isEmpty()) {
writeCode(QStringLiteral("source ") + findFileName(c, QStringLiteral(".tcl")));
writeCode(QStringLiteral("namespace import ::") + cleanName(c->name()));
} else {
writeCode(QStringLiteral("package require ") + myNs);
writeCode(QStringLiteral("namespace import ::") + myNs + QStringLiteral("::") +
cleanName(c->name()));
}
} else {
// source the file
writeCode(QStringLiteral("source ") + findFileName(c, QStringLiteral(".tcl")));
}
}
void TclWriter::writeConstructorHeader()
{
writeDocu(m_endl + QStringLiteral("@func constructor") + m_endl +
QStringLiteral("@par args contain all configuration parameters") + m_endl);
writeCode(QStringLiteral("constructor {args} {}") + m_endl);
}
void TclWriter::writeConstructorSource(UMLClassifier * c)
{
writeComm(mClassGlobal + QStringLiteral("::constructor"));
writeCode(mClassGlobal + QStringLiteral("::constructor {args} {"));
m_indentLevel++;
if (c->hasAttributes()) {
writeCode(QStringLiteral("initAttributes"));
}
writeCode(QStringLiteral("eval configure $args"));
m_indentLevel--;
writeCode(QLatin1Char('}') + m_endl);
}
void TclWriter::writeDestructorHeader()
{
writeDocu(m_endl + QStringLiteral("@func destructor") + m_endl);
writeCode(QStringLiteral("destructor {} {}"));
}
void TclWriter::writeDestructorSource()
{
writeComm(mClassGlobal + QStringLiteral("::destructor"));
writeCode(mClassGlobal + QStringLiteral("::destructor {} {") + m_endl + QLatin1Char('}') + m_endl);
}
/**
* Writes the Attribute declarations
* @param c classifier
* @param writeStatic whether to write static or non-static attributes out
* @param visibility the visibility of the attribs to print out
*/
void TclWriter::writeAttributeDecl(UMLClassifier * c, Uml::Visibility::Enum visibility, bool writeStatic)
{
if (c->isInterface())
return;
QString scope = Uml::Visibility::toString(visibility);
QString type;
if (writeStatic) {
type = QStringLiteral("common");
} else {
type = QStringLiteral("variable");
}
UMLAttributeList list;
if (writeStatic) {
list = c->getAttributeListStatic(visibility);
}
else {
list = c->getAttributeList(visibility);
}
if (list.count() > 0) {
writeComm(m_endl + scope + QLatin1Char(' ') + type + QStringLiteral(" attributes") + m_endl);
// write attrib declarations now
QString documentation;
for(UMLAttribute *at : list) {
documentation = at->doc();
QString varName = cleanName(at->name());
QString typeName = fixTypeName(at->getTypeName());
writeDocu(m_endl + QStringLiteral("@var ") + scope + QLatin1Char(' ') + type + QLatin1Char(' ') + typeName + QLatin1Char(' ') +
varName + m_endl + documentation);
writeCode(scope + QLatin1Char(' ') + type + QLatin1Char(' ') + varName + m_endl);
}
}
}
/**
* Searches a list of associations for appropriate ones to write out as attributes.
*/
void TclWriter::writeAssociationDecl(UMLAssociationList associations,
Uml::Visibility::Enum permitScope, Uml::ID::Type id,
const QString &type)
{
Q_UNUSED(type);
if (forceSections() || !associations.isEmpty()) {
bool printRoleA = false, printRoleB = false;
for(UMLAssociation * a : associations) {
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id && !a->getRoleName(Uml::RoleType::B).isEmpty())
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id && !a->getRoleName(Uml::RoleType::A).isEmpty())
printRoleA = true;
// First: we insert documentation for association IF it has either role AND some documentation (!)
// print RoleB decl
if (printRoleB && a->visibility(Uml::RoleType::B) == permitScope) {
QString fieldClassName =
cleanName(getUMLObjectName(a->getObject(Uml::RoleType::B)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::B),
a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B),
Uml::Visibility::toString(permitScope));
}
// print RoleA decl
if (printRoleA && a->visibility(Uml::RoleType::A) == permitScope) {
QString fieldClassName =
cleanName(getUMLObjectName(a->getObject(Uml::RoleType::A)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::A),
a->getMultiplicity(Uml::RoleType::A), a->getRoleDoc(Uml::RoleType::A),
Uml::Visibility::toString(permitScope));
}
// reset for next association in our loop
printRoleA = false;
printRoleB = false;
}
}
}
/**
* Writes out an association as an attribute using Vector.
*/
void TclWriter::writeAssociationRoleDecl(const QString &fieldClassName, const QString &roleName,
const QString &multi, const QString &doc, const QString &scope)
{
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared in the code
if (roleName.isEmpty())
return;
// declare the association based on whether it is this a single variable
// or a List (Vector). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$")))) {
QString fieldVarName = roleName.toLower();
// record this for later consideration of initialization IF the
// multi value requires 1 of these objects
if (ObjectFieldVariables.indexOf(fieldVarName) == -1 &&
multi.contains(QRegularExpression(QStringLiteral("^1$")))
) {
// ugh. UGLY. Storing variable name and its class in pairs.
ObjectFieldVariables.append(fieldVarName);
ObjectFieldVariables.append(fieldClassName);
}
writeDocu(m_endl + QStringLiteral("@var ") + scope + QStringLiteral(" variable <") + fieldClassName +
QStringLiteral("> ") + fieldVarName + m_endl + doc);
writeCode(scope + QStringLiteral(" variable ") + fieldVarName + m_endl);
} else {
QString fieldVarName = roleName.toLower();
// record unique occurrences for later when we want to check
// for initialization of this vector
if (VectorFieldVariables.indexOf(fieldVarName) == -1)
VectorFieldVariables.append(fieldVarName);
writeDocu(m_endl + QStringLiteral("@var") + scope + QStringLiteral(" variable <") + fieldClassName +
QStringLiteral("*> ") + fieldVarName + m_endl + doc);
writeCode(scope + QStringLiteral(" variable ") + fieldVarName + m_endl);
}
}
/**
* If needed, write out the declaration for the method to initialize attributes of our class.
*/
void TclWriter::writeInitAttributeHeader(UMLClassifier * c)
{
if (c->hasAttributes()) {
writeDocu(QStringLiteral("@method private initAttributes") + m_endl +
QStringLiteral("Initialize all internal variables"));
writeCode(QStringLiteral("private method initAttributes {}"));
}
}
/**
* If needed, write out the declaration for the method to initialize attributes of our class.
*/
void TclWriter::writeInitAttributeSource(UMLClassifier* c)
{
// only need to do this under certain conditions
if (c->hasAttributes()) {
QString varName;
writeComm(mClassGlobal + QStringLiteral("::initAttributes"));
writeCode(QStringLiteral("body ") + mClassGlobal + QStringLiteral("::initAttributes {} {"));
m_indentLevel++;
// first, initiation of fields derived from attributes
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute * at : atl) {
if (!at->getInitialValue().isEmpty()) {
varName = cleanName(at->name());
writeCode(QStringLiteral("set ") + varName + QLatin1Char(' ') + at->getInitialValue());
}
}
// Now initialize the association related fields (e.g. vectors)
QStringList::Iterator it;
for (it = VectorFieldVariables.begin();
it != VectorFieldVariables.end(); ++it) {
varName = *it;
writeCode(QStringLiteral("set ") + varName + QStringLiteral(" [list]"));
}
for (it = ObjectFieldVariables.begin();
it != ObjectFieldVariables.end(); ++it) {
varName = *it;
it++;
QString fieldClassName = *it;
writeCode(QStringLiteral("set ") + varName + QStringLiteral(" [list]"));
}
// clean up
ObjectFieldVariables.clear(); // shouldn't be needed?
VectorFieldVariables.clear(); // shouldn't be needed?
m_indentLevel--;
writeCode(QLatin1Char('}') + m_endl);
}
}
void TclWriter::writeOperationHeader(UMLClassifier * c, Uml::Visibility::Enum permitScope)
{
UMLOperationList oplist;
int j;
//sort operations by scope first and see if there are abstract methods
UMLOperationList inputlist = c->getOpList();
for(UMLOperation * op : inputlist) {
switch (op->visibility()) {
case Uml::Visibility::Public:
if (permitScope == Uml::Visibility::Public)
oplist.append(op);
break;
case Uml::Visibility::Protected:
if (permitScope == Uml::Visibility::Protected)
oplist.append(op);
break;
case Uml::Visibility::Private:
if (permitScope == Uml::Visibility::Private)
oplist.append(op);
break;
default:
break;
}
}
// generate method decl for each operation given
if (oplist.count() > 0) {
writeComm(QStringLiteral("Operations"));
}
for(UMLOperation* op : oplist) {
QString doc;
QString code;
QString methodReturnType = fixTypeName(op->getTypeName());
QString name = cleanName(op->name());
QString scope = Uml::Visibility::toString(permitScope);
if (op->isAbstract() || c->isInterface()) {
//TODO declare abstract method as 'virtual'
// str += "virtual ";
}
// declaration for header file
if (op->isStatic()) {
doc = m_endl + QStringLiteral("@fn ") + scope + QStringLiteral(" proc ") + name + m_endl;
code = scope + QStringLiteral(" proc ") + name + QStringLiteral(" {");
} else {
doc = m_endl + QStringLiteral("@fn ") + scope + QStringLiteral(" method ") + name + m_endl;
code = scope + QStringLiteral(" method ") + name + QStringLiteral(" {");
}
// method parameters
UMLAttributeList atl = op->getParmList();
j = 0;
for(UMLAttribute* at : atl) {
QString typeName = fixTypeName(at->getTypeName());
QString atName = cleanName(at->name());
if (at->getInitialValue().isEmpty()) {
doc +=
QStringLiteral("@param ") + typeName + QLatin1Char(' ') + atName + m_endl + at->doc() +
m_endl;
code += QLatin1Char(' ') + atName;
} else {
doc +=
QStringLiteral("@param ") + typeName + QLatin1Char(' ') + atName + QStringLiteral(" (default=") +
at->getInitialValue() + QStringLiteral(") ") + m_endl + at->doc() + m_endl;
code += QStringLiteral(" {") + atName + QLatin1Char(' ') + at->getInitialValue() + QStringLiteral("} ");
}
j++;
}
if (methodReturnType != QStringLiteral("void")) {
doc += QStringLiteral("@return ") + methodReturnType + m_endl;
}
writeDocu(doc + op->doc());
writeCode(code + QStringLiteral("} {}") + m_endl);
}
}
void TclWriter::writeOperationSource(UMLClassifier * c, Uml::Visibility::Enum permitScope)
{
UMLOperationList oplist;
int j;
//sort operations by scope first and see if there are abstract methods
UMLOperationList inputlist = c->getOpList();
for(UMLOperation * op : inputlist) {
switch (op->visibility()) {
case Uml::Visibility::Public:
if (permitScope == Uml::Visibility::Public)
oplist.append(op);
break;
case Uml::Visibility::Protected:
if (permitScope == Uml::Visibility::Protected)
oplist.append(op);
break;
case Uml::Visibility::Private:
if (permitScope == Uml::Visibility::Private)
oplist.append(op);
break;
default:
break;
}
}
// generate source for each operation given
for(UMLOperation* op : oplist) {
QString code;
QString methodReturnType = fixTypeName(op->getTypeName());
QString name;
// no code needed
if (op->isAbstract() || c->isInterface()) {
continue;
}
name = mClassGlobal + QStringLiteral("::") + cleanName(op->name());
writeComm(name);
code = QStringLiteral("body ") + name + QStringLiteral(" {");
// parameters
UMLAttributeList atl = op->getParmList();
j = 0;
for(UMLAttribute* at : atl) {
QString atName = cleanName(at->name());
if (at->getInitialValue().isEmpty()) {
code += QLatin1Char(' ') + atName;
} else {
code += QStringLiteral(" {") + atName + QLatin1Char(' ') + at->getInitialValue() + QStringLiteral("} ");
}
j++;
}
writeCode(code += QStringLiteral("} {"));
m_indentLevel++;
QString sourceCode = op->getSourceCode();
if (!sourceCode.isEmpty()) {
*mStream << formatSourceCode(sourceCode, indent());
}
if (methodReturnType != QStringLiteral("void")) {
writeCode(QStringLiteral("return ") + methodReturnType);
} else {
writeCode(QStringLiteral("return"));
}
m_indentLevel--;
writeCode(QLatin1Char('}') + m_endl);
}
}
void TclWriter::writeAttributeSource(UMLClassifier * c)
{
UMLAttributeList list = c->getAttributeList(Uml::Visibility::Public);
for(UMLAttribute* at : list) {
QString name = mClassGlobal + QStringLiteral("::") + cleanName(at->name());
writeComm(name);
writeCode(QStringLiteral("configbody ") + name + QStringLiteral(" {} {") + m_endl + QLatin1Char('}') + m_endl);
}
}
void TclWriter::writeAssociationSource(UMLAssociationList associations,
Uml::ID::Type id)
{
if (associations.isEmpty()) {
return;
}
bool printRoleA = false, printRoleB = false;
for(UMLAssociation * a : associations) {
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id && !a->getRoleName(Uml::RoleType::B).isEmpty())
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id && !a->getRoleName(Uml::RoleType::A).isEmpty())
printRoleA = true;
// print RoleB source
if (printRoleB && a->visibility(Uml::RoleType::B) == Uml::Visibility::Public) {
QString fieldClassName =
cleanName(getUMLObjectName(a->getObject(Uml::RoleType::B)));
writeAssociationRoleSource(fieldClassName, a->getRoleName(Uml::RoleType::B),
a->getMultiplicity(Uml::RoleType::B));
}
// print RoleA source
if (printRoleA && a->visibility(Uml::RoleType::A) == Uml::Visibility::Public) {
QString fieldClassName =
cleanName(getUMLObjectName(a->getObject(Uml::RoleType::A)));
writeAssociationRoleSource(fieldClassName, a->getRoleName(Uml::RoleType::A),
a->getMultiplicity(Uml::RoleType::A));
}
// reset for next association in our loop
printRoleA = false;
printRoleB = false;
}
}
void TclWriter::writeAssociationRoleSource(const QString &fieldClassName,
const QString &roleName, const QString &multi)
{
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared in the code
if (roleName.isEmpty())
return;
// declare the association based on whether it is this a single variable
// or a List (Vector). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$")))) {
QString fieldVarName = roleName.toLower();
writeCode(QStringLiteral("configbody ") + mClassGlobal + QStringLiteral("::") + fieldVarName + QStringLiteral(" {} {"));
m_indentLevel++;
writeCode(QStringLiteral("if {![$") + fieldVarName + QStringLiteral(" isa ") + fieldClassName + QStringLiteral("]} {"));
m_indentLevel++;
writeCode(QStringLiteral("return -code error \"expected object of class: ") +
fieldClassName + QStringLiteral("\""));
m_indentLevel--;
writeCode(QStringLiteral("}"));
m_indentLevel--;
} else {
QString fieldVarName = roleName.toLower();
writeCode(QStringLiteral("configbody ") + mClassGlobal + QStringLiteral("::") + fieldVarName + QStringLiteral(" {} {"));
m_indentLevel++;
writeCode(QStringLiteral("foreach myObj $") + fieldVarName + QStringLiteral(" {"));
m_indentLevel++;
writeCode(QStringLiteral("if {![$myObj isa ") + fieldClassName + QStringLiteral("]} {"));
m_indentLevel++;
writeCode(QStringLiteral("return -code error \"expected object of class: ") +
fieldClassName + QStringLiteral("\""));
m_indentLevel--;
writeCode(QStringLiteral("}"));
m_indentLevel--;
writeCode(QStringLiteral("}"));
m_indentLevel--;
}
writeCode(QLatin1Char('}') + m_endl);
}
/**
* Replaces `string' with STRING_TYPENAME.
*/
QString TclWriter::fixTypeName(const QString &string)
{
if (string.isEmpty())
return QStringLiteral("void");
return string;
}
/**
* Returns the name of the given object (if it exists).
* Methods like this _shouldn't_ be needed IF we properly did things thruought the code.
*/
QString TclWriter::getUMLObjectName(UMLObject * obj)
{
return (obj != nullptr) ? obj->name() : QStringLiteral("NULL");
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList TclWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 34,762
|
C++
|
.cpp
| 862
| 32.344548
| 139
| 0.614129
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,549
|
rubycodeclassfielddeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodeclassfielddeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "rubycodeclassfielddeclarationblock.h"
#include "classifier.h"
#include "codegenerator.h"
#include "rubycodeclassfield.h"
#include "rubyclassifiercodedocument.h"
#include "rubycodegenerationpolicy.h"
#include "umlrole.h"
#include "uml.h"
/**
* Constructor.
*/
RubyCodeClassFieldDeclarationBlock::RubyCodeClassFieldDeclarationBlock(CodeClassField * parent)
: CodeClassFieldDeclarationBlock(parent)
{
setOverallIndentationLevel(1);
}
/**
* Empty Destructor.
*/
RubyCodeClassFieldDeclarationBlock::~RubyCodeClassFieldDeclarationBlock()
{
}
/**
* This will be called by syncToParent whenever the parent object is "modified".
*/
void RubyCodeClassFieldDeclarationBlock::updateContent()
{
CodeClassField * cf = getParentClassField();
RubyCodeClassField * rcf = dynamic_cast<RubyCodeClassField*>(cf);
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
Uml::Visibility::Enum scopePolicy = p->getAssociationFieldScope();
// Set the comment
QString notes = getParentObject()->doc();
getComment()->setText(notes);
// Set the body
QString staticValue = getParentObject()->isStatic() ? QStringLiteral("static ") : QString();
QString scopeStr = Uml::Visibility::toString(getParentObject()->visibility());
// IF this is from an association, then scope taken as appropriate to policy
if (!rcf->parentIsAttribute())
{
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
scopeStr = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing here... will leave as from parent object
break;
}
}
QString typeName = rcf->getTypeName();
QString fieldName = rcf->getFieldName();
QString initialV = rcf->getInitialValue();
if (!cf->parentIsAttribute() && !cf->fieldIsSingleValue())
typeName = QStringLiteral("Array");
QString body = staticValue + scopeStr + QLatin1Char(' ') + typeName + QLatin1Char(' ') + fieldName;
if (!initialV.isEmpty())
body.append(QStringLiteral(" = ") + initialV);
else if (!cf->parentIsAttribute())
{
const UMLRole * role = cf->getParentObject()->asUMLRole();
if (role && role->object()->baseType() == UMLObject::ot_Interface)
{
// do nothing.. can't instantiate an interface
} else {
// FIX?: IF a constructor method exists in the classifiercodedoc
// of the parent Object, then we can use that instead (if its empty).
if (cf->fieldIsSingleValue())
{
if (!typeName.isEmpty())
body.append(QStringLiteral(" = ") + typeName + QStringLiteral(".new()"));
} else
body.append(QStringLiteral(" = []"));
}
}
setText(body);
}
| 3,184
|
C++
|
.cpp
| 84
| 31.845238
| 103
| 0.67034
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,550
|
rubycodeaccessormethod.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodeaccessormethod.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodeaccessormethod.h"
// local includes
#include "attribute.h"
#include "codegenerator.h"
#include "classifiercodedocument.h"
#include "codegen_utils.h"
#include "debug_utils.h"
#include "rubyclassifiercodedocument.h"
#include "rubycodegenerationpolicy.h"
#include "rubycodegenerator.h"
#include "rubycodeclassfield.h"
#include "rubycodedocumentation.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
#include <QXmlStreamWriter>
/**
* Constructor.
*/
RubyCodeAccessorMethod::RubyCodeAccessorMethod(CodeClassField * field, CodeAccessorMethod::AccessorType type)
: CodeAccessorMethod(field)
{
setType(type);
// lets use full-blown comment
RubyClassifierCodeDocument *rccd = dynamic_cast<RubyClassifierCodeDocument*>(field->getParentDocument());
setComment(new RubyCodeDocumentation(rccd));
}
/**
* Empty Destructor.
*/
RubyCodeAccessorMethod::~RubyCodeAccessorMethod()
{
}
/**
* Set attributes of the node that represents this class
* in the XMI document.
*/
void RubyCodeAccessorMethod::setAttributesOnNode(QXmlStreamWriter& writer)
{
// set super-class attributes
CodeAccessorMethod::setAttributesOnNode(writer);
// set local attributes now
}
/**
* Set the class attributes of this object from
* the passed element node.
*/
void RubyCodeAccessorMethod::setAttributesFromNode(QDomElement& root)
{
// set attributes from superclass method the XMI
CodeAccessorMethod::setAttributesFromNode(root);
// load local stuff
}
void RubyCodeAccessorMethod::updateContent()
{
CodeClassField * parentField = getParentClassField();
RubyCodeClassField * rubyfield = dynamic_cast<RubyCodeClassField*>(parentField);
// Check for dynamic casting failure!
if (rubyfield == nullptr)
{
logError0("rubyfield: invalid dynamic cast");
return;
}
QString fieldName = rubyfield->getFieldName();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
QString text;
switch(getType()) {
case CodeAccessorMethod::ADD:
{
int maxOccurs = rubyfield->maximumListOccurances();
QString fieldType = rubyfield->getTypeName();
QString indent = getIndentation();
if (maxOccurs > 0)
text += QStringLiteral("if ") + fieldName + QStringLiteral(".size() < ")+ QString::number(maxOccurs) + QLatin1Char(' ') + endLine + indent;
text += fieldName + QStringLiteral(".push(value)");
if (maxOccurs > 0)
{
text += endLine + QStringLiteral("else") + endLine;
text += indent + QStringLiteral("puts(\"ERROR: Cannot add") + fieldType + QStringLiteral(" to ") + fieldName
+ QStringLiteral(", minimum number of items reached.\")") + endLine + QStringLiteral("end") + endLine;
}
break;
}
case CodeAccessorMethod::GET:
// text = QStringLiteral("return ") + fieldName;
break;
case CodeAccessorMethod::LIST:
text = QStringLiteral("return ") + fieldName;
break;
case CodeAccessorMethod::REMOVE:
{
int minOccurs = rubyfield->minimumListOccurances();
QString fieldType = rubyfield->getTypeName();
QString indent = getIndentation();
if (minOccurs > 0)
text += QStringLiteral("if ") + fieldName + QStringLiteral(".size() >= ") + QString::number(minOccurs) + endLine + indent;
text += fieldName + QStringLiteral(".delete(value)");
if (minOccurs > 0)
{
text += endLine + QStringLiteral("else") + endLine;
text += indent + QStringLiteral("puts(\"ERROR: Cant remove") + fieldType + QStringLiteral(" from ") + fieldName + QStringLiteral(", minimum number of items reached.\")") + endLine + QStringLiteral("end") + endLine;
}
break;
}
case CodeAccessorMethod::SET:
// text = fieldName + QStringLiteral(" = value");
break;
default:
// do nothing
break;
}
setText(text);
}
void RubyCodeAccessorMethod::updateMethodDeclaration()
{
RubyCodeClassField * rubyfield = dynamic_cast<RubyCodeClassField*>(getParentClassField());
// Check for dynamic casting failure!
if (rubyfield == nullptr)
{
logError0("rubyfield: invalid dynamic cast");
return;
}
// gather defs
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
Uml::Visibility::Enum scopePolicy = p->getAttributeAccessorScope();
QString strVis = Uml::Visibility::toString(rubyfield->getVisibility());
QString fieldName = RubyCodeGenerator::cppToRubyName(rubyfield->getFieldName());
QString fieldType = RubyCodeGenerator::cppToRubyType(rubyfield->getTypeName());
QString objectType = rubyfield->getListObjectType();
if (objectType.isEmpty())
objectType = fieldName;
QString endLine = p->getNewLineEndingChars();
QString description = getParentObject()->doc();
description.remove(QRegularExpression(QStringLiteral("m_[npb](?=[A-Z])")));
description.remove(QStringLiteral("m_"));
description.replace(QRegularExpression(QStringLiteral("[\\n\\r]+[\\t ]*")), endLine);
// set scope of this accessor appropriately..if its an attribute,
// we need to be more sophisticated
if (rubyfield->parentIsAttribute())
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
strVis = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing..already have taken parent value
break;
}
// some variables we will need to populate
QString headerText;
QString methodReturnType;
QString methodName;
QString methodParams;
switch(getType()) {
case CodeAccessorMethod::ADD:
methodName = QStringLiteral("add") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QString();
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Add an object of type ") + objectType + QStringLiteral(" to the Array ") + fieldName + endLine + description + endLine + QStringLiteral("@return nil");
setStartMethodText(QStringLiteral("def ")+ methodName + QLatin1Char('(') + methodParams + QLatin1Char(')'));
setEndMethodText(QStringLiteral("end"));
break;
case CodeAccessorMethod::GET:
headerText = QStringLiteral("Get the value of ") + fieldName + endLine + description;
setStartMethodText(QString(QStringLiteral("attr_reader :")) + fieldName);
setEndMethodText(QString());
break;
case CodeAccessorMethod::LIST:
methodName = QStringLiteral("get") + Codegen_Utils::capitalizeFirstLetter(fieldType) + QStringLiteral("List");
methodReturnType = QString();
headerText = QStringLiteral("Get the list of ") + fieldName + endLine + description + endLine + QStringLiteral("_returns_ List of ") + fieldName;
setStartMethodText(QStringLiteral("def ")+ methodName + QLatin1Char('(') + methodParams + QLatin1Char(')'));
setEndMethodText(QStringLiteral("end"));
break;
case CodeAccessorMethod::REMOVE:
methodName = QStringLiteral("remove") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QString();
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Remove an object of type ") + objectType + QStringLiteral(" from the List ") + fieldName + endLine + description;
setStartMethodText(QStringLiteral("def ") + methodName + QLatin1Char('(') + methodParams + QLatin1Char(')'));
setEndMethodText(QStringLiteral("end"));
break;
case CodeAccessorMethod::SET:
headerText = QStringLiteral("Set the value of ") + fieldName + endLine + description;
setStartMethodText(QString(QStringLiteral("attr_writer :")) + fieldName);
setEndMethodText(QString());
break;
default:
// do nothing..no idea what this is
logWarn1("Warning: cannot generate RubyCodeAccessorMethod for type: %1", getType());
break;
}
// set header once.
if (getComment()->getText().isEmpty())
getComment()->setText(headerText);
}
/**
* Must be called before this object is usable.
*/
void RubyCodeAccessorMethod::update()
{
updateMethodDeclaration();
updateContent();
}
| 8,916
|
C++
|
.cpp
| 214
| 35.383178
| 230
| 0.679539
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,551
|
rubycodegenerationpolicypage.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodegenerationpolicypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodegenerationpolicypage.h"
// app includes
#include "codegenerationpolicy.h"
#include "uml.h"
// kde includes
#include <KLocalizedString>
RubyCodeGenerationPolicyPage::RubyCodeGenerationPolicyPage(QWidget *parent, const char *name, RubyCodeGenerationPolicy * policy)
: CodeGenerationPolicyPage(parent, name, policy)
{
CodeGenerationPolicy *common = UMLApp::app()->commonPolicy();
form.setupUi(this);
form.m_SelectCommentStyle->setCurrentIndex((int)(common->getCommentStyle()));
form.m_generateConstructors->setChecked(common->getAutoGenerateConstructors());
form.m_generateAttribAccessors->setChecked(policy->getAutoGenerateAttribAccessors());
form.m_generateAssocAccessors->setChecked(policy->getAutoGenerateAssocAccessors());
form.m_accessorScopeCB->setCurrentIndex(common->getAttributeAccessorScope());
form.m_assocFieldScopeCB->setCurrentIndex(common->getAssociationFieldScope());
}
RubyCodeGenerationPolicyPage::~RubyCodeGenerationPolicyPage()
{
}
void RubyCodeGenerationPolicyPage::apply()
{
CodeGenerationPolicy *common = UMLApp::app()->commonPolicy();
// now do our ruby-specific configs
RubyCodeGenerationPolicy * parent = (RubyCodeGenerationPolicy*) m_parentPolicy;
// block signals so we don't cause too many update content calls to code documents
parent->blockSignals(true);
common->setCommentStyle((CodeGenerationPolicy::CommentStyle) form.m_SelectCommentStyle->currentIndex());
common->setAttributeAccessorScope(Uml::Visibility::fromInt(form.m_accessorScopeCB->currentIndex()));
common->setAssociationFieldScope(Uml::Visibility::fromInt(form.m_assocFieldScopeCB->currentIndex()));
common->setAutoGenerateConstructors(form.m_generateConstructors->isChecked());
parent->setAutoGenerateAttribAccessors(form.m_generateAttribAccessors->isChecked());
parent->setAutoGenerateAssocAccessors(form.m_generateAssocAccessors->isChecked());
parent->blockSignals(false);
// now send out modified code content signal
common->emitModifiedCodeContentSig();
}
| 2,315
|
C++
|
.cpp
| 44
| 49
| 128
| 0.797166
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,552
|
rubyclassifiercodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubyclassifiercodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubyclassifiercodedocument.h"
// local includes
#include "codegen_utils.h"
#include "classifier.h"
#include "debug_utils.h"
#include "rubycodegenerator.h"
#include "rubycodecomment.h"
#include "rubyclassdeclarationblock.h"
#include "rubycodeclassfielddeclarationblock.h"
#include "rubycodeoperation.h"
#include "uml.h"
DEBUG_REGISTER_DISABLED(RubyClassifierCodeDocument)
// qt includes
#include <QRegularExpression>
/**
* Constructor.
*/
RubyClassifierCodeDocument::RubyClassifierCodeDocument(UMLClassifier * classifier)
: ClassifierCodeDocument(classifier)
{
init();
}
/**
* Empty Destructor.
*/
RubyClassifierCodeDocument::~RubyClassifierCodeDocument()
{
}
/**
* Make it easier on ourselves.
*/
RubyCodeGenerationPolicy * RubyClassifierCodeDocument::getRubyPolicy() const
{
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
RubyCodeGenerationPolicy * policy = dynamic_cast<RubyCodeGenerationPolicy*>(pe);
return policy;
}
//**
// * Get the dialog widget which allows user interaction with the object parameters.
// * @return CodeDocumentDialog
// */
/*
CodeDocumentDialog RubyClassifierCodeDocument::getDialog()
{
}
*/
/**
* Overwritten by Ruby language implementation to get lowercase path.
*/
QString RubyClassifierCodeDocument::getPath() const
{
QString path = getPackage();
// Replace all white spaces with blanks
path = path.simplified();
// Replace all blanks with underscore
path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
path.replace(QRegularExpression(QStringLiteral("\\.")),QStringLiteral("/"));
path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/"));
path = path.toLower();
return path;
}
QString RubyClassifierCodeDocument::getRubyClassName(const QString &name) const
{
CodeGenerator *g = UMLApp::app()->generator();
return Codegen_Utils::capitalizeFirstLetter(g->cleanName(name));
}
// Initialize this ruby classifier code document
void RubyClassifierCodeDocument::init()
{
setFileExtension(QStringLiteral(".rb"));
//initCodeClassFields(); // this is dubious because it calls down to
// CodeGenFactory::newCodeClassField(this)
// but "this" is still in construction at that time.
classDeclCodeBlock = nullptr;
publicBlock = nullptr;
protectedBlock = nullptr;
privateBlock = nullptr;
pubConstructorBlock = nullptr;
protConstructorBlock = nullptr;
privConstructorBlock = nullptr;
pubOperationsBlock = nullptr;
privOperationsBlock = nullptr;
protOperationsBlock = nullptr;
// this will call updateContent() as well as other things that sync our document.
synchronize();
}
/**
* Add a code operation to this ruby classifier code document.
* In the vanilla version, we just tack all operations on the end
* of the document.
* @param op the code operation
* @return bool which is true IF the code operation was added successfully
*/
bool RubyClassifierCodeDocument::addCodeOperation(CodeOperation * op)
{
Uml::Visibility::Enum scope = op->getParentOperation()->visibility();
if (!op->getParentOperation()->isConstructorOperation())
{
switch (scope) {
default:
case Uml::Visibility::Public:
return pubOperationsBlock->addTextBlock(op);
break;
case Uml::Visibility::Protected:
return protOperationsBlock->addTextBlock(op);
break;
case Uml::Visibility::Private:
return privOperationsBlock->addTextBlock(op);
break;
}
} else {
switch (scope) {
default:
case Uml::Visibility::Public:
return pubConstructorBlock->addTextBlock(op);
break;
case Uml::Visibility::Protected:
return protConstructorBlock->addTextBlock(op);
break;
case Uml::Visibility::Private:
return privConstructorBlock->addTextBlock(op);
break;
}
}
}
/**
* Need to overwrite this for ruby since we need to pick up the
* ruby class declaration block.
* Sigh. NOT optimal. The only reason that we need to have this
* is so we can create the RubyClassDeclarationBlock.
* would be better if we could create a handler interface that each
* codeblock used so all we have to do here is add the handler
* for "rubyclassdeclarationblock".
*/
void RubyClassifierCodeDocument::loadChildTextBlocksFromNode(QDomElement & root)
{
QDomNode tnode = root.firstChild();
QDomElement telement = tnode.toElement();
bool loadCheckForChildrenOK = false;
while (!telement.isNull()) {
QString nodeName = telement.tagName();
if (nodeName == QStringLiteral("textblocks")) {
QDomNode node = telement.firstChild();
QDomElement element = node.toElement();
// if there is nothing to begin with, then we don't worry about it
loadCheckForChildrenOK = element.isNull() ? true : false;
while (!element.isNull()) {
QString name = element.tagName();
if (name == QStringLiteral("codecomment")) {
CodeComment * block = new RubyCodeComment(this);
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode : unable to add codeComment");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeaccessormethod") ||
name == QStringLiteral("ccfdeclarationcodeblock")) {
QString acctag = element.attribute(QStringLiteral("tag"));
// search for our method in the
TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
if (!tb || !addTextBlock(tb)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode : unable to add codeclassfield child method");
// DON'T delete
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblock")) {
CodeBlock * block = newCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode : unable to add codeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblockwithcomments")) {
CodeBlockWithComments * block = newCodeBlockWithComments();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode : unable to add codeBlockwithcomments");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("header")) {
// do nothing.. this is treated elsewhere
} else if (name == QStringLiteral("hierarchicalcodeblock")) {
HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: Unable to add hierarchicalcodeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeoperation")) {
// find the code operation by id
QString id = element.attribute(QStringLiteral("parent_id"), QStringLiteral("-1"));
UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
UMLOperation * op = obj->asUMLOperation();
if (op) {
CodeOperation * block = new RubyCodeOperation(this, op);
block->loadFromXMI(element);
if (addTextBlock(block)) {
loadCheckForChildrenOK= true;
} else {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: Unable to add codeoperation");
block->deleteLater();
}
} else {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: Unable to find operation create codeoperation");
}
} else if (name == QStringLiteral("rubyclassdeclarationblock")) {
RubyClassDeclarationBlock * block = getClassDecl();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: Unable to add ruby code declaration block");
// DON'T delete.
// block->deleteLater();
} else {
loadCheckForChildrenOK= true;
}
} else {
logDebug1("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: Got strange tag in "
"text block stack: %1, ignoring", name);
}
node = element.nextSibling();
element = node.toElement();
}
break;
}
tnode = telement.nextSibling();
telement = tnode.toElement();
}
if (!loadCheckForChildrenOK)
{
logWarn1("RubyClassifierCodeDocument::loadChildTextBlocksFromNode: unable to initialize any "
"child blocks in doc: %1", getFileName());
}
}
RubyClassDeclarationBlock * RubyClassifierCodeDocument::getClassDecl()
{
if (!classDeclCodeBlock)
{
classDeclCodeBlock = new RubyClassDeclarationBlock (this);
classDeclCodeBlock->updateContent();
classDeclCodeBlock->setTag(QStringLiteral("ClassDeclBlock"));
}
return classDeclCodeBlock;
}
/**
* Reset/clear our inventory of textblocks in this document.
*/
void RubyClassifierCodeDocument::resetTextBlocks()
{
// all special pointers to text blocks need to be zero'd out
operationsBlock = nullptr;
constructorBlock = nullptr;
classDeclCodeBlock = nullptr;
// now do traditional release of text blocks.
ClassifierCodeDocument::resetTextBlocks();
}
// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we reasonably will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void RubyClassifierCodeDocument::updateContent()
{
// Gather info on the various fields and parent objects of this class...
UMLClassifier * c = getParentClassifier();
RubyCodeGenerator * gen = dynamic_cast<RubyCodeGenerator*>(UMLApp::app()->generator());
// first, set the global flag on whether or not to show classfield info
// This depends on whether or not we have attribute/association classes
const CodeClassFieldList * cfList = getCodeClassFieldList();
CodeClassFieldList::const_iterator it = cfList->begin();
CodeClassFieldList::const_iterator end = cfList->end();
for (; it != end; ++it) {
CodeClassField * field = *it;
if (field->parentIsAttribute())
field->setWriteOutMethods(gen->getAutoGenerateAttribAccessors());
else
field->setWriteOutMethods(gen->getAutoGenerateAssocAccessors());
}
// attribute-based ClassFields
// we do it this way to have the static fields sorted out from regular ones
CodeClassFieldList staticPublicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Public);
CodeClassFieldList publicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Public);
CodeClassFieldList staticProtectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Protected);
CodeClassFieldList protectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Protected);
CodeClassFieldList staticPrivateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Private);
CodeClassFieldList privateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Private);
// association-based ClassFields
// don't care if they are static or not..all are lumped together
CodeClassFieldList publicPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Public);
CodeClassFieldList publicAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Public);
CodeClassFieldList publicCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Public);
CodeClassFieldList protPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Protected);
CodeClassFieldList protAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Protected);
CodeClassFieldList protCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Protected);
CodeClassFieldList privPlainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation, Uml::Visibility::Private);
CodeClassFieldList privAggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation, Uml::Visibility::Private);
CodeClassFieldList privCompositionClassFields = getSpecificClassFields (CodeClassField::Composition, Uml::Visibility::Private);
bool isInterface = parentIsInterface();
bool hasOperationMethods = false;
Q_ASSERT(c != nullptr);
if (c) {
UMLOperationList list = c->getOpList();
hasOperationMethods = ! list.isEmpty();
}
CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy();
QString endLine = pol->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time
//
// START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
//
// CLASS DECLARATION BLOCK
//
// get the declaration block. If it is not already present, add it too
RubyClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl();
addTextBlock(myClassDeclCodeBlock); // note: wont add if already present
// declare public, protected and private methods, attributes (fields).
// set the start text ONLY if this is the first time we created the objects.
bool createdPublicBlock = publicBlock == nullptr ? true : false;
publicBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("publicBlock"), QStringLiteral("Public Items"), 0);
if (createdPublicBlock)
publicBlock->setStartText(QStringLiteral("public"));
bool createdProtBlock = protectedBlock == nullptr ? true : false;
protectedBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("protectedBlock"), QStringLiteral("Protected Items"), 0);
if (createdProtBlock)
protectedBlock->setStartText(QStringLiteral("protected"));
bool createdPrivBlock = privateBlock == nullptr ? true : false;
privateBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("privateBlock"), QStringLiteral("Private Items"), 0);
if (createdPrivBlock)
privateBlock->setStartText(QStringLiteral("private"));
// NOW create document in sections..
// now we want to populate the body of our class
// our layout is the following general groupings of code blocks:
// start ruby classifier document
// header comment
// class declaration
// section:
// section:
// - methods section comment
// sub-section: constructor ops
// - constructor method section comment
// - constructor methods (0+ codeblocks)
// sub-section: accessors
// - accessor method section comment
// - static accessor methods (0+ codeblocks)
// - non-static accessor methods (0+ codeblocks)
// sub-section: non-constructor ops
// - operation method section comment
// - operations (0+ codeblocks)
// end class declaration
// end ruby classifier document
// Q: Why use the more complicated scheme of arranging code blocks within codeblocks?
// A: This will allow us later to preserve the format of our document so that if
// codeblocks are added, they may be easily added in the correct place, rather than at
// the end of the document, or by using a difficult algorithm to find the location of
// the last appropriate code block sibling (which may not exist.. for example user adds
// a constructor operation, but there currently are no constructor code blocks
// within the document).
//
// METHODS section
//
// get/create the method codeblock
// public methods
HierarchicalCodeBlock * pubMethodsBlock = publicBlock->getHierarchicalCodeBlock(QStringLiteral("pubMethodsBlock"), QString(), 1);
CodeComment * pubMethodsComment = pubMethodsBlock->getComment();
bool forceDoc = pol->getCodeVerboseDocumentComments();
// set conditions for showing this comment
if (!forceDoc && !hasClassFields() && !hasOperationMethods)
pubMethodsComment->setWriteOutText(false);
else
pubMethodsComment->setWriteOutText(true);
// protected methods
HierarchicalCodeBlock * protMethodsBlock = protectedBlock->getHierarchicalCodeBlock(QStringLiteral("protMethodsBlock"), QString(), 1);
CodeComment * protMethodsComment = protMethodsBlock->getComment();
// set conditions for showing this comment
if (!forceDoc && !hasClassFields() && !hasOperationMethods)
protMethodsComment->setWriteOutText(false);
else
protMethodsComment->setWriteOutText(true);
// private methods
HierarchicalCodeBlock * privMethodsBlock = privateBlock->getHierarchicalCodeBlock(QStringLiteral("privMethodsBlock"), QString(), 1);
CodeComment * privMethodsComment = privMethodsBlock->getComment();
// set conditions for showing this comment
if (!forceDoc && !hasClassFields() && !hasOperationMethods)
privMethodsComment->setWriteOutText(false);
else
privMethodsComment->setWriteOutText(true);
// METHODS sub-section : constructor methods
//
// public
pubConstructorBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * pubConstComment = pubConstructorBlock->getComment();
if (!forceDoc && (isInterface || !pol->getAutoGenerateConstructors()))
pubConstComment->setWriteOutText(false);
else
pubConstComment->setWriteOutText(true);
// protected
protConstructorBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * protConstComment = protConstructorBlock->getComment();
if (!forceDoc && (isInterface || !pol->getAutoGenerateConstructors()))
protConstComment->setWriteOutText(false);
else
protConstComment->setWriteOutText(true);
// private
privConstructorBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructionMethods"), QStringLiteral("Constructors"), 1);
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * privConstComment = privConstructorBlock->getComment();
if (!forceDoc && (isInterface || !pol->getAutoGenerateConstructors()))
privConstComment->setWriteOutText(false);
else
privConstComment->setWriteOutText(true);
// get/create the accessor codeblock
// public
HierarchicalCodeBlock * pubAccessorBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * pubAccessComment = pubAccessorBlock->getComment();
if (!forceDoc && !hasClassFields())
pubAccessComment->setWriteOutText(false);
else
pubAccessComment->setWriteOutText(true);
// protected
HierarchicalCodeBlock * protAccessorBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * protAccessComment = protAccessorBlock->getComment();
if (!forceDoc && !hasClassFields())
protAccessComment->setWriteOutText(false);
else
protAccessComment->setWriteOutText(true);
// private
HierarchicalCodeBlock * privAccessorBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * privAccessComment = privAccessorBlock->getComment();
if (!forceDoc && !hasClassFields())
privAccessComment->setWriteOutText(false);
else
privAccessComment->setWriteOutText(true);
// now, 2 sub-sub sections in accessor block
// add/update accessor methods for attributes
HierarchicalCodeBlock * pubStaticAccessors = pubAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("pubStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * pubRegularAccessors = pubAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("pubRegularAccessorMethods"), QString(), 1);
pubStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
pubRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
HierarchicalCodeBlock * protStaticAccessors = protAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("protStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * protRegularAccessors = protAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("protRegularAccessorMethods"), QString(), 1);
protStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
protRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
HierarchicalCodeBlock * privStaticAccessors = privAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("privStaticAccessorMethods"), QString(), 1);
HierarchicalCodeBlock * privRegularAccessors = privAccessorBlock->getHierarchicalCodeBlock(QStringLiteral("privRegularAccessorMethods"), QString(), 1);
privStaticAccessors->getComment()->setWriteOutText(false); // never write block comment
privRegularAccessors->getComment()->setWriteOutText(false); // never write block comment
// now add in accessors as appropriate
// public stuff
pubStaticAccessors->addCodeClassFieldMethods(staticPublicAttribClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicAttribClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicPlainAssocClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicAggregationClassFields);
pubRegularAccessors->addCodeClassFieldMethods(publicCompositionClassFields);
// protected stuff
protStaticAccessors->addCodeClassFieldMethods(staticProtectedAttribClassFields);
protRegularAccessors->addCodeClassFieldMethods(protectedAttribClassFields);
protRegularAccessors->addCodeClassFieldMethods(protPlainAssocClassFields);
protRegularAccessors->addCodeClassFieldMethods(protAggregationClassFields);
protRegularAccessors->addCodeClassFieldMethods(protCompositionClassFields);
// private stuff
privStaticAccessors->addCodeClassFieldMethods(staticPrivateAttribClassFields);
privRegularAccessors->addCodeClassFieldMethods(privateAttribClassFields);
privRegularAccessors->addCodeClassFieldMethods(privPlainAssocClassFields);
privRegularAccessors->addCodeClassFieldMethods(privAggregationClassFields);
privRegularAccessors->addCodeClassFieldMethods(privCompositionClassFields);
// METHODS subsection : Operation methods (which aren't constructors)
//
// setup/get/create the operations codeblock
// public
pubOperationsBlock = pubMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * pubOcomment = pubOperationsBlock->getComment();
if (!forceDoc && !hasOperationMethods)
pubOcomment->setWriteOutText(false);
else
pubOcomment->setWriteOutText(true);
//protected
protOperationsBlock = protMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * protOcomment = protOperationsBlock->getComment();
if (!forceDoc && !hasOperationMethods)
protOcomment->setWriteOutText(false);
else
protOcomment->setWriteOutText(true);
//private
privOperationsBlock = privMethodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * privOcomment = privOperationsBlock->getComment();
if (!forceDoc && !hasOperationMethods)
privOcomment->setWriteOutText(false);
else
privOcomment->setWriteOutText(true);
}
| 27,070
|
C++
|
.cpp
| 516
| 44.397287
| 165
| 0.706762
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,553
|
rubyclassdeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubyclassdeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "rubyclassdeclarationblock.h"
#include "rubycodedocumentation.h"
#include "rubycodegenerator.h"
#include "uml.h"
RubyClassDeclarationBlock::RubyClassDeclarationBlock
(RubyClassifierCodeDocument * parentDoc, const QString &startText, const QString &endText, const QString &comment)
: OwnedHierarchicalCodeBlock(parentDoc->getParentClassifier(), parentDoc, startText, endText, comment)
{
init(parentDoc, comment);
}
RubyClassDeclarationBlock::~RubyClassDeclarationBlock ()
{
}
/**
* Save the XMI representation of this object
*/
void RubyClassDeclarationBlock::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("rubyclassdeclarationblock"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
/**
* load params from the appropriate XMI element node.
*/
void RubyClassDeclarationBlock::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
/**
* update the start and end text for this ownedhierarchicalcodeblock.
*/
void RubyClassDeclarationBlock::updateContent ()
{
RubyClassifierCodeDocument *parentDoc = dynamic_cast<RubyClassifierCodeDocument*>(getParentDocument());
Q_ASSERT(parentDoc);
UMLClassifier *c = parentDoc->getParentClassifier();
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
QString endLine = p->getNewLineEndingChars();
bool isInterface = parentDoc->parentIsInterface(); // a little shortcut
QString RubyClassName = parentDoc->getRubyClassName(c->name());
bool forceDoc = p->getCodeVerboseDocumentComments();
// COMMENT
QString comment = c->doc();
comment.remove(QStringLiteral("@ref "));
comment.replace(QStringLiteral("@see"), QStringLiteral("_See_"));
comment.replace(QStringLiteral("@short"), QStringLiteral("_Summary_"));
comment.replace(QStringLiteral("@author"), QStringLiteral("_Author_"));
if (isInterface)
getComment()->setText(QStringLiteral("Module ") + RubyClassName + endLine + comment);
else
getComment()->setText(QStringLiteral("Class ") + RubyClassName + endLine + comment);
if (forceDoc || !c->doc().isEmpty())
getComment()->setWriteOutText(true);
else
getComment()->setWriteOutText(false);
// Now set START/ENDING Text
QString startText;
if (parentDoc->parentIsInterface()) {
startText.append(QStringLiteral("module "));
} else {
startText.append(QStringLiteral("class "));
}
UMLClassifierList superclasses = c->findSuperClassConcepts(UMLClassifier::CLASS);
UMLClassifierList superinterfaces = c->findSuperClassConcepts(UMLClassifier::INTERFACE);
// write out inheritance
startText.append(RubyClassName);
int i = 0;
for(UMLClassifier* classifier : superclasses) {
if (i == 0) {
startText.append(QString(QStringLiteral(" < ")) + RubyCodeGenerator::cppToRubyType(classifier->name()) + endLine);
} else {
// After the first superclass name in the list, assume the classes
// are ruby modules that can be mixed in,
startText.append(QStringLiteral("include ") + RubyCodeGenerator::cppToRubyType(classifier->name()) + endLine);
}
i++;
}
// Write out the interfaces we 'implement'. Are these modules to be mixed in, in Ruby?
for(UMLClassifier* classifier : superinterfaces) {
startText.append(QString(QStringLiteral("include ")) + RubyCodeGenerator::cppToRubyType(classifier->name()) + endLine);
}
// Set the header and end text for the hier.codeblock
setStartText(startText);
}
void RubyClassDeclarationBlock::init (RubyClassifierCodeDocument *parentDoc, const QString &comment)
{
setComment(new RubyCodeDocumentation(parentDoc));
getComment()->setText(comment);
setEndText(QStringLiteral("end"));
}
| 4,066
|
C++
|
.cpp
| 96
| 37.635417
| 127
| 0.731763
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,554
|
rubycodedocumentation.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodedocumentation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodedocumentation.h"
// local includes
#include "rubyclassifiercodedocument.h"
#include "rubycodegenerationpolicy.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
RubyCodeDocumentation::RubyCodeDocumentation(RubyClassifierCodeDocument * doc, const QString & text)
: CodeComment((CodeDocument*) doc, text)
{
}
RubyCodeDocumentation::~RubyCodeDocumentation()
{
}
void RubyCodeDocumentation::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("rubycodedocumentation"));
setAttributesOnNode(writer); // as we added no additional fields to this class we may
// just use parent TextBlock method
writer.writeEndElement();
}
QString RubyCodeDocumentation::toString() const
{
QString output;
// simple output method
if (getWriteOutText())
{
bool useHashOutput = true;
// need to figure out output type from ruby policy
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if (p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
useHashOutput = false;
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
if (useHashOutput)
{
if (!body.isEmpty())
output.append(formatMultiLineText (body, indent + QStringLiteral("# "), endLine));
} else {
output.append(QStringLiteral("=begin rdoc") + endLine);
output.append(formatMultiLineText (body, indent + QLatin1Char(' '), endLine));
output.append(QStringLiteral("=end") + endLine);
}
}
return output;
}
QString RubyCodeDocumentation::getNewEditorLine(int amount)
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if (p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return getIndentationString(amount) + QLatin1Char(' ');
else
return getIndentationString(amount) + QStringLiteral("# ");
}
int RubyCodeDocumentation::firstEditableLine()
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if (p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return 1;
return 0;
}
int RubyCodeDocumentation::lastEditableLine()
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if (p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
return -1; // very last line is NOT editable
}
return 0;
}
QString RubyCodeDocumentation::unformatText(const QString & text, const QString & indent)
{
QString mytext = TextBlock::unformatText(text, indent);
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
// remove leading or trailing comment stuff
mytext.remove(QRegularExpression(QLatin1Char('^') + indent));
if (p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
mytext.remove(QRegularExpression(QStringLiteral("^=begin\\s*(rdoc)?\\s*\n?")));
mytext.remove(QRegularExpression(QStringLiteral("^=end\\s*\n?$")));
} else
mytext.remove(QRegularExpression(QStringLiteral("^#\\s*")));
return mytext;
}
| 3,381
|
C++
|
.cpp
| 91
| 32.10989
| 100
| 0.70608
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,555
|
rubycodecomment.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodecomment.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "rubycodecomment.h"
#include <QRegularExpression>
RubyCodeComment::RubyCodeComment(CodeDocument * doc, const QString & text)
: CodeComment(doc, text)
{
}
RubyCodeComment::~RubyCodeComment()
{
}
QString RubyCodeComment::getNewEditorLine(int amount)
{
QString line = getIndentationString(amount) + QStringLiteral("# ");
return line;
}
QString RubyCodeComment::unformatText(const QString & text, const QString & indent)
{
// remove leading or trailing comment stuff
QString mytext = TextBlock::unformatText(text, indent);
// now leading hash
mytext.remove(QRegularExpression(QStringLiteral("^#\\s*")));
return mytext;
}
QString RubyCodeComment::toString() const
{
QString output;
// simple output method
if (getWriteOutText()) {
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
output.append(formatMultiLineText(getText(), indent + QStringLiteral("# "), endLine + endLine));
}
return output;
}
| 1,253
|
C++
|
.cpp
| 38
| 29.263158
| 104
| 0.738372
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,556
|
rubycodegenerationpolicy.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodegenerationpolicy.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodegenerationpolicy.h"
// qt/kde includes
#include <kconfig.h>
// app includes
#include "optionstate.h"
#include "rubycodegenerationpolicypage.h"
#include "rubycodegenerator.h"
#include "uml.h"
#include "umbrellosettings.h"
/**
* Constructor.
*/
RubyCodeGenerationPolicy::RubyCodeGenerationPolicy()
{
m_commonPolicy = UMLApp::app()->commonPolicy();
init();
}
/**
* Destructor.
*/
RubyCodeGenerationPolicy::~RubyCodeGenerationPolicy()
{
}
/**
* Set the value of m_autoGenerateAttribAccessors.
* @param var the new value
*/
void RubyCodeGenerationPolicy::setAutoGenerateAttribAccessors(bool var)
{
Settings::optionState().codeGenerationState.rubyCodeGenerationState.autoGenerateAttributeAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Set the value of m_autoGenerateAssocAccessors.
* @param var the new value
*/
void RubyCodeGenerationPolicy::setAutoGenerateAssocAccessors(bool var)
{
Settings::optionState().codeGenerationState.rubyCodeGenerationState.autoGenerateAssocAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Get the value of m_autoGenerateAttribAccessors
* @return the value of m_autoGenerateAttribAccessors
*/
bool RubyCodeGenerationPolicy::getAutoGenerateAttribAccessors()
{
return Settings::optionState().codeGenerationState.rubyCodeGenerationState.autoGenerateAttributeAccessors;
}
/**
* Get the value of m_autoGenerateAssocAccessors.
* @return the value of m_autoGenerateAssocAccessors
*/
bool RubyCodeGenerationPolicy::getAutoGenerateAssocAccessors()
{
return Settings::optionState().codeGenerationState.rubyCodeGenerationState.autoGenerateAssocAccessors;
}
/**
* Set the defaults for this code generator from the passed generator.
* @param defaults the defaults to set
* @param emitUpdateSignal flag whether to emit the update signal
*/
void RubyCodeGenerationPolicy::setDefaults (CodeGenPolicyExt * defaults, bool emitUpdateSignal)
{
RubyCodeGenerationPolicy * rclone;
if (!defaults)
return;
// NOW block signals for ruby param setting
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
// now do ruby-specific stuff IF our clone is also a RubyCodeGenerationPolicy object
if((rclone = dynamic_cast<RubyCodeGenerationPolicy*>(defaults)))
{
setAutoGenerateAttribAccessors(rclone->getAutoGenerateAttribAccessors());
setAutoGenerateAssocAccessors(rclone->getAutoGenerateAssocAccessors());
}
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Set the defaults from a config file for this code generator from the passed KConfig pointer.
* @param emitUpdateSignal flag whether to emit the update signal
*/
void RubyCodeGenerationPolicy::setDefaults(bool emitUpdateSignal)
{
// call the superclass to init default stuff
m_commonPolicy->setDefaults(false);
// NOW block signals (because call to super-class method will leave value at "true")
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
// now do ruby specific stuff
setAutoGenerateAttribAccessors(UmbrelloSettings::autoGenerateAttributeAccessorsRuby());
setAutoGenerateAssocAccessors(UmbrelloSettings::autoGenerateAssocAccessorsRuby());
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Create a new dialog interface for this object.
* @param parent the parent widget
* @param name the name of the page
* @return dialog object
*/
CodeGenerationPolicyPage * RubyCodeGenerationPolicy::createPage (QWidget *parent, const char *name)
{
return new RubyCodeGenerationPolicyPage (parent, name, this);
}
/**
* Initialisation.
*/
void RubyCodeGenerationPolicy::init()
{
blockSignals(true);
Settings::OptionState optionState = Settings::optionState();
setAutoGenerateAttribAccessors(optionState.codeGenerationState.rubyCodeGenerationState.autoGenerateAttributeAccessors);
setAutoGenerateAssocAccessors(optionState.codeGenerationState.rubyCodeGenerationState.autoGenerateAssocAccessors);
blockSignals(false);
}
| 4,753
|
C++
|
.cpp
| 127
| 34.425197
| 123
| 0.785093
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,557
|
rubycodeoperation.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodeoperation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodeoperation.h"
// local includes
#include "debug_utils.h"
#include "rubyclassifiercodedocument.h"
#include "rubycodedocumentation.h"
#include "rubycodegenerator.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
RubyCodeOperation::RubyCodeOperation (RubyClassifierCodeDocument * doc, UMLOperation *parent, const QString & body, const QString & comment)
: CodeOperation (doc, parent, body, comment)
{
// lets not go with the default comment and instead use
// full-blown ruby documentation object instead
setComment(new RubyCodeDocumentation(doc));
// these things never change..
setOverallIndentationLevel(1);
}
RubyCodeOperation::~RubyCodeOperation()
{
}
// we basically want to update the doc and start text of this method
void RubyCodeOperation::updateMethodDeclaration()
{
CodeDocument * doc = getParentDocument();
RubyClassifierCodeDocument * rubydoc = dynamic_cast<RubyClassifierCodeDocument*>(doc);
Q_ASSERT(rubydoc);
UMLClassifier *c = rubydoc->getParentClassifier();
UMLOperation * o = getParentOperation();
bool isInterface = rubydoc->getParentClassifier()->isInterface();
QString endLine = getNewLineEndingChars();
// now, the starting text.
//:UNUSED: QString strVis = o->visibility().toString();
// no return type for constructors
QString fixedReturn = RubyCodeGenerator::cppToRubyType(o->getTypeName());
QString returnType = o->isConstructorOperation() ? QString() : (fixedReturn + QString(QStringLiteral(" ")));
QString methodName = o->name();
QString RubyClassName = rubydoc->getRubyClassName(c->name());
// Skip destructors, and operator methods which
// can't be defined in ruby
if (methodName.startsWith(QLatin1Char('~'))
|| QRegularExpression(QStringLiteral("operator\\s*(=|--|\\+\\+|!=)$")).match(methodName).hasMatch())
{
getComment()->setText(QString());
return;
}
if (RubyClassName == methodName) {
methodName = QStringLiteral("initialize");
}
methodName.remove(QRegularExpression(QStringLiteral("operator\\s*")));
methodName = methodName.mid(0, 1).toLower() + methodName.mid(1);
QString paramStr;
QStringList commentedParams;
// assemble parameters
UMLAttributeList list = getParentOperation()->getParmList();
int nrofParam = list.count();
int paramNum = 0;
for (UMLAttribute* parm : list) {
QString paramName = RubyCodeGenerator::cppToRubyName(parm->name());
paramStr += paramName;
if (! parm->getInitialValue().isEmpty()) {
paramStr += QString(QStringLiteral(" = ")) + RubyCodeGenerator::cppToRubyType(parm->getInitialValue());
}
paramNum++;
if (paramNum != nrofParam)
paramStr += QStringLiteral(", ");
}
QString startText;
if (isInterface) {
// Assume 'isInterface' means a module in Ruby, so
// generate module methods
startText = QStringLiteral("def ") + RubyClassName + QLatin1Char('.') + methodName + QLatin1Char('(') + paramStr + QLatin1Char(')');
} else {
startText = QStringLiteral("def ")+ methodName + QLatin1Char('(') + paramStr + QLatin1Char(')');
}
// startText += ""; ???
setEndMethodText(QStringLiteral("end"));
setStartMethodText(startText);
// Lastly, for text content generation, we fix the comment on the
// operation, IF the codeop is autogenerated & currently empty
QString comment = o->doc();
if (comment.isEmpty()) {
if (contentType() == CodeBlock::AutoGenerated) {
UMLAttributeList parameters = o->getParmList();
for(UMLAttribute* currentAtt : parameters) {
comment += endLine + QStringLiteral("* _") + currentAtt->name() + QStringLiteral("_ ");
comment += (QLatin1Char(' ') + currentAtt->doc().replace(QRegularExpression(QStringLiteral("[\\n\\r]+[\\t ]*")), endLine + QStringLiteral(" ")));
}
// add a returns statement too
if (!returnType.isEmpty() && !QRegularExpression(QStringLiteral("^void\\s*$")).match(returnType).hasMatch())
comment += endLine + QStringLiteral("* _returns_ ") + returnType + QLatin1Char(' ');
getComment()->setText(comment);
}
} else {
comment.replace(QRegularExpression(QStringLiteral("[\\n\\r]+ *")), endLine);
comment.replace(QRegularExpression(QStringLiteral("[\\n\\r]+\\t*")), endLine);
comment.replace(QStringLiteral(" m_"), QStringLiteral(" "));
comment.replace(QRegularExpression(QStringLiteral("\\s[npb](?=[A-Z])")), QStringLiteral(" "));
QRegularExpression re_params(QStringLiteral("@param (\\w)(\\w*)"));
QRegularExpressionMatch re_mat = re_params.match(comment);
int pos = comment.indexOf(re_params);
while (pos != -1) {
comment.replace(re_mat.captured(0),
QString(QStringLiteral("@param _")) + re_mat.captured(1).toLower() + re_mat.captured(2) + QLatin1Char('_'));
commentedParams.append(re_mat.captured(1).toLower() + re_mat.captured(2));
pos += re_mat.capturedLength() + 3;
pos = comment.indexOf(re_params, pos);
}
UMLAttributeList parameters = o->getParmList();
for(UMLAttribute* currentAtt : parameters) {
// Only write an individual @param entry if one hasn't been found already
// in the main doc comment
if (commentedParams.contains(RubyCodeGenerator::cppToRubyName(currentAtt->name())) == 0) {
comment += (endLine + QStringLiteral("@param _") + RubyCodeGenerator::cppToRubyName(currentAtt->name()) + QLatin1Char('_'));
if (currentAtt->doc().isEmpty()) {
comment += (QLatin1Char(' ') + RubyCodeGenerator::cppToRubyType(currentAtt->getTypeName()));
} else {
comment += (QLatin1Char(' ') + currentAtt->doc().replace(QRegularExpression(QStringLiteral("[\\n\\r]+[\\t ]*")), endLine + QStringLiteral(" ")));
}
}
}
comment.remove(QStringLiteral("@ref "));
comment.replace(QStringLiteral("@param"), QStringLiteral("*"));
comment.replace(QStringLiteral("@return"), QStringLiteral("* _returns_"));
// All lines after the first one starting with '*' in the doc comment
// must be indented correctly. If they aren't a list
// item starting with '*', then indent the text with
// two spaces, ' ', to line up with the list item.
pos = comment.indexOf(endLine + QLatin1Char('*'));
if (pos != -1) {
pos += endLine.length() + 1;
pos = comment.indexOf(endLine, pos);
}
while (pos > 0) {
pos += endLine.length();
if (comment[pos] != QLatin1Char('*')) {
comment.insert(pos, QStringLiteral(" "));
pos += 2;
}
pos = comment.indexOf(endLine, pos);
}
QString typeStr = RubyCodeGenerator::cppToRubyType(o->getTypeName());
if (!typeStr.isEmpty()
&& !QRegularExpression(QStringLiteral("^void\\s*$")).match(typeStr).hasMatch()
&& comment.contains(QStringLiteral("_returns_")) == 0)
{
comment += endLine + QStringLiteral("* _returns_ ") + typeStr;
}
getComment()->setText(comment);
}
// In Java, for interfaces..we DON'T write out non-public
// method declarations. And for Ruby modules?
if (isInterface) {
UMLOperation * o = getParentOperation();
if (o->visibility() != Uml::Visibility::Public)
setWriteOutText(false);
}
}
int RubyCodeOperation::lastEditableLine()
{
ClassifierCodeDocument * doc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());
// Check for dynamic casting failure
if (doc == nullptr)
{
logError0("RubyCodeOperation::lastEditableLine doc: invalid dynamic cast");
return -1;
}
if (doc->parentIsInterface())
return -1; // very last line is NOT editable as its a one-line declaration w/ no body in
// an interface.
return 0;
}
| 8,536
|
C++
|
.cpp
| 178
| 39.955056
| 166
| 0.636418
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,558
|
rubywriter.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubywriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "rubywriter.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "umldoc.h"
#include "umlattributelist.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
RubyWriter::RubyWriter()
{
}
RubyWriter::~RubyWriter()
{
}
/**
* Call this method to generate C++ code for a UMLClassifier.
* @param c the class you want to generate code for.
*/
void RubyWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("RubyWriter::writeClass: Cannot write class of NULL classifier");
return;
}
UMLClassifierList superclasses = c->getSuperClasses();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
//find an appropriate name for our file
fileName_ = findFileName(c, QStringLiteral(".rb"));
if (fileName_.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile fileh;
if (!openFile(fileh, fileName_)) {
Q_EMIT codeGenerated(c, false);
return;
}
QTextStream h(&fileh);
className_ = cleanName(c->name());
//////////////////////////////
//Start generating the code!!
/////////////////////////////
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".rb"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName_);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), fileh.fileName());
h << str << m_endl;
}
if (forceDoc() || !c->doc().isEmpty()) {
QString docStr = c->doc();
docStr.replace(QRegularExpression(QStringLiteral("\\n")), QStringLiteral("\n# "));
docStr.remove(QStringLiteral("@ref "));
docStr.replace(QStringLiteral("@see"), QStringLiteral("_See_"));
docStr.replace(QStringLiteral("@short"), QStringLiteral("_Summary_"));
docStr.replace(QStringLiteral("@author"), QStringLiteral("_Author_"));
h << "#" << m_endl;
h << "# " << docStr << m_endl;
h << "#" << m_endl << m_endl;
}
// write inheritances out
h << "class " << cppToRubyType(className_) << (superclasses.count() > 0 ? QStringLiteral(" < ") : QString());
int i = 0;
for(UMLClassifier *classifier: superclasses) {
if (i == 0) {
h << cppToRubyType(classifier->name()) << m_endl;
} else {
// Assume ruby modules that can be mixed in, after the first
// superclass name in the list
h << m_indentation << "include " << cppToRubyType(classifier->name()) << m_endl;
}
i++;
}
h << m_endl;
// write comment for sub-section IF needed
if (forceDoc() || c->hasAccessorMethods()) {
h << m_indentation << "#" << m_endl;
h << m_indentation << "# Accessor Methods" << m_endl;
h << m_indentation << "#" << m_endl << m_endl;
// Accessor methods for attributes
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Public), Uml::Visibility::Public, h);
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Protected), Uml::Visibility::Protected, h);
writeAttributeMethods(c->getAttributeList(Uml::Visibility::Private), Uml::Visibility::Private, h);
h << m_endl;
}
//operations
writeOperations(c, h);
//finish files
h << "end" << m_endl << m_endl;
//close files and notfiy we are done
fileh.close();
Q_EMIT codeGenerated(c, true);
}
/**
* Convert a C++ type such as 'int' or 'QWidget' to
* ruby types Integer and Qt::Widget.
* @param typeStr the C++ type to be converted
*/
QString RubyWriter::cppToRubyType(const QString &typeStr)
{
QString type = cleanName(typeStr);
type.remove(QStringLiteral("const "));
type.remove(QRegularExpression(QStringLiteral("[*&\\s]")));
type.replace(QRegularExpression(QStringLiteral("[<>]")), QStringLiteral("_"));
type.replace(QStringLiteral("QStringList"), QStringLiteral("Array"));
type.replace(QStringLiteral("QString"), QStringLiteral("String"));
type.replace(QStringLiteral("bool"), QStringLiteral("true|false"));
type.replace(QRegularExpression(QStringLiteral("^(uint|int|ushort|short|ulong|long)$")), QStringLiteral("Integer"));
type.replace(QRegularExpression(QStringLiteral("^(float|double)$")), QStringLiteral("Float"));
type.replace(QRegularExpression(QStringLiteral("^Q(?=[A-Z])")), QStringLiteral("Qt::"));
type.replace(QRegularExpression(QStringLiteral("^K(?!(DE|Parts|IO)")), QStringLiteral("KDE::"));
return type;
}
/**
* Convert C++ names such as 'm_foobar' or pFoobar to
* just 'foobar' for ruby.
* @param nameStr the C++ name to be converted
*/
QString RubyWriter::cppToRubyName(const QString &nameStr)
{
QString name = cleanName(nameStr);
name.remove(QRegularExpression(QStringLiteral("^m_")));
name.remove(QRegularExpression(QStringLiteral("^[pbn](?=[A-Z])")));
name = name.mid(0, 1).toLower() + name.mid(1);
return name;
}
/**
* Write all operations for a given class.
* @param c the classifier we are generating code for
* @param h output stream for the header file
*/
void RubyWriter::writeOperations(UMLClassifier *c, QTextStream &h)
{
//Lists to store operations sorted by scope
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
UMLOperationList opl(c->getOpList());
for(UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
QString classname(cleanName(c->name()));
//write operations to file
if (forceSections() || !oppub.isEmpty()) {
writeOperations(classname, oppub, Uml::Visibility::Public, h);
}
if (forceSections() || !opprot.isEmpty()) {
writeOperations(classname, opprot, Uml::Visibility::Protected, h);
}
if (forceSections() || !oppriv.isEmpty()) {
writeOperations(classname, oppriv, Uml::Visibility::Private, h);
}
}
/**
* Write a list of class operations.
* @param classname the name of the class
* @param opList the list of operations
* @param permitScope the visibility enum
* @param h output stream for the header file
*/
void RubyWriter::writeOperations(const QString &classname, const UMLOperationList &opList,
Uml::Visibility::Enum permitScope, QTextStream &h)
{
// UMLOperation *op;
// UMLAttribute *at;
switch (permitScope) {
case Uml::Visibility::Public:
h << m_indentation << "public" << m_endl << m_endl;
break;
case Uml::Visibility::Protected:
h << m_indentation << "protected" << m_endl << m_endl;
break;
case Uml::Visibility::Private:
h << m_indentation << "private" << m_endl << m_endl;
break;
default:
break;
}
for(const UMLOperation *op : opList) {
QString methodName = cleanName(op->name());
QStringList commentedParams;
// Skip destructors, and operator methods which
// can't be defined in ruby
if (methodName.startsWith(QLatin1Char('~'))
|| methodName == QStringLiteral("operator =")
|| methodName == QStringLiteral("operator --")
|| methodName == QStringLiteral("operator ++")
|| methodName == QStringLiteral("operator !="))
{
continue;
}
if (methodName == classname) {
methodName = QStringLiteral("initialize");
}
methodName.remove(QStringLiteral("operator "));
methodName = methodName.mid(0, 1).toLower() + methodName.mid(1);
UMLAttributeList atl = op->getParmList();
// Always write out the docs for ruby as the type of the
// arguments and return value of the methods is useful
bool writeDoc = true;
// for (UMLAttribute& at = atl.first(); at; at = atl.next())
// writeDoc |= !at->getDoc().isEmpty();
if (writeDoc) {
h << m_indentation << "#" << m_endl;
QString docStr = op->doc();
docStr.replace(QRegularExpression(QStringLiteral("[\\n\\r]+ *")), m_endl);
docStr.replace(QRegularExpression(QStringLiteral("[\\n\\r]+\\t*")), m_endl);
docStr.replace(QStringLiteral(" m_"), QStringLiteral(" "));
docStr.replace(QRegularExpression(QStringLiteral("\\s[npb](?=[A-Z])")), QStringLiteral(" "));
QRegularExpression re_params(QStringLiteral("@param (\\w)(\\w*)"));
QRegularExpressionMatch re_mat = re_params.match(docStr);
int pos = docStr.indexOf(re_params);
while (pos != -1) {
docStr.replace(re_mat.captured(0),
QString(QStringLiteral("@param _")) + re_mat.captured(1).toLower() + re_mat.captured(2) + QLatin1Char('_'));
commentedParams.append(re_mat.captured(1).toLower() + re_mat.captured(2));
pos += re_mat.capturedLength() + 3;
pos = docStr.indexOf(docStr, pos);
}
docStr.replace(QLatin1Char('\n'), QString(QStringLiteral("\n")) + m_indentation + QStringLiteral("# "));
// Write parameter documentation
for(UMLAttribute* at : atl) {
// Only write an individual @param entry if one hasn't been found already
// in the main doc comment
if (commentedParams.contains(cppToRubyName(at->name())) == 0) {
docStr += (m_endl + m_indentation + QStringLiteral("# @param _") + cppToRubyName(at->name()) + QLatin1Char('_'));
if (at->doc().isEmpty()) {
docStr += (QLatin1Char(' ') + cppToRubyType(at->getTypeName()));
} else {
docStr += (QLatin1Char(' ') + at->doc().replace(QRegularExpression(QStringLiteral("[\\n\\r]+[\\t ]*")), m_endl + QStringLiteral(" ")));
}
}
}
docStr.remove(QStringLiteral("@ref "));
docStr.replace(QStringLiteral("@param"), QStringLiteral("*"));
docStr.replace(QStringLiteral("@return"), QStringLiteral("* _returns_"));
// All lines after the first '# *' in the doc comment
// must be indented correctly. If they aren't a list
// item starting with '# *', then indent the text with
// three spaces, '# ', to line up with the list item.
pos = docStr.indexOf(QStringLiteral("# *"));
QRegularExpression re_linestart(QStringLiteral("# (?!\\*)"));
QRegularExpressionMatch re_ls_mat = re_linestart.match(docStr);
pos = docStr.indexOf(re_linestart, pos);
while (pos > 0) {
docStr.insert(pos + 1, QStringLiteral(" "));
pos += re_ls_mat.capturedLength() + 2;
pos = docStr.indexOf(re_linestart, pos);
}
h << m_indentation << "# " << docStr << m_endl;
QString typeStr = cppToRubyType(op->getTypeName());
if (!typeStr.isEmpty() && typeStr != QStringLiteral("void") && docStr.contains(QStringLiteral("_returns_")) == 0) {
h << m_indentation << "# * _returns_ " << typeStr << m_endl;
}
}
h << m_indentation << "def " << methodName << "(";
int j=0;
for(UMLAttribute *at : atl) {
QString nameStr = cppToRubyName(at->name());
if (j > 0) {
h << ", " << nameStr;
} else {
h << nameStr;
}
h << (!(at->getInitialValue().isEmpty()) ?
QStringLiteral(" = ") + cppToRubyType(at->getInitialValue()) :
QString());
j++;
}
h <<")" << m_endl;
// write body
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) { // empty method body
h << m_indentation << m_indentation << m_endl;
}
else {
h << formatSourceCode(sourceCode, m_indentation + m_indentation);
}
h << m_indentation << "end" << m_endl << m_endl;
}//end for
}
/**
* Calls @ref writeSingleAttributeAccessorMethods() on each of the attributes in attribs list.
* @param attribs the attribute
* @param visibility the visibility of the attribute
* @param stream output stream to the generated file
*/
void RubyWriter::writeAttributeMethods(UMLAttributeList attribs,
Uml::Visibility::Enum visibility, QTextStream &stream)
{
// return now if NO attributes to work on
if (attribs.count() == 0 || visibility == Uml::Visibility::Private)
return;
for(UMLAttribute *at: attribs)
{
QString varName = cppToRubyName(cleanName(at->name()));
writeSingleAttributeAccessorMethods(varName, at->doc(), stream);
}
}
/**
* Write all method declarations, for attributes and associations
* for the given permitted scope.
* @param fieldName the field name
* @param descr the description
* @param h output stream to the generated file
*/
void RubyWriter::writeSingleAttributeAccessorMethods(
const QString &fieldName,
const QString &descr,
QTextStream &h)
{
QString description = descr;
description.remove(QRegularExpression(QStringLiteral("m_[npb](?=[A-Z])")));
description.remove(QStringLiteral("m_"));
description.replace(QLatin1Char('\n'), QString(QStringLiteral("\n")) + m_indentation + QStringLiteral("# "));
if (!description.isEmpty()) {
h << m_indentation << "# " << description << m_endl;
}
h << m_indentation << "attr_accessor :" << fieldName << m_endl << m_endl;
return;
}
/**
* Returns "Ruby".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum RubyWriter::language() const
{
return Uml::ProgrammingLanguage::Ruby;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList RubyWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("__FILE__")
<< QStringLiteral("__LINE__")
<< QStringLiteral("BEGIN")
<< QStringLiteral("END")
<< QStringLiteral("alias")
<< QStringLiteral("and")
<< QStringLiteral("begin")
<< QStringLiteral("break")
<< QStringLiteral("case")
<< QStringLiteral("class")
<< QStringLiteral("def")
<< QStringLiteral("defined?")
<< QStringLiteral("do")
<< QStringLiteral("else")
<< QStringLiteral("elsif")
<< QStringLiteral("end")
<< QStringLiteral("ensure")
<< QStringLiteral("false")
<< QStringLiteral("for")
<< QStringLiteral("if")
<< QStringLiteral("in")
<< QStringLiteral("module")
<< QStringLiteral("next")
<< QStringLiteral("nil")
<< QStringLiteral("not")
<< QStringLiteral("or")
<< QStringLiteral("redo")
<< QStringLiteral("rescue")
<< QStringLiteral("retry")
<< QStringLiteral("return")
<< QStringLiteral("self")
<< QStringLiteral("super")
<< QStringLiteral("then")
<< QStringLiteral("true")
<< QStringLiteral("undef")
<< QStringLiteral("unless")
<< QStringLiteral("until")
<< QStringLiteral("when")
<< QStringLiteral("while")
<< QStringLiteral("yield");
}
return keywords;
}
| 16,498
|
C++
|
.cpp
| 405
| 32.920988
| 161
| 0.598365
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,559
|
rubycodeclassfield.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodeclassfield.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodeclassfield.h"
// local includes
#include "attribute.h"
#include "debug_utils.h"
#include "rubyclassifiercodedocument.h"
#include "rubycodecomment.h"
#include "rubycodegenerator.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
// qt includes
RubyCodeClassField::RubyCodeClassField (ClassifierCodeDocument * parentDoc, UMLRole * role)
: CodeClassField(parentDoc, role)
{
}
RubyCodeClassField::RubyCodeClassField (ClassifierCodeDocument * parentDoc, UMLAttribute * attrib)
: CodeClassField(parentDoc, attrib)
{
}
RubyCodeClassField::~RubyCodeClassField ()
{
}
QString RubyCodeClassField::getFieldName()
{
if (parentIsAttribute())
{
UMLAttribute * at = (UMLAttribute*) getParentObject();
return cleanName(at->name());
}
else
{
UMLRole * role = (UMLRole*) getParentObject();
QString roleName = role->name();
if(fieldIsSingleValue()) {
return roleName.replace(0, 1, roleName.left(1).toLower());
} else {
return roleName.toLower() + QStringLiteral("Array");
}
}
}
QString RubyCodeClassField::getInitialValue()
{
if (parentIsAttribute())
{
const UMLAttribute * at = getParentObject()->asUMLAttribute();
if (at) {
return fixInitialStringDeclValue(at->getInitialValue(), getTypeName());
} else {
logError0("RubyCodeClassField::getInitialValue: parent object is not a UMLAttribute");
return QString();
}
}
else
{
if(fieldIsSingleValue()) {
// FIX : IF the multiplicity is "1" then we should init a new object here, if it is 0 or 1,
// then we can just return 'empty' string (minor problem).
return QString();
} else {
return RubyCodeGenerator::getListFieldClassName() + QStringLiteral(".new()");
}
}
}
QString RubyCodeClassField::getTypeName ()
{
return RubyCodeGenerator::cppToRubyType(CodeClassField::getTypeName());
}
| 2,291
|
C++
|
.cpp
| 73
| 26.09589
| 103
| 0.676644
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,560
|
rubycodegenerator.cpp
|
KDE_umbrello/umbrello/codegenerators/ruby/rubycodegenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005 Richard Dale <Richard_Dale@tipitina.demon.co.uk>
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "rubycodegenerator.h"
// local includes
#include "rubycodecomment.h"
#include "codeviewerdialog.h"
#include "uml.h"
// kde includes
#include <kconfig.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QRegularExpression>
/**
* Constructor.
*/
RubyCodeGenerator::RubyCodeGenerator()
: AdvancedCodeGenerator()
{
// These initializations are done in CodeGenFactory::createObject()
//UMLApp::app()->setPolicyExt (new RubyCodeGenerationPolicy(UMLApp::app()->getConfig()));
// load Classifier documents from parent document
//initFromParentDocument();
connectSlots();
}
/**
* Destructor.
*/
RubyCodeGenerator::~RubyCodeGenerator()
{
}
/**
* Return our language.
* @return language identifier
*/
Uml::ProgrammingLanguage::Enum RubyCodeGenerator::language() const
{
return Uml::ProgrammingLanguage::Ruby;
}
/**
* Get the editing dialog for this code document.
* @return code viewer dialog object
*/
CodeViewerDialog * RubyCodeGenerator::getCodeViewerDialog(QWidget* parent, CodeDocument *doc,
Settings::CodeViewerState & state)
{
CodeViewerDialog *dialog = new CodeViewerDialog(parent, doc, state);
return dialog;
}
/**
* Utility function for getting the ruby code generation policy.
* @return Ruby code generation policy object
*/
RubyCodeGenerationPolicy * RubyCodeGenerator::getRubyPolicy()
{
return dynamic_cast<RubyCodeGenerationPolicy*>(UMLApp::app()->policyExt());
}
/**
* A utility method to get the rubyCodeGenerationPolicy()->getAutoGenerateAttribAccessors() value.
* @return flag
*/
bool RubyCodeGenerator::getAutoGenerateAttribAccessors()
{
return getRubyPolicy()->getAutoGenerateAttribAccessors();
}
/**
* A utility method to get the rubyCodeGenerationPolicy()->getAutoGenerateAssocAccessors() value.
* @return flag
*/
bool RubyCodeGenerator::getAutoGenerateAssocAccessors()
{
return getRubyPolicy()->getAutoGenerateAssocAccessors();
}
/**
* Get the list variable class name to use. For Ruby, we have set this to "Array".
* @return name of list field class
*/
QString RubyCodeGenerator::getListFieldClassName()
{
return QString(QStringLiteral("Array"));
}
/**
* Convert a C++ type such as 'int' or 'QWidget' to
* ruby types Integer and Qt::Widget.
* @param cppType the C++ type to be converted
* @return the ruby type as string
*/
QString RubyCodeGenerator::cppToRubyType(const QString &cppType)
{
QString type = cleanName(cppType);
type.remove(QStringLiteral("const "));
type.remove(QRegularExpression(QStringLiteral("[*&\\s]")));
type.replace(QRegularExpression(QStringLiteral("[<>]")), QStringLiteral("_"));
type.replace(QStringLiteral("QStringList"), QStringLiteral("Array"));
type.replace(QRegularExpression(QStringLiteral("^string$")),QStringLiteral("String"));
type.replace(QStringLiteral("QString"), QStringLiteral("String"));
type.replace(QStringLiteral("bool"), QStringLiteral("true|false"));
type.replace(QRegularExpression(QStringLiteral("^(uint|int|ushort|short|ulong|long)$")), QStringLiteral("Integer"));
type.replace(QRegularExpression(QStringLiteral("^(float|double)$")), QStringLiteral("Float"));
type.replace(QRegularExpression(QStringLiteral("^Q(?=[A-Z])")), QStringLiteral("Qt::"));
type.replace(QRegularExpression(QStringLiteral("^K(?!(DE|Parts|IO)")), QStringLiteral("KDE::"));
return type;
}
/**
* Convert C++ names such as 'm_foobar' or pFoobar to
* just 'foobar' for ruby.
* @param cppName the C++ name to be converted
* @return the ruby name as string
*/
QString RubyCodeGenerator::cppToRubyName(const QString &cppName)
{
QString name = cleanName(cppName);
name.remove(QRegularExpression(QStringLiteral("^m_")));
name.remove(QRegularExpression(QStringLiteral("^[pbn](?=[A-Z])")));
name = name.mid(0, 1).toLower() + name.mid(1);
return name;
}
/**
* Create a new classifier code document.
* @param classifier the UML classifier
* @return a new classifier code document
*/
CodeDocument * RubyCodeGenerator::newClassifierCodeDocument(UMLClassifier * classifier)
{
RubyClassifierCodeDocument * doc = new RubyClassifierCodeDocument(classifier);
doc->initCodeClassFields();
return doc;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList RubyCodeGenerator::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("__FILE__")
<< QStringLiteral("__LINE__")
<< QStringLiteral("BEGIN")
<< QStringLiteral("END")
<< QStringLiteral("alias")
<< QStringLiteral("and")
<< QStringLiteral("begin")
<< QStringLiteral("break")
<< QStringLiteral("case")
<< QStringLiteral("class")
<< QStringLiteral("def")
<< QStringLiteral("defined?")
<< QStringLiteral("do")
<< QStringLiteral("else")
<< QStringLiteral("elsif")
<< QStringLiteral("end")
<< QStringLiteral("ensure")
<< QStringLiteral("false")
<< QStringLiteral("for")
<< QStringLiteral("if")
<< QStringLiteral("in")
<< QStringLiteral("module")
<< QStringLiteral("next")
<< QStringLiteral("nil")
<< QStringLiteral("not")
<< QStringLiteral("or")
<< QStringLiteral("redo")
<< QStringLiteral("rescue")
<< QStringLiteral("retry")
<< QStringLiteral("return")
<< QStringLiteral("self")
<< QStringLiteral("super")
<< QStringLiteral("then")
<< QStringLiteral("true")
<< QStringLiteral("undef")
<< QStringLiteral("unless")
<< QStringLiteral("until")
<< QStringLiteral("when")
<< QStringLiteral("while")
<< QStringLiteral("yield");
}
return keywords;
}
| 6,215
|
C++
|
.cpp
| 184
| 29.23913
| 120
| 0.691181
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,561
|
adawriter.cpp
|
KDE_umbrello/umbrello/codegenerators/ada/adawriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2002 Oliver Kellogg <okellogg@users.sourceforge.net>
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "adawriter.h"
#include "debug_utils.h"
#include "umldoc.h"
#include "uml.h"
#include "classifier.h"
#include "enum.h"
#include "classifierlistitem.h"
#include "umlclassifierlistitemlist.h"
#include "umltemplatelist.h"
#include "folder.h"
#include "association.h"
#include "attribute.h"
#include "operation.h"
#include "template.h"
#include <KLocalizedString>
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
const QString AdaWriter::defaultPackageSuffix = QStringLiteral("_Holder");
/**
* Basic Constructor
*/
AdaWriter::AdaWriter()
: SimpleCodeGenerator()
{
m_indentLevel = 1; // due to different handling, see finalizeRun()
}
/**
* Empty Destructor
*/
AdaWriter::~AdaWriter()
{
}
/**
* Returns "Ada".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum AdaWriter::language() const
{
return Uml::ProgrammingLanguage::Ada;
}
/**
* Return true if `c' is a tagged type or Ada2005 interface.
*/
bool AdaWriter::isOOClass(const UMLClassifier *c)
{
UMLObject::ObjectType ot = c->baseType();
if (ot == UMLObject::ot_Interface)
return true;
if (ot == UMLObject::ot_Enum)
return false;
if (ot != UMLObject::ot_Class) {
logWarn1("AdaWriter::isOOClass unexpected object type %1", UMLObject::toString(ot));
return false;
}
QString stype = c->stereotype();
if (stype == QStringLiteral("CORBAConstant") || stype == QStringLiteral("CORBATypedef") ||
stype == QStringLiteral("CORBAStruct") || stype == QStringLiteral("CORBAUnion"))
return false;
// CORBAValue, CORBAInterface, and all empty/unknown stereotypes are
// assumed to be object oriented classes.
return true;
}
/**
* Returns the class name.
*/
QString AdaWriter::className(UMLClassifier *c, bool inOwnScope)
{
// If the class has an enclosing package then it is assumed that
// the class name is the type name; if the class does not have an
// enclosing package then the class name acts as the Ada package
// name.
QString retval;
QString className = cleanName(c->name());
UMLPackage *umlPkg = c->umlPackage();
if (umlPkg == UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical)) {
if (! inOwnScope)
retval = className + QLatin1Char('.');
retval.append(QStringLiteral("Object"));
} else {
if (! inOwnScope)
retval = umlPkg->fullyQualifiedName(QStringLiteral(".")) + QLatin1Char('.');
retval.append(className);
}
return retval;
}
/**
* Returns the package name.
*/
QString AdaWriter::packageName(UMLPackage *p)
{
// If the class has an enclosing package then it is assumed that
// the class name is the type name; if the class does not have an
// enclosing package then the class name acts as the Ada package
// name.
UMLPackage *umlPkg = p->umlPackage();
QString className = cleanName(p->name());
QString retval;
if (umlPkg == UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical))
umlPkg = nullptr;
const UMLClassifier *c = p->asUMLClassifier();
if (umlPkg == nullptr) {
retval = className;
if (c == nullptr || !isOOClass(c))
retval.append(defaultPackageSuffix);
} else {
retval = umlPkg->fullyQualifiedName(QStringLiteral("."));
}
return retval;
}
/**
* Compute the type and role name from the given association.
*
* @param c The UMLClassifier for which code is being generated.
* @param a The UMLAssociation to analyze.
* @param typeName Return value: type name.
* @param roleName Return value: role name.
*/
void AdaWriter::computeAssocTypeAndRole(UMLClassifier *c,
UMLAssociation *a,
QString& typeName, QString& roleName)
{
UMLClassifier* assocEnd = a->getObject(Uml::RoleType::B)->asUMLClassifier();
if (assocEnd == nullptr)
return;
const Uml::AssociationType::Enum assocType = a->getAssocType();
if (assocType != Uml::AssociationType::Aggregation && assocType != Uml::AssociationType::Composition)
return;
const QString multi = a->getMultiplicity(Uml::RoleType::B);
bool hasNonUnityMultiplicity = (!multi.isEmpty() && multi != QStringLiteral("1"));
hasNonUnityMultiplicity &= !multi.contains(QRegularExpression(QStringLiteral("^1 *\\.\\. *1$")));
roleName = cleanName(a->getRoleName(Uml::RoleType::B));
if (roleName.isEmpty())
roleName = cleanName(a->name());
if (roleName.isEmpty()) {
QString artificialName = cleanName(assocEnd->name());
if (hasNonUnityMultiplicity) {
roleName = artificialName;
roleName.append(QStringLiteral("_Vector"));
} else {
roleName = QStringLiteral("M_");
roleName.append(artificialName);
}
}
typeName = className(assocEnd, (assocEnd == c));
if (hasNonUnityMultiplicity)
typeName.append(QStringLiteral("_Array_Ptr"));
else if (assocType == Uml::AssociationType::Aggregation)
typeName.append(QStringLiteral("_Ptr"));
}
void AdaWriter::declareClass(UMLClassifier *c, QTextStream &ada)
{
UMLClassifierList superclasses = c->getSuperClasses();
UMLClassifier *firstSuperClass = nullptr;
if (!superclasses.isEmpty()) {
for(UMLClassifier* super : superclasses) {
if (!super->isInterface()) {
firstSuperClass = super;
break;
}
}
if (firstSuperClass == nullptr)
firstSuperClass = superclasses.first();
}
const QString name = className(c);
ada << indent() << "type " << name << " is ";
if (c->isAbstract())
ada << "abstract ";
if (superclasses.isEmpty()) {
ada << "tagged ";
} else {
ada << "new " << className(firstSuperClass, false);
for(UMLClassifier* super : superclasses) {
if (super->isInterface() && super != firstSuperClass)
ada << " and " << className(super, false);
}
ada << " with ";
}
}
/**
* Call this method to generate Ada code for a UMLClassifier.
* @param c the class to generate code for
*/
void AdaWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("AdaWriter::writeClass: Cannot write class of NULL classifier!");
return;
}
if (m_classesGenerated.contains(c))
return;
const bool isClass = !c->isInterface();
QString classname = cleanName(c->name());
QString pkg = packageName(c);
QString fileName = pkg.toLower();
fileName.replace(QLatin1Char('.'), QLatin1Char('-'));
//find an appropriate name for our file
fileName = overwritableName(c, fileName, QStringLiteral(".ads"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile *file = nullptr;
bool isNewFile = false;
PackageFileMap::iterator it = m_pkgsGenerated.find(pkg);
if (it != m_pkgsGenerated.end()) {
file = it.value();
} else {
file = new QFile();
if (!openFile(*file, fileName)) {
Q_EMIT codeGenerated(c, false);
delete file;
return;
}
m_pkgsGenerated[pkg] = file;
isNewFile = true;
}
// Start generating the code.
QTextStream ada(file);
if (isNewFile) {
//try to find a heading file(license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".ads"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file->fileName());
ada << str << m_endl;
}
// Import referenced classes.
UMLPackageList imports;
findObjectsRelated(c, imports);
if (imports.count()) {
for(UMLPackage* con : imports) {
if (con->isUMLDatatype())
continue;
QString pkgDep = packageName(con);
if (pkgDep != pkg)
ada << "with " << pkgDep << "; " << m_endl;
}
ada << m_endl;
}
// Generate generic formals.
UMLTemplateList template_params = c->getTemplateList();
if (template_params.count()) {
ada << indent() << "generic" << m_endl;
m_indentLevel++;
for(UMLTemplate* t : template_params) {
QString formalName = t->name();
QString typeName = t->getTypeName();
if (typeName == QStringLiteral("class")) {
ada << indent() << "type " << formalName << " is tagged private;"
<< m_endl;
} else {
// Check whether it's a data type.
UMLClassifier *typeObj = t->getType();
if (typeObj == nullptr) {
logError1("template_param %1: typeObj is NULL", typeName);
ada << indent() << "type " << formalName << " is new " << typeName
<< " with private; -- CHECK: codegen error"
<< m_endl;
} else if (typeObj->isUMLDatatype()) {
ada << indent() << formalName << " : " << typeName << ";"
<< m_endl;
} else {
ada << indent() << "type " << typeName << " is new "
<< formalName << " with private;" << m_endl;
}
}
}
m_indentLevel--;
}
// Here comes the package proper.
ada << "package " << pkg << " is" << m_endl << m_endl;
}
if (c->baseType() == UMLObject::ot_Enum) {
UMLEnum *ue = c->asUMLEnum();
UMLClassifierListItemList litList = ue->getFilteredList(UMLObject::ot_EnumLiteral);
uint i = 0;
ada << indent() << "type " << classname << " is (" << m_endl;
m_indentLevel++;
for(UMLClassifierListItem* lit : litList) {
QString enumLiteral = cleanName(lit->name());
ada << indent() << enumLiteral;
if (++i < (uint)litList.count())
ada << "," << m_endl;
}
m_indentLevel--;
ada << ");" << m_endl << m_endl;
ada << "end " << pkg << ";" << m_endl << m_endl;
return;
}
if (! isOOClass(c)) {
QString stype = c->stereotype();
if (stype == QStringLiteral("CORBAConstant")) {
ada << indent() << "-- " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else if (stype == QStringLiteral("CORBAStruct")) {
if (isClass) {
UMLAttributeList atl = c->getAttributeList();
ada << indent() << "type " << classname << " is record" << m_endl;
m_indentLevel++;
for(UMLAttribute* at : atl) {
QString name = cleanName(at->name());
QString typeName = at->getTypeName();
ada << indent() << name << " : " << typeName;
QString initialVal = at->getInitialValue();
if (! initialVal.isEmpty() && ! initialVal.toLatin1().isEmpty())
ada << " := " << initialVal;
ada << ";" << m_endl;
}
m_indentLevel--;
ada << indent() << "end record;" << m_endl << m_endl;
}
} else if (stype == QStringLiteral("CORBAUnion")) {
ada << indent() << "-- " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else if (stype == QStringLiteral("CORBATypedef")) {
ada << indent() << "-- " << stype << " is Not Yet Implemented" << m_endl << m_endl;
} else {
ada << indent() << "-- " << stype << ": Unknown stereotype" << m_endl << m_endl;
}
ada << "end " << pkg << ";" << m_endl << m_endl;
return;
}
UMLClassifierList superclasses = c->getSuperClasses();
if (!superclasses.isEmpty()) {
// Ensure that superclasses in same package are declared before this class.
for(UMLClassifier* super : superclasses) {
if (packageName(super) == pkg && !m_classesGenerated.contains(super)) {
writeClass(super);
}
}
}
m_classesGenerated.append(c);
// Write class Documentation if non-empty or if force option set.
if (forceDoc() || !c->doc().isEmpty()) {
ada << "--" << m_endl;
ada << "-- class " << classname << m_endl;
ada << formatDoc(c->doc(), QStringLiteral("-- "));
ada << m_endl;
}
const QString name = className(c);
if (isClass) {
declareClass(c, ada);
ada << "private;" << m_endl << m_endl;
} else {
ada << indent() << "type " << name << " is interface";
for(UMLClassifier* super : superclasses) {
if (super->isInterface())
ada << " and " << className(super, false);
}
ada << ";" << m_endl << m_endl;
}
ada << indent() << "type " << name << "_Ptr is access all " << name << "'Class;" << m_endl << m_endl;
ada << indent() << "type " << name << "_Array is array (Positive range <>) of " << name << "_Ptr;" << m_endl << m_endl;
ada << indent() << "type " << name << "_Array_Ptr is access " << name << "_Array;" << m_endl << m_endl;
// Generate accessors for public attributes.
UMLAttributeList atl;
if (isClass) {
UMLAttributeList atpub;
atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
if (at->visibility() == Uml::Visibility::Public)
atpub.append(at);
}
if (forceSections() || atpub.count())
ada << indent() << "-- Accessors for public attributes:" << m_endl << m_endl;
for(UMLAttribute* at : atpub) {
QString member = cleanName(at->name());
ada << indent() << "procedure Set_" << member << " (";
if (! at->isStatic())
ada << "Self : access " << name << "; ";
ada << "To : " << at->getTypeName() << ");" << m_endl;
ada << indent() << "function Get_" << member;
if (! at->isStatic())
ada << " (Self : access " << name << ")";
ada << " return " << at->getTypeName() << ";" << m_endl << m_endl;
}
}
// Generate public operations.
UMLOperationList opl(c->getOpList());
UMLOperationList oppub;
for(UMLOperation* op : opl) {
if (op->visibility() == Uml::Visibility::Public)
oppub.append(op);
}
if (forceSections() || oppub.count())
ada << indent() << "-- Public methods:" << m_endl << m_endl;
for(UMLOperation* op : oppub) {
writeOperation(op, ada);
}
Q_EMIT codeGenerated(c, true);
}
/**
* Write one operation.
* @param op the class for which we are generating code
* @param ada the stream associated with the output file
* @param is_comment flag for a comment
*/
void AdaWriter::writeOperation(UMLOperation *op, QTextStream &ada, bool is_comment)
{
UMLAttributeList atl = op->getParmList();
QString rettype = op->getTypeName();
bool use_procedure = (rettype.isEmpty() || rettype == QStringLiteral("void"));
ada << indent();
if (is_comment)
ada << "-- ";
if (use_procedure)
ada << "procedure ";
else
ada << "function ";
ada << cleanName(op->name()) << " ";
if (! (op->isStatic() && atl.count() == 0))
ada << "(";
UMLClassifier *parentClassifier = op->umlParent()->asUMLClassifier();
if (! op->isStatic()) {
ada << "Self : access " << className(parentClassifier);
if (atl.count())
ada << ";" << m_endl;
}
if (atl.count()) {
uint i = 0;
m_indentLevel++;
for(UMLAttribute* at : atl) {
ada << indent();
if (is_comment)
ada << "-- ";
ada << cleanName(at->name()) << " : ";
Uml::ParameterDirection::Enum pk = at->getParmKind();
if (pk == Uml::ParameterDirection::Out)
ada << "out ";
else if (pk == Uml::ParameterDirection::InOut)
ada << "in out ";
else
ada << "in ";
ada << at->getTypeName();
if (! at->getInitialValue().isEmpty())
ada << " := " << at->getInitialValue();
if (++i < (uint)atl.count()) //FIXME gcc warning
ada << ";" << m_endl;
}
m_indentLevel--;
}
if (! (op->isStatic() && atl.count() == 0))
ada << ")";
if (! use_procedure)
ada << " return " << rettype;
if (op->isAbstract())
ada << " is abstract";
ada << ";" << m_endl << m_endl;
}
/**
* Returns the default datatypes.
*/
QStringList AdaWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("Boolean"));
l.append(QStringLiteral("Character"));
l.append(QStringLiteral("Positive"));
l.append(QStringLiteral("Natural"));
l.append(QStringLiteral("Integer"));
l.append(QStringLiteral("Short_Integer"));
l.append(QStringLiteral("Long_Integer"));
l.append(QStringLiteral("Float"));
l.append(QStringLiteral("Long_Float"));
l.append(QStringLiteral("Duration"));
l.append(QStringLiteral("String"));
return l;
}
/**
* Check whether the given string is a reserved word for the
* language of this code generator
*
* @param rPossiblyReservedKeyword The string to check.
*/
bool AdaWriter::isReservedKeyword(const QString & rPossiblyReservedKeyword)
{
const QStringList keywords = reservedKeywords();
QStringList::ConstIterator it;
for (it = keywords.begin(); it != keywords.end(); ++it) {
if ((*it).toLower() == rPossiblyReservedKeyword.toLower()) {
return true;
}
}
return false;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList AdaWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords.append(QStringLiteral("abort"));
keywords.append(QStringLiteral("abs"));
keywords.append(QStringLiteral("abstract"));
keywords.append(QStringLiteral("accept"));
keywords.append(QStringLiteral("access"));
keywords.append(QStringLiteral("aliased"));
keywords.append(QStringLiteral("all"));
keywords.append(QStringLiteral("and"));
keywords.append(QStringLiteral("Argument_Error"));
keywords.append(QStringLiteral("array"));
keywords.append(QStringLiteral("Assert_Failure"));
keywords.append(QStringLiteral("at"));
keywords.append(QStringLiteral("begin"));
keywords.append(QStringLiteral("body"));
keywords.append(QStringLiteral("Boolean"));
keywords.append(QStringLiteral("case"));
keywords.append(QStringLiteral("Character"));
keywords.append(QStringLiteral("constant"));
keywords.append(QStringLiteral("Constraint_Error"));
keywords.append(QStringLiteral("Conversion_Error"));
keywords.append(QStringLiteral("Data_Error"));
keywords.append(QStringLiteral("declare"));
keywords.append(QStringLiteral("delay"));
keywords.append(QStringLiteral("delta"));
keywords.append(QStringLiteral("Dereference_Error"));
keywords.append(QStringLiteral("Device_Error"));
keywords.append(QStringLiteral("digits"));
keywords.append(QStringLiteral("do"));
keywords.append(QStringLiteral("Duration"));
keywords.append(QStringLiteral("else"));
keywords.append(QStringLiteral("elsif"));
keywords.append(QStringLiteral("end"));
keywords.append(QStringLiteral("End_Error"));
keywords.append(QStringLiteral("entry"));
keywords.append(QStringLiteral("exception"));
keywords.append(QStringLiteral("exit"));
keywords.append(QStringLiteral("false"));
keywords.append(QStringLiteral("Float"));
keywords.append(QStringLiteral("for"));
keywords.append(QStringLiteral("function"));
keywords.append(QStringLiteral("generic"));
keywords.append(QStringLiteral("goto"));
keywords.append(QStringLiteral("if"));
keywords.append(QStringLiteral("in"));
keywords.append(QStringLiteral("Index_Error"));
keywords.append(QStringLiteral("Integer"));
keywords.append(QStringLiteral("interface"));
keywords.append(QStringLiteral("is"));
keywords.append(QStringLiteral("Layout_Error"));
keywords.append(QStringLiteral("Length_Error"));
keywords.append(QStringLiteral("limited"));
keywords.append(QStringLiteral("Long_Float"));
keywords.append(QStringLiteral("Long_Integer"));
keywords.append(QStringLiteral("Long_Long_Float"));
keywords.append(QStringLiteral("Long_Long_Integer"));
keywords.append(QStringLiteral("loop"));
keywords.append(QStringLiteral("mod"));
keywords.append(QStringLiteral("Mode_Error"));
keywords.append(QStringLiteral("Name_Error"));
keywords.append(QStringLiteral("Natural"));
keywords.append(QStringLiteral("new"));
keywords.append(QStringLiteral("not"));
keywords.append(QStringLiteral("null"));
keywords.append(QStringLiteral("of"));
keywords.append(QStringLiteral("or"));
keywords.append(QStringLiteral("others"));
keywords.append(QStringLiteral("out"));
keywords.append(QStringLiteral("package"));
keywords.append(QStringLiteral("Pattern_Error"));
keywords.append(QStringLiteral("Picture_Error"));
keywords.append(QStringLiteral("Pointer_Error"));
keywords.append(QStringLiteral("Positive"));
keywords.append(QStringLiteral("pragma"));
keywords.append(QStringLiteral("private"));
keywords.append(QStringLiteral("procedure"));
keywords.append(QStringLiteral("Program_Error"));
keywords.append(QStringLiteral("protected"));
keywords.append(QStringLiteral("raise"));
keywords.append(QStringLiteral("range"));
keywords.append(QStringLiteral("record"));
keywords.append(QStringLiteral("rem"));
keywords.append(QStringLiteral("renames"));
keywords.append(QStringLiteral("requeue"));
keywords.append(QStringLiteral("return"));
keywords.append(QStringLiteral("reverse"));
keywords.append(QStringLiteral("select"));
keywords.append(QStringLiteral("separate"));
keywords.append(QStringLiteral("Short_Float"));
keywords.append(QStringLiteral("Short_Integer"));
keywords.append(QStringLiteral("Short_Short_Float"));
keywords.append(QStringLiteral("Short_Short_Integer"));
keywords.append(QStringLiteral("Status_Error"));
keywords.append(QStringLiteral("Storage_Error"));
keywords.append(QStringLiteral("String"));
keywords.append(QStringLiteral("subtype"));
keywords.append(QStringLiteral("Tag_Error"));
keywords.append(QStringLiteral("tagged"));
keywords.append(QStringLiteral("task"));
keywords.append(QStringLiteral("Tasking_Error"));
keywords.append(QStringLiteral("terminate"));
keywords.append(QStringLiteral("Terminator_Error"));
keywords.append(QStringLiteral("then"));
keywords.append(QStringLiteral("Time_Error"));
keywords.append(QStringLiteral("Translation_Error"));
keywords.append(QStringLiteral("true"));
keywords.append(QStringLiteral("type"));
keywords.append(QStringLiteral("until"));
keywords.append(QStringLiteral("Update_Error"));
keywords.append(QStringLiteral("use"));
keywords.append(QStringLiteral("Use_Error"));
keywords.append(QStringLiteral("when"));
keywords.append(QStringLiteral("while"));
keywords.append(QStringLiteral("Wide_Character"));
keywords.append(QStringLiteral("Wide_String"));
keywords.append(QStringLiteral("with"));
keywords.append(QStringLiteral("xor"));
}
return keywords;
}
void AdaWriter::finalizeRun()
{
PackageFileMap::iterator end(m_pkgsGenerated.end());
for (PackageFileMap::iterator i = m_pkgsGenerated.begin(); i != end; ++i) {
QString pkg = i.key();
QFile *file = i.value();
QTextStream ada(file);
ada << m_endl << "private" << m_endl << m_endl;
for(UMLClassifier* c : m_classesGenerated) {
if (packageName(c) != pkg)
continue;
bool isClass = !c->isInterface();
if (isClass) {
declareClass(c, ada);
ada << "record" << m_endl;
m_indentLevel++;
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
if (forceSections() || !aggregations.isEmpty()) {
ada << indent() << "-- Aggregations:" << m_endl;
for(UMLAssociation *a : aggregations) {
if (c != a->getObject(Uml::RoleType::A))
continue;
QString typeName, roleName;
computeAssocTypeAndRole(c, a, typeName, roleName);
ada << indent() << roleName << " : " << typeName << ";" << m_endl;
}
ada << m_endl;
}
if (forceSections() || !compositions.isEmpty()) {
ada << indent() << "-- Compositions:" << m_endl;
for(UMLAssociation *a : compositions) {
if (c != a->getObject(Uml::RoleType::A))
continue;
QString typeName, roleName;
computeAssocTypeAndRole(c, a, typeName, roleName);
ada << indent() << roleName << " : " << typeName << ";" << m_endl;
}
ada << m_endl;
}
UMLAttributeList atl = c->getAttributeList();
if (forceSections() || atl.count()) {
ada << indent() << "-- Attributes:" << m_endl;
for(UMLAttribute* at : atl) {
if (!at || at->isStatic())
continue;
ada << indent() << cleanName(at->name()) << " : "
<< at->getTypeName();
if (!at->getInitialValue().isEmpty() && !at->getInitialValue().toLatin1().isEmpty())
ada << " := " << at->getInitialValue();
ada << ";" << m_endl;
}
}
const bool haveAttrs = (atl.count() != 0);
if (aggregations.isEmpty() && compositions.isEmpty() && !haveAttrs)
ada << indent() << "null;" << m_endl;
m_indentLevel--;
ada << indent() << "end record;" << m_endl << m_endl;
if (haveAttrs) {
bool seen_static_attr = false;
for(UMLAttribute* at : atl) {
if (! at->isStatic())
continue;
if (! seen_static_attr) {
ada << indent() << "-- Static attributes:" << m_endl;
seen_static_attr = true;
}
ada << indent();
if (at->visibility() == Uml::Visibility::Private)
ada << "-- Private: ";
ada << cleanName(at->name()) << " : " << at->getTypeName();
if (at && ! at->getInitialValue().isEmpty() && ! at->getInitialValue().toLatin1().isEmpty())
ada << " := " << at->getInitialValue();
ada << ";" << m_endl;
}
if (seen_static_attr)
ada << m_endl;
}
}
UMLOperationList opl(c->getOpList());
// Generate protected operations.
UMLOperationList opprot;
for(UMLOperation* op : opl) {
if (op->visibility() == Uml::Visibility::Protected)
opprot.append(op);
}
if (forceSections() || opprot.count())
ada << indent() << "-- Protected methods:" << m_endl << m_endl;
for(UMLOperation* op : opprot) {
writeOperation(op, ada);
}
// Generate private operations.
// These are currently only generated as comments in the private part
// of the spec.
// Once umbrello supports the merging of automatically generated and
// hand written code sections, private operations should be generated
// into the package body.
UMLOperationList oppriv;
for(UMLOperation* op : opl) {
const Uml::Visibility::Enum vis = op->visibility();
if (vis == Uml::Visibility::Private ||
vis == Uml::Visibility::Implementation)
oppriv.append(op);
}
if (forceSections() || oppriv.count())
ada << indent() << "-- Private methods:" << m_endl << m_endl;
for(UMLOperation* op : oppriv) {
writeOperation(op, ada, true);
}
}
ada << m_endl << "end " << i.key() << ";" << m_endl;
file->close();
Q_EMIT showGeneratedFile(file->fileName());
delete file;
}
}
| 30,410
|
C++
|
.cpp
| 734
| 31.757493
| 123
| 0.564658
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,562
|
dcodeoperation.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodeoperation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "dcodeoperation.h"
#include "dcodegenerator.h"
#include "dcodegenerationpolicy.h"
#include "dclassifiercodedocument.h"
#include "dcodedocumentation.h"
#include "uml.h"
// Constructors/Destructors
//
DCodeOperation::DCodeOperation(DClassifierCodeDocument * doc, UMLOperation *parent,
const QString & body, const QString & comment) : CodeOperation (doc, parent, body, comment)
{
// lets not go with the default comment and instead use
// full-blown d documentation object instead
setComment(new DCodeDocumentation(doc));
// these things never change..
setOverallIndentationLevel(1);
}
DCodeOperation::~DCodeOperation()
{
}
// we basically want to update the doc and start text of this method
void DCodeOperation::updateMethodDeclaration()
{
CodeDocument * doc = getParentDocument();
DClassifierCodeDocument * ddoc = dynamic_cast<DClassifierCodeDocument*>(doc);
Q_ASSERT(ddoc);
UMLOperation * o = getParentOperation();
bool isInterface = ddoc->getParentClassifier()->isInterface();
QString endLine = getNewLineEndingChars();
/*
* Member function declaration
*
* (visibility) (static | abstract | override) retType name (param1, ..., paramN) (; | {)
* a b c d e f g h
*/
QString startText;
// (a) visibility modifier
//FIXME: startText += o->getVisibility().toString() + " ";
// (b) static
if (o->isStatic()) startText += QStringLiteral("static ");
// (c) abstract
//TODO
// (d) override
//TODO
// (e) return type
if (!o->isConstructorOperation()) {
//FIXME: startText += DCodeGenerator::fixTypeName(o->getTypeName()) + QStringLiteral(" ");
}
// (f) name
startText += o->name();
// (g) params
startText += QLatin1Char('(');
// assemble parameters
QString paramStr;
UMLAttributeList list = getParentOperation()->getParmList();
int paramNum = list.count();
for(UMLAttribute* parm : list) {
QString rType = parm->getTypeName();
QString paramName = parm->name();
paramStr += rType + QLatin1Char(' ') + paramName;
paramNum--;
if (paramNum > 0) paramStr += QStringLiteral(", ");
}
startText += paramStr;
startText += QLatin1Char(')');
// (h) function body
if(isInterface) {
startText += QLatin1Char(';');
setEndMethodText(QString());
} else {
startText += QStringLiteral(" {");
setEndMethodText(QStringLiteral("}"));
}
setStartMethodText(startText);
// Lastly, for text content generation, we fix the comment on the
// operation, IF the codeop is autogenerated & currently empty
QString comment = o->doc();
if(comment.isEmpty() && contentType() == CodeBlock::AutoGenerated)
{
UMLAttributeList parameters = o->getParmList();
for(UMLAttribute* currentAtt : parameters) {
comment += endLine + QStringLiteral("@param ") + currentAtt->name() + QLatin1Char(' ');
comment += currentAtt->doc();
}
// add a returns statement too
// TODO proper return type comments
//if(!returnType.isEmpty())
// comment += endLine + QStringLiteral("@return ") + returnType + QLatin1Char(' ');
getComment()->setText(comment);
}
}
int DCodeOperation::lastEditableLine()
{
ClassifierCodeDocument * doc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());
// very last line is NOT editable as its a one-line declaration
// w/ no body in an interface.
if (doc->parentIsInterface()) return -1;
return 0;
}
| 3,897
|
C++
|
.cpp
| 104
| 32.230769
| 99
| 0.655145
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,563
|
dwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dwriter.h"
// app includes
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#include "codegen_utils.h"
#include "debug_utils.h"
#include "operation.h"
#include "template.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include "umltemplatelist.h"
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
/**
* Constructor, initialises a couple of variables.
*/
DWriter::DWriter()
: isInterface(false)
{
startline = m_endl + m_indentation;
}
/**
* Destructor, empty.
*/
DWriter::~DWriter()
{
}
/**
* Returns "D".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum DWriter::language() const
{
return Uml::ProgrammingLanguage::D;
}
// FIXME: doesn't work yet
void DWriter::writeModuleDecl(UMLClassifier *c, QTextStream &d)
{
if (!c->package().isEmpty())
d << "module " << c->package() << ";" << m_endl;
writeBlankLine(d);
}
void DWriter::writeModuleImports(UMLClassifier *c, QTextStream &d)
{
// another preparation, determine what we have
UMLAssociationList associations = c->getSpecificAssocs(Uml::AssociationType::Association); // BAD! only way to get "general" associations.
UMLAssociationList uniAssociations = c->getUniAssociationToBeImplemented();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
bool hasAssociations = aggregations.count() + associations.count() +
compositions.count() + uniAssociations.count() > 0;
if (hasAssociations) {
// import tango, if that mode is set
writeBlankLine(d);
}
//only import classes in a different package as this class
UMLPackageList imports;
findObjectsRelated(c, imports);
for(UMLPackage* con : imports) {
if (con->isUMLDatatype())
continue;
QString pkg = con->package();
if (!pkg.isEmpty() && pkg != c->package())
d << "import " << pkg << "." << cleanName(con->name()) << ";"
<< m_endl;
}
writeBlankLine(d);
}
/**
* Call this method to generate d code for a UMLClassifier.
* @param c the class to generate code for
*/
void DWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("DWriter::writeClass: Cannot write class of NULL classifier");
return;
}
isInterface = c->isInterface();
QString fileName = cleanName(c->name().toLower());
//find an appropriate name for our file
fileName = findFileName(c, QStringLiteral(".d"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
// check that we may open that file for writing
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
// open text stream to file
QTextStream d(&file);
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".d"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
d<<str<<m_endl;
}
// source file begins with the module declaration
writeModuleDecl(c, d);
// imports
writeModuleImports(c, d);
// write the opening declaration for the class incl any documentation,
// interfaces and/or inheritance issues we have
writeClassDecl(c, d);
// start body of class
d << " {" << m_endl;
// Preparations
//
// sort attributes by Scope
UMLAttributeList atl;
UMLAttributeList atpub, atprot, atpriv, atpkg, atexport;
UMLAttributeList final_atpub, final_atprot, final_atpriv, final_atpkg, final_atexport;
if (!isInterface) {
UMLAttributeList atl = c->getAttributeList();
for(UMLAttribute* at : atl) {
switch(at->visibility())
{
case Uml::Visibility::Public:
if (at->isStatic())
final_atpub.append(at);
else
atpub.append(at);
break;
case Uml::Visibility::Protected:
if (at->isStatic())
final_atprot.append(at);
else
atprot.append(at);
break;
case Uml::Visibility::Private:
if (at->isStatic())
final_atpriv.append(at);
else
atpriv.append(at);
break;/* TODO: requires support from the gui & other structures
case Uml::Visibility::Package:
if (at->getStatic())
final_atpkg.append(at);
else
atpkg.append(at);
break;
case Uml::Visibility::Export:
if (at->getStatic())
final_atexport.append(at);
else
atexport.append(at);
break;*/
default:
break;
}
}
}
// another preparation, determine what we have
UMLAssociationList associations = c->getSpecificAssocs(Uml::AssociationType::Association); // BAD! only way to get "general" associations.
UMLAssociationList uniAssociations = c->getUniAssociationToBeImplemented();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
bool hasAssociations = aggregations.count() + associations.count() + compositions.count() + uniAssociations.count() > 0;
bool hasAttributes = atl.count() > 0;
bool hasAccessorMethods = hasAttributes || hasAssociations;
bool hasOperationMethods = c->getOpList().count() > 0;
// ATTRIBUTES
//
// write comment for section IF needed
if (forceDoc() || hasAccessorMethods)
{
writeComment(QString(), m_indentation, d);
writeComment(QStringLiteral("Fields"), m_indentation, d);
writeComment(QString(), m_indentation, d);
writeBlankLine(d);
}
writeAttributeDecls(final_atpub, final_atprot, final_atpriv, d);
writeAttributeDecls(atpub, atprot, atpriv, d);
writeAssociationDecls(associations, c->id(), d);
writeAssociationDecls(uniAssociations, c->id(), d);
writeAssociationDecls(aggregations, c->id(), d);
writeAssociationDecls(compositions, c->id(), d);
//FIXME: find constructors and write them here
// write constructors
if (!isInterface) writeConstructor(c, d);
// METHODS
//
// write comment for sub-section IF needed
if (forceDoc() || hasAccessorMethods) {
writeComment(QString(), m_indentation, d);
writeComment(QStringLiteral("Accessors"), m_indentation, d);
writeComment(QString(), m_indentation, d);
writeBlankLine(d);
}
// Accessors for attributes
writeAttributeMethods(final_atpub, Uml::Visibility::Public, d);
writeAttributeMethods(final_atprot, Uml::Visibility::Protected, d);
writeAttributeMethods(final_atpriv, Uml::Visibility::Private, d);
writeAttributeMethods(atpub, Uml::Visibility::Public, d);
writeAttributeMethods(atprot, Uml::Visibility::Protected, d);
writeAttributeMethods(atpriv, Uml::Visibility::Private, d);
// accessor methods for associations
// first: determine the name of the other class
writeAssociationMethods(associations, c, d);
writeAssociationMethods(uniAssociations, c, d);
writeAssociationMethods(aggregations, c, d);
writeAssociationMethods(compositions, c, d);
// Other operation methods
// all other operations are now written
// write comment for sub-section IF needed
if (forceDoc() || hasOperationMethods) {
writeComment(QString(), m_indentation, d);
writeComment(QStringLiteral("Other methods"), m_indentation, d);
writeComment(QString(), m_indentation, d);
writeBlankLine(d);
}
writeOperations(c, d);
d << "}" << m_endl; // end class
file.close();
Q_EMIT codeGenerated(c, true);
}
void DWriter::writeClassDecl(UMLClassifier *c, QTextStream &d)
{
// class documentation
if (!c->doc().isEmpty()) {
writeDocumentation(QString(), c->doc(), QString(), QString(), d);
}
/*
* Class declaration
*
* (private) class foo(T, ..., Z) : class1, ..., classN, interface1, ..., interfaceN
* a b c d e f g
*/
// (a) visibility modifier
switch(c->visibility()) {
case Uml::Visibility::Private: d << "private "; break;
default: break;
}
// (b) keyword
// TODO what about structs?
if (isInterface) {
d << "interface ";
} else {
if (c->isAbstract()) {
d << "abstract ";
}
d << "class ";
}
// (c) class name
QString classname = cleanName(c->name()); // our class name
d << classname;
// (d) template parameters
UMLTemplateList template_params = c->getTemplateList();
if (template_params.count()) {
d << "(";
for (UMLTemplateListIt tlit(template_params); tlit.hasNext();) {
UMLTemplate* t = tlit.next();
// TODO: hm, leaving the type blank results in "class"
// so we omit it (also because "class" in this context is illegal)
if (t->getTypeName() != QStringLiteral("class")) {
d << t->getTypeName();
d << " ";
}
d << t->name();
if (tlit.hasNext()) {
tlit.next();
d << ", ";
}
}
d << ")";
}
// (e) inheritances
UMLClassifierList superclasses =
c->findSuperClassConcepts(UMLClassifier::CLASS);
UMLClassifierList superinterfaces =
c->findSuperClassConcepts(UMLClassifier::INTERFACE);
int count = superclasses.count() + superinterfaces.count();
if (count > 0) {
d << " : ";
// (f) base classes
for(UMLClassifier* classifier : superclasses) {
d << cleanName(classifier->name());
count--;
if (count>0) d << ", ";
}
// (g) interfaces
for(UMLClassifier* classifier : superinterfaces) {
d << cleanName(classifier->name());
count--;
if (count>0) d << ", ";
}
}
}
void DWriter::writeProtectionMod(Uml::Visibility::Enum visibility, QTextStream &d)
{
d << m_indentation << Uml::Visibility::toString(visibility) << ":" << m_endl << m_endl;
}
void DWriter::writeAttributeDecl(Uml::Visibility::Enum visibility, UMLAttributeList &atlist, QTextStream &d)
{
if (atlist.count()==0) return;
writeProtectionMod(visibility, d);
for(UMLAttribute* at : atlist) {
// documentation
if (!at->doc().isEmpty()) {
writeComment(at->doc(), m_indentation, d, true);
}
d << m_indentation;
// static attribute?
if (at->isStatic()) d << "static ";
// method return type
d << fixTypeName(at->getTypeName()) << " ";
// TODO: find out whether this class has accessors or not
bool hasAccessorMethods = true;
// attribute name
if (hasAccessorMethods) {
d << "m_";
}
d << cleanName(at->name());
// initial value
QString initVal = fixInitialStringDeclValue(at->getInitialValue(), at->getTypeName());
if (!initVal.isEmpty()) d << " = " << initVal;
d << ";" << m_endl << m_endl;
}
}
void DWriter::writeAttributeDecls(UMLAttributeList &atpub, UMLAttributeList &atprot,
UMLAttributeList &atpriv, QTextStream &d)
{
writeAttributeDecl(Uml::Visibility::Public, atpub, d);
writeAttributeDecl(Uml::Visibility::Protected, atprot, d);
writeAttributeDecl(Uml::Visibility::Private, atpriv, d);
//TODO: export and package
}
void DWriter::writeAttributeMethods(UMLAttributeList &atpub, Uml::Visibility::Enum visibility, QTextStream &d)
{
if (atpub.count()==0) return;
writeProtectionMod(visibility, d);
for(UMLAttribute* at : atpub) {
QString fieldName = cleanName(at->name());
writeSingleAttributeAccessorMethods(
at->getTypeName(), QStringLiteral("m_") + fieldName, fieldName, at->doc(),
visibility, Uml::Changeability::Changeable, at->isStatic(), d);
}
}
void DWriter::writeComment(const QString &comment, const QString &myIndent,
QTextStream &d, bool dDocStyle)
{
if (dDocStyle) {
d << myIndent << "/**" << m_endl;
}
QStringList lines = comment.split(QStringLiteral("\n"));
if (lines.count() == 0) lines << comment;
for (int i = 0; i < lines.count(); ++i) {
QString tmp = lines[i];
while (tmp.count() > 77) {
int l = tmp.left(77).lastIndexOf(QLatin1Char(' '));
if (l < 1) l = tmp.indexOf(QLatin1Char(' '), 77);
if (l < 1 || l > tmp.count()) {
d << myIndent << (dDocStyle ? " * " : "// ") << tmp << m_endl;
break;
}
d << myIndent << (dDocStyle ? " * " : "// ") << tmp.left(l) << m_endl;
tmp = tmp.right(tmp.count() - l);
}
d << myIndent << (dDocStyle ? " * " : "// ") << tmp << m_endl;
}
if (dDocStyle) {
d << myIndent << " */" << m_endl;
}
}
void DWriter::writeDocumentation(QString header, QString body, QString end, QString indent, QTextStream &d)
{
d << indent << "/**" << m_endl;
if (!header.isEmpty())
d << formatDoc(header, indent + QStringLiteral(" * "));
if (!body.isEmpty())
d << formatDoc(body, indent + QStringLiteral(" * "));
if (!end.isEmpty())
{
QStringList lines = end.split(QStringLiteral("\n"));
for (int i= 0; i < lines.count(); ++i) {
d << formatDoc(lines[i], indent + QStringLiteral(" * "));
}
}
d << indent << " */" << m_endl;
}
void DWriter::writeAssociationDecls(UMLAssociationList associations, Uml::ID::Type id, QTextStream &d)
{
if (forceSections() || !associations.isEmpty())
{
bool printRoleA = false, printRoleB = false;
for(UMLAssociation *a : associations) {
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id)
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id)
printRoleA = true;
// First: we insert documentation for association IF it has either role AND some documentation (!)
if ((printRoleA || printRoleB) && !(a->doc().isEmpty()))
writeComment(a->doc(), m_indentation, d);
// print RoleB decl
if (printRoleB)
{
QString fieldClassName = cleanName(getUMLObjectName(a->getObject(Uml::RoleType::B)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::B), a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B), a->visibility(Uml::RoleType::B), d);
}
// print RoleA decl
if (printRoleA)
{
QString fieldClassName = cleanName(getUMLObjectName(a->getObject(Uml::RoleType::A)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::A), a->getMultiplicity(Uml::RoleType::A), a->getRoleDoc(Uml::RoleType::A), a->visibility(Uml::RoleType::A), d);
}
}
}
}
void DWriter::writeAssociationRoleDecl(QString fieldClassName,
QString roleName, QString multi,
QString doc, Uml::Visibility::Enum /*visib*/, QTextStream &d)
{
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared in the code
if (roleName.isEmpty()) return;
if (!doc.isEmpty()) {
writeComment(doc, m_indentation, d);
}
bool hasAccessors = true;
// declare the association based on whether it is this a single variable
// or a List (Vector). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$")))) {
d << m_indentation << fieldClassName << " ";
if (hasAccessors) d << "m_";
d << deCapitaliseFirstLetter(roleName) << ";";
} else {
d << m_indentation << fieldClassName << "[] ";
//TODO: templated containers
if (hasAccessors) d << "m_";
d << pluralize(deCapitaliseFirstLetter(roleName)) << ";";
// from here we could initialize default values, or put in an init() section
// of the constructors
}
// always put space between this and following decl, if any
writeBlankLine(d);
}
void DWriter::writeAssociationMethods (UMLAssociationList associations, UMLClassifier *thisClass, QTextStream &d)
{
if (forceSections() || !associations.isEmpty()) {
for(UMLAssociation *a : associations) {
// insert the methods to access the role of the other
// class in the code of this one
if (a->getObjectId(Uml::RoleType::A) == thisClass->id()) {
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::B).isEmpty()) {
QString fieldClassName = getUMLObjectName(a->getObject(Uml::RoleType::B));
writeAssociationRoleMethod(fieldClassName,
a->getRoleName(Uml::RoleType::B),
a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B),
a->visibility(Uml::RoleType::B),
a->changeability(Uml::RoleType::B), d);
}
}
if (a->getObjectId(Uml::RoleType::B) == thisClass->id()) {
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::A).isEmpty()) {
QString fieldClassName = getUMLObjectName(a->getObject(Uml::RoleType::A));
writeAssociationRoleMethod(fieldClassName, a->getRoleName(Uml::RoleType::A),
a->getMultiplicity(Uml::RoleType::A),
a->getRoleDoc(Uml::RoleType::A),
a->visibility(Uml::RoleType::A),
a->changeability(Uml::RoleType::A),
d);
}
}
}
}
}
void DWriter::writeAssociationRoleMethod (QString fieldClassName, QString roleName, QString multi,
QString description, Uml::Visibility::Enum visib, Uml::Changeability::Enum change,
QTextStream &d)
{
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$")))) {
QString fieldVarName = QStringLiteral("m_") + deCapitaliseFirstLetter(roleName);
writeSingleAttributeAccessorMethods(
fieldClassName, fieldVarName, roleName, description, visib, change, false, d);
} else {
QString fieldVarName = QStringLiteral("m_") + pluralize(deCapitaliseFirstLetter(roleName));
writeVectorAttributeAccessorMethods(
fieldClassName, fieldVarName, pluralize(roleName), description, visib, change, d);
}
}
void DWriter::writeVectorAttributeAccessorMethods (QString fieldClassName, QString fieldVarName,
QString fieldName, QString description,
Uml::Visibility::Enum visibility, Uml::Changeability::Enum changeType,
QTextStream &d)
{
Q_UNUSED(visibility);
fieldClassName = fixTypeName(fieldClassName);
QString fieldNameUP = unPluralize(fieldName);
QString fieldNameUC = Codegen_Utils::capitalizeFirstLetter(fieldNameUP);
// ONLY IF changeability is NOT Frozen
if (changeType != Uml::Changeability::Frozen) {
writeDocumentation(QStringLiteral("Adds a ") + fieldNameUP + QStringLiteral(" to the list of ") +
fieldName + QLatin1Char('.'), description, QString(), m_indentation, d);
d << m_indentation << "void add" << fieldNameUC << "(";
d << fieldClassName << " new" << fieldNameUC << ") {";
d << startline << m_indentation << fieldVarName << " ~= new" << fieldNameUC << ";";
d << startline << "}" << m_endl << m_endl;
}
// ONLY IF changeability is Changeable
if (changeType == Uml::Changeability::Changeable) {
writeDocumentation(QStringLiteral("Removes a ") + fieldNameUP + QStringLiteral(" from the list of ") +
fieldName + QLatin1Char('.'), description, QString(), m_indentation, d);
d << m_indentation << "void remove" << fieldNameUC << "(";
d << fieldClassName << " " << fieldNameUP << ") {" << startline;
d << m_indentation << "int idx = " << fieldVarName << ".length;" << startline;
d << m_indentation << "foreach(i, o; " << fieldVarName << ")" << startline;
d << m_indentation << m_indentation << "if (o && o == " << fieldNameUP << ") {" << startline;
d << m_indentation << m_indentation << m_indentation << "idx = i;" << startline;
d << m_indentation << m_indentation << m_indentation << "break;" << startline;
d << m_indentation << m_indentation << "}" << m_endl << startline;
d << m_indentation << fieldVarName << " = " << fieldVarName;
d << "[0..idx] ~ " << fieldVarName << "[idx..$];" << startline;
d << "}" << m_endl << m_endl;
}
// always allow getting the list of stuff
writeDocumentation(QStringLiteral("Returns the list of ") + fieldName + QLatin1Char('.'),
description, QStringLiteral("@return List of ") + fieldName + QLatin1Char('.'),
m_indentation, d);
d << m_indentation << fieldClassName << "[] get" << fieldName << "() {";
d << startline << m_indentation << "return " << fieldVarName << ";";
d << startline << "}" << m_endl << m_endl;
}
void DWriter::writeSingleAttributeAccessorMethods(QString fieldClassName,
QString fieldVarName, QString fieldName, QString description, Uml::Visibility::Enum /*visibility*/,
Uml::Changeability::Enum change, bool isFinal, QTextStream &d) {
fieldClassName = fixTypeName(fieldClassName);
QString fieldNameUC = Codegen_Utils::capitalizeFirstLetter(fieldName);
if (fieldName.left(2) == QStringLiteral("m_")) fieldName = fieldName.right(fieldName.count()-2);
// set method
if (change == Uml::Changeability::Changeable && !isFinal) {
writeDocumentation(QStringLiteral("Sets the value of ") + fieldName + QLatin1Char('.'), description,
QStringLiteral("@param new") + fieldNameUC + QStringLiteral(" The new value of ") + fieldName + QLatin1Char('.'),
m_indentation, d);
d << m_indentation << fieldClassName << " " << fieldName << "(";
d << fieldClassName << " new" << fieldNameUC << ") {";
d << startline << m_indentation << "return " << fieldVarName << " = new" << fieldNameUC << ";";
d << startline << "}" << m_endl << m_endl;
}
// get method
writeDocumentation(QStringLiteral("Returns the value of ") + fieldName + QLatin1Char('.'), description,
QStringLiteral("@return The value of ") + fieldName + QLatin1Char('.'),
m_indentation, d);
d << m_indentation << fieldClassName << " " << fieldName << "() {";
d << startline << m_indentation << "return " << fieldVarName << ";";
d << startline << "}" << m_endl << m_endl;
}
void DWriter::writeConstructor(UMLClassifier *c, QTextStream &d)
{
if (forceDoc())
{
d<<startline;
writeComment(QString(), m_indentation, d);
writeComment(QStringLiteral("Constructors"), m_indentation, d);
writeComment(QString(), m_indentation, d);
writeBlankLine(d);
}
// write the first constructor
QString className = cleanName(c->name());
d << m_indentation << "public this("<<") { }";
}
// IF the type is "string" we need to declare it as
// the D Object "String" (there is no string primitive in D).
// Same thing again for "bool" to "boolean"
QString DWriter::fixTypeName(const QString& string)
{
if (string.isEmpty())
return QStringLiteral("void");
if (string == QStringLiteral("string"))
return QStringLiteral("char[]");
if (string == QStringLiteral("unsigned short"))
return QStringLiteral("ushort");
if (string == QStringLiteral("unsigned int"))
return QStringLiteral("uint");
if (string == QStringLiteral("unsigned long"))
return QStringLiteral("ulong");
return string;
}
/**
* Return the default datatypes.
* (Overrides method from class CodeGenerator.)
* @return list of default datatypes
*/
QStringList DWriter::defaultDatatypes() const
{
QStringList l;
l << QStringLiteral("void")
<< QStringLiteral("bool")
<< QStringLiteral("byte")
<< QStringLiteral("ubyte")
<< QStringLiteral("short")
<< QStringLiteral("ushort")
<< QStringLiteral("int")
<< QStringLiteral("uint")
<< QStringLiteral("long")
<< QStringLiteral("ulong")
<< QStringLiteral("cent")
<< QStringLiteral("ucent")
<< QStringLiteral("float")
<< QStringLiteral("double")
<< QStringLiteral("real")
<< QStringLiteral("ifloat")
<< QStringLiteral("idouble")
<< QStringLiteral("ireal")
<< QStringLiteral("cfloat")
<< QStringLiteral("cdouble")
<< QStringLiteral("creal")
<< QStringLiteral("char")
<< QStringLiteral("wchar")
<< QStringLiteral("dchar")
<< QStringLiteral("string");
return l;
}
bool DWriter::compareDMethod(UMLOperation *op1, UMLOperation *op2)
{
if (op1 == nullptr || op2 == nullptr)
return false;
if (op1 == op2)
return true;
if (op1->name() != op2->name())
return false;
UMLAttributeList atl1 = op1->getParmList();
UMLAttributeList atl2 = op2->getParmList();
if (atl1.count() != atl2.count())
return false;
for (UMLAttributeListIt atl1It(atl1), atl2It(atl2); atl1It.hasNext() && atl2It.hasNext();) {
UMLAttribute* at1 = atl1It.next(), *at2 = atl2It.next();
if (at1->getTypeName() != at2->getTypeName())
return false;
}
return true;
}
bool DWriter::dMethodInList(UMLOperation *umlOp, UMLOperationList &opl)
{
for(UMLOperation* op : opl) {
if (DWriter::compareDMethod(op, umlOp)) {
return true;
}
}
return false;
}
void DWriter::getSuperImplementedOperations(UMLClassifier *c, UMLOperationList &yetImplementedOpList, UMLOperationList &toBeImplementedOpList, bool noClassInPath)
{
UMLClassifierList superClasses = c->findSuperClassConcepts();
for(UMLClassifier* classifier : superClasses) {
getSuperImplementedOperations(classifier, yetImplementedOpList, toBeImplementedOpList, (classifier->isInterface() && noClassInPath));
UMLOperationList opl = classifier->getOpList();
for(UMLOperation* op : opl) {
if (classifier->isInterface() && noClassInPath) {
if (!DWriter::dMethodInList(op, toBeImplementedOpList))
toBeImplementedOpList.append(op);
}
else
{
if (!DWriter::dMethodInList(op, yetImplementedOpList))
yetImplementedOpList.append(op);
}
}
}
}
void DWriter::getInterfacesOperationsToBeImplemented(UMLClassifier *c, UMLOperationList &opList)
{
UMLOperationList yetImplementedOpList;
UMLOperationList toBeImplementedOpList;
getSuperImplementedOperations(c, yetImplementedOpList, toBeImplementedOpList);
for(UMLOperation* op : toBeImplementedOpList) {
if (! DWriter::dMethodInList(op, yetImplementedOpList) && ! DWriter::dMethodInList(op, opList))
opList.append(op);
}
}
void DWriter::writeOperations(UMLClassifier *c, QTextStream &d)
{
UMLOperationList opl;
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
opl = c->getOpList();
if (! c->isInterface()) {
getInterfacesOperationsToBeImplemented(c, opl);
}
for(UMLOperation* op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default: //TODO: package, export
break;
}
}
// do people REALLY want these comments? Hmm.
/*
if (forceSections() || oppub.count())
{
writeComment("public operations", m_indentation, d);
writeBlankLine(d);
}
*/
if (oppub.count() > 0) {
writeProtectionMod(Uml::Visibility::Public, d);
writeOperations(oppub, d);
}
if (opprot.count() > 0) {
writeProtectionMod(Uml::Visibility::Protected, d);
writeOperations(opprot, d);
}
if (oppriv.count() > 0) {
writeProtectionMod(Uml::Visibility::Private, d);
writeOperations(oppriv, d);
}
}
void DWriter::writeOperations(UMLOperationList &oplist, QTextStream &d)
{
UMLAttributeList atl;
QString str;
// generate method decl for each operation given
for(UMLOperation* op : oplist) {
QString doc;
// write documentation
QString methodReturnType = fixTypeName(op->getTypeName());
//TODO: return type comment
if (methodReturnType != QStringLiteral("void")) {
doc += QStringLiteral("@return ") + methodReturnType + m_endl;
}
str = QString(); // reset for next method
if (op->isAbstract() && !isInterface) str += QStringLiteral("abstract ");
if (op->isStatic()) str += QStringLiteral("static ");
str += methodReturnType + QLatin1Char(' ') + cleanName(op->name()) + QLatin1Char('(');
atl = op->getParmList();
int i = atl.count();
int j = 0;
for (UMLAttributeListIt atlIt(atl); atlIt.hasNext(); ++j) {
UMLAttribute* at = atlIt.next();
QString typeName = fixTypeName(at->getTypeName());
QString atName = cleanName(at->name());
str += typeName + QLatin1Char(' ') + atName +
(!(at->getInitialValue().isEmpty()) ?
(QStringLiteral(" = ") + at->getInitialValue()) : QString())
+ ((j < i-1) ? QStringLiteral(", ") : QString());
doc += QStringLiteral("@param ") + atName + QLatin1Char(' ') + at->doc() + m_endl;
}
doc = doc.remove(doc.size() - 1, 1); // remove last '\n' of comment
str += QLatin1Char(')');
// method only gets a body IF it is not abstract
if (op->isAbstract() || isInterface)
str += QLatin1Char(';'); // terminate now
else {
str += startline + QLatin1Char('{') + m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
// empty method body - TODO: throw exception
}
else {
str += formatSourceCode(sourceCode, m_indentation + m_indentation);
}
str += m_indentation + QLatin1Char('}');
}
// write it out
writeDocumentation(QString(), op->doc(), doc, m_indentation, d);
d << m_indentation << str << m_endl << m_endl;
}
}
QString DWriter::fixInitialStringDeclValue(const QString& val, const QString& type)
{
QString value = val;
// check for strings only
if (!value.isEmpty() && type == QStringLiteral("String")) {
if (!value.startsWith(QLatin1Char('"')))
value.prepend(QLatin1Char('"'));
if (!value.endsWith(QLatin1Char('"')))
value.append(QLatin1Char('"'));
}
return value;
}
// methods like this _shouldn't_ be needed IF we properly did things thruought the code.
QString DWriter::getUMLObjectName(UMLObject *obj)
{
return (obj ? obj->name() : QStringLiteral("NULL"));
}
QString DWriter::deCapitaliseFirstLetter(const QString& str)
{
QString string = str;
string.replace(0, 1, string[0].toLower());
return string;
}
QString DWriter::pluralize(const QString& string)
{
return string + (string.right(1) == QStringLiteral("s") ? QStringLiteral("es") : QStringLiteral("s"));
}
QString DWriter::unPluralize(const QString& string)
{
// does not handle special cases liek datum -> data, etc.
if (string.count() > 2 && string.right(3) == QStringLiteral("ses")) {
return string.left(string.count() - 2);
}
if (string.right(1) == QStringLiteral("s")) {
return string.left(string.count() - 1);
}
return string;
}
void DWriter::writeBlankLine(QTextStream &d)
{
d << m_endl;
}
| 33,960
|
C++
|
.cpp
| 826
| 32.874092
| 198
| 0.602785
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,564
|
dcodegenerationpolicy.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodegenerationpolicy.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodegenerationpolicy.h"
// qt/kde includes
#include <kconfig.h>
// app includes
#include "dcodegenerationpolicypage.h"
#include "dcodegenerator.h"
#include "uml.h"
#include "umbrellosettings.h"
#include "optionstate.h"
/*
DCodeGenerationPolicy::DCodeGenerationPolicy(CodeGenerationPolicy *defaults)
: CodeGenerationPolicy(defaults)
{
init();
setDefaults(defaults, false);
}
*/
/**
* Constructor.
*/
DCodeGenerationPolicy::DCodeGenerationPolicy()
// : CodeGenerationPolicy()
{
m_commonPolicy = UMLApp::app()->commonPolicy();
init();
}
/**
* Destructor.
*/
DCodeGenerationPolicy::~DCodeGenerationPolicy()
{
}
/**
* Set the value of m_autoGenerateAttribAccessors
* @param var the new value
*/
void DCodeGenerationPolicy::setAutoGenerateAttribAccessors(bool var)
{
Settings::optionState().codeGenerationState.dCodeGenerationState.autoGenerateAttributeAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Set the value of m_autoGenerateAssocAccessors
* @param var the new value
*/
void DCodeGenerationPolicy::setAutoGenerateAssocAccessors(bool var)
{
Settings::optionState().codeGenerationState.dCodeGenerationState.autoGenerateAssocAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Get the value of m_autoGenerateAttribAccessors
* @return the value of m_autoGenerateAttribAccessors
*/
bool DCodeGenerationPolicy::getAutoGenerateAttribAccessors()
{
return Settings::optionState().codeGenerationState.dCodeGenerationState.autoGenerateAttributeAccessors;
}
/**
* Get the value of m_autoGenerateAssocAccessors
* @return the value of m_autoGenerateAssocAccessors
*/
bool DCodeGenerationPolicy::getAutoGenerateAssocAccessors()
{
return Settings::optionState().codeGenerationState.dCodeGenerationState.autoGenerateAssocAccessors;
}
/**
* Set the defaults for this code generator from the passed generator.
* @param clone the code gen policy ext object
* @param emitUpdateSignal flag whether to emit the update signal
*/
void DCodeGenerationPolicy::setDefaults (CodeGenPolicyExt * clone, bool emitUpdateSignal)
{
DCodeGenerationPolicy * jclone;
if (!clone)
return;
// NOW block signals for d param setting
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
// now do d-specific stuff IF our clone is also a DCodeGenerationPolicy object
if((jclone = dynamic_cast<DCodeGenerationPolicy*>(clone)))
{
setAutoGenerateAttribAccessors(jclone->getAutoGenerateAttribAccessors());
setAutoGenerateAssocAccessors(jclone->getAutoGenerateAssocAccessors());
}
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal) {
m_commonPolicy->emitModifiedCodeContentSig();
}
}
/**
* Set the defaults from a config file for this code generator from the passed KConfig pointer.
* @param emitUpdateSignal flag whether to emit the update signal
*/
void DCodeGenerationPolicy::setDefaults(bool emitUpdateSignal)
{
// call method at the common policy to init default stuff
m_commonPolicy->setDefaults(false);
// NOW block signals (because call to super-class method will leave value at "true")
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
// now do d specific stuff
setAutoGenerateAttribAccessors(UmbrelloSettings::autoGenerateAttributeAccessorsD());
setAutoGenerateAssocAccessors(UmbrelloSettings::autoGenerateAssocAccessorsD());
/*
CodeGenerator *codegen = UMLApp::app()->getGenerator();
DCodeGenerator *dcodegen = dynamic_cast<DCodeGenerator*>(codegen);
if (dcodegen) {
bool mkant = UmbrelloSettings::buildANTDocumentD();
dcodegen->setCreateANTBuildFile(mkant);
}*/
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal) {
m_commonPolicy->emitModifiedCodeContentSig();
}
}
/**
* Create a new dialog interface for this object.
* @param parent the parent widget
* @param name name of policy page
* @return dialog object
*/
CodeGenerationPolicyPage * DCodeGenerationPolicy::createPage (QWidget *parent, const char *name)
{
return new DCodeGenerationPolicyPage (parent, name, this);
}
/**
* Initialisation routine.
*/
void DCodeGenerationPolicy::init()
{
blockSignals(true);
Settings::OptionState optionState = Settings::optionState();
setAutoGenerateAttribAccessors(optionState.codeGenerationState.dCodeGenerationState.autoGenerateAttributeAccessors);
setAutoGenerateAssocAccessors(optionState.codeGenerationState.dCodeGenerationState.autoGenerateAssocAccessors);
blockSignals(false);
}
| 5,159
|
C++
|
.cpp
| 145
| 32.358621
| 120
| 0.772116
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,565
|
dcodegenerationpolicypage.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodegenerationpolicypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodegenerationpolicypage.h"
// app includes
#include "uml.h"
// kde includes
#include <KLocalizedString>
DCodeGenerationPolicyPage::DCodeGenerationPolicyPage(QWidget *parent, const char *name, DCodeGenerationPolicy * policy)
: CodeGenerationPolicyPage(parent, name, policy)
{
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
form = new DCodeGenerationFormBase(this);
form->m_SelectCommentStyle->setCurrentIndex((int)(commonPolicy->getCommentStyle()));
form->m_generateConstructors->setChecked(commonPolicy->getAutoGenerateConstructors());
form->m_generateAttribAccessors->setChecked(policy->getAutoGenerateAttribAccessors());
form->m_generateAssocAccessors->setChecked(policy->getAutoGenerateAssocAccessors());
form->m_accessorScopeCB->setCurrentIndex(commonPolicy->getAttributeAccessorScope());
form->m_assocFieldScopeCB->setCurrentIndex(commonPolicy->getAssociationFieldScope());
/**
* @todo unclean - CreateANTBuildFile attribute should be in d policy
CodeGenerator *codegen = UMLApp::app()->getGenerator();
DCodeGenerator *dcodegen = dynamic_cast<DCodeGenerator*>(codegen);
if (dcodegen)
form->m_makeANTDocumentCheckBox->setChecked(dcodegen->getCreateANTBuildFile());
*/
}
DCodeGenerationPolicyPage::~DCodeGenerationPolicyPage()
{
}
void DCodeGenerationPolicyPage::apply()
{
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
DCodeGenerationPolicy * parent = (DCodeGenerationPolicy*) m_parentPolicy;
// block signals so we don't cause too many update content calls to code documents
commonPolicy->blockSignals(true);
commonPolicy->setCommentStyle((CodeGenerationPolicy::CommentStyle) form->m_SelectCommentStyle->currentIndex());
commonPolicy->setAttributeAccessorScope(Uml::Visibility::fromInt(form->m_accessorScopeCB->currentIndex()));
commonPolicy->setAssociationFieldScope(Uml::Visibility::fromInt(form->m_assocFieldScopeCB->currentIndex()));
commonPolicy->setAutoGenerateConstructors(form->m_generateConstructors->isChecked());
parent->setAutoGenerateAttribAccessors(form->m_generateAttribAccessors->isChecked());
parent->setAutoGenerateAssocAccessors(form->m_generateAssocAccessors->isChecked());
/**
* @todo unclean - CreateANTBuildFile attribute should be in d policy
CodeGenerator *codegen = UMLApp::app()->getGenerator();
DCodeGenerator *dcodegen = dynamic_cast<DCodeGenerator*>(codegen);
if (dcodegen)
dcodegen->setCreateANTBuildFile(form->m_makeANTDocumentCheckBox->isChecked());
*/
commonPolicy->blockSignals(false);
// now send out modified code content signal
commonPolicy->emitModifiedCodeContentSig();
}
| 2,964
|
C++
|
.cpp
| 56
| 48.696429
| 119
| 0.778776
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,566
|
dcodegenerator.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodegenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodegenerator.h"
// local includes
#include "codeviewerdialog.h"
#include "dcodecomment.h"
#include "uml.h"
// kde includes
#include <kconfig.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QRegularExpression>
/**
* Constructor.
*/
DCodeGenerator::DCodeGenerator()
: AdvancedCodeGenerator()
{
// load Classifier documents from parent document
//initFromParentDocument();
connectSlots();
}
/**
* Destructor.
*/
DCodeGenerator::~DCodeGenerator()
{
}
/**
* Return our language.
* @return language identifier
*/
Uml::ProgrammingLanguage::Enum DCodeGenerator::language() const
{
return Uml::ProgrammingLanguage::D;
}
/**
* Get the editing dialog for this code document.
* In the D version, we make the ANT build file also available.
*/
CodeViewerDialog * DCodeGenerator::getCodeViewerDialog (QWidget* parent, CodeDocument *doc,
Settings::CodeViewerState & state)
{
CodeViewerDialog *dialog = new CodeViewerDialog(parent, doc, state);
return dialog;
}
/**
* Utility function for getting the d code generation policy.
* @return generation policy object
*/
DCodeGenerationPolicy * DCodeGenerator::getDPolicy()
{
return dynamic_cast<DCodeGenerationPolicy*>(UMLApp::app()->policyExt());
}
/**
* A utility method to get the dCodeGenerationPolicy()->getAutoGenerateAttribAccessors() value.
* @return value of flag
*/
bool DCodeGenerator::getAutoGenerateAttribAccessors ()
{
return getDPolicy()->getAutoGenerateAttribAccessors ();
}
/**
* A utility method to get the dCodeGenerationPolicy()->getAutoGenerateAssocAccessors() value.
* @return value of flag
*/
bool DCodeGenerator::getAutoGenerateAssocAccessors ()
{
return getDPolicy()->getAutoGenerateAssocAccessors ();
}
/**
* Get the list variable class name to use. For D, we have set this to "Vector".
* @return name of list field class
*/
QString DCodeGenerator::getListFieldClassName ()
{
return QString(QStringLiteral("Vector"));
}
/**
* General purpose function we may reuse for all types of D code documents.
* @param item the item to change
* @return the changed item
*/
QString DCodeGenerator::capitalizeFirstLetter(const QString &item)
{
// we could lowercase everything tostart and then capitalize? Nah, it would
// screw up formatting like getMyRadicalVariable() to getMyradicalvariable(). Bah.
QChar firstChar = item.at(0);
return firstChar.toUpper() + item.mid(1);
}
/**
* IF the type is "string" we need to declare it as
* the D Object "String" (there is no string primitive in D).
* Same thing again for "bool" to "boolean".
* @param item the item to change
* @return the changed item
*/
QString DCodeGenerator::fixTypeName(const QString &item)
{
if (item.isEmpty() || item.contains(QRegularExpression(QStringLiteral("^\\s+$"))))
return QStringLiteral("void");
if (item == QStringLiteral("string"))
return QStringLiteral("char[]");
return cleanName(item);
}
/**
* Create a new classifier code document.
* @param classifier the UML classifier
* @return the created classifier code document object
*/
CodeDocument * DCodeGenerator::newClassifierCodeDocument (UMLClassifier * classifier)
{
DClassifierCodeDocument * doc = new DClassifierCodeDocument(classifier);
doc->initCodeClassFields();
return doc;
}
/**
* Adds D's primitives as datatypes.
* @return the list of primitive datatypes
*/
QStringList DCodeGenerator::defaultDatatypes() const
{
QStringList l;
l << QStringLiteral("void")
<< QStringLiteral("bool")
<< QStringLiteral("byte")
<< QStringLiteral("ubyte")
<< QStringLiteral("short")
<< QStringLiteral("ushort")
<< QStringLiteral("int")
<< QStringLiteral("uint")
<< QStringLiteral("long")
<< QStringLiteral("ulong")
<< QStringLiteral("cent")
<< QStringLiteral("ucent")
<< QStringLiteral("float")
<< QStringLiteral("double")
<< QStringLiteral("real")
<< QStringLiteral("ifloat")
<< QStringLiteral("idouble")
<< QStringLiteral("ireal")
<< QStringLiteral("cfloat")
<< QStringLiteral("cdouble")
<< QStringLiteral("creal")
<< QStringLiteral("char")
<< QStringLiteral("wchar")
<< QStringLiteral("dchar")
<< QStringLiteral("string");
return l;
}
/**
* Get list of reserved keywords.
* @return the list of reserved keywords
*/
QStringList DCodeGenerator::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("abstract")
<< QStringLiteral("alias")
<< QStringLiteral("align")
<< QStringLiteral("asm")
<< QStringLiteral("assert")
<< QStringLiteral("auto")
<< QStringLiteral("body")
<< QStringLiteral("bool")
<< QStringLiteral("break")
<< QStringLiteral("byte")
<< QStringLiteral("case")
<< QStringLiteral("cast")
<< QStringLiteral("catch")
<< QStringLiteral("cdouble")
<< QStringLiteral("cent")
<< QStringLiteral("cfloat")
<< QStringLiteral("char")
<< QStringLiteral("class")
<< QStringLiteral("const")
<< QStringLiteral("continue")
<< QStringLiteral("creal")
<< QStringLiteral("dchar")
<< QStringLiteral("debug")
<< QStringLiteral("default")
<< QStringLiteral("delegate")
<< QStringLiteral("delete")
<< QStringLiteral("deprecated")
<< QStringLiteral("do")
<< QStringLiteral("double")
<< QStringLiteral("else")
<< QStringLiteral("enum")
<< QStringLiteral("export")
<< QStringLiteral("extern")
<< QStringLiteral("false")
<< QStringLiteral("final")
<< QStringLiteral("finally")
<< QStringLiteral("float")
<< QStringLiteral("for")
<< QStringLiteral("foreach")
<< QStringLiteral("foreach_reverse")
<< QStringLiteral("function")
<< QStringLiteral("goto")
<< QStringLiteral("idouble")
<< QStringLiteral("if")
<< QStringLiteral("ifloat")
<< QStringLiteral("import")
<< QStringLiteral("in")
<< QStringLiteral("inout")
<< QStringLiteral("int")
<< QStringLiteral("interface")
<< QStringLiteral("invariant")
<< QStringLiteral("ireal")
<< QStringLiteral("is")
<< QStringLiteral("lazy")
<< QStringLiteral("long")
<< QStringLiteral("macro")
<< QStringLiteral("mixin")
<< QStringLiteral("module")
<< QStringLiteral("msg")
<< QStringLiteral("new")
<< QStringLiteral("null")
<< QStringLiteral("out")
<< QStringLiteral("override")
<< QStringLiteral("package")
<< QStringLiteral("pragma")
<< QStringLiteral("private")
<< QStringLiteral("protected")
<< QStringLiteral("public")
<< QStringLiteral("real")
<< QStringLiteral("ref")
<< QStringLiteral("return")
<< QStringLiteral("scope")
<< QStringLiteral("short")
<< QStringLiteral("static")
<< QStringLiteral("struct")
<< QStringLiteral("super")
<< QStringLiteral("switch")
<< QStringLiteral("synchronized")
<< QStringLiteral("template")
<< QStringLiteral("this")
<< QStringLiteral("throw")
<< QStringLiteral("true")
<< QStringLiteral("try")
<< QStringLiteral("typedef")
<< QStringLiteral("typeid")
<< QStringLiteral("typeof")
<< QStringLiteral("ubyte")
<< QStringLiteral("ucent")
<< QStringLiteral("uint")
<< QStringLiteral("ulong")
<< QStringLiteral("union")
<< QStringLiteral("unittest")
<< QStringLiteral("ushort")
<< QStringLiteral("version")
<< QStringLiteral("void")
<< QStringLiteral("volatile")
<< QStringLiteral("wchar")
<< QStringLiteral("while")
<< QStringLiteral("with");
}
return keywords;
}
| 8,553
|
C++
|
.cpp
| 266
| 26.067669
| 95
| 0.638553
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,567
|
dclassifiercodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dclassifiercodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dclassifiercodedocument.h"
// local includes
#include "dcodegenerator.h"
#include "dcodecomment.h"
#include "dclassdeclarationblock.h"
#include "dcodeclassfielddeclarationblock.h"
#include "codegen_utils.h"
#include "classifier.h"
#include "codegenerationpolicy.h"
#include "debug_utils.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
DEBUG_REGISTER(DClassifierCodeDocument)
/**
* Constructor.
*/
DClassifierCodeDocument::DClassifierCodeDocument(UMLClassifier * classifier)
: ClassifierCodeDocument(classifier)
{
init();
}
/**
* Empty Destructor.
*/
DClassifierCodeDocument::~DClassifierCodeDocument()
{
}
// Make it easier on ourselves
DCodeGenerationPolicy * DClassifierCodeDocument::getDPolicy()
{
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe);
return policy;
}
// /**
// * Get the dialog widget which allows user interaction with the object parameters.
// * @return CodeDocumentDialog
// */
/*
CodeDocumentDialog DClassifierCodeDocument::getDialog()
{
}
*/
bool DClassifierCodeDocument::forceDoc()
{
return UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
}
// We overwritten by D language implementation to get lowercase path
QString DClassifierCodeDocument::getPath() const
{
QString path = getPackage();
// Replace all white spaces with blanks
path = path.simplified();
// Replace all blanks with underscore
path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
path.replace(QRegularExpression(QStringLiteral("\\.")),QStringLiteral("/"));
path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/"));
path = path.toLower();
return path;
}
QString DClassifierCodeDocument::getDClassName(const QString &name) const
{
return Codegen_Utils::capitalizeFirstLetter(CodeGenerator::cleanName(name));
}
// Initialize this d classifier code document
void DClassifierCodeDocument::init()
{
setFileExtension(QStringLiteral(".d"));
//initCodeClassFields(); // this is dubious because it calls down to
// CodeGenFactory::newCodeClassField(this)
// but "this" is still in construction at that time.
classDeclCodeBlock = nullptr;
operationsBlock = nullptr;
constructorBlock = nullptr;
// this will call updateContent() as well as other things that sync our document.
synchronize();
}
/**
* Add a code operation to this d classifier code document.
* In the vanilla version, we just tack all operations on the end
* of the document.
* @param op the code operation
* @return bool which is true IF the code operation was added successfully
*/
bool DClassifierCodeDocument::addCodeOperation(CodeOperation * op)
{
if (!op->getParentOperation()->isLifeOperation())
return operationsBlock->addTextBlock(op);
else
return constructorBlock->addTextBlock(op);
}
/**
* Need to overwrite this for d since we need to pick up the
* d class declaration block.
* Sigh. NOT optimal. The only reason that we need to have this
* is so we can create the DClassDeclarationBlock.
* would be better if we could create a handler interface that each
* codeblock used so all we have to do here is add the handler
* for "dclassdeclarationblock".
*/
void DClassifierCodeDocument::loadChildTextBlocksFromNode(QDomElement & root)
{
QDomNode tnode = root.firstChild();
QDomElement telement = tnode.toElement();
bool loadCheckForChildrenOK = false;
while (!telement.isNull()) {
QString nodeName = telement.tagName();
if (nodeName == QStringLiteral("textblocks")) {
QDomNode node = telement.firstChild();
QDomElement element = node.toElement();
// if there is nothing to begin with, then we don't worry about it
loadCheckForChildrenOK = element.isNull() ? true : false;
while (!element.isNull()) {
QString name = element.tagName();
if (name == QStringLiteral("codecomment")) {
CodeComment * block = new DCodeComment(this);
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("loadFromXMI : unable to add codeComment");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeaccessormethod") ||
name == QStringLiteral("ccfdeclarationcodeblock")) {
QString acctag = element.attribute(QStringLiteral("tag"));
// search for our method in the
TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
if (!tb || !addTextBlock(tb)) {
logError0("loadFromXMI : unable to add codeclassfield child method");
// DON'T delete
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblock")) {
CodeBlock * block = newCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("loadFromXMI : unable to add codeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblockwithcomments")) {
CodeBlockWithComments * block = newCodeBlockWithComments();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("loadFromXMI : unable to add codeBlockwithcomments");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("header")) {
// do nothing.. this is treated elsewhere
} else if (name == QStringLiteral("hierarchicalcodeblock")) {
HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("Unable to add hierarchicalcodeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeoperation")) {
// find the code operation by id
QString id = element.attribute(QStringLiteral("parent_id"), QStringLiteral("-1"));
UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
UMLOperation * op = obj->asUMLOperation();
if (op) {
CodeOperation * block = new DCodeOperation(this, op);
block->loadFromXMI(element);
if (addTextBlock(block)) {
loadCheckForChildrenOK= true;
} else {
logError0("Unable to add codeoperation");
block->deleteLater();
}
} else {
logError0("Unable to find operation create codeoperation");
}
} else if (name == QStringLiteral("dclassdeclarationblock")) {
DClassDeclarationBlock * block = getClassDecl();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("Unable to add d code declaration block");
// DON'T delete.
// block->deleteLater();
} else {
loadCheckForChildrenOK= true;
}
} else {
logDebug1("loadChildTextBlocksFromNode: Got strange tag in text block stack: %1, ignoring",
name);
}
node = element.nextSibling();
element = node.toElement();
}
break;
}
tnode = telement.nextSibling();
telement = tnode.toElement();
}
if (!loadCheckForChildrenOK)
{
logWarn1("loadChildTextBlocksFromNode : unable to initialize any child blocks in doc: %1", getFileName());
}
}
DClassDeclarationBlock * DClassifierCodeDocument::getClassDecl()
{
if (!classDeclCodeBlock)
{
classDeclCodeBlock = new DClassDeclarationBlock (this);
classDeclCodeBlock->updateContent();
classDeclCodeBlock->setTag(QStringLiteral("ClassDeclBlock"));
}
return classDeclCodeBlock;
}
/**
* Reset/clear our inventory of textblocks in this document.
*/
void DClassifierCodeDocument::resetTextBlocks()
{
// all special pointers to text blocks need to be zero'd out
operationsBlock = nullptr;
constructorBlock = nullptr;
classDeclCodeBlock = nullptr;
// now do traditional release of text blocks.
ClassifierCodeDocument::resetTextBlocks();
}
// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we reasonably will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void DClassifierCodeDocument::updateContent()
{
// Gather info on the various fields and parent objects of this class...
UMLClassifier * c = getParentClassifier();
Q_ASSERT(c != nullptr);
CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy();
CodeGenPolicyExt * pe = UMLApp::app()->policyExt();
DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe);
// first, set the global flag on whether or not to show classfield info
// This depends on whether or not we have attribute/association classes
const CodeClassFieldList * cfList = getCodeClassFieldList();
CodeClassFieldList::const_iterator it = cfList->begin();
CodeClassFieldList::const_iterator end = cfList->end();
for (; it != end; ++it) {
CodeClassField * field = *it;
if (field->parentIsAttribute())
field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors());
else
field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors());
}
// attribute-based ClassFields
// we do it this way to have the static fields sorted out from regular ones
CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true);
CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false);
// association-based ClassFields
// don't care if they are static or not..all are lumped together
CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation);
CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation);
CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition);
bool isInterface = parentIsInterface();
bool hasOperationMethods = false;
UMLOperationList list = c->getOpList();
hasOperationMethods = ! list.isEmpty();
QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time
//
// START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
//
//
// PACKAGE CODE BLOCK
//
QString pkgs = getPackage();
pkgs.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("."));
QString packageText = getPackage().isEmpty() ? QString() : QString(QStringLiteral("package ")+pkgs+QLatin1Char(';')+endLine);
CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("packages"), packageText, QString(), 0, false);
if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated)
pblock->setWriteOutText(false);
else
pblock->setWriteOutText(true);
// IMPORT CODEBLOCK
//
// Q: Why all utils? Aren't just List and Vector the only classes we are using?
// A: doesn't matter at all; it is more readable to just include '*' and d compilers
// don't slow down or anything. (TZ)
QString importStatement;
if (hasObjectVectorClassFields())
importStatement.append(QStringLiteral("import d.util.*;"));
//only import classes in a different package from this class
UMLPackageList imports;
QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages
CodeGenerator::findObjectsRelated(c, imports);
for (UMLPackageListIt importsIt(imports); importsIt.hasNext();) {
UMLPackage *con = importsIt.next();
// NO (default) datatypes in the import statement.. use defined
// ones whould be possible, but no idea how to do that...at least for now.
// Dynamic casting is slow..not an optimal way to do this.
if (!packageMap.contains(con) && !con->isUMLDatatype())
{
packageMap.insert(con, con->package());
// now, we DON'T need to import classes that are already in our own package
// (that is, IF a package is specified). Otherwise, we should have a declaration.
if (con->package() != c->package() ||
(c->package().isEmpty() && con->package().isEmpty()))
{
importStatement.append(endLine+QStringLiteral("import "));
if (!con->package().isEmpty())
importStatement.append(con->package()+QLatin1Char('.'));
importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';'));
}
}
}
// now, add/update the imports codeblock
CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("imports"), importStatement, QString(), 0, false);
if (importStatement.isEmpty() && iblock->contentType() == CodeBlock::AutoGenerated)
iblock->setWriteOutText(false);
else
iblock->setWriteOutText(true);
// CLASS DECLARATION BLOCK
//
// get the declaration block. If it is not already present, add it too
DClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl();
addTextBlock(myClassDeclCodeBlock); // note: wont add if already present
// NOW create document in sections..
// now we want to populate the body of our class
// our layout is the following general groupings of code blocks:
// start d classifier document
// header comment
// package code block
// import code block
// class declaration
// section:
// - class field declaration section comment
// - class field declarations (0+ codeblocks)
// section:
// - methods section comment
// sub-section: constructor ops
// - constructor method section comment
// - constructor methods (0+ codeblocks)
// sub-section: accessors
// - accessor method section comment
// - static accessor methods (0+ codeblocks)
// - non-static accessor methods (0+ codeblocks)
// sub-section: non-constructor ops
// - operation method section comment
// - operations (0+ codeblocks)
// end class declaration
// end d classifier document
// Q: Why use the more complicated scheme of arranging code blocks within codeblocks?
// A: This will allow us later to preserve the format of our document so that if
// codeblocks are added, they may be easily added in the correct place, rather than at
// the end of the document, or by using a difficult algorithm to find the location of
// the last appropriate code block sibling (which may not exist.. for example user adds
// a constructor operation, but there currently are no constructor code blocks
// within the document).
//
// * CLASS FIELD declaration section
//
// get/create the field declaration code block
HierarchicalCodeBlock * fieldDeclBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("fieldsDecl"), QStringLiteral("Fields"), 1);
// Update the comment: we only set comment to appear under the following conditions
CodeComment * fcomment = fieldDeclBlock->getComment();
if (isInterface || (!forceDoc() && !hasClassFields()))
fcomment->setWriteOutText(false);
else
fcomment->setWriteOutText(true);
// now actually declare the fields within the appropriate HCodeBlock
declareClassFields(staticAttribClassFields, fieldDeclBlock);
declareClassFields(attribClassFields, fieldDeclBlock);
declareClassFields(plainAssocClassFields, fieldDeclBlock);
declareClassFields(aggregationClassFields, fieldDeclBlock);
declareClassFields(compositionClassFields, fieldDeclBlock);
//
// METHODS section
//
// get/create the method codeblock
HierarchicalCodeBlock * methodsBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("methodsBlock"), QStringLiteral("Methods"), 1);
// Update the section comment
CodeComment * methodsComment = methodsBlock->getComment();
// set conditions for showing this comment
if (!forceDoc() && !hasClassFields() && !hasOperationMethods)
methodsComment->setWriteOutText(false);
else
methodsComment->setWriteOutText(true);
// METHODS sub-section : constructor methods
//
// get/create the constructor codeblock
HierarchicalCodeBlock * constBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructorMethods"), QStringLiteral("Constructors"), 1);
constructorBlock = constBlock; // record this codeblock for later, when operations are updated
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * constComment = constBlock->getComment();
CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy();
if (!forceDoc() && (isInterface || !pol->getAutoGenerateConstructors()))
constComment->setWriteOutText(false);
else
constComment->setWriteOutText(true);
// add/get the empty constructor
QString DClassName = getDClassName(c->name());
QString emptyConstStatement = QStringLiteral("public ")+DClassName+QStringLiteral(" () { }");
CodeBlockWithComments * emptyConstBlock =
constBlock->addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("emptyconstructor"), emptyConstStatement, QStringLiteral("Empty Constructor"), 1, false);
// Now, as an additional condition we only show the empty constructor block
// IF it was desired to be shown
if (parentIsClass() && pol->getAutoGenerateConstructors())
emptyConstBlock->setWriteOutText(true);
else
emptyConstBlock->setWriteOutText(false);
// METHODS subsection : ACCESSOR METHODS
//
// get/create the accessor codeblock
HierarchicalCodeBlock * accessorBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * accessComment = accessorBlock->getComment();
if (!forceDoc() && !hasClassFields())
accessComment->setWriteOutText(false);
else
accessComment->setWriteOutText(true);
// now, 2 sub-sub sections in accessor block
// add/update accessor methods for attributes
HierarchicalCodeBlock * staticAccessors = accessorBlock->getHierarchicalCodeBlock(QStringLiteral("staticAccessorMethods"), QString(), 1);
staticAccessors->getComment()->setWriteOutText(false); // never write block comment
staticAccessors->addCodeClassFieldMethods(staticAttribClassFields);
staticAccessors->addCodeClassFieldMethods(attribClassFields);
// add/update accessor methods for associations
HierarchicalCodeBlock * regularAccessors = accessorBlock->getHierarchicalCodeBlock(QStringLiteral("regularAccessorMethods"), QString(), 1);
regularAccessors->getComment()->setWriteOutText(false); // never write block comment
regularAccessors->addCodeClassFieldMethods(plainAssocClassFields);
regularAccessors->addCodeClassFieldMethods(aggregationClassFields);
regularAccessors->addCodeClassFieldMethods(compositionClassFields);
// METHODS subsection : Operation methods (which arent constructors)
//
// get/create the operations codeblock
operationsBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * ocomment = operationsBlock->getComment();
if (!forceDoc() && !hasOperationMethods)
ocomment->setWriteOutText(false);
else
ocomment->setWriteOutText(true);
}
| 21,815
|
C++
|
.cpp
| 452
| 39.873894
| 163
| 0.670458
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,568
|
dclassdeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dclassdeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "dclassdeclarationblock.h"
#include "dcodegenerator.h"
#include "dcodegenerationpolicy.h"
#include "dcodedocumentation.h"
#include "model_utils.h"
#include "uml.h"
DClassDeclarationBlock::DClassDeclarationBlock
(DClassifierCodeDocument * parentDoc, const QString &startText, const QString &endText, const QString &comment)
: OwnedHierarchicalCodeBlock(parentDoc->getParentClassifier(), parentDoc, startText, endText, comment)
{
init(parentDoc, comment);
}
DClassDeclarationBlock::~DClassDeclarationBlock ()
{
}
void DClassDeclarationBlock::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
void DClassDeclarationBlock::setAttributesFromObject (TextBlock * obj)
{
HierarchicalCodeBlock::setAttributesFromObject(obj);
}
void DClassDeclarationBlock::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("dclassdeclarationblock"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
void DClassDeclarationBlock::updateContent ()
{
DClassifierCodeDocument *parentDoc = dynamic_cast<DClassifierCodeDocument*>(getParentDocument());
UMLClassifier *c = parentDoc->getParentClassifier();
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
QString endLine = commonPolicy->getNewLineEndingChars();
bool isInterface = parentDoc->parentIsInterface(); // a little shortcut
QString DClassName = parentDoc->getDClassName(c->name());
// COMMENT
getComment()->setText(
(isInterface ? QStringLiteral("Interface ") : QStringLiteral("Class ")) +
DClassName + endLine + c->doc());
bool forceDoc = commonPolicy->getCodeVerboseDocumentComments();
getComment()->setWriteOutText(forceDoc || !c->doc().isEmpty());
/*
* Class declaration
*
* (private) class foo : class1, ..., classN, interface1, ..., interfaceN {
* a b c d e f g
*/
QString startText;
// (a) visibility modifier
switch(c->visibility()) {
case Uml::Visibility::Private: startText += QStringLiteral("private "); break;
default: break;
}
// (b) keyword
if (isInterface) {
startText += QStringLiteral("interface ");
} else {
if (c->isAbstract()) {
startText += QStringLiteral("abstract ");
}
startText += QStringLiteral("class ");
}
// (c) class name
startText += DClassName;
// (d) inheritances
UMLClassifierList superclasses =
c->findSuperClassConcepts(UMLClassifier::CLASS);
UMLClassifierList superinterfaces =
c->findSuperClassConcepts(UMLClassifier::INTERFACE);
int count = superclasses.count() + superinterfaces.count();
if (count > 0) startText += QStringLiteral(" : ");
// (e) base classes
for(UMLClassifier* classifier : superclasses) {
startText += parentDoc->cleanName(classifier->name());
count--;
if (count>0) startText += QStringLiteral(", ");
}
// (f) interfaces
for(UMLClassifier* classifier : superinterfaces) {
startText += parentDoc->cleanName(classifier->name());
count--;
if (count>0) startText += QStringLiteral(", ");
}
// (g) block start
startText += QStringLiteral(" {");
setStartText(startText);
}
void DClassDeclarationBlock::init (DClassifierCodeDocument *parentDoc, const QString &comment)
{
setComment(new DCodeDocumentation(parentDoc));
getComment()->setText(comment);
setEndText(QStringLiteral("}"));
}
| 3,801
|
C++
|
.cpp
| 100
| 33
| 113
| 0.696424
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,569
|
dcodeaccessormethod.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodeaccessormethod.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodeaccessormethod.h"
// local includes
#include "attribute.h"
#include "codegenerator.h"
#include "codegenerationpolicy.h"
#include "codegen_utils.h"
#include "classifiercodedocument.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
#include "dclassifiercodedocument.h"
#include "dcodegenerationpolicy.h"
#include "dcodeclassfield.h"
#include "dcodedocumentation.h"
// qt/kde includes
#include <QXmlStreamWriter>
DCodeAccessorMethod::DCodeAccessorMethod (CodeClassField * field, CodeAccessorMethod::AccessorType type)
: CodeAccessorMethod (field)
{
setType(type);
// lets use full-blown comment
DClassifierCodeDocument* jccd = dynamic_cast<DClassifierCodeDocument*>(field->getParentDocument());
setComment(new DCodeDocumentation(jccd));
}
DCodeAccessorMethod::~DCodeAccessorMethod ()
{
}
void DCodeAccessorMethod::setAttributesOnNode (QXmlStreamWriter& writer)
{
// set super-class attributes
CodeAccessorMethod::setAttributesOnNode(writer);
// set local attributes now
}
void DCodeAccessorMethod::setAttributesFromNode(QDomElement & root)
{
// set attributes from superclass method the XMI
CodeAccessorMethod::setAttributesFromNode(root);
// load local stuff
}
void DCodeAccessorMethod::updateContent()
{
CodeClassField * parentField = getParentClassField();
DCodeClassField * dfield = dynamic_cast<DCodeClassField*>(parentField);
QString fieldName = dfield->getFieldName();
QString text;
switch(getType()) {
case CodeAccessorMethod::ADD:
{
int maxOccurs = dfield->maximumListOccurances();
QString fieldType = dfield->getTypeName();
QString indent = getIndentation();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
if(maxOccurs > 0)
text += QStringLiteral("if (") + fieldName + QStringLiteral(".size() < ")+ QString::number(maxOccurs) + QStringLiteral(") {") + endLine + indent;
text += fieldName + QStringLiteral(".add(value);");
if(maxOccurs > 0)
{
text += endLine + QStringLiteral("} else {") + endLine;
text += indent + QStringLiteral("System.err.println(\"ERROR: Cant add") + fieldType + QStringLiteral(" to ") + fieldName + QStringLiteral(", minimum number of items reached.\");") + endLine + QLatin1Char('}') + endLine;
}
break;
}
case CodeAccessorMethod::GET:
text = QStringLiteral("return ") + fieldName + QLatin1Char(';');
break;
case CodeAccessorMethod::LIST:
text = QStringLiteral("return (List) ") + fieldName + QLatin1Char(';');
break;
case CodeAccessorMethod::REMOVE:
{
int minOccurs = dfield->minimumListOccurances();
QString fieldType = dfield->getTypeName();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
QString indent = getIndentation();
if(minOccurs > 0)
text += QStringLiteral("if (") + fieldName + QStringLiteral(".size() >= ")+ QString::number(minOccurs) + QStringLiteral(") {") + endLine + indent;
text += fieldName + QStringLiteral(".remove(value);");
if(minOccurs > 0)
{
text += endLine + QStringLiteral("} else {") + endLine;
text += indent + QStringLiteral("System.err.println(\"ERROR: Cant remove") + fieldType + QStringLiteral(" from ") + fieldName + QStringLiteral(", minimum number of items reached.\");") + endLine + QLatin1Char('}') + endLine;
}
break;
}
case CodeAccessorMethod::SET:
text = fieldName + QStringLiteral(" = value;");
break;
default:
// do nothing
break;
}
setText(text);
}
void DCodeAccessorMethod::updateMethodDeclaration()
{
DCodeClassField * dfield = dynamic_cast<DCodeClassField*>(getParentClassField());
// Check for dynamic casting failure!
if (dfield == nullptr)
{
logError0("dfield: invalid dynamic cast");
return;
}
CodeGenerationPolicy *commonpolicy = UMLApp::app()->commonPolicy();
// gather defs
Uml::Visibility::Enum scopePolicy = commonpolicy->getAttributeAccessorScope();
QString strVis = Uml::Visibility::toString(dfield->getVisibility());
QString fieldName = dfield->getFieldName();
QString fieldType = dfield->getTypeName();
QString objectType = dfield->getListObjectType();
if(objectType.isEmpty())
objectType = fieldName;
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
// set scope of this accessor appropriately..if its an attribute,
// we need to be more sophisticated
if (dfield->parentIsAttribute()) {
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
strVis = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing..already have taken parent value
break;
}
}
// some variables we will need to populate
QString headerText;
QString methodReturnType;
QString methodName;
QString methodParams;
switch(getType()) {
case CodeAccessorMethod::ADD:
methodName = QStringLiteral("add") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Add an object of type ") + objectType + QStringLiteral(" to the List ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return void");
break;
case CodeAccessorMethod::GET:
methodName = QStringLiteral("get") + Codegen_Utils::capitalizeFirstLetter(fieldName);
methodReturnType = fieldType;
headerText = QStringLiteral("Get the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return the value of ") + fieldName;
break;
case CodeAccessorMethod::LIST:
methodName = QStringLiteral("get") + Codegen_Utils::capitalizeFirstLetter(fieldType) + QStringLiteral("List");
methodReturnType = QStringLiteral("List");
headerText = QStringLiteral("Get the list of ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return List of ") + fieldName;
break;
case CodeAccessorMethod::REMOVE:
methodName = QStringLiteral("remove") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Remove an object of type ") + objectType + QStringLiteral(" from the List ") + fieldName + endLine + getParentObject()->doc();
break;
case CodeAccessorMethod::SET:
methodName = QStringLiteral("set") + Codegen_Utils::capitalizeFirstLetter(fieldName);
methodReturnType = QStringLiteral("void");
methodParams = fieldType + QStringLiteral(" value ");
headerText = QStringLiteral("Set the value of ") + fieldName + endLine + getParentObject()->doc() + endLine;
break;
default:
// do nothing..no idea what this is
logWarn1("Cannot generate DCodeAccessorMethod for type: %1", getType());
break;
}
// set header once.
if(getComment()->getText().isEmpty())
getComment()->setText(headerText);
// set start/end method text
setStartMethodText(strVis + QLatin1Char(' ') + methodReturnType + QLatin1Char(' ') + methodName + QStringLiteral(" (") + methodParams + QStringLiteral(") {"));
setEndMethodText(QStringLiteral("}"));
}
void DCodeAccessorMethod::update()
{
updateMethodDeclaration();
updateContent();
}
| 8,244
|
C++
|
.cpp
| 185
| 37.772973
| 240
| 0.673225
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,570
|
dcodeclassfielddeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodeclassfielddeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "dcodeclassfielddeclarationblock.h"
#include "dcodeclassfield.h"
#include "dclassifiercodedocument.h"
#include "dcodegenerationpolicy.h"
#include "codegenerator.h"
#include "classifier.h"
#include "umlrole.h"
#include "uml.h"
#include "debug_utils.h"
/**
* Constructor.
*/
DCodeClassFieldDeclarationBlock::DCodeClassFieldDeclarationBlock(CodeClassField * parent)
: CodeClassFieldDeclarationBlock(parent)
{
setOverallIndentationLevel(1);
}
/**
* Empty Destructor.
*/
DCodeClassFieldDeclarationBlock::~DCodeClassFieldDeclarationBlock()
{
}
/**
* This will be called by syncToParent whenever the parent object is "modified".
*/
void DCodeClassFieldDeclarationBlock::updateContent()
{
CodeClassField * cf = getParentClassField();
DCodeClassField * jcf = dynamic_cast<DCodeClassField*>(cf);
if (!jcf)
{
logError0("jcf: invalid dynamic cast");
return;
}
CodeGenerationPolicy * commonpolicy = UMLApp::app()->commonPolicy();
Uml::Visibility::Enum scopePolicy = commonpolicy->getAssociationFieldScope();
// Set the comment
QString notes = getParentObject()->doc();
getComment()->setText(notes);
// Set the body
QString staticValue = getParentObject()->isStatic() ? QStringLiteral("static ") : QString();
QString scopeStr = Uml::Visibility::toString(getParentObject()->visibility());
// IF this is from an association, then scope taken as appropriate to policy
if (!jcf->parentIsAttribute())
{
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
scopeStr = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing here... will leave as from parent object
break;
}
}
QString typeName = jcf->getTypeName();
QString fieldName = jcf->getFieldName();
QString initialV = jcf->getInitialValue();
if (!cf->parentIsAttribute() && !cf->fieldIsSingleValue())
typeName = QStringLiteral("List");
QString body = staticValue + scopeStr + QLatin1Char(' ') + typeName + QLatin1Char(' ') + fieldName;
if (!initialV.isEmpty())
body.append(QStringLiteral(" = ") + initialV);
else if (!cf->parentIsAttribute())
{
const UMLRole * role = cf->getParentObject()->asUMLRole();
// Check for dynamic casting failure!
if (role == nullptr)
{
logError0("role: invalid dynamic cast");
return;
}
if (role->object()->baseType() == UMLObject::ot_Interface)
{
// do nothing.. can't instantiate an interface
} else {
// FIX?: IF a constructor method exists in the classifiercodedoc
// of the parent Object, then we can use that instead (if its empty).
if(cf->fieldIsSingleValue())
{
if(!typeName.isEmpty())
body.append(QStringLiteral(" = new ") + typeName + QStringLiteral(" ()"));
} else
body.append(QStringLiteral(" = new Vector ()"));
}
}
setText(body + QLatin1Char(';'));
}
| 3,467
|
C++
|
.cpp
| 96
| 29.729167
| 103
| 0.655615
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,571
|
dcodecomment.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodecomment.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodecomment.h"
// qt/kde includes
#include <QRegularExpression>
DCodeComment::DCodeComment (CodeDocument * doc, const QString & text)
: CodeComment (doc, text)
{
}
DCodeComment::~DCodeComment ()
{
}
void DCodeComment::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("dcodecomment"));
// as we added no additional fields to this class we may
// just use parent TextBlock method
setAttributesOnNode(writer);
writer.writeEndElement();
}
QString DCodeComment::toString () const
{
QString output;
// simple output method
if(getWriteOutText())
{
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
// check the need for multiline comments
if (body.indexOf(QRegularExpression(endLine)) >= 0) {
output += indent + QStringLiteral("/**") + endLine;
output += formatMultiLineText (body, indent + QStringLiteral(" * "), endLine);
output += indent + QStringLiteral(" */") + endLine;
} else {
output += formatMultiLineText (body, indent + QStringLiteral("// "), endLine);
}
}
return output;
}
// TODO: where is this used?
QString DCodeComment::getNewEditorLine (int amount)
{
QString line = getIndentationString(amount) + QStringLiteral("// ");
return line;
}
// TODO: where is this used?
QString DCodeComment::unformatText (const QString & text, const QString & indent)
{
// remove leading or trailing comment stuff
QString mytext = TextBlock::unformatText(text, indent);
// now leading slashes
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
| 1,988
|
C++
|
.cpp
| 59
| 29.101695
| 92
| 0.692629
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,572
|
dcodedocumentation.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodedocumentation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodedocumentation.h"
// app includes
#include "codedocument.h"
#include "codegenerator.h"
#include "codegenerationpolicy.h"
#include "uml.h"
// qt/kde includes
#include <QRegularExpression>
DCodeDocumentation::DCodeDocumentation(CodeDocument * doc, const QString & text)
: CodeComment(doc, text)
{
}
DCodeDocumentation::~DCodeDocumentation()
{
}
void DCodeDocumentation::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("dcodedocumentation"));
setAttributesOnNode(writer); // as we added no additional fields to this class we may
// just use parent TextBlock method
writer.writeEndElement();
}
QString DCodeDocumentation::toString() const
{
QString output;
// simple output method
if(getWriteOutText())
{
bool useDoubleDashOutput = true;
// need to figure out output type from d policy
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
useDoubleDashOutput = false;
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
if(useDoubleDashOutput)
{
if(!body.isEmpty()) {
output += (formatMultiLineText (body, indent + QStringLiteral("// "), endLine));
}
} else {
output += indent + QStringLiteral("/**") + endLine;
output += formatMultiLineText (body, indent + QStringLiteral(" * "), endLine);
output += indent + QStringLiteral(" */") + endLine;
}
}
return output;
}
QString DCodeDocumentation::getNewEditorLine(int amount)
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return getIndentationString(amount) + QStringLiteral(" * ");
else
return getIndentationString(amount) + QStringLiteral("// ");
}
int DCodeDocumentation::firstEditableLine()
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return 1;
return 0;
}
int DCodeDocumentation::lastEditableLine()
{
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
return -1; // very last line is NOT editable
}
return 0;
}
/**
* UnFormat a long text string. Typically, this means removing
* the indentation (linePrefix) and/or newline chars from each line.
*/
QString DCodeDocumentation::unformatText(const QString & text, const QString & indent)
{
QString mytext = TextBlock::unformatText(text, indent);
CodeGenerationPolicy * p = UMLApp::app()->commonPolicy();
// remove leading or trailing comment stuff
mytext.remove(QRegularExpression(QLatin1Char('^') + indent));
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\*\\*\\s*\n?")));
mytext.remove(QRegularExpression(QStringLiteral("\\s*\\*\\/\\s*\n?$")));
mytext.remove(QRegularExpression(QStringLiteral("^\\s*\\*\\s*")));
} else
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
| 3,558
|
C++
|
.cpp
| 98
| 31.295918
| 96
| 0.689244
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,573
|
dcodeclassfield.cpp
|
KDE_umbrello/umbrello/codegenerators/d/dcodeclassfield.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2007 Jari-Matti Mäkelä <jmjm@iki.fi>
SPDX-FileCopyrightText: 2008-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "dcodeclassfield.h"
// local includes
#include "attribute.h"
#include "dcodecomment.h"
#include "dcodegenerator.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
// #include "dcodeaccessormethod.h"
#include "dclassifiercodedocument.h"
// qt includes
DCodeClassField::DCodeClassField (ClassifierCodeDocument * parentDoc, UMLRole * role)
: CodeClassField(parentDoc, role)
{
}
DCodeClassField::DCodeClassField (ClassifierCodeDocument * parentDoc, UMLAttribute * attrib)
: CodeClassField(parentDoc, attrib)
{
}
DCodeClassField::~DCodeClassField()
{
}
QString DCodeClassField::getFieldName()
{
if (parentIsAttribute())
{
UMLAttribute * at = (UMLAttribute*) getParentObject();
return cleanName(at->name());
}
else
{
UMLRole * role = (UMLRole*) getParentObject();
QString roleName = role->name();
roleName = roleName.replace(0, 1, roleName[0].toLower());
if(fieldIsSingleValue()) {
return roleName;
} else {
return roleName + (roleName.right(1) == QStringLiteral("s") ? QStringLiteral("es") : QStringLiteral("s"));
}
}
}
QString DCodeClassField::getInitialValue()
{
if (parentIsAttribute())
{
const UMLAttribute * at = getParentObject()->asUMLAttribute();
if (at) {
return fixInitialStringDeclValue(at->getInitialValue(), getTypeName());
} else {
logError0("parent object is not a UMLAttribute");
return QString();
}
}
else
{
if(fieldIsSingleValue()) {
// FIX : IF the multiplicity is "1" then we should init a new object here, if its 0 or 1,
// then we can just return 'empty' string (minor problem).
return QString();
} else {
return QStringLiteral(" new ") + DCodeGenerator::getListFieldClassName() + QStringLiteral("()");
}
}
}
QString DCodeClassField::getTypeName()
{
return DCodeGenerator::fixTypeName(CodeClassField::getTypeName());
}
| 2,325
|
C++
|
.cpp
| 75
| 25.68
| 118
| 0.663832
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,574
|
javacodeclassfielddeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodeclassfielddeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "javacodeclassfielddeclarationblock.h"
#include "codegenerator.h"
#include "classifier.h"
#include "debug_utils.h"
#include "javacodeclassfield.h"
#include "javaclassifiercodedocument.h"
#include "javacodegenerationpolicy.h"
#include "umlrole.h"
#include "uml.h"
/**
* Constructor.
*/
JavaCodeClassFieldDeclarationBlock::JavaCodeClassFieldDeclarationBlock(CodeClassField* parent)
: CodeClassFieldDeclarationBlock(parent)
{
setOverallIndentationLevel(1);
}
/**
* Empty Destructor.
*/
JavaCodeClassFieldDeclarationBlock::~JavaCodeClassFieldDeclarationBlock()
{
}
/**
* This will be called by syncToParent whenever the parent object is "modified".
*/
void JavaCodeClassFieldDeclarationBlock::updateContent()
{
CodeClassField * cf = getParentClassField();
JavaCodeClassField * jcf = dynamic_cast<JavaCodeClassField*>(cf);
if (!jcf){
logError0("JavaCodeClassFieldDeclarationBlock::updateContent: invalid dynamic cast");
return;
}
CodeGenerationPolicy * commonpolicy = UMLApp::app()->commonPolicy();
Uml::Visibility::Enum scopePolicy = commonpolicy->getAssociationFieldScope();
// Set the comment
QString notes = getParentObject()->doc();
getComment()->setText(notes);
// Set the body
QString staticValue = getParentObject()->isStatic() ? QStringLiteral("static ") : QString();
QString scopeStr = Uml::Visibility::toString(getParentObject()->visibility());
// IF this is from an association, then scope taken as appropriate to policy
if(!jcf->parentIsAttribute())
{
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
scopeStr = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing here... will leave as from parent object
break;
}
}
QString typeName = jcf->getTypeName();
QString fieldName = jcf->getFieldName();
QString initialV = jcf->getInitialValue();
if (!cf->parentIsAttribute() && !cf->fieldIsSingleValue())
typeName = QStringLiteral("List");
QString body = staticValue+scopeStr+QLatin1Char(' ')+typeName+QLatin1Char(' ')+fieldName;
if (!initialV.isEmpty())
body.append(QStringLiteral(" = ") + initialV);
else if (!cf->parentIsAttribute())
{
const UMLRole * role = cf->getParentObject()->asUMLRole();
// Check for dynamic casting failure
if (role == nullptr)
{
logError0("JavaCodeClassFieldDeclarationBlock::updateContent role: invalid dynamic cast");
return;
}
if (role->object()->baseType() == UMLObject::ot_Interface)
{
// do nothing.. can't instantiate an interface
} else {
// FIX?: IF a constructor method exists in the classifiercodedoc
// of the parent Object, then we can use that instead (if its empty).
if(cf->fieldIsSingleValue())
{
if(!typeName.isEmpty())
body.append(QStringLiteral(" = new ") + typeName + QStringLiteral(" ()"));
} else
body.append(QStringLiteral(" = new Vector ()"));
}
}
setText(body+QLatin1Char(';'));
}
| 3,579
|
C++
|
.cpp
| 95
| 31.368421
| 102
| 0.672633
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,575
|
javacodecomment.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodecomment.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "javacodecomment.h"
#include <QRegularExpression>
JavaCodeComment::JavaCodeComment (CodeDocument * doc, const QString & text)
: CodeComment (doc, text)
{
}
JavaCodeComment::~JavaCodeComment ()
{
}
QString JavaCodeComment::getNewEditorLine (int amount)
{
QString line = getIndentationString(amount) + QStringLiteral("// ");
return line;
}
/** UnFormat a long text string. Typically, this means removing
* the indentation (linePrefix) and/or newline chars from each line.
*/
QString JavaCodeComment::unformatText (const QString & text, const QString & indent)
{
// remove leading or trailing comment stuff
QString mytext = TextBlock::unformatText(text, indent);
// now leading slashes
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
/**
* @return QString
*/
QString JavaCodeComment::toString () const
{
QString output;
// simple output method
if (getWriteOutText()) {
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
output.append(formatMultiLineText (getText(), indent + QStringLiteral("// "), endLine));
}
return output;
}
| 1,425
|
C++
|
.cpp
| 44
| 28.954545
| 96
| 0.727007
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,576
|
javacodeoperation.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodeoperation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "javacodeoperation.h"
#include "debug_utils.h"
#include "javaclassifiercodedocument.h"
#include "javacodedocumentation.h"
#include "javacodegenerator.h"
#include "uml.h"
JavaCodeOperation::JavaCodeOperation
(JavaClassifierCodeDocument * doc, UMLOperation *parent, const QString & body, const QString & comment)
: CodeOperation (doc, parent, body, comment)
{
// lets not go with the default comment and instead use
// full-blown java documentation object instead
setComment(new JavaCodeDocumentation(doc));
// these things never change..
setOverallIndentationLevel(1);
}
JavaCodeOperation::~JavaCodeOperation()
{
}
// we basically want to update the doc and start text of this method
void JavaCodeOperation::updateMethodDeclaration()
{
CodeDocument * doc = getParentDocument();
JavaClassifierCodeDocument * javadoc = dynamic_cast<JavaClassifierCodeDocument*>(doc);
Q_ASSERT(javadoc);
UMLOperation * o = getParentOperation();
bool isInterface = javadoc->getParentClassifier()->isInterface();
QString endLine = getNewLineEndingChars();
// now, the starting text.
QString strVis = Uml::Visibility::toString(o->visibility());
// no return type for constructors
QString fixedReturn = JavaCodeGenerator::fixTypeName(o->getTypeName());
QString returnType = o->isConstructorOperation() ? QString() : (fixedReturn + QStringLiteral(" "));
QString methodName = o->name();
QString paramStr;
// assemble parameters
UMLAttributeList list = getParentOperation()->getParmList();
int nrofParam = list.count();
int paramNum = 0;
for(UMLAttribute* parm : list) {
QString rType = parm->getTypeName();
QString paramName = parm->name();
paramStr += rType + QLatin1Char(' ') + paramName;
paramNum++;
if (paramNum != nrofParam)
paramStr += QStringLiteral(", ");
}
QString maybeStatic;
if (o->isStatic())
maybeStatic = QStringLiteral("static ");
QString startText = strVis + QLatin1Char(' ') + maybeStatic + returnType + methodName + QStringLiteral(" (") + paramStr + QLatin1Char(')');
// IF the parent is an interface, our operations look different
// e.g. they have no body
if(isInterface) {
startText += QLatin1Char(';');
setEndMethodText(QString());
} else {
startText += QStringLiteral(" {");
setEndMethodText(QStringLiteral("}"));
}
setStartMethodText(startText);
// Lastly, for text content generation, we fix the comment on the
// operation, IF the codeop is autogenerated & currently empty
QString comment = o->doc();
if(comment.isEmpty() && contentType() == CodeBlock::AutoGenerated)
{
UMLAttributeList parameters = o->getParmList();
for(UMLAttribute* currentAtt : parameters) {
comment += endLine + QStringLiteral("@param ") + currentAtt->name() + QLatin1Char(' ');
comment += currentAtt->doc();
}
// add a returns statement too
if(!returnType.isEmpty())
comment += endLine + QStringLiteral("@return ") + returnType + QLatin1Char(' ');
getComment()->setText(comment);
}
// In Java, for interfaces..we DON'T write out non-public
// method declarations.
if(isInterface)
{
UMLOperation * o = getParentOperation();
if(o->visibility() != Uml::Visibility::Public)
setWriteOutText(false);
}
}
int JavaCodeOperation::lastEditableLine()
{
ClassifierCodeDocument * doc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());
// Check for dynamic casting failure
if (doc == nullptr)
{
logError0("JavaCodeOperation::lastEditableLine doc: invalid dynamic cast");
return -1;
}
if(doc->parentIsInterface())
return -1; // very last line is NOT editable as its a one-line declaration w/ no body in
// an interface.
return 0;
}
| 4,196
|
C++
|
.cpp
| 104
| 34.778846
| 143
| 0.685076
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,577
|
javaclassifiercodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javaclassifiercodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
/**
* We carve the Java document up into sections as follows:
* - header
* - package declaration
* - import statements
* - class declaration
* - guts of the class (e.g. field decl, accessor methods, operations, dependent classes)
*/
// own header
#include "javaclassifiercodedocument.h"
// local includes
#include "javacodegenerator.h"
#include "javacodecomment.h"
#include "javaclassdeclarationblock.h"
#include "javacodeclassfielddeclarationblock.h"
#include "codegen_utils.h"
#include "classifier.h"
#include "codegenerationpolicy.h"
#include "debug_utils.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
DEBUG_REGISTER(JavaClassifierCodeDocument)
JavaClassifierCodeDocument::JavaClassifierCodeDocument (UMLClassifier * classifier)
: ClassifierCodeDocument (classifier)
{
init();
}
JavaClassifierCodeDocument::~JavaClassifierCodeDocument ()
{
}
// Make it easier on ourselves
JavaCodeGenerationPolicy * JavaClassifierCodeDocument::getJavaPolicy() const
{
CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
JavaCodeGenerationPolicy * policy = dynamic_cast<JavaCodeGenerationPolicy*>(pe);
return policy;
}
//**
// * Get the dialog widget which allows user interaction with the object parameters.
// * @return CodeDocumentDialog
// */
/*
CodeDocumentDialog JavaClassifierCodeDocument::getDialog ()
{
}
*/
bool JavaClassifierCodeDocument::forceDoc ()
{
return UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
}
// We overwritten by Java language implementation to get lowercase path
QString JavaClassifierCodeDocument::getPath () const
{
QString path = getPackage();
// Replace all white spaces with blanks
path = path.simplified();
// Replace all blanks with underscore
path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
path.replace(QRegularExpression(QStringLiteral("\\.")),QStringLiteral("/"));
path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/"));
return path.toLower();
}
QString JavaClassifierCodeDocument::getJavaClassName (const QString &name) const
{
return Codegen_Utils::capitalizeFirstLetter(CodeGenerator::cleanName(name));
}
// Initialize this java classifier code document
void JavaClassifierCodeDocument::init ()
{
setFileExtension(QStringLiteral(".java"));
//initCodeClassFields(); // this is dubious because it calls down to
// CodeGenFactory::newCodeClassField(this)
// but "this" is still in construction at that time.
classDeclCodeBlock = nullptr;
operationsBlock = nullptr;
constructorBlock = nullptr;
// this will call updateContent() as well as other things that sync our document.
synchronize();
}
/**
* @param op
*/
// in the vanilla version, we just tack all operations on the end
// of the document
bool JavaClassifierCodeDocument::addCodeOperation (CodeOperation * op)
{
if (!op->getParentOperation()->isLifeOperation())
return operationsBlock == nullptr ? false : operationsBlock->addTextBlock(op);
else
return constructorBlock == nullptr ? false : constructorBlock->addTextBlock(op);
}
// Sigh. NOT optimal. The only reason that we need to have this
// is so we can create the JavaClassDeclarationBlock.
// would be better if we could create a handler interface that each
// codeblock used so all we have to do here is add the handler
// for "javaclassdeclarationblock"
void JavaClassifierCodeDocument::loadChildTextBlocksFromNode (QDomElement & root)
{
QDomNode tnode = root.firstChild();
QDomElement telement = tnode.toElement();
bool loadCheckForChildrenOK = false;
while (!telement.isNull()) {
QString nodeName = telement.tagName();
if (nodeName == QStringLiteral("textblocks")) {
QDomNode node = telement.firstChild();
QDomElement element = node.toElement();
// if there is nothing to begin with, then we don't worry about it
loadCheckForChildrenOK = element.isNull() ? true : false;
while (!element.isNull()) {
QString name = element.tagName();
if (name == QStringLiteral("codecomment")) {
CodeComment * block = new JavaCodeComment(this);
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaClassifierCodeDocument: loadFromXMI : unable to add codeComment");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeaccessormethod") ||
name == QStringLiteral("ccfdeclarationcodeblock")) {
QString acctag = element.attribute(QStringLiteral("tag"));
// search for our method in the
TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
if (!tb || !addTextBlock(tb)) {
logError0("JavaClassifierCodeDocument: loadFromXMI : unable to add codeclassfield child method");
// DON'T delete
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblock")) {
CodeBlock * block = newCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaClassifierCodeDocument: loadFromXMI : unable to add codeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblockwithcomments")) {
CodeBlockWithComments * block = newCodeBlockWithComments();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaClassifierCodeDocument: loadFromXMI : unable to add codeBlockwithcomments");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("header")) {
// do nothing.. this is treated elsewhere
} else if (name == QStringLiteral("hierarchicalcodeblock")) {
HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaClassifierCodeDocument: Unable to add hierarchicalcodeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeoperation")) {
// find the code operation by id
QString id = element.attribute(QStringLiteral("parent_id"), QStringLiteral("-1"));
UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
UMLOperation * op = obj->asUMLOperation();
if (op) {
CodeOperation * block = new JavaCodeOperation(this, op);
block->loadFromXMI(element);
if (addTextBlock(block)) {
loadCheckForChildrenOK= true;
} else {
logError0("JavaClassifierCodeDocument: Unable to add codeoperation");
block->deleteLater();
}
} else {
logError0("JavaClassifierCodeDocument: Unable to find operation create codeoperation");
}
} else if (name == QStringLiteral("javaclassdeclarationblock")) {
JavaClassDeclarationBlock * block = getClassDecl();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaClassifierCodeDocument: Unable to add java code declaration block");
// DON'T delete.
// block->deleteLater();
} else {
loadCheckForChildrenOK= true;
}
} else {
logDebug1("JavaClassifierCodeDocument::loadChildTextBlocksFromNode: Got strange tag in "
"text block stack:%1, ignoring", name);
}
node = element.nextSibling();
element = node.toElement();
}
break;
}
tnode = telement.nextSibling();
telement = tnode.toElement();
}
if (!loadCheckForChildrenOK) {
logWarn1("loadChildBlocks : unable to initialize any child blocks in doc: %1", getFileName());
}
}
JavaClassDeclarationBlock * JavaClassifierCodeDocument::getClassDecl()
{
if (!classDeclCodeBlock) {
classDeclCodeBlock = new JavaClassDeclarationBlock (this);
classDeclCodeBlock->updateContent();
classDeclCodeBlock->setTag(QStringLiteral("ClassDeclBlock"));
}
return classDeclCodeBlock;
}
void JavaClassifierCodeDocument::resetTextBlocks()
{
// all special pointers to text blocks need to be zero'd out
operationsBlock = nullptr;
constructorBlock = nullptr;
classDeclCodeBlock = nullptr;
// now do traditional release of text blocks.
ClassifierCodeDocument::resetTextBlocks();
}
// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we reasonably will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void JavaClassifierCodeDocument::updateContent()
{
// Gather info on the various fields and parent objects of this class...
UMLClassifier * c = getParentClassifier();
Q_ASSERT(c != nullptr);
CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy();
CodeGenPolicyExt * pe = UMLApp::app()->policyExt();
JavaCodeGenerationPolicy * policy = dynamic_cast<JavaCodeGenerationPolicy*>(pe);
// first, set the global flag on whether or not to show classfield info
// This depends on whether or not we have attribute/association classes
const CodeClassFieldList * cfList = getCodeClassFieldList();
CodeClassFieldList::const_iterator it = cfList->begin();
CodeClassFieldList::const_iterator end = cfList->end();
for (; it != end; ++it) {
CodeClassField * field = *it;
if (field->parentIsAttribute())
field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors());
else
field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors());
}
// attribute-based ClassFields
// we do it this way to have the static fields sorted out from regular ones
CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true);
CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false);
// association-based ClassFields
// don't care if they are static or not..all are lumped together
CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation);
CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation);
CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition);
bool isInterface = parentIsInterface();
bool hasOperationMethods = false;
UMLOperationList list = c->getOpList();
hasOperationMethods = ! list.isEmpty();
QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time
//
// START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
//
//
// PACKAGE CODE BLOCK
//
QString pkgs = getPackage();
pkgs.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("."));
QString packageText = getPackage().isEmpty() ? QString() : QStringLiteral("package ") + pkgs + QLatin1Char(';') + endLine;
CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("packages"), packageText, QString(), 0, false);
if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated)
pblock->setWriteOutText(false);
else
pblock->setWriteOutText(true);
// IMPORT CODEBLOCK
//
// Q: Why all utils? Aren't just List and Vector the only classes we are using?
// A: doesn't matter at all; it is more readable to just include '*' and java compilers
// don't slow down or anything. (TZ)
QString importStatement;
if (hasObjectVectorClassFields())
importStatement.append(QStringLiteral("import java.util.*;"));
//only import classes in a different package from this class
UMLPackageList imports;
QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages
CodeGenerator::findObjectsRelated(c, imports);
UMLPackageListIt importsIt(imports);
while (importsIt.hasNext()) {
UMLPackage* con = importsIt.next();
// NO (default) datatypes in the import statement.. use defined
// ones whould be possible, but no idea how to do that...at least for now.
// Dynamic casting is slow..not an optimal way to do this.
if (!packageMap.contains(con) && !con->isUMLDatatype())
{
packageMap.insert(con, con->package());
// now, we DON'T need to import classes that are already in our own package
// (that is, IF a package is specified). Otherwise, we should have a declaration.
if (con->package() != c->package() ||
(c->package().isEmpty() && con->package().isEmpty()))
{
importStatement.append(endLine+QStringLiteral("import "));
if (!con->package().isEmpty())
importStatement.append(con->package()+QLatin1Char('.'));
importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';'));
}
}
}
// now, add/update the imports codeblock
CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("imports"), importStatement, QString(), 0, false);
if (importStatement.isEmpty() && iblock->contentType() == CodeBlock::AutoGenerated)
iblock->setWriteOutText(false);
else
iblock->setWriteOutText(true);
// CLASS DECLARATION BLOCK
//
// get the declaration block. If it is not already present, add it too
JavaClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl();
addTextBlock(myClassDeclCodeBlock); // note: wont add if already present
// NOW create document in sections..
// now we want to populate the body of our class
// our layout is the following general groupings of code blocks:
// start java classifier document
// header comment
// package code block
// import code block
// class declaration
// section:
// - class field declaration section comment
// - class field declarations (0+ codeblocks)
// section:
// - methods section comment
// sub-section: constructor ops
// - constructor method section comment
// - constructor methods (0+ codeblocks)
// sub-section: accessors
// - accessor method section comment
// - static accessor methods (0+ codeblocks)
// - non-static accessor methods (0+ codeblocks)
// sub-section: non-constructor ops
// - operation method section comment
// - operations (0+ codeblocks)
// end class declaration
// end java classifier document
// Q: Why use the more complicated scheme of arranging code blocks within codeblocks?
// A: This will allow us later to preserve the format of our document so that if
// codeblocks are added, they may be easily added in the correct place, rather than at
// the end of the document, or by using a difficult algorithm to find the location of
// the last appropriate code block sibling (which may not exist.. for example user adds
// a constructor operation, but there currently are no constructor code blocks
// within the document).
//
// * CLASS FIELD declaration section
//
// get/create the field declaration code block
HierarchicalCodeBlock * fieldDeclBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("fieldsDecl"), QStringLiteral("Fields"), 1);
// Update the comment: we only set comment to appear under the following conditions
CodeComment * fcomment = fieldDeclBlock->getComment();
if (isInterface || (!forceDoc() && !hasClassFields()))
fcomment->setWriteOutText(false);
else
fcomment->setWriteOutText(true);
// now actually declare the fields within the appropriate HCodeBlock
declareClassFields(staticAttribClassFields, fieldDeclBlock);
declareClassFields(attribClassFields, fieldDeclBlock);
declareClassFields(plainAssocClassFields, fieldDeclBlock);
declareClassFields(aggregationClassFields, fieldDeclBlock);
declareClassFields(compositionClassFields, fieldDeclBlock);
//
// METHODS section
//
// get/create the method codeblock
HierarchicalCodeBlock * methodsBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QStringLiteral("methodsBlock"), QStringLiteral("Methods"), 1);
// Update the section comment
CodeComment * methodsComment = methodsBlock->getComment();
// set conditions for showing this comment
if (!forceDoc() && !hasClassFields() && !hasOperationMethods)
methodsComment->setWriteOutText(false);
else
methodsComment->setWriteOutText(true);
// METHODS sub-section : constructor methods
//
// get/create the constructor codeblock
HierarchicalCodeBlock * constBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("constructorMethods"), QStringLiteral("Constructors"), 1);
constructorBlock = constBlock; // record this codeblock for later, when operations are updated
// special conditions for showing comment: only when autogenerateding empty constructors
// Although, we *should* check for other constructor methods too
CodeComment * constComment = constBlock->getComment();
CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy();
if (!forceDoc() && (isInterface || !pol->getAutoGenerateConstructors()))
constComment->setWriteOutText(false);
else
constComment->setWriteOutText(true);
// add/get the empty constructor
QString JavaClassName = getJavaClassName(c->name());
QString emptyConstStatement = QStringLiteral("public ") + JavaClassName + QStringLiteral(" () { }");
CodeBlockWithComments * emptyConstBlock =
constBlock->addOrUpdateTaggedCodeBlockWithComments(QStringLiteral("emptyconstructor"), emptyConstStatement, QStringLiteral("Empty Constructor"), 1, false);
// Now, as an additional condition we only show the empty constructor block
// IF it was desired to be shown
if (parentIsClass() && pol->getAutoGenerateConstructors())
emptyConstBlock->setWriteOutText(true);
else
emptyConstBlock->setWriteOutText(false);
// METHODS subsection : ACCESSOR METHODS
//
// get/create the accessor codeblock
HierarchicalCodeBlock * accessorBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("accessorMethods"), QStringLiteral("Accessor Methods"), 1);
// set conditions for showing section comment
CodeComment * accessComment = accessorBlock->getComment();
if (!forceDoc() && !hasClassFields())
accessComment->setWriteOutText(false);
else
accessComment->setWriteOutText(true);
// now, 2 sub-sub sections in accessor block
// add/update accessor methods for attributes
HierarchicalCodeBlock * staticAccessors = accessorBlock->getHierarchicalCodeBlock(QStringLiteral("staticAccessorMethods"), QString(), 1);
staticAccessors->getComment()->setWriteOutText(false); // never write block comment
staticAccessors->addCodeClassFieldMethods(staticAttribClassFields);
staticAccessors->addCodeClassFieldMethods(attribClassFields);
// add/update accessor methods for associations
HierarchicalCodeBlock * regularAccessors = accessorBlock->getHierarchicalCodeBlock(QStringLiteral("regularAccessorMethods"), QString(), 1);
regularAccessors->getComment()->setWriteOutText(false); // never write block comment
regularAccessors->addCodeClassFieldMethods(plainAssocClassFields);
regularAccessors->addCodeClassFieldMethods(aggregationClassFields);
regularAccessors->addCodeClassFieldMethods(compositionClassFields);
// METHODS subsection : Operation methods (which arent constructors)
//
// get/create the operations codeblock
operationsBlock = methodsBlock->getHierarchicalCodeBlock(QStringLiteral("operationMethods"), QStringLiteral("Operations"), 1);
// set conditions for showing section comment
CodeComment * ocomment = operationsBlock->getComment();
if (!forceDoc() && !hasOperationMethods)
ocomment->setWriteOutText(false);
else
ocomment->setWriteOutText(true);
}
| 22,139
|
C++
|
.cpp
| 443
| 41.48307
| 163
| 0.675288
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,578
|
javacodeclassfield.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodeclassfield.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodeclassfield.h"
// local includes
#include "attribute.h"
#include "debug_utils.h"
#include "javacodecomment.h"
#include "javacodegenerator.h"
// #include "javacodeaccessormethod.h"
#include "javaclassifiercodedocument.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
JavaCodeClassField::JavaCodeClassField (ClassifierCodeDocument * parentDoc, UMLRole * role)
: CodeClassField(parentDoc, role)
{
}
JavaCodeClassField::JavaCodeClassField (ClassifierCodeDocument * parentDoc, UMLAttribute * attrib)
: CodeClassField(parentDoc, attrib)
{
}
JavaCodeClassField::~JavaCodeClassField ()
{
}
QString JavaCodeClassField::getFieldName()
{
if (parentIsAttribute())
{
UMLAttribute * at = (UMLAttribute*) getParentObject();
return cleanName(at->name());
}
else
{
UMLRole * role = (UMLRole*) getParentObject();
QString roleName = role->name();
if(fieldIsSingleValue()) {
return roleName.replace(0, 1, roleName.left(1).toLower());
} else {
return roleName.toLower() + QStringLiteral("Vector");
}
}
}
QString JavaCodeClassField::getInitialValue()
{
if (parentIsAttribute())
{
const UMLAttribute * at = getParentObject()->asUMLAttribute();
if (at) {
return fixInitialStringDeclValue(at->getInitialValue(), getTypeName());
} else {
logError0("JavaCodeClassField::getInitialValue: parent object is not a UMLAttribute");
return QString();
}
}
else
{
if(fieldIsSingleValue()) {
// FIX : IF the multiplicity is "1" then we should init a new object here, if its 0 or 1,
// then we can just return 'empty' string (minor problem).
return QString();
} else {
return QStringLiteral(" new ") + JavaCodeGenerator::getListFieldClassName() + QStringLiteral("()");
}
}
}
QString JavaCodeClassField::getTypeName ()
{
return JavaCodeGenerator::fixTypeName(CodeClassField::getTypeName());
}
| 2,326
|
C++
|
.cpp
| 73
| 26.616438
| 111
| 0.677664
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,579
|
javawriter.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javawriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <brian.thomas@gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javawriter.h"
// app includes
#include "codegen_utils.h"
#include "classifier.h"
#include "debug_utils.h"
#include "operation.h"
#include "attribute.h"
#include "association.h"
#include "template.h"
#include "umldoc.h"
#include "uml.h" // Only needed for log{Warn,Error}
#include "umltemplatelist.h"
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
/**
* Constructor, initialises a couple of variables.
*/
JavaWriter::JavaWriter()
: m_isInterface(false)
{
m_startline = m_endl + m_indentation;
}
/**
* Destructor, empty.
*/
JavaWriter::~JavaWriter()
{
}
/**
* Returns "Java".
* @return the programming language identifier
*/
Uml::ProgrammingLanguage::Enum JavaWriter::language() const
{
return Uml::ProgrammingLanguage::Java;
}
/**
* Call this method to generate java code for a UMLClassifier.
* @param c the class to generate code for
*/
void JavaWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("JavaWriter::writeClass: Cannot write class of NULL classifier");
return;
}
m_isInterface = c->isInterface();
QString fileName = cleanName(c->name().toLower());
//find an appropriate name for our file
fileName = findFileName(c, QStringLiteral(".java"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
// check that we may open that file for writing
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
// Preparations
//
// sort attributes by Scope
UMLAttributeList atl;
UMLAttributeList atpub, atprot, atpriv;
UMLAttributeList final_atpub, final_atprot, final_atpriv;
if (!m_isInterface) {
UMLAttributeList atl = c->getAttributeList();
for (UMLAttribute *at : atl) {
switch(at->visibility())
{
case Uml::Visibility::Public:
if (at->isStatic())
final_atpub.append(at);
else
atpub.append(at);
break;
case Uml::Visibility::Protected:
if (at->isStatic())
final_atprot.append(at);
else
atprot.append(at);
break;
case Uml::Visibility::Private:
if (at->isStatic())
final_atpriv.append(at);
else
atpriv.append(at);
break;
default:
break;
}
}
}
// another preparation, determine what we have
UMLAssociationList associations = c->getSpecificAssocs(Uml::AssociationType::Association); // BAD! only way to get "general" associations.
UMLAssociationList uniAssociations = c->getUniAssociationToBeImplemented();
UMLAssociationList aggregations = c->getAggregations();
UMLAssociationList compositions = c->getCompositions();
bool hasAssociations = aggregations.count() > 0 || associations.count() > 0 || compositions.count() > 0 || uniAssociations.count() > 0;
bool hasAttributes = (atl.count() > 0);
bool hasAccessorMethods = hasAttributes || hasAssociations;
bool hasOperationMethods = (c->getOpList().count() > 0);
// this is a bit too simplistic..some associations are for
// SINGLE objects, and WONT be declared as Vectors, so this
// is a bit overly inclusive
bool hasVectorFields = hasAssociations ? true : false;
// open text stream to file
QTextStream java(&file);
//try to find a heading file (license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".java"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
java << str << m_endl;
}
if (!c->package().isEmpty())
java << "package " << c->package() << ";" << m_endl;
// IMPORT statements
// Q: Why all utils? Aren't just List and Vector the only classes we are using?
// A: doesn't matter at all; it is more readable to just include '*' and java compilers
// don't slow down or anything. (TZ)
if (hasVectorFields)
{
writeBlankLine(java);
java << "import java.util.*;" << m_endl;
}
//only import classes in a different package as this class
UMLPackageList imports;
findObjectsRelated(c, imports);
for (UMLPackage* con : imports) {
if (con->isUMLDatatype())
continue;
QString pkg = con->package();
if (!pkg.isEmpty() && pkg != c->package())
java << "import " << pkg << "." << cleanName(con->name()) << ";"
<< m_endl;
}
writeBlankLine(java);
// write the opening declaration for the class incl any documentation,
// interfaces and/or inheritance issues we have
writeClassDecl(c, java);
// start body of class
java << " {" << m_endl;
// ATTRIBUTES
//
// write comment for section IF needed
if (forceDoc() || hasAccessorMethods)
{
writeComment(QString(), m_indentation, java);
writeComment(QStringLiteral("Fields"), m_indentation, java);
writeComment(QString(), m_indentation, java);
writeBlankLine(java);
}
writeAttributeDecls(final_atpub, final_atprot, final_atpriv, java);
writeAttributeDecls(atpub, atprot, atpriv, java);
writeAssociationDecls(associations, c->id(), java);
writeAssociationDecls(uniAssociations, c->id(), java);
writeAssociationDecls(aggregations, c->id(), java);
writeAssociationDecls(compositions, c->id(), java);
// Constructors: anything we more we need to do here ?
//
if (!m_isInterface)
writeConstructor(c, java);
// METHODS
//
// write comment for section IF needed
if (forceDoc() || hasAccessorMethods || hasOperationMethods)
{
java << m_startline;
writeComment(QString(), m_indentation, java);
writeComment(QStringLiteral("Methods"), m_indentation, java);
writeComment(QString(), m_indentation, java);
writeBlankLine(java);
writeBlankLine(java);
}
// write comment for sub-section IF needed
if (forceDoc() || hasAccessorMethods)
{
writeComment(QString(), m_indentation, java);
writeComment(QStringLiteral("Accessor methods"), m_indentation, java);
writeComment(QString(), m_indentation, java);
writeBlankLine(java);
}
// Accessors for attributes
writeAttributeMethods(final_atpub, Uml::Visibility::Public, java);
writeAttributeMethods(final_atprot, Uml::Visibility::Public, java);
writeAttributeMethods(final_atpriv, Uml::Visibility::Public, java);
writeAttributeMethods(atpub, Uml::Visibility::Public, java);
writeAttributeMethods(atprot, Uml::Visibility::Public, java);
writeAttributeMethods(atpriv, Uml::Visibility::Public, java);
// accessor methods for associations
// first: determine the name of the other class
writeAssociationMethods(associations, c, java);
writeAssociationMethods(uniAssociations, c, java);
writeAssociationMethods(aggregations, c, java);
writeAssociationMethods(compositions, c, java);
// Other operation methods
// all other operations are now written
// write comment for sub-section IF needed
if (forceDoc() || hasOperationMethods)
{
writeComment(QString(), m_indentation, java);
writeComment(QStringLiteral("Other methods"), m_indentation, java);
writeComment(QString(), m_indentation, java);
writeBlankLine(java);
}
writeOperations(c, java);
writeBlankLine(java);
java << "}" << m_endl; // end class
file.close();
Q_EMIT codeGenerated(c, true);
}
/**
* Writes class's documentation then the class header
* "public abstract class Foo extents {".
*/
void JavaWriter::writeClassDecl(UMLClassifier *c, QTextStream &java)
{
QString classname = cleanName(c->name()); // our class name
// write documentation for class, if any, first
if (forceDoc() || !c->doc().isEmpty())
{
if (m_isInterface)
writeDocumentation(QStringLiteral("Interface ") + classname, c->doc(), QString(), QString(), java);
else
writeDocumentation(QStringLiteral("Class ") + classname, c->doc(), QString(), QString(), java);
writeBlankLine(java);
}
// Now write the actual class declaration
QString scope; // = c->getVisibility().toString();
if (c->visibility() != Uml::Visibility::Public) {
// We should emit a warning in here .. java doesn't like to allow
// private/protected classes. The best we can do (I believe)
// is to let these declarations default to "package visibility"
// which is a level between traditional "private" and "protected"
// scopes. To get this visibility level we just print nothing..
} else
scope = QStringLiteral("public ");
java << ((c->isAbstract() && !m_isInterface) ? QStringLiteral("abstract ") : QString()) << scope;
if (m_isInterface)
java << "interface ";
else
java << "class ";
java << classname;
// Generics
UMLTemplateList template_params = c->getTemplateList();
if (template_params.count()) {
java << "<";
for (UMLTemplateListIt tlit(template_params); tlit.hasNext();) {
UMLTemplate* t = tlit.next();
QString formalName = t->name();
java << formalName;
QString typeName = t->getTypeName();
if (typeName != QStringLiteral("class")) {
java << " extends " << typeName;
}
if (tlit.hasNext()) {
tlit.next();
java << ", ";
}
}
java << ">" << m_endl;
}
// write inheritances out
UMLClassifierList superclasses = c->findSuperClassConcepts(UMLClassifier::CLASS);
int i = 0;
for (UMLClassifier *classifier : superclasses) {
if (i == 0)
{
java << " extends ";
}
else
{
//The java generated code is wrong ! : No multiple inheritance of class
java << ", " ;
}
java << cleanName(classifier->name());
i++;
}
UMLClassifierList superInterfaces = c->findSuperClassConcepts(UMLClassifier::INTERFACE);
i = 0;
for (UMLClassifier *classifier : superInterfaces) {
if (i == 0)
{
if (m_isInterface)
java << " extends ";
else
java << " implements ";
}
else
{
//The java generated code is OK ! : multiple inheritance of interface
java << ", " ;
}
java << cleanName(classifier->name());
i++;
}
}
/**
* Writes the Attribute declarations.
* @param atpub list of public attributes
* @param atprot list of protected attributes
* @param atpriv list of private attributes
* @param java text stream
*/
void JavaWriter::writeAttributeDecls(UMLAttributeList &atpub, UMLAttributeList &atprot,
UMLAttributeList &atpriv, QTextStream &java)
{
for (UMLAttribute *at : atpub) {
QString documentation = at->doc();
QString staticValue = at->isStatic() ? QStringLiteral("static ") : QString();
QString typeName = fixTypeName(at->getTypeName());
QString initialValue = fixInitialStringDeclValue(at->getInitialValue(), typeName);
if (!documentation.isEmpty())
writeComment(documentation, m_indentation, java, true);
java << m_startline << staticValue << "public " << typeName << " " << cleanName(at->name())
<< (initialValue.isEmpty() ? QString() : QStringLiteral(" = ") + initialValue) << ";";
}
for (UMLAttribute *at : atprot){
QString documentation = at->doc();
QString typeName = fixTypeName(at->getTypeName());
QString staticValue = at->isStatic() ? QStringLiteral("static ") : QString();
QString initialValue = fixInitialStringDeclValue(at->getInitialValue(), typeName);
if (!documentation.isEmpty())
writeComment(documentation, m_indentation, java, true);
java << m_startline << staticValue << "protected " << typeName << " " << cleanName(at->name())
<< (initialValue.isEmpty() ? QString() : QStringLiteral(" = ") + initialValue) << ";";
}
for (UMLAttribute *at : atpriv) {
QString documentation = at->doc();
QString typeName = fixTypeName(at->getTypeName());
QString staticValue = at->isStatic() ? QStringLiteral("static ") : QString();
QString initialValue = fixInitialStringDeclValue(at->getInitialValue(), typeName);
if (!documentation.isEmpty())
writeComment(documentation, m_indentation, java, true);
java << m_startline << staticValue << "private " << typeName << " " << cleanName(at->name())
<< (initialValue.isEmpty() ? QString() : QStringLiteral(" = ") + initialValue) << ";";
}
}
/**
* Calls @ref writeSingleAttributeAccessorMethods() on each of the attributes in atpub.
*/
void JavaWriter::writeAttributeMethods(UMLAttributeList &atpub, Uml::Visibility::Enum visibility, QTextStream &java)
{
for (UMLAttribute *at : atpub){
QString fieldName = cleanName(at->name());
// force capitalizing the field name, this is silly,
// from what I can tell, this IS the default behavior for
// cleanName. I dunno why it is not working -b.t.
fieldName.replace(0, 1, fieldName.at(0).toUpper());
writeSingleAttributeAccessorMethods(at->getTypeName(),
cleanName(at->name()),
fieldName,
at->doc(),
visibility, Uml::Changeability::Changeable, at->isStatic(), java);
}
}
/**
* Writes a // style comment.
*/
void JavaWriter::writeComment(const QString &comment, const QString &myIndent,
QTextStream &java, bool javaDocStyle)
{
// in the case we have several line comment..
// NOTE: this part of the method has the problem of adopting UNIX newline,
// need to resolve for using with MAC/WinDoze eventually I assume
if (comment.contains(QRegularExpression(QStringLiteral("\n")))) {
if (javaDocStyle)
java << myIndent << "/**" << m_endl;
QStringList lines = comment.split(QStringLiteral("\n"));
for (int i= 0; i < lines.count(); i++)
{
writeBlankLine(java);
if (javaDocStyle)
java << myIndent << " * ";
else
java << myIndent << "// ";
java << lines[i];
}
if (javaDocStyle)
java << myIndent << " */" << m_endl;
} else {
// this should be more fancy in the future, breaking it up into 80 char
// lines so that it doesn't look too bad
writeBlankLine(java);
if (javaDocStyle)
java << myIndent << "/**" << m_endl << myIndent << " *";
else
java << myIndent << "//";
if (comment.length() > 0)
java << " " << comment;
if (javaDocStyle)
java << m_endl << myIndent << " */";
}
}
/**
* Writes a documentation comment.
*/
void JavaWriter::writeDocumentation(QString header, QString body, QString end, QString indent, QTextStream &java)
{
writeBlankLine(java);
java << indent << "/**" << m_endl;
if (!header.isEmpty())
java << formatDoc(header, indent + QStringLiteral(" * "));
if (!body.isEmpty())
java << formatDoc(body, indent + QStringLiteral(" * "));
if (!end.isEmpty())
{
QStringList lines = end.split(QStringLiteral("\n"));
for (int i= 0; i < lines.count(); i++)
java << formatDoc(lines[i], indent + QStringLiteral(" * "));
}
java << indent << " */";
}
/**
* Searches a list of associations for appropriate ones to write out as attributes.
*/
void JavaWriter::writeAssociationDecls(UMLAssociationList associations, Uml::ID::Type id, QTextStream &java)
{
if (forceSections() || !associations.isEmpty())
{
bool printRoleA = false, printRoleB = false;
for (UMLAssociation *a : associations) {
// it may seem counter intuitive, but you want to insert the role of the
// *other* class into *this* class.
if (a->getObjectId(Uml::RoleType::A) == id)
printRoleB = true;
if (a->getObjectId(Uml::RoleType::B) == id)
printRoleA = true;
// First: we insert documentation for association IF it has either role AND some documentation (!)
if ((printRoleA || printRoleB) && !(a->doc().isEmpty()))
writeComment(a->doc(), m_indentation, java);
// print RoleB decl
if (printRoleB)
{
QString fieldClassName = cleanName(getUMLObjectName(a->getObject(Uml::RoleType::B)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::B), a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B), a->visibility(Uml::RoleType::B), java);
}
// print RoleA decl
if (printRoleA)
{
QString fieldClassName = cleanName(getUMLObjectName(a->getObject(Uml::RoleType::A)));
writeAssociationRoleDecl(fieldClassName, a->getRoleName(Uml::RoleType::A), a->getMultiplicity(Uml::RoleType::A), a->getRoleDoc(Uml::RoleType::A), a->visibility(Uml::RoleType::A), java);
}
}
}
}
/**
* Writes out an association as an attribute using Vector.
*/
void JavaWriter::writeAssociationRoleDecl(QString fieldClassName,
QString roleName, QString multi,
QString doc, Uml::Visibility::Enum visib, QTextStream &java)
{
// ONLY write out IF there is a rolename given
// otherwise it is not meant to be declared in the code
if (roleName.isEmpty())
return;
QString scope = Uml::Visibility::toString(visib);
// always put space between this and prior decl, if any
writeBlankLine(java);
if (!doc.isEmpty())
writeComment(doc, m_indentation, java);
// declare the association based on whether it is this a single variable
// or a List (Vector). One day this will be done correctly with special
// multiplicity object that we don't have to figure out what it means via regex.
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$"))))
{
QString fieldVarName = QStringLiteral("m_") + roleName.replace(0, 1, roleName.left(1).toLower());
java << m_startline << scope << " " << fieldClassName << " " << fieldVarName << ";";
}
else
{
QString fieldVarName = roleName.toLower() + QStringLiteral("Vector");
java << m_startline << scope << " Vector " << fieldVarName << " = new Vector();";
// from here we could initialize default values, or put in an init() section
// of the constructors
}
}
/**
* Calls @ref writeAssociationRoleMethod() on each of the associations in the given list.
*/
void JavaWriter::writeAssociationMethods (UMLAssociationList associations, UMLClassifier *thisClass, QTextStream &java)
{
if (forceSections() || !associations.isEmpty()) {
for (UMLAssociation *a : associations) {
// insert the methods to access the role of the other
// class in the code of this one
if (a->getObjectId(Uml::RoleType::A) == thisClass->id())
{
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::B).isEmpty()) {
QString fieldClassName = getUMLObjectName(a->getObject(Uml::RoleType::B));
writeAssociationRoleMethod(fieldClassName,
a->getRoleName(Uml::RoleType::B),
a->getMultiplicity(Uml::RoleType::B), a->getRoleDoc(Uml::RoleType::B),
a->visibility(Uml::RoleType::B),
a->changeability(Uml::RoleType::B), java);
}
}
if (a->getObjectId(Uml::RoleType::B) == thisClass->id())
{
// only write out IF there is a rolename given
if (!a->getRoleName(Uml::RoleType::A).isEmpty()) {
QString fieldClassName = getUMLObjectName(a->getObject(Uml::RoleType::A));
writeAssociationRoleMethod(fieldClassName, a->getRoleName(Uml::RoleType::A),
a->getMultiplicity(Uml::RoleType::A),
a->getRoleDoc(Uml::RoleType::A),
a->visibility(Uml::RoleType::A),
a->changeability(Uml::RoleType::A),
java);
}
}
}
}
}
/**
* Calls @ref writeSingleAttributeAccessorMethods() or @ref
* writeVectorAttributeAccessorMethods() on the association
* role.
*/
void JavaWriter::writeAssociationRoleMethod (QString fieldClassName, QString roleName, QString multi,
QString description, Uml::Visibility::Enum visib, Uml::Changeability::Enum change,
QTextStream &java)
{
if (multi.isEmpty() || multi.contains(QRegularExpression(QStringLiteral("^[01]$"))))
{
QString fieldVarName = QStringLiteral("m_") + roleName.replace(0, 1, roleName.left(1).toLower());
writeSingleAttributeAccessorMethods(fieldClassName, fieldVarName, roleName,
description, visib, change, false, java);
}
else
{
QString fieldVarName = roleName.toLower() + QStringLiteral("Vector");
writeVectorAttributeAccessorMethods(fieldClassName, fieldVarName, roleName,
description, visib, change, java);
}
}
/**
* Writes addFoo() and removeFoo() accessor methods for the Vector attribute.
*/
void JavaWriter::writeVectorAttributeAccessorMethods(QString fieldClassName, QString fieldVarName,
QString fieldName, QString description,
Uml::Visibility::Enum visibility, Uml::Changeability::Enum changeType,
QTextStream &java)
{
fieldClassName = fixTypeName(fieldClassName);
fieldName = Codegen_Utils::capitalizeFirstLetter(fieldName);
QString strVis = Uml::Visibility::toString(visibility);
// ONLY IF changeability is NOT Frozen
if (changeType != Uml::Changeability::Frozen)
{
writeDocumentation(QStringLiteral("Add a ") + fieldName + QStringLiteral(" object to the ") + fieldVarName + QStringLiteral(" List"),
description, QString(), m_indentation, java);
java << m_startline << strVis << " void add" << fieldName << " (" << fieldClassName << " new_object) {";
java << m_startline << m_indentation << fieldVarName << ".add(new_object);";
java << m_startline << "}" << m_endl;
}
// ONLY IF changeability is Changeable
if (changeType == Uml::Changeability::Changeable)
{
writeDocumentation(QStringLiteral("Remove a ") + fieldName + QStringLiteral(" object from ") + fieldVarName + QStringLiteral(" List"),
description, QString(), m_indentation, java);
java << m_startline << strVis << " void remove" << fieldName << " (" << fieldClassName << " new_object)";
java << m_startline << "{";
java << m_startline << m_indentation << fieldVarName << ".remove(new_object);";
java << m_startline << "}" << m_endl;
}
// always allow getting the list of stuff
writeDocumentation(QStringLiteral("Get the List of ") + fieldName + QStringLiteral(" objects held by ") + fieldVarName, description, QStringLiteral("@return List of ") + fieldName + QStringLiteral(" objects held by ") + fieldVarName, m_indentation, java);
java << m_startline << strVis << " List get" << fieldName << "List () {";
java << m_startline << m_indentation << "return (List) " << fieldVarName << ";";
java << m_startline << "}" << m_endl;
writeBlankLine(java);
}
/**
* Writes getFoo() and setFoo() accessor methods for the attribute.
*/
void JavaWriter::writeSingleAttributeAccessorMethods(QString fieldClassName, QString fieldVarName,
QString fieldName, QString description,
Uml::Visibility::Enum visibility, Uml::Changeability::Enum change,
bool isFinal, QTextStream &java)
{
QString strVis = Uml::Visibility::toString(visibility);
fieldClassName = fixTypeName(fieldClassName);
fieldName = Codegen_Utils::capitalizeFirstLetter(fieldName);
// set method
if (change == Uml::Changeability::Changeable && !isFinal) {
writeDocumentation(QStringLiteral("Set the value of ") + fieldVarName, description, QStringLiteral("@param newVar the new value of ") + fieldVarName, m_indentation, java);
java << m_startline << strVis << " void set" << fieldName << " (" << fieldClassName << " newVar) {";
java << m_startline << m_indentation << fieldVarName << " = newVar;";
java << m_startline << "}" << m_endl;
}
// get method
writeDocumentation(QStringLiteral("Get the value of ") + fieldVarName, description, QStringLiteral("@return the value of ") + fieldVarName, m_indentation, java);
java << m_startline << strVis << " " << fieldClassName << " get" << fieldName << " () {";
java << m_startline << m_indentation << "return " << fieldVarName << ";";
java << m_startline << "}";
writeBlankLine(java);
}
/**
* Writes the comment and class constructor.
*/
void JavaWriter::writeConstructor(UMLClassifier *c, QTextStream &java)
{
if (forceDoc()) {
java << m_startline;
writeComment(QString(), m_indentation, java);
writeComment(QStringLiteral("Constructors"), m_indentation, java);
writeComment(QString(), m_indentation, java);
writeBlankLine(java);
}
// write the first constructor
QString className = cleanName(c->name());
java << m_indentation << "public " << className << " () { };";
}
/**
* Replaces `string' with `String' and `bool' with `boolean'.
* IF the type is "string" we need to declare it as
* the Java Object "String" (there is no string primitive in Java).
* Same thing again for "bool" to "boolean".
*/
QString JavaWriter::fixTypeName(const QString& string)
{
if (string.isEmpty())
return QStringLiteral("void");
if (string == QStringLiteral("string"))
return QStringLiteral("String");
if (string == QStringLiteral("bool"))
return QStringLiteral("boolean");
return string;
}
/**
* Overrides method from class CodeGenerator.
* @return the list of default datatypes
*/
QStringList JavaWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("int"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("boolean"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("byte"));
l.append(QStringLiteral("short"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("String"));
l.append(QStringLiteral("Integer"));
l.append(QStringLiteral("Character"));
l.append(QStringLiteral("Boolean"));
l.append(QStringLiteral("Float"));
l.append(QStringLiteral("Double"));
l.append(QStringLiteral("Byte"));
l.append(QStringLiteral("Short"));
l.append(QStringLiteral("Long"));
l.append(QStringLiteral("StringBuffer"));
l.append(QStringLiteral("StringBuilder"));
return l;
}
/**
* Return true if the two operations have the same name and the same parameters.
* @param op1 first operation to be compared
* @param op2 second operation to be compared
*/
bool JavaWriter::compareJavaMethod(UMLOperation *op1, UMLOperation *op2)
{
if (op1 == nullptr || op2 == nullptr)
return false;
if (op1 == op2)
return true;
if (op1->name() != op2->name())
return false;
UMLAttributeList atl1 = op1->getParmList();
UMLAttributeList atl2 = op2->getParmList();
if (atl1.count() != atl2.count())
return false;
for (UMLAttributeListIt atl1It(atl1), atl2It(atl2); atl1It.hasNext() && atl2It.hasNext();) {
UMLAttribute *at1 = atl1It.next();
UMLAttribute *at2 = atl2It.next();
if (at1->getTypeName() != at2->getTypeName())
return false;
}
return true;
}
/**
* Return true if the operation is in the list.
* @param umlOp operation to be searched
* @param opl list of operations
*/
bool JavaWriter::javaMethodInList(UMLOperation *umlOp, UMLOperationList &opl)
{
for (UMLOperation *op : opl) {
if (JavaWriter::compareJavaMethod(op, umlOp)) {
return true;
}
}
return false;
}
/**
* Get all operations which a given class inherit from all its super interfaces and get all operations
* which this given class inherit from all its super classes.
* @param c the class for which we are generating code
* @param yetImplementedOpList the list of yet implemented operations
* @param toBeImplementedOpList the list of to be implemented operations
* @param noClassInPath tells if there is a class between the base class and the current interface
*/
void JavaWriter::getSuperImplementedOperations(UMLClassifier *c, UMLOperationList &yetImplementedOpList, UMLOperationList &toBeImplementedOpList, bool noClassInPath)
{
UMLClassifierList superClasses = c->findSuperClassConcepts();
for (UMLClassifier *classifier : superClasses) {
getSuperImplementedOperations(classifier, yetImplementedOpList, toBeImplementedOpList, (classifier->isInterface() && noClassInPath));
UMLOperationList opl = classifier->getOpList();
for (UMLOperation *op : opl) {
if (classifier->isInterface() && noClassInPath) {
if (!JavaWriter::javaMethodInList(op, toBeImplementedOpList))
toBeImplementedOpList.append(op);
}
else
{
if (!JavaWriter::javaMethodInList(op, yetImplementedOpList))
yetImplementedOpList.append(op);
}
}
}
}
/**
* Get all operations which a given class inherit from all its super interfaces and that should be implemented.
* @param c the class for which we are generating code
* @param opList the list of operations used to append the operations
*/
void JavaWriter::getInterfacesOperationsToBeImplemented(UMLClassifier *c, UMLOperationList &opList)
{
UMLOperationList yetImplementedOpList;
UMLOperationList toBeImplementedOpList;
getSuperImplementedOperations(c, yetImplementedOpList, toBeImplementedOpList);
for (UMLOperation *op : toBeImplementedOpList) {
if (! JavaWriter::javaMethodInList(op, yetImplementedOpList) && ! JavaWriter::javaMethodInList(op, opList))
opList.append(op);
}
}
/**
* Write all operations for a given class.
* @param c the class for which we are generating code
* @param java the stream associated with the output file
*/
void JavaWriter::writeOperations(UMLClassifier *c, QTextStream &java) {
UMLOperationList opl;
UMLOperationList oppub, opprot, oppriv;
//sort operations by scope first and see if there are abstract methods
opl = c->getOpList();
if (! c->isInterface()) {
getInterfacesOperationsToBeImplemented(c, opl);
}
for (UMLOperation *op : opl) {
switch(op->visibility()) {
case Uml::Visibility::Public:
oppub.append(op);
break;
case Uml::Visibility::Protected:
opprot.append(op);
break;
case Uml::Visibility::Private:
oppriv.append(op);
break;
default:
break;
}
}
// do people REALLY want these comments? Hmm.
/*
if (forceSections() || oppub.count())
{
writeComment(QStringLiteral("public operations"), m_indentation, java);
writeBlankLine(java);
}
*/
writeOperations(oppub, java);
/*
if (forceSections() || opprot.count())
{
writeComment(QStringLiteral("protected operations"), m_indentation, java);
writeBlankLine(java);
}
*/
writeOperations(opprot, java);
/*
if (forceSections() || oppriv.count())
{
writeComment(QStringLiteral("private operations"), m_indentation, java);
writeBlankLine(java);
}
*/
writeOperations(oppriv, java);
}
/**
* Write a list of operations for a given class.
* @param oplist the list of operations you want to write
* @param java the stream associated with the output file
*/
void JavaWriter::writeOperations(UMLOperationList &oplist, QTextStream &java)
{
UMLAttributeList atl;
int i, j;
QString str;
// generate method decl for each operation given
for (UMLOperation* op : oplist) {
QString doc;
// write documentation
QString methodReturnType = fixTypeName(op->getTypeName());
if (methodReturnType != QStringLiteral("void"))
doc += QStringLiteral("@return ") + methodReturnType + QLatin1Char('\n');
str = QString(); // reset for next method
str += ((op->isAbstract() && !m_isInterface) ? QStringLiteral("abstract ") : QString());
str += Uml::Visibility::toString(op->visibility()) + QLatin1Char(' ');
str += (op->isStatic() ? QStringLiteral("static ") : QString());
str += methodReturnType + QLatin1Char(' ') + cleanName(op->name()) + QLatin1Char('(');
atl = op->getParmList();
i= atl.count();
j=0;
for (UMLAttribute* at : atl) {
QString typeName = fixTypeName(at->getTypeName());
QString atName = cleanName(at->name());
str += typeName + QLatin1Char(' ') + atName +
(!(at->getInitialValue().isEmpty()) ?
(QStringLiteral(" = ") + at->getInitialValue()) : QString())
+ ((j < i-1) ? QStringLiteral(", ") : QString());
doc += QStringLiteral("@param ") + atName + QLatin1Char(' ') + at->doc() + QLatin1Char('\n');
j++;
}
doc = doc.remove(doc.size() - 1, 1); // remove last '\n' of comment
str += QLatin1Char(')');
// method only gets a body IF it is not abstract
if (op->isAbstract() || m_isInterface)
str += QStringLiteral(";\n\n"); // terminate now
else {
str += m_startline + QLatin1Char('{') + m_endl;
QString sourceCode = op->getSourceCode();
if (sourceCode.isEmpty()) {
// empty method body - TODO: throw exception
}
else {
str += formatSourceCode(sourceCode, m_indentation + m_indentation);
}
str += m_indentation + QLatin1Char('}') + m_endl + m_endl;
}
// write it out
writeDocumentation(QString(), op->doc(), doc, m_indentation, java);
java << m_startline << str;
}
}
/**
* Check that initial values of strings have quotes around them.
*/
QString JavaWriter::fixInitialStringDeclValue(const QString& val, const QString& type)
{
QString value = val;
// check for strings only
if (!value.isEmpty() && type == QStringLiteral("String")) {
if (!value.startsWith(QLatin1Char('"')))
value.prepend(QLatin1Char('"'));
if (!value.endsWith(QLatin1Char('"')))
value.append(QLatin1Char('"'));
}
return value;
}
/**
* Returns the name of the given object (if it exists).
*/
QString JavaWriter::getUMLObjectName(UMLObject *obj)
{
return (obj ? obj->name() : QStringLiteral("NULL"));
}
/**
* Write a blank line.
* Note: Methods like this _shouldn't_ be needed IF we properly did things thruought the code.
*/
void JavaWriter::writeBlankLine(QTextStream &java)
{
java << m_endl;
}
| 36,910
|
C++
|
.cpp
| 891
| 33.746352
| 259
| 0.622699
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,580
|
javacodegenerator.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodegenerator.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodegenerator.h"
// local includes
#include "javacodecomment.h"
#include "codeviewerdialog.h"
#include "uml.h"
#include "umbrellosettings.h"
// kde includes
#include <kconfig.h>
#include <KLocalizedString>
#include <KMessageBox>
// qt includes
#include <QRegularExpression>
static const char *reserved_words[] = {
"abstract",
"AbstractMethodError",
"ArithmeticException",
"ArrayIndexOutOfBoundsException",
"ArrayStoreException",
"assert",
"AssertionError",
"auto",
"boolean",
"Boolean",
"break",
"byte",
"Byte",
"catch",
"char",
"Character",
"CharSequence",
"Class",
"ClassCastException",
"ClassCircularityError",
"ClassFormatError",
"ClassLoader",
"ClassNotFoundException",
"clone",
"Cloneable",
"CloneNotSupportedException",
"Comparable",
"Compiler",
"const",
"continue",
"default",
"delete",
"do",
"double",
"Double",
"else",
"enum",
"equals",
"Error",
"Exception",
"ExceptionInInitializerError",
"extends",
"extern",
"false",
"final",
"finalize",
"finally",
"float",
"Float",
"for",
"friend",
"getClass",
"goto",
"hashCode",
"if",
"IllegalAccessError",
"IllegalAccessException",
"IllegalArgumentException",
"IllegalMonitorStateException",
"IllegalStateException",
"IllegalThreadStateException",
"implements",
"import",
"IncompatibleClassChangeError",
"IndexOutOfBoundsException",
"InheritableThreadLocal",
"inline",
"instanceof",
"InstantiationError",
"InstantiationException",
"int",
"Integer",
"interface",
"InternalError",
"InterruptedException",
"LinkageError",
"long",
"Long",
"Math",
"native",
"NegativeArraySizeException",
"new",
"nextgroup=javaUserLabelRef",
"NoClassDefFoundError",
"NoSuchFieldError",
"NoSuchFieldException",
"NoSuchMethodError",
"NoSuchMethodException",
"notifyAll",
"null",
"NullPointerException",
"Number",
"NumberFormatException",
"Object",
"operator",
"OutOfMemoryError",
"package",
"Package",
"private",
"Process",
"protected",
"redeclared",
"register",
"return",
"Runnable",
"Runtime",
"RuntimeException",
"RuntimePermission",
"SecurityException",
"SecurityManager",
"serializable",
"short",
"Short",
"signed",
"sizeof",
"skipwhite",
"StackOverflowError",
"StackTraceElement",
"static",
"strictfp",
"StrictMath",
"String",
"StringBuffer",
"StringIndexOutOfBoundsException",
"struct",
"super",
"switch",
"synchronized",
"template",
"this",
"Thread",
"ThreadDeath",
"ThreadGroup",
"ThreadLocal",
"throw",
"Throwable",
"throws",
"toString",
"transient",
"true",
"try",
"typedef",
"union",
"UnknownError",
"UnsatisfiedLinkError",
"unsigned",
"UnsupportedClassVersionError",
"UnsupportedOperationException",
"VirtualMachineError",
"void",
"Void",
"volatile",
"wait",
"while",
nullptr
};
/**
* Constructor.
*/
JavaCodeGenerator::JavaCodeGenerator()
: AdvancedCodeGenerator()
{
// load Classifier documents from parent document
//initFromParentDocument();
// add in an ANT document
JavaANTCodeDocument * buildDoc = newANTCodeDocument();
addCodeDocument(buildDoc);
// set our 'writeout' policy for that code document
setCreateANTBuildFile(UmbrelloSettings::buildANTDocumentJava());
connectSlots();
}
/**
* Destructor.
*/
JavaCodeGenerator::~JavaCodeGenerator()
{
}
/**
* Return "Java".
* @return programming language identifier
*/
Uml::ProgrammingLanguage::Enum JavaCodeGenerator::language() const
{
return Uml::ProgrammingLanguage::Java;
}
/**
* Set the value of m_createANTBuildFile
* @param buildIt the new value of m_createANTBuildFile
*/
void JavaCodeGenerator::setCreateANTBuildFile(bool buildIt)
{
m_createANTBuildFile = buildIt;
CodeDocument * antDoc = findCodeDocumentByID(QStringLiteral("ANTDOC"));
if (antDoc)
antDoc->setWriteOutCode(buildIt);
}
/**
* Get the value of m_createANTBuildFile
* @return the value of m_createANTBuildFile
*/
bool JavaCodeGenerator::getCreateANTBuildFile()
{
return m_createANTBuildFile;
}
/**
* Get the editing dialog for this code document.
* In the Java version, we make the ANT build file also available.
*/
CodeViewerDialog * JavaCodeGenerator::getCodeViewerDialog(QWidget* parent, CodeDocument *doc,
Settings::CodeViewerState & state)
{
CodeViewerDialog *dialog = new CodeViewerDialog(parent, doc, state);
if(getCreateANTBuildFile())
dialog->addCodeDocument(findCodeDocumentByID(QStringLiteral("ANTDOC")));
return dialog;
}
/**
* Utility function for getting the java code generation policy.
*/
JavaCodeGenerationPolicy * JavaCodeGenerator::getJavaPolicy()
{
return dynamic_cast<JavaCodeGenerationPolicy*>(UMLApp::app()->policyExt());
}
/**
* A utility method to get the javaCodeGenerationPolicy()->getAutoGenerateAttribAccessors() value.
*/
bool JavaCodeGenerator::getAutoGenerateAttribAccessors()
{
return getJavaPolicy()->getAutoGenerateAttribAccessors ();
}
/**
* A utility method to get the javaCodeGenerationPolicy()->getAutoGenerateAssocAccessors() value.
*/
bool JavaCodeGenerator::getAutoGenerateAssocAccessors()
{
return getJavaPolicy()->getAutoGenerateAssocAccessors ();
}
/**
* Get the list variable class name to use. For Java, we have set this to "Vector".
*/
QString JavaCodeGenerator::getListFieldClassName()
{
return QStringLiteral("Vector");
}
/**
* IF the type is "string" we need to declare it as
* the Java Object "String" (there is no string primitive in Java).
* Same thing again for "bool" to "boolean".
*/
QString JavaCodeGenerator::fixTypeName(const QString &string)
{
if (string.isEmpty() || string.contains(QRegularExpression(QStringLiteral("^\\s+$"))))
return QStringLiteral("void");
if (string == QStringLiteral("string"))
return QStringLiteral("String");
if (string == QStringLiteral("bool"))
return QStringLiteral("boolean");
return cleanName(string);
}
/**
* Create ANT code document.
* @return JavaANTCodeDocument object
*/
JavaANTCodeDocument * JavaCodeGenerator::newANTCodeDocument()
{
return new JavaANTCodeDocument();
}
/**
* Create a classifier code document.
* @param classifier the UML classifier
* @return the created classifier code document
*/
CodeDocument * JavaCodeGenerator::newClassifierCodeDocument(UMLClassifier * classifier)
{
JavaClassifierCodeDocument * doc = new JavaClassifierCodeDocument(classifier);
doc->initCodeClassFields();
return doc;
}
/**
* Adds Java's primitives as datatypes.
* @return a string list of Java primitives
*/
QStringList JavaCodeGenerator::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("int"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("boolean"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("byte"));
l.append(QStringLiteral("short"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("String"));
l.append(QStringLiteral("Integer"));
l.append(QStringLiteral("Character"));
l.append(QStringLiteral("Boolean"));
l.append(QStringLiteral("Float"));
l.append(QStringLiteral("Double"));
l.append(QStringLiteral("Byte"));
l.append(QStringLiteral("Short"));
l.append(QStringLiteral("Long"));
l.append(QStringLiteral("StringBuffer"));
l.append(QStringLiteral("StringBuilder"));
return l;
}
/**
* Get list of reserved keywords.
* @return the string list of reserved keywords for Java
*/
QStringList JavaCodeGenerator::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
for (int i = 0; reserved_words[i]; ++i) {
keywords.append(QLatin1String(reserved_words[i]));
}
}
return keywords;
}
| 8,488
|
C++
|
.cpp
| 339
| 21.117994
| 98
| 0.697981
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,581
|
javaantcodedocument.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javaantcodedocument.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javaantcodedocument.h"
// local includes
#include "debug_utils.h"
#include "javacodegenerator.h"
#include "xmlcodecomment.h"
#include "xmlelementcodeblock.h"
#include "codegenfactory.h"
#include "umldoc.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
#include <QXmlStreamWriter>
DEBUG_REGISTER(JavaANTCodeDocument)
JavaANTCodeDocument::JavaANTCodeDocument ()
{
setFileName(QStringLiteral("build")); // default name
setFileExtension(QStringLiteral(".xml"));
setID(QStringLiteral("ANTDOC")); // default id tag for this type of document
}
JavaANTCodeDocument::~JavaANTCodeDocument ()
{
}
//**
// * create a new CodeBlockWithComments object belonging to this CodeDocument.
// * @return CodeBlockWithComments
// */
/*
CodeBlockWithComments * JavaANTCodeDocument::newCodeBlockWithComments ()
{
return new XMLElementCodeBlock(this,"empty");
}
*/
HierarchicalCodeBlock * JavaANTCodeDocument::newHierarchicalCodeBlock ()
{
return new XMLElementCodeBlock(this, QStringLiteral("empty"));
}
// Sigh. NOT optimal. The only reason that we need to have this
// is so we can create the XMLNodes, if needed.
// would be better if we could create a handler interface that each
// codeblock used so all we have to do here is add the handler
void JavaANTCodeDocument::loadChildTextBlocksFromNode (QDomElement & root)
{
QDomNode tnode = root.firstChild();
QDomElement telement = tnode.toElement();
bool loadCheckForChildrenOK = false;
while (!telement.isNull()) {
QString nodeName = telement.tagName();
if (nodeName == QStringLiteral("textblocks")) {
QDomNode node = telement.firstChild();
QDomElement element = node.toElement();
// if there is nothing to begin with, then we don't worry about it
loadCheckForChildrenOK = element.isNull() ? true : false;
while (!element.isNull()) {
QString name = element.tagName();
if (name == QStringLiteral("codecomment")) {
CodeComment * block = new XMLCodeComment(this);
block->loadFromXMI(element);
if (!addTextBlock(block))
{
logError0("JavaANTCodeDocument: Unable to add codeComment");
delete block;
} else
loadCheckForChildrenOK= true;
} else if (name == QStringLiteral("codeaccessormethod") ||
name == QStringLiteral("ccfdeclarationcodeblock")) {
QString acctag = element.attribute(QStringLiteral("tag"));
// search for our method in the
TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
if (!tb || !addTextBlock(tb)) {
logError0("JavaANTCodeDocument: Unable to add codeclassfield child method");
// DON'T delete
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblock")) {
CodeBlock * block = newCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaANTCodeDocument: Unable to add codeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeblockwithcomments")) {
CodeBlockWithComments * block = newCodeBlockWithComments();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaANTCodeDocument: Unable to add codeBlockwithcomments");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("header")) {
// do nothing.. this is treated elsewhere
} else if (name == QStringLiteral("hierarchicalcodeblock")) {
HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("JavaANTCodeDocument: Unable to add hierarchicalcodeBlock");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else if (name == QStringLiteral("codeoperation")) {
// find the code operation by id
QString id = element.attribute(QStringLiteral("parent_id"),QStringLiteral("-1"));
UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
const UMLOperation * op = obj->asUMLOperation();
if (op) {
CodeOperation *block = nullptr;
logWarn0("TODO: implement CodeGenFactory::newCodeOperation() for JavaANTCodeDocument");
break; // remove when above is implemented
block->loadFromXMI(element);
if (addTextBlock(block)) {
loadCheckForChildrenOK= true;
} else {
logError0("JavaANTCodeDocument: Unable to add codeoperation");
block->deleteLater();
}
} else {
logError0("JavaANTCodeDocument: Unable to find operation create codeoperation");
}
} else if (name == QStringLiteral("xmlelementblock")) {
QString xmltag = element.attribute(QStringLiteral("nodeName"),QStringLiteral("UNKNOWN"));
XMLElementCodeBlock * block = new XMLElementCodeBlock(this, xmltag);
block->loadFromXMI(element);
if (!addTextBlock(block)) {
logError0("Unable to add XMLelement to Java ANT document");
delete block;
} else {
loadCheckForChildrenOK= true;
}
} else {
logDebug1("JavaANTCodeDocument::loadChildTextBlocksFromNode: Got strange tag in "
"text block stack: %1, ignoring", name);
}
node = element.nextSibling();
element = node.toElement();
}
break;
}
tnode = telement.nextSibling();
telement = tnode.toElement();
}
if (!loadCheckForChildrenOK)
{
logWarn1("loadChildBlocks : unable to initialize any child blocks in doc %1", getFileName());
}
}
/** set the class attributes of this object from
* the passed element node.
*/
void JavaANTCodeDocument::setAttributesFromNode (QDomElement & root)
{
// superclass save
CodeDocument::setAttributesFromNode(root);
// now set local attributes
// setPackage(root.attribute("package"));
}
/**
* load params from the appropriate XMI element node.
*/
void JavaANTCodeDocument::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
/** set attributes of the node that represents this class
* in the XMI document.
*/
void JavaANTCodeDocument::setAttributesOnNode (QXmlStreamWriter& writer)
{
// superclass call
CodeDocument::setAttributesOnNode(writer);
// now set local attributes/fields
//FIX
}
/**
* Save the XMI representation of this object
*/
void JavaANTCodeDocument::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("codedocument"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
// we add in our code blocks that describe how to generate
// the project here...
void JavaANTCodeDocument::updateContent()
{
// FIX : fill in more content based on classes
// which exist
CodeBlockWithComments * xmlDecl = getCodeBlockWithComments(QStringLiteral("xmlDecl"), QString(), 0);
xmlDecl->setText(QStringLiteral("<?xml version=\"1.0\"?>"));
addTextBlock(xmlDecl);
XMLElementCodeBlock * rootNode = new XMLElementCodeBlock(this, QStringLiteral("project"), QStringLiteral("Java ANT build document"));
rootNode->setTag(QStringLiteral("projectDecl"));
addTextBlock(rootNode);
// <project name="XDF" default="help" basedir=".">
//HierarchicalCodeBlock * projDecl = xmlDecl->getHierarchicalCodeBlock("projectDecl", "Java ANT build document", 1);
// set some global properties for the build
/*
<!-- set global properties for this build -->
<!-- paths -->
<property name="docApi.dir" value="docs/api"/>
<property name="path" value="gov/nasa/gsfc/adc/xdf"/>
<property name="src" value="src/${path}/"/>
<property name="top" value="."/>
<property name="build" value="${top}/gov"/>
<property name="buildDir" value="${path}"/>
<!-- compiler directives -->
<property name="build.compiler" value="modern"/>
<property name="useDeprecation" value="no"/>
<property name="jarname" value="${project}.jar"/>
*/
}
// We overwritten by Java language implementation to get lowercase path
QString JavaANTCodeDocument::getPath () const
{
QString path = getPackage();
// Replace all white spaces with blanks
path = path.simplified();
// Replace all blanks with underscore
path.replace(QRegularExpression(QStringLiteral(" ")), QStringLiteral("_"));
path.replace(QRegularExpression(QStringLiteral("\\.")),QStringLiteral("/"));
path.replace(QRegularExpression(QStringLiteral("::")), QStringLiteral("/"));
path = path.toLower();
return path;
}
| 10,235
|
C++
|
.cpp
| 234
| 33.132479
| 137
| 0.605802
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,582
|
javacodeaccessormethod.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodeaccessormethod.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodeaccessormethod.h"
// local includes
#include "attribute.h"
#include "codegenerator.h"
#include "codegenerationpolicy.h"
#include "classifiercodedocument.h"
#include "debug_utils.h"
#include "umlobject.h"
#include "umlrole.h"
#include "uml.h"
#include "codegen_utils.h"
#include "javaclassifiercodedocument.h"
#include "javacodegenerationpolicy.h"
#include "javacodeclassfield.h"
#include "javacodedocumentation.h"
// qt includes
#include <QXmlStreamWriter>
JavaCodeAccessorMethod::JavaCodeAccessorMethod (CodeClassField * field, CodeAccessorMethod::AccessorType type)
: CodeAccessorMethod (field)
{
setType(type);
// lets use full-blown comment
JavaClassifierCodeDocument* jccd = dynamic_cast<JavaClassifierCodeDocument*>(field->getParentDocument());
setComment(new JavaCodeDocumentation(jccd));
}
JavaCodeAccessorMethod::~JavaCodeAccessorMethod ()
{
}
void JavaCodeAccessorMethod::setAttributesOnNode (QXmlStreamWriter& writer)
{
// set super-class attributes
CodeAccessorMethod::setAttributesOnNode(writer);
// set local attributes now
}
void JavaCodeAccessorMethod::setAttributesFromNode(QDomElement & root)
{
// set attributes from superclass method the XMI
CodeAccessorMethod::setAttributesFromNode(root);
// load local stuff
}
void JavaCodeAccessorMethod::updateContent()
{
CodeClassField * parentField = getParentClassField();
JavaCodeClassField * javafield = dynamic_cast<JavaCodeClassField*>(parentField);
QString fieldName = javafield->getFieldName();
QString text;
switch(getType()) {
case CodeAccessorMethod::ADD:
{
int maxOccurs = javafield->maximumListOccurances();
QString fieldType = javafield->getTypeName();
QString indent = getIndentation();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
if(maxOccurs > 0)
text += QStringLiteral("if (") + fieldName + QStringLiteral(".size() < ") + QString::number(maxOccurs) + QStringLiteral(") {") + endLine + indent;
text += fieldName + QStringLiteral(".add(value);");
if(maxOccurs > 0)
{
text += endLine + QStringLiteral("} else {") + endLine;
text += indent + QStringLiteral("System.err.println(\"ERROR: Cant add") + fieldType + QStringLiteral(" to ") + fieldName + QStringLiteral(", minimum number of items reached.\");") + endLine + QLatin1Char('}') + endLine;
}
break;
}
case CodeAccessorMethod::GET:
text = QStringLiteral("return ") + fieldName + QLatin1Char(';');
break;
case CodeAccessorMethod::LIST:
text = QStringLiteral("return (List) ") + fieldName + QLatin1Char(';');
break;
case CodeAccessorMethod::REMOVE:
{
int minOccurs = javafield->minimumListOccurances();
QString fieldType = javafield->getTypeName();
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
QString indent = getIndentation();
if(minOccurs > 0)
text += QStringLiteral("if (") + fieldName + QStringLiteral(".size() >= ") + QString::number(minOccurs) + QStringLiteral(") {") + endLine + indent;
text += fieldName + QStringLiteral(".remove(value);");
if(minOccurs > 0)
{
text += endLine + QStringLiteral("} else {") + endLine;
text += indent + QStringLiteral("System.err.println(\"ERROR: Cant remove") + fieldType + QStringLiteral(" from ") + fieldName + QStringLiteral(", minimum number of items reached.\");") + endLine + QLatin1Char('}') + endLine;
}
break;
}
case CodeAccessorMethod::SET:
text = fieldName + QStringLiteral(" = value;");
break;
default:
// do nothing
break;
}
setText(text);
}
void JavaCodeAccessorMethod::updateMethodDeclaration()
{
JavaCodeClassField * javafield = dynamic_cast<JavaCodeClassField*>(getParentClassField());
CodeGenerationPolicy *commonpolicy = UMLApp::app()->commonPolicy();
// gather defs
Uml::Visibility::Enum scopePolicy = commonpolicy->getAttributeAccessorScope();
QString strVis = Uml::Visibility::toString(javafield->getVisibility());
QString fieldName = javafield->getFieldName();
if (fieldName.isEmpty()) {
logError0("empty FieldName in ParentClassField");
return;
}
QString fieldType = javafield->getTypeName();
QString objectType = javafield->getListObjectType();
if(objectType.isEmpty())
objectType = fieldName;
QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();
// set scope of this accessor appropriately..if its an attribute,
// we need to be more sophisticated
if(javafield->parentIsAttribute())
switch (scopePolicy) {
case Uml::Visibility::Public:
case Uml::Visibility::Private:
case Uml::Visibility::Protected:
strVis = Uml::Visibility::toString(scopePolicy);
break;
default:
case Uml::Visibility::FromParent:
// do nothing..already have taken parent value
break;
}
// some variables we will need to populate
QString headerText;
QString methodReturnType;
QString methodName;
QString methodParams;
switch(getType()) {
case CodeAccessorMethod::ADD:
methodName = QStringLiteral("add") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Add an object of type ") + objectType + QStringLiteral(" to the List ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return void");
break;
case CodeAccessorMethod::GET:
methodName = QStringLiteral("get") + Codegen_Utils::capitalizeFirstLetter(fieldName);
methodReturnType = fieldType;
headerText = QStringLiteral("Get the value of ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return the value of ") + fieldName;
break;
case CodeAccessorMethod::LIST:
methodName = QStringLiteral("get") + Codegen_Utils::capitalizeFirstLetter(fieldType) + QStringLiteral("List");
methodReturnType = QStringLiteral("List");
headerText = QStringLiteral("Get the list of ") + fieldName + endLine + getParentObject()->doc() + endLine + QStringLiteral("@return List of ") + fieldName;
break;
case CodeAccessorMethod::REMOVE:
methodName = QStringLiteral("remove") + Codegen_Utils::capitalizeFirstLetter(fieldType);
methodReturnType = QStringLiteral("void");
methodParams = objectType + QStringLiteral(" value ");
headerText = QStringLiteral("Remove an object of type ") + objectType + QStringLiteral(" from the List ") + fieldName + endLine + getParentObject()->doc();
break;
case CodeAccessorMethod::SET:
methodName = QStringLiteral("set") + Codegen_Utils::capitalizeFirstLetter(fieldName);
methodReturnType = QStringLiteral("void");
methodParams = fieldType + QStringLiteral(" value ");
headerText = QStringLiteral("Set the value of ") + fieldName + endLine + getParentObject()->doc() + endLine;
break;
default:
// do nothing..no idea what this is
logWarn1("Warning: cant generate JavaCodeAccessorMethod for type: %1", getType());
break;
}
// set header once.
if(getComment()->getText().isEmpty())
getComment()->setText(headerText);
// set start/end method text
setStartMethodText(strVis + QLatin1Char(' ') + methodReturnType + QLatin1Char(' ') + methodName + QStringLiteral(" (") + methodParams + QStringLiteral(") {"));
setEndMethodText(QStringLiteral("}"));
}
void JavaCodeAccessorMethod::update()
{
updateMethodDeclaration();
updateContent();
}
| 8,313
|
C++
|
.cpp
| 182
| 38.884615
| 240
| 0.678796
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,583
|
javacodegenerationpolicy.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodegenerationpolicy.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodegenerationpolicy.h"
// app includes
#include "javacodegenerationpolicypage.h"
#include "javacodegenerator.h"
#include "optionstate.h"
#include "uml.h"
#include "umbrellosettings.h"
// kde includes
#include <kconfig.h>
/*
JavaCodeGenerationPolicy::JavaCodeGenerationPolicy(CodeGenerationPolicy *defaults)
: CodeGenerationPolicy(defaults)
{
init();
setDefaults(defaults, false);
}
*/
/**
* Constructor.
*/
JavaCodeGenerationPolicy::JavaCodeGenerationPolicy()
// : CodeGenerationPolicy()
{
m_commonPolicy = UMLApp::app()->commonPolicy();
init();
}
/**
* Empty Destructor.
*/
JavaCodeGenerationPolicy::~JavaCodeGenerationPolicy()
{
}
/**
* Set the value of m_autoGenerateAttribAccessors.
* @param var the new value
*/
void JavaCodeGenerationPolicy::setAutoGenerateAttribAccessors(bool var)
{
Settings::optionState().codeGenerationState.javaCodeGenerationState.autoGenerateAttributeAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Set the value of m_autoGenerateAssocAccessors.
* @param var the new value
*/
void JavaCodeGenerationPolicy::setAutoGenerateAssocAccessors(bool var)
{
Settings::optionState().codeGenerationState.javaCodeGenerationState.autoGenerateAssocAccessors = var;
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Get the value of m_autoGenerateAttribAccessors.
* @return the value of m_autoGenerateAttribAccessors
*/
bool JavaCodeGenerationPolicy::getAutoGenerateAttribAccessors()
{
return Settings::optionState().codeGenerationState.javaCodeGenerationState.autoGenerateAttributeAccessors;
}
/**
* Get the value of m_autoGenerateAssocAccessors
* @return the value of m_autoGenerateAssocAccessors
*/
bool JavaCodeGenerationPolicy::getAutoGenerateAssocAccessors()
{
return Settings::optionState().codeGenerationState.javaCodeGenerationState.autoGenerateAssocAccessors;
}
/**
* Set the defaults for this code generator from the passed generator.
* @param defaults the defaults to set
* @param emitUpdateSignal flag whether update signal has to be emitted
*/
void JavaCodeGenerationPolicy::setDefaults (CodeGenPolicyExt * defaults, bool emitUpdateSignal)
{
JavaCodeGenerationPolicy * jclone;
if (!defaults)
return;
// NOW block signals for java param setting
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
// now do java-specific stuff IF our clone is also a JavaCodeGenerationPolicy object
if((jclone = dynamic_cast<JavaCodeGenerationPolicy*>(defaults)))
{
setAutoGenerateAttribAccessors(jclone->getAutoGenerateAttribAccessors());
setAutoGenerateAssocAccessors(jclone->getAutoGenerateAssocAccessors());
}
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Set the defaults from a config file for this code generator from the passed KConfig pointer.
* @param emitUpdateSignal flag whether update signal has to be emitted
*/
void JavaCodeGenerationPolicy::setDefaults(bool emitUpdateSignal)
{
// call method at the common policy to init default stuff
m_commonPolicy->setDefaults(false);
// NOW block signals (because call to super-class method will leave value at "true")
blockSignals(true); // we need to do this because otherwise most of these
// settors below will each send the modifiedCodeContent() signal
// needlessly (we can just make one call at the end).
setAutoGenerateAttribAccessors(UmbrelloSettings::autoGenerateAttributeAccessorsJava());
setAutoGenerateAssocAccessors(UmbrelloSettings::autoGenerateAssocAccessorsJava());
CodeGenerator *codegen = UMLApp::app()->generator();
JavaCodeGenerator *javacodegen = dynamic_cast<JavaCodeGenerator*>(codegen);
if (javacodegen) {
bool mkant = UmbrelloSettings::buildANTDocumentJava();
javacodegen->setCreateANTBuildFile(mkant);
}
blockSignals(false); // "as you were citizen"
if(emitUpdateSignal)
m_commonPolicy->emitModifiedCodeContentSig();
}
/**
* Create a new dialog interface for this object.
* @param parent the parent widget
* @param name page name
* @return dialog object
*/
CodeGenerationPolicyPage * JavaCodeGenerationPolicy::createPage (QWidget *parent, const char *name)
{
return new JavaCodeGenerationPolicyPage (parent, name, this);
}
/**
* Initialisation.
*/
void JavaCodeGenerationPolicy::init()
{
blockSignals(true);
Settings::OptionState optionState = Settings::optionState();
setAutoGenerateAttribAccessors(optionState.codeGenerationState.javaCodeGenerationState.autoGenerateAttributeAccessors);
setAutoGenerateAssocAccessors(optionState.codeGenerationState.javaCodeGenerationState.autoGenerateAssocAccessors);
blockSignals(false);
}
| 5,224
|
C++
|
.cpp
| 141
| 33.93617
| 123
| 0.78125
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,584
|
javaclassdeclarationblock.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javaclassdeclarationblock.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "javaclassdeclarationblock.h"
#include "codegenerator.h"
#include "codegenerationpolicy.h"
#include "javacodedocumentation.h"
#include "uml.h"
JavaClassDeclarationBlock::JavaClassDeclarationBlock
(JavaClassifierCodeDocument * parentDoc, const QString &startText, const QString &endText, const QString &comment)
: OwnedHierarchicalCodeBlock(parentDoc->getParentClassifier(), parentDoc, startText, endText, comment)
{
init(parentDoc, comment);
}
JavaClassDeclarationBlock::~JavaClassDeclarationBlock ()
{
}
/**
* Save the XMI representation of this object
*/
void JavaClassDeclarationBlock::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("javaclassdeclarationblock"));
setAttributesOnNode(writer);
writer.writeEndElement();
}
/**
* load params from the appropriate XMI element node.
*/
void JavaClassDeclarationBlock::loadFromXMI (QDomElement & root)
{
setAttributesFromNode(root);
}
/**
* update the start and end text for this ownedhierarchicalcodeblock.
*/
void JavaClassDeclarationBlock::updateContent ()
{
JavaClassifierCodeDocument *parentDoc = dynamic_cast<JavaClassifierCodeDocument*>(getParentDocument());
Q_ASSERT(parentDoc);
UMLClassifier *c = parentDoc->getParentClassifier();
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
QString endLine = commonPolicy->getNewLineEndingChars();
bool isInterface = parentDoc->parentIsInterface(); // a little shortcut
QString JavaClassName = parentDoc->getJavaClassName(c->name());
// COMMENT
if (isInterface)
getComment()->setText(QStringLiteral("Interface ")+JavaClassName+endLine+c->doc());
else
getComment()->setText(QStringLiteral("Class ")+JavaClassName+endLine+c->doc());
bool forceDoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
if (forceDoc || !c->doc().isEmpty())
getComment()->setWriteOutText(true);
else
getComment()->setWriteOutText(false);
// Now set START/ENDING Text
QString startText;
// In Java, we need declare abstract only on classes
if (c->isAbstract() && !isInterface)
startText.append(QStringLiteral("abstract "));
if (c->visibility() != Uml::Visibility::Public) {
// We should probably emit a warning in here .. java doesn't like to allow
// private/protected classes. The best we can do (I believe)
// is to let these declarations default to "package visibility"
// which is a level between traditional "private" and "protected"
// scopes. To get this visibility level we just print nothing..
} else
startText.append(QStringLiteral("public "));
if (parentDoc->parentIsInterface())
startText.append(QStringLiteral("interface "));
else
startText.append(QStringLiteral("class "));
startText.append(JavaClassName);
// write inheritances out
UMLClassifierList superclasses =
c->findSuperClassConcepts(UMLClassifier::CLASS);
UMLClassifierList superinterfaces =
c->findSuperClassConcepts(UMLClassifier::INTERFACE);
int nrof_superclasses = superclasses.count();
int nrof_superinterfaces = superinterfaces.count();
// write out inheritance
int i = 0;
if (nrof_superclasses >0)
startText.append(QStringLiteral(" extends "));
for (UMLClassifier* classifier: superclasses) {
startText.append(parentDoc->cleanName(classifier->name()));
if(i != (nrof_superclasses-1))
startText.append(QStringLiteral(", "));
i++;
}
// write out what we 'implement'
i = 0;
if(nrof_superinterfaces >0)
{
// In Java interfaces "extend" other interfaces. Classes "implement" interfaces
if(isInterface)
startText.append(QStringLiteral(" extends "));
else
startText.append(QStringLiteral(" implements "));
}
for (UMLClassifier* classifier: superinterfaces) {
startText.append(parentDoc->cleanName(classifier->name()));
if(i != (nrof_superinterfaces-1))
startText.append(QStringLiteral(", "));
i++;
}
// Set the header and end text for the hier.codeblock
setStartText(startText+QStringLiteral(" {"));
// setEndText(QStringLiteral("}")); // not needed
}
void JavaClassDeclarationBlock::init (JavaClassifierCodeDocument *parentDoc, const QString &comment)
{
setComment(new JavaCodeDocumentation(parentDoc));
getComment()->setText(comment);
setEndText(QStringLiteral("}"));
}
| 4,797
|
C++
|
.cpp
| 118
| 35.440678
| 115
| 0.7172
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,585
|
javacodedocumentation.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodedocumentation.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodedocumentation.h"
// local includes
#include "codegenerationpolicy.h"
#include "javaclassifiercodedocument.h"
#include "uml.h"
// qt includes
#include <QRegularExpression>
JavaCodeDocumentation::JavaCodeDocumentation(JavaClassifierCodeDocument * doc, const QString & text)
: CodeComment(doc, text)
{
}
JavaCodeDocumentation::~JavaCodeDocumentation()
{
}
/**
* Save the XMI representation of this object
*/
void JavaCodeDocumentation::saveToXMI(QXmlStreamWriter& writer)
{
writer.writeStartElement(QStringLiteral("javacodedocumentation"));
setAttributesOnNode(writer); // as we added no additional fields to this class we may
// just use parent TextBlock method
writer.writeEndElement();
}
/**
* @return QString
*/
QString JavaCodeDocumentation::toString() const
{
QString output;
// simple output method
if(getWriteOutText())
{
bool useDoubleDashOutput = true;
// need to figure out output type from java policy
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
useDoubleDashOutput = false;
QString indent = getIndentationString();
QString endLine = getNewLineEndingChars();
QString body = getText();
if(useDoubleDashOutput)
{
if(!body.isEmpty())
output.append(formatMultiLineText (body, indent + QStringLiteral("// "), endLine));
} else {
output.append(indent + QStringLiteral("/**") + endLine);
output.append(formatMultiLineText (body, indent + QStringLiteral(" * "), endLine));
output.append(indent + QStringLiteral(" */") + endLine);
}
}
return output;
}
QString JavaCodeDocumentation::getNewEditorLine(int amount)
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return getIndentationString(amount) + QStringLiteral(" * ");
else
return getIndentationString(amount) + QStringLiteral("// ");
}
int JavaCodeDocumentation::firstEditableLine()
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
return 1;
return 0;
}
int JavaCodeDocumentation::lastEditableLine()
{
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
return -1; // very last line is NOT editable
}
return 0;
}
/** UnFormat a long text string. Typically, this means removing
* the indentation (linePrefix) and/or newline chars from each line.
*/
QString JavaCodeDocumentation::unformatText(const QString & text, const QString & indent)
{
QString mytext = TextBlock::unformatText(text, indent);
CodeGenerationPolicy *p = UMLApp::app()->commonPolicy();
// remove leading or trailing comment stuff
mytext.remove(QRegularExpression(QLatin1Char('^') + indent));
if(p->getCommentStyle() == CodeGenerationPolicy::MultiLine)
{
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\*\\*\\s*\n?")));
mytext.remove(QRegularExpression(QStringLiteral("\\s*\\*\\/\\s*\n?$")));
mytext.remove(QRegularExpression(QStringLiteral("^\\s*\\*\\s*")));
} else
mytext.remove(QRegularExpression(QStringLiteral("^\\/\\/\\s*")));
return mytext;
}
| 3,686
|
C++
|
.cpp
| 101
| 31.722772
| 100
| 0.700673
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,586
|
javacodegenerationpolicypage.cpp
|
KDE_umbrello/umbrello/codegenerators/java/javacodegenerationpolicypage.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov>
SPDX-FileCopyrightText: 2004-2020 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javacodegenerationpolicypage.h"
// app includes
#include "uml.h"
// kde includes
#include <KLocalizedString>
JavaCodeGenerationPolicyPage::JavaCodeGenerationPolicyPage(QWidget *parent, const char *name, JavaCodeGenerationPolicy * policy)
: CodeGenerationPolicyPage(parent, name, policy)
{
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
form = new JavaCodeGenerationFormBase(this);
form->m_SelectCommentStyle->setCurrentIndex((int)(commonPolicy->getCommentStyle()));
form->m_generateConstructors->setChecked(commonPolicy->getAutoGenerateConstructors());
form->m_generateAttribAccessors->setChecked(policy->getAutoGenerateAttribAccessors());
form->m_generateAssocAccessors->setChecked(policy->getAutoGenerateAssocAccessors());
form->m_accessorScopeCB->setCurrentIndex(commonPolicy->getAttributeAccessorScope());
form->m_assocFieldScopeCB->setCurrentIndex(commonPolicy->getAssociationFieldScope());
/**
* @todo unclean - CreateANTBuildFile attribute should be in java policy
CodeGenerator *codegen = UMLApp::app()->getGenerator();
JavaCodeGenerator *javacodegen = dynamic_cast<JavaCodeGenerator*>(codegen);
if (javacodegen)
form->m_makeANTDocumentCheckBox->setChecked(javacodegen->getCreateANTBuildFile());
*/
}
JavaCodeGenerationPolicyPage::~JavaCodeGenerationPolicyPage()
{
}
void JavaCodeGenerationPolicyPage::apply()
{
CodeGenerationPolicy *commonPolicy = UMLApp::app()->commonPolicy();
JavaCodeGenerationPolicy * parent = (JavaCodeGenerationPolicy*) m_parentPolicy;
// block signals so we don't cause too many update content calls to code documents
commonPolicy->blockSignals(true);
commonPolicy->setCommentStyle((CodeGenerationPolicy::CommentStyle) form->m_SelectCommentStyle->currentIndex());
commonPolicy->setAttributeAccessorScope(Uml::Visibility::fromInt(form->m_accessorScopeCB->currentIndex()));
commonPolicy->setAssociationFieldScope(Uml::Visibility::fromInt(form->m_assocFieldScopeCB->currentIndex()));
commonPolicy->setAutoGenerateConstructors(form->m_generateConstructors->isChecked());
parent->setAutoGenerateAttribAccessors(form->m_generateAttribAccessors->isChecked());
parent->setAutoGenerateAssocAccessors(form->m_generateAssocAccessors->isChecked());
/**
* @todo unclean - CreateANTBuildFile attribute should be in java policy
CodeGenerator *codegen = UMLApp::app()->getGenerator();
JavaCodeGenerator *javacodegen = dynamic_cast<JavaCodeGenerator*>(codegen);
if (javacodegen)
javacodegen->setCreateANTBuildFile(form->m_makeANTDocumentCheckBox->isChecked());
*/
commonPolicy->blockSignals(false);
// now send out modified code content signal
commonPolicy->emitModifiedCodeContentSig();
}
| 3,040
|
C++
|
.cpp
| 56
| 50.089286
| 128
| 0.784248
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
749,587
|
idlwriter.cpp
|
KDE_umbrello/umbrello/codegenerators/idl/idlwriter.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2003-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "idlwriter.h"
#include "umldoc.h"
#include "uml.h" // only needed for log{Warn,Error}
#include "debug_utils.h"
#include "classifier.h"
#include "debug_utils.h"
#include "enum.h"
#include "classifierlistitem.h"
#include "umlclassifierlistitemlist.h"
#include "package.h"
#include "association.h"
#include "attribute.h"
#include "operation.h"
#include <KMessageBox>
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
IDLWriter::IDLWriter() : SimpleCodeGenerator(false)
{
}
IDLWriter::~IDLWriter()
{
}
bool IDLWriter::isOOClass(UMLClassifier *c)
{
QString stype = c->stereotype();
QRegularExpression nonOO(QStringLiteral("(Constant|Enum|Struct|Union|Sequence|Array|Typedef)$"),
QRegularExpression::PatternOption::CaseInsensitiveOption);
if (stype.contains(nonOO))
return false;
// idlValue/CORBAValue, idlInterface/CORBAInterface, and empty/unknown stereotypes are
// assumed to designate OO classes.
return true;
}
bool IDLWriter::assocTypeIsMappableToAttribute(Uml::AssociationType::Enum at)
{
return (at == Uml::AssociationType::Aggregation || at == Uml::AssociationType::Association ||
at == Uml::AssociationType::Composition || at == Uml::AssociationType::UniAssociation);
}
/**
* Returns "IDL".
*/
Uml::ProgrammingLanguage::Enum IDLWriter::language() const
{
return Uml::ProgrammingLanguage::IDL;
}
void IDLWriter::computeAssocTypeAndRole(UMLAssociation *a, UMLClassifier *c,
QString& typeName, QString& roleName)
{
// Determine which is the "remote" end of the association:
bool IAmRoleA = true;
UMLObject *other = a->getObject(Uml::RoleType::B);
Uml::AssociationType::Enum at = a->getAssocType();
if (c->name() == other->name()) {
if (at == Uml::AssociationType::Aggregation || at == Uml::AssociationType::Composition ||
at == Uml::AssociationType::UniAssociation) {
// Assuming unidirectional association, and we are
// at the "wrong" side.
// Returning roleName = QString() tells caller to
// skip this association at this side.
roleName.clear();
return;
}
IAmRoleA = false;
other = a->getObject(Uml::RoleType::A);
}
// Construct the type name:
typeName = cleanName(other->name());
QString multiplicity;
if (IAmRoleA)
multiplicity = a->getMultiplicity(Uml::RoleType::B);
else
multiplicity = a->getMultiplicity(Uml::RoleType::A);
if (!multiplicity.isEmpty() && multiplicity != QStringLiteral("1"))
typeName.append(QStringLiteral("Vector"));
// Construct the member name:
if (IAmRoleA)
roleName = a->getRoleName(Uml::RoleType::B);
else
roleName = a->getRoleName(Uml::RoleType::A);
if (roleName.isEmpty()) {
roleName = a->name();
if (roleName.isEmpty()) {
roleName = QStringLiteral("m_") + typeName;
}
}
}
/**
* Call this method to generate IDL code for a UMLClassifier.
* @param c the class to generate code for
*/
void IDLWriter::writeClass(UMLClassifier *c)
{
if (!c) {
logWarn0("IDLWriter::writeClass: Cannot write class of NULL classifier");
return;
}
const bool isClass = !c->isInterface();
QString classname = cleanName(c->name());
//find an appropriate name for our file
QString fileName = findFileName(c, QStringLiteral(".idl"));
if (fileName.isEmpty()) {
Q_EMIT codeGenerated(c, false);
return;
}
QFile file;
if (!openFile(file, fileName)) {
Q_EMIT codeGenerated(c, false);
return;
}
// Start generating the code.
QTextStream idl(&file);
//try to find a heading file(license, comments, etc)
QString str;
str = getHeadingFile(QStringLiteral(".idl"));
if (!str.isEmpty()) {
str.replace(QRegularExpression(QStringLiteral("%filename%")), fileName);
str.replace(QRegularExpression(QStringLiteral("%filepath%")), file.fileName());
idl << str << m_endl;
}
// Write includes.
UMLPackageList includes;
findObjectsRelated(c, includes);
if (includes.count()) {
for(UMLPackage* conc : includes) {
if (conc->isUMLDatatype())
continue;
QString incName = findFileName(conc, QStringLiteral(".idl"));
if (!incName.isEmpty())
idl << "#include \"" << incName << "\"" << m_endl;
}
idl << m_endl;
}
// Generate the module declaration(s) for the package(s) in which
// we are embedded.
UMLPackageList pkgList = c->packages();
for(UMLPackage* pkg: pkgList) {
idl << indent() << "module " << pkg->name() << " {" << m_endl << m_endl;
m_indentLevel++;
}
// Write class Documentation if non-empty or if force option set.
if (forceDoc() || !c->doc().isEmpty()) {
idl << "//" << m_endl;
idl << "// class " << classname << m_endl;
idl << formatDoc(c->doc(), QStringLiteral("// "));
idl << m_endl;
}
if (c->baseType() == UMLObject::ot_Enum) {
UMLClassifierListItemList litList = c->getFilteredList(UMLObject::ot_EnumLiteral);
uint i = 0;
idl << indent() << "enum " << classname << " {" << m_endl;
m_indentLevel++;
for(UMLClassifierListItem *lit : litList) {
QString enumLiteral = cleanName(lit->name());
idl << indent() << enumLiteral;
if (++i < (uint)litList.count())
idl << ",";
idl << m_endl;
}
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
// Close the modules inside which we might be nested.
for (int i = 0; i < pkgList.count(); ++i) {
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
}
return;
}
if (! isOOClass(c)) {
QString stype = c->stereotype();
if (stype.contains(QStringLiteral("Constant"))) {
logError2("The stereotype %1 cannot be applied to %2 but only to attributes",
stype, c->name());
return;
}
if (!isClass) {
logError2("The stereotype %1 cannot be applied to %2 but only to classes",
stype, c->name());
return;
}
if (stype.contains(QStringLiteral("Enum"))) {
UMLAttributeList atl = c->getAttributeList();
idl << indent() << "enum " << classname << " {" << m_endl;
m_indentLevel++;
uint i = 0;
for(UMLAttribute* at : atl) {
QString enumLiteral = cleanName(at->name());
idl << indent() << enumLiteral;
if (++i < (uint)atl.count())
idl << ",";
idl << m_endl;
}
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
} else if (stype.contains(QStringLiteral("Struct"))) {
UMLAttributeList atl = c->getAttributeList();
idl << indent() << "struct " << classname << " {" << m_endl;
m_indentLevel++;
for(UMLAttribute* at : atl) {
QString name = cleanName(at->name());
idl << indent() << at->getTypeName() << " " << name << ";" << m_endl;
// Initial value not possible in IDL.
}
UMLAssociationList compositions = c->getCompositions();
if (!compositions.isEmpty()) {
idl << indent() << "// Compositions." << m_endl;
for(UMLAssociation *a : compositions) {
QString memberType, memberName;
computeAssocTypeAndRole(a, c, memberType, memberName);
idl << indent() << memberType << " " << memberName << ";" << m_endl;
}
}
UMLAssociationList aggregations = c->getAggregations();
if (!aggregations.isEmpty()) {
idl << indent() << "// Aggregations." << m_endl;
for(UMLAssociation *a: aggregations) {
QString memberType, memberName;
computeAssocTypeAndRole(a, c, memberType, memberName);
idl << indent() << memberType << " " << memberName << ";" << m_endl;
}
}
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
} else if (stype.contains(QStringLiteral("Union"))) {
// idl << indent() << "// " << stype << " " << c->name() << " is Not Yet Implemented" << m_endl << m_endl;
UMLAttributeList atl = c->getAttributeList();
if (atl.count()) {
UMLAttribute *discrim = atl.front();
idl << indent() << "union " << c->name() << " switch (" << discrim->getTypeName()
<< ") {" << m_endl << m_endl;
atl.pop_front();
m_indentLevel++;
for(UMLAttribute *at : atl) {
QString attName = cleanName(at->name());
const QStringList& tags = at->tags();
if (tags.count()) {
const QString& caseVals = tags.front();
for(const QString& caseVal : caseVals.split(QLatin1Char(' '))) {
idl << indent() << "case " << caseVal << ":" << m_endl;
}
} else {
// uError() << "missing 'case' tag at union attribute " << attName;
idl << indent() << "default:" << m_endl;
}
idl << indent() << m_indentation << at->getTypeName() << " " << attName << ";"
<< m_endl << m_endl;
}
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
} else {
logError1("Empty <<union>> %1", c->name());
idl << indent() << "// <<union>> " << c->name() << " is empty, please check model" << m_endl;
idl << indent() << "union " << c->name() << ";" << m_endl << m_endl;
}
} else if (stype.contains(QStringLiteral("Typedef"))) {
UMLClassifierList superclasses = c->getSuperClasses();
if (superclasses.count()) {
UMLClassifier* firstParent = superclasses.first();
idl << indent() << "typedef " << firstParent->name() << " "
<< c->name() << ";" << m_endl << m_endl;
} else {
logError1("typedef %1 parent (origin type) is missing", c->name());
idl << indent() << "// typedef origin type is missing, please check model" << m_endl;
idl << indent() << "typedef long " << c->name() << ";" << m_endl << m_endl;
}
} else {
idl << indent() << "// " << stype << ": Unknown stereotype" << m_endl << m_endl;
}
// Close the modules inside which we might be nested.
for (int i = 0; i < pkgList.count(); ++i) {
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
}
return;
}
idl << indent();
if (c->isAbstract())
idl << "abstract ";
bool isValuetype = (c->stereotype().contains(QStringLiteral("Value")));
if (isValuetype)
idl << "valuetype ";
else
idl << "interface ";
idl << c->name();
UMLClassifierList superclasses = c->getSuperClasses();
if (! superclasses.isEmpty()) {
idl << " : ";
int count = superclasses.count();
for(UMLClassifier* parent : superclasses) {
count--;
idl << parent->fullyQualifiedName(QStringLiteral("::"));
if (count)
idl << ", ";
}
}
idl << " {" << m_endl << m_endl;
m_indentLevel++;
// Generate auxiliary declarations for multiplicity of associations
bool didComment = false;
UMLAssociationList assocs = c->getAssociations();
for(UMLAssociation *a : assocs) {
if (! assocTypeIsMappableToAttribute(a->getAssocType()))
continue;
QString multiplicity = a->getMultiplicity(Uml::RoleType::A);
if (multiplicity.isEmpty() || multiplicity == QStringLiteral("1"))
continue;
if (!didComment) {
idl << indent() << "// Types for association multiplicities" << m_endl << m_endl;
didComment = true;
}
UMLClassifier* other = (UMLClassifier*)a->getObject(Uml::RoleType::A);
QString bareName = cleanName(other->name());
idl << indent() << "typedef sequence<" << other->fullyQualifiedName(QStringLiteral("::"))
<< "> " << bareName << "Vector;" << m_endl << m_endl;
}
// Generate public attributes.
if (isClass) {
UMLAttributeList atl = c->getAttributeList();
if (forceSections() || atl.count()) {
idl << indent() << "// Attributes:" << m_endl << m_endl;
for(UMLAttribute *at : atl) {
QString attName = cleanName(at->name());
Uml::Visibility::Enum scope = at->visibility();
idl << indent();
if (isValuetype) {
if (scope == Uml::Visibility::Public)
idl << "public ";
else
idl << "private ";
} else {
if (scope != Uml::Visibility::Public) {
idl << "// visibility should be: "
<< Uml::Visibility::toString(scope)
<< m_endl;
idl << indent();
}
idl << "attribute ";
}
idl << at->getTypeName() << " " << attName << ";"
<< m_endl << m_endl;
}
}
}
// Generate public operations.
UMLOperationList opl(c->getOpList());
UMLOperationList oppub;
for(UMLOperation* op : opl) {
if (op->visibility() == Uml::Visibility::Public)
oppub.append(op);
}
if (forceSections() || oppub.count()) {
idl << indent() << "// Public methods:" << m_endl << m_endl;
for(UMLOperation* op : oppub)
writeOperation(op, idl);
idl << m_endl;
}
if (forceSections() || !assocs.isEmpty()) {
idl << indent() << "// Associations:" << m_endl << m_endl;
for(UMLAssociation* a : assocs) {
Uml::AssociationType::Enum at = a->getAssocType();
if (! assocTypeIsMappableToAttribute(at))
continue;
QString typeName, roleName;
computeAssocTypeAndRole(a, c, typeName, roleName);
if (roleName.isEmpty()) // presumably because we are at the "wrong" end
continue;
idl << indent() << "// " << Uml::AssociationType::toString(at) << m_endl;
idl << indent();
if (isValuetype)
idl << "public ";
else
idl << "attribute ";
idl << typeName << " " << roleName << ";" << m_endl;
}
idl << m_endl;
}
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
// Close the modules inside which we might be nested.
for (int i = 0; i < pkgList.count(); ++i) {
m_indentLevel--;
idl << indent() << "};" << m_endl << m_endl;
}
file.close();
Q_EMIT codeGenerated(c, true);
Q_EMIT showGeneratedFile(file.fileName());
}
/**
* Write one operation.
* @param op the class for which we are generating code
* @param idl the stream associated with the output file
* @param is_comment specifying true generates the operation as commented out
*/
void IDLWriter::writeOperation(UMLOperation *op, QTextStream &idl, bool is_comment)
{
UMLAttributeList atl = op->getParmList();
QString rettype = op->getTypeName();
if (rettype.isEmpty())
rettype = QStringLiteral("void");
idl << indent();
if (is_comment)
idl << "// ";
idl << rettype << " " << cleanName(op->name()) << " (";
if (atl.count()) {
idl << m_endl;
m_indentLevel++;
uint i = 0;
for(UMLAttribute *at : atl) {
idl << indent();
if (is_comment)
idl << "// ";
Uml::ParameterDirection::Enum pk = at->getParmKind();
if (pk == Uml::ParameterDirection::Out)
idl << "out ";
else if (pk == Uml::ParameterDirection::InOut)
idl << "inout ";
else
idl << "in ";
idl << at->getTypeName() << " " << cleanName(at->name());
if (++i < (uint)atl.count())
idl << "," << m_endl;
}
m_indentLevel--;
}
idl << ");" << m_endl << m_endl;
}
QStringList IDLWriter::defaultDatatypes() const
{
QStringList l;
l.append(QStringLiteral("boolean"));
l.append(QStringLiteral("char"));
l.append(QStringLiteral("octet"));
l.append(QStringLiteral("short"));
l.append(QStringLiteral("unsigned short"));
l.append(QStringLiteral("long"));
l.append(QStringLiteral("unsigned long"));
l.append(QStringLiteral("long long"));
l.append(QStringLiteral("unsigned long long"));
l.append(QStringLiteral("float"));
l.append(QStringLiteral("double"));
l.append(QStringLiteral("long double"));
l.append(QStringLiteral("string"));
l.append(QStringLiteral("any"));
return l;
}
/**
* Get list of reserved keywords.
*/
QStringList IDLWriter::reservedKeywords() const
{
static QStringList keywords;
if (keywords.isEmpty()) {
keywords
<< QStringLiteral("any")
<< QStringLiteral("attribute")
<< QStringLiteral("boolean")
<< QStringLiteral("case")
<< QStringLiteral("char")
<< QStringLiteral("const")
<< QStringLiteral("context")
<< QStringLiteral("default")
<< QStringLiteral("double")
<< QStringLiteral("enum")
<< QStringLiteral("exception")
<< QStringLiteral("FALSE")
<< QStringLiteral("float")
<< QStringLiteral("in")
<< QStringLiteral("inout")
<< QStringLiteral("interface")
<< QStringLiteral("long")
<< QStringLiteral("module")
<< QStringLiteral("octet")
<< QStringLiteral("oneway")
<< QStringLiteral("out")
<< QStringLiteral("raises")
<< QStringLiteral("readonly")
<< QStringLiteral("sequence")
<< QStringLiteral("short")
<< QStringLiteral("string")
<< QStringLiteral("struct")
<< QStringLiteral("switch")
<< QStringLiteral("TRUE")
<< QStringLiteral("typedef")
<< QStringLiteral("union")
<< QStringLiteral("unsigned")
<< QStringLiteral("void");
}
return keywords;
}
| 19,353
|
C++
|
.cpp
| 493
| 29.48073
| 118
| 0.534084
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,588
|
csvalaimportbase.cpp
|
KDE_umbrello/umbrello/codeimport/csvalaimportbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2011-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "csvalaimportbase.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "codeimpthread.h"
#define DBG_SRC QStringLiteral("CsValaImportBase")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
#include "umlpackagelist.h"
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QStringList>
#include <QTextStream>
DEBUG_REGISTER(CsValaImportBase)
QStringList CsValaImportBase::s_filesAlreadyParsed;
int CsValaImportBase::s_parseDepth = 0;
/**
* Constructor.
*/
CsValaImportBase::CsValaImportBase(CodeImpThread* thread)
: NativeImportBase(QStringLiteral("//"), thread),
m_defaultCurrentAccess(Uml::Visibility::Public)
{
m_language = Uml::ProgrammingLanguage::CSharp;
setMultiLineComment(QStringLiteral("/*"), QStringLiteral("*/"));
initVars();
}
/**
* Destructor.
*/
CsValaImportBase::~CsValaImportBase()
{
}
QString CsValaImportBase::fileExtension()
{
return QString(); // to be reimplemented by the derived classes
}
/**
* Reimplement operation from NativeImportBase.
*/
void CsValaImportBase::initVars()
{
m_isStatic = false;
}
/**
* Figure out if the type is really an array or template of the given typeName.
* Catenate possible template arguments/array dimensions to the end of the type name.
* @param typeName the type name
* @return the type name with the additional information
*/
QString CsValaImportBase::joinTypename(const QString& typeName)
{
QString typeNameRet(typeName);
QString next = lookAhead();
if (!next.isEmpty()) {
if (next == QStringLiteral("<") || next == QStringLiteral("[")) {
int start = ++m_srcIndex;
if (! skipToClosing(m_source[start][0]))
return typeNameRet;
for (int i = start; i <= m_srcIndex; ++i) {
typeNameRet += m_source[i];
}
}
}
// to handle multidimensional arrays, call recursively
if (lookAhead() == QStringLiteral("[")) {
typeNameRet = joinTypename(typeNameRet);
}
return typeNameRet;
}
/**
* Override operation from NativeImportBase.
*/
bool CsValaImportBase::preprocess(QString& line)
{
if (NativeImportBase::preprocess(line))
return true; // done
// Quick and dirty: Ignore preprocessor lines.
// TODO: Implement this properly. For example of hooking up an external
// preprocessor see idlimport.cpp constructor IDLImport(CodeImpThread*)
QString trimmed = line.trimmed();
if (trimmed.startsWith(QLatin1Char('#')))
return true; // done
return false;
}
/**
* Implement abstract operation from NativeImportBase.
* @param word whitespace delimited item
*/
void CsValaImportBase::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
for (uint i = 0; i < len; ++i) {
const QChar& c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('.')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
m_source.append(QString(c));
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
// Condense single dimension array into the type name as done for the
// predefined types in the CSharpWriter and ValaWriter code generators.
const int last = m_source.size() - 1;
if (last > 1 && m_source.at(last-1) == QStringLiteral("[")
&& m_source.at(last) == QStringLiteral("]")) {
m_source.removeLast();
m_source.removeLast();
m_source.last() += QStringLiteral("[]");
}
}
/**
* Spawn off an import of the specified file.
* @param file the specified file
*/
void CsValaImportBase::spawnImport(const QString& file)
{
// if the file is being parsed, don't bother
if (s_filesAlreadyParsed.contains(file)) {
return;
}
if (QFile::exists(file)) {
CsValaImportBase importer;
QStringList fileList;
fileList.append(file);
s_filesAlreadyParsed.append(file);
importer.importFiles(fileList);
}
}
/**
* Returns the UML Object if found, or null otherwise.
* @param name name of the uml object
* @param parentPkg parent package
* @return null or the uml objecct
*/
UMLObject* CsValaImportBase::findObject(const QString& name, UMLPackage *parentPkg)
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLObject * o = umldoc->findUMLObject(name, UMLObject::ot_UMLObject, parentPkg);
return o;
}
/**
* Try to resolve the specified class the current class depends on.
* @param className the name of the class
*/
UMLObject* CsValaImportBase::resolveClass(const QString& className)
{
UMLObject *existing = findObject(className, currentScope());
if (existing)
return existing;
logDebug1("CsValaImportBase::resolveClass trying to resolve %1", className);
// keep track if we are dealing with an array
bool isArray = className.contains(QLatin1Char('['));
// remove any [] so that the class itself can be resolved
QString baseClassName = className;
baseClassName.remove(QLatin1Char('['));
baseClassName.remove(QLatin1Char(']'));
// java has a few implicit imports. Most relevant for this is the
// current package, which is in the same directory as the current file
// being parsed
QStringList file = m_currentFileName.split(QLatin1Char('/'));
// remove the filename. This leaves the full path to the containing
// dir which should also include the package hierarchy
file.pop_back();
// the file we're looking for might be in the same directory as the
// current class
QString myDir = file.join(QStringLiteral("/"));
QString myFile = myDir + QLatin1Char('/') + baseClassName + fileExtension();
if (QFile::exists(myFile)) {
spawnImport(myFile);
if (isArray) {
// we have imported the type. For arrays we want to return
// the array type
return Import_Utils::createUMLObject(UMLObject::ot_Class, className, currentScope());
}
return findObject(baseClassName, currentScope());
}
// the class we want is not in the same package as the one being imported.
// use the imports to find the one we want.
QStringList package = m_currentPackage.split(QLatin1Char('.'));
int dirsInPackageCount = package.size();
for (int count = 0; count < dirsInPackageCount; ++count) {
// pop off one by one the directories, until only the source root remains
file.pop_back();
}
// this is now the root of any further source imports
QString sourceRoot = file.join(QStringLiteral("/")) + QLatin1Char('/');
for (QStringList::Iterator pathIt = m_imports.begin();
pathIt != m_imports.end(); ++pathIt) {
QString import = (*pathIt);
QStringList split = import.split(QLatin1Char('.'));
split.pop_back(); // remove the * or the classname
if (import.endsWith(QLatin1Char('*')) || import.endsWith(baseClassName)) {
// check if the file we want is in this imported package
// convert the org.test type package into a filename
QString aFile = sourceRoot + split.join(QStringLiteral("/")) + QLatin1Char('/') + baseClassName + fileExtension();
if (QFile::exists(aFile)) {
spawnImport(aFile);
// we need to set the package for the class that will be resolved
// start at the root package
UMLPackage *parent = nullptr;
UMLPackage *current = nullptr;
for (QStringList::Iterator it = split.begin(); it != split.end(); ++it) {
QString name = (*it);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, parent);
current = ns->asUMLPackage();
parent = current;
} // for
if (isArray) {
// we have imported the type. For arrays we want to return
// the array type
return Import_Utils::createUMLObject(UMLObject::ot_Class, className, current);
}
// now that we have the right package, the class should be findable
return findObject(baseClassName, current);
} // if file exists
} // if import matches
} //foreach import
return nullptr; // no match
}
/**
* Keep track of the current file being parsed and reset the list of imports.
* @param filename the name of the file being parsed
*/
bool CsValaImportBase::parseFile(const QString& filename)
{
logDebug1("CsValaImportBase::parseFile %1", filename);
m_currentFileName = filename;
m_imports.clear();
// default visibility is Impl, unless we are an interface, then it is
// public for member vars and methods
m_defaultCurrentAccess = Uml::Visibility::Implementation;
m_currentAccess = m_defaultCurrentAccess;
s_parseDepth++;
// in the case of self referencing types, we can avoid parsing the
// file twice by adding it to the list
s_filesAlreadyParsed.append(filename);
NativeImportBase::parseFile(filename);
s_parseDepth--;
if (s_parseDepth <= 0) {
// if the user decides to clear things out and reparse, we need
// to honor the request, so reset things for next time.
s_filesAlreadyParsed.clear();
s_parseDepth = 0;
}
return true;
}
/**
* Implement abstract operation from NativeImportBase.
* compilation-unit:
* using-directives? global-attributes? namespace-member-declarations?
* @return success status of operation
*/
bool CsValaImportBase::parseStmt()
{
QString keyword = m_source[m_srcIndex];
//uDebug() << '"' << keyword << '"';
if (keyword == QStringLiteral("using")) {
return parseUsingDirectives();
}
if (keyword == QStringLiteral("namespace")) {
return parseNamespaceMemberDeclarations();
}
if (keyword == QStringLiteral("[")) {
return parseAttributes(); //:TODO: more than one
}
while (isClassModifier(keyword)) {
keyword = advance();
}
// type-declaration - class, interface, struct, enum, delegate
if (isTypeDeclaration(keyword)) {
if (keyword == QStringLiteral("struct")) {
return parseStructDeclaration();
}
if (keyword == QStringLiteral("enum")) {
return parseEnumDeclaration();
}
if (keyword == QStringLiteral("delegate")) {
return parseDelegateDeclaration();
}
// "class" or "interface"
return parseClassDeclaration(keyword);
}
if (keyword == QStringLiteral("[")) { // ...
advance();
skipToClosing(QLatin1Char('['));
return true;
}
if (keyword == QStringLiteral("}")) {
if (scopeIndex())
m_klass = popScope()->asUMLClassifier();
else
logError0("CsValaImportBase::parseStmt: too many }");
return true;
}
// At this point, we expect to encounter a class/interface member
// or property or method declaration.
// These may be preceded by the visibility (public, private etc)
// and/or other modifiers.
while (isCommonModifier(keyword)) {
keyword = advance();
}
// At this point, we expect `keyword` to be a type name
// (of a member of class or interface, or return type
// of an operation.) Up next is the name of the attribute
// or operation.
if (! keyword.contains(QRegularExpression(QStringLiteral("^\\w")))) {
if (m_klass)
logError4("CsValaImportBase::parseStmt: ignoring keyword %1 at index %2 of %3 (%4)",
keyword, m_srcIndex, m_source.count(), m_klass->name());
else
logError3("CsValaImportBase::parseStmt: ignoring keyword %1 at index %2 of %3",
keyword, m_srcIndex, m_source.count());
return false;
}
QString typeName = joinTypename(keyword);
// At this point we need a class.
if (m_klass == nullptr) {
logError1("CsValaImportBase::parseStmt: no class set for %1", typeName);
return false;
}
QString name = advance();
QString nextToken;
if (typeName == m_klass->name() && name == QStringLiteral("(")) {
// Constructor.
nextToken = name;
name = typeName;
typeName.clear();
} else {
nextToken = advance();
}
if (name.contains(QRegularExpression(QStringLiteral("\\W")))) {
logError1("CsValaImportBase::parseStmt: expecting name at %1", name);
return false;
}
if (nextToken == QStringLiteral("(")) {
// operation
UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
m_srcIndex++;
while (m_srcIndex < m_source.count() && m_source[m_srcIndex] != QStringLiteral(")")) {
QString typeName = m_source[m_srcIndex];
if (typeName == QStringLiteral("final") || typeName.startsWith(QStringLiteral("//"))) {
// ignore the "final" keyword and any comments in method args
typeName = advance();
}
typeName = joinTypename(typeName);
QString parName = advance();
// the Class might not be resolved yet so resolve it if necessary
UMLObject *obj = resolveClass(typeName);
if (obj) {
// by prepending the package, unwanted placeholder types will not get created
typeName = obj->fullyQualifiedName(QStringLiteral("."));
}
/* UMLAttribute *att = */ Import_Utils::addMethodParameter(op, typeName, parName);
if (advance() != QStringLiteral(","))
break;
m_srcIndex++;
}
// before adding the method, try resolving the return type
if (typeName == QStringLiteral("void")) {
typeName.clear();
} else {
UMLObject *obj = resolveClass(typeName);
if (obj) {
// using the fully qualified name means that a placeholder type will not be created.
typeName = obj->fullyQualifiedName(QStringLiteral("."));
}
}
Import_Utils::insertMethod(m_klass, op, m_currentAccess, typeName,
m_isStatic, m_isAbstract, false /*isFriend*/,
false /*isConstructor*/, false, m_comment);
m_isAbstract = m_isStatic = false;
// reset the default visibility
m_currentAccess = m_defaultCurrentAccess;
// At this point we do not know whether the method has a body or not.
do {
nextToken = advance();
} while (nextToken != QStringLiteral("{") && nextToken != QStringLiteral(";"));
if (nextToken == QStringLiteral(";")) {
// No body (interface or abstract)
return true;
} else {
return skipToClosing(QLatin1Char('{'));
}
}
// At this point it should be some kind of data member or property declaration.
if (nextToken == QStringLiteral("{")) { // property
// try to resolve the class type, or create a placeholder if that fails
UMLObject *type = resolveClass(typeName);
if (type) {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
type->asUMLClassifier(), m_comment, m_isStatic);
} else {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
typeName, m_comment, m_isStatic);
}
skipToClosing(QLatin1Char('{'));
// reset visibility to default
m_currentAccess = m_defaultCurrentAccess;
return true;
}
while (1) {
while (nextToken != QStringLiteral(",") && nextToken != QStringLiteral(";")) {
if (nextToken == QStringLiteral("=")) {
if ((nextToken = advance()) == QStringLiteral("new")) {
advance();
if ((nextToken = advance()) == QStringLiteral("(")) {
skipToClosing(QLatin1Char('('));
if ((nextToken = advance()) == QStringLiteral("{")) {
skipToClosing(QLatin1Char('{'));
} else {
skipStmt();
break;
}
} else {
skipStmt();
break;
}
} else {
skipStmt();
break;
}
} else {
name += nextToken; // add possible array dimensions to `name`
}
nextToken = advance();
if (nextToken.isEmpty()) {
break;
}
}
// try to resolve the class type, or create a placeholder if that fails
UMLObject *type = resolveClass(typeName);
if (type) {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
type->asUMLClassifier(), m_comment, m_isStatic);
} else {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
typeName, m_comment, m_isStatic);
}
// UMLAttribute *attr = o->asUMLAttribute();
if (nextToken != QStringLiteral(",")) {
// reset the modifiers
m_isStatic = m_isAbstract = false;
break;
}
name = advance();
nextToken = advance();
}
// reset visibility to default
m_currentAccess = m_defaultCurrentAccess;
if (m_srcIndex < m_source.count()) {
if (m_source[m_srcIndex] != QStringLiteral(";")) {
logError1("CsValaImportBase::parseStmt: ignoring trailing items at %1", name);
skipStmt();
}
} else {
logError1("CsValaImportBase::parseStmt index out of range: ignoring statement %1", name);
skipStmt();
}
return true;
}
/**
* Parsing the statement 'using'.
* Keep track of imports so we can resolve classes we are dependent on.
* @return success status of parsing
*/
bool CsValaImportBase::parseUsingDirectives()
{
QString import = advance();
log(QStringLiteral("using ") + import);
if (import.contains(QLatin1Char('='))) {
//this is an alias to represent the namespace name
//:TODO: import = import + advance();
}
m_imports.append(import);
// move past ;
skipStmt();
return true;
}
/**
* Parsing global attributes.
* @return success status of parsing
*/
bool CsValaImportBase::parseGlobalAttributes()
{
//:TODO:
return true;
}
/**
* Parsing the statement 'namespace'.
* @return success status of parsing
*/
bool CsValaImportBase::parseNamespaceMemberDeclarations()
{
QString m_currentNamespace = advance();
log(QStringLiteral("namespace ") + m_currentNamespace);
// move past {
skipStmt(QStringLiteral("{"));
return true;
}
/**
* Parsing attributes.
* @return success status of parsing
*/
bool CsValaImportBase::parseAttributes()
{
QString attribute = advance();
log(QStringLiteral("attribute ") + attribute);
skipStmt(QStringLiteral("]"));
return true;
}
/**
* Check if keyword is belonging to a type-declaration.
* @return result of check
*/
bool CsValaImportBase::isTypeDeclaration(const QString& keyword)
{
if (keyword == QStringLiteral("class") ||
keyword == QStringLiteral("struct") ||
keyword == QStringLiteral("interface") ||
keyword == QStringLiteral("enum") ||
keyword == QStringLiteral("delegate")) {
// log("type-declaration: " + keyword);
return true;
}
else {
return false;
}
}
/**
* Check if keyword is a class-modifier.
* @return result of check
*/
bool CsValaImportBase::isClassModifier(const QString& keyword)
{
if (isCommonModifier(keyword) ||
keyword == QStringLiteral("sealed")) {
return true;
}
if (keyword == QStringLiteral("abstract")) {
m_isAbstract = true;
return true;
}
return false;
}
/**
* Check if keyword is an interface, struct, enum or delegate modifier.
* @return result of check
*/
bool CsValaImportBase::isCommonModifier(const QString& keyword)
{
if (keyword == QStringLiteral("public")) {
m_currentAccess = Uml::Visibility::Public;
return true;
}
if (keyword == QStringLiteral("protected")) {
m_currentAccess = Uml::Visibility::Protected;
return true;
}
if (keyword == QStringLiteral("private")) {
m_currentAccess = Uml::Visibility::Private;
return true;
}
if (keyword == QStringLiteral("static")) {
m_isStatic = true;
return true;
}
if (keyword == QStringLiteral("new") ||
keyword == QStringLiteral("internal") ||
keyword == QStringLiteral("readonly") ||
keyword == QStringLiteral("volatile") ||
keyword == QStringLiteral("virtual") ||
keyword == QStringLiteral("override") ||
keyword == QStringLiteral("unsafe") ||
keyword == QStringLiteral("extern") ||
keyword == QStringLiteral("partial") ||
keyword == QStringLiteral("async")) {
return true;
}
return false;
}
/**
* Parsing the statement 'enum'.
* @return success status of parsing
*/
bool CsValaImportBase::parseEnumDeclaration()
{
const QString& name = advance();
log(QStringLiteral("enum ") + name);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum,
name, currentScope(), m_comment);
UMLEnum *enumType = ns->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(ns, currentScope());
skipStmt(QStringLiteral("{"));
while (m_srcIndex < m_source.count() - 1 && advance() != QStringLiteral("}")) {
QString next = advance();
if (next == QStringLiteral("=")) {
next = advance();
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, m_source[m_srcIndex - 2], QString(), m_source[m_srcIndex]);
next = advance();
} else {
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, m_source[m_srcIndex - 1]);
}
if (next == QStringLiteral("{") || next == QStringLiteral("(")) {
if (! skipToClosing(next[0]))
return false;
next = advance();
}
if (next != QStringLiteral(",")) {
if (next == QStringLiteral(";")) {
// @todo handle methods in enum
// For now, we cheat (skip them)
m_source[m_srcIndex] = QLatin1Char('{');
if (! skipToClosing(QLatin1Char('{')))
return false;
}
break;
}
}
return true;
}
/**
* Parsing a struct-declaration.
* @return success status of parsing
*/
bool CsValaImportBase::parseStructDeclaration()
{
const QString& name = advance();
log(QStringLiteral("struct ") + name + QStringLiteral(" --> parsing not yet implemented!"));
return true;
}
/**
* Parsing a delegate-declaration.
* @return success status of parsing
*/
bool CsValaImportBase::parseDelegateDeclaration()
{
// return-type identifier (formal-parameter-list?) ;
const QString& returnType = advance();
const QString& name = advance();
log(QStringLiteral("delegate ") + name + QStringLiteral("with return-type ") + returnType);
skipStmt(QStringLiteral(";"));
return true;
}
/**
* Parsing the statement 'class' or 'interface'.
* @return success status of parsing
*/
bool CsValaImportBase::parseClassDeclaration(const QString& keyword)
{
const QString& name = advance();
const UMLObject::ObjectType ot = (keyword == QStringLiteral("class") ? UMLObject::ot_Class
: UMLObject::ot_Interface);
log(keyword + QLatin1Char(' ') + name);
UMLObject *ns = Import_Utils::createUMLObject(ot, name, currentScope(), m_comment);
pushScope(m_klass = ns->asUMLClassifier());
m_klass->setStatic(m_isStatic);
m_klass->setVisibilityCmd(m_currentAccess);
// The UMLObject found by createUMLObject might originally have been created as a
// placeholder with a type of class but if is really an interface, then we need to
// change it.
m_klass->setBaseType(ot);
// TODO: UMLClassifier::setBaseType() resets abstract flag
m_klass->setAbstract(m_isAbstract);
m_isAbstract = m_isStatic = false;
// if no modifier is specified in an interface, then it means public
if (m_klass->isInterface()) {
m_defaultCurrentAccess = Uml::Visibility::Public;
}
if (advance() == QStringLiteral(";")) // forward declaration
return true;
if (m_source[m_srcIndex] == QStringLiteral("<")) {
// template args - preliminary, rudimentary implementation
// @todo implement all template arg syntax
uint start = m_srcIndex;
if (! skipToClosing(QLatin1Char('<'))) {
logError1("CsValaImportBase::parseClassDeclaration (%1): template syntax error", name);
return false;
}
while(1) {
const QString arg = m_source[++start];
if (! arg.contains(QRegularExpression(QStringLiteral("^[A-Za-z_]")))) {
logDebug2("import C# (%1): cannot handle template syntax (%2)", name, arg);
break;
}
/* UMLTemplate *tmpl = */ m_klass->addTemplate(arg);
const QString next = m_source[++start];
if (next == QStringLiteral(">"))
break;
if (next != QStringLiteral(",")) {
logDebug2("import C# (%1): cannot handle template syntax (%2)", name, next);
break;
}
}
advance(); // skip over ">"
}
if (m_source[m_srcIndex] == QStringLiteral(":")) { // derivation
while (m_srcIndex < m_source.count() - 1 && advance() != QStringLiteral("{")) {
const QString& baseName = m_source[m_srcIndex];
// try to resolve the interface we are implementing, if this fails
// create a placeholder
UMLObject *interface = resolveClass(baseName);
if (interface) {
Import_Utils::createGeneralization(m_klass, interface->asUMLClassifier());
} else {
logDebug1("CsValaImportBase::parseClassDeclaration: implementing interface %1 "
"is not resolvable. Creating placeholder", baseName);
Import_Utils::createGeneralization(m_klass, baseName);
}
if (advance() != QStringLiteral(","))
break;
}
}
if (m_source[m_srcIndex] != QStringLiteral("{")) {
logError2("CsValaImportBase::parseClassDeclaration ignoring excess chars at %1 (index %2)",
name, m_source[m_srcIndex]);
skipStmt(QStringLiteral("{"));
}
return true;
}
| 27,878
|
C++
|
.cpp
| 745
| 29.622819
| 126
| 0.605849
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,589
|
classimport.cpp
|
KDE_umbrello/umbrello/codeimport/classimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "classimport.h"
// app includes
#define DBG_SRC QStringLiteral("ClassImport")
#include "debug_utils.h"
#include "folder.h"
#include "uml.h"
#include "umldoc.h"
#include "idlimport.h"
#include "pythonimport.h"
#include "javaimport.h"
#include "adaimport.h"
#include "pascalimport.h"
#include "sqlimport.h"
#include "cppimport.h"
#include "csharpimport.h"
#include "codeimpthread.h"
#include "valaimport.h"
#ifdef ENABLE_PHP_IMPORT
#include "phpimport.h"
#endif
// kde includes
#include <KLocalizedString>
// qt includes
#include <QRegularExpression>
/**
* Factory method for creating a ClassImport concretization by file extension
* @param fileName name of imported file
* @param thread pointer to @ref CodeImpThread within which the importer runs
* @return the class import object
*/
ClassImport *ClassImport::createImporterByFileExt(const QString &fileName, CodeImpThread* thread)
{
ClassImport *classImporter;
if (fileName.endsWith(QStringLiteral(".idl")))
classImporter = new IDLImport(thread);
else if (fileName.contains(QRegularExpression(QStringLiteral("\\.pyw?$"))))
classImporter = new PythonImport(thread);
else if (fileName.endsWith(QStringLiteral(".java")))
classImporter = new JavaImport(thread);
else if (fileName.contains(QRegularExpression(QStringLiteral("\\.ad[sba]$"))))
classImporter = new AdaImport(thread);
else if (fileName.endsWith(QStringLiteral(".pas")))
classImporter = new PascalImport(thread);
else if (fileName.endsWith(QStringLiteral(".cs")))
classImporter = new CSharpImport(thread);
else if (fileName.contains(QRegularExpression(QStringLiteral(".va[lp][ai]$"))))
classImporter = new ValaImport(thread);
else if (fileName.endsWith(QStringLiteral(".sql")))
classImporter = new SQLImport(thread);
#ifdef ENABLE_PHP_IMPORT
else if (fileName.endsWith(QStringLiteral(".php")))
classImporter = new PHPImport(thread);
#endif
else
classImporter = new CppImport(thread); // the default.
return classImporter;
}
ClassImport::ClassImport(CodeImpThread* thread)
: m_thread(thread),
m_enabled(true)
{
}
ClassImport::~ClassImport()
{
}
/**
* Do initializations before importing a single file.
* This is called by importFile() before calling parseFile().
* @todo check if the default implementation should do anything
*/
void ClassImport::initPerFile()
{
}
/**
* Import files.
* @param fileNames List of files to import.
*/
bool ClassImport::importFiles(const QStringList& fileNames)
{
initialize();
UMLDoc *umldoc = UMLApp::app()->document();
uint processedFilesCount = 0;
bool result = true;
umldoc->setLoading(true);
umldoc->setImporting(true);
for(const QString& fileName : fileNames) {
umldoc->writeToStatusBar(i18n("Importing file: %1 Progress: %2/%3",
fileName, processedFilesCount, fileNames.size()));
if (!importFile(fileName))
result = false;
processedFilesCount++;
}
umldoc->setLoading(false);
umldoc->setImporting(false);
umldoc->writeToStatusBar(result ? i18nc("ready to status bar", "Ready.") : i18nc("failed to status bar", "Failed."));
return result;
}
/**
* Import a single file.
* @param fileName The file to import.
*/
bool ClassImport::importFile(const QString& fileName)
{
initPerFile();
return parseFile(fileName);
}
void ClassImport::setRootPath(const QString &path)
{
m_rootPath = path;
}
/**
* Write info to a logger or to the debug output.
* @param file the name of the parsed file
* @param text the text to write
*/
void ClassImport::log(const QString& file, const QString& text)
{
if (m_thread) {
m_thread->emitMessageToLog(file, text);
} else {
QString msg;
if (!file.isEmpty())
msg.append(file).append(QStringLiteral(" - "));
msg.append(text);
UMLApp::app()->log(msg);
}
}
/**
* Write info to a logger or to the debug output.
* @param text the text to write
*/
void ClassImport::log(const QString& text)
{
log(QString(), text);
}
| 4,322
|
C++
|
.cpp
| 140
| 27.2
| 121
| 0.706404
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,590
|
pascalimport.cpp
|
KDE_umbrello/umbrello/codeimport/pascalimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "pascalimport.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "datatype.h"
#define DBG_SRC QStringLiteral("PascalImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
// qt includes
#include <stdio.h>
DEBUG_REGISTER(PascalImport)
/**
* Constructor.
*/
PascalImport::PascalImport(CodeImpThread* thread) : NativeImportBase(QStringLiteral("//"), thread)
{
setMultiLineComment(QStringLiteral("(*"), QStringLiteral("*)"));
setMultiLineAltComment(QStringLiteral("{"), QStringLiteral("}"));
initVars();
}
/**
* Destructor.
*/
PascalImport::~PascalImport()
{
}
/**
* Reimplement operation from NativeImportBase.
*/
void PascalImport::initVars()
{
m_inInterface = false;
m_section = sect_NONE;
NativeImportBase::m_currentAccess = Uml::Visibility::Public;
}
/**
* We need to reimplement the split operation from NativeImportBase
* because Delphi appears to support UUIDs with syntax such as
* ['{23170F69-40C1-278A-0000-000500100000}']
* which the NativeImportBase implementation does not split properly.
*/
QStringList PascalImport::split(const QString& line)
{
// @todo implement this properly
return NativeImportBase::split(line);
}
/**
* Implement abstract operation from NativeImportBase.
*/
void PascalImport::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
for (uint i = 0; i < len; ++i) {
QChar c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('.') || c == QLatin1Char('#')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
if (i+1 < len && c == QLatin1Char(':') && word[i + 1] == QLatin1Char('=')) {
m_source.append(QStringLiteral(":="));
i++;
} else {
m_source.append(QString(c));
}
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
}
/**
* Check for, and skip over, all modifiers following a method.
* Set the output arguments on encountering abstract and/or virtual.
* @param isVirtual return value, set to true when "virtual" seen
* @param isAbstract return value, set to true when "abstract" seen
*/
void PascalImport::checkModifiers(bool& isVirtual, bool& isAbstract)
{
const int srcLength = m_source.count();
while (m_srcIndex < srcLength - 1) {
QString lookAhead = m_source[m_srcIndex + 1].toLower();
if (lookAhead != QStringLiteral("virtual") && lookAhead != QStringLiteral("abstract") &&
lookAhead != QStringLiteral("override") &&
lookAhead != QStringLiteral("register") && lookAhead != QStringLiteral("cdecl") &&
lookAhead != QStringLiteral("pascal") && lookAhead != QStringLiteral("stdcall") &&
lookAhead != QStringLiteral("safecall") && lookAhead != QStringLiteral("saveregisters") &&
lookAhead != QStringLiteral("popstack"))
break;
if (lookAhead == QStringLiteral("abstract"))
isAbstract = true;
else if (lookAhead == QStringLiteral("virtual"))
isVirtual = true;
advance();
skipStmt();
}
}
/**
* Implement abstract operation from NativeImportBase.
* @return success status of operation
*/
bool PascalImport::parseStmt()
{
const int srcLength = m_source.count();
QString token = m_source[m_srcIndex];
QString nextTok = (m_srcIndex < srcLength-1 ? m_source[m_srcIndex + 1] : QStringLiteral("!END!"));
QString keyword = token.toLower();
logDebug3("PascalImport::parseStmt : %1 (%2) index %3", token, nextTok, m_srcIndex);
if (keyword == QStringLiteral("uses")) {
while (m_srcIndex < srcLength - 1) {
QString unit = advance();
const QString& prefix = unit.toLower();
if (prefix == QStringLiteral("sysutils") || prefix == QStringLiteral("types") || prefix == QStringLiteral("classes") ||
prefix == QStringLiteral("graphics") || prefix == QStringLiteral("controls") || prefix == QStringLiteral("strings") ||
prefix == QStringLiteral("forms") || prefix == QStringLiteral("windows") || prefix == QStringLiteral("messages") ||
prefix == QStringLiteral("variants") || prefix == QStringLiteral("stdctrls") || prefix == QStringLiteral("extctrls") ||
prefix == QStringLiteral("activex") || prefix == QStringLiteral("comobj") || prefix == QStringLiteral("registry") ||
prefix == QStringLiteral("classes") || prefix == QStringLiteral("dialogs")) {
if (advance() != QStringLiteral(","))
break;
continue;
}
QString filename = unit + QStringLiteral(".pas");
if (! m_parsedFiles.contains(unit)) {
// Save current m_source and m_srcIndex.
QStringList source(m_source);
uint srcIndex = m_srcIndex;
m_source.clear();
parseFile(filename);
// Restore m_source and m_srcIndex.
m_source = source;
m_srcIndex = srcIndex;
// Also reset m_currentAccess.
// CHECK: need to reset more stuff?
m_currentAccess = Uml::Visibility::Public;
}
if (advance() != QStringLiteral(","))
break;
}
skipStmt();
return true;
}
if (keyword == QStringLiteral("unit")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package, name,
currentScope(), m_comment);
pushScope(ns->asUMLPackage());
skipStmt();
return true;
}
if (keyword == QStringLiteral("interface")) {
m_inInterface = true;
return true;
}
if (keyword == QStringLiteral("initialization") || keyword == QStringLiteral("implementation")) {
m_inInterface = false;
return true;
}
if (! m_inInterface) {
// @todo parseStmt() should support a notion for "quit parsing, close file immediately"
return false;
}
if (keyword == QStringLiteral("label")) {
m_section = sect_LABEL;
return true;
}
if (keyword == QStringLiteral("const")) {
m_section = sect_CONST;
return true;
}
if (keyword == QStringLiteral("resourcestring")) {
m_section = sect_RESOURCESTRING;
return true;
}
if (keyword == QStringLiteral("type")) {
m_section = sect_TYPE;
return true;
}
if (keyword == QStringLiteral("var")) {
m_section = sect_VAR;
return true;
}
if (keyword == QStringLiteral("threadvar")) {
m_section = sect_THREADVAR;
return true;
}
if (keyword == QStringLiteral("automated") || keyword == QStringLiteral("published") // no classifier in UML
|| keyword == QStringLiteral("public")) {
m_currentAccess = Uml::Visibility::Public;
return true;
}
if (keyword == QStringLiteral("protected")) {
m_currentAccess = Uml::Visibility::Protected;
return true;
}
if (keyword == QStringLiteral("private")) {
m_currentAccess = Uml::Visibility::Private;
return true;
}
if (keyword == QStringLiteral("packed")) {
return true; // TBC: perhaps this could be stored in a TaggedValue
}
if (keyword == QStringLiteral("[")) {
//skipStmt(QStringLiteral("]"));
// Not using skipStmt here because the closing bracket may be glued on to
// some other character(s), e.g. '] (quote)
// This is an imperfection in the token splitter.
// @todo flesh out function split() which should be reimplemented from NativeImportBase
while (m_srcIndex < m_source.count()) {
if (advance().endsWith(QStringLiteral("]")))
break;
}
return true;
}
if (keyword == QStringLiteral("end")) {
if (m_klass) {
m_klass = nullptr;
} else if (scopeIndex()) {
popScope();
m_currentAccess = Uml::Visibility::Public;
} else {
logError2("PascalImport::parseStmt: too many \"end\" at index %1 of %2",
m_srcIndex, m_source.count());
}
skipStmt();
return true;
}
if (keyword == QStringLiteral("function") || keyword == QStringLiteral("procedure") ||
keyword == QStringLiteral("constructor") || keyword == QStringLiteral("destructor")) {
if (m_klass == nullptr) {
// Unlike a Pascal unit, a UML package does not support subprograms.
// In order to map those, we would need to create a UML class with
// stereotype <<utility>> for the unit, https://bugs.kde.org/89167
bool dummyVirtual = false;
bool dummyAbstract = false;
checkModifiers(dummyVirtual, dummyAbstract);
skipStmt();
return true;
}
const QString& name = advance();
UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
if (m_source[m_srcIndex + 1] == QStringLiteral("(")) {
advance();
const uint MAX_PARNAMES = 16;
while (m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(")")) {
QString nextToken = m_source[m_srcIndex + 1].toLower();
Uml::ParameterDirection::Enum dir = Uml::ParameterDirection::In;
if (nextToken == QStringLiteral("var")) {
dir = Uml::ParameterDirection::InOut;
advance();
} else if (nextToken == QStringLiteral("const")) {
advance();
} else if (nextToken == QStringLiteral("out")) {
dir = Uml::ParameterDirection::Out;
advance();
}
QString parName[MAX_PARNAMES];
uint parNameCount = 0;
do {
if (parNameCount >= MAX_PARNAMES) {
logError1("PascalImport::parseStmt: MAX_PARNAMES is exceeded at %1", name);
break;
}
parName[parNameCount++] = advance();
} while (advance() == QStringLiteral(","));
if (m_source[m_srcIndex] != QStringLiteral(":")) {
logError1("PascalImport::parseStmt: expecting ':' at %1", m_source[m_srcIndex]);
skipStmt();
break;
}
nextToken = advance();
if (nextToken.toLower() == QStringLiteral("array")) {
nextToken = advance().toLower();
if (nextToken != QStringLiteral("of")) {
logError2("PascalImport::parseStmt(%1) : expecting 'array OF' at %2", name, nextToken);
skipStmt();
return false;
}
nextToken = advance();
}
for (uint i = 0; i < parNameCount; ++i) {
UMLAttribute *att = Import_Utils::addMethodParameter(op, nextToken, parName[i]);
att->setParmKind(dir);
}
if (advance() != QStringLiteral(";"))
break;
}
}
bool isConstructor = false;
bool isDestructor = false;
QString returnType;
if (keyword == QStringLiteral("function")) {
if (advance() != QStringLiteral(":")) {
logError1("PascalImport::parseStmt: expecting \":\" at function %1", name);
return false;
}
returnType = advance();
} else if (keyword == QStringLiteral("constructor")) {
isConstructor = true;
} else if (keyword == QStringLiteral("destructor")) {
isDestructor = true;
}
skipStmt();
bool isVirtual = false;
bool isAbstract = false;
checkModifiers(isVirtual, isAbstract);
Import_Utils::insertMethod(m_klass, op, m_currentAccess, returnType,
!isVirtual, isAbstract, false, isConstructor,
isDestructor, m_comment);
return true;
}
if (m_section != sect_TYPE) {
skipStmt();
return true;
}
if (m_klass == nullptr) {
const QString& name = m_source[m_srcIndex];
QString nextToken = advance();
if (nextToken != QStringLiteral("=")) {
logDebug2("PascalImport::parseStmt %1: expecting '=' at %2", name, nextToken);
return false;
}
QString rhsName = advance();
keyword = rhsName.toLower();
if (keyword == QStringLiteral("(")) {
// enum type
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum,
name, currentScope(), m_comment);
UMLEnum *enumType = ns->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(ns, currentScope());
while (++m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(")")) {
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, m_source[m_srcIndex]);
if (advance() != QStringLiteral(","))
break;
}
skipStmt();
return true;
}
if (keyword == QStringLiteral("set")) { // @todo implement Pascal set types
skipStmt();
return true;
}
if (keyword == QStringLiteral("array")) { // @todo implement Pascal array types
skipStmt();
return true;
}
if (keyword == QStringLiteral("file")) { // @todo implement Pascal file types
skipStmt();
return true;
}
if (keyword == QStringLiteral("^")) { // @todo implement Pascal pointer types
skipStmt();
return true;
}
if (keyword == QStringLiteral("class") || keyword == QStringLiteral("interface")) {
UMLObject::ObjectType t = (keyword == QStringLiteral("class") ? UMLObject::ot_Class
: UMLObject::ot_Interface);
UMLObject *ns = Import_Utils::createUMLObject(t, name,
currentScope(), m_comment);
UMLClassifier *klass = ns->asUMLClassifier();
m_comment.clear();
QString lookAhead = m_source[m_srcIndex + 1];
if (lookAhead == QStringLiteral("(")) {
advance();
do {
QString base = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class, base, nullptr);
UMLClassifier *parent = ns->asUMLClassifier();
m_comment.clear();
Import_Utils::createGeneralization(klass, parent);
} while (advance() == QStringLiteral(","));
if (m_source[m_srcIndex] != QStringLiteral(")")) {
logError1("PascalImport::parseStmt: expecting \")\" at %1", m_source[m_srcIndex]);
return false;
}
lookAhead = m_source[m_srcIndex + 1];
}
if (lookAhead == QStringLiteral(";")) {
skipStmt();
return true;
}
if (lookAhead == QStringLiteral("of")) {
// @todo implement class-reference type
return false;
}
m_klass = klass;
m_currentAccess = Uml::Visibility::Public;
return true;
}
if (keyword == QStringLiteral("record")) {
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class, name,
currentScope(), m_comment);
ns->setStereotype(QStringLiteral("record"));
m_klass = ns->asUMLClassifier();
return true;
}
if (keyword == QStringLiteral("function") || keyword == QStringLiteral("procedure")) {
/*UMLObject *ns =*/ Import_Utils::createUMLObject(UMLObject::ot_Datatype, name,
currentScope(), m_comment);
if (m_source[m_srcIndex + 1] == QStringLiteral("("))
skipToClosing(QLatin1Char('('));
skipStmt();
return true;
}
// Datatypes
UMLObject *o = nullptr;
UMLDoc *umldoc = UMLApp::app()->document();
UMLDatatype *newType = umldoc->findDatatype(name);
if (!newType) {
o = Import_Utils::createUMLObject(UMLObject::ot_Datatype, name,
currentScope(), m_comment);
newType = dynamic_cast<UMLDatatype*>(o);
}
if (!newType) {
logError1("PascalImport::parseStmt: Finding/creating datatype %1 failed", name);
skipStmt();
return false;
}
/* TODO: Create <<typedef>> from originType to newType
UMLDatatype *originType = umldoc->findDatatype(rhsName);
if (originType) {
....
} */
o = newType;
skipStmt();
return true;
}
// At this point we need a class because we're expecting its member attributes.
if (m_klass == nullptr) {
logDebug1("PascalImport::parseStmt: skipping %1", m_source[m_srcIndex]);
skipStmt();
return true;
}
QString name, stereotype;
if (keyword == QStringLiteral("property")) {
stereotype = keyword;
name = advance();
} else {
name = m_source[m_srcIndex];
}
if (advance() != QStringLiteral(":")) {
logError2("PascalImport::parseStmt: expecting ':' at %1 %2", name, m_source[m_srcIndex]);
skipStmt();
return true;
}
QString typeName = advance();
QString initialValue;
if (advance() == QStringLiteral("=")) {
initialValue = advance();
QString token;
while ((token = advance()) != QStringLiteral(";")) {
initialValue.append(QLatin1Char(' ') + token);
}
}
UMLObject *o = Import_Utils::insertAttribute(m_klass, m_currentAccess, name,
typeName, m_comment);
if (!o) {
logDebug2("PascalImport::parseStmt: Could not insert attribute %1 in class %2",
name, m_klass->name());
return false;
}
UMLAttribute *attr = o->asUMLAttribute();
if (!attr) {
logDebug2("PascalImport::parseStmt: insertAttribute returned different object named %1 in class %2",
name, m_klass->name());
return false;
}
attr->setStereotype(stereotype);
attr->setInitialValue(initialValue);
skipStmt();
return true;
}
| 19,598
|
C++
|
.cpp
| 486
| 29.590535
| 135
| 0.550267
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,591
|
sqlimport.cpp
|
KDE_umbrello/umbrello/codeimport/sqlimport.cpp
|
/*
SPDX-FileCopyrightText: 2015 Ralf Habacker <ralf.habacker@freenet.de>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
// own header
#include "sqlimport.h"
// app includes
#include "association.h"
#include "attribute.h"
#include "checkconstraint.h"
#include "classifier.h"
#define DBG_SRC QStringLiteral("SqlImport")
#include "debug_utils.h"
#include "enum.h"
#include "folder.h"
#include "import_utils.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "entity.h"
#include "entityattribute.h"
#include "foreignkeyconstraint.h"
#include "uniqueconstraint.h"
#include "umldoc.h"
#include "umlpackagelist.h"
// qt includes
#include <QProcess>
#include <QStandardPaths>
#include <QStringList>
#include <stdio.h>
DEBUG_REGISTER(SQLImport)
/**
* Constructor.
*
* @param thread thread in which the code import runs
*/
SQLImport::SQLImport(CodeImpThread* thread) : NativeImportBase(QStringLiteral("--"), thread)
{
setMultiLineComment(QStringLiteral("/*"), QStringLiteral("*/"));
}
/**
* Destructor.
*/
SQLImport::~SQLImport()
{
}
/**
* Implement abstract operation from NativeImportBase.
*/
void SQLImport::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
for (uint i = 0; i < len; ++i) {
QChar c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
m_source.append(QString(c));
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
}
/**
* Strip qoutes from identifier.
*
* @param token string with current token
* @return stripped string
*/
QString &stripQuotes(QString &token)
{
if (token.contains(QStringLiteral("\"")))
token.replace(QStringLiteral("\""), QStringLiteral(""));
else if (token.contains(QStringLiteral("`")))
token.replace(QStringLiteral("`"), QStringLiteral(""));
else if (token.contains(QStringLiteral("'")))
token.replace(QStringLiteral("'"), QStringLiteral(""));
return token;
}
/**
* Parse identifier.
*
* @param token string with current token
* @return parsed identifier
*/
QString SQLImport::parseIdentifier(QString &token)
{
QString value;
if (token == QStringLiteral("`")) { // mysql
value = advance();
token = advance();
} else
value = token;
token = advance();
if (token == QStringLiteral(".")) {
// FIXME we do not support packages yet
#if 0
value += token;
value += advance();
token = advance();
#else
value = advance();
token = advance();
#endif
}
return stripQuotes(value);
}
/**
* Parse identifier list.
*
* @param token string with current token
* @return string list with identifiers
*/
QStringList SQLImport::parseIdentifierList(QString &token)
{
QStringList values;
if (token.toLower() == QStringLiteral("(")) {
for (token = advance(); token != QStringLiteral(")");) {
if (token == QStringLiteral(",")) {
token = advance();
continue;
}
QString value = parseIdentifier(token);
values.append(value);
}
token = advance();
}
else {
;// error;
}
return values;
}
/**
* Parse field type.
*
* @param token string with current token
* @return string list containing field type (index 0), size/count (index 1) and optional values (index > 2)
*/
QStringList SQLImport::parseFieldType(QString &token)
{
QString type = token;
QString typeLength;
// handle type extensions
token = advance();
// schema.type
if (token == QStringLiteral(".")) {
type += token;
type += advance();
token = advance();
if (token.toLower() == QStringLiteral("precision")) {
type += token;
token = advance();
}
}
if (type.toLower() == QStringLiteral("enum")) {
QStringList values = parseIdentifierList(token);
return QStringList() << type << QString() << values;
}
if (token.toLower() == QStringLiteral("varying")) {
type += QStringLiteral(" ") + token;
token = advance(); // '('
}
// (number) | (number,number)
if (token.toLower() == QStringLiteral("(")) {
typeLength = advance(); // value
token = advance();
if (token == QStringLiteral(",")) {
typeLength += token;
typeLength += advance();
token = advance();
}
token = advance();
} else if (token.toLower() == QStringLiteral("precision")) {
type += QStringLiteral(" ") + token;
token = advance();
}
if (token == QStringLiteral("[")) {
token = advance();
if (token == QStringLiteral("]")) {
type += QStringLiteral("[]");
token = advance();
}
} else if (token.toLower().startsWith(QStringLiteral("with"))) {
type += QStringLiteral(" ") + token;
token = advance();
type += QStringLiteral(" ") + token;
token = advance();
type += QStringLiteral(" ") + token;
token = advance();
} else if (token.toLower() == QStringLiteral("unsigned")) { // mysql
token = advance();
}
return QStringList() << type << typeLength;
}
/**
* Parse default expression.
*
* The expression could be in the form
* (expression)\::\<type\>
* function(expression)
*
* @param token string with current token
* @return string with default expression
*/
QString SQLImport::parseDefaultExpression(QString &token)
{
QString defaultValue;
if (token == QStringLiteral("(")) {
int index = m_srcIndex;
skipToClosing(QLatin1Char('('));
token = advance();
for (int i = index; i < m_srcIndex; i++)
defaultValue += m_source[i];
} else {
defaultValue += token;
token = advance();
}
if (token == (QStringLiteral(":"))) {
defaultValue += token;
token = advance();
if (token == (QStringLiteral(":"))) {
defaultValue += token;
token = advance();
defaultValue += parseFieldType(token).first();
}
}
if (token == QStringLiteral("(")) {
int index = m_srcIndex;
skipToClosing(QLatin1Char('('));
token = advance();
for (int i = index; i < m_srcIndex; i++)
defaultValue += m_source[i];
}
return defaultValue;
}
/**
* Parse column constraint.
*
* pgsql:
* [ CONSTRAINT constraint_name ]
* { NOT NULL |
* NULL |
* CHECK ( expression ) |
* COLLATE collation |
* DEFAULT default_expr |
* UNIQUE index_parameters |
* PRIMARY KEY index_parameters |
* REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
* [ ON DELETE action ] [ ON UPDATE action ] }
* [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
*
* mysql:
* [ PRIMARY KEY index_parameters |
* KEY key_name ( fields )
* CHARACTER SET charset_name |
* COLLATE collation ]
*
* @param token string with current token
* @return column constraints
*/
SQLImport::ColumnConstraints SQLImport::parseColumnConstraints(QString &token)
{
ColumnConstraints constraints;
while (token != QStringLiteral(",") && token != QStringLiteral(")") && token.toLower() != QStringLiteral("comment")) {
const int origIndex = m_srcIndex;
if (token.toLower() == QStringLiteral("character")) { // mysql
token = advance(); // set
if (token.toLower() == QStringLiteral("set")) {
constraints.characterSet = advance(); // <value>
token = advance();
}
else {
m_srcIndex--; // take back
token = m_source[m_srcIndex];
}
}
if (token.toLower() == QStringLiteral("collate")) { // mysql
constraints.collate = advance();
token = advance();
}
// [ CONSTRAINT constraint_name ]
if (token.toLower() == QStringLiteral("constraint")) {
constraints.constraintName = advance();
token = advance();
}
// NOT NULL
if (token.toLower() == QStringLiteral("not")) {
token = advance();
if (token.toLower() == QStringLiteral("null")) {
constraints.notNullConstraint = true;
token = advance();
}
}
// NULL
if (token.toLower() == QStringLiteral("null")) {
constraints.notNullConstraint = false;
token = advance();
}
// CHECK ( expression )
if (token.toLower() == QStringLiteral("check")) {
skipStmt(QStringLiteral(")"));
token = advance();
}
// DEFAULT default_expr
if (token.toLower() == QStringLiteral("default")) {
token = advance();
constraints.defaultValue = parseDefaultExpression(token);
}
// UNIQUE index_parameters
if (token.toLower() == QStringLiteral("unique")) {
constraints.uniqueKey = true;
token = advance();
// WITH ( storage_parameter [= value] [, ... ] )
if (token.toLower() == QStringLiteral("with")) {
skipStmt(QStringLiteral(")"));
token = advance();
}
// USING INDEX TABLESPACE tablespace
if (token.toLower() == QStringLiteral("using")) {
token = advance();
token = advance();
token = advance();
token = advance();
}
}
// PRIMARY KEY index_parameters
if (token.toLower() == QStringLiteral("primary")) {
token = advance();
if (token.toLower() == QStringLiteral("key")) {
constraints.primaryKey = true;
token = advance();
// WITH ( storage_parameter [= value] [, ... ] )
if (token.toLower() == QStringLiteral("with")) {
skipStmt(QStringLiteral(")"));
token = advance();
}
// USING INDEX TABLESPACE tablespace
if (token.toLower() == QStringLiteral("using")) {
token = advance(); // INDEX
token = advance(); // TABLESPACE
token = advance(); // tablespace
token = advance();
}
}
}
// REFERENCES reftable [ ( refcolumn ) ]
if (token.toLower() == QStringLiteral("references")) {
token = advance();
token = advance();
if (token == QStringLiteral("(")) {
skipStmt(QStringLiteral(")"));
token = advance();
}
// [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
if (token.toLower() == QStringLiteral("match")) {
token = advance();
token = advance();
}
// [ ON DELETE action ]
if (token.toLower() == QStringLiteral("on")) {
token = advance();
token = advance();
token = advance();
}
// [ ON UPDATE action ]
if (token.toLower() == QStringLiteral("on")) {
token = advance();
token = advance();
token = advance();
}
}
// [ DEFERRABLE | NOT DEFERRABLE ]
if (token.toLower() == QStringLiteral("deferrable")) {
token = advance();
}
else if (token.toLower() == QStringLiteral("not")) {
token = advance();
token = advance();
}
// [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
if (token.toLower() == QStringLiteral("initially")) {
token = advance();
token = advance();
}
if (token.toLower() == QStringLiteral("auto_increment")) { // mysql
constraints.autoIncrement = true;
token = advance();
}
if (m_srcIndex == origIndex) {
log(m_parsedFiles.first(), QStringLiteral("could not parse column constraint '") + token + QStringLiteral("'"));
token = advance();
}
}
if (token.toLower() == QStringLiteral("comment")) {
while (token != QStringLiteral(",") && token != QStringLiteral(")")) {
token = advance();
}
}
return constraints;
}
/**
* Parse table constraint.
*
* pgsql:
*
* [ CONSTRAINT constraint_name ]
* { CHECK ( expression ) |
* UNIQUE ( column_name [, ... ] ) index_parameters |
* PRIMARY KEY ( column_name [, ... ] ) index_parameters |
* EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ] ) index_parameters [ WHERE ( predicate ) ] |
* FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
* [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] }
* [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
*
* mysql:
* PRIMARY KEY (`uid`, `pid`) |
* KEY `t3ver_oid` (`t3ver_oid`,`t3ver_wsid`)
* UNIQUE KEY `entry_identifier` (`entry_namespace`,`entry_key`)
*
* @param token string with current token
* @return table constraints
*/
SQLImport::TableConstraints SQLImport::parseTableConstraints(QString &token)
{
TableConstraints constraints;
if (token.toLower() == QStringLiteral("constraint")) {
constraints.constraintName = advance();
token = advance();
}
// CHECK ( expression )
if (token.toLower() == QStringLiteral("check")) {
token = advance();
if (token == QStringLiteral("(")) {
int index = m_srcIndex;
skipToClosing(QLatin1Char('('));
token = advance();
constraints.checkConstraint = true;
for (int i = index; i < m_srcIndex; i++)
constraints.checkExpression += m_source[i];
}
}
// PRIMARY KEY (`uid`, `pid`),
if (token.toLower() == QStringLiteral("primary")) {
token = advance(); // key
token = advance(); // (
constraints.primaryKey = true;
constraints.primaryKeyFields = parseIdentifierList(token);
}
// UNIQUE KEY `entry_identifier` (`entry_namespace`,`entry_key`)
else if (token.toLower() == QStringLiteral("unique")) {
token = advance();
token = advance();
constraints.uniqueKeys = true;
constraints.uniqueKeyName = parseIdentifier(token);
constraints.uniqueKeysFields = parseIdentifierList(token);
}
// KEY `t3ver_oid` (`t3ver_oid`,`t3ver_wsid`) // mysql
else if (token.toLower() == QStringLiteral("key")) {
if (m_source[m_srcIndex+4] == QStringLiteral("(") ) {
token = advance();
constraints.uniqueKeys = true;
constraints.uniqueKeyName = parseIdentifier(token);
constraints.uniqueKeysFields = parseIdentifierList(token);
}
}
return constraints;
}
/**
* Parse table create definition.
*
* @param token string with current token
* @param entity entity to save the definition into
* @return true on success
* @return false on error
*/
bool SQLImport::parseCreateDefinition(QString &token, UMLEntity *entity)
{
if (token != QStringLiteral("(")) {
skipStmt(QStringLiteral(";"));
return false;
}
while (m_source.count() > m_srcIndex) {
token = advance();
if (token == QStringLiteral(")")) {
break;
}
TableConstraints tableConstraints = parseTableConstraints(token);
if (tableConstraints.primaryKey) {
if (!addPrimaryKey(entity, tableConstraints.constraintName, tableConstraints.primaryKeyFields)) {
; // log error
}
}
if (tableConstraints.uniqueKeys) {
if (!addUniqueConstraint(entity, tableConstraints.uniqueKeyName, tableConstraints.uniqueKeysFields)) {
; // log error
}
}
if (tableConstraints.checkConstraint) {
if (entity) {
QString name;
if (!tableConstraints.constraintName.isEmpty())
name = tableConstraints.constraintName;
else
name = entity->name() + QStringLiteral("_check");
UMLCheckConstraint *cc = new UMLCheckConstraint(entity, name);
cc->setCheckCondition(tableConstraints.checkExpression);
entity->addConstraint(cc);
} else {
logError1("SQLImport::parseCreateDefinition: Could not add check constraint '%1' because of zero entity.",
tableConstraints.constraintName);
}
}
if (token == QStringLiteral(","))
continue;
else if (token == QStringLiteral(")"))
break;
// handle field name
QString fieldName = parseIdentifier(token);
// handle field type
QStringList fieldType = parseFieldType(token);
SQLImport::ColumnConstraints constraints = parseColumnConstraints(token);
logDebug2("SQLImport::parseCreateDefinition: field %1 type %2", fieldName, fieldType.at(0));
if (entity && !fieldName.isEmpty()) {
UMLObject *type = addDatatype(fieldType);
UMLEntityAttribute *a = new UMLEntityAttribute(nullptr, fieldName,
Uml::ID::None,
Uml::Visibility::Public,
type);
if (constraints.primaryKey)
a->setIndexType(UMLEntityAttribute::Primary);
a->setNull(!constraints.notNullConstraint);
// convert index to value if present, see https://dev.mysql.com/doc/refman/8.0/en/enum.html
if (UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::MySQL && type->isUMLEnum()) {
bool ok;
int index = constraints.defaultValue.toInt(&ok);
if (!ok) // string (not checked if valid) or empty
a->setInitialValue(constraints.defaultValue);
else if (index > 0) {
index--; // 0 is empty
const UMLEnum *_enum = type->asUMLEnum();
UMLClassifierListItemList enumLiterals = _enum->getFilteredList(UMLObject::ot_EnumLiteral);
if (index < enumLiterals.size())
a->setInitialValue(enumLiterals.at(index)->name());
}
} else {
a->setInitialValue(constraints.defaultValue);
}
a->setValues(fieldType.at(1));
a->setAutoIncrement(constraints.autoIncrement);
if (constraints.primaryKey) {
UMLUniqueConstraint *pkey = new UMLUniqueConstraint(a, a->name() + QStringLiteral("_pkey"));
entity->setAsPrimaryKey(pkey);
}
else if (constraints.uniqueKey) {
UMLUniqueConstraint *uc = new UMLUniqueConstraint(a, a->name() + QStringLiteral("_unique"));
entity->addConstraint(uc);
}
QStringList attributes;
if (!constraints.characterSet.isEmpty())
attributes.append(QStringLiteral("CHARACTER SET ") + constraints.characterSet);
if (!constraints.collate.isEmpty())
attributes.append(QStringLiteral("COLLATE ") + constraints.collate);
if (attributes.size() > 0)
a->setAttributes(attributes.join(QStringLiteral(" ")));
entity->addEntityAttribute(a);
} else if (!entity) {
logError1("SQLImport::parseCreateDefinition: Could not add field '%1' because of zero entity.", fieldName);
}
if (token == QStringLiteral(","))
continue;
else if (token == QStringLiteral(")"))
break;
}
token = advance();
return true;
}
/**
* Parse create table statement.
*
* @param token string with current token
* @return true on success
* @return false on error
*/
bool SQLImport::parseCreateTable(QString &token)
{
bool returnValue = true;
QString tableName = parseIdentifier(token);
logDebug1("SQLImport::parseCreateTable: parsing create table %1", tableName);
UMLFolder *folder = UMLApp::app()->document()->rootFolder(Uml::ModelType::EntityRelationship);
UMLObject *o = Import_Utils::createUMLObject(UMLObject::ot_Entity,
tableName, folder, m_comment);
UMLEntity *entity = o->asUMLEntity();
m_comment.clear();
if (token.toLower() == QStringLiteral("as")) {
skipStmt(QStringLiteral(";"));
return false;
} else if (token == QStringLiteral("(")) {
parseCreateDefinition(token, entity);
} else {
skipStmt(QStringLiteral(";"));
return false;
}
if (token.toLower() == QStringLiteral("inherits")) {
token = advance(); // (
const QString &baseTable = advance();
token = advance(); // )
UMLObject *b = Import_Utils::createUMLObject(UMLObject::ot_Entity,
baseTable, folder, m_comment);
UMLAssociation *a = new UMLAssociation(Uml::AssociationType::Generalization, o, b);
if (entity)
entity->addAssocToConcepts(a);
else {
logError1("SQLImport::parseCreateTable: Could not add generalization '%1' because of zero entity.",
baseTable);
returnValue = false;
}
}
skipStmt(QStringLiteral(";"));
return returnValue;
}
/**
* Parse alter table statement.
*
* @param token string with current token
* @return true on success
* @return false on error
*/
bool SQLImport::parseAlterTable(QString &token)
{
if (token.toLower() == QStringLiteral("only"))
token = advance();
QString tableName = token;
token = advance();
if (token == QStringLiteral(".")) {
tableName += token;
token = advance();
if (token.contains(QStringLiteral("\"")))
token.replace(QStringLiteral("\""), QStringLiteral(""));
tableName += token;
token = advance();
}
if (token.toLower() == QStringLiteral("add")) {
token = advance();
if (token.toLower() == QStringLiteral("constraint")) {
const QString &constraintName = advance();
token = advance();
UMLFolder *folder = UMLApp::app()->document()->rootFolder(Uml::ModelType::EntityRelationship);
UMLObject *o = UMLApp::app()->document()->findUMLObject(tableName, UMLObject::ot_Entity, folder);
if (token.toLower() == QStringLiteral("primary")) {
token = advance(); // key
token = advance();
const QStringList &fieldNames = parseIdentifierList(token);
if (!o) {
// report error
}
UMLEntity *entity = o->asUMLEntity();
if (!addPrimaryKey(entity, constraintName, fieldNames)) {
; // reporter error
}
}
else if (token.toLower() == QStringLiteral("unique")) {
token = advance();
const QStringList &fieldNames = parseIdentifierList(token);
if (!o) {
// report error
}
UMLEntity *entity = o->asUMLEntity();
if (!addUniqueConstraint(entity, constraintName, fieldNames)) {
; // report error
}
}
// FOREIGN KEY (<NAME>) REFERENCES <TABLE> (<FIELD>)
else if (token.toLower() == QStringLiteral("foreign")) {
token = advance(); // key
token = advance();
const QStringList &localFieldNames = parseIdentifierList(token);
token = advance(); // references
const QString &referencedTableName = parseIdentifier(token);
const QStringList &referencedFieldNames = parseIdentifierList(token);
// ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED;
// use parseColumnConstraint()
if (token.toLower() == QStringLiteral("on")) {
token = advance();
token = advance(); // delete/update
if (token.toLower() == QStringLiteral("cascade"))
token = advance();
}
else if (token.toLower() == QStringLiteral("match")) {
token = advance();
token = advance(); // full
}
if (!o) {
// report error
}
UMLEntity *entity = o->asUMLEntity();
if (!addForeignConstraint(entity, constraintName, localFieldNames, referencedTableName, referencedFieldNames)) {
; // report error
}
}
}
} else
skipStmt(QStringLiteral(";"));
return true;
}
/**
* Implement abstract operation from NativeImportBase.
*/
bool SQLImport::parseStmt()
{
const QString& keyword = m_source[m_srcIndex];
if (keyword.toLower() == QStringLiteral("set")) {
skipStmt(QStringLiteral(";"));
return true;
}
// CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ]
else if (keyword.toLower() == QStringLiteral("create")) {
QString type = advance();
// [ GLOBAL | LOCAL ]
if (type.toLower() == QStringLiteral("global"))
type = advance();
else if (type.toLower() == QStringLiteral("local"))
type = advance();
// [ { TEMPORARY | TEMP } | UNLOGGED ]
if (type.toLower() == QStringLiteral("temp"))
type = advance();
else if (type.toLower() == QStringLiteral("temporary"))
type = advance();
if (type.toLower() == QStringLiteral("unlogged"))
type = advance();
// TABLE
if (type.toLower() == QStringLiteral("table")) {
QString token = advance();
// [ IF NOT EXISTS ]
if (token.toLower() == QStringLiteral("if")) {
token = advance();
token = advance();
token = advance();
}
return parseCreateTable(token);
} else if (m_source[m_srcIndex] != QStringLiteral(";")) {
skipStmt(QStringLiteral(";"));
return true;
}
} else if (keyword.toLower() == QStringLiteral("alter")) {
QString type = advance();
if (type.toLower() == QStringLiteral("table")) {
QString token = advance();
return parseAlterTable(token);
} else if (m_source[m_srcIndex] != QStringLiteral(";")) {
skipStmt(QStringLiteral(";"));
return true;
}
}
return true;
}
/**
* Implement virtual method
* @return string with next token
*/
QString SQLImport::advance()
{
QString token = NativeImportBase::advance();
logDebug2("SQLImport::advance : index %1 token %2", m_srcIndex, token);
return token;
}
UMLObject *SQLImport::addDatatype(const QStringList &type)
{
UMLObject *datatype = nullptr;
UMLPackage *parent = UMLApp::app()->document()->datatypeFolder();
if (type.at(0).toLower() == QStringLiteral("enum")) {
QString name = Model_Utils::uniqObjectName(UMLObject::ot_Enum, parent, type.at(0));
datatype = Import_Utils::createUMLObject(UMLObject::ot_Enum, name, parent);
UMLEnum *enumType = datatype->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(datatype, currentScope());
if (enumType) {
for (int i = 2; i < type.size(); i++) {
Import_Utils::addEnumLiteral(enumType, type.at(i));
}
} else {
logError0("SQLImport::addDatatype: Invalid dynamic cast to UMLEnum from datatype.");
}
} else {
datatype = Import_Utils::createUMLObject(UMLObject::ot_Datatype, type.at(0), parent);
}
return datatype;
}
bool SQLImport::addPrimaryKey(UMLEntity *entity, const QString &_name, const QStringList &fields)
{
if (!entity) {
logError1("SQLImport::addPrimaryKey: Could not add primary key '%1' because of zero entity.", _name);
return false;
}
QString name;
if (_name.isEmpty())
name = entity->name() + QStringLiteral("_pkey");
else
name = _name;
for(UMLObject *a : entity->getFilteredList(UMLObject::ot_EntityConstraint)) {
if (a->name() == name)
return false;
}
UMLUniqueConstraint *pkey = new UMLUniqueConstraint(entity, name);
for(const QString &field: fields) {
for(UMLEntityAttribute *a : entity->getEntityAttributes()) {
if (a->name() == field)
pkey->addEntityAttribute(a);
}
}
// update list view item to see 'P'
bool state = UMLApp::app()->document()->loading();
UMLApp::app()->document()->setLoading(false);
bool result = entity->setAsPrimaryKey(pkey);
UMLApp::app()->document()->setLoading(state);
return result;
}
/**
* Add UML object for unique constraint.
*
* @param entity entity object
* @param _name unique constraint name
* @param fields field list
* @return true on success
* @return false on error
*/
bool SQLImport::addUniqueConstraint(UMLEntity *entity, const QString &_name, const QStringList &fields)
{
if (!entity) {
logError1("SQLImport::addUniqueConstraint: Could not add unique constraint '%1' because of zero entity.",
_name);
return false;
}
QString name;
if (_name.isEmpty())
name = entity->name() + QStringLiteral("_unique");
else
name = _name;
for(UMLObject *a : entity->getFilteredList(UMLObject::ot_EntityConstraint)) {
if (a->name() == name)
return false;
}
UMLUniqueConstraint *uc = new UMLUniqueConstraint(entity, name);
for(const QString &field: fields) {
for(UMLEntityAttribute *a : entity->getEntityAttributes()) {
if (a->name() == field)
uc->addEntityAttribute(a);
}
}
return entity->addConstraint(uc);
}
/**
* Add UML object foreign constraint.
*
* @param entityA entity object the foreign constraint belongs
* @param _name name of foreign constraint
* @param fieldNames list of field names
* @param referencedTable referenced table name
* @param referencedFields list of referenced field names
* @return true on success
* @return false on error
*/
bool SQLImport::addForeignConstraint(UMLEntity *entityA, const QString &_name, const QStringList &fieldNames,
const QString &referencedTable, const QStringList &referencedFields)
{
if (!entityA) {
logError1("SQLImport::addForeignConstraint: Could not add foreign constraint '%1' because of zero entity.",
_name);
return false;
}
QString name;
if (_name.isEmpty())
name = entityA->name() + QStringLiteral("_foreign");
else
name = _name;
for(UMLObject *a : entityA->getFilteredList(UMLObject::ot_EntityConstraint)) {
if (a->name() == name)
return false;
}
UMLFolder *root = UMLApp::app()->document()->rootFolder(Uml::ModelType::EntityRelationship);
UMLObject *o = UMLApp::app()->document()->findUMLObject(referencedTable, UMLObject::ot_Entity, root);
UMLEntity *entityB = o->asUMLEntity();
if (!entityB)
return false;
UMLForeignKeyConstraint *fc = new UMLForeignKeyConstraint(entityA, name);
if (fieldNames.size() != referencedFields.size()) {
return false;
}
fc->setReferencedEntity(entityB);
for(int i = 0; i < fieldNames.size(); i++) {
const QString &fieldA = fieldNames.at(i);
const QString &fieldB = referencedFields.at(i);
UMLEntityAttribute *aA = nullptr;
UMLEntityAttribute *aB = nullptr;
for(UMLEntityAttribute *a : entityA->getEntityAttributes()) {
if (a->name() == fieldA) {
aA = a;
break;
}
}
for(UMLEntityAttribute *a : entityB->getEntityAttributes()) {
if (a->name() == fieldB) {
aB = a;
break;
}
}
if (!aA || !aB)
return false;
fc->addEntityAttributePair(aA, aB);
}
return entityA->addConstraint(fc);
}
| 33,121
|
C++
|
.cpp
| 916
| 27.587336
| 128
| 0.572425
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,592
|
javaimport.cpp
|
KDE_umbrello/umbrello/codeimport/javaimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "javaimport.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "codeimpthread.h"
#define DBG_SRC QStringLiteral("JavaImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
#include "umlpackagelist.h"
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QStringList>
#include <QTextStream>
DEBUG_REGISTER(JavaImport)
QStringList JavaImport::s_filesAlreadyParsed;
int JavaImport::s_parseDepth = 0;
/**
* Constructor.
*/
JavaImport::JavaImport(CodeImpThread* thread)
: NativeImportBase(QStringLiteral("//"), thread),
m_defaultCurrentAccess(Uml::Visibility::Public)
{
setMultiLineComment(QStringLiteral("/*"), QStringLiteral("*/"));
initVars();
}
/**
* Destructor.
*/
JavaImport::~JavaImport()
{
}
/**
* Reimplement operation from NativeImportBase.
*/
void JavaImport::initVars()
{
m_isStatic = false;
}
/**
* Figure out if the type is really an array or template of the given typeName.
* Catenate possible template arguments/array dimensions to the end of the type name.
* @param typeName the type name
* @return the type name with the additional information
*/
QString JavaImport::joinTypename(const QString& typeName)
{
QString typeNameRet(typeName);
if (m_srcIndex + 1 < m_source.size()) {
if (m_source[m_srcIndex + 1] == QStringLiteral("<") ||
m_source[m_srcIndex + 1] == QStringLiteral("[")) {
int start = ++m_srcIndex;
if (! skipToClosing(m_source[start][0]))
return typeNameRet;
for (int i = start; i <= m_srcIndex; ++i) {
typeNameRet += m_source[i];
}
}
}
// to handle multidimensional arrays, call recursively
if ((m_srcIndex + 1 < m_source.size()) && (m_source[m_srcIndex + 1] == QStringLiteral("["))) {
typeNameRet = joinTypename(typeNameRet);
}
return typeNameRet;
}
/**
* Implement abstract operation from NativeImportBase.
* @param word whitespace delimited item
*/
void JavaImport::fillSource(const QString& word)
{
QString w(word);
/* In Java, method varargs are represented by three dots following the
type name. For portability to other C family languages, we replace
the "..." by "[]".
*/
if (w.contains(QStringLiteral("..."))) {
w.replace(QStringLiteral("..."), QStringLiteral("[]"));
}
QString lexeme;
const uint len = w.length();
for (uint i = 0; i < len; ++i) {
const QChar& c = w[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('.')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
m_source.append(QString(c));
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
}
/**
* Spawn off an import of the specified file.
* @param file the specified file
*/
void JavaImport::spawnImport(const QString& file)
{
// if the file is being parsed, don't bother
//
if (s_filesAlreadyParsed.contains(file)) {
return;
}
if (QFile::exists(file)) {
JavaImport importer;
QStringList fileList;
fileList.append(file);
s_filesAlreadyParsed.append(file);
importer.importFiles(fileList);
}
}
/**
* Returns the UML Object if found, or null otherwise.
* @param name name of the uml object
* @param parentPkg parent package
* @return null or the uml objecct
*/
UMLObject* JavaImport::findObject(const QString& name, UMLPackage *parentPkg)
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLObject * o = umldoc->findUMLObject(name, UMLObject::ot_UMLObject, parentPkg);
return o;
}
/**
* Try to resolve the specified class the current class depends on.
* @param className the name of the class
*/
UMLObject* JavaImport::resolveClass (const QString& className)
{
logDebug1("importJava trying to resolve %1", className);
// keep track if we are dealing with an array
//
bool isArray = className.contains(QLatin1Char('['));
// remove any [] so that the class itself can be resolved
//
QString baseClassName = className;
baseClassName.remove(QLatin1Char('['));
baseClassName.remove(QLatin1Char(']'));
// remove template class name so that the class itself can be resolved
int index = baseClassName.indexOf(QLatin1Char('<'));
if (index != -1) {
baseClassName = baseClassName.remove(index, baseClassName.size()-index);
}
// java has a few implicit imports. Most relevant for this is the
// current package, which is in the same directory as the current file
// being parsed
//
QStringList file = m_currentFileName.split(QLatin1Char('/'));
// remove the filename. This leaves the full path to the containing
// dir which should also include the package hierarchy
//
file.pop_back();
// the file we're looking for might be in the same directory as the
// current class
//
QString myDir = file.join(QStringLiteral("/"));
QString myFile = myDir + QLatin1Char('/') + baseClassName + QStringLiteral(".java");
if (QFile::exists(myFile)) {
spawnImport(myFile);
if (isArray) {
// we have imported the type. For arrays we want to return
// the array type
return Import_Utils::createUMLObject(UMLObject::ot_Class, className, currentScope());
}
return findObject(baseClassName, currentScope());
}
// the class we want is not in the same package as the one being imported.
// use the imports to find the one we want.
//
QStringList package = m_currentPackage.split(QLatin1Char('.'));
int dirsInPackageCount = package.size();
// in case the path does not fit into the package hierarchy
// we cannot check the imports
if (dirsInPackageCount >= file.size())
return nullptr;
for (int count=0; count < dirsInPackageCount; ++count) {
// pop off one by one the directories, until only the source root remains
//
file.pop_back();
}
// this is now the root of any further source imports
QString sourceRoot = file.join(QStringLiteral("/")) + QLatin1Char('/');
for (QStringList::Iterator pathIt = m_imports.begin();
pathIt != m_imports.end(); ++pathIt) {
QString import = (*pathIt);
QStringList split = import.split(QLatin1Char('.'));
split.pop_back(); // remove the * or the classname
if (import.endsWith(QLatin1Char('*')) || import.endsWith(baseClassName)) {
// check if the file we want is in this imported package
// convert the org.test type package into a filename
//
QString aFile = sourceRoot + split.join(QStringLiteral("/")) + QLatin1Char('/') + baseClassName + QStringLiteral(".java");
if (QFile::exists(aFile)) {
spawnImport(aFile);
// we need to set the package for the class that will be resolved
// start at the root package
UMLPackage *parent = nullptr;
UMLPackage *current = nullptr;
for (QStringList::Iterator it = split.begin(); it != split.end(); ++it) {
QString name = (*it);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, parent,
QString(), QString(),
true, false);
current = ns->asUMLPackage();
parent = current;
} // for
if (isArray) {
// we have imported the type. For arrays we want to return
// the array type
return Import_Utils::createUMLObject(UMLObject::ot_Class, className, current,
QString(), QString(), true, false);
}
// now that we have the right package, the class should be findable
return findObject(baseClassName, current);
// imported class is specified but seems to be external
} else if (import.endsWith(baseClassName)) {
// we need to set the package for the class that will be resolved
// start at the root package
UMLPackage *parent = nullptr;
UMLPackage *current = nullptr;
for (QStringList::Iterator it = split.begin(); it != split.end(); ++it) {
QString name = (*it);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, parent);
current = ns->asUMLPackage();
parent = current;
} // for
if (isArray) {
// we have imported the type. For arrays we want to return
// the array type
return Import_Utils::createUMLObject(UMLObject::ot_Class, className, current);
}
// now that we have the right package, the class should be findable
return Import_Utils::createUMLObject(UMLObject::ot_Class,
baseClassName, current);
} // if file exists
} // if import matches
} //foreach import
return nullptr; // no match
}
/**
* Keep track of the current file being parsed and reset the list of imports.
* @param filename the name of the file being parsed
*/
bool JavaImport::parseFile(const QString& filename)
{
m_currentFileName = filename;
m_imports.clear();
// default visibility is Impl, unless we are an interface, then it is
// public for member vars and methods
m_defaultCurrentAccess = Uml::Visibility::Implementation;
m_currentAccess = m_defaultCurrentAccess;
s_parseDepth++;
// in the case of self referencing types, we can avoid parsing the
// file twice by adding it to the list
if (s_filesAlreadyParsed.contains(filename)) {
s_parseDepth--;
return true;
}
s_filesAlreadyParsed.append(filename);
NativeImportBase::parseFile(filename);
s_parseDepth--;
if (s_parseDepth <= 0) {
// if the user decides to clear things out and reparse, we need
// to honor the request, so reset things for next time.
s_filesAlreadyParsed.clear();
s_parseDepth = 0;
}
return true;
}
/**
* Implement abstract operation from NativeImportBase.
* @return success status of operation
*/
bool JavaImport::parseStmt()
{
const int srcLength = m_source.count();
QString keyword = m_source[m_srcIndex];
//uDebug() << '"' << keyword << '"';
if (keyword == QStringLiteral("package")) {
m_currentPackage = advance();
const QString& qualifiedName = m_currentPackage;
const QStringList names = qualifiedName.split(QLatin1Char('.'));
for (QStringList::ConstIterator it = names.begin(); it != names.end(); ++it) {
QString name = (*it);
log(keyword + QLatin1Char(' ') + name);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, currentScope(), m_comment, QString(), true);
pushScope(ns->asUMLPackage());
}
if (advance() != QStringLiteral(";")) {
logError1("JavaImport::parseStmt: unexpected: %1", m_source[m_srcIndex]);
skipStmt();
}
return true;
}
if (keyword == QStringLiteral("class") || keyword == QStringLiteral("interface")) {
const QString& name = advance();
const UMLObject::ObjectType ot = (keyword == QStringLiteral("class") ? UMLObject::ot_Class
: UMLObject::ot_Interface);
log(keyword + QLatin1Char(' ') + name);
UMLObject *ns = Import_Utils::createUMLObject(ot, name, currentScope(), m_comment);
m_klass = ns->asUMLClassifier();
// The name is already used but is package
if (ns && ns->isUMLPackage() && !m_klass) {
ns = Object_Factory::createNewUMLObject(ot, name, ns->asUMLPackage());
ns->setDoc(m_comment);
m_klass = ns->asUMLClassifier();
m_klass->setUMLPackage(currentScope());
currentScope()->addObject(m_klass, false); // false => non interactively
}
pushScope(m_klass);
m_klass->setStatic(m_isStatic);
m_klass->setVisibilityCmd(m_currentAccess);
// The UMLObject found by createUMLObject might originally have been created as a
// placeholder with a type of class but if is really an interface then we need to
// change it.
m_klass->setBaseType(ot);
// TODO: UMLClassifier::setBaseType() resets abstract flag
m_klass->setAbstract(m_isAbstract);
m_isAbstract = m_isStatic = false;
// if no modifier is specified in an interface then it means public
if (m_klass->isInterface()) {
m_defaultCurrentAccess = Uml::Visibility::Public;
}
if (advance() == QStringLiteral(";")) // forward declaration
return true;
if (m_source[m_srcIndex] == QStringLiteral("<")) {
// template args - preliminary, rudimentary implementation
// @todo implement all template arg syntax
uint start = m_srcIndex;
if (! skipToClosing(QLatin1Char('<'))) {
logError1("JavaImport::parseStmt(%1): template syntax error", name);
return false;
}
while (1) {
const QString arg = m_source[++start];
if (! arg.contains(QRegularExpression(QStringLiteral("^[A-Za-z_]")))) {
logDebug2("JavaImport::parseStmt(%1): cannot handle template syntax (%2)",
name, arg);
break;
}
/* UMLTemplate *tmpl = */ m_klass->addTemplate(arg);
const QString next = m_source[++start];
if (next == QStringLiteral(">"))
break;
if (next != QStringLiteral(",")) {
logDebug2("JavaImport::parseStmt(%1): cannot handle template syntax (%2)",
name, next);
break;
}
}
advance(); // skip over ">"
}
if (m_source[m_srcIndex] == QStringLiteral("extends")) {
const QString& baseName = advance();
// try to resolve the class we are extending, or if impossible
// create a placeholder
UMLObject *parent = resolveClass(baseName);
if (parent) {
Import_Utils::createGeneralization(m_klass, parent->asUMLClassifier());
} else {
logDebug1("importJava parentClass %1 is not resolveable. Creating placeholder",
baseName);
Import_Utils::createGeneralization(m_klass, baseName);
}
advance();
}
if (m_source[m_srcIndex] == QStringLiteral("implements")) {
while (m_srcIndex < srcLength - 1 && advance() != QStringLiteral("{")) {
const QString& baseName = m_source[m_srcIndex];
// try to resolve the interface we are implementing, if this fails
// create a placeholder
UMLObject *interface = resolveClass(baseName);
if (interface) {
Import_Utils::createGeneralization(m_klass, interface->asUMLClassifier());
} else {
logDebug1("importJava implementing interface %1 is not resolvable. "
"Creating placeholder", baseName);
Import_Utils::createGeneralization(m_klass, baseName);
}
if (advance() != QStringLiteral(","))
break;
}
}
if (m_source[m_srcIndex] != QStringLiteral("{")) {
logError2("JavaImport::parseStmt: ignoring excess chars at %1 (%2)", name, m_source[m_srcIndex]);
skipStmt(QStringLiteral("{"));
}
return true;
}
if (keyword == QStringLiteral("enum")) {
const QString& name = advance();
log(keyword + QLatin1Char(' ') + name);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum,
name, currentScope(), m_comment);
UMLEnum *enumType = ns->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(ns, currentScope());
skipStmt(QStringLiteral("{"));
while (m_srcIndex < srcLength - 1 && advance() != QStringLiteral("}")) {
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, m_source[m_srcIndex]);
QString next = advance();
if (next == QStringLiteral("{") || next == QStringLiteral("(")) {
if (! skipToClosing(next[0]))
return false;
next = advance();
}
if (next != QStringLiteral(",")) {
if (next == QStringLiteral(";")) {
// @todo handle methods in enum
// For now, we cheat (skip them)
m_source[m_srcIndex] = QLatin1Char('{');
if (! skipToClosing(QLatin1Char('{')))
return false;
}
break;
}
}
return true;
}
if (keyword == QStringLiteral("static")) {
m_isStatic = true;
return true;
}
// if we detected static previously and keyword is { then this is a static block
if (m_isStatic && keyword == QStringLiteral("{")) {
// reset static flag and jump to end of static block
m_isStatic = false;
return skipToClosing(QLatin1Char('{'));
}
if (keyword == QStringLiteral("abstract")) {
m_isAbstract = true;
return true;
}
if (keyword == QStringLiteral("public")) {
m_currentAccess = Uml::Visibility::Public;
return true;
}
if (keyword == QStringLiteral("protected")) {
m_currentAccess = Uml::Visibility::Protected;
return true;
}
if (keyword == QStringLiteral("private")) {
m_currentAccess = Uml::Visibility::Private;
return true;
}
if (keyword == QStringLiteral("final") ||
keyword == QStringLiteral("native") ||
keyword == QStringLiteral("synchronized") ||
keyword == QStringLiteral("transient") ||
keyword == QStringLiteral("volatile")) {
//@todo anything to do here?
return true;
}
if (keyword == QStringLiteral("import")) {
// keep track of imports so we can resolve classes we are dependent on
QString import = advance();
if (import.endsWith(QLatin1Char('.'))) {
//this most likely an import that ends with a *
//
import = import + advance();
}
m_imports.append(import);
// move past ;
skipStmt();
return true;
}
if (keyword == QStringLiteral("@")) { // annotation
advance();
if (m_source[m_srcIndex + 1] == QStringLiteral("(")) {
advance();
skipToClosing(QLatin1Char('('));
}
return true;
}
if (keyword == QStringLiteral("}")) {
if (scopeIndex()) {
m_klass = popScope()->asUMLClassifier();
}
else
logError1("JavaImport::parseStmt: too many } at index %1", m_srcIndex);
return true;
}
if (keyword == QStringLiteral("<")) { // @todo generic parameters
if (! skipToClosing(QLatin1Char('<'))) {
logError1("JavaImport::parseStmt(%1): template syntax error", keyword);
return false;
}
advance();
if (m_srcIndex == srcLength)
return false;
keyword = m_source[m_srcIndex];
}
// At this point, we expect `keyword` to be a type name
// (of a member of class or interface, or return type
// of an operation.) Up next is the name of the attribute
// or operation.
if (! keyword.contains(QRegularExpression(QStringLiteral("^\\w")))) {
if (m_klass) {
logError4("JavaImport::parseStmt: ignoring %1 at index %2 of %3 in %4",
keyword, m_srcIndex, m_source.count(), m_klass->name());
} else {
logError3("JavaImport::parseStmt: ignoring %1 at index %2 of %3 (outside class)",
keyword, m_srcIndex, m_source.count());
}
return false;
}
QString typeName = m_source[m_srcIndex];
typeName = joinTypename(typeName);
// At this point we need a class.
if (m_klass == nullptr) {
logError1("JavaImport::parseStmt: no class set for %1", typeName);
return false;
}
QString name = advance();
QString nextToken;
if (typeName == m_klass->name() && name == QStringLiteral("(")) {
// Constructor.
nextToken = name;
name = typeName;
typeName.clear();
} else {
nextToken = advance();
}
if (name.contains(QRegularExpression(QStringLiteral("\\W")))) {
logError1("JavaImport::parseStmt: expecting name in %1", name);
return false;
}
if (nextToken == QStringLiteral("(")) {
// operation
UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
m_srcIndex++;
while (m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(")")) {
QString typeName = m_source[m_srcIndex];
if (typeName == QStringLiteral("final") || typeName.startsWith(QStringLiteral("//"))) {
// ignore the "final" keyword and any comments in method args
typeName = advance();
}
typeName = joinTypename(typeName);
QString parName = advance();
// the Class might not be resolved yet so resolve it if necessary
UMLObject *obj = resolveClass(typeName);
if (obj) {
// by prepending the package, unwanted placeholder types will not get created
typeName = obj->fullyQualifiedName(QStringLiteral("."));
}
/* UMLAttribute *att = */ Import_Utils::addMethodParameter(op, typeName, parName);
if (advance() != QStringLiteral(","))
break;
m_srcIndex++;
}
if (!typeName.isEmpty() && typeName != QStringLiteral("void")) {
// before adding the method, try resolving the return type
UMLObject *obj = resolveClass(typeName);
if (obj) {
// using the fully qualified name means that a placeholder type will not be created.
typeName = obj->fullyQualifiedName(QStringLiteral("."));
}
}
Import_Utils::insertMethod(m_klass, op, m_currentAccess, typeName,
m_isStatic, m_isAbstract, false /*isFriend*/,
false /*isConstructor*/, false, m_comment);
m_isAbstract = m_isStatic = false;
// reset the default visibility
m_currentAccess = m_defaultCurrentAccess;
// At this point we do not know whether the method has a body or not.
do {
nextToken = advance();
} while (nextToken != QStringLiteral("{") && nextToken != QStringLiteral(";"));
if (nextToken == QStringLiteral(";")) {
// No body (interface or abstract)
return true;
} else {
return skipToClosing(QLatin1Char('{'));
}
}
// At this point we know it's some kind of attribute declaration.
while (1) {
while (nextToken != QStringLiteral(",") && nextToken != QStringLiteral(";")) {
if (nextToken == QStringLiteral("=")) {
if ((nextToken = advance()) == QStringLiteral("new")) {
advance();
if ((nextToken = advance()) == QStringLiteral("(")) {
skipToClosing(QLatin1Char('('));
if ((nextToken = advance()) == QStringLiteral("{")) {
skipToClosing(QLatin1Char('{'));
} else {
skipStmt();
break;
}
} else {
skipStmt();
break;
}
} else {
skipStmt();
break;
}
} else {
name += nextToken; // add possible array dimensions to `name`
}
nextToken = advance();
if (nextToken.isEmpty()) {
break;
}
}
// try to resolve the class type, or create a placeholder if that fails
UMLObject *type = resolveClass(typeName);
if (type) {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
type->asUMLClassifier(), m_comment, m_isStatic);
} else {
Import_Utils::insertAttribute(
m_klass, m_currentAccess, name,
typeName, m_comment, m_isStatic);
}
// UMLAttribute *attr = o->asUMLAttribute();
if (nextToken != QStringLiteral(",")) {
// reset the modifiers
m_isStatic = m_isAbstract = false;
break;
}
name = advance();
nextToken = advance();
}
// reset visibility to default
m_currentAccess = m_defaultCurrentAccess;
if (m_srcIndex < m_source.count()) {
if (m_source[m_srcIndex] != QStringLiteral(";")) {
logError1("JavaImport::parseStmt: ignoring trailing items at %1", name);
skipStmt();
}
}
else {
logError1("JavaImport::parseStmt index out of range: ignoring statement %1", name);
skipStmt();
}
return true;
}
| 26,963
|
C++
|
.cpp
| 659
| 30.587253
| 134
| 0.565112
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,593
|
idlimport.cpp
|
KDE_umbrello/umbrello/codeimport/idlimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "idlimport.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "codeimpthread.h"
#define DBG_SRC QStringLiteral("IDLImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "package.h"
#include "stereotype.h"
#include "uml.h"
#include "umldoc.h"
#include "umlpackagelist.h"
// qt includes
#include <QProcess>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QStringList>
#include <stdio.h>
DEBUG_REGISTER(IDLImport)
QString IDLImport::m_preProcessor;
QStringList IDLImport::m_preProcessorArguments;
bool IDLImport::m_preProcessorChecked = false;
IDLImport::IDLImport(CodeImpThread* thread) : NativeImportBase(QStringLiteral("//"), thread)
{
m_doc = UMLApp::app()->document();
m_isOneway = m_isReadonly = m_isAttribute = m_isUnionDefault = false;
setMultiLineComment(QStringLiteral("/*"), QStringLiteral("*/"));
// we do not want to find the executable on each imported file
if (m_preProcessorChecked) {
m_enabled = !m_preProcessor.isEmpty();
return;
}
QStringList arguments;
QString executable = QStandardPaths::findExecutable(QStringLiteral("cpp"));
if (!executable.isEmpty()) {
arguments << QStringLiteral("-C"); // -C means "preserve comments"
}
#ifdef Q_OS_WIN
else {
executable = QStandardPaths::findExecutable(QStringLiteral("cl"));
if (executable.isEmpty()) {
QString path = QLatin1String(qgetenv("VS100COMNTOOLS").constData());
if (!path.isEmpty())
executable = QStandardPaths::findExecutable(QStringLiteral("cl"), QStringList() << path + QStringLiteral("/../../VC/bin"));
}
if (!executable.isEmpty()) {
arguments << QStringLiteral("-E"); // -E means "preprocess to stdout"
}
}
#endif
if (!executable.isEmpty()) {
m_preProcessor = executable;
m_preProcessorArguments = arguments;
}
else {
log(QStringLiteral("Error: Cannot find any of the supported preprocessors (gcc, Microsoft Visual Studio 2010)"));
m_enabled = false;
}
m_preProcessorChecked = true;
}
IDLImport::~IDLImport()
{
}
/// Check for split type names (e.g. unsigned long long)
QString IDLImport::joinTypename()
{
QString typeName = m_source[m_srcIndex];
if (m_source[m_srcIndex] == QStringLiteral("unsigned"))
typeName += QLatin1Char(' ') + advance();
if (m_source[m_srcIndex] == QStringLiteral("long") &&
(m_source[m_srcIndex + 1] == QStringLiteral("long") ||
m_source[m_srcIndex + 1] == QStringLiteral("double")))
typeName += QLatin1Char(' ') + advance();
return typeName;
}
/**
* Override operation from NativeImportBase.
*/
bool IDLImport::preprocess(QString& line)
{
// Ignore C preprocessor generated lines.
if (line.startsWith(QLatin1Char('#')))
return true; // done
return NativeImportBase::preprocess(line);
}
/**
* Implement abstract operation from NativeImportBase.
*/
void IDLImport::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
for (uint i = 0; i < len; ++i) {
QChar c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
lexeme += c;
} else if (c == QLatin1Char(':') && i < len-1 && word[i + 1] == QLatin1Char(':')) {
// compress scoped name into lexeme
lexeme += QStringLiteral("::");
i++;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
m_source.append(QString(c));
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
}
/**
* Reimplement operation from NativeImportBase.
* Need to do this because we use the external C preprocessor.
*/
bool IDLImport::parseFile(const QString& filename)
{
if (filename.contains(QLatin1Char('/'))) {
QString path = filename;
path.remove(QRegularExpression(QStringLiteral("/[^/]+$")));
logDebug1("IDLImport::parseFile adding path %1", path);
Import_Utils::addIncludePath(path);
}
const QStringList includePaths = Import_Utils::includePathList();
if (m_preProcessor.isEmpty()) {
log(QStringLiteral("Error: no preprocessor installed, could not import file"));
return false;
}
QStringList arguments(m_preProcessorArguments);
QProcess p(UMLApp::app());
for (QStringList::ConstIterator pathIt = includePaths.begin();
pathIt != includePaths.end(); ++pathIt) {
QString path = (*pathIt);
arguments << QStringLiteral("-I") + path;
}
arguments << filename;
logDebug2("importIDL::parseFile: %1 %2", m_preProcessor, arguments.join(QStringLiteral(" ")));
p.start(m_preProcessor, arguments);
if (!p.waitForStarted()) {
log(QStringLiteral("Error: could not run preprocessor"));
return false;
}
if (!p.waitForFinished()) {
log(QStringLiteral("Error: could not run preprocessor"));
return false;
}
int exitCode = p.exitCode();
if (exitCode != 0) {
QString errMsg = QStringLiteral("Error: preprocessor returned error");
log(errMsg + QString::number(exitCode));
return false;
}
QByteArray out = p.readAllStandardOutput();
QTextStream data(out);
// Scan the input file into the QStringList m_source.
m_source.clear();
while (!data.atEnd()) {
NativeImportBase::scan(data.readLine());
}
// Parse the QStringList m_source.
m_scope.clear();
pushScope(nullptr); // global scope
const int srcLength = m_source.count();
for (m_srcIndex = 0; m_srcIndex < srcLength; ++m_srcIndex) {
const QString& keyword = m_source[m_srcIndex];
//uDebug() << QLatin1Char('"') << keyword << QLatin1Char('"');
if (keyword.startsWith(m_singleLineCommentIntro)) {
m_comment = keyword.mid(m_singleLineCommentIntro.length());
continue;
}
if (! parseStmt())
skipStmt();
m_currentAccess = Uml::Visibility::Public;
m_comment.clear();
}
return true;
}
/**
* Skip to the end of struct/union/valuetype/interface declaration.
*
* @return True for success, false for non recoverable syntax error
* related to brace matching (missing opening or closing brace).
*/
bool IDLImport::skipStructure()
{
bool status = skipToClosing(QLatin1Char('{')); // skip to '}'
// Skipping of ';' after '}' is done by NativeImportBase::parseFile
return status;
}
/**
* Returns true if the given text is a valid IDL scoped name.
*/
bool IDLImport::isValidScopedName(QString text) {
QRegularExpression validScopedName(QStringLiteral("^[A-Za-z_:][A-Za-z0-9_:]*$"));
return text.contains(validScopedName);
}
/**
* Implement abstract operation from NativeImportBase.
* The function only returns false if an error is encountered from which
* no recovery is possible.
* On recoverable syntax errors, the function issues an error message,
* skips to the end of the offending declaration, and returns true.
* Returning true in spite of a local syntax error is done in the interest
* of best effort (returning false would abort the entire code import).
* A syntax error is typically unrecoverable when it involves imbalance of
* braces, in particular when the closing "}" of an opening "{" is missing.
*/
bool IDLImport::parseStmt()
{
QString keyword = m_source[m_srcIndex];
const int srcLength = m_source.count();
logDebug1("IDLImport::parseStmt: keyword is %1", keyword);
if (keyword == QStringLiteral("module")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, currentScope(), m_comment);
pushScope(ns->asUMLPackage());
currentScope()->setStereotype(QStringLiteral("idlModule"));
if (advance() != QStringLiteral("{")) {
log(QStringLiteral("Error: importIDL: unexpected: ") + m_source[m_srcIndex]);
skipStmt(QStringLiteral("{"));
}
return true;
}
if (keyword == QStringLiteral("interface")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class,
name, currentScope(), m_comment);
m_klass = ns->asUMLClassifier();
m_klass->setStereotype(QStringLiteral("idlInterface"));
m_klass->setAbstract(m_isAbstract);
m_isAbstract = false;
m_comment.clear();
if (advance() == QStringLiteral(";")) // forward declaration
return true;
pushScope(m_klass);
if (m_source[m_srcIndex] == QStringLiteral(":")) {
while (++m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral("{")) {
const QString& baseName = m_source[m_srcIndex];
Import_Utils::createGeneralization(m_klass, baseName);
if (advance() != QStringLiteral(","))
break;
}
}
if (m_source[m_srcIndex] != QStringLiteral("{")) {
log(QStringLiteral("Error: importIDL: ignoring excess chars at ") + name);
skipStmt(QStringLiteral("{"));
}
return true;
}
if (keyword == QStringLiteral("struct") || keyword == QStringLiteral("exception")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class,
name, currentScope(), m_comment);
m_klass = ns->asUMLClassifier();
pushScope(m_klass);
if (keyword == QStringLiteral("struct"))
m_klass->setStereotype(QStringLiteral("idlStruct"));
else
m_klass->setStereotype(QStringLiteral("idlException"));
if (advance() != QStringLiteral("{")) {
log(QStringLiteral("Error: importIDL: expecting '{' at ") + name);
skipStmt(QStringLiteral("{"));
}
return true;
}
if (keyword == QStringLiteral("union")) {
const QString& name = advance();
// create union type
UMLObject *u = Import_Utils::createUMLObject(UMLObject::ot_Class,
name, currentScope(), m_comment,
QStringLiteral("idlUnion"));
if (!u) {
log(QStringLiteral("Error: importIDL: Could not create union ") + name);
return skipStructure();
}
UMLClassifier *uc = u->asUMLClassifier();
if (!uc) {
log(QStringLiteral("Error: importIDL(") + name +
QStringLiteral("): Expecting type ot_Class, actual type is ") +
UMLObject::toString(u->baseType()));
return skipStructure();
}
if (advance() != QStringLiteral("switch")) {
log(QStringLiteral("Error: importIDL: expecting 'switch' after ") + name);
return skipStructure();
}
if (advance() != QStringLiteral("(")) {
log(QStringLiteral("Error: importIDL: expecting '(' after 'switch'"));
return skipStructure();
}
const QString& switchType = advance();
if (!isValidScopedName(switchType)) {
log(QStringLiteral("Error: importIDL: expecting typename after 'switch'"));
return skipStructure();
}
// find or create discriminator type
UMLObject *dt = Import_Utils::createUMLObject(UMLObject::ot_Class,
switchType, currentScope(), m_comment);
if (!dt) {
log(QStringLiteral("Error: importIDL(") + name +
QStringLiteral("): Could not create switchtype ") + switchType);
return skipStructure();
}
UMLClassifier *discrType = dt->asUMLClassifier();
if (!discrType) {
log(QStringLiteral("Error: importIDL(") + name +
QStringLiteral(") swichtype: Expecting classifier type, found ") +
UMLObject::toString(dt->baseType()));
return skipStructure();
}
m_currentAccess = Uml::Visibility::Public;
UMLAttribute *discr = Import_Utils::insertAttribute(uc, m_currentAccess,
QStringLiteral("discriminator"),
discrType, m_comment);
if (!discr) {
log(QStringLiteral("Error: importIDL(") + name +
QStringLiteral("): Could not create switch attribute"));
return skipStructure();
}
discr->setStereotype(QStringLiteral("idlSwitch"));
if (advance() != QStringLiteral(")")) {
log(QStringLiteral("Error: importIDL: expecting ')' after switch type"));
return skipStructure();
}
if (advance() != QStringLiteral("{")) {
log(QStringLiteral("Error: importIDL(") + name +
QStringLiteral("): expecting '{' after switch type"));
return skipStructure();
}
m_klass = uc;
pushScope(m_klass);
m_unionCases.clear();
m_isUnionDefault = false;
return true;
}
if (keyword == QStringLiteral("case")) {
QString caseValue = advance();
if (!isValidScopedName(caseValue)) {
log(QStringLiteral("Error: importIDL: expecting symbolic identifier after 'case'"));
skipStmt(QStringLiteral(":"));
}
m_unionCases.append(caseValue);
if (advance() != QStringLiteral(":")) {
log(QStringLiteral("Error: importIDL: expecting ':' after 'case'"));
}
return true;
}
if (keyword == QStringLiteral("default")) {
m_isUnionDefault = true;
if (advance() != QStringLiteral(":")) {
log(QStringLiteral("Error: importIDL: expecting ':' after 'default'"));
}
return true;
}
if (keyword == QStringLiteral("enum")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum,
name, currentScope(), m_comment);
UMLEnum *enumType = ns->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(ns, currentScope());
m_srcIndex++; // skip name
while (++m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral("}")) {
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, m_source[m_srcIndex]);
if (advance() != QStringLiteral(","))
break;
}
skipStmt();
return true;
}
if (keyword == QStringLiteral("typedef")) {
if (m_source[m_srcIndex + 2] == QStringLiteral("<")) {
keyword = advance();
m_srcIndex += 2;
QString oldType;
QString bound;
if (keyword == QStringLiteral("sequence")) {
oldType = joinTypename();
if (advance() == QStringLiteral(",")) {
bound = advance();
m_srcIndex++; // position on ">"
}
} else if (keyword == QStringLiteral("string")) {
bound = m_source[m_srcIndex];
m_srcIndex++; // position on ">"
} else {
log(QStringLiteral("Error: parseStmt: Expecting 'sequence' or 'string', found ") +
keyword);
skipStmt();
return true;
}
const QString& newType = advance();
skipStmt();
UMLObject::ObjectType ot = (oldType.length() ? UMLObject::ot_Class : UMLObject::ot_Datatype);
UMLObject *pOld = m_doc->findUMLObject(oldType, UMLObject::ot_UMLObject, currentScope());
if (pOld == nullptr) {
pOld = Import_Utils::createUMLObject(ot, oldType, currentScope());
}
UMLObject *dt = Import_Utils::createUMLObject(ot, newType, currentScope(), m_comment);
if (!dt) {
log(QStringLiteral("Error: importIDL(typedef ") + keyword +
QStringLiteral("): Could not create datatype ") + newType);
return true;
}
QString stereoName = (oldType.length() ? QStringLiteral("idlSequence") : QStringLiteral("idlString"));
UMLStereotype *pStereo = m_doc->findStereotype(stereoName);
if (pStereo == nullptr) {
pStereo = m_doc->createStereotype(stereoName);
UMLStereotype::AttributeDef tagDef(QStringLiteral("bound"), Uml::PrimitiveTypes::UnlimitedNatural);
// Empty bound stands for "unbounded".
pStereo->getAttributeDefs().append(tagDef);
}
if (oldType.length()) {
UMLAttribute *typeAttr = Object_Factory::createAttribute(dt, QStringLiteral("members"), pOld);
Q_UNUSED(typeAttr);
/*
UMLClassifier *cl = dt->asUMLClassifier();
if (cl == 0) {
logError1("parseStmt(typedef %1) internal error: object returned by "
"Import_Utils::createUMLObject is not a Class", newType);
return false;
} */
}
dt->setUMLStereotype(pStereo);
dt->tags().append(bound);
return true;
}
m_srcIndex++;
const QString& oldType = joinTypename();
const QString& newType = advance();
logDebug3("IDLImport::parseStmt(typedef) : oldType is %1, newType is %2, scopeIndex is %3",
oldType, newType, scopeIndex());
UMLObject::ObjectType ot = UMLObject::ot_Class;
UMLObject *pOld = m_doc->findUMLObject(oldType, UMLObject::ot_UMLObject, currentScope());
if (pOld) {
ot = pOld->baseType();
} else {
pOld = Import_Utils::createUMLObject(ot, oldType, currentScope());
}
UMLClassifier *oldClassifier = pOld->asUMLClassifier();
UMLObject *pNew = Import_Utils::createUMLObject(ot, newType, currentScope(), m_comment,
QStringLiteral("idlTypedef")); /* stereotype */
UMLClassifier *newClassifier = pNew->asUMLClassifier();
if (oldClassifier == nullptr) {
log(QStringLiteral("Error: importIDL(typedef ") + newType +
QStringLiteral("): Origin type ") + oldType + QStringLiteral(" is not a classifier"));
} else if (newClassifier == nullptr) {
log(QStringLiteral("Error: importIDL(typedef ") + newType +
QStringLiteral(") internal error: Import_Utils::createUMLObject did not return a classifier"));
} else {
Import_Utils::createGeneralization(newClassifier, oldClassifier);
}
skipStmt();
return true;
}
if (keyword == QStringLiteral("const")) {
skipStmt();
return true;
}
if (keyword == QStringLiteral("custom")) {
return true;
}
if (keyword == QStringLiteral("abstract")) {
m_isAbstract = true;
return true;
}
if (keyword == QStringLiteral("valuetype")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class,
name, currentScope(), m_comment);
m_klass = ns->asUMLClassifier();
m_klass->setStereotype(QStringLiteral("idlValue"));
m_klass->setAbstract(m_isAbstract);
m_isAbstract = false;
if (advance() == QStringLiteral(";")) // forward declaration
return true;
pushScope(m_klass);
if (m_source[m_srcIndex] == QStringLiteral(":")) {
if (advance() == QStringLiteral("truncatable"))
m_srcIndex++;
while (m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral("{")) {
const QString& baseName = m_source[m_srcIndex];
Import_Utils::createGeneralization(m_klass, baseName);
if (advance() != QStringLiteral(","))
break;
m_srcIndex++;
}
}
if (m_source[m_srcIndex] != QStringLiteral("{")) {
log(QStringLiteral("Error: importIDL: ignoring excess chars at ") + name);
skipStmt(QStringLiteral("{"));
}
return true;
}
if (keyword == QStringLiteral("public")) {
return true;
}
if (keyword == QStringLiteral("private")) {
m_currentAccess = Uml::Visibility::Private;
return true;
}
if (keyword == QStringLiteral("readonly")) {
m_isReadonly = true;
return true;
}
if (keyword == QStringLiteral("attribute")) {
m_isAttribute = true;
return true;
}
if (keyword == QStringLiteral("oneway")) {
m_isOneway = true;
return true;
}
if (keyword == QStringLiteral("}")) {
if (scopeIndex())
m_klass = popScope()->asUMLClassifier();
else
log(QStringLiteral("Error: importIDL: too many }"));
m_srcIndex++; // skip ';'
return true;
}
if (keyword == QStringLiteral(";"))
return true;
// At this point, we expect `keyword` to be a type name
// (of a member of struct or valuetype, or return type
// of an operation.) Up next is the name of the attribute
// or operation.
if (! keyword.contains(QRegularExpression(QStringLiteral("^\\w")))) {
log(QStringLiteral("Error: importIDL: ignoring ") + keyword);
return false;
}
QString typeName = joinTypename();
QString name = advance();
if (name.contains(QRegularExpression(QStringLiteral("\\W")))) {
log(QStringLiteral("Error: importIDL: expecting name in ") + name);
return false;
}
// At this point we most definitely need a class.
if (m_klass == nullptr) {
log(QStringLiteral("Error: importIDL: no class set for ") + name);
return false;
}
QString nextToken = advance();
if (nextToken == QStringLiteral("(")) {
// operation
UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
m_srcIndex++;
while (m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(")")) {
const QString &direction = m_source[m_srcIndex++];
QString typeName = joinTypename();
const QString &parName = advance();
UMLAttribute *att = Import_Utils::addMethodParameter(op, typeName, parName);
Uml::ParameterDirection::Enum dir;
if (Model_Utils::stringToDirection(direction, dir))
att->setParmKind(dir);
else
log(QStringLiteral("Error: importIDL: expecting parameter direction at ") +
direction);
if (advance() != QStringLiteral(","))
break;
m_srcIndex++;
}
Import_Utils::insertMethod(m_klass, op, Uml::Visibility::Public, typeName,
false, false, false, false, false, m_comment);
if (m_isOneway) {
op->setStereotype(QStringLiteral("oneway"));
m_isOneway = false;
}
skipStmt(); // skip possible "raises" clause
return true;
}
// At this point we know it's some kind of attribute declaration.
while (1) {
while (nextToken != QStringLiteral(",") && nextToken != QStringLiteral(";")) {
name += nextToken; // add possible array dimensions to `name`
nextToken = advance();
}
UMLAttribute *attr = Import_Utils::insertAttribute(m_klass, m_currentAccess, name, typeName, m_comment);
if (m_isReadonly) {
attr->setStereotype(QStringLiteral("readonly"));
m_isReadonly = false;
}
if (m_unionCases.count()) {
const QString stereoName = QStringLiteral("idlCase");
UMLStereotype *pStereo = m_doc->findStereotype(stereoName);
if (pStereo == nullptr) {
pStereo = m_doc->createStereotype(stereoName);
UMLStereotype::AttributeDef tagDef(QStringLiteral("label"), Uml::PrimitiveTypes::String);
pStereo->getAttributeDefs().append(tagDef);
}
attr->setUMLStereotype(pStereo);
const QString caseLabels = m_unionCases.join(QLatin1Char(' '));
attr->tags().append(caseLabels);
m_unionCases.clear();
} else if (m_isUnionDefault) {
attr->setStereotype(QStringLiteral("idlDefault"));
m_isUnionDefault = false;
}
if (nextToken != QStringLiteral(","))
break;
name = advance();
nextToken = advance();
}
return true;
}
| 25,458
|
C++
|
.cpp
| 616
| 31.795455
| 139
| 0.586308
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,594
|
phpimport.cpp
|
KDE_umbrello/umbrello/codeimport/phpimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2017-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "phpimport.h"
// app includes
#include "artifact.h"
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#define DBG_SRC QStringLiteral("PHPImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "object_factory.h"
#include "operation.h"
#include "optionstate.h"
#include "package.h"
#include "template.h"
#include "uml.h"
#include "umldoc.h"
#include "umlobject.h"
// KDE includes
#include <KLocalizedString>
// qt includes
#include <QListWidget>
#include <QMap>
QTextStream qout(stdout);
QTextStream qerr(stderr);
QTextStream qin(stdin);
// kdevphp
#include <parser/parsesession.h>
#include <parser/phplexer.h>
#include <parser/phpparser.h>
#include <parser/phpdebugvisitor.h>
#include <parser/phpast.h>
#include <parser/tokenstream.h>
#include <parser/phptokentext.h>
// kdevplatform
#include <tests/autotestshell.h>
#include <language/duchain/duchain.h>
#include <language/duchain/problem.h>
#include <language/codegen/coderepresentation.h>
#include <language/editor/documentrange.h>
#include <tests/testcore.h>
DEBUG_REGISTER(PHPImport)
namespace Php {
typedef QMap<QString, QString> VariableMapping;
class PHPIncludeFileVisitor : public DefaultVisitor
{
public:
PHPIncludeFileVisitor(TokenStream *str, const QString& content = QString())
: m_str (str),
m_content(content),
m_indent(0),
m_dependencies(0)
{}
void setFilePath(const QString &path)
{
m_filePath = path;
}
void setVariableMapping(VariableMapping &map)
{
m_map = map;
}
void setDependencies(QStringList &dependencies)
{
m_dependencies = &dependencies;
}
virtual void visitUnaryExpression(UnaryExpressionAst *node)
{
if (node->includeExpression) {
visitIncludeExpression(node->includeExpression);
}
DefaultVisitor::visitUnaryExpression(node);
}
void visitIncludeExpression(UnaryExpressionAst *node)
{
QString tokenString;
if (!m_content.isEmpty())
{
TokenStream::Token startToken = m_str->at(node->startToken);
TokenStream::Token endToken = m_str->at(node->endToken);
int begin = startToken.begin;
int end = endToken.end;
tokenString = m_content.mid(begin, end-begin+1);
if (tokenString.startsWith("(\"") || tokenString.startsWith("('"))
tokenString = tokenString.mid(2, tokenString.size() - 4);
else if (tokenString.startsWith("("))
tokenString = tokenString.mid(1, tokenString.size() - 2);
const QString search = "dirname(__FILE__).";
if (tokenString.contains(search)) {
tokenString.replace(search, m_filePath);
tokenString.replace("\"", "");
tokenString.replace("\'", "");
} else if(tokenString.startsWith("$")) {
int i = tokenString.indexOf('.');
QString key = tokenString.mid(1, i-1);
if (m_map.contains(key)) {
tokenString.replace("$" + key + ".", m_map[key]);
tokenString.replace("\"", "");
tokenString.replace("\'", "");
}
} // generate parse error for unknown variables
qDebug() << "-------------------include ----- " << tokenString;
if (!m_dependencies->contains(tokenString))
m_dependencies->append(tokenString);
}
}
TokenStream *m_str;
QString m_content;
int m_indent;
QStringList *m_dependencies;
QString m_filePath;
VariableMapping m_map;
};
const int NamespaceSize = 100;
/**
* Derived visitor class
*/
class PHPImportVisitor : public DefaultVisitor
{
public:
PHPImportVisitor(TokenStream *str, const QString& content = QString())
: m_str (str),
m_content(content),
m_indent(0),
m_nsCnt(0)
{
m_currentNamespace.fill(0, NamespaceSize);
Import_Utils::createUMLObject(UMLObject::ot_Datatype, "auto", 0);
}
void setFileName(const QString &fileName)
{
m_fileName = fileName;
}
QString tokenValue(AstNode *node)
{
TokenStream::Token startToken = m_str->at(node->startToken);
TokenStream::Token endToken = m_str->at(node->endToken);
int begin = startToken.begin;
int end = endToken.end;
return m_content.mid(begin, end-begin+1);
}
QString tokenValue(const KDevPG::ListNode<Php::NamespacedIdentifierAst*> *node)
{
QStringList names;
const KDevPG::ListNode<NamespacedIdentifierAst*> *__it = node->front(), *__end = __it;
do
{
names.append(tokenValue(__it->element));
__it = __it->next;
}
while (__it != __end);
return names.join("::");
}
void visitStart(StartAst *node)
{
if (Settings::optionState().codeImportState.createArtifacts) {
QFileInfo fi(m_fileName);
UMLObject *o = Import_Utils::createArtifactFolder(fi.canonicalPath(), 0, QString());
UMLPackage *p = o->asUMLPackage();
QString fileName = fi.fileName();
o = UMLApp::app()->document()->findUMLObject(fileName, UMLObject::ot_Artifact, p);
if (!o)
o = Object_Factory::createNewUMLObject(UMLObject::ot_Artifact, fileName, p, true);
UMLArtifact *a = o->asUMLArtifact();
if (a)
a->setDrawAsType(UMLArtifact::file);
else
logError1("PHPImportVisitor::visitStart could not add artifact %1", m_fileName);
//a->setDoc(comment);
}
DefaultVisitor::visitStart(node);
}
void visitSimpleNamespaceDeclarationStatement(NamespaceDeclarationStatementAst *node)
{
QStringList nsNames;
if (node->namespaceNameSequence)
{
const KDevPG::ListNode<IdentifierAst*> *it = node->namespaceNameSequence->front(), *end = it;
do {
nsNames.append(tokenValue(it->element));
visitNode(it->element);
it = it->next;
} while (it != end);
}
m_nsCnt = 0;
for(const QString &nsName : nsNames) {
UMLPackage *parentPackage = m_currentNamespace[m_nsCnt];
UMLObject *o = UMLApp::app()->document()->findUMLObject(nsName, UMLObject::ot_Package, parentPackage);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Package, nsName, parentPackage);
if (++m_nsCnt > NamespaceSize) {
logError0("PHPImportVisitor::visitSimpleNamespaceDeclarationStatement: excessive namespace nesting");
m_nsCnt = NamespaceSize;
}
UMLPackage *ns = o->asUMLPackage();
m_currentScope.push_back(nsName);
m_currentNamespace[m_nsCnt] = ns;
}
}
void visitStapledNamespaceDeclarationStatement(NamespaceDeclarationStatementAst *node)
{
QStringList nsNames;
if (node->namespaceNameSequence)
{
const KDevPG::ListNode<IdentifierAst*> *it = node->namespaceNameSequence->front(), *end = it;
do {
nsNames.append(tokenValue(it->element));
visitNode(it->element);
it = it->next;
} while (it != end);
}
m_nsCnt = 0;
for(const QString &nsName : nsNames) {
UMLPackage *parentPackage = m_currentNamespace[m_nsCnt];
UMLObject *o = UMLApp::app()->document()->findUMLObject(nsName, UMLObject::ot_Package, parentPackage);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Package, nsName, parentPackage);
if (++m_nsCnt > NamespaceSize) {
logError0("PHPImportVisitor::visitStapledNamespaceDeclarationStatement: excessive namespace nesting");
m_nsCnt = NamespaceSize;
}
UMLPackage *ns = o->asUMLPackage();
m_currentScope.push_back(nsName);
m_currentNamespace[m_nsCnt] = ns;
}
visitNode(node->body);
m_nsCnt = 0;
m_currentScope.clear();
}
void visitNamespaceDeclarationStatement(NamespaceDeclarationStatementAst *node)
{
if (!node->body)
visitSimpleNamespaceDeclarationStatement(node);
else
visitStapledNamespaceDeclarationStatement(node);
}
void visitUseNamespace(UseNamespaceAst *node)
{
QStringList nsNames;
if (node->identifier->namespaceNameSequence)
{
const KDevPG::ListNode<IdentifierAst*> *it = node->identifier->namespaceNameSequence->front(), *end = it;
do {
nsNames.append(tokenValue(it->element));
visitNode(it->element);
it = it->next;
} while (it != end);
}
UMLPackage *parent = nullptr;
QString names = nsNames.join("::");
UMLObject *o = UMLApp::app()->document()->findUMLObject(names, UMLObject::ot_Class, parent);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Class, names, parent);
if (o) {
m_usingClasses.append(o->asUMLClassifier());
logDebug1("using class %1", names);
}
DefaultVisitor::visitUseNamespace(node);
}
void visitClassVariable(ClassVariableAst *node)
{
DefaultVisitor::visitClassVariable(node);
_printToken(node->variable, "VariableIdentifierAst", "ClassVariableAst");
}
void visitClassStatement(ClassStatementAst *node)
{
if (!node || !node->methodName)
return;
QString methodName = tokenValue(node->methodName);
Uml::Visibility::Enum m_currentAccess = Uml::Visibility::Public;
QString returnType = "auto";
bool isStatic = false;
bool isAbstract = false;
bool isFriend = false;
bool isConstructor = false;
bool isDestructor = false;
QString m_comment;
UMLPackage *parentPackage = m_currentNamespace[m_nsCnt];
UMLClassifier *c = parentPackage->asUMLClassifier();
UMLOperation *m = nullptr;
if (c) {
m = Import_Utils::makeOperation(c, methodName);
} else {
logError1("PHPImportVisitor::visitClassStatement: no parent class found for method %1", methodName);
}
if (m) {
if (node->parameters && node->parameters->parametersSequence) {
const KDevPG::ListNode<ParameterAst*> *__it = node->parameters->parametersSequence->front(), *__end = __it;
do {
QString type = "auto";
QString name = tokenValue(__it->element->variable).mid(1);
Import_Utils::addMethodParameter(m, type, name);
__it = __it->next;
} while (__it != __end);
}
Import_Utils::insertMethod(c, m, m_currentAccess, returnType,
isStatic, isAbstract, isFriend, isConstructor,
isDestructor, m_comment);
}
DefaultVisitor::visitClassStatement(node);
}
void visitClassExtends(ClassExtendsAst *node)
{
if (node->identifier) {
QString baseName = tokenValue(node->identifier);
UMLClassifier *a = m_currentNamespace[m_nsCnt]->asUMLClassifier();
for(UMLObject *uc : m_usingClasses) {
if (uc->name() == baseName) {
Import_Utils::createGeneralization(a, uc->asUMLClassifier());
}
}
}
DefaultVisitor::visitClassExtends(node);
}
void visitClassImplements(ClassImplementsAst *node)
{
if (node->implementsSequence) {
QString baseName = tokenValue(node->implementsSequence);
UMLClassifier *a = m_currentNamespace[m_nsCnt]->asUMLClassifier();
bool found = false;
for(UMLObject *uc : m_usingClasses) {
if (uc->name() == baseName) {
Import_Utils::createGeneralization(a, uc->asUMLClassifier());
found = true;
}
}
if (!found) {
UMLObject *o = UMLApp::app()->document()->findUMLObject(baseName, UMLObject::ot_Interface,
m_currentNamespace[m_nsCnt-1]);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Interface, baseName,
m_currentNamespace[m_nsCnt-1],
QString()/*ast->comment()*/, QString(), true);
Import_Utils::createGeneralization(a, o->asUMLClassifier());
}
}
DefaultVisitor::visitClassImplements(node);
}
void visitInterfaceDeclarationStatement(InterfaceDeclarationStatementAst *node)
{
QString interfaceName = tokenValue(node->interfaceName);
UMLObject *o = UMLApp::app()->document()->findUMLObject(interfaceName, UMLObject::ot_Interface, m_currentNamespace[m_nsCnt]);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Interface, interfaceName,
m_currentNamespace[m_nsCnt],
QString()/*ast->comment()*/, QString(), true);
m_currentScope.push_back(interfaceName);
if (++m_nsCnt > NamespaceSize) {
logError0("PHPImportVisitor::visitInterfaceDeclarationStatement: excessive namespace nesting");
m_nsCnt = NamespaceSize;
}
UMLPackage *ns = o->asUMLPackage();
m_currentNamespace[m_nsCnt] = ns;
// handle modifier
DefaultVisitor::visitInterfaceDeclarationStatement(node);
--m_nsCnt;
m_currentScope.pop_back();
}
void visitClassDeclarationStatement(ClassDeclarationStatementAst *node)
{
_printToken(node->className, "IdentifierAst", "ClassDeclarationStatement");
QString className = tokenValue(node->className);
UMLObject *o = UMLApp::app()->document()->findUMLObject(className, UMLObject::ot_Class, m_currentNamespace[m_nsCnt]);
if (!o)
o = UMLApp::app()->document()->findUMLObject(className, UMLObject::ot_Datatype, m_currentNamespace[m_nsCnt]);
if (!o)
o = Import_Utils::createUMLObject(UMLObject::ot_Class, className,
m_currentNamespace[m_nsCnt],
QString()/*ast->comment()*/, QString(), true);
m_currentScope.push_back(className);
if (++m_nsCnt > NamespaceSize) {
logError0("PHPImportVisitor::visitClassDeclarationStatement: excessive namespace nesting");
m_nsCnt = NamespaceSize;
}
UMLPackage *ns = o->asUMLPackage();
m_currentNamespace[m_nsCnt] = ns;
// UMLClassifier *klass = o->asUMLClassifier();
// handle modifier, extents, implements
DefaultVisitor::visitClassDeclarationStatement(node);
--m_nsCnt;
m_currentScope.pop_back();
}
void visitFunctionDeclarationStatement(FunctionDeclarationStatementAst *node)
{
if (!node || !node->functionName)
return;
QString methodName = tokenValue(node->functionName);
Uml::Visibility::Enum m_currentAccess = Uml::Visibility::Public;
QString returnType = "auto";
bool isStatic = false;
bool isAbstract = false;
bool isFriend = false;
bool isConstructor = false;
bool isDestructor = false;
QString m_comment;
UMLPackage *parentPackage = m_currentNamespace[m_nsCnt];
UMLClassifier *c = parentPackage->asUMLClassifier();
UMLOperation *m = nullptr;
if (c) {
m = Import_Utils::makeOperation(c, methodName);
} else {
logError1("PHPImportVisitor::visitFunctionDeclarationStatement: no parent class found for method %1",
methodName);
}
if (m) {
if (node->parameters && node->parameters->parametersSequence) {
const KDevPG::ListNode<ParameterAst*> *__it = node->parameters->parametersSequence->front(), *__end = __it;
do {
QString type = "auto";
QString name = tokenValue(__it->element->variable).mid(1);
Import_Utils::addMethodParameter(m, type, name);
__it = __it->next;
} while (__it != __end);
}
Import_Utils::insertMethod(c, m, m_currentAccess, returnType,
isStatic, isAbstract, isFriend, isConstructor,
isDestructor, m_comment);
}
DefaultVisitor::visitFunctionDeclarationStatement(node);
}
void _printToken(AstNode *node, const QString &mType, const QString &mName = QString())
{
if (!node)
return;
QString tokenString;
if (!m_content.isEmpty())
{
TokenStream::Token startToken = m_str->at(node->startToken);
TokenStream::Token endToken = m_str->at(node->endToken);
int begin = startToken.begin;
int end = endToken.end;
if (end-begin > 30)
{
tokenString = m_content.mid(begin, 10);
tokenString += " ...";
tokenString += QStringLiteral("%1 more").arg(end-begin-20);
tokenString += "... ";
tokenString += m_content.mid(end-10, 10);
}
else
{
tokenString = m_content.mid(begin, end-begin+1);
}
tokenString = tokenString.replace('\n', "\\n");
tokenString = tokenString.replace('\r', "\\r");
}
qint64 beginLine,endLine,beginCol,endCol;
m_str->startPosition(node->startToken, &beginLine, &beginCol);
m_str->endPosition(node->endToken, &endLine, &endCol);
qDebug() << "++++" << QString().fill(' ', m_indent) + mName + (!mName.isEmpty() ? "->" : "") + mType + "[" << m_str->at( node->startToken ).begin << "," << beginLine << "," << beginCol << "] --- [" << m_str->at( node->endToken ).end << "," << endLine << "," << endCol << "] " << tokenString;
}
TokenStream *m_str;
QString m_content;
int m_indent;
QVector<QPointer<UMLPackage>> m_currentNamespace;
QList<QPointer<UMLClassifier>> m_usingClasses;
QStringList m_currentScope;
QString m_fileName;
int m_nsCnt;
};
} // namespace
/**
* Auxiliary type for template class @ref DebugLanguageParserHelper
*/
typedef QString (*TokenTextFunc)(int);
/**
* This class is a pure helper to use for binaries that you can
* run on short snippets of test code or whole files and let
* it print the generated tokens or AST.
*
* It should work fine for any KDevelop-PG-Qt based parser.
*
*
* @param SessionT the parse session for your language.
* @param TokenStreamT the token stream for your language, based on KDevPG::TokenStreamBase.
* @param TokenT the token class for your language, based on KDevPG::Token.
* @param LexerT the Lexer for your language.
* @param StartAstT the AST node that is returned from @c SessionT::parse().
* @param DebugVisitorT the debug visitor for your language.
* @param TokenToTextT function pointer to the function that returns a string representation for an integral token.
*/
template<class SessionT, class TokenStreamT, class TokenT, class LexerT,
class StartAstT, class DebugVisitorT, TokenTextFunc TokenTextT>
class DebugLanguageParserHelper {
public:
DebugLanguageParserHelper(const bool printAst, const bool printTokens)
: m_printAst(printAst),
m_printTokens(printTokens),
m_ast(0),
m_isFed(false)
{
m_session.setDebug(printAst);
}
/// parse contents of a file
bool parseFile( const QString &fileName )
{
if (!m_session.readFile(fileName, "utf-8")) {
qerr << "Can't open file " << fileName << endl;
std::exit(255);
} else {
qout << "Parsing file " << fileName << endl;
}
return runSession(fileName);
}
/// parse code directly
bool parseCode( const QString &code )
{
m_session.setContents(code);
qout << "Parsing input" << endl;
return runSession();
}
Php::TokenStream *tokenStream()
{
return m_session.tokenStream();
}
QString contents() const
{
return m_session.contents();
}
QStringList dependencies() const
{
return m_dependencies;
}
StartAstT *ast() const
{
return m_ast;
}
void setFed(bool state)
{
m_isFed = state;
}
bool wasFed()
{
return m_isFed;
}
private:
/**
* actually run the parse session
*/
bool runSession(const QString &fileName=QString())
{
bool result = true;
if (m_printTokens) {
TokenStreamT tokenStream;
LexerT lexer(&tokenStream, m_session.contents());
int token;
while ((token = lexer.nextTokenKind())) {
TokenT &t = tokenStream.push();
t.begin = lexer.tokenBegin();
t.end = lexer.tokenEnd();
t.kind = token;
printToken(token, lexer);
}
printToken(token, lexer);
if ( tokenStream.size() > 0 ) {
qint64 line;
qint64 column;
tokenStream.endPosition(tokenStream.size() - 1, &line, &column);
qDebug() << "last token endPosition: line" << line << "column" << column;
} else {
qDebug() << "empty token stream";
}
}
m_ast = 0;
if (!m_session.parse(&m_ast)) {
qerr << "no AST tree could be generated" << QLatin1Char('\n');
result = false;
} else {
qout << "AST tree successfully generated" << QLatin1Char('\n');
if (m_printAst) {
DebugVisitorT debugVisitor(m_session.tokenStream(), m_session.contents());
debugVisitor.visitStart(m_ast);
}
Php::PHPIncludeFileVisitor includeFileVisitor(m_session.tokenStream(), m_session.contents());
Php::VariableMapping map;
QString filePath = QFileInfo(fileName).canonicalPath();
map["afw_root"] = filePath;
includeFileVisitor.setFilePath(filePath);
includeFileVisitor.setDependencies(m_dependencies);
includeFileVisitor.setVariableMapping(map);
includeFileVisitor.visitStart(m_ast);
}
if (!m_session.problems().isEmpty()) {
qout << QLatin1Char('\n') << "problems encountered during parsing:" << QLatin1Char('\n');
for(KDevelop::ProblemPointer p: m_session.problems()) {
QString item = QString::fromLatin1("%1:%2:%3: %4: %5")
.arg(fileName).arg(p->finalLocation().start().line()+1)
.arg(p->finalLocation().start().column())
.arg(p->severityString()).arg(p->description());
UMLApp::app()->log(item);
}
} else {
qout << "no problems encountered during parsing" << QLatin1Char('\n');
}
return result;
}
void printToken(int token, const LexerT& lexer) const
{
int begin = lexer.tokenBegin();
int end = lexer.tokenEnd();
qout << m_session.contents().mid(begin, end - begin + 1).replace('\n', "\\n")
<< ' ' << TokenTextT(token) << endl;
}
SessionT m_session;
const bool m_printAst;
const bool m_printTokens;
StartAstT* m_ast;
QStringList m_dependencies;
bool m_isFed;
};
typedef DebugLanguageParserHelper<Php::ParseSession, Php::TokenStream, Php::Parser::Token, Php::Lexer, Php::StartAst, Php::DebugVisitor, Php::tokenText> PhpParser;
class PHPImportPrivate {
public:
PHPImportPrivate()
: m_printAst(false),
m_printTokens(false)
{
KDevelop::AutoTestShell::init();
KDevelop::TestCore::initialize(KDevelop::Core::NoUi);
KDevelop::DUChain::self()->disablePersistentStorage();
KDevelop::CodeRepresentation::setDiskChangesForbidden(true);
}
~PHPImportPrivate()
{
qDeleteAll(m_parsers);
m_parsers.clear();
KDevelop::TestCore::shutdown();
}
bool parseFile(const QStringList &files)
{
for(const QString &fileName: files) {
PhpParser *parser = new PhpParser(m_printAst, m_printTokens);
QFileInfo fi(fileName);
parser->parseFile(fi.canonicalFilePath());
m_parsers[fi.canonicalFilePath()] = parser;
for(const QString dependency: parser->dependencies()) {
QFileInfo di(dependency);
QFileInfo ei(di.isAbsolute() ? dependency : fi.canonicalPath() + "/" + dependency);
QString usePath = ei.canonicalFilePath();
if (usePath.isEmpty()) {
logError1("PHPImportPrivate::parseFile could not parse empty file path for dependency %1",
dependency);
continue;
}
if (!m_parsers.contains(usePath)) {
PhpParser *parser = new PhpParser(m_printAst, m_printTokens);
parser->parseFile(usePath);
m_parsers[usePath] = parser;
}
}
}
qDebug() << m_parsers.size();
//qDebug() << m_parsers;
return true;
}
QStringList getParsedFiles(const QString &fileName)
{
QStringList files;
QFileInfo fi(fileName);
QString f = fi.canonicalFilePath();
if (!m_parsers.contains(f))
return files;
files.append(f);
for(const QString dependency: m_parsers[f]->dependencies()) {
QFileInfo di(dependency);
QFileInfo ei(di.isAbsolute() ? dependency : fi.canonicalPath() + "/" + dependency);
QString path = ei.canonicalFilePath();
if (m_parsers.contains(path))
files.append(path);
}
return files;
}
bool m_printAst;
bool m_printTokens;
QMap<QString, PhpParser*> m_parsers;
};
/**
* Constructor.
*/
PHPImport::PHPImport(CodeImpThread* thread)
: ClassImport(thread),
m_d(new PHPImportPrivate)
{
}
/**
* Destructor.
*/
PHPImport::~PHPImport()
{
delete m_d;
}
/**
* Auxiliary method for recursively traversing the \#include dependencies
* in order to feed innermost includes to the model before dependent
* includes. It is important that includefiles are fed to the model
* in proper order so that references between UML objects are created
* properly.
* @param fileName the file to import
*/
void PHPImport::feedTheModel(const QString& fileName)
{
for(const QString &file: m_d->getParsedFiles(fileName)) {
PhpParser *p = m_d->m_parsers[file];
Php::PHPImportVisitor visitor(p->tokenStream(), p->contents());
visitor.setFileName(file);
if (p->ast() && !p->wasFed()) {
logDebug1("feeding %1", file);
visitor.visitStart(p->ast());
p->setFed(true);
}
}
}
/**
* Implement abstract operation from ClassImport for PHP
*/
void PHPImport::initialize()
{
}
/**
* Implement abstract operation from ClassImport for PHP
*/
void PHPImport::initPerFile()
{
}
/**
* Import a single file.
* @param fileName The file to import.
*/
bool PHPImport::parseFile(const QString& fileName)
{
bool result = false;
QFileInfo fi(fileName);
QString f = fi.canonicalFilePath();
if (!m_d->m_parsers.contains(f))
result = m_d->parseFile(QStringList() << f);
if (!result)
return false;
feedTheModel(f);
return true;
}
| 28,599
|
C++
|
.cpp
| 744
| 29.008065
| 299
| 0.592442
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,595
|
import_utils.cpp
|
KDE_umbrello/umbrello/codeimport/import_utils.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "import_utils.h"
// app includes
#include "association.h"
#include "artifact.h"
#include "classifier.h"
#include "datatype.h"
#define DBG_SRC QStringLiteral("Import_Utils")
#include "debug_utils.h"
#include "folder.h"
#include "enum.h"
#include "object_factory.h"
#include "operation.h"
#include "package.h"
#include "template.h"
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "umlobject.h"
// kde includes
#include <KMessageBox>
#include <KLocalizedString>
// qt includes
#include <QtGlobal>
#ifdef Q_OS_WIN
#define PATH_SEPARATOR QLatin1Char(';')
#else
#define PATH_SEPARATOR QLatin1Char(':')
#endif
DEBUG_REGISTER_DISABLED(Import_Utils)
namespace Import_Utils {
/**
* Flag manipulated by createUMLObject().
* Global state is generally bad, I know.
* It would be cleaner to make this into a return value from
* createUMLObject().
*/
bool bNewUMLObjectWasCreated = false;
/**
* Related classifier for creation of dependencies on template
* parameters in createUMLObject().
*/
UMLClassifier *gRelatedClassifier = nullptr;
/**
* On encountering a scoped typename string where the scopes
* have not yet been seen, we synthesize UML objects for the
* unknown scopes (using a question dialog to the user to decide
* whether to treat a scope as a class or as a package.)
* However, such an unknown scope is put at the global level.
* I.e. before calling createUMLObject() we set this flag to true.
*/
bool bPutAtGlobalScope = false;
/**
* The include path list (see addIncludePath() and includePathList())
*/
QStringList incPathList;
/**
* Control whether an object which is newly created by createUMLObject()
* is put at the global scope.
*
* @param yesno When set to false, the object is created at the scope
* given by the parentPkg argument of createUMLObject().
*/
void putAtGlobalScope(bool yesno)
{
bPutAtGlobalScope = yesno;
}
/**
* Set a related classifier for creation of dependencies on template
* parameters in createUMLObject().
*/
void setRelatedClassifier(UMLClassifier *c)
{
gRelatedClassifier = c;
}
/**
* Control whether the creation methods solicit a new unique ID for the
* created object.
* By default, unique ID generation is turned on.
*
* @param yesno False turns UID generation off, true turns it on.
*/
void assignUniqueIdOnCreation(bool yesno)
{
Object_Factory::assignUniqueIdOnCreation(yesno);
}
/**
* Returns whether the last createUMLObject() actually created
* a new object or just returned an existing one.
*/
bool newUMLObjectWasCreated()
{
return bNewUMLObjectWasCreated;
}
/**
* Strip comment lines of leading whitespace and stars.
*/
QString formatComment(const QString &comment)
{
if (comment.isEmpty())
return comment;
QStringList lines = comment.split(QLatin1Char('\n'));
QString& first = lines.first();
QRegularExpression wordex(QStringLiteral("\\w"));
if (first.startsWith(QStringLiteral("/*"))) {
QRegularExpressionMatch match = wordex.match(first);
if (match.hasMatch())
first = first.mid(match.capturedStart()); // remove comment start
else
lines.pop_front(); // nothing interesting on this line
}
if (! lines.count())
return QString();
QString& last = lines.last();
int endpos = last.indexOf(QStringLiteral("*/"));
if (endpos != -1) {
if (last.contains(wordex))
last = last.mid(0, endpos - 1); // remove comment end
else
lines.pop_back(); // nothing interesting on this line
}
if (! lines.count())
return QString();
QStringList::Iterator end(lines.end());
for (QStringList::Iterator lit(lines.begin()); lit != end; ++lit) {
(*lit).remove(QRegularExpression(QStringLiteral("^\\s+")));
(*lit).remove(QRegularExpression(QStringLiteral("^\\*+\\s?")));
}
return lines.join(QStringLiteral("\n"));
}
/**
* Peculiarity of Umbrello: std::string must be mapped to "string" because
* that is the predefined type in the Datatypes folder, and if we leave
* std::string as it is then there will be a second type "string" in the
* package "std" generated by the import.
* Having two types "string" would create confusion for the user and would
* not fit with the C++ code generator which generates "std::string" from
* the "string" of the Datatypes folder.
*
* @param typeName Writable reference to QString variable: If content is
* "std::string" then it will be changed to "string".
*/
void checkStdString(QString& typeName)
{
if (typeName == QStringLiteral("std::string"))
typeName = QStringLiteral("string");
}
/**
* Find or create a document object.
* @param type object type
* @param inName name of uml object
* @param parentPkg parent package
* @param comment comment for uml object
* @param stereotype stereotype for uml object
* @param searchInParentPackageOnly flags to search only in parent package
* @param remapParent flag to control remapping of parents if a uml object has been found
* @return new object or zero
*/
UMLObject *createUMLObject(UMLObject::ObjectType type,
const QString& inName,
UMLPackage *parentPkg,
const QString& comment,
const QString& stereotype,
bool searchInParentPackageOnly,
bool remapParent)
{
QString name = inName;
UMLDoc *umldoc = UMLApp::app()->document();
UMLFolder *logicalView = umldoc->rootFolder(Uml::ModelType::Logical);
if (parentPkg == nullptr) {
// logDebug1("Import_Utils::createUMLObject(%1): parentPkg is 0, assuming Logical View", name);
parentPkg = logicalView;
} else if (parentPkg->baseType() == UMLObject::ot_Artifact) {
logDebug1("Import_Utils::createUMLObject(%1): Artifact as parent package is not supported yet, "
"using Logical View", name);
parentPkg = logicalView;
} else if (parentPkg->baseType() == UMLObject::ot_Association) {
#ifdef QT_NO_DEBUG
logError1("Import_Utils::createUMLObject(%1) grave error: "
"Attempt to use Association as parent package", name);
#else
qFatal("Import_Utils::createUMLObject(%s): Attempt to use Association as parent package",
qPrintable(name));
#endif
parentPkg = logicalView;
} else if (name.startsWith(QStringLiteral("::"))) {
name = name.mid(2);
parentPkg = logicalView;
} else if (UMLApp::app()->activeLanguage() == Uml::ProgrammingLanguage::Ada &&
name.startsWith(QStringLiteral("Standard."), Qt::CaseInsensitive)) {
name = name.mid(9);
parentPkg = logicalView;
}
checkStdString(name);
bNewUMLObjectWasCreated = false;
UMLObject *o = nullptr;
if (searchInParentPackageOnly) {
o = Model_Utils::findUMLObject(parentPkg->containedObjects(), name, type);
if (!o) {
o = Object_Factory::createNewUMLObject(type, name, parentPkg);
bNewUMLObjectWasCreated = true;
bPutAtGlobalScope = false;
}
} else {
o = umldoc->findUMLObject(name, type, parentPkg);
}
if (o == nullptr) {
// Strip possible adornments and look again.
bool isConst = false;
if (name.contains(QRegularExpression(QStringLiteral("^const ")))) {
name.remove(QRegularExpression(QStringLiteral("^const\\s+")));
isConst = true;
}
if (name.contains(QRegularExpression(QStringLiteral("\\bconst\\b")))) {
// Here, we lose info of the exact placement of the `const` qualifier.
// I argue that we are looking at a level of C++ detail that UML was not
// designed for. Feel free to disagree and implement this :)
name.remove(QRegularExpression(QStringLiteral("\\s+const\\b")));
name.remove(QRegularExpression(QStringLiteral("\\bconst\\s+")));
isConst = true;
}
const bool isVolatile = name.contains(QRegularExpression(QStringLiteral("^volatile ")));
name.remove(QRegularExpression(QStringLiteral("^volatile\\s+")));
const bool isMutable = name.contains(QRegularExpression(QStringLiteral("^mutable ")));
name.remove(QRegularExpression(QStringLiteral("^mutable\\s+")));
QString typeName(name);
bool isAdorned = typeName.contains(QRegularExpression(QStringLiteral("[^\\w:\\. ]")));
const bool isPointer = typeName.contains(QLatin1Char('*'));
const bool isRef = typeName.contains(QLatin1Char('&'));
typeName.remove(QRegularExpression(QStringLiteral("[^\\w:\\. ].*$")));
typeName = typeName.simplified();
checkStdString(typeName);
UMLObject *origType = umldoc->findUMLObject(typeName, UMLObject::ot_UMLObject, parentPkg);
if (origType == nullptr) {
// Still not found. Create the stripped down type.
if (bPutAtGlobalScope)
parentPkg = logicalView;
// Find, or create, the scopes.
QStringList components;
QString scopeSeparator = UMLApp::app()->activeLanguageScopeSeparator();
if (typeName.contains(scopeSeparator)) {
components = typeName.split(scopeSeparator, QString::SkipEmptyParts);
} else if (typeName.contains(QStringLiteral("..."))) {
// Java variable length arguments
type = UMLObject::ot_Datatype;
parentPkg = umldoc->datatypeFolder();
isAdorned = false;
}
const bool isScopedName = (components.count() > 1);
if (isScopedName) {
typeName = components.back();
components.pop_back(); // remove the type name leaving only its scope path
while (components.count()) {
QString scopeName = components.front();
components.pop_front();
o = umldoc->findUMLObject(scopeName, UMLObject::ot_UMLObject, parentPkg);
if (o) {
parentPkg = o->asUMLPackage();
continue;
}
o = Object_Factory::createUMLObject(UMLObject::ot_Class, scopeName, parentPkg);
o->setStereotypeCmd(QStringLiteral("class-or-package"));
// setStereotypeCmd() triggers tree view item update if not loading by default
if (umldoc->loading()) {
UMLListViewItem *item = UMLApp::app()->listView()->findUMLObject(o);
if (item)
item->updateObject();
}
parentPkg = o->asUMLPackage();
Model_Utils::treeViewSetCurrentItem(o);
}
// All scope qualified datatypes live in the global scope.
bPutAtGlobalScope = true;
}
UMLObject::ObjectType t = type;
if (type == UMLObject::ot_UMLObject)
t = UMLObject::ot_Class;
origType = Object_Factory::createUMLObject(t, typeName, parentPkg, false);
bNewUMLObjectWasCreated = true;
bPutAtGlobalScope = false;
}
if (isConst || isAdorned || isMutable || isVolatile) {
// Create the full given type (including adornments.)
if (isVolatile)
name.prepend(QStringLiteral("volatile "));
if (isMutable)
name.prepend(QStringLiteral("mutable "));
if (isConst)
name.prepend(QStringLiteral("const "));
o = Object_Factory::createUMLObject(UMLObject::ot_Datatype, name,
umldoc->datatypeFolder(),
false); //solicitNewName
UMLDatatype *dt = o ? o->asUMLDatatype() : nullptr;
UMLClassifier *c = origType->asUMLClassifier();
if (dt && c)
dt->setOriginType(c);
else
logError2("Import_Utils::createUMLObject(%1): origType %2 is not a UMLClassifier", name, typeName);
if (dt && (isRef || isPointer))
dt->setIsReference();
/*
if (isPointer) {
UMLObject *pointerDecl = Object_Factory::createUMLObject(UMLObject::ot_Datatype, type);
UMLClassifier *dt = pointerDecl->asUMLClassifier();
dt->setOriginType(classifier);
dt->setIsReference();
classifier = dt;
} */
} else {
o = origType;
}
} else if (parentPkg && !bPutAtGlobalScope && remapParent) {
UMLPackage *existingPkg = o->umlPackage();
if (existingPkg != parentPkg && existingPkg != umldoc->datatypeFolder()) {
if (existingPkg)
existingPkg->removeObject(o);
else
logError1("Import_Utils::createUMLObject(%1): o->getUMLPackage() was NULL", name);
parentPkg->addObject(o);
o->setUMLPackage(parentPkg);
// setUMLPackage() triggers tree view item update if not loading by default
if (umldoc->loading()) {
UMLListViewItem *item = UMLApp::app()->listView()->findUMLObject(o);
if (item)
item->updateObject();
}
}
}
QString strippedComment = formatComment(comment);
if (! strippedComment.isEmpty()) {
o->setDoc(strippedComment);
}
if (o && !stereotype.isEmpty()) {
o->setStereotype(stereotype);
}
if (gRelatedClassifier == nullptr || gRelatedClassifier == o)
return o;
QRegularExpression templateInstantiation(QStringLiteral("^[\\w:\\.]+\\s*<(.*)>"));
QRegularExpressionMatch match = templateInstantiation.match(name);
if (!match.hasMatch())
return o;
// Create dependencies on template parameters.
QString caption = match.captured();
const QStringList params = caption.split(QRegularExpression(QStringLiteral("[^\\w:\\.]+")));
if (!params.count())
return o;
QStringList::ConstIterator end(params.end());
for (QStringList::ConstIterator it(params.begin()); it != end; ++it) {
UMLObject *p = umldoc->findUMLObject(*it, UMLObject::ot_UMLObject, parentPkg);
if (p == nullptr || p->isUMLDatatype())
continue;
const Uml::AssociationType::Enum at = Uml::AssociationType::Dependency;
UMLAssociation *assoc = umldoc->findAssociation(at, gRelatedClassifier, p);
if (assoc)
continue;
assoc = new UMLAssociation(at, gRelatedClassifier, p);
assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical));
umldoc->addAssociation(assoc);
}
if (o == nullptr) {
logError1("Import_Utils::createUMLObject(%1) : operation failed", inName);
}
return o;
}
/**
* Create hierarchical tree of UML objects
*
* This method creates the UML object specified by @p type and @p name including an optional namespace hierarchy
* if included in the @p name e.g. NamespaceA::ClassA in C++.
*
* @param type type of UML object to create
* @param name name of UML object
* @param topLevelParent UML package to add the hierarchy of UML objects
* @return pointer to created or found UML object
*/
UMLObject* createUMLObjectHierarchy(UMLObject::ObjectType type, const QString &name, UMLPackage *topLevelParent)
{
UMLPackage *parent = topLevelParent;
QString objectName;
QString scopeSeparator = UMLApp::app()->activeLanguageScopeSeparator();
UMLObject *o = nullptr;
if (name.contains(scopeSeparator)) {
QStringList components = name.split(scopeSeparator);
objectName = components.takeLast();
for(const QString scopeName : components) {
o = parent->findObject(scopeName);
if (o && (o->isUMLPackage() || o->isUMLClassifier())) {
parent = o->asUMLPackage();
continue;
}
o = Object_Factory::createNewUMLObject(UMLObject::ot_Class, scopeName, parent, false);
parent->addObject(o);
o->setStereotypeCmd(QStringLiteral("class-or-package"));
parent = o->asUMLPackage();
}
} else {
objectName = name;
}
o = parent->findObject(objectName);
if (o && (o->isUMLPackage() || o->isUMLClassifier()))
return o;
o = Object_Factory::createNewUMLObject(type, objectName, parent);
parent->addObject(o);
return o;
}
/**
* Create a UMLOperation.
* The reason for this method is to not generate any Qt signals.
* Instead, these are generated by insertMethod().
* (If we generated a creation signal prematurely, i.e. without
* the method parameters being known yet, then that would lead to
* a conflict with a pre-existing parameterless method of the same
* name.)
*/
UMLOperation* makeOperation(UMLClassifier *parent, const QString &name)
{
UMLOperation *op = Object_Factory::createOperation(parent, name);
return op;
}
/**
* Create a UMLAttribute and insert it into the document.
* Use the specified existing attrType.
*/
UMLAttribute* insertAttribute(UMLClassifier *owner,
Uml::Visibility::Enum scope,
const QString& name,
UMLClassifier *attrType,
const QString& comment /* =QString() */,
bool isStatic /* =false */)
{
UMLObject::ObjectType ot = owner->baseType();
Uml::ProgrammingLanguage::Enum pl = UMLApp::app()->activeLanguage();
if (! (ot == UMLObject::ot_Class ||
(ot == UMLObject::ot_Interface && pl == Uml::ProgrammingLanguage::Java))) {
logDebug2("Import_Utils::insertAttribute: Don't know what to do with %1 (object type %2)",
owner->name(), UMLObject::toString(ot));
return nullptr;
}
UMLObject *o = owner->findChildObject(name, UMLObject::ot_Attribute);
if (o) {
return o->asUMLAttribute();
}
UMLAttribute *attr = owner->addAttribute(name, attrType, scope);
attr->setStatic(isStatic);
QString strippedComment = formatComment(comment);
if (! strippedComment.isEmpty()) {
attr->setDoc(strippedComment);
}
UMLApp::app()->document()->setModified(true);
return attr;
}
/**
* Create a UMLAttribute and insert it into the document.
*/
UMLAttribute *insertAttribute(UMLClassifier *owner, Uml::Visibility::Enum scope,
const QString& name,
const QString& type,
const QString& comment /* =QString() */,
bool isStatic /* =false */)
{
UMLObject *attrType = owner->findTemplate(type);
if (attrType == nullptr) {
bPutAtGlobalScope = true;
gRelatedClassifier = owner;
attrType = createUMLObject(UMLObject::ot_UMLObject, type, owner);
gRelatedClassifier = nullptr;
bPutAtGlobalScope = false;
}
return insertAttribute (owner, scope, name,
attrType->asUMLClassifier(),
comment, isStatic);
}
/**
* Insert the UMLOperation into the given classifier.
*
* @param klass The classifier into which the operation shall be added.
* @param op Reference to pointer to the temporary UMLOperation
* for insertion. The caller relinquishes ownership of the
* object pointed to. If a UMLOperation of same signature
* already exists at the classifier then the incoming
* UMLOperation is deleted and the pointer is set to the
* existing UMLOperation.
* @param scope The Uml::Visibility of the method
* @param type The return type
* @param isStatic boolean switch to decide if method is static
* @param isAbstract boolean switch to decide if method is abstract
* @param isFriend true boolean switch to decide if methods is a friend function
* @param isConstructor boolean switch to decide if methods is a constructor
* @param isDestructor boolean switch to decide if methods is a destructor
* @param comment The Documentation for this method
*/
void insertMethod(UMLClassifier *klass, UMLOperation* &op,
Uml::Visibility::Enum scope, const QString& type,
bool isStatic, bool isAbstract,
bool isFriend, bool isConstructor,
bool isDestructor, const QString& comment)
{
op->setVisibilityCmd(scope);
if (!type.isEmpty() // return type may be missing (constructor/destructor)
&& type != QStringLiteral("void")) {
if (type == klass->name()) {
op->setType(klass);
} else {
UMLObject *typeObj = klass->findTemplate(type);
if (typeObj == nullptr) {
bPutAtGlobalScope = true;
gRelatedClassifier = klass;
typeObj = createUMLObject(UMLObject::ot_UMLObject, type, klass);
gRelatedClassifier = nullptr;
bPutAtGlobalScope = false;
op->setType(typeObj);
}
}
}
op->setStatic(isStatic);
op->setAbstract(isAbstract);
// if the operation is friend, add it as a stereotype
if (isFriend)
op->setStereotype(QStringLiteral("friend"));
// if the operation is a constructor, add it as a stereotype
if (isConstructor)
op->setStereotype(QStringLiteral("constructor"));
if (isDestructor)
op->setStereotype(QStringLiteral("destructor"));
QString strippedComment = formatComment(comment);
if (! strippedComment.isEmpty()) {
op->setDoc(strippedComment);
}
UMLAttributeList params = op->getParmList();
UMLOperation *exist = klass->checkOperationSignature(op->name(), params);
if (exist) {
// copy contents to existing operation
exist->setVisibilityCmd(scope);
exist->setStatic(isStatic);
exist->setAbstract(isAbstract);
if (! strippedComment.isEmpty())
exist->setDoc(strippedComment);
UMLAttributeList exParams = exist->getParmList();
for (UMLAttributeListIt it(params), exIt(exParams) ; it.hasNext() ;) {
UMLAttribute *param = it.next(), *exParam = exIt.next();
exParam->setName(param->name());
exParam->setVisibilityCmd(param->visibility());
exParam->setStatic(param->isStatic());
exParam->setAbstract(param->isAbstract());
exParam->setDoc(param->doc());
exParam->setInitialValue(param->getInitialValue());
exParam->setParmKind(param->getParmKind());
}
// delete incoming UMLOperation and pass out the existing one
delete op;
op = exist;
} else {
klass->addOperation(op);
}
}
/**
* Add an argument to a UMLOperation.
*/
UMLAttribute* addMethodParameter(UMLOperation *method,
const QString& type,
const QString& name)
{
UMLClassifier *owner = method->umlParent()->asUMLClassifier();
UMLObject *typeObj = owner ? owner->findTemplate(type) : nullptr;
if (typeObj == nullptr) {
bPutAtGlobalScope = true;
gRelatedClassifier = owner;
typeObj = createUMLObject(UMLObject::ot_UMLObject, type, owner);
gRelatedClassifier = nullptr;
bPutAtGlobalScope = false;
}
UMLAttribute *attr = Object_Factory::createAttribute(method, name, typeObj);
method->addParm(attr);
return attr;
}
/**
* Add an enum literal to a UMLEnum.
*/
void addEnumLiteral(UMLEnum *enumType, const QString &literal, const QString &comment, const QString &value)
{
UMLObject *el = enumType->addEnumLiteral(literal, Uml::ID::None, value);
el->setDoc(comment);
}
/**
* Create a generalization from the given child classifier to the given
* parent classifier.
*/
UMLAssociation *createGeneralization(UMLClassifier *child, UMLClassifier *parent)
{
// if the child is an interface, so is the parent.
if (child->isInterface())
parent->setBaseType(UMLObject::ot_Interface);
Uml::AssociationType::Enum association = Uml::AssociationType::Generalization;
if (parent->isInterface() && !child->isInterface()) {
// if the parent is an interface, but the child is not, then
// this is really realization.
//
association = Uml::AssociationType::Realization;
}
UMLAssociation *assoc = new UMLAssociation(association, child, parent);
if (child->umlPackage()) {
assoc->setUMLPackage(child->umlPackage());
child->addAssociationEnd(assoc);
} else {
logDebug2("Import_Utils::createGeneralization(child %1, parent %2) : "
"Package is not set on child", child->name(), parent->name());
UMLDoc *umldoc = UMLApp::app()->document();
UMLPackage *owningPackage = umldoc->rootFolder(Uml::ModelType::Logical);
assoc->setUMLPackage(owningPackage);
umldoc->addAssociation(assoc);
}
return assoc;
}
/**
* Create a subdir with the given name.
*/
UMLFolder *createSubDir(const QString& name,
UMLFolder *parentPkg,
const QString &comment)
{
UMLDoc *umldoc = UMLApp::app()->document();
if (!parentPkg) {
parentPkg = umldoc->rootFolder(Uml::ModelType::Component);
}
UMLObject::ObjectType type = UMLObject::ot_Folder;
UMLFolder *o = umldoc->findUMLObjectRaw(parentPkg, name, type)->asUMLFolder();
if (o)
return o;
o = Object_Factory::createUMLObject(type, name, parentPkg, false)->asUMLFolder();
if (o)
o->setDoc(comment);
return o;
}
/**
* Create a folder for artifacts
*/
UMLObject *createArtifactFolder(const QString& name,
UMLPackage *parentPkg,
const QString &comment)
{
Q_UNUSED(parentPkg);
UMLObject::ObjectType type = UMLObject::ot_Folder;
UMLDoc *umldoc = UMLApp::app()->document();
UMLFolder *componentView = umldoc->rootFolder(Uml::ModelType::Component);
UMLObject *o = umldoc->findUMLObjectRaw(componentView, name, type);
if (o)
return o;
o = Object_Factory::createUMLObject(type, name, componentView, false);
UMLFolder *a = o->asUMLFolder();
a->setDoc(comment);
logDebug2("Import_Utils::createArtifactFolder %1 %2", name, comment);
return o;
}
/**
* Create an artifact with the given name.
*/
UMLObject *createArtifact(const QString& name,
UMLFolder *parentPkg,
const QString &comment)
{
UMLDoc *umldoc = UMLApp::app()->document();
if (!parentPkg) {
parentPkg = umldoc->rootFolder(Uml::ModelType::Component);
}
UMLObject::ObjectType type = UMLObject::ot_Artifact;
UMLObject *o = umldoc->findUMLObjectRaw(parentPkg, name, type);
if (o)
return o;
o = Object_Factory::createUMLObject(type, name, parentPkg, false);
UMLArtifact *a = o->asUMLArtifact();
a->setDrawAsType(UMLArtifact::file);
a->setDoc(comment);
logDebug2("Import_Utils::createArtifact %1 %2", name, comment);
return o;
}
/**
* Create a generalization from the existing child UMLObject to the given
* parent class name.
* This method does not handle scopes well and is only a last resort.
* The method
* createGeneralization(UMLClassifier *child, UMLClassifier *parent)
* should be used instead.
*/
void createGeneralization(UMLClassifier *child, const QString &parentName)
{
const QString& scopeSep = UMLApp::app()->activeLanguageScopeSeparator();
UMLObject *parentObj = nullptr;
if (parentName.contains(scopeSep)) {
QStringList split = parentName.split(scopeSep);
QString className = split.last();
split.pop_back(); // remove the classname
UMLPackage *parent = nullptr;
UMLPackage *current = nullptr;
for (QStringList::Iterator it = split.begin(); it != split.end(); ++it) {
QString name = (*it);
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
name, parent,
QString(), QString(),
true, false);
current = ns->asUMLPackage();
parent = current;
}
UMLObject::ObjectType type = UMLObject::ot_Class;
if (child->baseType() == UMLObject::ot_Interface)
type = UMLObject::ot_Interface;
parentObj = Import_Utils::createUMLObject(type, className, parent,
QString(), QString(), true, false);
} else {
parentObj = createUMLObject(UMLObject::ot_Class, parentName);
}
UMLClassifier *parent = parentObj->asUMLClassifier();
createGeneralization(child, parent);
}
/**
* Remap UMLObject instance in case it does not have the correct type.
*
* @param ns uml object instance with incorrect class
* @param currentScope parent uml object
* @return newly created UMLEnum instance or zero in case of error
*/
UMLEnum *remapUMLEnum(UMLObject *ns, UMLPackage *currentScope)
{
if (ns == nullptr) {
return nullptr;
}
QString comment = ns->doc();
QString name = ns->name();
QString stereotype = ns->stereotype();
Uml::Visibility::Enum visibility = ns->visibility();
UMLApp::app()->document()->removeUMLObject(ns, true);
if (currentScope == nullptr)
currentScope = UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical);
UMLObject *o = Object_Factory::createNewUMLObject(UMLObject::ot_Enum, name, currentScope, false);
if (!o) {
logDebug1("Import_Utils::remapUMLEnum(%1) : Object_Factory::createNewUMLObject(ot_Enum) returns null",
name);
return nullptr;
}
UMLEnum *e = o->asUMLEnum();
if (!e) {
logDebug1("Import_Utils::remapUMLEnum(%1) : object returned by Object_Factory::createNewUMLObject "
"is not Enum", name);
return nullptr;
}
e->setDoc(comment);
e->setStereotypeCmd(stereotype.isEmpty() ? QStringLiteral("enum") : stereotype);
e->setVisibilityCmd(visibility);
// add to parents child list
if (currentScope->addObject(e, false)) // false => non interactively
return e;
logDebug2("Import_Utils::remapUMLEnum(%1) : name is already present in %2", name, currentScope->name());
return nullptr;
}
/**
* Return the list of paths set by previous calls to addIncludePath()
* and the environment variable UMBRELLO_INCPATH.
* This list can be used for finding included (or Ada with'ed or...)
* files.
*/
QStringList includePathList()
{
QStringList includePathList(incPathList);
QString umbrello_incpath = QString::fromLatin1(qgetenv("UMBRELLO_INCPATH"));
if (!umbrello_incpath.isEmpty()) {
includePathList += umbrello_incpath.split(PATH_SEPARATOR);
}
return includePathList;
}
/**
* Add a path to the include path list.
*/
void addIncludePath(const QString& path)
{
if (! incPathList.contains(path))
incPathList.append(path);
}
/**
* Returns true if a type is an actual Datatype
*/
bool isDatatype(const QString& name, UMLPackage *parentPkg)
{
UMLDoc *umldoc = UMLApp::app()->document();
UMLObject * o = umldoc->findUMLObject(name, UMLObject::ot_Datatype, parentPkg);
return (o != nullptr);
}
/**
* Returns the UML package of the global scope.
*/
UMLPackage *globalScope()
{
UMLFolder *logicalView = UMLApp::app()->document()->rootFolder(Uml::ModelType::Logical);
return logicalView;
}
} // end namespace Import_Utils
| 32,387
|
C++
|
.cpp
| 798
| 32.947368
| 115
| 0.635095
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,596
|
adaimport.cpp
|
KDE_umbrello/umbrello/codeimport/adaimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "adaimport.h"
// app includes
#include "association.h"
#include "attribute.h"
#include "classifier.h"
#define DBG_SRC QStringLiteral("AdaImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
// qt includes
#include <QRegularExpression>
DEBUG_REGISTER(AdaImport)
/**
* Constructor.
*/
AdaImport::AdaImport(CodeImpThread* thread)
: NativeImportBase(QStringLiteral("--"), thread)
{
initVars();
}
/**
* Destructor.
*/
AdaImport::~AdaImport()
{
}
/**
* Reimplement operation from NativeImportBase.
*/
void AdaImport::initVars()
{
m_inGenericFormalPart = false;
m_classesDefinedInThisScope.clear();
m_renaming.clear();
}
/**
* Split the line so that a string is returned as a single element of the list.
* When not in a string then split at white space.
* Reimplementation of method from NativeImportBase is required because of
* Ada's tic which is liable to be confused with the beginning of a character
* constant.
*/
QStringList AdaImport::split(const QString& lin)
{
QStringList list;
QString listElement;
bool inString = false;
bool seenSpace = false;
QString line = lin.trimmed();
uint len = line.length();
for (uint i = 0; i < len; ++i) {
const QChar& c = line[i];
if (inString) {
listElement += c;
if (c == QLatin1Char('"')) {
if (i < len - 1 && line[i + 1] == QLatin1Char('"')) {
i++; // escaped quotation mark
continue;
}
list.append(listElement);
listElement.clear();
inString = false;
}
} else if (c == QLatin1Char('"')) {
inString = true;
if (!listElement.isEmpty())
list.append(listElement);
listElement = QString(c);
seenSpace = false;
} else if (c == QLatin1Char('\'')) {
if (i < len - 2 && line[i + 2] == QLatin1Char('\'')) {
// character constant
if (!listElement.isEmpty())
list.append(listElement);
listElement = line.mid(i, 3);
i += 2;
list.append(listElement);
listElement.clear();
continue;
}
listElement += c;
seenSpace = false;
} else if (c.isSpace()) {
if (seenSpace)
continue;
seenSpace = true;
if (!listElement.isEmpty()) {
list.append(listElement);
listElement.clear();
}
} else {
listElement += c;
seenSpace = false;
}
}
if (!listElement.isEmpty())
list.append(listElement);
return list;
}
/**
* Implement abstract operation from NativeImportBase.
*/
void AdaImport::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
for (uint i = 0; i < len; ++i) {
QChar c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_')
|| c == QLatin1Char('.') || c == QLatin1Char('#')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
lexeme.clear();
}
if (c == QLatin1Char(':') && i < len - 1 && word[i + 1] == QLatin1Char('=')) {
m_source.append(QStringLiteral(":="));
i++;
} else {
m_source.append(QString(c));
}
}
}
if (!lexeme.isEmpty())
m_source.append(lexeme);
}
/**
* Apply package renamings to the given name.
* @return expanded name
*/
QString AdaImport::expand(const QString& name)
{
QRegularExpression pfxRegExp(QStringLiteral("^(\\w+)\\."));
pfxRegExp.setPatternOptions(QRegularExpression::PatternOption::CaseInsensitiveOption);
QRegularExpressionMatch match = pfxRegExp.match(name);
if (!match.hasMatch()) {
return name;
}
QString result = name;
QString pfx = match.captured(1);;
if (m_renaming.contains(pfx)) {
result.remove(pfxRegExp);
result.prepend(m_renaming[pfx] + QLatin1Char('.'));
}
return result;
}
/**
* Parse all files that can be formed by concatenation of the given stems.
*/
void AdaImport::parseStems(const QStringList& stems)
{
if (stems.isEmpty())
return;
QString base = stems.first();
int i = 0;
while (1) {
QString filename = base + QStringLiteral(".ads");
if (! m_parsedFiles.contains(filename)) {
// Save current m_source and m_srcIndex.
QStringList source(m_source);
uint srcIndex = m_srcIndex;
m_source.clear();
parseFile(filename);
// Restore m_source and m_srcIndex.
m_source = source;
m_srcIndex = srcIndex;
// Also reset m_currentAccess.
// CHECK: need to reset more stuff?
m_currentAccess = Uml::Visibility::Public;
}
if (++i >= stems.count())
break;
base += QLatin1Char('-') + stems[i];
}
}
/**
* Implement abstract operation from NativeImportBase.
*/
bool AdaImport::parseStmt()
{
const int srcLength = m_source.count();
QString keyword = m_source[m_srcIndex];
UMLDoc *umldoc = UMLApp::app()->document();
//uDebug() << '"' << keyword << '"';
if (keyword == QStringLiteral("with")) {
if (m_inGenericFormalPart) {
// mapping of generic formal subprograms or packages is not yet implemented
return false;
}
while (++m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(";")) {
QStringList components = m_source[m_srcIndex].toLower().split(QLatin1Char('.'));
const QString& prefix = components.first();
if (prefix == QStringLiteral("system")
|| prefix == QStringLiteral("ada")
|| prefix == QStringLiteral("gnat")
|| prefix == QStringLiteral("interfaces")
|| prefix == QStringLiteral("text_io")
|| prefix == QStringLiteral("unchecked_conversion")
|| prefix == QStringLiteral("unchecked_deallocation")) {
if (advance() != QStringLiteral(","))
break;
continue;
}
parseStems(components);
if (advance() != QStringLiteral(","))
break;
}
return true;
}
if (keyword == QStringLiteral("generic")) {
m_inGenericFormalPart = true;
return true;
}
if (keyword == QStringLiteral("package")) {
const QString& name = advance();
QStringList parentPkgs = name.toLower().split(QLatin1Char('.'));
parentPkgs.pop_back(); // exclude the current package
parseStems(parentPkgs);
UMLObject *ns = nullptr;
if (advance() == QStringLiteral("is")) {
ns = Import_Utils::createUMLObject(UMLObject::ot_Package, name,
currentScope(), m_comment);
if (m_source[m_srcIndex + 1] == QStringLiteral("new")) {
m_srcIndex++;
QString pkgName = advance();
UMLObject *gp = Import_Utils::createUMLObject(UMLObject::ot_Package, pkgName,
currentScope());
gp->setStereotype(QStringLiteral("generic"));
// Add binding from instantiator to instantiatee
UMLAssociation *assoc = new UMLAssociation(Uml::AssociationType::Dependency, ns, gp);
assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical));
assoc->setStereotype(QStringLiteral("bind"));
// Work around missing display of stereotype in AssociationWidget:
assoc->setName(assoc->stereotype(true));
umldoc->addAssociation(assoc);
skipStmt();
} else {
pushScope(ns->asUMLPackage());
}
} else if (m_source[m_srcIndex] == QStringLiteral("renames")) {
m_renaming[name] = advance();
} else {
logError1("AdaImport::parseStmt unexpected: %1", m_source[m_srcIndex]);
skipStmt(QStringLiteral("is"));
}
if (m_inGenericFormalPart) {
if (ns)
ns->setStereotype(QStringLiteral("generic"));
m_inGenericFormalPart = false;
}
return true;
}
if (m_inGenericFormalPart)
return false; // skip generic formal parameter (not yet implemented)
if (keyword == QStringLiteral("subtype")) {
QString name = advance();
advance(); // "is"
QString base = expand(advance());
base.remove(QStringLiteral("Standard."), Qt::CaseInsensitive);
UMLObject *type = umldoc->findUMLObject(base, UMLObject::ot_UMLObject, currentScope());
if (type == nullptr) {
type = Import_Utils::createUMLObject(UMLObject::ot_Datatype, base, currentScope());
}
UMLObject *subtype = Import_Utils::createUMLObject(type->baseType(), name,
currentScope(), m_comment);
UMLAssociation *assoc = new UMLAssociation(Uml::AssociationType::Dependency, subtype, type);
assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical));
assoc->setStereotype(QStringLiteral("subtype"));
// Work around missing display of stereotype in AssociationWidget:
assoc->setName(assoc->stereotype(true));
umldoc->addAssociation(assoc);
skipStmt();
return true;
}
if (keyword == QStringLiteral("type")) {
QString name = advance();
QString next = advance();
if (next == QStringLiteral("(")) {
logDebug1("AdaImport::parseStmt %1: discriminant handling is not yet implemented", name);
// @todo Find out how to map discriminated record to UML.
// For now, we just create a pro forma empty record.
Import_Utils::createUMLObject(UMLObject::ot_Class, name, currentScope(),
m_comment, QStringLiteral("record"));
skipStmt(QStringLiteral("end"));
if ((next = advance()) == QStringLiteral("case"))
m_srcIndex += 2; // skip "case" ";"
skipStmt();
return true;
}
if (next == QStringLiteral(";")) {
// forward declaration
Import_Utils::createUMLObject(UMLObject::ot_Class, name, currentScope(),
m_comment);
return true;
}
if (next != QStringLiteral("is")) {
logError1("AdaImport::parseStmt: expecting \"is\" at %1", next);
return false;
}
next = advance();
if (next == QStringLiteral("(")) {
// enum type
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum,
name, currentScope(), m_comment);
UMLEnum *enumType = ns->asUMLEnum();
if (enumType == nullptr)
enumType = Import_Utils::remapUMLEnum(ns, enumType);
while ((next = advance()) != QStringLiteral(")")) {
if (enumType != nullptr)
Import_Utils::addEnumLiteral(enumType, next, m_comment);
m_comment.clear();
if (advance() != QStringLiteral(","))
break;
}
skipStmt();
return true;
}
bool isTaggedType = false;
if (next == QStringLiteral("abstract")) {
m_isAbstract = true;
next = advance();
}
if (next == QStringLiteral("tagged")) {
isTaggedType = true;
next = advance();
}
if (next == QStringLiteral("limited") ||
next == QStringLiteral("task") ||
next == QStringLiteral("protected") ||
next == QStringLiteral("synchronized")) {
next = advance(); // we can't (yet?) represent that
}
if (next == QStringLiteral("private") ||
next == QStringLiteral("interface") ||
next == QStringLiteral("record") ||
(next == QStringLiteral("null") &&
m_source[m_srcIndex+1] == QStringLiteral("record"))) {
UMLObject::ObjectType t = (next == QStringLiteral("interface") ? UMLObject::ot_Interface
: UMLObject::ot_Class);
UMLObject *ns = Import_Utils::createUMLObject(t, name, currentScope(), m_comment);
if (t == UMLObject::ot_Interface) {
while ((next = advance()) == QStringLiteral("and")) {
UMLClassifier *klass = ns->asUMLClassifier();
QString base = expand(advance());
UMLObject *p = Import_Utils::createUMLObject(UMLObject::ot_Interface, base, currentScope());
UMLClassifier *parent = p->asUMLClassifier();
Import_Utils::createGeneralization(klass, parent);
}
} else {
ns->setAbstract(m_isAbstract);
}
m_isAbstract = false;
if (isTaggedType) {
if (! m_classesDefinedInThisScope.contains(ns))
m_classesDefinedInThisScope.append(ns);
} else {
ns->setStereotype(QStringLiteral("record"));
}
if (next == QStringLiteral("record"))
m_klass = ns->asUMLClassifier();
else
skipStmt();
return true;
}
if (next == QStringLiteral("new")) {
QString base = expand(advance());
QStringList baseInterfaces;
while ((next = advance()) == QStringLiteral("and")) {
baseInterfaces.append(expand(advance()));
}
const bool isExtension = (next == QStringLiteral("with"));
UMLObject::ObjectType t;
if (isExtension || m_isAbstract) {
t = UMLObject::ot_Class;
} else {
base.remove(QStringLiteral("Standard."), Qt::CaseInsensitive);
UMLObject *known = umldoc->findUMLObject(base, UMLObject::ot_UMLObject, currentScope());
t = (known ? known->baseType() : UMLObject::ot_Datatype);
}
UMLObject *ns = Import_Utils::createUMLObject(t, base, nullptr);
UMLClassifier *parent = ns->asUMLClassifier();
ns = Import_Utils::createUMLObject(t, name, currentScope(), m_comment);
if (isExtension) {
next = advance();
if (next == QStringLiteral("null") || next == QStringLiteral("record")) {
UMLClassifier *klass = ns->asUMLClassifier();
Import_Utils::createGeneralization(klass, parent);
if (next == QStringLiteral("record")) {
// Set the m_klass for attributes.
m_klass = klass;
}
if (baseInterfaces.count()) {
t = UMLObject::ot_Interface;
QStringList::Iterator end(baseInterfaces.end());
for (QStringList::Iterator bi(baseInterfaces.begin()); bi != end; ++bi) {
ns = Import_Utils::createUMLObject(t, *bi, currentScope());
parent = ns->asUMLClassifier();
Import_Utils::createGeneralization(klass, parent);
}
}
}
}
skipStmt();
return true;
}
// Datatypes: TO BE DONE
return false;
}
if (keyword == QStringLiteral("private")) {
m_currentAccess = Uml::Visibility::Private;
return true;
}
if (keyword == QStringLiteral("end")) {
if (m_klass) {
if (advance() != QStringLiteral("record")) {
logError1("AdaImport::parseStmt end: expecting \"record\" at %1",
m_source[m_srcIndex]);
}
m_klass = nullptr;
} else if (scopeIndex()) {
if (advance() != QStringLiteral(";")) {
QString scopeName = currentScope()->fullyQualifiedName();
if (scopeName.toLower() != m_source[m_srcIndex].toLower())
logError2("AdaImport::parseStmt end: expecting %1, found %2",
scopeName, m_source[m_srcIndex]);
}
popScope();
m_currentAccess = Uml::Visibility::Public; // @todo make a stack for this
} else {
logError1("AdaImport::parseStmt: too many \"end\" at index %1", m_srcIndex);
}
skipStmt();
return true;
}
// subprogram
if (keyword == QStringLiteral("not"))
keyword = advance();
if (keyword == QStringLiteral("overriding"))
keyword = advance();
if (keyword == QStringLiteral("function") || keyword == QStringLiteral("procedure")) {
const QString& name = advance();
QString returnType;
if (advance() != QStringLiteral("(")) {
// Unlike an Ada package, a UML package does not support
// subprograms.
// In order to map those, we would need to create a UML
// class with stereotype <<utility>> for the Ada package.
logDebug2("AdaImport::parseStmt(%1): ignoring parameterless %2", keyword, name);
skipStmt();
return true;
}
UMLClassifier *klass = nullptr;
UMLOperation *op = nullptr;
const uint MAX_PARNAMES = 16;
while (m_srcIndex < srcLength && m_source[m_srcIndex] != QStringLiteral(")")) {
QString parName[MAX_PARNAMES];
uint parNameCount = 0;
do {
if (parNameCount >= MAX_PARNAMES) {
logError1("AdaImport::parseStmt: MAX_PARNAMES is exceeded at %1", name);
break;
}
parName[parNameCount++] = advance();
} while (advance() == QStringLiteral(","));
if (m_source[m_srcIndex] != QStringLiteral(":")) {
logError2("AdaImport::parseStmt: expecting ':' at %1 (index %2)",
m_source[m_srcIndex], m_srcIndex);
skipStmt();
break;
}
const QString &direction = advance();
QString typeName;
Uml::ParameterDirection::Enum dir = Uml::ParameterDirection::In;
if (direction == QStringLiteral("access")) {
// Oops, we have to improvise here because there
// is no such thing as "access" in UML.
// So we use the next best thing, "inout".
// Better ideas, anyone?
dir = Uml::ParameterDirection::InOut;
typeName = advance();
} else if (direction == QStringLiteral("in")) {
if (m_source[m_srcIndex + 1] == QStringLiteral("out")) {
dir = Uml::ParameterDirection::InOut;
m_srcIndex++;
}
typeName = advance();
} else if (direction == QStringLiteral("out")) {
dir = Uml::ParameterDirection::Out;
typeName = advance();
} else {
typeName = direction; // In Ada, the default direction is "in"
}
typeName.remove(QStringLiteral("Standard."), Qt::CaseInsensitive);
typeName = expand(typeName);
if (op == nullptr) {
// In Ada, the first parameter indicates the class.
UMLObject *type = Import_Utils::createUMLObject(UMLObject::ot_Class, typeName, currentScope());
UMLObject::ObjectType t = type->baseType();
if ((t != UMLObject::ot_Interface &&
(t != UMLObject::ot_Class || type->stereotype() == QStringLiteral("record"))) ||
!m_classesDefinedInThisScope.contains(type)) {
// Not an instance bound method - we cannot represent it.
skipStmt(QStringLiteral(")"));
break;
}
klass = type->asUMLClassifier();
op = Import_Utils::makeOperation(klass, name);
// The controlling parameter is suppressed.
parNameCount--;
if (parNameCount) {
for (uint i = 0; i < parNameCount; ++i) {
parName[i] = parName[i + 1];
}
}
}
for (uint i = 0; i < parNameCount; ++i) {
UMLAttribute *att = Import_Utils::addMethodParameter(op, typeName, parName[i]);
att->setParmKind(dir);
}
if (advance() != QStringLiteral(";"))
break;
}
if (keyword == QStringLiteral("function")) {
if (advance() != QStringLiteral("return")) {
if (klass)
logError1("AdaImport::parseStmt: expecting \"return\" at function %1", name);
else
logError1("AdaImport::parseStmt: expecting \"return\" at %1", m_source[m_srcIndex]);
return false;
}
returnType = expand(advance());
returnType.remove(QStringLiteral("Standard."), Qt::CaseInsensitive);
}
bool isAbstract = false;
if (advance() == QStringLiteral("is") && advance() == QStringLiteral("abstract"))
isAbstract = true;
if (klass != nullptr && op != nullptr)
Import_Utils::insertMethod(klass, op, m_currentAccess, returnType,
false, isAbstract, false, false, false, m_comment);
skipStmt();
return true;
}
if (keyword == QStringLiteral("task") || keyword == QStringLiteral("protected")) {
// Can task and protected objects/types be mapped to UML?
QString name = advance();
if (name == QStringLiteral("type")) {
name = advance();
}
QString next = advance();
if (next == QStringLiteral("(")) {
skipStmt(QStringLiteral(")")); // skip discriminant
next = advance();
}
if (next == QStringLiteral("is"))
skipStmt(QStringLiteral("end"));
skipStmt();
return true;
}
if (keyword == QStringLiteral("for")) { // rep spec
QString typeName = advance();
QString next = advance();
if (next == QStringLiteral("'")) {
advance(); // skip qualifier
next = advance();
}
if (next == QStringLiteral("use")) {
if (advance() == QStringLiteral("record"))
skipStmt(QStringLiteral("end"));
} else {
logError1("AdaImport::parseStmt: expecting \"use\" at rep spec of %1", typeName);
}
skipStmt();
return true;
}
// At this point we're only interested in attribute declarations.
if (m_klass == nullptr || keyword == QStringLiteral("null")) {
skipStmt();
return true;
}
const QString& name = keyword;
if (advance() != QStringLiteral(":")) {
logError2("AdaImport::parseStmt:: expecting \":\" at %1 %2", name, m_source[m_srcIndex]);
skipStmt();
return true;
}
QString nextToken = advance();
if (nextToken == QStringLiteral("aliased"))
nextToken = advance();
QString typeName = expand(nextToken);
QString initialValue;
if (advance() == QStringLiteral(":=")) {
initialValue = advance();
QString token;
while ((token = advance()) != QStringLiteral(";")) {
initialValue.append(QLatin1Char(' ') + token);
}
}
UMLObject *o = Import_Utils::insertAttribute(m_klass, m_currentAccess, name,
typeName, m_comment);
if (o) {
UMLAttribute *attr = o->asUMLAttribute();
attr->setInitialValue(initialValue);
}
skipStmt();
return true;
}
| 24,908
|
C++
|
.cpp
| 616
| 28.792208
| 112
| 0.53215
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,597
|
pythonimport.cpp
|
KDE_umbrello/umbrello/codeimport/pythonimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2006-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "pythonimport.h"
// app includes
#include "attribute.h"
#include "classifier.h"
#include "codeimpthread.h"
#define DBG_SRC QStringLiteral("PythonImport")
#include "debug_utils.h"
#include "enum.h"
#include "import_utils.h"
#include "operation.h"
#include "package.h"
#include "uml.h"
#include "umldoc.h"
#include "umlpackagelist.h"
// qt includes
#include <QRegularExpression>
DEBUG_REGISTER(PythonImport)
/**
* Constructor.
*/
PythonImport::PythonImport(CodeImpThread* thread)
: NativeImportBase(QStringLiteral("#"), thread)
{
setMultiLineComment(QStringLiteral("\"\"\""), QStringLiteral("\"\"\""));
initVars();
}
/**
* Destructor.
*/
PythonImport::~PythonImport()
{
}
/**
* Reimplement operation from NativeImportBase.
*/
void PythonImport::initVars()
{
m_srcIndentIndex = 0;
m_srcIndent[m_srcIndentIndex] = 0;
m_braceWasOpened = false;
m_isStatic = false;
}
/**
* Reimplement operation from NativeImportBase.
* In addition to handling multiline comments, this method transforms
* changes in leading indentation into braces (opening brace for increase
* in indentation, closing brace for decrease in indentation) in m_source.
* Removal of Python's indentation sensitivity simplifies subsequent
* processing using Umbrello's native import framework.
* @param line the line to preprocess
* @return success status of operation
*/
bool PythonImport::preprocess(QString& line)
{
if (NativeImportBase::preprocess(line))
return true;
// Handle single line comment
int pos = line.indexOf(m_singleLineCommentIntro);
if (pos != -1) {
QString cmnt = line.mid(pos);
m_source.append(cmnt);
m_srcIndex++;
if (pos == 0)
return true;
line = line.left(pos);
line.remove(QRegularExpression(QStringLiteral("\\s+$")));
}
// Transform changes in indentation into braces a la C++/Java/Perl/...
pos = line.indexOf(QRegularExpression(QStringLiteral("\\S")));
if (pos == -1)
return true;
bool isContinuation = false;
int leadingWhite = line.left(pos).count(QRegularExpression(QStringLiteral("\\s")));
if (leadingWhite > m_srcIndent[m_srcIndentIndex]) {
if (m_srcIndex == 0) {
logError0("PythonImport::preprocess internal error");
return true;
}
if (m_braceWasOpened) {
m_srcIndent[++m_srcIndentIndex] = leadingWhite;
m_braceWasOpened = false;
} else {
isContinuation = true;
}
} else {
while (m_srcIndentIndex > 0 && leadingWhite < m_srcIndent[m_srcIndentIndex]) {
m_srcIndentIndex--;
m_source.append(QStringLiteral("}"));
m_srcIndex++;
}
}
if (m_braceWasOpened && m_srcIndentIndex == 0) {
m_source.append(QStringLiteral("}"));
m_srcIndex++;
}
if (line.endsWith(QLatin1Char(':'))) {
line.replace(QRegularExpression(QStringLiteral(":$")), QStringLiteral("{"));
m_braceWasOpened = true;
} else {
m_braceWasOpened = false;
}
if (!isContinuation && !m_braceWasOpened)
line += QLatin1Char(';');
return false; // The input was not completely consumed by preprocessing.
}
/**
* Implement abstract operation from NativeImportBase.
* @param word whitespace delimited item
*/
void PythonImport::fillSource(const QString& word)
{
QString lexeme;
const uint len = word.length();
uint i = 0;
if (word[0] == QLatin1Char('-') && len > 1) {
const QChar& c1 = word[1];
if (c1 == QLatin1Char('>')) {
m_source.append(QStringLiteral("->"));
i = 2;
} else if (c1.isDigit()) {
lexeme.append(word[0]).append(word[1]);
i = 2;
}
}
for (; i < len; ++i) {
const QChar& c = word[i];
if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('.')) {
lexeme += c;
} else {
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
m_srcIndex++;
lexeme.clear();
}
QString tok(c);
m_source.append(tok);
m_srcIndex++;
}
}
if (!lexeme.isEmpty()) {
m_source.append(lexeme);
m_srcIndex++;
}
}
/**
* Return an amount of spaces that corresponds to @param level
* @return spaces of indentation
*/
QString PythonImport::indentation(int level)
{
QString spaces;
for (int i = 0; i < level; ++i) {
spaces += QStringLiteral(" ");
}
return spaces;
}
/**
* Skip ahead to outermost closing brace.
* @param foundReturn Optional pointer to Uml::PrimitiveTypes::Enum.
* If given then the variable pointed to will be set if
* a 'return' statement is encountered while skipping:
* - If after 'return' there is a value True or False then
* *foundReturn is set to Boolean;
* - elsif after 'return' there is a number without decimal
* point then *foundReturn is set to Integer;
* - elsif after 'return' there is a number with decimal
* point then *foundReturn is set to Real;
* - else *foundReturn is set to String.
* If no 'return' statement was encountered then
* *foundReturn is set to Reserved.
* @return body contents skipped
*/
QString PythonImport::skipBody(Uml::PrimitiveTypes::Enum *foundReturn)
{
/* During input preprocessing, changes in indentation were replaced by
braces, and a semicolon was appended to each line ending.
In order to return the body, we try to reconstruct the original Python
syntax by reverting those changes.
*/
QString body;
if (foundReturn != nullptr)
*foundReturn = Uml::PrimitiveTypes::Reserved;
if (m_source[m_srcIndex] != QStringLiteral("{"))
skipStmt(QStringLiteral("{"));
bool firstTokenAfterNewline = true;
bool dictInitializer = false;
int braceNesting = 0;
QString token;
while (!(token = advance()).isNull()) {
if (token == QStringLiteral("}")) {
if (dictInitializer) {
body += QLatin1Char('}');
dictInitializer = false;
} else {
if (braceNesting <= 0)
break;
braceNesting--;
}
body += QLatin1Char('\n');
firstTokenAfterNewline = true;
} else if (token == QStringLiteral("{")) {
if (m_source[m_srcIndex - 1] == QStringLiteral("=")) {
body += QLatin1Char('{');
dictInitializer = true;
} else {
body += QLatin1Char(':');
braceNesting++;
}
body += QLatin1Char('\n');
firstTokenAfterNewline = true;
} else if (token == QStringLiteral(";")) {
body += QLatin1Char('\n');
firstTokenAfterNewline = true;
} else {
if (firstTokenAfterNewline) {
body += indentation(braceNesting);
firstTokenAfterNewline = false;
if (foundReturn != nullptr && token == QStringLiteral("return") &&
(*foundReturn == Uml::PrimitiveTypes::Reserved ||
*foundReturn == Uml::PrimitiveTypes::String)) {
QString next = lookAhead();
if (next == QStringLiteral("False") || next == QStringLiteral("True")) {
*foundReturn = Uml::PrimitiveTypes::Boolean;
} else if (next.contains(QRegularExpression(QStringLiteral("^-?\\d+$")))) {
*foundReturn = Uml::PrimitiveTypes::Integer;
} else if (next.contains(QRegularExpression(QStringLiteral("^-?\\d+\\.")))) {
*foundReturn = Uml::PrimitiveTypes::Real;
} else if (next != QStringLiteral("None")) {
*foundReturn = Uml::PrimitiveTypes::String;
}
}
} else if (body.contains(QRegularExpression(QStringLiteral("\\w$"))) &&
token.contains(QRegularExpression(QStringLiteral("^\\w")))) {
body += QLatin1Char(' ');
}
body += token;
}
}
return body;
}
/**
* Parses a python initializer
* @param _keyword current string from parser
* @param type returns type of assignment
* @param value returns assignment value
* @return success status of parsing
*/
bool PythonImport::parseInitializer(const QString &_keyword, QString &type, QString &value)
{
QString keyword = _keyword;
if (_keyword == QStringLiteral("-"))
keyword.append(advance());
if (keyword == QStringLiteral("[")) {
type = QStringLiteral("list");
int index = m_srcIndex;
skipToClosing(QLatin1Char('['));
for (int i = index; i <= m_srcIndex; i++)
value += m_source[i];
} else if (keyword == QStringLiteral("{")) {
type = QStringLiteral("dict");
int index = m_srcIndex;
skipToClosing(QLatin1Char('{'));
for (int i = index; i <= m_srcIndex; i++)
value += m_source[i];
} else if (keyword == QStringLiteral("(")) {
type = QStringLiteral("tuple");
int index = m_srcIndex;
skipToClosing(QLatin1Char('('));
for (int i = index; i <= m_srcIndex; i++)
value += m_source[i];
} else if (keyword.startsWith(QStringLiteral("\""))) {
type = QStringLiteral("str");
value = keyword;
} else if (keyword == QStringLiteral("True") || keyword == QStringLiteral("False")) {
type = QStringLiteral("bool");
value = keyword;
} else if (keyword.contains(QRegularExpression(QStringLiteral("-?\\d+\\.\\d*")))) {
type = QStringLiteral("float");
value = keyword;
} else if (keyword.contains(QRegularExpression(QStringLiteral("-?\\d+")))) {
type = QStringLiteral("int");
value = keyword;
} else if (keyword.toLower() == QStringLiteral("none")) {
type = QStringLiteral("object");
value = keyword;
} else if (!keyword.isEmpty()) {
if (lookAhead() == QStringLiteral("(")) {
advance();
type = keyword;
int index = m_srcIndex;
skipToClosing(QLatin1Char('('));
for (int i = index; i <= m_srcIndex; i++)
value += m_source[i];
} else {
type = QStringLiteral("object");
}
} else {
type = QStringLiteral("object");
}
return true;
}
/**
* Parse assignments in the form \<identifier\> '=' \<value\>
* Instance variables are identified by a prefixed 'self.'.
* @param keyword current string from parser
* @return success status of parsing
*/
bool PythonImport::parseAssignmentStmt(const QString &keyword)
{
QString variableName = keyword;
bool isStatic = true;
if (variableName.startsWith(QStringLiteral("self."))) {
variableName.remove(0,5);
isStatic = false;
}
Uml::Visibility::Enum visibility = Uml::Visibility::Public;
if (variableName.startsWith(QStringLiteral("__"))) {
visibility = Uml::Visibility::Private;
variableName.remove(0, 2);
} else if (variableName.startsWith(QStringLiteral("_"))) {
visibility = Uml::Visibility::Protected;
variableName.remove(0, 1);
}
QString type;
QString initialValue;
if (advance() == QStringLiteral("=")) {
if (!parseInitializer(advance(), type, initialValue))
return false;
}
UMLObject* o = Import_Utils::insertAttribute(m_klass, visibility, variableName,
type, m_comment, false);
UMLAttribute* a = o->asUMLAttribute();
a->setInitialValue(initialValue);
a->setStatic(isStatic);
return true;
}
/**
* Parses method parameter list
* @param op UMLOperation instance to add parameter
* @return success status of parsing
*/
bool PythonImport::parseMethodParameters(UMLOperation *op)
{
bool firstParam = true;
while (m_srcIndex < m_source.count() && advance() != QStringLiteral(")")) {
const QString& parName = m_source[m_srcIndex];
if (firstParam) {
firstParam = false;
if (parName.compare(QStringLiteral("self"), Qt::CaseInsensitive) == 0) {
if (lookAhead() == QStringLiteral(","))
advance();
continue;
}
m_isStatic = true;
}
QString type, value;
QString next = lookAhead();
if (next == QStringLiteral(":")) {
advance();
type = advance();
if (lookAhead() == QStringLiteral("[")) {
int index = ++m_srcIndex;
skipToClosing(QLatin1Char('['));
for (int i = index; i <= m_srcIndex; i++) {
type += m_source[i];
}
}
next = lookAhead();
}
if (next == QStringLiteral("=")) {
advance();
QString iniType;
parseInitializer(advance(), iniType, value);
if (type.isEmpty())
type = iniType;
}
UMLAttribute *attr = Import_Utils::addMethodParameter(op, type, parName);
if (!value.isEmpty())
attr->setInitialValue(value);
if (lookAhead() == QStringLiteral(","))
advance();
}
return true;
}
/**
* Implement abstract operation from NativeImportBase.
* @return success status of operation
*/
bool PythonImport::parseStmt()
{
const int srcLength = m_source.count();
QString keyword = m_source[m_srcIndex];
if (keyword == QStringLiteral("class")) {
const QString& name = advance();
UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Class, name,
currentScope(), m_comment);
pushScope(m_klass = ns->asUMLClassifier());
m_comment.clear();
if (advance() == QStringLiteral("(")) {
while (m_srcIndex < srcLength - 1 && advance() != QStringLiteral(")")) {
const QString& baseName = m_source[m_srcIndex];
Import_Utils::createGeneralization(m_klass, baseName);
if (advance() != QStringLiteral(","))
break;
}
}
if (m_source[m_srcIndex] != QStringLiteral("{")) {
skipStmt(QStringLiteral("{"));
}
log(QStringLiteral("class ") + name);
return true;
}
if (keyword == QStringLiteral("@")) {
const QString& annotation = m_source[++m_srcIndex];
logDebug1("PythonImport::parseStmt annotation: %1", annotation);
if (annotation == QStringLiteral("staticmethod"))
m_isStatic = true;
return true;
}
if (keyword == QStringLiteral("def")) {
if (m_klass == nullptr) {
// skip functions outside of a class
skipBody();
return true;
}
if (!m_klass->hasDoc() && !m_comment.isEmpty()) {
m_klass->setDoc(m_comment);
m_comment = QString();
}
QString name = advance();
bool isConstructor = name == QStringLiteral("__init__");
Uml::Visibility::Enum visibility = Uml::Visibility::Public;
if (!isConstructor) {
if (name.startsWith(QStringLiteral("__"))) {
name = name.mid(2);
visibility = Uml::Visibility::Private;
} else if (name.startsWith(QStringLiteral("_"))) {
name = name.mid(1);
visibility = Uml::Visibility::Protected;
}
}
UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
if (advance() != QStringLiteral("(")) {
logError1("PythonImport::parseStmt def %1: expecting \" (\"", name);
skipBody();
return true;
}
if (!parseMethodParameters(op)) {
logError1("PythonImport::parseStmt error on parsing method parameter for method %1", name);
skipBody();
return true;
}
// m_srcIndex is now at ")"
int srcIndex = ++m_srcIndex;
QString returnTypeName;
if (current() == QStringLiteral("->")) { // type hint
returnTypeName = advance();
if (returnTypeName == QStringLiteral("None"))
returnTypeName.clear();
++m_srcIndex;
}
Uml::PrimitiveTypes::Enum foundReturn;
const QString bodyCode(skipBody(&foundReturn));
if (returnTypeName.isEmpty() && foundReturn != Uml::PrimitiveTypes::Reserved) {
switch (foundReturn) {
case Uml::PrimitiveTypes::Boolean :
returnTypeName = QStringLiteral("bool");
break;
case Uml::PrimitiveTypes::Integer :
returnTypeName = QStringLiteral("int");
break;
case Uml::PrimitiveTypes::Real :
returnTypeName = QStringLiteral("float");
break;
case Uml::PrimitiveTypes::String :
returnTypeName = QStringLiteral("str");
break;
default:
break;
}
}
Import_Utils::insertMethod(m_klass, op, visibility, returnTypeName,
m_isStatic, false /*isAbstract*/, false /*isFriend*/,
isConstructor, false, m_comment);
op->setSourceCode(bodyCode);
m_isStatic = false;
if (!op->hasDoc() && !m_comment.isEmpty()) {
op->setDoc(m_comment);
m_comment = QString();
}
// parse instance variables from __init__ method
if (isConstructor) {
int indexSave = m_srcIndex;
m_srcIndex = srcIndex;
advance();
keyword = advance();
while (m_srcIndex < indexSave) {
if (lookAhead() == QStringLiteral("=")) {
parseAssignmentStmt(keyword);
// skip ; inserted by lexer
if (lookAhead() == QStringLiteral(";")) {
advance();
keyword = advance();
}
} else {
skipStmt(QStringLiteral(";"));
keyword = advance();
}
}
m_srcIndex = indexSave;
}
log(QStringLiteral("def ") + name);
return true;
}
// parse class variables
if (m_klass && lookAhead() == QStringLiteral("=")) {
bool result = parseAssignmentStmt(keyword);
log(QStringLiteral("class attribute ") + keyword);
return result;
}
if (keyword == QStringLiteral("}")) {
if (scopeIndex()) {
m_klass = popScope()->asUMLClassifier();
}
else
logError2("PythonImport::parseStmt: too many } at index %1 of %2",
m_srcIndex, m_source.count());
return true;
}
return false; // @todo parsing of attributes
}
| 19,647
|
C++
|
.cpp
| 536
| 27.712687
| 103
| 0.560685
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,598
|
nativeimportbase.cpp
|
KDE_umbrello/umbrello/codeimport/nativeimportbase.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "nativeimportbase.h"
// app includes
#include "codeimpthread.h"
#define DBG_SRC QStringLiteral("NativeImportBase")
#include "debug_utils.h"
#include "import_utils.h"
#include "uml.h" // only needed for log{Warn,Error}
// kde includes
#include <KLocalizedString>
// qt includes
#include <QFile>
#include <QRegularExpression>
#include <QTextStream>
DEBUG_REGISTER(NativeImportBase)
QStringList NativeImportBase::m_parsedFiles; // static, see nativeimportbase.h
/**
* Constructor
* @param singleLineCommentIntro "//" for IDL and Java, "--" for Ada
* @param thread thread in which the code import runs
*/
NativeImportBase::NativeImportBase(const QString &singleLineCommentIntro, CodeImpThread* thread)
: ClassImport(thread),
m_singleLineCommentIntro(singleLineCommentIntro),
m_srcIndex(0),
m_klass(nullptr),
m_currentAccess(Uml::Visibility::Public),
m_inComment(false),
m_isAbstract(false)
{
}
/**
* Destructor.
*/
NativeImportBase::~NativeImportBase()
{
}
/**
* Set the delimiter strings for a multi line comment.
* @param intro In languages with a C style multiline comment
* this is slash-star.
* @param end In languages with a C style multiline comment
* this is star-slash.
*/
void NativeImportBase::setMultiLineComment(const QString &intro, const QString &end)
{
m_multiLineCommentIntro = intro;
m_multiLineCommentEnd = end;
}
/**
* Set the delimiter strings for an alternative form of
* multi line comment. See setMultiLineComment().
* @param intro the start comment string
* @param end the end comment string
*/
void NativeImportBase::setMultiLineAltComment(const QString &intro, const QString &end)
{
m_multiLineAltCommentIntro = intro;
m_multiLineAltCommentEnd = end;
}
/**
* Advance m_srcIndex until m_source[m_srcIndex] contains the lexeme
* given by `until`.
* @param until the target string
*/
void NativeImportBase::skipStmt(const QString& until /* = ";" */)
{
const int srcLength = m_source.count();
while (m_srcIndex < srcLength && m_source[m_srcIndex] != until)
m_srcIndex++;
}
/**
* Advance m_srcIndex to the index of the corresponding closing character
* of the given opening. Nested opening/closing pairs are respected.
* Valid openers are: '{' '[' '(' '<'
* @param opener the opener string
* @return True for success, false for misuse (invalid opener) or
* if no matching closing character is found in m_source.
*/
bool NativeImportBase::skipToClosing(QChar opener)
{
QString closing;
switch (opener.toLatin1()) {
case '{':
closing = QStringLiteral("}");
break;
case '[':
closing = QStringLiteral("]");
break;
case '(':
closing = QStringLiteral(")");
break;
case '<':
closing = QStringLiteral(">");
break;
default:
logError1("NativeImportBase::skipToClosing opener='%1': illegal input character", opener);
return false;
}
const QString opening(opener);
skipStmt(opening);
const int srcLength = m_source.count();
int nesting = 0;
while (m_srcIndex < srcLength) {
QString nextToken = advance();
if (nextToken.isEmpty())
break;
if (nextToken == closing) {
if (nesting <= 0)
break;
nesting--;
} else if (nextToken == opening) {
nesting++;
}
}
if (m_srcIndex == srcLength)
return false;
return true;
}
/**
* Set package as current scope.
* @param p UML package to set as current scope
*/
void NativeImportBase::pushScope(UMLPackage *p)
{
m_scope.append(p);
}
/**
* Return previously defined scope.
*
* @return previous scope
*/
UMLPackage *NativeImportBase::popScope()
{
m_scope.takeLast();
UMLPackage *p = m_scope.last();
return p;
}
/**
* Return current scope.
* If the scope stack is empty then return nullptr.
*
* @return scope
*/
UMLPackage *NativeImportBase::currentScope()
{
UMLPackage *p = m_scope.last();
return p;
}
/**
* Return current scope index.
*
* @return >= 0 index, -1 empty
*/
int NativeImportBase::scopeIndex()
{
return m_scope.size() - 1;
}
/**
* Get the current lexeme.
* If the end of parse was reached then return an empty string.
* @return the current lexeme
*/
QString NativeImportBase::current()
{
if (m_srcIndex < m_source.count() - 1)
return m_source[m_srcIndex];
return QString();
}
/**
* Get the next lexeme without advancing.
* @return the next lexeme or an empty string
*/
QString NativeImportBase::lookAhead()
{
if (m_srcIndex < m_source.count() - 1)
return m_source[m_srcIndex+1];
return QString();
}
/**
* Advance m_srcIndex until m_source[m_srcIndex] contains a non-comment.
* Comments encountered during advancement are accumulated in `m_comment`.
* If m_srcIndex hits the end of m_source then QString() is returned.
* @return the current lexeme or an empty string
*/
QString NativeImportBase::advance()
{
while (m_srcIndex < m_source.count() - 1) {
m_srcIndex++;
if (m_source[m_srcIndex].startsWith(m_singleLineCommentIntro))
m_comment += m_source[m_srcIndex].mid(m_singleLineCommentIntro.length());
else
break;
}
if (m_srcIndex >= m_source.count() - 1 ||
// if last item in m_source is a comment then it is dropped too
(m_srcIndex == m_source.count() - 1 &&
m_source[m_srcIndex].startsWith(m_singleLineCommentIntro))) {
return QString();
}
return m_source[m_srcIndex];
}
/**
* Preprocess a line.
* May modify the given line to remove items consumed by the
* preprocessing such as comments or preprocessor directives.
* The default implementation handles multi-line comments.
* @param line The line to preprocess.
* @return True if the line was completely consumed,
* false if there are still items left in the line
* for further analysis.
*/
bool NativeImportBase::preprocess(QString& line)
{
if (line.isEmpty())
return true;
if (m_multiLineCommentIntro.isEmpty())
return false;
// Check for end of multi line comment.
if (m_inComment) {
int delimiterLen = 0;
int pos = line.indexOf(m_multiLineCommentEnd);
if (pos == -1) {
if (! m_multiLineAltCommentEnd.isEmpty())
pos = line.indexOf(m_multiLineAltCommentEnd);
if (pos == -1) {
m_comment += line + QLatin1Char('\n');
return true; // done
}
delimiterLen = m_multiLineAltCommentEnd.length();
} else {
delimiterLen = m_multiLineCommentEnd.length();
}
if (pos > 0) {
QString text = line.mid(0, pos - 1);
m_comment += text.trimmed();
}
m_source.append(m_singleLineCommentIntro + m_comment); // denotes comments in `m_source`
m_srcIndex++;
m_comment = QString();
m_inComment = false;
pos += delimiterLen; // pos now points behind the closed comment
if (pos == (int)line.length())
return true; // done
line = line.mid(pos);
}
// If we get here then m_inComment is false.
// Check for start of multi line comment.
int delimIntroLen = 0;
int delimEndLen = 0;
int pos = line.indexOf(m_multiLineCommentIntro);
if (pos != -1) {
delimIntroLen = m_multiLineCommentIntro.length();
} else if (!m_multiLineAltCommentIntro.isEmpty()) {
pos = line.indexOf(m_multiLineAltCommentIntro);
if (pos != -1)
delimIntroLen = m_multiLineAltCommentIntro.length();
}
if (pos != -1) {
int sPos = line.indexOf(m_singleLineCommentIntro);
if (sPos != -1 && sPos < pos) {
// multi line comment intro found in single line comment
pos = -1; // is no multi line comment after all
}
}
if (pos != -1) {
int endpos = line.indexOf(m_multiLineCommentEnd, pos + delimIntroLen);
if (endpos != -1) {
delimEndLen = m_multiLineCommentEnd.length();
} else if (!m_multiLineAltCommentEnd.isEmpty()) {
endpos = line.indexOf(m_multiLineAltCommentEnd, pos + delimIntroLen);
if (endpos != -1)
delimEndLen = m_multiLineAltCommentEnd.length();
}
if (endpos == -1) {
m_inComment = true;
if (pos + delimIntroLen < (int)line.length()) {
QString cmnt = line.mid(pos + delimIntroLen);
m_comment += cmnt.trimmed() + QLatin1Char('\n');
}
if (pos == 0)
return true; // done
line = line.left(pos);
} else { // It's a multiline comment on a single line.
if (endpos > pos + delimIntroLen) {
QString cmnt = line.mid(pos + delimIntroLen, endpos - pos - delimIntroLen);
cmnt = cmnt.trimmed();
if (!cmnt.isEmpty())
m_source.append(m_singleLineCommentIntro + cmnt);
}
endpos++; // endpos now points at the slash of "*/"
QString pre;
if (pos > 0)
pre = line.left(pos);
QString post;
if (endpos + delimEndLen < (int)line.length())
post = line.mid(endpos + 1);
line = pre + post;
}
}
return false; // The input was not completely consumed by preprocessing.
}
/**
* Split the line so that a string is returned as a single element of the list.
* When not in a string then split at white space.
* The default implementation is suitable for C style strings and char constants.
* @param line the line to split
* @return the parts of the line
*/
QStringList NativeImportBase::split(const QString& line)
{
QStringList list;
QString listElement;
QChar stringIntro; // buffers the string introducer character
bool seenSpace = false;
QString ln = line.trimmed();
for (int i = 0; i < ln.length(); ++i) {
const QChar& c = ln[i];
if (stringIntro.toLatin1()) { // we are in a string
listElement += c;
if (c == stringIntro) {
if (ln[i - 1] != QLatin1Char('\\')) {
list.append(listElement);
listElement.clear();
stringIntro = QChar(); // we are no longer in a string
}
}
} else if (c == QLatin1Char('"') || c == QLatin1Char('\'')) {
if (!listElement.isEmpty()) {
list.append(listElement);
}
listElement = stringIntro = c;
seenSpace = false;
} else if (c == QLatin1Char(' ') || c == QLatin1Char('\t')) {
if (seenSpace)
continue;
seenSpace = true;
if (!listElement.isEmpty()) {
list.append(listElement);
listElement.clear();
}
} else {
listElement += c;
seenSpace = false;
}
}
if (!listElement.isEmpty())
list.append(listElement);
return list;
}
/**
* Scan a single line.
* parseFile() calls this for each line read from the input file.
* This in turn calls other methods such as preprocess() and fillSource().
* The lexer. Tokenizes the given string and fills `m_source`.
* Stores possible comments in `m_comment`.
* @param line The line to scan.
*/
void NativeImportBase::scan(const QString& line)
{
QString ln = line;
if (preprocess(ln))
return;
// Check for single line comment.
int pos = ln.indexOf(m_singleLineCommentIntro);
if (pos != -1) {
QString cmnt = ln.mid(pos);
m_source.append(cmnt);
if (pos == 0)
return;
ln = ln.left(pos);
}
if (ln.contains(QRegularExpression(QStringLiteral("^\\s*$"))))
return;
const QStringList words = split(ln);
for (QStringList::ConstIterator it = words.begin(); it != words.end(); ++it) {
QString word = *it;
if (word[0] == QLatin1Char('"') || word[0] == QLatin1Char('\''))
m_source.append(word); // string constants are handled by split()
else
fillSource(word);
}
}
/**
* Initialize auxiliary variables.
* This is called by the default implementation of parseFile()
* after scanning (before parsing the QStringList m_source.)
* The default implementation is empty.
*/
void NativeImportBase::initVars()
{
}
/**
* Import a single file.
* The default implementation should be feasible for languages that
* don't depend on an external preprocessor.
* @param filename The file to import.
* @return state of parsing - false means errors
*/
bool NativeImportBase::parseFile(const QString& filename)
{
QString nameWithoutPath = filename;
nameWithoutPath.remove(QRegularExpression(QStringLiteral("^.*/")));
if (m_parsedFiles.contains(nameWithoutPath))
return true;
m_parsedFiles.append(nameWithoutPath);
QString fname = filename;
const QString msgPrefix = filename + QStringLiteral(": ");
if (filename.contains(QLatin1Char('/'))) {
QString path = filename;
path.remove(QRegularExpression(QStringLiteral("/[^/]+$")));
logDebug2("NativeImportBase::parseFile %1 adding path %2", msgPrefix, path);
Import_Utils::addIncludePath(path);
}
if (!QFile::exists(filename)) {
QFileInfo fi(filename);
if (fi.isAbsolute()) {
logError1("NativeImportBase::parseFile: cannot find absolute file %1", filename);
return false;
}
bool found = false;
const QStringList includePaths = Import_Utils::includePathList();
for (QStringList::ConstIterator pathIt = includePaths.begin();
pathIt != includePaths.end(); ++pathIt) {
QString path = (*pathIt);
if (! path.endsWith(QLatin1Char('/'))) {
path.append(QLatin1Char('/'));
}
if (QFile::exists(path + filename)) {
fname.prepend(path);
found = true;
break;
}
}
if (! found) {
logError1("NativeImportBase::parseFile: cannot find file %1", filename);
return false;
}
}
QFile file(fname);
if (! file.open(QIODevice::ReadOnly)) {
logError1("NativeImportBase::parseFile: cannot open file %1", fname);
return false;
}
log(nameWithoutPath, QStringLiteral("parsing..."));
// Scan the input file into the QStringList m_source.
m_source.clear();
m_srcIndex = 0;
initVars();
QTextStream stream(&file);
int lineCount = 0;
while (! stream.atEnd()) {
QString line = stream.readLine();
lineCount++;
scan(line);
}
log(nameWithoutPath, QStringLiteral("file size: ") + QString::number(file.size()) +
QStringLiteral(" / lines: ") + QString::number(lineCount));
file.close();
// Parse the QStringList m_source.
m_klass = nullptr;
m_currentAccess = Uml::Visibility::Public;
m_scope.clear();
pushScope(Import_Utils::globalScope()); // index 0 is reserved for the global scope
const int srcLength = m_source.count();
for (m_srcIndex = 0; m_srcIndex < srcLength; ++m_srcIndex) {
const QString& firstToken = m_source[m_srcIndex];
//uDebug() << '"' << firstToken << '"';
if (firstToken.startsWith(m_singleLineCommentIntro)) {
m_comment += firstToken.mid(m_singleLineCommentIntro.length());
continue;
}
if (! parseStmt())
skipStmt();
m_comment.clear();
}
log(nameWithoutPath, QStringLiteral("...end of parse"));
return true;
}
/**
* Implement abstract operation from ClassImport.
*/
void NativeImportBase::initialize()
{
m_parsedFiles.clear();
}
| 16,346
|
C++
|
.cpp
| 490
| 26.930612
| 102
| 0.614024
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,599
|
cppimport.cpp
|
KDE_umbrello/umbrello/codeimport/cppimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2005-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cppimport.h"
#include "lexer.h"
#include "driver.h"
#include "kdevcppparser/cpptree2uml.h"
// app includes
#define DBG_SRC QStringLiteral("CppImport")
#include "debug_utils.h"
#include "import_utils.h"
#include "uml.h"
#include "umlobject.h"
#include "package.h"
#include "enum.h"
#include "classifier.h"
#include "operation.h"
#include "attribute.h"
#include "template.h"
#include "association.h"
#include "optionstate.h"
// qt includes
#include <QListWidget>
#include <QMap>
// static members
CppDriver * CppImport::ms_driver;
QStringList CppImport::ms_seenFiles;
class CppDriver : public Driver
{
public:
void setupLexer(Lexer* lexer)
{
Driver::setupLexer(lexer);
lexer->setRecordComments(true);
}
};
DEBUG_REGISTER(CppImport)
/**
* Constructor.
*/
CppImport::CppImport(CodeImpThread* thread)
: ClassImport(thread)
{
ms_driver = new CppDriver();
}
/**
* Destructor.
*/
CppImport::~CppImport()
{
}
/**
* Auxiliary method for recursively traversing the \#include dependencies
* in order to feed innermost includes to the model before dependent
* includes. It is important that includefiles are fed to the model
* in proper order so that references between UML objects are created
* properly.
* @param fileName the file to import
*/
void CppImport::feedTheModel(const QString& fileName)
{
if (ms_seenFiles.indexOf(fileName) != -1)
return;
QMap<QString, Dependence> deps = ms_driver->dependences(fileName);
if (! deps.empty()) {
QMap<QString, Dependence>::Iterator it;
for (it = deps.begin(); it != deps.end(); ++it) {
if (it.value().second == Dep_Global) // don't want these
continue;
QString includeFile = it.key();
if (includeFile.isEmpty()) {
logError2("CppImport::feedTheModel(%1) : %2 not found", fileName, it.value().first);
continue;
}
logDebug3("CppImport::feedTheModel(%1): %2 => %3", fileName, includeFile, it.value().first);
if (ms_seenFiles.indexOf(includeFile) == -1)
ms_seenFiles.append(includeFile);
feedTheModel(includeFile);
}
}
ParsedFilePointer ast = ms_driver->translationUnit(fileName);
if (!ast) {
logError1("CppImport::feedTheModel: %1 not found in list of parsed files", fileName);
return;
}
ms_seenFiles.append(fileName);
CppTree2Uml modelFeeder(fileName, m_thread);
modelFeeder.setRootPath(m_rootPath);
modelFeeder.parseTranslationUnit(*ast);
}
/**
* Implement abstract operation from ClassImport for C++.
*/
void CppImport::initialize()
{
// Reset the driver
ms_driver->reset();
ms_driver->setResolveDependencesEnabled(Settings::optionState().codeImportState.resolveDependencies);
// FIXME: port to win32
// Add some standard include paths
ms_driver->addIncludePath(QStringLiteral("/usr/include"));
ms_driver->addIncludePath(QStringLiteral("/usr/include/c++"));
ms_driver->addIncludePath(QStringLiteral("/usr/include/g++"));
ms_driver->addIncludePath(QStringLiteral("/usr/local/include"));
const QStringList incPathList = Import_Utils::includePathList();
if (incPathList.count()) {
QStringList::ConstIterator end(incPathList.end());
for (QStringList::ConstIterator i(incPathList.begin()); i != end; ++i) {
ms_driver->addIncludePath(*i);
}
}
}
/**
* Reimplement method from ClassImport
*/
void CppImport::initPerFile()
{
ms_seenFiles.clear();
}
/**
* Import a single file.
* @param fileName The file to import.
*/
bool CppImport::parseFile(const QString& fileName)
{
if (ms_seenFiles.indexOf(fileName) != -1)
return true;
bool result = ms_driver->parseFile(fileName);
for(const Problem &problem : ms_driver->problems(fileName)) {
QString level;
if (problem.level() == Problem::Level_Error)
level = QStringLiteral("error");
else if (problem.level() == Problem::Level_Warning)
level = QStringLiteral("warning");
else if (problem.level() == Problem::Level_Todo)
level = QStringLiteral("todo");
else if (problem.level() == Problem::Level_Fixme)
level = QStringLiteral("fixme");
QString item = QString::fromLatin1("%1:%2:%3: %4: %5")
.arg(problem.fileName()).arg(problem.line()+1)
.arg(problem.column()).arg(level).arg(problem.text());
UMLApp::app()->log(item);
}
if (!result)
return false;
feedTheModel(fileName);
return true;
}
| 4,800
|
C++
|
.cpp
| 150
| 27.113333
| 105
| 0.668033
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,600
|
valaimport.cpp
|
KDE_umbrello/umbrello/codeimport/vala/valaimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2018-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
#include "valaimport.h"
/**
* Constructor
*/
ValaImport::ValaImport(CodeImpThread *thread)
: CsValaImportBase(thread)
{
m_language = Uml::ProgrammingLanguage::Vala;
}
/**
* Destructor
*/
ValaImport::~ValaImport()
{
}
/**
* Reimplementation of method from CsValaImportBase
*/
QString ValaImport::fileExtension()
{
return QStringLiteral(".vala");
}
| 515
|
C++
|
.cpp
| 26
| 17.615385
| 92
| 0.743802
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,601
|
csharpimport.cpp
|
KDE_umbrello/umbrello/codeimport/csharp/csharpimport.cpp
|
/*
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2011-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "csharpimport.h"
/**
* Constructor.
*/
CSharpImport::CSharpImport(CodeImpThread *thread)
: CsValaImportBase(thread)
{
m_language = Uml::ProgrammingLanguage::CSharp;
}
/**
* Destructor.
*/
CSharpImport::~CSharpImport()
{
}
/**
* Reimplementation of method from CsValaImportBase
*/
QString CSharpImport::fileExtension()
{
return QStringLiteral(".cs");
}
/**
* Reimplement operation from CsValaImportBase.
* @param word whitespace delimited item
*/
void CSharpImport::fillSource(const QString& word)
{
CsValaImportBase::fillSource(word);
if (m_source.isEmpty())
return;
// Map .NET types to their native C# equivalents
static const char *dotNet2CSharp[] = {
"System.Boolean", "bool",
"System.Byte", "byte",
"System.SByte", "sbyte",
"System.Char", "char",
"System.Decimal", "decimal",
"System.Double", "double",
"System.Single", "float",
"System.Int32", "int",
"System.UInt32", "uint",
"System.IntPtr", "nint",
"System.UIntPtr", "nuint",
"System.Int64", "long",
"System.UInt64", "ulong",
"System.Int16", "short",
"System.UInt16", "ushort",
"System.Object", "object",
"System.String", "string",
};
QString& last = m_source.last();
for (size_t i = 0; i < sizeof(dotNet2CSharp) / sizeof(char*); i += 2) {
if (last == QLatin1String(dotNet2CSharp[i]))
last = QLatin1String(dotNet2CSharp[i + 1]);
}
}
| 1,708
|
C++
|
.cpp
| 62
| 22.790323
| 92
| 0.623932
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,602
|
cpptree2uml.cpp
|
KDE_umbrello/umbrello/codeimport/kdevcppparser/cpptree2uml.cpp
|
/*
Based on kdevelop-3.0 languages/cpp/store_walker.cpp by Roberto Raggi
SPDX-License-Identifier: GPL-2.0-or-later
SPDX-FileCopyrightText: 2004-2022 Umbrello UML Modeller Authors <umbrello-devel@kde.org>
*/
// own header
#include "cpptree2uml.h"
// app includes
#include "uml.h"
#include "umldoc.h"
#include "umllistview.h"
#include "datatype.h"
#include "operation.h"
#define DBG_SRC QStringLiteral("CppTree2Uml")
#include "debug_utils.h"
#include "ast_utils.h"
#include "codeimpthread.h"
#include "driver.h"
#include "import_utils.h"
// FIXME: The sole reason for the next 2 includes is parseTypedef().
// Make capsule methods in ClassImport, and remove these includes.
#include "classifier.h"
// FIXME The next include is motivated by template params
#include "template.h"
// qt includes
#include <QDir>
#include <QFileInfo>
#include <QList>
#include <QRegularExpression>
DEBUG_REGISTER(CppTree2Uml)
CppTree2Uml::CppTree2Uml(const QString& fileName, CodeImpThread* thread)
: m_thread(thread),
m_rootFolder(nullptr),
m_doc(UMLApp::app()->document())
{
clear();
QDir dir(fileName);
m_fileName = dir.canonicalPath();
}
CppTree2Uml::~CppTree2Uml()
{
}
void CppTree2Uml::clear()
{
m_currentScope.clear();
m_currentNamespace[0] = nullptr; // index 0 is reserved (always 0)
m_currentClass[0] = nullptr; // index 0 is reserved (always 0)
m_nsCnt = 0;
m_clsCnt = 0;
m_currentAccess = Uml::Visibility::Public;
m_inSlots = false;
m_inSignals = false;
m_inStorageSpec = false;
m_inTypedef = false;
m_currentDeclarator = nullptr;
m_anon = 0;
}
void CppTree2Uml::setRootPath(const QString &rootPath)
{
m_rootPath = QDir::fromNativeSeparators(rootPath);
if (Settings::optionState().codeImportState.createArtifacts) {
if (!m_rootFolder) {
UMLFolder *componentView = m_doc->rootFolder(Uml::ModelType::Component);
if (!m_rootPath.isEmpty()) {
UMLFolder *root = Import_Utils::createSubDir(m_rootPath, componentView);
m_rootFolder = root;
} else {
m_rootFolder = componentView;
}
}
}
}
void CppTree2Uml::parseTranslationUnit(const ParsedFile &file)
{
clear();
if (Settings::optionState().codeImportState.createArtifacts) {
QFileInfo fi(file.fileName());
UMLFolder *parent = m_rootFolder;
QString path;
if (!m_rootPath.isEmpty())
path = fi.path().replace(m_rootPath + QStringLiteral("/"), QStringLiteral(""));
else
path = fi.absolutePath();
if (!path.isEmpty())
parent = Import_Utils::createSubDir(path, m_rootFolder);
Import_Utils::createArtifact(fi.fileName(), parent, file->comment());
}
TreeParser::parseTranslationUnit(file);
}
void CppTree2Uml::parseNamespace(NamespaceAST* ast)
{
if (m_clsCnt > 0) {
logDebug0("CppTree2Uml::parseNamespace error - cannot nest namespace inside class");
return;
}
QString nsName;
if (!ast->namespaceName() || ast->namespaceName()->text().isEmpty()){
QFileInfo fileInfo(m_fileName);
QString shortFileName = fileInfo.baseName();
nsName = QStringLiteral("(%s_%d)").arg(shortFileName).arg(m_anon++);
} else {
nsName = ast->namespaceName()->text();
}
logDebug1("CppTree2Uml::parseNamespace %1", nsName);
if (m_thread) {
m_thread->emitMessageToLog(QString(), QStringLiteral("namespace ") + nsName);
}
UMLObject *o = m_doc->findUMLObject(nsName, UMLObject::ot_Package, m_currentNamespace[m_nsCnt]);
if (!o)
o = m_doc->findUMLObject(nsName, UMLObject::ot_Class, m_currentNamespace[m_nsCnt]);
if (o && o->stereotype() == QStringLiteral("class-or-package")) {
o->setStereotype(QString());
o->setBaseType(UMLObject::ot_Package);
}
// TODO reduce multiple finds
else
o = Import_Utils::createUMLObject(UMLObject::ot_Package, nsName,
m_currentNamespace[m_nsCnt],
ast->comment());
UMLPackage *ns = (UMLPackage *)o;
m_currentScope.push_back(nsName);
if (++m_nsCnt > STACKSIZE) {
logError0("CppTree2Uml::parseNamespace: excessive namespace nesting");
m_nsCnt = STACKSIZE;
}
m_currentNamespace[m_nsCnt] = ns;
TreeParser::parseNamespace(ast);
--m_nsCnt;
m_currentScope.pop_back();
}
void CppTree2Uml::parseTypedef(TypedefAST* ast)
{
TypeSpecifierAST* typeSpec = ast->typeSpec();
InitDeclaratorListAST* declarators = ast->initDeclaratorList();
if (typeSpec && declarators){
QString typeId;
if (typeSpec->name())
typeId = typeSpec->name()->text();
QList<InitDeclaratorAST*> l(declarators->initDeclaratorList());
InitDeclaratorAST *initDecl = nullptr;
for (int i = 0; i < l.size(); ++i) {
initDecl = l.at(i);
if (initDecl==nullptr) break;
QString type, id;
if (initDecl->declarator()){
type = typeOfDeclaration(typeSpec, initDecl->declarator());
DeclaratorAST* d = initDecl->declarator();
while (d->subDeclarator()){
d = d->subDeclarator();
}
if (d->declaratorId())
id = d->declaratorId()->text();
}
/* @todo Trace typedefs back to their root type for deciding
whether to build a Datatype (for pointers.) */
/* check out if the ID type is a Datatype
ex: typedef unsigned int uint;
where unsigned int is a known datatype
I'm not sure if setIsReference() should be run
*/
bool isDatatype = Import_Utils::isDatatype(typeId, m_currentNamespace[m_nsCnt]);
if (type.contains(QLatin1Char('*')) || isDatatype) {
UMLObject *inner = nullptr;
if (m_currentNamespace[m_nsCnt] &&
m_currentNamespace[m_nsCnt]->baseType() == UMLObject::ot_Class &&
typeId == m_currentNamespace[m_nsCnt]->name())
inner = m_currentNamespace[m_nsCnt];
else
inner = Import_Utils::createUMLObject(UMLObject::ot_Class, type,
m_currentNamespace[m_nsCnt]);
UMLObject *typedefObj =
Import_Utils::createUMLObject(UMLObject::ot_Datatype, id,
m_currentNamespace[m_nsCnt]);
UMLDatatype *dt = typedefObj->asUMLDatatype();
if (dt) {
dt->setIsReference();
dt->setOriginType(inner->asUMLClassifier());
}
else {
logError1("CppTree2Uml::parseTypedef: Could not create datatype from id %1", id);
}
} else {
Import_Utils::createUMLObject(UMLObject::ot_Class, id,
m_currentNamespace[m_nsCnt],
QString() /* doc */,
QStringLiteral("typedef") /* stereotype */);
}
}
}
}
void CppTree2Uml::parseTemplateDeclaration(TemplateDeclarationAST* ast)
{
TemplateParameterListAST* parmListAST = ast->templateParameterList();
if (parmListAST == nullptr)
return;
QList<TemplateParameterAST*> parmList = parmListAST->templateParameterList();
for (int i = 0; i < parmList.size(); ++i) {
// The template is either a typeParameter or a typeValueParameter.
TemplateParameterAST* tmplParmNode = parmList.at(i);
TypeParameterAST* typeParmNode = tmplParmNode->typeParameter();
if (typeParmNode) {
NameAST* nameNode = typeParmNode->name();
if (nameNode) {
QString typeName = nameNode->unqualifiedName()->text();
Model_Utils::NameAndType nt(typeName, nullptr);
m_templateParams.append(nt);
} else {
logError0("CppTree2Uml::parseTemplateDeclaration: nameNode is NULL");
}
}
ParameterDeclarationAST* valueNode = tmplParmNode->typeValueParameter();
if (valueNode) {
TypeSpecifierAST* typeSpec = valueNode->typeSpec();
if (typeSpec == nullptr) {
logError0("CppTree2Uml::parseTemplateDeclaration: typeSpec is NULL");
continue;
}
QString typeName = typeSpec->name()->text();
UMLObject *t = Import_Utils::createUMLObject(UMLObject::ot_UMLObject, typeName,
m_currentNamespace[m_nsCnt]);
DeclaratorAST* declNode = valueNode->declarator();
NameAST* nameNode = declNode->declaratorId();
if (nameNode == nullptr) {
logError0("CppTree2Uml::parseTemplateDeclaration(value): nameNode is NULL");
continue;
}
QString paramName = nameNode->unqualifiedName()->text();
Model_Utils::NameAndType nt(paramName, t);
m_templateParams.append(nt);
}
}
if (ast->declaration())
TreeParser::parseDeclaration(ast->declaration());
}
void CppTree2Uml::parseSimpleDeclaration(SimpleDeclarationAST* ast)
{
TypeSpecifierAST* typeSpec = ast->typeSpec();
InitDeclaratorListAST* declarators = ast->initDeclaratorList();
GroupAST* storageSpec = ast->storageSpecifier();
if (storageSpec && storageSpec->text() == QStringLiteral("friend"))
return;
m_comment = ast->comment();
if (typeSpec)
parseTypeSpecifier(typeSpec);
if (declarators){
QList<InitDeclaratorAST*> l = declarators->initDeclaratorList();
for (int i = 0; i < l.size(); ++i) {
parseDeclaration2(ast->functionSpecifier(), ast->storageSpecifier(), typeSpec, l.at(i));
}
}
}
void CppTree2Uml::parseFunctionDefinition(FunctionDefinitionAST* ast)
{
TypeSpecifierAST* typeSpec = ast->typeSpec();
GroupAST* funSpec = ast->functionSpecifier();
GroupAST* storageSpec = ast->storageSpecifier();
if (!ast->initDeclarator())
return;
DeclaratorAST* d = ast->initDeclarator()->declarator();
if (!d->declaratorId())
return;
bool isFriend = false;
bool isVirtual = false;
bool isStatic = false;
bool isInline = false;
bool isConstructor = false;
bool isDestructor = false;
bool isExplicit = false;
bool isConstExpression = false;
if (funSpec) {
QList<AST*> l = funSpec->nodeList();
for (int i = 0; i < l.size(); ++i) {
QString text = l.at(i)->text();
if (text == QStringLiteral("virtual"))
isVirtual = true;
else if (text == QStringLiteral("inline"))
isInline = true;
else if (text == QStringLiteral("explicit"))
isExplicit = true;
}
}
if (storageSpec) {
QList<AST*> l = storageSpec->nodeList();
for (int i = 0; i < l.size(); ++i) {
QString text = l.at(i)->text();
if (text == QStringLiteral("friend"))
isFriend = true;
else if (text == QStringLiteral("static"))
isStatic = true;
else if (text == QStringLiteral("constexpr"))
isConstExpression = true;
}
}
QString id = d->declaratorId()->unqualifiedName()->text().trimmed();
if (m_thread) {
m_thread->emitMessageToLog(QString(), QStringLiteral("method ") + id);
}
logDebug1("CppTree2Uml::parseFunctionDefinition %1", id);
UMLClassifier *c = m_currentClass[m_clsCnt];
if (c == nullptr) {
logDebug1("CppTree2Uml::parseFunctionDefinition %1: need a surrounding class.", id);
return;
}
QString returnType = typeOfDeclaration(typeSpec, d);
UMLOperation *m = Import_Utils::makeOperation(c, id);
if (isConstExpression)
m->setStereotype(QStringLiteral("constexpr"));
if (isVirtual)
m->setVirtual(true);
if (isInline)
m->setInline(true);
if (d->final_())
m->setFinal(true);
if (d->override_())
m->setOverride(true);
if (d->constant())
m->setConst(true);
// if a class has no return type, it could be a constructor or
// a destructor
if (d && returnType.isEmpty()) {
if (id.indexOf(QLatin1Char('~')) == -1)
isConstructor = true;
else
isDestructor = true;
}
parseFunctionArguments(d, m);
Import_Utils::insertMethod(c, m, m_currentAccess, returnType,
isStatic, false /*isAbstract*/, isFriend, isConstructor,
isDestructor, m_comment);
m_comment = QString();
if (isConstructor) {
QString stereotype;
if (isExplicit)
stereotype.append(QStringLiteral("explicit "));
if (isConstExpression)
stereotype.append(QStringLiteral("constexpr "));
stereotype.append(QStringLiteral("constructor"));
m->setStereotype(stereotype);
} else if (isConstExpression)
m->setStereotype(QStringLiteral("constexpr"));
/* For reference, Kdevelop does some more:
method->setFileName(m_fileName);
if (m_inSignals)
method->setSignal(true);
if (m_inSlots)
method->setSlot(true);
*/
}
void CppTree2Uml::parseClassSpecifier(ClassSpecifierAST* ast)
{
Uml::Visibility::Enum oldAccess = m_currentAccess;
bool oldInSlots = m_inSlots;
bool oldInSignals = m_inSignals;
QString kind = ast->classKey()->text();
m_currentAccess = Uml::Visibility::fromString(kind);
m_inSlots = false;
m_inSignals = false;
QString className;
if (!ast->name() && m_currentDeclarator && m_currentDeclarator->declaratorId()) {
className = m_currentDeclarator->declaratorId()->text().trimmed();
} else if (!ast->name()){
QFileInfo fileInfo(m_fileName);
QString shortFileName = fileInfo.baseName();
className.asprintf("(%s_%d)", shortFileName.toLocal8Bit().constData(), m_anon++);
} else {
className = ast->name()->unqualifiedName()->text().trimmed();
}
logDebug1("CppTree2Uml::parseClassSpecifier name=%1", className);
if (m_thread) {
m_thread->emitMessageToLog(QString(), QStringLiteral("class ") + className);
}
QStringList scope = scopeOfName(ast->name(), QStringList());
UMLObject *localParent = nullptr;
if (!scope.isEmpty()) {
localParent = m_doc->findUMLObject(scope.join(QStringLiteral("::")),
UMLObject::ot_Class, m_currentNamespace[m_nsCnt]);
if (!localParent)
localParent = m_doc->findUMLObject(scope.join(QStringLiteral("::")),
UMLObject::ot_Package, m_currentNamespace[m_nsCnt]);
if (!localParent) {
localParent = Import_Utils::createUMLObject(UMLObject::ot_Class, className,
m_currentNamespace[m_nsCnt],
ast->comment(), QString(), true);
localParent->setStereotype(QStringLiteral("class-or-package"));
}
m_currentNamespace[++m_nsCnt] = localParent->asUMLPackage();
}
if (className.isEmpty()) {
className = QStringLiteral("anon_") + QString::number(m_anon);
m_anon++;
}
UMLObject *o = m_doc->findUMLObject(className, UMLObject::ot_Class, m_currentNamespace[m_nsCnt]);
if (!o)
o = m_doc->findUMLObject(className, UMLObject::ot_Datatype, m_currentNamespace[m_nsCnt]);
if (o && o->stereotype() == QStringLiteral("class-or-package")) {
o->setStereotype(QString());
o->setBaseType(UMLObject::ot_Class);
}
// TODO reduce multiple finds
else
o = Import_Utils::createUMLObject(UMLObject::ot_Class, className,
m_currentNamespace[m_nsCnt],
ast->comment(), QString(), true);
UMLClassifier *klass = o->asUMLClassifier();
flushTemplateParams(klass);
if (ast->baseClause())
parseBaseClause(ast->baseClause(), klass);
m_currentScope.push_back(className);
if (++m_clsCnt > STACKSIZE) {
logError0("CppTree2Uml::parseClassSpecifier: excessive class nesting");
m_clsCnt = STACKSIZE;
}
m_currentClass[m_clsCnt] = klass;
if (++m_nsCnt > STACKSIZE) {
logError0("CppTree2Uml::parseClassSpecifier: excessive namespace nesting");
m_nsCnt = STACKSIZE;
}
m_currentNamespace[m_nsCnt] = (UMLPackage*)klass;
TreeParser::parseClassSpecifier(ast);
--m_nsCnt;
--m_clsCnt;
m_currentScope.pop_back();
// check if class is an interface
bool isInterface = true;
for(UMLOperation *op : klass->getOpList()) {
if (!op->isDestructorOperation() && op->isAbstract() == false)
isInterface = false;
}
for(UMLAttribute *attr : klass->getAttributeList()) {
if (!(attr->isStatic() && attr->getTypeName().contains(QStringLiteral("const"))))
isInterface = false;
}
if (isInterface)
klass->setBaseType(UMLObject::ot_Interface);
m_currentAccess = oldAccess;
m_inSlots = oldInSlots;
m_inSignals = oldInSignals;
if (localParent)
m_currentNamespace[m_nsCnt--] = nullptr;
}
void CppTree2Uml::parseEnumSpecifier(EnumSpecifierAST* ast)
{
NameAST *nameNode = ast->name();
if (nameNode == nullptr)
return; // skip constants
QString typeName = nameNode->unqualifiedName()->text().trimmed();
if (typeName.isEmpty())
return; // skip constants
UMLObject *o = Import_Utils::createUMLObject(UMLObject::ot_Enum, typeName,
m_currentNamespace[m_nsCnt],
ast->comment());
QList<EnumeratorAST*> l = ast->enumeratorList();
for (int i = 0; i < l.size(); ++i) {
QString enumLiteral = l.at(i)->id()->text();
QString enumLiteralValue = QString();
if (l.at(i)->expr()) {
enumLiteralValue = l.at(i)->expr()->text();
}
Import_Utils::addEnumLiteral((UMLEnum*)o, enumLiteral, QString(), enumLiteralValue);
}
}
void CppTree2Uml::parseElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST* typeSpec)
{
// This is invoked for forward declarations.
/// @todo Refine - Currently only handles class forward declarations.
/// - Using typeSpec->text() is probably not good, decode
/// the kind() instead.
QString text = typeSpec->text();
logDebug1("CppTree2Uml::parseElaboratedTypeSpecifier forward declaration of %1", text);
if (m_thread) {
m_thread->emitMessageToLog(QString(), QStringLiteral("forward declaration of ") + text);
}
text.remove(QRegularExpression(QStringLiteral("^class\\s+")));
UMLObject *o = Import_Utils::createUMLObject(UMLObject::ot_Class, text, m_currentNamespace[m_nsCnt]);
flushTemplateParams(o->asUMLClassifier());
}
void CppTree2Uml::parseDeclaration2(GroupAST* funSpec, GroupAST* storageSpec,
TypeSpecifierAST* typeSpec, InitDeclaratorAST* decl)
{
if (m_inStorageSpec)
return;
DeclaratorAST* d = decl->declarator();
if (!d)
return;
if (!d->subDeclarator() && d->parameterDeclarationClause())
return parseFunctionDeclaration(funSpec, storageSpec, typeSpec, decl);
DeclaratorAST* t = d;
while (t && t->subDeclarator())
t = t->subDeclarator();
QString id;
if (t && t->declaratorId() && t->declaratorId()->unqualifiedName())
id = t->declaratorId()->unqualifiedName()->text();
if (!scopeOfDeclarator(d, QStringList()).isEmpty()){
logDebug1("CppTree2Uml::parseDeclaration2 %1: skipping.", id);
return;
}
UMLClassifier *c = m_currentClass[m_clsCnt];
if (c == nullptr) {
logDebug1("CppTree2Uml::parseDeclaration2 %1: need a surrounding class.", id);
return;
}
QString typeName = typeOfDeclaration(typeSpec, d);
bool isFriend = false;
bool isStatic = false;
//:unused: bool isInitialized = decl->initializer() != 0;
if (storageSpec){
QList<AST*> l = storageSpec->nodeList();
for (int i = 0; i < l.size(); ++i) {
QString text = l.at(i)->text();
if (text == QStringLiteral("static"))
isStatic = true;
else if (text == QStringLiteral("mutable"))
typeName.prepend(text + QStringLiteral(" "));
else if (text == QStringLiteral("friend"))
isFriend = true;
}
}
UMLAttribute *attribute = Import_Utils::insertAttribute(c, m_currentAccess, id, typeName, m_comment, isStatic);
if (isFriend)
attribute->setStereotype(QStringLiteral("friend"));
m_comment = QString();
}
void CppTree2Uml::parseAccessDeclaration(AccessDeclarationAST * access)
{
QList<AST*> l = access->accessList();
QString accessStr = l.at(0)->text();
m_currentAccess=Uml::Visibility::fromString(accessStr);
m_inSlots = l.count() > 1 ? l.at(1)->text() == QStringLiteral("slots") : false;
m_inSignals = l.count() >= 1 ? l.at(0)->text() == QStringLiteral("signals") : false;
}
void CppTree2Uml::parseFunctionDeclaration(GroupAST* funSpec, GroupAST* storageSpec,
TypeSpecifierAST * typeSpec, InitDeclaratorAST * decl)
{
bool isFriend = false;
bool isVirtual = false;
bool isStatic = false;
bool isInline = false;
bool isPure = decl->initializer() != nullptr;
bool isConstructor = false;
bool isConstExpression = false;
bool isDestructor = false;
bool isExplicit = false;
if (funSpec){
QList<AST*> l = funSpec->nodeList();
for (int i = 0; i < l.size(); ++i) {
QString text = l.at(i)->text();
if (text == QStringLiteral("virtual"))
isVirtual = true;
else if (text == QStringLiteral("inline"))
isInline = true;
else if (text == QStringLiteral("explicit"))
isExplicit = true;
}
}
if (storageSpec){
QList<AST*> l = storageSpec->nodeList();
for (int i = 0; i < l.size(); ++i) {
QString text = l.at(i)->text();
if (text == QStringLiteral("friend")) isFriend = true;
else if (text == QStringLiteral("static")) isStatic = true;
else if (text == QStringLiteral("constexpr"))
isConstExpression = true;
}
}
DeclaratorAST* d = decl->declarator();
QString id = d->declaratorId()->unqualifiedName()->text();
UMLClassifier *c = m_currentClass[m_clsCnt];
if (c == nullptr) {
logDebug1("CppTree2Uml::parseFunctionDeclaration %1: need a surrounding class.", id);
return;
}
QString returnType = typeOfDeclaration(typeSpec, d);
// if a class has no return type it could be a constructor or a destructor
if (d && returnType.isEmpty()) {
if (id.contains(QLatin1Char('~'))) {
isDestructor = true;
id.remove(QStringLiteral(" "));
} else {
isConstructor = true;
}
}
UMLOperation *m = Import_Utils::makeOperation(c, id);
if (d->final_())
m->setFinal(true);
if (d->override_())
m->setOverride(true);
if (d->constant())
m->setConst(true);
if (isConstExpression)
m->setStereotype(QStringLiteral("constexpr"));
if (isVirtual)
m->setVirtual(true);
if (isInline)
m->setInline(true);
parseFunctionArguments(d, m);
Import_Utils::insertMethod(c, m, m_currentAccess, returnType,
isStatic, isPure, isFriend, isConstructor, isDestructor, m_comment);
if (isPure)
c->setAbstract(true);
if (isConstructor) {
QString stereotype;
if (isExplicit)
stereotype.append(QStringLiteral("explicit "));
if (isConstExpression)
stereotype.append(QStringLiteral("constexpr "));
stereotype.append(QStringLiteral("constructor"));
m->setStereotype(stereotype);
} else if (isConstExpression)
m->setStereotype(QStringLiteral("constexpr"));
m_comment = QString();
}
void CppTree2Uml::parseFunctionArguments(DeclaratorAST* declarator,
UMLOperation* method)
{
if (!declarator)
return;
ParameterDeclarationClauseAST* clause = declarator->parameterDeclarationClause();
if (clause && clause->parameterDeclarationList()){
ParameterDeclarationListAST* params = clause->parameterDeclarationList();
QList<ParameterDeclarationAST*> l(params->parameterList());
for (int i = 0; i < l.size(); ++i) {
ParameterDeclarationAST* param = l.at(i);
QString name;
if (param->declarator())
name = declaratorToString(param->declarator(), QString(), true);
QString tp = typeOfDeclaration(param->typeSpec(), param->declarator());
if (tp != QStringLiteral("void"))
Import_Utils::addMethodParameter(method, tp, name);
}
}
}
QString CppTree2Uml::typeOfDeclaration(TypeSpecifierAST* typeSpec, DeclaratorAST* declarator)
{
if (!typeSpec || !declarator)
return QString();
QString text;
text += typeSpec->text();
QList<AST*> ptrOpList = declarator->ptrOpList();
for (int i = 0; i < ptrOpList.size(); ++i) {
QString ptr = ptrOpList.at(i)->text();
text += ptr.replace(QStringLiteral(" "), QStringLiteral(""));
}
QList<AST*> arrays = declarator->arrayDimensionList();
for(int i = 0; i < arrays.size(); ++i) {
QString dim = arrays.at(i)->text();
text += dim.replace(QStringLiteral(" "), QStringLiteral(""));
}
return text;
}
void CppTree2Uml::parseBaseClause(BaseClauseAST * baseClause, UMLClassifier* klass)
{
QList<BaseSpecifierAST*> l = baseClause->baseSpecifierList();
for (int i = 0; i < l.size(); ++i) {
BaseSpecifierAST* baseSpecifier = l.at(i);
NameAST *name = baseSpecifier->name();
if (name == nullptr) {
logDebug0("CppTree2Uml::parseBaseClause: baseSpecifier->name() is NULL");
continue;
}
ClassOrNamespaceNameAST *cons = name->unqualifiedName();
if (cons == nullptr) {
logDebug0("CppTree2Uml::parseBaseClause: name->unqualifiedName() is NULL");
continue;
}
QString baseName = cons->name()->text();
Import_Utils::putAtGlobalScope(true);
UMLObject *c = Import_Utils::createUMLObject(UMLObject::ot_Class, baseName,
m_currentNamespace[m_nsCnt],
baseSpecifier->comment());
Import_Utils::putAtGlobalScope(false);
Import_Utils::createGeneralization(klass, c->asUMLClassifier());
}
}
QStringList CppTree2Uml::scopeOfName(NameAST* id, const QStringList& startScope)
{
QStringList scope = startScope;
if (id && id->classOrNamespaceNameList().count()){
if (id->isGlobal())
scope.clear();
QList<ClassOrNamespaceNameAST*> l = id->classOrNamespaceNameList();
for (int i = 0; i < l.size(); ++i) {
if (l.at(i)->name()){
scope << l.at(i)->name()->text();
}
}
}
return scope;
}
QStringList CppTree2Uml::scopeOfDeclarator(DeclaratorAST* d, const QStringList& startScope)
{
return scopeOfName(d->declaratorId(), startScope);
}
/**
* Flush template parameters pending in m_templateParams to the klass.
*/
void CppTree2Uml::flushTemplateParams(UMLClassifier *klass)
{
if (m_templateParams.count()) {
Model_Utils::NameAndType_ListIt it;
for (it = m_templateParams.begin(); it != m_templateParams.end(); ++it) {
const Model_Utils::NameAndType &nt = *it;
logDebug1("CppTree2Uml::flushTemplateParams adding template param: %1", nt.m_name);
UMLTemplate *tmpl = klass->addTemplate(nt.m_name);
tmpl->setType(nt.m_type);
}
m_templateParams.clear();
}
}
| 28,805
|
C++
|
.cpp
| 708
| 31.713277
| 115
| 0.60528
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
749,605
|
phpdebug.h
|
KDE_umbrello/lib/kdev5-php/phpdebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2014 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef PHPDEBUG_H
#define PHPDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(PHP)
#endif /* PHPDEBUG_H */
| 270
|
C++
|
.h
| 9
| 27.555556
| 63
| 0.769531
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,608
|
testproviderdebug.h
|
KDE_umbrello/lib/kdev5-php/testprovider/testproviderdebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2014 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef TESTPROVIDERDEBUG_H
#define TESTPROVIDERDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(TESTPROVIDER)
#endif /* TESTPROVIDERDEBUG_H */
| 306
|
C++
|
.h
| 9
| 31.555556
| 63
| 0.797945
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,612
|
parserdebug.h
|
KDE_umbrello/lib/kdev5-php/parser/parserdebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2014 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef PARSERDEBUG_H
#define PARSERDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(PARSER)
#endif /* PARSERDEBUG_H */
| 282
|
C++
|
.h
| 9
| 28.888889
| 63
| 0.779851
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,627
|
completiondebug.h
|
KDE_umbrello/lib/kdev5-php/completion/completiondebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2014 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef COMPLETIONDEBUG_H
#define COMPLETIONDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(COMPLETION)
#endif /* COMPLETIONDEBUG_H */
| 298
|
C++
|
.h
| 9
| 30.666667
| 63
| 0.792254
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,630
|
phpdocsdebug.h
|
KDE_umbrello/lib/kdev5-php/docs/phpdocsdebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2015 Kevin Funk <kfunk@kde.org>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef PHPDOCSDEBUG_H
#define PHPDOCSDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(DOCS)
#endif /* PHPDOCSDEBUG_H */
| 280
|
C++
|
.h
| 9
| 28.555556
| 59
| 0.777358
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,636
|
dumptypes.h
|
KDE_umbrello/lib/kdev5-php/duchain/dumptypes.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2006 Hamish Rodda <rodda@kde.org>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef DUMPTYPES_H
#define DUMPTYPES_H
#include <language/duchain/types/typesystem.h>
#include "phpduchainexport.h"
namespace Php
{
class KDEVPHPDUCHAIN_EXPORT DumpTypes : protected KDevelop::TypeVisitor
{
public:
DumpTypes();
virtual ~DumpTypes();
void dump(const KDevelop::AbstractType* type);
protected:
virtual bool preVisit(const KDevelop::AbstractType * type);
virtual void postVisit(const KDevelop::AbstractType *);
virtual void visit(const KDevelop::IntegralType *);
virtual bool visit(const KDevelop::AbstractType *);
virtual bool visit(const KDevelop::PointerType * type);
virtual void endVisit(const KDevelop::PointerType *);
virtual bool visit(const KDevelop::ReferenceType * type);
virtual void endVisit(const KDevelop::ReferenceType *);
virtual bool visit(const KDevelop::FunctionType * type);
virtual void endVisit(const KDevelop::FunctionType *);
virtual bool visit(const KDevelop::StructureType * type);
virtual void endVisit(const KDevelop::StructureType *);
virtual bool visit(const KDevelop::ArrayType * type);
virtual void endVisit(const KDevelop::ArrayType *);
private:
bool seen(const KDevelop::AbstractType* type);
class CppEditorIntegrator* m_editor;
int indent;
QSet<const KDevelop::AbstractType*> m_encountered;
};
}
#endif // DUMPTYPES_H
| 1,510
|
C++
|
.h
| 39
| 34.897436
| 71
| 0.759119
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,640
|
duchaindebug.h
|
KDE_umbrello/lib/kdev5-php/duchain/duchaindebug.h
|
/* This file is part of KDevelop
SPDX-FileCopyrightText: 2014 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef DUCHAINDEBUG_H
#define DUCHAINDEBUG_H
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(DUCHAIN)
#endif /* DUCHAINDEBUG_H */
| 286
|
C++
|
.h
| 9
| 29.333333
| 63
| 0.783088
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,645
|
integraltypeextended.h
|
KDE_umbrello/lib/kdev5-php/duchain/types/integraltypeextended.h
|
/*
This file is part of KDevelop
SPDX-FileCopyrightText: 2009 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef INTEGRALTYPEEXTENDED_H
#define INTEGRALTYPEEXTENDED_H
#include <language/duchain/types/integraltype.h>
#include <language/duchain/types/typesystemdata.h>
#include "phpduchainexport.h"
namespace Php
{
typedef KDevelop::IntegralTypeData IntegralTypeExtendedData;
/**
* Drop-In replacement for the IntegralType in KDevplatform with
* some extended logic specific for PHP
*/
class KDEVPHPDUCHAIN_EXPORT IntegralTypeExtended: public KDevelop::IntegralType
{
public:
typedef KDevelop::TypePtr<IntegralTypeExtended> Ptr;
enum PHPIntegralTypes {
TypeResource = KDevelop::IntegralType::TypeLanguageSpecific
};
/// Default constructor
IntegralTypeExtended(uint type = TypeNone);
/// Copy constructor. \param rhs type to copy
IntegralTypeExtended(const IntegralTypeExtended& rhs);
/// Constructor using raw data. \param data internal data.
IntegralTypeExtended(IntegralTypeExtendedData& data);
virtual QString toString() const;
virtual KDevelop::AbstractType* clone() const;
virtual bool equals(const KDevelop::AbstractType* rhs) const;
virtual uint hash() const;
enum {
///TODO: is that value OK?
Identity = 50
};
typedef KDevelop::IntegralTypeData Data;
typedef KDevelop::IntegralType BaseType;
protected:
TYPE_DECLARE_DATA(IntegralTypeExtended);
};
}
namespace KDevelop
{
template<>
inline Php::IntegralTypeExtended* fastCast<Php::IntegralTypeExtended*>(AbstractType* from) {
if ( !from || from->whichType() != AbstractType::TypeIntegral ) {
return 0;
} else {
return dynamic_cast<Php::IntegralTypeExtended*>(from);
}
}
}
#endif // PHPINTEGRALTYPE_H
| 1,845
|
C++
|
.h
| 56
| 29.160714
| 92
| 0.756787
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,647
|
structuretype.h
|
KDE_umbrello/lib/kdev5-php/duchain/types/structuretype.h
|
/*
This file is part of KDevelop
SPDX-FileCopyrightText: 2009 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef PHP_STRUCTURETYPE_H
#define PHP_STRUCTURETYPE_H
#include <language/duchain/types/structuretype.h>
#include <language/duchain/types/typesystemdata.h>
#include "phpduchainexport.h"
namespace Php
{
class KDEVPHPDUCHAIN_EXPORT StructureTypeData : public KDevelop::StructureTypeData
{
public:
/// Constructor
StructureTypeData()
: KDevelop::StructureTypeData()
{
}
/// Copy constructor. \param rhs data to copy
StructureTypeData( const StructureTypeData& rhs )
: KDevelop::StructureTypeData(rhs), prettyName(rhs.prettyName)
{
}
KDevelop::IndexedString prettyName;
};
/**
* Drop-In replacement for the StructureType in KDevplatform which
* makes it possible to store the type as lower case but
* keeping the "pretty" name intact.
*/
class KDEVPHPDUCHAIN_EXPORT StructureType: public KDevelop::StructureType
{
public:
typedef KDevelop::TypePtr<StructureType> Ptr;
/// Default constructor
StructureType();
/// Copy constructor. \param rhs type to copy
StructureType(const StructureType& rhs);
/// Constructor using raw data. \param data internal data.
StructureType(StructureTypeData& data);
void setPrettyName(const KDevelop::IndexedString& name);
KDevelop::IndexedString prettyName() const;
virtual QString toString() const;
virtual KDevelop::AbstractType* clone() const;
virtual uint hash() const;
enum {
///TODO: is that value OK?
Identity = 51
};
typedef StructureTypeData Data;
typedef KDevelop::StructureType BaseType;
protected:
TYPE_DECLARE_DATA(StructureType);
};
}
namespace KDevelop
{
template<>
inline Php::StructureType* fastCast<Php::StructureType*>(AbstractType* from) {
if ( !from || from->whichType() != AbstractType::TypeStructure ) {
return 0;
} else {
return dynamic_cast<Php::StructureType*>(from);
}
}
}
#endif // PHP_STRUCTURETYPE_H
| 2,093
|
C++
|
.h
| 69
| 26.478261
| 82
| 0.733899
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,655
|
typebuilder.h
|
KDE_umbrello/lib/kdev5-php/duchain/builders/typebuilder.h
|
/*
This file is part of KDevelop
SPDX-FileCopyrightText: 2008 Niko Sams <niko.sams@gmail.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef TYPEBUILDER_H
#define TYPEBUILDER_H
#include "contextbuilder.h"
#include <language/duchain/builders/abstracttypebuilder.h>
#include <language/duchain/types/functiontype.h>
#include <language/duchain/declaration.h>
#include <language/duchain/identifier.h>
namespace Php
{
typedef KDevelop::AbstractTypeBuilder<AstNode, IdentifierAst, ContextBuilder> TypeBuilderBase;
/**
* Create types from an AstNode tree.
*
* \note This builder overrides visitDeclarator, in order to support
* array types; parent classes will not have
* their visitDeclarator function called.
*/
class KDEVPHPDUCHAIN_EXPORT TypeBuilder: public TypeBuilderBase
{
public:
TypeBuilder();
~TypeBuilder();
protected:
virtual void visitClassDeclarationStatement(ClassDeclarationStatementAst* node);
virtual void visitInterfaceDeclarationStatement(InterfaceDeclarationStatementAst* node);
virtual void visitTraitDeclarationStatement(TraitDeclarationStatementAst* node);
virtual void visitClassStatement(ClassStatementAst *node);
virtual void visitClassVariable(ClassVariableAst *node);
virtual void visitConstantDeclaration(ConstantDeclarationAst* node);
virtual void visitParameter(ParameterAst *node);
virtual void visitFunctionDeclarationStatement(FunctionDeclarationStatementAst* node);
virtual void visitClosure(ClosureAst* node);
virtual void visitStatement(StatementAst* node);
virtual void visitAssignmentExpression(AssignmentExpressionAst* node);
virtual void visitStaticVar(StaticVarAst *node);
virtual void visitCatchItem(CatchItemAst *node);
/// The declaration builder implements this and updates
/// the type of the current declaration
virtual void updateCurrentType();
KDevelop::AbstractType::Ptr getTypeForNode(AstNode* node);
private:
KDevelop::FunctionType::Ptr m_currentFunctionType;
QList<KDevelop::AbstractType::Ptr> m_currentFunctionParams;
bool m_gotTypeFromDocComment;
bool m_gotReturnTypeFromDocComment;
KDevelop::FunctionType::Ptr openFunctionType(AstNode* node);
KDevelop::AbstractType::Ptr injectParseType(QString type, AstNode* node);
KDevelop::AbstractType::Ptr parseType(QString type, AstNode* node);
KDevelop::AbstractType::Ptr parseDocComment(AstNode* node, const QString& docCommentName);
QList<KDevelop::AbstractType::Ptr> parseDocCommentParams(AstNode* node);
};
}
#endif // TYPEBUILDER_H
| 2,583
|
C++
|
.h
| 58
| 40.982759
| 94
| 0.804946
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
749,660
|
includenavigationcontext.h
|
KDE_umbrello/lib/kdev5-php/duchain/navigation/includenavigationcontext.h
|
/*
SPDX-FileCopyrightText: 2009 Milian Wolff <mail@milianw.de>
SPDX-License-Identifier: LGPL-2.0-only
*/
#ifndef INCLUDENAVIGATIONCONTEXT_H
#define INCLUDENAVIGATIONCONTEXT_H
#include <language/duchain/navigation/abstractincludenavigationcontext.h>
namespace Php {
class IncludeNavigationContext : public KDevelop::AbstractIncludeNavigationContext {
public:
IncludeNavigationContext(const KDevelop::IncludeItem& item, KDevelop::TopDUContextPointer topContext);
};
}
#endif // INCLUDENAVIGATIONCONTEXT_H
| 522
|
C++
|
.h
| 14
| 34.928571
| 106
| 0.836327
|
KDE/umbrello
| 114
| 36
| 0
|
GPL-2.0
|
9/20/2024, 9:41:49 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.