doxygengenerator.cpp 11.6 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
25

26 27
#include "doxygengenerator.h"

28 29
#include <texteditor/convenience.h>

30
#include <cplusplus/BackwardsScanner.h>
31 32
#include <cplusplus/CppDocument.h>

33
#include <utils/fileutils.h>
34 35
#include <utils/qtcassert.h>

36 37
#include <QStringBuilder>
#include <QTextDocument>
38 39
#include <QDebug>

40 41
#include <limits>

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
using namespace CppTools;
using namespace CPlusPlus;

DoxygenGenerator::DoxygenGenerator()
    : m_addLeadingAsterisks(true)
    , m_generateBrief(true)
    , m_startComment(true)
    , m_style(QtStyle)
{}

void DoxygenGenerator::setStyle(DocumentationStyle style)
{
    m_style = style;
}

void DoxygenGenerator::setStartComment(bool start)
{
    m_startComment = start;
}

void DoxygenGenerator::setGenerateBrief(bool get)
{
    m_generateBrief = get;
}

void DoxygenGenerator::setAddLeadingAsterisks(bool add)
{
    m_addLeadingAsterisks = add;
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
static int lineBeforeCursor(const QTextCursor &cursor)
{
    int line, column;
    const bool converted = TextEditor::Convenience::convertPosition(cursor.document(),
                                                                    cursor.position(),
                                                                    &line,
                                                                    &column);
    QTC_ASSERT(converted, return std::numeric_limits<int>::max());

    return line - 1;
}

QString DoxygenGenerator::generate(QTextCursor cursor,
                                   const CPlusPlus::Snapshot &snapshot,
                                   const Utils::FileName &documentFilePath)
87
{
88 89
    const QTextCursor initialCursor = cursor;

90 91 92 93 94 95 96 97 98
    const QChar &c = cursor.document()->characterAt(cursor.position());
    if (!c.isLetter() && c != QLatin1Char('_'))
        return QString();

    // Try to find what would be the declaration we are interested in.
    SimpleLexer lexer;
    QTextBlock block = cursor.block();
    while (block.isValid()) {
        const QString &text = block.text();
99
        const Tokens &tks = lexer(text);
100 101 102
        foreach (const Token &tk, tks) {
            if (tk.is(T_SEMICOLON) || tk.is(T_LBRACE)) {
                // No need to continue beyond this, we might already have something meaningful.
103
                cursor.setPosition(block.position() + tk.utf16charsEnd(), QTextCursor::KeepAnchor);
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
                break;
            }
        }

        if (cursor.hasSelection())
            break;

        block = block.next();
    }

    if (!cursor.hasSelection())
        return QString();

    QString declCandidate = cursor.selectedText();
    declCandidate.replace(QChar::ParagraphSeparator, QLatin1Char('\n'));

    // Let's append a closing brace in the case we got content like 'class MyType {'
    if (declCandidate.endsWith(QLatin1Char('{')))
        declCandidate.append(QLatin1Char('}'));

124 125 126
    Document::Ptr doc = snapshot.preprocessedDocument(declCandidate.toUtf8(),
                                                      documentFilePath,
                                                      lineBeforeCursor(initialCursor));
127 128 129 130 131 132 133 134 135 136 137 138
    doc->parse(Document::ParseDeclaration);
    doc->check(Document::FastCheck);

    if (!doc->translationUnit()
            || !doc->translationUnit()->ast()
            || !doc->translationUnit()->ast()->asDeclaration()) {
        return QString();
    }

    return generate(cursor, doc->translationUnit()->ast()->asDeclaration());
}

139
QString DoxygenGenerator::generate(QTextCursor cursor, DeclarationAST *decl)
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
{
    SpecifierAST *spec = 0;
    DeclaratorAST *decltr = 0;
    if (SimpleDeclarationAST *simpleDecl = decl->asSimpleDeclaration()) {
        if (simpleDecl->declarator_list
                && simpleDecl->declarator_list->value) {
            decltr = simpleDecl->declarator_list->value;
        } else if (simpleDecl->decl_specifier_list
                   && simpleDecl->decl_specifier_list->value) {
            spec = simpleDecl->decl_specifier_list->value;
        }
    } else if (FunctionDefinitionAST * defDecl = decl->asFunctionDefinition()) {
        decltr = defDecl->declarator;
    }

    assignCommentOffset(cursor);

    QString comment;
    if (m_startComment)
        writeStart(&comment);
    writeNewLine(&comment);
    writeContinuation(&comment);

    if (decltr
            && decltr->core_declarator
            && decltr->core_declarator->asDeclaratorId()
            && decltr->core_declarator->asDeclaratorId()->name) {
        CoreDeclaratorAST *coreDecl = decltr->core_declarator;
        if (m_generateBrief)
            writeBrief(&comment, m_printer.prettyName(coreDecl->asDeclaratorId()->name->name));
        else
            writeNewLine(&comment);

        if (decltr->postfix_declarator_list
                && decltr->postfix_declarator_list->value
                && decltr->postfix_declarator_list->value->asFunctionDeclarator()) {
            FunctionDeclaratorAST *funcDecltr =
                    decltr->postfix_declarator_list->value->asFunctionDeclarator();
            if (funcDecltr->parameter_declaration_clause
                    && funcDecltr->parameter_declaration_clause->parameter_declaration_list) {
                for (ParameterDeclarationListAST *it =
                        funcDecltr->parameter_declaration_clause->parameter_declaration_list;
                     it;
                     it = it->next) {
                    ParameterDeclarationAST *paramDecl = it->value;
                    if (paramDecl->declarator
                            && paramDecl->declarator->core_declarator
                            && paramDecl->declarator->core_declarator->asDeclaratorId()
                            && paramDecl->declarator->core_declarator->asDeclaratorId()->name) {
                        DeclaratorIdAST *paramId =
                                paramDecl->declarator->core_declarator->asDeclaratorId();
                        writeContinuation(&comment);
                        writeCommand(&comment,
                                     ParamCommand,
                                     m_printer.prettyName(paramId->name->name));
                    }
                }
            }
            if (funcDecltr->symbol
                    && funcDecltr->symbol->returnType().type()
                    && !funcDecltr->symbol->returnType()->isVoidType()
                    && !funcDecltr->symbol->returnType()->isUndefinedType()) {
                writeContinuation(&comment);
                writeCommand(&comment, ReturnCommand);
            }
        }
    } else if (spec && m_generateBrief) {
        bool briefWritten = false;
        if (ClassSpecifierAST *classSpec = spec->asClassSpecifier()) {
            if (classSpec->name) {
                QString aggregate;
                if (classSpec->symbol->isClass())
                    aggregate = QLatin1String("class");
                else if (classSpec->symbol->isStruct())
                    aggregate = QLatin1String("struct");
                else
                    aggregate = QLatin1String("union");
                writeBrief(&comment,
                           m_printer.prettyName(classSpec->name->name),
                           QLatin1String("The"),
                           aggregate);
                briefWritten = true;
            }
        } else if (EnumSpecifierAST *enumSpec = spec->asEnumSpecifier()) {
            if (enumSpec->name) {
                writeBrief(&comment,
                           m_printer.prettyName(enumSpec->name->name),
                           QLatin1String("The"),
                           QLatin1String("enum"));
                briefWritten = true;
            }
        }
        if (!briefWritten)
            writeNewLine(&comment);
    } else {
        writeNewLine(&comment);
    }

    writeEnd(&comment);

    return comment;
}

QChar DoxygenGenerator::startMark() const
{
    if (m_style == QtStyle)
        return QLatin1Char('!');
    return QLatin1Char('*');
}

QChar DoxygenGenerator::styleMark() const
{
252
    if (m_style == QtStyle || m_style == CppStyleA || m_style == CppStyleB)
253 254 255 256 257 258 259 260 261 262 263
        return QLatin1Char('\\');
    return QLatin1Char('@');
}

QString DoxygenGenerator::commandSpelling(Command command)
{
    if (command == ParamCommand)
        return QLatin1String("param ");
    if (command == ReturnCommand)
        return QLatin1String("return ");

264
    QTC_ASSERT(command == BriefCommand, return QString());
265 266 267 268 269
    return QLatin1String("brief ");
}

void DoxygenGenerator::writeStart(QString *comment) const
{
270 271 272 273 274 275
    if (m_style == CppStyleA)
        comment->append(QLatin1String("///"));
    if (m_style == CppStyleB)
        comment->append(QLatin1String("//!"));
    else
        comment->append(offsetString() % QLatin1String("/*") % startMark());
276 277 278 279
}

void DoxygenGenerator::writeEnd(QString *comment) const
{
280 281 282 283 284 285
    if (m_style == CppStyleA)
        comment->append(QLatin1String("///"));
    else if (m_style == CppStyleB)
        comment->append(QLatin1String("//!"));
    else
        comment->append(offsetString() % QLatin1String(" */"));
286 287 288 289
}

void DoxygenGenerator::writeContinuation(QString *comment) const
{
290 291 292 293 294
    if (m_style == CppStyleA)
        comment->append(offsetString() % QLatin1String("///"));
    else if (m_style == CppStyleB)
        comment->append(offsetString() % QLatin1String("//!"));
    else if (m_addLeadingAsterisks)
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        comment->append(offsetString() % QLatin1String(" *"));
    else
        comment->append(offsetString() % QLatin1String("  "));
}

void DoxygenGenerator::writeNewLine(QString *comment) const
{
    comment->append(QLatin1Char('\n'));
}

void DoxygenGenerator::writeCommand(QString *comment,
                                    Command command,
                                    const QString &commandContent) const
{
    comment->append(QLatin1Char(' ')
                    % styleMark()
                    % commandSpelling(command)
                    % commandContent
                    % QLatin1Char('\n'));
}

void DoxygenGenerator::writeBrief(QString *comment,
                                  const QString &brief,
                                  const QString &prefix,
                                  const QString &suffix)
{
    QString content = prefix % QLatin1Char(' ') % brief % QLatin1Char(' ') % suffix;
    writeCommand(comment, BriefCommand, content.trimmed());
}

void DoxygenGenerator::assignCommentOffset(QTextCursor cursor)
{
    if (cursor.hasSelection()) {
        if (cursor.anchor() < cursor.position())
            cursor.setPosition(cursor.anchor());
    }

332 333
    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
    m_commentOffset = cursor.selectedText();
334 335 336 337
}

QString DoxygenGenerator::offsetString() const
{
338
    return m_commentOffset;
339
}