From 293297269f976b3b1a82c306c099fda9b0f095f5 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Thu, 1 Feb 2024 10:13:39 +0100 Subject: [PATCH 0001/1060] Tests: Provide example tasks file Change-Id: I529102dba9cd259de25d69a527e3ac2a0e1a9380 Reviewed-by: hjk --- tests/manual/otherfiles/dummy_taskfile.tasks | 65 ++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 tests/manual/otherfiles/dummy_taskfile.tasks diff --git a/tests/manual/otherfiles/dummy_taskfile.tasks b/tests/manual/otherfiles/dummy_taskfile.tasks new file mode 100644 index 00000000000..1317a0e4c19 --- /dev/null +++ b/tests/manual/otherfiles/dummy_taskfile.tasks @@ -0,0 +1,65 @@ +ba/Z6xF/M0IIRI2d5pvaSyknCSyOAissFvJYsntwrQ.h 4762 other unused +/iQTQFzlxBsJGnfJbt5rCA8YH4oe7rqvyW3hCrWO84QN.cpp 4104 error dummy information +/2Sm4hfyhGRG8TAXhYv874ysHRuEuabzjz1/gdng7MHZIhyp2S.h 9442 other syntax error +/Oc2S9dMhbZDZymQChSiiv3Brqqp1FzSUUfnxhFHAvnwk3rSbMd.cpp 282 warn missing information +/igZwSBi65YI9RZCkYucjgnA0nFzyhwQHsR5zIHbCFBz69oSo.h 2266 error missing information +/Z6hIBPwiXv3lxn2WggqDP62WLthQxPdQmzjSHd.cpp 9289 error unknown error +sdef/rpx9V404NdbmV/9Ph7jXqAsK7wsB31y6Tx9KIBG.h 8316 other missing information +/tRdL//67g/paZsnLpdGN4J6q6/RdBYYVXSpP1djxfg3w.cpp 4717 error not found +/EdL/stJAk2wbrL1V21xUSbfX3OVV5hWDz0O9r6fYsV93yU.h 1894 warn unknown error +/aAokPAGz8zR6AiBN19mndJRs7w84oQlxUFkBSYrn.cpp 1102 other syntax error +/6uwjGfQ2o/j5/SEUbs57xxqxIMSl14deuLY7km5oLBc.h 9359 warn unused +/nBQ8eQ63Sb4HZc5lE2yvWZwck6OSx9zwT9hpzL.cpp 2969 warn syntax error +sdf/SqzyeibvrCAHNelVI715AtjFC83Q4feZpepvCMr78Kb8.h 3691 error unknown error +/xhlVpBsiOkm0ZmH01wXXk0QHImeJbcCOF7/M4f.cpp 1038 other unused +/8gvIBNXwX3l224T/4l75YAzmOvMcyHW/plILha7.h 2525 warn unused +/uu46Fvj6IwAptMDDaN23HzoyBQ61Ls917LOoWMZfhLX.cpp 4573 other dummy information +/rJcO7WZR2fGNYO3pTvnyXOFELxAfsuSCffRb/aMfm5.h 5148 warn missing information +/Srj2krdE/UPV1OYlZSYOu6w10kgzBscAfqw//9776pSGa8L76.cpp 4690 warn dummy information +/VlJRNSuHVpjFqCQVVWPf7R4gOSoRuGPxtGpO/xjuLceiHf.h 9683 error syntax error +sdf/Q/YgTtEdgAj9PzbPyBF604wEZSYXrciun69ut57e.cpp 8272 error not found +/rapyyxw6cXoUd9XHWCx4V4IwO9g0LlVyXFmh5sXJk8xvuZCq.h 4329 warn syntax error +/TVizFLbV7VZVeX56p3Mc2olEeNWSEIpI9iZaBhmgm/.cpp 692 error not found +sdf/Yaoc6iF24WOdamUb5j2/SDfeBoW5U92nig/6XkpE3pyEX9m.h 8336 warn syntax error +/rnUQ3Ew7J8yWckFBbfMg8qAMuEMgTIv0UryeYMw.cpp 8612 error unused +/6AJYrSTsALywqx8TinQxxsfu7Qu19xgb4Shm3uxUVmOC.h 3948 warn dummy information +/owg0bC1TF0ImRR7acppvAJhdBT6cUadw8696pOVgpx2oa40.cpp 4850 error not found +//LbsNqHaAIdYRDMwBKr7nmZ1b4njJTb1h1WSl60F.h 4893 warn missing information +/ivHIukAf5HoFD6cxs34JkKnHrlrxD73WRi7UvfzBQt.cpp 7724 warn dummy information +/Tivy85ab71MZu5bta8ordtMzAa38Y8LAZcs61eJLHNXP.h 7556 error unused +sdf/RZEHytd0Kmq5VUCoLqNAhAI3hlZlxltDTDdWU3WV2yuktyfg.cpp 6721 error dummy information +/ENk8j0noHhsZbTlqRJ46cDhjZ7PHDhfa7te8n1OsXgVO.h 5374 error missing information +/edEInJsvjm3dqakU9oyYMT7Nybmet4L6olT/dedWLDltWEjz.cpp 9621 other missing information +/q1MlgSvwv8Ikq4Bjcqa0X9OY/q1GRQ5ARhejOOZKu15XDVb7/M.h 1068 error dummy information +/EvcJN3d5iiIP4H2TLC6ssHeQoTUf/HHC1/gq8m.cpp 7062 warn dummy information +sdfxc/XISMZsHJSJNL1jKTYE1ZyJK9ekBnx4WpyrVdNjmRasxm.h 8513 error unknown error +/uJWF20pUZPpedDMfGNz0cCCwIymTW1JtxK5ut4fHScwq.cpp 1234 error syntax error +/kgQCRBmcKWNd966rPIz4IPfekDqxjQm1eAZ7/Y3Vl8.h 476 error unknown error +/I3aGZ2vLcuMjmcUI40eB4XTwsYQ34sSIgcj28SRPVRyu8.cpp 2175 error dummy information +/q3M0KxZi3Umo2CWe9EzDqMo4LcNVeQhrnV2Yu7zR.h 3969 error syntax error +/tcVCRlsoFo61oIMMwP8seWKpKfC8KskferbtgI.cpp 10 warn not found +sdf/wQSRjPZZJwzREWemLQ96RisR0x2HKpVvZTohxwWRVevBIrtN2.h 5836 error unknown error +/cgMEkzRs9dJfJZvejXqppDjyhbT8gs6/Q07mSJPOQD.cpp 3882 error unknown error +/CBipJCtJq5JHOtz5njHmH6eM5dvPjRQ3KO0PDXUIghI3rO6pm.h 3818 error not found +/ucFWsPMwDK3d8OuKH2d5kfrHTsz2Nlw8wZV4MfNzm.cpp 1303 error missing information +/eiWeH306mDV9AZKSqRV/h2OhJlmXuvPUuLrmUoDfvK.h 887 warn dummy information +/nSaLMeLNeFgWkppVcacpGzQbnwDgnHy43/P0zDb6y/4PWkIyKq.cpp 7644 error unknown error +/BF1mxdQbpB7spT8uj/XPjkxRyKJXO53v0RDs3c.h 4909 other unknown error +/HLpMI/AdAabKQJgZ3CfoZ3IkUH8d2AKak6WME/Ff2.cpp 92 error dummy information +/rM2GH8fkUddRFYRc4ZAxoNmZVnccOQ13sRTAMp.h 2487 error dummy information +/pQ4QD264U3z1H1odOUGSuDpvq9FIMlonytSsNpUnVkBMTl.cpp 835 error syntax error +/olSx6ZAKh7x43uFC6TeSqfdRsnNHozb1Oa8jgHuAx.h 8006 error unknown error +/36QcXAGehPbcSpreu8Dps1jTYaGLhYokbga3Ez.cpp 1219 warn missing information +/kLtmnkB88UvQNB2tNpQkEIRBPk2w9VQY4XKWwkcNsGYN.h 9212 warn dummy information +/HdhlYekmcIsnI4752ng8bT/sJEzpP/rbqrOLJ47.cpp 2818 warn syntax error +/nSQVu9In4/D3Mo2JQfjLuMzz49ZC1K/OQkO0t6Vibrl.h 6785 error missing information +/uOyhgr9Y5cvev6HeW9GAiy2g6QMDzUBABLNb5KIHLaJiKHsUXu.cpp 5833 warn syntax error +/vej4BOeRTak5ILrWzxPhYLXCx7akC8LXkVKwbJyok4r80tstgr.h 1863 other syntax error +/jGz0VyhokwjE4mmQSMpPoKK5teActVfmL2CGupQT39.cpp 175 warn unknown error +/PCcGDSa7h208wlJz1wa81nREtA/Kx/ZAMraQQ9QYTg.h 7977 other unused +/OaEQzW35Ng2yeSqs41f6ji/RWSnx71G4BlmlWX.cpp 3650 warn not found +/1e6Ric7K9WElXkBE6ymSMPXtFuu86QbI8mYAEy63c1Asp/hO.h 3725 error unknown error +/qaPzTGefWpHBNGX3XWne5zBkkLCBiMi3mm9x2cIU9l9szD.cpp 1338 warn syntax error +/YAPg7LHxjrOeBJ4CZBVkoXR6lKI7jrSV5bD7kfXOAf8mzM.h 3389 error unused +/IMjUnSaqSsKs5xCzhDcrgk1saAcr2wKnJZ3tyxI6VbSeX.cpp 2404 other unknown error +/5rQ9UzSyJFvYZhyI9sItDZHnBrANcz84rtDfDfJh.h 7293 warn not found From c9ea3c6a51a4d1c3fa734ce1ec3afeee8d7ae367 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Tue, 6 Feb 2024 15:01:00 +0100 Subject: [PATCH 0002/1060] OutputWindow: Add "clear" to all context menus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I989b15eb602d3224813510eacf020e3fdc90c650 Reviewed-by: Orgad Shaneh Reviewed-by: André Hartmann Reviewed-by: --- src/plugins/coreplugin/outputwindow.cpp | 18 +++++++++++++ src/plugins/coreplugin/outputwindow.h | 2 ++ src/plugins/vcsbase/vcsoutputwindow.cpp | 35 +++++++------------------ 3 files changed, 29 insertions(+), 26 deletions(-) diff --git a/src/plugins/coreplugin/outputwindow.cpp b/src/plugins/coreplugin/outputwindow.cpp index 7e32bcc807d..ca0de974560 100644 --- a/src/plugins/coreplugin/outputwindow.cpp +++ b/src/plugins/coreplugin/outputwindow.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -195,6 +196,8 @@ void OutputWindow::handleLink(const QPoint &pos) d->formatter.handleLink(href); } +void OutputWindow::adaptContextMenu(QMenu *, const QPoint &) {} + void OutputWindow::mouseReleaseEvent(QMouseEvent *e) { if (d->linksActive && d->mouseButtonPressed == Qt::LeftButton) @@ -279,6 +282,21 @@ void OutputWindow::wheelEvent(QWheelEvent *e) updateMicroFocus(); } +void OutputWindow::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = createStandardContextMenu(event->pos()); + menu->setAttribute(Qt::WA_DeleteOnClose); + + adaptContextMenu(menu, event->pos()); + + menu->addSeparator(); + QAction *clearAction = menu->addAction(Tr::tr("Clear")); + connect(clearAction, &QAction::triggered, this, [this] { clear(); }); + clearAction->setEnabled(!document()->isEmpty()); + + menu->popup(event->globalPos()); +} + void OutputWindow::setBaseFont(const QFont &newFont) { float zoom = fontZoom(); diff --git a/src/plugins/coreplugin/outputwindow.h b/src/plugins/coreplugin/outputwindow.h index 83681a988e4..cfcea8aae05 100644 --- a/src/plugins/coreplugin/outputwindow.h +++ b/src/plugins/coreplugin/outputwindow.h @@ -75,6 +75,7 @@ public slots: protected: virtual void handleLink(const QPoint &pos); + virtual void adaptContextMenu(QMenu *menu, const QPoint &pos); private: QMimeData *createMimeDataFromSelection() const override; @@ -85,6 +86,7 @@ private: void resizeEvent(QResizeEvent *e) override; void showEvent(QShowEvent *) override; void wheelEvent(QWheelEvent *e) override; + void contextMenuEvent(QContextMenuEvent *event) override; using QPlainTextEdit::setFont; // call setBaseFont instead, which respects the zoom factor void enableUndoRedo(); diff --git a/src/plugins/vcsbase/vcsoutputwindow.cpp b/src/plugins/vcsbase/vcsoutputwindow.cpp index 4b6eab6fb17..fdd91a5ed0d 100644 --- a/src/plugins/vcsbase/vcsoutputwindow.cpp +++ b/src/plugins/vcsbase/vcsoutputwindow.cpp @@ -79,7 +79,7 @@ public: const FilePath &repository); protected: - void contextMenuEvent(QContextMenuEvent *event) override; + void adaptContextMenu(QMenu *menu, const QPoint &pos) override; void handleLink(const QPoint &pos) override; private: @@ -138,15 +138,15 @@ QString OutputWindowPlainTextEdit::identifierUnderCursor(const QPoint &widgetPos return endPos > startPos ? block.mid(startPos, endPos - startPos) : QString(); } -void OutputWindowPlainTextEdit::contextMenuEvent(QContextMenuEvent *event) +void OutputWindowPlainTextEdit::adaptContextMenu(QMenu *menu, const QPoint &pos) { - const QString href = anchorAt(event->pos()); - QMenu *menu = href.isEmpty() ? createStandardContextMenu(event->pos()) : new QMenu; - menu->setAttribute(Qt::WA_DeleteOnClose); + const QString href = anchorAt(pos); + if (!href.isEmpty()) + menu->clear(); // Add 'open file' FilePath repo; - const QString token = identifierUnderCursor(event->pos(), &repo); + const QString token = identifierUnderCursor(pos, &repo); if (!repo.isEmpty() && !href.isEmpty()) m_parser->fillLinkContextMenu(menu, repo, href); QAction *openAction = nullptr; @@ -157,26 +157,9 @@ void OutputWindowPlainTextEdit::contextMenuEvent(QContextMenuEvent *event) if (repo.isFile()) { menu->addSeparator(); openAction = menu->addAction(Tr::tr("Open \"%1\"").arg(repo.nativePath())); - openAction->setData(repo.absoluteFilePath().toVariant()); - } - } - QAction *clearAction = nullptr; - if (href.isEmpty()) { - // Add 'clear' - menu->addSeparator(); - clearAction = menu->addAction(Tr::tr("Clear")); - } - - // Run - QAction *action = menu->exec(event->globalPos()); - if (action) { - if (action == clearAction) { - clear(); - return; - } - if (action == openAction) { - const auto fileName = FilePath::fromVariant(action->data()); - EditorManager::openEditor(fileName); + connect(openAction, &QAction::triggered, this, [fp = repo.absoluteFilePath()] { + EditorManager::openEditor(fp); + }); } } } From e2756fde8b3fb1eb6d9750b24d7cbd4154f9d4d1 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 5 Feb 2024 16:57:56 +0100 Subject: [PATCH 0003/1060] CppEditor: Add quickfix for converting a function call ... to a Qt meta-method invocation. Fixes: QTCREATORBUG-15972 Change-Id: Id84c83c5832cef32a877a451b0931ec47d2afe9d Reviewed-by: Christian Stenger --- src/plugins/cppeditor/cppquickfix_test.cpp | 87 ++++++++++ src/plugins/cppeditor/cppquickfix_test.h | 3 + src/plugins/cppeditor/cppquickfixes.cpp | 193 ++++++++++++++++++--- src/plugins/cppeditor/cppquickfixes.h | 9 + 4 files changed, 267 insertions(+), 25 deletions(-) diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp index b0064ab790a..80a4af36db1 100644 --- a/src/plugins/cppeditor/cppquickfix_test.cpp +++ b/src/plugins/cppeditor/cppquickfix_test.cpp @@ -9468,4 +9468,91 @@ void QuickfixTest::testMoveComments() QuickFixOperationTest(documents, &factory, {}, {}, failMessage); } +void QuickfixTest::testConvertToMetaMethodInvocation_data() +{ + QTest::addColumn("input"); + QTest::addColumn("expected"); + + // ^ marks the cursor locations. + // $ marks the replacement regions. + // The quoted string in the comment is the data tag. + // The rest of the comment is the replacement string. + const QByteArray allCases = R"( +class C { +public: + C() { + $this->^aSignal()$; // "signal from region on pointer to object" QMetaObject::invokeMethod(this, "aSignal") + C c; + $c.^aSignal()$; // "signal from region on object value" QMetaObject::invokeMethod(&c, "aSignal") + $(new C)->^aSignal()$; // "signal from region on expression" QMetaObject::invokeMethod((new C), "aSignal") + $emit this->^aSignal()$; // "signal from region, with emit" QMetaObject::invokeMethod(this, "aSignal") + $Q_EMIT this->^aSignal()$; // "signal from region, with Q_EMIT" QMetaObject::invokeMethod(this, "aSignal") + $this->^aSlot()$; // "slot from region" QMetaObject::invokeMethod(this, "aSlot") + $this->^noArgs()$; // "Q_SIGNAL, no arguments" QMetaObject::invokeMethod(this, "noArgs") + $this->^oneArg(0)$; // "Q_SLOT, one argument" QMetaObject::invokeMethod(this, "oneArg", Q_ARG(int, 0)) + $this->^twoArgs(0, c)$; // "Q_INVOKABLE, two arguments" QMetaObject::invokeMethod(this, "twoArgs", Q_ARG(int, 0), Q_ARG(C, c)) + this->^notInvokable(); // "not invokable" + } + +signals: + void aSignal(); + +private slots: + void aSlot(); + +private: + Q_SIGNAL void noArgs(); + Q_SLOT void oneArg(int index); + Q_INVOKABLE void twoArgs(int index, const C &value); + void notInvokable(); +}; +)"; + + qsizetype nextCursor = allCases.indexOf('^'); + while (nextCursor != -1) { + const int commentStart = allCases.indexOf("//", nextCursor); + QVERIFY(commentStart != -1); + const int tagStart = allCases.indexOf('"', commentStart + 2); + QVERIFY(tagStart != -1); + const int tagEnd = allCases.indexOf('"', tagStart + 1); + QVERIFY(tagEnd != -1); + QByteArray input = allCases; + QByteArray output = allCases; + input.replace(nextCursor, 1, "@"); + const QByteArray tag = allCases.mid(tagStart + 1, tagEnd - tagStart - 1); + const int prevNewline = allCases.lastIndexOf('\n', nextCursor); + const int regionStart = allCases.lastIndexOf('$', nextCursor); + bool hasReplacement = false; + if (regionStart != -1 && regionStart > prevNewline) { + const int regionEnd = allCases.indexOf('$', regionStart + 1); + QVERIFY(regionEnd != -1); + const int nextNewline = allCases.indexOf('\n', tagEnd); + QVERIFY(nextNewline != -1); + const QByteArray replacement + = allCases.mid(tagEnd + 1, nextNewline - tagEnd - 1).trimmed(); + output.replace(regionStart, regionEnd - regionStart, replacement); + hasReplacement = true; + } + static const auto matcher = [](char c) { return c == '^' || c == '$'; }; + input.removeIf(matcher); + if (hasReplacement) { + output.removeIf(matcher); + output.prepend("#include \n\n"); + } else { + output.clear(); + } + QTest::newRow(tag.data()) << input << output; + nextCursor = allCases.indexOf('^', nextCursor + 1); + } +} + +void QuickfixTest::testConvertToMetaMethodInvocation() +{ + QFETCH(QByteArray, input); + QFETCH(QByteArray, expected); + + ConvertToMetaMethodCall factory; + QuickFixOperationTest({CppTestDocument::create("file.cpp", input, expected)}, &factory); +} + } // namespace CppEditor::Internal::Tests diff --git a/src/plugins/cppeditor/cppquickfix_test.h b/src/plugins/cppeditor/cppquickfix_test.h index cc589f1908a..e677d88af24 100644 --- a/src/plugins/cppeditor/cppquickfix_test.h +++ b/src/plugins/cppeditor/cppquickfix_test.h @@ -224,6 +224,9 @@ private slots: void testMoveComments_data(); void testMoveComments(); + + void testConvertToMetaMethodInvocation_data(); + void testConvertToMetaMethodInvocation(); }; } // namespace Tests diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp index 74862772e5a..b2f01eaad47 100644 --- a/src/plugins/cppeditor/cppquickfixes.cpp +++ b/src/plugins/cppeditor/cppquickfixes.cpp @@ -221,8 +221,10 @@ Namespace *isNamespaceFunction(const LookupContext &context, Function *function) } // Given include is e.g. "afile.h" or (quotes/angle brackets included!). -void insertNewIncludeDirective(const QString &include, CppRefactoringFilePtr file, - const Document::Ptr &cppDocument) +static void insertNewIncludeDirective(const QString &include, + CppRefactoringFilePtr file, + const Document::Ptr &cppDocument, + ChangeSet &changes) { // Find optimal position unsigned newLinesToPrepend = 0; @@ -245,10 +247,7 @@ void insertNewIncludeDirective(const QString &include, CppRefactoringFilePtr fil const QString textToInsert = prependedNewLines + includeLine + appendedNewLines; // Insert - ChangeSet changes; changes.insert(insertPosition, textToInsert); - file->setChangeSet(changes); - file->apply(); } bool nameIncludesOperatorName(const Name *name) @@ -322,6 +321,32 @@ QString nameString(const NameAST *name) return CppCodeStyleSettings::currentProjectCodeStyleOverview().prettyName(name->name); } +static FullySpecifiedType typeOfExpr(const ExpressionAST *expr, + const CppRefactoringFilePtr &file, + const Snapshot &snapshot, + const LookupContext &context) +{ + TypeOfExpression typeOfExpression; + typeOfExpression.init(file->cppDocument(), snapshot, context.bindings()); + Scope *scope = file->scopeAt(expr->firstToken()); + const QList result = typeOfExpression( + file->textOf(expr).toUtf8(), scope, TypeOfExpression::Preprocess); + if (result.isEmpty()) + return {}; + + SubstitutionEnvironment env; + env.setContext(context); + env.switchScope(result.first().scope()); + ClassOrNamespace *con = typeOfExpression.context().lookupType(scope); + if (!con) + con = typeOfExpression.context().globalNamespace(); + UseMinimalNames q(con); + env.enter(&q); + + Control *control = context.bindings()->control().get(); + return rewriteType(result.first().type(), &env, control); +} + // FIXME: Needs to consider the scope at the insertion site. QString declFromExpr(const TypeOrExpr &typeOrExpr, const CallAST *call, const NameAST *varName, const Snapshot &snapshot, const LookupContext &context, @@ -338,25 +363,7 @@ QString declFromExpr(const TypeOrExpr &typeOrExpr, const CallAST *call, const Na return {}; }; const auto getTypeOfExpr = [&](const ExpressionAST *expr) -> FullySpecifiedType { - TypeOfExpression typeOfExpression; - typeOfExpression.init(file->cppDocument(), snapshot, context.bindings()); - Scope *scope = file->scopeAt(expr->firstToken()); - const QList result = typeOfExpression( - file->textOf(expr).toUtf8(), scope, TypeOfExpression::Preprocess); - if (result.isEmpty()) - return {}; - - SubstitutionEnvironment env; - env.setContext(context); - env.switchScope(result.first().scope()); - ClassOrNamespace *con = typeOfExpression.context().lookupType(scope); - if (!con) - con = typeOfExpression.context().globalNamespace(); - UseMinimalNames q(con); - env.enter(&q); - - Control *control = context.bindings()->control().get(); - return rewriteType(result.first().type(), &env, control); + return typeOfExpr(expr, file, snapshot, context); }; const Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview(); @@ -1791,7 +1798,10 @@ void AddIncludeForUndefinedIdentifierOp::perform() CppRefactoringChanges refactoring(snapshot()); CppRefactoringFilePtr file = refactoring.cppFile(filePath()); - insertNewIncludeDirective(m_include, file, semanticInfo().doc); + ChangeSet changes; + insertNewIncludeDirective(m_include, file, semanticInfo().doc, changes); + file->setChangeSet(changes); + file->apply(); } AddForwardDeclForUndefinedIdentifierOp::AddForwardDeclForUndefinedIdentifierOp( @@ -9801,6 +9811,138 @@ void MoveFunctionComments::doMatch(const CppQuickFixInterface &interface, } } +namespace { +class ConvertToMetaMethodCallOp : public CppQuickFixOperation +{ +public: + ConvertToMetaMethodCallOp(const CppQuickFixInterface &interface, CallAST *callAst) + : CppQuickFixOperation(interface), m_callAst(callAst) + { + setDescription(Tr::tr("Convert function call to Qt meta-method invocation")); + } + +private: + void perform() override + { + // Construct the argument list. + Overview ov; + QStringList arguments; + for (ExpressionListAST *it = m_callAst->expression_list; it; it = it->next) { + if (!it->value) + return; + const FullySpecifiedType argType + = typeOfExpr(it->value, currentFile(), snapshot(), context()); + if (!argType.isValid()) + return; + arguments << QString::fromUtf8("Q_ARG(%1, %2)") + .arg(ov.prettyType(argType), currentFile()->textOf(it->value)); + } + QString argsString = arguments.join(", "); + if (!argsString.isEmpty()) + argsString.prepend(", "); + + // Construct the replace string. + const auto memberAccessAst = m_callAst->base_expression->asMemberAccess(); + QTC_ASSERT(memberAccessAst, return); + QString baseExpr = currentFile()->textOf(memberAccessAst->base_expression); + const FullySpecifiedType baseExprType + = typeOfExpr(memberAccessAst->base_expression, currentFile(), snapshot(), context()); + if (!baseExprType.isValid()) + return; + if (!baseExprType->asPointerType()) + baseExpr.prepend('&'); + const QString functionName = currentFile()->textOf(memberAccessAst->member_name); + const QString qMetaObject = "QMetaObject"; + const QString newCall = QString::fromUtf8("%1::invokeMethod(%2, \"%3\"%4)") + .arg(qMetaObject, baseExpr, functionName, argsString); + + // Determine the start and end positions of the replace operation. + // If the call is preceded by an "emit" keyword, that one has to be removed as well. + int firstToken = m_callAst->firstToken(); + if (firstToken > 0) + switch (semanticInfo().doc->translationUnit()->tokenKind(firstToken - 1)) { + case T_EMIT: case T_Q_EMIT: --firstToken; break; + default: break; + } + const TranslationUnit *const tu = semanticInfo().doc->translationUnit(); + const int startPos = tu->getTokenPositionInDocument(firstToken, textDocument()); + const int endPos = tu->getTokenPositionInDocument(m_callAst->lastToken(), textDocument()); + + // Replace the old call with the new one. + ChangeSet changes; + changes.replace(startPos, endPos, newCall); + + // Insert include for QMetaObject, if necessary. + const Identifier qMetaObjectId(qPrintable(qMetaObject), qMetaObject.size()); + Scope * const scope = currentFile()->scopeAt(firstToken); + const QList results = context().lookup(&qMetaObjectId, scope); + bool isDeclared = false; + for (const LookupItem &item : results) { + if (Symbol *declaration = item.declaration(); declaration && declaration->asClass()) { + isDeclared = true; + break; + } + } + if (!isDeclared) { + insertNewIncludeDirective('<' + qMetaObject + '>', currentFile(), semanticInfo().doc, + changes); + } + + // Apply the changes. + currentFile()->setChangeSet(changes); + currentFile()->apply(); + } + + const CallAST * const m_callAst; +}; +} // namespace + +void ConvertToMetaMethodCall::doMatch(const CppQuickFixInterface &interface, + TextEditor::QuickFixOperations &result) +{ + const Document::Ptr &cppDoc = interface.currentFile()->cppDocument(); + const QList path = ASTPath(cppDoc)(interface.cursor()); + if (path.isEmpty()) + return; + + // Are we on a member function call? + CallAST *callAst = nullptr; + for (auto it = path.crbegin(); it != path.crend(); ++it) { + if ((callAst = (*it)->asCall())) + break; + } + if (!callAst || !callAst->base_expression) + return; + ExpressionAST *baseExpr = nullptr; + const NameAST *nameAst = nullptr; + if (const MemberAccessAST * const ast = callAst->base_expression->asMemberAccess()) { + baseExpr = ast->base_expression; + nameAst = ast->member_name; + } + if (!baseExpr || !nameAst || !nameAst->name) + return; + + // Locate called function and check whether it is invokable. + Scope *scope = cppDoc->globalNamespace(); + for (auto it = path.crbegin(); it != path.crend(); ++it) { + if (const CompoundStatementAST * const stmtAst = (*it)->asCompoundStatement()) { + scope = stmtAst->symbol; + break; + } + } + const LookupContext context(cppDoc, interface.snapshot()); + TypeOfExpression exprType; + exprType.setExpandTemplates(true); + exprType.init(cppDoc, interface.snapshot()); + const QList typeMatches = exprType(callAst->base_expression, cppDoc, scope); + for (const LookupItem &item : typeMatches) { + if (const auto func = item.type()->asFunctionType(); func && func->methodKey()) { + result << new ConvertToMetaMethodCallOp(interface, callAst); + return; + } + } +} + void createCppQuickFixes() { new AddIncludeForUndefinedIdentifier; @@ -9860,6 +10002,7 @@ void createCppQuickFixes() new GenerateConstructor; new ConvertCommentStyle; new MoveFunctionComments; + new ConvertToMetaMethodCall; } void destroyCppQuickFixes() diff --git a/src/plugins/cppeditor/cppquickfixes.h b/src/plugins/cppeditor/cppquickfixes.h index 953cfa5468e..99904ffcb19 100644 --- a/src/plugins/cppeditor/cppquickfixes.h +++ b/src/plugins/cppeditor/cppquickfixes.h @@ -617,5 +617,14 @@ private: TextEditor::QuickFixOperations &result) override; }; +//! Converts a normal function call into a meta method invocation, if the functions is +//! marked as invokable. +class ConvertToMetaMethodCall : public CppQuickFixFactory +{ +private: + void doMatch(const CppQuickFixInterface &interface, + TextEditor::QuickFixOperations &result) override; +}; + } // namespace Internal } // namespace CppEditor From 971bcb1a5abd396819510644e55ef437978adcd5 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Fri, 9 Feb 2024 06:11:27 +0100 Subject: [PATCH 0004/1060] TextEditor: fix multi text cursor unindent via backspace Change-Id: Iec2e9251b977ccbd7433009ac3e706a9327c704c Reviewed-by: Marcus Tillmanns --- src/plugins/texteditor/texteditor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 1ed6d0db513..1184749e86e 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -6846,7 +6846,7 @@ void TextEditorWidgetPrivate::handleBackspaceKey() if (cursorWithinSnippet) m_snippetOverlay->accept(); cursorWithinSnippet = false; - q->unindent(); + c = m_document->unindent(MultiTextCursor({c})).mainCursor(); } handled = true; } From 7a055a2f0ad7bd99eb5629f8ce6dfa5ae7a27080 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Tue, 6 Feb 2024 15:21:13 +0100 Subject: [PATCH 0005/1060] OutputWindow: Add "Save Contents" to context menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit And give individual output windows the option to set a default file name. Change-Id: If3090063055c1b37f4f2d63b971fe0476f11806e Reviewed-by: Orgad Shaneh Reviewed-by: André Hartmann Reviewed-by: Reviewed-by: Tasuku Suzuki --- src/plugins/coreplugin/outputwindow.cpp | 14 ++++++++++++++ src/plugins/coreplugin/outputwindow.h | 2 ++ src/plugins/projectexplorer/appoutputpane.cpp | 2 ++ .../projectexplorer/compileoutputwindow.cpp | 2 ++ 4 files changed, 20 insertions(+) diff --git a/src/plugins/coreplugin/outputwindow.cpp b/src/plugins/coreplugin/outputwindow.cpp index ca0de974560..dbbcdde585a 100644 --- a/src/plugins/coreplugin/outputwindow.cpp +++ b/src/plugins/coreplugin/outputwindow.cpp @@ -73,6 +73,8 @@ public: QTimer scrollTimer; QElapsedTimer lastMessage; QHash> taskPositions; + //: default file name suggested for saving text from output views + QString outputFileNameHint{Tr::tr("output.txt")}; }; } // namespace Internal @@ -289,6 +291,13 @@ void OutputWindow::contextMenuEvent(QContextMenuEvent *event) adaptContextMenu(menu, event->pos()); + menu->addSeparator(); + QAction *saveAction = menu->addAction(Tr::tr("Save Contents...")); + connect(saveAction, &QAction::triggered, this, [this] { + QFileDialog::saveFileContent(toPlainText().toUtf8(), d->outputFileNameHint); + }); + saveAction->setEnabled(!document()->isEmpty()); + menu->addSeparator(); QAction *clearAction = menu->addAction(Tr::tr("Clear")); connect(clearAction, &QAction::triggered, this, [this] { clear(); }); @@ -368,6 +377,11 @@ void OutputWindow::updateFilterProperties( filterNewContent(); } +void OutputWindow::setOutputFileNameHint(const QString &fileName) +{ + d->outputFileNameHint = fileName; +} + void OutputWindow::filterNewContent() { QTextBlock lastBlock = document()->findBlockByNumber(d->lastFilteredBlockNumber); diff --git a/src/plugins/coreplugin/outputwindow.h b/src/plugins/coreplugin/outputwindow.h index cfcea8aae05..cd44e5678e9 100644 --- a/src/plugins/coreplugin/outputwindow.h +++ b/src/plugins/coreplugin/outputwindow.h @@ -67,6 +67,8 @@ public: bool regexp, bool isInverted); + void setOutputFileNameHint(const QString &fileName); + signals: void wheelZoom(); diff --git a/src/plugins/projectexplorer/appoutputpane.cpp b/src/plugins/projectexplorer/appoutputpane.cpp index 898acaba2a9..94e2694acc2 100644 --- a/src/plugins/projectexplorer/appoutputpane.cpp +++ b/src/plugins/projectexplorer/appoutputpane.cpp @@ -429,6 +429,8 @@ void AppOutputPane::createNewOutputWindow(RunControl *rc) ow->setWindowIcon(Icons::WINDOW.icon()); ow->setWordWrapEnabled(m_settings.wrapOutput); ow->setMaxCharCount(m_settings.maxCharCount); + //: file name suggested for saving application output, %1 = run configuration display name + ow->setOutputFileNameHint(Tr::tr("application-output-%1.txt").arg(rc->displayName())); auto updateFontSettings = [ow] { ow->setBaseFont(TextEditor::TextEditorSettings::fontSettings().font()); diff --git a/src/plugins/projectexplorer/compileoutputwindow.cpp b/src/plugins/projectexplorer/compileoutputwindow.cpp index 8d2b12983bd..c5255d127f5 100644 --- a/src/plugins/projectexplorer/compileoutputwindow.cpp +++ b/src/plugins/projectexplorer/compileoutputwindow.cpp @@ -61,6 +61,8 @@ CompileOutputWindow::CompileOutputWindow(QAction *cancelBuildAction) : m_outputWindow->setReadOnly(true); m_outputWindow->setUndoRedoEnabled(false); m_outputWindow->setMaxCharCount(Core::Constants::DEFAULT_MAX_CHAR_COUNT); + //: file name suggested for saving compile output + m_outputWindow->setOutputFileNameHint(Tr::tr("compile-output.txt")); Utils::ProxyAction *cancelBuildProxyButton = Utils::ProxyAction::proxyActionWithIcon(cancelBuildAction, From 1af555ad09be169bebc7525e4bb7e10ad4de271d Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 8 Feb 2024 15:00:55 +0100 Subject: [PATCH 0006/1060] ClangCodeModel: Let users configure the clangd index location Fixes: QTCREATORBUG-27346 Change-Id: I9bc59f759682e70b761c0f22a011868008fc0360 Reviewed-by: Reviewed-by: Qt CI Bot Reviewed-by: hjk Reviewed-by: Eike Ziller --- .../clangmodelmanagersupport.cpp | 21 ++++---- src/plugins/coreplugin/coreplugin.cpp | 4 ++ .../cppeditor/cppcodemodelsettings.cpp | 32 +++++++++++ src/plugins/cppeditor/cppcodemodelsettings.h | 38 ++++++++----- .../cppeditor/cppcodemodelsettingspage.cpp | 53 ++++++++++++++++++- 5 files changed, 122 insertions(+), 26 deletions(-) diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp index 53d0e6f3784..3c3fc18c911 100644 --- a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp +++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include @@ -472,17 +473,15 @@ void ClangModelManagerSupport::connectToWidgetsMarkContextMenuRequested(QWidget } } -static FilePath getJsonDbDir(const Project *project) +static FilePath getJsonDbDir(Project *project) { - static const QString dirName(".qtc_clangd"); - if (!project) { - const QString sessionDirName = FileUtils::fileSystemFriendlyName( - SessionManager::activeSession()); - return ICore::userResourcePath() / dirName / sessionDirName; // TODO: Make configurable? - } - if (const Target * const target = project->activeTarget()) { - if (const BuildConfiguration * const bc = target->activeBuildConfiguration()) - return bc->buildDirectory() / dirName; + if (!project) + return ClangdSettings::instance().sessionIndexPath(*globalMacroExpander()); + if (const Target *const target = project->activeTarget()) { + if (const BuildConfiguration *const bc = target->activeBuildConfiguration()) { + return ClangdSettings(ClangdProjectSettings(project).settings()) + .projectIndexPath(*bc->macroExpander()); + } } return {}; } @@ -696,7 +695,7 @@ ClangdClient *ClangModelManagerSupport::clientWithProject(const Project *project void ClangModelManagerSupport::updateStaleIndexEntries() { QHash lastModifiedCache; - for (const Project * const project : ProjectManager::projects()) { + for (Project * const project : ProjectManager::projects()) { const FilePath jsonDbDir = getJsonDbDir(project); if (jsonDbDir.isEmpty()) continue; diff --git a/src/plugins/coreplugin/coreplugin.cpp b/src/plugins/coreplugin/coreplugin.cpp index 49ca2fec8af..2ff53a68d04 100644 --- a/src/plugins/coreplugin/coreplugin.cpp +++ b/src/plugins/coreplugin/coreplugin.cpp @@ -226,6 +226,10 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage) Tr::tr("The directory where %1 finds its pre-installed resources.") .arg(QGuiApplication::applicationDisplayName()), [] { return ICore::resourcePath().toString(); }); + expander->registerVariable("IDE:UserResourcePath", + Tr::tr("The directory where %1 puts custom user data.") + .arg(QGuiApplication::applicationDisplayName()), + [] { return ICore::userResourcePath().toString(); }); expander->registerPrefix("CurrentDate:", Tr::tr("The current date (QDate formatstring)."), [](const QString &fmt) { return QDate::currentDate().toString(fmt); }); expander->registerPrefix("CurrentTime:", Tr::tr("The current time (QTime formatstring)."), diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index db6231cfe99..1c294af4150 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -15,10 +15,12 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -45,6 +47,8 @@ static Key clangdSettingsKey() { return "ClangdSettings"; } static Key useClangdKey() { return "UseClangdV7"; } static Key clangdPathKey() { return "ClangdPath"; } static Key clangdIndexingKey() { return "ClangdIndexing"; } +static Key clangdProjectIndexPathKey() { return "ClangdProjectIndexPath"; } +static Key clangdSessionIndexPathKey() { return "ClangdSessionIndexPath"; } static Key clangdIndexingPriorityKey() { return "ClangdIndexingPriority"; } static Key clangdHeaderSourceSwitchModeKey() { return "ClangdHeaderSourceSwitchMode"; } static Key clangdCompletionRankingModelKey() { return "ClangdCompletionRankingModel"; } @@ -248,6 +252,16 @@ QString ClangdSettings::rankingModelToDisplayString(CompletionRankingModel model QTC_ASSERT(false, return {}); } +QString ClangdSettings::defaultProjectIndexPathTemplate() +{ + return QDir::toNativeSeparators("%{BuildConfig:BuildDirectory:FilePath}/.qtc_clangd"); +} + +QString ClangdSettings::defaultSessionIndexPathTemplate() +{ + return QDir::toNativeSeparators("%{IDE:UserResourcePath}/.qtc_clangd/%{Session:FileBaseName}"); +} + ClangdSettings &ClangdSettings::instance() { static ClangdSettings settings; @@ -318,6 +332,16 @@ FilePath ClangdSettings::clangdFilePath() const return fallbackClangdFilePath(); } +FilePath ClangdSettings::projectIndexPath(const Utils::MacroExpander &expander) const +{ + return FilePath::fromUserInput(expander.expand(m_data.projectIndexPathTemplate)); +} + +FilePath ClangdSettings::sessionIndexPath(const Utils::MacroExpander &expander) const +{ + return FilePath::fromUserInput(expander.expand(m_data.sessionIndexPathTemplate)); +} + bool ClangdSettings::sizeIsOkay(const Utils::FilePath &fp) const { return !sizeThresholdEnabled() || sizeThresholdInKb() * 1024 >= fp.fileSize(); @@ -559,6 +583,10 @@ Store ClangdSettings::Data::toMap() const map.insertValueWithDefault(clangdIndexingPriorityKey(), int(indexingPriority), int(DefaultIndexingPriority)); + map.insertValueWithDefault(clangdProjectIndexPathKey(), projectIndexPathTemplate, + defaultProjectIndexPathTemplate()); + map.insertValueWithDefault(clangdSessionIndexPathKey(), sessionIndexPathTemplate, + defaultSessionIndexPathTemplate()); map.insertValueWithDefault(clangdHeaderSourceSwitchModeKey(), int(headerSourceSwitchMode), @@ -610,6 +638,10 @@ void ClangdSettings::Data::fromMap(const Store &map) const auto it = map.find(clangdIndexingKey()); if (it != map.end() && !it->toBool()) indexingPriority = IndexingPriority::Off; + projectIndexPathTemplate + = map.value(clangdProjectIndexPathKey(), defaultProjectIndexPathTemplate()).toString(); + sessionIndexPathTemplate + = map.value(clangdSessionIndexPathKey(), defaultSessionIndexPathTemplate()).toString(); headerSourceSwitchMode = HeaderSourceSwitchMode( map.value(clangdHeaderSourceSwitchModeKey(), int(DefaultHeaderSourceSwitchMode)).toInt()); completionRankingModel = CompletionRankingModel( diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index b4f8ac7269d..df0b81d9ca1 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -17,6 +17,7 @@ #include namespace ProjectExplorer { class Project; } +namespace Utils { class MacroExpander; } namespace CppEditor { @@ -92,6 +93,8 @@ public: static QString headerSourceSwitchModeToDisplayString(HeaderSourceSwitchMode mode); static QString rankingModelToCmdLineString(CompletionRankingModel model); static QString rankingModelToDisplayString(CompletionRankingModel model); + static QString defaultProjectIndexPathTemplate(); + static QString defaultSessionIndexPathTemplate(); class CPPEDITOR_EXPORT Data { @@ -103,6 +106,8 @@ public: { return s1.useClangd == s2.useClangd && s1.executableFilePath == s2.executableFilePath + && s1.projectIndexPathTemplate == s2.projectIndexPathTemplate + && s1.sessionIndexPathTemplate == s2.sessionIndexPathTemplate && s1.sessionsWithOneClangd == s2.sessionsWithOneClangd && s1.customDiagnosticConfigs == s2.customDiagnosticConfigs && s1.diagnosticConfigId == s2.diagnosticConfigId @@ -119,13 +124,28 @@ public: } friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } - static int defaultCompletionResults(); - Utils::FilePath executableFilePath; QStringList sessionsWithOneClangd; ClangDiagnosticConfigs customDiagnosticConfigs; Utils::Id diagnosticConfigId; + int workerThreadLimit = DefaultWorkerThreadLimit; + int documentUpdateThreshold = DefaultDocumentUpdateThreshold; + qint64 sizeThresholdInKb = DefaultSizeThresholdInKb; + bool useClangd = DefaultUseClangd; + IndexingPriority indexingPriority = DefaultIndexingPriority; + QString projectIndexPathTemplate = defaultProjectIndexPathTemplate(); + QString sessionIndexPathTemplate = defaultSessionIndexPathTemplate(); + HeaderSourceSwitchMode headerSourceSwitchMode = DefaultHeaderSourceSwitchMode; + CompletionRankingModel completionRankingModel = DefaultCompletionRankingModel; + bool autoIncludeHeaders = DefaultAutoIncludeHeaders; + bool sizeThresholdEnabled = DefaultSizeThresholdEnabled; + bool haveCheckedHardwareReqirements = false; + int completionResults = defaultCompletionResults(); + + private: + static int defaultCompletionResults(); + static constexpr auto DefaultWorkerThreadLimit = 0; static constexpr auto DefaultDocumentUpdateThreshold = 500; static constexpr auto DefaultSizeThresholdInKb = 1024ll; @@ -135,18 +155,6 @@ public: static constexpr auto DefaultCompletionRankingModel = CompletionRankingModel::Default; static constexpr auto DefaultAutoIncludeHeaders = false; static constexpr auto DefaultSizeThresholdEnabled = false; - - int workerThreadLimit = DefaultWorkerThreadLimit; - int documentUpdateThreshold = DefaultDocumentUpdateThreshold; - qint64 sizeThresholdInKb = DefaultSizeThresholdInKb; - bool useClangd = DefaultUseClangd; - IndexingPriority indexingPriority = DefaultIndexingPriority; - HeaderSourceSwitchMode headerSourceSwitchMode = DefaultHeaderSourceSwitchMode; - CompletionRankingModel completionRankingModel = DefaultCompletionRankingModel; - bool autoIncludeHeaders = DefaultAutoIncludeHeaders; - bool sizeThresholdEnabled = DefaultSizeThresholdEnabled; - bool haveCheckedHardwareReqirements = false; - int completionResults = defaultCompletionResults(); }; ClangdSettings(const Data &data) : m_data(data) {} @@ -163,6 +171,8 @@ public: static void setCustomDiagnosticConfigs(const ClangDiagnosticConfigs &configs); Utils::FilePath clangdFilePath() const; IndexingPriority indexingPriority() const { return m_data.indexingPriority; } + Utils::FilePath projectIndexPath(const Utils::MacroExpander &expander) const; + Utils::FilePath sessionIndexPath(const Utils::MacroExpander &expander) const; HeaderSourceSwitchMode headerSourceSwitchMode() const { return m_data.headerSourceSwitchMode; } CompletionRankingModel completionRankingModel() const { return m_data.completionRankingModel; } bool autoIncludeHeaders() const { return m_data.autoIncludeHeaders; } diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index bc47a78c9df..b4a19ccaae6 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -18,11 +18,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include @@ -36,6 +38,7 @@ #include #include #include +#include #include #include @@ -220,6 +223,8 @@ signals: private: QCheckBox m_useClangdCheckBox; QComboBox m_indexingComboBox; + Utils::FancyLineEdit m_projectIndexPathTemplateLineEdit; + Utils::FancyLineEdit m_sessionIndexPathTemplateLineEdit; QComboBox m_headerSourceSwitchComboBox; QComboBox m_completionRankingModelComboBox; QCheckBox m_autoIncludeHeadersCheckBox; @@ -249,6 +254,12 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD "cores unused.

" "

Normal Priority: Reduced priority compared to interactive work.

" "

Low Priority: Same priority as other clangd work.

"); + const QString projectIndexPathToolTip = Tr::tr( + "The location of the per-project clangd index.

" + "This is also where the compile_commands.json file will go."); + const QString sessionIndexPathToolTip = Tr::tr( + "The location of the per-session clangd index.

" + "This is also where the compile_commands.json file will go."); const QString headerSourceSwitchToolTip = Tr::tr( "

The C/C++ backend to use for switching between header and source files.

" "

While the clangd implementation has more capabilities than the built-in " @@ -296,6 +307,8 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD m_indexingComboBox.setCurrentIndex(m_indexingComboBox.count() - 1); } m_indexingComboBox.setToolTip(indexingToolTip); + m_projectIndexPathTemplateLineEdit.setText(settings.data().projectIndexPathTemplate); + m_sessionIndexPathTemplateLineEdit.setText(settings.data().sessionIndexPathTemplate); using SwitchMode = ClangdSettings::HeaderSourceSwitchMode; for (SwitchMode mode : {SwitchMode::BuiltinOnly, SwitchMode::ClangdOnly, SwitchMode::Both}) { m_headerSourceSwitchComboBox.addItem( @@ -360,6 +373,33 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD indexingPriorityLabel->setToolTip(indexingToolTip); formLayout->addRow(indexingPriorityLabel, indexingPriorityLayout); + for (const auto &[text, edit, toolTip, defaultValue] : + {std::make_tuple(Tr::tr("Per-project index location:"), + &m_projectIndexPathTemplateLineEdit, + projectIndexPathToolTip, + ClangdSettings::defaultProjectIndexPathTemplate()), + std::make_tuple(Tr::tr("Per-session index location:"), + &m_sessionIndexPathTemplateLineEdit, + sessionIndexPathToolTip, + ClangdSettings::defaultSessionIndexPathTemplate())}) { + if (isForProject && edit == &m_sessionIndexPathTemplateLineEdit) + continue; + + const auto chooser = new Utils::VariableChooser(edit); + chooser->addSupportedWidget(edit); + chooser->addMacroExpanderProvider([] { return Utils::globalMacroExpander(); }); + + const auto resetButton = new QPushButton(Tr::tr("Reset")); + connect(resetButton, &QPushButton::clicked, [e = edit, v = defaultValue] { e->setText(v); }); + const auto layout = new QHBoxLayout; + const auto label = new QLabel(text); + label->setToolTip(toolTip); + edit->setToolTip(toolTip); + layout->addWidget(edit); + layout->addWidget(resetButton); + formLayout->addRow(label, layout); + } + const auto headerSourceSwitchLayout = new QHBoxLayout; headerSourceSwitchLayout->addWidget(&m_headerSourceSwitchComboBox); headerSourceSwitchLayout->addStretch(1); @@ -530,6 +570,10 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_indexingComboBox, &QComboBox::currentIndexChanged, this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_projectIndexPathTemplateLineEdit, &QLineEdit::textChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_sessionIndexPathTemplateLineEdit, &QLineEdit::textChanged, + this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_headerSourceSwitchComboBox, &QComboBox::currentIndexChanged, this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_completionRankingModelComboBox, &QComboBox::currentIndexChanged, @@ -559,6 +603,8 @@ ClangdSettings::Data ClangdSettingsWidget::settingsData() const data.executableFilePath = m_clangdChooser.filePath(); data.indexingPriority = ClangdSettings::IndexingPriority( m_indexingComboBox.currentData().toInt()); + data.projectIndexPathTemplate = m_projectIndexPathTemplateLineEdit.text(); + data.sessionIndexPathTemplate = m_sessionIndexPathTemplateLineEdit.text(); data.headerSourceSwitchMode = ClangdSettings::HeaderSourceSwitchMode( m_headerSourceSwitchComboBox.currentData().toInt()); data.completionRankingModel = ClangdSettings::CompletionRankingModel( @@ -641,9 +687,14 @@ public: m_settings.setSettings(m_widget.settingsData()); }); - connect(&m_widget, &ClangdSettingsWidget::settingsDataChanged, this, [this] { + const auto timer = new QTimer(this); + timer->setSingleShot(true); + timer->setInterval(5000); + connect(timer, &QTimer::timeout, this, [this] { m_settings.setSettings(m_widget.settingsData()); }); + connect(&m_widget, &ClangdSettingsWidget::settingsDataChanged, + timer, qOverload<>(&QTimer::start)); } private: From b39b1925189416585933c017e189d04d6e4c478d Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 25 Jan 2024 12:21:48 +0100 Subject: [PATCH 0007/1060] ExtensionSystem: Refactor PluginSpec Splits the functionality between plugin type specific and general. Allows Plugins to be loaded after the first pass, e.g. for Lua scripted plugins. Change-Id: If2712817a672c49d554fdc308250cb06ca7eb3f8 Reviewed-by: Eike Ziller --- src/libs/extensionsystem/CMakeLists.txt | 2 +- src/libs/extensionsystem/extensionsystem.qbs | 1 - src/libs/extensionsystem/optionsparser.cpp | 17 +- src/libs/extensionsystem/pluginmanager.cpp | 176 +++--- src/libs/extensionsystem/pluginmanager.h | 2 + src/libs/extensionsystem/pluginmanager_p.h | 8 +- src/libs/extensionsystem/pluginspec.cpp | 569 +++++++++--------- src/libs/extensionsystem/pluginspec.h | 171 ++++-- src/libs/extensionsystem/pluginspec_p.h | 107 ---- src/libs/extensionsystem/pluginview.cpp | 8 +- .../coreplugin/plugininstallwizard.cpp | 4 +- .../pluginspec/testspecs/spec_wrong2.json | 1 + .../pluginspec/testspecs/spec_wrong3.json | 1 + .../pluginspec/testspecs/spec_wrong4.json | 1 + .../pluginspec/testspecs/spec_wrong5.json | 1 + .../pluginspec/tst_pluginspec.cpp | 290 ++++----- 16 files changed, 678 insertions(+), 681 deletions(-) delete mode 100644 src/libs/extensionsystem/pluginspec_p.h diff --git a/src/libs/extensionsystem/CMakeLists.txt b/src/libs/extensionsystem/CMakeLists.txt index fb836631d93..c8e37668060 100644 --- a/src/libs/extensionsystem/CMakeLists.txt +++ b/src/libs/extensionsystem/CMakeLists.txt @@ -11,7 +11,7 @@ add_qtc_library(ExtensionSystem pluginerroroverview.cpp pluginerroroverview.h pluginerrorview.cpp pluginerrorview.h pluginmanager.cpp pluginmanager.h pluginmanager_p.h - pluginspec.cpp pluginspec.h pluginspec_p.h + pluginspec.cpp pluginspec.h pluginview.cpp pluginview.h EXPLICIT_MOC pluginmanager.h diff --git a/src/libs/extensionsystem/extensionsystem.qbs b/src/libs/extensionsystem/extensionsystem.qbs index 8748c27ba69..72fe2f4c3cf 100644 --- a/src/libs/extensionsystem/extensionsystem.qbs +++ b/src/libs/extensionsystem/extensionsystem.qbs @@ -29,7 +29,6 @@ QtcLibrary { "pluginmanager_p.h", "pluginspec.cpp", "pluginspec.h", - "pluginspec_p.h", "pluginview.cpp", "pluginview.h", ] diff --git a/src/libs/extensionsystem/optionsparser.cpp b/src/libs/extensionsystem/optionsparser.cpp index 205442488e6..dd9d03944a2 100644 --- a/src/libs/extensionsystem/optionsparser.cpp +++ b/src/libs/extensionsystem/optionsparser.cpp @@ -6,7 +6,6 @@ #include "extensionsystemtr.h" #include "pluginmanager.h" #include "pluginmanager_p.h" -#include "pluginspec_p.h" #include @@ -119,7 +118,7 @@ bool OptionsParser::checkForTestOptions() } else { m_pmPrivate->testSpecs.emplace_back(spec, args); } - } else { + } else { if (m_errorString) *m_errorString = Tr::tr("The plugin \"%1\" does not exist.").arg(pluginName); m_hasError = true; @@ -177,7 +176,7 @@ bool OptionsParser::checkForLoadOption() if (nextToken(RequiredToken)) { if (m_currentArg == QLatin1String("all")) { for (PluginSpec *spec : std::as_const(m_pmPrivate->pluginSpecs)) - spec->d->setForceEnabled(true); + spec->setForceEnabled(true); m_isDependencyRefreshNeeded = true; } else { PluginSpec *spec = m_pmPrivate->pluginByName(m_currentArg); @@ -186,7 +185,7 @@ bool OptionsParser::checkForLoadOption() *m_errorString = Tr::tr("The plugin \"%1\" does not exist.").arg(m_currentArg); m_hasError = true; } else { - spec->d->setForceEnabled(true); + spec->setForceEnabled(true); m_isDependencyRefreshNeeded = true; } } @@ -202,7 +201,7 @@ bool OptionsParser::checkForNoLoadOption() if (nextToken(RequiredToken)) { if (m_currentArg == QLatin1String("all")) { for (PluginSpec *spec : std::as_const(m_pmPrivate->pluginSpecs)) - spec->d->setForceDisabled(true); + spec->setForceDisabled(true); m_isDependencyRefreshNeeded = true; } else { PluginSpec *spec = m_pmPrivate->pluginByName(m_currentArg); @@ -211,10 +210,10 @@ bool OptionsParser::checkForNoLoadOption() *m_errorString = Tr::tr("The plugin \"%1\" does not exist.").arg(m_currentArg); m_hasError = true; } else { - spec->d->setForceDisabled(true); + spec->setForceDisabled(true); // recursively disable all plugins that require this plugin for (PluginSpec *dependantSpec : PluginManager::pluginsRequiringPlugin(spec)) - dependantSpec->d->setForceDisabled(true); + dependantSpec->setForceDisabled(true); m_isDependencyRefreshNeeded = true; } } @@ -292,10 +291,10 @@ bool OptionsParser::checkForUnknownOption() void OptionsParser::forceDisableAllPluginsExceptTestedAndForceEnabled() { for (const PluginManagerPrivate::TestSpec &testSpec : m_pmPrivate->testSpecs) - testSpec.pluginSpec->d->setForceEnabled(true); + testSpec.pluginSpec->setForceEnabled(true); for (PluginSpec *spec : std::as_const(m_pmPrivate->pluginSpecs)) { if (!spec->isForceEnabled() && !spec->isRequired()) - spec->d->setForceDisabled(true); + spec->setForceDisabled(true); } } diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp index fcb3062faa9..43b8f3d2fa5 100644 --- a/src/libs/extensionsystem/pluginmanager.cpp +++ b/src/libs/extensionsystem/pluginmanager.cpp @@ -8,7 +8,6 @@ #include "optionsparser.h" #include "pluginmanager_p.h" #include "pluginspec.h" -#include "pluginspec_p.h" #include @@ -35,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -327,6 +327,11 @@ void PluginManager::loadPluginsAtRuntime(const QSet &plugins) d->loadPluginsAtRuntime(plugins); } +void PluginManager::addPlugins(const QVector &specs) +{ + d->addPlugins(specs); +} + /*! Returns \c true if any plugin has errors even though it is enabled. Most useful to call after loadPlugins(). @@ -903,14 +908,6 @@ QVector PluginManager::loadQueue() //============PluginManagerPrivate=========== -/*! - \internal -*/ -PluginSpec *PluginManagerPrivate::createSpec() -{ - return new PluginSpec(); -} - /*! \internal */ @@ -935,14 +932,6 @@ void PluginManagerPrivate::setGlobalSettings(QtcSettings *s) globalSettings->setParent(this); } -/*! - \internal -*/ -PluginSpecPrivate *PluginManagerPrivate::privateSpec(PluginSpec *spec) -{ - return spec->d; -} - void PluginManagerPrivate::startDelayedInitialize() { Utils::setMimeStartupPhase(MimeStartupPhase::PluginsDelayedInitializing); @@ -954,8 +943,8 @@ void PluginManagerPrivate::startDelayedInitialize() delayedInitializeQueue.pop(); NANOTRACE_SCOPE(specName, specName + "::delayedInitialized"); profilingReport(">delayedInitialize", spec); - bool delay = spec->d->delayedInitialize(); - profilingReport("d->performanceData.delayedInitialize); + bool delay = spec->delayedInitialize(); + profilingReport("performanceData().delayedInitialize); if (delay) // give UI a bit of breathing space, but prevent user interaction QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } @@ -1068,10 +1057,8 @@ void PluginManagerPrivate::checkForDuplicatePlugins() if (spec->isEffectivelyEnabled() && other->isEffectivelyEnabled()) { const QString error = Tr::tr( "Multiple versions of the same plugin have been found."); - spec->d->hasError = true; - spec->d->errorString = error; - other->d->hasError = true; - other->d->errorString = error; + spec->setError(error); + other->setError(error); } } else { seen.insert(spec->name(), spec); @@ -1403,7 +1390,7 @@ void PluginManagerPrivate::loadPlugins() delayedInitializeQueue.push(spec); } else { // Plugin initialization failed, so cleanup after it - spec->d->kill(); + spec->kill(); } }); } @@ -1421,10 +1408,23 @@ void PluginManagerPrivate::loadPlugins() void PluginManagerPrivate::loadPluginsAtRuntime(const QSet &plugins) { QTC_CHECK(allOf(plugins, [](PluginSpec *spec) { return spec->isSoftLoadable(); })); - // load the plugins ordered by dependency + + // load the plugins and their dependencies (if possible) ordered by dependency const QList queue = filtered(loadQueue(), [&plugins](PluginSpec *spec) { - return plugins.contains(spec); + // Is the current plugin already running, or not soft loadable? + if (spec->state() == PluginSpec::State::Running || !spec->isSoftLoadable()) + return false; + + // Is the current plugin in the list of plugins to load? + if (plugins.contains(spec)) + return true; + + // Is the current plugin a dependency of any of the plugins we want to load? + return plugins.contains(spec) || Utils::anyOf(plugins, [spec](PluginSpec *other) { + return other->requiresAny({spec}); + }); }); + std::queue localDelayedInitializeQueue; for (PluginSpec *spec : queue) loadPlugin(spec, PluginSpec::Loaded); @@ -1434,12 +1434,12 @@ void PluginManagerPrivate::loadPluginsAtRuntime(const QSet &plugin [this](PluginSpec *spec) { loadPlugin(spec, PluginSpec::Running); }); Utils::reverseForeach(queue, [](PluginSpec *spec) { if (spec->state() == PluginSpec::Running) { - const bool delay = spec->d->delayedInitialize(); + const bool delay = spec->delayedInitialize(); if (delay) QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } else { // Plugin initialization failed, so cleanup after it - spec->d->kill(); + spec->kill(); } }); emit q->pluginsChanged(); @@ -1494,17 +1494,17 @@ bool PluginManagerPrivate::loadQueue(PluginSpec *spec, return true; // check for circular dependencies if (circularityCheckQueue.contains(spec)) { - spec->d->hasError = true; - spec->d->errorString = Tr::tr("Circular dependency detected:"); - spec->d->errorString += QLatin1Char('\n'); + QString errorString = Tr::tr("Circular dependency detected:"); + errorString += QLatin1Char('\n'); int index = circularityCheckQueue.indexOf(spec); for (int i = index; i < circularityCheckQueue.size(); ++i) { const PluginSpec *depSpec = circularityCheckQueue.at(i); - spec->d->errorString.append(Tr::tr("%1 (%2) depends on") - .arg(depSpec->name(), depSpec->version())); - spec->d->errorString += QLatin1Char('\n'); + errorString.append( + Tr::tr("%1 (%2) depends on").arg(depSpec->name(), depSpec->version())); + errorString += QLatin1Char('\n'); } - spec->d->errorString.append(Tr::tr("%1 (%2)").arg(spec->name(), spec->version())); + errorString.append(Tr::tr("%1 (%2)").arg(spec->name(), spec->version())); + spec->setError(errorString); return false; } circularityCheckQueue.append(spec); @@ -1523,10 +1523,9 @@ bool PluginManagerPrivate::loadQueue(PluginSpec *spec, continue; PluginSpec *depSpec = it.value(); if (!loadQueue(depSpec, queue, circularityCheckQueue)) { - spec->d->hasError = true; - spec->d->errorString = + spec->setError( Tr::tr("Cannot load plugin because dependency failed to load: %1 (%2)\nReason: %3") - .arg(depSpec->name(), depSpec->version(), depSpec->errorString()); + .arg(depSpec->name(), depSpec->version(), depSpec->errorString())); return false; } } @@ -1619,9 +1618,9 @@ void PluginManagerPrivate::checkForProblematicPlugins() dialog.addButton(Tr::tr("Continue"), QMessageBox::RejectRole); dialog.exec(); if (dialog.clickedButton() == disableButton) { - spec->d->setForceDisabled(true); + spec->setForceDisabled(true); for (PluginSpec *other : dependents) - other->d->setForceDisabled(true); + other->setForceDisabled(true); enableDependenciesIndirectly(); } } @@ -1664,15 +1663,15 @@ void PluginManagerPrivate::loadPlugin(PluginSpec *spec, PluginSpec::State destSt case PluginSpec::Running: { NANOTRACE_SCOPE(specName, specName + "::extensionsInitialized"); profilingReport(">initializeExtensions", spec); - spec->d->initializeExtensions(); + spec->initializeExtensions(); profilingReport("d->performanceData.extensionsInitialized); + &spec->performanceData().extensionsInitialized); return; } case PluginSpec::Deleted: profilingReport(">delete", spec); - spec->d->kill(); + spec->kill(); profilingReport("state() != destState) { - spec->d->hasError = true; - spec->d->errorString = - Tr::tr("Cannot load plugin because dependency failed to load: %1(%2)\nReason: %3") - .arg(depSpec->name(), depSpec->version(), depSpec->errorString()); + spec->setError( + Tr::tr( + "Cannot load plugin because dependency failed to load: %1(%2)\nReason: %3") + .arg(depSpec->name(), depSpec->version(), depSpec->errorString())); return; } } @@ -1698,20 +1697,20 @@ void PluginManagerPrivate::loadPlugin(PluginSpec *spec, PluginSpec::State destSt case PluginSpec::Loaded: { NANOTRACE_SCOPE(specName, specName + "::load"); profilingReport(">loadLibrary", spec); - spec->d->loadLibrary(); - profilingReport("d->performanceData.load); + spec->loadLibrary(); + profilingReport("performanceData().load); break; } case PluginSpec::Initialized: { NANOTRACE_SCOPE(specName, specName + "::initialize"); profilingReport(">initializePlugin", spec); - spec->d->initializePlugin(); - profilingReport("d->performanceData.initialize); + spec->initializePlugin(); + profilingReport("performanceData().initialize); break; } case PluginSpec::Stopped: profilingReport(">stop", spec); - if (spec->d->stop() == IPlugin::AsynchronousShutdown) { + if (spec->stop() == IPlugin::AsynchronousShutdown) { asynchronousPlugins << spec; connect(spec->plugin(), &IPlugin::asynchronousShutdownFinished, this, [this, spec] { asynchronousPlugins.remove(spec); @@ -1753,45 +1752,24 @@ static const QStringList pluginFiles(const QStringList &pluginPaths) return pluginFiles; } -/*! - \internal -*/ -void PluginManagerPrivate::readPluginPaths() +void PluginManagerPrivate::addPlugins(const QVector &specs) { - qDeleteAll(pluginSpecs); - pluginSpecs.clear(); - pluginCategories.clear(); + pluginSpecs += specs; - // default - pluginCategories.insert(QString(), QVector()); - - // from the file system - for (const QString &pluginFile : pluginFiles(pluginPaths)) { - PluginSpec *spec = PluginSpec::read(pluginFile); - if (spec) // Qt Creator plugin - pluginSpecs.append(spec); - } - // static - for (const QStaticPlugin &plugin : QPluginLoader::staticPlugins()) { - PluginSpec *spec = PluginSpec::read(plugin); - if (spec) // Qt Creator plugin - pluginSpecs.append(spec); - } - - for (PluginSpec *spec : pluginSpecs) { + for (PluginSpec *spec : specs) { // defaultDisabledPlugins and defaultEnabledPlugins from install settings // is used to override the defaults read from the plugin spec if (spec->isEnabledByDefault() && defaultDisabledPlugins.contains(spec->name())) { - spec->d->setEnabledByDefault(false); - spec->d->setEnabledBySettings(false); + spec->setEnabledByDefault(false); + spec->setEnabledBySettings(false); } else if (!spec->isEnabledByDefault() && defaultEnabledPlugins.contains(spec->name())) { - spec->d->setEnabledByDefault(true); - spec->d->setEnabledBySettings(true); + spec->setEnabledByDefault(true); + spec->setEnabledBySettings(true); } if (!spec->isEnabledByDefault() && forceEnabledPlugins.contains(spec->name())) - spec->d->setEnabledBySettings(true); + spec->setEnabledBySettings(true); if (spec->isEnabledByDefault() && disabledPlugins.contains(spec->name())) - spec->d->setEnabledBySettings(false); + spec->setEnabledBySettings(false); pluginCategories[spec->category()].append(spec); } @@ -1803,21 +1781,49 @@ void PluginManagerPrivate::readPluginPaths() emit q->pluginsChanged(); } +/*! + \internal +*/ +void PluginManagerPrivate::readPluginPaths() +{ + QVector newSpecs; + + // from the file system + for (const QString &pluginFile : pluginFiles(pluginPaths)) { + expected_str spec = PluginSpecImpl::read(pluginFile); + if (!spec) { + qCWarning(pluginLog).noquote() + << QString("Ignoring plugin \"%1\" because: %2").arg(pluginFile).arg(spec.error()); + continue; + } + newSpecs.append(*spec); + } + + // static + for (const QStaticPlugin &plugin : QPluginLoader::staticPlugins()) { + expected_str spec = PluginSpecImpl::read(plugin); + QTC_ASSERT_EXPECTED(spec, continue); + newSpecs.append(*spec); + } + + addPlugins(newSpecs); +} + void PluginManagerPrivate::resolveDependencies() { for (PluginSpec *spec : std::as_const(pluginSpecs)) - spec->d->resolveDependencies(pluginSpecs); + spec->resolveDependencies(pluginSpecs); } void PluginManagerPrivate::enableDependenciesIndirectly() { for (PluginSpec *spec : std::as_const(pluginSpecs)) - spec->d->enabledIndirectly = false; + spec->setEnabledIndirectly(false); // cannot use reverse loadQueue here, because test dependencies can introduce circles QVector queue = Utils::filtered(pluginSpecs, &PluginSpec::isEffectivelyEnabled); while (!queue.isEmpty()) { PluginSpec *spec = queue.takeFirst(); - queue += spec->d->enableDependenciesIndirectly(containsTestSpec(spec)); + queue += spec->enableDependenciesIndirectly(containsTestSpec(spec)); } } diff --git a/src/libs/extensionsystem/pluginmanager.h b/src/libs/extensionsystem/pluginmanager.h index a38f3c3fe7b..74237db5b34 100644 --- a/src/libs/extensionsystem/pluginmanager.h +++ b/src/libs/extensionsystem/pluginmanager.h @@ -82,6 +82,8 @@ public: static void checkForProblematicPlugins(); static PluginSpec *specForPlugin(IPlugin *plugin); + static void addPlugins(const QVector &specs); + // Settings static void setSettings(Utils::QtcSettings *settings); static Utils::QtcSettings *settings(); diff --git a/src/libs/extensionsystem/pluginmanager_p.h b/src/libs/extensionsystem/pluginmanager_p.h index 27efbf4c8f3..2404a8b49e9 100644 --- a/src/libs/extensionsystem/pluginmanager_p.h +++ b/src/libs/extensionsystem/pluginmanager_p.h @@ -36,8 +36,6 @@ class PluginManager; namespace Internal { -class PluginSpecPrivate; - class EXTENSIONSYSTEM_TEST_EXPORT PluginManagerPrivate : public QObject { public: @@ -52,6 +50,8 @@ public: void checkForProblematicPlugins(); void loadPlugins(); void loadPluginsAtRuntime(const QSet &plugins); + void addPlugins(const QVector &specs); + void shutdown(); void setPluginPaths(const QStringList &paths); const QVector loadQueue(); @@ -119,10 +119,6 @@ public: PluginSpec *pluginForOption(const QString &option, bool *requiresArgument) const; PluginSpec *pluginByName(const QString &name) const; - // used by tests - static PluginSpec *createSpec(); - static PluginSpecPrivate *privateSpec(PluginSpec *spec); - static void addTestCreator(IPlugin *plugin, const std::function &testCreator); mutable QReadWriteLock m_lock; diff --git a/src/libs/extensionsystem/pluginspec.cpp b/src/libs/extensionsystem/pluginspec.cpp index 49f9c680fe8..8740854e7e5 100644 --- a/src/libs/extensionsystem/pluginspec.cpp +++ b/src/libs/extensionsystem/pluginspec.cpp @@ -6,7 +6,6 @@ #include "extensionsystemtr.h" #include "iplugin.h" #include "pluginmanager.h" -#include "pluginspec_p.h" #include #include @@ -25,6 +24,7 @@ #include using namespace ExtensionSystem::Internal; +using namespace Utils; namespace ExtensionSystem { @@ -168,22 +168,78 @@ QString PluginDependency::toString() const return name + " (" + version + typeString(type) + ")"; } -/*! - \internal -*/ -PluginSpec::PluginSpec() - : d(new PluginSpecPrivate(this)) +namespace Internal { +class PluginSpecImplPrivate { -} +public: + std::optional loader; + std::optional staticPlugin; + + IPlugin *plugin; +}; + +class PluginSpecPrivate +{ +public: + ExtensionSystem::PerformanceData performanceData; + + QString name; + QString version; + QString compatVersion; + QString vendor; + QString category; + QString description; + QString longDescription; + QString url; + QString license; + QString revision; + QString copyright; + QStringList arguments; + QRegularExpression platformSpecification; + QVector dependencies; + + PluginSpecImpl::PluginArgumentDescriptions argumentDescriptions; + QString location; + QString filePath; + + bool experimental{false}; + bool deprecated{false}; + bool required{false}; + + bool enabledByDefault{false}; + bool enabledBySettings{true}; + bool enabledIndirectly{false}; + bool forceEnabled{false}; + bool forceDisabled{false}; + bool softLoadable{false}; + + std::optional errorString; + + PluginSpec::State state; + QHash dependencySpecs; + + QJsonObject metaData; + + Utils::expected_str readMetaData(const QJsonObject &metaData); + Utils::expected_str reportError(const QString &error) + { + errorString = error; + return {}; + }; +}; +} // namespace Internal /*! \internal */ -PluginSpec::~PluginSpec() -{ - delete d; - d = nullptr; -} +PluginSpecImpl::PluginSpecImpl() + : d(new PluginSpecImplPrivate) +{} + +/*! + \internal +*/ +PluginSpecImpl::~PluginSpecImpl() = default; /*! Returns the plugin name. This is valid after the PluginSpec::Read state is @@ -278,10 +334,7 @@ QString PluginSpec::category() const QString PluginSpec::revision() const { - const QJsonValue revision = metaData().value("Revision"); - if (revision.isString()) - return revision.toString(); - return QString(); + return d->revision; } /*! @@ -419,7 +472,7 @@ QJsonObject PluginSpec::metaData() const return d->metaData; } -const PerformanceData &PluginSpec::performanceData() const +PerformanceData &PluginSpec::performanceData() const { return d->performanceData; } @@ -491,7 +544,7 @@ PluginSpec::State PluginSpec::state() const */ bool PluginSpec::hasError() const { - return d->hasError; + return d->errorString.has_value(); } /*! @@ -500,7 +553,7 @@ bool PluginSpec::hasError() const */ QString PluginSpec::errorString() const { - return d->errorString; + return d->errorString.value_or(QString()); } /*! @@ -509,9 +562,13 @@ QString PluginSpec::errorString() const \sa PluginSpec::dependencies() */ -bool PluginSpec::provides(const QString &pluginName, const QString &version) const +bool PluginSpec::provides(const QString &pluginName, const QString &pluginVersion) const { - return d->provides(pluginName, version); + if (QString::compare(pluginName, name(), Qt::CaseInsensitive) != 0) + return false; + + return (versionCompare(version(), pluginVersion) >= 0) + && (versionCompare(compatVersion(), pluginVersion) <= 0); } /*! @@ -519,7 +576,7 @@ bool PluginSpec::provides(const QString &pluginName, const QString &version) con already been successfully loaded. That is, the PluginSpec::Loaded state is reached. */ -IPlugin *PluginSpec::plugin() const +IPlugin *PluginSpecImpl::plugin() const { return d->plugin; } @@ -548,6 +605,11 @@ bool PluginSpec::requiresAny(const QSet &plugins) const return false; } +void PluginSpec::setEnabledByDefault(bool value) +{ + d->enabledByDefault = value; +} + /*! Sets whether the plugin should be loaded at startup to \a value. @@ -555,27 +617,40 @@ bool PluginSpec::requiresAny(const QSet &plugins) const */ void PluginSpec::setEnabledBySettings(bool value) { - d->setEnabledBySettings(value); + d->enabledBySettings = value; +} +void PluginSpec::setEnabledIndirectly(bool value) +{ + d->enabledIndirectly = value; +} +void PluginSpec::setForceDisabled(bool value) +{ + d->forceDisabled = value; +} +void PluginSpec::setForceEnabled(bool value) +{ + d->forceEnabled = value; } -PluginSpec *PluginSpec::read(const QString &filePath) +// returns the plugins that it actually indirectly enabled +QVector PluginSpec::enableDependenciesIndirectly(bool enableTestDependencies) { - auto spec = new PluginSpec; - if (!spec->d->read(filePath)) { // not a Qt Creator plugin - delete spec; - return nullptr; - } - return spec; -} + if (!isEffectivelyEnabled()) // plugin not enabled, nothing to do + return {}; -PluginSpec *PluginSpec::read(const QStaticPlugin &plugin) -{ - auto spec = new PluginSpec; - if (!spec->d->read(plugin)) { // not a Qt Creator plugin - delete spec; - return nullptr; + QVector enabled; + for (auto it = d->dependencySpecs.cbegin(), end = d->dependencySpecs.cend(); it != end; ++it) { + if (it.key().type != PluginDependency::Required + && (!enableTestDependencies || it.key().type != PluginDependency::Test)) + continue; + + PluginSpec *dependencySpec = it.value(); + if (!dependencySpec->isEffectivelyEnabled()) { + dependencySpec->setEnabledIndirectly(true); + enabled << dependencySpec; + } } - return spec; + return enabled; } //==========PluginSpecPrivate================== @@ -610,112 +685,45 @@ namespace { const char ARGUMENT_PARAMETER[] = "Parameter"; const char ARGUMENT_DESCRIPTION[] = "Description"; } -/*! - \internal -*/ -PluginSpecPrivate::PluginSpecPrivate(PluginSpec *spec) - : q(spec) -{} - -void PluginSpecPrivate::reset() -{ - name.clear(); - version.clear(); - compatVersion.clear(); - vendor.clear(); - copyright.clear(); - license.clear(); - description.clear(); - longDescription.clear(); - url.clear(); - category.clear(); - location.clear(); - filePath.clear(); - state = PluginSpec::Invalid; - hasError = false; - errorString.clear(); - dependencies.clear(); - metaData = QJsonObject(); - loader.reset(); - staticPlugin.reset(); -} /*! \internal Returns false if the file does not represent a Qt Creator plugin. */ -bool PluginSpecPrivate::read(const QString &fileName) +expected_str PluginSpecImpl::read(const QString &fileName) { - qCDebug(pluginLog) << "\nReading meta data of" << fileName; - reset(); + auto spec = new PluginSpecImpl; + QFileInfo fileInfo(fileName); - location = fileInfo.absolutePath(); - filePath = fileInfo.absoluteFilePath(); - loader.emplace(); + spec->setLocation(fileInfo.absolutePath()); + spec->setFilePath(fileInfo.absoluteFilePath()); + spec->d->loader.emplace(); + if (Utils::HostOsInfo::isMacHost()) - loader->setLoadHints(QLibrary::ExportExternalSymbolsHint); - loader->setFileName(filePath); - if (loader->fileName().isEmpty()) { - qCDebug(pluginLog) << "Cannot open file"; - return false; - } + spec->d->loader->setLoadHints(QLibrary::ExportExternalSymbolsHint); - if (!readMetaData(loader->metaData())) - return false; + spec->d->loader->setFileName(fileInfo.absoluteFilePath()); + if (spec->d->loader->fileName().isEmpty()) + return make_unexpected(::ExtensionSystem::Tr::tr("Cannot open file")); - state = PluginSpec::Read; - return true; + expected_str r = spec->readMetaData(spec->d->loader->metaData()); + if (!r) + return make_unexpected(r.error()); + + return spec; } -bool PluginSpecPrivate::read(const QStaticPlugin &plugin) +expected_str PluginSpecImpl::read(const QStaticPlugin &plugin) { + auto spec = new PluginSpecImpl; + qCDebug(pluginLog) << "\nReading meta data of static plugin"; - reset(); - staticPlugin = plugin; - if (!readMetaData(plugin.metaData())) - return false; + spec->d->staticPlugin = plugin; + expected_str r = spec->readMetaData(plugin.metaData()); + if (!r) + return make_unexpected(r.error()); - state = PluginSpec::Read; - return true; -} - -void PluginSpecPrivate::setEnabledBySettings(bool value) -{ - enabledBySettings = value; -} - -void PluginSpecPrivate::setEnabledByDefault(bool value) -{ - enabledByDefault = value; -} - -void PluginSpecPrivate::setForceEnabled(bool value) -{ - forceEnabled = value; - if (value) - forceDisabled = false; -} - -void PluginSpecPrivate::setForceDisabled(bool value) -{ - if (value) - forceEnabled = false; - forceDisabled = value; -} - -void PluginSpecPrivate::setSoftLoadable(bool value) -{ - softLoadable = value; -} - -/*! - \internal -*/ -bool PluginSpecPrivate::reportError(const QString &err) -{ - errorString = err; - hasError = true; - return true; + return spec; } static inline QString msgValueMissing(const char *key) @@ -725,58 +733,67 @@ static inline QString msgValueMissing(const char *key) static inline QString msgValueIsNotAString(const char *key) { - return Tr::tr("Value for key \"%1\" is not a string") - .arg(QLatin1String(key)); + return Tr::tr("Value for key \"%1\" is not a string").arg(QLatin1String(key)); } static inline QString msgValueIsNotABool(const char *key) { - return Tr::tr("Value for key \"%1\" is not a bool") - .arg(QLatin1String(key)); + return Tr::tr("Value for key \"%1\" is not a bool").arg(QLatin1String(key)); } static inline QString msgValueIsNotAObjectArray(const char *key) { - return Tr::tr("Value for key \"%1\" is not an array of objects") - .arg(QLatin1String(key)); + return Tr::tr("Value for key \"%1\" is not an array of objects").arg(QLatin1String(key)); } static inline QString msgValueIsNotAMultilineString(const char *key) { return Tr::tr("Value for key \"%1\" is not a string and not an array of strings") - .arg(QLatin1String(key)); + .arg(QLatin1String(key)); } static inline QString msgInvalidFormat(const char *key, const QString &content) { - return Tr::tr("Value \"%2\" for key \"%1\" has invalid format") - .arg(QLatin1String(key), content); + return Tr::tr("Value \"%2\" for key \"%1\" has invalid format").arg(QLatin1String(key), content); +} + +Utils::expected_str PluginSpec::readMetaData(const QJsonObject &metaData) +{ + return d->readMetaData(metaData); +} +Utils::expected_str PluginSpec::reportError(const QString &error) +{ + return d->reportError(error); } /*! \internal */ -bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) +expected_str PluginSpecImpl::readMetaData(const QJsonObject &pluginMetaData) { - qCDebug(pluginLog) << "MetaData:" << QJsonDocument(pluginMetaData).toJson(); + qCDebug(pluginLog).noquote() << "MetaData:" << QJsonDocument(pluginMetaData).toJson(); QJsonValue value; value = pluginMetaData.value(QLatin1String("IID")); - if (!value.isString()) { - qCDebug(pluginLog) << "Not a plugin (no string IID found)"; - return false; - } - if (value.toString() != PluginManager::pluginIID()) { - qCDebug(pluginLog) << "Plugin ignored (IID does not match)"; - return false; - } + if (!value.isString()) + return make_unexpected(::ExtensionSystem::Tr::tr("No IID found")); + + if (value.toString() != PluginManager::pluginIID()) + return make_unexpected(::ExtensionSystem::Tr::tr("Expected IID \"%1\", but found \"%2\"") + .arg(PluginManager::pluginIID()) + .arg(value.toString())); value = pluginMetaData.value(QLatin1String(PLUGIN_METADATA)); - if (!value.isObject()) { + if (!value.isObject()) return reportError(::ExtensionSystem::Tr::tr("Plugin meta data not found")); - } - metaData = value.toObject(); - value = metaData.value(QLatin1String(PLUGIN_NAME)); + return PluginSpec::readMetaData(value.toObject()); +} + +Utils::expected_str PluginSpecPrivate::readMetaData(const QJsonObject &data) +{ + metaData = data; + + QJsonValue value = metaData.value(QLatin1String(PLUGIN_NAME)); if (value.isUndefined()) return reportError(msgValueMissing(PLUGIN_NAME)); if (!value.isString()) @@ -789,14 +806,14 @@ bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) if (!value.isString()) return reportError(msgValueIsNotAString(PLUGIN_VERSION)); version = value.toString(); - if (!isValidVersion(version)) + if (!PluginSpec::isValidVersion(version)) return reportError(msgInvalidFormat(PLUGIN_VERSION, version)); value = metaData.value(QLatin1String(PLUGIN_COMPATVERSION)); if (!value.isUndefined() && !value.isString()) return reportError(msgValueIsNotAString(PLUGIN_COMPATVERSION)); compatVersion = value.toString(version); - if (!value.isUndefined() && !isValidVersion(compatVersion)) + if (!value.isUndefined() && !PluginSpec::isValidVersion(compatVersion)) return reportError(msgInvalidFormat(PLUGIN_COMPATVERSION, compatVersion)); value = metaData.value(QLatin1String(PLUGIN_REQUIRED)); @@ -844,11 +861,11 @@ bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) copyright = value.toString(); value = metaData.value(QLatin1String(DESCRIPTION)); - if (!value.isUndefined() && !Utils::readMultiLineString(value, &description)) + if (!value.isUndefined() && !readMultiLineString(value, &description)) return reportError(msgValueIsNotAString(DESCRIPTION)); value = metaData.value(QLatin1String(LONGDESCRIPTION)); - if (!value.isUndefined() && !Utils::readMultiLineString(value, &longDescription)) + if (!value.isUndefined() && !readMultiLineString(value, &longDescription)) return reportError(msgValueIsNotAString(LONGDESCRIPTION)); value = metaData.value(QLatin1String(URL)); @@ -862,9 +879,14 @@ bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) category = value.toString(); value = metaData.value(QLatin1String(LICENSE)); - if (!value.isUndefined() && !Utils::readMultiLineString(value, &license)) + if (!value.isUndefined() && !readMultiLineString(value, &license)) return reportError(msgValueIsNotAMultilineString(LICENSE)); + value = metaData.value("Revision"); + if (!value.isUndefined() && !value.isString()) + return reportError(msgValueIsNotAString("Revision")); + revision = value.toString(); + value = metaData.value(QLatin1String(PLATFORM)); if (!value.isUndefined() && !value.isString()) return reportError(msgValueIsNotAString(PLATFORM)); @@ -906,7 +928,7 @@ bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) .arg(msgValueIsNotAString(DEPENDENCY_VERSION))); } dep.version = value.toString(); - if (!isValidVersion(dep.version)) { + if (!PluginSpec::isValidVersion(dep.version)) { return reportError( ::ExtensionSystem::Tr::tr("Dependency: %1") .arg(msgInvalidFormat(DEPENDENCY_VERSION, dep.version))); @@ -987,23 +1009,15 @@ bool PluginSpecPrivate::readMetaData(const QJsonObject &pluginMetaData) } } - return true; + state = PluginSpecImpl::Read; + + return {}; } /*! \internal */ -bool PluginSpecPrivate::provides(const QString &pluginName, const QString &pluginVersion) const -{ - if (QString::compare(pluginName, name, Qt::CaseInsensitive) != 0) - return false; - return (versionCompare(version, pluginVersion) >= 0) && (versionCompare(compatVersion, pluginVersion) <= 0); -} - -/*! - \internal -*/ -const QRegularExpression &PluginSpecPrivate::versionRegExp() +static const QRegularExpression &versionRegExp() { static const QRegularExpression reg("^([0-9]+)(?:[.]([0-9]+))?(?:[.]([0-9]+))?(?:_([0-9]+))?$"); return reg; @@ -1011,7 +1025,7 @@ const QRegularExpression &PluginSpecPrivate::versionRegExp() /*! \internal */ -bool PluginSpecPrivate::isValidVersion(const QString &version) +bool PluginSpec::isValidVersion(const QString &version) { return versionRegExp().match(version).hasMatch(); } @@ -1019,7 +1033,7 @@ bool PluginSpecPrivate::isValidVersion(const QString &version) /*! \internal */ -int PluginSpecPrivate::versionCompare(const QString &version1, const QString &version2) +int PluginSpec::versionCompare(const QString &version1, const QString &version2) { const QRegularExpressionMatch match1 = versionRegExp().match(version1); const QRegularExpressionMatch match2 = versionRegExp().match(version2); @@ -1041,196 +1055,205 @@ int PluginSpecPrivate::versionCompare(const QString &version1, const QString &ve /*! \internal */ -bool PluginSpecPrivate::resolveDependencies(const QVector &specs) +bool PluginSpec::resolveDependencies(const QVector &specs) { - if (hasError) + if (hasError()) return false; - if (state == PluginSpec::Resolved) - state = PluginSpec::Read; // Go back, so we just re-resolve the dependencies. - if (state != PluginSpec::Read) { - errorString = ::ExtensionSystem::Tr::tr("Resolving dependencies failed because state != Read"); - hasError = true; + if (state() > PluginSpecImpl::Resolved) + return true; // We are resolved already. + if (state() == PluginSpecImpl::Resolved) + setState(PluginSpecImpl::Read); // Go back, so we just re-resolve the dependencies. + if (state() != PluginSpecImpl::Read) { + setError(::ExtensionSystem::Tr::tr("Resolving dependencies failed because state != Read")); return false; } + QHash resolvedDependencies; - for (const PluginDependency &dependency : std::as_const(dependencies)) { - PluginSpec * const found = Utils::findOrDefault(specs, [&dependency](PluginSpec *spec) { + for (const PluginDependency &dependency : d->dependencies) { + PluginSpec *const found = findOrDefault(specs, [&dependency](PluginSpec *spec) { return spec->provides(dependency.name, dependency.version); }); if (!found) { if (dependency.type == PluginDependency::Required) { - hasError = true; - if (!errorString.isEmpty()) - errorString.append(QLatin1Char('\n')); - errorString.append(::ExtensionSystem::Tr::tr("Could not resolve dependency '%1(%2)'") - .arg(dependency.name, dependency.version)); + const QString error = ::ExtensionSystem::Tr::tr( + "Could not resolve dependency '%1(%2)'") + .arg(dependency.name, dependency.version); + if (hasError()) + setError(errorString() + '\n' + error); + else + setError(error); } continue; } resolvedDependencies.insert(dependency, found); } - if (hasError) + if (hasError()) return false; - dependencySpecs = resolvedDependencies; + d->dependencySpecs = resolvedDependencies; - state = PluginSpec::Resolved; + d->state = PluginSpecImpl::Resolved; return true; } -// returns the plugins that it actually indirectly enabled -QVector PluginSpecPrivate::enableDependenciesIndirectly(bool enableTestDependencies) +PluginSpec::PluginSpec() + : d(new PluginSpecPrivate()) +{} + +PluginSpec::~PluginSpec() = default; + +void PluginSpec::setState(State state) { - if (!q->isEffectivelyEnabled()) // plugin not enabled, nothing to do - return {}; - QVector enabled; - for (auto it = dependencySpecs.cbegin(), end = dependencySpecs.cend(); it != end; ++it) { - if (it.key().type != PluginDependency::Required - && (!enableTestDependencies || it.key().type != PluginDependency::Test)) - continue; - PluginSpec *dependencySpec = it.value(); - if (!dependencySpec->isEffectivelyEnabled()) { - dependencySpec->d->enabledIndirectly = true; - enabled << dependencySpec; - } - } - return enabled; + d->state = state; +} + +void PluginSpec::setLocation(const QString &location) +{ + d->location = location; +} + +void PluginSpec::setFilePath(const QString &filePath) +{ + d->filePath = filePath; +} + +void PluginSpec::setError(const QString &errorString) +{ + d->errorString = errorString; } /*! \internal */ -bool PluginSpecPrivate::loadLibrary() +bool PluginSpecImpl::loadLibrary() { - if (hasError) + if (hasError()) return false; - if (state != PluginSpec::Resolved) { - if (state == PluginSpec::Loaded) + + if (state() != PluginSpecImpl::Resolved) { + if (state() == PluginSpecImpl::Loaded) return true; - errorString = - ::ExtensionSystem::Tr::tr("Loading the library failed because state != Resolved"); - hasError = true; + setError(::ExtensionSystem::Tr::tr("Loading the library failed because state != Resolved")); return false; } - if (loader && !loader->load()) { - hasError = true; - errorString = QDir::toNativeSeparators(filePath) + QString::fromLatin1(": ") - + loader->errorString(); + if (d->loader && !d->loader->load()) { + setError(QDir::toNativeSeparators(filePath()) + QString::fromLatin1(": ") + + d->loader->errorString()); return false; } - auto *pluginObject = loader ? qobject_cast(loader->instance()) - : qobject_cast(staticPlugin->instance()); + auto *pluginObject = d->loader ? qobject_cast(d->loader->instance()) + : qobject_cast(d->staticPlugin->instance()); if (!pluginObject) { - hasError = true; - errorString = - ::ExtensionSystem::Tr::tr("Plugin is not valid (does not derive from IPlugin)"); - if (loader) - loader->unload(); + setError(::ExtensionSystem::Tr::tr("Plugin is not valid (does not derive from IPlugin)")); + if (d->loader) + d->loader->unload(); return false; } - state = PluginSpec::Loaded; - plugin = pluginObject; + setState(PluginSpecImpl::Loaded); + d->plugin = pluginObject; return true; } /*! \internal */ -bool PluginSpecPrivate::initializePlugin() +bool PluginSpecImpl::initializePlugin() { - if (hasError) + if (hasError()) return false; - if (state != PluginSpec::Loaded) { - if (state == PluginSpec::Initialized) + + if (state() != PluginSpecImpl::Loaded) { + if (state() == PluginSpecImpl::Initialized) return true; - errorString = ::ExtensionSystem::Tr::tr( - "Initializing the plugin failed because state != Loaded"); - hasError = true; + setError( + ::ExtensionSystem::Tr::tr("Initializing the plugin failed because state != Loaded")); return false; } - if (!plugin) { - errorString = ::ExtensionSystem::Tr::tr( - "Internal error: have no plugin instance to initialize"); - hasError = true; + if (!d->plugin) { + setError( + ::ExtensionSystem::Tr::tr("Internal error: have no plugin instance to initialize")); return false; } QString err; - if (!plugin->initialize(arguments, &err)) { - errorString = ::ExtensionSystem::Tr::tr("Plugin initialization failed: %1").arg(err); - hasError = true; + if (!d->plugin->initialize(arguments(), &err)) { + setError(::ExtensionSystem::Tr::tr("Plugin initialization failed: %1").arg(err)); return false; } - state = PluginSpec::Initialized; + setState(PluginSpecImpl::Initialized); return true; } /*! \internal */ -bool PluginSpecPrivate::initializeExtensions() +bool PluginSpecImpl::initializeExtensions() { - if (hasError) + if (hasError()) return false; - if (state != PluginSpec::Initialized) { - if (state == PluginSpec::Running) + + if (state() != PluginSpecImpl::Initialized) { + if (state() == PluginSpecImpl::Running) return true; - errorString = ::ExtensionSystem::Tr::tr( - "Cannot perform extensionsInitialized because state != Initialized"); - hasError = true; + setError(::ExtensionSystem::Tr::tr( + "Cannot perform extensionsInitialized because state != Initialized")); return false; } - if (!plugin) { - errorString = ::ExtensionSystem::Tr::tr( - "Internal error: have no plugin instance to perform extensionsInitialized"); - hasError = true; + if (!d->plugin) { + setError(::ExtensionSystem::Tr::tr( + "Internal error: have no plugin instance to perform extensionsInitialized")); return false; } - plugin->extensionsInitialized(); - state = PluginSpec::Running; + d->plugin->extensionsInitialized(); + setState(PluginSpecImpl::Running); return true; } /*! \internal */ -bool PluginSpecPrivate::delayedInitialize() +bool PluginSpecImpl::delayedInitialize() { - if (hasError) + if (hasError()) + return true; + + if (state() != PluginSpecImpl::Running) return false; - if (state != PluginSpec::Running) - return false; - if (!plugin) { - errorString = ::ExtensionSystem::Tr::tr( - "Internal error: have no plugin instance to perform delayedInitialize"); - hasError = true; + if (!d->plugin) { + setError(::ExtensionSystem::Tr::tr( + "Internal error: have no plugin instance to perform delayedInitialize")); return false; } - const bool res = plugin->delayedInitialize(); + const bool res = d->plugin->delayedInitialize(); return res; } /*! \internal */ -IPlugin::ShutdownFlag PluginSpecPrivate::stop() +IPlugin::ShutdownFlag PluginSpecImpl::stop() { - if (!plugin) + if (hasError()) + return IPlugin::ShutdownFlag::SynchronousShutdown; + + if (!d->plugin) return IPlugin::SynchronousShutdown; - state = PluginSpec::Stopped; - return plugin->aboutToShutdown(); + setState(PluginSpecImpl::Stopped); + return d->plugin->aboutToShutdown(); } /*! \internal */ -void PluginSpecPrivate::kill() +void PluginSpecImpl::kill() { - if (!plugin) + if (hasError()) return; - delete plugin; - plugin = nullptr; - state = PluginSpec::Deleted; -} -} // ExtensionSystem + if (!d->plugin) + return; + delete d->plugin; + d->plugin = nullptr; + setState(PluginSpecImpl::Deleted); +} +} // namespace ExtensionSystem diff --git a/src/libs/extensionsystem/pluginspec.h b/src/libs/extensionsystem/pluginspec.h index 8db6bb44114..09b8f55618f 100644 --- a/src/libs/extensionsystem/pluginspec.h +++ b/src/libs/extensionsystem/pluginspec.h @@ -5,6 +5,10 @@ #include "extensionsystem_global.h" +#include "iplugin.h" + +#include + #include #include #include @@ -14,17 +18,19 @@ QT_BEGIN_NAMESPACE class QRegularExpression; QT_END_NAMESPACE +class tst_PluginSpec; + namespace ExtensionSystem { namespace Internal { class OptionsParser; -class PluginSpecPrivate; +class PluginSpecImplPrivate; class PluginManagerPrivate; +class PluginSpecPrivate; } // Internal -class IPlugin; class PluginView; struct EXTENSIONSYSTEM_EXPORT PluginDependency @@ -37,8 +43,6 @@ struct EXTENSIONSYSTEM_EXPORT PluginDependency PluginDependency() : type(Required) {} - friend size_t qHash(const PluginDependency &value); - QString name; QString version; Type type; @@ -46,6 +50,8 @@ struct EXTENSIONSYSTEM_EXPORT PluginDependency QString toString() const; }; +size_t EXTENSIONSYSTEM_EXPORT qHash(const PluginDependency &value); + struct EXTENSIONSYSTEM_EXPORT PluginArgumentDescription { QString name; @@ -73,77 +79,126 @@ struct EXTENSIONSYSTEM_EXPORT PerformanceData class EXTENSIONSYSTEM_EXPORT PluginSpec { + friend class ::tst_PluginSpec; + friend class Internal::PluginManagerPrivate; + friend class Internal::OptionsParser; + public: - enum State { Invalid, Read, Resolved, Loaded, Initialized, Running, Stopped, Deleted}; - - ~PluginSpec(); - - // information from the xml file, valid after 'Read' state is reached - QString name() const; - QString version() const; - QString compatVersion() const; - QString vendor() const; - QString copyright() const; - QString license() const; - QString description() const; - QString longDescription() const; - QString url() const; - QString category() const; - QString revision() const; - QRegularExpression platformSpecification() const; - bool isAvailableForHostPlatform() const; - bool isRequired() const; - bool isExperimental() const; - bool isDeprecated() const; - bool isEnabledByDefault() const; - bool isEnabledBySettings() const; - bool isEffectivelyEnabled() const; - bool isEnabledIndirectly() const; - bool isForceEnabled() const; - bool isForceDisabled() const; - bool isSoftLoadable() const; - QVector dependencies() const; - QJsonObject metaData() const; - const PerformanceData &performanceData() const; + PluginSpec(); + virtual ~PluginSpec(); using PluginArgumentDescriptions = QVector; - PluginArgumentDescriptions argumentDescriptions() const; + enum State { Invalid, Read, Resolved, Loaded, Initialized, Running, Stopped, Deleted}; - // other information, valid after 'Read' state is reached - QString location() const; - QString filePath() const; + // information read from the plugin, valid after 'Read' state is reached + virtual QString name() const; + virtual QString version() const; + virtual QString compatVersion() const; + virtual QString vendor() const; + virtual QString copyright() const; + virtual QString license() const; + virtual QString description() const; + virtual QString longDescription() const; + virtual QString url() const; + virtual QString category() const; + virtual QString revision() const; + virtual QRegularExpression platformSpecification() const; - QStringList arguments() const; - void setArguments(const QStringList &arguments); - void addArgument(const QString &argument); + virtual bool isAvailableForHostPlatform() const; + virtual bool isRequired() const; + virtual bool isExperimental() const; + virtual bool isDeprecated() const; + virtual bool isEnabledByDefault() const; + virtual bool isEnabledBySettings() const; + virtual bool isEffectivelyEnabled() const; + virtual bool isEnabledIndirectly() const; + virtual bool isForceEnabled() const; + virtual bool isForceDisabled() const; + virtual bool isSoftLoadable() const; - bool provides(const QString &pluginName, const QString &version) const; + virtual QVector dependencies() const; + virtual QJsonObject metaData() const; + virtual PerformanceData &performanceData() const; + virtual PluginArgumentDescriptions argumentDescriptions() const; + virtual QString location() const; + virtual QString filePath() const; + virtual QStringList arguments() const; + virtual void setArguments(const QStringList &arguments); + virtual void addArgument(const QString &argument); + virtual QHash dependencySpecs() const; - // dependency specs, valid after 'Resolved' state is reached - QHash dependencySpecs() const; - bool requiresAny(const QSet &plugins) const; + virtual bool provides(const QString &pluginName, const QString &pluginVersion) const; + virtual bool requiresAny(const QSet &plugins) const; + virtual QVector enableDependenciesIndirectly(bool enableTestDependencies); + virtual bool resolveDependencies(const QVector &pluginSpecs); - // linked plugin instance, valid after 'Loaded' state is reached - IPlugin *plugin() const; + virtual IPlugin *plugin() const = 0; + virtual State state() const; + virtual bool hasError() const; + virtual QString errorString() const; - // state - State state() const; - bool hasError() const; - QString errorString() const; + static bool isValidVersion(const QString &version); + static int versionCompare(const QString &version1, const QString &version2); - void setEnabledBySettings(bool value); + virtual void setEnabledBySettings(bool value); - static PluginSpec *read(const QString &filePath); - static PluginSpec *read(const QStaticPlugin &plugin); +protected: + virtual void setEnabledByDefault(bool value); + virtual void setEnabledIndirectly(bool value); + virtual void setForceDisabled(bool value); + virtual void setForceEnabled(bool value); + + virtual bool loadLibrary() = 0; + virtual bool initializePlugin() = 0; + virtual bool initializeExtensions() = 0; + virtual bool delayedInitialize() = 0; + virtual IPlugin::ShutdownFlag stop() = 0; + virtual void kill() = 0; + + virtual void setError(const QString &errorString); + +protected: + virtual void setState(State state); + + virtual void setLocation(const QString &location); + virtual void setFilePath(const QString &filePath); + virtual Utils::expected_str readMetaData(const QJsonObject &metaData); + Utils::expected_str reportError(const QString &error); private: - PluginSpec(); + std::unique_ptr d; +}; - Internal::PluginSpecPrivate *d; +class EXTENSIONSYSTEM_TEST_EXPORT PluginSpecImpl : public PluginSpec +{ +public: + ~PluginSpecImpl() override; + + // linked plugin instance, valid after 'Loaded' state is reached + IPlugin *plugin() const override; + + bool loadLibrary() override; + bool initializePlugin() override; + bool initializeExtensions() override; + bool delayedInitialize() override; + IPlugin::ShutdownFlag stop() override; + void kill() override; + + static Utils::expected_str read(const QString &filePath); + static Utils::expected_str read(const QStaticPlugin &plugin); + + Utils::expected_str readMetaData(const QJsonObject &pluginMetaData) override; + +protected: + PluginSpecImpl(); + +private: + std::unique_ptr d; friend class PluginView; friend class Internal::OptionsParser; friend class Internal::PluginManagerPrivate; - friend class Internal::PluginSpecPrivate; + friend class Internal::PluginSpecImplPrivate; + friend class ::tst_PluginSpec; }; } // namespace ExtensionSystem diff --git a/src/libs/extensionsystem/pluginspec_p.h b/src/libs/extensionsystem/pluginspec_p.h deleted file mode 100644 index 61832213cad..00000000000 --- a/src/libs/extensionsystem/pluginspec_p.h +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "pluginspec.h" -#include "iplugin.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace ExtensionSystem { - -class IPlugin; - -namespace Internal { - -class EXTENSIONSYSTEM_TEST_EXPORT PluginSpecPrivate : public QObject -{ - Q_OBJECT - -public: - PluginSpecPrivate(PluginSpec *spec); - - void reset(); - bool read(const QString &fileName); - bool read(const QStaticPlugin &plugin); - bool provides(const QString &pluginName, const QString &version) const; - bool resolveDependencies(const QVector &specs); - bool loadLibrary(); - bool initializePlugin(); - bool initializeExtensions(); - bool delayedInitialize(); - IPlugin::ShutdownFlag stop(); - void kill(); - - void setEnabledBySettings(bool value); - void setEnabledByDefault(bool value); - void setForceEnabled(bool value); - void setForceDisabled(bool value); - void setSoftLoadable(bool value); - - std::optional loader; - std::optional staticPlugin; - - QString name; - QString version; - QString compatVersion; - bool required = false; - bool experimental = false; - bool enabledByDefault = true; - bool deprecated = false; - QString vendor; - QString copyright; - QString license; - QString description; - QString longDescription; - QString url; - QString category; - QRegularExpression platformSpecification; - QVector dependencies; - QJsonObject metaData; - bool enabledBySettings = true; - bool enabledIndirectly = false; - bool forceEnabled = false; - bool forceDisabled = false; - bool softLoadable = false; - - QString location; - QString filePath; - QStringList arguments; - - QHash dependencySpecs; - PluginSpec::PluginArgumentDescriptions argumentDescriptions; - IPlugin *plugin = nullptr; - - QList registeredPluginTests; - - PluginSpec::State state = PluginSpec::Invalid; - bool hasError = false; - QString errorString; - - PerformanceData performanceData; - - static bool isValidVersion(const QString &version); - static int versionCompare(const QString &version1, const QString &version2); - - QVector enableDependenciesIndirectly(bool enableTestDependencies = false); - - bool readMetaData(const QJsonObject &pluginMetaData); - -private: - PluginSpec *q; - - bool reportError(const QString &err); - static const QRegularExpression &versionRegExp(); -}; - -} // namespace Internal -} // namespace ExtensionSystem diff --git a/src/libs/extensionsystem/pluginview.cpp b/src/libs/extensionsystem/pluginview.cpp index 40738be487f..07fa11c7a9a 100644 --- a/src/libs/extensionsystem/pluginview.cpp +++ b/src/libs/extensionsystem/pluginview.cpp @@ -5,7 +5,7 @@ #include "extensionsystemtr.h" #include "pluginmanager.h" -#include "pluginspec_p.h" +#include "pluginspec.h" #include #include @@ -416,8 +416,8 @@ bool PluginView::setPluginsEnabled(const QSet &plugins, bool enabl }); QTC_ASSERT(item, continue); if (m_affectedPlugins.find(spec) == m_affectedPlugins.end()) - m_affectedPlugins[spec] = spec->d->enabledBySettings; - spec->d->setEnabledBySettings(enable); + m_affectedPlugins[spec] = spec->isEnabledBySettings(); + spec->setEnabledBySettings(enable); item->updateColumn(LoadedColumn); item->parent()->updateColumn(LoadedColumn); } @@ -428,7 +428,7 @@ bool PluginView::setPluginsEnabled(const QSet &plugins, bool enabl void PluginView::cancelChanges() { for (auto element : m_affectedPlugins) - element.first->d->setEnabledBySettings(element.second); + element.first->setEnabledBySettings(element.second); } } // namespace ExtensionSystem diff --git a/src/plugins/coreplugin/plugininstallwizard.cpp b/src/plugins/coreplugin/plugininstallwizard.cpp index 5b342bf6c6a..55d77496744 100644 --- a/src/plugins/coreplugin/plugininstallwizard.cpp +++ b/src/plugins/coreplugin/plugininstallwizard.cpp @@ -154,11 +154,11 @@ void checkContents(QPromise &promise, const FilePath &tempDir) if (promise.isCanceled()) return; it.next(); - PluginSpec *spec = PluginSpec::read(it.filePath()); + expected_str spec = PluginSpecImpl::read(it.filePath()); if (spec) { // Is a Qt Creator plugin. Let's see if we find a Core dependency and check the // version - const QVector dependencies = spec->dependencies(); + const QVector dependencies = (*spec)->dependencies(); const auto found = std::find_if(dependencies.constBegin(), dependencies.constEnd(), [coreplugin](const PluginDependency &d) { return d.name == coreplugin->name(); }); if (found == dependencies.constEnd()) diff --git a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong2.json b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong2.json index 2fd9df4d5d9..63a7fc5c551 100644 --- a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong2.json +++ b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong2.json @@ -11,6 +11,7 @@ "end of terms" ], "Description" : [ + "This spec is broken because no name is set.", "This plugin is just a test.", " it demonstrates the great use of the plugin spec." ], diff --git a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong3.json b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong3.json index 0b053f60140..7c43ef41d26 100644 --- a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong3.json +++ b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong3.json @@ -11,6 +11,7 @@ "end of terms" ], "Description" : [ + "This spec is wrong because no version is set.", "This plugin is just a test.", " it demonstrates the great use of the plugin spec." ], diff --git a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong4.json b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong4.json index c3a0d26922e..c8e1dd53d9f 100644 --- a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong4.json +++ b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong4.json @@ -12,6 +12,7 @@ "end of terms" ], "Description" : [ + "This spec is wrong because the first dependency has no name.", "This plugin is just a test.", " it demonstrates the great use of the plugin spec." ], diff --git a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong5.json b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong5.json index bdb095b3420..680ec4002ac 100644 --- a/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong5.json +++ b/tests/auto/extensionsystem/pluginspec/testspecs/spec_wrong5.json @@ -12,6 +12,7 @@ "end of terms" ], "Description" : [ + "This spec is wrong because the first dependencies version is invalid.", "This plugin is just a test.", " it demonstrates the great use of the plugin spec." ], diff --git a/tests/auto/extensionsystem/pluginspec/tst_pluginspec.cpp b/tests/auto/extensionsystem/pluginspec/tst_pluginspec.cpp index 762142b95ee..f919ef4139d 100644 --- a/tests/auto/extensionsystem/pluginspec/tst_pluginspec.cpp +++ b/tests/auto/extensionsystem/pluginspec/tst_pluginspec.cpp @@ -1,10 +1,9 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include -#include -#include #include +#include +#include #include #include @@ -85,109 +84,110 @@ void tst_PluginSpec::cleanupTestCase() void tst_PluginSpec::read() { - Internal::PluginSpecPrivate spec(0); - QCOMPARE(spec.state, PluginSpec::Invalid); + PluginSpecImpl spec; + QCOMPARE(spec.state(), PluginSpec::Invalid); QVERIFY(spec.readMetaData(metaData("testspecs/spec1.json"))); - QVERIFY(!spec.hasError); - QVERIFY(spec.errorString.isEmpty()); - QCOMPARE(spec.name, QString("test")); - QCOMPARE(spec.version, QString("1.0.1")); - QCOMPARE(spec.compatVersion, QString("1.0.0")); - QCOMPARE(spec.required, false); - QCOMPARE(spec.experimental, false); - QCOMPARE(spec.enabledBySettings, true); - QCOMPARE(spec.vendor, QString("The Qt Company Ltd")); - QCOMPARE(spec.copyright, QString("(C) 2015 The Qt Company Ltd")); - QCOMPARE(spec.license, QString("This is a default license bla\nblubbblubb\nend of terms")); - QCOMPARE(spec.description, QString("This plugin is just a test.")); + QVERIFY(!spec.hasError()); + QVERIFY(spec.errorString().isEmpty()); + QCOMPARE(spec.name(), QString("test")); + QCOMPARE(spec.version(), QString("1.0.1")); + QCOMPARE(spec.compatVersion(), QString("1.0.0")); + QCOMPARE(spec.isRequired(), false); + QCOMPARE(spec.isExperimental(), false); + QCOMPARE(spec.isEnabledBySettings(), true); + QCOMPARE(spec.vendor(), QString("The Qt Company Ltd")); + QCOMPARE(spec.copyright(), QString("(C) 2015 The Qt Company Ltd")); + QCOMPARE(spec.license(), QString("This is a default license bla\nblubbblubb\nend of terms")); + QCOMPARE(spec.description(), QString("This plugin is just a test.")); QCOMPARE( - spec.longDescription, + spec.longDescription(), QString( "This plugin is just a test.\n it demonstrates the great use of the plugin spec.")); - QCOMPARE(spec.url, QString("http://www.qt.io")); + QCOMPARE(spec.url(), QString("http://www.qt.io")); PluginDependency dep1; dep1.name = QString("SomeOtherPlugin"); dep1.version = QString("2.3.0_2"); PluginDependency dep2; dep2.name = QString("EvenOther"); dep2.version = QString("1.0.0"); - QCOMPARE(spec.dependencies, QVector() << dep1 << dep2); + QCOMPARE(spec.dependencies(), QVector() << dep1 << dep2); // test missing compatVersion behavior // and 'required' attribute QVERIFY(spec.readMetaData(metaData("testspecs/spec2.json"))); - QCOMPARE(spec.version, QString("3.1.4_10")); - QCOMPARE(spec.compatVersion, QString("3.1.4_10")); - QCOMPARE(spec.required, true); + QCOMPARE(spec.version(), QString("3.1.4_10")); + QCOMPARE(spec.compatVersion(), QString("3.1.4_10")); + QCOMPARE(spec.isRequired(), true); } void tst_PluginSpec::readError() { - Internal::PluginSpecPrivate spec(0); - QCOMPARE(spec.state, PluginSpec::Invalid); + PluginSpecImpl spec; + QCOMPARE(spec.state(), PluginSpec::Invalid); QVERIFY(!spec.readMetaData(metaData("non-existing-file.json"))); - QCOMPARE(spec.state, PluginSpec::Invalid); - QVERIFY(!spec.hasError); - QVERIFY(spec.errorString.isEmpty()); + QCOMPARE(spec.state(), PluginSpec::Invalid); + QVERIFY(!spec.hasError()); + QVERIFY(spec.errorString().isEmpty()); QVERIFY(spec.readMetaData(metaData("testspecs/spec_wrong2.json"))); - QCOMPARE(spec.state, PluginSpec::Invalid); - QVERIFY(spec.hasError); - QVERIFY(!spec.errorString.isEmpty()); + QCOMPARE(spec.state(), PluginSpec::Invalid); + QVERIFY(spec.hasError()); + QVERIFY(!spec.errorString().isEmpty()); QVERIFY(spec.readMetaData(metaData("testspecs/spec_wrong3.json"))); - QCOMPARE(spec.state, PluginSpec::Invalid); - QVERIFY(spec.hasError); - QVERIFY(!spec.errorString.isEmpty()); + QCOMPARE(spec.state(), PluginSpec::Invalid); + QVERIFY(spec.hasError()); + QVERIFY(!spec.errorString().isEmpty()); QVERIFY(spec.readMetaData(metaData("testspecs/spec_wrong4.json"))); - QCOMPARE(spec.state, PluginSpec::Invalid); - QVERIFY(spec.hasError); - QVERIFY(!spec.errorString.isEmpty()); + QCOMPARE(spec.state(), PluginSpec::Invalid); + QVERIFY(spec.hasError()); + QVERIFY(!spec.errorString().isEmpty()); QVERIFY(spec.readMetaData(metaData("testspecs/spec_wrong5.json"))); - QCOMPARE(spec.state, PluginSpec::Invalid); - QVERIFY(spec.hasError); - QVERIFY(!spec.errorString.isEmpty()); + QCOMPARE(spec.state(), PluginSpec::Invalid); + QVERIFY(spec.hasError()); + QVERIFY(!spec.errorString().isEmpty()); } void tst_PluginSpec::isValidVersion() { - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("2")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("53")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("52_1")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("3.12")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("31.1_12")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("31.1.0")); - QVERIFY(Internal::PluginSpecPrivate::isValidVersion("1.0.2_1")); + QVERIFY(PluginSpec::isValidVersion("2")); + QVERIFY(PluginSpec::isValidVersion("53")); + QVERIFY(PluginSpec::isValidVersion("52_1")); + QVERIFY(PluginSpec::isValidVersion("3.12")); + QVERIFY(PluginSpec::isValidVersion("31.1_12")); + QVERIFY(PluginSpec::isValidVersion("31.1.0")); + QVERIFY(PluginSpec::isValidVersion("1.0.2_1")); - QVERIFY(!Internal::PluginSpecPrivate::isValidVersion("")); - QVERIFY(!Internal::PluginSpecPrivate::isValidVersion("1..0")); - QVERIFY(!Internal::PluginSpecPrivate::isValidVersion("1.0_")); - QVERIFY(!Internal::PluginSpecPrivate::isValidVersion("1.0.0.0")); + QVERIFY(!PluginSpec::isValidVersion("")); + QVERIFY(!PluginSpec::isValidVersion("1..0")); + QVERIFY(!PluginSpec::isValidVersion("1.0_")); + QVERIFY(!PluginSpec::isValidVersion("1.0.0.0")); } void tst_PluginSpec::versionCompare() { - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3", "3") == 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.0.0", "3") == 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.0", "3") == 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.0.0_1", "3_1") == 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.0_21", "3_21") == 0); + QVERIFY(PluginSpec::versionCompare("3", "3") == 0); + QVERIFY(PluginSpec::versionCompare("3.0.0", "3") == 0); + QVERIFY(PluginSpec::versionCompare("3.0", "3") == 0); + QVERIFY(PluginSpec::versionCompare("3.0.0_1", "3_1") == 0); + QVERIFY(PluginSpec::versionCompare("3.0_21", "3_21") == 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3", "1") > 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3", "1.0_12") > 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3_1", "3") > 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.1.0_23", "3.1") > 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.1_23", "3.1_12") > 0); + QVERIFY(PluginSpec::versionCompare("3", "1") > 0); + QVERIFY(PluginSpec::versionCompare("3", "1.0_12") > 0); + QVERIFY(PluginSpec::versionCompare("3_1", "3") > 0); + QVERIFY(PluginSpec::versionCompare("3.1.0_23", "3.1") > 0); + QVERIFY(PluginSpec::versionCompare("3.1_23", "3.1_12") > 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("1", "3") < 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("1.0_12", "3") < 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3", "3_1") < 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.1", "3.1.0_23") < 0); - QVERIFY(Internal::PluginSpecPrivate::versionCompare("3.1_12", "3.1_23") < 0); + QVERIFY(PluginSpec::versionCompare("1", "3") < 0); + QVERIFY(PluginSpec::versionCompare("1.0_12", "3") < 0); + QVERIFY(PluginSpec::versionCompare("3", "3_1") < 0); + QVERIFY(PluginSpec::versionCompare("3.1", "3.1.0_23") < 0); + QVERIFY(PluginSpec::versionCompare("3.1_12", "3.1_23") < 0); } void tst_PluginSpec::provides() { - Internal::PluginSpecPrivate spec(0); + PluginSpecImpl spec; QVERIFY(spec.readMetaData(metaData("testspecs/simplespec.json"))); + QVERIFY(!spec.provides("SomeOtherPlugin", "2.2.3_9")); QVERIFY(!spec.provides("MyPlugin", "2.2.3_10")); QVERIFY(!spec.provides("MyPlugin", "2.2.4")); @@ -211,112 +211,132 @@ void tst_PluginSpec::provides() void tst_PluginSpec::experimental() { - Internal::PluginSpecPrivate spec(0); + PluginSpecImpl spec; QVERIFY(spec.readMetaData(metaData("testspecs/simplespec_experimental.json"))); - QCOMPARE(spec.experimental, true); - QCOMPARE(spec.enabledBySettings, false); + + QCOMPARE(spec.isExperimental(), true); + QCOMPARE(spec.isEnabledBySettings(), false); } void tst_PluginSpec::locationAndPath() { - Internal::PluginSpecPrivate spec(0); - QVERIFY(spec.read(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + libraryName(QLatin1String("test")))); - QCOMPARE(spec.location, QString(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin"))); - QCOMPARE(spec.filePath, QString(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + libraryName(QLatin1String("test")))); + Utils::expected_str ps = PluginSpecImpl::read( + QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + + libraryName(QLatin1String("test"))); + QVERIFY(ps); + PluginSpecImpl *spec = static_cast(ps.value()); + QCOMPARE(spec->location(), QString(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin"))); + QCOMPARE(spec->filePath(), + QString(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + + libraryName(QLatin1String("test")))); } void tst_PluginSpec::resolveDependencies() { QVector specs; - PluginSpec *spec1 = Internal::PluginManagerPrivate::createSpec(); + PluginSpec *spec1 = new PluginSpecImpl(); specs.append(spec1); - Internal::PluginSpecPrivate *spec1Priv = Internal::PluginManagerPrivate::privateSpec(spec1); - spec1Priv->readMetaData(metaData("testdependencies/spec1.json")); - spec1Priv->state = PluginSpec::Read; // fake read state for plugin resolving + spec1->readMetaData(metaData("testdependencies/spec1.json")); + spec1->setState(PluginSpec::Read); // fake read state for plugin resolving - PluginSpec *spec2 = Internal::PluginManagerPrivate::createSpec(); + PluginSpec *spec2 = new PluginSpecImpl(); specs.append(spec2); - Internal::PluginSpecPrivate *spec2Priv = Internal::PluginManagerPrivate::privateSpec(spec2); - spec2Priv->readMetaData(metaData("testdependencies/spec2.json")); - spec2Priv->state = PluginSpec::Read; // fake read state for plugin resolving + spec2->readMetaData(metaData("testdependencies/spec2.json")); + spec2->setState(PluginSpec::Read); // fake read state for plugin resolving - PluginSpec *spec3 = Internal::PluginManagerPrivate::createSpec(); + PluginSpec *spec3 = new PluginSpecImpl(); specs.append(spec3); - Internal::PluginSpecPrivate *spec3Priv = Internal::PluginManagerPrivate::privateSpec(spec3); - spec3Priv->readMetaData(metaData("testdependencies/spec3.json")); - spec3Priv->state = PluginSpec::Read; // fake read state for plugin resolving + spec3->readMetaData(metaData("testdependencies/spec3.json")); + spec3->setState(PluginSpec::Read); // fake read state for plugin resolving - PluginSpec *spec4 = Internal::PluginManagerPrivate::createSpec(); + PluginSpec *spec4 = new PluginSpecImpl(); specs.append(spec4); - Internal::PluginSpecPrivate *spec4Priv = Internal::PluginManagerPrivate::privateSpec(spec4); - spec4Priv->readMetaData(metaData("testdependencies/spec4.json")); - spec4Priv->state = PluginSpec::Read; // fake read state for plugin resolving + spec4->readMetaData(metaData("testdependencies/spec4.json")); + spec4->setState(PluginSpec::Read); // fake read state for plugin resolving - PluginSpec *spec5 = Internal::PluginManagerPrivate::createSpec(); + PluginSpec *spec5 = new PluginSpecImpl(); specs.append(spec5); - Internal::PluginSpecPrivate *spec5Priv = Internal::PluginManagerPrivate::privateSpec(spec5); - spec5Priv->readMetaData(metaData("testdependencies/spec5.json")); - spec5Priv->state = PluginSpec::Read; // fake read state for plugin resolving + spec5->readMetaData(metaData("testdependencies/spec5.json")); + spec5->setState(PluginSpec::Read); // fake read state for plugin resolving - QVERIFY(spec1Priv->resolveDependencies(specs)); - QCOMPARE(spec1Priv->dependencySpecs.size(), 2); - QVERIFY(!spec1Priv->dependencySpecs.key(spec2).name.isEmpty()); - QVERIFY(!spec1Priv->dependencySpecs.key(spec3).name.isEmpty()); - QCOMPARE(spec1Priv->state, PluginSpec::Resolved); - QVERIFY(!spec4Priv->resolveDependencies(specs)); - QVERIFY(spec4Priv->hasError); - QCOMPARE(spec4Priv->state, PluginSpec::Read); + QVERIFY(spec1->resolveDependencies(specs)); + QCOMPARE(spec1->dependencySpecs().size(), 2); + QVERIFY(!spec1->dependencySpecs().key(spec2).name.isEmpty()); + QVERIFY(!spec1->dependencySpecs().key(spec3).name.isEmpty()); + QCOMPARE(spec1->state(), PluginSpec::Resolved); + QVERIFY(!spec4->resolveDependencies(specs)); + QVERIFY(spec4->hasError()); + QCOMPARE(spec4->state(), PluginSpec::Read); } void tst_PluginSpec::loadLibrary() { - PluginSpec *ps = Internal::PluginManagerPrivate::createSpec(); - Internal::PluginSpecPrivate *spec = Internal::PluginManagerPrivate::privateSpec(ps); - QVERIFY(spec->read(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + libraryName(QLatin1String("test")))); + Utils::expected_str ps = PluginSpecImpl::read( + QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + + libraryName(QLatin1String("test"))); + + QVERIFY(ps); + PluginSpecImpl *spec = static_cast(ps.value()); + QVERIFY(spec->resolveDependencies(QVector())); - QVERIFY2(spec->loadLibrary(), qPrintable(spec->errorString)); - QVERIFY(spec->plugin != 0); - QVERIFY(QLatin1String(spec->plugin->metaObject()->className()) == QLatin1String("MyPlugin::MyPluginImpl")); - QCOMPARE(spec->state, PluginSpec::Loaded); - QVERIFY(!spec->hasError); - QCOMPARE(spec->plugin, ps->plugin()); - delete ps; + QVERIFY2(spec->loadLibrary(), qPrintable(spec->errorString())); + QVERIFY(spec->plugin() != 0); + QVERIFY(QLatin1String(spec->plugin()->metaObject()->className()) + == QLatin1String("MyPlugin::MyPluginImpl")); + QCOMPARE(spec->state(), PluginSpec::Loaded); + QVERIFY(!spec->hasError()); + + delete *ps; } void tst_PluginSpec::initializePlugin() { - Internal::PluginSpecPrivate spec(0); - QVERIFY(spec.read(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + libraryName(QLatin1String("test")))); - QVERIFY(spec.resolveDependencies(QVector())); - QVERIFY2(spec.loadLibrary(), qPrintable(spec.errorString)); + Utils::expected_str ps = PluginSpecImpl::read( + QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + + libraryName(QLatin1String("test"))); + QVERIFY(ps); + PluginSpecImpl *spec = static_cast(ps.value()); + QVERIFY(spec->resolveDependencies(QVector())); + QVERIFY2(spec->loadLibrary(), qPrintable(spec->errorString())); bool isInitialized; - QMetaObject::invokeMethod(spec.plugin, "isInitialized", - Qt::DirectConnection, Q_RETURN_ARG(bool, isInitialized)); + QMetaObject::invokeMethod(spec->plugin(), + "isInitialized", + Qt::DirectConnection, + Q_RETURN_ARG(bool, isInitialized)); QVERIFY(!isInitialized); - QVERIFY(spec.initializePlugin()); - QCOMPARE(spec.state, PluginSpec::Initialized); - QVERIFY(!spec.hasError); - QMetaObject::invokeMethod(spec.plugin, "isInitialized", - Qt::DirectConnection, Q_RETURN_ARG(bool, isInitialized)); + QVERIFY(spec->initializePlugin()); + QCOMPARE(spec->state(), PluginSpec::Initialized); + QVERIFY(!spec->hasError()); + QMetaObject::invokeMethod(spec->plugin(), + "isInitialized", + Qt::DirectConnection, + Q_RETURN_ARG(bool, isInitialized)); QVERIFY(isInitialized); } void tst_PluginSpec::initializeExtensions() { - Internal::PluginSpecPrivate spec(0); - QVERIFY(spec.read(QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + libraryName(QLatin1String("test")))); - QVERIFY(spec.resolveDependencies(QVector())); - QVERIFY2(spec.loadLibrary(), qPrintable(spec.errorString)); + Utils::expected_str ps = PluginSpecImpl::read( + QLatin1String(PLUGIN_DIR) + QLatin1String("/testplugin/") + + libraryName(QLatin1String("test"))); + QVERIFY(ps); + PluginSpecImpl *spec = static_cast(ps.value()); + QVERIFY(spec->resolveDependencies(QVector())); + QVERIFY2(spec->loadLibrary(), qPrintable(spec->errorString())); bool isExtensionsInitialized; - QVERIFY(spec.initializePlugin()); - QMetaObject::invokeMethod(spec.plugin, "isExtensionsInitialized", - Qt::DirectConnection, Q_RETURN_ARG(bool, isExtensionsInitialized)); + QVERIFY(spec->initializePlugin()); + QMetaObject::invokeMethod(spec->plugin(), + "isExtensionsInitialized", + Qt::DirectConnection, + Q_RETURN_ARG(bool, isExtensionsInitialized)); QVERIFY(!isExtensionsInitialized); - QVERIFY(spec.initializeExtensions()); - QCOMPARE(spec.state, PluginSpec::Running); - QVERIFY(!spec.hasError); - QMetaObject::invokeMethod(spec.plugin, "isExtensionsInitialized", - Qt::DirectConnection, Q_RETURN_ARG(bool, isExtensionsInitialized)); + QVERIFY(spec->initializeExtensions()); + QCOMPARE(spec->state(), PluginSpec::Running); + QVERIFY(!spec->hasError()); + QMetaObject::invokeMethod(spec->plugin(), + "isExtensionsInitialized", + Qt::DirectConnection, + Q_RETURN_ARG(bool, isExtensionsInitialized)); QVERIFY(isExtensionsInitialized); } From cf53f157f7cb30a62753a9f59c44f8ca39ef7a13 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Thu, 15 Feb 2024 07:00:04 +0100 Subject: [PATCH 0008/1060] ExtensionSystem: Fix initialization and silence logging Avoids crash on start when running tests. Change-Id: I924290f1d7c5d079ed96112e3d2375e53428221f Reviewed-by: Marcus Tillmanns --- src/libs/extensionsystem/pluginmanager.cpp | 2 +- src/libs/extensionsystem/pluginspec.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp index 43b8f3d2fa5..d8fdc096854 100644 --- a/src/libs/extensionsystem/pluginmanager.cpp +++ b/src/libs/extensionsystem/pluginmanager.cpp @@ -1792,7 +1792,7 @@ void PluginManagerPrivate::readPluginPaths() for (const QString &pluginFile : pluginFiles(pluginPaths)) { expected_str spec = PluginSpecImpl::read(pluginFile); if (!spec) { - qCWarning(pluginLog).noquote() + qCInfo(pluginLog).noquote() << QString("Ignoring plugin \"%1\" because: %2").arg(pluginFile).arg(spec.error()); continue; } diff --git a/src/libs/extensionsystem/pluginspec.cpp b/src/libs/extensionsystem/pluginspec.cpp index 8740854e7e5..abed26c7fbe 100644 --- a/src/libs/extensionsystem/pluginspec.cpp +++ b/src/libs/extensionsystem/pluginspec.cpp @@ -175,7 +175,7 @@ public: std::optional loader; std::optional staticPlugin; - IPlugin *plugin; + IPlugin *plugin = nullptr; }; class PluginSpecPrivate From 837e951b29240d28b4c5849acae04d2ebbcd03f1 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 7 Feb 2024 14:12:11 +0100 Subject: [PATCH 0009/1060] CppEditor: Add curly braces for more control statements Fixes: QTCREATORBUG-24542 Change-Id: I3e0893e1c736730d94e2c9ab2baa0aa580393fe4 Reviewed-by: Reviewed-by: Christian Stenger Reviewed-by: Qt CI Bot --- src/plugins/cppeditor/cppquickfix_test.cpp | 96 ++++++++++++++++-- src/plugins/cppeditor/cppquickfix_test.h | 1 + src/plugins/cppeditor/cppquickfixes.cpp | 109 ++++++++++++++------- src/plugins/cppeditor/cppquickfixes.h | 6 +- 4 files changed, 166 insertions(+), 46 deletions(-) diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp index 48c9bbc68af..56ae513a8a1 100644 --- a/src/plugins/cppeditor/cppquickfix_test.cpp +++ b/src/plugins/cppeditor/cppquickfix_test.cpp @@ -8229,29 +8229,105 @@ void QuickfixTest::testExtractLiteralAsParameterNotTriggeringForInvalidCode() QuickFixOperationTest(testDocuments, &factory); } -void QuickfixTest::testAddCurlyBraces() +void QuickfixTest::testAddCurlyBraces_data() { - QList testDocuments; - const QByteArray original = R"delim( + QTest::addColumn("original"); + QTest::addColumn("expected"); + + QByteArray original = R"delim( void MyObject::f() { @if (true) emit mySig(); -} -)delim"; - const QByteArray expected = R"delim( +})delim"; + QByteArray expected = R"delim( void MyObject::f() { if (true) { emit mySig(); } +})delim"; + QTest::newRow("if") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @while (true) + emit mySig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + while (true) { + emit mySig(); + } +})delim"; + QTest::newRow("while") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @for (int i = 0; i < 10; ++i) + emit mySig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + for (int i = 0; i < 10; ++i) { + emit mySig(); + } +})delim"; + QTest::newRow("for") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @for (int i : list) + emit mySig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + for (int i : list) { + emit mySig(); + } +})delim"; + QTest::newRow("range-based for") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @do + emit mySig(); + while (true); +})delim"; + expected = R"delim( +void MyObject::f() +{ + do { + emit mySig(); + } while (true); +})delim"; + QTest::newRow("do") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @do { + emit mySig(); + } while (true); +})delim"; + expected.clear(); + QTest::newRow("already has braces") << original << expected; } -)delim"; - testDocuments << CppTestDocument::create("file.cpp", original, expected); - AddBracesToIf factory; - QuickFixOperationTest(testDocuments, &factory); +void QuickfixTest::testAddCurlyBraces() +{ + QFETCH(QByteArray, original); + QFETCH(QByteArray, expected); + AddBracesToControlStatement factory; + QuickFixOperationTest({CppTestDocument::create("file.cpp", original, expected)}, &factory); } void QuickfixTest::testConvertQt4ConnectConnectOutOfClass() diff --git a/src/plugins/cppeditor/cppquickfix_test.h b/src/plugins/cppeditor/cppquickfix_test.h index 4d734c9c09c..917abe19c73 100644 --- a/src/plugins/cppeditor/cppquickfix_test.h +++ b/src/plugins/cppeditor/cppquickfix_test.h @@ -209,6 +209,7 @@ private slots: void testExtractLiteralAsParameterMemberFunctionSeparateFiles(); void testExtractLiteralAsParameterNotTriggeringForInvalidCode(); + void testAddCurlyBraces_data(); void testAddCurlyBraces(); void testRemoveUsingNamespace_data(); diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp index 90563ccd33d..bf3f1375117 100644 --- a/src/plugins/cppeditor/cppquickfixes.cpp +++ b/src/plugins/cppeditor/cppquickfixes.cpp @@ -764,13 +764,49 @@ void SplitSimpleDeclaration::doMatch(const CppQuickFixInterface &interface, } namespace { +template Statement *asControlStatement(AST *node) +{ + if constexpr (std::is_same_v) + return node->asIfStatement(); + if constexpr (std::is_same_v) + return node->asWhileStatement(); + if constexpr (std::is_same_v) + return node->asForStatement(); + if constexpr (std::is_same_v) + return node->asRangeBasedForStatement(); + if constexpr (std::is_same_v) + return node->asDoStatement(); + return nullptr; +} -class AddBracesToIfOp: public CppQuickFixOperation +template +int triggerToken(const Statement *statement) +{ + if constexpr (std::is_same_v) + return statement->if_token; + if constexpr (std::is_same_v) + return statement->while_token; + if constexpr (std::is_same_v) + return statement->do_token; + if constexpr (std::is_same_v + || std::is_same_v) { + return statement->for_token; + } +} + +template +int tokenToInsertOpeningBraceAfter(const Statement *statement) +{ + if constexpr (std::is_same_v) + return statement->do_token; + return statement->rparen_token; +} + +template class AddBracesToControlStatementOp : public CppQuickFixOperation { public: - AddBracesToIfOp(const CppQuickFixInterface &interface, int priority, - const IfStatementAST *statement) - : CppQuickFixOperation(interface, priority) + AddBracesToControlStatementOp(const CppQuickFixInterface &interface, const Statement *statement) + : CppQuickFixOperation(interface, 0) , _statement(statement) { setDescription(Tr::tr("Add Curly Braces")); @@ -783,51 +819,58 @@ public: ChangeSet changes; - const int start = currentFile->endOf(_statement->rparen_token); + const int start = currentFile->endOf(tokenToInsertOpeningBraceAfter(_statement)); changes.insert(start, QLatin1String(" {")); - const int end = currentFile->endOf(_statement->statement->lastToken() - 1); - changes.insert(end, QLatin1String("\n}")); + if constexpr (std::is_same_v) { + const int end = currentFile->startOf(_statement->while_token); + changes.insert(end, QLatin1String("} ")); + } else { + const int end = currentFile->endOf(_statement->statement->lastToken() - 1); + changes.insert(end, QLatin1String("\n}")); + } + // TODO: For if statements, also bracify all else cases. + // Also check all else cases in the factory. currentFile->setChangeSet(changes); currentFile->apply(); } private: - const IfStatementAST * const _statement; + const Statement * const _statement; }; } // anonymous namespace -void AddBracesToIf::doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) +template +bool checkControlStatementsHelper(const CppQuickFixInterface &interface, QuickFixOperations &result) { - const QList &path = interface.path(); - if (path.isEmpty()) - return; + Statement * const statement = asControlStatement(interface.path().last()); + if (!statement) + return false; - // show when we're on the 'if' of an if statement - int index = path.size() - 1; - IfStatementAST *ifStatement = path.at(index)->asIfStatement(); - if (ifStatement && interface.isCursorOn(ifStatement->if_token) && ifStatement->statement - && !ifStatement->statement->asCompoundStatement()) { - result << new AddBracesToIfOp(interface, index, ifStatement); - return; + if (interface.isCursorOn(triggerToken(statement)) && statement->statement + && !statement->statement->asCompoundStatement()) { + result << new AddBracesToControlStatementOp(interface, statement); } + return true; +} - // or if we're on the statement contained in the if - // ### This may not be such a good idea, consider nested ifs... - for (; index != -1; --index) { - IfStatementAST *ifStatement = path.at(index)->asIfStatement(); - if (ifStatement && ifStatement->statement - && interface.isCursorOn(ifStatement->statement) - && !ifStatement->statement->asCompoundStatement()) { - result << new AddBracesToIfOp(interface, index, ifStatement); - return; - } - } +template +void checkControlStatements(const CppQuickFixInterface &interface, QuickFixOperations &result) +{ + (... || checkControlStatementsHelper(interface, result)); +} - // ### This could very well be extended to the else branch - // and other nodes entirely. +void AddBracesToControlStatement::doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) +{ + if (interface.path().isEmpty()) + return; + checkControlStatements(interface, result); } namespace { @@ -9969,7 +10012,7 @@ void createCppQuickFixes() new SplitIfStatement; new SplitSimpleDeclaration; - new AddBracesToIf; + new AddBracesToControlStatement; new RearrangeParamDeclarationList; new ReformatPointerDeclaration; diff --git a/src/plugins/cppeditor/cppquickfixes.h b/src/plugins/cppeditor/cppquickfixes.h index 99904ffcb19..10f82c9dda3 100644 --- a/src/plugins/cppeditor/cppquickfixes.h +++ b/src/plugins/cppeditor/cppquickfixes.h @@ -287,7 +287,7 @@ public: }; /*! - Add curly braces to a if statement that doesn't already contain a + Add curly braces to a control statement that doesn't already contain a compound statement. I.e. if (a) @@ -297,9 +297,9 @@ public: b; } - Activates on: the if + Activates on: the keyword */ -class AddBracesToIf: public CppQuickFixFactory +class AddBracesToControlStatement : public CppQuickFixFactory { public: void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override; From f00666a9853c8554f8d6b2a16aaf4a5f9521dae1 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 7 Feb 2024 17:45:29 +0100 Subject: [PATCH 0010/1060] ProjectExplorer: Accept plain folder nodes as drag & drop targets As opposed to just project nodes. Task-number: QTCREATORBUG-26545 Change-Id: I33eb2623763fdfacb9b6b8bb1bcd6b4626b3d71e Reviewed-by: Reviewed-by: Christian Stenger --- src/plugins/projectexplorer/projectmodels.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp index dcbd3a89c89..53f33f58b31 100644 --- a/src/plugins/projectexplorer/projectmodels.cpp +++ b/src/plugins/projectexplorer/projectmodels.cpp @@ -679,6 +679,8 @@ bool FlatModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int r return n->parentProjectNode() != sourceProjectNode; })) { return true; } + FolderNode * const sourceFolderNode = fileNodes.first()->parentFolderNode(); + const bool sourceNodeIsSubDir = sourceFolderNode != sourceProjectNode; Node *targetNode = nodeForIndex(index(row, column, parent)); if (!targetNode) targetNode = nodeForIndex(parent); @@ -687,20 +689,22 @@ bool FlatModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int r if (!targetProjectNode) targetProjectNode = targetNode->parentProjectNode(); QTC_ASSERT(targetProjectNode, return true); - if (sourceProjectNode == targetProjectNode) + const bool targetNodeIsSubDir = targetNode != targetProjectNode && targetNode->asFolderNode(); + if (sourceProjectNode == targetProjectNode && !targetNodeIsSubDir && !sourceNodeIsSubDir) return true; // Node weirdness: Sometimes the "file path" is a directory, sometimes it's a file... - const auto dirForProjectNode = [](const ProjectNode *pNode) { - const FilePath dir = pNode->filePath(); + const auto dirForFolderNode = [](const FolderNode *node) { + const FilePath dir = node->filePath(); if (dir.isDir()) return dir; return FilePath::fromString(dir.toFileInfo().path()); }; - FilePath targetDir = dirForProjectNode(targetProjectNode); + FilePath targetDir = dirForFolderNode(targetNodeIsSubDir ? targetNode->asFolderNode() + : targetProjectNode); // Ask the user what to do now: Copy or add? With or without file transfer? - DropFileDialog dlg(targetDir == dirForProjectNode(sourceProjectNode) ? FilePath() : targetDir); + DropFileDialog dlg(targetDir == dirForFolderNode(sourceFolderNode) ? FilePath() : targetDir); if (dlg.exec() != QDialog::Accepted) return true; if (!dlg.targetDir().isEmpty()) From 5334081270b97d1021e8101f6a25e6bfba657243 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Thu, 15 Feb 2024 12:04:41 +0100 Subject: [PATCH 0011/1060] Bump version to 14.0.0-beta1 Change-Id: I62f28969f68889f628fb37e8a1eb390a62bd6e46 Reviewed-by: David Schulz --- cmake/QtCreatorIDEBranding.cmake | 6 +++--- qbs/modules/qtc/qtc.qbs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cmake/QtCreatorIDEBranding.cmake b/cmake/QtCreatorIDEBranding.cmake index 275454a6684..e37467b6616 100644 --- a/cmake/QtCreatorIDEBranding.cmake +++ b/cmake/QtCreatorIDEBranding.cmake @@ -1,6 +1,6 @@ -set(IDE_VERSION "12.0.82") # The IDE version. -set(IDE_VERSION_COMPAT "12.0.82") # The IDE Compatibility version. -set(IDE_VERSION_DISPLAY "13.0.0-beta1") # The IDE display version. +set(IDE_VERSION "13.0.82") # The IDE version. +set(IDE_VERSION_COMPAT "13.0.82") # The IDE Compatibility version. +set(IDE_VERSION_DISPLAY "14.0.0-beta1") # The IDE display version. set(IDE_COPYRIGHT_YEAR "2024") # The IDE current copyright year. set(IDE_SETTINGSVARIANT "QtProject") # The IDE settings variation. diff --git a/qbs/modules/qtc/qtc.qbs b/qbs/modules/qtc/qtc.qbs index 1fe9fe91354..cf145a73d12 100644 --- a/qbs/modules/qtc/qtc.qbs +++ b/qbs/modules/qtc/qtc.qbs @@ -4,14 +4,14 @@ import qbs.FileInfo import qbs.Utilities Module { - property string qtcreator_display_version: '13.0.0-beta1' - property string ide_version_major: '12' + property string qtcreator_display_version: '14.0.0-beta1' + property string ide_version_major: '13' property string ide_version_minor: '0' property string ide_version_release: '82' property string qtcreator_version: ide_version_major + '.' + ide_version_minor + '.' + ide_version_release - property string ide_compat_version_major: '12' + property string ide_compat_version_major: '13' property string ide_compat_version_minor: '0' property string ide_compat_version_release: '82' property string qtcreator_compat_version: ide_compat_version_major + '.' From 7c5a0e6bb2740d31de82e78e2316727258851845 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 15 Feb 2024 17:50:52 +0100 Subject: [PATCH 0012/1060] Rename RunControl::aspect to RunControl::aspectData It's the "persisted" form of the content of the original aspect's data, calling it 'aspect' already confused me a few times. Change-Id: I88a6f76f0ca39d3d36dde9b84287032ceecf7033 Reviewed-by: Christian Kandeler --- .../android/androidqmlpreviewworker.cpp | 2 +- src/plugins/android/androidrunnerworker.cpp | 4 ++-- .../debugservers/gdb/gdbserverprovider.cpp | 4 ++-- .../debugservers/uvsc/uvscserverprovider.cpp | 2 +- src/plugins/debugger/debuggerruncontrol.cpp | 12 +++++------ src/plugins/debugger/terminal.cpp | 2 +- src/plugins/ios/iosrunner.cpp | 6 +++--- .../mcusupport/mcusupportrunconfiguration.cpp | 2 +- .../perfprofiler/perfprofilerruncontrol.cpp | 2 +- src/plugins/projectexplorer/runcontrol.cpp | 10 +++++----- src/plugins/projectexplorer/runcontrol.h | 8 ++++---- .../qmlpreview/qmlpreviewruncontrol.cpp | 2 +- src/plugins/qmlprofiler/qmlprofilertool.cpp | 2 +- .../qmlmultilanguageaspect.cpp | 2 +- src/plugins/qnx/slog2inforunner.cpp | 2 +- .../appmanagerruncontrol.cpp | 20 +++++++++---------- src/plugins/valgrind/valgrindengine.cpp | 2 +- .../webassemblyrunconfiguration.cpp | 2 +- 18 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/plugins/android/androidqmlpreviewworker.cpp b/src/plugins/android/androidqmlpreviewworker.cpp index 06a14edc06e..dceedd36734 100644 --- a/src/plugins/android/androidqmlpreviewworker.cpp +++ b/src/plugins/android/androidqmlpreviewworker.cpp @@ -459,7 +459,7 @@ bool AndroidQmlPreviewWorker::startPreviewApp() const QDir destDir(apkInfo()->uploadDir); const QString qmlrcPath = destDir.filePath(m_uploadInfo.uploadPackage.baseName() + packageSuffix); - const QStringList envVars = m_rc->aspect()->environment.toStringList(); + const QStringList envVars = m_rc->aspectData()->environment.toStringList(); const QStringList command { "am", "start", diff --git a/src/plugins/android/androidrunnerworker.cpp b/src/plugins/android/androidrunnerworker.cpp index 6cba25a0179..f21928f27d8 100644 --- a/src/plugins/android/androidrunnerworker.cpp +++ b/src/plugins/android/androidrunnerworker.cpp @@ -210,7 +210,7 @@ AndroidRunnerWorker::AndroidRunnerWorker(RunWorker *runner, const QString &packa auto runControl = runner->runControl(); m_useLldb = Debugger::DebuggerKitAspect::engineType(runControl->kit()) == Debugger::LldbEngineType; - auto aspect = runControl->aspect(); + auto aspect = runControl->aspectData(); Utils::Id runMode = runControl->runMode(); const bool debuggingMode = runMode == ProjectExplorer::Constants::DEBUG_RUN_MODE; m_useCppDebugger = debuggingMode && aspect->useCppDebugger; @@ -242,7 +242,7 @@ AndroidRunnerWorker::AndroidRunnerWorker(RunWorker *runner, const QString &packa m_deviceSerialNumber = AndroidManager::deviceSerialNumber(target); m_apiLevel = AndroidManager::deviceApiLevel(target); - m_extraEnvVars = runControl->aspect()->environment; + m_extraEnvVars = runControl->aspectData()->environment; qCDebug(androidRunWorkerLog).noquote() << "Environment variables for the app" << m_extraEnvVars.toStringList(); diff --git a/src/plugins/baremetal/debugservers/gdb/gdbserverprovider.cpp b/src/plugins/baremetal/debugservers/gdb/gdbserverprovider.cpp index 3da6b06254f..885e20fac42 100644 --- a/src/plugins/baremetal/debugservers/gdb/gdbserverprovider.cpp +++ b/src/plugins/baremetal/debugservers/gdb/gdbserverprovider.cpp @@ -139,7 +139,7 @@ bool GdbServerProvider::aboutToRun(DebuggerRunTool *runTool, QString &errorMessa { QTC_ASSERT(runTool, return false); const RunControl *runControl = runTool->runControl(); - const auto exeAspect = runControl->aspect(); + const auto exeAspect = runControl->aspectData(); QTC_ASSERT(exeAspect, return false); const FilePath bin = FilePath::fromString(exeAspect->executable.path()); @@ -155,7 +155,7 @@ bool GdbServerProvider::aboutToRun(DebuggerRunTool *runTool, QString &errorMessa ProcessRunData inferior; inferior.command.setExecutable(bin); - if (const auto argAspect = runControl->aspect()) + if (const auto argAspect = runControl->aspectData()) inferior.command.setArguments(argAspect->arguments); runTool->setInferior(inferior); runTool->setSymbolFile(bin); diff --git a/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.cpp b/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.cpp index f77a0ce0cfd..ed84508322c 100644 --- a/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.cpp +++ b/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.cpp @@ -169,7 +169,7 @@ bool UvscServerProvider::aboutToRun(DebuggerRunTool *runTool, QString &errorMess { QTC_ASSERT(runTool, return false); const RunControl *runControl = runTool->runControl(); - const auto exeAspect = runControl->aspect(); + const auto exeAspect = runControl->aspectData(); QTC_ASSERT(exeAspect, return false); const FilePath bin = exeAspect->executable; diff --git a/src/plugins/debugger/debuggerruncontrol.cpp b/src/plugins/debugger/debuggerruncontrol.cpp index 4a0f20b8d64..d6fd83e7637 100644 --- a/src/plugins/debugger/debuggerruncontrol.cpp +++ b/src/plugins/debugger/debuggerruncontrol.cpp @@ -529,8 +529,8 @@ void DebuggerRunTool::start() return; } - if (auto interpreterAspect = runControl()->aspect()) { - if (auto mainScriptAspect = runControl()->aspect()) { + if (auto interpreterAspect = runControl()->aspectData()) { + if (auto mainScriptAspect = runControl()->aspectData()) { const FilePath mainScript = mainScriptAspect->filePath; const FilePath interpreter = interpreterAspect->filePath; if (!interpreter.isEmpty() && mainScript.endsWith(".py")) { @@ -831,11 +831,11 @@ DebuggerRunTool::DebuggerRunTool(RunControl *runControl, AllowTerminal allowTerm m_runParameters.displayName = runControl->displayName(); - if (auto symbolsAspect = runControl->aspect()) + if (auto symbolsAspect = runControl->aspectData()) m_runParameters.symbolFile = symbolsAspect->filePath; - if (auto terminalAspect = runControl->aspect()) + if (auto terminalAspect = runControl->aspectData()) m_runParameters.useTerminal = terminalAspect->useTerminal; - if (auto runAsRootAspect = runControl->aspect()) + if (auto runAsRootAspect = runControl->aspectData()) m_runParameters.runAsRoot = runAsRootAspect->value; Kit *kit = runControl->kit(); @@ -850,7 +850,7 @@ DebuggerRunTool::DebuggerRunTool(RunControl *runControl, AllowTerminal allowTerm if (QtSupport::QtVersion *qtVersion = QtSupport::QtKitAspect::qtVersion(kit)) m_runParameters.qtSourceLocation = qtVersion->sourcePath(); - if (auto aspect = runControl->aspect()) { + if (auto aspect = runControl->aspectData()) { if (!aspect->useCppDebugger) m_runParameters.cppEngineType = NoEngineType; m_runParameters.isQmlDebugging = aspect->useQmlDebugger; diff --git a/src/plugins/debugger/terminal.cpp b/src/plugins/debugger/terminal.cpp index 18092f132fe..54969c5281d 100644 --- a/src/plugins/debugger/terminal.cpp +++ b/src/plugins/debugger/terminal.cpp @@ -175,7 +175,7 @@ void TerminalRunner::start() ProcessRunData stub = m_stubRunnable(); bool runAsRoot = false; - if (auto runAsRootAspect = runControl()->aspect()) + if (auto runAsRootAspect = runControl()->aspectData()) runAsRoot = runAsRootAspect->value; m_stubProc = new Process(this); diff --git a/src/plugins/ios/iosrunner.cpp b/src/plugins/ios/iosrunner.cpp index e2ed4191292..c58c5731ba3 100644 --- a/src/plugins/ios/iosrunner.cpp +++ b/src/plugins/ios/iosrunner.cpp @@ -114,7 +114,7 @@ DeviceCtlRunner::DeviceCtlRunner(RunControl *runControl) : RunWorker(runControl) { setId("IosDeviceCtlRunner"); - const IosDeviceTypeAspect::Data *data = runControl->aspect(); + const IosDeviceTypeAspect::Data *data = runControl->aspectData(); QTC_ASSERT(data, return); m_bundlePath = data->bundleDirectory; m_arguments = ProcessArgs::splitArgs(runControl->commandLine().arguments(), OsTypeMac); @@ -436,7 +436,7 @@ IosRunner::IosRunner(RunControl *runControl) { setId("IosRunner"); stopRunningRunControl(runControl); - const IosDeviceTypeAspect::Data *data = runControl->aspect(); + const IosDeviceTypeAspect::Data *data = runControl->aspectData(); QTC_ASSERT(data, return); m_bundleDir = data->bundleDirectory; m_device = DeviceKitAspect::device(runControl->kit()); @@ -826,7 +826,7 @@ void IosDebugSupport::start() setIosPlatform("ios-simulator"); } - const IosDeviceTypeAspect::Data *data = runControl()->aspect(); + const IosDeviceTypeAspect::Data *data = runControl()->aspectData(); QTC_ASSERT(data, reportFailure("Broken IosDeviceTypeAspect setup."); return); setRunControlName(data->applicationName); diff --git a/src/plugins/mcusupport/mcusupportrunconfiguration.cpp b/src/plugins/mcusupport/mcusupportrunconfiguration.cpp index 9e936c4faeb..260b908c854 100644 --- a/src/plugins/mcusupport/mcusupportrunconfiguration.cpp +++ b/src/plugins/mcusupport/mcusupportrunconfiguration.cpp @@ -81,7 +81,7 @@ public: { setStartModifier([this, runControl] { const Target *target = runControl->target(); - setCommandLine({cmakeFilePath(target), runControl->aspect()->value, + setCommandLine({cmakeFilePath(target), runControl->aspectData()->value, CommandLine::Raw}); setWorkingDirectory(target->activeBuildConfiguration()->buildDirectory()); setEnvironment(target->activeBuildConfiguration()->environment()); diff --git a/src/plugins/perfprofiler/perfprofilerruncontrol.cpp b/src/plugins/perfprofiler/perfprofilerruncontrol.cpp index 2d35f1790ee..797fb4c2ade 100644 --- a/src/plugins/perfprofiler/perfprofilerruncontrol.cpp +++ b/src/plugins/perfprofiler/perfprofilerruncontrol.cpp @@ -97,7 +97,7 @@ public: void start() final { - auto perfAspect = runControl()->aspect(); + auto perfAspect = runControl()->aspectData(); QTC_ASSERT(perfAspect, reportFailure(); return); PerfSettings *settings = static_cast(perfAspect->currentSettings); QTC_ASSERT(settings, reportFailure(); return); diff --git a/src/plugins/projectexplorer/runcontrol.cpp b/src/plugins/projectexplorer/runcontrol.cpp index d2481f2ac63..0de0ff04628 100644 --- a/src/plugins/projectexplorer/runcontrol.cpp +++ b/src/plugins/projectexplorer/runcontrol.cpp @@ -852,7 +852,7 @@ void RunControlPrivate::showError(const QString &msg) void RunControl::setupFormatter(OutputFormatter *formatter) const { QList parsers = createOutputParsers(target()); - if (const auto customParsersAspect = aspect()) { + if (const auto customParsersAspect = aspectData()) { for (const Id id : std::as_const(customParsersAspect->parsers)) { if (auto parser = createCustomParserFromId(id)) parsers << parser; @@ -969,12 +969,12 @@ const MacroExpander *RunControl::macroExpander() const return d->macroExpander; } -const BaseAspect::Data *RunControl::aspect(Id instanceId) const +const BaseAspect::Data *RunControl::aspectData(Id instanceId) const { return d->aspectData.aspect(instanceId); } -const BaseAspect::Data *RunControl::aspect(BaseAspect::Data::ClassId classId) const +const BaseAspect::Data *RunControl::aspectData(BaseAspect::Data::ClassId classId) const { return d->aspectData.aspect(classId); } @@ -1502,11 +1502,11 @@ void SimpleTargetRunner::start() d->m_startModifier(); bool useTerminal = false; - if (auto terminalAspect = runControl()->aspect()) + if (auto terminalAspect = runControl()->aspectData()) useTerminal = terminalAspect->useTerminal; bool runAsRoot = false; - if (auto runAsRootAspect = runControl()->aspect()) + if (auto runAsRootAspect = runControl()->aspectData()) runAsRoot = runAsRootAspect->value; d->m_stopForced = false; diff --git a/src/plugins/projectexplorer/runcontrol.h b/src/plugins/projectexplorer/runcontrol.h index d969ca47c5f..629fff8346a 100644 --- a/src/plugins/projectexplorer/runcontrol.h +++ b/src/plugins/projectexplorer/runcontrol.h @@ -186,10 +186,10 @@ public: Kit *kit() const; const Utils::MacroExpander *macroExpander() const; - const Utils::BaseAspect::Data *aspect(Utils::Id instanceId) const; - const Utils::BaseAspect::Data *aspect(Utils::BaseAspect::Data::ClassId classId) const; - template const typename T::Data *aspect() const { - return dynamic_cast(aspect(&T::staticMetaObject)); + const Utils::BaseAspect::Data *aspectData(Utils::Id instanceId) const; + const Utils::BaseAspect::Data *aspectData(Utils::BaseAspect::Data::ClassId classId) const; + template const typename T::Data *aspectData() const { + return dynamic_cast(aspectData(&T::staticMetaObject)); } QString buildKey() const; diff --git a/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp b/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp index 209bc06d1d3..41bac4cd8e5 100644 --- a/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp +++ b/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp @@ -206,7 +206,7 @@ public: setStartModifier([this, runControl, serverUrl] { CommandLine cmd = commandLine(); - if (const auto aspect = runControl->aspect()) { + if (const auto aspect = runControl->aspectData()) { const auto qmlBuildSystem = qobject_cast( runControl->target()->buildSystem()); QTC_ASSERT(qmlBuildSystem, return); diff --git a/src/plugins/qmlprofiler/qmlprofilertool.cpp b/src/plugins/qmlprofiler/qmlprofilertool.cpp index aa2397a18a4..753d7ea0145 100644 --- a/src/plugins/qmlprofiler/qmlprofilertool.cpp +++ b/src/plugins/qmlprofiler/qmlprofilertool.cpp @@ -353,7 +353,7 @@ void QmlProfilerTool::finalizeRunControl(QmlProfilerRunner *runWorker) { d->m_toolBusy = true; auto runControl = runWorker->runControl(); - if (auto aspect = runControl->aspect()) { + if (auto aspect = runControl->aspectData()) { if (auto settings = static_cast(aspect->currentSettings)) { d->m_profilerConnections->setFlushInterval(settings->flushEnabled() ? settings->flushInterval() : 0); diff --git a/src/plugins/qmlprojectmanager/qmlmultilanguageaspect.cpp b/src/plugins/qmlprojectmanager/qmlmultilanguageaspect.cpp index 1b3238a425b..ae16f09fc22 100644 --- a/src/plugins/qmlprojectmanager/qmlmultilanguageaspect.cpp +++ b/src/plugins/qmlprojectmanager/qmlmultilanguageaspect.cpp @@ -69,7 +69,7 @@ QmlMultiLanguageAspect::QmlMultiLanguageAspect(AspectContainer *container) connect(this, &BoolAspect::changed, this, [this] { for (RunControl *runControl : ProjectExplorerPlugin::allRunControls()) { - if (auto aspect = runControl->aspect()) { + if (auto aspect = runControl->aspectData()) { if (auto origin = aspect->origin; origin == this) runControl->initiateStop(); } diff --git a/src/plugins/qnx/slog2inforunner.cpp b/src/plugins/qnx/slog2inforunner.cpp index 71264da1e7c..47aa850e819 100644 --- a/src/plugins/qnx/slog2inforunner.cpp +++ b/src/plugins/qnx/slog2inforunner.cpp @@ -22,7 +22,7 @@ Slog2InfoRunner::Slog2InfoRunner(RunControl *runControl) : RunWorker(runControl) { setId("Slog2InfoRunner"); - m_applicationId = runControl->aspect()->executable.fileName(); + m_applicationId = runControl->aspectData()->executable.fileName(); // See QTCREATORBUG-10712 for details. // We need to limit length of ApplicationId to 63 otherwise it would not match one in slog2info. diff --git a/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp b/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp index ec1aa7244ed..37ade563161 100644 --- a/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp +++ b/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp @@ -53,12 +53,12 @@ public: }); setStartModifier([this, runControl] { - FilePath controller = runControl->aspect()->filePath; - QString appId = runControl->aspect()->value; - QString instanceId = runControl->aspect()->value; - QString documentUrl = runControl->aspect()->value; + FilePath controller = runControl->aspectData()->filePath; + QString appId = runControl->aspectData()->value; + QString instanceId = runControl->aspectData()->value; + QString documentUrl = runControl->aspectData()->value; QStringList envVars; - if (auto envAspect = runControl->aspect()) + if (auto envAspect = runControl->aspectData()) envVars = envAspect->environment.toStringList(); // Always use the default environment to start the appman-controller in @@ -115,12 +115,12 @@ public: addStartDependency(m_portsGatherer); setStartModifier([this, runControl] { - FilePath controller = runControl->aspect()->filePath; - QString appId = runControl->aspect()->value; - QString instanceId = runControl->aspect()->value; - QString documentUrl = runControl->aspect()->value; + FilePath controller = runControl->aspectData()->filePath; + QString appId = runControl->aspectData()->value; + QString instanceId = runControl->aspectData()->value; + QString documentUrl = runControl->aspectData()->value; QStringList envVars; - if (auto envAspect = runControl->aspect()) + if (auto envAspect = runControl->aspectData()) envVars = envAspect->environment.toStringList(); // const int perfPort = m_portsGatherer->gdbServer().port(); diff --git a/src/plugins/valgrind/valgrindengine.cpp b/src/plugins/valgrind/valgrindengine.cpp index 9cf1d6475d0..57f62a0c4b3 100644 --- a/src/plugins/valgrind/valgrindengine.cpp +++ b/src/plugins/valgrind/valgrindengine.cpp @@ -73,7 +73,7 @@ void ValgrindToolRunner::start() m_runner.setValgrindCommand(valgrind); m_runner.setDebuggee(runControl()->runnable()); - if (auto aspect = runControl()->aspect()) + if (auto aspect = runControl()->aspectData()) m_runner.setUseTerminal(aspect->useTerminal); if (!m_runner.start()) { diff --git a/src/plugins/webassembly/webassemblyrunconfiguration.cpp b/src/plugins/webassembly/webassemblyrunconfiguration.cpp index e78222c0a6d..593f0b95803 100644 --- a/src/plugins/webassembly/webassemblyrunconfiguration.cpp +++ b/src/plugins/webassembly/webassemblyrunconfiguration.cpp @@ -210,7 +210,7 @@ public: setStartModifier([this, runControl, portsGatherer] { const QString browserId = - runControl->aspect()->currentBrowser; + runControl->aspectData()->currentBrowser; setCommandLine(emrunCommand(runControl->target(), runControl->buildKey(), browserId, From 737bf48a0ce12bb1509d4fa9a093dcd2e883b5dd Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 16 Feb 2024 16:47:43 +0100 Subject: [PATCH 0013/1060] Utils: Add convenience class for parsing and caching process output ... and base the existing uses of this pattern on it. Change-Id: I0eaf7535b68ff8c3e8e1c923ce08e63896cc83f7 Reviewed-by: hjk --- src/libs/utils/CMakeLists.txt | 1 + src/libs/utils/algorithm.h | 13 + src/libs/utils/datafromprocess.h | 95 +++++++ src/libs/utils/pathchooser.cpp | 14 +- src/libs/utils/utils.qbs | 1 + src/plugins/clangtools/clangtoolssettings.cpp | 2 +- .../clangtools/diagnosticconfigswidget.cpp | 4 +- src/plugins/clangtools/executableinfo.cpp | 232 +++++++++--------- src/plugins/clangtools/executableinfo.h | 9 +- src/plugins/clangtools/runsettingswidget.cpp | 2 +- src/plugins/projectexplorer/msvctoolchain.cpp | 25 +- 11 files changed, 238 insertions(+), 160 deletions(-) create mode 100644 src/libs/utils/datafromprocess.h diff --git a/src/libs/utils/CMakeLists.txt b/src/libs/utils/CMakeLists.txt index eb2eaed9ddc..7e7bb51ec5f 100644 --- a/src/libs/utils/CMakeLists.txt +++ b/src/libs/utils/CMakeLists.txt @@ -31,6 +31,7 @@ add_qtc_library(Utils completingtextedit.cpp completingtextedit.h cpplanguage_details.h crumblepath.cpp crumblepath.h + datafromprocess.h delegates.cpp delegates.h detailsbutton.cpp detailsbutton.h detailswidget.cpp detailswidget.h diff --git a/src/libs/utils/algorithm.h b/src/libs/utils/algorithm.h index b781d68102d..d1c3f37bff4 100644 --- a/src/libs/utils/algorithm.h +++ b/src/libs/utils/algorithm.h @@ -22,7 +22,9 @@ #include #include +#include #include +#include namespace Utils { @@ -1532,6 +1534,17 @@ void addToHash(QHash *result, const QHash &additionalContents) result->insert(additionalContents); } +template +static std::size_t tupleHashHelper(uint seed, const Tuple &tuple, std::index_sequence) +{ + return qHashMulti(seed, (std::get(tuple), ...)); +} + +template std::size_t qHash(const std::tuple &tuple, uint seed = 0) +{ + return tupleHashHelper(seed, tuple, std::make_index_sequence()); +} + // Workaround for missing information from QSet::insert() // Return type could be a pair like for std::set, but we never use the iterator anyway. template [[nodiscard]] bool insert(QSet &s, const U &v) diff --git a/src/libs/utils/datafromprocess.h b/src/libs/utils/datafromprocess.h new file mode 100644 index 00000000000..909252ce505 --- /dev/null +++ b/src/libs/utils/datafromprocess.h @@ -0,0 +1,95 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "algorithm.h" +#include "commandline.h" +#include "environment.h" +#include "filepath.h" +#include "process.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Utils { + +// Use this facility for cached retrieval of data from a tool that always returns the same +// output for the same parameters and is side effect free. +// A prime example is version info via a --version switch. +template class DataFromProcess +{ +public: + class Parameters + { + public: + using OutputParser = std::function(const QString &)>; + using ErrorHandler = std::function; + + Parameters(const CommandLine &cmdLine, const OutputParser &parser) + : commandLine(cmdLine) + , parser(parser) + {} + + CommandLine commandLine; + Environment environment = Environment::systemEnvironment(); + std::chrono::seconds timeout = std::chrono::seconds(10); + OutputParser parser; + ErrorHandler errorHandler; + QList allowedResults{ProcessResult::FinishedWithSuccess}; + }; + + static std::optional getData(const Parameters ¶ms); + + // TODO: async variant. + +private: + using Key = std::tuple; + using Value = std::pair, QDateTime>; + static inline QHash m_cache; + static inline QMutex m_cacheMutex; +}; + +template +inline std::optional DataFromProcess::getData(const Parameters ¶ms) +{ + if (params.commandLine.executable().isEmpty()) + return {}; + + const auto key = std::make_tuple(params.commandLine.executable(), + params.environment.toStringList(), + params.commandLine.arguments()); + const QDateTime exeTimestamp = params.commandLine.executable().lastModified(); + { + QMutexLocker cacheLocker(&m_cacheMutex); + const auto it = m_cache.constFind(key); + if (it != m_cache.constEnd() && it.value().second == exeTimestamp) + return it.value().first; + } + + Process outputRetriever; + outputRetriever.setCommand(params.commandLine); + outputRetriever.runBlocking(params.timeout); + + // Do not store into cache: The next call might succeed. + if (outputRetriever.result() == ProcessResult::Canceled) + return {}; + + std::optional data; + if (params.allowedResults.contains(outputRetriever.result())) + data = params.parser(outputRetriever.cleanedStdOut()); + else if (params.errorHandler) + params.errorHandler(outputRetriever); + QMutexLocker cacheLocker(&m_cacheMutex); + m_cache.insert(key, std::make_pair(data, exeTimestamp)); + return data; +} + +} // namespace Utils diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp index 437b94bb5cd..b8704061cd5 100644 --- a/src/libs/utils/pathchooser.cpp +++ b/src/libs/utils/pathchooser.cpp @@ -5,6 +5,7 @@ #include "async.h" #include "commandline.h" +#include "datafromprocess.h" #include "environment.h" #include "fileutils.h" #include "guard.h" @@ -130,15 +131,12 @@ bool BinaryVersionToolTipEventFilter::eventFilter(QObject *o, QEvent *e) QString BinaryVersionToolTipEventFilter::toolVersion(const CommandLine &cmd) { - if (cmd.executable().isEmpty()) - return QString(); - Process proc; - proc.setCommand(cmd); + DataFromProcess::Parameters params(cmd, [](const QString &output) { return output; }); using namespace std::chrono_literals; - proc.runBlocking(1s); - if (proc.result() != ProcessResult::FinishedWithSuccess) - return QString(); - return proc.allOutput(); + params.timeout = 1s; + if (const auto version = DataFromProcess::getData(params)) + return *version; + return {}; } // Extends BinaryVersionToolTipEventFilter to prepend the existing pathchooser diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs index 7bf55d8f247..9cc3aced5a3 100644 --- a/src/libs/utils/utils.qbs +++ b/src/libs/utils/utils.qbs @@ -77,6 +77,7 @@ QtcLibrary { "cpplanguage_details.h", "crumblepath.cpp", "crumblepath.h", + "datafromprocess.h", "delegates.cpp", "delegates.h", "detailsbutton.cpp", diff --git a/src/plugins/clangtools/clangtoolssettings.cpp b/src/plugins/clangtools/clangtoolssettings.cpp index 6699be10bdc..c8494c60ee0 100644 --- a/src/plugins/clangtools/clangtoolssettings.cpp +++ b/src/plugins/clangtools/clangtoolssettings.cpp @@ -230,7 +230,7 @@ VersionAndSuffix ClangToolsSettings::clangTidyVersion() QVersionNumber ClangToolsSettings::clazyVersion() { - return ClazyStandaloneInfo::getInfo(Internal::toolExecutable(ClangToolType::Clazy)).version; + return ClazyStandaloneInfo(Internal::toolExecutable(ClangToolType::Clazy)).version; } } // namespace Internal diff --git a/src/plugins/clangtools/diagnosticconfigswidget.cpp b/src/plugins/clangtools/diagnosticconfigswidget.cpp index b787777f9d9..dcbcd70e13d 100644 --- a/src/plugins/clangtools/diagnosticconfigswidget.cpp +++ b/src/plugins/clangtools/diagnosticconfigswidget.cpp @@ -1263,7 +1263,7 @@ QString removeClangTidyCheck(const QString &checks, const QString &check) QString removeClazyCheck(const QString &checks, const QString &check) { - const ClazyStandaloneInfo clazyInfo = ClazyStandaloneInfo::getInfo(toolExecutable(ClangToolType::Clazy)); + const ClazyStandaloneInfo clazyInfo = ClazyStandaloneInfo(toolExecutable(ClangToolType::Clazy)); ClazyChecksTreeModel model(clazyInfo.supportedChecks); model.enableChecks(checks.split(',', Qt::SkipEmptyParts)); const QModelIndex index = model.indexForName(check.mid(QString("clazy-").length())); @@ -1314,7 +1314,7 @@ void disableChecks(const QList &diagnostics) if (config.clazyMode() == ClangDiagnosticConfig::ClazyMode::UseDefaultChecks) { config.setClazyMode(ClangDiagnosticConfig::ClazyMode::UseCustomChecks); const ClazyStandaloneInfo clazyInfo - = ClazyStandaloneInfo::getInfo(toolExecutable(ClangToolType::Clazy)); + = ClazyStandaloneInfo(toolExecutable(ClangToolType::Clazy)); config.setChecks(ClangToolType::Clazy, clazyInfo.defaultChecks.join(',')); } config.setChecks(ClangToolType::Clazy, diff --git a/src/plugins/clangtools/executableinfo.cpp b/src/plugins/clangtools/executableinfo.cpp index 22898b5734a..b1c5e2343d5 100644 --- a/src/plugins/clangtools/executableinfo.cpp +++ b/src/plugins/clangtools/executableinfo.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -21,27 +22,10 @@ using namespace Utils; namespace ClangTools { namespace Internal { -static QString runExecutable(const Utils::CommandLine &commandLine, QueryFailMode queryFailMode) +static void handleProcessError(const Process &p) { - if (commandLine.executable().isEmpty() || !commandLine.executable().toFileInfo().isExecutable()) - return {}; - - Process cpp; - Environment env = Environment::systemEnvironment(); - env.setupEnglishOutput(); - cpp.setEnvironment(env); - cpp.setCommand(commandLine); - - cpp.runBlocking(); - if (cpp.result() != ProcessResult::FinishedWithSuccess - && (queryFailMode == QueryFailMode::Noisy - || cpp.result() != ProcessResult::FinishedWithError)) { - Core::MessageManager::writeFlashing(cpp.exitMessage()); - Core::MessageManager::writeFlashing(QString::fromUtf8(cpp.allRawOutput())); - return {}; - } - - return cpp.cleanedStdOut(); + Core::MessageManager::writeFlashing(p.exitMessage()); + Core::MessageManager::writeFlashing(QString::fromUtf8(p.allRawOutput())); } static QStringList queryClangTidyChecks(const FilePath &executable, @@ -51,47 +35,37 @@ static QStringList queryClangTidyChecks(const FilePath &executable, if (!checksArgument.isEmpty()) arguments.prepend(checksArgument); - const CommandLine commandLine(executable, arguments); - QString output = runExecutable(commandLine, QueryFailMode::Noisy); - if (output.isEmpty()) - return {}; - // Expected output is (clang-tidy 8.0): // Enabled checks: // abseil-duration-comparison // abseil-duration-division // abseil-duration-factory-float // ... + static const auto parser = [](const QString &stdOut) -> std::optional { + QString output = stdOut; + QTextStream stream(&output); + QString line = stream.readLine(); + if (!line.startsWith("Enabled checks:")) + return {}; + QStringList checks; + while (!stream.atEnd()) { + const QString candidate = stream.readLine().trimmed(); + if (!candidate.isEmpty()) + checks << candidate; + } + return checks; + }; - QTextStream stream(&output); - QString line = stream.readLine(); - if (!line.startsWith("Enabled checks:")) - return {}; - - QStringList checks; - while (!stream.atEnd()) { - const QString candidate = stream.readLine().trimmed(); - if (!candidate.isEmpty()) - checks << candidate; - } - - return checks; + DataFromProcess::Parameters params({executable, arguments}, parser); + params.environment.setupEnglishOutput(); + params.errorHandler = handleProcessError; + if (const auto checks = DataFromProcess::getData(params)) + return *checks; + return {}; } static ClazyChecks querySupportedClazyChecks(const FilePath &executablePath) { - static const QString queryFlag = "-supported-checks-json"; - QString jsonOutput = runExecutable(CommandLine(executablePath, {queryFlag}), - QueryFailMode::Noisy); - - // Some clazy 1.6.x versions have a bug where they expect an argument after the - // option. - if (jsonOutput.isEmpty()) - jsonOutput = runExecutable(CommandLine(executablePath, {queryFlag, "dummy"}), - QueryFailMode::Noisy); - if (jsonOutput.isEmpty()) - return {}; - // Expected output is (clazy-standalone 1.6): // { // "available_categories" : ["readability", "qt4", "containers", ... ], @@ -111,29 +85,41 @@ static ClazyChecks querySupportedClazyChecks(const FilePath &executablePath) // ... // ] // } + static const auto parser = [](const QString &jsonOutput) -> std::optional { + const QJsonDocument document = QJsonDocument::fromJson(jsonOutput.toUtf8()); + if (document.isNull()) + return {}; + const QJsonArray checksArray = document.object()["checks"].toArray(); + ClazyChecks infos; + for (const QJsonValue &item: checksArray) { + const QJsonObject checkObject = item.toObject(); + ClazyCheck info; + info.name = checkObject["name"].toString().trimmed(); + if (info.name.isEmpty()) + continue; + info.level = checkObject["level"].toInt(); + for (const QJsonValue &item : checkObject["categories"].toArray()) + info.topics.append(item.toString().trimmed()); + infos << info; + } + return infos; + }; - ClazyChecks infos; - - const QJsonDocument document = QJsonDocument::fromJson(jsonOutput.toUtf8()); - if (document.isNull()) - return {}; - const QJsonArray checksArray = document.object()["checks"].toArray(); - - for (const QJsonValue &item: checksArray) { - const QJsonObject checkObject = item.toObject(); - - ClazyCheck info; - info.name = checkObject["name"].toString().trimmed(); - if (info.name.isEmpty()) - continue; - info.level = checkObject["level"].toInt(); - for (const QJsonValue &item : checkObject["categories"].toArray()) - info.topics.append(item.toString().trimmed()); - - infos << info; + static const QString queryFlag = "-supported-checks-json"; + DataFromProcess::Parameters params(CommandLine(executablePath, {queryFlag}), + parser); + params.environment.setupEnglishOutput(); + params.errorHandler = handleProcessError; + auto checks = DataFromProcess::getData(params); + if (!checks) { + // Some clazy 1.6.x versions have a bug where they expect an argument after the + // option. + params.commandLine = CommandLine(executablePath, {queryFlag, "dummy"}); + checks = DataFromProcess::getData(params); } - - return infos; + if (checks) + return *checks; + return {}; } ClangTidyInfo::ClangTidyInfo(const FilePath &executablePath) @@ -141,76 +127,80 @@ ClangTidyInfo::ClangTidyInfo(const FilePath &executablePath) , supportedChecks(queryClangTidyChecks(executablePath, "-checks=*")) {} -ClazyStandaloneInfo ClazyStandaloneInfo::getInfo(const FilePath &executablePath) -{ - const QDateTime timeStamp = executablePath.lastModified(); - const auto it = cache.find(executablePath); - if (it == cache.end()) { - const ClazyStandaloneInfo info(executablePath); - cache.insert(executablePath, {timeStamp, info}); - return info; - } - if (it->first != timeStamp) { - it->first = timeStamp; - it->second = ClazyStandaloneInfo::getInfo(executablePath); - } - return it->second; -} - ClazyStandaloneInfo::ClazyStandaloneInfo(const FilePath &executablePath) : defaultChecks(queryClangTidyChecks(executablePath, {})) // Yup, behaves as clang-tidy. , supportedChecks(querySupportedClazyChecks(executablePath)) { - QString output = runExecutable({executablePath, {"--version"}}, QueryFailMode::Silent); - QTextStream stream(&output); - while (!stream.atEnd()) { - // It's just "clazy version " right now, but let's be prepared for someone adding a colon - // later on. - static const QStringList versionPrefixes{"clazy version ", "clazy version: "}; - const QString line = stream.readLine().simplified(); - for (const QString &prefix : versionPrefixes) { - if (line.startsWith(prefix)) { - version = QVersionNumber::fromString(line.mid(prefix.length())); - break; + static const auto parser = [](const QString &stdOut) -> std::optional { + QString output = stdOut; + QTextStream stream(&output); + while (!stream.atEnd()) { + // It's just "clazy version " right now, but let's be prepared for someone + // adding a colon later on. + static const QStringList versionPrefixes{"clazy version ", "clazy version: "}; + const QString line = stream.readLine().simplified(); + for (const QString &prefix : versionPrefixes) { + if (line.startsWith(prefix)) + return QVersionNumber::fromString(line.mid(prefix.length())); } } - } + return {}; + }; + DataFromProcess::Parameters params({{executablePath, {"--version"}}, parser}); + params.environment.setupEnglishOutput(); + if (const auto v = DataFromProcess::getData(params)) + version = *v; } static FilePath queryResourceDir(const FilePath &clangToolPath) { - QString output = runExecutable(CommandLine(clangToolPath, {"someFilePath", "--", - "-print-resource-dir"}), - QueryFailMode::Silent); - // Expected output is (clang-tidy 10): // lib/clang/10.0.1 // Error while trying to load a compilation database: // ... + const auto parser = [&clangToolPath](const QString &stdOut) -> std::optional { + QString output = stdOut; + QTextStream stream(&output); + const QString path = clangToolPath.parentDir().parentDir() + .pathAppended(stream.readLine()).toString(); + const auto filePath = FilePath::fromUserInput(QDir::cleanPath(path)); + if (filePath.exists()) + return filePath; + return {}; + }; - // Parse - QTextStream stream(&output); - const QString path = clangToolPath.parentDir().parentDir() - .pathAppended(stream.readLine()).toString(); - const auto filePath = FilePath::fromUserInput(QDir::cleanPath(path)); - if (filePath.exists()) - return filePath; + DataFromProcess::Parameters params({clangToolPath, + {"someFilePath", "--", "-print-resource-dir"}}, + parser); + params.environment.setupEnglishOutput(); + params.allowedResults << ProcessResult::FinishedWithError; + if (const auto filePath = DataFromProcess::getData(params)) + return *filePath; return {}; } QString queryVersion(const FilePath &clangToolPath, QueryFailMode failMode) { - QString output = runExecutable(CommandLine(clangToolPath, {"--version"}), failMode); - QTextStream stream(&output); - while (!stream.atEnd()) { - static const QStringList versionPrefixes{"LLVM version ", "clang version: "}; - const QString line = stream.readLine().simplified(); - for (const QString &prefix : versionPrefixes) { - auto idx = line.indexOf(prefix); - if (idx >= 0) - return line.mid(idx + prefix.length()); + static const auto parser = [](const QString &stdOut) -> std::optional { + QString output = stdOut; + QTextStream stream(&output); + while (!stream.atEnd()) { + static const QStringList versionPrefixes{"LLVM version ", "clang version: "}; + const QString line = stream.readLine().simplified(); + for (const QString &prefix : versionPrefixes) { + auto idx = line.indexOf(prefix); + if (idx >= 0) + return line.mid(idx + prefix.length()); + } } - } + return {}; + }; + DataFromProcess::Parameters params({clangToolPath, {"--version"}}, parser); + params.environment.setupEnglishOutput(); + if (failMode == QueryFailMode::Noisy) + params.errorHandler = handleProcessError; + if (const auto version = DataFromProcess::getData(params)) + return *version; return {}; } @@ -233,7 +223,5 @@ QPair getClangIncludeDirAndVersion(const FilePath &clangToolP return it.value(); } -QHash> ClazyStandaloneInfo::cache; - } // namespace Internal } // namespace ClangTools diff --git a/src/plugins/clangtools/executableinfo.h b/src/plugins/clangtools/executableinfo.h index cfa51b98b2c..5db586b5356 100644 --- a/src/plugins/clangtools/executableinfo.h +++ b/src/plugins/clangtools/executableinfo.h @@ -5,8 +5,6 @@ #include -#include -#include #include #include #include @@ -40,16 +38,11 @@ using ClazyChecks = QVector; class ClazyStandaloneInfo { public: - static ClazyStandaloneInfo getInfo(const Utils::FilePath &executablePath); + ClazyStandaloneInfo(const Utils::FilePath &executablePath); QVersionNumber version; QStringList defaultChecks; ClazyChecks supportedChecks; - -private: - ClazyStandaloneInfo(const Utils::FilePath &executablePath); - - static QHash> cache; }; } // namespace Internal diff --git a/src/plugins/clangtools/runsettingswidget.cpp b/src/plugins/clangtools/runsettingswidget.cpp index cd0dc6a1ee3..81a8b7c644a 100644 --- a/src/plugins/clangtools/runsettingswidget.cpp +++ b/src/plugins/clangtools/runsettingswidget.cpp @@ -85,7 +85,7 @@ static ClangDiagnosticConfigsWidget *createEditWidget(const ClangDiagnosticConfi return new DiagnosticConfigsWidget(configs, configToSelect, ClangTidyInfo(clangTidyPath), - ClazyStandaloneInfo::getInfo(clazyStandalonePath)); + ClazyStandaloneInfo(clazyStandalonePath)); } void RunSettingsWidget::fromSettings(const RunSettings &s) diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp index 67d3f327814..5c1ded6a84b 100644 --- a/src/plugins/projectexplorer/msvctoolchain.cpp +++ b/src/plugins/projectexplorer/msvctoolchain.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -42,8 +43,6 @@ #include #include -#include - using namespace Utils; using namespace std::chrono_literals; @@ -1580,7 +1579,6 @@ private: FilePath m_filePath; QVersionNumber m_version; Abi m_defaultAbi; - static inline QHash> m_cache; }; static const MsvcToolchain *selectMsvcToolChain(const QString &displayedVarsBat, @@ -2280,18 +2278,8 @@ ClangClInfo ClangClInfo::getInfo(const FilePath &filePath) { QTC_ASSERT(!filePath.isEmpty(), return {}); - auto &entry = m_cache[filePath]; - ClangClInfo &info = entry.first; - const QDateTime lastModified = filePath.lastModified(); - if (entry.second == lastModified) - return info; - - entry.second = lastModified; - Process clangClProcess; - clangClProcess.setCommand({filePath, {"--version"}}); - clangClProcess.runBlocking(); - if (clangClProcess.result() == ProcessResult::FinishedWithSuccess) { - const QString stdOut = clangClProcess.cleanedStdOut(); + static const auto parser = [](const QString &stdOut) { + ClangClInfo info; const QRegularExpressionMatch versionMatch = QRegularExpression("clang version (\\d+(\\.\\d+)+)").match(stdOut); if (versionMatch.hasMatch()) @@ -2314,9 +2302,10 @@ ClangClInfo ClangClInfo::getInfo(const FilePath &filePath) detectedAbi.wordWidth()); } } - } - m_cache.insert(filePath, entry); - return info; + return info; + }; + const auto info = DataFromProcess::getData({{filePath, {"--version"}}, parser}); + return info ? *info : ClangClInfo(); } } // namespace ProjectExplorer::Internal From d56ce22baeebb8ddf79d0c2d04fcf2cc8733defa Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 19 Feb 2024 17:53:36 +0100 Subject: [PATCH 0014/1060] FakeVim: Remove some dead code Found by the Axivion plugin. Change-Id: I9ebc2ad47c4eb7d19534db932d4a0d087429a35d Reviewed-by: Jarek Kobus --- src/plugins/fakevim/fakevimhandler.cpp | 16 ---------------- src/plugins/fakevim/fakevimhandler.h | 3 +-- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/src/plugins/fakevim/fakevimhandler.cpp b/src/plugins/fakevim/fakevimhandler.cpp index bf00f7715c3..1e25113fe3b 100644 --- a/src/plugins/fakevim/fakevimhandler.cpp +++ b/src/plugins/fakevim/fakevimhandler.cpp @@ -943,11 +943,6 @@ Range::Range(int b, int e, RangeMode m) : beginPos(qMin(b, e)), endPos(qMax(b, e)), rangemode(m) {} -QString Range::toString() const -{ - return QString("%1-%2 (mode: %3)").arg(beginPos).arg(endPos).arg(rangemode); -} - bool Range::isValid() const { return beginPos >= 0 && endPos >= 0; @@ -959,10 +954,6 @@ QDebug operator<<(QDebug ts, const Range &range) } -ExCommand::ExCommand(const QString &c, const QString &a, const Range &r) - : cmd(c), args(a), range(r) -{} - bool ExCommand::matches(const QString &min, const QString &full) const { return cmd.startsWith(min) && full.startsWith(cmd); @@ -973,13 +964,6 @@ QDebug operator<<(QDebug ts, const ExCommand &cmd) return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range; } -QDebug operator<<(QDebug ts, const QList &sels) -{ - for (const QTextEdit::ExtraSelection &sel : sels) - ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position(); - return ts; -} - QString quoteUnprintable(const QString &ba) { QString res; diff --git a/src/plugins/fakevim/fakevimhandler.h b/src/plugins/fakevim/fakevimhandler.h index 4532fa374cf..2809cb22918 100644 --- a/src/plugins/fakevim/fakevimhandler.h +++ b/src/plugins/fakevim/fakevimhandler.h @@ -27,7 +27,7 @@ struct Range { Range() = default; Range(int b, int e, RangeMode m = RangeCharMode); - QString toString() const; + bool isValid() const; int beginPos = -1; @@ -38,7 +38,6 @@ struct Range struct ExCommand { ExCommand() = default; - ExCommand(const QString &cmd, const QString &args = {}, const Range &range = {}); bool matches(const QString &min, const QString &full) const; From 15fc626a78fea88747bcf39d894bfc219b4f53e7 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 19 Feb 2024 18:06:32 +0100 Subject: [PATCH 0015/1060] VcsBase: Remove unused OptionMapping constructor Change-Id: I9f2dac687e6178a48790314fbb361c479666ec1b Reviewed-by: Reviewed-by: Jarek Kobus --- src/plugins/vcsbase/vcsbaseeditorconfig.cpp | 7 ------- src/plugins/vcsbase/vcsbaseeditorconfig.h | 1 - 2 files changed, 8 deletions(-) diff --git a/src/plugins/vcsbase/vcsbaseeditorconfig.cpp b/src/plugins/vcsbase/vcsbaseeditorconfig.cpp index fdf8542ab32..d629c0f88c2 100644 --- a/src/plugins/vcsbase/vcsbaseeditorconfig.cpp +++ b/src/plugins/vcsbase/vcsbaseeditorconfig.cpp @@ -267,13 +267,6 @@ void VcsBaseEditorConfig::executeCommand() emit commandExecutionRequested(); } -VcsBaseEditorConfig::OptionMapping::OptionMapping(const QString &option, QObject *obj) : - object(obj) -{ - if (!option.isEmpty()) - options << option; -} - VcsBaseEditorConfig::OptionMapping::OptionMapping(const QStringList &optionList, QObject *obj) : options(optionList), object(obj) diff --git a/src/plugins/vcsbase/vcsbaseeditorconfig.h b/src/plugins/vcsbase/vcsbaseeditorconfig.h index 5a0878b05b5..3879b002ac1 100644 --- a/src/plugins/vcsbase/vcsbaseeditorconfig.h +++ b/src/plugins/vcsbase/vcsbaseeditorconfig.h @@ -78,7 +78,6 @@ protected: { public: OptionMapping() = default; - OptionMapping(const QString &option, QObject *obj); OptionMapping(const QStringList &optionList, QObject *obj); QStringList options; QObject *object = nullptr; From 4a722bfa9dddd8542a41dd68bf0768434f4f80f7 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 19 Feb 2024 15:46:46 +0100 Subject: [PATCH 0016/1060] Utils: Add async variant of DataFromProcess ... and make use of it in PathChooser. Change-Id: I0e81afec2caf38f488a8ab98b55016535c187fc2 Reviewed-by: Reviewed-by: hjk Reviewed-by: Qt CI Bot --- src/libs/utils/datafromprocess.h | 79 +++++++++++++++++---- src/libs/utils/pathchooser.cpp | 70 +++++++++--------- src/libs/utils/pathchooser.h | 2 - src/plugins/git/gerrit/gerritparameters.cpp | 9 ++- 4 files changed, 108 insertions(+), 52 deletions(-) diff --git a/src/libs/utils/datafromprocess.h b/src/libs/utils/datafromprocess.h index 909252ce505..7cd833a9114 100644 --- a/src/libs/utils/datafromprocess.h +++ b/src/libs/utils/datafromprocess.h @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -32,6 +33,7 @@ public: public: using OutputParser = std::function(const QString &)>; using ErrorHandler = std::function; + using Callback = std::function &)>; Parameters(const CommandLine &cmdLine, const OutputParser &parser) : commandLine(cmdLine) @@ -43,25 +45,50 @@ public: std::chrono::seconds timeout = std::chrono::seconds(10); OutputParser parser; ErrorHandler errorHandler; + Callback callback; QList allowedResults{ProcessResult::FinishedWithSuccess}; }; + // Use the first variant whenever possible. + static void provideData(const Parameters ¶ms); static std::optional getData(const Parameters ¶ms); - // TODO: async variant. - private: using Key = std::tuple; using Value = std::pair, QDateTime>; + + static std::optional getOrProvideData(const Parameters ¶ms); + static std::optional handleProcessFinished(const Parameters ¶ms, + const QDateTime &exeTimestamp, + const Key &cacheKey, + const std::shared_ptr &process); + static inline QHash m_cache; static inline QMutex m_cacheMutex; }; +template +inline void DataFromProcess::provideData(const Parameters ¶ms) +{ + QTC_ASSERT(params.callback, return); + getOrProvideData(params); +} + template inline std::optional DataFromProcess::getData(const Parameters ¶ms) { - if (params.commandLine.executable().isEmpty()) + QTC_ASSERT(!params.callback, return {}); + return getOrProvideData(params); +} + +template +inline std::optional DataFromProcess::getOrProvideData(const Parameters ¶ms) +{ + if (params.commandLine.executable().isEmpty()) { + if (params.callback) + params.callback({}); return {}; + } const auto key = std::make_tuple(params.commandLine.executable(), params.environment.toStringList(), @@ -74,21 +101,47 @@ inline std::optional DataFromProcess::getData(const Parameters ¶ return it.value().first; } - Process outputRetriever; - outputRetriever.setCommand(params.commandLine); - outputRetriever.runBlocking(params.timeout); - - // Do not store into cache: The next call might succeed. - if (outputRetriever.result() == ProcessResult::Canceled) + const auto outputRetriever = std::make_shared(); + outputRetriever->setCommand(params.commandLine); + if (params.callback) { + QObject::connect(outputRetriever.get(), + &Process::done, + [params, exeTimestamp, key, outputRetriever] { + handleProcessFinished(params, exeTimestamp, key, outputRetriever); + }); + outputRetriever->start(); return {}; + } + + outputRetriever->runBlocking(params.timeout); + return handleProcessFinished(params, exeTimestamp, key, outputRetriever); +} + +template +inline std::optional DataFromProcess::handleProcessFinished( + const Parameters ¶ms, + const QDateTime &exeTimestamp, + const Key &cacheKey, + const std::shared_ptr &process) +{ + // Do not store into cache: The next call might succeed. + if (process->result() == ProcessResult::Canceled) { + if (params.callback) + params.callback({}); + return {}; + } std::optional data; - if (params.allowedResults.contains(outputRetriever.result())) - data = params.parser(outputRetriever.cleanedStdOut()); + if (params.allowedResults.contains(process->result())) + data = params.parser(process->cleanedStdOut()); else if (params.errorHandler) - params.errorHandler(outputRetriever); + params.errorHandler(*process); QMutexLocker cacheLocker(&m_cacheMutex); - m_cache.insert(key, std::make_pair(data, exeTimestamp)); + m_cache.insert(cacheKey, std::make_pair(data, exeTimestamp)); + if (params.callback) { + params.callback(data); + return {}; + } return data; } diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp index b8704061cd5..edef66e1f8a 100644 --- a/src/libs/utils/pathchooser.cpp +++ b/src/libs/utils/pathchooser.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -85,8 +86,6 @@ public: QStringList arguments() const { return m_arguments; } void setArguments(const QStringList &arguments) { m_arguments = arguments; } - static QString toolVersion(const CommandLine &cmd); - private: // Extension point for concatenating existing tooltips. virtual QString defaultToolTip() const { return QString(); } @@ -108,35 +107,41 @@ bool BinaryVersionToolTipEventFilter::eventFilter(QObject *o, QEvent *e) QTC_ASSERT(le, return false); const QString binary = le->text(); - if (!binary.isEmpty()) { - const QString version = BinaryVersionToolTipEventFilter::toolVersion( - CommandLine(FilePath::fromString(QDir::cleanPath(binary)), m_arguments)); - if (!version.isEmpty()) { - // Concatenate tooltips. - QString tooltip = ""; - const QString defaultValue = defaultToolTip(); - if (!defaultValue.isEmpty()) { - tooltip += "

"; - tooltip += defaultValue; - tooltip += "

"; - } - tooltip += "
";
-            tooltip += version;
-            tooltip += "
"; - le->setToolTip(tooltip); - } - } - return false; -} + DataFromProcess::Parameters params(CommandLine(FilePath::fromString( + QDir::cleanPath(binary)), + m_arguments), + [](const QString &output) { return output; }); + params.callback = [binary, self = QPointer(this), + le = QPointer(le)](const std::optional &version) { + if (!self || !le) + return; + if (!version || version->isEmpty()) + return; + if (binary != le->text()) + return; -QString BinaryVersionToolTipEventFilter::toolVersion(const CommandLine &cmd) -{ - DataFromProcess::Parameters params(cmd, [](const QString &output) { return output; }); - using namespace std::chrono_literals; - params.timeout = 1s; - if (const auto version = DataFromProcess::getData(params)) - return *version; - return {}; + // Concatenate tooltips. + QString tooltip = ""; + const QString defaultValue = self->defaultToolTip(); + if (!defaultValue.isEmpty()) { + tooltip += "

"; + tooltip += defaultValue; + tooltip += "

"; + } + tooltip += "
";
+        tooltip += *version;
+        tooltip += "
"; + le->setToolTip(tooltip); + if (QRect(le->mapToGlobal(QPoint(0, 0)), le->size()).contains(QCursor::pos())) { + QCoreApplication::postEvent(le, + new QHelpEvent(QEvent::ToolTip, + le->mapFromGlobal(QCursor::pos()), + QCursor::pos())); + } + }; + DataFromProcess::provideData(params); + + return false; } // Extends BinaryVersionToolTipEventFilter to prepend the existing pathchooser @@ -722,11 +727,6 @@ FancyLineEdit *PathChooser::lineEdit() const return d->m_lineEdit; } -QString PathChooser::toolVersion(const CommandLine &cmd) -{ - return BinaryVersionToolTipEventFilter::toolVersion(cmd); -} - void PathChooser::installLineEditVersionToolTip(QLineEdit *le, const QStringList &arguments) { auto ef = new BinaryVersionToolTipEventFilter(le); diff --git a/src/libs/utils/pathchooser.h b/src/libs/utils/pathchooser.h index a91a853938f..a3e259a748d 100644 --- a/src/libs/utils/pathchooser.h +++ b/src/libs/utils/pathchooser.h @@ -99,8 +99,6 @@ public: QStringList commandVersionArguments() const; void setCommandVersionArguments(const QStringList &arguments); - // Utility to run a tool and return its stdout. - static QString toolVersion(const CommandLine &cmd); // Install a tooltip on lineedits used for binaries showing the version. static void installLineEditVersionToolTip(QLineEdit *le, const QStringList &arguments); diff --git a/src/plugins/git/gerrit/gerritparameters.cpp b/src/plugins/git/gerrit/gerritparameters.cpp index 781597e5e78..8aa9f73ca73 100644 --- a/src/plugins/git/gerrit/gerritparameters.cpp +++ b/src/plugins/git/gerrit/gerritparameters.cpp @@ -5,6 +5,7 @@ #include "gerritplugin.h" #include +#include #include #include #include @@ -70,8 +71,12 @@ void GerritParameters::setPortFlagBySshType() { bool isPlink = false; if (!ssh.isEmpty()) { - const QString version = PathChooser::toolVersion({ssh, {"-V"}}); - isPlink = version.contains("plink", Qt::CaseInsensitive); + DataFromProcess::Parameters params({ssh, {"-V"}}, + [](const QString &output) { return output; }); + using namespace std::chrono_literals; + params.timeout = 1s; + if (const auto version = DataFromProcess::getData(params)) + isPlink = version->contains("plink", Qt::CaseInsensitive); } portFlag = QLatin1String(isPlink ? "-P" : defaultPortFlag); } From fb2b861fb794afff65a49fa863041f4844bc026f Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 20 Feb 2024 13:45:39 +0100 Subject: [PATCH 0017/1060] Utils: Replace explicit cleanPath call by FilePath::fromUserInput Change-Id: I85199d1389864971f6e9fb6ca4290ad094b0a1c5 Reviewed-by: Reviewed-by: Christian Kandeler --- src/libs/utils/pathchooser.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp index edef66e1f8a..00b99e66719 100644 --- a/src/libs/utils/pathchooser.cpp +++ b/src/libs/utils/pathchooser.cpp @@ -107,8 +107,7 @@ bool BinaryVersionToolTipEventFilter::eventFilter(QObject *o, QEvent *e) QTC_ASSERT(le, return false); const QString binary = le->text(); - DataFromProcess::Parameters params(CommandLine(FilePath::fromString( - QDir::cleanPath(binary)), + DataFromProcess::Parameters params(CommandLine(FilePath::fromUserInput(binary), m_arguments), [](const QString &output) { return output; }); params.callback = [binary, self = QPointer(this), From 8893e5f14ab83e966e253cbefa46b1ef1882f4ed Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 20 Feb 2024 13:43:05 +0100 Subject: [PATCH 0018/1060] Debugger: Fix C++20 complaint about or-ing different enums Change-Id: Ie3648b3473476c3f71339006dff2c5dccf817b15 Reviewed-by: Jarek Kobus Reviewed-by: --- src/plugins/debugger/cdb/cdbengine.cpp | 2 +- src/plugins/debugger/cdb/cdbengine.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/debugger/cdb/cdbengine.cpp b/src/plugins/debugger/cdb/cdbengine.cpp index d292028050a..3d9777f51e1 100644 --- a/src/plugins/debugger/cdb/cdbengine.cpp +++ b/src/plugins/debugger/cdb/cdbengine.cpp @@ -2781,7 +2781,7 @@ void CdbEngine::setupScripting(const DebuggerResponse &response) showMessage("Reading " + codeFile.toUserOutput(), LogInput); runCommand({QString("module = types.ModuleType('%1')").arg(module), ScriptCommand}); runCommand({QString("code = bytes.fromhex('%1').decode('utf-8')") - .arg(QString::fromUtf8(code->toHex())), ScriptCommand | DebuggerCommand::Silent}); + .arg(QString::fromUtf8(code->toHex())), ScriptCommand | Silent}); runCommand({QString("exec(code, module.__dict__)"), ScriptCommand}); runCommand({QString("sys.modules['%1'] = module").arg(module), ScriptCommand}); runCommand({QString("import %1").arg(module), ScriptCommand}); diff --git a/src/plugins/debugger/cdb/cdbengine.h b/src/plugins/debugger/cdb/cdbengine.h index b8afe1e2d91..1cf499085e1 100644 --- a/src/plugins/debugger/cdb/cdbengine.h +++ b/src/plugins/debugger/cdb/cdbengine.h @@ -110,6 +110,7 @@ private: }; enum CommandFlags { NoFlags = 0, + Silent = DebuggerCommand::Silent, BuiltinCommand = DebuggerCommand::Silent << 1, ExtensionCommand = DebuggerCommand::Silent << 2, ScriptCommand = DebuggerCommand::Silent << 3 From b9e4c98f1d0c9aac74ada21e1bd43795063b92d5 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 19 Feb 2024 07:46:33 +0100 Subject: [PATCH 0019/1060] Debugger: Add a settings for gdb's debuginfod feature Fixes: QTCREATORBUG-28868 Change-Id: I216dbf8b46329c64607c869b5a8e090ef67fabb0 Reviewed-by: Christian Stenger --- src/plugins/debugger/debuggeractions.cpp | 1 + src/plugins/debugger/debuggeractions.h | 1 + src/plugins/debugger/gdb/gdbengine.cpp | 10 ++++++++++ src/plugins/debugger/gdb/gdbsettings.cpp | 7 +++++++ src/plugins/debugger/gdb/gdbsettings.h | 1 + 5 files changed, 20 insertions(+) diff --git a/src/plugins/debugger/debuggeractions.cpp b/src/plugins/debugger/debuggeractions.cpp index 5c313d1be53..1110c4e5593 100644 --- a/src/plugins/debugger/debuggeractions.cpp +++ b/src/plugins/debugger/debuggeractions.cpp @@ -60,6 +60,7 @@ DebuggerSettings::DebuggerSettings() : intelFlavor{gdbSettings().intelFlavor}, usePseudoTracepoints{gdbSettings().usePseudoTracepoints}, useIndexCache{gdbSettings().useIndexCache}, + useDebugInfoD{gdbSettings().useDebugInfoD}, gdbStartupCommands{gdbSettings().gdbStartupCommands}, gdbPostAttachCommands{gdbSettings().gdbPostAttachCommands}, targetAsync{gdbSettings().targetAsync}, diff --git a/src/plugins/debugger/debuggeractions.h b/src/plugins/debugger/debuggeractions.h index f20d60839b0..a9dbafff94e 100644 --- a/src/plugins/debugger/debuggeractions.h +++ b/src/plugins/debugger/debuggeractions.h @@ -48,6 +48,7 @@ public: Utils::BoolAspect &intelFlavor; Utils::BoolAspect &usePseudoTracepoints; Utils::BoolAspect &useIndexCache; + Utils::TriStateAspect &useDebugInfoD; Utils::StringAspect &gdbStartupCommands; Utils::StringAspect &gdbPostAttachCommands; diff --git a/src/plugins/debugger/gdb/gdbengine.cpp b/src/plugins/debugger/gdb/gdbengine.cpp index 9efc98f24c3..e89c96624ef 100644 --- a/src/plugins/debugger/gdb/gdbengine.cpp +++ b/src/plugins/debugger/gdb/gdbengine.cpp @@ -1492,6 +1492,16 @@ void GdbEngine::handleShowVersion(const DebuggerResponse &response) runCommand({"set target-async off", ConsoleCommand}); //runCommand("set build-id-verbose 2", ConsoleCommand); + + if (m_gdbVersion >= 100100) { + const TriState useDebugInfoD = settings().useDebugInfoD(); + if (useDebugInfoD == TriState::Enabled) { + runCommand({"set debuginfod verbose 1"}); + runCommand({"set debuginfod enabled on"}); + } else if (useDebugInfoD == TriState::Disabled) { + runCommand({"set debuginfod enabled off"}); + } + } } } diff --git a/src/plugins/debugger/gdb/gdbsettings.cpp b/src/plugins/debugger/gdb/gdbsettings.cpp index eef19df9719..d0088d59f0e 100644 --- a/src/plugins/debugger/gdb/gdbsettings.cpp +++ b/src/plugins/debugger/gdb/gdbsettings.cpp @@ -166,6 +166,12 @@ GdbSettings::GdbSettings() "binary in the future.")); useIndexCache.setDefaultValue(true); + useDebugInfoD.setSettingsKey("UseDebugInfoD"); + useDebugInfoD.setLabelText(Tr::tr("Use debug info daemon")); + useDebugInfoD.setOptionTexts({}, {}, tr("Use system settings")); + useDebugInfoD.setToolTip(Tr::tr("Lets GDB attempt to automatically retrieve " + "debug information for system packages.")); + skipKnownFrames.setSettingsKey("SkipKnownFrames"); skipKnownFrames.setDisplayName(Tr::tr("Skip Known Frames")); skipKnownFrames.setLabelText(Tr::tr("Skip known frames when stepping")); @@ -221,6 +227,7 @@ GdbSettings::GdbSettings() intelFlavor, usePseudoTracepoints, useIndexCache, + Row { useDebugInfoD, st }, st } }; diff --git a/src/plugins/debugger/gdb/gdbsettings.h b/src/plugins/debugger/gdb/gdbsettings.h index 73c2646e1ca..98b1bf78cb5 100644 --- a/src/plugins/debugger/gdb/gdbsettings.h +++ b/src/plugins/debugger/gdb/gdbsettings.h @@ -22,6 +22,7 @@ public: Utils::BoolAspect intelFlavor{this}; Utils::BoolAspect usePseudoTracepoints{this}; Utils::BoolAspect useIndexCache{this}; + Utils::TriStateAspect useDebugInfoD{this}; Utils::StringAspect gdbStartupCommands{this}; Utils::StringAspect gdbPostAttachCommands{this}; From 5956254e6f8676d3f409e1c55b0388cfdda3dd2e Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 20 Feb 2024 16:23:25 +0100 Subject: [PATCH 0020/1060] CppEditor: Make check for clangd more fine-grained ... in the quickfix factories. We want to be able to offer or not offer certain quickfixes based on the current clangd version. Change-Id: I7dca69ff990ab9f1a691785cd72e633f7882ae3d Reviewed-by: Reviewed-by: Christian Stenger Reviewed-by: Qt CI Bot --- .../clangcodemodel/clangmodelmanagersupport.cpp | 7 +++++-- src/plugins/clangcodemodel/clangmodelmanagersupport.h | 2 +- src/plugins/cppeditor/cppeditordocument.cpp | 2 +- src/plugins/cppeditor/cppmodelmanager.cpp | 2 +- src/plugins/cppeditor/cppmodelmanager.h | 4 +++- src/plugins/cppeditor/cppmodelmanagersupport.h | 8 +++++++- src/plugins/cppeditor/cppquickfix.h | 10 +++++++--- src/plugins/cppeditor/cppquickfix_test.cpp | 2 +- src/plugins/cppeditor/cppquickfixes.cpp | 9 ++++++--- src/plugins/cppeditor/cppquickfixes.h | 4 ++-- src/plugins/designer/qtcreatorintegration.cpp | 3 ++- 11 files changed, 36 insertions(+), 17 deletions(-) diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp index 3c3fc18c911..ddb928f5e99 100644 --- a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp +++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp @@ -428,9 +428,12 @@ void ClangModelManagerSupport::checkUnused(const Link &link, SearchResult *searc CppModelManager::Backend::Builtin)->checkUnused(link, search, callback); } -bool ClangModelManagerSupport::usesClangd(const TextEditor::TextDocument *document) const +std::optional ClangModelManagerSupport::usesClangd( + const TextEditor::TextDocument *document) const { - return clientForFile(document->filePath()); + if (const auto client = clientForFile(document->filePath())) + return client->versionNumber(); + return {}; } BaseEditorDocumentProcessor *ClangModelManagerSupport::createEditorDocumentProcessor( diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.h b/src/plugins/clangcodemodel/clangmodelmanagersupport.h index a598bea8bbd..839e71deb62 100644 --- a/src/plugins/clangcodemodel/clangmodelmanagersupport.h +++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.h @@ -42,7 +42,7 @@ public: CppEditor::BaseEditorDocumentProcessor *createEditorDocumentProcessor( TextEditor::TextDocument *baseTextDocument) override; - bool usesClangd(const TextEditor::TextDocument *document) const override; + std::optional usesClangd(const TextEditor::TextDocument *document) const override; static QList clientsForOpenProjects(); static ClangdClient *clientForProject(const ProjectExplorer::Project *project); diff --git a/src/plugins/cppeditor/cppeditordocument.cpp b/src/plugins/cppeditor/cppeditordocument.cpp index badd02b751b..459ae32977a 100644 --- a/src/plugins/cppeditor/cppeditordocument.cpp +++ b/src/plugins/cppeditor/cppeditordocument.cpp @@ -475,7 +475,7 @@ bool CppEditorDocument::saveImpl(QString *errorString, const FilePath &filePath, bool CppEditorDocument::usesClangd() const { - return CppModelManager::usesClangd(this); + return CppModelManager::usesClangd(this).has_value(); } void CppEditorDocument::onDiagnosticsChanged(const FilePath &fileName, const QString &kind) diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index 27aab615b71..a6e62518980 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -1714,7 +1714,7 @@ bool CppModelManager::isCppEditor(IEditor *editor) return editor->context().contains(ProjectExplorer::Constants::CXX_LANGUAGE_ID); } -bool CppModelManager::usesClangd(const TextEditor::TextDocument *document) +std::optional CppModelManager::usesClangd(const TextEditor::TextDocument *document) { return d->m_activeModelManagerSupport->usesClangd(document); } diff --git a/src/plugins/cppeditor/cppmodelmanager.h b/src/plugins/cppeditor/cppmodelmanager.h index 0fe9e151ae4..77cb212c6eb 100644 --- a/src/plugins/cppeditor/cppmodelmanager.h +++ b/src/plugins/cppeditor/cppmodelmanager.h @@ -19,9 +19,11 @@ #include #include #include +#include #include #include +#include #include namespace Core { @@ -132,7 +134,7 @@ public: static void emitAbstractEditorSupportRemoved(const QString &filePath); static bool isCppEditor(Core::IEditor *editor); - static bool usesClangd(const TextEditor::TextDocument *document); + static std::optional usesClangd(const TextEditor::TextDocument *document); static bool isClangCodeModelActive(); static QSet abstractEditorSupports(); diff --git a/src/plugins/cppeditor/cppmodelmanagersupport.h b/src/plugins/cppeditor/cppmodelmanagersupport.h index c2c463df59a..ca90d6758b7 100644 --- a/src/plugins/cppeditor/cppmodelmanagersupport.h +++ b/src/plugins/cppeditor/cppmodelmanagersupport.h @@ -9,7 +9,10 @@ #include +#include + #include +#include namespace Core { class SearchResult; } namespace TextEditor { @@ -31,7 +34,10 @@ public: virtual BaseEditorDocumentProcessor *createEditorDocumentProcessor( TextEditor::TextDocument *baseTextDocument) = 0; - virtual bool usesClangd(const TextEditor::TextDocument *) const { return false; } + virtual std::optional usesClangd(const TextEditor::TextDocument *) const + { + return {}; + } virtual void followSymbol(const CursorInEditor &data, const Utils::LinkHandler &processLinkCallback, diff --git a/src/plugins/cppeditor/cppquickfix.h b/src/plugins/cppeditor/cppquickfix.h index eab753ad6bd..e901b2bd306 100644 --- a/src/plugins/cppeditor/cppquickfix.h +++ b/src/plugins/cppeditor/cppquickfix.h @@ -8,6 +8,10 @@ #include +#include + +#include + namespace CppEditor { namespace Internal { class CppQuickFixInterface; @@ -52,8 +56,8 @@ public: static const QList &cppQuickFixFactories(); - bool hasClangdReplacement() const { return m_hasClangdReplacement; } - void setHasClangdReplacement() { m_hasClangdReplacement = true; } + std::optional clangdReplacement() const { return m_clangdReplacement; } + void setClangdReplacement(const QVersionNumber &version) { m_clangdReplacement = version; } private: /*! @@ -63,7 +67,7 @@ private: virtual void doMatch(const Internal::CppQuickFixInterface &interface, QuickFixOperations &result) = 0; - bool m_hasClangdReplacement = false; + std::optional m_clangdReplacement; }; } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp index 56ae513a8a1..d6de78b3765 100644 --- a/src/plugins/cppeditor/cppquickfix_test.cpp +++ b/src/plugins/cppeditor/cppquickfix_test.cpp @@ -191,7 +191,7 @@ QuickFixOperationTest::QuickFixOperationTest(const QList &testD const QByteArray &clangFormatSettings) : BaseQuickFixTestCase(testDocuments, headerPaths, clangFormatSettings) { - if (factory->hasClangdReplacement() && CppModelManager::isClangCodeModelActive()) + if (factory->clangdReplacement() && CppModelManager::isClangCodeModelActive()) return; QVERIFY(succeededSoFar()); diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp index bf3f1375117..df6c76bcf60 100644 --- a/src/plugins/cppeditor/cppquickfixes.cpp +++ b/src/plugins/cppeditor/cppquickfixes.cpp @@ -104,9 +104,12 @@ CppQuickFixFactory::~CppQuickFixFactory() void CppQuickFixFactory::match(const Internal::CppQuickFixInterface &interface, QuickFixOperations &result) { - if (m_hasClangdReplacement - && CppModelManager::usesClangd(interface.currentFile()->editor()->textDocument())) { - return; + if (m_clangdReplacement) { + if (const auto clangdVersion = CppModelManager::usesClangd( + interface.currentFile()->editor()->textDocument()); + clangdVersion && clangdVersion >= m_clangdReplacement) { + return; + } } doMatch(interface, result); diff --git a/src/plugins/cppeditor/cppquickfixes.h b/src/plugins/cppeditor/cppquickfixes.h index 10f82c9dda3..bd47b318c72 100644 --- a/src/plugins/cppeditor/cppquickfixes.h +++ b/src/plugins/cppeditor/cppquickfixes.h @@ -338,7 +338,7 @@ public: class CompleteSwitchCaseStatement: public CppQuickFixFactory { public: - CompleteSwitchCaseStatement() { setHasClangdReplacement(); } + CompleteSwitchCaseStatement() { setClangdReplacement({12}); } private: void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override; @@ -580,7 +580,7 @@ public: class RemoveUsingNamespace : public CppQuickFixFactory { public: - RemoveUsingNamespace() { setHasClangdReplacement(); } + RemoveUsingNamespace() { setClangdReplacement({10}); } private: void doMatch(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result) override; diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp index 267e0ddeeba..2da21f0e541 100644 --- a/src/plugins/designer/qtcreatorintegration.cpp +++ b/src/plugins/designer/qtcreatorintegration.cpp @@ -747,7 +747,8 @@ void QtCreatorIntegration::handleSymbolRenameStage2( // In the case of clangd, this entails doing a "virtual rename" on the TextDocument, // as the LanguageClient cannot be forced into taking a document and assuming a different // file path. - const bool usesClangd = CppEditor::CppModelManager::usesClangd(editorWidget->textDocument()); + const bool usesClangd + = CppEditor::CppModelManager::usesClangd(editorWidget->textDocument()).has_value(); if (usesClangd) editorWidget->textDocument()->setFilePath(uiHeader); editorWidget->textDocument()->setPlainText(QString::fromUtf8(virtualContent)); From ad30de78d694673296f29ea5122c56d632027ccf Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 20 Feb 2024 13:54:57 +0100 Subject: [PATCH 0021/1060] CppEditor: Do not store default values for code model settings Change-Id: I707135c4256953457ca2f6a4abc3245e45d8b5eb Reviewed-by: David Schulz Reviewed-by: --- .../cppeditor/cppcodemodelsettings.cpp | 74 +++++++++---------- src/plugins/cppeditor/cppcodemodelsettings.h | 8 +- 2 files changed, 39 insertions(+), 43 deletions(-) diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 304ffb90cb1..f5fae9cd6d0 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -31,8 +31,6 @@ using namespace Utils; namespace CppEditor { static Id initialClangDiagnosticConfigId() { return Constants::CPP_CLANG_DIAG_CONFIG_BUILDSYSTEM; } -static CppCodeModelSettings::PCHUsage initialPchUsage() - { return CppCodeModelSettings::PchUse_BuildSystem; } static Key enableLowerClazyLevelsKey() { return "enableLowerClazyLevels"; } static Key pchUsageKey() { return Constants::CPPEDITOR_MODEL_MANAGER_PCH_USAGE; } static Key interpretAmbiguousHeadersAsCHeadersKey() @@ -72,37 +70,25 @@ static FilePath fallbackClangdFilePath() return Environment::systemEnvironment().searchInPath("clangd"); } -CppCodeModelSettings::CppCodeModelSettings() -{ - fromSettings(Core::ICore::settings()); -} - void CppCodeModelSettings::fromSettings(QtcSettings *s) { s->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); - setEnableLowerClazyLevels(s->value(enableLowerClazyLevelsKey(), true).toBool()); - - const QVariant pchUsageVariant = s->value(pchUsageKey(), initialPchUsage()); - setPCHUsage(static_cast(pchUsageVariant.toInt())); - - const QVariant interpretAmbiguousHeadersAsCHeaders - = s->value(interpretAmbiguousHeadersAsCHeadersKey(), false); - setInterpretAmbigiousHeadersAsCHeaders(interpretAmbiguousHeadersAsCHeaders.toBool()); - - const QVariant skipIndexingBigFiles = s->value(skipIndexingBigFilesKey(), true); - setSkipIndexingBigFiles(skipIndexingBigFiles.toBool()); - - const QVariant ignoreFiles = s->value(ignoreFilesKey(), false); - setIgnoreFiles(ignoreFiles.toBool()); - - const QVariant ignorePattern = s->value(ignorePatternKey(), ""); - setIgnorePattern(ignorePattern.toString()); - - setUseBuiltinPreprocessor(s->value(useBuiltinPreprocessorKey(), true).toBool()); - - const QVariant indexerFileSizeLimit = s->value(indexerFileSizeLimitKey(), 5); - setIndexerFileSizeLimitInMb(indexerFileSizeLimit.toInt()); + const CppCodeModelSettings def; + setEnableLowerClazyLevels( + s->value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels()).toBool()); + setPCHUsage(static_cast(s->value(pchUsageKey(), def.pchUsage()).toInt())); + setInterpretAmbigiousHeadersAsCHeaders(s->value(interpretAmbiguousHeadersAsCHeadersKey(), + def.interpretAmbigiousHeadersAsCHeaders()) + .toBool()); + setSkipIndexingBigFiles( + s->value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles()).toBool()); + setIgnoreFiles(s->value(ignoreFilesKey(), def.ignoreFiles()).toBool()); + setIgnorePattern(s->value(ignorePatternKey(), def.ignorePattern()).toString()); + setUseBuiltinPreprocessor( + s->value(useBuiltinPreprocessorKey(), def.useBuiltinPreprocessor()).toBool()); + setIndexerFileSizeLimitInMb( + s->value(indexerFileSizeLimitKey(), def.indexerFileSizeLimitInMb()).toInt()); s->endGroup(); @@ -113,15 +99,25 @@ void CppCodeModelSettings::toSettings(QtcSettings *s) { s->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); - s->setValue(enableLowerClazyLevelsKey(), enableLowerClazyLevels()); - s->setValue(pchUsageKey(), pchUsage()); - - s->setValue(interpretAmbiguousHeadersAsCHeadersKey(), interpretAmbigiousHeadersAsCHeaders()); - s->setValue(skipIndexingBigFilesKey(), skipIndexingBigFiles()); - s->setValue(ignoreFilesKey(), ignoreFiles()); - s->setValue(ignorePatternKey(), QVariant(ignorePattern())); - s->setValue(useBuiltinPreprocessorKey(), useBuiltinPreprocessor()); - s->setValue(indexerFileSizeLimitKey(), indexerFileSizeLimitInMb()); + const CppCodeModelSettings def; + s->setValueWithDefault(enableLowerClazyLevelsKey(), + enableLowerClazyLevels(), + def.enableLowerClazyLevels()); + s->setValueWithDefault(pchUsageKey(), pchUsage(), def.pchUsage()); + s->setValueWithDefault(interpretAmbiguousHeadersAsCHeadersKey(), + interpretAmbigiousHeadersAsCHeaders(), + def.interpretAmbigiousHeadersAsCHeaders()); + s->setValueWithDefault(skipIndexingBigFilesKey(), + skipIndexingBigFiles(), + def.skipIndexingBigFiles()); + s->setValueWithDefault(ignoreFilesKey(), ignoreFiles(), def.ignoreFiles()); + s->setValueWithDefault(ignorePatternKey(), ignorePattern(), def.ignorePattern()); + s->setValueWithDefault(useBuiltinPreprocessorKey(), + useBuiltinPreprocessor(), + def.useBuiltinPreprocessor()); + s->setValueWithDefault(indexerFileSizeLimitKey(), + indexerFileSizeLimitInMb(), + def.indexerFileSizeLimitInMb()); s->endGroup(); @@ -670,7 +666,7 @@ int ClangdSettings::Data::defaultCompletionResults() CppCodeModelSettings &cppCodeModelSettings() { - static CppCodeModelSettings theCppCodeModelSettings; + static CppCodeModelSettings theCppCodeModelSettings(Core::ICore::settings()); return theCppCodeModelSettings; } diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index 123d6394556..f471710014c 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -31,13 +31,10 @@ public: PchUse_BuildSystem = 2 }; -public: - CppCodeModelSettings(); + CppCodeModelSettings(Utils::QtcSettings *s) { fromSettings(s); } - void fromSettings(Utils::QtcSettings *s); void toSettings(Utils::QtcSettings *s); -public: bool enableLowerClazyLevels() const; void setEnableLowerClazyLevels(bool yesno); @@ -69,6 +66,9 @@ signals: void changed(); private: + CppCodeModelSettings() = default; + void fromSettings(Utils::QtcSettings *s); + PCHUsage m_pchUsage = PchUse_BuildSystem; bool m_interpretAmbigiousHeadersAsCHeaders = false; bool m_skipIndexingBigFiles = true; From 68cc7f11b7268a93610877e8b33135954d685eb8 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 20 Feb 2024 15:41:42 +0100 Subject: [PATCH 0022/1060] CppEditor: Use Utils::Store in CppCodeModelSettings Preparation for introducing a per-project variant. Change-Id: I40897f3ad5261e0d28e6c1332a6951f61f5e749b Reviewed-by: David Schulz --- .../cppeditor/cppcodemodelsettings.cpp | 88 ++++++++++--------- src/plugins/cppeditor/cppcodemodelsettings.h | 7 +- 2 files changed, 52 insertions(+), 43 deletions(-) diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index f5fae9cd6d0..e06272084d6 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -72,56 +73,59 @@ static FilePath fallbackClangdFilePath() void CppCodeModelSettings::fromSettings(QtcSettings *s) { - s->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); - - const CppCodeModelSettings def; - setEnableLowerClazyLevels( - s->value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels()).toBool()); - setPCHUsage(static_cast(s->value(pchUsageKey(), def.pchUsage()).toInt())); - setInterpretAmbigiousHeadersAsCHeaders(s->value(interpretAmbiguousHeadersAsCHeadersKey(), - def.interpretAmbigiousHeadersAsCHeaders()) - .toBool()); - setSkipIndexingBigFiles( - s->value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles()).toBool()); - setIgnoreFiles(s->value(ignoreFilesKey(), def.ignoreFiles()).toBool()); - setIgnorePattern(s->value(ignorePatternKey(), def.ignorePattern()).toString()); - setUseBuiltinPreprocessor( - s->value(useBuiltinPreprocessorKey(), def.useBuiltinPreprocessor()).toBool()); - setIndexerFileSizeLimitInMb( - s->value(indexerFileSizeLimitKey(), def.indexerFileSizeLimitInMb()).toInt()); - - s->endGroup(); - + fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); emit changed(); } void CppCodeModelSettings::toSettings(QtcSettings *s) { - s->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); + storeToSettings(Constants::CPPEDITOR_SETTINGSGROUP, s, toMap()); + emit changed(); // TODO: Why? +} +Store CppCodeModelSettings::toMap() const +{ const CppCodeModelSettings def; - s->setValueWithDefault(enableLowerClazyLevelsKey(), - enableLowerClazyLevels(), - def.enableLowerClazyLevels()); - s->setValueWithDefault(pchUsageKey(), pchUsage(), def.pchUsage()); - s->setValueWithDefault(interpretAmbiguousHeadersAsCHeadersKey(), - interpretAmbigiousHeadersAsCHeaders(), - def.interpretAmbigiousHeadersAsCHeaders()); - s->setValueWithDefault(skipIndexingBigFilesKey(), - skipIndexingBigFiles(), - def.skipIndexingBigFiles()); - s->setValueWithDefault(ignoreFilesKey(), ignoreFiles(), def.ignoreFiles()); - s->setValueWithDefault(ignorePatternKey(), ignorePattern(), def.ignorePattern()); - s->setValueWithDefault(useBuiltinPreprocessorKey(), - useBuiltinPreprocessor(), - def.useBuiltinPreprocessor()); - s->setValueWithDefault(indexerFileSizeLimitKey(), - indexerFileSizeLimitInMb(), - def.indexerFileSizeLimitInMb()); + Store store; + store.insertValueWithDefault(enableLowerClazyLevelsKey(), + enableLowerClazyLevels(), + def.enableLowerClazyLevels()); + store.insertValueWithDefault(pchUsageKey(), pchUsage(), def.pchUsage()); + store.insertValueWithDefault(interpretAmbiguousHeadersAsCHeadersKey(), + interpretAmbigiousHeadersAsCHeaders(), + def.interpretAmbigiousHeadersAsCHeaders()); + store.insertValueWithDefault(skipIndexingBigFilesKey(), + skipIndexingBigFiles(), + def.skipIndexingBigFiles()); + store.insertValueWithDefault(ignoreFilesKey(), ignoreFiles(), def.ignoreFiles()); + store.insertValueWithDefault(ignorePatternKey(), ignorePattern(), def.ignorePattern()); + store.insertValueWithDefault(useBuiltinPreprocessorKey(), + useBuiltinPreprocessor(), + def.useBuiltinPreprocessor()); + store.insertValueWithDefault(indexerFileSizeLimitKey(), + indexerFileSizeLimitInMb(), + def.indexerFileSizeLimitInMb()); + return store; +} - s->endGroup(); - - emit changed(); +void CppCodeModelSettings::fromMap(const Utils::Store &store) +{ + const CppCodeModelSettings def; + setEnableLowerClazyLevels( + store.value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels()).toBool()); + setPCHUsage(static_cast(store.value(pchUsageKey(), def.pchUsage()).toInt())); + setInterpretAmbigiousHeadersAsCHeaders(store + .value(interpretAmbiguousHeadersAsCHeadersKey(), + def.interpretAmbigiousHeadersAsCHeaders()) + .toBool()); + setSkipIndexingBigFiles( + store.value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles()).toBool()); + setIgnoreFiles(store.value(ignoreFilesKey(), def.ignoreFiles()).toBool()); + setIgnorePattern(store.value(ignorePatternKey(), def.ignorePattern()).toString()); + setUseBuiltinPreprocessor( + store.value(useBuiltinPreprocessorKey(), def.useBuiltinPreprocessor()).toBool()); + setIndexerFileSizeLimitInMb( + store.value(indexerFileSizeLimitKey(), def.indexerFileSizeLimitInMb()).toInt()); } CppCodeModelSettings::PCHUsage CppCodeModelSettings::pchUsage() const diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index f471710014c..2343ca0efe3 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -17,7 +17,10 @@ #include namespace ProjectExplorer { class Project; } -namespace Utils { class MacroExpander; } +namespace Utils { +class MacroExpander; +class Store; +} // namespace Utils namespace CppEditor { @@ -68,6 +71,8 @@ signals: private: CppCodeModelSettings() = default; void fromSettings(Utils::QtcSettings *s); + Utils::Store toMap() const; + void fromMap(const Utils::Store &store); PCHUsage m_pchUsage = PchUse_BuildSystem; bool m_interpretAmbigiousHeadersAsCHeaders = false; From 59dc7c9c92b06e2e994e8de2b73fdebb1e8caa09 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 19 Feb 2024 15:09:18 +0100 Subject: [PATCH 0023/1060] Utils: Change individual TriStateAspect display strings individually Seems to be the more common case. Change-Id: Iff6b236983e37ebe74845a9013bac4a2b659edbb Reviewed-by: Marcus Tillmanns --- src/libs/utils/aspects.cpp | 31 ++++++++++++------- src/libs/utils/aspects.h | 17 +++++----- .../debuggerrunconfigurationaspect.cpp | 6 ++-- src/plugins/debugger/gdb/gdbsettings.cpp | 2 +- 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/libs/utils/aspects.cpp b/src/libs/utils/aspects.cpp index b72fc2060e3..1565e4bc300 100644 --- a/src/libs/utils/aspects.cpp +++ b/src/libs/utils/aspects.cpp @@ -2511,9 +2511,9 @@ void DoubleAspect::setSingleStep(double step) */ TriStateAspect::TriStateAspect(AspectContainer *container, - const QString &onString, - const QString &offString, - const QString &defaultString) + const QString &enabledDisplay, + const QString &disabledDisplay, + const QString &defaultDisplay) : SelectionAspect(container) { setDisplayStyle(DisplayStyle::ComboBox); @@ -2521,17 +2521,26 @@ TriStateAspect::TriStateAspect(AspectContainer *container, SelectionAspect::addOption({}); SelectionAspect::addOption({}); SelectionAspect::addOption({}); - setOptionTexts(onString, offString, defaultString); + setOptionText(TriState::EnabledValue, enabledDisplay); + setOptionText(TriState::DisabledValue, disabledDisplay); + setOptionText(TriState::DefaultValue, defaultDisplay); } -void TriStateAspect::setOptionTexts(const QString &onString, - const QString &offString, - const QString &defaultString) +static QString defaultTristateDisplay(TriState::Value tristate) { - QTC_ASSERT(d->m_options.size() == 3, return); - d->m_options[0].displayName = onString.isEmpty() ? Tr::tr("Enable") : onString; - d->m_options[1].displayName = offString.isEmpty() ? Tr::tr("Disable") : offString; - d->m_options[2].displayName = defaultString.isEmpty() ? Tr::tr("Leave at Default") : defaultString; + switch (tristate) { + case TriState::EnabledValue: return Tr::tr("Enable"); + case TriState::DisabledValue: return Tr::tr("Disable"); + case TriState::DefaultValue: return Tr::tr("Default"); + } + QTC_CHECK(false); + return {}; +} + +void TriStateAspect::setOptionText(const TriState::Value tristate, const QString &display) +{ + d->m_options[tristate].displayName = display.isEmpty() + ? defaultTristateDisplay(tristate) : display; } TriState TriStateAspect::value() const diff --git a/src/libs/utils/aspects.h b/src/libs/utils/aspects.h index cb885cc495a..9d4d7cc390f 100644 --- a/src/libs/utils/aspects.h +++ b/src/libs/utils/aspects.h @@ -773,11 +773,11 @@ private: class QTCREATOR_UTILS_EXPORT TriState { - enum Value { EnabledValue, DisabledValue, DefaultValue }; - explicit TriState(Value v) : m_value(v) {} - public: + enum Value { EnabledValue, DisabledValue, DefaultValue }; + TriState() = default; + explicit TriState(Value v) : m_value(v) {} int toInt() const { return int(m_value); } QVariant toVariant() const { return int(m_value); } @@ -801,9 +801,9 @@ class QTCREATOR_UTILS_EXPORT TriStateAspect : public SelectionAspect public: TriStateAspect(AspectContainer *container = nullptr, - const QString &onString = {}, - const QString &offString = {}, - const QString &defaultString = {}); + const QString &enabledDisplay = {}, + const QString &disabledDisplay = {}, + const QString &defaultDisplay = {}); TriState operator()() const { return value(); } TriState value() const; @@ -812,9 +812,8 @@ public: TriState defaultValue() const; void setDefaultValue(TriState setting); - void setOptionTexts(const QString &onString, - const QString &offString, - const QString &defaultString); + void setOptionText(const TriState::Value tristate, const QString &display); + private: void addOption(const QString &displayName, const QString &toolTip = {}) = delete; void addOption(const Option &option) = delete; diff --git a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp index cff934e398d..54ac38e8ece 100644 --- a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp +++ b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp @@ -111,15 +111,15 @@ DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(Target *target) m_cppAspect.setSettingsKey("RunConfiguration.UseCppDebugger"); m_cppAspect.setLabelText(Tr::tr("C++ debugger:")); - m_cppAspect.setOptionTexts(Tr::tr("Enabled"), Tr::tr("Disabled"), Tr::tr("Automatic")); + m_cppAspect.setOptionText(TriState::DefaultValue, Tr::tr("Automatic")); m_qmlAspect.setSettingsKey("RunConfiguration.UseQmlDebugger"); m_qmlAspect.setLabelText(Tr::tr("QML debugger:")); - m_qmlAspect.setOptionTexts(Tr::tr("Enabled"), Tr::tr("Disabled"), Tr::tr("Automatic")); + m_qmlAspect.setOptionText(TriState::DefaultValue, Tr::tr("Automatic")); m_pythonAspect.setSettingsKey("RunConfiguration.UsePythonDebugger"); m_pythonAspect.setLabelText(Tr::tr("Python debugger:")); - m_pythonAspect.setOptionTexts(Tr::tr("Enabled"), Tr::tr("Disabled"), Tr::tr("Automatic")); + m_pythonAspect.setOptionText(TriState::DefaultValue, Tr::tr("Automatic")); // Make sure at least one of the debuggers is set to be active. connect(&m_cppAspect, &TriStateAspect::changed, this, [this] { diff --git a/src/plugins/debugger/gdb/gdbsettings.cpp b/src/plugins/debugger/gdb/gdbsettings.cpp index d0088d59f0e..3d1bed263c8 100644 --- a/src/plugins/debugger/gdb/gdbsettings.cpp +++ b/src/plugins/debugger/gdb/gdbsettings.cpp @@ -168,7 +168,7 @@ GdbSettings::GdbSettings() useDebugInfoD.setSettingsKey("UseDebugInfoD"); useDebugInfoD.setLabelText(Tr::tr("Use debug info daemon")); - useDebugInfoD.setOptionTexts({}, {}, tr("Use system settings")); + useDebugInfoD.setOptionText(TriState::DefaultValue, tr("Use system settings")); useDebugInfoD.setToolTip(Tr::tr("Lets GDB attempt to automatically retrieve " "debug information for system packages.")); From 467dfa14dd96f04e862d6d0b9f3aa70b9efa6c70 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Mon, 19 Feb 2024 16:19:41 +0100 Subject: [PATCH 0024/1060] Utils: Rename HostArchitecture enum Since its not only good for the Host and to bring it in line with the OsType we rename HostArchitecture to OsArch. To make it work on all Platforms we change hostArchitecture to use QSysInfo instead of using Os specific calls. Change-Id: I1a9a4c8f9faa2a504694d8288110c9ee5c483440 Reviewed-by: hjk Reviewed-by: David Schulz Reviewed-by: --- src/libs/utils/hostosinfo.cpp | 42 +++++++------------ src/libs/utils/hostosinfo.h | 4 +- src/libs/utils/osspecificaspects.h | 2 + src/plugins/debugger/debuggeritemmanager.cpp | 2 +- src/plugins/projectexplorer/msvctoolchain.cpp | 20 ++++----- 5 files changed, 29 insertions(+), 41 deletions(-) diff --git a/src/libs/utils/hostosinfo.cpp b/src/libs/utils/hostosinfo.cpp index d8361266f08..e1ea49dfa0f 100644 --- a/src/libs/utils/hostosinfo.cpp +++ b/src/libs/utils/hostosinfo.cpp @@ -29,36 +29,26 @@ namespace Utils { Qt::CaseSensitivity HostOsInfo::m_overrideFileNameCaseSensitivity = Qt::CaseSensitive; bool HostOsInfo::m_useOverrideFileNameCaseSensitivity = false; -#ifdef Q_OS_WIN -static WORD hostProcessorArchitecture() +static OsArch parseArchitecture() { - SYSTEM_INFO info; - GetNativeSystemInfo(&info); - return info.wProcessorArchitecture; + QString currentArchitecture = QSysInfo::currentCpuArchitecture(); + if (currentArchitecture == QLatin1String("x86_64")) + return OsArchAMD64; + if (currentArchitecture == QLatin1String("x86")) + return OsArchX86; + if (currentArchitecture == QLatin1String("ia64")) + return OsArchItanium; + if (currentArchitecture == QLatin1String("arm")) + return OsArchArm; + if (currentArchitecture == QLatin1String("arm64")) + return OsArchArm64; + return OsArchUnknown; } -#endif -HostOsInfo::HostArchitecture HostOsInfo::hostArchitecture() +OsArch HostOsInfo::hostArchitecture() { -#ifdef Q_OS_WIN - static const WORD processorArchitecture = hostProcessorArchitecture(); - switch (processorArchitecture) { - case PROCESSOR_ARCHITECTURE_AMD64: - return HostOsInfo::HostArchitectureAMD64; - case PROCESSOR_ARCHITECTURE_INTEL: - return HostOsInfo::HostArchitectureX86; - case PROCESSOR_ARCHITECTURE_IA64: - return HostOsInfo::HostArchitectureItanium; - case PROCESSOR_ARCHITECTURE_ARM: - return HostOsInfo::HostArchitectureArm; - case PROCESSOR_ARCHITECTURE_ARM64: - return HostOsInfo::HostArchitectureArm64; - default: - return HostOsInfo::HostArchitectureUnknown; - } -#else - return HostOsInfo::HostArchitectureUnknown; -#endif + static const OsArch arch = parseArchitecture(); + return arch; } bool HostOsInfo::isRunningUnderRosetta() diff --git a/src/libs/utils/hostosinfo.h b/src/libs/utils/hostosinfo.h index 44880f7885c..fa153f24d54 100644 --- a/src/libs/utils/hostosinfo.h +++ b/src/libs/utils/hostosinfo.h @@ -41,9 +41,7 @@ public: #endif } - enum HostArchitecture { HostArchitectureX86, HostArchitectureAMD64, HostArchitectureItanium, - HostArchitectureArm, HostArchitectureArm64, HostArchitectureUnknown }; - static HostArchitecture hostArchitecture(); + static OsArch hostArchitecture(); static constexpr bool isWindowsHost() { return hostOs() == OsTypeWindows; } static constexpr bool isLinuxHost() { return hostOs() == OsTypeLinux; } diff --git a/src/libs/utils/osspecificaspects.h b/src/libs/utils/osspecificaspects.h index c735f313abc..d2a588688be 100644 --- a/src/libs/utils/osspecificaspects.h +++ b/src/libs/utils/osspecificaspects.h @@ -14,6 +14,8 @@ namespace Utils { // Add more as needed. enum OsType { OsTypeWindows, OsTypeLinux, OsTypeMac, OsTypeOtherUnix, OsTypeOther }; +enum OsArch { OsArchUnknown, OsArchX86, OsArchAMD64, OsArchItanium, OsArchArm, OsArchArm64 }; + inline QString osTypeToString(OsType osType) { switch (osType) { diff --git a/src/plugins/debugger/debuggeritemmanager.cpp b/src/plugins/debugger/debuggeritemmanager.cpp index 2644e3fa125..87b62472985 100644 --- a/src/plugins/debugger/debuggeritemmanager.cpp +++ b/src/plugins/debugger/debuggeritemmanager.cpp @@ -549,7 +549,7 @@ void DebuggerItemModel::autoDetectCdbDebuggers() for (const QFileInfo &kitFolderFi : kitFolders) { const QString path = kitFolderFi.absoluteFilePath(); QStringList abis = {"x86", "x64"}; - if (HostOsInfo::hostArchitecture() == HostOsInfo::HostArchitectureArm64) + if (HostOsInfo::hostArchitecture() == Utils::OsArchArm64) abis << "arm64"; for (const QString &abi: abis) { const QFileInfo cdbBinary(path + "/Debuggers/" + abi + "/cdb.exe"); diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp index 5c1ded6a84b..f5d66994696 100644 --- a/src/plugins/projectexplorer/msvctoolchain.cpp +++ b/src/plugins/projectexplorer/msvctoolchain.cpp @@ -124,19 +124,19 @@ static QString platformName(MsvcToolchain::Platform t) static bool hostPrefersPlatform(MsvcToolchain::Platform platform) { switch (HostOsInfo::hostArchitecture()) { - case HostOsInfo::HostArchitectureAMD64: + case Utils::OsArchAMD64: return platform == MsvcToolchain::amd64 || platform == MsvcToolchain::amd64_arm || platform == MsvcToolchain::amd64_x86 || platform == MsvcToolchain::amd64_arm64; - case HostOsInfo::HostArchitectureX86: + case Utils::OsArchX86: return platform == MsvcToolchain::x86 || platform == MsvcToolchain::x86_amd64 || platform == MsvcToolchain::x86_ia64 || platform == MsvcToolchain::x86_arm || platform == MsvcToolchain::x86_arm64; - case HostOsInfo::HostArchitectureArm: + case Utils::OsArchArm: return platform == MsvcToolchain::arm; - case HostOsInfo::HostArchitectureArm64: + case Utils::OsArchArm64: return platform == MsvcToolchain::arm64 || platform == MsvcToolchain::arm64_x86 || platform == MsvcToolchain::arm64_amd64; - case HostOsInfo::HostArchitectureItanium: + case Utils::OsArchItanium: return platform == MsvcToolchain::ia64; default: return false; @@ -151,12 +151,12 @@ static bool hostSupportsPlatform(MsvcToolchain::Platform platform) switch (HostOsInfo::hostArchitecture()) { // The x86 host toolchains are not the preferred toolchains on amd64 but they are still // supported by that host - case HostOsInfo::HostArchitectureAMD64: + case Utils::OsArchAMD64: return platform == MsvcToolchain::x86 || platform == MsvcToolchain::x86_amd64 || platform == MsvcToolchain::x86_ia64 || platform == MsvcToolchain::x86_arm || platform == MsvcToolchain::x86_arm64; // The Arm64 host can run the cross-compilers via emulation of x86 and amd64 - case HostOsInfo::HostArchitectureArm64: + case Utils::OsArchArm64: return platform == MsvcToolchain::x86_arm || platform == MsvcToolchain::x86_arm64 || platform == MsvcToolchain::amd64_arm || platform == MsvcToolchain::amd64_arm64 || platform == MsvcToolchain::x86 || platform == MsvcToolchain::x86_amd64 @@ -1228,8 +1228,7 @@ MsvcToolchain::Platform MsvcToolchain::platform() const QStringList args = m_varsBatArg.split(' '); if (const MsvcPlatform *entry = platformEntryFromName(args.value(0))) return entry->platform; - return Utils::HostOsInfo::hostArchitecture() == Utils::HostOsInfo::HostArchitectureAMD64 ? amd64 - : x86; + return Utils::HostOsInfo::hostArchitecture() == Utils::OsArchAMD64 ? amd64 : x86; } // -------------------------------------------------------------------------- @@ -1308,8 +1307,7 @@ public: m_varsBatPathCombo->addItem(nativeVcVars); } } - const bool isAmd64 - = Utils::HostOsInfo::hostArchitecture() == Utils::HostOsInfo::HostArchitectureAMD64; + const bool isAmd64 = Utils::HostOsInfo::hostArchitecture() == Utils::OsArchAMD64; // TODO: Add missing values to MsvcToolChain::Platform m_varsBatArchCombo->addItem(Tr::tr(""), isAmd64 ? MsvcToolchain::amd64 : MsvcToolchain::x86); m_varsBatArchCombo->addItem("x86", MsvcToolchain::x86); From 48d3e57e7a3f8df2edf3c6b82659e706ecd957c4 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 22 Feb 2024 10:58:58 +0100 Subject: [PATCH 0025/1060] Utils: Add osArchFromString() Change-Id: I3c49d28341148858027c5679101c180d28de0c08 Reviewed-by: David Schulz --- src/libs/utils/hostosinfo.cpp | 18 +----------------- src/libs/utils/osspecificaspects.h | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/libs/utils/hostosinfo.cpp b/src/libs/utils/hostosinfo.cpp index e1ea49dfa0f..717dc900cd8 100644 --- a/src/libs/utils/hostosinfo.cpp +++ b/src/libs/utils/hostosinfo.cpp @@ -29,25 +29,9 @@ namespace Utils { Qt::CaseSensitivity HostOsInfo::m_overrideFileNameCaseSensitivity = Qt::CaseSensitive; bool HostOsInfo::m_useOverrideFileNameCaseSensitivity = false; -static OsArch parseArchitecture() -{ - QString currentArchitecture = QSysInfo::currentCpuArchitecture(); - if (currentArchitecture == QLatin1String("x86_64")) - return OsArchAMD64; - if (currentArchitecture == QLatin1String("x86")) - return OsArchX86; - if (currentArchitecture == QLatin1String("ia64")) - return OsArchItanium; - if (currentArchitecture == QLatin1String("arm")) - return OsArchArm; - if (currentArchitecture == QLatin1String("arm64")) - return OsArchArm64; - return OsArchUnknown; -} - OsArch HostOsInfo::hostArchitecture() { - static const OsArch arch = parseArchitecture(); + static const OsArch arch = osArchFromString(QSysInfo::currentCpuArchitecture()); return arch; } diff --git a/src/libs/utils/osspecificaspects.h b/src/libs/utils/osspecificaspects.h index d2a588688be..d0705df6371 100644 --- a/src/libs/utils/osspecificaspects.h +++ b/src/libs/utils/osspecificaspects.h @@ -46,6 +46,21 @@ inline OsType osTypeFromString(const QString &string) return OsTypeOther; } +inline OsArch osArchFromString(const QString &architecture) +{ + if (architecture == QLatin1String("x86_64")) + return OsArchAMD64; + if (architecture == QLatin1String("x86")) + return OsArchX86; + if (architecture == QLatin1String("ia64")) + return OsArchItanium; + if (architecture == QLatin1String("arm")) + return OsArchArm; + if (architecture == QLatin1String("arm64")) + return OsArchArm64; + return OsArchUnknown; +} + namespace OsSpecificAspects { inline QString withExecutableSuffix(OsType osType, const QString &executable) From e678da9934acfdf3fe2dd4f2eaed8881f7cd35f3 Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 30 Jun 2023 07:32:46 +0200 Subject: [PATCH 0026/1060] Require C++20 Change-Id: Id6581a4c32ec6411195edb51339f017e4ddb51ff Reviewed-by: Marco Bubke Reviewed-by: Eike Ziller --- CMakeLists.txt | 2 +- qbs/imports/QtcProduct.qbs | 2 +- share/qtcreator/cplusplus/examples/CMakeLists.txt | 2 +- src/libs/qtcreatorcdbext/CMakeLists.txt | 2 +- src/tools/qml2puppet/CMakeLists.txt | 2 +- src/tools/sdktool/CMakeLists.txt | 2 +- src/tools/wininterrupt/CMakeLists.txt | 2 +- tests/auto/debugger/CMakeLists.txt | 2 +- tests/manual/debugger/gui/CMakeLists.txt | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2aefb1a58dd..ef82879259e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,7 +25,7 @@ mark_as_advanced(IDE_REVISION IDE_REVISION_STR IDE_REVISION_URL) project(QtCreator VERSION ${IDE_VERSION}) # Force C++ standard, do not fall back, do not use compiler extensions -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/qbs/imports/QtcProduct.qbs b/qbs/imports/QtcProduct.qbs index adf7314d0b2..428a23791df 100644 --- a/qbs/imports/QtcProduct.qbs +++ b/qbs/imports/QtcProduct.qbs @@ -47,7 +47,7 @@ Product { } return flags; } - cpp.cxxLanguageVersion: "c++17" + cpp.cxxLanguageVersion: "c++20" cpp.defines: qtc.generalDefines Properties { condition: sanitizable && qbs.toolchain.contains("gcc") diff --git a/share/qtcreator/cplusplus/examples/CMakeLists.txt b/share/qtcreator/cplusplus/examples/CMakeLists.txt index 004deeded3e..7d14eba5b98 100644 --- a/share/qtcreator/cplusplus/examples/CMakeLists.txt +++ b/share/qtcreator/cplusplus/examples/CMakeLists.txt @@ -8,7 +8,7 @@ set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui Widgets REQUIRED) diff --git a/src/libs/qtcreatorcdbext/CMakeLists.txt b/src/libs/qtcreatorcdbext/CMakeLists.txt index 97307164f65..8a737e3fadb 100644 --- a/src/libs/qtcreatorcdbext/CMakeLists.txt +++ b/src/libs/qtcreatorcdbext/CMakeLists.txt @@ -4,7 +4,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake") project(qtcreatorcdbext) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/src/tools/qml2puppet/CMakeLists.txt b/src/tools/qml2puppet/CMakeLists.txt index 9244a9454db..c03567e0381 100644 --- a/src/tools/qml2puppet/CMakeLists.txt +++ b/src/tools/qml2puppet/CMakeLists.txt @@ -9,7 +9,7 @@ if (NOT QT_CREATOR_API_DEFINED) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) - set(CMAKE_CXX_STANDARD 17) + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/src/tools/sdktool/CMakeLists.txt b/src/tools/sdktool/CMakeLists.txt index 19b8571f562..97c96909b61 100644 --- a/src/tools/sdktool/CMakeLists.txt +++ b/src/tools/sdktool/CMakeLists.txt @@ -7,7 +7,7 @@ project(sdktool) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/src/tools/wininterrupt/CMakeLists.txt b/src/tools/wininterrupt/CMakeLists.txt index ee40ff769b8..fdd5a33e4d1 100644 --- a/src/tools/wininterrupt/CMakeLists.txt +++ b/src/tools/wininterrupt/CMakeLists.txt @@ -4,7 +4,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake") project(wininterrupt) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/tests/auto/debugger/CMakeLists.txt b/tests/auto/debugger/CMakeLists.txt index 2f06a6b2fc7..01761ba5aa2 100644 --- a/tests/auto/debugger/CMakeLists.txt +++ b/tests/auto/debugger/CMakeLists.txt @@ -16,7 +16,7 @@ if (NOT QT_CREATOR_API_DEFINED) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) - set(CMAKE_CXX_STANDARD 17) + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/tests/manual/debugger/gui/CMakeLists.txt b/tests/manual/debugger/gui/CMakeLists.txt index 412b0cdc429..1201ebd4f1c 100644 --- a/tests/manual/debugger/gui/CMakeLists.txt +++ b/tests/manual/debugger/gui/CMakeLists.txt @@ -5,7 +5,7 @@ project(manual_test_debugger_gui LANGUAGES CXX) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets) From 0aa54364f84a9da0ba5a00c54b9781102bc30625 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 22 Feb 2024 10:42:42 +0100 Subject: [PATCH 0027/1060] Utils: Remove offset parameter from writeFileContents It never worked and was not used, so remove it for now. Change-Id: If271bf83e1c766cc31fdb24dbab9eac228fda0a2 Reviewed-by: hjk --- src/libs/utils/devicefileaccess.cpp | 16 +++------------- src/libs/utils/devicefileaccess.h | 9 +++------ src/libs/utils/filepath.cpp | 4 ++-- src/libs/utils/filepath.h | 2 +- 4 files changed, 9 insertions(+), 22 deletions(-) diff --git a/src/libs/utils/devicefileaccess.cpp b/src/libs/utils/devicefileaccess.cpp index 39bdc736e09..d3a8360136e 100644 --- a/src/libs/utils/devicefileaccess.cpp +++ b/src/libs/utils/devicefileaccess.cpp @@ -314,12 +314,10 @@ expected_str DeviceFileAccess::fileContents(const FilePath &filePath } expected_str DeviceFileAccess::writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const + const QByteArray &data) const { Q_UNUSED(filePath) Q_UNUSED(data) - Q_UNUSED(offset) QTC_CHECK(false); return make_unexpected( Tr::tr("writeFileContents is not implemented for \"%1\".").arg(filePath.toUserOutput())); @@ -738,8 +736,7 @@ expected_str DesktopDeviceFileAccess::fileContents(const FilePath &f } expected_str DesktopDeviceFileAccess::writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const + const QByteArray &data) const { QFile file(filePath.path()); const bool isOpened = file.open(QFile::WriteOnly | QFile::Truncate); @@ -747,8 +744,6 @@ expected_str DesktopDeviceFileAccess::writeFileContents(const FilePath & return make_unexpected( Tr::tr("Could not open file \"%1\" for writing.").arg(filePath.toUserOutput())); - if (offset != 0) - file.seek(offset); qint64 res = file.write(data); if (res != data.size()) return make_unexpected( @@ -1088,17 +1083,12 @@ expected_str UnixDeviceFileAccess::fileContents(const FilePath &file } expected_str UnixDeviceFileAccess::writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const + const QByteArray &data) const { if (disconnected()) return make_unexpected_disconnected(); QStringList args = {"of=" + filePath.path()}; - if (offset != 0) { - args.append("bs=1"); - args.append(QString("seek=%1").arg(offset)); - } RunResult result = runInShell({"dd", args, OsType::OsTypeLinux}, data); if (result.exitCode != 0) { diff --git a/src/libs/utils/devicefileaccess.h b/src/libs/utils/devicefileaccess.h index ba484541275..8a0884ec1d0 100644 --- a/src/libs/utils/devicefileaccess.h +++ b/src/libs/utils/devicefileaccess.h @@ -69,8 +69,7 @@ protected: qint64 offset) const; virtual expected_str writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const; + const QByteArray &data) const; virtual expected_str createTempFile(const FilePath &filePath); }; @@ -125,8 +124,7 @@ protected: qint64 limit, qint64 offset) const override; expected_str writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const override; + const QByteArray &data) const override; expected_str createTempFile(const FilePath &filePath) override; @@ -178,8 +176,7 @@ protected: qint64 limit, qint64 offset) const override; expected_str writeFileContents(const FilePath &filePath, - const QByteArray &data, - qint64 offset) const override; + const QByteArray &data) const override; expected_str createTempFile(const FilePath &filePath) override; diff --git a/src/libs/utils/filepath.cpp b/src/libs/utils/filepath.cpp index 562f3247bd8..1b9b6e943c3 100644 --- a/src/libs/utils/filepath.cpp +++ b/src/libs/utils/filepath.cpp @@ -655,9 +655,9 @@ bool FilePath::ensureReachable(const FilePath &other) const return false; } -expected_str FilePath::writeFileContents(const QByteArray &data, qint64 offset) const +expected_str FilePath::writeFileContents(const QByteArray &data) const { - return fileAccess()->writeFileContents(*this, data, offset); + return fileAccess()->writeFileContents(*this, data); } FileStreamHandle FilePath::asyncCopy(const FilePath &target, QObject *context, diff --git a/src/libs/utils/filepath.h b/src/libs/utils/filepath.h index 2b1eb14069e..cb975248ec2 100644 --- a/src/libs/utils/filepath.h +++ b/src/libs/utils/filepath.h @@ -139,7 +139,7 @@ public: FilePaths dirEntries(const FileFilter &filter, QDir::SortFlags sort = QDir::NoSort) const; FilePaths dirEntries(QDir::Filters filters) const; expected_str fileContents(qint64 maxSize = -1, qint64 offset = 0) const; - expected_str writeFileContents(const QByteArray &data, qint64 offset = 0) const; + expected_str writeFileContents(const QByteArray &data) const; FilePathInfo filePathInfo() const; [[nodiscard]] FilePath operator/(const QString &str) const; From 8b443ace57f4b64b1a295394211446f0a0e24552 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 22 Feb 2024 10:43:55 +0100 Subject: [PATCH 0028/1060] Utils: Compare osType case insensitively Change-Id: I1bc8fb24a579a00114eb2a8ef27806a0c79c35ae Reviewed-by: hjk --- src/libs/utils/osspecificaspects.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/libs/utils/osspecificaspects.h b/src/libs/utils/osspecificaspects.h index d0705df6371..239290faec7 100644 --- a/src/libs/utils/osspecificaspects.h +++ b/src/libs/utils/osspecificaspects.h @@ -35,13 +35,14 @@ inline QString osTypeToString(OsType osType) inline OsType osTypeFromString(const QString &string) { - if (string == "Windows") + if (string.compare("windows", Qt::CaseInsensitive) == 0) return OsTypeWindows; - if (string == "Linux") + if (string.compare("linux", Qt::CaseInsensitive) == 0) return OsTypeLinux; - if (string == "Mac") + if (string.compare("mac", Qt::CaseInsensitive) == 0 + || string.compare("darwin", Qt::CaseInsensitive) == 0) return OsTypeMac; - if (string == "Other Unix") + if (string.compare("other unix", Qt::CaseInsensitive) == 0) return OsTypeOtherUnix; return OsTypeOther; } From faa6ad50c46d1a8f141cbfa81a446a63ba7e591b Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 22 Feb 2024 12:53:02 +0100 Subject: [PATCH 0029/1060] CppEditor: Remove unused signal Amends 760cf632afddbdbc6cf1ded0655e8286ccbffd1f. Change-Id: I4b5b1c74549d293a3664825bee461c9a3cfbd342 Reviewed-by: David Schulz --- src/plugins/cppeditor/cppcodemodelsettings.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index 2343ca0efe3..fbca534c384 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -65,7 +65,6 @@ public: void setIgnorePattern(const QString& ignorePattern); signals: - void clangDiagnosticConfigsInvalidated(const QVector &configId); void changed(); private: From 111795495039e6d479a77319828d8c946a4152a4 Mon Sep 17 00:00:00 2001 From: Andre Hartmann Date: Thu, 22 Feb 2024 09:19:04 +0100 Subject: [PATCH 0030/1060] Git: Respect author and mail mapping Git allows mapping authors and mail addresses: https://git-scm.com/docs/gitmailmap While using this file already worked for (instant) blame, log and show still used the original values from the repo. This patch makes the display within Creator consistent. Change-Id: I3c0e764c435a505e285941f4fdc91131f85af590 Reviewed-by: Orgad Shaneh Reviewed-by: --- src/plugins/git/gitclient.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp index eb857c46859..9e2144c3217 100644 --- a/src/plugins/git/gitclient.cpp +++ b/src/plugins/git/gitclient.cpp @@ -69,8 +69,8 @@ const char graphOption[] = "--graph"; const char decorateOption[] = "--decorate"; const char showFormatC[] = "--pretty=format:commit %H%d%n" - "Author: %an <%ae>, %ad (%ar)%n" - "Committer: %cn <%ce>, %cd (%cr)%n" + "Author: %aN <%aE>, %ad (%ar)%n" + "Committer: %cN <%cE>, %cd (%cr)%n" "%n" "%B"; @@ -686,7 +686,7 @@ public: "--pretty=format:" "%C(%1)%h%Creset " "%C(%2)%d%Creset " - "%C(%3)%an%Creset " + "%C(%3)%aN%Creset " "%C(%4)%s%Creset " "%C(%5)%ci%Creset" ).arg(commitHash, decoration, authorName, commitSubject, commitDate); @@ -696,7 +696,7 @@ public: if (gitHasRgbColors()) graphArgs << formatArg; else - graphArgs << "--pretty=format:%h %d %an %s %ci"; + graphArgs << "--pretty=format:%h %d %aN %s %ci"; return graphArgs; } @@ -1021,7 +1021,7 @@ static QStringList normalLogArguments() const QString logArgs = QStringLiteral( "--pretty=format:" "commit %C(%1)%H%Creset %C(%2)%d%Creset%n" - "Author: %C(%3)%an <%ae>%Creset%n" + "Author: %C(%3)%aN <%aE>%Creset%n" "Date: %C(%4)%cD %Creset%n%n" "%C(%5)%w(0,4,4)%s%Creset%n%n%b" ).arg(commitHash, decoration, authorName, commitDate, commitSubject); @@ -1593,7 +1593,7 @@ QString GitClient::synchronousShortDescription(const FilePath &workingDirectory, const QString quoteReplacement = "_-_"; // Short SHA1, author, subject - const QString defaultShortLogFormat = "%h (%an " + quoteReplacement + "%s"; + const QString defaultShortLogFormat = "%h (%aN " + quoteReplacement + "%s"; const int maxShortLogLength = 120; // Short SHA 1, author, subject @@ -2569,7 +2569,7 @@ bool GitClient::readDataFromCommit(const FilePath &repoDirectory, const QString QString *commitTemplate) { // Get commit data as "SHA1authoremailmessage". - const QStringList arguments = {"log", "--max-count=1", "--pretty=format:%h\n%an\n%ae\n%B", commit}; + const QStringList arguments = {"log", "--max-count=1", "--pretty=format:%h\n%aN\n%aE\n%B", commit}; const CommandResult result = vcsSynchronousExec(repoDirectory, arguments, RunFlags::NoOutput); if (result.result() != ProcessResult::FinishedWithSuccess) { From 0459d3dde75b287ed4a8b06341ebc7efb03db3be Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 2 Feb 2024 14:55:06 +0100 Subject: [PATCH 0031/1060] CppEditor: Un-export CppProjectUpdater Does not seem to be used outside. Change-Id: I9ed27e20ebb23ffd59b7f557b1ff56dbcadd6a2d Reviewed-by: Christian Kandeler --- src/plugins/cppeditor/cppprojectupdater.cpp | 28 ++++++++++++++----- src/plugins/cppeditor/cppprojectupdater.h | 30 ++------------------- 2 files changed, 23 insertions(+), 35 deletions(-) diff --git a/src/plugins/cppeditor/cppprojectupdater.cpp b/src/plugins/cppeditor/cppprojectupdater.cpp index a4ddbd49f68..80ab1ad6cd5 100644 --- a/src/plugins/cppeditor/cppprojectupdater.cpp +++ b/src/plugins/cppeditor/cppprojectupdater.cpp @@ -12,30 +12,45 @@ #include #include +#include +#include + +#include #include #include +#include #include using namespace ProjectExplorer; using namespace Tasking; using namespace Utils; -namespace CppEditor { +namespace CppEditor::Internal { + +class CppProjectUpdater final : public ProjectUpdater +{ +public: + void update(const ProjectUpdateInfo &projectUpdateInfo, + const QList &extraCompilers) final; + void cancel() final; + +private: + FutureSynchronizer m_futureSynchronizer; + TaskTreeRunner m_taskTreeRunner; +}; void CppProjectUpdater::update(const ProjectUpdateInfo &projectUpdateInfo, - const QList &extraCompilers) + const QList &extraCompilers) { // Stop previous update. cancel(); - const QList> compilers = + const QList> compilers = Utils::transform(extraCompilers, [](ExtraCompiler *compiler) { return QPointer(compiler); }); - using namespace ProjectExplorer; - // Run the project info generator in a worker thread and continue if that one is finished. const auto infoGenerator = [=](QPromise &promise) { ProjectUpdateInfo fullProjectUpdateInfo = projectUpdateInfo; @@ -45,7 +60,6 @@ void CppProjectUpdater::update(const ProjectUpdateInfo &projectUpdateInfo, promise.addResult(generator.generate(promise)); }; - using namespace Tasking; struct UpdateStorage { ProjectInfo::ConstPtr projectInfo = nullptr; }; @@ -112,4 +126,4 @@ void setupCppProjectUpdater() static CppProjectUpdaterFactory theCppProjectUpdaterFactory; } -} // namespace CppEditor +} // CppEditor::Internal diff --git a/src/plugins/cppeditor/cppprojectupdater.h b/src/plugins/cppeditor/cppprojectupdater.h index 1057feaed6a..19c7c038e30 100644 --- a/src/plugins/cppeditor/cppprojectupdater.h +++ b/src/plugins/cppeditor/cppprojectupdater.h @@ -3,34 +3,8 @@ #pragma once -#include "cppeditor_global.h" - -#include -#include - -#include - -#include - -namespace ProjectExplorer { class ExtraCompiler; } - -namespace CppEditor { - -class CPPEDITOR_EXPORT CppProjectUpdater final - : public QObject, public ProjectExplorer::ProjectUpdater -{ - Q_OBJECT - -public: - void update(const ProjectExplorer::ProjectUpdateInfo &projectUpdateInfo, - const QList &extraCompilers) override; - void cancel() override; - -private: - Utils::FutureSynchronizer m_futureSynchronizer; - Tasking::TaskTreeRunner m_taskTreeRunner; -}; +namespace CppEditor::Internal { void setupCppProjectUpdater(); -} // namespace CppEditor +} // CppEditor::Internal From 48a8fa4c5df86807506a0faa20feec1abb19ffc0 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Fri, 23 Feb 2024 16:37:27 +0100 Subject: [PATCH 0032/1060] Utils: Fix build with too old MSVC Change-Id: Ib845a702eea3f61b3c453d3531f94a70db03a95e Reviewed-by: Christian Kandeler --- src/libs/utils/ranges.h | 2 +- src/libs/utils/utils.qbs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libs/utils/ranges.h b/src/libs/utils/ranges.h index 8b574e08d6f..738521df467 100644 --- a/src/libs/utils/ranges.h +++ b/src/libs/utils/ranges.h @@ -3,7 +3,7 @@ #pragma once -#if __cplusplus >= 202002L +#if __cplusplus >= 202002L && defined(__cpp_lib_ranges) #include namespace Utils { diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs index 9cc3aced5a3..348ee3e2661 100644 --- a/src/libs/utils/utils.qbs +++ b/src/libs/utils/utils.qbs @@ -260,6 +260,7 @@ QtcLibrary { "qtcolorbutton.h", "qtcsettings.cpp", "qtcsettings.h", + "ranges.h", "reloadpromptutils.cpp", "reloadpromptutils.h", "removefiledialog.cpp", From 3f692e2f1743d58bf7af6312a9199a857fc7ddee Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 21 Feb 2024 15:49:10 +0100 Subject: [PATCH 0033/1060] CppEditor: Refactor CppCodeModelSettings Preparation for per-project settings. Change-Id: I78ecf0cde6150e40353c4aea6a98717d119f05c7 Reviewed-by: David Schulz Reviewed-by: --- .../cppeditor/baseeditordocumentprocessor.cpp | 6 +- .../clangdiagnosticconfigsselectionwidget.cpp | 4 - .../cppeditor/cppcodemodelsettings.cpp | 183 +++++++----------- src/plugins/cppeditor/cppcodemodelsettings.h | 74 +++---- .../cppeditor/cppcodemodelsettingspage.cpp | 93 +++------ 5 files changed, 137 insertions(+), 223 deletions(-) diff --git a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp index f48c5a710be..d7da8251ee8 100644 --- a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp @@ -35,9 +35,9 @@ BaseEditorDocumentProcessor::~BaseEditorDocumentProcessor() = default; void BaseEditorDocumentProcessor::run(bool projectsUpdated) { - const Utils::Language languagePreference = codeModelSettings()->interpretAmbigiousHeadersAsCHeaders() - ? Utils::Language::C - : Utils::Language::Cxx; + const Utils::Language languagePreference = codeModelSettings()->interpretAmbigiousHeadersAsC() + ? Utils::Language::C + : Utils::Language::Cxx; runImpl({CppModelManager::workingCopy(), ProjectExplorer::ProjectManager::startupProject(), diff --git a/src/plugins/cppeditor/clangdiagnosticconfigsselectionwidget.cpp b/src/plugins/cppeditor/clangdiagnosticconfigsselectionwidget.cpp index 3a3ceacad4e..8cdc803f462 100644 --- a/src/plugins/cppeditor/clangdiagnosticconfigsselectionwidget.cpp +++ b/src/plugins/cppeditor/clangdiagnosticconfigsselectionwidget.cpp @@ -90,11 +90,7 @@ void ClangDiagnosticConfigsSelectionWidget::onButtonClicked() connect(buttonsBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); connect(buttonsBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); - const bool previousEnableLowerClazyLevels = codeModelSettings()->enableLowerClazyLevels(); if (dialog.exec() == QDialog::Accepted) { - if (previousEnableLowerClazyLevels != codeModelSettings()->enableLowerClazyLevels()) - codeModelSettings()->toSettings(Core::ICore::settings()); - m_diagnosticConfigsModel = ClangDiagnosticConfigsModel(widget->configs()); m_currentConfigId = widget->currentConfig().id(); m_button->setText(widget->currentConfig().displayName()); diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index e06272084d6..2c574907017 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -71,135 +71,98 @@ static FilePath fallbackClangdFilePath() return Environment::systemEnvironment().searchInPath("clangd"); } +bool operator==(const CppEditor::CppCodeModelSettings::Data &s1, + const CppEditor::CppCodeModelSettings::Data &s2) +{ + return s1.pchUsage == s2.pchUsage + && s1.interpretAmbigiousHeadersAsC == s2.interpretAmbigiousHeadersAsC + && s1.skipIndexingBigFiles == s2.skipIndexingBigFiles + && s1.useBuiltinPreprocessor == s2.useBuiltinPreprocessor + && s1.indexerFileSizeLimitInMb == s2.indexerFileSizeLimitInMb + && s1.enableLowerClazyLevels == s2.enableLowerClazyLevels + && s1.categorizeFindReferences == s2.categorizeFindReferences + && s1.ignoreFiles == s2.ignoreFiles && s1.ignorePattern == s2.ignorePattern; +} + +Store CppCodeModelSettings::Data::toMap() const +{ + const CppCodeModelSettings::Data def; + Store store; + store.insertValueWithDefault(enableLowerClazyLevelsKey(), + enableLowerClazyLevels, + def.enableLowerClazyLevels); + store.insertValueWithDefault(pchUsageKey(), pchUsage, def.pchUsage); + store.insertValueWithDefault(interpretAmbiguousHeadersAsCHeadersKey(), + interpretAmbigiousHeadersAsC, + def.interpretAmbigiousHeadersAsC); + store.insertValueWithDefault(skipIndexingBigFilesKey(), + skipIndexingBigFiles, + def.skipIndexingBigFiles); + store.insertValueWithDefault(ignoreFilesKey(), ignoreFiles, def.ignoreFiles); + store.insertValueWithDefault(ignorePatternKey(), ignorePattern, def.ignorePattern); + store.insertValueWithDefault(useBuiltinPreprocessorKey(), + useBuiltinPreprocessor, + def.useBuiltinPreprocessor); + store.insertValueWithDefault(indexerFileSizeLimitKey(), + indexerFileSizeLimitInMb, + def.indexerFileSizeLimitInMb); + return store; +} + +void CppCodeModelSettings::Data::fromMap(const Utils::Store &store) +{ + const CppCodeModelSettings::Data def; + enableLowerClazyLevels + = store.value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels).toBool(); + pchUsage = static_cast(store.value(pchUsageKey(), def.pchUsage).toInt()); + interpretAmbigiousHeadersAsC = store + .value(interpretAmbiguousHeadersAsCHeadersKey(), + def.interpretAmbigiousHeadersAsC) + .toBool(); + skipIndexingBigFiles = store.value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles).toBool(); + ignoreFiles = store.value(ignoreFilesKey(), def.ignoreFiles).toBool(); + ignorePattern = store.value(ignorePatternKey(), def.ignorePattern).toString(); + useBuiltinPreprocessor + = store.value(useBuiltinPreprocessorKey(), def.useBuiltinPreprocessor).toBool(); + indexerFileSizeLimitInMb + = store.value(indexerFileSizeLimitKey(), def.indexerFileSizeLimitInMb).toInt(); +} + void CppCodeModelSettings::fromSettings(QtcSettings *s) { - fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); + m_data.fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); emit changed(); } void CppCodeModelSettings::toSettings(QtcSettings *s) { - storeToSettings(Constants::CPPEDITOR_SETTINGSGROUP, s, toMap()); + storeToSettings(Constants::CPPEDITOR_SETTINGSGROUP, s, m_data.toMap()); emit changed(); // TODO: Why? } -Store CppCodeModelSettings::toMap() const +void CppCodeModelSettings::setData(const Data &data) { - const CppCodeModelSettings def; - Store store; - store.insertValueWithDefault(enableLowerClazyLevelsKey(), - enableLowerClazyLevels(), - def.enableLowerClazyLevels()); - store.insertValueWithDefault(pchUsageKey(), pchUsage(), def.pchUsage()); - store.insertValueWithDefault(interpretAmbiguousHeadersAsCHeadersKey(), - interpretAmbigiousHeadersAsCHeaders(), - def.interpretAmbigiousHeadersAsCHeaders()); - store.insertValueWithDefault(skipIndexingBigFilesKey(), - skipIndexingBigFiles(), - def.skipIndexingBigFiles()); - store.insertValueWithDefault(ignoreFilesKey(), ignoreFiles(), def.ignoreFiles()); - store.insertValueWithDefault(ignorePatternKey(), ignorePattern(), def.ignorePattern()); - store.insertValueWithDefault(useBuiltinPreprocessorKey(), - useBuiltinPreprocessor(), - def.useBuiltinPreprocessor()); - store.insertValueWithDefault(indexerFileSizeLimitKey(), - indexerFileSizeLimitInMb(), - def.indexerFileSizeLimitInMb()); - return store; + if (m_data != data) { + m_data = data; + toSettings(Core::ICore::settings()); + emit changed(); + } } -void CppCodeModelSettings::fromMap(const Utils::Store &store) +void CppCodeModelSettings::setEnableLowerClazyLevels(bool enable) { - const CppCodeModelSettings def; - setEnableLowerClazyLevels( - store.value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels()).toBool()); - setPCHUsage(static_cast(store.value(pchUsageKey(), def.pchUsage()).toInt())); - setInterpretAmbigiousHeadersAsCHeaders(store - .value(interpretAmbiguousHeadersAsCHeadersKey(), - def.interpretAmbigiousHeadersAsCHeaders()) - .toBool()); - setSkipIndexingBigFiles( - store.value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles()).toBool()); - setIgnoreFiles(store.value(ignoreFilesKey(), def.ignoreFiles()).toBool()); - setIgnorePattern(store.value(ignorePatternKey(), def.ignorePattern()).toString()); - setUseBuiltinPreprocessor( - store.value(useBuiltinPreprocessorKey(), def.useBuiltinPreprocessor()).toBool()); - setIndexerFileSizeLimitInMb( - store.value(indexerFileSizeLimitKey(), def.indexerFileSizeLimitInMb()).toInt()); + Data d = data(); + d.enableLowerClazyLevels = enable; + setData(d); } -CppCodeModelSettings::PCHUsage CppCodeModelSettings::pchUsage() const +void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { - return m_pchUsage; + Data d = data(); + d.categorizeFindReferences = categorize; + setData(d); } -void CppCodeModelSettings::setPCHUsage(CppCodeModelSettings::PCHUsage pchUsage) -{ - m_pchUsage = pchUsage; -} - -bool CppCodeModelSettings::interpretAmbigiousHeadersAsCHeaders() const -{ - return m_interpretAmbigiousHeadersAsCHeaders; -} - -void CppCodeModelSettings::setInterpretAmbigiousHeadersAsCHeaders(bool yesno) -{ - m_interpretAmbigiousHeadersAsCHeaders = yesno; -} - -bool CppCodeModelSettings::skipIndexingBigFiles() const -{ - return m_skipIndexingBigFiles; -} - -void CppCodeModelSettings::setSkipIndexingBigFiles(bool yesno) -{ - m_skipIndexingBigFiles = yesno; -} - -int CppCodeModelSettings::indexerFileSizeLimitInMb() const -{ - return m_indexerFileSizeLimitInMB; -} - -void CppCodeModelSettings::setIndexerFileSizeLimitInMb(int sizeInMB) -{ - m_indexerFileSizeLimitInMB = sizeInMB; -} - -bool CppCodeModelSettings::ignoreFiles() const -{ - return m_ignoreFiles; -} - -void CppCodeModelSettings::setIgnoreFiles(bool ignoreFiles) -{ - m_ignoreFiles = ignoreFiles; -} - -QString CppCodeModelSettings::ignorePattern() const -{ - return m_ignorePattern; -} - -void CppCodeModelSettings::setIgnorePattern(const QString& ignorePattern) -{ - m_ignorePattern = ignorePattern; -} - - -bool CppCodeModelSettings::enableLowerClazyLevels() const -{ - return m_enableLowerClazyLevels; -} - -void CppCodeModelSettings::setEnableLowerClazyLevels(bool yesno) -{ - m_enableLowerClazyLevels = yesno; -} - - QString ClangdSettings::priorityToString(const IndexingPriority &priority) { switch (priority) { diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index fbca534c384..c81fbda6f02 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -34,54 +34,56 @@ public: PchUse_BuildSystem = 2 }; + class Data + { + public: + Utils::Store toMap() const; + void fromMap(const Utils::Store &store); + + friend bool operator==(const Data &s1, const Data &s2); + friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } + + PCHUsage pchUsage = PchUse_BuildSystem; + bool interpretAmbigiousHeadersAsC = false; + bool skipIndexingBigFiles = true; + bool useBuiltinPreprocessor = true; + int indexerFileSizeLimitInMb = 5; + bool enableLowerClazyLevels = true; // For UI behavior only + bool categorizeFindReferences = false; // Ephemeral! + bool ignoreFiles = false; + QString ignorePattern; + }; + CppCodeModelSettings(Utils::QtcSettings *s) { fromSettings(s); } - void toSettings(Utils::QtcSettings *s); + void setData(const Data &data); + Data data() const { return m_data; } - bool enableLowerClazyLevels() const; - void setEnableLowerClazyLevels(bool yesno); + bool enableLowerClazyLevels() const { return m_data.enableLowerClazyLevels; } + PCHUsage pchUsage() const { return m_data.pchUsage; } + bool interpretAmbigiousHeadersAsC() const { return m_data.interpretAmbigiousHeadersAsC; } + bool skipIndexingBigFiles() const { return m_data.skipIndexingBigFiles; } + bool useBuiltinPreprocessor() const { return m_data.useBuiltinPreprocessor; } + int indexerFileSizeLimitInMb() const { return m_data.indexerFileSizeLimitInMb; } + bool categorizeFindReferences() const { return m_data.categorizeFindReferences; } + bool ignoreFiles() const { return m_data.ignoreFiles; } + QString ignorePattern() const { return m_data.ignorePattern; } - PCHUsage pchUsage() const; - void setPCHUsage(PCHUsage pchUsage); + // FIXME: Doesn't belong here. + void setEnableLowerClazyLevels(bool enable); - bool interpretAmbigiousHeadersAsCHeaders() const; - void setInterpretAmbigiousHeadersAsCHeaders(bool yesno); - - bool skipIndexingBigFiles() const; - void setSkipIndexingBigFiles(bool yesno); - - bool useBuiltinPreprocessor() const { return m_useBuiltinPreprocessor; } - void setUseBuiltinPreprocessor(bool useBuiltin) { m_useBuiltinPreprocessor = useBuiltin; } - - int indexerFileSizeLimitInMb() const; - void setIndexerFileSizeLimitInMb(int sizeInMB); - - void setCategorizeFindReferences(bool categorize) { m_categorizeFindReferences = categorize; } - bool categorizeFindReferences() const { return m_categorizeFindReferences; } - - bool ignoreFiles() const; - void setIgnoreFiles(bool ignoreFiles); - QString ignorePattern() const; - void setIgnorePattern(const QString& ignorePattern); + void setCategorizeFindReferences(bool categorize); signals: void changed(); private: CppCodeModelSettings() = default; - void fromSettings(Utils::QtcSettings *s); - Utils::Store toMap() const; - void fromMap(const Utils::Store &store); - PCHUsage m_pchUsage = PchUse_BuildSystem; - bool m_interpretAmbigiousHeadersAsCHeaders = false; - bool m_skipIndexingBigFiles = true; - bool m_useBuiltinPreprocessor = true; - int m_indexerFileSizeLimitInMB = 5; - bool m_enableLowerClazyLevels = true; // For UI behavior only - bool m_categorizeFindReferences = false; // Ephemeral! - bool m_ignoreFiles = false; - QString m_ignorePattern; + void toSettings(Utils::QtcSettings *s); + void fromSettings(Utils::QtcSettings *s); + + Data m_data; }; class CPPEDITOR_EXPORT ClangdSettings : public QObject diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index b4a19ccaae6..b267b66242c 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -51,14 +51,13 @@ namespace CppEditor::Internal { class CppCodeModelSettingsWidget final : public Core::IOptionsPageWidget { public: - CppCodeModelSettingsWidget(); + CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); private: - void apply() final; + void apply() final { codeModelSettings()->setData(data()); } - bool applyGeneralWidgetsToSettings() const; + CppCodeModelSettings::Data data() const; - CppCodeModelSettings *m_settings = nullptr; QCheckBox *m_interpretAmbiguousHeadersAsCHeaders; QCheckBox *m_ignorePchCheckBox; QCheckBox *m_useBuiltinPreprocessorCheckBox; @@ -68,19 +67,18 @@ private: QPlainTextEdit *m_ignorePatternTextEdit; }; -CppCodeModelSettingsWidget::CppCodeModelSettingsWidget() - : m_settings(&cppCodeModelSettings()) +CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data) { m_interpretAmbiguousHeadersAsCHeaders = new QCheckBox(Tr::tr("Interpret ambiguous headers as C headers")); m_skipIndexingBigFilesCheckBox = new QCheckBox(Tr::tr("Do not index files greater than")); - m_skipIndexingBigFilesCheckBox->setChecked(m_settings->skipIndexingBigFiles()); + m_skipIndexingBigFilesCheckBox->setChecked(data.skipIndexingBigFiles); m_bigFilesLimitSpinBox = new QSpinBox; m_bigFilesLimitSpinBox->setSuffix(Tr::tr("MB")); m_bigFilesLimitSpinBox->setRange(1, 500); - m_bigFilesLimitSpinBox->setValue(m_settings->indexerFileSizeLimitInMb()); + m_bigFilesLimitSpinBox->setValue(data.indexerFileSizeLimitInMb); m_ignoreFilesCheckBox = new QCheckBox(Tr::tr("Ignore files")); m_ignoreFilesCheckBox->setToolTip( @@ -88,8 +86,8 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget() + Tr::tr("Ignore files that match these wildcard patterns, one wildcard per line.") + "

"); - m_ignoreFilesCheckBox->setChecked(m_settings->ignoreFiles()); - m_ignorePatternTextEdit = new QPlainTextEdit(m_settings->ignorePattern()); + m_ignoreFilesCheckBox->setChecked(data.ignoreFiles); + m_ignorePatternTextEdit = new QPlainTextEdit(data.ignorePattern); m_ignorePatternTextEdit->setToolTip(m_ignoreFilesCheckBox->toolTip()); m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); @@ -109,11 +107,9 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget() (Tr::tr("Uncheck this to invoke the actual compiler " "to show a pre-processed source file in the editor.")); - m_interpretAmbiguousHeadersAsCHeaders->setChecked( - m_settings->interpretAmbigiousHeadersAsCHeaders()); - - m_ignorePchCheckBox->setChecked(m_settings->pchUsage() == CppCodeModelSettings::PchUse_None); - m_useBuiltinPreprocessorCheckBox->setChecked(m_settings->useBuiltinPreprocessor()); + m_interpretAmbiguousHeadersAsCHeaders->setChecked(data.interpretAmbigiousHeadersAsC); + m_ignorePchCheckBox->setChecked(data.pchUsage == CppCodeModelSettings::PchUse_None); + m_useBuiltinPreprocessorCheckBox->setChecked(data.useBuiltinPreprocessor); using namespace Layouting; @@ -132,61 +128,18 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget() }.attachTo(this); } -void CppCodeModelSettingsWidget::apply() +CppCodeModelSettings::Data CppCodeModelSettingsWidget::data() const { - if (applyGeneralWidgetsToSettings()) - m_settings->toSettings(Core::ICore::settings()); -} - -bool CppCodeModelSettingsWidget::applyGeneralWidgetsToSettings() const -{ - bool settingsChanged = false; - - const bool newInterpretAmbiguousHeaderAsCHeaders - = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); - if (m_settings->interpretAmbigiousHeadersAsCHeaders() - != newInterpretAmbiguousHeaderAsCHeaders) { - m_settings->setInterpretAmbigiousHeadersAsCHeaders(newInterpretAmbiguousHeaderAsCHeaders); - settingsChanged = true; - } - - const bool newSkipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); - if (m_settings->skipIndexingBigFiles() != newSkipIndexingBigFiles) { - m_settings->setSkipIndexingBigFiles(newSkipIndexingBigFiles); - settingsChanged = true; - } - const bool newUseBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); - if (m_settings->useBuiltinPreprocessor() != newUseBuiltinPreprocessor) { - m_settings->setUseBuiltinPreprocessor(newUseBuiltinPreprocessor); - settingsChanged = true; - } - const bool ignoreFiles = m_ignoreFilesCheckBox->isChecked(); - if (m_settings->ignoreFiles() != ignoreFiles) { - m_settings->setIgnoreFiles(ignoreFiles); - settingsChanged = true; - } - const QString ignorePattern = m_ignorePatternTextEdit->toPlainText(); - if (m_settings->ignorePattern() != ignorePattern) { - m_settings->setIgnorePattern(ignorePattern); - settingsChanged = true; - } - const int newFileSizeLimit = m_bigFilesLimitSpinBox->value(); - if (m_settings->indexerFileSizeLimitInMb() != newFileSizeLimit) { - m_settings->setIndexerFileSizeLimitInMb(newFileSizeLimit); - settingsChanged = true; - } - - const bool newIgnorePch = m_ignorePchCheckBox->isChecked(); - const bool previousIgnorePch = m_settings->pchUsage() == CppCodeModelSettings::PchUse_None; - if (newIgnorePch != previousIgnorePch) { - const CppCodeModelSettings::PCHUsage pchUsage = m_ignorePchCheckBox->isChecked() - ? CppCodeModelSettings::PchUse_None - : CppCodeModelSettings::PchUse_BuildSystem; - m_settings->setPCHUsage(pchUsage); - settingsChanged = true; - } - - return settingsChanged; + CppCodeModelSettings::Data data; + data.interpretAmbigiousHeadersAsC = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); + data.skipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); + data.useBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); + data.ignoreFiles = m_ignoreFilesCheckBox->isChecked(); + data.ignorePattern = m_ignorePatternTextEdit->toPlainText(); + data.indexerFileSizeLimitInMb = m_bigFilesLimitSpinBox->value(); + data.pchUsage = m_ignorePchCheckBox->isChecked() ? CppCodeModelSettings::PchUse_None + : CppCodeModelSettings::PchUse_BuildSystem; + return data; } class CppCodeModelSettingsPage final : public Core::IOptionsPage @@ -199,7 +152,7 @@ public: setCategory(Constants::CPP_SETTINGS_CATEGORY); setDisplayCategory(Tr::tr("C++")); setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); - setWidgetCreator([] { return new CppCodeModelSettingsWidget; }); + setWidgetCreator([] { return new CppCodeModelSettingsWidget(codeModelSettings()->data()); }); } }; From e43fde322e932ceac1bba3825c29919ea04a1087 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 26 Feb 2024 15:13:28 +0100 Subject: [PATCH 0034/1060] CppEditor: Fix indentation of function call arguments ... following an argument with an array subscript operator. Fixes: QTCREATORBUG-29225 Change-Id: Iba38043d94be718efee30ce50f5b55aac4ba6ecd Reviewed-by: Christian Stenger --- src/plugins/cppeditor/cppcodeformatter.cpp | 2 +- .../cplusplus/codeformatter/tst_codeformatter.cpp | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/plugins/cppeditor/cppcodeformatter.cpp b/src/plugins/cppeditor/cppcodeformatter.cpp index 6b30e78fa6c..d09fa37d455 100644 --- a/src/plugins/cppeditor/cppcodeformatter.cpp +++ b/src/plugins/cppeditor/cppcodeformatter.cpp @@ -204,7 +204,7 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block) case T_IDENTIFIER: // '&', id, 'this' are allowed both in the capture list and subscribtion case T_AMPER: case T_THIS: break; - default: leave(); leave(); tryExpression(m_currentState.at(m_currentState.size() - 1).type == declaration_start); break; + default: tryExpression(m_currentState.at(m_currentState.size() - 2).type == declaration_start); break; // any other symbol allowed only in subscribtion operator } break; diff --git a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp index ce57e939ee5..344f6f1bef4 100644 --- a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp +++ b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp @@ -107,6 +107,7 @@ private Q_SLOTS: void shiftWithinInitializer(); void lambdaWithReturnType(); void structuredBinding(); + void subscriptOperatorInFunctionCall(); }; struct Line { @@ -2199,6 +2200,19 @@ void tst_CodeFormatter::structuredBinding() checkIndent(data); } +void tst_CodeFormatter::subscriptOperatorInFunctionCall() +{ + QList data; + data << Line("int main() {") + << Line(" func(array[0],") + << Line(" ~ 0);") + << Line(" func(array[i],") + << Line(" ~ i);") + << Line("}") + ; + checkIndent(data); +} + QTEST_GUILESS_MAIN(tst_CodeFormatter) #include "tst_codeformatter.moc" From 0d7abc019f328e54913ce65de2da4701d153540f Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 22 Feb 2024 13:40:50 +0100 Subject: [PATCH 0035/1060] ClangTools: Remove support for reading settings from ancient versions Change-Id: I643c553686ec72556fbae62fe1b8c9c9fe327787 Reviewed-by: Reviewed-by: David Schulz --- src/plugins/clangtools/clangtoolssettings.cpp | 67 +++---------------- 1 file changed, 9 insertions(+), 58 deletions(-) diff --git a/src/plugins/clangtools/clangtoolssettings.cpp b/src/plugins/clangtools/clangtoolssettings.cpp index c8494c60ee0..c53fa394b6d 100644 --- a/src/plugins/clangtools/clangtoolssettings.cpp +++ b/src/plugins/clangtools/clangtoolssettings.cpp @@ -104,76 +104,27 @@ ClangToolsSettings::ClangToolsSettings() readSettings(); } -static Store convertToMapFromVersionBefore410(QtcSettings *s) -{ - const char oldParallelJobsKey[] = "simultaneousProcesses"; - const char oldBuildBeforeAnalysisKey[] = "buildBeforeAnalysis"; - - Store map; - map.insert(diagnosticConfigIdKey, s->value(oldDiagnosticConfigIdKey)); - map.insert(parallelJobsKey, s->value(oldParallelJobsKey)); - map.insert(buildBeforeAnalysisKey, s->value(oldBuildBeforeAnalysisKey)); - - s->remove(oldDiagnosticConfigIdKey); - s->remove(oldParallelJobsKey); - s->remove(oldBuildBeforeAnalysisKey); - - return map; -} - -ClangDiagnosticConfigs importDiagnosticConfigsFromCodeModel() -{ - const ClangDiagnosticConfigs configs = ClangdSettings::instance().customDiagnosticConfigs(); - - ClangDiagnosticConfigs tidyClazyConfigs; - ClangDiagnosticConfigs clangOnlyConfigs; - std::tie(tidyClazyConfigs, clangOnlyConfigs) - = Utils::partition(configs, [](const ClangDiagnosticConfig &config) { - return !config.checks(ClangToolType::Clazy).isEmpty() - || (!config.checks(ClangToolType::Tidy).isEmpty() - && config.checks(ClangToolType::Tidy) != "-*"); - }); - return tidyClazyConfigs; -} - void ClangToolsSettings::readSettings() { - // Transfer tidy/clazy configs from code model - bool write = false; - ClangDiagnosticConfigs importedConfigs = importDiagnosticConfigsFromCodeModel(); - m_diagnosticConfigs.append(importedConfigs); - if (!importedConfigs.isEmpty()) - write = true; - AspectContainer::readSettings(); + // TODO: The remaining things should be ready for aspectification now. QtcSettings *s = Core::ICore::settings(); s->beginGroup(Constants::SETTINGS_ID); m_diagnosticConfigs.append(diagnosticConfigsFromSettings(s)); - Store map; - if (!s->value(oldDiagnosticConfigIdKey).isNull()) { - map = convertToMapFromVersionBefore410(s); - write = true; - } else { - Store defaults; - defaults.insert(diagnosticConfigIdKey, defaultDiagnosticId().toSetting()); - defaults.insert(parallelJobsKey, m_runSettings.parallelJobs()); - defaults.insert(preferConfigFileKey, m_runSettings.preferConfigFile()); - defaults.insert(buildBeforeAnalysisKey, m_runSettings.buildBeforeAnalysis()); - defaults.insert(analyzeOpenFilesKey, m_runSettings.analyzeOpenFiles()); - map = defaults; - for (Store::ConstIterator it = defaults.constBegin(); it != defaults.constEnd(); ++it) - map.insert(it.key(), s->value(it.key(), it.value())); - } - // Run settings + Store map; + map.insert(diagnosticConfigIdKey, + s->value(diagnosticConfigIdKey, defaultDiagnosticId().toSetting())); + map.insert(parallelJobsKey, s->value(parallelJobsKey, m_runSettings.parallelJobs())); + map.insert(preferConfigFileKey, s->value(preferConfigFileKey, m_runSettings.preferConfigFile())); + map.insert(buildBeforeAnalysisKey, + s->value(buildBeforeAnalysisKey, m_runSettings.buildBeforeAnalysis())); + map.insert(analyzeOpenFilesKey, s->value(analyzeOpenFilesKey, m_runSettings.analyzeOpenFiles())); m_runSettings.fromMap(map); s->endGroup(); - - if (write) - writeSettings(); } void ClangToolsSettings::writeSettings() const From fc59b375ff9638672d02abf49c437bd5c3c5ee35 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Thu, 22 Feb 2024 22:52:49 +0100 Subject: [PATCH 0036/1060] TextEditor: Move editor field outside of FormatTask struct It doesn't take part in format() processing function, so move this field outside. The format() may be called in separate thread, so, just for safety, don't keep this field there so that nobody accesses it from non-main thread. Remove the c'tor of FormatTask and use list-initialization instead. Change-Id: I54daf1461243a46bbd7f58c91ba051909b6cf280 Reviewed-by: David Schulz --- src/plugins/texteditor/formattexteditor.cpp | 22 ++++++++++----------- src/plugins/texteditor/formattexteditor.h | 16 ++------------- 2 files changed, 12 insertions(+), 26 deletions(-) diff --git a/src/plugins/texteditor/formattexteditor.cpp b/src/plugins/texteditor/formattexteditor.cpp index 14f3d4e4e78..caebeb8c235 100644 --- a/src/plugins/texteditor/formattexteditor.cpp +++ b/src/plugins/texteditor/formattexteditor.cpp @@ -256,7 +256,7 @@ static void showError(const QString &error) * Checks the state of @a task and if the formatting was successful calls updateEditorText() with * the respective members of @a task. */ -static void checkAndApplyTask(const FormatTask &task) +static void checkAndApplyTask(const QPointer &textEditor, const FormatTask &task) { if (!task.error.isEmpty()) { showError(task.error); @@ -264,15 +264,12 @@ static void checkAndApplyTask(const FormatTask &task) } if (task.formattedData.isEmpty()) { - showError(Tr::tr("Could not format file %1.").arg( - task.filePath.displayName())); + showError(Tr::tr("Could not format file %1.").arg(task.filePath.displayName())); return; } - QPlainTextEdit *textEditor = task.editor; if (!textEditor) { - showError(Tr::tr("File %1 was closed.").arg( - task.filePath.displayName())); + showError(Tr::tr("File %1 was closed.").arg(task.filePath.displayName())); return; } @@ -298,8 +295,8 @@ void formatEditor(TextEditorWidget *editor, const Command &command, int startPos const QString sd = sourceData(editor, startPos, endPos); if (sd.isEmpty()) return; - checkAndApplyTask(format(FormatTask(editor, editor->textDocument()->filePath(), sd, - command, startPos, endPos))); + checkAndApplyTask(editor, + format({editor->textDocument()->filePath(), sd, command, startPos, endPos})); } /** @@ -316,15 +313,16 @@ void formatEditorAsync(TextEditorWidget *editor, const Command &command, int sta auto watcher = new QFutureWatcher; const TextDocument *doc = editor->textDocument(); QObject::connect(doc, &TextDocument::contentsChanged, watcher, &QFutureWatcher::cancel); - QObject::connect(watcher, &QFutureWatcherBase::finished, [watcher] { + QObject::connect(watcher, &QFutureWatcherBase::finished, + [watcher, editor = QPointer(editor)] { if (watcher->isCanceled()) showError(Tr::tr("File was modified.")); else - checkAndApplyTask(watcher->result()); + checkAndApplyTask(editor, watcher->result()); watcher->deleteLater(); }); - watcher->setFuture(Utils::asyncRun(&format, FormatTask(editor, doc->filePath(), sd, - command, startPos, endPos))); + watcher->setFuture( + Utils::asyncRun(&format, FormatTask{doc->filePath(), sd, command, startPos, endPos})); } } // namespace TextEditor diff --git a/src/plugins/texteditor/formattexteditor.h b/src/plugins/texteditor/formattexteditor.h index e1c58cdf94f..fc66b874598 100644 --- a/src/plugins/texteditor/formattexteditor.h +++ b/src/plugins/texteditor/formattexteditor.h @@ -10,7 +10,6 @@ #include #include -#include namespace TextEditor { @@ -19,24 +18,13 @@ class TextEditorWidget; class TEXTEDITOR_EXPORT FormatTask { public: - FormatTask(QPlainTextEdit *_editor, const Utils::FilePath &_filePath, const QString &_sourceData, - const Command &_command, int _startPos = -1, int _endPos = 0) : - editor(_editor), - filePath(_filePath), - sourceData(_sourceData), - command(_command), - startPos(_startPos), - endPos(_endPos) - {} - - QPointer editor; Utils::FilePath filePath; QString sourceData; TextEditor::Command command; int startPos = -1; int endPos = 0; - QString formattedData; - QString error; + QString formattedData = {}; + QString error = {}; }; TEXTEDITOR_EXPORT void formatCurrentFile(const TextEditor::Command &command, int startPos = -1, int endPos = 0); From 69a0f1654710ba9dc708c968c7312b48038774dd Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Thu, 22 Feb 2024 23:01:06 +0100 Subject: [PATCH 0037/1060] TextEditor: Hide FormatTask in cpp file Unexport it. Change-Id: Ib2e73486e31d115a3e960c7bb4420014172313a7 Reviewed-by: David Schulz --- src/plugins/texteditor/formattexteditor.cpp | 12 ++++++++++++ src/plugins/texteditor/formattexteditor.h | 12 ------------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/plugins/texteditor/formattexteditor.cpp b/src/plugins/texteditor/formattexteditor.cpp index caebeb8c235..d4d1d616367 100644 --- a/src/plugins/texteditor/formattexteditor.cpp +++ b/src/plugins/texteditor/formattexteditor.cpp @@ -27,6 +27,18 @@ using namespace std::chrono_literals; namespace TextEditor { +class FormatTask +{ +public: + Utils::FilePath filePath; + QString sourceData; + TextEditor::Command command; + int startPos = -1; + int endPos = 0; + QString formattedData = {}; + QString error = {}; +}; + void formatCurrentFile(const Command &command, int startPos, int endPos) { if (TextEditorWidget *editor = TextEditorWidget::currentTextEditorWidget()) diff --git a/src/plugins/texteditor/formattexteditor.h b/src/plugins/texteditor/formattexteditor.h index fc66b874598..929763ecba8 100644 --- a/src/plugins/texteditor/formattexteditor.h +++ b/src/plugins/texteditor/formattexteditor.h @@ -15,18 +15,6 @@ namespace TextEditor { class TextEditorWidget; -class TEXTEDITOR_EXPORT FormatTask -{ -public: - Utils::FilePath filePath; - QString sourceData; - TextEditor::Command command; - int startPos = -1; - int endPos = 0; - QString formattedData = {}; - QString error = {}; -}; - TEXTEDITOR_EXPORT void formatCurrentFile(const TextEditor::Command &command, int startPos = -1, int endPos = 0); TEXTEDITOR_EXPORT void formatEditor(TextEditorWidget *editor, const TextEditor::Command &command, int startPos = -1, int endPos = 0); From 5af531cd39067366cea627e3db1a0b83d7172873 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Tue, 27 Feb 2024 16:08:45 +0100 Subject: [PATCH 0038/1060] Utils: Fix build with MSVC with C++20 Rename process.h back to qtcprocess.h MSVC's "threads" standard header includes , and that ends up including our process.h from Utils. There already was a hacky workaround in place for a similar issue with MINGW, but that doesn't work with MSVC because that doesn't have Simply use a name that doesn't conflict. Change-Id: I1159cd2096b4f2dbc4a1728d0131dd6edd30ebd3 Reviewed-by: Qt CI Bot Reviewed-by: Reviewed-by: hjk --- src/libs/extensionsystem/pluginmanager.cpp | 2 +- src/libs/qmljs/qmljsplugindumper.cpp | 2 +- src/libs/utils/CMakeLists.txt | 2 +- src/libs/utils/buildablehelperlibrary.cpp | 2 +- src/libs/utils/clangutils.cpp | 2 +- src/libs/utils/datafromprocess.h | 2 +- src/libs/utils/devicefileaccess.cpp | 2 +- src/libs/utils/deviceshell.cpp | 2 +- src/libs/utils/externalterminalprocessimpl.cpp | 2 +- src/libs/utils/filestreamer.cpp | 2 +- src/libs/utils/pathchooser.cpp | 2 +- src/libs/utils/processinfo.cpp | 2 +- src/libs/utils/{process.cpp => qtcprocess.cpp} | 4 ++-- src/libs/utils/{process.h => qtcprocess.h} | 8 +------- src/libs/utils/terminalhooks.cpp | 2 +- src/libs/utils/unarchiver.h | 2 +- src/libs/utils/utils.qbs | 4 ++-- src/plugins/android/androidavdmanager.cpp | 2 +- src/plugins/android/androidbuildapkstep.cpp | 2 +- src/plugins/android/androidconfigurations.cpp | 2 +- src/plugins/android/androidcreatekeystorecertificate.cpp | 2 +- src/plugins/android/androiddebugsupport.cpp | 2 +- src/plugins/android/androiddeployqtstep.cpp | 2 +- src/plugins/android/androiddevice.cpp | 2 +- src/plugins/android/androidmanager.cpp | 2 +- src/plugins/android/androidpackageinstallationstep.cpp | 2 +- src/plugins/android/androidqmlpreviewworker.cpp | 2 +- src/plugins/android/androidrunconfiguration.cpp | 2 +- src/plugins/android/androidrunnerworker.cpp | 2 +- src/plugins/android/androidsdkmanager.cpp | 2 +- src/plugins/android/androidsettingswidget.cpp | 2 +- src/plugins/android/androidsignaloperation.cpp | 2 +- src/plugins/autotest/boost/boosttestoutputreader.cpp | 2 +- src/plugins/autotest/gtest/gtestoutputreader.cpp | 2 +- src/plugins/autotest/testoutputreader.cpp | 2 +- src/plugins/autotest/testrunner.cpp | 2 +- src/plugins/autotoolsprojectmanager/autogenstep.cpp | 2 +- src/plugins/autotoolsprojectmanager/autoreconfstep.cpp | 2 +- src/plugins/autotoolsprojectmanager/configurestep.cpp | 2 +- src/plugins/autotoolsprojectmanager/makefileparser.cpp | 2 +- src/plugins/baremetal/baremetaldebugsupport.cpp | 2 +- .../baremetal/debugservers/gdb/jlinkgdbserverprovider.cpp | 2 +- .../debugservers/gdb/openocdgdbserverprovider.cpp | 2 +- .../baremetal/debugservers/uvsc/uvscserverprovider.h | 2 +- src/plugins/baremetal/iarewtoolchain.cpp | 2 +- src/plugins/baremetal/keiltoolchain.cpp | 2 +- src/plugins/baremetal/sdcctoolchain.cpp | 2 +- src/plugins/beautifier/artisticstyle/artisticstyle.cpp | 2 +- src/plugins/beautifier/beautifiertool.cpp | 2 +- src/plugins/beautifier/uncrustify/uncrustify.cpp | 2 +- src/plugins/boot2qt/device-detection/qdbwatcher.cpp | 2 +- src/plugins/boot2qt/qdbdevice.cpp | 2 +- src/plugins/boot2qt/qdbdevicedebugsupport.cpp | 2 +- src/plugins/boot2qt/qdbmakedefaultappstep.cpp | 2 +- src/plugins/boot2qt/qdbplugin.cpp | 2 +- src/plugins/boot2qt/qdbstopapplicationstep.cpp | 2 +- src/plugins/clangtools/clangtoolrunner.cpp | 2 +- src/plugins/clangtools/clangtoolsutils.cpp | 2 +- src/plugins/clangtools/executableinfo.cpp | 2 +- src/plugins/clearcase/clearcaseplugin.cpp | 2 +- src/plugins/clearcase/clearcasesync.cpp | 2 +- src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp | 2 +- src/plugins/cmakeprojectmanager/cmakeprocess.cpp | 2 +- src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp | 2 +- src/plugins/cmakeprojectmanager/cmaketool.cpp | 2 +- src/plugins/cmakeprojectmanager/fileapidataextractor.cpp | 2 +- src/plugins/coreplugin/dialogs/externaltoolconfig.cpp | 2 +- src/plugins/coreplugin/externaltool.cpp | 2 +- src/plugins/coreplugin/fileutils.cpp | 2 +- src/plugins/coreplugin/locator/executefilter.cpp | 2 +- src/plugins/coreplugin/locator/spotlightlocatorfilter.cpp | 2 +- src/plugins/coreplugin/patchtool.cpp | 2 +- src/plugins/coreplugin/plugininstallwizard.cpp | 2 +- .../coreplugin/progressmanager/processprogress.cpp | 2 +- src/plugins/cppcheck/cppcheckrunner.h | 2 +- src/plugins/cppeditor/cppcodemodelsettings.cpp | 2 +- src/plugins/cppeditor/cppmodelmanager.cpp | 2 +- src/plugins/debugger/cdb/cdbengine.cpp | 2 +- src/plugins/debugger/cdb/cdbengine.h | 2 +- src/plugins/debugger/dap/dapclient.cpp | 2 +- src/plugins/debugger/dap/dapclient.h | 2 +- src/plugins/debugger/dap/dapengine.cpp | 2 +- src/plugins/debugger/dap/dapengine.h | 2 +- src/plugins/debugger/debuggerengine.cpp | 2 +- src/plugins/debugger/debuggeritem.cpp | 2 +- src/plugins/debugger/debuggeritemmanager.cpp | 2 +- src/plugins/debugger/debuggerruncontrol.cpp | 2 +- src/plugins/debugger/debuggersourcepathmappingwidget.cpp | 2 +- src/plugins/debugger/gdb/gdbengine.cpp | 2 +- src/plugins/debugger/gdb/gdbengine.h | 2 +- src/plugins/debugger/lldb/lldbengine.cpp | 2 +- src/plugins/debugger/lldb/lldbengine.h | 2 +- src/plugins/debugger/moduleshandler.cpp | 2 +- src/plugins/debugger/pdb/pdbengine.cpp | 2 +- src/plugins/debugger/pdb/pdbengine.h | 2 +- src/plugins/debugger/qml/qmlengine.cpp | 2 +- src/plugins/debugger/terminal.cpp | 2 +- src/plugins/docker/dockerapi.cpp | 2 +- src/plugins/docker/dockerdevice.cpp | 2 +- src/plugins/effectcomposer/effectcomposermodel.cpp | 2 +- src/plugins/fakevim/fakevimplugin.cpp | 2 +- src/plugins/fossil/fossilclient.cpp | 2 +- src/plugins/genericprojectmanager/genericproject.cpp | 2 +- src/plugins/git/branchmodel.cpp | 2 +- src/plugins/git/branchview.cpp | 2 +- src/plugins/git/changeselectiondialog.cpp | 2 +- src/plugins/git/gerrit/gerritmodel.cpp | 2 +- src/plugins/git/gerrit/gerritplugin.cpp | 2 +- src/plugins/git/gitclient.cpp | 2 +- src/plugins/git/gitgrep.cpp | 2 +- src/plugins/git/mergetool.h | 2 +- src/plugins/gitlab/gitlabclonedialog.cpp | 2 +- src/plugins/gitlab/queryrunner.h | 2 +- src/plugins/haskell/haskellmanager.cpp | 2 +- src/plugins/incredibuild/cmakecommandbuilder.cpp | 2 +- src/plugins/ios/iosbuildstep.cpp | 2 +- src/plugins/ios/iosconfigurations.cpp | 2 +- src/plugins/ios/iosdeploystep.cpp | 2 +- src/plugins/ios/iosdevice.cpp | 2 +- src/plugins/ios/iosdsymbuildstep.cpp | 2 +- src/plugins/ios/iosprobe.cpp | 2 +- src/plugins/ios/iosrunconfiguration.cpp | 2 +- src/plugins/ios/iosrunner.cpp | 2 +- src/plugins/ios/iossimulator.cpp | 2 +- src/plugins/ios/iostoolhandler.cpp | 2 +- src/plugins/ios/simulatorcontrol.cpp | 2 +- src/plugins/languageclient/client.cpp | 2 +- src/plugins/languageclient/languageclientinterface.h | 2 +- src/plugins/languageclient/languageclientutils.cpp | 2 +- src/plugins/mcusupport/mcuqmlprojectnode.h | 2 +- src/plugins/mcusupport/mcusupportversiondetection.cpp | 2 +- src/plugins/mercurial/mercurialclient.cpp | 2 +- .../mesonprojectmanager/mesonbuildconfiguration.cpp | 2 +- src/plugins/mesonprojectmanager/mesonwrapper.h | 2 +- src/plugins/mesonprojectmanager/toolwrapper.cpp | 2 +- src/plugins/nim/project/nimblebuildsystem.cpp | 2 +- src/plugins/nim/project/nimcompilerbuildstep.cpp | 2 +- src/plugins/nim/project/nimtoolchain.cpp | 2 +- src/plugins/nim/suggest/server.h | 2 +- src/plugins/perforce/perforcechecker.h | 2 +- src/plugins/perforce/perforceplugin.cpp | 2 +- src/plugins/perfprofiler/perfprofilerruncontrol.cpp | 2 +- src/plugins/perfprofiler/perfsettings.cpp | 2 +- src/plugins/perfprofiler/perftracepointdialog.cpp | 2 +- src/plugins/projectexplorer/abstractprocessstep.cpp | 2 +- .../customwizard/customwizardscriptgenerator.cpp | 2 +- .../projectexplorer/devicesupport/desktopdevice.cpp | 2 +- .../projectexplorer/devicesupport/devicemanager.cpp | 2 +- .../devicesupport/deviceusedportsgatherer.cpp | 2 +- .../projectexplorer/devicesupport/sshparameters.cpp | 2 +- src/plugins/projectexplorer/extracompiler.cpp | 2 +- src/plugins/projectexplorer/gcctoolchain.cpp | 2 +- src/plugins/projectexplorer/makestep.cpp | 2 +- src/plugins/projectexplorer/msvctoolchain.cpp | 2 +- src/plugins/projectexplorer/processparameters.cpp | 2 +- src/plugins/projectexplorer/projectmodels.cpp | 2 +- src/plugins/projectexplorer/runconfigurationaspects.cpp | 2 +- src/plugins/projectexplorer/runcontrol.cpp | 2 +- src/plugins/projectexplorer/targetsetuppage.cpp | 2 +- src/plugins/projectexplorer/taskfile.cpp | 2 +- src/plugins/projectexplorer/toolchainconfigwidget.cpp | 2 +- src/plugins/projectexplorer/userfileaccessor.cpp | 2 +- src/plugins/python/pipsupport.cpp | 2 +- src/plugins/python/pipsupport.h | 2 +- src/plugins/python/pyside.cpp | 2 +- src/plugins/python/pysideuicextracompiler.cpp | 2 +- src/plugins/python/pythonbuildconfiguration.cpp | 2 +- src/plugins/python/pythonkitaspect.cpp | 2 +- src/plugins/python/pythonlanguageclient.cpp | 2 +- src/plugins/python/pythonsettings.cpp | 2 +- src/plugins/python/pythonutils.cpp | 2 +- src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp | 2 +- src/plugins/qbsprojectmanager/qbsprofilemanager.cpp | 2 +- src/plugins/qbsprojectmanager/qbssession.cpp | 2 +- src/plugins/qbsprojectmanager/qbssettings.cpp | 2 +- .../qmakeprojectmanager/librarydetailscontroller.cpp | 2 +- src/plugins/qmakeprojectmanager/makefileparse.cpp | 2 +- .../qmakeprojectmanager/qmakebuildconfiguration.cpp | 2 +- src/plugins/qmakeprojectmanager/qmakemakestep.cpp | 2 +- src/plugins/qmakeprojectmanager/qmakeparsernodes.cpp | 2 +- src/plugins/qmakeprojectmanager/qmakeproject.cpp | 2 +- src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp | 2 +- src/plugins/qmakeprojectmanager/qmakestep.cpp | 2 +- .../components/componentcore/modelnodeoperations.cpp | 2 +- .../designercore/instances/nodeinstanceview.cpp | 2 +- src/plugins/qmldesigner/generateresource.cpp | 2 +- src/plugins/qmlpreview/qmlpreviewruncontrol.cpp | 2 +- src/plugins/qmlprofiler/qmlprofilerruncontrol.cpp | 2 +- src/plugins/qmlprojectmanager/qmlproject.cpp | 2 +- src/plugins/qmlprojectmanager/qmlprojectplugin.cpp | 2 +- .../qmlprojectmanager/qmlprojectrunconfiguration.cpp | 2 +- src/plugins/qnx/qnxanalyzesupport.cpp | 2 +- src/plugins/qnx/qnxdebugsupport.cpp | 2 +- src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp | 2 +- src/plugins/qnx/qnxdevice.cpp | 2 +- src/plugins/qnx/qnxdevicetester.cpp | 2 +- src/plugins/qnx/qnxutils.cpp | 2 +- src/plugins/qnx/slog2inforunner.cpp | 2 +- .../qtapplicationmanager/appmanagerinstallpackagestep.cpp | 2 +- src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp | 2 +- src/plugins/qtsupport/baseqtversion.cpp | 2 +- src/plugins/qtsupport/externaleditors.cpp | 2 +- src/plugins/qtsupport/qtsupportplugin.cpp | 2 +- src/plugins/qtsupport/qtversionmanager.cpp | 2 +- src/plugins/qtsupport/uicgenerator.cpp | 2 +- src/plugins/remotelinux/customcommanddeploystep.cpp | 2 +- src/plugins/remotelinux/filesystemaccess_test.cpp | 2 +- src/plugins/remotelinux/genericdeploystep.cpp | 2 +- src/plugins/remotelinux/genericdirectuploadstep.cpp | 2 +- src/plugins/remotelinux/linuxdevice.cpp | 2 +- src/plugins/remotelinux/linuxdevicetester.cpp | 2 +- src/plugins/remotelinux/makeinstallstep.cpp | 2 +- src/plugins/remotelinux/publickeydeploymentdialog.cpp | 2 +- src/plugins/remotelinux/remotelinuxsignaloperation.cpp | 2 +- src/plugins/remotelinux/sshkeycreationdialog.cpp | 2 +- src/plugins/remotelinux/tarpackagedeploystep.cpp | 2 +- src/plugins/screenrecorder/cropandtrim.cpp | 2 +- src/plugins/screenrecorder/export.cpp | 2 +- src/plugins/screenrecorder/ffmpegutils.cpp | 2 +- src/plugins/screenrecorder/record.cpp | 2 +- src/plugins/silversearcher/findinfilessilversearcher.cpp | 2 +- src/plugins/squish/objectsmapdocument.cpp | 2 +- src/plugins/squish/squishprocessbase.h | 2 +- src/plugins/squish/squishtools.h | 2 +- src/plugins/subversion/subversionclient.cpp | 2 +- src/plugins/terminal/shellintegration.h | 2 +- src/plugins/terminal/terminalwidget.h | 2 +- src/plugins/texteditor/basefilefind.cpp | 2 +- src/plugins/texteditor/formattexteditor.cpp | 2 +- src/plugins/updateinfo/updateinfoplugin.cpp | 2 +- src/plugins/valgrind/callgrindengine.cpp | 2 +- src/plugins/valgrind/callgrindengine.h | 2 +- src/plugins/valgrind/callgrindtool.cpp | 2 +- src/plugins/valgrind/memchecktool.cpp | 2 +- src/plugins/valgrind/valgrindmemcheckparsertest.cpp | 2 +- src/plugins/valgrind/valgrindprocess.cpp | 2 +- src/plugins/vcsbase/vcsbaseclient.cpp | 2 +- src/plugins/vcsbase/vcsbasediffeditorcontroller.cpp | 2 +- src/plugins/vcsbase/vcsbaseplugin.cpp | 2 +- src/plugins/vcsbase/vcsbasesubmiteditor.cpp | 2 +- src/plugins/vcsbase/vcscommand.cpp | 2 +- src/plugins/vcsbase/vcsoutputwindow.cpp | 2 +- src/plugins/webassembly/webassemblyemsdk.cpp | 2 +- src/plugins/webassembly/webassemblyrunconfiguration.cpp | 2 +- tests/auto/utils/commandline/tst_commandline.cpp | 2 +- tests/auto/utils/deviceshell/tst_deviceshell.cpp | 2 +- tests/auto/utils/process/processtestapp/main.cpp | 2 +- .../auto/utils/process/processtestapp/processtestapp.cpp | 2 +- tests/auto/utils/process/tst_process.cpp | 2 +- tests/manual/deviceshell/tst_deviceshell.cpp | 2 +- 250 files changed, 252 insertions(+), 258 deletions(-) rename src/libs/utils/{process.cpp => qtcprocess.cpp} (99%) rename src/libs/utils/{process.h => qtcprocess.h} (96%) diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp index d8fdc096854..b5a64e20541 100644 --- a/src/libs/extensionsystem/pluginmanager.cpp +++ b/src/libs/extensionsystem/pluginmanager.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/libs/qmljs/qmljsplugindumper.cpp b/src/libs/qmljs/qmljsplugindumper.cpp index 36f2cd802db..653fa8a7013 100644 --- a/src/libs/qmljs/qmljsplugindumper.cpp +++ b/src/libs/qmljs/qmljsplugindumper.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/libs/utils/CMakeLists.txt b/src/libs/utils/CMakeLists.txt index 7e7bb51ec5f..4db25ba7494 100644 --- a/src/libs/utils/CMakeLists.txt +++ b/src/libs/utils/CMakeLists.txt @@ -124,7 +124,6 @@ add_qtc_library(Utils port.cpp port.h portlist.cpp portlist.h predicates.h - process.cpp process.h processenums.h processhandle.cpp processhandle.h processhelper.cpp processhelper.h @@ -137,6 +136,7 @@ add_qtc_library(Utils qrcparser.cpp qrcparser.h qtcassert.cpp qtcassert.h qtcolorbutton.cpp qtcolorbutton.h + qtcprocess.cpp qtcprocess.h qtcsettings.cpp qtcsettings.h ranges.h reloadpromptutils.cpp reloadpromptutils.h diff --git a/src/libs/utils/buildablehelperlibrary.cpp b/src/libs/utils/buildablehelperlibrary.cpp index 3b54d11412b..2be40b6c9bf 100644 --- a/src/libs/utils/buildablehelperlibrary.cpp +++ b/src/libs/utils/buildablehelperlibrary.cpp @@ -4,7 +4,7 @@ #include "buildablehelperlibrary.h" #include "environment.h" #include "hostosinfo.h" -#include "process.h" +#include "qtcprocess.h" #include #include diff --git a/src/libs/utils/clangutils.cpp b/src/libs/utils/clangutils.cpp index 6cf265820e7..4c8c7d801db 100644 --- a/src/libs/utils/clangutils.cpp +++ b/src/libs/utils/clangutils.cpp @@ -4,7 +4,7 @@ #include "clangutils.h" #include "filepath.h" -#include "process.h" +#include "qtcprocess.h" #include "utilstr.h" #include diff --git a/src/libs/utils/datafromprocess.h b/src/libs/utils/datafromprocess.h index 7cd833a9114..5acb220ba4e 100644 --- a/src/libs/utils/datafromprocess.h +++ b/src/libs/utils/datafromprocess.h @@ -7,7 +7,7 @@ #include "commandline.h" #include "environment.h" #include "filepath.h" -#include "process.h" +#include "qtcprocess.h" #include #include diff --git a/src/libs/utils/devicefileaccess.cpp b/src/libs/utils/devicefileaccess.cpp index c2475853e7a..50d1f276ef1 100644 --- a/src/libs/utils/devicefileaccess.cpp +++ b/src/libs/utils/devicefileaccess.cpp @@ -13,7 +13,7 @@ #include "utilstr.h" #ifndef UTILS_STATIC_LIBRARY -#include "process.h" +#include "qtcprocess.h" #endif #include diff --git a/src/libs/utils/deviceshell.cpp b/src/libs/utils/deviceshell.cpp index abccaa1b56b..69abc5ce4a4 100644 --- a/src/libs/utils/deviceshell.cpp +++ b/src/libs/utils/deviceshell.cpp @@ -3,7 +3,7 @@ #include "deviceshell.h" -#include "process.h" +#include "qtcprocess.h" #include "processinterface.h" #include "qtcassert.h" #include "utilstr.h" diff --git a/src/libs/utils/externalterminalprocessimpl.cpp b/src/libs/utils/externalterminalprocessimpl.cpp index ca178d7bf9c..41b7259b8f5 100644 --- a/src/libs/utils/externalterminalprocessimpl.cpp +++ b/src/libs/utils/externalterminalprocessimpl.cpp @@ -4,7 +4,7 @@ #include "externalterminalprocessimpl.h" #include "algorithm.h" -#include "process.h" +#include "qtcprocess.h" #include "terminalcommand.h" #include "utilstr.h" diff --git a/src/libs/utils/filestreamer.cpp b/src/libs/utils/filestreamer.cpp index 2fd40079242..663f505b881 100644 --- a/src/libs/utils/filestreamer.cpp +++ b/src/libs/utils/filestreamer.cpp @@ -4,7 +4,7 @@ #include "filestreamer.h" #include "async.h" -#include "process.h" +#include "qtcprocess.h" #include #include diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp index 00b99e66719..9b2177fedb6 100644 --- a/src/libs/utils/pathchooser.cpp +++ b/src/libs/utils/pathchooser.cpp @@ -12,7 +12,7 @@ #include "hostosinfo.h" #include "macroexpander.h" #include "optionpushbutton.h" -#include "process.h" +#include "qtcprocess.h" #include "qtcassert.h" #include "utilstr.h" diff --git a/src/libs/utils/processinfo.cpp b/src/libs/utils/processinfo.cpp index 499745473ee..0717bddbe9e 100644 --- a/src/libs/utils/processinfo.cpp +++ b/src/libs/utils/processinfo.cpp @@ -4,7 +4,7 @@ #include "processinfo.h" #include "algorithm.h" -#include "process.h" +#include "qtcprocess.h" #include #include diff --git a/src/libs/utils/process.cpp b/src/libs/utils/qtcprocess.cpp similarity index 99% rename from src/libs/utils/process.cpp rename to src/libs/utils/qtcprocess.cpp index 5bf44513654..2ebc6b351d4 100644 --- a/src/libs/utils/process.cpp +++ b/src/libs/utils/qtcprocess.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "process.h" +#include "qtcprocess.h" #include "algorithm.h" #include "environment.h" @@ -2175,4 +2175,4 @@ void ProcessTaskAdapter::start() } // namespace Utils -#include "process.moc" +#include "qtcprocess.moc" diff --git a/src/libs/utils/process.h b/src/libs/utils/qtcprocess.h similarity index 96% rename from src/libs/utils/process.h rename to src/libs/utils/qtcprocess.h index 694c1a12a86..a7e00882a31 100644 --- a/src/libs/utils/process.h +++ b/src/libs/utils/qtcprocess.h @@ -1,11 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#if defined(Q_CC_MINGW) && defined(WIN_PTHREADS_H) && !defined(_INC_PROCESS) - // Arrived here via which wants to include - #include_next -#elif !defined(UTILS_PROCESS_H) -#define UTILS_PROCESS_H +#pragma once #include "utils_global.h" @@ -223,5 +219,3 @@ public: using ProcessTask = Tasking::CustomTask; } // namespace Utils - -#endif // UTILS_PROCESS_H diff --git a/src/libs/utils/terminalhooks.cpp b/src/libs/utils/terminalhooks.cpp index 52bcc056295..3e5151e6f39 100644 --- a/src/libs/utils/terminalhooks.cpp +++ b/src/libs/utils/terminalhooks.cpp @@ -5,7 +5,7 @@ #include "externalterminalprocessimpl.h" #include "filepath.h" -#include "process.h" +#include "qtcprocess.h" #include "utilstr.h" #include diff --git a/src/libs/utils/unarchiver.h b/src/libs/utils/unarchiver.h index b255cd49900..61818318bb7 100644 --- a/src/libs/utils/unarchiver.h +++ b/src/libs/utils/unarchiver.h @@ -6,7 +6,7 @@ #include "utils_global.h" #include "commandline.h" -#include "process.h" +#include "qtcprocess.h" #include diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs index 348ee3e2661..c6dc3b79435 100644 --- a/src/libs/utils/utils.qbs +++ b/src/libs/utils/utils.qbs @@ -233,8 +233,8 @@ QtcLibrary { "portlist.cpp", "portlist.h", "predicates.h", - "process.cpp", - "process.h", + "qtcprocess.cpp", + "qtcprocess.h", "processenums.h", "processhandle.cpp", "processhandle.h", diff --git a/src/plugins/android/androidavdmanager.cpp b/src/plugins/android/androidavdmanager.cpp index a939fb59102..c37daf43b89 100644 --- a/src/plugins/android/androidavdmanager.cpp +++ b/src/plugins/android/androidavdmanager.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidbuildapkstep.cpp b/src/plugins/android/androidbuildapkstep.cpp index 34c6a9b619a..dfd8f4d3cea 100644 --- a/src/plugins/android/androidbuildapkstep.cpp +++ b/src/plugins/android/androidbuildapkstep.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidconfigurations.cpp b/src/plugins/android/androidconfigurations.cpp index fae6c64bbe3..4180917d950 100644 --- a/src/plugins/android/androidconfigurations.cpp +++ b/src/plugins/android/androidconfigurations.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/android/androidcreatekeystorecertificate.cpp b/src/plugins/android/androidcreatekeystorecertificate.cpp index 7a6fd7cf593..77aed2a6ad4 100644 --- a/src/plugins/android/androidcreatekeystorecertificate.cpp +++ b/src/plugins/android/androidcreatekeystorecertificate.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androiddebugsupport.cpp b/src/plugins/android/androiddebugsupport.cpp index 2f016eb23a8..cea404ef6f2 100644 --- a/src/plugins/android/androiddebugsupport.cpp +++ b/src/plugins/android/androiddebugsupport.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androiddeployqtstep.cpp b/src/plugins/android/androiddeployqtstep.cpp index fcf5b9703ad..6e520d3721b 100644 --- a/src/plugins/android/androiddeployqtstep.cpp +++ b/src/plugins/android/androiddeployqtstep.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/android/androiddevice.cpp b/src/plugins/android/androiddevice.cpp index b3f99159243..1d87fa1ddd0 100644 --- a/src/plugins/android/androiddevice.cpp +++ b/src/plugins/android/androiddevice.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidmanager.cpp b/src/plugins/android/androidmanager.cpp index b95b6bb4dd1..3666762be6f 100644 --- a/src/plugins/android/androidmanager.cpp +++ b/src/plugins/android/androidmanager.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidpackageinstallationstep.cpp b/src/plugins/android/androidpackageinstallationstep.cpp index 0fea1e283cc..8f1d4b01d57 100644 --- a/src/plugins/android/androidpackageinstallationstep.cpp +++ b/src/plugins/android/androidpackageinstallationstep.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidqmlpreviewworker.cpp b/src/plugins/android/androidqmlpreviewworker.cpp index dceedd36734..d37986e97ff 100644 --- a/src/plugins/android/androidqmlpreviewworker.cpp +++ b/src/plugins/android/androidqmlpreviewworker.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidrunconfiguration.cpp b/src/plugins/android/androidrunconfiguration.cpp index 8a057a3faa1..323e5d45b46 100644 --- a/src/plugins/android/androidrunconfiguration.cpp +++ b/src/plugins/android/androidrunconfiguration.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidrunnerworker.cpp b/src/plugins/android/androidrunnerworker.cpp index f21928f27d8..8f64e647764 100644 --- a/src/plugins/android/androidrunnerworker.cpp +++ b/src/plugins/android/androidrunnerworker.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/android/androidsdkmanager.cpp b/src/plugins/android/androidsdkmanager.cpp index 029cfd83524..7ae9ce05aaa 100644 --- a/src/plugins/android/androidsdkmanager.cpp +++ b/src/plugins/android/androidsdkmanager.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidsettingswidget.cpp b/src/plugins/android/androidsettingswidget.cpp index ca0ff057dfb..168ae2712e6 100644 --- a/src/plugins/android/androidsettingswidget.cpp +++ b/src/plugins/android/androidsettingswidget.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/android/androidsignaloperation.cpp b/src/plugins/android/androidsignaloperation.cpp index 9b71a07a9b3..5016b2573e2 100644 --- a/src/plugins/android/androidsignaloperation.cpp +++ b/src/plugins/android/androidsignaloperation.cpp @@ -4,7 +4,7 @@ #include "androidconfigurations.h" #include "androidsignaloperation.h" -#include +#include #include using namespace Utils; diff --git a/src/plugins/autotest/boost/boosttestoutputreader.cpp b/src/plugins/autotest/boost/boosttestoutputreader.cpp index 7b58d74f528..c069de97014 100644 --- a/src/plugins/autotest/boost/boosttestoutputreader.cpp +++ b/src/plugins/autotest/boost/boosttestoutputreader.cpp @@ -9,7 +9,7 @@ #include "../autotesttr.h" #include "../testtreeitem.h" -#include +#include #include #include diff --git a/src/plugins/autotest/gtest/gtestoutputreader.cpp b/src/plugins/autotest/gtest/gtestoutputreader.cpp index b24291caeb5..c0c08196ada 100644 --- a/src/plugins/autotest/gtest/gtestoutputreader.cpp +++ b/src/plugins/autotest/gtest/gtestoutputreader.cpp @@ -8,7 +8,7 @@ #include "../autotesttr.h" #include -#include +#include #include diff --git a/src/plugins/autotest/testoutputreader.cpp b/src/plugins/autotest/testoutputreader.cpp index cef36c90e76..727feeac7d3 100644 --- a/src/plugins/autotest/testoutputreader.cpp +++ b/src/plugins/autotest/testoutputreader.cpp @@ -6,7 +6,7 @@ #include "autotesttr.h" #include "testtreeitem.h" -#include +#include #include #include diff --git a/src/plugins/autotest/testrunner.cpp b/src/plugins/autotest/testrunner.cpp index 3631459fec4..29b7898835b 100644 --- a/src/plugins/autotest/testrunner.cpp +++ b/src/plugins/autotest/testrunner.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/autotoolsprojectmanager/autogenstep.cpp b/src/plugins/autotoolsprojectmanager/autogenstep.cpp index 020a9ad96ce..f1dde9c9211 100644 --- a/src/plugins/autotoolsprojectmanager/autogenstep.cpp +++ b/src/plugins/autotoolsprojectmanager/autogenstep.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp index 810272ecad3..8ad689f1305 100644 --- a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp +++ b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp @@ -13,7 +13,7 @@ #include #include -#include +#include using namespace ProjectExplorer; using namespace Utils; diff --git a/src/plugins/autotoolsprojectmanager/configurestep.cpp b/src/plugins/autotoolsprojectmanager/configurestep.cpp index 97fdf3576e6..4303b298f72 100644 --- a/src/plugins/autotoolsprojectmanager/configurestep.cpp +++ b/src/plugins/autotoolsprojectmanager/configurestep.cpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/autotoolsprojectmanager/makefileparser.cpp b/src/plugins/autotoolsprojectmanager/makefileparser.cpp index 8a2f684f877..d4468daa8a7 100644 --- a/src/plugins/autotoolsprojectmanager/makefileparser.cpp +++ b/src/plugins/autotoolsprojectmanager/makefileparser.cpp @@ -5,7 +5,7 @@ #include "autotoolsprojectmanagertr.h" -#include +#include #include #include diff --git a/src/plugins/baremetal/baremetaldebugsupport.cpp b/src/plugins/baremetal/baremetaldebugsupport.cpp index e3d32b3d5c2..521289650fd 100644 --- a/src/plugins/baremetal/baremetaldebugsupport.cpp +++ b/src/plugins/baremetal/baremetaldebugsupport.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include using namespace Debugger; diff --git a/src/plugins/baremetal/debugservers/gdb/jlinkgdbserverprovider.cpp b/src/plugins/baremetal/debugservers/gdb/jlinkgdbserverprovider.cpp index 56495e32c6f..8d8a968c091 100644 --- a/src/plugins/baremetal/debugservers/gdb/jlinkgdbserverprovider.cpp +++ b/src/plugins/baremetal/debugservers/gdb/jlinkgdbserverprovider.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/baremetal/debugservers/gdb/openocdgdbserverprovider.cpp b/src/plugins/baremetal/debugservers/gdb/openocdgdbserverprovider.cpp index ff4ae311afd..2ee3b266d76 100644 --- a/src/plugins/baremetal/debugservers/gdb/openocdgdbserverprovider.cpp +++ b/src/plugins/baremetal/debugservers/gdb/openocdgdbserverprovider.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.h b/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.h index 2cce62f6c18..61bbe83f814 100644 --- a/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.h +++ b/src/plugins/baremetal/debugservers/uvsc/uvscserverprovider.h @@ -10,7 +10,7 @@ #include // for RunWorker -#include +#include namespace Utils { class PathChooser; } diff --git a/src/plugins/baremetal/iarewtoolchain.cpp b/src/plugins/baremetal/iarewtoolchain.cpp index 4fa7dfe2e50..ef804b0a8a2 100644 --- a/src/plugins/baremetal/iarewtoolchain.cpp +++ b/src/plugins/baremetal/iarewtoolchain.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/baremetal/keiltoolchain.cpp b/src/plugins/baremetal/keiltoolchain.cpp index 50ae98178d9..0ca7495c94c 100644 --- a/src/plugins/baremetal/keiltoolchain.cpp +++ b/src/plugins/baremetal/keiltoolchain.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/baremetal/sdcctoolchain.cpp b/src/plugins/baremetal/sdcctoolchain.cpp index 17130e861b4..971fd9f13a8 100644 --- a/src/plugins/baremetal/sdcctoolchain.cpp +++ b/src/plugins/baremetal/sdcctoolchain.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp index feb532d1471..2982ac267bc 100644 --- a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp +++ b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/beautifier/beautifiertool.cpp b/src/plugins/beautifier/beautifiertool.cpp index 72f5a726209..cfcc117667f 100644 --- a/src/plugins/beautifier/beautifiertool.cpp +++ b/src/plugins/beautifier/beautifiertool.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/beautifier/uncrustify/uncrustify.cpp b/src/plugins/beautifier/uncrustify/uncrustify.cpp index e806b9026c4..75bd5252ed9 100644 --- a/src/plugins/beautifier/uncrustify/uncrustify.cpp +++ b/src/plugins/beautifier/uncrustify/uncrustify.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/boot2qt/device-detection/qdbwatcher.cpp b/src/plugins/boot2qt/device-detection/qdbwatcher.cpp index 869b2d84fcb..8a18a3b5ac9 100644 --- a/src/plugins/boot2qt/device-detection/qdbwatcher.cpp +++ b/src/plugins/boot2qt/device-detection/qdbwatcher.cpp @@ -8,7 +8,7 @@ #include "../qdbutils.h" #include -#include +#include #include #include diff --git a/src/plugins/boot2qt/qdbdevice.cpp b/src/plugins/boot2qt/qdbdevice.cpp index 9cc4852831f..1ede480417b 100644 --- a/src/plugins/boot2qt/qdbdevice.cpp +++ b/src/plugins/boot2qt/qdbdevice.cpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/boot2qt/qdbdevicedebugsupport.cpp b/src/plugins/boot2qt/qdbdevicedebugsupport.cpp index 15373e4b4cf..87b885668e8 100644 --- a/src/plugins/boot2qt/qdbdevicedebugsupport.cpp +++ b/src/plugins/boot2qt/qdbdevicedebugsupport.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include using namespace Debugger; diff --git a/src/plugins/boot2qt/qdbmakedefaultappstep.cpp b/src/plugins/boot2qt/qdbmakedefaultappstep.cpp index 3a777ddcb81..ca15acf7d47 100644 --- a/src/plugins/boot2qt/qdbmakedefaultappstep.cpp +++ b/src/plugins/boot2qt/qdbmakedefaultappstep.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include using namespace ProjectExplorer; using namespace Tasking; diff --git a/src/plugins/boot2qt/qdbplugin.cpp b/src/plugins/boot2qt/qdbplugin.cpp index fbcd2667f6f..c0a5bb25ca8 100644 --- a/src/plugins/boot2qt/qdbplugin.cpp +++ b/src/plugins/boot2qt/qdbplugin.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include using namespace Core; using namespace ProjectExplorer; diff --git a/src/plugins/boot2qt/qdbstopapplicationstep.cpp b/src/plugins/boot2qt/qdbstopapplicationstep.cpp index ce437993f34..341691c368d 100644 --- a/src/plugins/boot2qt/qdbstopapplicationstep.cpp +++ b/src/plugins/boot2qt/qdbstopapplicationstep.cpp @@ -13,7 +13,7 @@ #include -#include +#include using namespace ProjectExplorer; using namespace Tasking; diff --git a/src/plugins/clangtools/clangtoolrunner.cpp b/src/plugins/clangtools/clangtoolrunner.cpp index bd97eac2ea0..46fdf7c2730 100644 --- a/src/plugins/clangtools/clangtoolrunner.cpp +++ b/src/plugins/clangtools/clangtoolrunner.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/clangtools/clangtoolsutils.cpp b/src/plugins/clangtools/clangtoolsutils.cpp index 029a879ce11..6a650e9c551 100644 --- a/src/plugins/clangtools/clangtoolsutils.cpp +++ b/src/plugins/clangtools/clangtoolsutils.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/clangtools/executableinfo.cpp b/src/plugins/clangtools/executableinfo.cpp index b1c5e2343d5..7cda766e7d8 100644 --- a/src/plugins/clangtools/executableinfo.cpp +++ b/src/plugins/clangtools/executableinfo.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/clearcase/clearcaseplugin.cpp b/src/plugins/clearcase/clearcaseplugin.cpp index f566b8223d4..bc4cc82958a 100644 --- a/src/plugins/clearcase/clearcaseplugin.cpp +++ b/src/plugins/clearcase/clearcaseplugin.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/clearcase/clearcasesync.cpp b/src/plugins/clearcase/clearcasesync.cpp index 71682126a67..a92ab7da7bd 100644 --- a/src/plugins/clearcase/clearcasesync.cpp +++ b/src/plugins/clearcase/clearcasesync.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp b/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp index f93f41e3e88..0ba54b60a81 100644 --- a/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp +++ b/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp @@ -47,7 +47,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/cmakeprojectmanager/cmakeprocess.cpp b/src/plugins/cmakeprojectmanager/cmakeprocess.cpp index ef120914def..40cc41d64a5 100644 --- a/src/plugins/cmakeprojectmanager/cmakeprocess.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeprocess.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp index 52ed82f8d77..8bffb72ebc9 100644 --- a/src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/cmakeprojectmanager/cmaketool.cpp b/src/plugins/cmakeprojectmanager/cmaketool.cpp index e90bc963a6f..6c06238dfdb 100644 --- a/src/plugins/cmakeprojectmanager/cmaketool.cpp +++ b/src/plugins/cmakeprojectmanager/cmaketool.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/cmakeprojectmanager/fileapidataextractor.cpp b/src/plugins/cmakeprojectmanager/fileapidataextractor.cpp index d573fcf6a68..f105a9155c7 100644 --- a/src/plugins/cmakeprojectmanager/fileapidataextractor.cpp +++ b/src/plugins/cmakeprojectmanager/fileapidataextractor.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp index 1916a3ba259..dc434547de7 100644 --- a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp +++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/coreplugin/externaltool.cpp b/src/plugins/coreplugin/externaltool.cpp index ea13e50c502..e0b60d4c550 100644 --- a/src/plugins/coreplugin/externaltool.cpp +++ b/src/plugins/coreplugin/externaltool.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/coreplugin/fileutils.cpp b/src/plugins/coreplugin/fileutils.cpp index e432543604f..5712c9c8b5b 100644 --- a/src/plugins/coreplugin/fileutils.cpp +++ b/src/plugins/coreplugin/fileutils.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/coreplugin/locator/executefilter.cpp b/src/plugins/coreplugin/locator/executefilter.cpp index a2cd1de91c0..629099207ed 100644 --- a/src/plugins/coreplugin/locator/executefilter.cpp +++ b/src/plugins/coreplugin/locator/executefilter.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/coreplugin/locator/spotlightlocatorfilter.cpp b/src/plugins/coreplugin/locator/spotlightlocatorfilter.cpp index 7ecd298a8c9..b360ad595db 100644 --- a/src/plugins/coreplugin/locator/spotlightlocatorfilter.cpp +++ b/src/plugins/coreplugin/locator/spotlightlocatorfilter.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/coreplugin/patchtool.cpp b/src/plugins/coreplugin/patchtool.cpp index c17db9ba927..fc463be49e3 100644 --- a/src/plugins/coreplugin/patchtool.cpp +++ b/src/plugins/coreplugin/patchtool.cpp @@ -9,7 +9,7 @@ #include "systemsettings.h" #include -#include +#include #include diff --git a/src/plugins/coreplugin/plugininstallwizard.cpp b/src/plugins/coreplugin/plugininstallwizard.cpp index 55d77496744..df47cfb0705 100644 --- a/src/plugins/coreplugin/plugininstallwizard.cpp +++ b/src/plugins/coreplugin/plugininstallwizard.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/coreplugin/progressmanager/processprogress.cpp b/src/plugins/coreplugin/progressmanager/processprogress.cpp index e9348fce41d..e3769f54ca9 100644 --- a/src/plugins/coreplugin/progressmanager/processprogress.cpp +++ b/src/plugins/coreplugin/progressmanager/processprogress.cpp @@ -6,7 +6,7 @@ #include "progressmanager.h" #include "../coreplugintr.h" -#include +#include #include #include diff --git a/src/plugins/cppcheck/cppcheckrunner.h b/src/plugins/cppcheck/cppcheckrunner.h index 686a6c9eb97..0ec49aceb54 100644 --- a/src/plugins/cppcheck/cppcheckrunner.h +++ b/src/plugins/cppcheck/cppcheckrunner.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include #include diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 2c574907017..c767bc64260 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index a6e62518980..98cd232326a 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -66,7 +66,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/cdb/cdbengine.cpp b/src/plugins/debugger/cdb/cdbengine.cpp index 7a428c6a857..48f6c8290c7 100644 --- a/src/plugins/debugger/cdb/cdbengine.cpp +++ b/src/plugins/debugger/cdb/cdbengine.cpp @@ -43,7 +43,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/cdb/cdbengine.h b/src/plugins/debugger/cdb/cdbengine.h index 1cf499085e1..6d40bce2ffb 100644 --- a/src/plugins/debugger/cdb/cdbengine.h +++ b/src/plugins/debugger/cdb/cdbengine.h @@ -10,7 +10,7 @@ #include -#include +#include #include diff --git a/src/plugins/debugger/dap/dapclient.cpp b/src/plugins/debugger/dap/dapclient.cpp index 327d62da7a8..00fe60da022 100644 --- a/src/plugins/debugger/dap/dapclient.cpp +++ b/src/plugins/debugger/dap/dapclient.cpp @@ -4,7 +4,7 @@ #include "dapclient.h" #include "qjsonarray.h" -#include +#include #include #include diff --git a/src/plugins/debugger/dap/dapclient.h b/src/plugins/debugger/dap/dapclient.h index 887b32eebb7..92acb0ddb1a 100644 --- a/src/plugins/debugger/dap/dapclient.h +++ b/src/plugins/debugger/dap/dapclient.h @@ -5,7 +5,7 @@ #include -#include +#include #include diff --git a/src/plugins/debugger/dap/dapengine.cpp b/src/plugins/debugger/dap/dapengine.cpp index 7f4f515e80c..d2f94b9feeb 100644 --- a/src/plugins/debugger/dap/dapengine.cpp +++ b/src/plugins/debugger/dap/dapengine.cpp @@ -31,7 +31,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/dap/dapengine.h b/src/plugins/debugger/dap/dapengine.h index 19edd255982..b5b72eec07e 100644 --- a/src/plugins/debugger/dap/dapengine.h +++ b/src/plugins/debugger/dap/dapengine.h @@ -5,7 +5,7 @@ #include -#include +#include #include #include diff --git a/src/plugins/debugger/debuggerengine.cpp b/src/plugins/debugger/debuggerengine.cpp index b2224ac32b8..3c290c76dd8 100644 --- a/src/plugins/debugger/debuggerengine.cpp +++ b/src/plugins/debugger/debuggerengine.cpp @@ -54,7 +54,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/debuggeritem.cpp b/src/plugins/debugger/debuggeritem.cpp index 591b4bd38bc..c5b1bc7f6b6 100644 --- a/src/plugins/debugger/debuggeritem.cpp +++ b/src/plugins/debugger/debuggeritem.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/debuggeritemmanager.cpp b/src/plugins/debugger/debuggeritemmanager.cpp index d9926ed59b1..0aa3b2e7692 100644 --- a/src/plugins/debugger/debuggeritemmanager.cpp +++ b/src/plugins/debugger/debuggeritemmanager.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/debuggerruncontrol.cpp b/src/plugins/debugger/debuggerruncontrol.cpp index 80827a7228b..a46d34ccda1 100644 --- a/src/plugins/debugger/debuggerruncontrol.cpp +++ b/src/plugins/debugger/debuggerruncontrol.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/debuggersourcepathmappingwidget.cpp b/src/plugins/debugger/debuggersourcepathmappingwidget.cpp index 1cb7c6402cd..be983cf584c 100644 --- a/src/plugins/debugger/debuggersourcepathmappingwidget.cpp +++ b/src/plugins/debugger/debuggersourcepathmappingwidget.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/gdb/gdbengine.cpp b/src/plugins/debugger/gdb/gdbengine.cpp index e89c96624ef..70766eafca3 100644 --- a/src/plugins/debugger/gdb/gdbengine.cpp +++ b/src/plugins/debugger/gdb/gdbengine.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/debugger/gdb/gdbengine.h b/src/plugins/debugger/gdb/gdbengine.h index c7efe0cbaf6..f002f8c33f9 100644 --- a/src/plugins/debugger/gdb/gdbengine.h +++ b/src/plugins/debugger/gdb/gdbengine.h @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/lldb/lldbengine.cpp b/src/plugins/debugger/lldb/lldbengine.cpp index 1bb409bf948..171df7625f8 100644 --- a/src/plugins/debugger/lldb/lldbengine.cpp +++ b/src/plugins/debugger/lldb/lldbengine.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/lldb/lldbengine.h b/src/plugins/debugger/lldb/lldbengine.h index 57cbd1e7c75..faf2cc3f6fb 100644 --- a/src/plugins/debugger/lldb/lldbengine.h +++ b/src/plugins/debugger/lldb/lldbengine.h @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/moduleshandler.cpp b/src/plugins/debugger/moduleshandler.cpp index 9072d02463d..3d72f704576 100644 --- a/src/plugins/debugger/moduleshandler.cpp +++ b/src/plugins/debugger/moduleshandler.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/pdb/pdbengine.cpp b/src/plugins/debugger/pdb/pdbengine.cpp index 96a06c7b810..e0bfa126f5a 100644 --- a/src/plugins/debugger/pdb/pdbengine.cpp +++ b/src/plugins/debugger/pdb/pdbengine.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/pdb/pdbengine.h b/src/plugins/debugger/pdb/pdbengine.h index 1e365b36a7f..49dceb24417 100644 --- a/src/plugins/debugger/pdb/pdbengine.h +++ b/src/plugins/debugger/pdb/pdbengine.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include diff --git a/src/plugins/debugger/qml/qmlengine.cpp b/src/plugins/debugger/qml/qmlengine.cpp index 2ffe5bf313a..27624f61dd3 100644 --- a/src/plugins/debugger/qml/qmlengine.cpp +++ b/src/plugins/debugger/qml/qmlengine.cpp @@ -38,7 +38,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/debugger/terminal.cpp b/src/plugins/debugger/terminal.cpp index 54969c5281d..3ca2b004c20 100644 --- a/src/plugins/debugger/terminal.cpp +++ b/src/plugins/debugger/terminal.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/docker/dockerapi.cpp b/src/plugins/docker/dockerapi.cpp index 900e5bb18b2..537b6c66f38 100644 --- a/src/plugins/docker/dockerapi.cpp +++ b/src/plugins/docker/dockerapi.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/docker/dockerdevice.cpp b/src/plugins/docker/dockerdevice.cpp index 68cdee29d03..69098b732db 100644 --- a/src/plugins/docker/dockerdevice.cpp +++ b/src/plugins/docker/dockerdevice.cpp @@ -46,7 +46,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/effectcomposer/effectcomposermodel.cpp b/src/plugins/effectcomposer/effectcomposermodel.cpp index 3f376d0633a..7b1a51f6ec0 100644 --- a/src/plugins/effectcomposer/effectcomposermodel.cpp +++ b/src/plugins/effectcomposer/effectcomposermodel.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/fakevim/fakevimplugin.cpp b/src/plugins/fakevim/fakevimplugin.cpp index 07b5ec3b740..7a7554da9ea 100644 --- a/src/plugins/fakevim/fakevimplugin.cpp +++ b/src/plugins/fakevim/fakevimplugin.cpp @@ -51,7 +51,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/fossil/fossilclient.cpp b/src/plugins/fossil/fossilclient.cpp index d24935595a6..662785930d4 100644 --- a/src/plugins/fossil/fossilclient.cpp +++ b/src/plugins/fossil/fossilclient.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/genericprojectmanager/genericproject.cpp b/src/plugins/genericprojectmanager/genericproject.cpp index b201b2e1fe1..17af30f9ea1 100644 --- a/src/plugins/genericprojectmanager/genericproject.cpp +++ b/src/plugins/genericprojectmanager/genericproject.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/git/branchmodel.cpp b/src/plugins/git/branchmodel.cpp index 99e6e010057..aca355f2cb3 100644 --- a/src/plugins/git/branchmodel.cpp +++ b/src/plugins/git/branchmodel.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/git/branchview.cpp b/src/plugins/git/branchview.cpp index c99789a100a..555db9b01be 100644 --- a/src/plugins/git/branchview.cpp +++ b/src/plugins/git/branchview.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/git/changeselectiondialog.cpp b/src/plugins/git/changeselectiondialog.cpp index 12cc91eddb3..24daa938297 100644 --- a/src/plugins/git/changeselectiondialog.cpp +++ b/src/plugins/git/changeselectiondialog.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/git/gerrit/gerritmodel.cpp b/src/plugins/git/gerrit/gerritmodel.cpp index 8af786ac5e5..f0c3d0cadf5 100644 --- a/src/plugins/git/gerrit/gerritmodel.cpp +++ b/src/plugins/git/gerrit/gerritmodel.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/git/gerrit/gerritplugin.cpp b/src/plugins/git/gerrit/gerritplugin.cpp index 3ef90358b9b..749084c20a9 100644 --- a/src/plugins/git/gerrit/gerritplugin.cpp +++ b/src/plugins/git/gerrit/gerritplugin.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp index 9e2144c3217..9d4d133ee4a 100644 --- a/src/plugins/git/gitclient.cpp +++ b/src/plugins/git/gitclient.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/git/gitgrep.cpp b/src/plugins/git/gitgrep.cpp index 5675fe0f484..73feffd68f8 100644 --- a/src/plugins/git/gitgrep.cpp +++ b/src/plugins/git/gitgrep.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/git/mergetool.h b/src/plugins/git/mergetool.h index 727f9a85df0..1fd32e3a4fe 100644 --- a/src/plugins/git/mergetool.h +++ b/src/plugins/git/mergetool.h @@ -3,7 +3,7 @@ #pragma once -#include +#include #include #include diff --git a/src/plugins/gitlab/gitlabclonedialog.cpp b/src/plugins/gitlab/gitlabclonedialog.cpp index abd442de088..ae5390e941b 100644 --- a/src/plugins/gitlab/gitlabclonedialog.cpp +++ b/src/plugins/gitlab/gitlabclonedialog.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/gitlab/queryrunner.h b/src/plugins/gitlab/queryrunner.h index 08afc56e1b6..bdb5e06034a 100644 --- a/src/plugins/gitlab/queryrunner.h +++ b/src/plugins/gitlab/queryrunner.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include diff --git a/src/plugins/haskell/haskellmanager.cpp b/src/plugins/haskell/haskellmanager.cpp index b57b4177ffb..e62fa04bb23 100644 --- a/src/plugins/haskell/haskellmanager.cpp +++ b/src/plugins/haskell/haskellmanager.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/incredibuild/cmakecommandbuilder.cpp b/src/plugins/incredibuild/cmakecommandbuilder.cpp index 2f0dd751ae9..8732601cbc4 100644 --- a/src/plugins/incredibuild/cmakecommandbuilder.cpp +++ b/src/plugins/incredibuild/cmakecommandbuilder.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include // Compile-time only diff --git a/src/plugins/ios/iosbuildstep.cpp b/src/plugins/ios/iosbuildstep.cpp index 8edfb3dbc2b..c9d396ddd46 100644 --- a/src/plugins/ios/iosbuildstep.cpp +++ b/src/plugins/ios/iosbuildstep.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/ios/iosconfigurations.cpp b/src/plugins/ios/iosconfigurations.cpp index 8e748bfd6ef..b29a73c1f13 100644 --- a/src/plugins/ios/iosconfigurations.cpp +++ b/src/plugins/ios/iosconfigurations.cpp @@ -34,7 +34,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/ios/iosdeploystep.cpp b/src/plugins/ios/iosdeploystep.cpp index 4d0117f627d..596dc84d6bb 100644 --- a/src/plugins/ios/iosdeploystep.cpp +++ b/src/plugins/ios/iosdeploystep.cpp @@ -21,7 +21,7 @@ #include -#include +#include #include #include diff --git a/src/plugins/ios/iosdevice.cpp b/src/plugins/ios/iosdevice.cpp index a99f9a338d7..e81c263672b 100644 --- a/src/plugins/ios/iosdevice.cpp +++ b/src/plugins/ios/iosdevice.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/ios/iosdsymbuildstep.cpp b/src/plugins/ios/iosdsymbuildstep.cpp index 0c07ff4182d..c0aa4a06eea 100644 --- a/src/plugins/ios/iosdsymbuildstep.cpp +++ b/src/plugins/ios/iosdsymbuildstep.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/ios/iosprobe.cpp b/src/plugins/ios/iosprobe.cpp index e934ea01f91..883263ae723 100644 --- a/src/plugins/ios/iosprobe.cpp +++ b/src/plugins/ios/iosprobe.cpp @@ -4,7 +4,7 @@ #include "iosprobe.h" #include -#include +#include #include #include diff --git a/src/plugins/ios/iosrunconfiguration.cpp b/src/plugins/ios/iosrunconfiguration.cpp index 6f5384cc9b6..676fb68724a 100644 --- a/src/plugins/ios/iosrunconfiguration.cpp +++ b/src/plugins/ios/iosrunconfiguration.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/ios/iosrunner.cpp b/src/plugins/ios/iosrunner.cpp index cf8c5b70e26..ff3d10f4915 100644 --- a/src/plugins/ios/iosrunner.cpp +++ b/src/plugins/ios/iosrunner.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/ios/iossimulator.cpp b/src/plugins/ios/iossimulator.cpp index e030fe911e0..ed9a5abf66a 100644 --- a/src/plugins/ios/iossimulator.cpp +++ b/src/plugins/ios/iossimulator.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/ios/iostoolhandler.cpp b/src/plugins/ios/iostoolhandler.cpp index 811404b2da8..2f3fe4f288d 100644 --- a/src/plugins/ios/iostoolhandler.cpp +++ b/src/plugins/ios/iostoolhandler.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/ios/simulatorcontrol.cpp b/src/plugins/ios/simulatorcontrol.cpp index f6968107609..4def4c0e471 100644 --- a/src/plugins/ios/simulatorcontrol.cpp +++ b/src/plugins/ios/simulatorcontrol.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include #ifdef Q_OS_MAC diff --git a/src/plugins/languageclient/client.cpp b/src/plugins/languageclient/client.cpp index 7095c450481..12cd46c4016 100644 --- a/src/plugins/languageclient/client.cpp +++ b/src/plugins/languageclient/client.cpp @@ -54,7 +54,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/languageclient/languageclientinterface.h b/src/plugins/languageclient/languageclientinterface.h index a6dee5e4eeb..1a9d56bfa94 100644 --- a/src/plugins/languageclient/languageclientinterface.h +++ b/src/plugins/languageclient/languageclientinterface.h @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/languageclient/languageclientutils.cpp b/src/plugins/languageclient/languageclientutils.cpp index 8b9962b6c9b..0428fd6a844 100644 --- a/src/plugins/languageclient/languageclientutils.cpp +++ b/src/plugins/languageclient/languageclientutils.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/mcusupport/mcuqmlprojectnode.h b/src/plugins/mcusupport/mcuqmlprojectnode.h index bf40a696f6b..2a06e5cde55 100644 --- a/src/plugins/mcusupport/mcuqmlprojectnode.h +++ b/src/plugins/mcusupport/mcuqmlprojectnode.h @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/mcusupport/mcusupportversiondetection.cpp b/src/plugins/mcusupport/mcusupportversiondetection.cpp index 56fe961569c..79c12cc9b3f 100644 --- a/src/plugins/mcusupport/mcusupportversiondetection.cpp +++ b/src/plugins/mcusupport/mcusupportversiondetection.cpp @@ -4,7 +4,7 @@ #include "mcusupportversiondetection.h" #include "mcuhelpers.h" -#include +#include #include #include diff --git a/src/plugins/mercurial/mercurialclient.cpp b/src/plugins/mercurial/mercurialclient.cpp index fd568c9741f..6140706d001 100644 --- a/src/plugins/mercurial/mercurialclient.cpp +++ b/src/plugins/mercurial/mercurialclient.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/mesonprojectmanager/mesonbuildconfiguration.cpp b/src/plugins/mesonprojectmanager/mesonbuildconfiguration.cpp index 93ce63ad564..38d525502cd 100644 --- a/src/plugins/mesonprojectmanager/mesonbuildconfiguration.cpp +++ b/src/plugins/mesonprojectmanager/mesonbuildconfiguration.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/mesonprojectmanager/mesonwrapper.h b/src/plugins/mesonprojectmanager/mesonwrapper.h index 9b2e2bdbeb1..c38927fc9f2 100644 --- a/src/plugins/mesonprojectmanager/mesonwrapper.h +++ b/src/plugins/mesonprojectmanager/mesonwrapper.h @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/mesonprojectmanager/toolwrapper.cpp b/src/plugins/mesonprojectmanager/toolwrapper.cpp index 632465c219e..c0da501ec4b 100644 --- a/src/plugins/mesonprojectmanager/toolwrapper.cpp +++ b/src/plugins/mesonprojectmanager/toolwrapper.cpp @@ -3,7 +3,7 @@ #include "toolwrapper.h" -#include +#include #include diff --git a/src/plugins/nim/project/nimblebuildsystem.cpp b/src/plugins/nim/project/nimblebuildsystem.cpp index baed02b5254..91f4eb2f202 100644 --- a/src/plugins/nim/project/nimblebuildsystem.cpp +++ b/src/plugins/nim/project/nimblebuildsystem.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include using namespace ProjectExplorer; diff --git a/src/plugins/nim/project/nimcompilerbuildstep.cpp b/src/plugins/nim/project/nimcompilerbuildstep.cpp index af730b4c854..aaf6ff42969 100644 --- a/src/plugins/nim/project/nimcompilerbuildstep.cpp +++ b/src/plugins/nim/project/nimcompilerbuildstep.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/nim/project/nimtoolchain.cpp b/src/plugins/nim/project/nimtoolchain.cpp index 61362314d73..80036592644 100644 --- a/src/plugins/nim/project/nimtoolchain.cpp +++ b/src/plugins/nim/project/nimtoolchain.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/nim/suggest/server.h b/src/plugins/nim/suggest/server.h index 73e28096e29..15fd2b04ad0 100644 --- a/src/plugins/nim/suggest/server.h +++ b/src/plugins/nim/suggest/server.h @@ -3,7 +3,7 @@ #pragma once -#include +#include namespace Nim::Suggest { diff --git a/src/plugins/perforce/perforcechecker.h b/src/plugins/perforce/perforcechecker.h index d0f608de705..5f7d2b16739 100644 --- a/src/plugins/perforce/perforcechecker.h +++ b/src/plugins/perforce/perforcechecker.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include namespace Perforce::Internal { diff --git a/src/plugins/perforce/perforceplugin.cpp b/src/plugins/perforce/perforceplugin.cpp index 7e8dca82656..a9c14748ea9 100644 --- a/src/plugins/perforce/perforceplugin.cpp +++ b/src/plugins/perforce/perforceplugin.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/perfprofiler/perfprofilerruncontrol.cpp b/src/plugins/perfprofiler/perfprofilerruncontrol.cpp index 797fb4c2ade..adf8bbed20b 100644 --- a/src/plugins/perfprofiler/perfprofilerruncontrol.cpp +++ b/src/plugins/perfprofiler/perfprofilerruncontrol.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/perfprofiler/perfsettings.cpp b/src/plugins/perfprofiler/perfsettings.cpp index d5f3ac88ca6..5bd9e802e17 100644 --- a/src/plugins/perfprofiler/perfsettings.cpp +++ b/src/plugins/perfprofiler/perfsettings.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/perfprofiler/perftracepointdialog.cpp b/src/plugins/perfprofiler/perftracepointdialog.cpp index d5cb2e16e3d..d726aa7d867 100644 --- a/src/plugins/perfprofiler/perftracepointdialog.cpp +++ b/src/plugins/perfprofiler/perftracepointdialog.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/abstractprocessstep.cpp b/src/plugins/projectexplorer/abstractprocessstep.cpp index 547599bc9d6..5cfb66e8114 100644 --- a/src/plugins/projectexplorer/abstractprocessstep.cpp +++ b/src/plugins/projectexplorer/abstractprocessstep.cpp @@ -9,7 +9,7 @@ #include "projectexplorertr.h" #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp b/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp index fa1f455af4a..686c766838c 100644 --- a/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp +++ b/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp b/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp index 08880aff3b7..2dae1a9b685 100644 --- a/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp +++ b/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp index c8b95084de8..015b215fef5 100644 --- a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp +++ b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp index 5312026f735..920d7f69c55 100644 --- a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp +++ b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/devicesupport/sshparameters.cpp b/src/plugins/projectexplorer/devicesupport/sshparameters.cpp index 1467f958b99..2b2ebdabc00 100644 --- a/src/plugins/projectexplorer/devicesupport/sshparameters.cpp +++ b/src/plugins/projectexplorer/devicesupport/sshparameters.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/extracompiler.cpp b/src/plugins/projectexplorer/extracompiler.cpp index 45d1c0e7344..0d281297339 100644 --- a/src/plugins/projectexplorer/extracompiler.cpp +++ b/src/plugins/projectexplorer/extracompiler.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp index 7daa47c0814..28792276a61 100644 --- a/src/plugins/projectexplorer/gcctoolchain.cpp +++ b/src/plugins/projectexplorer/gcctoolchain.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/makestep.cpp b/src/plugins/projectexplorer/makestep.cpp index fe3796bb303..730215d81c8 100644 --- a/src/plugins/projectexplorer/makestep.cpp +++ b/src/plugins/projectexplorer/makestep.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp index f5d66994696..5066d0969ae 100644 --- a/src/plugins/projectexplorer/msvctoolchain.cpp +++ b/src/plugins/projectexplorer/msvctoolchain.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/processparameters.cpp b/src/plugins/projectexplorer/processparameters.cpp index d9338ad03a2..a60f1059475 100644 --- a/src/plugins/projectexplorer/processparameters.cpp +++ b/src/plugins/projectexplorer/processparameters.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp index 53f33f58b31..9d603b47309 100644 --- a/src/plugins/projectexplorer/projectmodels.cpp +++ b/src/plugins/projectexplorer/projectmodels.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/runconfigurationaspects.cpp b/src/plugins/projectexplorer/runconfigurationaspects.cpp index 96e4bc1e1f7..7b6c7f4f5d3 100644 --- a/src/plugins/projectexplorer/runconfigurationaspects.cpp +++ b/src/plugins/projectexplorer/runconfigurationaspects.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/runcontrol.cpp b/src/plugins/projectexplorer/runcontrol.cpp index 0de0ff04628..0a7122560a6 100644 --- a/src/plugins/projectexplorer/runcontrol.cpp +++ b/src/plugins/projectexplorer/runcontrol.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/projectexplorer/targetsetuppage.cpp b/src/plugins/projectexplorer/targetsetuppage.cpp index 72e77fd6644..5b752071fd5 100644 --- a/src/plugins/projectexplorer/targetsetuppage.cpp +++ b/src/plugins/projectexplorer/targetsetuppage.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/taskfile.cpp b/src/plugins/projectexplorer/taskfile.cpp index b6a95c0325a..1c95254e2ef 100644 --- a/src/plugins/projectexplorer/taskfile.cpp +++ b/src/plugins/projectexplorer/taskfile.cpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/toolchainconfigwidget.cpp b/src/plugins/projectexplorer/toolchainconfigwidget.cpp index c7ce623b50a..60b1479e7d8 100644 --- a/src/plugins/projectexplorer/toolchainconfigwidget.cpp +++ b/src/plugins/projectexplorer/toolchainconfigwidget.cpp @@ -7,7 +7,7 @@ #include "projectexplorertr.h" #include -#include +#include #include #include diff --git a/src/plugins/projectexplorer/userfileaccessor.cpp b/src/plugins/projectexplorer/userfileaccessor.cpp index 6a1059bcd1c..a370d80ff69 100644 --- a/src/plugins/projectexplorer/userfileaccessor.cpp +++ b/src/plugins/projectexplorer/userfileaccessor.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/python/pipsupport.cpp b/src/plugins/python/pipsupport.cpp index db58b3869c3..8723ca75109 100644 --- a/src/plugins/python/pipsupport.cpp +++ b/src/plugins/python/pipsupport.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include using namespace Utils; diff --git a/src/plugins/python/pipsupport.h b/src/plugins/python/pipsupport.h index 7d7b9e135f1..da217282eb9 100644 --- a/src/plugins/python/pipsupport.h +++ b/src/plugins/python/pipsupport.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include #include diff --git a/src/plugins/python/pyside.cpp b/src/plugins/python/pyside.cpp index 5df87ff1bb7..79ffb8b9518 100644 --- a/src/plugins/python/pyside.cpp +++ b/src/plugins/python/pyside.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/python/pysideuicextracompiler.cpp b/src/plugins/python/pysideuicextracompiler.cpp index 45fb68066f9..c195aeaa1f7 100644 --- a/src/plugins/python/pysideuicextracompiler.cpp +++ b/src/plugins/python/pysideuicextracompiler.cpp @@ -3,7 +3,7 @@ #include "pysideuicextracompiler.h" -#include +#include using namespace ProjectExplorer; using namespace Utils; diff --git a/src/plugins/python/pythonbuildconfiguration.cpp b/src/plugins/python/pythonbuildconfiguration.cpp index 9e1192bcd80..d13e8cbc6ae 100644 --- a/src/plugins/python/pythonbuildconfiguration.cpp +++ b/src/plugins/python/pythonbuildconfiguration.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include using namespace ProjectExplorer; using namespace Utils; diff --git a/src/plugins/python/pythonkitaspect.cpp b/src/plugins/python/pythonkitaspect.cpp index 26ad44bad48..b3c17977f85 100644 --- a/src/plugins/python/pythonkitaspect.cpp +++ b/src/plugins/python/pythonkitaspect.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include diff --git a/src/plugins/python/pythonlanguageclient.cpp b/src/plugins/python/pythonlanguageclient.cpp index dbe6c434de6..86cebde0e94 100644 --- a/src/plugins/python/pythonlanguageclient.cpp +++ b/src/plugins/python/pythonlanguageclient.cpp @@ -32,7 +32,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/python/pythonsettings.cpp b/src/plugins/python/pythonsettings.cpp index b144f4a7e84..2f2fcbaace1 100644 --- a/src/plugins/python/pythonsettings.cpp +++ b/src/plugins/python/pythonsettings.cpp @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/python/pythonutils.cpp b/src/plugins/python/pythonutils.cpp index 2ecfe495bcd..f012bdfd65d 100644 --- a/src/plugins/python/pythonutils.cpp +++ b/src/plugins/python/pythonutils.cpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp index 34fa9057450..6cf4cc7e31b 100644 --- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp +++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qbsprojectmanager/qbsprofilemanager.cpp b/src/plugins/qbsprojectmanager/qbsprofilemanager.cpp index cf9f663bc7e..3cfd68d5ce9 100644 --- a/src/plugins/qbsprojectmanager/qbsprofilemanager.cpp +++ b/src/plugins/qbsprojectmanager/qbsprofilemanager.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qbsprojectmanager/qbssession.cpp b/src/plugins/qbsprojectmanager/qbssession.cpp index 4bbdbb6ebc7..b2801acfa26 100644 --- a/src/plugins/qbsprojectmanager/qbssession.cpp +++ b/src/plugins/qbsprojectmanager/qbssession.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qbsprojectmanager/qbssettings.cpp b/src/plugins/qbsprojectmanager/qbssettings.cpp index 79299bbb32c..ea89d659855 100644 --- a/src/plugins/qbsprojectmanager/qbssettings.cpp +++ b/src/plugins/qbsprojectmanager/qbssettings.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp b/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp index 800d7350c19..c4652d2e352 100644 --- a/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp +++ b/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/makefileparse.cpp b/src/plugins/qmakeprojectmanager/makefileparse.cpp index 60a04cee0a8..6ba748b0c1d 100644 --- a/src/plugins/qmakeprojectmanager/makefileparse.cpp +++ b/src/plugins/qmakeprojectmanager/makefileparse.cpp @@ -5,7 +5,7 @@ #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp index 798eae306f6..55b31efae08 100644 --- a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp +++ b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp @@ -36,7 +36,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakemakestep.cpp b/src/plugins/qmakeprojectmanager/qmakemakestep.cpp index 901cf5653c6..ae8b370b778 100644 --- a/src/plugins/qmakeprojectmanager/qmakemakestep.cpp +++ b/src/plugins/qmakeprojectmanager/qmakemakestep.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakeparsernodes.cpp b/src/plugins/qmakeprojectmanager/qmakeparsernodes.cpp index 9faa6e6c536..9c6ca5caa41 100644 --- a/src/plugins/qmakeprojectmanager/qmakeparsernodes.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeparsernodes.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakeproject.cpp b/src/plugins/qmakeprojectmanager/qmakeproject.cpp index 6575366a44c..c118ba1920e 100644 --- a/src/plugins/qmakeprojectmanager/qmakeproject.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeproject.cpp @@ -51,7 +51,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp index 20cebc3ac72..200de04db76 100644 --- a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmakeprojectmanager/qmakestep.cpp b/src/plugins/qmakeprojectmanager/qmakestep.cpp index 1d07e4e13ac..e012499b540 100644 --- a/src/plugins/qmakeprojectmanager/qmakestep.cpp +++ b/src/plugins/qmakeprojectmanager/qmakestep.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp index a9bbd2ecdb8..4f4fabe2ebe 100644 --- a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp +++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp @@ -60,7 +60,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp index f16acf380f8..3fd4814b0aa 100644 --- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp +++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp @@ -75,7 +75,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/qmldesigner/generateresource.cpp b/src/plugins/qmldesigner/generateresource.cpp index 10cdecafdb2..fc0fa9d137d 100644 --- a/src/plugins/qmldesigner/generateresource.cpp +++ b/src/plugins/qmldesigner/generateresource.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp b/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp index 41bac4cd8e5..83598125e74 100644 --- a/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp +++ b/src/plugins/qmlpreview/qmlpreviewruncontrol.cpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmlprofiler/qmlprofilerruncontrol.cpp b/src/plugins/qmlprofiler/qmlprofilerruncontrol.cpp index af91963e023..3ab0647e810 100644 --- a/src/plugins/qmlprofiler/qmlprofilerruncontrol.cpp +++ b/src/plugins/qmlprofiler/qmlprofilerruncontrol.cpp @@ -20,7 +20,7 @@ #include -#include +#include #include #include diff --git a/src/plugins/qmlprojectmanager/qmlproject.cpp b/src/plugins/qmlprojectmanager/qmlproject.cpp index d2cac841a92..388169b3756 100644 --- a/src/plugins/qmlprojectmanager/qmlproject.cpp +++ b/src/plugins/qmlprojectmanager/qmlproject.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp index cd2910ec7fe..62abce5fe96 100644 --- a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp +++ b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp @@ -50,7 +50,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp index 77650c9dd81..5742b945a8d 100644 --- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp +++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qnx/qnxanalyzesupport.cpp b/src/plugins/qnx/qnxanalyzesupport.cpp index fe87c15eafd..d21d0b44c02 100644 --- a/src/plugins/qnx/qnxanalyzesupport.cpp +++ b/src/plugins/qnx/qnxanalyzesupport.cpp @@ -9,7 +9,7 @@ #include -#include +#include #include diff --git a/src/plugins/qnx/qnxdebugsupport.cpp b/src/plugins/qnx/qnxdebugsupport.cpp index b2d923f2cbe..27c26e269c0 100644 --- a/src/plugins/qnx/qnxdebugsupport.cpp +++ b/src/plugins/qnx/qnxdebugsupport.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp b/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp index a134d25615f..8b3baadb20e 100644 --- a/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp +++ b/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qnx/qnxdevice.cpp b/src/plugins/qnx/qnxdevice.cpp index c810a3f2866..4d04d69b42c 100644 --- a/src/plugins/qnx/qnxdevice.cpp +++ b/src/plugins/qnx/qnxdevice.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qnx/qnxdevicetester.cpp b/src/plugins/qnx/qnxdevicetester.cpp index f4a94f0efc4..b2208d92c12 100644 --- a/src/plugins/qnx/qnxdevicetester.cpp +++ b/src/plugins/qnx/qnxdevicetester.cpp @@ -6,7 +6,7 @@ #include "qnxconstants.h" #include "qnxtr.h" -#include +#include using namespace Utils; diff --git a/src/plugins/qnx/qnxutils.cpp b/src/plugins/qnx/qnxutils.cpp index 634800fe993..6ab907b6e90 100644 --- a/src/plugins/qnx/qnxutils.cpp +++ b/src/plugins/qnx/qnxutils.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qnx/slog2inforunner.cpp b/src/plugins/qnx/slog2inforunner.cpp index 47aa850e819..e717e56e337 100644 --- a/src/plugins/qnx/slog2inforunner.cpp +++ b/src/plugins/qnx/slog2inforunner.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/qtapplicationmanager/appmanagerinstallpackagestep.cpp b/src/plugins/qtapplicationmanager/appmanagerinstallpackagestep.cpp index f89514ba005..67c9f6bec6f 100644 --- a/src/plugins/qtapplicationmanager/appmanagerinstallpackagestep.cpp +++ b/src/plugins/qtapplicationmanager/appmanagerinstallpackagestep.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include using namespace ProjectExplorer; using namespace Utils; diff --git a/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp b/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp index f1bbebf575a..df916ccc55e 100644 --- a/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp +++ b/src/plugins/qtapplicationmanager/appmanagerruncontrol.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include using namespace ProjectExplorer; diff --git a/src/plugins/qtsupport/baseqtversion.cpp b/src/plugins/qtsupport/baseqtversion.cpp index 399efc3a1cd..ccc72baf6ec 100644 --- a/src/plugins/qtsupport/baseqtversion.cpp +++ b/src/plugins/qtsupport/baseqtversion.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/qtsupport/externaleditors.cpp b/src/plugins/qtsupport/externaleditors.cpp index 47e8d21e840..4009025b8dc 100644 --- a/src/plugins/qtsupport/externaleditors.cpp +++ b/src/plugins/qtsupport/externaleditors.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qtsupport/qtsupportplugin.cpp b/src/plugins/qtsupport/qtsupportplugin.cpp index db0f8888af4..72c2ac4ae95 100644 --- a/src/plugins/qtsupport/qtsupportplugin.cpp +++ b/src/plugins/qtsupport/qtsupportplugin.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include diff --git a/src/plugins/qtsupport/qtversionmanager.cpp b/src/plugins/qtsupport/qtversionmanager.cpp index 715eec8aa2d..3aa1397b309 100644 --- a/src/plugins/qtsupport/qtversionmanager.cpp +++ b/src/plugins/qtsupport/qtversionmanager.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/qtsupport/uicgenerator.cpp b/src/plugins/qtsupport/uicgenerator.cpp index 74b8355af9a..e79788f174e 100644 --- a/src/plugins/qtsupport/uicgenerator.cpp +++ b/src/plugins/qtsupport/uicgenerator.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/customcommanddeploystep.cpp b/src/plugins/remotelinux/customcommanddeploystep.cpp index 211f48b4f47..97826fde5e9 100644 --- a/src/plugins/remotelinux/customcommanddeploystep.cpp +++ b/src/plugins/remotelinux/customcommanddeploystep.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include using namespace ProjectExplorer; using namespace Tasking; diff --git a/src/plugins/remotelinux/filesystemaccess_test.cpp b/src/plugins/remotelinux/filesystemaccess_test.cpp index d23ac3f3a1b..0f2e5bd9379 100644 --- a/src/plugins/remotelinux/filesystemaccess_test.cpp +++ b/src/plugins/remotelinux/filesystemaccess_test.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/genericdeploystep.cpp b/src/plugins/remotelinux/genericdeploystep.cpp index bddc7bfcd3d..95a0a8360ff 100644 --- a/src/plugins/remotelinux/genericdeploystep.cpp +++ b/src/plugins/remotelinux/genericdeploystep.cpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include using namespace ProjectExplorer; diff --git a/src/plugins/remotelinux/genericdirectuploadstep.cpp b/src/plugins/remotelinux/genericdirectuploadstep.cpp index 9817ce3f0af..383722873bc 100644 --- a/src/plugins/remotelinux/genericdirectuploadstep.cpp +++ b/src/plugins/remotelinux/genericdirectuploadstep.cpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp index 30fac20a9d9..e29533a41b5 100644 --- a/src/plugins/remotelinux/linuxdevice.cpp +++ b/src/plugins/remotelinux/linuxdevice.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/remotelinux/linuxdevicetester.cpp b/src/plugins/remotelinux/linuxdevicetester.cpp index f279bc0c382..aad08703064 100644 --- a/src/plugins/remotelinux/linuxdevicetester.cpp +++ b/src/plugins/remotelinux/linuxdevicetester.cpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/remotelinux/makeinstallstep.cpp b/src/plugins/remotelinux/makeinstallstep.cpp index 08e65e61261..38edbb6791e 100644 --- a/src/plugins/remotelinux/makeinstallstep.cpp +++ b/src/plugins/remotelinux/makeinstallstep.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/publickeydeploymentdialog.cpp b/src/plugins/remotelinux/publickeydeploymentdialog.cpp index 6d0ead4ac6f..d3ade682cb2 100644 --- a/src/plugins/remotelinux/publickeydeploymentdialog.cpp +++ b/src/plugins/remotelinux/publickeydeploymentdialog.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/remotelinuxsignaloperation.cpp b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp index a4cd369ca4b..95e68a64854 100644 --- a/src/plugins/remotelinux/remotelinuxsignaloperation.cpp +++ b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include using namespace ProjectExplorer; diff --git a/src/plugins/remotelinux/sshkeycreationdialog.cpp b/src/plugins/remotelinux/sshkeycreationdialog.cpp index ca00cca76af..03c6f7a543f 100644 --- a/src/plugins/remotelinux/sshkeycreationdialog.cpp +++ b/src/plugins/remotelinux/sshkeycreationdialog.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/remotelinux/tarpackagedeploystep.cpp b/src/plugins/remotelinux/tarpackagedeploystep.cpp index aa8fe3db309..5f79272f4a8 100644 --- a/src/plugins/remotelinux/tarpackagedeploystep.cpp +++ b/src/plugins/remotelinux/tarpackagedeploystep.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include using namespace ProjectExplorer; diff --git a/src/plugins/screenrecorder/cropandtrim.cpp b/src/plugins/screenrecorder/cropandtrim.cpp index cdd63994a89..fe37fd5cf6e 100644 --- a/src/plugins/screenrecorder/cropandtrim.cpp +++ b/src/plugins/screenrecorder/cropandtrim.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/screenrecorder/export.cpp b/src/plugins/screenrecorder/export.cpp index 0c9b67d2a34..15f38993adc 100644 --- a/src/plugins/screenrecorder/export.cpp +++ b/src/plugins/screenrecorder/export.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/screenrecorder/ffmpegutils.cpp b/src/plugins/screenrecorder/ffmpegutils.cpp index 96223c3781e..fa0a6f45ae7 100644 --- a/src/plugins/screenrecorder/ffmpegutils.cpp +++ b/src/plugins/screenrecorder/ffmpegutils.cpp @@ -12,7 +12,7 @@ #endif // WITH_TESTS #include -#include +#include #include #include diff --git a/src/plugins/screenrecorder/record.cpp b/src/plugins/screenrecorder/record.cpp index 7f14d3dc0d3..aba61ed2eba 100644 --- a/src/plugins/screenrecorder/record.cpp +++ b/src/plugins/screenrecorder/record.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/silversearcher/findinfilessilversearcher.cpp b/src/plugins/silversearcher/findinfilessilversearcher.cpp index a6f79ce6091..cb290e046d8 100644 --- a/src/plugins/silversearcher/findinfilessilversearcher.cpp +++ b/src/plugins/silversearcher/findinfilessilversearcher.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/squish/objectsmapdocument.cpp b/src/plugins/squish/objectsmapdocument.cpp index 20c77d9ccee..ba5f70b0cd1 100644 --- a/src/plugins/squish/objectsmapdocument.cpp +++ b/src/plugins/squish/objectsmapdocument.cpp @@ -9,7 +9,7 @@ #include "squishtr.h" #include -#include +#include #include diff --git a/src/plugins/squish/squishprocessbase.h b/src/plugins/squish/squishprocessbase.h index 6582c95062b..d8af2e9d4f2 100644 --- a/src/plugins/squish/squishprocessbase.h +++ b/src/plugins/squish/squishprocessbase.h @@ -5,7 +5,7 @@ #include "squishconstants.h" -#include +#include #include diff --git a/src/plugins/squish/squishtools.h b/src/plugins/squish/squishtools.h index 223bfb7c23e..87b45d5af07 100644 --- a/src/plugins/squish/squishtools.h +++ b/src/plugins/squish/squishtools.h @@ -9,7 +9,7 @@ #include "suiteconf.h" #include -#include +#include #include #include diff --git a/src/plugins/subversion/subversionclient.cpp b/src/plugins/subversion/subversionclient.cpp index e30abd5bc81..e69809143d3 100644 --- a/src/plugins/subversion/subversionclient.cpp +++ b/src/plugins/subversion/subversionclient.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/terminal/shellintegration.h b/src/plugins/terminal/shellintegration.h index 4f1215fad94..905b088b389 100644 --- a/src/plugins/terminal/shellintegration.h +++ b/src/plugins/terminal/shellintegration.h @@ -5,7 +5,7 @@ #pragma once #include -#include +#include #include diff --git a/src/plugins/terminal/terminalwidget.h b/src/plugins/terminal/terminalwidget.h index acba039ba96..351ae457205 100644 --- a/src/plugins/terminal/terminalwidget.h +++ b/src/plugins/terminal/terminalwidget.h @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/texteditor/basefilefind.cpp b/src/plugins/texteditor/basefilefind.cpp index 399e275fe4f..ce6d2f4999f 100644 --- a/src/plugins/texteditor/basefilefind.cpp +++ b/src/plugins/texteditor/basefilefind.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/texteditor/formattexteditor.cpp b/src/plugins/texteditor/formattexteditor.cpp index d4d1d616367..879387b991a 100644 --- a/src/plugins/texteditor/formattexteditor.cpp +++ b/src/plugins/texteditor/formattexteditor.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/updateinfo/updateinfoplugin.cpp b/src/plugins/updateinfo/updateinfoplugin.cpp index a23d6c7cfc2..98e1160f3f6 100644 --- a/src/plugins/updateinfo/updateinfoplugin.cpp +++ b/src/plugins/updateinfo/updateinfoplugin.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/valgrind/callgrindengine.cpp b/src/plugins/valgrind/callgrindengine.cpp index 06ff38f5abe..8422bb01769 100644 --- a/src/plugins/valgrind/callgrindengine.cpp +++ b/src/plugins/valgrind/callgrindengine.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/valgrind/callgrindengine.h b/src/plugins/valgrind/callgrindengine.h index 2379e917374..c0e5ce2a8b6 100644 --- a/src/plugins/valgrind/callgrindengine.h +++ b/src/plugins/valgrind/callgrindengine.h @@ -8,7 +8,7 @@ #include "callgrind/callgrindparsedata.h" #include "callgrind/callgrindparser.h" -#include +#include #include namespace Valgrind::Internal { diff --git a/src/plugins/valgrind/callgrindtool.cpp b/src/plugins/valgrind/callgrindtool.cpp index 9718193279a..75d8dfac9d9 100644 --- a/src/plugins/valgrind/callgrindtool.cpp +++ b/src/plugins/valgrind/callgrindtool.cpp @@ -46,7 +46,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/valgrind/memchecktool.cpp b/src/plugins/valgrind/memchecktool.cpp index 742d648caf1..8ae89a3193e 100644 --- a/src/plugins/valgrind/memchecktool.cpp +++ b/src/plugins/valgrind/memchecktool.cpp @@ -45,7 +45,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/valgrind/valgrindmemcheckparsertest.cpp b/src/plugins/valgrind/valgrindmemcheckparsertest.cpp index 66824f718c3..44cac3712c6 100644 --- a/src/plugins/valgrind/valgrindmemcheckparsertest.cpp +++ b/src/plugins/valgrind/valgrindmemcheckparsertest.cpp @@ -11,7 +11,7 @@ #include "xmlprotocol/status.h" #include "xmlprotocol/suppression.h" -#include +#include #include #include diff --git a/src/plugins/valgrind/valgrindprocess.cpp b/src/plugins/valgrind/valgrindprocess.cpp index d543f3e66a3..b86eb0cf7a6 100644 --- a/src/plugins/valgrind/valgrindprocess.cpp +++ b/src/plugins/valgrind/valgrindprocess.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/vcsbase/vcsbaseclient.cpp b/src/plugins/vcsbase/vcsbaseclient.cpp index 81a816c0099..2327e75bc7b 100644 --- a/src/plugins/vcsbase/vcsbaseclient.cpp +++ b/src/plugins/vcsbase/vcsbaseclient.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/vcsbase/vcsbasediffeditorcontroller.cpp b/src/plugins/vcsbase/vcsbasediffeditorcontroller.cpp index cbd33f48fcf..4ba6baba34e 100644 --- a/src/plugins/vcsbase/vcsbasediffeditorcontroller.cpp +++ b/src/plugins/vcsbase/vcsbasediffeditorcontroller.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include using namespace DiffEditor; using namespace Tasking; diff --git a/src/plugins/vcsbase/vcsbaseplugin.cpp b/src/plugins/vcsbase/vcsbaseplugin.cpp index b506f0ed380..a66596d49fe 100644 --- a/src/plugins/vcsbase/vcsbaseplugin.cpp +++ b/src/plugins/vcsbase/vcsbaseplugin.cpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp index 4c29da91f2f..7a52cc96090 100644 --- a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp +++ b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/plugins/vcsbase/vcscommand.cpp b/src/plugins/vcsbase/vcscommand.cpp index f1995b2d844..a10586458ec 100644 --- a/src/plugins/vcsbase/vcscommand.cpp +++ b/src/plugins/vcsbase/vcscommand.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/vcsbase/vcsoutputwindow.cpp b/src/plugins/vcsbase/vcsoutputwindow.cpp index 3ad77c9eb01..3ada77fb200 100644 --- a/src/plugins/vcsbase/vcsoutputwindow.cpp +++ b/src/plugins/vcsbase/vcsoutputwindow.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/webassembly/webassemblyemsdk.cpp b/src/plugins/webassembly/webassemblyemsdk.cpp index 12c4d649678..6541200eaa7 100644 --- a/src/plugins/webassembly/webassemblyemsdk.cpp +++ b/src/plugins/webassembly/webassemblyemsdk.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/webassembly/webassemblyrunconfiguration.cpp b/src/plugins/webassembly/webassemblyrunconfiguration.cpp index 593f0b95803..1c8f6b60c1d 100644 --- a/src/plugins/webassembly/webassemblyrunconfiguration.cpp +++ b/src/plugins/webassembly/webassemblyrunconfiguration.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include diff --git a/tests/auto/utils/commandline/tst_commandline.cpp b/tests/auto/utils/commandline/tst_commandline.cpp index 1c7b7d4f807..d884e47c8d6 100644 --- a/tests/auto/utils/commandline/tst_commandline.cpp +++ b/tests/auto/utils/commandline/tst_commandline.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include diff --git a/tests/auto/utils/deviceshell/tst_deviceshell.cpp b/tests/auto/utils/deviceshell/tst_deviceshell.cpp index 6e081495c36..f94d0dc5b40 100644 --- a/tests/auto/utils/deviceshell/tst_deviceshell.cpp +++ b/tests/auto/utils/deviceshell/tst_deviceshell.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include diff --git a/tests/auto/utils/process/processtestapp/main.cpp b/tests/auto/utils/process/processtestapp/main.cpp index 34923c407aa..5b0dda04b32 100644 --- a/tests/auto/utils/process/processtestapp/main.cpp +++ b/tests/auto/utils/process/processtestapp/main.cpp @@ -6,7 +6,7 @@ #include #include -#include +#include #include #include diff --git a/tests/auto/utils/process/processtestapp/processtestapp.cpp b/tests/auto/utils/process/processtestapp/processtestapp.cpp index e080b580205..0148d1e2613 100644 --- a/tests/auto/utils/process/processtestapp/processtestapp.cpp +++ b/tests/auto/utils/process/processtestapp/processtestapp.cpp @@ -3,7 +3,7 @@ #include "processtestapp.h" -#include +#include #include #include diff --git a/tests/auto/utils/process/tst_process.cpp b/tests/auto/utils/process/tst_process.cpp index 60f3a72aa67..cd9f8715152 100644 --- a/tests/auto/utils/process/tst_process.cpp +++ b/tests/auto/utils/process/tst_process.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/tests/manual/deviceshell/tst_deviceshell.cpp b/tests/manual/deviceshell/tst_deviceshell.cpp index 99c506d1bda..96638763f8e 100644 --- a/tests/manual/deviceshell/tst_deviceshell.cpp +++ b/tests/manual/deviceshell/tst_deviceshell.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include From ff04dc53ef94ff424789c1ff9a71a32417d4160b Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Mon, 19 Feb 2024 16:11:58 +0100 Subject: [PATCH 0039/1060] Require Qt 6.4.3 for building Qt Creator And remove unneeded conditions from CMake files Change-Id: Ibb4646f83599c5a91fbd18ce3489103e4150c49f Reviewed-by: Qt CI Bot Reviewed-by: hjk Reviewed-by: --- CMakeLists.txt | 8 ++------ cmake/QtCreatorAPI.cmake | 2 +- src/plugins/qmlprojectmanager/CMakeLists.txt | 1 - 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ef82879259e..a3a60e5dd0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -73,12 +73,8 @@ find_package(Qt6 REQUIRED ) -if (Qt6_VERSION VERSION_GREATER_EQUAL 6.4.3) - option(WITH_QMLDESIGNER "Build QmlDesigner" ${ENV_QTC_WITH_QMLDESIGNER}) -else() - option(WITH_QMLDESIGNER "Build QmlDesigner" OFF) -endif() -add_feature_info("Build QmlDesigner and related code (only if Qt is 6.4.3 or newer)" ${WITH_QMLDESIGNER} "") +option(WITH_QMLDESIGNER "Build QmlDesigner" ${ENV_QTC_WITH_QMLDESIGNER}) +add_feature_info("Build QmlDesigner and related code" ${WITH_QMLDESIGNER} "") # hack for Qbs which still supports Qt5 and Qt6 if (TARGET Qt6::Core5CompatPrivate) diff --git a/cmake/QtCreatorAPI.cmake b/cmake/QtCreatorAPI.cmake index 5cbd9cd4bf4..116f84c85ea 100644 --- a/cmake/QtCreatorAPI.cmake +++ b/cmake/QtCreatorAPI.cmake @@ -3,7 +3,7 @@ if(QT_CREATOR_API_DEFINED) endif() set(QT_CREATOR_API_DEFINED TRUE) -set(IDE_QT_VERSION_MIN "6.2.0") +set(IDE_QT_VERSION_MIN "6.4.3") include(${CMAKE_CURRENT_LIST_DIR}/QtCreatorAPIInternal.cmake) include(${CMAKE_CURRENT_LIST_DIR}/QtcSeparateDebugInfo.cmake) diff --git a/src/plugins/qmlprojectmanager/CMakeLists.txt b/src/plugins/qmlprojectmanager/CMakeLists.txt index b94bc29400d..0dc4c697160 100644 --- a/src/plugins/qmlprojectmanager/CMakeLists.txt +++ b/src/plugins/qmlprojectmanager/CMakeLists.txt @@ -53,7 +53,6 @@ extend_qtc_plugin(QmlProjectManager ) add_qtc_library(QmlProjectManagerLib OBJECT - CONDITION Qt6_VERSION VERSION_GREATER_EQUAL 6.4.3 EXCLUDE_FROM_INSTALL DEPENDS QmlJS Utils From c4e8963d8dd97a934b5253babc53a98e944a0606 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Mon, 19 Feb 2024 16:23:50 +0100 Subject: [PATCH 0040/1060] Remove unneeded version checks After we raised the minimum Qt version. Change-Id: Ife81a25c3c205646eece30d6dd1a95f4b97eda01 Reviewed-by: Marco Bubke Reviewed-by: hjk Reviewed-by: Qt CI Bot Reviewed-by: Jarek Kobus Reviewed-by: --- src/libs/languageserverprotocol/jsonobject.h | 15 --------------- src/libs/tracing/timelineitemsrenderpass.cpp | 4 ---- src/libs/tracing/timelinenotesrenderpass.cpp | 4 ---- src/libs/utils/async.cpp | 11 ----------- src/libs/utils/fsengine/fsengine_impl.cpp | 8 -------- src/libs/utils/fsengine/fsengine_impl.h | 5 ----- src/libs/utils/smallstring.h | 2 -- src/libs/utils/smallstringview.h | 2 -- src/plugins/coreplugin/manhattanstyle.cpp | 8 -------- .../collectioneditor/collectiondetails.cpp | 7 ------- .../components/componentcore/designericons.cpp | 14 -------------- .../qmldesignerbase/studio/studiostyle.cpp | 9 --------- .../qmlprofilerbindingloopsrenderpass.cpp | 4 ---- src/tools/iostool/relayserver.cpp | 4 ---- .../tst_subdirfilecontainer.cpp | 5 ----- 15 files changed, 102 deletions(-) diff --git a/src/libs/languageserverprotocol/jsonobject.h b/src/libs/languageserverprotocol/jsonobject.h index 178e74e5ad7..fd90453da1a 100644 --- a/src/libs/languageserverprotocol/jsonobject.h +++ b/src/libs/languageserverprotocol/jsonobject.h @@ -10,26 +10,11 @@ #include #include -#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) #include -#else -#include -#endif namespace LanguageServerProtocol { -#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) using Key = QLatin1StringView; -#else -class Key : public QLatin1String -{ -public: - using QLatin1String::QLatin1String; - constexpr inline explicit Key(const char *s) noexcept - : QLatin1String(s, std::char_traits::length(s)) - {} -}; -#endif class LANGUAGESERVERPROTOCOL_EXPORT JsonObject { diff --git a/src/libs/tracing/timelineitemsrenderpass.cpp b/src/libs/tracing/timelineitemsrenderpass.cpp index b93bd83b427..5b50a153e6c 100644 --- a/src/libs/tracing/timelineitemsrenderpass.cpp +++ b/src/libs/tracing/timelineitemsrenderpass.cpp @@ -464,11 +464,7 @@ bool TimelineItemsMaterialShader::updateUniformData(RenderState &state, TimelineItemsMaterial::TimelineItemsMaterial() : m_selectedItem(-1) { setFlag(QSGMaterial::Blending, false); -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) setFlag(QSGMaterial::NoBatching, true); -#else - setFlag(QSGMaterial::CustomCompileStep, true); -#endif // >= Qt 6.3/6.0 } QVector2D TimelineItemsMaterial::scale() const diff --git a/src/libs/tracing/timelinenotesrenderpass.cpp b/src/libs/tracing/timelinenotesrenderpass.cpp index 0f3fa00de32..5a3939b4f32 100644 --- a/src/libs/tracing/timelinenotesrenderpass.cpp +++ b/src/libs/tracing/timelinenotesrenderpass.cpp @@ -152,11 +152,7 @@ TimelineNotesRenderPassState::TimelineNotesRenderPassState(int numExpandedRows) m_nullGeometry(NotesGeometry::point2DWithDistanceFromTop(), 0) { m_material.setFlag(QSGMaterial::Blending, true); -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) m_material.setFlag(QSGMaterial::NoBatching, true); -#else - m_material.setFlag(QSGMaterial::CustomCompileStep, true); -#endif // >= Qt 6.3 m_expandedRows.reserve(numExpandedRows); for (int i = 0; i < numExpandedRows; ++i) m_expandedRows << createNode(); diff --git a/src/libs/utils/async.cpp b/src/libs/utils/async.cpp index 33487db73be..b67e83fc721 100644 --- a/src/libs/utils/async.cpp +++ b/src/libs/utils/async.cpp @@ -17,16 +17,6 @@ public: } }; -#if QT_VERSION < QT_VERSION_CHECK(6, 3, 0) -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_idle, (QThread::IdlePriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_lowest, (QThread::LowestPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_low, (QThread::LowPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_normal, (QThread::NormalPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_high, (QThread::HighPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_highest, (QThread::HighestPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_timeCritical, (QThread::TimeCriticalPriority)); -Q_GLOBAL_STATIC_WITH_ARGS(AsyncThreadPool, s_inherit, (QThread::InheritPriority)); -#else Q_GLOBAL_STATIC(AsyncThreadPool, s_idle, QThread::IdlePriority); Q_GLOBAL_STATIC(AsyncThreadPool, s_lowest, QThread::LowestPriority); Q_GLOBAL_STATIC(AsyncThreadPool, s_low, QThread::LowPriority); @@ -35,7 +25,6 @@ Q_GLOBAL_STATIC(AsyncThreadPool, s_high, QThread::HighPriority); Q_GLOBAL_STATIC(AsyncThreadPool, s_highest, QThread::HighestPriority); Q_GLOBAL_STATIC(AsyncThreadPool, s_timeCritical, QThread::TimeCriticalPriority); Q_GLOBAL_STATIC(AsyncThreadPool, s_inherit, QThread::InheritPriority); -#endif QThreadPool *asyncThreadPool(QThread::Priority priority) { diff --git a/src/libs/utils/fsengine/fsengine_impl.cpp b/src/libs/utils/fsengine/fsengine_impl.cpp index ade8236d5e1..05147709d47 100644 --- a/src/libs/utils/fsengine/fsengine_impl.cpp +++ b/src/libs/utils/fsengine/fsengine_impl.cpp @@ -35,11 +35,7 @@ FSEngineImpl::~FSEngineImpl() delete m_tempStorage; } -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) bool FSEngineImpl::open(QIODeviceBase::OpenMode openMode, std::optional) -#else -bool FSEngineImpl::open(QIODevice::OpenMode openMode) -#endif { const FilePathInfoCache::CachedData data = g_filePathInfoCache.cached(m_filePath, createCacheData); @@ -162,12 +158,8 @@ bool FSEngineImpl::link(const QString &newName) return false; } -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) bool FSEngineImpl::mkdir(const QString &dirName, bool createParentDirectories, std::optional) const -#else -bool FSEngineImpl::mkdir(const QString &dirName, bool createParentDirectories) const -#endif { Q_UNUSED(createParentDirectories) return FilePath::fromString(dirName).createDir(); diff --git a/src/libs/utils/fsengine/fsengine_impl.h b/src/libs/utils/fsengine/fsengine_impl.h index 17481c1a6ae..6fcba8ac523 100644 --- a/src/libs/utils/fsengine/fsengine_impl.h +++ b/src/libs/utils/fsengine/fsengine_impl.h @@ -19,15 +19,10 @@ public: ~FSEngineImpl(); public: -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) bool open(QIODeviceBase::OpenMode openMode, std::optional permissions = std::nullopt) override; bool mkdir(const QString &dirName, bool createParentDirectories, std::optional permissions = std::nullopt) const override; -#else - bool open(QIODevice::OpenMode openMode) override; - bool mkdir(const QString &dirName, bool createParentDirectories) const override; -#endif bool close() override; bool flush() override; bool syncToDisk() override; diff --git a/src/libs/utils/smallstring.h b/src/libs/utils/smallstring.h index c424e9e1ab2..0b2f0b629f1 100644 --- a/src/libs/utils/smallstring.h +++ b/src/libs/utils/smallstring.h @@ -200,12 +200,10 @@ public: operator SmallStringView() const noexcept { return SmallStringView(data(), size()); } - #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) explicit operator QLatin1StringView() const noexcept { return QLatin1StringView(data(), Utils::ssize(*this)); } -#endif operator QUtf8StringView() const noexcept { diff --git a/src/libs/utils/smallstringview.h b/src/libs/utils/smallstringview.h index 5a272178196..28f8b781501 100644 --- a/src/libs/utils/smallstringview.h +++ b/src/libs/utils/smallstringview.h @@ -79,12 +79,10 @@ public: explicit operator QByteArray() const { return QByteArray(data(), int(size())); } -#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) explicit operator QLatin1StringView() const noexcept { return QLatin1StringView(data(), Utils::ssize(*this)); } -#endif operator QUtf8StringView() const noexcept { diff --git a/src/plugins/coreplugin/manhattanstyle.cpp b/src/plugins/coreplugin/manhattanstyle.cpp index 4aa3c6464d5..20df27bea5b 100644 --- a/src/plugins/coreplugin/manhattanstyle.cpp +++ b/src/plugins/coreplugin/manhattanstyle.cpp @@ -190,14 +190,6 @@ QRect ManhattanStyle::subControlRect( SubControl subControl, const QWidget *widget) const { -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 5) - // Workaround for QTBUG-101581, can be removed when building with Qt 6.2.5 or higher - if (control == CC_ScrollBar) { - const auto scrollbar = qstyleoption_cast(option); - if (scrollbar && qint64(scrollbar->maximum) - scrollbar->minimum > INT_MAX) - return QRect(); // breaks the scrollbar, but avoids the crash - } -#endif return QProxyStyle::subControlRect(control, option, subControl, widget); } diff --git a/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp b/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp index f35e9f2ed26..56296143cff 100644 --- a/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp +++ b/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp @@ -44,14 +44,7 @@ public: inline static bool isValidColorName(const QString &colorName) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) return QColor::isValidColorName(colorName); -#else - constexpr QStringView colorPattern( - u"(?^(?:#(?:(?:[0-9a-fA-F]{2}){3,4}|(?:[0-9a-fA-F]){3,4}))$)"); - static const QRegularExpression colorRegex(colorPattern.toString()); - return colorRegex.match(colorName).hasMatch(); -#endif // >= Qt 6.4 } /** diff --git a/src/plugins/qmldesigner/components/componentcore/designericons.cpp b/src/plugins/qmldesigner/components/componentcore/designericons.cpp index 31e7b45fcdb..13f72764e8a 100644 --- a/src/plugins/qmldesigner/components/componentcore/designericons.cpp +++ b/src/plugins/qmldesigner/components/componentcore/designericons.cpp @@ -223,16 +223,8 @@ struct JsonMap> { QJsonObject output; - #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) for (const auto &[key, val] : map.asKeyValueRange()) output[DesignerIconEnums::toString(key)] = JsonMap::json(val); - #else - const auto mapKeys = map.keys(); - for (const Key &key : mapKeys) { - const Value &val = map.value(key); - output[DesignerIconEnums::toString(key)] = JsonMap::json(val); - } - #endif return output; } @@ -397,15 +389,9 @@ void DesignerIcons::loadIconSettings(const QString &fileName) QJsonObject areaPackObject = areaPack.toObject(); singleAreaMap = JsonMap::value(areaPackObject, {}); -#if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) for (const auto &mapItem : singleAreaMap.asKeyValueRange()) { const IconId &id = mapItem.first; const AreaMap &areaMap = mapItem.second; -#else - const auto mapKeys = singleAreaMap.keys(); - for (const IconId &id : mapKeys) { - const AreaMap &areaMap = singleAreaMap.value(id); -#endif if (d->icons.contains(id)) { AreaMap &oldAreaMap = d->icons[id]; for (const auto &areaMapItem : areaMap.asKeyValueRange()) diff --git a/src/plugins/qmldesignerbase/studio/studiostyle.cpp b/src/plugins/qmldesignerbase/studio/studiostyle.cpp index d1891ca88db..6924e40f7cc 100644 --- a/src/plugins/qmldesignerbase/studio/studiostyle.cpp +++ b/src/plugins/qmldesignerbase/studio/studiostyle.cpp @@ -973,15 +973,6 @@ QRect StudioStyle::subControlRect( SubControl subControl, const QWidget *widget) const { -#if QT_VERSION < QT_VERSION_CHECK(6, 2, 5) - // Workaround for QTBUG-101581, can be removed when building with Qt 6.2.5 or higher - if (control == CC_ScrollBar) { - const auto scrollbar = qstyleoption_cast(option); - if (scrollbar && qint64(scrollbar->maximum) - scrollbar->minimum > INT_MAX) - return QRect(); // breaks the scrollbar, but avoids the crash - } -#endif - switch (control) { case CC_Slider: { if (const auto slider = qstyleoption_cast(option)) { diff --git a/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp index 406ece2860d..0db02375ae3 100644 --- a/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp +++ b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp @@ -309,11 +309,7 @@ bool BindingLoopMaterialShader::updateUniformData(RenderState &state, QSGMateria BindingLoopMaterial::BindingLoopMaterial() { setFlag(QSGMaterial::Blending, false); -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) setFlag(QSGMaterial::NoBatching, true); -#else - setFlag(QSGMaterial::CustomCompileStep, true); -#endif // >= Qt 6.3 } QSGMaterialType *BindingLoopMaterial::type() const diff --git a/src/tools/iostool/relayserver.cpp b/src/tools/iostool/relayserver.cpp index 571a338b26f..0ea1be33ce9 100644 --- a/src/tools/iostool/relayserver.cpp +++ b/src/tools/iostool/relayserver.cpp @@ -33,11 +33,7 @@ void Relayer::setClientSocket(QTcpSocket *clientSocket) QTC_CHECK(!m_clientSocket); m_clientSocket = clientSocket; if (m_clientSocket) { -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - const auto errorOccurred = QOverload::of(&QAbstractSocket::error); -#else const auto errorOccurred = &QAbstractSocket::errorOccurred; -#endif connect(m_clientSocket, errorOccurred, this, &Relayer::handleClientHasError); connect(m_clientSocket, &QAbstractSocket::disconnected, this, [this](){server()->removeRelayConnection(this);}); diff --git a/tests/manual/subdirfilecontainer/tst_subdirfilecontainer.cpp b/tests/manual/subdirfilecontainer/tst_subdirfilecontainer.cpp index 89993b6a2b6..ca4925a9439 100644 --- a/tests/manual/subdirfilecontainer/tst_subdirfilecontainer.cpp +++ b/tests/manual/subdirfilecontainer/tst_subdirfilecontainer.cpp @@ -247,12 +247,7 @@ private slots: QDirIterator it(m_tempDir->path(), s_filters, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks); while (it.hasNext()) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0) const QFileInfo fi = it.nextFileInfo(); -#else - it.next(); - const QFileInfo fi = it.fileInfo(); -#endif if (fi.isDir()) { ++dirsCount; } else { From db5ac2dc15f0ac607c03416e538ae2ffc5482467 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Wed, 28 Feb 2024 09:21:15 +0100 Subject: [PATCH 0041/1060] Utils: Fix build on macOS < 13 with C++20 The Clang implementation of span is incomplete until LLVM 15 / Xcode 15 / macOS 13.5 Change-Id: Iac8514fc84643cb4dae9cfaac603df5e798f9ff4 Reviewed-by: Marco Bubke Reviewed-by: --- src/libs/utils/span.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/libs/utils/span.h b/src/libs/utils/span.h index b1fba814472..d21bb9ab00b 100644 --- a/src/libs/utils/span.h +++ b/src/libs/utils/span.h @@ -5,7 +5,9 @@ #include -#if __cplusplus >= 202002L +// The (Apple) Clang implementation of span is incomplete until LLVM 15 / Xcode 14.3 / macOS 13 +#if __cplusplus >= 202002L \ + && !(defined(__apple_build_version__) && __apple_build_version__ < 14030022) #include namespace Utils { @@ -22,6 +24,11 @@ QT_WARNING_PUSH #elif defined(Q_CC_GNU) || defined(Q_CC_CLANG) #pragma GCC system_header #endif + +// disable automatic usage of std::span in span-lite +// since we make that decision ourselves at the top of this header +#define span_CONFIG_SELECT_SPAN span_SPAN_NONSTD + #include <3rdparty/span/span.hpp> namespace Utils { using namespace nonstd; From 19feaad265f40df546917f7cbe00e2a19c7cec08 Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Wed, 6 Mar 2024 15:09:30 +0100 Subject: [PATCH 0042/1060] Android: Register AndroidDevice creator regardless of SDK state The AndroidDeviceFactory only registered the AndroidDevice creator function if the Android SDK was correctly set up. That check occurred only once during the Qt Creator start up sequence. As a consequence, Qt Creator had to be restarted after an initial set up of the Android SDK. Users are not notified of such requirement, and we actually don't want to enforce a restart. With this change, the AndroidDevice creator function is always registered, and the "Add Android Device" wizard always selectable. Users who try to add an Android device without having set up Android before get to see an info message box. Change-Id: I0600e36575c2dd075af9398597c3c8dab3bb243d Reviewed-by: hjk Reviewed-by: Christian Kandeler --- src/plugins/android/androiddevice.cpp | 35 +++++++++++++++------------ 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/plugins/android/androiddevice.cpp b/src/plugins/android/androiddevice.cpp index 1d87fa1ddd0..56ffbf45b9f 100644 --- a/src/plugins/android/androiddevice.cpp +++ b/src/plugins/android/androiddevice.cpp @@ -836,24 +836,27 @@ public: setCombinedIcon(":/android/images/androiddevicesmall.png", ":/android/images/androiddevice.png"); setConstructionFunction(&AndroidDevice::create); - if (androidConfig().sdkToolsOk()) { - setCreator([] { - AvdDialog dialog = AvdDialog(Core::ICore::dialogParent()); - if (dialog.exec() != QDialog::Accepted) - return IDevice::Ptr(); + setCreator([] { + if (!androidConfig().sdkToolsOk()) { + AndroidDeviceWidget::infoDialog(Tr::tr("Android support is not yet configured.")); + return IDevice::Ptr(); + } - const IDevice::Ptr dev = dialog.device(); - if (const auto androidDev = static_cast(dev.get())) { - qCDebug(androidDeviceLog, "Created new Android AVD id \"%s\".", - qPrintable(androidDev->avdName())); - } else { - AndroidDeviceWidget::criticalDialog( - Tr::tr("The device info returned from AvdDialog is invalid.")); - } + AvdDialog dialog = AvdDialog(Core::ICore::dialogParent()); + if (dialog.exec() != QDialog::Accepted) + return IDevice::Ptr(); - return IDevice::Ptr(dev); - }); - } + const IDevice::Ptr dev = dialog.device(); + if (const auto androidDev = static_cast(dev.get())) { + qCDebug(androidDeviceLog, "Created new Android AVD id \"%s\".", + qPrintable(androidDev->avdName())); + } else { + AndroidDeviceWidget::criticalDialog( + Tr::tr("The device info returned from AvdDialog is invalid.")); + } + + return IDevice::Ptr(dev); + }); } }; From 498625520a0e32e2f5b18754a0351997d7767ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20L=C3=B6hning?= Date: Thu, 7 Mar 2024 09:47:43 +0100 Subject: [PATCH 0043/1060] SquishTests: Don't try removing packages directories Seems they are not being created anymore. Change-Id: I8b48a848793fb73ea193918c14c322d6166b2053 Reviewed-by: Christian Stenger --- tests/system/shared/utils.py | 7 ------- tests/system/suite_WELP/tst_WELP03/test.py | 10 ---------- 2 files changed, 17 deletions(-) diff --git a/tests/system/shared/utils.py b/tests/system/shared/utils.py index 853c5f6fde0..2e4b5a1dae1 100644 --- a/tests/system/shared/utils.py +++ b/tests/system/shared/utils.py @@ -464,13 +464,6 @@ def setFixedHelpViewer(helpViewer): selectFromCombo(":Startup.contextHelpComboBox_QComboBox", mode) clickButton(waitForObject(":Options.OK_QPushButton")) -def removePackagingDirectory(projectPath): - qtcPackaging = os.path.join(projectPath, "qtc_packaging") - if os.path.exists(qtcPackaging): - test.log("Removing old packaging directory '%s'" % qtcPackaging) - deleteDirIfExists(qtcPackaging) - else: - test.log("Couldn't remove packaging directory '%s' - did not exist." % qtcPackaging) # returns the indices from a QAbstractItemModel def dumpIndices(model, parent=None, column=0): diff --git a/tests/system/suite_WELP/tst_WELP03/test.py b/tests/system/suite_WELP/tst_WELP03/test.py index 50f7b503cc7..8d4fa29a9bb 100644 --- a/tests/system/suite_WELP/tst_WELP03/test.py +++ b/tests/system/suite_WELP/tst_WELP03/test.py @@ -83,8 +83,6 @@ def main(): proFiles = [os.path.join(p, "opengl", "2dpainting", "2dpainting.pro") for p in QtPath.getPaths(QtPath.EXAMPLES)] cleanUpUserFiles(proFiles) - for p in proFiles: - removePackagingDirectory(os.path.dirname(p)) example = openExample(examplesLineEdit, "2d painting", "2D Painting.*", "2D Painting Example") if example is not None: @@ -96,17 +94,12 @@ def main(): waitFor("navTree.model().rowCount(navTree.rootIndex()) == 0", 2000) test.verify(not checkIfObjectItemExists(":Qt Creator_Utils::NavigationTreeView", "2dpainting"), "Verifying: The first example is closed.") - # clean up created packaging directories - for p in proFiles: - removePackagingDirectory(os.path.dirname(p)) # go to "Welcome" page and choose another example switchViewTo(ViewConstants.WELCOME) proFiles = [os.path.join(p, "widgets", "itemviews", "addressbook", "addressbook.pro") for p in QtPath.getPaths(QtPath.EXAMPLES)] cleanUpUserFiles(proFiles) - for p in proFiles: - removePackagingDirectory(os.path.dirname(p)) examplesLineEdit = waitForObject(search %(expect[1][0], expect[1][1])) example = openExample(examplesLineEdit, "address book", "(0000 )?Address Book.*", "Address Book Example", 3) @@ -122,8 +115,5 @@ def main(): waitFor("navTree.model().rowCount(navTree.rootIndex()) == 0", 2000) test.verify(not checkIfObjectItemExists(":Qt Creator_Utils::NavigationTreeView", "addressbook"), "Verifying: The second example is closed.") - # clean up created packaging directories - for p in proFiles: - removePackagingDirectory(os.path.dirname(p)) # exit Qt Creator invokeMenuItem("File", "Exit") From cdd85477fb890c16f106a34daabd63088fbd654a Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 22 Feb 2024 14:17:10 +0100 Subject: [PATCH 0044/1060] ClangTools: Put a clazy setting to its proper place We do not go out of our way to retain the old settings value, as the setting affects only the UI behavior in the same widget it is displayed in. Change-Id: Ie0d66b3909364e15a05013eddaf742b161941f67 Reviewed-by: David Schulz --- src/plugins/clangtools/clangtoolssettings.cpp | 4 +++- src/plugins/clangtools/clangtoolssettings.h | 2 ++ src/plugins/clangtools/diagnosticconfigswidget.cpp | 5 ++--- src/plugins/cppeditor/cppcodemodelsettings.cpp | 12 ------------ src/plugins/cppeditor/cppcodemodelsettings.h | 5 ----- 5 files changed, 7 insertions(+), 21 deletions(-) diff --git a/src/plugins/clangtools/clangtoolssettings.cpp b/src/plugins/clangtools/clangtoolssettings.cpp index c53fa394b6d..f66f35ff6fb 100644 --- a/src/plugins/clangtools/clangtoolssettings.cpp +++ b/src/plugins/clangtools/clangtoolssettings.cpp @@ -98,9 +98,11 @@ ClangToolsSettings::ClangToolsSettings() setSettingsGroup(Constants::SETTINGS_ID); clangTidyExecutable.setSettingsKey("ClangTidyExecutable"); - clazyStandaloneExecutable.setSettingsKey("ClazyStandaloneExecutable"); + enableLowerClazyLevels.setSettingsKey("EnableLowerClazyLevels"); + enableLowerClazyLevels.setDefaultValue(true); + readSettings(); } diff --git a/src/plugins/clangtools/clangtoolssettings.h b/src/plugins/clangtools/clangtoolssettings.h index 1c8656981df..eaaccc11883 100644 --- a/src/plugins/clangtools/clangtoolssettings.h +++ b/src/plugins/clangtools/clangtoolssettings.h @@ -71,6 +71,8 @@ public: Utils::FilePath executable(CppEditor::ClangToolType tool) const; void setExecutable(CppEditor::ClangToolType tool, const Utils::FilePath &path); + Utils::BoolAspect enableLowerClazyLevels{this}; + CppEditor::ClangDiagnosticConfigs diagnosticConfigs() const { return m_diagnosticConfigs; } void setDiagnosticConfigs(const CppEditor::ClangDiagnosticConfigs &configs) { m_diagnosticConfigs = configs; } diff --git a/src/plugins/clangtools/diagnosticconfigswidget.cpp b/src/plugins/clangtools/diagnosticconfigswidget.cpp index dcbcd70e13d..81aa6fb2305 100644 --- a/src/plugins/clangtools/diagnosticconfigswidget.cpp +++ b/src/plugins/clangtools/diagnosticconfigswidget.cpp @@ -10,7 +10,6 @@ #include "clangtoolsutils.h" #include "executableinfo.h" -#include #include #include @@ -1008,10 +1007,10 @@ DiagnosticConfigsWidget::DiagnosticConfigsWidget(const ClangDiagnosticConfigs &c connect(m_clazyChecks->enableLowerLevelsCheckBox, &QCheckBox::stateChanged, this, [this] { const bool enable = m_clazyChecks->enableLowerLevelsCheckBox->isChecked(); m_clazyTreeModel->setEnableLowerLevels(enable); - codeModelSettings()->setEnableLowerClazyLevels(enable); + ClangToolsSettings::instance()->enableLowerClazyLevels.setValue(enable); }); const Qt::CheckState checkEnableLowerClazyLevels - = codeModelSettings()->enableLowerClazyLevels() ? Qt::Checked : Qt::Unchecked; + = ClangToolsSettings::instance()->enableLowerClazyLevels.value() ? Qt::Checked : Qt::Unchecked; m_clazyChecks->enableLowerLevelsCheckBox->setCheckState(checkEnableLowerClazyLevels); m_tidyChecks = new TidyChecksWidget; diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 07d3d926584..38f57ddba81 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -32,7 +32,6 @@ using namespace Utils; namespace CppEditor { static Id initialClangDiagnosticConfigId() { return Constants::CPP_CLANG_DIAG_CONFIG_BUILDSYSTEM; } -static Key enableLowerClazyLevelsKey() { return "enableLowerClazyLevels"; } static Key pchUsageKey() { return Constants::CPPEDITOR_MODEL_MANAGER_PCH_USAGE; } static Key interpretAmbiguousHeadersAsCHeadersKey() { return Constants::CPPEDITOR_INTERPRET_AMBIGIUOUS_HEADERS_AS_C_HEADERS; } @@ -79,7 +78,6 @@ bool operator==(const CppEditor::CppCodeModelSettings::Data &s1, && s1.skipIndexingBigFiles == s2.skipIndexingBigFiles && s1.useBuiltinPreprocessor == s2.useBuiltinPreprocessor && s1.indexerFileSizeLimitInMb == s2.indexerFileSizeLimitInMb - && s1.enableLowerClazyLevels == s2.enableLowerClazyLevels && s1.categorizeFindReferences == s2.categorizeFindReferences && s1.ignoreFiles == s2.ignoreFiles && s1.ignorePattern == s2.ignorePattern; } @@ -87,7 +85,6 @@ bool operator==(const CppEditor::CppCodeModelSettings::Data &s1, Store CppCodeModelSettings::Data::toMap() const { Store store; - store.insert(enableLowerClazyLevelsKey(), enableLowerClazyLevels); store.insert(pchUsageKey(), pchUsage); store.insert(interpretAmbiguousHeadersAsCHeadersKey(), interpretAmbigiousHeadersAsC); store.insert(skipIndexingBigFilesKey(), skipIndexingBigFiles); @@ -101,8 +98,6 @@ Store CppCodeModelSettings::Data::toMap() const void CppCodeModelSettings::Data::fromMap(const Utils::Store &store) { const CppCodeModelSettings::Data def; - enableLowerClazyLevels - = store.value(enableLowerClazyLevelsKey(), def.enableLowerClazyLevels).toBool(); pchUsage = static_cast(store.value(pchUsageKey(), def.pchUsage).toInt()); interpretAmbigiousHeadersAsC = store .value(interpretAmbiguousHeadersAsCHeadersKey(), @@ -139,13 +134,6 @@ void CppCodeModelSettings::setData(const Data &data) } } -void CppCodeModelSettings::setEnableLowerClazyLevels(bool enable) -{ - Data d = data(); - d.enableLowerClazyLevels = enable; - setData(d); -} - void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { Data d = data(); diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index b13acb3f053..5989c14f865 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -47,7 +47,6 @@ public: bool skipIndexingBigFiles = true; bool useBuiltinPreprocessor = true; int indexerFileSizeLimitInMb = 5; - bool enableLowerClazyLevels = true; // For UI behavior only bool categorizeFindReferences = false; // Ephemeral! bool ignoreFiles = false; QString ignorePattern; @@ -58,7 +57,6 @@ public: void setData(const Data &data); Data data() const { return m_data; } - bool enableLowerClazyLevels() const { return m_data.enableLowerClazyLevels; } PCHUsage pchUsage() const { return m_data.pchUsage; } bool interpretAmbigiousHeadersAsC() const { return m_data.interpretAmbigiousHeadersAsC; } bool skipIndexingBigFiles() const { return m_data.skipIndexingBigFiles; } @@ -68,9 +66,6 @@ public: bool ignoreFiles() const { return m_data.ignoreFiles; } QString ignorePattern() const { return m_data.ignorePattern; } - // FIXME: Doesn't belong here. - void setEnableLowerClazyLevels(bool enable); - void setCategorizeFindReferences(bool categorize); signals: From 2524e2adb3fb9a3a840a20422798aec0e20fc614 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 23 Feb 2024 14:31:30 +0100 Subject: [PATCH 0045/1060] CppEditor: Let users provide statement macros Like ClangFormat has. Fixes: QTCREATORBUG-15069 Fixes: QTCREATORBUG-18789 Change-Id: I0ffb70be502d1c73aaaf436484ddc6704f152621 Reviewed-by: David Schulz --- src/plugins/cppeditor/cppcodeformatter.cpp | 5 +++- src/plugins/cppeditor/cppcodeformatter.h | 2 ++ .../cppeditor/cppcodestylesettings.cpp | 4 +++ src/plugins/cppeditor/cppcodestylesettings.h | 1 + .../cppeditor/cppcodestylesettingspage.cpp | 27 +++++++++++++++++-- .../codeformatter/tst_codeformatter.cpp | 18 +++++++++++++ 6 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/plugins/cppeditor/cppcodeformatter.cpp b/src/plugins/cppeditor/cppcodeformatter.cpp index ca14d22a7c1..3d015394406 100644 --- a/src/plugins/cppeditor/cppcodeformatter.cpp +++ b/src/plugins/cppeditor/cppcodeformatter.cpp @@ -842,7 +842,8 @@ bool CodeFormatter::tryDeclaration() if (tokenText.startsWith(QLatin1String("Q_")) || tokenText.startsWith(QLatin1String("QT_")) || tokenText.startsWith(QLatin1String("QML_")) - || tokenText.startsWith(QLatin1String("QDOC_"))) { + || tokenText.startsWith(QLatin1String("QDOC_")) + || m_statementMacros.contains(tokenText)) { enter(qt_like_macro); return true; } @@ -1118,6 +1119,7 @@ QtStyleCodeFormatter::QtStyleCodeFormatter(const TabSettings &tabSettings, , m_styleSettings(settings) { setTabSize(tabSettings.m_tabSize); + setStatementMacros(m_styleSettings.statementMacros); } void QtStyleCodeFormatter::setTabSettings(const TabSettings &tabSettings) @@ -1129,6 +1131,7 @@ void QtStyleCodeFormatter::setTabSettings(const TabSettings &tabSettings) void QtStyleCodeFormatter::setCodeStyleSettings(const CppCodeStyleSettings &settings) { m_styleSettings = settings; + setStatementMacros(m_styleSettings.statementMacros); } void QtStyleCodeFormatter::saveBlockData(QTextBlock *block, const BlockData &data) const diff --git a/src/plugins/cppeditor/cppcodeformatter.h b/src/plugins/cppeditor/cppcodeformatter.h index 828fec763b0..98aacbc55ed 100644 --- a/src/plugins/cppeditor/cppcodeformatter.h +++ b/src/plugins/cppeditor/cppcodeformatter.h @@ -40,6 +40,7 @@ public: void indentForNewLineAfter(const QTextBlock &block, int *indent, int *padding); void setTabSize(int tabSize); + void setStatementMacros(const QStringList ¯os) { m_statementMacros = macros; } void invalidateCache(QTextDocument *document); @@ -224,6 +225,7 @@ private: int m_paddingDepth = 0; int m_tabSize = 4; + QStringList m_statementMacros; friend class Internal::CppCodeFormatterData; }; diff --git a/src/plugins/cppeditor/cppcodestylesettings.cpp b/src/plugins/cppeditor/cppcodestylesettings.cpp index 733f066eaca..5499005c62b 100644 --- a/src/plugins/cppeditor/cppcodestylesettings.cpp +++ b/src/plugins/cppeditor/cppcodestylesettings.cpp @@ -17,6 +17,7 @@ #include +static const char statementMacrosKey[] = "StatementMacros"; static const char indentBlockBracesKey[] = "IndentBlockBraces"; static const char indentBlockBodyKey[] = "IndentBlockBody"; static const char indentClassBracesKey[] = "IndentClassBraces"; @@ -50,6 +51,7 @@ CppCodeStyleSettings::CppCodeStyleSettings() = default; Store CppCodeStyleSettings::toMap() const { return { + {statementMacrosKey, statementMacros}, {indentBlockBracesKey, indentBlockBraces}, {indentBlockBodyKey, indentBlockBody}, {indentClassBracesKey, indentClassBraces}, @@ -76,6 +78,7 @@ Store CppCodeStyleSettings::toMap() const void CppCodeStyleSettings::fromMap(const Store &map) { + statementMacros = map.value(statementMacrosKey, statementMacros).toStringList(); indentBlockBraces = map.value(indentBlockBracesKey, indentBlockBraces).toBool(); indentBlockBody = map.value(indentBlockBodyKey, indentBlockBody).toBool(); indentClassBraces = map.value(indentClassBracesKey, indentClassBraces).toBool(); @@ -128,6 +131,7 @@ bool CppCodeStyleSettings::equals(const CppCodeStyleSettings &rhs) const && bindStarToRightSpecifier == rhs.bindStarToRightSpecifier && extraPaddingForConditionsIfConfusingAlign == rhs.extraPaddingForConditionsIfConfusingAlign && alignAssignments == rhs.alignAssignments + && statementMacros == rhs.statementMacros && preferGetterNameWithoutGetPrefix == rhs.preferGetterNameWithoutGetPrefix #ifdef WITH_TESTS && forceFormatting == rhs.forceFormatting diff --git a/src/plugins/cppeditor/cppcodestylesettings.h b/src/plugins/cppeditor/cppcodestylesettings.h index 8369df099e8..a798ca7434d 100644 --- a/src/plugins/cppeditor/cppcodestylesettings.h +++ b/src/plugins/cppeditor/cppcodestylesettings.h @@ -18,6 +18,7 @@ class CPPEDITOR_EXPORT CppCodeStyleSettings public: CppCodeStyleSettings(); + QStringList statementMacros; bool indentBlockBraces = false; bool indentBlockBody = true; bool indentClassBraces = false; diff --git a/src/plugins/cppeditor/cppcodestylesettingspage.cpp b/src/plugins/cppeditor/cppcodestylesettingspage.cpp index 74f505d663c..c1dfcebb3b3 100644 --- a/src/plugins/cppeditor/cppcodestylesettingspage.cpp +++ b/src/plugins/cppeditor/cppcodestylesettingspage.cpp @@ -163,8 +163,9 @@ public: , m_bindStarToRightSpecifier(createCheckBox(Tr::tr("Right const/volatile"), Tr::tr("This does not apply to references."))) , m_tabSettingsWidget(new TabSettingsWidget) + , m_statementMacros(new QPlainTextEdit) { - QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(m_tabSettingsWidget->sizePolicy().hasHeightForWidth()); @@ -241,11 +242,25 @@ public: } }; + sizePolicy.setVerticalPolicy(QSizePolicy::Preferred); + m_statementMacros->setToolTip( + Tr::tr("Macros that can be used as statements without a trailing semicolon")); + m_statementMacros->setSizePolicy(sizePolicy); + const Group statementMacrosGroup { + title(Tr::tr("Statement macros")), + Column { m_statementMacros} + }; + QObject::connect(m_statementMacros, &QPlainTextEdit::textChanged, q, [this] { + m_handlingStatementMacroChange = true; + q->slotCodeStyleSettingsChanged(); + m_handlingStatementMacroChange = false; + }); + Row { TabWidget { bindTo(&m_categoryTab), Tab { Tr::tr("General"), - Row { Column { m_tabSettingsWidget, st }, createPreview(0) } + Row { Column { m_tabSettingsWidget, statementMacrosGroup }, createPreview(0) } }, Tab { Tr::tr("Content"), Row { contentGroup, createPreview(1) } }, Tab { Tr::tr("Braces"), Row { bracesGroup, createPreview(2) } }, @@ -310,6 +325,8 @@ public: QTabWidget *m_categoryTab = nullptr; TabSettingsWidget *m_tabSettingsWidget = nullptr; + QPlainTextEdit * const m_statementMacros; + bool m_handlingStatementMacroChange = false; }; CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent) @@ -361,6 +378,10 @@ CppCodeStyleSettings CppCodeStylePreferencesWidget::cppCodeStyleSettings() const { CppCodeStyleSettings set; + set.statementMacros + = Utils::transform(d->m_statementMacros->toPlainText().trimmed().split('\n', + Qt::SkipEmptyParts), + [](const QString &line) { return line.trimmed(); }); set.indentBlockBraces = d->m_indentBlockBraces->isChecked(); set.indentBlockBody = d->m_indentBlockBody->isChecked(); set.indentClassBraces = d->m_indentClassBraces->isChecked(); @@ -399,6 +420,8 @@ void CppCodeStylePreferencesWidget::setCodeStyleSettings(const CppCodeStyleSetti { const bool wasBlocked = m_blockUpdates; m_blockUpdates = true; + if (!d->m_handlingStatementMacroChange) + d->m_statementMacros->setPlainText(s.statementMacros.join('\n')); d->m_indentBlockBraces->setChecked(s.indentBlockBraces); d->m_indentBlockBody->setChecked(s.indentBlockBody); d->m_indentClassBraces->setChecked(s.indentClassBraces); diff --git a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp index b61f91fc3bc..29ecbb58ed9 100644 --- a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp +++ b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp @@ -108,6 +108,7 @@ private Q_SLOTS: void lambdaWithReturnType(); void structuredBinding(); void subscriptOperatorInFunctionCall(); + void statementMacros(); }; struct Line { @@ -2213,6 +2214,23 @@ void tst_CodeFormatter::subscriptOperatorInFunctionCall() checkIndent(data); } +void tst_CodeFormatter::statementMacros() +{ + QList data; + data << Line("MY_MACRO") + << Line("template") + << Line("~ class C;"); + checkIndent(data); + + data.clear(); + CppCodeStyleSettings settings; + settings.statementMacros << "MY_MACRO"; + data << Line("MY_MACRO") + << Line("template") + << Line("class C;"); + checkIndent(data, settings); +} + QTEST_GUILESS_MAIN(tst_CodeFormatter) #include "tst_codeformatter.moc" From 2f78fd4358f0126ac25a17ceeff259c7f53db0de Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Tue, 26 Dec 2023 14:45:10 +0200 Subject: [PATCH 0046/1060] FileIteratorWrapper: simplify constructor The other two parameters, QDir::Filter and nameFilters string list, can be retrieved from the baseIterator. Change-Id: Id33a95f3b490e8f5846e9728fc66da0df5195be9 Reviewed-by: Marcus Tillmanns --- src/libs/utils/fsengine/fileiteratordevicesappender.h | 6 ++---- src/libs/utils/fsengine/rootinjectfsengine.h | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index a28f1190806..28c308ddabc 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -36,10 +36,8 @@ class FileIteratorWrapper : public QAbstractFileEngineIterator }; public: - FileIteratorWrapper(std::unique_ptr &&baseIterator, - QDir::Filters filters, - const QStringList &filterNames) - : QAbstractFileEngineIterator(filters, filterNames) + FileIteratorWrapper(std::unique_ptr &&baseIterator) + : QAbstractFileEngineIterator(baseIterator->filters(), baseIterator->nameFilters()) , m_baseIterator(std::move(baseIterator)) {} diff --git a/src/libs/utils/fsengine/rootinjectfsengine.h b/src/libs/utils/fsengine/rootinjectfsengine.h index 6e40f5f742b..d57747dab96 100644 --- a/src/libs/utils/fsengine/rootinjectfsengine.h +++ b/src/libs/utils/fsengine/rootinjectfsengine.h @@ -20,7 +20,7 @@ public: { std::unique_ptr baseIterator( QFSFileEngine::beginEntryList(filters, filterNames)); - return new FileIteratorWrapper(std::move(baseIterator), filters, filterNames); + return new FileIteratorWrapper(std::move(baseIterator)); } }; From 5760654674bb5a864a6b5ce9032ae9ed5df5a9ad Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Wed, 6 Mar 2024 20:09:08 +0200 Subject: [PATCH 0047/1060] FileIteratorWrapper: remove redundant if statement Change-Id: I5b9a50802adc3d2cfc48748235a7cd6ee01fa5a4 Reviewed-by: Marcus Tillmanns --- src/libs/utils/fsengine/fileiteratordevicesappender.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index 28c308ddabc..329d76613e8 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -106,9 +106,6 @@ private: void checkStatus() const { - if (m_status == State::NotIteratingRoot) { - return; - } if (m_status == State::IteratingRoot) { if (m_baseIterator->hasNext() == false) { m_status = State::BaseIteratorEnd; From 71e6916b37ed2dd269c97197d0a6d5bb43402882 Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Wed, 6 Mar 2024 20:25:46 +0200 Subject: [PATCH 0048/1060] FileIteratorWrapper: fix typo in "__qtc__devices__" It should be what FilePath::specialRootName() returns, "__qtc_devices__". Looks like nothing used the string retured by next() so this didn't cause issues before. Change-Id: Ib9c48d8ea032b1ca7d9ec08003f9d51c5a2ae528 Reviewed-by: Marcus Tillmanns --- src/libs/utils/fsengine/fileiteratordevicesappender.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index 329d76613e8..77864117f46 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -52,7 +52,7 @@ public: if (m_status == State::BaseIteratorEnd) { m_status = State::Ended; - return "__qtc__devices__"; + return FilePath::specialRootName(); } return m_baseIterator->next(); From 8295f11576285166ad6b284a7718f492f7c1c864 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 27 Feb 2024 12:41:05 +0100 Subject: [PATCH 0049/1060] CppEditor: Skip redundant check for large files The only caller of refreshSourceFiles() is updateSourceFiles(), which already does the respective filtering. Amends 1960503ae994d14d79bad6507f2ed692e5c2230d. Change-Id: Ief7b2a728138c3693276edbd1912fa59cadaf4a6 Reviewed-by: Reviewed-by: David Schulz --- src/plugins/cppeditor/cppindexingsupport.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/plugins/cppeditor/cppindexingsupport.cpp b/src/plugins/cppeditor/cppindexingsupport.cpp index 3a418a5b782..14ce23c79ab 100644 --- a/src/plugins/cppeditor/cppindexingsupport.cpp +++ b/src/plugins/cppeditor/cppindexingsupport.cpp @@ -44,7 +44,6 @@ public: ProjectExplorer::HeaderPaths headerPaths; WorkingCopy workingCopy; QSet sourceFiles; - int indexerFileSizeLimitInMb = -1; }; class WriteTaskFileForDiagnostics @@ -161,7 +160,6 @@ static void indexFindErrors(QPromise &promise, const ParseParams params) static void index(QPromise &promise, const ParseParams params) { QScopedPointer sourceProcessor(CppModelManager::createSourceProcessor()); - sourceProcessor->setFileSizeLimitInMb(params.indexerFileSizeLimitInMb); sourceProcessor->setHeaderPaths(params.headerPaths); sourceProcessor->setWorkingCopy(params.workingCopy); @@ -305,7 +303,6 @@ QFuture CppIndexingSupport::refreshSourceFiles(const QSet &source CppModelManager::ProgressNotificationMode mode) { ParseParams params; - params.indexerFileSizeLimitInMb = indexerFileSizeLimitInMb(); params.headerPaths = CppModelManager::headerPaths(); params.workingCopy = CppModelManager::workingCopy(); params.sourceFiles = sourceFiles; From 8c5c849b71dd2175acfdf70d761966c39bbad67d Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 7 Mar 2024 10:50:20 +0100 Subject: [PATCH 0050/1060] CppEditor: Refactor AddBracesToControlStatement quickfix Preparation for bracifying if-else chains. No functional changes. Change-Id: Idc101131c02aac88598a6de1f8f511f89c958346 Reviewed-by: Qt CI Bot Reviewed-by: Christian Stenger Reviewed-by: --- src/plugins/cppeditor/cppquickfixes.cpp | 34 ++++++++++++------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp index df6c76bcf60..383c5245ae1 100644 --- a/src/plugins/cppeditor/cppquickfixes.cpp +++ b/src/plugins/cppeditor/cppquickfixes.cpp @@ -808,9 +808,10 @@ int tokenToInsertOpeningBraceAfter(const Statement *statement) template class AddBracesToControlStatementOp : public CppQuickFixOperation { public: - AddBracesToControlStatementOp(const CppQuickFixInterface &interface, const Statement *statement) + AddBracesToControlStatementOp(const CppQuickFixInterface &interface, + const QList &statements) : CppQuickFixOperation(interface, 0) - , _statement(statement) + , m_statements(statements) { setDescription(Tr::tr("Add Curly Braces")); } @@ -821,26 +822,24 @@ public: CppRefactoringFilePtr currentFile = refactoring.cppFile(filePath()); ChangeSet changes; - - const int start = currentFile->endOf(tokenToInsertOpeningBraceAfter(_statement)); - changes.insert(start, QLatin1String(" {")); - - if constexpr (std::is_same_v) { - const int end = currentFile->startOf(_statement->while_token); - changes.insert(end, QLatin1String("} ")); - } else { - const int end = currentFile->endOf(_statement->statement->lastToken() - 1); - changes.insert(end, QLatin1String("\n}")); + for (Statement * const statement : m_statements) { + const int start = currentFile->endOf(tokenToInsertOpeningBraceAfter(statement)); + changes.insert(start, QLatin1String(" {")); + if constexpr (std::is_same_v) { + const int end = currentFile->startOf(statement->while_token); + changes.insert(end, QLatin1String("} ")); + } else { + const int end = currentFile->endOf(statement->statement->lastToken() - 1); + changes.insert(end, QLatin1String("\n}")); + } } - // TODO: For if statements, also bracify all else cases. - // Also check all else cases in the factory. currentFile->setChangeSet(changes); currentFile->apply(); } private: - const Statement * const _statement; + const QList m_statements; }; } // anonymous namespace @@ -854,7 +853,7 @@ bool checkControlStatementsHelper(const CppQuickFixInterface &interface, QuickFi if (interface.isCursorOn(triggerToken(statement)) && statement->statement && !statement->statement->asCompoundStatement()) { - result << new AddBracesToControlStatementOp(interface, statement); + result << new AddBracesToControlStatementOp(interface, QList{statement}); } return true; } @@ -865,7 +864,8 @@ void checkControlStatements(const CppQuickFixInterface &interface, QuickFixOpera (... || checkControlStatementsHelper(interface, result)); } -void AddBracesToControlStatement::doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) +void AddBracesToControlStatement::doMatch(const CppQuickFixInterface &interface, + QuickFixOperations &result) { if (interface.path().isEmpty()) return; From 2607e07b20c6844b14c271ef01d14fb4988560ce Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 23 Feb 2024 17:09:58 +0100 Subject: [PATCH 0051/1060] CppEditor: Try to handle "declaration macros" Fixes: QTCREATORBUG-13640 Change-Id: I6566add09011388627c62394dfc3e47d29bac9cd Reviewed-by: Reviewed-by: David Schulz Reviewed-by: Christian Kandeler --- src/plugins/clangformat/clangformatutils.cpp | 1 + src/plugins/cppeditor/cppcodeformatter.cpp | 32 +++++++++++++++----- src/plugins/cppeditor/cppcodeformatter.h | 2 ++ 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/plugins/clangformat/clangformatutils.cpp b/src/plugins/clangformat/clangformatutils.cpp index 747c30c2a57..7ccc9ad7188 100644 --- a/src/plugins/clangformat/clangformatutils.cpp +++ b/src/plugins/clangformat/clangformatutils.cpp @@ -346,6 +346,7 @@ void addQtcStatementMacros(clang::format::FormatStyle &style) "Q_GADGET", "Q_GADGET_EXPORT", "Q_INTERFACES", + "Q_LOGGING_CATEGORY", "Q_MOC_INCLUDE", "Q_NAMESPACE", "Q_NAMESPACE_EXPORT", diff --git a/src/plugins/cppeditor/cppcodeformatter.cpp b/src/plugins/cppeditor/cppcodeformatter.cpp index 3d015394406..447a5a04871 100644 --- a/src/plugins/cppeditor/cppcodeformatter.cpp +++ b/src/plugins/cppeditor/cppcodeformatter.cpp @@ -152,6 +152,12 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block) case T_GREATER_GREATER: break; case T_LBRACKET: break; case T_NAMESPACE: leave(); enter(namespace_start); break; + case T_IDENTIFIER: + if (isStatementMacroOrEquivalent()) { + enter(qt_like_macro); + break; + } + [[fallthrough]]; default: tryExpression(true); break; } break; @@ -272,7 +278,14 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block) case T_SEMICOLON: leave(true); break; case T_LBRACE: enter(brace_list_open); break; case T_RBRACE: leave(true); continue; - case T_RPAREN: leave(); break; + case T_RPAREN: + leave(); + if (m_currentState.top().type == qt_like_macro && m_currentState.size() > 1 + && m_currentState.at(m_currentState.size() - 2).type == declaration_start) { + leave(); + leave(); + } + break; default: tryExpression(); break; } break; @@ -754,6 +767,16 @@ void CodeFormatter::correctIndentation(const QTextBlock &block) adjustIndent(m_tokens, lexerState, &m_indentDepth, &m_paddingDepth); } +bool CodeFormatter::isStatementMacroOrEquivalent() const +{ + const QStringView tokenText = currentTokenText(); + return tokenText.startsWith(QLatin1String("Q_")) + || tokenText.startsWith(QLatin1String("QT_")) + || tokenText.startsWith(QLatin1String("QML_")) + || tokenText.startsWith(QLatin1String("QDOC_")) + || m_statementMacros.contains(tokenText); +} + bool CodeFormatter::tryExpression(bool alsoExpression) { int newState = -1; @@ -838,12 +861,7 @@ bool CodeFormatter::tryDeclaration() return true; case T_IDENTIFIER: if (m_tokenIndex == 0) { - const QStringView tokenText = currentTokenText(); - if (tokenText.startsWith(QLatin1String("Q_")) - || tokenText.startsWith(QLatin1String("QT_")) - || tokenText.startsWith(QLatin1String("QML_")) - || tokenText.startsWith(QLatin1String("QDOC_")) - || m_statementMacros.contains(tokenText)) { + if (isStatementMacroOrEquivalent()) { enter(qt_like_macro); return true; } diff --git a/src/plugins/cppeditor/cppcodeformatter.h b/src/plugins/cppeditor/cppcodeformatter.h index 98aacbc55ed..93d32faf263 100644 --- a/src/plugins/cppeditor/cppcodeformatter.h +++ b/src/plugins/cppeditor/cppcodeformatter.h @@ -209,6 +209,8 @@ private: void leave(bool statementDone = false); void correctIndentation(const QTextBlock &block); + bool isStatementMacroOrEquivalent() const; + private: static QStack initialState(); From 1de045f687213fca17f07a17f8db60cc107efe8f Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 26 Feb 2024 16:34:32 +0100 Subject: [PATCH 0052/1060] CppEditor: Move some convenience functions to CppCodeModelSettings class Change-Id: I0af8560c23374ce4f6c46f98d498d44f7cb50db3 Reviewed-by: Reviewed-by: David Schulz --- src/plugins/clangcodemodel/clangdclient.cpp | 14 ++++++++--- src/plugins/clangcodemodel/clangutils.cpp | 2 +- .../clangcodemodel/test/clangdtests.cpp | 2 +- src/plugins/clangtools/clangtoolrunner.cpp | 6 +++-- .../cppeditor/baseeditordocumentprocessor.cpp | 6 ++--- .../builtineditordocumentprocessor.cpp | 9 ++++--- .../cppeditor/compileroptionsbuilder.h | 2 +- .../cppeditor/cppcodemodelsettings.cpp | 25 ++++++++++++++----- src/plugins/cppeditor/cppcodemodelsettings.h | 8 +++--- .../cppeditor/cppcodemodelsettingspage.cpp | 5 ++-- src/plugins/cppeditor/cppeditorplugin.cpp | 4 +-- src/plugins/cppeditor/cppfindreferences.cpp | 7 +++--- src/plugins/cppeditor/cppindexingsupport.cpp | 1 + src/plugins/cppeditor/cppmodelmanager.cpp | 12 +++++---- src/plugins/cppeditor/cpptoolsreuse.cpp | 24 ------------------ src/plugins/cppeditor/cpptoolsreuse.h | 6 ----- 16 files changed, 66 insertions(+), 67 deletions(-) diff --git a/src/plugins/clangcodemodel/clangdclient.cpp b/src/plugins/clangcodemodel/clangdclient.cpp index b36ff8a4258..23dd71af16a 100644 --- a/src/plugins/clangcodemodel/clangdclient.cpp +++ b/src/plugins/clangcodemodel/clangdclient.cpp @@ -418,7 +418,8 @@ ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir, c CppEditor::CompilerOptionsBuilder optionsBuilder = clangOptionsBuilder( *CppEditor::CppModelManager::fallbackProjectPart(), warningsConfigForProject(nullptr), includeDir, {}); - const CppEditor::UsePrecompiledHeaders usePch = CppEditor::getPchUsage(); + const CppEditor::UsePrecompiledHeaders usePch + = CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders(); const QJsonArray projectPartOptions = fullProjectPartOptions( optionsBuilder, globalClangOptions()); const QJsonArray clangOptions = clangOptionsForFile({}, optionsBuilder.projectPart(), @@ -599,7 +600,7 @@ void ClangdClient::findUsages(const CppEditor::CursorInEditor &cursor, } } - const bool categorize = CppEditor::codeModelSettings()->categorizeFindReferences(); + const bool categorize = CppEditor::CppCodeModelSettings::instance().categorizeFindReferences(); // If it's a "normal" symbol, go right ahead. if (searchTerm != "operator" && Utils::allOf(searchTerm, [](const QChar &c) { @@ -919,8 +920,13 @@ void ClangdClient::updateParserConfig(const Utils::FilePath &filePath, CppEditor::ProjectFile::classify(filePath.toString())); const QJsonArray projectPartOptions = fullProjectPartOptions( optionsBuilder, globalClangOptions()); - addToCompilationDb(cdbChanges, *projectPart, CppEditor::getPchUsage(), projectPartOptions, - filePath.parentDir(), file, optionsBuilder.isClStyle()); + addToCompilationDb(cdbChanges, + *projectPart, + CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders(), + projectPartOptions, + filePath.parentDir(), + file, + optionsBuilder.isClStyle()); QJsonObject settings; addCompilationDb(settings, cdbChanges); DidChangeConfigurationParams configChangeParams; diff --git a/src/plugins/clangcodemodel/clangutils.cpp b/src/plugins/clangcodemodel/clangutils.cpp index a9b19fa2752..a718a9ed966 100644 --- a/src/plugins/clangcodemodel/clangutils.cpp +++ b/src/plugins/clangcodemodel/clangutils.cpp @@ -166,7 +166,7 @@ GenerateCompilationDbResult generateCompilationDB(QList p } compileCommandsFile.write("["); - const UsePrecompiledHeaders usePch = getPchUsage(); + const UsePrecompiledHeaders usePch = CppCodeModelSettings::instance().usePrecompiledHeaders(); const QJsonArray jsonProjectOptions = QJsonArray::fromStringList(projectOptions); for (const ProjectInfo::ConstPtr &projectInfo : std::as_const(projectInfoList)) { QTC_ASSERT(projectInfo, continue); diff --git a/src/plugins/clangcodemodel/test/clangdtests.cpp b/src/plugins/clangcodemodel/test/clangdtests.cpp index d4dd092b837..88a3176a6b2 100644 --- a/src/plugins/clangcodemodel/test/clangdtests.cpp +++ b/src/plugins/clangcodemodel/test/clangdtests.cpp @@ -249,7 +249,7 @@ private: void ClangdTestFindReferences::initTestCase() { ClangdTest::initTestCase(); - CppEditor::codeModelSettings()->setCategorizeFindReferences(true); + CppEditor::CppCodeModelSettings::instance().setCategorizeFindReferences(true); connect(client(), &ClangdClient::foundReferences, this, [this](const SearchResultItems &results) { if (results.isEmpty()) diff --git a/src/plugins/clangtools/clangtoolrunner.cpp b/src/plugins/clangtools/clangtoolrunner.cpp index 46fdf7c2730..13fdfba742f 100644 --- a/src/plugins/clangtools/clangtoolrunner.cpp +++ b/src/plugins/clangtools/clangtoolrunner.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -25,7 +26,6 @@ #include #include - static Q_LOGGING_CATEGORY(LOG, "qtc.clangtools.runner", QtWarningMsg) using namespace CppEditor; @@ -49,7 +49,9 @@ AnalyzeUnit::AnalyzeUnit(const FileInfo &fileInfo, actualClangIncludeDir); file = fileInfo.file; arguments = extraClangToolsPrependOptions(); - arguments.append(optionsBuilder.build(fileInfo.kind, CppEditor::getPchUsage())); + arguments.append( + optionsBuilder.build(fileInfo.kind, + CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders())); arguments.append(extraClangToolsAppendOptions()); } diff --git a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp index d7da8251ee8..d377a25337b 100644 --- a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp @@ -35,9 +35,9 @@ BaseEditorDocumentProcessor::~BaseEditorDocumentProcessor() = default; void BaseEditorDocumentProcessor::run(bool projectsUpdated) { - const Utils::Language languagePreference = codeModelSettings()->interpretAmbigiousHeadersAsC() - ? Utils::Language::C - : Utils::Language::Cxx; + const Utils::Language languagePreference + = CppCodeModelSettings::instance().interpretAmbigiousHeadersAsC() ? Utils::Language::C + : Utils::Language::Cxx; runImpl({CppModelManager::workingCopy(), ProjectExplorer::ProjectManager::startupProject(), diff --git a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp index b934d1e7aed..bd820c9222f 100644 --- a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp @@ -143,16 +143,17 @@ QList toTextEditorBlocks( BuiltinEditorDocumentProcessor::BuiltinEditorDocumentProcessor(TextEditor::TextDocument *document) : BaseEditorDocumentProcessor(document->document(), document->filePath()) - , m_parser(new BuiltinEditorDocumentParser(document->filePath(), indexerFileSizeLimitInMb())) + , m_parser(new BuiltinEditorDocumentParser(document->filePath(), + CppCodeModelSettings::instance() + .effectiveIndexerFileSizeLimitInMb())) , m_codeWarningsUpdated(false) , m_semanticHighlighter(new SemanticHighlighter(document)) { using namespace Internal; - const CppCodeModelSettings *cms = &cppCodeModelSettings(); - BaseEditorDocumentParser::Configuration config = m_parser->configuration(); - config.usePrecompiledHeaders = cms->pchUsage() != CppCodeModelSettings::PchUse_None; + config.usePrecompiledHeaders = CppCodeModelSettings::instance().pchUsage() + != CppCodeModelSettings::PchUse_None; m_parser->setConfiguration(config); m_semanticHighlighter->setHighlightingRunner( diff --git a/src/plugins/cppeditor/compileroptionsbuilder.h b/src/plugins/cppeditor/compileroptionsbuilder.h index 3a8c1446a52..3c72dee2c64 100644 --- a/src/plugins/cppeditor/compileroptionsbuilder.h +++ b/src/plugins/cppeditor/compileroptionsbuilder.h @@ -9,7 +9,7 @@ namespace CppEditor { -enum class UsePrecompiledHeaders : char { Yes, No }; +enum class UsePrecompiledHeaders { Yes, No }; enum class UseSystemHeader : char { Yes, No }; enum class UseTweakedHeaderPaths : char { Yes, Tools, No }; enum class UseToolchainMacros : char { Yes, No }; diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 38f57ddba81..8a28fcf691c 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -4,6 +4,7 @@ #include "cppcodemodelsettings.h" #include "clangdiagnosticconfigsmodel.h" +#include "compileroptionsbuilder.h" #include "cppeditorconstants.h" #include "cppeditortr.h" #include "cpptoolsreuse.h" @@ -125,6 +126,12 @@ void CppCodeModelSettings::toSettings(QtcSettings *s) emit changed(); // TODO: Why? } +CppCodeModelSettings &CppCodeModelSettings::instance() +{ + static CppCodeModelSettings theCppCodeModelSettings(Core::ICore::settings()); + return theCppCodeModelSettings; +} + void CppCodeModelSettings::setData(const Data &data) { if (m_data != data) { @@ -134,6 +141,18 @@ void CppCodeModelSettings::setData(const Data &data) } } +UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders() const +{ + if (instance().pchUsage() == CppCodeModelSettings::PchUse_None) + return UsePrecompiledHeaders::No; + return UsePrecompiledHeaders::Yes; +} + +int CppCodeModelSettings::effectiveIndexerFileSizeLimitInMb() const +{ + return instance().skipIndexingBigFiles() ? instance().indexerFileSizeLimitInMb() : -1; +} + void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { Data d = data(); @@ -578,10 +597,4 @@ int ClangdSettings::Data::defaultCompletionResults() return ok ? userValue : 100; } -CppCodeModelSettings &cppCodeModelSettings() -{ - static CppCodeModelSettings theCppCodeModelSettings(Core::ICore::settings()); - return theCppCodeModelSettings; -} - } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index 5989c14f865..c76f3318f20 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -22,6 +22,7 @@ class MacroExpander; } // namespace Utils namespace CppEditor { +enum class UsePrecompiledHeaders; class CPPEDITOR_EXPORT CppCodeModelSettings : public QObject { @@ -52,16 +53,18 @@ public: QString ignorePattern; }; - CppCodeModelSettings(Utils::QtcSettings *s) { fromSettings(s); } + static CppCodeModelSettings &instance(); void setData(const Data &data); Data data() const { return m_data; } PCHUsage pchUsage() const { return m_data.pchUsage; } + UsePrecompiledHeaders usePrecompiledHeaders() const; bool interpretAmbigiousHeadersAsC() const { return m_data.interpretAmbigiousHeadersAsC; } bool skipIndexingBigFiles() const { return m_data.skipIndexingBigFiles; } bool useBuiltinPreprocessor() const { return m_data.useBuiltinPreprocessor; } int indexerFileSizeLimitInMb() const { return m_data.indexerFileSizeLimitInMb; } + int effectiveIndexerFileSizeLimitInMb() const; bool categorizeFindReferences() const { return m_data.categorizeFindReferences; } bool ignoreFiles() const { return m_data.ignoreFiles; } QString ignorePattern() const { return m_data.ignorePattern; } @@ -73,6 +76,7 @@ signals: private: CppCodeModelSettings() = default; + CppCodeModelSettings(Utils::QtcSettings *s) { fromSettings(s); } void toSettings(Utils::QtcSettings *s); void fromSettings(Utils::QtcSettings *s); @@ -224,6 +228,4 @@ private: bool m_blockIndexing = false; }; -CppCodeModelSettings &cppCodeModelSettings(); - } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index b267b66242c..bb911657054 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -54,7 +54,7 @@ public: CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); private: - void apply() final { codeModelSettings()->setData(data()); } + void apply() final { CppCodeModelSettings::instance().setData(data()); } CppCodeModelSettings::Data data() const; @@ -152,7 +152,8 @@ public: setCategory(Constants::CPP_SETTINGS_CATEGORY); setDisplayCategory(Tr::tr("C++")); setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); - setWidgetCreator([] { return new CppCodeModelSettingsWidget(codeModelSettings()->data()); }); + setWidgetCreator( + [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::instance().data()); }); } }; diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index c9185e372c1..5b9e360be79 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -348,9 +348,9 @@ void CppEditorPlugin::addPerSymbolActions() findRefsCategorized.addToContainers(menus, Constants::G_SYMBOL); findRefsCategorized.addOnTriggered(this, [] { if (const auto w = currentCppEditorWidget()) { - codeModelSettings()->setCategorizeFindReferences(true); + CppCodeModelSettings::instance().setCategorizeFindReferences(true); w->findUsages(); - codeModelSettings()->setCategorizeFindReferences(false); + CppCodeModelSettings::instance().setCategorizeFindReferences(false); } }); diff --git a/src/plugins/cppeditor/cppfindreferences.cpp b/src/plugins/cppeditor/cppfindreferences.cpp index 25b3e110d53..683eda587a4 100644 --- a/src/plugins/cppeditor/cppfindreferences.cpp +++ b/src/plugins/cppeditor/cppfindreferences.cpp @@ -388,7 +388,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, search->setTextToReplace(replacement); if (callback) search->makeNonInteractive(callback); - if (codeModelSettings()->categorizeFindReferences()) + if (CppCodeModelSettings::instance().categorizeFindReferences()) search->setFilter(new CppSearchResultFilter); setupSearch(search); search->setSearchAgainSupported(true); @@ -397,7 +397,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, CppFindReferencesParameters parameters; parameters.symbolId = fullIdForSymbol(symbol); parameters.symbolFilePath = symbol->filePath(); - parameters.categorize = codeModelSettings()->categorizeFindReferences(); + parameters.categorize = CppCodeModelSettings::instance().categorizeFindReferences(); parameters.preferLowerCaseFileNames = preferLowerCaseFileNames( ProjectManager::projectForFile(symbol->filePath())); @@ -408,7 +408,8 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, } search->setUserData(QVariant::fromValue(parameters)); - findAll_helper(search, symbol, context, codeModelSettings()->categorizeFindReferences()); + findAll_helper(search, symbol, context, + CppCodeModelSettings::instance().categorizeFindReferences()); } void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, diff --git a/src/plugins/cppeditor/cppindexingsupport.cpp b/src/plugins/cppeditor/cppindexingsupport.cpp index 14ce23c79ab..1d637f6e8ab 100644 --- a/src/plugins/cppeditor/cppindexingsupport.cpp +++ b/src/plugins/cppeditor/cppindexingsupport.cpp @@ -5,6 +5,7 @@ #include "builtineditordocumentparser.h" #include "cppchecksymbols.h" +#include "cppcodemodelsettings.h" #include "cppeditorconstants.h" #include "cppeditortr.h" #include "cppsourceprocessor.h" diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index 98cd232326a..6e81e86f0ca 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -407,7 +407,7 @@ void CppModelManager::showPreprocessedFile(bool inNextSplit) saveAndOpen(outFilePath, content.append(preprocessedDoc->utf8Source()), inNextSplit); }; - if (codeModelSettings()->useBuiltinPreprocessor()) { + if (CppCodeModelSettings::instance().useBuiltinPreprocessor()) { useBuiltinPreprocessor(); return; } @@ -1349,10 +1349,12 @@ QFuture CppModelManager::updateSourceFiles(const QSet &sourceFil if (sourceFiles.isEmpty() || !d->m_indexerEnabled) return QFuture(); - const QSet filteredFiles = filteredFilesRemoved(transform(sourceFiles, &FilePath::toString), - indexerFileSizeLimitInMb(), - codeModelSettings()->ignoreFiles(), - codeModelSettings()->ignorePattern()); + const CppCodeModelSettings &settings = CppCodeModelSettings::instance(); + const QSet filteredFiles + = filteredFilesRemoved(transform(sourceFiles, &FilePath::toString), + settings.effectiveIndexerFileSizeLimitInMb(), + settings.ignoreFiles(), + settings.ignorePattern()); return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode); } diff --git a/src/plugins/cppeditor/cpptoolsreuse.cpp b/src/plugins/cppeditor/cpptoolsreuse.cpp index 6555010c8f4..f6e58abddf9 100644 --- a/src/plugins/cppeditor/cpptoolsreuse.cpp +++ b/src/plugins/cppeditor/cpptoolsreuse.cpp @@ -357,22 +357,6 @@ CppCompletionAssistProcessor *getCppCompletionAssistProcessor() return new Internal::InternalCppCompletionAssistProcessor(); } -CppCodeModelSettings *codeModelSettings() -{ - return &cppCodeModelSettings(); -} - -int indexerFileSizeLimitInMb() -{ - const CppCodeModelSettings *settings = codeModelSettings(); - QTC_ASSERT(settings, return -1); - - if (settings->skipIndexingBigFiles()) - return settings->indexerFileSizeLimitInMb(); - - return -1; -} - bool fileSizeExceedsLimit(const FilePath &filePath, int sizeLimitInMb) { if (sizeLimitInMb <= 0) @@ -392,14 +376,6 @@ bool fileSizeExceedsLimit(const FilePath &filePath, int sizeLimitInMb) return false; } -UsePrecompiledHeaders getPchUsage() -{ - const CppCodeModelSettings *cms = codeModelSettings(); - if (cms->pchUsage() == CppCodeModelSettings::PchUse_None) - return UsePrecompiledHeaders::No; - return UsePrecompiledHeaders::Yes; -} - static void addBuiltinConfigs(ClangDiagnosticConfigsModel &model) { ClangDiagnosticConfig config; diff --git a/src/plugins/cppeditor/cpptoolsreuse.h b/src/plugins/cppeditor/cpptoolsreuse.h index 89bf8961976..8b1da79113d 100644 --- a/src/plugins/cppeditor/cpptoolsreuse.h +++ b/src/plugins/cppeditor/cpptoolsreuse.h @@ -73,14 +73,11 @@ Utils::FilePath CPPEDITOR_EXPORT correspondingHeaderOrSource( void CPPEDITOR_EXPORT openEditor(const Utils::FilePath &filePath, bool inNextSplit, Utils::Id editorId = {}); -class CppCodeModelSettings; -CppCodeModelSettings CPPEDITOR_EXPORT *codeModelSettings(); QString CPPEDITOR_EXPORT preferredCxxHeaderSuffix(ProjectExplorer::Project *project); QString CPPEDITOR_EXPORT preferredCxxSourceSuffix(ProjectExplorer::Project *project); bool CPPEDITOR_EXPORT preferLowerCaseFileNames(ProjectExplorer::Project *project); - QList CPPEDITOR_EXPORT symbolOccurrencesInText( const QTextDocument &doc, QStringView text, int offset, const QString &symbolName); Utils::SearchResultItems CPPEDITOR_EXPORT @@ -88,9 +85,6 @@ symbolOccurrencesInDeclarationComments(const Utils::SearchResultItems &symbolOcc QList CPPEDITOR_EXPORT symbolOccurrencesInDeclarationComments( CppEditorWidget *editorWidget, const QTextCursor &cursor); -UsePrecompiledHeaders CPPEDITOR_EXPORT getPchUsage(); - -int indexerFileSizeLimitInMb(); bool fileSizeExceedsLimit(const Utils::FilePath &filePath, int sizeLimitInMb); ProjectExplorer::Project CPPEDITOR_EXPORT *projectForProjectInfo(const ProjectInfo &info); From e01909a8a1f2cee864c40eac9878db9098bf6d30 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 1 Mar 2024 17:36:32 +0100 Subject: [PATCH 0053/1060] LSP: Implement SymbolTag support Change-Id: I6e57d315a5ecd7402c0082df68e083e33dfeab7e Reviewed-by: David Schulz Reviewed-by: --- .../languageserverprotocol/callhierarchy.cpp | 5 ++++ .../languageserverprotocol/callhierarchy.h | 2 ++ .../clientcapabilities.cpp | 14 +++++++++++ .../clientcapabilities.h | 19 +++++++++++++++ src/libs/languageserverprotocol/jsonkeys.h | 2 ++ src/libs/languageserverprotocol/lsptypes.cpp | 24 +++++++++++++++++++ src/libs/languageserverprotocol/lsptypes.h | 13 +++++++++- src/plugins/languageclient/callhierarchy.cpp | 4 ++++ src/plugins/languageclient/client.cpp | 3 +++ 9 files changed, 85 insertions(+), 1 deletion(-) diff --git a/src/libs/languageserverprotocol/callhierarchy.cpp b/src/libs/languageserverprotocol/callhierarchy.cpp index 4b19d71fa82..49b789c28ac 100644 --- a/src/libs/languageserverprotocol/callhierarchy.cpp +++ b/src/libs/languageserverprotocol/callhierarchy.cpp @@ -25,4 +25,9 @@ CallHierarchyOutgoingCallsRequest::CallHierarchyOutgoingCallsRequest( : Request(methodName, params) {} +std::optional> CallHierarchyItem::symbolTags() const +{ + return Internal::getSymbolTags(*this); +} + } // namespace LanguageServerProtocol diff --git a/src/libs/languageserverprotocol/callhierarchy.h b/src/libs/languageserverprotocol/callhierarchy.h index 1cc022d6d1f..27e241b8ba9 100644 --- a/src/libs/languageserverprotocol/callhierarchy.h +++ b/src/libs/languageserverprotocol/callhierarchy.h @@ -18,6 +18,8 @@ public: SymbolKind symbolKind() const { return SymbolKind(typedValue(kindKey)); } void setSymbolKind(const SymbolKind &symbolKind) { insert(kindKey, int(symbolKind)); } + std::optional> symbolTags() const; + Range range() const { return typedValue(rangeKey); } void setRange(const Range &range) { insert(rangeKey, range); } diff --git a/src/libs/languageserverprotocol/clientcapabilities.cpp b/src/libs/languageserverprotocol/clientcapabilities.cpp index acae7ad554a..60ea4523fd8 100644 --- a/src/libs/languageserverprotocol/clientcapabilities.cpp +++ b/src/libs/languageserverprotocol/clientcapabilities.cpp @@ -19,6 +19,20 @@ void SymbolCapabilities::SymbolKindCapabilities::setValueSet(const QList(valueSet)); } +std::optional > SymbolCapabilities::SymbolTagCapabilities::valueSet() const +{ + if (std::optional> array = optionalArray(valueSetKey)) { + return std::make_optional( + Utils::transform(*array, [](int value) { return static_cast(value); })); + } + return std::nullopt; +} + +void SymbolCapabilities::SymbolTagCapabilities::setValueSet(const QList &valueSet) +{ + insert(valueSetKey, enumArrayToJsonArray(valueSet)); +} + WorkspaceClientCapabilities::WorkspaceClientCapabilities() { setWorkspaceFolders(true); diff --git a/src/libs/languageserverprotocol/clientcapabilities.h b/src/libs/languageserverprotocol/clientcapabilities.h index 367e1b3fe4c..b2311d7e726 100644 --- a/src/libs/languageserverprotocol/clientcapabilities.h +++ b/src/libs/languageserverprotocol/clientcapabilities.h @@ -131,12 +131,31 @@ public: void clearValueSet() { remove(valueSetKey); } }; + class LANGUAGESERVERPROTOCOL_EXPORT SymbolTagCapabilities : public JsonObject + { + public: + using JsonObject::JsonObject; + + /* + * The client supports tags on `SymbolInformation` and `WorkspaceSymbol`. + * Clients supporting tags have to handle unknown tags gracefully. + */ + std::optional> valueSet() const; + void setValueSet(const QList &valueSet); + void clearValueSet() { remove(valueSetKey); } + }; + // Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. std::optional symbolKind() const { return optionalValue(symbolKindKey); } void setSymbolKind(const SymbolKindCapabilities &symbolKind) { insert(symbolKindKey, symbolKind); } void clearSymbolKind() { remove(symbolKindKey); } + std::optional symbolTag() const + { return optionalValue(tagSupportKey); } + void setSymbolTag(const SymbolTagCapabilities &symbolTag) { insert(tagSupportKey, symbolTag); } + void clearSymbolTag() { remove(tagSupportKey); } + std::optional hierarchicalDocumentSymbolSupport() const { return optionalValue(hierarchicalDocumentSymbolSupportKey); } void setHierarchicalDocumentSymbolSupport(bool hierarchicalDocumentSymbolSupport) diff --git a/src/libs/languageserverprotocol/jsonkeys.h b/src/libs/languageserverprotocol/jsonkeys.h index 236d28bfda1..c2b5e545f29 100644 --- a/src/libs/languageserverprotocol/jsonkeys.h +++ b/src/libs/languageserverprotocol/jsonkeys.h @@ -193,10 +193,12 @@ constexpr Key startKey{"start"}; constexpr Key supportedKey{"supported"}; constexpr Key symbolKey{"symbol"}; constexpr Key symbolKindKey{"symbolKind"}; +constexpr Key symbolTagKey{"symbolTag"}; constexpr Key syncKindKey{"syncKind"}; constexpr Key synchronizationKey{"synchronization"}; constexpr Key tabSizeKey{"tabSize"}; constexpr Key tagsKey{"tags"}; +constexpr Key tagSupportKey{"tagSupport"}; constexpr Key targetKey{"target"}; constexpr Key textDocumentKey{"textDocument"}; constexpr Key textDocumentSyncKey{"textDocumentSync"}; diff --git a/src/libs/languageserverprotocol/lsptypes.cpp b/src/libs/languageserverprotocol/lsptypes.cpp index ddd9b0e66c0..cb327642e36 100644 --- a/src/libs/languageserverprotocol/lsptypes.cpp +++ b/src/libs/languageserverprotocol/lsptypes.cpp @@ -6,6 +6,7 @@ #include "languageserverprotocoltr.h" #include "lsputils.h" +#include #include #include @@ -487,4 +488,27 @@ bool DeleteFileOperation::isValid() const return contains(uriKey) && value(kindKey) == "delete"; } +namespace Internal { +std::optional> getSymbolTags(const JsonObject &o) +{ + const QJsonObject &obj = o; + const QJsonValue &val = obj.value(tagsKey); + if (val.isUndefined() || !val.isArray()) + return std::nullopt; + + return Utils::transform>(val.toArray(), [](const QJsonValue &v) { + return static_cast(v.toInt()); + }); +} +} // namespace Internal + +std::optional> SymbolInformation::symbolTags() const +{ + return Internal::getSymbolTags(*this); +} + +std::optional> DocumentSymbol::symbolTags() const +{ + return Internal::getSymbolTags(*this); +} } // namespace LanguageServerProtocol diff --git a/src/libs/languageserverprotocol/lsptypes.h b/src/libs/languageserverprotocol/lsptypes.h index ae19f36145b..6e25fcb49d0 100644 --- a/src/libs/languageserverprotocol/lsptypes.h +++ b/src/libs/languageserverprotocol/lsptypes.h @@ -574,6 +574,13 @@ public: { return contains(uriKey) && contains(nameKey); } }; +enum class SymbolTag { + Deprecated = 1, +}; +namespace Internal { +std::optional> getSymbolTags(const JsonObject &o); +} // namespace Internal + class LANGUAGESERVERPROTOCOL_EXPORT SymbolInformation : public JsonObject { public: @@ -585,6 +592,8 @@ public: int kind() const { return typedValue(kindKey); } void setKind(int kind) { insert(kindKey, kind); } + std::optional> symbolTags() const; + std::optional deprecated() const { return optionalValue(deprecatedKey); } void setDeprecated(bool deprecated) { insert(deprecatedKey, deprecated); } void clearDeprecated() { remove(deprecatedKey); } @@ -616,6 +625,8 @@ public: int kind() const { return typedValue(kindKey); } void setKind(int kind) { insert(kindKey, kind); } + std::optional> symbolTags() const; + std::optional deprecated() const { return optionalValue(deprecatedKey); } void setDeprecated(bool deprecated) { insert(deprecatedKey, deprecated); } void clearDeprecated() { remove(deprecatedKey); } @@ -693,4 +704,4 @@ enum Kind { }; } // namespace CompletionItemKind -} // namespace LanguageClient +} // namespace LanguageServerProtocol diff --git a/src/plugins/languageclient/callhierarchy.cpp b/src/plugins/languageclient/callhierarchy.cpp index 32023e6a98f..dcb47f595ee 100644 --- a/src/plugins/languageclient/callhierarchy.cpp +++ b/src/plugins/languageclient/callhierarchy.cpp @@ -52,6 +52,8 @@ public: { switch (role) { case Qt::DecorationRole: + if (m_item.symbolTags().value_or(QList()).contains(SymbolTag::Deprecated)) + return Utils::Icons::WARNING.icon(); return symbolIcon(int(m_item.symbolKind())); case Qt::DisplayRole: return m_item.name(); @@ -158,6 +160,8 @@ public: { switch (role) { case Qt::DecorationRole: + if (m_item.symbolTags().value_or(QList()).contains(SymbolTag::Deprecated)) + return Utils::Icons::WARNING.icon(); return symbolIcon(int(m_item.symbolKind())); case Qt::DisplayRole: return m_item.name(); diff --git a/src/plugins/languageclient/client.cpp b/src/plugins/languageclient/client.cpp index 1b16e9dfb00..15a71adae37 100644 --- a/src/plugins/languageclient/client.cpp +++ b/src/plugins/languageclient/client.cpp @@ -437,6 +437,9 @@ static ClientCapabilities generateClientCapabilities() SymbolKind::EnumMember, SymbolKind::Struct, SymbolKind::Event, SymbolKind::Operator, SymbolKind::TypeParameter}); symbolCapabilities.setSymbolKind(symbolKindCapabilities); + SymbolCapabilities::SymbolTagCapabilities symbolTagCapabilities; + symbolTagCapabilities.setValueSet({SymbolTag::Deprecated}); + symbolCapabilities.setSymbolTag(symbolTagCapabilities); symbolCapabilities.setHierarchicalDocumentSymbolSupport(true); documentCapabilities.setDocumentSymbol(symbolCapabilities); From f5de774d776439516da0a4a3db850a765de731dc Mon Sep 17 00:00:00 2001 From: David Schulz Date: Tue, 12 Mar 2024 11:40:35 +0100 Subject: [PATCH 0054/1060] LanguageClient: improve callhierarchy direction items Do not use the icon of the root function for the artificial "Incoming" and "Outgoing" items in the call hierarchy. In the case of deprecated functions this can be a warning icon. Change-Id: Ib75a66296210d4da24208e98efb527b9af37b793 Reviewed-by: Christian Kandeler --- src/plugins/languageclient/callhierarchy.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/plugins/languageclient/callhierarchy.cpp b/src/plugins/languageclient/callhierarchy.cpp index dcb47f595ee..b6ead79a7f6 100644 --- a/src/plugins/languageclient/callhierarchy.cpp +++ b/src/plugins/languageclient/callhierarchy.cpp @@ -141,6 +141,8 @@ public: { if (role == Qt::DisplayRole) return m_direction == Incoming ? Tr::tr("Incoming") : Tr::tr("Outgoing"); + if (role == Qt::DecorationRole) + return {}; return CallHierarchyItem::data(column, role); } }; From 3f457c158f3381519228db7c26085446b49b9132 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 5 Mar 2024 10:33:50 +0100 Subject: [PATCH 0055/1060] TextEditor: Add type hierarchy infrastructure We want to support more than one back-end in the future. Task-number: QTCREATORBUG-28116 Change-Id: I72020c94b36072a297e13f44130e5e2482922cd4 Reviewed-by: David Schulz --- src/plugins/cppeditor/cppeditorconstants.h | 3 - src/plugins/cppeditor/cppeditorplugin.cpp | 2 + src/plugins/cppeditor/cpptypehierarchy.cpp | 72 ++++------ src/plugins/cppeditor/cpptypehierarchy.h | 3 - .../cppeditor/fileandtokenactions_test.cpp | 4 +- src/plugins/texteditor/CMakeLists.txt | 1 + src/plugins/texteditor/texteditor.cpp | 5 + src/plugins/texteditor/texteditor.qbs | 5 +- .../texteditor/texteditoractionhandler.cpp | 17 ++- .../texteditor/texteditoractionhandler.h | 3 +- src/plugins/texteditor/texteditorconstants.h | 2 + src/plugins/texteditor/texteditorplugin.cpp | 2 + src/plugins/texteditor/typehierarchy.cpp | 136 ++++++++++++++++++ src/plugins/texteditor/typehierarchy.h | 39 +++++ 14 files changed, 238 insertions(+), 56 deletions(-) create mode 100644 src/plugins/texteditor/typehierarchy.cpp create mode 100644 src/plugins/texteditor/typehierarchy.h diff --git a/src/plugins/cppeditor/cppeditorconstants.h b/src/plugins/cppeditor/cppeditorconstants.h index 1c5cffee98f..1d4c0cc18b4 100644 --- a/src/plugins/cppeditor/cppeditorconstants.h +++ b/src/plugins/cppeditor/cppeditorconstants.h @@ -22,9 +22,6 @@ const char M_REFACTORING_MENU_INSERTION_POINT[] = "CppEditor.RefactorGroup"; const char UPDATE_CODEMODEL[] = "CppEditor.UpdateCodeModel"; const char INSPECT_CPP_CODEMODEL[] = "CppEditor.InspectCppCodeModel"; -const char TYPE_HIERARCHY_ID[] = "CppEditor.TypeHierarchy"; -const char OPEN_TYPE_HIERARCHY[] = "CppEditor.OpenTypeHierarchy"; - const char INCLUDE_HIERARCHY_ID[] = "CppEditor.IncludeHierarchy"; const char OPEN_INCLUDE_HIERARCHY[] = "CppEditor.OpenIncludeHierarchy"; diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 5b9e360be79..a98a76ec423 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -144,6 +144,7 @@ public: | TextEditorActionHandler::FollowSymbolUnderCursor | TextEditorActionHandler::FollowTypeUnderCursor | TextEditorActionHandler::RenameSymbol + | TextEditorActionHandler::TypeHierarchy | TextEditorActionHandler::FindUsage); } }; @@ -358,6 +359,7 @@ void CppEditorPlugin::addPerSymbolActions() setupCppTypeHierarchy(); + addSymbolActionToMenus(TextEditor::Constants::OPEN_TYPE_HIERARCHY); addSymbolActionToMenus(TextEditor::Constants::OPEN_CALL_HIERARCHY); // Refactoring sub-menu diff --git a/src/plugins/cppeditor/cpptypehierarchy.cpp b/src/plugins/cppeditor/cpptypehierarchy.cpp index 57b3e95f1a7..d0a523ce133 100644 --- a/src/plugins/cppeditor/cpptypehierarchy.cpp +++ b/src/plugins/cppeditor/cpptypehierarchy.cpp @@ -4,6 +4,7 @@ #include "cpptypehierarchy.h" #include "cppeditorconstants.h" +#include "cppeditordocument.h" #include "cppeditortr.h" #include "cppeditorwidget.h" #include "cppelementevaluator.h" @@ -11,11 +12,10 @@ #include #include #include -#include -#include #include #include +#include #include #include @@ -53,7 +53,7 @@ public: QMimeData *mimeData(const QModelIndexList &indexes) const override; }; -class CppTypeHierarchyWidget : public QWidget +class CppTypeHierarchyWidget : public TextEditor::TypeHierarchyWidget { public: CppTypeHierarchyWidget(); @@ -61,6 +61,8 @@ public: void perform(); private: + void reload() override { perform(); } + void displayHierarchy(); typedef QList CppClass::*HierarchyMember; void performFromExpression(const QString &expression, const FilePath &filePath); @@ -87,6 +89,7 @@ private: ProgressIndicator *m_progressIndicator = nullptr; QString m_oldClass; bool m_showOldClass = false; + int m_runningIndexers = 0; }; enum ItemRole { @@ -197,10 +200,22 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget() connect(&m_futureWatcher, &QFutureWatcher::finished, this, &CppTypeHierarchyWidget::displayHierarchy); + + connect(ProgressManager::instance(), &ProgressManager::taskStarted, [this](Id type) { + if (type == Constants::TASK_INDEX) + ++m_runningIndexers; + }); + connect(ProgressManager::instance(), &ProgressManager::allTasksFinished, [this](Id type) { + if (type == Constants::TASK_INDEX) + --m_runningIndexers; + }); } void CppTypeHierarchyWidget::perform() { + if (m_runningIndexers > 0) + return; + if (m_future.isRunning()) m_future.cancel(); @@ -397,47 +412,19 @@ QMimeData *CppTypeHierarchyModel::mimeData(const QModelIndexList &indexes) const // CppTypeHierarchyFactory -class CppTypeHierarchyFactory final : public INavigationWidgetFactory +class CppTypeHierarchyFactory final : public TextEditor::TypeHierarchyWidgetFactory { -public: - CppTypeHierarchyFactory() + TextEditor::TypeHierarchyWidget *createWidget(Core::IEditor *editor) final { - setDisplayName(Tr::tr("Type Hierarchy")); - setPriority(700); - setId(Constants::TYPE_HIERARCHY_ID); + const auto textEditor = qobject_cast(editor); + if (!textEditor) + return nullptr; + const auto cppDoc = qobject_cast(textEditor->textDocument()); + if (!cppDoc /* || cppDoc->usesClangd() */) + return nullptr; - ActionBuilder openTypeHierarchy(this, Constants::OPEN_TYPE_HIERARCHY); - openTypeHierarchy.setText(Tr::tr("Open Type Hierarchy")); - openTypeHierarchy.setContext(Context(Constants::CPPEDITOR_ID)); - openTypeHierarchy.bindContextAction(&m_openTypeHierarchyAction); - openTypeHierarchy.setDefaultKeySequence(Tr::tr("Meta+Shift+T"), Tr::tr("Ctrl+Shift+T")); - openTypeHierarchy.addToContainers({Constants::M_TOOLS_CPP, Constants::M_CONTEXT}, - Constants::G_SYMBOL); - - connect(m_openTypeHierarchyAction, &QAction::triggered, this, [] { - NavigationWidget::activateSubWidget(Constants::TYPE_HIERARCHY_ID, Side::Left); - }); - - connect(ProgressManager::instance(), &ProgressManager::taskStarted, [this](Id type) { - if (type == Constants::TASK_INDEX) - m_openTypeHierarchyAction->setEnabled(false); - }); - connect(ProgressManager::instance(), &ProgressManager::allTasksFinished, [this](Id type) { - if (type == Constants::TASK_INDEX) - m_openTypeHierarchyAction->setEnabled(true); - }); + return new CppTypeHierarchyWidget; } - - NavigationView createWidget() final - { - auto w = new CppTypeHierarchyWidget; - connect(m_openTypeHierarchyAction, &QAction::triggered, w, &CppTypeHierarchyWidget::perform); - w->perform(); - - return {w, {}}; - } - - QAction *m_openTypeHierarchyAction = nullptr; }; static CppTypeHierarchyFactory &cppTypeHierarchyFactory() @@ -446,11 +433,6 @@ static CppTypeHierarchyFactory &cppTypeHierarchyFactory() return theCppTypeHierarchyFactory; } -void openCppTypeHierarchy() -{ - cppTypeHierarchyFactory().m_openTypeHierarchyAction->trigger(); -} - void setupCppTypeHierarchy() { (void) cppTypeHierarchyFactory(); // Trigger instantiation diff --git a/src/plugins/cppeditor/cpptypehierarchy.h b/src/plugins/cppeditor/cpptypehierarchy.h index c6c99f214f7..ffe7edbc134 100644 --- a/src/plugins/cppeditor/cpptypehierarchy.h +++ b/src/plugins/cppeditor/cpptypehierarchy.h @@ -4,8 +4,5 @@ #pragma once namespace CppEditor::Internal { - -void openCppTypeHierarchy(); void setupCppTypeHierarchy(); - } // CppEditor::Internal diff --git a/src/plugins/cppeditor/fileandtokenactions_test.cpp b/src/plugins/cppeditor/fileandtokenactions_test.cpp index f341cc1808d..5acca7fa116 100644 --- a/src/plugins/cppeditor/fileandtokenactions_test.cpp +++ b/src/plugins/cppeditor/fileandtokenactions_test.cpp @@ -9,7 +9,6 @@ #include "cppinsertvirtualmethods.h" #include "cppmodelmanager.h" #include "cpptoolstestcase.h" -#include "cpptypehierarchy.h" #include "cppworkingcopy.h" #include "projectinfo.h" @@ -18,6 +17,7 @@ #include #include #include +#include #include #include @@ -383,7 +383,7 @@ public: void OpenTypeHierarchyTokenAction::run(CppEditorWidget *) { - openCppTypeHierarchy(); + TextEditor::openTypeHierarchy(); QApplication::processEvents(); } diff --git a/src/plugins/texteditor/CMakeLists.txt b/src/plugins/texteditor/CMakeLists.txt index 886b98390ce..c36d4121ece 100644 --- a/src/plugins/texteditor/CMakeLists.txt +++ b/src/plugins/texteditor/CMakeLists.txt @@ -113,6 +113,7 @@ add_qtc_plugin(TextEditor textindenter.cpp textindenter.h textmark.cpp textmark.h textstyles.h + typehierarchy.cpp typehierarchy.h typingsettings.cpp typingsettings.h ) diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 3256ee91b79..42daeeff6d3 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -8759,6 +8759,11 @@ void TextEditorWidget::appendStandardContextMenuActions(QMenu *menu) if (!menu->actions().contains(action)) menu->addAction(action); } + if (optionalActions() & TextEditorActionHandler::TypeHierarchy) { + const auto action = ActionManager::command(Constants::OPEN_TYPE_HIERARCHY)->action(); + if (!menu->actions().contains(action)) + menu->addAction(action); + } menu->addSeparator(); appendMenuActionsFromContext(menu, Constants::M_STANDARDCONTEXTMENU); diff --git a/src/plugins/texteditor/texteditor.qbs b/src/plugins/texteditor/texteditor.qbs index 821d9a4a479..41fe08d51b5 100644 --- a/src/plugins/texteditor/texteditor.qbs +++ b/src/plugins/texteditor/texteditor.qbs @@ -137,7 +137,8 @@ QtcPlugin { "texteditor.cpp", "texteditor.h", "texteditor.qrc", - "texteditor_global.h", "texteditortr.h", + "texteditor_global.h", + "texteditortr.h", "texteditoractionhandler.cpp", "texteditoractionhandler.h", "texteditorconstants.cpp", @@ -152,6 +153,8 @@ QtcPlugin { "textmark.cpp", "textmark.h", "textstyles.h", + "typehierarchy.cpp", + "typehierarchy.h", "typingsettings.cpp", "typingsettings.h", ] diff --git a/src/plugins/texteditor/texteditoractionhandler.cpp b/src/plugins/texteditor/texteditoractionhandler.cpp index 240e8498ed1..2cf553689cc 100644 --- a/src/plugins/texteditor/texteditoractionhandler.cpp +++ b/src/plugins/texteditor/texteditoractionhandler.cpp @@ -9,6 +9,7 @@ #include "linenumberfilter.h" #include "texteditortr.h" #include "texteditorsettings.h" +#include "typehierarchy.h" #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -137,6 +139,7 @@ public: QAction *m_followToTypeInNextSplitAction = nullptr; QAction *m_findUsageAction = nullptr; QAction *m_openCallHierarchyAction = nullptr; + QAction *m_openTypeHierarchyAction = nullptr; QAction *m_renameSymbolAction = nullptr; QAction *m_jumpToFileAction = nullptr; QAction *m_jumpToFileInNextSplitAction = nullptr; @@ -269,7 +272,17 @@ void TextEditorActionHandlerPrivate::createActions() QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+E, F2") : Tr::tr("Ctrl+E, F2")).toString()); m_openCallHierarchyAction = registerAction(OPEN_CALL_HIERARCHY, [] (TextEditorWidget *w) { w->openCallHierarchy(); }, true, Tr::tr("Open Call Hierarchy")); - + m_openTypeHierarchyAction = registerAction( + OPEN_TYPE_HIERARCHY, + [](TextEditorWidget *) { + updateTypeHierarchy( + NavigationWidget::activateSubWidget(Constants::TYPE_HIERARCHY_FACTORY_ID, + Side::Left)); + }, + true, + Tr::tr("Open Type Hierarchy"), + QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+Shift+T") + : Tr::tr("Ctrl+Shift+T"))); registerAction(VIEW_PAGE_UP, [] (TextEditorWidget *w) { w->viewPageUp(); }, true, Tr::tr("Move the View a Page Up and Keep the Cursor Position"), QKeySequence(Tr::tr("Ctrl+PgUp"))); @@ -550,6 +563,8 @@ void TextEditorActionHandlerPrivate::updateOptionalActions() optionalActions & TextEditorActionHandler::RenameSymbol); m_openCallHierarchyAction->setEnabled( optionalActions & TextEditorActionHandler::CallHierarchy); + m_openTypeHierarchyAction->setEnabled( + optionalActions & TextEditorActionHandler::TypeHierarchy); bool formatEnabled = (optionalActions & TextEditorActionHandler::Format) && m_currentEditorWidget && !m_currentEditorWidget->isReadOnly(); diff --git a/src/plugins/texteditor/texteditoractionhandler.h b/src/plugins/texteditor/texteditoractionhandler.h index 344a4a553e1..ce969b7b6f1 100644 --- a/src/plugins/texteditor/texteditoractionhandler.h +++ b/src/plugins/texteditor/texteditoractionhandler.h @@ -38,7 +38,8 @@ public: JumpToFileUnderCursor = 32, RenameSymbol = 64, FindUsage = 128, - CallHierarchy = 256 + CallHierarchy = 256, + TypeHierarchy = 512, }; using TextEditorWidgetResolver = std::function; diff --git a/src/plugins/texteditor/texteditorconstants.h b/src/plugins/texteditor/texteditorconstants.h index e2115261882..2597deb6bba 100644 --- a/src/plugins/texteditor/texteditorconstants.h +++ b/src/plugins/texteditor/texteditorconstants.h @@ -212,6 +212,8 @@ const char FIND_USAGES[] = "TextEditor.FindUsages"; // moved from CppEditor to TextEditor avoid breaking the setting by using the old key const char RENAME_SYMBOL[] = "CppEditor.RenameSymbolUnderCursor"; const char OPEN_CALL_HIERARCHY[] = "TextEditor.OpenCallHierarchy"; +const char OPEN_TYPE_HIERARCHY[] = "TextEditor.OpenTypeHierarchy"; +const char TYPE_HIERARCHY_FACTORY_ID[] = "TextEditor.TypeHierarchy"; const char JUMP_TO_FILE_UNDER_CURSOR[] = "TextEditor.JumpToFileUnderCursor"; const char JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT[] = "TextEditor.JumpToFileUnderCursorInNextSplit"; diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index 04f11bcbb0b..d279b6254f4 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -26,6 +26,7 @@ #include "texteditorsettings.h" #include "texteditortr.h" #include "textmark.h" +#include "typehierarchy.h" #include "typingsettings.h" #ifdef WITH_TESTS @@ -105,6 +106,7 @@ void TextEditorPlugin::initialize() setupTextMarkRegistry(this); setupOutlineFactory(); + setupTypeHierarchyFactory(); setupLineNumberFilter(); // Goto line functionality for quick open setupPlainTextEditor(); diff --git a/src/plugins/texteditor/typehierarchy.cpp b/src/plugins/texteditor/typehierarchy.cpp new file mode 100644 index 00000000000..53924a2b9d6 --- /dev/null +++ b/src/plugins/texteditor/typehierarchy.cpp @@ -0,0 +1,136 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "typehierarchy.h" + +#include "texteditorconstants.h" +#include "texteditortr.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +using namespace Utils; + +namespace TextEditor { +namespace Internal { + +static QList g_widgetFactories; + +class TypeHierarchyFactory : public Core::INavigationWidgetFactory +{ +public: + TypeHierarchyFactory() + { + setDisplayName(Tr::tr("Type Hierarchy")); + setPriority(649); + setId(Constants::TYPE_HIERARCHY_FACTORY_ID); + } + +private: + Core::NavigationView createWidget() override; +}; + +class TypeHierarchyWidgetStack : public QStackedWidget +{ + Q_OBJECT + +public: + TypeHierarchyWidgetStack(); + + void reload(); +}; + +static TypeHierarchyFactory &typeHierarchyFactory() +{ + static TypeHierarchyFactory theFactory; + return theFactory; +} + +void setupTypeHierarchyFactory() +{ + (void) typeHierarchyFactory(); +} + +TypeHierarchyWidgetStack::TypeHierarchyWidgetStack() +{ + QLabel *label = new QLabel(Tr::tr("No type hierarchy available"), this); + label->setAlignment(Qt::AlignCenter); + + label->setAutoFillBackground(true); + label->setBackgroundRole(QPalette::Base); + + addWidget(label); + reload(); +} + +void TypeHierarchyWidgetStack::reload() +{ + const auto editor = Core::EditorManager::currentEditor(); + TypeHierarchyWidget *newWidget = nullptr; + + if (editor) { + for (TypeHierarchyWidgetFactory * const widgetFactory : std::as_const(g_widgetFactories)) { + if ((newWidget = widgetFactory->createWidget(editor))) + break; + } + } + + QWidget * const current = currentWidget(); + if (current) { + removeWidget(current); + current->deleteLater(); + } + if (newWidget) { + addWidget(newWidget); + setCurrentWidget(newWidget); + setFocusProxy(newWidget); + newWidget->reload(); + } +} + +Core::NavigationView TypeHierarchyFactory::createWidget() +{ + const auto placeholder = new TypeHierarchyWidgetStack; + const auto reloadButton = new QToolButton; + reloadButton->setIcon(Icons::RELOAD_TOOLBAR.icon()); + reloadButton->setToolTip(Tr::tr("Reloads the type hierarchy for the symbol under the cursor.")); + connect(reloadButton, &QToolButton::clicked, placeholder, &TypeHierarchyWidgetStack::reload); + return {placeholder, {reloadButton}}; +} + +void updateTypeHierarchy(QWidget *widget) +{ + if (const auto w = qobject_cast(widget)) + w->reload(); +} + +} // namespace Internal + +TypeHierarchyWidgetFactory::TypeHierarchyWidgetFactory() +{ + Internal::g_widgetFactories.append(this); +} + +TypeHierarchyWidgetFactory::~TypeHierarchyWidgetFactory() +{ + Internal::g_widgetFactories.removeOne(this); +} + +void openTypeHierarchy() +{ + if (const auto action = Core::ActionManager::command(Constants::OPEN_TYPE_HIERARCHY)->action()) + action->trigger(); +} + +} // namespace TextEditor + +#include diff --git a/src/plugins/texteditor/typehierarchy.h b/src/plugins/texteditor/typehierarchy.h new file mode 100644 index 00000000000..ee7c1fa1a7b --- /dev/null +++ b/src/plugins/texteditor/typehierarchy.h @@ -0,0 +1,39 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include + +#include + +namespace Core { class IEditor; } + +namespace TextEditor { +namespace Internal { +void setupTypeHierarchyFactory(); +void updateTypeHierarchy(QWidget *widget); +} + +class TEXTEDITOR_EXPORT TypeHierarchyWidget : public QWidget +{ + Q_OBJECT +public: + virtual void reload() = 0; +}; + +class TEXTEDITOR_EXPORT TypeHierarchyWidgetFactory : public QObject +{ + Q_OBJECT + +public: + virtual TypeHierarchyWidget *createWidget(Core::IEditor *editor) = 0; + +protected: + TypeHierarchyWidgetFactory(); + ~TypeHierarchyWidgetFactory() override; +}; + +TEXTEDITOR_EXPORT void openTypeHierarchy(); + +} // namespace TextEditor From ad446d56897549b2cddb7b42ce7cbd6641a3c59b Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Wed, 6 Mar 2024 15:48:07 +0200 Subject: [PATCH 0056/1060] FileIteratorWrapper: refactor setPath() Only call setPath() in hasNext(), the latter is called before any other member method, and setPath() is guarded by a bool to only run a single time. Split some code to a helper function, which will be reused when porting to new QAFEngine API. Change-Id: Ibda0ede18593a3a20729b31e03e994ad2de126de Reviewed-by: Marcus Tillmanns --- .../fsengine/fileiteratordevicesappender.h | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index 77864117f46..0ce327690f2 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -47,7 +47,6 @@ public: if (m_status == State::Ended) return QString(); - setPath(); checkStatus(); if (m_status == State::BaseIteratorEnd) { @@ -75,7 +74,6 @@ public: if (m_status == State::Ended) return FilePath::specialRootPath(); - setPath(); checkStatus(); return m_baseIterator->currentFileName(); } @@ -83,22 +81,26 @@ public: { if (m_status == State::Ended) return QFileInfo(FilePath::specialRootPath()); - setPath(); checkStatus(); return m_baseIterator->currentFileInfo(); } private: + QString setStatus() const + { + // path() can be "/somedir/.." so we need to clean it first. + // We only need QDir::cleanPath here, as the path is always + // a fs engine path and will not contain scheme:// etc. + QString p = QDir::cleanPath(path()); + if (p.compare(HostOsInfo::root().path(), Qt::CaseInsensitive) == 0) + m_status = State::IteratingRoot; + return p; + } + void setPath() const { if (!m_hasSetPath) { - // path() can be "/somedir/.." so we need to clean it first. - // We only need QDir::cleanPath here, as the path is always - // a fs engine path and will not contain scheme:// etc. - const QString p = QDir::cleanPath(path()); - if (p.compare(HostOsInfo::root().path(), Qt::CaseInsensitive) == 0) - m_status = State::IteratingRoot; - + const QString &p = setStatus(); ((*m_baseIterator).*get(QAFEITag()))(p); m_hasSetPath = true; } From 1ddc71fcda9c3e368c9edc936efb99b0641f145b Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Wed, 6 Mar 2024 20:20:28 +0200 Subject: [PATCH 0057/1060] FileIteratorWrapper: simplify the code Setting m_status to BaseIteratorEnd should only be done in hasNext(), because the latter is always called first, before any other member function. Change-Id: Ie55518a850655730fb760226d58c4fb171a7f2e1 Reviewed-by: Marcus Tillmanns --- .../fsengine/fileiteratordevicesappender.h | 34 ++++++------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index 0ce327690f2..e2afcf50fe7 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -47,8 +47,6 @@ public: if (m_status == State::Ended) return QString(); - checkStatus(); - if (m_status == State::BaseIteratorEnd) { m_status = State::Ended; return FilePath::specialRootName(); @@ -62,27 +60,26 @@ public: return false; setPath(); - checkStatus(); - if (m_status == State::BaseIteratorEnd) + const bool res = m_baseIterator->hasNext(); + if (m_status == State::IteratingRoot && !res) { + // m_baseIterator finished, but we need to advance one last time, so that + // e.g. next() and currentFileName() return FilePath::specialRootPath(). + m_status = State::BaseIteratorEnd; return true; + } - return m_baseIterator->hasNext(); + return res; } QString currentFileName() const override { - if (m_status == State::Ended) - return FilePath::specialRootPath(); - - checkStatus(); - return m_baseIterator->currentFileName(); + return m_status == State::Ended ? FilePath::specialRootPath() + : m_baseIterator->currentFileName(); } QFileInfo currentFileInfo() const override { - if (m_status == State::Ended) - return QFileInfo(FilePath::specialRootPath()); - checkStatus(); - return m_baseIterator->currentFileInfo(); + return m_status == State::Ended ? QFileInfo(FilePath::specialRootPath()) + : m_baseIterator->currentFileInfo(); } private: @@ -106,15 +103,6 @@ private: } } - void checkStatus() const - { - if (m_status == State::IteratingRoot) { - if (m_baseIterator->hasNext() == false) { - m_status = State::BaseIteratorEnd; - } - } - } - private: std::unique_ptr m_baseIterator; mutable bool m_hasSetPath{false}; From 2166647682cd34968ec002f859e8263b90585189 Mon Sep 17 00:00:00 2001 From: Xavier BESSON Date: Fri, 15 Dec 2023 12:16:45 +0100 Subject: [PATCH 0058/1060] Add option to display locate results using relative paths to project root Task-number: QTCREATORBUG-29462 Change-Id: Idc52ec206d73d23b958a60391e8d0be9a6b000b0 Reviewed-by: hjk Reviewed-by: Reviewed-by: Leena Miettinen --- src/plugins/coreplugin/locator/locator.cpp | 12 ++++++++++++ src/plugins/coreplugin/locator/locator.h | 3 +++ .../coreplugin/locator/locatorsettingspage.cpp | 14 +++++++++++++- src/plugins/coreplugin/locator/locatorwidget.cpp | 9 +++++++-- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/plugins/coreplugin/locator/locator.cpp b/src/plugins/coreplugin/locator/locator.cpp index 55aa984c08d..563a1d6010c 100644 --- a/src/plugins/coreplugin/locator/locator.cpp +++ b/src/plugins/coreplugin/locator/locator.cpp @@ -166,6 +166,7 @@ void Locator::loadSettings() const Settings def; DB::beginGroup(settingsGroup); m_refreshTimer.setInterval(minutes(DB::value("RefreshInterval", 60).toInt())); + m_relativePaths = DB::value("RelativePaths", false).toBool(); m_settings.useCenteredPopup = DB::value(kUseCenteredPopup, def.useCenteredPopup).toBool(); for (ILocatorFilter *filter : std::as_const(m_filters)) { @@ -294,6 +295,7 @@ void Locator::saveSettings() const DB::beginGroup("Locator"); DB::remove(QString()); DB::setValue("RefreshInterval", refreshInterval()); + DB::setValue("RelativePaths", relativePaths()); DB::setValueWithDefault(kUseCenteredPopup, m_settings.useCenteredPopup, def.useCenteredPopup); for (ILocatorFilter *filter : m_filters) { if (!m_customFilters.contains(filter) && filter->id().isValid()) { @@ -363,6 +365,16 @@ void Locator::setRefreshInterval(int interval) m_refreshTimer.start(); } +bool Locator::relativePaths() const +{ + return m_relativePaths; +} + +void Locator::setRelativePaths(bool use) +{ + m_relativePaths = use; +} + bool Locator::useCenteredPopupForShortcut() { return m_instance->m_settings.useCenteredPopup; diff --git a/src/plugins/coreplugin/locator/locator.h b/src/plugins/coreplugin/locator/locator.h index cee26782a6f..6cc69c6f9a6 100644 --- a/src/plugins/coreplugin/locator/locator.h +++ b/src/plugins/coreplugin/locator/locator.h @@ -40,6 +40,8 @@ public: void setCustomFilters(QList f); int refreshInterval() const; void setRefreshInterval(int interval); + bool relativePaths() const; + void setRelativePaths(bool use); static bool useCenteredPopupForShortcut(); static void setUseCenteredPopupForShortcut(bool center); @@ -73,6 +75,7 @@ private: QTimer m_refreshTimer; Tasking::TaskTreeRunner m_taskTreeRunner; QList m_refreshingFilters; + bool m_relativePaths = false; }; } // namespace Internal diff --git a/src/plugins/coreplugin/locator/locatorsettingspage.cpp b/src/plugins/coreplugin/locator/locatorsettingspage.cpp index 8f549cb1138..d379a5c858e 100644 --- a/src/plugins/coreplugin/locator/locatorsettingspage.cpp +++ b/src/plugins/coreplugin/locator/locatorsettingspage.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -273,6 +274,12 @@ public: m_refreshInterval->setSingleStep(5); m_refreshInterval->setValue(60); + auto relativePathsLabel = new QLabel(Tr::tr("Show Paths in Relation to Active Project:")); + relativePathsLabel->setToolTip(Tr::tr("Locator filters show relative paths to the active project when possible.")); + + m_relativePaths = new QCheckBox; + m_relativePaths->setToolTip(relativePathsLabel->toolTip()); + auto filterEdit = new FancyLineEdit; filterEdit->setFiltering(true); @@ -320,7 +327,9 @@ public: m_filterList, buttons, br, - Span(2, Row{refreshIntervalLabel, m_refreshInterval, st})} + Span(2, Row{refreshIntervalLabel, m_refreshInterval, st}), + br, + Span(2, Row{relativePathsLabel, m_relativePaths, st})} .attachTo(this); connect(filterEdit, &FancyLineEdit::filterChanged, this, &LocatorSettingsWidget::setFilter); @@ -355,6 +364,7 @@ public: addButton->setMenu(addMenu); m_refreshInterval->setValue(m_plugin->refreshInterval()); + m_relativePaths->setChecked(m_plugin->relativePaths()); saveFilterStates(); } @@ -376,6 +386,7 @@ private: QPushButton *m_removeButton; QPushButton *m_editButton; QSpinBox *m_refreshInterval; + QCheckBox *m_relativePaths; Locator *m_plugin = nullptr; Utils::TreeModel<> *m_model = nullptr; QSortFilterProxyModel *m_proxyModel = nullptr; @@ -399,6 +410,7 @@ void LocatorSettingsWidget::apply() m_plugin->setFilters(m_filters); m_plugin->setCustomFilters(m_customFilters); m_plugin->setRefreshInterval(m_refreshInterval->value()); + m_plugin->setRelativePaths(m_relativePaths->isChecked()); requestRefresh(); m_plugin->saveSettings(); saveFilterStates(); diff --git a/src/plugins/coreplugin/locator/locatorwidget.cpp b/src/plugins/coreplugin/locator/locatorwidget.cpp index 6b008ccc13a..e6acfee42f7 100644 --- a/src/plugins/coreplugin/locator/locatorwidget.cpp +++ b/src/plugins/coreplugin/locator/locatorwidget.cpp @@ -162,8 +162,13 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const case Qt::DisplayRole: if (index.column() == DisplayNameColumn) return m_entries.at(index.row()).displayName; - else if (index.column() == ExtraInfoColumn) - return m_entries.at(index.row()).extraInfo; + if (index.column() == ExtraInfoColumn) { + if (Locator::instance()->relativePaths()) { + return ICore::pathRelativeToActiveProject(FilePath::fromUserInput(m_entries.at(index.row()).extraInfo)).toUserOutput(); + } else { + return m_entries.at(index.row()).extraInfo; + } + } break; case Qt::ToolTipRole: { const LocatorFilterEntry &entry = m_entries.at(index.row()); From 3107633731c086771d45c46122625eb192294d2a Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Thu, 22 Feb 2024 23:41:12 +0100 Subject: [PATCH 0059/1060] TextEditor: Split FormatText into input and output structs Remove output data from FormatText and rename it into FormatInput. Use Utils::expected_str for output data and alias it with FormatOutput. Change-Id: I2cf21d73d2e973eeeb4431ae30b56bb5987986f6 Reviewed-by: Reviewed-by: David Schulz --- src/plugins/texteditor/formattexteditor.cpp | 124 +++++++++----------- 1 file changed, 57 insertions(+), 67 deletions(-) diff --git a/src/plugins/texteditor/formattexteditor.cpp b/src/plugins/texteditor/formattexteditor.cpp index 879387b991a..b5340281b37 100644 --- a/src/plugins/texteditor/formattexteditor.cpp +++ b/src/plugins/texteditor/formattexteditor.cpp @@ -12,8 +12,9 @@ #include #include -#include +#include #include +#include #include #include @@ -27,18 +28,17 @@ using namespace std::chrono_literals; namespace TextEditor { -class FormatTask +struct FormatInput { -public: Utils::FilePath filePath; QString sourceData; TextEditor::Command command; int startPos = -1; int endPos = 0; - QString formattedData = {}; - QString error = {}; }; +using FormatOutput = expected_str; + void formatCurrentFile(const Command &command, int startPos, int endPos) { if (TextEditorWidget *editor = TextEditorWidget::currentTextEditorWidget()) @@ -52,89 +52,80 @@ static QString sourceData(TextEditorWidget *editor, int startPos, int endPos) : Utils::Text::textAt(editor->textCursor(), startPos, (endPos - startPos)); } -static FormatTask format(FormatTask task) +static FormatOutput format(const FormatInput &input) { - task.error.clear(); - task.formattedData.clear(); - - const FilePath executable = task.command.executable(); + const FilePath executable = input.command.executable(); if (executable.isEmpty()) - return task; + return {}; - switch (task.command.processing()) { + switch (input.command.processing()) { case Command::FileProcessing: { // Save text to temporary file Utils::TempFileSaver sourceFile(Utils::TemporaryDirectory::masterDirectoryPath() - + "/qtc_beautifier_XXXXXXXX." - + task.filePath.suffix()); + + "/qtc_beautifier_XXXXXXXX." + input.filePath.suffix()); sourceFile.setAutoRemove(true); - sourceFile.write(task.sourceData.toUtf8()); + sourceFile.write(input.sourceData.toUtf8()); if (!sourceFile.finalize()) { - task.error = Tr::tr("Cannot create temporary file \"%1\": %2.") - .arg(sourceFile.filePath().toUserOutput(), sourceFile.errorString()); - return task; + return Utils::make_unexpected(Tr::tr("Cannot create temporary file \"%1\": %2.") + .arg(sourceFile.filePath().toUserOutput(), sourceFile.errorString())); } // Format temporary file - QStringList options = task.command.options(); + QStringList options = input.command.options(); options.replaceInStrings(QLatin1String("%file"), sourceFile.filePath().toString()); Process process; process.setCommand({executable, options}); process.runBlocking(5s); if (process.result() != ProcessResult::FinishedWithSuccess) { - task.error = Tr::tr("Failed to format: %1.").arg(process.exitMessage()); - return task; + return Utils::make_unexpected(Tr::tr("Failed to format: %1.") + .arg(process.exitMessage())); } const QString output = process.cleanedStdErr(); if (!output.isEmpty()) - task.error = executable.toUserOutput() + ": " + output; + return Utils::make_unexpected(executable.toUserOutput() + ": " + output); // Read text back Utils::FileReader reader; if (!reader.fetch(sourceFile.filePath(), QIODevice::Text)) { - task.error = Tr::tr("Cannot read file \"%1\": %2.") - .arg(sourceFile.filePath().toUserOutput(), reader.errorString()); - return task; + return Utils::make_unexpected(Tr::tr("Cannot read file \"%1\": %2.") + .arg(sourceFile.filePath().toUserOutput(), reader.errorString())); } - task.formattedData = QString::fromUtf8(reader.data()); + return QString::fromUtf8(reader.data()); } - return task; case Command::PipeProcessing: { Process process; - QStringList options = task.command.options(); - options.replaceInStrings("%filename", task.filePath.fileName()); - options.replaceInStrings("%file", task.filePath.toString()); + QStringList options = input.command.options(); + options.replaceInStrings("%filename", input.filePath.fileName()); + options.replaceInStrings("%file", input.filePath.toString()); process.setCommand({executable, options}); - process.setWriteData(task.sourceData.toUtf8()); + process.setWriteData(input.sourceData.toUtf8()); process.start(); if (!process.waitForFinished(5s)) { - task.error = Tr::tr("Cannot call %1 or some other error occurred. Timeout " - "reached while formatting file %2.") - .arg(executable.toUserOutput(), task.filePath.displayName()); - return task; + return Utils::make_unexpected(Tr::tr("Cannot call %1 or some other error occurred. " + "Timeout reached while formatting file %2.") + .arg(executable.toUserOutput(), input.filePath.displayName())); } const QString errorText = process.readAllStandardError(); if (!errorText.isEmpty()) { - task.error = QString("%1: %2").arg(executable.toUserOutput(), errorText); - return task; + return Utils::make_unexpected(QString("%1: %2").arg(executable.toUserOutput(), + errorText)); } - task.formattedData = process.readAllStandardOutput(); + QString formattedData = process.readAllStandardOutput(); - if (task.command.pipeAddsNewline() && task.formattedData.endsWith('\n')) { - task.formattedData.chop(1); - if (task.formattedData.endsWith('\r')) - task.formattedData.chop(1); + if (input.command.pipeAddsNewline() && formattedData.endsWith('\n')) { + formattedData.chop(1); + if (formattedData.endsWith('\r')) + formattedData.chop(1); } - if (task.command.returnsCRLF()) - task.formattedData.replace("\r\n", "\n"); + if (input.command.returnsCRLF()) + formattedData.replace("\r\n", "\n"); - return task; + return formattedData; } } - - return task; + return {}; } /** @@ -268,28 +259,26 @@ static void showError(const QString &error) * Checks the state of @a task and if the formatting was successful calls updateEditorText() with * the respective members of @a task. */ -static void checkAndApplyTask(const QPointer &textEditor, const FormatTask &task) +static void checkAndApplyTask(const QPointer &textEditor, const FormatInput &input, + const FormatOutput &output) { - if (!task.error.isEmpty()) { - showError(task.error); + if (!output.has_value()) { + showError(output.error()); return; } - if (task.formattedData.isEmpty()) { - showError(Tr::tr("Could not format file %1.").arg(task.filePath.displayName())); + if (output->isEmpty()) { + showError(Tr::tr("Could not format file %1.").arg(input.filePath.displayName())); return; } if (!textEditor) { - showError(Tr::tr("File %1 was closed.").arg(task.filePath.displayName())); + showError(Tr::tr("File %1 was closed.").arg(input.filePath.displayName())); return; } - const QString formattedData = (task.startPos < 0) - ? task.formattedData - : QString(textEditor->toPlainText()).replace( - task.startPos, (task.endPos - task.startPos), task.formattedData); - + const QString formattedData = (input.startPos < 0) ? *output + : textEditor->toPlainText().replace(input.startPos, (input.endPos - input.startPos), *output); updateEditorText(textEditor, formattedData); } @@ -307,8 +296,8 @@ void formatEditor(TextEditorWidget *editor, const Command &command, int startPos const QString sd = sourceData(editor, startPos, endPos); if (sd.isEmpty()) return; - checkAndApplyTask(editor, - format({editor->textDocument()->filePath(), sd, command, startPos, endPos})); + const FormatInput input{editor->textDocument()->filePath(), sd, command, startPos, endPos}; + checkAndApplyTask(editor, input, format(input)); } /** @@ -322,19 +311,20 @@ void formatEditorAsync(TextEditorWidget *editor, const Command &command, int sta if (sd.isEmpty()) return; - auto watcher = new QFutureWatcher; + auto watcher = new QFutureWatcher; const TextDocument *doc = editor->textDocument(); - QObject::connect(doc, &TextDocument::contentsChanged, watcher, &QFutureWatcher::cancel); - QObject::connect(watcher, &QFutureWatcherBase::finished, - [watcher, editor = QPointer(editor)] { + const FormatInput input{doc->filePath(), sd, command, startPos, endPos}; + QObject::connect(doc, &TextDocument::contentsChanged, watcher, + &QFutureWatcher::cancel); + QObject::connect(watcher, &QFutureWatcherBase::finished, watcher, + [watcher, editor = QPointer(editor), input] { if (watcher->isCanceled()) showError(Tr::tr("File was modified.")); else - checkAndApplyTask(editor, watcher->result()); + checkAndApplyTask(editor, input, watcher->result()); watcher->deleteLater(); }); - watcher->setFuture( - Utils::asyncRun(&format, FormatTask{doc->filePath(), sd, command, startPos, endPos})); + watcher->setFuture(Utils::asyncRun(&format, input)); } } // namespace TextEditor From b72c3bc8a21684b977d3919835bb238b6ab9ee13 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Tue, 12 Mar 2024 12:49:01 +0100 Subject: [PATCH 0060/1060] LanguageClient: add a tooltip to deprecated items in the call hierarchy Change-Id: Ica03cdd06eea755852e6e9e3335ffeb5f8cae499 Reviewed-by: Christian Kandeler --- src/plugins/languageclient/callhierarchy.cpp | 106 +++++++++---------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/src/plugins/languageclient/callhierarchy.cpp b/src/plugins/languageclient/callhierarchy.cpp index b6ead79a7f6..2f53a120ebe 100644 --- a/src/plugins/languageclient/callhierarchy.cpp +++ b/src/plugins/languageclient/callhierarchy.cpp @@ -36,13 +36,48 @@ enum { }; } -class CallHierarchyItem : public TreeItem +class CallHierarchyRootItem : public TreeItem { public: - CallHierarchyItem(const LanguageServerProtocol::CallHierarchyItem &item, - const Direction direction, - Client *client) + CallHierarchyRootItem(const CallHierarchyItem &item) : m_item(item) + {} + + QVariant data(int column, int role) const override + { + switch (role) { + case Qt::DecorationRole: + if (hasTag(SymbolTag::Deprecated)) + return Utils::Icons::WARNING.icon(); + return symbolIcon(int(m_item.symbolKind())); + case Qt::DisplayRole: + return m_item.name(); + case Qt::ToolTipRole: + if (hasTag(SymbolTag::Deprecated)) + return Tr::tr("Deprecated"); + break; + default: + break; + } + return TreeItem::data(column, role); + } + +protected: + const CallHierarchyItem m_item; + + bool hasTag(const SymbolTag tag) const + { + if (const std::optional> tags = m_item.symbolTags()) + return tags->contains(tag); + return false; + } +}; + +class CallHierarchyTreeItem : public CallHierarchyRootItem +{ +public: + CallHierarchyTreeItem(const CallHierarchyItem &item, const Direction direction, Client *client) + : CallHierarchyRootItem(item) , m_direction(direction) , m_client(client) { @@ -51,12 +86,6 @@ public: QVariant data(int column, int role) const override { switch (role) { - case Qt::DecorationRole: - if (m_item.symbolTags().value_or(QList()).contains(SymbolTag::Deprecated)) - return Utils::Icons::WARNING.icon(); - return symbolIcon(int(m_item.symbolKind())); - case Qt::DisplayRole: - return m_item.name(); case LinkRole: { if (!m_client) return QVariant(); @@ -69,8 +98,9 @@ public: return *detail; return {}; default: - return TreeItem::data(column, role); + break; } + return CallHierarchyRootItem::data(column, role); } bool canFetchMore() const override { @@ -95,7 +125,7 @@ public: if (result && !result->isNull()) { for (const CallHierarchyIncomingCall &item : result->toList()) { if (item.isValid()) - appendChild(new CallHierarchyItem(item.from(), m_direction, m_client)); + appendChild(new CallHierarchyTreeItem(item.from(), m_direction, m_client)); } } if (!hasChildren()) @@ -111,7 +141,7 @@ public: if (result && !result->isNull()) { for (const CallHierarchyOutgoingCall &item : result->toList()) { if (item.isValid()) - appendChild(new CallHierarchyItem(item.to(), m_direction, m_client)); + appendChild(new CallHierarchyTreeItem(item.to(), m_direction, m_client)); } } if (!hasChildren()) @@ -122,60 +152,28 @@ public: } protected: - const LanguageServerProtocol::CallHierarchyItem m_item; const Direction m_direction; bool m_fetchedChildren = false; QPointer m_client; }; -class CallHierarchyDirectionItem : public CallHierarchyItem +class CallHierarchyDirectionItem : public CallHierarchyTreeItem { public: - CallHierarchyDirectionItem(const LanguageServerProtocol::CallHierarchyItem &item, + CallHierarchyDirectionItem(const CallHierarchyItem &item, const Direction direction, Client *client) - : CallHierarchyItem(item, direction, client) + : CallHierarchyTreeItem(item, direction, client) {} QVariant data(int column, int role) const override { if (role == Qt::DisplayRole) return m_direction == Incoming ? Tr::tr("Incoming") : Tr::tr("Outgoing"); - if (role == Qt::DecorationRole) - return {}; - return CallHierarchyItem::data(column, role); + return TreeItem::data(column, role); } }; - -class CallHierarchyRootItem : public TreeItem -{ -public: - CallHierarchyRootItem(const LanguageServerProtocol::CallHierarchyItem &item, Client *client) - : m_item(item) - { - appendChild(new CallHierarchyDirectionItem(m_item, Incoming, client)); - appendChild(new CallHierarchyDirectionItem(m_item, Outgoing, client)); - } - - QVariant data(int column, int role) const override - { - switch (role) { - case Qt::DecorationRole: - if (m_item.symbolTags().value_or(QList()).contains(SymbolTag::Deprecated)) - return Utils::Icons::WARNING.icon(); - return symbolIcon(int(m_item.symbolKind())); - case Qt::DisplayRole: - return m_item.name(); - default: - return TreeItem::data(column, role); - } - } - -private: - const LanguageServerProtocol::CallHierarchyItem m_item; -}; - class CallHierarchy : public QWidget { public: @@ -212,7 +210,7 @@ public: AnnotatedItemDelegate m_delegate; NavigationTreeView *m_view; - TreeModel m_model; + TreeModel m_model; }; void CallHierarchy::updateHierarchyAtCursorPosition() @@ -254,11 +252,13 @@ void CallHierarchy::handlePrepareResponse(Client *client, if (error) client->log(*error); - const std::optional> + const std::optional> result = response.result(); if (result && !result->isNull()) { - for (const LanguageServerProtocol::CallHierarchyItem &item : result->toList()) { - auto newItem = new CallHierarchyRootItem(item, client); + for (const CallHierarchyItem &item : result->toList()) { + auto newItem = new CallHierarchyRootItem(item); + newItem->appendChild(new CallHierarchyDirectionItem(item, Incoming, client)); + newItem->appendChild(new CallHierarchyDirectionItem(item, Outgoing, client)); m_model.rootItem()->appendChild(newItem); m_view->expand(newItem->index()); newItem->forChildrenAtLevel(1, [&](const TreeItem *child) { From a7bf5f17c5f4baa2b5c208b6747d5bb5053f6a4d Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 2 Feb 2024 15:17:41 +0100 Subject: [PATCH 0061/1060] CppEditor: Code cosmetics in cppeditoroutline.cpp Mostly inlining and namepsaces. Change-Id: Ib5d22d40844d55ae029158d8cf3d694ecf2bc4c4 Reviewed-by: Christian Kandeler --- src/plugins/cppeditor/cppeditoroutline.cpp | 44 ++++++++-------------- 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/src/plugins/cppeditor/cppeditoroutline.cpp b/src/plugins/cppeditor/cppeditoroutline.cpp index d630a7ad1c6..9739bd50b4a 100644 --- a/src/plugins/cppeditor/cppeditoroutline.cpp +++ b/src/plugins/cppeditor/cppeditoroutline.cpp @@ -37,20 +37,17 @@ enum { UpdateOutlineIntervalInMs = 500 }; using namespace Core; using namespace Utils; -namespace { +namespace CppEditor::Internal { -class OutlineProxyModel : public QSortFilterProxyModel +class OutlineProxyModel final : public QSortFilterProxyModel { - Q_OBJECT - public: - OutlineProxyModel(CppEditor::Internal::OutlineModel &sourceModel, QObject *parent) + OutlineProxyModel(OutlineModel &sourceModel, QObject *parent) : QSortFilterProxyModel(parent) , m_sourceModel(sourceModel) - { - } + {} - bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const override + bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const final { // Ignore generated symbols, e.g. by macro expansion (Q_OBJECT) const QModelIndex sourceIndex = m_sourceModel.index(sourceRow, 0, sourceParent); @@ -63,19 +60,6 @@ private: CppEditor::Internal::OutlineModel &m_sourceModel; }; -QTimer *newSingleShotTimer(QObject *parent, int msInternal, const QString &objectName) -{ - auto *timer = new QTimer(parent); - timer->setObjectName(objectName); - timer->setSingleShot(true); - timer->setInterval(msInternal); - return timer; -} - -} // anonymous namespace - -namespace CppEditor::Internal { - static Key sortEditorDocumentOutlineKey() { return Key(Constants::CPPEDITOR_SETTINGSGROUP) @@ -101,7 +85,7 @@ static void setSortedEditorDocumentOutline(bool sorted) CppEditorOutline::CppEditorOutline(CppEditorWidget *editorWidget) : QObject(editorWidget) , m_editorWidget(editorWidget) - , m_combo(new Utils::TreeViewComboBox) + , m_combo(new TreeViewComboBox) { m_model = &editorWidget->cppEditorDocument()->outlineModel(); m_proxyModel = new OutlineProxyModel(*m_model, this); @@ -134,9 +118,13 @@ CppEditorOutline::CppEditorOutline(CppEditorWidget *editorWidget) connect(m_combo, &QComboBox::currentIndexChanged, this, &CppEditorOutline::updateToolTip); connect(m_model, &OutlineModel::modelReset, this, &CppEditorOutline::updateNow); + // Set up timers - m_updateIndexTimer = newSingleShotTimer(this, UpdateOutlineIntervalInMs, - QLatin1String("CppEditorOutline::m_updateIndexTimer")); + m_updateIndexTimer = new QTimer(this); + m_updateIndexTimer->setObjectName("CppEditorOutline::m_updateIndexTimer"); + m_updateIndexTimer->setSingleShot(true); + m_updateIndexTimer->setInterval(UpdateOutlineIntervalInMs); + connect(m_updateIndexTimer, &QTimer::timeout, this, &CppEditorOutline::updateIndexNow); } @@ -191,16 +179,14 @@ void CppEditorOutline::gotoSymbolInEditor() const QModelIndex modelIndex = m_combo->view()->currentIndex(); const QModelIndex sourceIndex = m_proxyModel->mapToSource(modelIndex); - const Utils::Link link = m_model->linkFromIndex(sourceIndex); + const Link link = m_model->linkFromIndex(sourceIndex); if (!link.hasValidTarget()) return; - Core::EditorManager::cutForwardNavigationHistory(); - Core::EditorManager::addCurrentPositionToNavigationHistory(); + EditorManager::cutForwardNavigationHistory(); + EditorManager::addCurrentPositionToNavigationHistory(); m_editorWidget->gotoLine(link.targetLine, link.targetColumn, true, true); emit m_editorWidget->activateEditor(); } } // namespace CppEditor::Internal - -#include From 1942506b2c84617a9d6f96df0f5b8421dc317c98 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Mon, 11 Mar 2024 11:43:43 +0100 Subject: [PATCH 0062/1060] Utils: Fix IntegerAspect::addToLayout The UI should show the volatileValue, not the value(). Change-Id: Ia4b4e596e757cfb3590d6df2f359f6a90f7c5790 Reviewed-by: hjk --- src/libs/utils/aspects.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/utils/aspects.cpp b/src/libs/utils/aspects.cpp index 1565e4bc300..6ef84c119e6 100644 --- a/src/libs/utils/aspects.cpp +++ b/src/libs/utils/aspects.cpp @@ -2354,7 +2354,7 @@ void IntegerAspect::addToLayout(Layouting::LayoutItem &parent) if (d->m_maximumValue && d->m_maximumValue) d->m_spinBox->setRange(int(d->m_minimumValue.value() / d->m_displayScaleFactor), int(d->m_maximumValue.value() / d->m_displayScaleFactor)); - d->m_spinBox->setValue(int(value() / d->m_displayScaleFactor)); // Must happen after setRange() + bufferToGui(); addLabeledItem(parent, d->m_spinBox); connect(d->m_spinBox.data(), &QSpinBox::valueChanged, this, &IntegerAspect::handleGuiChanged); From 685f452d91a4a733af5b9f9e3aff4a5e73ee37b2 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Mon, 11 Mar 2024 11:37:43 +0100 Subject: [PATCH 0063/1060] SettingsDialog: Call Aspect::cancel on cancel Previously the SettingsDialog did not call Aspect::cancel(). Without this, the volatile value is not reset if the user did some changes before pressing cancel. This "should" mean that re-opening the settings dialog should present the changed values again. But since not all aspects are implemented correctly, they reinitialize from their value instead of their volatileValue. When the Settings Dialog is reopened and applied, a warning is triggered as the container thinks its dirty, but the Aspect::apply returns false. Change-Id: I8fac66fc95f9118d69c789ced22481d121769f0b Reviewed-by: Reviewed-by: Christian Stenger Reviewed-by: hjk --- src/plugins/autotest/testsettingspage.cpp | 2 ++ .../artisticstyle/artisticstyle.cpp | 3 ++- .../beautifier/clangformat/clangformat.cpp | 1 + .../beautifier/uncrustify/uncrustify.cpp | 2 ++ .../coreplugin/dialogs/ioptionspage.cpp | 25 +++++++++++++++++++ src/plugins/coreplugin/dialogs/ioptionspage.h | 3 +++ .../coreplugin/dialogs/settingsdialog.cpp | 16 +++++++----- src/plugins/git/gerrit/gerritoptionspage.cpp | 10 ++++++-- 8 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/plugins/autotest/testsettingspage.cpp b/src/plugins/autotest/testsettingspage.cpp index c11e2dfe318..4bde0e98cb4 100644 --- a/src/plugins/autotest/testsettingspage.cpp +++ b/src/plugins/autotest/testsettingspage.cpp @@ -153,6 +153,8 @@ TestSettingsWidget::TestSettingsWidget() if (!changedIds.isEmpty()) TestTreeModel::instance()->rebuild(changedIds); }); + + setOnCancel([] { Internal::testSettings().cancel(); }); } enum TestBaseInfo diff --git a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp index 2982ac267bc..a3aa30d78e9 100644 --- a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp +++ b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp @@ -221,9 +221,10 @@ public: setOnApply([&s, configurations] { s.customStyle.setValue(configurations->currentConfiguration()); - settings().apply(); + s.apply(); s.save(); }); + setOnCancel([&s] { s.cancel(); }); s.read(); diff --git a/src/plugins/beautifier/clangformat/clangformat.cpp b/src/plugins/beautifier/clangformat/clangformat.cpp index 95de1965c3e..22bcea77f79 100644 --- a/src/plugins/beautifier/clangformat/clangformat.cpp +++ b/src/plugins/beautifier/clangformat/clangformat.cpp @@ -300,6 +300,7 @@ public: settings().apply(); settings().save(); }); + setOnCancel([] { settings().cancel(); }); s.read(); diff --git a/src/plugins/beautifier/uncrustify/uncrustify.cpp b/src/plugins/beautifier/uncrustify/uncrustify.cpp index 75bd5252ed9..a18371ff53b 100644 --- a/src/plugins/beautifier/uncrustify/uncrustify.cpp +++ b/src/plugins/beautifier/uncrustify/uncrustify.cpp @@ -225,6 +225,8 @@ public: settings().apply(); s.save(); }); + + setOnCancel([] { settings().cancel(); }); } }; diff --git a/src/plugins/coreplugin/dialogs/ioptionspage.cpp b/src/plugins/coreplugin/dialogs/ioptionspage.cpp index 6c2970ca45d..d4bc7276e2d 100644 --- a/src/plugins/coreplugin/dialogs/ioptionspage.cpp +++ b/src/plugins/coreplugin/dialogs/ioptionspage.cpp @@ -29,6 +29,7 @@ class IOptionsPageWidgetPrivate { public: std::function m_onApply; + std::function m_onCancel; std::function m_onFinish; }; @@ -104,6 +105,11 @@ void IOptionsPageWidget::setOnApply(const std::function &func) d->m_onApply = func; } +void IOptionsPageWidget::setOnCancel(const std::function &func) +{ + d->m_onCancel = func; +} + /*! Sets the function that is called by default on finish to \a func. */ @@ -122,6 +128,12 @@ void IOptionsPageWidget::apply() d->m_onApply(); } +void IOptionsPageWidget::cancel() +{ + if (d->m_onCancel) + d->m_onCancel(); +} + /*! Calls the finish function, if set. \sa setOnFinish @@ -260,6 +272,19 @@ void IOptionsPage::apply() } } +void IOptionsPage::cancel() +{ + if (auto widget = qobject_cast(d->m_widget)) + widget->cancel(); + + if (d->m_settingsProvider) { + AspectContainer *container = d->m_settingsProvider(); + QTC_ASSERT(container, return); + if (container->isDirty()) + container->cancel(); + } +} + /*! Called directly before the \uicontrol Options dialog closes. Here you should delete the widget that was created in widget() to free resources. diff --git a/src/plugins/coreplugin/dialogs/ioptionspage.h b/src/plugins/coreplugin/dialogs/ioptionspage.h index bb0886dd67a..618cbc80322 100644 --- a/src/plugins/coreplugin/dialogs/ioptionspage.h +++ b/src/plugins/coreplugin/dialogs/ioptionspage.h @@ -27,11 +27,13 @@ public: IOptionsPageWidget(); ~IOptionsPageWidget(); void setOnApply(const std::function &func); + void setOnCancel(const std::function &func); void setOnFinish(const std::function &func); protected: friend class IOptionsPage; virtual void apply(); + virtual void cancel(); virtual void finish(); private: @@ -59,6 +61,7 @@ public: virtual QWidget *widget(); virtual void apply(); + virtual void cancel(); virtual void finish(); virtual bool matches(const QRegularExpression ®exp) const; diff --git a/src/plugins/coreplugin/dialogs/settingsdialog.cpp b/src/plugins/coreplugin/dialogs/settingsdialog.cpp index 6dfd9106eb5..b2e4b9e969f 100644 --- a/src/plugins/coreplugin/dialogs/settingsdialog.cpp +++ b/src/plugins/coreplugin/dialogs/settingsdialog.cpp @@ -594,11 +594,13 @@ void SettingsDialog::createGui() QWidget *emptyWidget = new QWidget(this); m_stackedLayout->addWidget(emptyWidget); // no category selected, for example when filtering - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | - QDialogButtonBox::Apply | - QDialogButtonBox::Cancel); - connect(buttonBox->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, - this, &SettingsDialog::apply); + QDialogButtonBox *buttonBox = new QDialogButtonBox( + QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel); + connect( + buttonBox->button(QDialogButtonBox::Apply), + &QAbstractButton::clicked, + this, + &SettingsDialog::apply); connect(buttonBox, &QDialogButtonBox::accepted, this, &SettingsDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &SettingsDialog::reject); @@ -744,8 +746,10 @@ void SettingsDialog::reject() return; m_finished = true; disconnectTabWidgets(); - for (IOptionsPage *page : std::as_const(m_pages)) + for (IOptionsPage *page : std::as_const(m_pages)) { + page->cancel(); page->finish(); + } done(QDialog::Rejected); } diff --git a/src/plugins/git/gerrit/gerritoptionspage.cpp b/src/plugins/git/gerrit/gerritoptionspage.cpp index 8954db43aa8..392a8f81461 100644 --- a/src/plugins/git/gerrit/gerritoptionspage.cpp +++ b/src/plugins/git/gerrit/gerritoptionspage.cpp @@ -63,8 +63,14 @@ public: Git::Tr::tr("P&rotocol:"), httpsCheckBox }.attachTo(this); - setOnApply([this, hostLineEdit, userLineEdit, sshChooser, - curlChooser, portSpinBox, httpsCheckBox, onChanged] { + setOnApply([this, + hostLineEdit, + userLineEdit, + sshChooser, + curlChooser, + portSpinBox, + httpsCheckBox, + onChanged] { GerritParameters newParameters; newParameters.server = GerritServer(hostLineEdit->text().trimmed(), static_cast(portSpinBox->value()), From 71ada2b47872255112c4b0f000c39603e94b8fdd Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 7 Mar 2024 11:10:31 +0100 Subject: [PATCH 0064/1060] CppEditor: Consider all "else" branches ... in "Add braces to control statement" quickfix. Change-Id: Ie9dde7692e72300d350029cac01b712795c6e200 Reviewed-by: Christian Stenger Reviewed-by: Reviewed-by: Qt CI Bot --- src/plugins/cppeditor/cppquickfix_test.cpp | 292 +++++++++++++++++++++ src/plugins/cppeditor/cppquickfixes.cpp | 42 ++- 2 files changed, 331 insertions(+), 3 deletions(-) diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp index 98650baa217..0a5b71c814c 100644 --- a/src/plugins/cppeditor/cppquickfix_test.cpp +++ b/src/plugins/cppeditor/cppquickfix_test.cpp @@ -8243,6 +8243,298 @@ void MyObject::f() original = R"delim( void MyObject::f() +{ + @if (true) + emit mySig(); + else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + @if (true) { + emit mySig(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if with one else, unbraced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (true) { + emit mySig(); + } else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + @if (true) { + emit mySig(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if with one else, if braced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (true) + emit mySig(); + else { + emit otherSig(); + } +})delim"; + expected = R"delim( +void MyObject::f() +{ + @if (true) { + emit mySig(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if with one else, else braced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (true) { + emit mySig(); + } else { + emit otherSig(); + } +})delim"; + expected.clear(); + QTest::newRow("if with one else, both braced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) + emit sig2(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } +})delim"; + QTest::newRow("if-else chain without final else, unbraced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) { + emit sig1(); + } else if (x == 2) + emit sig2(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } +})delim"; + QTest::newRow("if-else chain without final else, partially braced 1") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) { + emit sig2(); + } +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } +})delim"; + QTest::newRow("if-else chain without final else, partially braced 2") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } +})delim"; + expected.clear(); + QTest::newRow("if-else chain without final else, fully braced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) + emit sig2(); + else if (x == 3) + emit sig3(); + else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if-else chain, unbraced") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) { + emit sig1(); + } else if (x == 2) + emit sig2(); + else if (x == 3) + emit sig3(); + else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if-else chain, partially braced 1") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) { + emit sig2(); + } else if (x == 3) + emit sig3(); + else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if-else chain, partially braced 2") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) + emit sig2(); + else if (x == 3) { + emit sig3(); + } else + emit otherSig(); +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if-else chain, partially braced 3") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) + emit sig1(); + else if (x == 2) + emit sig2(); + else if (x == 3) + emit sig3(); + else { + emit otherSig(); + } +})delim"; + expected = R"delim( +void MyObject::f() +{ + if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + QTest::newRow("if-else chain, partially braced 4") << original << expected; + + original = R"delim( +void MyObject::f() +{ + @if (x == 1) { + emit sig1(); + } else if (x == 2) { + emit sig2(); + } else if (x == 3) { + emit sig3(); + } else { + emit otherSig(); + } +})delim"; + expected.clear(); + QTest::newRow("if-else chain, fully braced") << original << expected; + + original = R"delim( +void MyObject::f() { @while (true) emit mySig(); diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp index 383c5245ae1..9ac67e1e29a 100644 --- a/src/plugins/cppeditor/cppquickfixes.cpp +++ b/src/plugins/cppeditor/cppquickfixes.cpp @@ -809,9 +809,11 @@ template class AddBracesToControlStatementOp : public CppQui { public: AddBracesToControlStatementOp(const CppQuickFixInterface &interface, - const QList &statements) + const QList &statements, + StatementAST *elseStatement, + int elseToken) : CppQuickFixOperation(interface, 0) - , m_statements(statements) + , m_statements(statements), m_elseStatement(elseStatement), m_elseToken(elseToken) { setDescription(Tr::tr("Add Curly Braces")); } @@ -828,11 +830,23 @@ public: if constexpr (std::is_same_v) { const int end = currentFile->startOf(statement->while_token); changes.insert(end, QLatin1String("} ")); + } else if constexpr (std::is_same_v) { + if (statement->else_statement) { + changes.insert(currentFile->startOf(statement->else_token), "} "); + } else { + changes.insert(currentFile->endOf(statement->statement->lastToken() - 1), + "\n}"); + } + } else { const int end = currentFile->endOf(statement->statement->lastToken() - 1); changes.insert(end, QLatin1String("\n}")); } } + if (m_elseStatement) { + changes.insert(currentFile->endOf(m_elseToken), " {"); + changes.insert(currentFile->endOf(m_elseStatement->lastToken() - 1), "\n}"); + } currentFile->setChangeSet(changes); currentFile->apply(); @@ -840,6 +854,8 @@ public: private: const QList m_statements; + StatementAST * const m_elseStatement; + const int m_elseToken; }; } // anonymous namespace @@ -851,10 +867,30 @@ bool checkControlStatementsHelper(const CppQuickFixInterface &interface, QuickFi if (!statement) return false; + QList statements; if (interface.isCursorOn(triggerToken(statement)) && statement->statement && !statement->statement->asCompoundStatement()) { - result << new AddBracesToControlStatementOp(interface, QList{statement}); + statements << statement; } + + StatementAST *elseStmt = nullptr; + int elseToken = 0; + if constexpr (std::is_same_v) { + IfStatementAST *currentIfStmt = statement; + for (elseStmt = currentIfStmt->else_statement, elseToken = currentIfStmt->else_token; + elseStmt && (currentIfStmt = elseStmt->asIfStatement()); + elseStmt = currentIfStmt->else_statement, elseToken = currentIfStmt->else_token) { + if (currentIfStmt->statement && !currentIfStmt->statement->asCompoundStatement()) + statements << currentIfStmt; + } + if (elseStmt && (elseStmt->asIfStatement() || elseStmt->asCompoundStatement())) { + elseStmt = nullptr; + elseToken = 0; + } + } + + if (!statements.isEmpty() || elseStmt) + result << new AddBracesToControlStatementOp(interface, statements, elseStmt, elseToken); return true; } From 699a9aa04a88e8d9669c11970ea0425f4ae68e8e Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Fri, 15 Mar 2024 08:21:38 +0100 Subject: [PATCH 0065/1060] QmlProjectManager: Fix qbs build Change-Id: I538c03d4f914510913e84c29748ab6f414a086c4 Reviewed-by: Tim Jenssen --- src/plugins/qmlprojectmanager/qmlprojectmanager.qbs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs index da6bebd6135..76fcd701578 100644 --- a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs +++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs @@ -50,6 +50,7 @@ QtcPlugin { "generatecmakelists.cpp", "generatecmakelists.h", "generatecmakelistsconstants.h", "checkablefiletreeitem.cpp", "checkablefiletreeitem.h", + "cmakegenerator.cpp", "cmakegenerator.h", "cmakegeneratordialogtreemodel.cpp", "cmakegeneratordialogtreemodel.h", "cmakegeneratordialog.cpp", "cmakegeneratordialog.h", "cmakeprojectconverter.cpp", "cmakeprojectconverter.h", From 7e01d9082438aa758d17c583a07c750565f8f205 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Fri, 15 Mar 2024 07:19:18 +0100 Subject: [PATCH 0066/1060] QmlDesigner: Fix build Change-Id: Iadf44d41d1f5236fa6311b93a4721829018eea6f Reviewed-by: Tim Jenssen --- .../components/collectioneditor/collectiondetails.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp b/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp index 600be3911ab..ddfb82746cd 100644 --- a/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp +++ b/src/plugins/qmldesigner/components/collectioneditor/collectiondetails.cpp @@ -724,7 +724,7 @@ QString CollectionDetails::toCsv() const if (value.isDouble()) content += QString::number(value.toDouble()) + ','; else if (value.isBool()) - content += value.toBool() ? "true," : "false,"; + content += value.toBool() ? QString("true,") : QString("false,"); else content += value.toString() + ','; } From 45de53d353a37a6d134cdbbd40d4a850a47e6748 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 1 Mar 2024 17:19:48 +0100 Subject: [PATCH 0067/1060] LSP: Add type hierarchy support Fixes: QTCREATORBUG-28116 Change-Id: Ibaed23144f63fa84fa97ae9106d0f0baf8f53118 Reviewed-by: David Schulz Reviewed-by: --- .../languageserverprotocol/CMakeLists.txt | 1 + .../clientcapabilities.h | 6 + src/libs/languageserverprotocol/jsonkeys.h | 2 + .../languageserverprotocol.qbs | 2 + .../servercapabilities.cpp | 22 + .../servercapabilities.h | 4 + .../languageserverprotocol/typehierarchy.cpp | 28 + .../languageserverprotocol/typehierarchy.h | 85 +++ src/plugins/cppeditor/cpptypehierarchy.cpp | 2 +- src/plugins/languageclient/CMakeLists.txt | 2 +- .../languageclient/callandtypehierarchy.cpp | 508 ++++++++++++++++++ ...callhierarchy.h => callandtypehierarchy.h} | 5 +- src/plugins/languageclient/callhierarchy.cpp | 318 ----------- src/plugins/languageclient/client.cpp | 5 +- src/plugins/languageclient/languageclient.qbs | 7 +- .../languageclient/languageclientplugin.cpp | 3 +- 16 files changed, 674 insertions(+), 326 deletions(-) create mode 100644 src/libs/languageserverprotocol/typehierarchy.cpp create mode 100644 src/libs/languageserverprotocol/typehierarchy.h create mode 100644 src/plugins/languageclient/callandtypehierarchy.cpp rename src/plugins/languageclient/{callhierarchy.h => callandtypehierarchy.h} (67%) delete mode 100644 src/plugins/languageclient/callhierarchy.cpp diff --git a/src/libs/languageserverprotocol/CMakeLists.txt b/src/libs/languageserverprotocol/CMakeLists.txt index a3031413a46..02610460165 100644 --- a/src/libs/languageserverprotocol/CMakeLists.txt +++ b/src/libs/languageserverprotocol/CMakeLists.txt @@ -22,5 +22,6 @@ add_qtc_library(LanguageServerProtocol servercapabilities.cpp servercapabilities.h shutdownmessages.cpp shutdownmessages.h textsynchronization.cpp textsynchronization.h + typehierarchy.cpp typehierarchy.h workspace.cpp workspace.h ) diff --git a/src/libs/languageserverprotocol/clientcapabilities.h b/src/libs/languageserverprotocol/clientcapabilities.h index b2311d7e726..91c9954cd7a 100644 --- a/src/libs/languageserverprotocol/clientcapabilities.h +++ b/src/libs/languageserverprotocol/clientcapabilities.h @@ -529,6 +529,12 @@ public: void setCallHierarchy(const DynamicRegistrationCapabilities &callHierarchy) { insert(callHierarchyKey, callHierarchy); } void clearCallHierarchy() { remove(callHierarchyKey); } + + std::optional typeHierarchy() const + { return optionalValue(typeHierarchyKey); } + void setTypeHierarchy(const DynamicRegistrationCapabilities &typeHierarchy) + { insert(typeHierarchyKey, typeHierarchy); } + void clearTypeHierarchy() { remove(typeHierarchyKey); } }; class LANGUAGESERVERPROTOCOL_EXPORT SemanticTokensWorkspaceClientCapabilities : public JsonObject diff --git a/src/libs/languageserverprotocol/jsonkeys.h b/src/libs/languageserverprotocol/jsonkeys.h index c2b5e545f29..37894f166e9 100644 --- a/src/libs/languageserverprotocol/jsonkeys.h +++ b/src/libs/languageserverprotocol/jsonkeys.h @@ -218,6 +218,8 @@ constexpr Key trimTrailingWhitespaceKey{"trimTrailingWhitespace"}; constexpr Key typeDefinitionKey{"typeDefinition"}; constexpr Key typeDefinitionProviderKey{"typeDefinitionProvider"}; constexpr Key typeKey{"type"}; +constexpr Key typeHierarchyKey{"typeHierarchy"}; +constexpr Key typeHierarchyProviderKey{"typeHierarchyProvider"}; constexpr Key unregistrationsKey{"unregistrations"}; constexpr Key uriKey{"uri"}; constexpr Key valueKey{"value"}; diff --git a/src/libs/languageserverprotocol/languageserverprotocol.qbs b/src/libs/languageserverprotocol/languageserverprotocol.qbs index 0368ceafee8..2bf717c2930 100644 --- a/src/libs/languageserverprotocol/languageserverprotocol.qbs +++ b/src/libs/languageserverprotocol/languageserverprotocol.qbs @@ -44,6 +44,8 @@ QtcLibrary { "shutdownmessages.h", "textsynchronization.cpp", "textsynchronization.h", + "typehierarchy.cpp", + "typehierarchy.h", "workspace.cpp", "workspace.h", ] diff --git a/src/libs/languageserverprotocol/servercapabilities.cpp b/src/libs/languageserverprotocol/servercapabilities.cpp index 885198d12e8..0c57f47131a 100644 --- a/src/libs/languageserverprotocol/servercapabilities.cpp +++ b/src/libs/languageserverprotocol/servercapabilities.cpp @@ -196,6 +196,28 @@ void ServerCapabilities::setCallHierarchyProvider( insert(callHierarchyProviderKey, val); } +std::optional> ServerCapabilities::typeHierarchyProvider() + const +{ + const QJsonValue &provider = value(typeHierarchyProviderKey); + if (provider.isBool()) + return provider.toBool(); + else if (provider.isObject()) + return WorkDoneProgressOptions(provider.toObject()); + return std::nullopt; +} + +void ServerCapabilities::setTypeHierarchyProvider( + const std::variant &typeHierarchyProvider) +{ + QJsonValue val; + if (std::holds_alternative(typeHierarchyProvider)) + val = std::get(typeHierarchyProvider); + else if (std::holds_alternative(typeHierarchyProvider)) + val = QJsonObject(std::get(typeHierarchyProvider)); + insert(typeHierarchyProviderKey, val); +} + std::optional> ServerCapabilities::workspaceSymbolProvider() const { diff --git a/src/libs/languageserverprotocol/servercapabilities.h b/src/libs/languageserverprotocol/servercapabilities.h index c3b50dd5904..32598d2afa5 100644 --- a/src/libs/languageserverprotocol/servercapabilities.h +++ b/src/libs/languageserverprotocol/servercapabilities.h @@ -330,6 +330,10 @@ public: void setCallHierarchyProvider(const std::variant &callHierarchyProvider); void clearCallHierarchyProvider() { remove(callHierarchyProviderKey); } + std::optional> typeHierarchyProvider() const; + void setTypeHierarchyProvider(const std::variant &typeHierarchyProvider); + void clearTypeHierarchyProvider() { remove(typeHierarchyProviderKey); } + // The server provides workspace symbol support. std::optional> workspaceSymbolProvider() const; void setWorkspaceSymbolProvider(std::variant workspaceSymbolProvider); diff --git a/src/libs/languageserverprotocol/typehierarchy.cpp b/src/libs/languageserverprotocol/typehierarchy.cpp new file mode 100644 index 00000000000..1734e25a6b6 --- /dev/null +++ b/src/libs/languageserverprotocol/typehierarchy.cpp @@ -0,0 +1,28 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0 WITH Qt-GPL-exception-1.0 + +#include "typehierarchy.h" + +namespace LanguageServerProtocol { + +bool TypeHierarchyItem::isValid() const +{ + return contains(nameKey) && contains(kindKey) && contains(uriKey) && contains(rangeKey) + && contains(selectionRangeKey); +} +std::optional> TypeHierarchyItem::symbolTags() const +{ + return Internal::getSymbolTags(*this); +} + +PrepareTypeHierarchyRequest::PrepareTypeHierarchyRequest(const TextDocumentPositionParams ¶ms) + : Request(methodName, params) +{} +TypeHierarchySupertypesRequest::TypeHierarchySupertypesRequest(const TypeHierarchyParams ¶ms) + : Request(methodName, params) +{} +TypeHierarchySubtypesRequest::TypeHierarchySubtypesRequest(const TypeHierarchyParams ¶ms) + : Request(methodName, params) +{} + +} // namespace LanguageServerProtocol diff --git a/src/libs/languageserverprotocol/typehierarchy.h b/src/libs/languageserverprotocol/typehierarchy.h new file mode 100644 index 00000000000..d5e88c8cfd3 --- /dev/null +++ b/src/libs/languageserverprotocol/typehierarchy.h @@ -0,0 +1,85 @@ +// Copyright (C) 2022 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0 WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "jsonrpcmessages.h" + +namespace LanguageServerProtocol { + +class LANGUAGESERVERPROTOCOL_EXPORT TypeHierarchyItem : public JsonObject +{ +public: + using JsonObject::JsonObject; + + QString name() const { return typedValue(nameKey); } + void setName(const QString &name) { insert(nameKey, name); } + + SymbolKind symbolKind() const { return SymbolKind(typedValue(kindKey)); } + void setSymbolKind(const SymbolKind &symbolKind) { insert(kindKey, int(symbolKind)); } + + std::optional> symbolTags() const; + + std::optional detail() const { return optionalValue(detailKey); } + void setDetail(const QString &detail) { insert(detailKey, detail); } + void clearDetail() { remove(detailKey); } + + DocumentUri uri() const { return DocumentUri::fromProtocol(typedValue(uriKey)); } + void setUri(const DocumentUri &uri) { insert(uriKey, uri); } + + Range range() const { return typedValue(rangeKey); } + void setRange(const Range &range) { insert(rangeKey, range); } + + Range selectionRange() const { return typedValue(selectionRangeKey); } + void setSelectionRange(Range selectionRange) { insert(selectionRangeKey, selectionRange); } + + /* + * A data entry field that is preserved between a type hierarchy prepare and + * supertypes or subtypes requests. It could also be used to identify the + * type hierarchy in the server, helping improve the performance on + * resolving supertypes and subtypes. + */ + std::optional data() const { return optionalValue(dataKey); } + + bool isValid() const override; +}; + +class LANGUAGESERVERPROTOCOL_EXPORT PrepareTypeHierarchyRequest : public Request< + LanguageClientArray, std::nullptr_t, TextDocumentPositionParams> +{ +public: + explicit PrepareTypeHierarchyRequest(const TextDocumentPositionParams ¶ms); + using Request::Request; + constexpr static const char methodName[] = "textDocument/prepareTypeHierarchy"; +}; + +class LANGUAGESERVERPROTOCOL_EXPORT TypeHierarchyParams : public JsonObject +{ +public: + using JsonObject::JsonObject; + + TypeHierarchyItem item() const { return typedValue(itemKey); } + void setItem(const TypeHierarchyItem &item) { insert(itemKey, item); } + + bool isValid() const override { return contains(itemKey); } +}; + +class LANGUAGESERVERPROTOCOL_EXPORT TypeHierarchySupertypesRequest : public Request< + LanguageClientArray, std::nullptr_t, TypeHierarchyParams> +{ +public: + explicit TypeHierarchySupertypesRequest(const TypeHierarchyParams ¶ms); + using Request::Request; + constexpr static const char methodName[] = "typeHierarchy/supertypes"; +}; + +class LANGUAGESERVERPROTOCOL_EXPORT TypeHierarchySubtypesRequest + : public Request, std::nullptr_t, TypeHierarchyParams> +{ +public: + explicit TypeHierarchySubtypesRequest(const TypeHierarchyParams ¶ms); + using Request::Request; + constexpr static const char methodName[] = "typeHierarchy/subtypes"; +}; + +} // namespace LanguageServerProtocol diff --git a/src/plugins/cppeditor/cpptypehierarchy.cpp b/src/plugins/cppeditor/cpptypehierarchy.cpp index d0a523ce133..ab4bc0525e8 100644 --- a/src/plugins/cppeditor/cpptypehierarchy.cpp +++ b/src/plugins/cppeditor/cpptypehierarchy.cpp @@ -420,7 +420,7 @@ class CppTypeHierarchyFactory final : public TextEditor::TypeHierarchyWidgetFact if (!textEditor) return nullptr; const auto cppDoc = qobject_cast(textEditor->textDocument()); - if (!cppDoc /* || cppDoc->usesClangd() */) + if (!cppDoc || cppDoc->usesClangd()) return nullptr; return new CppTypeHierarchyWidget; diff --git a/src/plugins/languageclient/CMakeLists.txt b/src/plugins/languageclient/CMakeLists.txt index a74bc330267..e098168a1c1 100644 --- a/src/plugins/languageclient/CMakeLists.txt +++ b/src/plugins/languageclient/CMakeLists.txt @@ -8,7 +8,7 @@ add_qtc_plugin(LanguageClient PUBLIC_DEPENDS LanguageServerProtocol Qt::Core PLUGIN_DEPENDS ProjectExplorer Core TextEditor SOURCES - callhierarchy.cpp callhierarchy.h + callandtypehierarchy.cpp callandtypehierarchy.h client.cpp client.h clientrequest.cpp clientrequest.h currentdocumentsymbolsrequest.cpp currentdocumentsymbolsrequest.h diff --git a/src/plugins/languageclient/callandtypehierarchy.cpp b/src/plugins/languageclient/callandtypehierarchy.cpp new file mode 100644 index 00000000000..14e5935c6a3 --- /dev/null +++ b/src/plugins/languageclient/callandtypehierarchy.cpp @@ -0,0 +1,508 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0 WITH Qt-GPL-exception-1.0 + +#include "callandtypehierarchy.h" + +#include "languageclientmanager.h" +#include "languageclienttr.h" + +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include + +using namespace Utils; +using namespace TextEditor; +using namespace LanguageServerProtocol; + +namespace LanguageClient { + +namespace { +enum { + AnnotationRole = Qt::UserRole + 1, + LinkRole +}; +} + +template +class HierarchyItem : public TreeItem +{ +public: + HierarchyItem(const Item &item, Client *client) + : m_item(item) + , m_client(client) + {} + +protected: + QVariant data(int column, int role) const override + { + switch (role) { + case Qt::DecorationRole: + if (hasTag(SymbolTag::Deprecated)) + return Utils::Icons::WARNING.icon(); + return symbolIcon(int(m_item.symbolKind())); + case Qt::DisplayRole: + return m_item.name(); + case Qt::ToolTipRole: + if (hasTag(SymbolTag::Deprecated)) + return Tr::tr("Deprecated"); + return {}; + case LinkRole: { + if (!m_client) + return QVariant(); + const Position start = m_item.selectionRange().start(); + return QVariant::fromValue( + Link(m_client->serverUriToHostPath(m_item.uri()), start.line() + 1, start.character())); + } + case AnnotationRole: + if (const std::optional detail = m_item.detail()) + return *detail; + return {}; + default: + return TreeItem::data(column, role); + } + } + +private: + bool canFetchMore() const override { return m_client && !m_fetchedChildren; } + + void fetchMore() override + { + m_fetchedChildren = true; + if (!m_client) + return; + + Params params; + params.setItem(m_item); + Request request(params); + request.setResponseCallback( + [this](const typename Request::Response &response) { + const std::optional> result = response.result(); + if (result && !result->isNull()) { + for (const Result &item : result->toList()) { + if (item.isValid()) + appendChild(new HierarchyItem(getSourceItem(item), m_client)); + } + } + if (!hasChildren()) + update(); + }); + m_client->sendMessage(request); + } + + Item getSourceItem(const Result &result) + { + if constexpr (std::is_same_v) + return result.from(); + if constexpr (std::is_same_v) + return result.to(); + if constexpr (std::is_same_v) + return result; + } + + bool hasTag(const SymbolTag tag) const + { + if (const std::optional> tags = m_item.symbolTags()) + return tags->contains(tag); + return false; + } + + const Item m_item; + bool m_fetchedChildren = false; + QPointer m_client; +}; + +class CallHierarchyIncomingItem : public HierarchyItem +{ +public: + CallHierarchyIncomingItem(const LanguageServerProtocol::CallHierarchyItem &item, Client *client) + : HierarchyItem(item, client) + {} + +private: + QVariant data(int column, int role) const override + { + if (role == Qt::DisplayRole) + return Tr::tr("Incoming"); + if (role == Qt::DecorationRole) + return {}; + return HierarchyItem::data(column, role); + } +}; + +class CallHierarchyOutgoingItem : public HierarchyItem +{ +public: + CallHierarchyOutgoingItem(const LanguageServerProtocol::CallHierarchyItem &item, Client *client) + : HierarchyItem(item, client) + {} + +private: + QVariant data(int column, int role) const override + { + if (role == Qt::DisplayRole) + return Tr::tr("Outgoing"); + if (role == Qt::DecorationRole) + return {}; + return HierarchyItem::data(column, role); + } +}; + +template class HierarchyRootItem : public TreeItem +{ +public: + HierarchyRootItem(const Item &item) + : m_item(item) + {} + +private: + QVariant data(int column, int role) const override + { + switch (role) { + case Qt::DecorationRole: + if (m_item.symbolTags().value_or(QList()).contains(SymbolTag::Deprecated)) + return Utils::Icons::WARNING.icon(); + return symbolIcon(int(m_item.symbolKind())); + case Qt::DisplayRole: + return m_item.name(); + default: + return TreeItem::data(column, role); + } + } + + const Item m_item; +}; + + +class CallHierarchyRootItem : public HierarchyRootItem +{ +public: + CallHierarchyRootItem(const LanguageServerProtocol::CallHierarchyItem &item, Client *client) + : HierarchyRootItem(item) + { + appendChild(new CallHierarchyIncomingItem(item, client)); + appendChild(new CallHierarchyOutgoingItem(item, client)); + } +}; + +class TypeHierarchyBasesItem : public HierarchyItem +{ +public: + TypeHierarchyBasesItem(const LanguageServerProtocol::TypeHierarchyItem &item, Client *client) + : HierarchyItem(item, client) + {} + +private: + QVariant data(int column, int role) const override + { + if (role == Qt::DisplayRole) + return Tr::tr("Bases"); + if (role == Qt::DecorationRole) + return {}; + return HierarchyItem::data(column, role); + } +}; + +class TypeHierarchyDerivedItem : public HierarchyItem +{ +public: + TypeHierarchyDerivedItem(const LanguageServerProtocol::TypeHierarchyItem &item, Client *client) + : HierarchyItem(item, client) + {} + +private: + QVariant data(int column, int role) const override + { + if (role == Qt::DisplayRole) + return Tr::tr("Derived"); + if (role == Qt::DecorationRole) + return {}; + return HierarchyItem::data(column, role); + } +}; + +class TypeHierarchyRootItem : public HierarchyRootItem +{ +public: + TypeHierarchyRootItem(const LanguageServerProtocol::TypeHierarchyItem &item, Client *client) + : HierarchyRootItem(item) + { + appendChild(new TypeHierarchyBasesItem(item, client)); + appendChild(new TypeHierarchyDerivedItem(item, client)); + } +}; + +class HierarchyWidgetHelper +{ +public: + HierarchyWidgetHelper(QWidget *theWidget) : m_view(new NavigationTreeView(theWidget)) + { + m_delegate.setDelimiter(" "); + m_delegate.setAnnotationRole(AnnotationRole); + + m_view->setModel(&m_model); + m_view->setActivationMode(SingleClickActivation); + m_view->setItemDelegate(&m_delegate); + + theWidget->setLayout(new QVBoxLayout); + theWidget->layout()->addWidget(m_view); + theWidget->layout()->setContentsMargins(0, 0, 0, 0); + theWidget->layout()->setSpacing(0); + + QObject::connect(m_view, &NavigationTreeView::activated, + theWidget, [this](const QModelIndex &index) { onItemActivated(index); }); + QObject::connect(m_view, &QTreeView::doubleClicked, + theWidget, [this](const QModelIndex &index) { onItemDoubleClicked(index); }); + } + + void updateHierarchyAtCursorPosition() + { + m_model.clear(); + + BaseTextEditor *editor = BaseTextEditor::currentTextEditor(); + if (!editor) + return; + + Core::IDocument *document = editor->document(); + + Client *client = LanguageClientManager::clientForFilePath(document->filePath()); + if (!client) + return; + + TextDocumentPositionParams params; + params.setTextDocument(TextDocumentIdentifier(client->hostPathToServerUri(document->filePath()))); + params.setPosition(Position(editor->editorWidget()->textCursor())); + sendRequest(client, params, document); + } + +protected: + void addItem(TreeItem *item) + { + m_model.rootItem()->appendChild(item); + m_view->expand(item->index()); + item->forChildrenAtLevel(1, [&](const TreeItem *child) { m_view->expand(child->index()); }); + } + +private: + virtual void sendRequest(Client *client, const TextDocumentPositionParams ¶ms, + const Core::IDocument *document) = 0; + + virtual void onItemDoubleClicked(const QModelIndex &index) { Q_UNUSED(index) } + + void onItemActivated(const QModelIndex &index) + { + const auto link = index.data(LinkRole).value(); + if (link.hasValidTarget()) + Core::EditorManager::openEditorAt(link); + } + + AnnotatedItemDelegate m_delegate; + NavigationTreeView * const m_view; + TreeModel m_model; +}; + +class CallHierarchy : public QWidget, public HierarchyWidgetHelper +{ +public: + CallHierarchy() : HierarchyWidgetHelper(this) + { + connect(LanguageClientManager::instance(), &LanguageClientManager::openCallHierarchy, + this, [this] { updateHierarchyAtCursorPosition(); }); + } + +private: + void sendRequest(Client *client, const TextDocumentPositionParams ¶ms, + const Core::IDocument *document) override + { + if (!supportsCallHierarchy(client, document)) + return; + + PrepareCallHierarchyRequest request(params); + request.setResponseCallback([this, client = QPointer(client)]( + const PrepareCallHierarchyRequest::Response &response) { + handlePrepareResponse(client, response); + }); + client->sendMessage(request); + } + + void handlePrepareResponse(Client *client, + const PrepareCallHierarchyRequest::Response &response) + { + if (!client) + return; + const std::optional error = response.error(); + if (error) + client->log(*error); + + const std::optional> + result = response.result(); + if (result && !result->isNull()) { + for (const LanguageServerProtocol::CallHierarchyItem &item : result->toList()) + addItem(new CallHierarchyRootItem(item, client)); + } + } +}; + +class TypeHierarchy : public TypeHierarchyWidget, public HierarchyWidgetHelper +{ +public: + TypeHierarchy() : HierarchyWidgetHelper(this) {} + +private: + void reload() override + { + updateHierarchyAtCursorPosition(); + } + + void sendRequest(Client *client, const TextDocumentPositionParams ¶ms, + const Core::IDocument *document) override + { + if (!supportsTypeHierarchy(client, document)) + return; + + PrepareTypeHierarchyRequest request(params); + request.setResponseCallback([this, client = QPointer(client)]( + const PrepareTypeHierarchyRequest::Response &response) { + handlePrepareResponse(client, response); + }); + client->sendMessage(request); + } + + void onItemDoubleClicked(const QModelIndex &index) override + { + if (const auto link = index.data(LinkRole).value(); link.hasValidTarget()) + reload(); + } + + void handlePrepareResponse(Client *client, + const PrepareTypeHierarchyRequest::Response &response) + { + if (!client) + return; + const std::optional error = response.error(); + if (error) + client->log(*error); + + const std::optional> + result = response.result(); + if (result && !result->isNull()) { + for (const LanguageServerProtocol::TypeHierarchyItem &item : result->toList()) + addItem(new TypeHierarchyRootItem(item, client)); + } + } +}; + +class CallHierarchyFactory : public Core::INavigationWidgetFactory +{ +public: + CallHierarchyFactory() + { + setDisplayName(Tr::tr("Call Hierarchy")); + setPriority(650); + setId(Constants::CALL_HIERARCHY_FACTORY_ID); + } + + Core::NavigationView createWidget() final + { + auto h = new CallHierarchy; + h->updateHierarchyAtCursorPosition(); + + Icons::RELOAD_TOOLBAR.icon(); + auto button = new QToolButton; + button->setIcon(Icons::RELOAD_TOOLBAR.icon()); + button->setToolTip(LanguageClient::Tr::tr( + "Reloads the call hierarchy for the symbol under cursor position.")); + connect(button, &QToolButton::clicked, this, [h] { h->updateHierarchyAtCursorPosition(); }); + return {h, {button}}; + } +}; + +class TypeHierarchyFactory final : public TypeHierarchyWidgetFactory +{ + TypeHierarchyWidget *createWidget(Core::IEditor *editor) final + { + const auto textEditor = qobject_cast(editor); + if (!textEditor) + return nullptr; + + Client *const client = LanguageClientManager::clientForFilePath( + textEditor->document()->filePath()); + if (!client || !supportsTypeHierarchy(client, textEditor->document())) + return nullptr; + + return new TypeHierarchy; + } +}; + +void setupCallHierarchyFactory() +{ + static CallHierarchyFactory theCallHierarchyFactory; +} + +static bool supportsHierarchy( + Client *client, + const Core::IDocument *document, + const QString &methodName, + const std::optional> &provider) +{ + std::optional registered = client->dynamicCapabilities().isRegistered(methodName); + bool supported = registered.value_or(false); + if (registered) { + if (supported) { + const QJsonValue &options = client->dynamicCapabilities().option(methodName); + const TextDocumentRegistrationOptions docOptions(options); + supported = docOptions.filterApplies(document->filePath(), + Utils::mimeTypeForName(document->mimeType())); + } + } else { + supported = provider.has_value(); + } + return supported; +} + +bool supportsCallHierarchy(Client *client, const Core::IDocument *document) +{ + return supportsHierarchy(client, + document, + PrepareCallHierarchyRequest::methodName, + client->capabilities().callHierarchyProvider()); +} + +void setupTypeHierarchyFactory() +{ + static TypeHierarchyFactory theTypeHierarchyFactory; +} + +bool supportsTypeHierarchy(Client *client, const Core::IDocument *document) +{ + return supportsHierarchy(client, + document, + PrepareTypeHierarchyRequest::methodName, + client->capabilities().typeHierarchyProvider()); +} + +} // namespace LanguageClient diff --git a/src/plugins/languageclient/callhierarchy.h b/src/plugins/languageclient/callandtypehierarchy.h similarity index 67% rename from src/plugins/languageclient/callhierarchy.h rename to src/plugins/languageclient/callandtypehierarchy.h index 860919b2b97..b49684d65a9 100644 --- a/src/plugins/languageclient/callhierarchy.h +++ b/src/plugins/languageclient/callandtypehierarchy.h @@ -1,4 +1,4 @@ -// Copyright (C) 2022 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -12,4 +12,7 @@ class Client; void setupCallHierarchyFactory(); bool supportsCallHierarchy(Client *client, const Core::IDocument *document); +void setupTypeHierarchyFactory(); +bool supportsTypeHierarchy(Client *client, const Core::IDocument *document); + } // namespace LanguageClient diff --git a/src/plugins/languageclient/callhierarchy.cpp b/src/plugins/languageclient/callhierarchy.cpp deleted file mode 100644 index 2f53a120ebe..00000000000 --- a/src/plugins/languageclient/callhierarchy.cpp +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (C) 2022 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0 WITH Qt-GPL-exception-1.0 - -#include "callhierarchy.h" - -#include "languageclientmanager.h" -#include "languageclienttr.h" - -#include -#include - -#include - -#include - -#include -#include -#include -#include - -#include -#include - -using namespace Utils; -using namespace TextEditor; -using namespace LanguageServerProtocol; - -namespace LanguageClient { - -namespace { -enum Direction { Incoming, Outgoing }; - -enum { - AnnotationRole = Qt::UserRole + 1, - LinkRole -}; -} - -class CallHierarchyRootItem : public TreeItem -{ -public: - CallHierarchyRootItem(const CallHierarchyItem &item) - : m_item(item) - {} - - QVariant data(int column, int role) const override - { - switch (role) { - case Qt::DecorationRole: - if (hasTag(SymbolTag::Deprecated)) - return Utils::Icons::WARNING.icon(); - return symbolIcon(int(m_item.symbolKind())); - case Qt::DisplayRole: - return m_item.name(); - case Qt::ToolTipRole: - if (hasTag(SymbolTag::Deprecated)) - return Tr::tr("Deprecated"); - break; - default: - break; - } - return TreeItem::data(column, role); - } - -protected: - const CallHierarchyItem m_item; - - bool hasTag(const SymbolTag tag) const - { - if (const std::optional> tags = m_item.symbolTags()) - return tags->contains(tag); - return false; - } -}; - -class CallHierarchyTreeItem : public CallHierarchyRootItem -{ -public: - CallHierarchyTreeItem(const CallHierarchyItem &item, const Direction direction, Client *client) - : CallHierarchyRootItem(item) - , m_direction(direction) - , m_client(client) - { - } - - QVariant data(int column, int role) const override - { - switch (role) { - case LinkRole: { - if (!m_client) - return QVariant(); - const Position start = m_item.selectionRange().start(); - return QVariant::fromValue( - Link(m_client->serverUriToHostPath(m_item.uri()), start.line() + 1, start.character())); - } - case AnnotationRole: - if (const std::optional detail = m_item.detail()) - return *detail; - return {}; - default: - break; - } - return CallHierarchyRootItem::data(column, role); - } - bool canFetchMore() const override - { - return m_client && !m_fetchedChildren; - } - - void fetchMore() override - { - m_fetchedChildren = true; - if (!m_client) - return; - - CallHierarchyCallsParams params; - params.setItem(m_item); - - if (m_direction == Incoming) { - CallHierarchyIncomingCallsRequest request(params); - request.setResponseCallback( - [this](const CallHierarchyIncomingCallsRequest::Response &response) { - const std::optional> result - = response.result(); - if (result && !result->isNull()) { - for (const CallHierarchyIncomingCall &item : result->toList()) { - if (item.isValid()) - appendChild(new CallHierarchyTreeItem(item.from(), m_direction, m_client)); - } - } - if (!hasChildren()) - update(); - }); - m_client->sendMessage(request); - } else { - CallHierarchyOutgoingCallsRequest request(params); - request.setResponseCallback( - [this](const CallHierarchyOutgoingCallsRequest::Response &response) { - const std::optional> result - = response.result(); - if (result && !result->isNull()) { - for (const CallHierarchyOutgoingCall &item : result->toList()) { - if (item.isValid()) - appendChild(new CallHierarchyTreeItem(item.to(), m_direction, m_client)); - } - } - if (!hasChildren()) - update(); - }); - m_client->sendMessage(request); - } - } - -protected: - const Direction m_direction; - bool m_fetchedChildren = false; - QPointer m_client; -}; - -class CallHierarchyDirectionItem : public CallHierarchyTreeItem -{ -public: - CallHierarchyDirectionItem(const CallHierarchyItem &item, - const Direction direction, - Client *client) - : CallHierarchyTreeItem(item, direction, client) - {} - - QVariant data(int column, int role) const override - { - if (role == Qt::DisplayRole) - return m_direction == Incoming ? Tr::tr("Incoming") : Tr::tr("Outgoing"); - return TreeItem::data(column, role); - } -}; - -class CallHierarchy : public QWidget -{ -public: - CallHierarchy() : m_view(new NavigationTreeView(this)) - { - m_delegate.setDelimiter(" "); - m_delegate.setAnnotationRole(AnnotationRole); - - m_view->setModel(&m_model); - m_view->setActivationMode(SingleClickActivation); - m_view->setItemDelegate(&m_delegate); - - setLayout(new QVBoxLayout); - layout()->addWidget(m_view); - layout()->setContentsMargins(0, 0, 0, 0); - layout()->setSpacing(0); - - connect(m_view, &NavigationTreeView::activated, this, &CallHierarchy::onItemActivated); - - connect(LanguageClientManager::instance(), &LanguageClientManager::openCallHierarchy, - this, &CallHierarchy::updateHierarchyAtCursorPosition); - } - - void onItemActivated(const QModelIndex &index) - { - const auto link = index.data(LinkRole).value(); - if (link.hasValidTarget()) - Core::EditorManager::openEditorAt(link); - } - - void updateHierarchyAtCursorPosition(); - void handlePrepareResponse(Client *client, - const PrepareCallHierarchyRequest::Response &response); - - AnnotatedItemDelegate m_delegate; - NavigationTreeView *m_view; - TreeModel m_model; -}; - -void CallHierarchy::updateHierarchyAtCursorPosition() -{ - m_model.clear(); - - BaseTextEditor *editor = BaseTextEditor::currentTextEditor(); - if (!editor) - return; - - Core::IDocument *document = editor->document(); - - Client *client = LanguageClientManager::clientForFilePath(document->filePath()); - if (!client) - return; - - if (!supportsCallHierarchy(client, document)) - return; - - TextDocumentPositionParams params; - params.setTextDocument(TextDocumentIdentifier(client->hostPathToServerUri(document->filePath()))); - params.setPosition(Position(editor->editorWidget()->textCursor())); - - PrepareCallHierarchyRequest request(params); - request.setResponseCallback([this, client = QPointer(client)]( - const PrepareCallHierarchyRequest::Response &response) { - handlePrepareResponse(client, response); - }); - - client->sendMessage(request); -} - -void CallHierarchy::handlePrepareResponse(Client *client, - const PrepareCallHierarchyRequest::Response &response) -{ - if (!client) - return; - const std::optional error = response.error(); - if (error) - client->log(*error); - - const std::optional> - result = response.result(); - if (result && !result->isNull()) { - for (const CallHierarchyItem &item : result->toList()) { - auto newItem = new CallHierarchyRootItem(item); - newItem->appendChild(new CallHierarchyDirectionItem(item, Incoming, client)); - newItem->appendChild(new CallHierarchyDirectionItem(item, Outgoing, client)); - m_model.rootItem()->appendChild(newItem); - m_view->expand(newItem->index()); - newItem->forChildrenAtLevel(1, [&](const TreeItem *child) { - m_view->expand(child->index()); - }); - } - } -} - -class CallHierarchyFactory final : public Core::INavigationWidgetFactory -{ -public: - CallHierarchyFactory() - { - setDisplayName(Tr::tr("Call Hierarchy")); - setPriority(650); - setId(Constants::CALL_HIERARCHY_FACTORY_ID); - } - - Core::NavigationView createWidget() final - { - auto h = new CallHierarchy; - h->updateHierarchyAtCursorPosition(); - - Icons::RELOAD_TOOLBAR.icon(); - auto button = new QToolButton; - button->setIcon(Icons::RELOAD_TOOLBAR.icon()); - button->setToolTip(::LanguageClient::Tr::tr("Reloads the call hierarchy for the symbol under cursor position.")); - connect(button, &QToolButton::clicked, this, [h] { h->updateHierarchyAtCursorPosition(); }); - return {h, {button}}; - } -}; - -void setupCallHierarchyFactory() -{ - static CallHierarchyFactory theCallHierarchyFactory; -} - -bool supportsCallHierarchy(Client *client, const Core::IDocument *document) -{ - const QString methodName = PrepareCallHierarchyRequest::methodName; - std::optional registered = client->dynamicCapabilities().isRegistered(methodName); - bool supported = registered.value_or(false); - if (registered) { - if (supported) { - const QJsonValue &options = client->dynamicCapabilities().option(methodName); - const TextDocumentRegistrationOptions docOptions(options); - supported = docOptions.filterApplies(document->filePath(), - Utils::mimeTypeForName(document->mimeType())); - } - } else { - supported = client->capabilities().callHierarchyProvider().has_value(); - } - return supported; -} - -} // namespace LanguageClient diff --git a/src/plugins/languageclient/client.cpp b/src/plugins/languageclient/client.cpp index 15a71adae37..5e3d240f8c1 100644 --- a/src/plugins/languageclient/client.cpp +++ b/src/plugins/languageclient/client.cpp @@ -3,7 +3,7 @@ #include "client.h" -#include "callhierarchy.h" +#include "callandtypehierarchy.h" #include "diagnosticmanager.h" #include "documentsymbolcache.h" #include "languageclientcompletionassist.h" @@ -527,6 +527,7 @@ static ClientCapabilities generateClientCapabilities() tokens.setFormats({"relative"}); documentCapabilities.setSemanticTokens(tokens); documentCapabilities.setCallHierarchy(allowDynamicRegistration); + documentCapabilities.setTypeHierarchy(allowDynamicRegistration); capabilities.setTextDocument(documentCapabilities); WindowClientClientCapabilities window; @@ -1013,6 +1014,8 @@ void Client::activateEditor(Core::IEditor *editor) optionalActions |= TextEditor::TextEditorActionHandler::FollowTypeUnderCursor; if (supportsCallHierarchy(this, textEditor->document())) optionalActions |= TextEditor::TextEditorActionHandler::CallHierarchy; + if (supportsTypeHierarchy(this, textEditor->document())) + optionalActions |= TextEditor::TextEditorActionHandler::TypeHierarchy; widget->setOptionalActions(optionalActions); } } diff --git a/src/plugins/languageclient/languageclient.qbs b/src/plugins/languageclient/languageclient.qbs index 96a88629f0d..04c2f0f3264 100644 --- a/src/plugins/languageclient/languageclient.qbs +++ b/src/plugins/languageclient/languageclient.qbs @@ -15,8 +15,8 @@ QtcPlugin { Depends { name: "TextEditor" } files: [ - "callhierarchy.cpp", - "callhierarchy.h", + "callandtypehierarchy.cpp", + "callandtypehierarchy.h", "client.cpp", "client.h", "clientrequest.cpp", @@ -30,7 +30,8 @@ QtcPlugin { "dynamiccapabilities.cpp", "dynamiccapabilities.h", "languageclient.qrc", - "languageclient_global.h", "languageclienttr.h", + "languageclient_global.h", + "languageclienttr.h", "languageclientformatter.cpp", "languageclientformatter.h", "languageclienthoverhandler.cpp", diff --git a/src/plugins/languageclient/languageclientplugin.cpp b/src/plugins/languageclient/languageclientplugin.cpp index 83a15122537..985f00da1ef 100644 --- a/src/plugins/languageclient/languageclientplugin.cpp +++ b/src/plugins/languageclient/languageclientplugin.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2018 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "callhierarchy.h" +#include "callandtypehierarchy.h" #include "languageclientmanager.h" #include "languageclientoutline.h" #include "languageclientsettings.h" @@ -43,6 +43,7 @@ void LanguageClientPlugin::initialize() using namespace Core; setupCallHierarchyFactory(); + setupTypeHierarchyFactory(); setupLanguageClientProjectPanel(); setupLanguageClientManager(this); From e0cf25fb55176d5607087241cdd800ca24f974f4 Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Thu, 14 Mar 2024 15:51:39 +0100 Subject: [PATCH 0068/1060] Spinner: Allow setting the spinner color Deeply under the hood, the color for ther Spinner was determined by the QApplication palette, color role "Text". In order to run the spinner on a dark toolbar (in a non-dark theme), though, the color needs to be bright. It is the case for the ScreenRecorder. This change adds a color setter to the Spinner classes, adds colored Spinners to tst_spinner and makes use of the feature in the ScreenRecorder. The default color of the Spinner remains QApplication palette, color role "Text". Change-Id: Ia75758707f225b1f994e73c5a314478101c80f5e Reviewed-by: Jarek Kobus --- src/libs/solutions/spinner/spinner.cpp | 31 ++++++++++++++++--- src/libs/solutions/spinner/spinner.h | 1 + .../screenrecorder/screenrecorderplugin.cpp | 1 + tests/manual/spinner/main.cpp | 16 ++++++++++ 4 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/libs/solutions/spinner/spinner.cpp b/src/libs/solutions/spinner/spinner.cpp index b56684720bb..9c1c43b4401 100644 --- a/src/libs/solutions/spinner/spinner.cpp +++ b/src/libs/solutions/spinner/spinner.cpp @@ -72,6 +72,8 @@ public: void setUpdateCallback(const UpdateCallback &cb) { m_callback = cb; } + void setColor(const QColor &color); + QSize size() const { return m_pixmap.size() / m_pixmap.devicePixelRatio(); } void paint(QPainter &painter, const QRect &rect) const; void startAnimation() { m_timer.start(); } @@ -87,6 +89,7 @@ private: QTimer m_timer; mutable QPixmap m_pixmap; UpdateCallback m_callback; + QColor m_color; }; static QString imageFileNameForSpinnerSize(SpinnerSize size) @@ -102,12 +105,12 @@ static QString imageFileNameForSpinnerSize(SpinnerSize size) return {}; } -static QPixmap themedPixmapForSpinnerSize(SpinnerSize size, qreal dpr) +static QPixmap themedPixmapForSpinnerSize(SpinnerSize size, const QColor &color, qreal dpr) { QImage mask(qt_findAtNxFile(imageFileNameForSpinnerSize(size), dpr)); mask.invertPixels(); QImage themedImage(mask.size(), QImage::Format_ARGB32); - themedImage.fill(qApp->palette().text().color()); + themedImage.fill(color); themedImage.setAlphaChannel(mask); QPixmap themedPixmap = QPixmap::fromImage(themedImage); themedPixmap.setDevicePixelRatio(mask.devicePixelRatio()); @@ -115,6 +118,7 @@ static QPixmap themedPixmapForSpinnerSize(SpinnerSize size, qreal dpr) } SpinnerPainter::SpinnerPainter(SpinnerSize size) + : m_color(qApp->palette().text().color()) { m_timer.setSingleShot(false); QObject::connect(&m_timer, &QTimer::timeout, &m_timer, [this] { @@ -130,14 +134,20 @@ void SpinnerPainter::setSize(SpinnerSize size) m_size = size; m_rotationStep = size == SpinnerSize::Small ? 45 : 30; m_timer.setInterval(size == SpinnerSize::Small ? 100 : 80); - m_pixmap = themedPixmapForSpinnerSize(size, qApp->devicePixelRatio()); + m_pixmap = themedPixmapForSpinnerSize(size, m_color, qApp->devicePixelRatio()); +} + +void SpinnerPainter::setColor(const QColor &color) +{ + m_color = color; + m_pixmap = themedPixmapForSpinnerSize(m_size, m_color, qApp->devicePixelRatio()); } void SpinnerPainter::paint(QPainter &painter, const QRect &rect) const { const qreal dpr = painter.device()->devicePixelRatioF(); if (!qFuzzyCompare(m_pixmap.devicePixelRatio(), dpr)) - m_pixmap = themedPixmapForSpinnerSize(m_size, dpr); + m_pixmap = themedPixmapForSpinnerSize(m_size, m_color, dpr); painter.save(); painter.setRenderHint(QPainter::SmoothPixmapTransform); QPoint translate(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2); @@ -173,6 +183,11 @@ public: } QSize sizeHint() const final { return m_paint.size(); } + void setColor(const QColor &color) + { + m_paint.setColor(color); + } + protected: void showEvent(QShowEvent *) final { m_paint.startAnimation(); } void hideEvent(QHideEvent *) final { m_paint.stopAnimation(); } @@ -231,6 +246,14 @@ void Spinner::setSize(SpinnerSize size) m_widget->setSize(size); } +/*! + Sets the color of the spinner to the given color. +*/ +void Spinner::setColor(const QColor &color) +{ + m_widget->setColor(color); +} + /*! Shows the animated spinner as an overlay for the parent widget set previously in the constructor. diff --git a/src/libs/solutions/spinner/spinner.h b/src/libs/solutions/spinner/spinner.h index 8ab7cb84d9a..8dd166a8640 100644 --- a/src/libs/solutions/spinner/spinner.h +++ b/src/libs/solutions/spinner/spinner.h @@ -27,6 +27,7 @@ class SPINNER_EXPORT Spinner : public QObject public: explicit Spinner(SpinnerSize size, QWidget *parent = nullptr); void setSize(SpinnerSize size); + void setColor(const QColor &color); void show(); void hide(); bool isVisible() const; diff --git a/src/plugins/screenrecorder/screenrecorderplugin.cpp b/src/plugins/screenrecorder/screenrecorderplugin.cpp index 662e8cc24c3..f0ad0405d33 100644 --- a/src/plugins/screenrecorder/screenrecorderplugin.cpp +++ b/src/plugins/screenrecorder/screenrecorderplugin.cpp @@ -86,6 +86,7 @@ public: }); m_spinner = new SpinnerSolution::Spinner(SpinnerSolution::SpinnerSize::Medium, this); + m_spinner->setColor(creatorTheme()->color(Theme::IconsBaseColor)); m_spinner->hide(); layout()->setSizeConstraint(QLayout::SetFixedSize); diff --git a/tests/manual/spinner/main.cpp b/tests/manual/spinner/main.cpp index ac98284fb8e..6aab09f0c74 100644 --- a/tests/manual/spinner/main.cpp +++ b/tests/manual/spinner/main.cpp @@ -50,6 +50,20 @@ QGroupBox *createGroupBox(SpinnerSize size, QWidget *widget) return groupBox; } +QGroupBox *createColorsGroupBox() +{ + QGroupBox *groupBox = new QGroupBox("Spinner::setColor(const QColor &color)"); + auto layout = new QHBoxLayout(groupBox); + for (auto color : {Qt::red, Qt::darkGreen, Qt::blue, Qt::darkYellow}) { + auto widget = new QWidget; + widget->setFixedSize(30, 30); + auto spinner = new Spinner(SpinnerSize::Medium, widget); + spinner->setColor(color); + layout->addWidget(widget); + } + return groupBox; +} + static QWidget *hr() { auto frame = new QFrame; @@ -91,6 +105,8 @@ int main(int argc, char *argv[]) QGroupBox *largeGroupBox = createGroupBox(SpinnerSize::Large, largeWidget); mainLayout->addWidget(largeGroupBox); + mainLayout->addWidget(createColorsGroupBox()); + mainWidget.show(); return app.exec(); From 812326eadc842e6c745ab676bc8eaa848fb07861 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 14 Mar 2024 17:49:56 +0100 Subject: [PATCH 0069/1060] CppEditor: Support try/catch in built-in indenter Fixes: QTCREATORBUG-29452 Change-Id: Icf3d86a6080aeb741436800ae77af7c8bec3155c Reviewed-by: Christian Stenger Reviewed-by: --- src/plugins/cppeditor/cppcodeformatter.cpp | 13 ++++++ src/plugins/cppeditor/cppcodeformatter.h | 2 + .../codeformatter/tst_codeformatter.cpp | 40 +++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/src/plugins/cppeditor/cppcodeformatter.cpp b/src/plugins/cppeditor/cppcodeformatter.cpp index 447a5a04871..85c841e2c72 100644 --- a/src/plugins/cppeditor/cppcodeformatter.cpp +++ b/src/plugins/cppeditor/cppcodeformatter.cpp @@ -284,6 +284,8 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block) && m_currentState.at(m_currentState.size() - 2).type == declaration_start) { leave(); leave(); + } else if (m_currentState.top().type == catch_statement) { + turnInto(substatement); } break; default: tryExpression(); break; @@ -414,6 +416,11 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block) default: leave(true); continue; } break; + case catch_statement: + switch (kind) { + case T_LPAREN: enter(arglist_open); break; + } break; + case for_statement_paren_open: enter(for_statement_init); continue; @@ -965,6 +972,12 @@ bool CodeFormatter::tryStatement() enter(do_statement); enter(substatement); return true; + case T_TRY: + enter(substatement); + return true; + case T_CATCH: + enter(catch_statement); + return true; case T_CASE: case T_DEFAULT: enter(case_start); diff --git a/src/plugins/cppeditor/cppcodeformatter.h b/src/plugins/cppeditor/cppcodeformatter.h index 93d32faf263..f3d69422ee0 100644 --- a/src/plugins/cppeditor/cppcodeformatter.h +++ b/src/plugins/cppeditor/cppcodeformatter.h @@ -119,6 +119,8 @@ public: // must be public to make Q_GADGET introspection work for_statement_condition, // The condition part of the for statement for_statement_expression, // The expression part of the for statement + catch_statement, + switch_statement, // After 'switch' token case_start, // after a 'case' or 'default' token case_cont, // after the colon in a case/default diff --git a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp index 29ecbb58ed9..12c3c528526 100644 --- a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp +++ b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp @@ -109,6 +109,7 @@ private Q_SLOTS: void structuredBinding(); void subscriptOperatorInFunctionCall(); void statementMacros(); + void tryCatchClause(); }; struct Line { @@ -2231,6 +2232,45 @@ void tst_CodeFormatter::statementMacros() checkIndent(data, settings); } +void tst_CodeFormatter::tryCatchClause() +{ + CppCodeStyleSettings settings; + settings.indentFunctionBody = true; + settings.indentFunctionBraces = false; + settings.indentBlockBody = false; + settings.indentBlockBraces = true; + QList data; + data << Line("int main()") + << Line("{") + << Line(" try") + << Line(" {") + << Line(" throw;") + << Line(" }") + << Line(" catch (const E &e)") + << Line(" {") + << Line(" handle(e);") + << Line(" }") + << Line(" catch (...)") + << Line(" {") + << Line(" handle();") + << Line(" }") + << Line("}"); + checkIndent(data, settings); + + data.clear(); + data << Line("int main()") + << Line("{") + << Line(" try {") + << Line(" throw;") + << Line(" } catch (const E &e) {") + << Line(" handle(e);") + << Line(" } catch (...) {") + << Line(" handle();") + << Line(" }") + << Line("}"); + checkIndent(data); +} + QTEST_GUILESS_MAIN(tst_CodeFormatter) #include "tst_codeformatter.moc" From faa595e38b830690a79904df413376996f728bb6 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 22 Feb 2024 16:26:13 +0100 Subject: [PATCH 0070/1060] CppEditor: Introduce per-project code model settings Change-Id: I325cc39e60d4b1f0fba1651502d772bfb9c6a91c Reviewed-by: Reviewed-by: David Schulz --- src/plugins/clangcodemodel/clangdclient.cpp | 8 +- src/plugins/clangcodemodel/clangutils.cpp | 13 +- .../clangcodemodel/test/clangdtests.cpp | 2 +- src/plugins/clangtools/clangfileinfo.h | 4 + src/plugins/clangtools/clangtool.cpp | 8 +- src/plugins/clangtools/clangtoolrunner.cpp | 2 +- .../clangtools/documentclangtoolrunner.cpp | 8 +- .../cppeditor/baseeditordocumentprocessor.cpp | 9 +- .../cppeditor/baseeditordocumentprocessor.h | 3 + .../builtineditordocumentprocessor.cpp | 6 +- .../cppeditor/cppcodemodelsettings.cpp | 112 ++++++++++++++---- src/plugins/cppeditor/cppcodemodelsettings.h | 40 ++++++- .../cppeditor/cppcodemodelsettingspage.cpp | 78 +++++++++++- .../cppeditor/cppcodemodelsettingspage.h | 3 +- src/plugins/cppeditor/cppeditorplugin.cpp | 11 +- src/plugins/cppeditor/cppfindreferences.cpp | 7 +- src/plugins/cppeditor/cppmodelmanager.cpp | 37 ++++-- src/plugins/cppeditor/cppmodelmanager.h | 1 + .../cppeditor/cppmodelmanager_test.cpp | 102 ++++++++++++++++ src/plugins/cppeditor/cppmodelmanager_test.h | 1 + src/plugins/cppeditor/projectinfo.cpp | 25 +++- src/plugins/cppeditor/projectinfo.h | 6 + .../projectexplorer/rawprojectpart.cpp | 8 ++ src/plugins/projectexplorer/rawprojectpart.h | 5 + 24 files changed, 430 insertions(+), 69 deletions(-) diff --git a/src/plugins/clangcodemodel/clangdclient.cpp b/src/plugins/clangcodemodel/clangdclient.cpp index 23dd71af16a..bf048486524 100644 --- a/src/plugins/clangcodemodel/clangdclient.cpp +++ b/src/plugins/clangcodemodel/clangdclient.cpp @@ -419,7 +419,7 @@ ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir, c *CppEditor::CppModelManager::fallbackProjectPart(), warningsConfigForProject(nullptr), includeDir, {}); const CppEditor::UsePrecompiledHeaders usePch - = CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders(); + = CppEditor::CppCodeModelSettings::usePrecompiledHeaders(nullptr); const QJsonArray projectPartOptions = fullProjectPartOptions( optionsBuilder, globalClangOptions()); const QJsonArray clangOptions = clangOptionsForFile({}, optionsBuilder.projectPart(), @@ -600,7 +600,7 @@ void ClangdClient::findUsages(const CppEditor::CursorInEditor &cursor, } } - const bool categorize = CppEditor::CppCodeModelSettings::instance().categorizeFindReferences(); + const bool categorize = CppEditor::CppCodeModelSettings::categorizeFindReferences(); // If it's a "normal" symbol, go right ahead. if (searchTerm != "operator" && Utils::allOf(searchTerm, [](const QChar &c) { @@ -920,9 +920,11 @@ void ClangdClient::updateParserConfig(const Utils::FilePath &filePath, CppEditor::ProjectFile::classify(filePath.toString())); const QJsonArray projectPartOptions = fullProjectPartOptions( optionsBuilder, globalClangOptions()); + const auto cppSettings = CppEditor::CppCodeModelSettings::settingsForProject( + projectPart->topLevelProject); addToCompilationDb(cdbChanges, *projectPart, - CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders(), + cppSettings.usePrecompiledHeaders(), projectPartOptions, filePath.parentDir(), file, diff --git a/src/plugins/clangcodemodel/clangutils.cpp b/src/plugins/clangcodemodel/clangutils.cpp index a718a9ed966..5e7f454d5ee 100644 --- a/src/plugins/clangcodemodel/clangutils.cpp +++ b/src/plugins/clangcodemodel/clangutils.cpp @@ -166,7 +166,6 @@ GenerateCompilationDbResult generateCompilationDB(QList p } compileCommandsFile.write("["); - const UsePrecompiledHeaders usePch = CppCodeModelSettings::instance().usePrecompiledHeaders(); const QJsonArray jsonProjectOptions = QJsonArray::fromStringList(projectOptions); for (const ProjectInfo::ConstPtr &projectInfo : std::as_const(projectInfoList)) { QTC_ASSERT(projectInfo, continue); @@ -183,9 +182,15 @@ GenerateCompilationDbResult generateCompilationDB(QList p jsonProjectOptions); } for (const ProjectFile &projFile : projectPart->files) { - const QJsonObject json = createFileObject(baseDir, args, *projectPart, projFile, - purpose, ppOptions, usePch, - optionsBuilder.isClStyle()); + const QJsonObject json + = createFileObject(baseDir, + args, + *projectPart, + projFile, + purpose, + ppOptions, + projectInfo->settings().usePrecompiledHeaders(), + optionsBuilder.isClStyle()); if (compileCommandsFile.size() > 1) compileCommandsFile.write(","); compileCommandsFile.write(QJsonDocument(json).toJson(QJsonDocument::Compact)); diff --git a/src/plugins/clangcodemodel/test/clangdtests.cpp b/src/plugins/clangcodemodel/test/clangdtests.cpp index 88a3176a6b2..ae92afb45ff 100644 --- a/src/plugins/clangcodemodel/test/clangdtests.cpp +++ b/src/plugins/clangcodemodel/test/clangdtests.cpp @@ -249,7 +249,7 @@ private: void ClangdTestFindReferences::initTestCase() { ClangdTest::initTestCase(); - CppEditor::CppCodeModelSettings::instance().setCategorizeFindReferences(true); + CppEditor::CppCodeModelSettings::setCategorizeFindReferences(true); connect(client(), &ClangdClient::foundReferences, this, [this](const SearchResultItems &results) { if (results.isEmpty()) diff --git a/src/plugins/clangtools/clangfileinfo.h b/src/plugins/clangtools/clangfileinfo.h index e9a71511607..deb53f60588 100644 --- a/src/plugins/clangtools/clangfileinfo.h +++ b/src/plugins/clangtools/clangfileinfo.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include @@ -19,9 +20,11 @@ public: FileInfo() = default; FileInfo(Utils::FilePath file, CppEditor::ProjectFile::Kind kind, + const CppEditor::CppCodeModelSettings &settings, CppEditor::ProjectPart::ConstPtr projectPart) : file(std::move(file)) , kind(kind) + , settings(settings.data()) , projectPart(projectPart) {} @@ -31,6 +34,7 @@ public: Utils::FilePath file; CppEditor::ProjectFile::Kind kind; + CppEditor::CppCodeModelSettings::Data settings; CppEditor::ProjectPart::ConstPtr projectPart; }; using FileInfos = std::vector; diff --git a/src/plugins/clangtools/clangtool.cpp b/src/plugins/clangtools/clangtool.cpp index 15635fc2514..b7108a43893 100644 --- a/src/plugins/clangtools/clangtool.cpp +++ b/src/plugins/clangtools/clangtool.cpp @@ -341,7 +341,8 @@ private: QMap m_refactoringFileInfos; }; -static FileInfos sortedFileInfos(const QVector &projectParts) +static FileInfos sortedFileInfos(const CppCodeModelSettings &settings, + const QVector &projectParts) { FileInfos fileInfos; @@ -359,7 +360,7 @@ static FileInfos sortedFileInfos(const QVector &projectPa if (file.active && (ProjectFile::isSource(file.kind) || ProjectFile::isHeader(file.kind))) { ProjectFile::Kind sourceKind = ProjectFile::sourceKind(file.kind); - fileInfos.emplace_back(file.path, sourceKind, projectPart); + fileInfos.emplace_back(file.path, sourceKind, settings, projectPart); } } } @@ -901,7 +902,8 @@ FileInfos ClangTool::collectFileInfos(Project *project, FileSelection fileSelect const auto projectInfo = CppModelManager::projectInfo(project); QTC_ASSERT(projectInfo, return FileInfos()); - const FileInfos allFileInfos = sortedFileInfos(projectInfo->projectParts()); + const FileInfos allFileInfos = sortedFileInfos(projectInfo->settings(), + projectInfo->projectParts()); if (selectionType && *selectionType == FileSelectionType::AllFiles) return allFileInfos; diff --git a/src/plugins/clangtools/clangtoolrunner.cpp b/src/plugins/clangtools/clangtoolrunner.cpp index 13fdfba742f..af3539b2ac0 100644 --- a/src/plugins/clangtools/clangtoolrunner.cpp +++ b/src/plugins/clangtools/clangtoolrunner.cpp @@ -51,7 +51,7 @@ AnalyzeUnit::AnalyzeUnit(const FileInfo &fileInfo, arguments = extraClangToolsPrependOptions(); arguments.append( optionsBuilder.build(fileInfo.kind, - CppEditor::CppCodeModelSettings::instance().usePrecompiledHeaders())); + CppCodeModelSettings(fileInfo.settings).usePrecompiledHeaders())); arguments.append(extraClangToolsAppendOptions()); } diff --git a/src/plugins/clangtools/documentclangtoolrunner.cpp b/src/plugins/clangtools/documentclangtoolrunner.cpp index d503f80d63b..1e3055cb48d 100644 --- a/src/plugins/clangtools/documentclangtoolrunner.cpp +++ b/src/plugins/clangtools/documentclangtoolrunner.cpp @@ -132,10 +132,12 @@ static FileInfo getFileInfo(const FilePath &file, Project *project) // found the best candidate, early return ProjectFile::Kind sourceKind = ProjectFile::sourceKind(projectFile.kind); if (projectPart->buildTargetType != BuildTargetType::Unknown) - return FileInfo(projectFile.path, sourceKind, projectPart); + return FileInfo(projectFile.path, sourceKind, projectInfo->settings(), projectPart); // found something but keep looking for better candidates - if (candidate.projectPart.isNull()) - candidate = FileInfo(projectFile.path, sourceKind, projectPart); + if (candidate.projectPart.isNull()) { + candidate + = FileInfo(projectFile.path, sourceKind, projectInfo->settings(), projectPart); + } } } diff --git a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp index d377a25337b..786999223ec 100644 --- a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp @@ -27,7 +27,8 @@ namespace CppEditor { BaseEditorDocumentProcessor::BaseEditorDocumentProcessor(QTextDocument *textDocument, const Utils::FilePath &filePath) : m_filePath(filePath), - m_textDocument(textDocument) + m_textDocument(textDocument), + m_settings(CppCodeModelSettings::settingsForFile(filePath)) { } @@ -35,9 +36,11 @@ BaseEditorDocumentProcessor::~BaseEditorDocumentProcessor() = default; void BaseEditorDocumentProcessor::run(bool projectsUpdated) { + if (projectsUpdated) + m_settings.setData(CppCodeModelSettings::settingsForFile(m_filePath).data()); + const Utils::Language languagePreference - = CppCodeModelSettings::instance().interpretAmbigiousHeadersAsC() ? Utils::Language::C - : Utils::Language::Cxx; + = m_settings.interpretAmbigiousHeadersAsC() ? Utils::Language::C : Utils::Language::Cxx; runImpl({CppModelManager::workingCopy(), ProjectExplorer::ProjectManager::startupProject(), diff --git a/src/plugins/cppeditor/baseeditordocumentprocessor.h b/src/plugins/cppeditor/baseeditordocumentprocessor.h index 78c0f55aabc..c825dc7a84a 100644 --- a/src/plugins/cppeditor/baseeditordocumentprocessor.h +++ b/src/plugins/cppeditor/baseeditordocumentprocessor.h @@ -4,6 +4,7 @@ #pragma once #include "baseeditordocumentparser.h" +#include "cppcodemodelsettings.h" #include "cppcursorinfo.h" #include "cppeditor_global.h" #include "cppsemanticinfo.h" @@ -72,6 +73,7 @@ public: virtual QFuture cursorInfo(const CursorInfoParams ¶ms) = 0; const Utils::FilePath &filePath() const { return m_filePath; } + const CppCodeModelSettings &settings() const { return m_settings; } signals: // Signal interface to implement @@ -102,6 +104,7 @@ private: private: Utils::FilePath m_filePath; QTextDocument *m_textDocument; + CppCodeModelSettings m_settings; }; } // namespace CppEditor diff --git a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp index bd820c9222f..5f827c74ce9 100644 --- a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp @@ -144,16 +144,14 @@ QList toTextEditorBlocks( BuiltinEditorDocumentProcessor::BuiltinEditorDocumentProcessor(TextEditor::TextDocument *document) : BaseEditorDocumentProcessor(document->document(), document->filePath()) , m_parser(new BuiltinEditorDocumentParser(document->filePath(), - CppCodeModelSettings::instance() - .effectiveIndexerFileSizeLimitInMb())) + settings().effectiveIndexerFileSizeLimitInMb())) , m_codeWarningsUpdated(false) , m_semanticHighlighter(new SemanticHighlighter(document)) { using namespace Internal; BaseEditorDocumentParser::Configuration config = m_parser->configuration(); - config.usePrecompiledHeaders = CppCodeModelSettings::instance().pchUsage() - != CppCodeModelSettings::PchUse_None; + config.usePrecompiledHeaders = settings().pchUsage() != CppCodeModelSettings::PchUse_None; m_parser->setConfiguration(config); m_semanticHighlighter->setHighlightingRunner( diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 8a28fcf691c..5c8e3caff18 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include @@ -28,6 +29,7 @@ #include #include +using namespace ProjectExplorer; using namespace Utils; namespace CppEditor { @@ -56,7 +58,7 @@ static Key clangdThreadLimitKey() { return "ClangdThreadLimit"; } static Key clangdDocumentThresholdKey() { return "ClangdDocumentThreshold"; } static Key clangdSizeThresholdEnabledKey() { return "ClangdSizeThresholdEnabled"; } static Key clangdSizeThresholdKey() { return "ClangdSizeThreshold"; } -static Key clangdUseGlobalSettingsKey() { return "useGlobalSettings"; } +static Key useGlobalSettingsKey() { return "useGlobalSettings"; } static Key clangdblockIndexingSettingsKey() { return "blockIndexing"; } static Key sessionsWithOneClangdKey() { return "SessionsWithOneClangd"; } static Key diagnosticConfigIdKey() { return "diagnosticConfigId"; } @@ -116,48 +118,118 @@ void CppCodeModelSettings::Data::fromMap(const Utils::Store &store) void CppCodeModelSettings::fromSettings(QtcSettings *s) { m_data.fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); - emit changed(); } void CppCodeModelSettings::toSettings(QtcSettings *s) { - const Data def; - storeToSettingsWithDefault(Constants::CPPEDITOR_SETTINGSGROUP, s, m_data.toMap(), def.toMap()); - emit changed(); // TODO: Why? + storeToSettingsWithDefault(Constants::CPPEDITOR_SETTINGSGROUP, s, m_data.toMap(), Data().toMap()); } -CppCodeModelSettings &CppCodeModelSettings::instance() +CppCodeModelSettings &CppCodeModelSettings::globalInstance() { static CppCodeModelSettings theCppCodeModelSettings(Core::ICore::settings()); return theCppCodeModelSettings; } -void CppCodeModelSettings::setData(const Data &data) +CppCodeModelSettings CppCodeModelSettings::settingsForProject(const ProjectExplorer::Project *project) { - if (m_data != data) { - m_data = data; - toSettings(Core::ICore::settings()); - emit changed(); - } + return {CppCodeModelProjectSettings(const_cast(project)).data()}; +} + +CppCodeModelSettings CppCodeModelSettings::settingsForProject(const Utils::FilePath &projectFile) +{ + return settingsForProject(ProjectManager::projectWithProjectFilePath(projectFile)); +} + +CppCodeModelSettings CppCodeModelSettings::settingsForFile(const Utils::FilePath &file) +{ + return settingsForProject(ProjectManager::projectForFile(file)); +} + +void CppCodeModelSettings::setGlobalData(const Data &data) +{ + if (globalInstance().m_data == data) + return; + + globalInstance().m_data = data; + globalInstance().toSettings(Core::ICore::settings()); + emit globalInstance().changed(nullptr); +} + +CppCodeModelSettings::PCHUsage CppCodeModelSettings::pchUsage(const Project *project) +{ + return CppCodeModelSettings::settingsForProject(project).pchUsage(); } UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders() const { - if (instance().pchUsage() == CppCodeModelSettings::PchUse_None) - return UsePrecompiledHeaders::No; - return UsePrecompiledHeaders::Yes; + return pchUsage() == CppCodeModelSettings::PchUse_None ? UsePrecompiledHeaders::No + : UsePrecompiledHeaders::Yes; +} + +UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders(const Project *project) +{ + return CppCodeModelSettings::settingsForProject(project).usePrecompiledHeaders(); } int CppCodeModelSettings::effectiveIndexerFileSizeLimitInMb() const { - return instance().skipIndexingBigFiles() ? instance().indexerFileSizeLimitInMb() : -1; + return skipIndexingBigFiles() ? indexerFileSizeLimitInMb() : -1; +} + +bool CppCodeModelSettings::categorizeFindReferences() +{ + return globalInstance().m_data.categorizeFindReferences; } void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { - Data d = data(); + Data d = globalInstance().data(); d.categorizeFindReferences = categorize; - setData(d); + globalInstance().setGlobalData(d); +} + +CppCodeModelProjectSettings::CppCodeModelProjectSettings(ProjectExplorer::Project *project) + : m_project(project) +{ + loadSettings(); +} + +CppCodeModelSettings::Data CppCodeModelProjectSettings::data() const +{ + return m_useGlobalSettings ? CppCodeModelSettings::globalInstance().data() : m_customSettings; +} + +void CppCodeModelProjectSettings::setData(const CppCodeModelSettings::Data &data) +{ + m_customSettings = data; + saveSettings(); + emit CppCodeModelSettings::globalInstance().changed(m_project); +} + +void CppCodeModelProjectSettings::setUseGlobalSettings(bool useGlobal) +{ + m_useGlobalSettings = useGlobal; + saveSettings(); + emit CppCodeModelSettings::globalInstance().changed(m_project); +} + +void CppCodeModelProjectSettings::loadSettings() +{ + if (!m_project) + return; + const Store data = storeFromVariant(m_project->namedSettings(Constants::CPPEDITOR_SETTINGSGROUP)); + m_useGlobalSettings = data.value(useGlobalSettingsKey(), true).toBool(); + m_customSettings.fromMap(data); +} + +void CppCodeModelProjectSettings::saveSettings() +{ + if (!m_project) + return; + Store data = m_customSettings.toMap(); + data.insert(useGlobalSettingsKey(), m_useGlobalSettings); + m_project->setNamedSettings(Constants::CPPEDITOR_SETTINGSGROUP, variantFromStore(data)); } QString ClangdSettings::priorityToString(const IndexingPriority &priority) @@ -513,7 +585,7 @@ void ClangdProjectSettings::loadSettings() if (!m_project) return; const Store data = storeFromVariant(m_project->namedSettings(clangdSettingsKey())); - m_useGlobalSettings = data.value(clangdUseGlobalSettingsKey(), true).toBool(); + m_useGlobalSettings = data.value(useGlobalSettingsKey(), true).toBool(); m_blockIndexing = data.value(clangdblockIndexingSettingsKey(), false).toBool(); if (!m_useGlobalSettings) m_customSettings.fromMap(data); @@ -526,7 +598,7 @@ void ClangdProjectSettings::saveSettings() Store data; if (!m_useGlobalSettings) data = m_customSettings.toMap(); - data.insert(clangdUseGlobalSettingsKey(), m_useGlobalSettings); + data.insert(useGlobalSettingsKey(), m_useGlobalSettings); data.insert(clangdblockIndexingSettingsKey(), m_blockIndexing); m_project->setNamedSettings(clangdSettingsKey(), variantFromStore(data)); } diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index c76f3318f20..19cc078b266 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -37,6 +37,8 @@ public: class Data { public: + Data() = default; + Data(const Utils::Store &store) { fromMap(store); } Utils::Store toMap() const; void fromMap(const Utils::Store &store); @@ -53,26 +55,35 @@ public: QString ignorePattern; }; - static CppCodeModelSettings &instance(); + CppCodeModelSettings(const Data &data) : m_data(data) {} - void setData(const Data &data); + static CppCodeModelSettings &globalInstance(); // TODO: Make inaccessible. + static CppCodeModelSettings settingsForProject(const ProjectExplorer::Project *project); + static CppCodeModelSettings settingsForProject(const Utils::FilePath &projectFile); + static CppCodeModelSettings settingsForFile(const Utils::FilePath &file); + + static void setGlobalData(const Data &data); // TODO: Make inaccessible. + void setData(const Data &data) { m_data = data; } Data data() const { return m_data; } PCHUsage pchUsage() const { return m_data.pchUsage; } + static PCHUsage pchUsage(const ProjectExplorer::Project *project); UsePrecompiledHeaders usePrecompiledHeaders() const; + static UsePrecompiledHeaders usePrecompiledHeaders(const ProjectExplorer::Project *project); + bool interpretAmbigiousHeadersAsC() const { return m_data.interpretAmbigiousHeadersAsC; } bool skipIndexingBigFiles() const { return m_data.skipIndexingBigFiles; } bool useBuiltinPreprocessor() const { return m_data.useBuiltinPreprocessor; } int indexerFileSizeLimitInMb() const { return m_data.indexerFileSizeLimitInMb; } int effectiveIndexerFileSizeLimitInMb() const; - bool categorizeFindReferences() const { return m_data.categorizeFindReferences; } bool ignoreFiles() const { return m_data.ignoreFiles; } QString ignorePattern() const { return m_data.ignorePattern; } - void setCategorizeFindReferences(bool categorize); + static bool categorizeFindReferences(); + static void setCategorizeFindReferences(bool categorize); signals: - void changed(); + void changed(ProjectExplorer::Project *project); private: CppCodeModelSettings() = default; @@ -84,6 +95,25 @@ private: Data m_data; }; +class CppCodeModelProjectSettings +{ +public: + CppCodeModelProjectSettings(ProjectExplorer::Project *project); + + CppCodeModelSettings::Data data() const; + void setData(const CppCodeModelSettings::Data &data); + bool useGlobalSettings() const { return m_useGlobalSettings; } + void setUseGlobalSettings(bool useGlobal); + +private: + void loadSettings(); + void saveSettings(); + + ProjectExplorer::Project * const m_project; + CppCodeModelSettings::Data m_customSettings; + bool m_useGlobalSettings = true; +}; + class CPPEDITOR_EXPORT ClangdSettings : public QObject { Q_OBJECT diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index bb911657054..616bb34f616 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -50,14 +50,18 @@ namespace CppEditor::Internal { class CppCodeModelSettingsWidget final : public Core::IOptionsPageWidget { + Q_OBJECT public: CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); -private: - void apply() final { CppCodeModelSettings::instance().setData(data()); } - CppCodeModelSettings::Data data() const; +signals: + void settingsDataChanged(); + +private: + void apply() final { CppCodeModelSettings::globalInstance().setGlobalData(data()); } + QCheckBox *m_interpretAmbiguousHeadersAsCHeaders; QCheckBox *m_ignorePchCheckBox; QCheckBox *m_useBuiltinPreprocessorCheckBox; @@ -126,6 +130,23 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSetting }, st }.attachTo(this); + + for (const QCheckBox *const b : {m_interpretAmbiguousHeadersAsCHeaders, + m_ignorePchCheckBox, + m_useBuiltinPreprocessorCheckBox, + m_skipIndexingBigFilesCheckBox, + m_ignoreFilesCheckBox}) { + connect(b, &QCheckBox::toggled, this, &CppCodeModelSettingsWidget::settingsDataChanged); + } + connect(m_bigFilesLimitSpinBox, &QSpinBox::valueChanged, + this, &CppCodeModelSettingsWidget::settingsDataChanged); + + const auto timer = new QTimer(this); + timer->setSingleShot(true); + timer->setInterval(1000); + connect(timer, &QTimer::timeout, this, &CppCodeModelSettingsWidget::settingsDataChanged); + connect(m_ignorePatternTextEdit, &QPlainTextEdit::textChanged, + timer, qOverload<>(&QTimer::start)); } CppCodeModelSettings::Data CppCodeModelSettingsWidget::data() const @@ -153,15 +174,62 @@ public: setDisplayCategory(Tr::tr("C++")); setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); setWidgetCreator( - [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::instance().data()); }); + [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::globalInstance().data()); }); } }; -void setupCppCodeModelSettings() +void setupCppCodeModelSettingsPage() { static CppCodeModelSettingsPage theCppCodeModelSettingsPage; } +class CppCodeModelProjectSettingsWidget : public ProjectSettingsWidget +{ +public: + CppCodeModelProjectSettingsWidget(const CppCodeModelProjectSettings &settings) + : m_settings(settings), m_widget(settings.data()) + { + setGlobalSettingsId(Constants::CPP_CODE_MODEL_SETTINGS_ID); + const auto layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(&m_widget); + + setUseGlobalSettings(m_settings.useGlobalSettings()); + m_widget.setEnabled(!useGlobalSettings()); + connect(this, &ProjectSettingsWidget::useGlobalSettingsChanged, this, + [this](bool checked) { + m_widget.setEnabled(!checked); + m_settings.setUseGlobalSettings(checked); + if (!checked) + m_settings.setData(m_widget.data()); + }); + + connect(&m_widget, &CppCodeModelSettingsWidget::settingsDataChanged, + this, [this] { m_settings.setData(m_widget.data()); }); + } + +private: + CppCodeModelProjectSettings m_settings; + CppCodeModelSettingsWidget m_widget; +}; + +class CppCodeModelProjectSettingsPanelFactory final : public ProjectPanelFactory +{ +public: + CppCodeModelProjectSettingsPanelFactory() + { + setPriority(100); + setDisplayName(Tr::tr("C++ Code Model")); + setCreateWidgetFunction([](Project *project) { + return new CppCodeModelProjectSettingsWidget(project); + }); + } +}; +void setupCppCodeModelProjectSettingsPanel() +{ + static CppCodeModelProjectSettingsPanelFactory factory; +} + class ClangdSettingsWidget final : public QWidget { Q_OBJECT diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.h b/src/plugins/cppeditor/cppcodemodelsettingspage.h index 35a6bc51110..4c11b6251e2 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.h +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.h @@ -5,7 +5,8 @@ namespace CppEditor::Internal { -void setupCppCodeModelSettings(); +void setupCppCodeModelSettingsPage(); +void setupCppCodeModelProjectSettingsPanel(); void setupClangdProjectSettingsPanel(); void setupClangdSettingsPage(); diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index a98a76ec423..4328c939707 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -70,6 +70,7 @@ #include #include #include +#include #include #include @@ -202,7 +203,10 @@ void CppEditorPlugin::initialize() d = new CppEditorPluginPrivate; setupCppQuickFixSettings(); - setupCppCodeModelSettings(); + setupCppCodeModelSettingsPage(); + provideCppSettingsRetriever([](const Project *p) { + return CppCodeModelSettings::settingsForProject(p).data().toMap(); + }); setupCppOutline(); setupCppCodeStyleSettings(); setupCppProjectUpdater(); @@ -227,6 +231,7 @@ void CppEditorPlugin::extensionsInitialized() { setupCppQuickFixProjectPanel(); setupCppFileSettings(); + setupCppCodeModelProjectSettingsPanel(); if (CppModelManager::isClangCodeModelActive()) { setupClangdProjectSettingsPanel(); @@ -349,9 +354,9 @@ void CppEditorPlugin::addPerSymbolActions() findRefsCategorized.addToContainers(menus, Constants::G_SYMBOL); findRefsCategorized.addOnTriggered(this, [] { if (const auto w = currentCppEditorWidget()) { - CppCodeModelSettings::instance().setCategorizeFindReferences(true); + CppCodeModelSettings::setCategorizeFindReferences(true); w->findUsages(); - CppCodeModelSettings::instance().setCategorizeFindReferences(false); + CppCodeModelSettings::setCategorizeFindReferences(false); } }); diff --git a/src/plugins/cppeditor/cppfindreferences.cpp b/src/plugins/cppeditor/cppfindreferences.cpp index 683eda587a4..35c9400e9ad 100644 --- a/src/plugins/cppeditor/cppfindreferences.cpp +++ b/src/plugins/cppeditor/cppfindreferences.cpp @@ -388,7 +388,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, search->setTextToReplace(replacement); if (callback) search->makeNonInteractive(callback); - if (CppCodeModelSettings::instance().categorizeFindReferences()) + if (CppCodeModelSettings::categorizeFindReferences()) search->setFilter(new CppSearchResultFilter); setupSearch(search); search->setSearchAgainSupported(true); @@ -397,7 +397,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, CppFindReferencesParameters parameters; parameters.symbolId = fullIdForSymbol(symbol); parameters.symbolFilePath = symbol->filePath(); - parameters.categorize = CppCodeModelSettings::instance().categorizeFindReferences(); + parameters.categorize = CppCodeModelSettings::categorizeFindReferences(); parameters.preferLowerCaseFileNames = preferLowerCaseFileNames( ProjectManager::projectForFile(symbol->filePath())); @@ -408,8 +408,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, } search->setUserData(QVariant::fromValue(parameters)); - findAll_helper(search, symbol, context, - CppCodeModelSettings::instance().categorizeFindReferences()); + findAll_helper(search, symbol, context, CppCodeModelSettings::categorizeFindReferences()); } void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index 6e81e86f0ca..5ea954add45 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -407,7 +407,7 @@ void CppModelManager::showPreprocessedFile(bool inNextSplit) saveAndOpen(outFilePath, content.append(preprocessedDoc->utf8Source()), inNextSplit); }; - if (CppCodeModelSettings::instance().useBuiltinPreprocessor()) { + if (CppCodeModelSettings::settingsForFile(filePath).useBuiltinPreprocessor()) { useBuiltinPreprocessor(); return; } @@ -1023,6 +1023,9 @@ CppModelManager::CppModelManager() connect(ICore::instance(), &ICore::coreAboutToClose, this, &CppModelManager::onCoreAboutToClose); + connect(&CppCodeModelSettings::globalInstance(), &CppCodeModelSettings::changed, + this, &CppModelManager::onSettingsChange); + d->m_fallbackProjectPartTimer.setSingleShot(true); d->m_fallbackProjectPartTimer.setInterval(5000); connect(&d->m_fallbackProjectPartTimer, &QTimer::timeout, @@ -1349,12 +1352,17 @@ QFuture CppModelManager::updateSourceFiles(const QSet &sourceFil if (sourceFiles.isEmpty() || !d->m_indexerEnabled) return QFuture(); - const CppCodeModelSettings &settings = CppCodeModelSettings::instance(); - const QSet filteredFiles - = filteredFilesRemoved(transform(sourceFiles, &FilePath::toString), - settings.effectiveIndexerFileSizeLimitInMb(), - settings.ignoreFiles(), - settings.ignorePattern()); + QHash> sourcesPerProject; // TODO: Work with QList from here on? + for (const FilePath &fp : sourceFiles) + sourcesPerProject[ProjectManager::projectForFile(fp)] << fp.toString(); + QSet filteredFiles; + for (auto it = sourcesPerProject.cbegin(); it != sourcesPerProject.cend(); ++it) { + const CppCodeModelSettings settings = CppCodeModelSettings::settingsForProject(it.key()); + filteredFiles.unite(filteredFilesRemoved(it.value(), + settings.effectiveIndexerFileSizeLimitInMb(), + settings.ignoreFiles(), + settings.ignorePattern())); + } return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode); } @@ -1992,6 +2000,21 @@ void CppModelManager::onCoreAboutToClose() d->m_enableGC = false; } +void CppModelManager::onSettingsChange(Project *project) +{ + ProjectInfoList info; + if (project) + info << projectInfo(project); + else + info << projectInfos(); + for (const ProjectInfo::ConstPtr &pi : std::as_const(info)) { + const CppCodeModelSettings newSettings = CppCodeModelSettings::settingsForProject( + pi->projectFilePath()); + if (pi->settings().data() != newSettings.data()) + updateProjectInfo(ProjectInfo::cloneWithNewSettings(pi, newSettings)); + } +} + void CppModelManager::setupFallbackProjectPart() { ToolchainInfo tcInfo; diff --git a/src/plugins/cppeditor/cppmodelmanager.h b/src/plugins/cppeditor/cppmodelmanager.h index 77cb212c6eb..d1a558ce9c9 100644 --- a/src/plugins/cppeditor/cppmodelmanager.h +++ b/src/plugins/cppeditor/cppmodelmanager.h @@ -288,6 +288,7 @@ private: static void onSourceFilesRefreshed(); static void onCurrentEditorChanged(Core::IEditor *editor); static void onCoreAboutToClose(); + static void onSettingsChange(ProjectExplorer::Project *project); static void setupFallbackProjectPart(); static void delayedGC(); diff --git a/src/plugins/cppeditor/cppmodelmanager_test.cpp b/src/plugins/cppeditor/cppmodelmanager_test.cpp index 9e72a224b9f..a896563a61f 100644 --- a/src/plugins/cppeditor/cppmodelmanager_test.cpp +++ b/src/plugins/cppeditor/cppmodelmanager_test.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -1174,4 +1175,105 @@ void ModelManagerTest::testDocumentsAndRevisions() VERIFY_DOCUMENT_REVISION(CppModelManager::document(filePath2), 4U); } +void ModelManagerTest::testSettingsChanges() +{ + ModelManagerTestHelper helper; + + int refreshCount = 0; + QSet refreshedFiles; + connect(CppModelManager::instance(), &CppModelManager::sourceFilesRefreshed, + &helper, [&](const QSet &files) { + ++refreshCount; + refreshedFiles.unite(files); + }); + const auto waitForRefresh = [] { + return ::CppEditor::Tests::waitForSignalOrTimeout(CppModelManager::instance(), + &CppModelManager::sourceFilesRefreshed, + 5000); + }; + + const auto setupProjectNodes = [](Project &p, const ProjectFiles &projectFiles) { + auto rootNode = std::make_unique(p.projectFilePath()); + for (const ProjectFile &sourceFile : projectFiles) { + rootNode->addNestedNode(std::make_unique(sourceFile.path, + sourceFile.isHeader() + ? FileType::Header + : FileType::Source)); + } + p.setRootProjectNode(std::move(rootNode)); + }; + + // Set up projects. + const MyTestDataDir p1Dir("testdata_project1"); + const FilePaths p1Files + = Utils::transform({"baz.h", "baz2.h", "baz3.h", "foo.cpp", "foo.h", "main.cpp"}, + [&](const QString &fn) { return p1Dir.filePath(fn); }); + const ProjectFiles p1ProjectFiles = Utils::transform(p1Files, [](const FilePath &fp) { + return ProjectFile(fp, ProjectFile::classify(fp.toString())); + }); + Project * const p1 = helper.createProject("testdata_project1", FilePath::fromString("p1.pro")); + setupProjectNodes(*p1, p1ProjectFiles); + RawProjectPart rpp1; + const auto part1 = ProjectPart::create(p1->projectFilePath(), rpp1, {}, p1ProjectFiles); + const auto pi1 = ProjectInfo::create(ProjectUpdateInfo(p1, KitInfo(nullptr), {}, {}), {part1}); + const auto p1Sources = Utils::transform>(p1Files, &FilePath::toString); + CppModelManager::updateProjectInfo(pi1); + + const MyTestDataDir p2Dir("testdata_project2"); + const FilePaths p2Files + = Utils::transform({"bar.h", "bar.cpp", "foobar2000.h", "foobar4000.h", "main.cpp"}, + [&](const QString &fn) { return p1Dir.filePath(fn); }); + const ProjectFiles p2ProjectFiles = Utils::transform(p2Files, [](const FilePath &fp) { + return ProjectFile(fp, ProjectFile::classify(fp.toString())); + }); + Project * const p2 = helper.createProject("testdata_project2", FilePath::fromString("p2.pro")); + setupProjectNodes(*p2, p2ProjectFiles); + RawProjectPart rpp2; + const auto part2 = ProjectPart::create(p2->projectFilePath(), rpp2, {}, p2ProjectFiles); + const auto pi2 = ProjectInfo::create(ProjectUpdateInfo(p2, KitInfo(nullptr), {}, {}), {part2}); + const auto p2Sources = Utils::transform>(p2Files, &FilePath::toString); + CppModelManager::updateProjectInfo(pi2); + + // Initial check: Have all files been indexed? + while (refreshCount < 2) + QVERIFY(waitForRefresh()); + const auto allSources = p1Sources + p2Sources; + QCOMPARE(refreshedFiles, allSources); + + // Switch first project from global to local settings. Nothing should get re-indexed, + // as the default values are the same. + refreshCount = 0; + refreshedFiles.clear(); + CppCodeModelProjectSettings p1Settings(p1); + QVERIFY(p1Settings.useGlobalSettings()); + p1Settings.setUseGlobalSettings(false); + QCOMPARE(refreshCount, 0); + QVERIFY(!waitForRefresh()); + + // Change global settings. Only the second project should get re-indexed, as the first one + // has its own settings, which are still the same. + CppCodeModelSettings::Data globalSettings + = CppCodeModelSettings::settingsForProject(nullptr).data(); + globalSettings.indexerFileSizeLimitInMb = 1; + CppCodeModelSettings::setGlobalData(globalSettings); + if (refreshCount == 0) + QVERIFY(waitForRefresh()); + QVERIFY(!waitForRefresh()); + QCOMPARE(refreshedFiles, p2Sources); + + // Change first project's settings. Only this project should get re-indexed. + refreshCount = 0; + refreshedFiles.clear(); + CppCodeModelSettings::Data p1Data = p1Settings.data(); + p1Data.ignoreFiles = true; + p1Data.ignorePattern = "baz3.h"; + p1Settings.setData(p1Data); + if (refreshCount == 0) + QVERIFY(waitForRefresh()); + QVERIFY(!waitForRefresh()); + QSet filteredP1Sources = p1Sources; + filteredP1Sources -= p1Dir.filePath("baz3.h").toString(); + QCOMPARE(refreshedFiles, filteredP1Sources); +} + } // CppEditor::Internal diff --git a/src/plugins/cppeditor/cppmodelmanager_test.h b/src/plugins/cppeditor/cppmodelmanager_test.h index 939c0f4cca4..26cbefd1c84 100644 --- a/src/plugins/cppeditor/cppmodelmanager_test.h +++ b/src/plugins/cppeditor/cppmodelmanager_test.h @@ -31,6 +31,7 @@ private slots: void testRenameIncludes(); void testRenameIncludesInEditor(); void testDocumentsAndRevisions(); + void testSettingsChanges(); }; } // namespace CppEditor::Internal diff --git a/src/plugins/cppeditor/projectinfo.cpp b/src/plugins/cppeditor/projectinfo.cpp index 57466d1cd95..8a393df6d35 100644 --- a/src/plugins/cppeditor/projectinfo.cpp +++ b/src/plugins/cppeditor/projectinfo.cpp @@ -19,6 +19,12 @@ ProjectInfo::ConstPtr ProjectInfo::create(const ProjectExplorer::ProjectUpdateIn return ConstPtr(new ProjectInfo(updateInfo, projectParts)); } +ProjectInfo::ConstPtr ProjectInfo::cloneWithNewSettings(const ConstPtr &pi, + const CppCodeModelSettings &settings) +{ + return ConstPtr(new ProjectInfo(pi, settings)); +} + bool ProjectInfo::operator ==(const ProjectInfo &other) const { return m_projectName == other.m_projectName @@ -27,6 +33,7 @@ bool ProjectInfo::operator ==(const ProjectInfo &other) const && m_projectParts == other.m_projectParts && m_headerPaths == other.m_headerPaths && m_sourceFiles == other.m_sourceFiles + && m_settings.data() == other.m_settings.data() && m_defines == other.m_defines; } @@ -42,7 +49,8 @@ bool ProjectInfo::definesChanged(const ProjectInfo &other) const bool ProjectInfo::configurationChanged(const ProjectInfo &other) const { - return definesChanged(other) || m_headerPaths != other.m_headerPaths; + return definesChanged(other) || m_headerPaths != other.m_headerPaths + || m_settings.data() != other.settings().data(); } bool ProjectInfo::configurationOrFilesChanged(const ProjectInfo &other) const @@ -89,7 +97,20 @@ ProjectInfo::ProjectInfo(const ProjectExplorer::ProjectUpdateInfo &updateInfo, m_buildRoot(updateInfo.buildRoot), m_headerPaths(getHeaderPaths(projectParts)), m_sourceFiles(getSourceFiles(projectParts)), - m_defines(getDefines(projectParts)) + m_defines(getDefines(projectParts)), + m_settings(CppCodeModelSettings::Data(updateInfo.cppSettings)) +{ +} + +ProjectInfo::ProjectInfo(const ConstPtr &pi, const CppCodeModelSettings &settings) + : m_projectParts(pi->projectParts()), + m_projectName(pi->projectName()), + m_projectFilePath(pi->projectFilePath()), + m_buildRoot(pi->buildRoot()), + m_headerPaths(pi->m_headerPaths), + m_sourceFiles(pi->sourceFiles()), + m_defines(pi->m_defines), + m_settings(settings.data()) { } diff --git a/src/plugins/cppeditor/projectinfo.h b/src/plugins/cppeditor/projectinfo.h index 26f92eb6a7f..3b18c7ae6fd 100644 --- a/src/plugins/cppeditor/projectinfo.h +++ b/src/plugins/cppeditor/projectinfo.h @@ -5,6 +5,7 @@ #include "cppeditor_global.h" +#include "cppcodemodelsettings.h" #include "projectpart.h" #include @@ -28,6 +29,8 @@ public: using ConstPtr = std::shared_ptr; static ConstPtr create(const ProjectExplorer::ProjectUpdateInfo &updateInfo, const QVector &projectParts); + static ConstPtr cloneWithNewSettings(const ProjectInfo::ConstPtr &pi, + const CppCodeModelSettings &settings); const QVector &projectParts() const { return m_projectParts; } const QSet &sourceFiles() const { return m_sourceFiles; } @@ -35,6 +38,7 @@ public: Utils::FilePath projectFilePath() const { return m_projectFilePath; } Utils::FilePath projectRoot() const { return m_projectFilePath.parentDir(); } Utils::FilePath buildRoot() const { return m_buildRoot; } + const CppCodeModelSettings &settings() const { return m_settings; } // Comparisons bool operator ==(const ProjectInfo &other) const; @@ -46,6 +50,7 @@ public: private: ProjectInfo(const ProjectExplorer::ProjectUpdateInfo &updateInfo, const QVector &projectParts); + ProjectInfo(const ProjectInfo::ConstPtr &pi, const CppCodeModelSettings &settings); const QVector m_projectParts; const QString m_projectName; @@ -54,6 +59,7 @@ private: const ProjectExplorer::HeaderPaths m_headerPaths; const QSet m_sourceFiles; const ProjectExplorer::Macros m_defines; + const CppCodeModelSettings m_settings; }; using ProjectInfoList = QList; diff --git a/src/plugins/projectexplorer/rawprojectpart.cpp b/src/plugins/projectexplorer/rawprojectpart.cpp index 3f525ea095a..9bb69c5e846 100644 --- a/src/plugins/projectexplorer/rawprojectpart.cpp +++ b/src/plugins/projectexplorer/rawprojectpart.cpp @@ -178,6 +178,12 @@ ToolchainInfo::ToolchainInfo(const Toolchain *toolChain, } } +static CppSettingsRetriever g_cppSettingsRetriever; +void provideCppSettingsRetriever(const CppSettingsRetriever &retriever) +{ + g_cppSettingsRetriever = retriever; +} + ProjectUpdateInfo::ProjectUpdateInfo(Project *project, const KitInfo &kitInfo, const Utils::Environment &env, @@ -188,6 +194,8 @@ ProjectUpdateInfo::ProjectUpdateInfo(Project *project, , cToolchainInfo(ToolchainInfo(kitInfo.cToolchain, kitInfo.sysRootPath, env)) , cxxToolchainInfo(ToolchainInfo(kitInfo.cxxToolchain, kitInfo.sysRootPath, env)) { + if (g_cppSettingsRetriever) + cppSettings = g_cppSettingsRetriever(project); if (project) { projectName = project->displayName(); projectFilePath = project->projectFilePath(); diff --git a/src/plugins/projectexplorer/rawprojectpart.h b/src/plugins/projectexplorer/rawprojectpart.h index 75503170da4..7ebe5eed1d7 100644 --- a/src/plugins/projectexplorer/rawprojectpart.h +++ b/src/plugins/projectexplorer/rawprojectpart.h @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -170,9 +171,13 @@ public: Utils::FilePath buildRoot; RawProjectParts rawProjectParts; RppGenerator rppGenerator; + Utils::Store cppSettings; ToolchainInfo cToolchainInfo; ToolchainInfo cxxToolchainInfo; }; +using CppSettingsRetriever = std::function; +void PROJECTEXPLORER_EXPORT provideCppSettingsRetriever(const CppSettingsRetriever &retriever); + } // namespace ProjectExplorer From ba3f0bc841a55ed45cb1f8270cdcc1bfbbb6e18b Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Tue, 26 Dec 2023 10:51:11 +0200 Subject: [PATCH 0071/1060] Adpat to changes in QAbstractFileEngine/Iterator in qtbase - Replace hasNext()/next() with a `bool advance()` method - Replace QAFE::FileTime with QFile::FileTime, they are identical - QAFE methods now return std::unique_ptr, which matches reality as call sites stored the pointers in a std::unique_ptr anyway FileIteratorWrapper: State::BaseIteratorEnd is only needed when using hasNext()/next(), hasNext() changes m_status to State::BaseIteratorEnd, then next() checks that and changes m_status to State::Ended; this isn't needed with advance() since it's only one method. Change-Id: I4414f334715237a2fc13ace6f4733d975e2cfaa3 Reviewed-by: Reviewed-by: Marcus Tillmanns --- src/libs/utils/fsengine/diriterator.h | 20 +++++++++ .../fsengine/fileiteratordevicesappender.h | 41 ++++++++++++++++++- src/libs/utils/fsengine/fixedlistfsengine.h | 11 +++++ src/libs/utils/fsengine/fsengine_impl.cpp | 15 ++++--- src/libs/utils/fsengine/fsengine_impl.h | 15 ++++++- src/libs/utils/fsengine/fsenginehandler.cpp | 34 ++++++++++++--- src/libs/utils/fsengine/fsenginehandler.h | 4 ++ src/libs/utils/fsengine/rootinjectfsengine.h | 10 +++++ .../qmlprivategate/qmlprivategate.cpp | 23 ++++++++--- 9 files changed, 155 insertions(+), 18 deletions(-) diff --git a/src/libs/utils/fsengine/diriterator.h b/src/libs/utils/fsengine/diriterator.h index 54e9d5d2dd3..ba332b94847 100644 --- a/src/libs/utils/fsengine/diriterator.h +++ b/src/libs/utils/fsengine/diriterator.h @@ -8,6 +8,7 @@ #include #include +#include #include @@ -17,14 +18,32 @@ namespace Internal { class DirIterator : public QAbstractFileEngineIterator { public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + DirIterator(FilePaths paths, + const QString &path, + QDir::Filters filters, + const QStringList &filterNames) + : QAbstractFileEngineIterator(path, filters, filterNames) +#else DirIterator(FilePaths paths) : QAbstractFileEngineIterator({}, {}) +#endif , m_filePaths(std::move(paths)) , it(m_filePaths.begin()) {} // QAbstractFileEngineIterator interface public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + bool advance() override + { + if (!m_filePaths.empty() && m_filePaths.end() != it + 1) { + ++it; + return true; + } + return false; + } +#else QString next() override { if (it == m_filePaths.end()) @@ -35,6 +54,7 @@ public: } bool hasNext() const override { return !m_filePaths.empty() && m_filePaths.end() != it + 1; } +#endif // QT_VERSION_CHECK(6, 8, 0) QString currentFileName() const override { diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index e2afcf50fe7..4e5b8ca632b 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -6,11 +6,13 @@ #include "../filepath.h" #include "../hostosinfo.h" +#include #include namespace Utils { namespace Internal { +#if QT_VERSION < QT_VERSION_CHECK(6, 8, 0) // Based on http://bloglitb.blogspot.com/2011/12/access-to-private-members-safer.htm template struct PrivateAccess @@ -25,6 +27,7 @@ struct QAFEITag }; template struct PrivateAccess; +#endif class FileIteratorWrapper : public QAbstractFileEngineIterator { @@ -37,11 +40,38 @@ class FileIteratorWrapper : public QAbstractFileEngineIterator public: FileIteratorWrapper(std::unique_ptr &&baseIterator) - : QAbstractFileEngineIterator(baseIterator->filters(), baseIterator->nameFilters()) + : QAbstractFileEngineIterator( +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + baseIterator->path(), +#endif + baseIterator->filters(), baseIterator->nameFilters()) , m_baseIterator(std::move(baseIterator)) - {} + { +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + // Can be called in the constructor since the iterator path + // has already been set + setStatus(); +#endif + } public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + bool advance() override + { + if (m_status == State::Ended) + return false; + + const bool res = m_baseIterator->advance(); + if (m_status == State::IteratingRoot && !res) { + // m_baseIterator finished, but we need to advance one last time, so that + // currentFileName() returns FilePath::specialRootPath(). + m_status = State::Ended; + return true; + } + + return res; + } +#else QString next() override { if (m_status == State::Ended) @@ -71,6 +101,7 @@ public: return res; } +#endif QString currentFileName() const override { return m_status == State::Ended ? FilePath::specialRootPath() @@ -94,6 +125,7 @@ private: return p; } +#if QT_VERSION < QT_VERSION_CHECK(6, 8, 0) void setPath() const { if (!m_hasSetPath) { @@ -102,10 +134,15 @@ private: m_hasSetPath = true; } } +#endif private: std::unique_ptr m_baseIterator; + +#if QT_VERSION < QT_VERSION_CHECK(6, 8, 0) mutable bool m_hasSetPath{false}; +#endif + mutable State m_status{State::NotIteratingRoot}; }; diff --git a/src/libs/utils/fsengine/fixedlistfsengine.h b/src/libs/utils/fsengine/fixedlistfsengine.h index 3518b5d0b5a..6875dd63822 100644 --- a/src/libs/utils/fsengine/fixedlistfsengine.h +++ b/src/libs/utils/fsengine/fixedlistfsengine.h @@ -9,6 +9,7 @@ #include "../stringutils.h" #include +#include namespace Utils { namespace Internal { @@ -63,10 +64,20 @@ public: return QAbstractFileEngine::fileName(file); } + +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + IteratorUniquePtr beginEntryList(const QString &path, + QDir::Filters filters, + const QStringList &filterNames) override + { + return std::make_unique(m_children, path, filters, filterNames); + } +#else Iterator *beginEntryList(QDir::Filters /*filters*/, const QStringList & /*filterNames*/) override { return new DirIterator(m_children); } +#endif }; } // namespace Internal diff --git a/src/libs/utils/fsengine/fsengine_impl.cpp b/src/libs/utils/fsengine/fsengine_impl.cpp index 05147709d47..295f0cac747 100644 --- a/src/libs/utils/fsengine/fsengine_impl.cpp +++ b/src/libs/utils/fsengine/fsengine_impl.cpp @@ -295,8 +295,14 @@ bool FSEngineImpl::cloneTo(QAbstractFileEngine *target) return QAbstractFileEngine::cloneTo(target); } +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) +QAbstractFileEngine::IteratorUniquePtr FSEngineImpl::beginEntryList(const QString &path, + QDir::Filters filters, + const QStringList &filterNames) +#else QAbstractFileEngine::Iterator *FSEngineImpl::beginEntryList(QDir::Filters filters, const QStringList &filterNames) +#endif { FilePaths paths{m_filePath.pathAppended(".")}; m_filePath.iterateDirectory( @@ -310,12 +316,11 @@ QAbstractFileEngine::Iterator *FSEngineImpl::beginEntryList(QDir::Filters filter }, {filterNames, filters}); +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(std::move(paths), path, filters, filterNames); +#else return new DirIterator(std::move(paths)); -} - -QAbstractFileEngine::Iterator *FSEngineImpl::endEntryList() -{ - return nullptr; +#endif } qint64 FSEngineImpl::read(char *data, qint64 maxlen) diff --git a/src/libs/utils/fsengine/fsengine_impl.h b/src/libs/utils/fsengine/fsengine_impl.h index 6fcba8ac523..8ba1ca0affa 100644 --- a/src/libs/utils/fsengine/fsengine_impl.h +++ b/src/libs/utils/fsengine/fsengine_impl.h @@ -8,6 +8,7 @@ #include #include +#include namespace Utils { namespace Internal { @@ -46,13 +47,25 @@ public: QString fileName(FileName file) const override; uint ownerId(FileOwner) const override; QString owner(FileOwner) const override; + +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + using FileTime = QFile::FileTime; +#endif bool setFileTime(const QDateTime &newDate, FileTime time) override; QDateTime fileTime(FileTime time) const override; void setFileName(const QString &file) override; int handle() const override; bool cloneTo(QAbstractFileEngine *target) override; + +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + IteratorUniquePtr beginEntryList(const QString &path, QDir::Filters filters, + const QStringList &filterNames) override; + IteratorUniquePtr endEntryList() override { return {}; } +#else Iterator *beginEntryList(QDir::Filters filters, const QStringList &filterNames) override; - Iterator *endEntryList() override; + Iterator *endEntryList() override { return nullptr; } +#endif + qint64 read(char *data, qint64 maxlen) override; qint64 readLine(char *data, qint64 maxlen) override; qint64 write(const char *data, qint64 len) override; diff --git a/src/libs/utils/fsengine/fsenginehandler.cpp b/src/libs/utils/fsengine/fsenginehandler.cpp index 2f828537d19..29fe759a861 100644 --- a/src/libs/utils/fsengine/fsenginehandler.cpp +++ b/src/libs/utils/fsengine/fsenginehandler.cpp @@ -46,10 +46,15 @@ static bool isRootPath(const QString &fileName) return fileName.size() == 1 && fileName[0] == '/'; } -QAbstractFileEngine *FSEngineHandler::create(const QString &fileName) const +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) +std::unique_ptr +#else +QAbstractFileEngine * +#endif +FSEngineHandler::create(const QString &fileName) const { if (fileName.startsWith(':')) - return nullptr; + return {}; static const QString rootPath = FilePath::specialRootPath(); static const FilePath rootFilePath = FilePath::fromString(rootPath); @@ -62,7 +67,11 @@ QAbstractFileEngine *FSEngineHandler::create(const QString &fileName) const return rootFilePath.pathAppended(scheme); }); +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(removeDoubleSlash(fileName), paths); +#else return new FixedListFSEngine(removeDoubleSlash(fileName), paths); +#endif } if (fixedFileName.startsWith(rootPath)) { @@ -74,20 +83,35 @@ QAbstractFileEngine *FSEngineHandler::create(const QString &fileName) const return root.scheme() == scheme; }); +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(removeDoubleSlash(fileName), + filteredRoots); +#else return new FixedListFSEngine(removeDoubleSlash(fileName), filteredRoots); +#endif } } FilePath fixedPath = FilePath::fromString(fixedFileName); - if (fixedPath.needsDevice()) + if (fixedPath.needsDevice()) { +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(removeDoubleSlash(fileName)); +#else return new FSEngineImpl(removeDoubleSlash(fileName)); +#endif + } } - if (isRootPath(fixedFileName)) + if (isRootPath(fixedFileName)) { +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(fileName); +#else return new RootInjectFSEngine(fileName); +#endif + } - return nullptr; + return {}; } } // Utils::Internal diff --git a/src/libs/utils/fsengine/fsenginehandler.h b/src/libs/utils/fsengine/fsenginehandler.h index 6fdb6a7ab9d..68421ddd92e 100644 --- a/src/libs/utils/fsengine/fsenginehandler.h +++ b/src/libs/utils/fsengine/fsenginehandler.h @@ -10,7 +10,11 @@ namespace Utils::Internal { class FSEngineHandler : public QAbstractFileEngineHandler { public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + std::unique_ptr create(const QString &fileName) const override; +#else QAbstractFileEngine *create(const QString &fileName) const override; +#endif }; } // Utils::Internal diff --git a/src/libs/utils/fsengine/rootinjectfsengine.h b/src/libs/utils/fsengine/rootinjectfsengine.h index d57747dab96..9eb6a8a8322 100644 --- a/src/libs/utils/fsengine/rootinjectfsengine.h +++ b/src/libs/utils/fsengine/rootinjectfsengine.h @@ -16,12 +16,22 @@ public: using QFSFileEngine::QFSFileEngine; public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + IteratorUniquePtr beginEntryList(const QString &path, + QDir::Filters filters, + const QStringList &filterNames) override + { + return std::make_unique( + QFSFileEngine::beginEntryList(path, filters, filterNames)); + } +#else Iterator *beginEntryList(QDir::Filters filters, const QStringList &filterNames) override { std::unique_ptr baseIterator( QFSFileEngine::beginEntryList(filters, filterNames)); return new FileIteratorWrapper(std::move(baseIterator)); } +#endif }; } // namespace Internal diff --git a/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp b/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp index 8abfed59160..123d4aee2dc 100644 --- a/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp +++ b/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp @@ -473,16 +473,25 @@ ComponentCompleteDisabler::~ComponentCompleteDisabler() class QrcEngineHandler : public QAbstractFileEngineHandler { public: +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + std::unique_ptr create(const QString &fileName) const final; +#else QAbstractFileEngine *create(const QString &fileName) const final; +#endif }; -QAbstractFileEngine *QrcEngineHandler::create(const QString &fileName) const +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) +std::unique_ptr +#else +QAbstractFileEngine * +#endif +QrcEngineHandler::create(const QString &fileName) const { if (fileName.startsWith(":/qt-project.org")) - return nullptr; + return {}; if (fileName.startsWith(":/qtquickplugin")) - return nullptr; + return {}; if (fileName.startsWith(":/")) { const QStringList searchPaths = qmlDesignerRCPath().split(';'); @@ -493,18 +502,22 @@ QAbstractFileEngine *QrcEngineHandler::create(const QString &fileName) const fixedPath.replace(":" + qrcDefintion.first(), qrcDefintion.last() + '/'); if (fileName == fixedPath) - return nullptr; + return {}; if (QFileInfo::exists(fixedPath)) { fixedPath.replace("//", "/"); fixedPath.replace('\\', '/'); +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + return std::make_unique(fixedPath); +#else return new QFSFileEngine(fixedPath); +#endif } } } } - return nullptr; + return {}; } static QrcEngineHandler* s_qrcEngineHandler = nullptr; From 27ce9634814b79cccef09f8ed91ff7b7967a617b Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Tue, 19 Mar 2024 06:37:28 +0100 Subject: [PATCH 0072/1060] Utils: Fix build with Qt6.4 Amends ba3f0bc841a55ed45cb1f8270cdcc1bfbbb6e18b. Change-Id: Ib405096a51f4c2583e9e3c281bfea8f6eaa44b48 Reviewed-by: Marcus Tillmanns --- src/libs/utils/fsengine/diriterator.h | 2 +- src/libs/utils/fsengine/fileiteratordevicesappender.h | 2 +- src/libs/utils/fsengine/fixedlistfsengine.h | 2 +- src/libs/utils/fsengine/fsengine_impl.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libs/utils/fsengine/diriterator.h b/src/libs/utils/fsengine/diriterator.h index ba332b94847..d6605b44264 100644 --- a/src/libs/utils/fsengine/diriterator.h +++ b/src/libs/utils/fsengine/diriterator.h @@ -8,7 +8,7 @@ #include #include -#include +#include #include diff --git a/src/libs/utils/fsengine/fileiteratordevicesappender.h b/src/libs/utils/fsengine/fileiteratordevicesappender.h index 4e5b8ca632b..ed87f7d5188 100644 --- a/src/libs/utils/fsengine/fileiteratordevicesappender.h +++ b/src/libs/utils/fsengine/fileiteratordevicesappender.h @@ -6,8 +6,8 @@ #include "../filepath.h" #include "../hostosinfo.h" -#include #include +#include namespace Utils { namespace Internal { diff --git a/src/libs/utils/fsengine/fixedlistfsengine.h b/src/libs/utils/fsengine/fixedlistfsengine.h index 6875dd63822..b27d3bc978a 100644 --- a/src/libs/utils/fsengine/fixedlistfsengine.h +++ b/src/libs/utils/fsengine/fixedlistfsengine.h @@ -9,7 +9,7 @@ #include "../stringutils.h" #include -#include +#include namespace Utils { namespace Internal { diff --git a/src/libs/utils/fsengine/fsengine_impl.h b/src/libs/utils/fsengine/fsengine_impl.h index 8ba1ca0affa..9d11b917ac9 100644 --- a/src/libs/utils/fsengine/fsengine_impl.h +++ b/src/libs/utils/fsengine/fsengine_impl.h @@ -7,8 +7,8 @@ #include +#include #include -#include namespace Utils { namespace Internal { From 1573a92150b42df0c5db7f19d2c79a940369089e Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Mon, 18 Mar 2024 14:23:43 +0100 Subject: [PATCH 0073/1060] macOS: Remove usage of deprecated API `NSApplicationActivateIgnoringOtherApps` is deprecated and doesn't have any effect any more. Switch this to `NSApplicationActivateAllWindows` which we actually want when running an application, and remove an unneeded cast. Change-Id: I75849533e4b172db577d5484ef12c8ee4df20d59 Reviewed-by: Reviewed-by: Marcus Tillmanns --- src/libs/utils/processhandle_mac.mm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libs/utils/processhandle_mac.mm b/src/libs/utils/processhandle_mac.mm index 52cc0d3e077..f492dae37d3 100644 --- a/src/libs/utils/processhandle_mac.mm +++ b/src/libs/utils/processhandle_mac.mm @@ -10,8 +10,7 @@ bool ProcessHandle::activate() { NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:pid()]; - return app && [app activateWithOptions:static_cast( - NSApplicationActivateIgnoringOtherApps)]; + return app && [app activateWithOptions:NSApplicationActivateAllWindows]; } } // Utils From f5ba46ccbdc90d06cd3aa2e161ab69e79f349dbe Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 18 Mar 2024 12:15:25 +0100 Subject: [PATCH 0074/1060] CppEditor: Tell clangd about path to CUDA At the very least, this fixes an ugly warning message for .cu files. May or may not improve other things as well. Task-number: QTCREATORBUG-23113 Change-Id: If389fd67a153f7da13e5d4d465189aaef352c976 Reviewed-by: Cristian Adam Reviewed-by: Christian Stenger Reviewed-by: Qt CI Bot Reviewed-by: --- src/plugins/cppeditor/projectpart.cpp | 29 ++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/plugins/cppeditor/projectpart.cpp b/src/plugins/cppeditor/projectpart.cpp index 680723750f8..24f9dc42e85 100644 --- a/src/plugins/cppeditor/projectpart.cpp +++ b/src/plugins/cppeditor/projectpart.cpp @@ -12,6 +12,7 @@ #include using namespace ProjectExplorer; +using namespace Utils; namespace CppEditor { @@ -115,6 +116,32 @@ static QStringList getIncludedFiles(const RawProjectPart &rpp, const RawProjectP return !rpp.includedFiles.isEmpty() ? rpp.includedFiles : flags.includedFiles; } +static QStringList getExtraCodeModelFlags(const RawProjectPart &rpp, const ProjectFiles &files) +{ + if (!Utils::anyOf(files, [](const ProjectFile &f) { return f.kind == ProjectFile::CudaSource; })) + return {}; + + Utils::FilePath cudaPath; + for (const HeaderPath &hp : rpp.headerPaths) { + if (hp.type == HeaderPathType::BuiltIn) + continue; + if (!hp.path.endsWith("/include")) + continue; + const Utils::FilePath includeDir = Utils::FilePath::fromString(hp.path); + if (!includeDir.pathAppended("cuda.h").exists()) + continue; + for (FilePath dir = includeDir.parentDir(); cudaPath.isEmpty() && !dir.isRootPath(); + dir = dir.parentDir()) { + if (dir.pathAppended("nvvm").exists()) + cudaPath = dir; + } + break; + } + if (!cudaPath.isEmpty()) + return {"--cuda-path=" + cudaPath.toUserOutput()}; + return {}; +} + ProjectPart::ProjectPart(const Utils::FilePath &topLevelProject, const RawProjectPart &rpp, const QString &displayName, @@ -149,7 +176,7 @@ ProjectPart::ProjectPart(const Utils::FilePath &topLevelProject, toolchainInstallDir(tcInfo.installDir), compilerFilePath(tcInfo.compilerFilePath), warningFlags(flags.warningFlags), - extraCodeModelFlags(tcInfo.extraCodeModelFlags), + extraCodeModelFlags(tcInfo.extraCodeModelFlags + getExtraCodeModelFlags(rpp, files)), compilerFlags(flags.commandLineFlags), m_macroReport(getToolchainMacros(flags, tcInfo, language)), languageFeatures(deriveLanguageFeatures()) From 0a27bc2e78c3e747926e02fcdeb1fe758e3fa93d Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Mon, 18 Mar 2024 16:45:59 +0100 Subject: [PATCH 0075/1060] Clang: Use -isystem for system headers The project manager was passing correctly the system headers, but the compileroptionsbuilder was ignoring them by having UseSystemHeader::No. This change makes the project's view to be reflected in clangd's compile_commands.json. Fixes: QTCREATORBUG-30474 Change-Id: Ie3b80642e27ada4c8c8725f21e3cfbb2a4051aa0 Reviewed-by: Christian Kandeler --- .../cppeditor/compileroptionsbuilder.cpp | 3 +-- .../cppeditor/compileroptionsbuilder_test.cpp | 18 +++++++++--------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/plugins/cppeditor/compileroptionsbuilder.cpp b/src/plugins/cppeditor/compileroptionsbuilder.cpp index be40b9c914f..a860edbee34 100644 --- a/src/plugins/cppeditor/compileroptionsbuilder.cpp +++ b/src/plugins/cppeditor/compileroptionsbuilder.cpp @@ -692,8 +692,7 @@ void CompilerOptionsBuilder::addIncludeDirOptionForPath(const HeaderPath &path) if (path.type == HeaderPathType::BuiltIn) { systemPath = true; } else if (path.type == HeaderPathType::System) { - if (m_useSystemHeader == UseSystemHeader::Yes) - systemPath = true; + systemPath = true; } else { // ProjectExplorer::HeaderPathType::User if (m_useSystemHeader == UseSystemHeader::Yes && m_projectPart.hasProject() diff --git a/src/plugins/cppeditor/compileroptionsbuilder_test.cpp b/src/plugins/cppeditor/compileroptionsbuilder_test.cpp index ed53ef99229..81cade277c3 100644 --- a/src/plugins/cppeditor/compileroptionsbuilder_test.cpp +++ b/src/plugins/cppeditor/compileroptionsbuilder_test.cpp @@ -196,7 +196,7 @@ void CompilerOptionsBuilderTest::testHeaderPathOptionsOrder() QCOMPARE(compilerOptionsBuilder.options(), (QStringList{"-nostdinc", "-nostdinc++", "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), "-isystem", t.toNative("/dummy"), + "-isystem", t.toNative("/tmp/system_path"), "-isystem", t.toNative("/dummy"), "-isystem", t.toNative("/tmp/builtin_path")})); } @@ -212,9 +212,9 @@ void CompilerOptionsBuilderTest::testHeaderPathOptionsOrderMsvc() QCOMPARE(compilerOptionsBuilder.options(), (QStringList{"-nostdinc", "-nostdinc++", "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), "/clang:-isystem", - "/clang:" + t.toNative("/dummy"), "/clang:-isystem", - "/clang:" + t.toNative("/tmp/builtin_path")})); + "/clang:-isystem", "/clang:" + t.toNative("/tmp/system_path"), + "/clang:-isystem", "/clang:" + t.toNative("/dummy"), + "/clang:-isystem", "/clang:" + t.toNative("/tmp/builtin_path")})); } void CompilerOptionsBuilderTest::testUseSystemHeader() @@ -239,7 +239,7 @@ void CompilerOptionsBuilderTest::testNoClangHeadersPath() t.compilerOptionsBuilder->addHeaderPathOptions(); QCOMPARE(t.compilerOptionsBuilder->options(), - (QStringList{"-I" + t.toNative("/tmp/path"), "-I" + t.toNative("/tmp/system_path")})); + (QStringList{"-I" + t.toNative("/tmp/path"), "-isystem", t.toNative("/tmp/system_path")})); } void CompilerOptionsBuilderTest::testClangHeadersAndCppIncludePathsOrderMacOs() @@ -260,7 +260,7 @@ void CompilerOptionsBuilderTest::testClangHeadersAndCppIncludePathsOrderMacOs() QCOMPARE(compilerOptionsBuilder.options(), (QStringList{"-nostdinc", "-nostdinc++", "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), + "-isystem", t.toNative("/tmp/system_path"), "-isystem", t.toNative("/usr/include/c++/4.2.1"), "-isystem", t.toNative("/usr/include/c++/4.2.1/backward"), "-isystem", t.toNative("/usr/local/include"), @@ -599,7 +599,7 @@ void CompilerOptionsBuilderTest::testBuildAllOptions() wrappedQtHeadersPath, // contains -I already wrappedQtCoreHeadersPath, // contains -I already "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), + "-isystem", t.toNative("/tmp/system_path"), "-isystem", t.toNative("/dummy"), "-isystem", t.toNative("/tmp/builtin_path")})); } @@ -628,7 +628,7 @@ void CompilerOptionsBuilderTest::testBuildAllOptionsMsvc() wrappedQtHeadersPath, // contains -I already wrappedQtCoreHeadersPath, // contains -I already "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), + "/clang:-isystem", "/clang:" + t.toNative("/tmp/system_path"), "/clang:-isystem", "/clang:" + t.toNative("/dummy"), "/clang:-isystem", "/clang:" + t.toNative("/tmp/builtin_path")})); } @@ -659,7 +659,7 @@ void CompilerOptionsBuilderTest::testBuildAllOptionsMsvcWithExceptions() wrappedQtHeadersPath, // contains -I already wrappedQtCoreHeadersPath, // contains -I already "-I" + t.toNative("/tmp/path"), - "-I" + t.toNative("/tmp/system_path"), + "/clang:-isystem", "/clang:" + t.toNative("/tmp/system_path"), "/clang:-isystem", "/clang:" + t.toNative("/dummy"), "/clang:-isystem", "/clang:" + t.toNative("/tmp/builtin_path")})); } From 2e86420052d18a3ada261f6610b491ac719aef03 Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 19 Mar 2024 12:54:07 +0100 Subject: [PATCH 0076/1060] Debugger: Add context menu entries to enable/disable all breakpoints Fixes: QTCREATORBUG-30564 Change-Id: I8b0458eed859c23f1ef9d40c0ad7cbe6b61ecf90 Reviewed-by: Marcus Tillmanns --- src/plugins/debugger/breakhandler.cpp | 58 +++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/plugins/debugger/breakhandler.cpp b/src/plugins/debugger/breakhandler.cpp index a3f6cc2f11c..3d907d20be6 100644 --- a/src/plugins/debugger/breakhandler.cpp +++ b/src/plugins/debugger/breakhandler.cpp @@ -1637,6 +1637,8 @@ bool BreakHandler::contextMenuEvent(const ItemViewEvent &ev) // bp.setThreadSpec(threadId); // }); + menu->addSeparator(); + addAction(this, menu, selectedBreakpoints.size() > 1 ? breakpointsEnabled ? Tr::tr("Disable Selected Breakpoints") : Tr::tr("Enable Selected Breakpoints") @@ -1651,6 +1653,37 @@ bool BreakHandler::contextMenuEvent(const ItemViewEvent &ev) } ); + QList enabledBreakpoints; + QList disabledBreakpoints; + forItemsAtLevel<1>([&enabledBreakpoints, &disabledBreakpoints](Breakpoint bp) { + if (bp) { + if (bp->isEnabled()) + enabledBreakpoints.append(bp); + else + disabledBreakpoints.append(bp); + } + }); + + addAction(this, menu, Tr::tr("Disable All Breakpoints"), + !enabledBreakpoints.isEmpty(), + [this, enabledBreakpoints] { + for (Breakpoint bp : enabledBreakpoints) { + if (GlobalBreakpoint gbp = bp->globalBreakpoint()) + gbp->setEnabled(false, false); + requestBreakpointEnabling(bp, false); + } + }); + + addAction(this, menu, Tr::tr("Enable All Breakpoints"), + !disabledBreakpoints.isEmpty(), + [this, disabledBreakpoints] { + for (Breakpoint bp : disabledBreakpoints) { + if (GlobalBreakpoint gbp = bp->globalBreakpoint()) + gbp->setEnabled(true, false); + requestBreakpointEnabling(bp, true); + } + }); + addAction(this, menu, selectedLocations.size() > 1 ? locationsEnabled ? Tr::tr("Disable Selected Locations") : Tr::tr("Enable Selected Locations") @@ -2661,6 +2694,31 @@ bool BreakpointManager::contextMenuEvent(const ItemViewEvent &ev) } ); + QList enabledBreakpoints; + QList disabledBreakpoints; + forItemsAtLevel<1>([&enabledBreakpoints, &disabledBreakpoints](GlobalBreakpoint gbp) { + if (gbp) { + if (gbp->isEnabled()) + enabledBreakpoints.append(gbp); + else + disabledBreakpoints.append(gbp); + } + }); + + addAction(this, menu, Tr::tr("Disable All Breakpoints"), + !enabledBreakpoints.isEmpty(), + [enabledBreakpoints] { + for (GlobalBreakpoint gbp : enabledBreakpoints) + gbp->setEnabled(false); + }); + + addAction(this, menu, Tr::tr("Enable All Breakpoints"), + !disabledBreakpoints.isEmpty(), + [disabledBreakpoints] { + for (GlobalBreakpoint gbp : disabledBreakpoints) + gbp->setEnabled(true); + }); + menu->addSeparator(); addAction(this, menu, Tr::tr("Delete All Breakpoints"), From 1f516cacf7f7e7d3697dff82b0bdbbd360b2b88c Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Mon, 18 Mar 2024 11:45:15 +0100 Subject: [PATCH 0077/1060] DeviceSettingsWidget: Don't leak QLayoutItem According to docs for QLayout::replaceWidget(), the returned item should be either deleted or inserted somewhere else. Change-Id: I02da36dd0d3fe7de7fa04747d26ea01620349421 Reviewed-by: Eike Ziller --- .../projectexplorer/devicesupport/devicesettingspage.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp b/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp index dfcfc83a1be..f1e520c4c66 100644 --- a/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp +++ b/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp @@ -156,7 +156,7 @@ DeviceSettingsWidget::DeviceSettingsWidget() }.attachTo(scrollAreaWidget); // Just a placeholder for the device name edit widget. - m_deviceNameEditWidget = new QWidget(); + m_deviceNameEditWidget = new QWidget; // clang-format off Form { @@ -341,8 +341,9 @@ void DeviceSettingsWidget::currentDeviceChanged(int index) Layouting::Column item{Layouting::noMargin()}; device->settings()->displayName.addToLayout(item); QWidget *newEdit = item.emerge(); - m_generalFormLayout->replaceWidget(m_deviceNameEditWidget, newEdit); - + QLayoutItem *oldItem = m_generalFormLayout->replaceWidget(m_deviceNameEditWidget, newEdit); + QTC_CHECK(oldItem); + delete oldItem; delete m_deviceNameEditWidget; m_deviceNameEditWidget = newEdit; From aaf839bcf0e0ee5b77f47fcc47b4c18c2bbe31b3 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 15 Mar 2024 17:45:22 +0100 Subject: [PATCH 0078/1060] CppEditor: Do not emit a signal when setting "categorize references" This is not an actual setting and should not result in a signal emission. Amends faa595e38b830690a79904df413376996f728bb6. Change-Id: Ic3816ca80090594659be66f5558ce52b921c0f02 Reviewed-by: Reviewed-by: David Schulz Reviewed-by: Qt CI Bot --- src/plugins/cppeditor/cppcodemodelsettings.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 5c8e3caff18..1a72174155f 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -184,9 +184,7 @@ bool CppCodeModelSettings::categorizeFindReferences() void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { - Data d = globalInstance().data(); - d.categorizeFindReferences = categorize; - globalInstance().setGlobalData(d); + globalInstance().m_data.categorizeFindReferences = categorize; } CppCodeModelProjectSettings::CppCodeModelProjectSettings(ProjectExplorer::Project *project) From 230bfa88a0a8de44e5ef5037d2397786c8913e73 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 19 Mar 2024 16:54:43 +0100 Subject: [PATCH 0079/1060] CppEditor: Fix soft assert when serializing clangd setting This was probably introduced by a merge commit. Change-Id: I5360b8fb25aa9cfbf8e6d3563b0219152a144815 Reviewed-by: Qt CI Bot Reviewed-by: Reviewed-by: Christian Stenger --- src/plugins/cppeditor/cppcodemodelsettings.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 1a72174155f..d1b4c470983 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -624,8 +624,7 @@ Store ClangdSettings::Data::toMap() const map.insert(clangdSizeThresholdKey(), sizeThresholdInKb); map.insert(sessionsWithOneClangdKey(), sessionsWithOneClangd); map.insert(diagnosticConfigIdKey(), diagnosticConfigId.toSetting()); - if (haveCheckedHardwareReqirements != false) - map.insert(checkedHardwareKey(), true); + map.insert(checkedHardwareKey(), haveCheckedHardwareReqirements); map.insert(completionResultsKey(), completionResults); return map; } From 353ddc87a41d08f275a11da2fef62a5efef595ac Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Sat, 17 Feb 2024 12:29:00 +0100 Subject: [PATCH 0080/1060] DockManager: Introduce read/writeAttribute() helpers They are going to be reused in reading / writing display name and mcus enabled. Change-Id: I679de8858c37fb8629774d0166a7dbc56e5dab76 Reviewed-by: Tim Jenssen --- .../advanceddockingsystem/dockmanager.cpp | 42 +++++++++++++++++++ src/libs/advanceddockingsystem/dockmanager.h | 5 ++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/libs/advanceddockingsystem/dockmanager.cpp b/src/libs/advanceddockingsystem/dockmanager.cpp index b718302f4cc..beb396bc663 100644 --- a/src/libs/advanceddockingsystem/dockmanager.cpp +++ b/src/libs/advanceddockingsystem/dockmanager.cpp @@ -1627,6 +1627,48 @@ bool DockManager::writeMcusEnabled(const FilePath &filePath, const QString &mcus return true; } +QString DockManager::readAttribute(const FilePath &filePath, QStringView key) +{ + auto data = loadFile(filePath); + if (data.isEmpty()) + return {}; + + auto tmp = data.startsWith(" content = filePath.fileContents(); + QTC_ASSERT_EXPECTED(content, return false); + + QDomDocument doc; + QString error_msg; + int error_line, error_col; + if (!doc.setContent(*content, &error_msg, &error_line, &error_col)) { + qWarning() << QString("XML error on line %1, col %2: %3") + .arg(error_line).arg(error_col).arg(error_msg); + return false; + } + + QDomElement docElem = doc.documentElement(); + docElem.setAttribute(key.toString(), value); + + const expected_str result = write(filePath, doc.toByteArray(workspaceXmlFormattingIndent)); + if (result) + return true; + + qWarning() << "Could not write" << key << value << "to" << filePath << ":" << result.error(); + return false; +} + expected_str DockManager::write(const FilePath &filePath, const QByteArray &data) { qCInfo(adsLog) << "Write" << filePath; diff --git a/src/libs/advanceddockingsystem/dockmanager.h b/src/libs/advanceddockingsystem/dockmanager.h index 23aa21a5781..b092eedef09 100644 --- a/src/libs/advanceddockingsystem/dockmanager.h +++ b/src/libs/advanceddockingsystem/dockmanager.h @@ -458,7 +458,7 @@ public: /** * This function sets the tool button style for the given dock widget state. It is possible to - * switch the tool button style depending on the state. If a dock widget is floating, then here + * switch the tool button style depending on the state. If a dock widget is floating, then here * are more space and it is possible to select a style that requires more space like * Qt::ToolButtonTextUnderIcon. For the docked state Qt::ToolButtonIconOnly might be better. */ @@ -783,6 +783,9 @@ signals: void lockWorkspaceChanged(); private: + static QString readAttribute(const Utils::FilePath &filePath, QStringView key); + static bool writeAttribute(const Utils::FilePath &filePath, QStringView key, + const QString &value); static Utils::expected_str write(const Utils::FilePath &filePath, const QByteArray &data); Utils::expected_str loadWorkspace(const Workspace &workspace) const; From 524c5fd5c9818ecd1cab84e5c5f299e2ae92c343 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Sat, 17 Feb 2024 12:22:35 +0100 Subject: [PATCH 0081/1060] DockManager: Limit code repetition Change-Id: I4dbbf0737a1df9aa0853aeb4b31fa9c16a7827df Reviewed-by: Tim Jenssen --- .../advanceddockingsystem/dockmanager.cpp | 86 +------------------ 1 file changed, 4 insertions(+), 82 deletions(-) diff --git a/src/libs/advanceddockingsystem/dockmanager.cpp b/src/libs/advanceddockingsystem/dockmanager.cpp index beb396bc663..60586ff4f43 100644 --- a/src/libs/advanceddockingsystem/dockmanager.cpp +++ b/src/libs/advanceddockingsystem/dockmanager.cpp @@ -1531,100 +1531,22 @@ QByteArray DockManager::loadFile(const FilePath &filePath) QString DockManager::readDisplayName(const FilePath &filePath) { - auto data = loadFile(filePath); - - if (data.isEmpty()) - return {}; - - auto tmp = data.startsWith(" content = filePath.fileContents(); - - QTC_ASSERT_EXPECTED(content, return false); - - QDomDocument doc; - QString error_msg; - int error_line, error_col; - if (!doc.setContent(*content, &error_msg, &error_line, &error_col)) { - qWarning() << QString("XML error on line %1, col %2: %3") - .arg(error_line) - .arg(error_col) - .arg(error_msg); - return false; - } - - QDomElement docElem = doc.documentElement(); - docElem.setAttribute(workspaceDisplayNameAttribute.toString(), displayName); - - const expected_str result = write(filePath, doc.toByteArray(workspaceXmlFormattingIndent)); - if (!result) { - qWarning() << "Could not write display name" << displayName << "to" << filePath << ":" - << result.error(); - return false; - } - - return true; + return writeAttribute(filePath, workspaceDisplayNameAttribute, displayName); } QString DockManager::readMcusEnabled(const FilePath &filePath) { - auto data = loadFile(filePath); - - if (data.isEmpty()) - return {}; - - auto tmp = data.startsWith(" content = filePath.fileContents(); - - QTC_ASSERT_EXPECTED(content, return false); - - QDomDocument doc; - QString error_msg; - int error_line, error_col; - if (!doc.setContent(*content, &error_msg, &error_line, &error_col)) { - qWarning() << QString("XML error on line %1, col %2: %3") - .arg(error_line) - .arg(error_col) - .arg(error_msg); - return false; - } - - QDomElement docElem = doc.documentElement(); - docElem.setAttribute(workspaceMcusEnabledAttribute.toString(), mcusEnabled); - - const expected_str result = write(filePath, doc.toByteArray(workspaceXmlFormattingIndent)); - if (!result) { - qWarning() << "Could not write mcusEnabled" << mcusEnabled << "to" << filePath << ":" - << result.error(); - return false; - } - - return true; + return writeAttribute(filePath, workspaceMcusEnabledAttribute, mcusEnabled); } QString DockManager::readAttribute(const FilePath &filePath, QStringView key) From 41c781891fb36f2d18b47673df5d520fdebaa799 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Wed, 20 Mar 2024 15:15:07 +0100 Subject: [PATCH 0082/1060] Qbs build: Fix copyright year again Amends the last merge Change-Id: Ia8d81e77a447345af48d42ed5f3f7fdbbef5eda2 Reviewed-by: Christian Kandeler Reviewed-by: --- qbs/modules/qtc/qtc.qbs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qbs/modules/qtc/qtc.qbs b/qbs/modules/qtc/qtc.qbs index cf145a73d12..8b399722dbe 100644 --- a/qbs/modules/qtc/qtc.qbs +++ b/qbs/modules/qtc/qtc.qbs @@ -17,7 +17,7 @@ Module { property string qtcreator_compat_version: ide_compat_version_major + '.' + ide_compat_version_minor + '.' + ide_compat_version_release - property string qtcreator_copyright_year: '2023' + property string qtcreator_copyright_year: '2024' property string qtcreator_copyright_string: "(C) " + qtcreator_copyright_year + " The Qt Company Ltd" property string ide_display_name: 'Qt Creator' From cb4f296498561ce43ebf2433593b46822b0d6740 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Thu, 21 Mar 2024 02:30:43 +0100 Subject: [PATCH 0083/1060] Cdbext: report HRESULT as an integral data type Fixes: QTCREATORBUG-30574 Change-Id: If877c32639c853bae9b6a5a5762f24a3954f60d5 Reviewed-by: Marcus Tillmanns Reviewed-by: --- src/libs/qtcreatorcdbext/pytype.cpp | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/libs/qtcreatorcdbext/pytype.cpp b/src/libs/qtcreatorcdbext/pytype.cpp index 9345c1d91af..479895bbcd9 100644 --- a/src/libs/qtcreatorcdbext/pytype.cpp +++ b/src/libs/qtcreatorcdbext/pytype.cpp @@ -49,10 +49,24 @@ static bool isType(const std::string &typeName, const std::vector & static bool isIntegralType(const std::string &typeName) { - static const std::vector integralTypes({"bool", - "char", "unsigned char", "char16_t", "char32_t", "wchar_t", - "short", "unsigned short", "int", "unsigned int", - "long", "unsigned long", "int64", "unsigned int64", "__int64", "unsigned __int64"}); + static const std::vector integralTypes( + {"bool", + "char", + "unsigned char", + "char16_t", + "char32_t", + "wchar_t", + "short", + "unsigned short", + "int", + "unsigned int", + "long", + "unsigned long", + "int64", + "unsigned int64", + "__int64", + "unsigned __int64", + "HRESULT"}); return isType(typeName, integralTypes); } From 4bebb11578b3aa8fbfdf9b9652bf738ebaacd404 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 20 Mar 2024 12:57:21 +0100 Subject: [PATCH 0084/1060] Doc: add infos to the generated requirements.txt for python projects Change-Id: I70b0e0bdb3b026bf082294c66659d901a30954f3 Reviewed-by: Leena Miettinen --- .../python/creator-tutorial-python-application-qt-widgets.qdoc | 3 ++- .../python/creator-tutorial-python-application-qtquick.qdoc | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc b/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc index d1da60de273..fc03f6f6ad6 100644 --- a/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc +++ b/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc @@ -69,7 +69,8 @@ project. \li \c {mywidget.py}, which has some boilerplate code for a class. \li \c {reguirements.txt}, which stores the PySide version of the - generated code. + generated code. You can use this file to install the required PySide version + using pip. \endlist \section1 Adding Qt Widgets Imports diff --git a/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc b/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc index c6ecaace78e..bce58c15507 100644 --- a/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc +++ b/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc @@ -59,7 +59,8 @@ \li \c {main.py}, which has some boilerplate code. \li \c {main.qml}, which imports Qt Quick controls. \li \c {reguirements.txt}, which stores the PySide version of the - generated code. + generated code. You can use this file to install the required PySide version + using pip. \endlist \section1 Adding Qt Quick Imports From 550862ce51e7b4cffd54d22ba417a9913b7558ea Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 20 Mar 2024 12:53:11 +0100 Subject: [PATCH 0085/1060] Doc: Expand description of the python kit selector Mention that a virtual environment is created by default and that the global interpreter can be accessed under the details of the kit. Change-Id: I276f1a594b0726914925b2b565eace43182342f4 Reviewed-by: Leena Miettinen --- .../creator-tutorial-python-application-qt-widgets.qdoc | 6 ++++-- .../python/creator-tutorial-python-application-qtquick.qdoc | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc b/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc index fc03f6f6ad6..9c96d3c73b7 100644 --- a/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc +++ b/doc/qtcreator/src/python/creator-tutorial-python-application-qt-widgets.qdoc @@ -54,8 +54,10 @@ \li Select \uicontrol{Next} or \uicontrol Continue to open the \uicontrol {Kit Selection} dialog. \image qtcreator-new-project-qt-for-python-kit-selection.webp {Selecting a kit for a Python project} - \li Select Qt for Python kits for building, deploying, and running the - project. + \li Select Python kits for building, deploying, and running the + project. By default, this creates a virtual environment for the project inside + the source directory. To use the global interpreter, select the build configuration + with the same name as the Python of the kit in \uicontrol{Details}. \li Select \uicontrol{Next} or \uicontrol Continue. \li Review the project settings, and select \uicontrol {Finish} (on Windows and Linux) or \uicontrol Done (on \macos) to create the diff --git a/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc b/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc index bce58c15507..f8570d1bbad 100644 --- a/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc +++ b/doc/qtcreator/src/python/creator-tutorial-python-application-qtquick.qdoc @@ -44,8 +44,10 @@ \li Select \uicontrol{Next} or \uicontrol Continue to open the \uicontrol {Kit Selection} dialog. \image qtcreator-new-project-qt-for-python-kit-selection.webp {Selecting a kit for a Python project} - \li Select Qt for Python kits for building, deploying, and running the - project. + \li Select Python kits for building, deploying, and running the + project. By default, this creates a virtual environment for the project inside + the source directory. To use the global interpreter, select the build configuration + with the same name as the Python of the kit in \uicontrol{Details}. \li Review the project settings, and select \uicontrol {Finish} (on Windows and Linux) or \uicontrol Done (on \macos) to create the project. From a2fa009b8b6b345afbaaaf2e7ef988d4f7b97aa1 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 21 Mar 2024 12:25:12 +0100 Subject: [PATCH 0086/1060] Core: Set default reload behavior to ReloadUnmodified Change-Id: I5b3e8d5371d1f9e571103a0578674e3646627e80 Reviewed-by: Eike Ziller --- src/plugins/coreplugin/systemsettings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/coreplugin/systemsettings.cpp b/src/plugins/coreplugin/systemsettings.cpp index d06d14f8dab..37a2075e1b4 100644 --- a/src/plugins/coreplugin/systemsettings.cpp +++ b/src/plugins/coreplugin/systemsettings.cpp @@ -129,7 +129,7 @@ SystemSettings::SystemSettings() reloadSetting.addOption(Tr::tr("Always Ask")); reloadSetting.addOption(Tr::tr("Reload All Unchanged Editors")); reloadSetting.addOption(Tr::tr("Ignore Modifications")); - reloadSetting.setDefaultValue(IDocument::AlwaysAsk); + reloadSetting.setDefaultValue(IDocument::ReloadUnmodified); reloadSetting.setLabelText(Tr::tr("When files are externally modified:")); askBeforeExit.setSettingsKey("AskBeforeExit"); From 43f760cf3f8b7487846531d6a6912e71513198cc Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Thu, 21 Mar 2024 16:08:42 +0100 Subject: [PATCH 0087/1060] Android: Introduce constant "firstQtWithAndroidDeployQt" Replace a couple of QVersionNumber(5, 4, 0) with it. Change-Id: Iebc39a534500992c8eb4d72d34d71fe621b8c7c0 Reviewed-by: hjk --- src/plugins/android/androidbuildapkstep.cpp | 2 +- src/plugins/android/androiddeployqtstep.cpp | 4 ++-- src/plugins/android/androidmanager.h | 3 +++ src/plugins/android/createandroidmanifestwizard.cpp | 4 ++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/plugins/android/androidbuildapkstep.cpp b/src/plugins/android/androidbuildapkstep.cpp index 940b3732981..317b72722b5 100644 --- a/src/plugins/android/androidbuildapkstep.cpp +++ b/src/plugins/android/androidbuildapkstep.cpp @@ -495,7 +495,7 @@ bool AndroidBuildApkStep::init() return false; } - if (version->qtVersion() < QVersionNumber(5, 4, 0)) { + if (version->qtVersion() < AndroidManager::firstQtWithAndroidDeployQt) { const QString error = Tr::tr("The minimum Qt version required for Gradle build to work is %1. " "It is recommended to install the latest Qt version.") .arg("5.4.0"); diff --git a/src/plugins/android/androiddeployqtstep.cpp b/src/plugins/android/androiddeployqtstep.cpp index 6e520d3721b..459bdb6eead 100644 --- a/src/plugins/android/androiddeployqtstep.cpp +++ b/src/plugins/android/androiddeployqtstep.cpp @@ -149,7 +149,7 @@ AndroidDeployQtStep::AndroidDeployQtStep(BuildStepList *parent, Id id) m_uninstallPreviousPackage.setValue(false); const QtSupport::QtVersion * const qt = QtSupport::QtKitAspect::qtVersion(kit()); - const bool forced = qt && qt->qtVersion() < QVersionNumber(5, 4, 0); + const bool forced = qt && qt->qtVersion() < AndroidManager::firstQtWithAndroidDeployQt; if (forced) { m_uninstallPreviousPackage.setValue(true); m_uninstallPreviousPackage.setEnabled(false); @@ -277,7 +277,7 @@ bool AndroidDeployQtStep::init() if (m_uninstallPreviousPackageRun) m_manifestName = AndroidManager::manifestPath(target()); - m_useAndroiddeployqt = version->qtVersion() >= QVersionNumber(5, 4, 0); + m_useAndroiddeployqt = version->qtVersion() >= AndroidManager::firstQtWithAndroidDeployQt; if (m_useAndroiddeployqt) { const QString buildKey = target()->activeBuildKey(); const ProjectNode *node = target()->project()->findNodeForBuildKey(buildKey); diff --git a/src/plugins/android/androidmanager.h b/src/plugins/android/androidmanager.h index 7a141b58ce5..f3b9302d13c 100644 --- a/src/plugins/android/androidmanager.h +++ b/src/plugins/android/androidmanager.h @@ -35,6 +35,9 @@ public: namespace AndroidManager { +// With Qt 5.4, a couple of android tooling features moved over from Qt Creator to Qt. +constexpr auto firstQtWithAndroidDeployQt = {5, 4, 0}; + QString packageName(const ProjectExplorer::Target *target); QString packageName(const Utils::FilePath &manifestFile); QString activityName(const ProjectExplorer::Target *target); diff --git a/src/plugins/android/createandroidmanifestwizard.cpp b/src/plugins/android/createandroidmanifestwizard.cpp index 7c334476a21..8f50666419a 100644 --- a/src/plugins/android/createandroidmanifestwizard.cpp +++ b/src/plugins/android/createandroidmanifestwizard.cpp @@ -228,7 +228,7 @@ CreateAndroidManifestWizard::CreateAndroidManifestWizard(BuildSystem *buildSyste const QList buildTargets = buildSystem->applicationTargets(); QtSupport::QtVersion *version = QtSupport::QtKitAspect::qtVersion(buildSystem->kit()); - m_copyGradle = version && version->qtVersion() >= QVersionNumber(5, 4, 0); + m_copyGradle = version && version->qtVersion() >= AndroidManager::firstQtWithAndroidDeployQt; if (buildTargets.isEmpty()) { // oh uhm can't create anything @@ -277,7 +277,7 @@ void CreateAndroidManifestWizard::createAndroidTemplateFiles() QtSupport::QtVersion *version = QtSupport::QtKitAspect::qtVersion(target->kit()); if (!version) return; - if (version->qtVersion() < QVersionNumber(5, 4, 0)) { + if (version->qtVersion() < AndroidManager::firstQtWithAndroidDeployQt) { FileUtils::copyRecursively(version->prefix() / "src/android/java/AndroidManifest.xml", m_directory / "AndroidManifest.xml", nullptr, From e57e0b0bfacea51275332feae60614a53a95591b Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Tue, 19 Mar 2024 20:17:13 +0100 Subject: [PATCH 0088/1060] Terminal: Fix terminal resizing on Windows using ConPty The official ConPty API doesn't give the ability to forward "-- resizeQuirk" to "conhost.exe". Fixing this involved taking parts from the WinConPty implementation (https://github.com/microsoft/terminal/tree/main/src/ winconpty) and porting them to work inside ptyqt. Fixes: QTCREATORBUG-30007 Fixes: QTCREATORBUG-30558 Change-Id: I45e81fa167c88a85b44958eade0d85f7680e8075 Reviewed-by: Cristian Adam Reviewed-by: Marcus Tillmanns --- qt_attributions.json | 13 + src/libs/3rdparty/libptyqt/LICENSE-CONPTY | 21 + src/libs/3rdparty/libptyqt/conptyprocess.cpp | 785 ++++++++++++++++++- 3 files changed, 794 insertions(+), 25 deletions(-) create mode 100644 src/libs/3rdparty/libptyqt/LICENSE-CONPTY diff --git a/qt_attributions.json b/qt_attributions.json index 0a9e762dae1..65a92cecc88 100644 --- a/qt_attributions.json +++ b/qt_attributions.json @@ -453,6 +453,19 @@ "LicenseFile": "src/libs/3rdparty/libptyqt/LICENSE", "Copyright": "Copyright (c) 2019 Vitaly Petrov" }, + { + "Id": "ptyqt-conpty", + "Name": "Pty-Qt/ConPty", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for the integrated terminal.", + "Path": "src/libs/3rdparty/libptyqt", + "Description": "Major parts of conptyprocess.cpp have been ported from microsofts terminal source code and integrated into ptyqt's class.", + "Homepage": "https://github.com/microsoft/terminal", + "License": "MIT License", + "LicenseFile": "src/libs/3rdparty/libptyqt/LICENSE-CONPTY", + "Copyright": "Copyright (c) Microsoft Corporation" + }, { "Id": "libvterm", "Name": "libvterm", diff --git a/src/libs/3rdparty/libptyqt/LICENSE-CONPTY b/src/libs/3rdparty/libptyqt/LICENSE-CONPTY new file mode 100644 index 00000000000..8cb179cdb69 --- /dev/null +++ b/src/libs/3rdparty/libptyqt/LICENSE-CONPTY @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/libs/3rdparty/libptyqt/conptyprocess.cpp b/src/libs/3rdparty/libptyqt/conptyprocess.cpp index 6464dbeb347..94bb53b5832 100644 --- a/src/libs/3rdparty/libptyqt/conptyprocess.cpp +++ b/src/libs/3rdparty/libptyqt/conptyprocess.cpp @@ -10,8 +10,740 @@ #include +#ifdef QTCREATOR_PCH_H +#ifndef IN +#define IN +#endif +#ifndef OUT +#define OUT +#endif +#endif + +#include + #define READ_INTERVAL_MSEC 500 +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 + +//////////////////////////////////////////////////////////////////////////////////////// +/// Ported from wil/result_macros.h + +#define FAILED_NTSTATUS(status) (((NTSTATUS)(status)) < 0) +#define SUCCEEDED_NTSTATUS(status) (((NTSTATUS)(status)) >= 0) + +#define RETURN_IF_NTSTATUS_FAILED(call) if(FAILED_NTSTATUS(call)) return E_FAIL; +#define RETURN_IF_WIN32_BOOL_FALSE(call) if((call) == FALSE) return E_FAIL; +#define RETURN_IF_NULL_ALLOC(call) if((call) == nullptr) return E_OUTOFMEMORY; +#define RETURN_IF_FAILED(call) {HRESULT hr = (call); if(hr != S_OK)return hr; } + +//! Set zero or more bitflags specified by `flags` in the variable `var`. +#define WI_SetAllFlags(var, flags) ((var) |= (flags)) +//! Set a single compile-time constant `flag` in the variable `var`. +#define WI_SetFlag(var, flag) WI_SetAllFlags(var,flag) + +//////////////////////////////////////////////////////////////////////////////////////// +/// Ported from wil +class unique_hmodule : public std::unique_ptr, decltype(&FreeLibrary)> +{ +public: + unique_hmodule() : std::unique_ptr, decltype(&FreeLibrary)>(nullptr, FreeLibrary) {} + unique_hmodule(HMODULE module) : std::unique_ptr, decltype(&FreeLibrary)>(module, FreeLibrary) {} +}; + +class unique_handle : public std::unique_ptr, decltype(&CloseHandle)> +{ +public: + unique_handle() : std::unique_ptr, decltype(&CloseHandle)>(nullptr, CloseHandle) {} + unique_handle(HANDLE module) : std::unique_ptr, decltype(&CloseHandle)>(module, CloseHandle) {} + + + class AddressOf { + public: + AddressOf(unique_handle &h) : m_h(h) {} + ~AddressOf() { + m_h.reset(m_dest); + } + + operator PHANDLE() {return &m_dest;} + + HANDLE m_dest{INVALID_HANDLE_VALUE}; + unique_handle &m_h; + }; + + AddressOf addressof() { + return AddressOf(*this); + } +}; + +class unique_process_information : public PROCESS_INFORMATION +{ +public: + unique_process_information() { + hProcess = 0; + hThread = 0; + dwProcessId = 0; + dwThreadId = 0; + } + ~unique_process_information() { + if (hProcess) + { + CloseHandle(hProcess); + } + + if (hThread) + { + CloseHandle(hThread); + } + } + + PROCESS_INFORMATION* addressof() { + return this; + } +}; + +template +class on_scope_exit { +public: + TLambda m_func; + bool m_call{true}; + on_scope_exit(TLambda &&func) : m_func(std::move(func)) {} + ~on_scope_exit() {if(m_call)m_func();} + + void release() {m_call = false;} +}; + +template +[[nodiscard]] inline auto scope_exit(TLambda&& lambda) noexcept +{ + return on_scope_exit(std::forward(lambda)); +} + +//////////////////////////////////////////////////////////////////////////////////////// + + + +class WinNTControl +{ +public: + [[nodiscard]] static NTSTATUS NtOpenFile(_Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG ShareAccess, + _In_ ULONG OpenOptions); + +private: + WinNTControl(); + + WinNTControl(WinNTControl const&) = delete; + void operator=(WinNTControl const&) = delete; + + static WinNTControl& GetInstance(); + + unique_hmodule const _NtDllDll; + + typedef NTSTATUS(NTAPI* PfnNtOpenFile)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, ULONG, ULONG); + PfnNtOpenFile const _NtOpenFile; +}; + +WinNTControl::WinNTControl() : + // NOTE: Use LoadLibraryExW with LOAD_LIBRARY_SEARCH_SYSTEM32 flag below to avoid unneeded directory traversal. + // This has triggered CPG boot IO warnings in the past. + _NtDllDll(/*THROW_LAST_ERROR_IF_NULL*/(LoadLibraryExW(L"ntdll.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32))), + _NtOpenFile(reinterpret_cast(/*THROW_LAST_ERROR_IF_NULL*/(GetProcAddress(_NtDllDll.get(), "NtOpenFile")))) +{ +} + +// Routine Description: +// - Provides the singleton pattern for WinNT control. Stores the single instance and returns it. +// Arguments: +// - +// Return Value: +// - Reference to the single instance of NTDLL.dll wrapped methods. +WinNTControl& WinNTControl::GetInstance() +{ + static WinNTControl Instance; + return Instance; +} + +// Routine Description: +// - Provides access to the NtOpenFile method documented at: +// https://msdn.microsoft.com/en-us/library/bb432381(v=vs.85).aspx +// Arguments: +// - See definitions at MSDN +// Return Value: +// - See definitions at MSDN +[[nodiscard]] NTSTATUS WinNTControl::NtOpenFile(_Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG ShareAccess, + _In_ ULONG OpenOptions) +{ + return GetInstance()._NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions); +} + +namespace DeviceHandle { + +/*++ +Routine Description: +- This routine opens a handle to the console driver. + +Arguments: +- Handle - Receives the handle. +- DeviceName - Supplies the name to be used to open the console driver. +- DesiredAccess - Supplies the desired access mask. +- Parent - Optionally supplies the parent object. +- Inheritable - Supplies a boolean indicating if the new handle is to be made inheritable. +- OpenOptions - Supplies the open options to be passed to NtOpenFile. A common + option for clients is FILE_SYNCHRONOUS_IO_NONALERT, to make the handle + synchronous. + +Return Value: +- NTSTATUS indicating if the handle was successfully created. +--*/ +[[nodiscard]] NTSTATUS +_CreateHandle( + _Out_ PHANDLE Handle, + _In_ PCWSTR DeviceName, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ HANDLE Parent, + _In_ BOOLEAN Inheritable, + _In_ ULONG OpenOptions) + +{ + ULONG Flags = OBJ_CASE_INSENSITIVE; + + if (Inheritable) + { + WI_SetFlag(Flags, OBJ_INHERIT); + } + + UNICODE_STRING Name; +#pragma warning(suppress : 26492) // const_cast is prohibited, but we can't avoid it for filling UNICODE_STRING. + Name.Buffer = const_cast(DeviceName); + //Name.Length = gsl::narrow_cast((wcslen(DeviceName) * sizeof(wchar_t))); + Name.Length = static_cast((wcslen(DeviceName) * sizeof(wchar_t))); + Name.MaximumLength = Name.Length + sizeof(wchar_t); + + OBJECT_ATTRIBUTES ObjectAttributes; +#pragma warning(suppress : 26477) // The QOS part of this macro in the define is 0. Can't fix that. + InitializeObjectAttributes(&ObjectAttributes, + &Name, + Flags, + Parent, + nullptr); + + IO_STATUS_BLOCK IoStatus; + return WinNTControl::NtOpenFile(Handle, + DesiredAccess, + &ObjectAttributes, + &IoStatus, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + OpenOptions); +} + +/*++ +Routine Description: +- This routine creates a handle to an input or output client of the given + server. No control io is sent to the server as this request must be coming + from the server itself. + +Arguments: +- Handle - Receives a handle to the new client. +- ServerHandle - Supplies a handle to the server to which to attach the + newly created client. +- Name - Supplies the name of the client object. +- Inheritable - Supplies a flag indicating if the handle must be inheritable. + +Return Value: +- NTSTATUS indicating if the client was successfully created. +--*/ +[[nodiscard]] NTSTATUS +CreateClientHandle( + _Out_ PHANDLE Handle, + _In_ HANDLE ServerHandle, + _In_ PCWSTR Name, + _In_ BOOLEAN Inheritable) +{ + return _CreateHandle(Handle, + Name, + GENERIC_WRITE | GENERIC_READ | SYNCHRONIZE, + ServerHandle, + Inheritable, + FILE_SYNCHRONOUS_IO_NONALERT); +} + +/*++ +Routine Description: +- This routine creates a new server on the driver and returns a handle to it. + +Arguments: +- Handle - Receives a handle to the new server. +- Inheritable - Supplies a flag indicating if the handle must be inheritable. + +Return Value: +- NTSTATUS indicating if the console was successfully created. +--*/ +[[nodiscard]] NTSTATUS +CreateServerHandle( + _Out_ PHANDLE Handle, + _In_ BOOLEAN Inheritable) +{ + return _CreateHandle(Handle, + L"\\Device\\ConDrv\\Server", + GENERIC_ALL, + nullptr, + Inheritable, + 0); +} + + +} // namespace DeviceHandle + +[[nodiscard]] static inline NTSTATUS CreateClientHandle(PHANDLE Handle, HANDLE ServerHandle, PCWSTR Name, BOOLEAN Inheritable) +{ + return DeviceHandle::CreateClientHandle(Handle, ServerHandle, Name, Inheritable); +} + +[[nodiscard]] static inline NTSTATUS CreateServerHandle(PHANDLE Handle, BOOLEAN Inheritable) +{ + return DeviceHandle::CreateServerHandle(Handle, Inheritable); +} + +typedef struct _PseudoConsole +{ + HANDLE hSignal; + HANDLE hPtyReference; + HANDLE hConPtyProcess; +} PseudoConsole; + +// Signals +// These are not defined publicly, but are used for controlling the conpty via +// the signal pipe. +#define PTY_SIGNAL_CLEAR_WINDOW (2u) +#define PTY_SIGNAL_RESIZE_WINDOW (8u) + +// CreatePseudoConsole Flags +// The other flag (PSEUDOCONSOLE_INHERIT_CURSOR) is actually defined in consoleapi.h in the OS repo +#ifndef PSEUDOCONSOLE_INHERIT_CURSOR +#define PSEUDOCONSOLE_INHERIT_CURSOR (0x1) +#endif +#define PSEUDOCONSOLE_RESIZE_QUIRK (0x2) +#define PSEUDOCONSOLE_WIN32_INPUT_MODE (0x4) + +static QString qSystemDirectory() +{ + static const QString result = []() -> QString { + QVarLengthArray fullPath = {}; + UINT retLen = ::GetSystemDirectoryW(fullPath.data(), MAX_PATH); + if (retLen > MAX_PATH) { + fullPath.resize(retLen); + retLen = ::GetSystemDirectoryW(fullPath.data(), retLen); + } + // in some rare cases retLen might be 0 + return QString::fromWCharArray(fullPath.constData(), int(retLen)); + }(); + return result; +} + +// Function Description: +// - Returns the path to conhost.exe as a process heap string. +static QString _InboxConsoleHostPath() +{ + return QString("\\\\?\\%1\\conhost.exe").arg(qSystemDirectory()); +} + +// Function Description: +// - Returns the path to either conhost.exe or the side-by-side OpenConsole, depending on whether this +// module is building with Windows and OpenConsole could be found. +// Return Value: +// - A pointer to permanent storage containing the path to the console host. +static const wchar_t* _ConsoleHostPath() +{ + // Use the magic of magic statics to only calculate this once. + static QString consoleHostPath = _InboxConsoleHostPath(); + return reinterpret_cast(consoleHostPath.utf16()); +} + +static bool _HandleIsValid(HANDLE h) noexcept +{ + return (h != INVALID_HANDLE_VALUE) && (h != nullptr); +} + + + +HRESULT _CreatePseudoConsole(const HANDLE hToken, + const COORD size, + const HANDLE hInput, + const HANDLE hOutput, + const DWORD dwFlags, + _Inout_ PseudoConsole* pPty) +{ + if (pPty == nullptr) + { + return E_INVALIDARG; + } + if (size.X == 0 || size.Y == 0) + { + return E_INVALIDARG; + } + + unique_handle serverHandle; + RETURN_IF_NTSTATUS_FAILED(CreateServerHandle(serverHandle.addressof(), TRUE)); + + unique_handle signalPipeConhostSide; + unique_handle signalPipeOurSide; + + SECURITY_ATTRIBUTES sa; + sa.nLength = sizeof(sa); + // Mark inheritable for signal handle when creating. It'll have the same value on the other side. + sa.bInheritHandle = FALSE; + sa.lpSecurityDescriptor = nullptr; + + RETURN_IF_WIN32_BOOL_FALSE(CreatePipe(signalPipeConhostSide.addressof(), signalPipeOurSide.addressof(), &sa, 0)); + RETURN_IF_WIN32_BOOL_FALSE(SetHandleInformation(signalPipeConhostSide.get(), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)); + + // GH4061: Ensure that the path to executable in the format is escaped so C:\Program.exe cannot collide with C:\Program Files + const wchar_t* pwszFormat = L"\"%s\" --headless %s%s%s--width %hu --height %hu --signal 0x%x --server 0x%x"; + // This is plenty of space to hold the formatted string + wchar_t cmd[MAX_PATH]{}; + const BOOL bInheritCursor = (dwFlags & PSEUDOCONSOLE_INHERIT_CURSOR) == PSEUDOCONSOLE_INHERIT_CURSOR; + const BOOL bResizeQuirk = (dwFlags & PSEUDOCONSOLE_RESIZE_QUIRK) == PSEUDOCONSOLE_RESIZE_QUIRK; + const BOOL bWin32InputMode = (dwFlags & PSEUDOCONSOLE_WIN32_INPUT_MODE) == PSEUDOCONSOLE_WIN32_INPUT_MODE; + swprintf_s(cmd, + MAX_PATH, + pwszFormat, + _ConsoleHostPath(), + bInheritCursor ? L"--inheritcursor " : L"", + bWin32InputMode ? L"--win32input " : L"", + bResizeQuirk ? L"--resizeQuirk " : L"", + size.X, + size.Y, + signalPipeConhostSide.get(), + serverHandle.get()); + + STARTUPINFOEXW siEx{ 0 }; + siEx.StartupInfo.cb = sizeof(STARTUPINFOEXW); + siEx.StartupInfo.hStdInput = hInput; + siEx.StartupInfo.hStdOutput = hOutput; + siEx.StartupInfo.hStdError = hOutput; + siEx.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; + + // Only pass the handles we actually want the conhost to know about to it: + const size_t INHERITED_HANDLES_COUNT = 4; + HANDLE inheritedHandles[INHERITED_HANDLES_COUNT]; + inheritedHandles[0] = serverHandle.get(); + inheritedHandles[1] = hInput; + inheritedHandles[2] = hOutput; + inheritedHandles[3] = signalPipeConhostSide.get(); + + // Get the size of the attribute list. We need one attribute, the handle list. + SIZE_T listSize = 0; + InitializeProcThreadAttributeList(nullptr, 1, 0, &listSize); + + // I have to use a HeapAlloc here because kernelbase can't link new[] or delete[] + PPROC_THREAD_ATTRIBUTE_LIST attrList = static_cast(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, listSize)); + RETURN_IF_NULL_ALLOC(attrList); + auto attrListDelete = scope_exit([&]() noexcept { + HeapFree(GetProcessHeap(), 0, attrList); + }); + + siEx.lpAttributeList = attrList; + RETURN_IF_WIN32_BOOL_FALSE(InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, &listSize)); + // Set cleanup data for ProcThreadAttributeList when successful. + auto cleanupProcThreadAttribute = scope_exit([&]() noexcept { + DeleteProcThreadAttributeList(siEx.lpAttributeList); + }); + RETURN_IF_WIN32_BOOL_FALSE(UpdateProcThreadAttribute(siEx.lpAttributeList, + 0, + PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + inheritedHandles, + (INHERITED_HANDLES_COUNT * sizeof(HANDLE)), + nullptr, + nullptr)); + unique_process_information pi; + { // wow64 disabled filesystem redirection scope + if (hToken == INVALID_HANDLE_VALUE || hToken == nullptr) + { + // Call create process + RETURN_IF_WIN32_BOOL_FALSE(CreateProcessW(_ConsoleHostPath(), + cmd, + nullptr, + nullptr, + TRUE, + EXTENDED_STARTUPINFO_PRESENT, + nullptr, + nullptr, + &siEx.StartupInfo, + pi.addressof())); + } + else + { + // Call create process + RETURN_IF_WIN32_BOOL_FALSE(CreateProcessAsUserW(hToken, + _ConsoleHostPath(), + cmd, + nullptr, + nullptr, + TRUE, + EXTENDED_STARTUPINFO_PRESENT, + nullptr, + nullptr, + &siEx.StartupInfo, + pi.addressof())); + } + } + + // Move the process handle out of the PROCESS_INFORMATION into out Pseudoconsole + pPty->hConPtyProcess = pi.hProcess; + pi.hProcess = nullptr; + + RETURN_IF_NTSTATUS_FAILED(CreateClientHandle(&pPty->hPtyReference, + serverHandle.get(), + L"\\Reference", + FALSE)); + + pPty->hSignal = signalPipeOurSide.release(); + + return S_OK; +} + +// Function Description: +// - Resizes the conpty +// Arguments: +// - hSignal: A signal pipe as returned by CreateConPty. +// - size: The new dimensions of the conpty, in characters. +// Return Value: +// - S_OK if the call succeeded, else an appropriate HRESULT for failing to +// write the resize message to the pty. +HRESULT _ResizePseudoConsole(_In_ const PseudoConsole* const pPty, _In_ const COORD size) +{ + if (pPty == nullptr || size.X < 0 || size.Y < 0) + { + return E_INVALIDARG; + } + + unsigned short signalPacket[3]; + signalPacket[0] = PTY_SIGNAL_RESIZE_WINDOW; + signalPacket[1] = size.X; + signalPacket[2] = size.Y; + + const BOOL fSuccess = WriteFile(pPty->hSignal, signalPacket, sizeof(signalPacket), nullptr, nullptr); + return fSuccess ? S_OK : HRESULT_FROM_WIN32(GetLastError()); +} + +// Function Description: +// - Clears the conpty +// Arguments: +// - hSignal: A signal pipe as returned by CreateConPty. +// Return Value: +// - S_OK if the call succeeded, else an appropriate HRESULT for failing to +// write the clear message to the pty. +HRESULT _ClearPseudoConsole(_In_ const PseudoConsole* const pPty) +{ + if (pPty == nullptr) + { + return E_INVALIDARG; + } + + unsigned short signalPacket[1]; + signalPacket[0] = PTY_SIGNAL_CLEAR_WINDOW; + + const BOOL fSuccess = WriteFile(pPty->hSignal, signalPacket, sizeof(signalPacket), nullptr, nullptr); + return fSuccess ? S_OK : HRESULT_FROM_WIN32(GetLastError()); +} + +// Function Description: +// - This closes each of the members of a PseudoConsole. It does not free the +// data associated with the PseudoConsole. This is helpful for testing, +// where we might stack allocate a PseudoConsole (instead of getting a +// HPCON via the API). +// Arguments: +// - pPty: A pointer to a PseudoConsole struct. +// Return Value: +// - +void _ClosePseudoConsoleMembers(_In_ PseudoConsole* pPty) +{ + if (pPty != nullptr) + { + // See MSFT:19918626 + // First break the signal pipe - this will trigger conhost to tear itself down + if (_HandleIsValid(pPty->hSignal)) + { + CloseHandle(pPty->hSignal); + pPty->hSignal = nullptr; + } + // Then, wait on the conhost process before killing it. + // We do this to make sure the conhost finishes flushing any output it + // has yet to send before we hard kill it. + if (_HandleIsValid(pPty->hConPtyProcess)) + { + // If the conhost is already dead, then that's fine. Presumably + // it's finished flushing it's output already. + DWORD dwExit = 0; + // If GetExitCodeProcess failed, it's likely conhost is already dead + // If so, skip waiting regardless of whatever error + // GetExitCodeProcess returned. + // We'll just go straight to killing conhost. + if (GetExitCodeProcess(pPty->hConPtyProcess, &dwExit) && dwExit == STILL_ACTIVE) + { + WaitForSingleObject(pPty->hConPtyProcess, INFINITE); + } + + TerminateProcess(pPty->hConPtyProcess, 0); + CloseHandle(pPty->hConPtyProcess); + pPty->hConPtyProcess = nullptr; + } + // Then take care of the reference handle. + // TODO GH#1810: Closing the reference handle late leaves conhost thinking + // that we have an outstanding connected client. + if (_HandleIsValid(pPty->hPtyReference)) + { + CloseHandle(pPty->hPtyReference); + pPty->hPtyReference = nullptr; + } + } +} + +// Function Description: +// - This closes each of the members of a PseudoConsole, and HeapFree's the +// memory allocated to it. This should be used to cleanup any +// PseudoConsoles that were created with CreatePseudoConsole. +// Arguments: +// - pPty: A pointer to a PseudoConsole struct. +// Return Value: +// - +VOID _ClosePseudoConsole(_In_ PseudoConsole* pPty) +{ + if (pPty != nullptr) + { + _ClosePseudoConsoleMembers(pPty); + HeapFree(GetProcessHeap(), 0, pPty); + } +} + +extern "C" HRESULT ConptyCreatePseudoConsoleAsUser(_In_ HANDLE hToken, + _In_ COORD size, + _In_ HANDLE hInput, + _In_ HANDLE hOutput, + _In_ DWORD dwFlags, + _Out_ HPCON* phPC) +{ + if (phPC == nullptr) + { + return E_INVALIDARG; + } + *phPC = nullptr; + if ((!_HandleIsValid(hInput)) && (!_HandleIsValid(hOutput))) + { + return E_INVALIDARG; + } + + PseudoConsole* pPty = (PseudoConsole*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PseudoConsole)); + RETURN_IF_NULL_ALLOC(pPty); + auto cleanupPty = scope_exit([&]() noexcept { + _ClosePseudoConsole(pPty); + }); + + unique_handle duplicatedInput; + unique_handle duplicatedOutput; + RETURN_IF_WIN32_BOOL_FALSE(DuplicateHandle(GetCurrentProcess(), hInput, GetCurrentProcess(), duplicatedInput.addressof(), 0, TRUE, DUPLICATE_SAME_ACCESS)); + RETURN_IF_WIN32_BOOL_FALSE(DuplicateHandle(GetCurrentProcess(), hOutput, GetCurrentProcess(), duplicatedOutput.addressof(), 0, TRUE, DUPLICATE_SAME_ACCESS)); + + RETURN_IF_FAILED(_CreatePseudoConsole(hToken, size, duplicatedInput.get(), duplicatedOutput.get(), dwFlags, pPty)); + + *phPC = (HPCON)pPty; + cleanupPty.release(); + + return S_OK; +} + +// These functions are defined in the console l1 apiset, which is generated from +// the consoleapi.apx file in minkernel\apiset\libs\Console. + +// Function Description: +// Creates a "Pseudo-console" (conpty) with dimensions (in characters) +// provided by the `size` parameter. The caller should provide two handles: +// - `hInput` is used for writing input to the pty, encoded as UTF-8 and VT sequences. +// - `hOutput` is used for reading the output of the pty, encoded as UTF-8 and VT sequences. +// Once the call completes, `phPty` will receive a token value to identify this +// conpty object. This value should be used in conjunction with the other +// Pseudoconsole API's. +// `dwFlags` is used to specify optional behavior to the created pseudoconsole. +// The flags can be combinations of the following values: +// INHERIT_CURSOR: This will cause the created conpty to attempt to inherit the +// cursor position of the parent terminal application. This can be useful +// for applications like `ssh`, where ssh (currently running in a terminal) +// might want to create a pseudoterminal session for an child application +// and the child inherit the cursor position of ssh. +// The created conpty will immediately emit a "Device Status Request" VT +// sequence to hOutput, that should be replied to on hInput in the format +// "\x1b[;R", where `` is the row and `` is the column of the +// cursor position. +// This requires a cooperating terminal application - if a caller does not +// reply to this message, the conpty will not process any input until it +// does. Most *nix terminals and the Windows Console (after Windows 10 +// Anniversary Update) will be able to handle such a message. + +extern "C" HRESULT WINAPI ConptyCreatePseudoConsole(_In_ COORD size, + _In_ HANDLE hInput, + _In_ HANDLE hOutput, + _In_ DWORD dwFlags, + _Out_ HPCON* phPC) +{ + return ConptyCreatePseudoConsoleAsUser(INVALID_HANDLE_VALUE, size, hInput, hOutput, dwFlags, phPC); +} + +// Function Description: +// Resizes the given conpty to the specified size, in characters. +extern "C" HRESULT WINAPI ConptyResizePseudoConsole(_In_ HPCON hPC, _In_ COORD size) +{ + const PseudoConsole* const pPty = (PseudoConsole*)hPC; + HRESULT hr = pPty == nullptr ? E_INVALIDARG : S_OK; + if (SUCCEEDED(hr)) + { + hr = _ResizePseudoConsole(pPty, size); + } + return hr; +} + +// Function Description: +// - Clear the contents of the conpty buffer, leaving the cursor row at the top +// of the viewport. +// - This is used exclusively by ConPTY to support GH#1193, GH#1882. This allows +// a terminal to clear the contents of the ConPTY buffer, which is important +// if the user would like to be able to clear the terminal-side buffer. +extern "C" HRESULT WINAPI ConptyClearPseudoConsole(_In_ HPCON hPC) +{ + const PseudoConsole* const pPty = (PseudoConsole*)hPC; + HRESULT hr = pPty == nullptr ? E_INVALIDARG : S_OK; + if (SUCCEEDED(hr)) + { + hr = _ClearPseudoConsole(pPty); + } + return hr; +} + +// Function Description: +// Closes the conpty and all associated state. +// Client applications attached to the conpty will also behave as though the +// console window they were running in was closed. +// This can fail if the conhost hosting the pseudoconsole failed to be +// terminated, or if the pseudoconsole was already terminated. +extern "C" VOID WINAPI ConptyClosePseudoConsole(_In_ HPCON hPC) +{ + PseudoConsole* const pPty = (PseudoConsole*)hPC; + if (pPty != nullptr) + { + _ClosePseudoConsole(pPty); + } +} + + //ConPTY is available only on Windows 10 released after 1903 (19H1) Windows release class WindowsContext { @@ -38,30 +770,9 @@ public: bool init() { - //already initialized - if (createPseudoConsole) - return true; - - //try to load symbols from library - //if it fails -> we can't use ConPty API - HANDLE kernel32Handle = LoadLibraryExW(L"kernel32.dll", 0, 0); - - if (kernel32Handle != nullptr) - { - createPseudoConsole = (CreatePseudoConsolePtr)GetProcAddress((HMODULE)kernel32Handle, "CreatePseudoConsole"); - resizePseudoConsole = (ResizePseudoConsolePtr)GetProcAddress((HMODULE)kernel32Handle, "ResizePseudoConsole"); - closePseudoConsole = (ClosePseudoConsolePtr)GetProcAddress((HMODULE)kernel32Handle, "ClosePseudoConsole"); - if (createPseudoConsole == NULL || resizePseudoConsole == NULL || closePseudoConsole == NULL) - { - m_lastError = QString("WindowsContext/ConPty error: %1").arg("Invalid on load API functions"); - return false; - } - } - else - { - m_lastError = QString("WindowsContext/ConPty error: %1").arg("Unable to load kernel32"); - return false; - } + createPseudoConsole = (CreatePseudoConsolePtr)ConptyCreatePseudoConsole; + resizePseudoConsole = (ResizePseudoConsolePtr)ConptyResizePseudoConsole; + closePseudoConsole = (ClosePseudoConsolePtr)ConptyClosePseudoConsole; return true; } @@ -81,6 +792,30 @@ private: QString m_lastError; }; +static bool checkConHostHasResizeQuirkOption() +{ + static bool hasResizeQuirk = std::invoke([](){ + QFile f(_InboxConsoleHostPath()); + if (!f.open(QIODevice::ReadOnly)) { + qWarning() << "couldn't open conhost.exe, assuming no resizeQuirk."; + return false; + } + // Conhost.exe should be around 1 MB + if (f.size() > 5 * 1024 * 1024) { + qWarning() << "conhost.exe is > 5MB, assuming no resizeQuirk."; + return false; + } + QByteArray content = f.readAll(); + QString searchString("--resizeQuirk"); + QByteArrayView v((const char*)searchString.data(), searchString.length()*2); + bool result = content.contains(v); + if (!result) + qDebug() << "No resizeQuirk option found in conhost."; + return result; + }); + + return hasResizeQuirk; +} HRESULT ConPtyProcess::createPseudoConsoleAndPipes(HPCON* phPC, HANDLE* phPipeIn, HANDLE* phPipeOut, qint16 cols, qint16 rows) { @@ -93,7 +828,7 @@ HRESULT ConPtyProcess::createPseudoConsoleAndPipes(HPCON* phPC, HANDLE* phPipeIn CreatePipe(phPipeIn, &hPipePTYOut, NULL, 0)) { // Create the Pseudo Console of the required size, attached to the PTY-end of the pipes - hr = WindowsContext::instance().createPseudoConsole({cols, rows}, hPipePTYIn, hPipePTYOut, 0, phPC); + hr = WindowsContext::instance().createPseudoConsole({cols, rows}, hPipePTYIn, hPipePTYOut, checkConHostHasResizeQuirkOption() ? PSEUDOCONSOLE_RESIZE_QUIRK : 0, phPC); // Note: We can close the handles to the PTY-end of the pipes here // because the handles are dup'ed into the ConHost and will be released From d4e775ebc6052bb82000110233fd9852715c4094 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 13 Mar 2024 14:57:59 +0100 Subject: [PATCH 0089/1060] TextEditor: handle syntax highlight in batches Use an elapsed timer in the syntax highlighter to periodically return from the highlight and push a continue highlight to the end of the event loop. This allows the user to interact with the editor in between those batches. If the user modifies the document in between highlighting batches, the area that still needs a rehighlight is increased if needed. This also reverts 62ea85ee6ad15c8e4d9cb5e35b1f10bee3c49ac7 and the related changes. Task-number: QTCREATORBUG-28727 Change-Id: I7c394dbdff658330bb72f3b68b9928980947db75 Reviewed-by: Reviewed-by: Christian Stenger --- src/plugins/cppeditor/cppautocompleter.cpp | 18 +- src/plugins/cppeditor/cppcompletion_test.cpp | 8 +- src/plugins/cppeditor/cppeditordocument.cpp | 5 +- src/plugins/cppeditor/cpphighlighter.cpp | 12 +- src/plugins/cppeditor/cpptoolstestcase.cpp | 6 +- src/plugins/cppeditor/semantichighlighter.cpp | 10 +- src/plugins/fakevim/fakevim_test.cpp | 10 +- src/plugins/glsleditor/glslhighlighter.cpp | 3 +- .../semantichighlightsupport.cpp | 6 +- .../qmljseditor/qmljssemantichighlighter.cpp | 4 +- src/plugins/texteditor/CMakeLists.txt | 1 - src/plugins/texteditor/highlighter_test.cpp | 7 +- src/plugins/texteditor/highlighterhelper.cpp | 5 +- .../texteditor/semantichighlighter.cpp | 30 +- src/plugins/texteditor/semantichighlighter.h | 7 +- src/plugins/texteditor/syntaxhighlighter.cpp | 225 +++++----- src/plugins/texteditor/syntaxhighlighter.h | 78 +--- .../texteditor/syntaxhighlighterrunner.cpp | 385 ------------------ .../texteditor/syntaxhighlighterrunner.h | 79 ---- src/plugins/texteditor/textdocument.cpp | 49 +-- src/plugins/texteditor/textdocument.h | 5 +- src/plugins/texteditor/texteditor.cpp | 33 +- src/plugins/texteditor/texteditor.qbs | 2 - .../vcsbase/baseannotationhighlighter.cpp | 3 +- src/plugins/vcsbase/vcsbaseeditor.cpp | 6 +- .../highlighter/tst_highlighter.cpp | 36 +- 26 files changed, 242 insertions(+), 791 deletions(-) delete mode 100644 src/plugins/texteditor/syntaxhighlighterrunner.cpp delete mode 100644 src/plugins/texteditor/syntaxhighlighterrunner.h diff --git a/src/plugins/cppeditor/cppautocompleter.cpp b/src/plugins/cppeditor/cppautocompleter.cpp index 07101318628..e5560e9d969 100644 --- a/src/plugins/cppeditor/cppautocompleter.cpp +++ b/src/plugins/cppeditor/cppautocompleter.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -17,6 +16,7 @@ #include #include +#include #include #include #include @@ -276,9 +276,9 @@ void AutoCompleterTest::testAutoComplete() TextEditor::BaseTextEditor *cppEditor = creteCppEditor(text); QVERIFY(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QTextCursor tc = openEditor(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QVERIFY(!tc.isNull()); @@ -339,9 +339,9 @@ void AutoCompleterTest::testSurroundWithSelection() const QScopeGuard cleanup([] { Core::EditorManager::closeAllEditors(false); }); TextEditor::BaseTextEditor *cppEditor = creteCppEditor(text); QVERIFY(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QTextCursor tc = openEditor(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QVERIFY(!tc.isNull()); @@ -376,9 +376,9 @@ void AutoCompleterTest::testAutoBackspace() const QScopeGuard cleanup([] { Core::EditorManager::closeAllEditors(false); }); TextEditor::BaseTextEditor *cppEditor = creteCppEditor(text); QVERIFY(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QTextCursor tc = openEditor(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QVERIFY(!tc.isNull()); @@ -420,9 +420,9 @@ void AutoCompleterTest::testInsertParagraph() const QScopeGuard cleanup([] { Core::EditorManager::closeAllEditors(false); }); TextEditor::BaseTextEditor *cppEditor = creteCppEditor(text); QVERIFY(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QTextCursor tc = openEditor(cppEditor); - QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); QVERIFY(!tc.isNull()); diff --git a/src/plugins/cppeditor/cppcompletion_test.cpp b/src/plugins/cppeditor/cppcompletion_test.cpp index cf8b163ab4e..fdc30e16be3 100644 --- a/src/plugins/cppeditor/cppcompletion_test.cpp +++ b/src/plugins/cppeditor/cppcompletion_test.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include @@ -146,12 +146,10 @@ public: TextEditor::BaseTextEditor *cppEditor = qobject_cast(m_editor); if (!cppEditor) return false; - if (cppEditor->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()) + if (cppEditor->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()) return true; return ::CppEditor::Tests::waitForSignalOrTimeout( - cppEditor->textDocument()->syntaxHighlighterRunner(), - &SyntaxHighlighterRunner::highlightingFinished, - 5000); + cppEditor->textDocument()->syntaxHighlighter(), &SyntaxHighlighter::finished, 5000); } private: diff --git a/src/plugins/cppeditor/cppeditordocument.cpp b/src/plugins/cppeditor/cppeditordocument.cpp index 459ae32977a..6f2a67fede4 100644 --- a/src/plugins/cppeditor/cppeditordocument.cpp +++ b/src/plugins/cppeditor/cppeditordocument.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include @@ -164,7 +163,7 @@ QByteArray CppEditorDocument::contentsText() const void CppEditorDocument::applyFontSettings() { - if (TextEditor::SyntaxHighlighterRunner *highlighter = syntaxHighlighterRunner()) + if (TextEditor::SyntaxHighlighter *highlighter = syntaxHighlighter()) highlighter->clearAllExtraFormats(); // Clear all additional formats since they may have changed TextDocument::applyFontSettings(); // rehighlights and updates additional formats if (m_processor) @@ -408,7 +407,7 @@ BaseEditorDocumentProcessor *CppEditorDocument::processor() connect(m_processor.data(), &BaseEditorDocumentProcessor::cppDocumentUpdated, this, [this](const CPlusPlus::Document::Ptr document) { // Update syntax highlighter - if (SyntaxHighlighterRunner *highlighter = syntaxHighlighterRunner()) + if (SyntaxHighlighter *highlighter = syntaxHighlighter()) highlighter->setLanguageFeaturesFlags(document->languageFeatures().flags); m_overviewModel.update(usesClangd() ? nullptr : document); diff --git a/src/plugins/cppeditor/cpphighlighter.cpp b/src/plugins/cppeditor/cpphighlighter.cpp index becebd11886..952d74707a2 100644 --- a/src/plugins/cppeditor/cpphighlighter.cpp +++ b/src/plugins/cppeditor/cpphighlighter.cpp @@ -84,8 +84,13 @@ void CppHighlighter::highlightBlock(const QString &text) const int firstNonSpace = tokens.first().utf16charsBegin(); // Keep "semantic parentheses". - Parentheses parentheses = Utils::filtered(TextDocumentLayout::parentheses(currentBlock()), - [](const Parenthesis &p) { return p.source.isValid(); }); + Parentheses parentheses; + if (TextBlockUserData *userData = TextDocumentLayout::textUserData(currentBlock())) { + parentheses = Utils::filtered(userData->parentheses(), [](const Parenthesis &p) { + return p.source.isValid(); + }); + } + const auto insertParen = [&parentheses](const Parenthesis &p) { insertSorted(parentheses, p); }; parentheses.reserve(5); @@ -235,7 +240,8 @@ void CppHighlighter::highlightBlock(const QString &text) // if the block is ifdefed out, we only store the parentheses, but // do not adjust the brace depth. - if (TextDocumentLayout::ifdefedOut(currentBlock())) { + if (TextBlockUserData *userData = TextDocumentLayout::textUserData(currentBlock()); + userData && userData->ifdefedOut()) { braceDepth = initialBraceDepth; foldingIndent = initialBraceDepth; } diff --git a/src/plugins/cppeditor/cpptoolstestcase.cpp b/src/plugins/cppeditor/cpptoolstestcase.cpp index b0151e7a813..869bbf9b84d 100644 --- a/src/plugins/cppeditor/cpptoolstestcase.cpp +++ b/src/plugins/cppeditor/cpptoolstestcase.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include @@ -238,8 +238,8 @@ bool TestCase::openCppEditor(const FilePath &filePath, TextEditor::BaseTextEdito [e] { return e->editorWidget() ->textDocument() - ->syntaxHighlighterRunner() - ->syntaxInfoUpdated(); + ->syntaxHighlighter() + ->syntaxHighlighterUpToDate(); }, 5000)) return false; diff --git a/src/plugins/cppeditor/semantichighlighter.cpp b/src/plugins/cppeditor/semantichighlighter.cpp index d841ae19c4e..a2ae3becb79 100644 --- a/src/plugins/cppeditor/semantichighlighter.cpp +++ b/src/plugins/cppeditor/semantichighlighter.cpp @@ -8,7 +8,6 @@ #include #include #include -#include #include #include @@ -67,12 +66,15 @@ void SemanticHighlighter::run() Parentheses SemanticHighlighter::getClearedParentheses(const QTextBlock &block) { - Parentheses parens = TextDocumentLayout::parentheses(block); + Parentheses parens; + if (TextBlockUserData *userData = TextDocumentLayout::textUserData(block)) + parens = userData->parentheses(); if (m_seenBlocks.insert(block.blockNumber()).second) { parens = Utils::filtered(parens, [](const Parenthesis &p) { return p.source != parenSource(); }); } + return parens; } @@ -107,7 +109,7 @@ void SemanticHighlighter::handleHighlighterResults() QElapsedTimer t; t.start(); - SyntaxHighlighterRunner *highlighter = m_baseTextDocument->syntaxHighlighterRunner(); + SyntaxHighlighter *highlighter = m_baseTextDocument->syntaxHighlighter(); QTC_ASSERT(highlighter, return); incrementalApplyExtraAdditionalFormats(highlighter, m_watcher->future(), from, to, m_formatMap); @@ -195,7 +197,7 @@ void SemanticHighlighter::onHighlighterFinished() t.start(); if (!m_watcher->isCanceled() && documentRevision() == m_revision) { - SyntaxHighlighterRunner *highlighter = m_baseTextDocument->syntaxHighlighterRunner(); + SyntaxHighlighter *highlighter = m_baseTextDocument->syntaxHighlighter(); if (QTC_GUARD(highlighter)) { qCDebug(log) << "onHighlighterFinished() - clearing formats"; clearExtraAdditionalFormatsUntilEnd(highlighter, m_watcher->future()); diff --git a/src/plugins/fakevim/fakevim_test.cpp b/src/plugins/fakevim/fakevim_test.cpp index c81a40a2280..ac1f0a5797c 100644 --- a/src/plugins/fakevim/fakevim_test.cpp +++ b/src/plugins/fakevim/fakevim_test.cpp @@ -9,9 +9,9 @@ #include "fakevimhandler.h" #include -#include +#include #include -#include +#include #include #include @@ -350,7 +350,7 @@ struct FakeVimTester::TestData void doCommand(const char *cmd) { doCommand(_(cmd)); } void doKeys(const QString &keys) { handler->handleInput(keys); - QTRY_VERIFY(editor()->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(editor()->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); } void doKeys(const char *keys) { doKeys(_(keys)); } @@ -364,7 +364,7 @@ struct FakeVimTester::TestData else i = 0; editor()->document()->setPlainText(_(str)); - QTRY_VERIFY(editor()->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(editor()->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); setPosition(i); QCOMPARE(position(), i); } @@ -375,7 +375,7 @@ struct FakeVimTester::TestData QTextCursor tc = editor()->textCursor(); tc.insertText(_(text)); editor()->setTextCursor(tc); - QTRY_VERIFY(editor()->textDocument()->syntaxHighlighterRunner()->syntaxInfoUpdated()); + QTRY_VERIFY(editor()->textDocument()->syntaxHighlighter()->syntaxHighlighterUpToDate()); } // Simulate external position change. diff --git a/src/plugins/glsleditor/glslhighlighter.cpp b/src/plugins/glsleditor/glslhighlighter.cpp index eae8419a049..a6da1d6221a 100644 --- a/src/plugins/glsleditor/glslhighlighter.cpp +++ b/src/plugins/glsleditor/glslhighlighter.cpp @@ -190,7 +190,8 @@ void GlslHighlighter::highlightBlock(const QString &text) // if the block is ifdefed out, we only store the parentheses, but // do not adjust the brace depth. - if (TextDocumentLayout::ifdefedOut(currentBlock())) { + if (TextBlockUserData *userData = TextDocumentLayout::textUserData(currentBlock()); + userData && userData->ifdefedOut()) { braceDepth = initialBraceDepth; foldingIndent = initialBraceDepth; } diff --git a/src/plugins/languageclient/semantichighlightsupport.cpp b/src/plugins/languageclient/semantichighlightsupport.cpp index b7434de18e0..431d84279df 100644 --- a/src/plugins/languageclient/semantichighlightsupport.cpp +++ b/src/plugins/languageclient/semantichighlightsupport.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include @@ -183,7 +183,7 @@ void SemanticTokenSupport::queueDocumentReload(TextEditor::TextDocument *doc) void SemanticTokenSupport::clearHighlight(TextEditor::TextDocument *doc) { if (m_tokens.contains(doc->filePath())){ - if (TextEditor::SyntaxHighlighterRunner *highlighter = doc->syntaxHighlighterRunner()) + if (TextEditor::SyntaxHighlighter *highlighter = doc->syntaxHighlighter()) highlighter->clearAllExtraFormats(); } } @@ -413,7 +413,7 @@ void SemanticTokenSupport::highlight(const Utils::FilePath &filePath, bool force TextDocument *doc = TextDocument::textDocumentForFilePath(filePath); if (!doc || LanguageClientManager::clientForDocument(doc) != m_client) return; - SyntaxHighlighterRunner *highlighter = doc->syntaxHighlighterRunner(); + SyntaxHighlighter *highlighter = doc->syntaxHighlighter(); if (!highlighter) return; const VersionedTokens versionedTokens = m_tokens.value(filePath); diff --git a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp index c414684df7a..67e14dfbcd5 100644 --- a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp +++ b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp @@ -569,7 +569,7 @@ void SemanticHighlighter::applyResults(int from, int to) if (m_enableHighlighting) TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats( - m_document->syntaxHighlighterRunner(), m_watcher.future(), from, to, m_extraFormats); + m_document->syntaxHighlighter(), m_watcher.future(), from, to, m_extraFormats); } void SemanticHighlighter::finished() @@ -584,7 +584,7 @@ void SemanticHighlighter::finished() if (m_enableHighlighting) TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd( - m_document->syntaxHighlighterRunner(), m_watcher.future()); + m_document->syntaxHighlighter(), m_watcher.future()); } void SemanticHighlighter::run(QPromise &promise, diff --git a/src/plugins/texteditor/CMakeLists.txt b/src/plugins/texteditor/CMakeLists.txt index c36d4121ece..e766ec06a10 100644 --- a/src/plugins/texteditor/CMakeLists.txt +++ b/src/plugins/texteditor/CMakeLists.txt @@ -96,7 +96,6 @@ add_qtc_plugin(TextEditor snippets/snippetssettingspage.cpp snippets/snippetssettingspage.h storagesettings.cpp storagesettings.h syntaxhighlighter.cpp syntaxhighlighter.h - syntaxhighlighterrunner.cpp syntaxhighlighterrunner.h tabsettings.cpp tabsettings.h tabsettingswidget.cpp tabsettingswidget.h textdocument.cpp textdocument.h diff --git a/src/plugins/texteditor/highlighter_test.cpp b/src/plugins/texteditor/highlighter_test.cpp index d50c560e23a..2cbd2b75d57 100644 --- a/src/plugins/texteditor/highlighter_test.cpp +++ b/src/plugins/texteditor/highlighter_test.cpp @@ -1,11 +1,10 @@ // Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "syntaxhighlighterrunner.h" - #include "highlighter_test.h" #include "fontsettings.h" +#include "syntaxhighlighter.h" #include "textdocument.h" #include "texteditor.h" #include "texteditorsettings.h" @@ -61,7 +60,7 @@ void GenerigHighlighterTests::initTestCase() m_editor->editorWidget()->configureGenericHighlighter( Utils::mimeTypeForName(Utils::Constants::JSON_MIMETYPE)); QVERIFY(m_editor); - m_editor->textDocument()->syntaxHighlighterRunner()->rehighlight(); + m_editor->textDocument()->syntaxHighlighter()->rehighlight(); } using FormatRanges = QList; @@ -214,7 +213,7 @@ void GenerigHighlighterTests::testPreeditText() block.layout()->setPreeditArea(7, "uaf"); c.endEditBlock(); - m_editor->textDocument()->syntaxHighlighterRunner()->rehighlight(); + m_editor->textDocument()->syntaxHighlighter()->rehighlight(); const FormatRanges formatRanges = {{0, 4, toFormat(C_VISUAL_WHITESPACE)}, {4, 3, toFormat(C_TYPE)}, diff --git a/src/plugins/texteditor/highlighterhelper.cpp b/src/plugins/texteditor/highlighterhelper.cpp index 6aa98439c05..e25b935f8ac 100644 --- a/src/plugins/texteditor/highlighterhelper.cpp +++ b/src/plugins/texteditor/highlighterhelper.cpp @@ -9,7 +9,6 @@ #include "texteditor.h" #include "texteditorsettings.h" #include "texteditortr.h" -#include "syntaxhighlighterrunner.h" #include #include @@ -210,8 +209,8 @@ void reload() highlightRepository()->reload(); for (auto editor : Core::DocumentModel::editorsForOpenedDocuments()) { if (auto textEditor = qobject_cast(editor)) { - if (auto highlighterRunner = textEditor->textDocument()->syntaxHighlighterRunner(); - highlighterRunner && highlighterRunner->useGenericHighlighter()) { + if (auto highlighter = textEditor->textDocument()->syntaxHighlighter(); + highlighter && qobject_cast(highlighter)) { textEditor->editorWidget()->configureGenericHighlighter(); } } diff --git a/src/plugins/texteditor/semantichighlighter.cpp b/src/plugins/texteditor/semantichighlighter.cpp index 9cee346d8b0..0c385d2e4b5 100644 --- a/src/plugins/texteditor/semantichighlighter.cpp +++ b/src/plugins/texteditor/semantichighlighter.cpp @@ -5,7 +5,6 @@ #include "syntaxhighlighter.h" #include "texteditorsettings.h" -#include "syntaxhighlighterrunner.h" #include @@ -75,7 +74,7 @@ const Ranges rangesForResult( } void SemanticHighlighter::incrementalApplyExtraAdditionalFormats( - SyntaxHighlighterRunner *highlighter, + SyntaxHighlighter *highlighter, const QFuture &future, int from, int to, @@ -114,21 +113,17 @@ void SemanticHighlighter::incrementalApplyExtraAdditionalFormats( formatRanges[range.block].append(range.formatRange); } - QList clearBlockNumberVector; - QMap> blockNumberMap; for (auto &[block, ranges] : formatRanges) { while (currentBlock < block) { - clearBlockNumberVector.append(currentBlock.blockNumber()); + highlighter->clearExtraFormats(currentBlock); currentBlock = currentBlock.next(); } - blockNumberMap[block.blockNumber()] = ranges; + highlighter->setExtraFormats(block, std::move(ranges)); currentBlock = block.next(); } - highlighter->clearExtraFormats(clearBlockNumberVector); - highlighter->setExtraFormats(blockNumberMap); } -void SemanticHighlighter::setExtraAdditionalFormats(SyntaxHighlighterRunner *highlighter, +void SemanticHighlighter::setExtraAdditionalFormats(SyntaxHighlighter *highlighter, const QList &results, const QHash &kindToFormat) { @@ -139,19 +134,19 @@ void SemanticHighlighter::setExtraAdditionalFormats(SyntaxHighlighterRunner *hig QTextDocument *doc = highlighter->document(); QTC_ASSERT(doc, return ); - QMap> blockNumberMap; + std::map> formatRanges; - for (const HighlightingResult &result : results) { - const Ranges ranges = rangesForResult(result, doc, kindToFormat); - for (const Range &range : ranges) - blockNumberMap[range.block.blockNumber()].append(range.formatRange); + for (auto result : results) { + for (const Range &range : rangesForResult(result, doc, kindToFormat)) + formatRanges[range.block].append(range.formatRange); } - highlighter->setExtraFormats(blockNumberMap); + for (auto &[block, ranges] : formatRanges) + highlighter->setExtraFormats(block, std::move(ranges)); } void SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd( - SyntaxHighlighterRunner *highlighter, const QFuture &future) + SyntaxHighlighter *highlighter, const QFuture &future) { const QTextDocument * const doc = highlighter->document(); QTextBlock firstBlockToClear = doc->begin(); @@ -168,7 +163,6 @@ void SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd( QList clearBlockNumberVector; for (QTextBlock b = firstBlockToClear; b.isValid(); b = b.next()) - clearBlockNumberVector.append(b.blockNumber()); + highlighter->clearExtraFormats(b); - highlighter->clearExtraFormats(clearBlockNumberVector); } diff --git a/src/plugins/texteditor/semantichighlighter.h b/src/plugins/texteditor/semantichighlighter.h index ad1d854b834..f8ae30a0eda 100644 --- a/src/plugins/texteditor/semantichighlighter.h +++ b/src/plugins/texteditor/semantichighlighter.h @@ -21,7 +21,6 @@ QT_END_NAMESPACE namespace TextEditor { class SyntaxHighlighter; -class SyntaxHighlighterRunner; class TEXTEDITOR_EXPORT HighlightingResult { @@ -74,7 +73,7 @@ using Splitter = std::function &future, int from, int to, @@ -85,7 +84,7 @@ incrementalApplyExtraAdditionalFormats(SyntaxHighlighterRunner *highlighter, // indicated by Result::kind and kindToFormat to the correct location using // SyntaxHighlighter::setExtraFormats. In contrast to // incrementalApplyExtraAdditionalFormats the results do not have to be ordered by line. -void TEXTEDITOR_EXPORT setExtraAdditionalFormats(SyntaxHighlighterRunner *highlighter, +void TEXTEDITOR_EXPORT setExtraAdditionalFormats(SyntaxHighlighter *highlighter, const HighlightingResults &results, const QHash &kindToFormat); @@ -93,7 +92,7 @@ void TEXTEDITOR_EXPORT setExtraAdditionalFormats(SyntaxHighlighterRunner *highli // until the end of the document. // Requires that results of the Future are ordered by line. void TEXTEDITOR_EXPORT clearExtraAdditionalFormatsUntilEnd( - SyntaxHighlighterRunner *highlighter, const QFuture &future); + SyntaxHighlighter *highlighter, const QFuture &future); } // namespace SemanticHighlighter } // namespace TextEditor diff --git a/src/plugins/texteditor/syntaxhighlighter.cpp b/src/plugins/texteditor/syntaxhighlighter.cpp index f7db190852d..0162cdeeff0 100644 --- a/src/plugins/texteditor/syntaxhighlighter.cpp +++ b/src/plugins/texteditor/syntaxhighlighter.cpp @@ -25,8 +25,6 @@ enum HighlighterTypeProperty class SyntaxHighlighterPrivate { - SyntaxHighlighter *q_ptr = nullptr; - Q_DECLARE_PUBLIC(SyntaxHighlighter) public: SyntaxHighlighterPrivate() = default; @@ -37,8 +35,10 @@ public: QPointer doc; + void updateFormats(int from, int charsRemoved, int charsAdded); void reformatBlocks(int from, int charsRemoved, int charsAdded); - void reformatBlock(const QTextBlock &block, int from, int charsRemoved, int charsAdded); + void reformatBlocks(); + void reformatBlock(const QTextBlock &block); inline void rehighlight(QTextCursor &cursor, QTextCursor::MoveOperation operation) { inReformatBlocks = true; @@ -48,7 +48,7 @@ public: inReformatBlocks = false; } - void applyFormatChanges(int from, int charsRemoved, int charsAdded); + void applyFormatChanges(); void updateFormats(const FontSettings &fontSettings); FontSettings fontSettings; @@ -61,6 +61,11 @@ public: QList> formatCategories; QTextCharFormat whitespaceFormat; QString mimeType; + bool syntaxInfoUpToDate = false; + int highlightStartBlock = 0; + int highlightEndBlock = 0; + QSet forceRehighlightBlocks; + SyntaxHighlighter *q; }; static bool adjustRange(QTextLayout::FormatRange &range, int from, int charsDelta) @@ -77,31 +82,30 @@ static bool adjustRange(QTextLayout::FormatRange &range, int from, int charsDelt void SyntaxHighlighter::delayedRehighlight() { - Q_D(SyntaxHighlighter); if (!d->rehighlightPending) return; d->rehighlightPending = false; - if (document()->isEmpty()) - return; - rehighlight(); } +void SyntaxHighlighter::continueRehighlight() +{ + d->reformatBlocks(); +} + #ifdef WITH_TESTS SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent, const FontSettings &fontsettings) - : QObject(parent), d_ptr(new SyntaxHighlighterPrivate(fontsettings)) + : QObject(parent), d(new SyntaxHighlighterPrivate(fontsettings)) { - d_ptr->q_ptr = this; + d->q = this; if (parent) setDocument(parent); } #endif -void SyntaxHighlighterPrivate::applyFormatChanges(int from, int charsRemoved, int charsAdded) +void SyntaxHighlighterPrivate::applyFormatChanges() { - bool formatsChanged = false; - QTextLayout *layout = currentBlock.layout(); QList ranges; @@ -111,12 +115,6 @@ void SyntaxHighlighterPrivate::applyFormatChanges(int from, int charsRemoved, in return range.format.property(SyntaxHighlight).toBool(); }); - if (currentBlock.contains(from)) { - const int charsDelta = charsAdded - charsRemoved; - for (QTextLayout::FormatRange &range : ranges) - formatsChanged |= adjustRange(range, from - currentBlock.position(), charsDelta); - } - QTextCharFormat emptyFormat; QTextLayout::FormatRange r; @@ -157,7 +155,7 @@ void SyntaxHighlighterPrivate::applyFormatChanges(int from, int charsRemoved, in newRanges << r; } - formatsChanged = formatsChanged || (newRanges.size() != oldRanges.size()); + bool formatsChanged = (newRanges.size() != oldRanges.size()); for (int i = 0; !formatsChanged && i < newRanges.size(); ++i) { const QTextLayout::FormatRange &o = oldRanges.at(i); @@ -174,85 +172,103 @@ void SyntaxHighlighterPrivate::applyFormatChanges(int from, int charsRemoved, in void SyntaxHighlighter::reformatBlocks(int from, int charsRemoved, int charsAdded) { - Q_D(SyntaxHighlighter); if (!d->inReformatBlocks) d->reformatBlocks(from, charsRemoved, charsAdded); } +void SyntaxHighlighterPrivate::updateFormats(int from, int charsRemoved, int charsAdded) +{ + bool formatsChanged = false; + + const QTextBlock block = doc->findBlock(from); + QTextLayout *layout = block.layout(); + + QList ranges = layout->formats(); + + const int charsDelta = charsAdded - charsRemoved; + for (QTextLayout::FormatRange &range : ranges) + formatsChanged |= adjustRange(range, from - block.position(), charsDelta); + + if (formatsChanged) { + layout->setFormats(ranges); + doc->markContentsDirty(block.position(), block.length()); + } +} + void SyntaxHighlighterPrivate::reformatBlocks(int from, int charsRemoved, int charsAdded) { - Q_Q(SyntaxHighlighter); - foldValidator.reset(); - - rehighlightPending = false; + updateFormats(from, charsRemoved, charsAdded); QTextBlock block = doc->findBlock(from); + if (block.isValid() && block.blockNumber() < highlightStartBlock) + highlightStartBlock = block.blockNumber(); + block = doc->findBlock(from + charsAdded + (charsRemoved > 0 ? 1 : 0)); if (!block.isValid()) - return; + highlightEndBlock = doc->blockCount() - 1; + else if (block.blockNumber() > highlightEndBlock) + highlightEndBlock = block.blockNumber(); - int endPosition; - QTextBlock lastBlock = doc->findBlock(from + charsAdded + (charsRemoved > 0 ? 1 : 0)); - if (lastBlock.isValid()) - endPosition = lastBlock.position() + lastBlock.length(); - else - endPosition = doc->lastBlock().position() + doc->lastBlock().length(); + reformatBlocks(); +} + +void SyntaxHighlighterPrivate::reformatBlocks() +{ + QElapsedTimer et; + et.start(); + + syntaxInfoUpToDate = false; + rehighlightPending = false; + + foldValidator.reset(); bool forceHighlightOfNextBlock = false; + QTextBlock block = doc->findBlockByNumber(highlightStartBlock); + QTC_ASSERT(block.isValid(), block = doc->firstBlock()); + QTextBlock endBlock = doc->findBlockByNumber(highlightEndBlock); + QTC_ASSERT(endBlock.isValid(), endBlock = doc->lastBlock()); - QList vecRes; - - SyntaxHighlighter::Result resStart; - resStart.m_state = SyntaxHighlighter::State::Start; - vecRes << resStart; - - while (block.isValid() && (block.position() < endPosition || forceHighlightOfNextBlock)) { - if (QThread::currentThread()->isInterruptionRequested() || q->isInterrupted()) { - inReformatBlocks = false; - emit q->resultsReady({}); - return; - } + while (block.isValid()) { + if (et.elapsed() > 20) + break; const int stateBeforeHighlight = block.userState(); - reformatBlock(block, from, charsRemoved, charsAdded); - - forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight); - - SyntaxHighlighter::Result res; - res.m_formatRanges = block.layout()->formats(); - res.fillByBlock(block); - vecRes << res; - - // Sending data to the text editor in chunks of 200 blocks is a sensible approach. - // This helps avoid UI slowdowns when applying formatting to the text. - if (vecRes.size() >= 200) { - emit q->resultsReady(vecRes); - vecRes.clear(); + if (forceHighlightOfNextBlock || forceRehighlightBlocks.contains(block.blockNumber()) + || block.blockNumber() <= highlightEndBlock) { + reformatBlock(block); + forceRehighlightBlocks.remove(block.blockNumber()); + forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight); } + highlightStartBlock = block.blockNumber(); + if (block == endBlock && !forceHighlightOfNextBlock) + break; block = block.next(); } formatChanges.clear(); - foldValidator.finalize(); - SyntaxHighlighter::Result res; - res.m_state = SyntaxHighlighter::State::Done; - vecRes << res; - emit q->resultsReady(vecRes); + + if (endBlock.isValid() && block.isValid() && block.blockNumber() < endBlock.blockNumber()) { + QMetaObject::invokeMethod(q, &SyntaxHighlighter::continueRehighlight, Qt::QueuedConnection); + if (forceHighlightOfNextBlock) + forceRehighlightBlocks << block.blockNumber(); + } else { + highlightEndBlock = 0; + syntaxInfoUpToDate = true; + emit q->finished(); + } } -void SyntaxHighlighterPrivate::reformatBlock(const QTextBlock &block, int from, int charsRemoved, int charsAdded) +void SyntaxHighlighterPrivate::reformatBlock(const QTextBlock &block) { - Q_Q(SyntaxHighlighter); - - Q_ASSERT_X(!currentBlock.isValid(), "SyntaxHighlighter::reformatBlock()", "reFormatBlock() called recursively"); + QTC_ASSERT(!currentBlock.isValid(), return); currentBlock = block; formatChanges.fill(QTextCharFormat(), block.length() - 1); q->highlightBlock(block.text()); - applyFormatChanges(from, charsRemoved, charsAdded); + applyFormatChanges(); foldValidator.process(currentBlock); @@ -293,9 +309,9 @@ void SyntaxHighlighterPrivate::reformatBlock(const QTextBlock &block, int from, Constructs a SyntaxHighlighter with the given \a parent. */ SyntaxHighlighter::SyntaxHighlighter(QObject *parent) - : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) + : QObject(parent), d(new SyntaxHighlighterPrivate) { - d_ptr->q_ptr = this; + d->q = this; } /*! @@ -304,9 +320,9 @@ SyntaxHighlighter::SyntaxHighlighter(QObject *parent) SyntaxHighlighter. */ SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) - : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) + : QObject(parent), d(new SyntaxHighlighterPrivate) { - d_ptr->q_ptr = this; + d->q = this; if (parent) setDocument(parent); } @@ -317,9 +333,9 @@ SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) the SyntaxHighlighter. */ SyntaxHighlighter::SyntaxHighlighter(QTextEdit *parent) - : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) + : QObject(parent), d(new SyntaxHighlighterPrivate) { - d_ptr->q_ptr = this; + d->q = this; if (parent) setDocument(parent->document()); } @@ -338,7 +354,6 @@ SyntaxHighlighter::~SyntaxHighlighter() */ void SyntaxHighlighter::setDocument(QTextDocument *doc) { - Q_D(SyntaxHighlighter); if (d->doc == doc) return; @@ -356,10 +371,7 @@ void SyntaxHighlighter::setDocument(QTextDocument *doc) documentChanged(oldDoc, d->doc); if (d->doc) { connect(d->doc, &QTextDocument::contentsChange, this, &SyntaxHighlighter::reformatBlocks); - d->rehighlightPending = true; - QMetaObject::invokeMethod(this, - &SyntaxHighlighter::delayedRehighlight, - Qt::QueuedConnection); + scheduleRehighlight(); d->foldValidator.setup(qobject_cast(doc->documentLayout())); } } @@ -370,19 +382,16 @@ void SyntaxHighlighter::setDocument(QTextDocument *doc) */ QTextDocument *SyntaxHighlighter::document() const { - Q_D(const SyntaxHighlighter); return d->doc; } void SyntaxHighlighter::setMimeType(const QString &mimeType) { - Q_D(SyntaxHighlighter); d->mimeType = mimeType; } QString SyntaxHighlighter::mimeType() const { - Q_D(const SyntaxHighlighter); return d->mimeType; } @@ -395,7 +404,6 @@ QString SyntaxHighlighter::mimeType() const */ void SyntaxHighlighter::rehighlight() { - Q_D(SyntaxHighlighter); if (!d->doc) return; @@ -403,6 +411,17 @@ void SyntaxHighlighter::rehighlight() d->rehighlight(cursor, QTextCursor::End); } +void SyntaxHighlighter::scheduleRehighlight() +{ + if (d->rehighlightPending) + return; + d->rehighlightPending = true; + d->syntaxInfoUpToDate = false; + QMetaObject::invokeMethod(this, + &SyntaxHighlighter::delayedRehighlight, + Qt::QueuedConnection); +} + /*! \since 4.6 @@ -412,7 +431,6 @@ void SyntaxHighlighter::rehighlight() */ void SyntaxHighlighter::rehighlightBlock(const QTextBlock &block) { - Q_D(SyntaxHighlighter); if (!d->doc || !block.isValid() || block.document() != d->doc) return; @@ -486,7 +504,6 @@ void SyntaxHighlighter::rehighlightBlock(const QTextBlock &block) */ void SyntaxHighlighter::setFormat(int start, int count, const QTextCharFormat &format) { - Q_D(SyntaxHighlighter); if (start < 0 || start >= d->formatChanges.count()) return; @@ -533,7 +550,6 @@ void SyntaxHighlighter::setFormat(int start, int count, const QFont &font) void SyntaxHighlighter::formatSpaces(const QString &text, int start, int count) { - Q_D(const SyntaxHighlighter); int offset = start; const int end = std::min(start + count, int(text.length())); while (offset < end) { @@ -585,10 +601,7 @@ void SyntaxHighlighter::setFormatWithSpaces(const QString &text, int start, int */ QTextCharFormat SyntaxHighlighter::format(int pos) const { - Q_D(const SyntaxHighlighter); - if (pos < 0 || pos >= d->formatChanges.count()) - return QTextCharFormat(); - return d->formatChanges.at(pos); + return d->formatChanges.value(pos); } /*! @@ -600,7 +613,6 @@ QTextCharFormat SyntaxHighlighter::format(int pos) const */ int SyntaxHighlighter::previousBlockState() const { - Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return -1; @@ -617,7 +629,6 @@ int SyntaxHighlighter::previousBlockState() const */ int SyntaxHighlighter::currentBlockState() const { - Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return -1; @@ -631,7 +642,6 @@ int SyntaxHighlighter::currentBlockState() const */ void SyntaxHighlighter::setCurrentBlockState(int newState) { - Q_D(SyntaxHighlighter); if (!d->currentBlock.isValid()) return; @@ -674,7 +684,6 @@ void SyntaxHighlighter::setCurrentBlockState(int newState) */ void SyntaxHighlighter::setCurrentBlockUserData(QTextBlockUserData *data) { - Q_D(SyntaxHighlighter); if (!d->currentBlock.isValid()) return; @@ -689,7 +698,6 @@ void SyntaxHighlighter::setCurrentBlockUserData(QTextBlockUserData *data) */ QTextBlockUserData *SyntaxHighlighter::currentBlockUserData() const { - Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return nullptr; @@ -703,7 +711,6 @@ QTextBlockUserData *SyntaxHighlighter::currentBlockUserData() const */ QTextBlock SyntaxHighlighter::currentBlock() const { - Q_D(const SyntaxHighlighter); return d->currentBlock; } @@ -715,8 +722,6 @@ static bool byStartOfRange(const QTextLayout::FormatRange &range, const QTextLay void SyntaxHighlighter::setExtraFormats(const QTextBlock &block, const QList &formats) { - Q_D(SyntaxHighlighter); - QList formatsCopy = formats; const int blockLength = block.length(); @@ -766,20 +771,17 @@ void SyntaxHighlighter::setExtraFormats(const QTextBlock &block, d->inReformatBlocks = true; block.layout()->setFormats(formatsToApply); - SyntaxHighlighter::Result res; - res.m_formatRanges = block.layout()->formats(); - res.fillByBlock(block); - res.m_state = SyntaxHighlighter::State::Extras; - emit resultsReady({std::move(res)}); - document()->markContentsDirty(block.position(), blockLength - 1); d->inReformatBlocks = wasInReformatBlocks; } +bool SyntaxHighlighter::syntaxHighlighterUpToDate() const +{ + return d->syntaxInfoUpToDate; +} + void SyntaxHighlighter::clearExtraFormats(const QTextBlock &block) { - Q_D(SyntaxHighlighter); - const int blockLength = block.length(); if (block.layout() == nullptr || blockLength == 0) return; @@ -793,12 +795,6 @@ void SyntaxHighlighter::clearExtraFormats(const QTextBlock &block) d->inReformatBlocks = true; block.layout()->setFormats(formatsToApply); - SyntaxHighlighter::Result res; - res.m_formatRanges = block.layout()->formats(); - res.fillByBlock(block); - res.m_state = SyntaxHighlighter::State::Extras; - emit resultsReady({std::move(res)}); - document()->markContentsDirty(block.position(), blockLength - 1); d->inReformatBlocks = wasInReformatBlocks; } @@ -848,13 +844,11 @@ QList SyntaxHighlighter::generateColors(int n, const QColor &background) void SyntaxHighlighter::setFontSettings(const FontSettings &fontSettings) { - Q_D(SyntaxHighlighter); d->updateFormats(fontSettings); } FontSettings SyntaxHighlighter::fontSettings() const { - Q_D(const SyntaxHighlighter); return d->fontSettings; } @@ -897,7 +891,6 @@ void SyntaxHighlighter::setTextFormatCategories(int count, */ void SyntaxHighlighter::setTextFormatCategories(const QList> &categories) { - Q_D(SyntaxHighlighter); d->formatCategories = categories; const int maxCategory = Utils::maxElementOr(categories, {-1, C_TEXT}).first; d->formats = QList(maxCategory + 1); @@ -906,7 +899,6 @@ void SyntaxHighlighter::setTextFormatCategories(const QListformats.size() > category, return QTextCharFormat()); return d->formats.at(category); @@ -914,7 +906,6 @@ QTextCharFormat SyntaxHighlighter::formatForCategory(int category) const QTextCharFormat SyntaxHighlighter::whitespacified(const QTextCharFormat &fmt) { - Q_D(SyntaxHighlighter); QTextCharFormat format = d->whitespaceFormat; format.setBackground(fmt.background()); return format; diff --git a/src/plugins/texteditor/syntaxhighlighter.h b/src/plugins/texteditor/syntaxhighlighter.h index 6b07d333f33..f5506374267 100644 --- a/src/plugins/texteditor/syntaxhighlighter.h +++ b/src/plugins/texteditor/syntaxhighlighter.h @@ -34,7 +34,6 @@ class SyntaxHighlighterPrivate; class TEXTEDITOR_EXPORT SyntaxHighlighter : public QObject { Q_OBJECT - Q_DECLARE_PRIVATE(SyntaxHighlighter) public: SyntaxHighlighter(QObject *parent = nullptr); SyntaxHighlighter(QTextDocument *parent); @@ -53,79 +52,16 @@ public: virtual void setFontSettings(const TextEditor::FontSettings &fontSettings); TextEditor::FontSettings fontSettings() const; - enum State { - Start, - InProgress, - Done, - Extras - }; - - struct Result - { - void fillByBlock(const QTextBlock &block) - { - m_blockNumber = block.blockNumber(); - m_userState = block.userState(); - - TextBlockUserData *userDate = TextDocumentLayout::textUserData(block); - if (!userDate) - return; - - m_hasBlockUserData = true; - m_foldingIndent = userDate->foldingIndent(); - m_ifdefedOut = userDate->ifdefedOut(); - m_foldingStartIncluded = userDate->foldingStartIncluded(); - m_foldingEndIncluded = userDate->foldingEndIncluded(); - m_parentheses = userDate->parentheses(); - m_expectedRawStringSuffix = userDate->expectedRawStringSuffix(); - } - - void copyToBlock(QTextBlock &block) const - { - block.setUserState(m_userState); - - if (!m_hasBlockUserData) - return; - - TextBlockUserData *data = TextDocumentLayout::userData(block); - data->setExpectedRawStringSuffix(m_expectedRawStringSuffix); - data->setFoldingIndent(m_foldingIndent); - data->setFoldingStartIncluded(m_foldingStartIncluded); - data->setFoldingEndIncluded(m_foldingEndIncluded); - - if (m_ifdefedOut) - data->setIfdefedOut(); - else - data->clearIfdefedOut(); - - data->setParentheses(m_parentheses); - } - - int m_blockNumber; - bool m_hasBlockUserData = false; - - int m_foldingIndent : 16; - uint m_ifdefedOut : 1; - uint m_foldingStartIncluded : 1; - uint m_foldingEndIncluded : 1; - - Parentheses m_parentheses; - QByteArray m_expectedRawStringSuffix; - int m_userState = -1; - QList m_formatRanges; - - State m_state = InProgress; - }; - - void setInterrupted(bool interrupted) { m_interrupted = interrupted; } - bool isInterrupted() { return m_interrupted; } void setExtraFormats(const QTextBlock &block, const QList &formats); virtual void setLanguageFeaturesFlags(unsigned int /*flags*/) {}; // needed for CppHighlighting virtual void setEnabled(bool /*enabled*/) {}; // needed for DiffAndLogHighlighter virtual void setDefinitionName(const QString & /*definitionName*/) {} // needed for Highlighter + bool syntaxHighlighterUpToDate() const; + public slots: virtual void rehighlight(); + virtual void scheduleRehighlight(); void rehighlightBlock(const QTextBlock &block); void clearExtraFormats(const QTextBlock &block); void reformatBlocks(int from, int charsRemoved, int charsAdded); @@ -160,18 +96,18 @@ protected: QTextBlock currentBlock() const; -protected: virtual void documentChanged(QTextDocument * /*oldDoc*/, QTextDocument * /*newDoc*/) {}; signals: - void resultsReady(const QList &result); + void finished(); private: void setTextFormatCategories(const QList> &categories); void delayedRehighlight(); + void continueRehighlight(); - QScopedPointer d_ptr; - std::atomic m_interrupted = false; + friend class SyntaxHighlighterPrivate; + std::unique_ptr d; #ifdef WITH_TESTS friend class tst_highlighter; diff --git a/src/plugins/texteditor/syntaxhighlighterrunner.cpp b/src/plugins/texteditor/syntaxhighlighterrunner.cpp deleted file mode 100644 index 874f8254abf..00000000000 --- a/src/plugins/texteditor/syntaxhighlighterrunner.cpp +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright (C) 2023 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "syntaxhighlighterrunner.h" - -#include "fontsettings.h" -#include "textdocumentlayout.h" -#include "texteditorsettings.h" -#include "highlighter.h" - -#include -#include - -#include -#include -#include -#include - -namespace TextEditor { - -struct BlockPreeditData { - int position; - QString text; -}; - -class SyntaxHighlighterRunnerPrivate : public QObject -{ - Q_OBJECT -public: - SyntaxHighlighterRunnerPrivate(SyntaxHighlighter *highlighter, - QTextDocument *document, - bool async) - : m_highlighter(highlighter) - { - if (async) { - m_document = new QTextDocument(this); - m_document->setDocumentLayout(new TextDocumentLayout(m_document)); - } else { - m_document = document; - } - - m_highlighter->setParent(m_document); - m_highlighter->setDocument(m_document); - - connect(m_highlighter, - &SyntaxHighlighter::resultsReady, - this, - &SyntaxHighlighterRunnerPrivate::resultsReady); - } - - void changeDocument(int from, - int charsRemoved, - const QString textAdded, - const QMap &blocksPreedit) - { - QTextCursor cursor(m_document); - cursor.setPosition(qMin(m_document->characterCount() - 1, from + charsRemoved)); - cursor.setPosition(from, QTextCursor::KeepAnchor); - cursor.insertText(textAdded); - - for (auto it = blocksPreedit.cbegin(); it != blocksPreedit.cend(); ++it) { - const QTextBlock block = m_document->findBlockByNumber(it.key()); - block.layout()->setPreeditArea(it.value().position, it.value().text); - } - } - - void setExtraFormats(const QMap> &formatMap) - { - QTC_ASSERT(m_highlighter, return); - for (auto it = formatMap.cbegin(); it != formatMap.cend(); ++it) - m_highlighter->setExtraFormats(m_document->findBlockByNumber(it.key()), it.value()); - } - - void clearExtraFormats(const QList &blockNumbers) - { - QTC_ASSERT(m_highlighter, return); - for (auto it = blockNumbers.cbegin(); it != blockNumbers.cend(); ++it) - m_highlighter->clearExtraFormats(m_document->findBlockByNumber(*it)); - } - - void clearAllExtraFormats() - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->clearAllExtraFormats(); - } - - void setFontSettings(const TextEditor::FontSettings &fontSettings) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->setFontSettings(fontSettings); - } - - void setDefinitionName(const QString &name) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->setDefinitionName(name); - } - - void setLanguageFeaturesFlags(unsigned int flags) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->setLanguageFeaturesFlags(flags); - } - - void setEnabled(bool enabled) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->setEnabled(enabled); - } - - void rehighlight() - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->rehighlight(); - } - - void reformatBlocks(int from, int charsRemoved, int charsAdded) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->reformatBlocks(from, charsRemoved, charsAdded); - } - - void setInterrupted(bool interrupted) - { - QTC_ASSERT(m_highlighter, return); - m_highlighter->setInterrupted(interrupted); - } - - QPointer m_highlighter = nullptr; - QTextDocument *m_document = nullptr; - -signals: - void resultsReady(const QList &result); - -}; - -void SyntaxHighlighterRunner::HighlightingStatus::notInterrupted(int from, - int charsRemoved, - int charsAdded) -{ - m_from = from; - m_addedChars = charsAdded; - m_removedChars = charsRemoved; - m_current = from; - m_newFrom = from + m_addedChars; - m_interruptionRequested = false; -} - -void SyntaxHighlighterRunner::HighlightingStatus::interrupted(int from, - int charsRemoved, - int charsAdded) -{ - m_newFrom = std::min(m_newFrom, from); - m_newFrom = std::min(m_current, m_newFrom); - m_removedChars += charsRemoved; - m_addedChars += charsAdded; - m_interruptionRequested = true; -} - -void SyntaxHighlighterRunner::HighlightingStatus::applyNewFrom() -{ - m_from = m_newFrom; - m_current = m_newFrom; - m_interruptionRequested = false; -} - -SyntaxHighlighterRunner::SyntaxHighlighterRunner(SyntaxHighlighter *highlighter, - QTextDocument *document, - bool async) - : d(new SyntaxHighlighterRunnerPrivate(highlighter, document, async)) - , m_document(document) -{ - m_useGenericHighlighter = qobject_cast(d->m_highlighter); - - if (async) { - m_thread.emplace(); - d->moveToThread(&*m_thread); - connect(&*m_thread, &QThread::finished, d, &QObject::deleteLater); - m_thread->start(); - - connect(d, - &SyntaxHighlighterRunnerPrivate::resultsReady, - this, - &SyntaxHighlighterRunner::applyFormatRanges); - - changeDocument(0, 0, m_document->characterCount()); - connect(m_document, - &QTextDocument::contentsChange, - this, - &SyntaxHighlighterRunner::changeDocument); - - m_foldValidator.setup(qobject_cast(document->documentLayout())); - } else { - connect(d, - &SyntaxHighlighterRunnerPrivate::resultsReady, - this, - [this](const QList &result) { - if (result.size() == 1 - && result.at(0).m_state == SyntaxHighlighter::State::Extras) - return; - - auto done = std::find_if(result.cbegin(), - result.cend(), - [](const SyntaxHighlighter::Result &res) { - return res.m_state - == SyntaxHighlighter::State::Done; - }); - if (done != result.cend()) { - m_syntaxInfoUpdated = SyntaxHighlighter::State::Done; - emit highlightingFinished(); - return; - } - m_syntaxInfoUpdated = SyntaxHighlighter::State::InProgress; - }); - } -} - -SyntaxHighlighterRunner::~SyntaxHighlighterRunner() -{ - if (m_thread) { - m_thread->requestInterruption(); - m_thread->quit(); - m_thread->wait(); - } else { - delete d; - } -} - -void SyntaxHighlighterRunner::applyFormatRanges(const QList &results) -{ - if (m_document == nullptr) - return; - - if (m_highlightingStatus.m_interruptionRequested) { - d->setInterrupted(false); - m_highlightingStatus.applyNewFrom(); - reformatBlocks(m_highlightingStatus.m_newFrom, - m_highlightingStatus.m_removedChars, - m_highlightingStatus.m_addedChars); - return; - } - - auto processResult = [this](SyntaxHighlighter::Result result, QTextBlock docBlock) { - if (!docBlock.isValid()) - return; - - result.copyToBlock(docBlock); - m_highlightingStatus.m_current = docBlock.position() + docBlock.length() - 1; - - if (result.m_formatRanges != docBlock.layout()->formats()) { - docBlock.layout()->setFormats(result.m_formatRanges); - m_document->markContentsDirty(docBlock.position(), docBlock.length()); - } - }; - - if (results.size() == 1 && results.at(0).m_state == SyntaxHighlighter::State::Extras) { - QTextBlock docBlock = m_document->findBlockByNumber(results.at(0).m_blockNumber); - processResult(results.at(0), docBlock); - return; - } - - for (const SyntaxHighlighter::Result &result : results) { - m_syntaxInfoUpdated = result.m_state; - if (m_syntaxInfoUpdated == SyntaxHighlighter::State::Start) { - m_foldValidator.reset(); - continue; - } - if (m_syntaxInfoUpdated == SyntaxHighlighter::State::Done) { - m_foldValidator.finalize(); - emit highlightingFinished(); - return; - } - - QTextBlock docBlock = m_document->findBlockByNumber(result.m_blockNumber); - processResult(result, docBlock); - m_foldValidator.process(docBlock); - } -} - -void SyntaxHighlighterRunner::changeDocument(int from, int charsRemoved, int charsAdded) -{ - QTC_ASSERT(m_document, return); - SyntaxHighlighter::State prevSyntaxInfoUpdated = m_syntaxInfoUpdated; - m_syntaxInfoUpdated = SyntaxHighlighter::State::InProgress; - - QMap blocksPreedit; - QTextBlock block = m_document->findBlock(from); - const QTextBlock endBlock = m_document->findBlock(from + charsAdded); - while (block.isValid() && block != endBlock) { - if (QTextLayout *layout = block.layout()) { - if (const int pos = layout->preeditAreaPosition(); pos != -1) - blocksPreedit[block.blockNumber()] = {pos, layout->preeditAreaText()}; - } - block = block.next(); - } - const QString text = Utils::Text::textAt(QTextCursor(m_document), from, charsAdded); - QMetaObject::invokeMethod(d, [this, from, charsRemoved, text, blocksPreedit] { - d->changeDocument(from, charsRemoved, text, blocksPreedit); - }); - - if (prevSyntaxInfoUpdated == SyntaxHighlighter::State::InProgress) { - m_highlightingStatus.interrupted(from, charsRemoved, charsAdded); - d->setInterrupted(true); - } else { - m_highlightingStatus.notInterrupted(from, charsRemoved, charsAdded); - d->setInterrupted(false); - } -} - -bool SyntaxHighlighterRunner::useGenericHighlighter() const -{ - return m_useGenericHighlighter; -} - -void SyntaxHighlighterRunner::setExtraFormats( - const QMap> &formatMap) -{ - QMetaObject::invokeMethod(d, [this, formatMap] { d->setExtraFormats(formatMap); }); -} - -void SyntaxHighlighterRunner::clearExtraFormats(const QList &blockNumbers) -{ - QMetaObject::invokeMethod(d, [this, blockNumbers] { d->clearExtraFormats(blockNumbers); }); -} - -void SyntaxHighlighterRunner::clearAllExtraFormats() -{ - QMetaObject::invokeMethod(d, [this] { d->clearAllExtraFormats(); }); -} - -void SyntaxHighlighterRunner::setFontSettings(const TextEditor::FontSettings &fontSettings) -{ - QMetaObject::invokeMethod(d, [this, fontSettings] { d->setFontSettings(fontSettings); }); - rehighlight(); -} - -void SyntaxHighlighterRunner::setLanguageFeaturesFlags(unsigned int flags) -{ - QMetaObject::invokeMethod(d, [this, flags] { d->setLanguageFeaturesFlags(flags); }); -} - -void SyntaxHighlighterRunner::setEnabled(bool enabled) -{ - QMetaObject::invokeMethod(d, [this, enabled] { d->setEnabled(enabled); }); -} - -void SyntaxHighlighterRunner::rehighlight() -{ - if (m_syntaxInfoUpdated == SyntaxHighlighter::State::InProgress) { - m_highlightingStatus.interrupted(0, 0, m_document->characterCount()); - d->setInterrupted(true); - } else { - m_highlightingStatus.notInterrupted(0, 0, m_document->characterCount()); - d->setInterrupted(false); - QMetaObject::invokeMethod(d, [this] { d->rehighlight(); }); - } -} - - -void SyntaxHighlighterRunner::reformatBlocks(int from, int charsRemoved, int charsAdded) -{ - QMetaObject::invokeMethod( - d, - [this, from, charsRemoved, charsAdded] { - d->reformatBlocks(from, charsRemoved, charsAdded); - }); -} - -QString SyntaxHighlighterRunner::definitionName() -{ - return m_definitionName; -} - -void SyntaxHighlighterRunner::setDefinitionName(const QString &name) -{ - if (name.isEmpty()) - return; - - m_definitionName = name; - QMetaObject::invokeMethod(d, [this, name] { d->setDefinitionName(name); }); -} - -} // namespace TextEditor - -#include "syntaxhighlighterrunner.moc" diff --git a/src/plugins/texteditor/syntaxhighlighterrunner.h b/src/plugins/texteditor/syntaxhighlighterrunner.h deleted file mode 100644 index 16b7c1535c8..00000000000 --- a/src/plugins/texteditor/syntaxhighlighterrunner.h +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (C) 2023 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include -#include -#include - -#include -#include - -QT_BEGIN_NAMESPACE -class QTextDocument; -QT_END_NAMESPACE - -namespace TextEditor { - -class SyntaxHighlighterRunnerPrivate; - -class TEXTEDITOR_EXPORT SyntaxHighlighterRunner : public QObject -{ - Q_OBJECT -public: - using SyntaxHighlighterCreator = std::function; - - SyntaxHighlighterRunner(SyntaxHighlighter *highlighter, QTextDocument *document, bool async); - virtual ~SyntaxHighlighterRunner(); - - void setExtraFormats(const QMap> &formats); - void clearExtraFormats(const QList &blockNumbers); - void clearAllExtraFormats(); - void setFontSettings(const TextEditor::FontSettings &fontSettings); - void setLanguageFeaturesFlags(unsigned int flags); - void setEnabled(bool enabled); - void rehighlight(); - void reformatBlocks(int from, int charsRemoved, int charsAdded); - - QString definitionName(); - void setDefinitionName(const QString &name); - - QTextDocument *document() const { return m_document; } - bool useGenericHighlighter() const; - - bool syntaxInfoUpdated() const { return m_syntaxInfoUpdated == SyntaxHighlighter::State::Done; } - -signals: - void highlightingFinished(); - -private: - void applyFormatRanges(const QList &results); - void changeDocument(int from, int charsRemoved, int charsAdded); - - SyntaxHighlighterRunnerPrivate *d; - QPointer m_document = nullptr; - SyntaxHighlighter::State m_syntaxInfoUpdated = SyntaxHighlighter::State::Done; - - struct HighlightingStatus - { - int m_from = 0; - int m_addedChars = 0; - int m_current = 0; - int m_removedChars = 0; - int m_newFrom = 0; - bool m_interruptionRequested = false; - - void notInterrupted(int from, int charsRemoved, int charsAdded); - void interrupted(int from, int charsRemoved, int charsAdded); - void applyNewFrom(); - } m_highlightingStatus; - - bool m_useGenericHighlighter = false; - QString m_definitionName; - std::optional m_thread; - TextDocumentLayout::FoldValidator m_foldValidator; -}; - -} // namespace TextEditor - diff --git a/src/plugins/texteditor/textdocument.cpp b/src/plugins/texteditor/textdocument.cpp index 2636ad46e23..9d8133912c8 100644 --- a/src/plugins/texteditor/textdocument.cpp +++ b/src/plugins/texteditor/textdocument.cpp @@ -10,10 +10,10 @@ #include "tabsettings.h" #include "textdocumentlayout.h" #include "texteditor.h" +#include "texteditorsettings.h" #include "texteditortr.h" #include "textindenter.h" #include "typingsettings.h" -#include "syntaxhighlighterrunner.h" #include #include @@ -64,8 +64,6 @@ public: ~TextDocumentPrivate() { - if (m_highlighterRunner) - m_highlighterRunner->deleteLater(); } MultiTextCursor indentOrUnindent(const MultiTextCursor &cursor, bool doIndent, const TabSettings &tabSettings); @@ -101,7 +99,7 @@ public: TextMarks m_marksCache; // Marks not owned Utils::Guard m_modificationChangedGuard; - SyntaxHighlighterRunner *m_highlighterRunner = nullptr; + SyntaxHighlighter *m_highlighter = nullptr; }; MultiTextCursor TextDocumentPrivate::indentOrUnindent(const MultiTextCursor &cursors, @@ -462,8 +460,8 @@ void TextDocument::applyFontSettings() block = block.next(); } updateLayout(); - if (d->m_highlighterRunner) - d->m_highlighterRunner->setFontSettings(d->m_fontSettings); + if (d->m_highlighter) + d->m_highlighter->setFontSettings(d->m_fontSettings); } const FontSettings &TextDocument::fontSettings() const @@ -533,6 +531,15 @@ bool TextDocument::applyChangeSet(const ChangeSet &changeSet) // the blocks list must be sorted void TextDocument::setIfdefedOutBlocks(const QList &blocks) { + if (syntaxHighlighter() && !syntaxHighlighter()->syntaxHighlighterUpToDate()) { + connect(syntaxHighlighter(), + &SyntaxHighlighter::finished, + this, + [this, blocks] { setIfdefedOutBlocks(blocks); }, + Qt::SingleShotConnection); + return; + } + QTextDocument *doc = document(); auto documentLayout = qobject_cast(doc->documentLayout()); QTC_ASSERT(documentLayout, return); @@ -635,11 +642,6 @@ QTextDocument *TextDocument::document() const return &d->m_document; } -SyntaxHighlighterRunner *TextDocument::syntaxHighlighterRunner() const -{ - return d->m_highlighterRunner; -} - /*! * Saves the document to the file specified by \a fileName. If errors occur, * \a errorString contains their cause. @@ -911,26 +913,19 @@ bool TextDocument::reload(QString *errorString, ReloadFlag flag, ChangeType type return reload(errorString); } -void TextDocument::resetSyntaxHighlighter(const std::function &creator, - bool threaded) +void TextDocument::resetSyntaxHighlighter(const std::function &creator) { - delete d->m_highlighterRunner; - - static const std::optional envValue = []() -> std::optional { - const QString key("QTC_USE_THREADED_HIGHLIGHTER"); - if (qtcEnvironmentVariableIsSet(key)) { - const QString value = qtcEnvironmentVariable(key).toUpper(); - return value != "FALSE" && value != "0"; - } - return {}; - }(); - SyntaxHighlighter *highlighter = creator(); + highlighter->setParent(this); + highlighter->setDocument(this->document()); highlighter->setFontSettings(TextEditorSettings::fontSettings()); highlighter->setMimeType(mimeType()); - d->m_highlighterRunner = new SyntaxHighlighterRunner(highlighter, - document(), - envValue.value_or(threaded)); + d->m_highlighter = highlighter; +} + +SyntaxHighlighter *TextDocument::syntaxHighlighter() const +{ + return d->m_highlighter; } void TextDocument::cleanWhitespace(const QTextCursor &cursor) diff --git a/src/plugins/texteditor/textdocument.h b/src/plugins/texteditor/textdocument.h index 5879d9e9ec2..b3bf77e5442 100644 --- a/src/plugins/texteditor/textdocument.h +++ b/src/plugins/texteditor/textdocument.h @@ -34,7 +34,6 @@ class FontSettings; class IAssistProvider; class StorageSettings; class SyntaxHighlighter; -class SyntaxHighlighterRunner; class TabSettings; class TextDocumentPrivate; class TextMark; @@ -127,8 +126,8 @@ public: QTextDocument *document() const; using SyntaxHighLighterCreator = std::function; - void resetSyntaxHighlighter(const SyntaxHighLighterCreator &creator, bool threaded = false); - SyntaxHighlighterRunner *syntaxHighlighterRunner() const; + void resetSyntaxHighlighter(const SyntaxHighLighterCreator &creator); + SyntaxHighlighter *syntaxHighlighter() const; bool reload(QString *errorString, QTextCodec *codec); void cleanWhitespace(const QTextCursor &cursor); diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 42daeeff6d3..85bd4732baa 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -34,7 +34,6 @@ #include "texteditorsettings.h" #include "texteditortr.h" #include "typingsettings.h" -#include "syntaxhighlighterrunner.h" #include @@ -1935,8 +1934,8 @@ void TextEditorWidgetPrivate::foldLicenseHeader() QStringList commentMarker; QStringList docMarker; HighlighterHelper::Definition def; - if (SyntaxHighlighterRunner *highlighter = q->textDocument()->syntaxHighlighterRunner()) - def = HighlighterHelper::definitionForName(highlighter->definitionName()); + if (auto highlighter = qobject_cast(q->textDocument()->syntaxHighlighter())) + def = highlighter->definition(); if (def.isValid()) { for (const QString &marker : @@ -3494,10 +3493,10 @@ QByteArray TextEditorWidget::saveState() const bool TextEditorWidget::singleShotAfterHighlightingDone(std::function &&f) { - if (d->m_document->syntaxHighlighterRunner() - && !d->m_document->syntaxHighlighterRunner()->syntaxInfoUpdated()) { - connect(d->m_document->syntaxHighlighterRunner(), - &SyntaxHighlighterRunner::highlightingFinished, + if (d->m_document->syntaxHighlighter() + && !d->m_document->syntaxHighlighter()->syntaxHighlighterUpToDate()) { + connect(d->m_document->syntaxHighlighter(), + &SyntaxHighlighter::finished, this, [f = std::move(f)] { f(); }, Qt::SingleShotConnection); return true; @@ -3741,10 +3740,11 @@ void TextEditorWidgetPrivate::configureGenericHighlighter( const QString definitionFilesPath = TextEditorSettings::highlighterSettings().definitionFilesPath().toString(); - m_document->resetSyntaxHighlighter([definitionFilesPath] { - return new Highlighter(definitionFilesPath); + m_document->resetSyntaxHighlighter([definitionFilesPath, definition] { + auto highlighter = new Highlighter(definitionFilesPath); + highlighter->setDefinition(definition); + return highlighter; }); - m_document->syntaxHighlighterRunner()->setDefinitionName(definition.name()); m_document->setFontSettings(TextEditorSettings::fontSettings()); } @@ -3769,8 +3769,8 @@ void TextEditorWidgetPrivate::setupFromDefinition(const KSyntaxHighlighting::Def KSyntaxHighlighting::Definition TextEditorWidgetPrivate::currentDefinition() { - if (SyntaxHighlighterRunner *highlighter = m_document->syntaxHighlighterRunner()) - return HighlighterHelper::definitionForName(highlighter->definitionName()); + if (auto *highlighter = qobject_cast(m_document->syntaxHighlighter())) + return highlighter->definition(); return {}; } @@ -5127,7 +5127,8 @@ void TextEditorWidgetPrivate::setupBlockLayout(const PaintEventData &data, blockData.layout = data.block.layout(); QTextOption option = blockData.layout->textOption(); - if (data.suppressSyntaxInIfdefedOutBlock && TextDocumentLayout::ifdefedOut(data.block)) { + if (data.suppressSyntaxInIfdefedOutBlock + && TextDocumentLayout::ifdefedOut(data.block)) { option.setFlags(option.flags() | QTextOption::SuppressColors); painter.setPen(data.ifdefedOutFormat.foreground().color()); } else { @@ -5746,8 +5747,8 @@ void TextEditorWidgetPrivate::paintCodeFolding(QPainter &painter, TextBlockUserData *nextBlockUserData = TextDocumentLayout::textUserData(nextBlock); bool drawBox = nextBlockUserData - && TextDocumentLayout::foldingIndent(data.block) < nextBlockUserData->foldingIndent(); - + && TextDocumentLayout::foldingIndent(data.block) + < nextBlockUserData->foldingIndent(); const int blockNumber = data.block.blockNumber(); bool active = blockNumber == extraAreaHighlightFoldBlockNumber; @@ -8183,7 +8184,7 @@ void TextEditorWidget::setDisplaySettings(const DisplaySettings &ds) optionFlags.setFlag(QTextOption::AddSpaceForLineAndParagraphSeparators); optionFlags.setFlag(QTextOption::ShowTabsAndSpaces, ds.m_visualizeWhitespace); if (optionFlags != currentOptionFlags) { - if (SyntaxHighlighterRunner *highlighter = textDocument()->syntaxHighlighterRunner()) + if (SyntaxHighlighter *highlighter = textDocument()->syntaxHighlighter()) highlighter->rehighlight(); QTextOption option = document()->defaultTextOption(); option.setFlags(optionFlags); diff --git a/src/plugins/texteditor/texteditor.qbs b/src/plugins/texteditor/texteditor.qbs index 41fe08d51b5..30a4712b731 100644 --- a/src/plugins/texteditor/texteditor.qbs +++ b/src/plugins/texteditor/texteditor.qbs @@ -124,8 +124,6 @@ QtcPlugin { "storagesettings.h", "syntaxhighlighter.cpp", "syntaxhighlighter.h", - "syntaxhighlighterrunner.cpp", - "syntaxhighlighterrunner.h", "tabsettings.cpp", "tabsettings.h", "tabsettingswidget.cpp", diff --git a/src/plugins/vcsbase/baseannotationhighlighter.cpp b/src/plugins/vcsbase/baseannotationhighlighter.cpp index e3dce5ba266..0809d2c5237 100644 --- a/src/plugins/vcsbase/baseannotationhighlighter.cpp +++ b/src/plugins/vcsbase/baseannotationhighlighter.cpp @@ -4,6 +4,7 @@ #include "baseannotationhighlighter.h" #include +#include #include #include @@ -163,7 +164,7 @@ void BaseAnnotationHighlighter::rehighlight() return; setChangeNumbers(changes); - TextEditor::SyntaxHighlighter::rehighlight(); + SyntaxHighlighter::rehighlight(); } } // namespace VcsBase diff --git a/src/plugins/vcsbase/vcsbaseeditor.cpp b/src/plugins/vcsbase/vcsbaseeditor.cpp index 38bb004a2d6..13338584bf1 100644 --- a/src/plugins/vcsbase/vcsbaseeditor.cpp +++ b/src/plugins/vcsbase/vcsbaseeditor.cpp @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include @@ -821,7 +821,7 @@ void VcsBaseEditorWidget::setFileLogAnnotateEnabled(bool e) void VcsBaseEditorWidget::setHighlightingEnabled(bool e) { - textDocument()->syntaxHighlighterRunner()->setEnabled(e); + textDocument()->syntaxHighlighter()->setEnabled(e); } FilePath VcsBaseEditorWidget::workingDirectory() const @@ -1102,7 +1102,7 @@ void VcsBaseEditorWidget::slotActivateAnnotation() disconnect(this, &QPlainTextEdit::textChanged, this, &VcsBaseEditorWidget::slotActivateAnnotation); - if (SyntaxHighlighterRunner *ah = textDocument()->syntaxHighlighterRunner()) { + if (SyntaxHighlighter *ah = textDocument()->syntaxHighlighter()) { ah->rehighlight(); } else { BaseAnnotationHighlighterCreator creator = annotationHighlighterCreator(); diff --git a/tests/auto/texteditor/highlighter/tst_highlighter.cpp b/tests/auto/texteditor/highlighter/tst_highlighter.cpp index 9044065a019..e0806382982 100644 --- a/tests/auto/texteditor/highlighter/tst_highlighter.cpp +++ b/tests/auto/texteditor/highlighter/tst_highlighter.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include @@ -32,7 +31,7 @@ private slots: private: QTextDocument *doc = nullptr; - SyntaxHighlighterRunner *highlighterRunner = nullptr; + SyntaxHighlighter *highlighter = nullptr; FontSettings fontsettings; QHash formatHash; QTextCharFormat whitespaceFormat; @@ -58,8 +57,7 @@ Last)"; doc = new QTextDocument(); doc->setPlainText(text); - auto highlighter = new SyntaxHighlighter(doc, fontsettings); - highlighterRunner = new SyntaxHighlighterRunner(highlighter, doc, false); + highlighter = new SyntaxHighlighter(doc, fontsettings); } static const HighlightingResults &highlightingResults() @@ -77,7 +75,7 @@ void tst_highlighter::test_setExtraAdditionalFormats() { QCOMPARE(doc->blockCount(), 4); - SemanticHighlighter::setExtraAdditionalFormats(highlighterRunner, highlightingResults(), formatHash); + SemanticHighlighter::setExtraAdditionalFormats(highlighter, highlightingResults(), formatHash); for (auto block = doc->firstBlock(); block.isValid(); block = block.next()) { QVERIFY(block.blockNumber() < 4); @@ -140,17 +138,17 @@ void tst_highlighter::test_clearExtraFormats() { QCOMPARE(doc->blockCount(), 4); - SemanticHighlighter::setExtraAdditionalFormats(highlighterRunner, highlightingResults(), formatHash); + SemanticHighlighter::setExtraAdditionalFormats(highlighter, highlightingResults(), formatHash); QTextBlock firstBlock = doc->findBlockByNumber(0); QTextBlock spacesLineBlock = doc->findBlockByNumber(1); QTextBlock emptyLineBlock = doc->findBlockByNumber(2); QTextBlock lastBlock = doc->findBlockByNumber(3); - highlighterRunner->clearExtraFormats({emptyLineBlock.blockNumber()}); + highlighter->clearExtraFormats(emptyLineBlock); QVERIFY(emptyLineBlock.layout()->formats().isEmpty()); - highlighterRunner->clearExtraFormats({spacesLineBlock.blockNumber()}); + highlighter->clearExtraFormats(spacesLineBlock); auto formats = spacesLineBlock.layout()->formats(); // the spaces are not extra formats and should remain when clearing extra formats @@ -185,7 +183,7 @@ void tst_highlighter::test_clearExtraFormats() QCOMPARE(formats.at(1).start, 0); QCOMPARE(formats.at(1).length, 5); - highlighterRunner->clearAllExtraFormats(); + highlighter->clearAllExtraFormats(); QVERIFY(firstBlock.layout()->formats().isEmpty()); QVERIFY(emptyLineBlock.layout()->formats().isEmpty()); @@ -221,7 +219,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QFutureInterface fiOld; fiOld.reportResults(highlightingResults()); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fiOld.future(), 2, 0, @@ -229,7 +227,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() auto formats = firstBlock.layout()->formats(); QVERIFY(formats.isEmpty()); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fiOld.future(), 0, 2, @@ -254,7 +252,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QCOMPARE(formats.at(1).start, 11); QCOMPARE(formats.at(1).length, 1); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fiOld.future(), 3, 6, @@ -280,7 +278,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QFutureInterface fiNew; fiNew.reportResults(newResults); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fiNew.future(), 0, 3, @@ -294,7 +292,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QCOMPARE(formats.at(0).start, 0); QCOMPARE(formats.at(0).length, 1); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fiNew.future(), 3, 4, @@ -305,14 +303,14 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QVERIFY(formats.isEmpty()); // QTCREATORBUG-29218 - highlighterRunner->clearAllExtraFormats(); + highlighter->clearAllExtraFormats(); const HighlightingResults bug29218Results{HighlightingResult(1, 1, 2, 0), HighlightingResult(1, 3, 2, 1)}; QFutureInterface fi29218; fi29218.reportResults(bug29218Results); formats = firstBlock.layout()->formats(); QVERIFY(formats.isEmpty()); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fi29218.future(), 0, 1, @@ -323,7 +321,7 @@ void tst_highlighter::test_incrementalApplyAdditionalFormats() QCOMPARE(formats.at(0).format.fontOverline(), false); QCOMPARE(formats.at(0).start, 0); QCOMPARE(formats.at(0).length, 2); - SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighterRunner, + SemanticHighlighter::incrementalApplyExtraAdditionalFormats(highlighter, fi29218.future(), 1, 2, @@ -347,7 +345,7 @@ void tst_highlighter::test_preeditText() QTextBlock firstBlock = doc->findBlockByNumber(0); firstBlock.layout()->setPreeditArea(2, "uaf"); - SemanticHighlighter::setExtraAdditionalFormats(highlighterRunner, highlightingResults(), formatHash); + SemanticHighlighter::setExtraAdditionalFormats(highlighter, highlightingResults(), formatHash); auto formats = firstBlock.layout()->formats(); QCOMPARE(formats.size(), 2); @@ -366,7 +364,7 @@ void tst_highlighter::cleanup() { delete doc; doc = nullptr; - highlighterRunner = nullptr; + highlighter = nullptr; } } // namespace TextEditor From 1d0246a89a360cdc67d111ce1ac0ccf1cb288d66 Mon Sep 17 00:00:00 2001 From: Sami Shalayel Date: Mon, 18 Mar 2024 16:21:32 +0100 Subject: [PATCH 0090/1060] qmljshoverhandler: do not show tooltips when qmlls is enabled Check if qmlls is enabled before showing tooltips from the QtC's code model. This way, other hoverhandlers, like the one used for language servers, have the possibility to show their tooltip. Task-number: QTCREATORBUG-29826 Change-Id: I5d879c7d4c04a27bc668e8900f54984788b02727 Reviewed-by: Fabian Kosmale --- src/plugins/qmljseditor/qmljshoverhandler.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/plugins/qmljseditor/qmljshoverhandler.cpp b/src/plugins/qmljseditor/qmljshoverhandler.cpp index 3f7d3a5c110..9dcc220e253 100644 --- a/src/plugins/qmljseditor/qmljshoverhandler.cpp +++ b/src/plugins/qmljseditor/qmljshoverhandler.cpp @@ -7,6 +7,7 @@ #include "qmljseditordocument.h" #include "qmljseditortr.h" #include "qmljshoverhandler.h" +#include "qmljseditingsettingspage.h" #include #include @@ -371,6 +372,12 @@ void QmlJSHoverHandler::reset() void QmlJSHoverHandler::operateTooltip(TextEditorWidget *editorWidget, const QPoint &point) { + // disable hoverhandling in case qmlls is enabled + if (QmlJsEditingSettings::get().qmllsSettings().useQmlls) { + BaseHoverHandler::operateTooltip(editorWidget, point); + return; + } + if (toolTip().isEmpty()) Utils::ToolTip::hide(); else if (m_colorTip.isValid()) From 7561612b3a041226a8cca5c4648e676d0dafc055 Mon Sep 17 00:00:00 2001 From: Dominik Holland Date: Thu, 7 Mar 2024 16:59:16 +0100 Subject: [PATCH 0091/1060] RunControl: Also check for a matching runConfig when creating a RunWorker Change-Id: Ic26b41e878ed2b8b20099b62ed1c122966165665 Reviewed-by: hjk --- src/plugins/boot2qt/qdbdevicedebugsupport.cpp | 1 + src/plugins/projectexplorer/runcontrol.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/boot2qt/qdbdevicedebugsupport.cpp b/src/plugins/boot2qt/qdbdevicedebugsupport.cpp index d9f3d647380..5de1c1fe231 100644 --- a/src/plugins/boot2qt/qdbdevicedebugsupport.cpp +++ b/src/plugins/boot2qt/qdbdevicedebugsupport.cpp @@ -298,6 +298,7 @@ public: setProduct(); addSupportedRunMode("PerfRecorder"); addSupportedDeviceType(Qdb::Constants::QdbLinuxOsType); + addSupportedRunConfig(Constants::QdbRunConfigurationId); } }; diff --git a/src/plugins/projectexplorer/runcontrol.cpp b/src/plugins/projectexplorer/runcontrol.cpp index 0a7122560a6..f5f24b05c79 100644 --- a/src/plugins/projectexplorer/runcontrol.cpp +++ b/src/plugins/projectexplorer/runcontrol.cpp @@ -500,7 +500,7 @@ RunWorker *RunControl::createWorker(Id workerId) { const Id deviceType = DeviceTypeKitAspect::deviceTypeId(d->kit); for (RunWorkerFactory *factory : std::as_const(g_runWorkerFactories)) { - if (factory->canCreate(workerId, deviceType, QString())) + if (factory->canCreate(workerId, deviceType, d->runConfigId.toString())) return factory->create(this); } return nullptr; From fc8f1bc47df91e829c569cb5977677b835b86f88 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Fri, 22 Mar 2024 09:48:16 +0100 Subject: [PATCH 0092/1060] LanguageClient: pimpl DiagnosticManager Change-Id: I4b5a2b0fe9818b676d08fd00f33b70366394539d Reviewed-by: Christian Stenger --- .../languageclient/diagnosticmanager.cpp | 88 ++++++++++++------- .../languageclient/diagnosticmanager.h | 21 +---- 2 files changed, 60 insertions(+), 49 deletions(-) diff --git a/src/plugins/languageclient/diagnosticmanager.cpp b/src/plugins/languageclient/diagnosticmanager.cpp index dd58407f9e0..da5a37a5f06 100644 --- a/src/plugins/languageclient/diagnosticmanager.cpp +++ b/src/plugins/languageclient/diagnosticmanager.cpp @@ -46,9 +46,35 @@ public: } }; +struct VersionedDiagnostics +{ + std::optional version; + QList diagnostics; +}; + +class Marks +{ +public: + ~Marks() { qDeleteAll(marks); } + bool enabled = true; + QList marks; +}; + +class DiagnosticManager::DiagnosticManagerPrivate +{ +public: + DiagnosticManagerPrivate(Client *client) + : m_client(client) + {} + + QMap m_diagnostics; + QMap m_marks; + Client *m_client; + Utils::Id m_extraSelectionsId = TextEditorWidget::CodeWarningsSelection; +}; + DiagnosticManager::DiagnosticManager(Client *client) - : m_client(client) - , m_extraSelectionsId(TextEditorWidget::CodeWarningsSelection) + : d(std::make_unique(client)) { } @@ -62,16 +88,16 @@ void DiagnosticManager::setDiagnostics(const FilePath &filePath, const std::optional &version) { hideDiagnostics(filePath); - m_diagnostics[filePath] = {version, filteredDiagnostics(diagnostics)}; + d->m_diagnostics[filePath] = {version, filteredDiagnostics(diagnostics)}; } void DiagnosticManager::hideDiagnostics(const Utils::FilePath &filePath) { if (auto doc = TextDocument::textDocumentForFilePath(filePath)) { for (BaseTextEditor *editor : BaseTextEditor::textEditorsForDocument(doc)) - editor->editorWidget()->setExtraSelections(m_extraSelectionsId, {}); + editor->editorWidget()->setExtraSelections(d->m_extraSelectionsId, {}); } - m_marks.remove(filePath); + d->m_marks.remove(filePath); } QList DiagnosticManager::filteredDiagnostics(const QList &diagnostics) const @@ -82,7 +108,7 @@ QList DiagnosticManager::filteredDiagnostics(const QList void DiagnosticManager::disableDiagnostics(TextEditor::TextDocument *document) { - Marks &marks = m_marks[document->filePath()]; + Marks &marks = d->m_marks[document->filePath()]; if (!marks.enabled) return; for (TextEditor::TextMark *mark : marks.marks) @@ -94,11 +120,11 @@ void DiagnosticManager::showDiagnostics(const FilePath &filePath, int version) { if (TextDocument *doc = TextDocument::textDocumentForFilePath(filePath)) { QList extraSelections; - const VersionedDiagnostics &versionedDiagnostics = m_diagnostics.value(filePath); + const VersionedDiagnostics &versionedDiagnostics = d->m_diagnostics.value(filePath); if (versionedDiagnostics.version.value_or(version) == version && !versionedDiagnostics.diagnostics.isEmpty()) { - Marks &marks = m_marks[filePath]; - const bool isProjectFile = m_client->fileBelongsToProject(filePath); + Marks &marks = d->m_marks[filePath]; + const bool isProjectFile = d->m_client->fileBelongsToProject(filePath); for (const Diagnostic &diagnostic : versionedDiagnostics.diagnostics) { const QTextEdit::ExtraSelection selection = createDiagnosticSelection(diagnostic, doc->document()); @@ -112,17 +138,22 @@ void DiagnosticManager::showDiagnostics(const FilePath &filePath, int version) } for (BaseTextEditor *editor : BaseTextEditor::textEditorsForDocument(doc)) - editor->editorWidget()->setExtraSelections(m_extraSelectionsId, extraSelections); + editor->editorWidget()->setExtraSelections(d->m_extraSelectionsId, extraSelections); } } +Client *DiagnosticManager::client() const +{ + return d->m_client; +} + TextEditor::TextMark *DiagnosticManager::createTextMark(TextDocument *doc, const Diagnostic &diagnostic, bool /*isProjectFile*/) const { static const QIcon icon = Icon::fromTheme("edit-copy"); static const QString tooltip = Tr::tr("Copy to Clipboard"); - auto mark = new TextMark(doc, diagnostic, m_client); + auto mark = new TextMark(doc, diagnostic, d->m_client); mark->setActionsProvider([text = diagnostic.message()] { QAction *action = new QAction(); action->setIcon(icon); @@ -153,13 +184,13 @@ QTextEdit::ExtraSelection DiagnosticManager::createDiagnosticSelection( void DiagnosticManager::setExtraSelectionsId(const Utils::Id &extraSelectionsId) { // this function should be called before any diagnostics are handled - QTC_CHECK(m_diagnostics.isEmpty()); - m_extraSelectionsId = extraSelectionsId; + QTC_CHECK(d->m_diagnostics.isEmpty()); + d->m_extraSelectionsId = extraSelectionsId; } void DiagnosticManager::forAllMarks(std::function func) { - for (const Marks &marks : std::as_const(m_marks)) { + for (const Marks &marks : std::as_const(d->m_marks)) { for (TextEditor::TextMark *mark : marks.marks) func(mark); } @@ -167,18 +198,18 @@ void DiagnosticManager::forAllMarks(std::function void DiagnosticManager::clearDiagnostics() { - for (const Utils::FilePath &path : m_diagnostics.keys()) + for (const Utils::FilePath &path : d->m_diagnostics.keys()) hideDiagnostics(path); - m_diagnostics.clear(); - QTC_ASSERT(m_marks.isEmpty(), m_marks.clear()); + d->m_diagnostics.clear(); + QTC_ASSERT(d->m_marks.isEmpty(), d->m_marks.clear()); } QList DiagnosticManager::diagnosticsAt(const FilePath &filePath, const QTextCursor &cursor) const { - const int documentRevision = m_client->documentVersion(filePath); - auto it = m_diagnostics.find(filePath); - if (it == m_diagnostics.end()) + const int documentRevision = d->m_client->documentVersion(filePath); + auto it = d->m_diagnostics.find(filePath); + if (it == d->m_diagnostics.end()) return {}; if (documentRevision != it->version.value_or(documentRevision)) return {}; @@ -193,10 +224,10 @@ bool DiagnosticManager::hasDiagnostic(const FilePath &filePath, { if (!doc) return false; - const auto it = m_diagnostics.find(filePath); - if (it == m_diagnostics.end()) + const auto it = d->m_diagnostics.find(filePath); + if (it == d->m_diagnostics.end()) return {}; - const int revision = m_client->documentVersion(filePath); + const int revision = d->m_client->documentVersion(filePath); if (revision != it->version.value_or(revision)) return false; return it->diagnostics.contains(diag); @@ -205,18 +236,13 @@ bool DiagnosticManager::hasDiagnostic(const FilePath &filePath, bool DiagnosticManager::hasDiagnostics(const TextDocument *doc) const { const FilePath docPath = doc->filePath(); - const auto it = m_diagnostics.find(docPath); - if (it == m_diagnostics.end()) + const auto it = d->m_diagnostics.find(docPath); + if (it == d->m_diagnostics.end()) return {}; - const int revision = m_client->documentVersion(docPath); + const int revision = d->m_client->documentVersion(docPath); if (revision != it->version.value_or(revision)) return false; return !it->diagnostics.isEmpty(); } -DiagnosticManager::Marks::~Marks() -{ - qDeleteAll(marks); -} - } // namespace LanguageClient diff --git a/src/plugins/languageclient/diagnosticmanager.h b/src/plugins/languageclient/diagnosticmanager.h index a4ad23e1b98..6d1626029b1 100644 --- a/src/plugins/languageclient/diagnosticmanager.h +++ b/src/plugins/languageclient/diagnosticmanager.h @@ -54,7 +54,7 @@ signals: void textMarkCreated(const Utils::FilePath &path); protected: - Client *client() const { return m_client; } + Client *client() const; virtual TextEditor::TextMark *createTextMark(TextEditor::TextDocument *doc, const LanguageServerProtocol::Diagnostic &diagnostic, bool isProjectFile) const; @@ -64,24 +64,9 @@ protected: void setExtraSelectionsId(const Utils::Id &extraSelectionsId); void forAllMarks(std::function func); - private: - struct VersionedDiagnostics - { - std::optional version; - QList diagnostics; - }; - QMap m_diagnostics; - class Marks - { - public: - ~Marks(); - bool enabled = true; - QList marks; - }; - QMap m_marks; - Client *m_client; - Utils::Id m_extraSelectionsId; + class DiagnosticManagerPrivate; + std::unique_ptr d; }; } // namespace LanguageClient From 3ca0deef536d33163256fee9a50895f1ee5e4a75 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 15 Mar 2024 16:02:50 +0100 Subject: [PATCH 0093/1060] CppEditor: Move ClangdSettings into a dedicated set of files They were originally put alongside the CppCodeModelSettings for simplicity, but there is no coupling (anymore?) between these two classes. Change-Id: Ic24df109b74a5b5c39de073c938c6de12f4aa319 Reviewed-by: Reviewed-by: David Schulz --- src/plugins/clangcodemodel/clangdclient.cpp | 1 + src/plugins/clangcodemodel/clangdclient.h | 2 +- .../clangmodelmanagersupport.cpp | 2 +- src/plugins/clangcodemodel/clangtextmark.cpp | 2 +- src/plugins/clangcodemodel/clangutils.cpp | 2 +- src/plugins/cppeditor/CMakeLists.txt | 1 + src/plugins/cppeditor/clangdsettings.cpp | 491 ++++++++++++++++++ src/plugins/cppeditor/clangdsettings.h | 162 ++++++ .../cppeditor/cppcodemodelsettings.cpp | 470 ----------------- src/plugins/cppeditor/cppcodemodelsettings.h | 150 ------ .../cppeditor/cppcodemodelsettingspage.cpp | 2 + src/plugins/cppeditor/cppeditor.qbs | 2 + src/plugins/cppeditor/cpptoolsreuse.cpp | 1 + .../followsymbol_switchmethoddecldef_test.cpp | 1 + 14 files changed, 665 insertions(+), 624 deletions(-) create mode 100644 src/plugins/cppeditor/clangdsettings.cpp create mode 100644 src/plugins/cppeditor/clangdsettings.h diff --git a/src/plugins/clangcodemodel/clangdclient.cpp b/src/plugins/clangcodemodel/clangdclient.cpp index bf048486524..248ef69b364 100644 --- a/src/plugins/clangcodemodel/clangdclient.cpp +++ b/src/plugins/clangcodemodel/clangdclient.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include diff --git a/src/plugins/clangcodemodel/clangdclient.h b/src/plugins/clangcodemodel/clangdclient.h index fbe2a31bbc6..0274bffc24f 100644 --- a/src/plugins/clangcodemodel/clangdclient.h +++ b/src/plugins/clangcodemodel/clangdclient.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include #include #include diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp index 3d8965248f8..79b4273771b 100644 --- a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp +++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/plugins/clangcodemodel/clangtextmark.cpp b/src/plugins/clangcodemodel/clangtextmark.cpp index 80e2956021f..d22127d3dd4 100644 --- a/src/plugins/clangcodemodel/clangtextmark.cpp +++ b/src/plugins/clangcodemodel/clangtextmark.cpp @@ -12,9 +12,9 @@ #include #include +#include #include #include -#include #include diff --git a/src/plugins/clangcodemodel/clangutils.cpp b/src/plugins/clangcodemodel/clangutils.cpp index 5e7f454d5ee..1b2550cbd3d 100644 --- a/src/plugins/clangcodemodel/clangutils.cpp +++ b/src/plugins/clangcodemodel/clangutils.cpp @@ -9,8 +9,8 @@ #include #include #include +#include #include -#include #include #include #include diff --git a/src/plugins/cppeditor/CMakeLists.txt b/src/plugins/cppeditor/CMakeLists.txt index ec5ad89cea3..93c37beaca6 100644 --- a/src/plugins/cppeditor/CMakeLists.txt +++ b/src/plugins/cppeditor/CMakeLists.txt @@ -93,6 +93,7 @@ add_qtc_plugin(CppEditor cppvirtualfunctionassistprovider.cpp cppvirtualfunctionassistprovider.h cppvirtualfunctionproposalitem.cpp cppvirtualfunctionproposalitem.h cppworkingcopy.cpp cppworkingcopy.h + clangdsettings.cpp clangdsettings.h cursorineditor.h doxygengenerator.cpp doxygengenerator.h editordocumenthandle.cpp editordocumenthandle.h diff --git a/src/plugins/cppeditor/clangdsettings.cpp b/src/plugins/cppeditor/clangdsettings.cpp new file mode 100644 index 00000000000..b5352af6d83 --- /dev/null +++ b/src/plugins/cppeditor/clangdsettings.cpp @@ -0,0 +1,491 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "clangdsettings.h" + +#include "clangdiagnosticconfigsmodel.h" +#include "cppeditorconstants.h" +#include "cppeditortr.h" +#include "cpptoolsreuse.h" + +#include +#include +#include +#include +#include + +#include +#include + +using namespace Utils; + +namespace CppEditor { + +static FilePath g_defaultClangdFilePath; +static FilePath fallbackClangdFilePath() +{ + if (g_defaultClangdFilePath.exists()) + return g_defaultClangdFilePath; + return Environment::systemEnvironment().searchInPath("clangd"); +} + +static Id initialClangDiagnosticConfigId() { return Constants::CPP_CLANG_DIAG_CONFIG_BUILDSYSTEM; } + +static Key clangdSettingsKey() { return "ClangdSettings"; } +static Key useClangdKey() { return "UseClangdV7"; } +static Key clangdPathKey() { return "ClangdPath"; } +static Key clangdIndexingKey() { return "ClangdIndexing"; } +static Key clangdProjectIndexPathKey() { return "ClangdProjectIndexPath"; } +static Key clangdSessionIndexPathKey() { return "ClangdSessionIndexPath"; } +static Key clangdIndexingPriorityKey() { return "ClangdIndexingPriority"; } +static Key clangdHeaderSourceSwitchModeKey() { return "ClangdHeaderSourceSwitchMode"; } +static Key clangdCompletionRankingModelKey() { return "ClangdCompletionRankingModel"; } +static Key clangdHeaderInsertionKey() { return "ClangdHeaderInsertion"; } +static Key clangdThreadLimitKey() { return "ClangdThreadLimit"; } +static Key clangdDocumentThresholdKey() { return "ClangdDocumentThreshold"; } +static Key clangdSizeThresholdEnabledKey() { return "ClangdSizeThresholdEnabled"; } +static Key clangdSizeThresholdKey() { return "ClangdSizeThreshold"; } +static Key useGlobalSettingsKey() { return "useGlobalSettings"; } +static Key clangdblockIndexingSettingsKey() { return "blockIndexing"; } +static Key sessionsWithOneClangdKey() { return "SessionsWithOneClangd"; } +static Key diagnosticConfigIdKey() { return "diagnosticConfigId"; } +static Key checkedHardwareKey() { return "checkedHardware"; } +static Key completionResultsKey() { return "completionResults"; } + +QString ClangdSettings::priorityToString(const IndexingPriority &priority) +{ + switch (priority) { + case IndexingPriority::Background: return "background"; + case IndexingPriority::Normal: return "normal"; + case IndexingPriority::Low: return "low"; + case IndexingPriority::Off: return {}; + } + return {}; +} + +QString ClangdSettings::priorityToDisplayString(const IndexingPriority &priority) +{ + switch (priority) { + case IndexingPriority::Background: return Tr::tr("Background Priority"); + case IndexingPriority::Normal: return Tr::tr("Normal Priority"); + case IndexingPriority::Low: return Tr::tr("Low Priority"); + case IndexingPriority::Off: return Tr::tr("Off"); + } + return {}; +} + +QString ClangdSettings::headerSourceSwitchModeToDisplayString(HeaderSourceSwitchMode mode) +{ + switch (mode) { + case HeaderSourceSwitchMode::BuiltinOnly: return Tr::tr("Use Built-in Only"); + case HeaderSourceSwitchMode::ClangdOnly: return Tr::tr("Use Clangd Only"); + case HeaderSourceSwitchMode::Both: return Tr::tr("Try Both"); + } + return {}; +} + +QString ClangdSettings::rankingModelToCmdLineString(CompletionRankingModel model) +{ + switch (model) { + case CompletionRankingModel::Default: break; + case CompletionRankingModel::DecisionForest: return "decision_forest"; + case CompletionRankingModel::Heuristics: return "heuristics"; + } + QTC_ASSERT(false, return {}); +} + +QString ClangdSettings::rankingModelToDisplayString(CompletionRankingModel model) +{ + switch (model) { + case CompletionRankingModel::Default: return Tr::tr("Default"); + case CompletionRankingModel::DecisionForest: return Tr::tr("Decision Forest"); + case CompletionRankingModel::Heuristics: return Tr::tr("Heuristics"); + } + QTC_ASSERT(false, return {}); +} + +QString ClangdSettings::defaultProjectIndexPathTemplate() +{ + return QDir::toNativeSeparators("%{BuildConfig:BuildDirectory:FilePath}/.qtc_clangd"); +} + +QString ClangdSettings::defaultSessionIndexPathTemplate() +{ + return QDir::toNativeSeparators("%{IDE:UserResourcePath}/.qtc_clangd/%{Session:FileBaseName}"); +} + +ClangdSettings &ClangdSettings::instance() +{ + static ClangdSettings settings; + return settings; +} + +ClangdSettings::ClangdSettings() +{ + loadSettings(); + const auto sessionMgr = Core::SessionManager::instance(); + connect(sessionMgr, &Core::SessionManager::sessionRemoved, this, [this](const QString &name) { + m_data.sessionsWithOneClangd.removeOne(name); + }); + connect(sessionMgr, + &Core::SessionManager::sessionRenamed, + this, + [this](const QString &oldName, const QString &newName) { + const auto index = m_data.sessionsWithOneClangd.indexOf(oldName); + if (index != -1) + m_data.sessionsWithOneClangd[index] = newName; + }); +} + +bool ClangdSettings::useClangd() const +{ + return m_data.useClangd && clangdVersion(clangdFilePath()) >= minimumClangdVersion(); +} + +void ClangdSettings::setUseClangd(bool use) { instance().m_data.useClangd = use; } + +void ClangdSettings::setUseClangdAndSave(bool use) +{ + setUseClangd(use); + instance().saveSettings(); +} + +bool ClangdSettings::hardwareFulfillsRequirements() +{ + instance().m_data.haveCheckedHardwareReqirements = true; + instance().saveSettings(); + const quint64 minRam = quint64(12) * 1024 * 1024 * 1024; + const std::optional totalRam = Utils::HostOsInfo::totalMemoryInstalledInBytes(); + return !totalRam || *totalRam >= minRam; +} + +bool ClangdSettings::haveCheckedHardwareRequirements() +{ + return instance().data().haveCheckedHardwareReqirements; +} + +void ClangdSettings::setDefaultClangdPath(const FilePath &filePath) +{ + g_defaultClangdFilePath = filePath; +} + +void ClangdSettings::setCustomDiagnosticConfigs(const ClangDiagnosticConfigs &configs) +{ + if (instance().customDiagnosticConfigs() == configs) + return; + instance().m_data.customDiagnosticConfigs = configs; + instance().saveSettings(); +} + +FilePath ClangdSettings::clangdFilePath() const +{ + if (!m_data.executableFilePath.isEmpty()) + return m_data.executableFilePath; + return fallbackClangdFilePath(); +} + +FilePath ClangdSettings::projectIndexPath(const Utils::MacroExpander &expander) const +{ + return FilePath::fromUserInput(expander.expand(m_data.projectIndexPathTemplate)); +} + +FilePath ClangdSettings::sessionIndexPath(const Utils::MacroExpander &expander) const +{ + return FilePath::fromUserInput(expander.expand(m_data.sessionIndexPathTemplate)); +} + +bool ClangdSettings::sizeIsOkay(const Utils::FilePath &fp) const +{ + return !sizeThresholdEnabled() || sizeThresholdInKb() * 1024 >= fp.fileSize(); +} + +ClangDiagnosticConfigs ClangdSettings::customDiagnosticConfigs() const +{ + return m_data.customDiagnosticConfigs; +} + +Id ClangdSettings::diagnosticConfigId() const +{ + if (!diagnosticConfigsModel().hasConfigWithId(m_data.diagnosticConfigId)) + return initialClangDiagnosticConfigId(); + return m_data.diagnosticConfigId; +} + +ClangDiagnosticConfig ClangdSettings::diagnosticConfig() const +{ + return diagnosticConfigsModel(customDiagnosticConfigs()).configWithId(diagnosticConfigId()); +} + +ClangdSettings::Granularity ClangdSettings::granularity() const +{ + if (m_data.sessionsWithOneClangd.contains(Core::SessionManager::activeSession())) + return Granularity::Session; + return Granularity::Project; +} + +void ClangdSettings::setData(const Data &data) +{ + if (this == &instance() && data != m_data) { + m_data = data; + saveSettings(); + emit changed(); + } +} + +static FilePath getClangHeadersPathFromClang(const FilePath &clangdFilePath) +{ + const FilePath clangFilePath = clangdFilePath.absolutePath().pathAppended("clang") + .withExecutableSuffix(); + if (!clangFilePath.exists()) + return {}; + Process clang; + clang.setCommand({clangFilePath, {"-print-resource-dir"}}); + clang.start(); + if (!clang.waitForFinished()) + return {}; + const FilePath resourceDir = FilePath::fromUserInput(QString::fromLocal8Bit( + clang.rawStdOut().trimmed())); + if (resourceDir.isEmpty() || !resourceDir.exists()) + return {}; + const FilePath includeDir = resourceDir.pathAppended("include"); + if (!includeDir.exists()) + return {}; + return includeDir; +} + +static FilePath getClangHeadersPath(const FilePath &clangdFilePath) +{ + const FilePath headersPath = getClangHeadersPathFromClang(clangdFilePath); + if (!headersPath.isEmpty()) + return headersPath; + + const QVersionNumber version = Utils::clangdVersion(clangdFilePath); + QTC_ASSERT(!version.isNull(), return {}); + static const QStringList libDirs{"lib", "lib64"}; + const QStringList versionStrings{QString::number(version.majorVersion()), version.toString()}; + for (const QString &libDir : libDirs) { + for (const QString &versionString : versionStrings) { + const FilePath includePath = clangdFilePath.absolutePath().parentDir() + .pathAppended(libDir).pathAppended("clang") + .pathAppended(versionString).pathAppended("include"); + if (includePath.exists()) + return includePath; + } + } + QTC_CHECK(false); + return {}; +} + +FilePath ClangdSettings::clangdIncludePath() const +{ + QTC_ASSERT(useClangd(), return {}); + FilePath clangdPath = clangdFilePath(); + QTC_ASSERT(!clangdPath.isEmpty() && clangdPath.exists(), return {}); + static QHash headersPathCache; + const auto it = headersPathCache.constFind(clangdPath); + if (it != headersPathCache.constEnd()) + return *it; + const FilePath headersPath = getClangHeadersPath(clangdPath); + if (!headersPath.isEmpty()) + headersPathCache.insert(clangdPath, headersPath); + return headersPath; +} + +FilePath ClangdSettings::clangdUserConfigFilePath() +{ + return FilePath::fromString( + QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)) + / "clangd/config.yaml"; +} + +void ClangdSettings::loadSettings() +{ + const auto settings = Core::ICore::settings(); + + m_data.fromMap(Utils::storeFromSettings(clangdSettingsKey(), settings)); + + settings->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); + m_data.customDiagnosticConfigs = diagnosticConfigsFromSettings(settings); + + // Pre-8.0 compat + static const Key oldKey("ClangDiagnosticConfig"); + const QVariant configId = settings->value(oldKey); + if (configId.isValid()) { + m_data.diagnosticConfigId = Id::fromSetting(configId); + settings->setValue(oldKey, {}); + } + + settings->endGroup(); +} + +void ClangdSettings::saveSettings() +{ + const auto settings = Core::ICore::settings(); + const ClangdSettings::Data defaultData; + Utils::storeToSettingsWithDefault(clangdSettingsKey(), + settings, + m_data.toMap(), + defaultData.toMap()); + settings->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); + diagnosticConfigsToSettings(settings, m_data.customDiagnosticConfigs); + settings->endGroup(); +} + +#ifdef WITH_TESTS +void ClangdSettings::setClangdFilePath(const FilePath &filePath) +{ + instance().m_data.executableFilePath = filePath; +} +#endif + +ClangdProjectSettings::ClangdProjectSettings(ProjectExplorer::Project *project) : m_project(project) +{ + loadSettings(); +} + +ClangdSettings::Data ClangdProjectSettings::settings() const +{ + const ClangdSettings::Data globalData = ClangdSettings::instance().data(); + ClangdSettings::Data data = globalData; + if (!m_useGlobalSettings) { + data = m_customSettings; + // This property is global by definition. + data.sessionsWithOneClangd = ClangdSettings::instance().data().sessionsWithOneClangd; + + // This list exists only once. + data.customDiagnosticConfigs = ClangdSettings::instance().data().customDiagnosticConfigs; + } + if (m_blockIndexing) + data.indexingPriority = ClangdSettings::IndexingPriority::Off; + return data; +} + +void ClangdProjectSettings::setSettings(const ClangdSettings::Data &data) +{ + m_customSettings = data; + saveSettings(); + ClangdSettings::setCustomDiagnosticConfigs(data.customDiagnosticConfigs); + emit ClangdSettings::instance().changed(); +} + +void ClangdProjectSettings::setUseGlobalSettings(bool useGlobal) +{ + m_useGlobalSettings = useGlobal; + saveSettings(); + emit ClangdSettings::instance().changed(); +} + +void ClangdProjectSettings::setDiagnosticConfigId(Utils::Id configId) +{ + m_customSettings.diagnosticConfigId = configId; + saveSettings(); + emit ClangdSettings::instance().changed(); +} + +void ClangdProjectSettings::blockIndexing() +{ + if (m_blockIndexing) + return; + m_blockIndexing = true; + saveSettings(); + emit ClangdSettings::instance().changed(); +} + +void ClangdProjectSettings::unblockIndexing() +{ + if (!m_blockIndexing) + return; + m_blockIndexing = false; + saveSettings(); + // Do not emit changed here since that would restart clients with blocked indexing +} + +void ClangdProjectSettings::loadSettings() +{ + if (!m_project) + return; + const Store data = storeFromVariant(m_project->namedSettings(clangdSettingsKey())); + m_useGlobalSettings = data.value(useGlobalSettingsKey(), true).toBool(); + m_blockIndexing = data.value(clangdblockIndexingSettingsKey(), false).toBool(); + if (!m_useGlobalSettings) + m_customSettings.fromMap(data); +} + +void ClangdProjectSettings::saveSettings() +{ + if (!m_project) + return; + Store data; + if (!m_useGlobalSettings) + data = m_customSettings.toMap(); + data.insert(useGlobalSettingsKey(), m_useGlobalSettings); + data.insert(clangdblockIndexingSettingsKey(), m_blockIndexing); + m_project->setNamedSettings(clangdSettingsKey(), variantFromStore(data)); +} + +Store ClangdSettings::Data::toMap() const +{ + Store map; + + map.insert(useClangdKey(), useClangd); + + map.insert(clangdPathKey(), + executableFilePath != fallbackClangdFilePath() ? executableFilePath.toString() + : QString()); + + map.insert(clangdIndexingKey(), indexingPriority != IndexingPriority::Off); + map.insert(clangdIndexingPriorityKey(), int(indexingPriority)); + map.insert(clangdProjectIndexPathKey(), projectIndexPathTemplate); + map.insert(clangdSessionIndexPathKey(), sessionIndexPathTemplate); + map.insert(clangdHeaderSourceSwitchModeKey(), int(headerSourceSwitchMode)); + map.insert(clangdCompletionRankingModelKey(), int(completionRankingModel)); + map.insert(clangdHeaderInsertionKey(), autoIncludeHeaders); + map.insert(clangdThreadLimitKey(), workerThreadLimit); + map.insert(clangdDocumentThresholdKey(), documentUpdateThreshold); + map.insert(clangdSizeThresholdEnabledKey(), sizeThresholdEnabled); + map.insert(clangdSizeThresholdKey(), sizeThresholdInKb); + map.insert(sessionsWithOneClangdKey(), sessionsWithOneClangd); + map.insert(diagnosticConfigIdKey(), diagnosticConfigId.toSetting()); + map.insert(checkedHardwareKey(), haveCheckedHardwareReqirements); + map.insert(completionResultsKey(), completionResults); + return map; +} + +void ClangdSettings::Data::fromMap(const Store &map) +{ + useClangd = map.value(useClangdKey(), true).toBool(); + executableFilePath = FilePath::fromString(map.value(clangdPathKey()).toString()); + indexingPriority = IndexingPriority( + map.value(clangdIndexingPriorityKey(), int(this->indexingPriority)).toInt()); + const auto it = map.find(clangdIndexingKey()); + if (it != map.end() && !it->toBool()) + indexingPriority = IndexingPriority::Off; + projectIndexPathTemplate + = map.value(clangdProjectIndexPathKey(), defaultProjectIndexPathTemplate()).toString(); + sessionIndexPathTemplate + = map.value(clangdSessionIndexPathKey(), defaultSessionIndexPathTemplate()).toString(); + headerSourceSwitchMode = HeaderSourceSwitchMode(map.value(clangdHeaderSourceSwitchModeKey(), + int(headerSourceSwitchMode)).toInt()); + completionRankingModel = CompletionRankingModel(map.value(clangdCompletionRankingModelKey(), + int(completionRankingModel)).toInt()); + autoIncludeHeaders = map.value(clangdHeaderInsertionKey(), false).toBool(); + workerThreadLimit = map.value(clangdThreadLimitKey(), 0).toInt(); + documentUpdateThreshold = map.value(clangdDocumentThresholdKey(), 500).toInt(); + sizeThresholdEnabled = map.value(clangdSizeThresholdEnabledKey(), false).toBool(); + sizeThresholdInKb = map.value(clangdSizeThresholdKey(), 1024).toLongLong(); + sessionsWithOneClangd = map.value(sessionsWithOneClangdKey()).toStringList(); + diagnosticConfigId = Id::fromSetting(map.value(diagnosticConfigIdKey(), + initialClangDiagnosticConfigId().toSetting())); + haveCheckedHardwareReqirements = map.value(checkedHardwareKey(), false).toBool(); + completionResults = map.value(completionResultsKey(), defaultCompletionResults()).toInt(); +} + +int ClangdSettings::Data::defaultCompletionResults() +{ + // Default clangd --limit-results value is 100 + bool ok = false; + const int userValue = qtcEnvironmentVariableIntValue("QTC_CLANGD_COMPLETION_RESULTS", &ok); + return ok ? userValue : 100; +} + +} // namespace CppEditor diff --git a/src/plugins/cppeditor/clangdsettings.h b/src/plugins/cppeditor/clangdsettings.h new file mode 100644 index 00000000000..c1fb3b6ae86 --- /dev/null +++ b/src/plugins/cppeditor/clangdsettings.h @@ -0,0 +1,162 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "clangdiagnosticconfig.h" +#include "cppeditor_global.h" + +#include +#include + +namespace ProjectExplorer { class Project; } +namespace Utils { class MacroExpander; } + +namespace CppEditor { + +// TODO: Can we move this to ClangCodeModel? +class CPPEDITOR_EXPORT ClangdSettings : public QObject +{ + Q_OBJECT +public: + enum class IndexingPriority { Off, Background, Normal, Low, }; + enum class HeaderSourceSwitchMode { BuiltinOnly, ClangdOnly, Both }; + enum class CompletionRankingModel { Default, DecisionForest, Heuristics }; + + static QString priorityToString(const IndexingPriority &priority); + static QString priorityToDisplayString(const IndexingPriority &priority); + static QString headerSourceSwitchModeToDisplayString(HeaderSourceSwitchMode mode); + static QString rankingModelToCmdLineString(CompletionRankingModel model); + static QString rankingModelToDisplayString(CompletionRankingModel model); + static QString defaultProjectIndexPathTemplate(); + static QString defaultSessionIndexPathTemplate(); + + class CPPEDITOR_EXPORT Data + { + public: + Utils::Store toMap() const; + void fromMap(const Utils::Store &map); + + friend bool operator==(const Data &s1, const Data &s2) + { + return s1.useClangd == s2.useClangd + && s1.executableFilePath == s2.executableFilePath + && s1.projectIndexPathTemplate == s2.projectIndexPathTemplate + && s1.sessionIndexPathTemplate == s2.sessionIndexPathTemplate + && s1.sessionsWithOneClangd == s2.sessionsWithOneClangd + && s1.customDiagnosticConfigs == s2.customDiagnosticConfigs + && s1.diagnosticConfigId == s2.diagnosticConfigId + && s1.workerThreadLimit == s2.workerThreadLimit + && s1.indexingPriority == s2.indexingPriority + && s1.headerSourceSwitchMode == s2.headerSourceSwitchMode + && s1.completionRankingModel == s2.completionRankingModel + && s1.autoIncludeHeaders == s2.autoIncludeHeaders + && s1.documentUpdateThreshold == s2.documentUpdateThreshold + && s1.sizeThresholdEnabled == s2.sizeThresholdEnabled + && s1.sizeThresholdInKb == s2.sizeThresholdInKb + && s1.haveCheckedHardwareReqirements == s2.haveCheckedHardwareReqirements + && s1.completionResults == s2.completionResults; + } + friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } + + Utils::FilePath executableFilePath; + QStringList sessionsWithOneClangd; + ClangDiagnosticConfigs customDiagnosticConfigs; + Utils::Id diagnosticConfigId; + + int workerThreadLimit = 0; + int documentUpdateThreshold = 500; + qint64 sizeThresholdInKb = 1024; + bool useClangd = true; + IndexingPriority indexingPriority = IndexingPriority::Low; + QString projectIndexPathTemplate = defaultProjectIndexPathTemplate(); + QString sessionIndexPathTemplate = defaultSessionIndexPathTemplate(); + HeaderSourceSwitchMode headerSourceSwitchMode = HeaderSourceSwitchMode::Both; + CompletionRankingModel completionRankingModel = CompletionRankingModel::Default; + bool autoIncludeHeaders = false; + bool sizeThresholdEnabled = false; + bool haveCheckedHardwareReqirements = false; + int completionResults = defaultCompletionResults(); + + private: + static int defaultCompletionResults(); + }; + + ClangdSettings(const Data &data) : m_data(data) {} + + static ClangdSettings &instance(); + bool useClangd() const; + static void setUseClangd(bool use); + static void setUseClangdAndSave(bool use); + + static bool hardwareFulfillsRequirements(); + static bool haveCheckedHardwareRequirements(); + + static void setDefaultClangdPath(const Utils::FilePath &filePath); + static void setCustomDiagnosticConfigs(const ClangDiagnosticConfigs &configs); + Utils::FilePath clangdFilePath() const; + IndexingPriority indexingPriority() const { return m_data.indexingPriority; } + Utils::FilePath projectIndexPath(const Utils::MacroExpander &expander) const; + Utils::FilePath sessionIndexPath(const Utils::MacroExpander &expander) const; + HeaderSourceSwitchMode headerSourceSwitchMode() const { return m_data.headerSourceSwitchMode; } + CompletionRankingModel completionRankingModel() const { return m_data.completionRankingModel; } + bool autoIncludeHeaders() const { return m_data.autoIncludeHeaders; } + int workerThreadLimit() const { return m_data.workerThreadLimit; } + int documentUpdateThreshold() const { return m_data.documentUpdateThreshold; } + qint64 sizeThresholdInKb() const { return m_data.sizeThresholdInKb; } + bool sizeThresholdEnabled() const { return m_data.sizeThresholdEnabled; } + int completionResults() const { return m_data.completionResults; } + bool sizeIsOkay(const Utils::FilePath &fp) const; + ClangDiagnosticConfigs customDiagnosticConfigs() const; + Utils::Id diagnosticConfigId() const; + ClangDiagnosticConfig diagnosticConfig() const; + + enum class Granularity { Project, Session }; + Granularity granularity() const; + + void setData(const Data &data); + Data data() const { return m_data; } + + Utils::FilePath clangdIncludePath() const; + static Utils::FilePath clangdUserConfigFilePath(); + +#ifdef WITH_TESTS + static void setClangdFilePath(const Utils::FilePath &filePath); +#endif + +signals: + void changed(); + +private: + ClangdSettings(); + + void loadSettings(); + void saveSettings(); + + Data m_data; +}; + +class CPPEDITOR_EXPORT ClangdProjectSettings +{ +public: + ClangdProjectSettings(ProjectExplorer::Project *project); + + ClangdSettings::Data settings() const; + void setSettings(const ClangdSettings::Data &data); + bool useGlobalSettings() const { return m_useGlobalSettings; } + void setUseGlobalSettings(bool useGlobal); + void setDiagnosticConfigId(Utils::Id configId); + void blockIndexing(); + void unblockIndexing(); + +private: + void loadSettings(); + void saveSettings(); + + ProjectExplorer::Project * const m_project; + ClangdSettings::Data m_customSettings; + bool m_useGlobalSettings = true; + bool m_blockIndexing = false; +}; + +} // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index d1b4c470983..d4a309363ac 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -3,14 +3,10 @@ #include "cppcodemodelsettings.h" -#include "clangdiagnosticconfigsmodel.h" #include "compileroptionsbuilder.h" #include "cppeditorconstants.h" -#include "cppeditortr.h" -#include "cpptoolsreuse.h" #include -#include #include #include @@ -27,14 +23,12 @@ #include #include #include -#include using namespace ProjectExplorer; using namespace Utils; namespace CppEditor { -static Id initialClangDiagnosticConfigId() { return Constants::CPP_CLANG_DIAG_CONFIG_BUILDSYSTEM; } static Key pchUsageKey() { return Constants::CPPEDITOR_MODEL_MANAGER_PCH_USAGE; } static Key interpretAmbiguousHeadersAsCHeadersKey() { return Constants::CPPEDITOR_INTERPRET_AMBIGIUOUS_HEADERS_AS_C_HEADERS; } @@ -43,35 +37,7 @@ static Key ignoreFilesKey() { return Constants::CPPEDITOR_IGNORE_FILES; } static Key ignorePatternKey() { return Constants::CPPEDITOR_IGNORE_PATTERN; } static Key useBuiltinPreprocessorKey() { return Constants::CPPEDITOR_USE_BUILTIN_PREPROCESSOR; } static Key indexerFileSizeLimitKey() { return Constants::CPPEDITOR_INDEXER_FILE_SIZE_LIMIT; } - -static Key clangdSettingsKey() { return "ClangdSettings"; } -static Key useClangdKey() { return "UseClangdV7"; } -static Key clangdPathKey() { return "ClangdPath"; } -static Key clangdIndexingKey() { return "ClangdIndexing"; } -static Key clangdProjectIndexPathKey() { return "ClangdProjectIndexPath"; } -static Key clangdSessionIndexPathKey() { return "ClangdSessionIndexPath"; } -static Key clangdIndexingPriorityKey() { return "ClangdIndexingPriority"; } -static Key clangdHeaderSourceSwitchModeKey() { return "ClangdHeaderSourceSwitchMode"; } -static Key clangdCompletionRankingModelKey() { return "ClangdCompletionRankingModel"; } -static Key clangdHeaderInsertionKey() { return "ClangdHeaderInsertion"; } -static Key clangdThreadLimitKey() { return "ClangdThreadLimit"; } -static Key clangdDocumentThresholdKey() { return "ClangdDocumentThreshold"; } -static Key clangdSizeThresholdEnabledKey() { return "ClangdSizeThresholdEnabled"; } -static Key clangdSizeThresholdKey() { return "ClangdSizeThreshold"; } static Key useGlobalSettingsKey() { return "useGlobalSettings"; } -static Key clangdblockIndexingSettingsKey() { return "blockIndexing"; } -static Key sessionsWithOneClangdKey() { return "SessionsWithOneClangd"; } -static Key diagnosticConfigIdKey() { return "diagnosticConfigId"; } -static Key checkedHardwareKey() { return "checkedHardware"; } -static Key completionResultsKey() { return "completionResults"; } - -static FilePath g_defaultClangdFilePath; -static FilePath fallbackClangdFilePath() -{ - if (g_defaultClangdFilePath.exists()) - return g_defaultClangdFilePath; - return Environment::systemEnvironment().searchInPath("clangd"); -} bool operator==(const CppEditor::CppCodeModelSettings::Data &s1, const CppEditor::CppCodeModelSettings::Data &s2) @@ -230,440 +196,4 @@ void CppCodeModelProjectSettings::saveSettings() m_project->setNamedSettings(Constants::CPPEDITOR_SETTINGSGROUP, variantFromStore(data)); } -QString ClangdSettings::priorityToString(const IndexingPriority &priority) -{ - switch (priority) { - case IndexingPriority::Background: return "background"; - case IndexingPriority::Normal: return "normal"; - case IndexingPriority::Low: return "low"; - case IndexingPriority::Off: return {}; - } - return {}; -} - -QString ClangdSettings::priorityToDisplayString(const IndexingPriority &priority) -{ - switch (priority) { - case IndexingPriority::Background: return Tr::tr("Background Priority"); - case IndexingPriority::Normal: return Tr::tr("Normal Priority"); - case IndexingPriority::Low: return Tr::tr("Low Priority"); - case IndexingPriority::Off: return Tr::tr("Off"); - } - return {}; -} - -QString ClangdSettings::headerSourceSwitchModeToDisplayString(HeaderSourceSwitchMode mode) -{ - switch (mode) { - case HeaderSourceSwitchMode::BuiltinOnly: return Tr::tr("Use Built-in Only"); - case HeaderSourceSwitchMode::ClangdOnly: return Tr::tr("Use Clangd Only"); - case HeaderSourceSwitchMode::Both: return Tr::tr("Try Both"); - } - return {}; -} - -QString ClangdSettings::rankingModelToCmdLineString(CompletionRankingModel model) -{ - switch (model) { - case CompletionRankingModel::Default: break; - case CompletionRankingModel::DecisionForest: return "decision_forest"; - case CompletionRankingModel::Heuristics: return "heuristics"; - } - QTC_ASSERT(false, return {}); -} - -QString ClangdSettings::rankingModelToDisplayString(CompletionRankingModel model) -{ - switch (model) { - case CompletionRankingModel::Default: return Tr::tr("Default"); - case CompletionRankingModel::DecisionForest: return Tr::tr("Decision Forest"); - case CompletionRankingModel::Heuristics: return Tr::tr("Heuristics"); - } - QTC_ASSERT(false, return {}); -} - -QString ClangdSettings::defaultProjectIndexPathTemplate() -{ - return QDir::toNativeSeparators("%{BuildConfig:BuildDirectory:FilePath}/.qtc_clangd"); -} - -QString ClangdSettings::defaultSessionIndexPathTemplate() -{ - return QDir::toNativeSeparators("%{IDE:UserResourcePath}/.qtc_clangd/%{Session:FileBaseName}"); -} - -ClangdSettings &ClangdSettings::instance() -{ - static ClangdSettings settings; - return settings; -} - -ClangdSettings::ClangdSettings() -{ - loadSettings(); - const auto sessionMgr = Core::SessionManager::instance(); - connect(sessionMgr, &Core::SessionManager::sessionRemoved, this, [this](const QString &name) { - m_data.sessionsWithOneClangd.removeOne(name); - }); - connect(sessionMgr, - &Core::SessionManager::sessionRenamed, - this, - [this](const QString &oldName, const QString &newName) { - const auto index = m_data.sessionsWithOneClangd.indexOf(oldName); - if (index != -1) - m_data.sessionsWithOneClangd[index] = newName; - }); -} - -bool ClangdSettings::useClangd() const -{ - return m_data.useClangd && clangdVersion(clangdFilePath()) >= minimumClangdVersion(); -} - -void ClangdSettings::setUseClangd(bool use) { instance().m_data.useClangd = use; } - -void ClangdSettings::setUseClangdAndSave(bool use) -{ - setUseClangd(use); - instance().saveSettings(); -} - -bool ClangdSettings::hardwareFulfillsRequirements() -{ - instance().m_data.haveCheckedHardwareReqirements = true; - instance().saveSettings(); - const quint64 minRam = quint64(12) * 1024 * 1024 * 1024; - const std::optional totalRam = Utils::HostOsInfo::totalMemoryInstalledInBytes(); - return !totalRam || *totalRam >= minRam; -} - -bool ClangdSettings::haveCheckedHardwareRequirements() -{ - return instance().data().haveCheckedHardwareReqirements; -} - -void ClangdSettings::setDefaultClangdPath(const FilePath &filePath) -{ - g_defaultClangdFilePath = filePath; -} - -void ClangdSettings::setCustomDiagnosticConfigs(const ClangDiagnosticConfigs &configs) -{ - if (instance().customDiagnosticConfigs() == configs) - return; - instance().m_data.customDiagnosticConfigs = configs; - instance().saveSettings(); -} - -FilePath ClangdSettings::clangdFilePath() const -{ - if (!m_data.executableFilePath.isEmpty()) - return m_data.executableFilePath; - return fallbackClangdFilePath(); -} - -FilePath ClangdSettings::projectIndexPath(const Utils::MacroExpander &expander) const -{ - return FilePath::fromUserInput(expander.expand(m_data.projectIndexPathTemplate)); -} - -FilePath ClangdSettings::sessionIndexPath(const Utils::MacroExpander &expander) const -{ - return FilePath::fromUserInput(expander.expand(m_data.sessionIndexPathTemplate)); -} - -bool ClangdSettings::sizeIsOkay(const Utils::FilePath &fp) const -{ - return !sizeThresholdEnabled() || sizeThresholdInKb() * 1024 >= fp.fileSize(); -} - -ClangDiagnosticConfigs ClangdSettings::customDiagnosticConfigs() const -{ - return m_data.customDiagnosticConfigs; -} - -Id ClangdSettings::diagnosticConfigId() const -{ - if (!diagnosticConfigsModel().hasConfigWithId(m_data.diagnosticConfigId)) - return initialClangDiagnosticConfigId(); - return m_data.diagnosticConfigId; -} - -ClangDiagnosticConfig ClangdSettings::diagnosticConfig() const -{ - return diagnosticConfigsModel(customDiagnosticConfigs()).configWithId(diagnosticConfigId()); -} - -ClangdSettings::Granularity ClangdSettings::granularity() const -{ - if (m_data.sessionsWithOneClangd.contains(Core::SessionManager::activeSession())) - return Granularity::Session; - return Granularity::Project; -} - -void ClangdSettings::setData(const Data &data) -{ - if (this == &instance() && data != m_data) { - m_data = data; - saveSettings(); - emit changed(); - } -} - -static FilePath getClangHeadersPathFromClang(const FilePath &clangdFilePath) -{ - const FilePath clangFilePath = clangdFilePath.absolutePath().pathAppended("clang") - .withExecutableSuffix(); - if (!clangFilePath.exists()) - return {}; - Process clang; - clang.setCommand({clangFilePath, {"-print-resource-dir"}}); - clang.start(); - if (!clang.waitForFinished()) - return {}; - const FilePath resourceDir = FilePath::fromUserInput(QString::fromLocal8Bit( - clang.rawStdOut().trimmed())); - if (resourceDir.isEmpty() || !resourceDir.exists()) - return {}; - const FilePath includeDir = resourceDir.pathAppended("include"); - if (!includeDir.exists()) - return {}; - return includeDir; -} - -static FilePath getClangHeadersPath(const FilePath &clangdFilePath) -{ - const FilePath headersPath = getClangHeadersPathFromClang(clangdFilePath); - if (!headersPath.isEmpty()) - return headersPath; - - const QVersionNumber version = Utils::clangdVersion(clangdFilePath); - QTC_ASSERT(!version.isNull(), return {}); - static const QStringList libDirs{"lib", "lib64"}; - const QStringList versionStrings{QString::number(version.majorVersion()), version.toString()}; - for (const QString &libDir : libDirs) { - for (const QString &versionString : versionStrings) { - const FilePath includePath = clangdFilePath.absolutePath().parentDir() - .pathAppended(libDir).pathAppended("clang") - .pathAppended(versionString).pathAppended("include"); - if (includePath.exists()) - return includePath; - } - } - QTC_CHECK(false); - return {}; -} - -FilePath ClangdSettings::clangdIncludePath() const -{ - QTC_ASSERT(useClangd(), return {}); - FilePath clangdPath = clangdFilePath(); - QTC_ASSERT(!clangdPath.isEmpty() && clangdPath.exists(), return {}); - static QHash headersPathCache; - const auto it = headersPathCache.constFind(clangdPath); - if (it != headersPathCache.constEnd()) - return *it; - const FilePath headersPath = getClangHeadersPath(clangdPath); - if (!headersPath.isEmpty()) - headersPathCache.insert(clangdPath, headersPath); - return headersPath; -} - -FilePath ClangdSettings::clangdUserConfigFilePath() -{ - return FilePath::fromString( - QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)) - / "clangd/config.yaml"; -} - -void ClangdSettings::loadSettings() -{ - const auto settings = Core::ICore::settings(); - - m_data.fromMap(Utils::storeFromSettings(clangdSettingsKey(), settings)); - - settings->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); - m_data.customDiagnosticConfigs = diagnosticConfigsFromSettings(settings); - - // Pre-8.0 compat - static const Key oldKey("ClangDiagnosticConfig"); - const QVariant configId = settings->value(oldKey); - if (configId.isValid()) { - m_data.diagnosticConfigId = Id::fromSetting(configId); - settings->setValue(oldKey, {}); - } - - settings->endGroup(); -} - -void ClangdSettings::saveSettings() -{ - const auto settings = Core::ICore::settings(); - const ClangdSettings::Data defaultData; - Utils::storeToSettingsWithDefault(clangdSettingsKey(), - settings, - m_data.toMap(), - defaultData.toMap()); - settings->beginGroup(Constants::CPPEDITOR_SETTINGSGROUP); - diagnosticConfigsToSettings(settings, m_data.customDiagnosticConfigs); - settings->endGroup(); -} - -#ifdef WITH_TESTS -void ClangdSettings::setClangdFilePath(const FilePath &filePath) -{ - instance().m_data.executableFilePath = filePath; -} -#endif - -ClangdProjectSettings::ClangdProjectSettings(ProjectExplorer::Project *project) : m_project(project) -{ - loadSettings(); -} - -ClangdSettings::Data ClangdProjectSettings::settings() const -{ - const ClangdSettings::Data globalData = ClangdSettings::instance().data(); - ClangdSettings::Data data = globalData; - if (!m_useGlobalSettings) { - data = m_customSettings; - // This property is global by definition. - data.sessionsWithOneClangd = ClangdSettings::instance().data().sessionsWithOneClangd; - - // This list exists only once. - data.customDiagnosticConfigs = ClangdSettings::instance().data().customDiagnosticConfigs; -} - if (m_blockIndexing) - data.indexingPriority = ClangdSettings::IndexingPriority::Off; - return data; -} - -void ClangdProjectSettings::setSettings(const ClangdSettings::Data &data) -{ - m_customSettings = data; - saveSettings(); - ClangdSettings::setCustomDiagnosticConfigs(data.customDiagnosticConfigs); - emit ClangdSettings::instance().changed(); -} - -void ClangdProjectSettings::setUseGlobalSettings(bool useGlobal) -{ - m_useGlobalSettings = useGlobal; - saveSettings(); - emit ClangdSettings::instance().changed(); -} - -void ClangdProjectSettings::setDiagnosticConfigId(Utils::Id configId) -{ - m_customSettings.diagnosticConfigId = configId; - saveSettings(); - emit ClangdSettings::instance().changed(); -} - -void ClangdProjectSettings::blockIndexing() -{ - if (m_blockIndexing) - return; - m_blockIndexing = true; - saveSettings(); - emit ClangdSettings::instance().changed(); -} - -void ClangdProjectSettings::unblockIndexing() -{ - if (!m_blockIndexing) - return; - m_blockIndexing = false; - saveSettings(); - // Do not emit changed here since that would restart clients with blocked indexing -} - -void ClangdProjectSettings::loadSettings() -{ - if (!m_project) - return; - const Store data = storeFromVariant(m_project->namedSettings(clangdSettingsKey())); - m_useGlobalSettings = data.value(useGlobalSettingsKey(), true).toBool(); - m_blockIndexing = data.value(clangdblockIndexingSettingsKey(), false).toBool(); - if (!m_useGlobalSettings) - m_customSettings.fromMap(data); -} - -void ClangdProjectSettings::saveSettings() -{ - if (!m_project) - return; - Store data; - if (!m_useGlobalSettings) - data = m_customSettings.toMap(); - data.insert(useGlobalSettingsKey(), m_useGlobalSettings); - data.insert(clangdblockIndexingSettingsKey(), m_blockIndexing); - m_project->setNamedSettings(clangdSettingsKey(), variantFromStore(data)); -} - -Store ClangdSettings::Data::toMap() const -{ - Store map; - - map.insert(useClangdKey(), useClangd); - - map.insert(clangdPathKey(), - executableFilePath != fallbackClangdFilePath() ? executableFilePath.toString() - : QString()); - - map.insert(clangdIndexingKey(), indexingPriority != IndexingPriority::Off); - map.insert(clangdIndexingPriorityKey(), int(indexingPriority)); - map.insert(clangdProjectIndexPathKey(), projectIndexPathTemplate); - map.insert(clangdSessionIndexPathKey(), sessionIndexPathTemplate); - map.insert(clangdHeaderSourceSwitchModeKey(), int(headerSourceSwitchMode)); - map.insert(clangdCompletionRankingModelKey(), int(completionRankingModel)); - map.insert(clangdHeaderInsertionKey(), autoIncludeHeaders); - map.insert(clangdThreadLimitKey(), workerThreadLimit); - map.insert(clangdDocumentThresholdKey(), documentUpdateThreshold); - map.insert(clangdSizeThresholdEnabledKey(), sizeThresholdEnabled); - map.insert(clangdSizeThresholdKey(), sizeThresholdInKb); - map.insert(sessionsWithOneClangdKey(), sessionsWithOneClangd); - map.insert(diagnosticConfigIdKey(), diagnosticConfigId.toSetting()); - map.insert(checkedHardwareKey(), haveCheckedHardwareReqirements); - map.insert(completionResultsKey(), completionResults); - return map; -} - -void ClangdSettings::Data::fromMap(const Store &map) -{ - useClangd = map.value(useClangdKey(), true).toBool(); - executableFilePath = FilePath::fromString(map.value(clangdPathKey()).toString()); - indexingPriority = IndexingPriority( - map.value(clangdIndexingPriorityKey(), int(this->indexingPriority)).toInt()); - const auto it = map.find(clangdIndexingKey()); - if (it != map.end() && !it->toBool()) - indexingPriority = IndexingPriority::Off; - projectIndexPathTemplate - = map.value(clangdProjectIndexPathKey(), defaultProjectIndexPathTemplate()).toString(); - sessionIndexPathTemplate - = map.value(clangdSessionIndexPathKey(), defaultSessionIndexPathTemplate()).toString(); - headerSourceSwitchMode = HeaderSourceSwitchMode(map.value(clangdHeaderSourceSwitchModeKey(), - int(headerSourceSwitchMode)).toInt()); - completionRankingModel = CompletionRankingModel(map.value(clangdCompletionRankingModelKey(), - int(completionRankingModel)).toInt()); - autoIncludeHeaders = map.value(clangdHeaderInsertionKey(), false).toBool(); - workerThreadLimit = map.value(clangdThreadLimitKey(), 0).toInt(); - documentUpdateThreshold = map.value(clangdDocumentThresholdKey(), 500).toInt(); - sizeThresholdEnabled = map.value(clangdSizeThresholdEnabledKey(), false).toBool(); - sizeThresholdInKb = map.value(clangdSizeThresholdKey(), 1024).toLongLong(); - sessionsWithOneClangd = map.value(sessionsWithOneClangdKey()).toStringList(); - diagnosticConfigId = Id::fromSetting(map.value(diagnosticConfigIdKey(), - initialClangDiagnosticConfigId().toSetting())); - haveCheckedHardwareReqirements = map.value(checkedHardwareKey(), false).toBool(); - completionResults = map.value(completionResultsKey(), defaultCompletionResults()).toInt(); -} - -int ClangdSettings::Data::defaultCompletionResults() -{ - // Default clangd --limit-results value is 100 - bool ok = false; - const int userValue = qtcEnvironmentVariableIntValue("QTC_CLANGD_COMPLETION_RESULTS", &ok); - return ok ? userValue : 100; -} - } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index 19cc078b266..0bd9b05fbd3 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -3,10 +3,8 @@ #pragma once -#include "clangdiagnosticconfig.h" #include "cppeditor_global.h" -#include #include #include #include @@ -14,12 +12,8 @@ #include #include -#include namespace ProjectExplorer { class Project; } -namespace Utils { -class MacroExpander; -} // namespace Utils namespace CppEditor { enum class UsePrecompiledHeaders; @@ -114,148 +108,4 @@ private: bool m_useGlobalSettings = true; }; -class CPPEDITOR_EXPORT ClangdSettings : public QObject -{ - Q_OBJECT -public: - enum class IndexingPriority { Off, Background, Normal, Low, }; - enum class HeaderSourceSwitchMode { BuiltinOnly, ClangdOnly, Both }; - enum class CompletionRankingModel { Default, DecisionForest, Heuristics }; - - static QString priorityToString(const IndexingPriority &priority); - static QString priorityToDisplayString(const IndexingPriority &priority); - static QString headerSourceSwitchModeToDisplayString(HeaderSourceSwitchMode mode); - static QString rankingModelToCmdLineString(CompletionRankingModel model); - static QString rankingModelToDisplayString(CompletionRankingModel model); - static QString defaultProjectIndexPathTemplate(); - static QString defaultSessionIndexPathTemplate(); - - class CPPEDITOR_EXPORT Data - { - public: - Utils::Store toMap() const; - void fromMap(const Utils::Store &map); - - friend bool operator==(const Data &s1, const Data &s2) - { - return s1.useClangd == s2.useClangd - && s1.executableFilePath == s2.executableFilePath - && s1.projectIndexPathTemplate == s2.projectIndexPathTemplate - && s1.sessionIndexPathTemplate == s2.sessionIndexPathTemplate - && s1.sessionsWithOneClangd == s2.sessionsWithOneClangd - && s1.customDiagnosticConfigs == s2.customDiagnosticConfigs - && s1.diagnosticConfigId == s2.diagnosticConfigId - && s1.workerThreadLimit == s2.workerThreadLimit - && s1.indexingPriority == s2.indexingPriority - && s1.headerSourceSwitchMode == s2.headerSourceSwitchMode - && s1.completionRankingModel == s2.completionRankingModel - && s1.autoIncludeHeaders == s2.autoIncludeHeaders - && s1.documentUpdateThreshold == s2.documentUpdateThreshold - && s1.sizeThresholdEnabled == s2.sizeThresholdEnabled - && s1.sizeThresholdInKb == s2.sizeThresholdInKb - && s1.haveCheckedHardwareReqirements == s2.haveCheckedHardwareReqirements - && s1.completionResults == s2.completionResults; - } - friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } - - Utils::FilePath executableFilePath; - QStringList sessionsWithOneClangd; - ClangDiagnosticConfigs customDiagnosticConfigs; - Utils::Id diagnosticConfigId; - - int workerThreadLimit = 0; - int documentUpdateThreshold = 500; - qint64 sizeThresholdInKb = 1024; - bool useClangd = true; - IndexingPriority indexingPriority = IndexingPriority::Low; - QString projectIndexPathTemplate = defaultProjectIndexPathTemplate(); - QString sessionIndexPathTemplate = defaultSessionIndexPathTemplate(); - HeaderSourceSwitchMode headerSourceSwitchMode = HeaderSourceSwitchMode::Both; - CompletionRankingModel completionRankingModel = CompletionRankingModel::Default; - bool autoIncludeHeaders = false; - bool sizeThresholdEnabled = false; - bool haveCheckedHardwareReqirements = false; - int completionResults = defaultCompletionResults(); - - private: - static int defaultCompletionResults(); - }; - - ClangdSettings(const Data &data) : m_data(data) {} - - static ClangdSettings &instance(); - bool useClangd() const; - static void setUseClangd(bool use); - static void setUseClangdAndSave(bool use); - - static bool hardwareFulfillsRequirements(); - static bool haveCheckedHardwareRequirements(); - - static void setDefaultClangdPath(const Utils::FilePath &filePath); - static void setCustomDiagnosticConfigs(const ClangDiagnosticConfigs &configs); - Utils::FilePath clangdFilePath() const; - IndexingPriority indexingPriority() const { return m_data.indexingPriority; } - Utils::FilePath projectIndexPath(const Utils::MacroExpander &expander) const; - Utils::FilePath sessionIndexPath(const Utils::MacroExpander &expander) const; - HeaderSourceSwitchMode headerSourceSwitchMode() const { return m_data.headerSourceSwitchMode; } - CompletionRankingModel completionRankingModel() const { return m_data.completionRankingModel; } - bool autoIncludeHeaders() const { return m_data.autoIncludeHeaders; } - int workerThreadLimit() const { return m_data.workerThreadLimit; } - int documentUpdateThreshold() const { return m_data.documentUpdateThreshold; } - qint64 sizeThresholdInKb() const { return m_data.sizeThresholdInKb; } - bool sizeThresholdEnabled() const { return m_data.sizeThresholdEnabled; } - int completionResults() const { return m_data.completionResults; } - bool sizeIsOkay(const Utils::FilePath &fp) const; - ClangDiagnosticConfigs customDiagnosticConfigs() const; - Utils::Id diagnosticConfigId() const; - ClangDiagnosticConfig diagnosticConfig() const; - - enum class Granularity { Project, Session }; - Granularity granularity() const; - - void setData(const Data &data); - Data data() const { return m_data; } - - Utils::FilePath clangdIncludePath() const; - static Utils::FilePath clangdUserConfigFilePath(); - -#ifdef WITH_TESTS - static void setClangdFilePath(const Utils::FilePath &filePath); -#endif - -signals: - void changed(); - -private: - ClangdSettings(); - - void loadSettings(); - void saveSettings(); - - Data m_data; -}; - -class CPPEDITOR_EXPORT ClangdProjectSettings -{ -public: - ClangdProjectSettings(ProjectExplorer::Project *project); - - ClangdSettings::Data settings() const; - void setSettings(const ClangdSettings::Data &data); - bool useGlobalSettings() const { return m_useGlobalSettings; } - void setUseGlobalSettings(bool useGlobal); - void setDiagnosticConfigId(Utils::Id configId); - void blockIndexing(); - void unblockIndexing(); - -private: - void loadSettings(); - void saveSettings(); - - ProjectExplorer::Project * const m_project; - ClangdSettings::Data m_customSettings; - bool m_useGlobalSettings = true; - bool m_blockIndexing = false; -}; - } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index 616bb34f616..0e880fcb55b 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -5,6 +5,7 @@ #include "clangdiagnosticconfigsselectionwidget.h" #include "clangdiagnosticconfigswidget.h" +#include "clangdsettings.h" #include "cppcodemodelsettings.h" #include "cppeditorconstants.h" #include "cppeditortr.h" @@ -18,6 +19,7 @@ #include #include +#include #include #include #include diff --git a/src/plugins/cppeditor/cppeditor.qbs b/src/plugins/cppeditor/cppeditor.qbs index b684b0e0eac..b805e3fae9b 100644 --- a/src/plugins/cppeditor/cppeditor.qbs +++ b/src/plugins/cppeditor/cppeditor.qbs @@ -45,6 +45,8 @@ QtcPlugin { "clangdiagnosticconfigsselectionwidget.h", "clangdiagnosticconfigswidget.cpp", "clangdiagnosticconfigswidget.h", + "clangdsettings.cpp", + "clangdsettings.h", "compileroptionsbuilder.cpp", "compileroptionsbuilder.h", "cppautocompleter.cpp", diff --git a/src/plugins/cppeditor/cpptoolsreuse.cpp b/src/plugins/cppeditor/cpptoolsreuse.cpp index f6e58abddf9..947ecdd4c6f 100644 --- a/src/plugins/cppeditor/cpptoolsreuse.cpp +++ b/src/plugins/cppeditor/cpptoolsreuse.cpp @@ -4,6 +4,7 @@ #include "cpptoolsreuse.h" #include "clangdiagnosticconfigsmodel.h" +#include "clangdsettings.h" #include "cppautocompleter.h" #include "cppcanonicalsymbol.h" #include "cppcodemodelsettings.h" diff --git a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp index 9bef50b0b8a..41dd6b538f6 100644 --- a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp +++ b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp @@ -3,6 +3,7 @@ #include "followsymbol_switchmethoddecldef_test.h" +#include "clangdsettings.h" #include "cppcodemodelsettings.h" #include "cppeditorwidget.h" #include "cppfollowsymbolundercursor.h" From 340f1d7b427641f48fbc1e8807f5bb681ecd4386 Mon Sep 17 00:00:00 2001 From: Sergey Silin Date: Tue, 13 Feb 2024 02:49:42 +0300 Subject: [PATCH 0094/1060] Add a README section for xcb plugin problem Linux users may encounter a problem of missing xcb plugin while using Qt6 built from sources. Missing plugin prevents QtCreator from starting with default settings. The new section provides solution gathered from Qt forum Change-Id: I2917965c99fa6a05feac0d1506c7e60ff63796b1 Reviewed-by: hjk Reviewed-by: Eike Ziller --- README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/README.md b/README.md index 9f4b6f1457d..71f02d884ec 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,33 @@ get LLVM. cmake -DCMAKE_BUILD_TYPE=Debug -G Ninja "-DCMAKE_PREFIX_PATH=/path/to/Qt;/path/to/llvm" /path/to/qtcreator_sources cmake --build . +#### Troubleshooting: libxcb plugin not found while using Qt libraries built locally from source + +Ensure all prerequisites for building Qt are installed: +https://doc.qt.io/qt-6/linux.html +https://doc.qt.io/qt-6/linux-requirements.html + +If they were installed before building Qt and xcb plugin is missing try reinstall them with + +```sh + sudo apt-get --reinstall +``` + +Reset building configuration for Qt libraries at '/path/to/qt_sources' + +```sh + cmake --build . --target=clean +``` + +and remove CMakeCache.txt + +```sh + rm CMakeCache.txt +``` + +Try building Qt source again. + + ### Windows These instructions assume that Ninja is installed and in the `PATH`, Qt Creator From a8b7f6c29162b6a062b285103de5cde52139f3a7 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Fri, 22 Mar 2024 12:58:35 +0100 Subject: [PATCH 0095/1060] QmlDesignerLite: Add condition target check Change-Id: I0f1c1136adf99684f5a57a18d21ccd9245de53b4 Reviewed-by: Reviewed-by: hjk --- src/plugins/qmldesignerlite/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/plugins/qmldesignerlite/CMakeLists.txt b/src/plugins/qmldesignerlite/CMakeLists.txt index 95c1035b09b..67e007ae65a 100644 --- a/src/plugins/qmldesignerlite/CMakeLists.txt +++ b/src/plugins/qmldesignerlite/CMakeLists.txt @@ -10,6 +10,7 @@ add_feature_info("Treat warnings as errors in QmlDesigner" ${ENABLE_COMPILE_WARN add_qtc_plugin(QmlDesignerLite PLUGIN_DEPENDS QmlDesigner + CONDITION TARGET QmlDesigner SOURCES qmldesignerliteplugin.cpp qmldesignerliteplugin.h ) From 043abe69a7c80f14ec0241172842e05b3c652ccc Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 10:28:07 +0200 Subject: [PATCH 0096/1060] Docker: Remove temporary mounts Temporary mounts are more problem than solution. We want the user to specifically mount paths himself instead of trying to guess which ones should be mounted. Change-Id: I635ac2555e11979a4eb8cd60c1a22b02a377a5ba Reviewed-by: hjk --- src/plugins/docker/dockerdevice.cpp | 62 +++-------------------------- 1 file changed, 6 insertions(+), 56 deletions(-) diff --git a/src/plugins/docker/dockerdevice.cpp b/src/plugins/docker/dockerdevice.cpp index c54bd000ebe..d225bbf6e6d 100644 --- a/src/plugins/docker/dockerdevice.cpp +++ b/src/plugins/docker/dockerdevice.cpp @@ -341,8 +341,6 @@ public: return deviceSettings->clangdExecutable(); } - bool addTemporaryMount(const FilePath &path, const FilePath &containerPath); - QStringList createMountArgs() const; bool isImageAvailable() const; @@ -350,14 +348,12 @@ public: DockerDevice *const q; DockerDeviceSettings *deviceSettings; - struct TemporaryMountInfo + struct MountPair { FilePath path; FilePath containerPath; }; - QList m_temporaryMounts; - QMutex m_shellMutex; std::unique_ptr m_shell; @@ -750,7 +746,7 @@ QString escapeMountPath(const FilePath &fp) return escapeMountPathUnix(fp); } -QStringList toMountArg(const DockerDevicePrivate::TemporaryMountInfo &mi) +QStringList toMountArg(const DockerDevicePrivate::MountPair &mi) { QString escapedPath; QString escapedContainerPath; @@ -765,7 +761,7 @@ QStringList toMountArg(const DockerDevicePrivate::TemporaryMountInfo &mi) return QStringList{"--mount", mountArg}; } -expected_str isValidMountInfo(const DockerDevicePrivate::TemporaryMountInfo &mi) +expected_str isValidMountInfo(const DockerDevicePrivate::MountPair &mi) { if (mi.path.needsDevice()) return make_unexpected(QString("The path \"%1\" is not local.").arg(mi.path.toUserOutput())); @@ -801,11 +797,11 @@ expected_str isValidMountInfo(const DockerDevicePrivate::TemporaryMountInf QStringList DockerDevicePrivate::createMountArgs() const { QStringList cmds; - QList mounts = m_temporaryMounts; + QList mounts; for (const FilePath &m : deviceSettings->mounts()) mounts.append({m, m}); - for (const TemporaryMountInfo &mi : mounts) { + for (const MountPair &mi : mounts) { if (isValidMountInfo(mi)) cmds += toMountArg(mi); } @@ -1307,33 +1303,6 @@ void DockerDeviceFactory::shutdownExistingDevices() } } -bool DockerDevicePrivate::addTemporaryMount(const FilePath &path, const FilePath &containerPath) -{ - const bool alreadyAdded = anyOf(m_temporaryMounts, - [containerPath](const TemporaryMountInfo &info) { - return info.containerPath == containerPath; - }); - - if (alreadyAdded) - return false; - - const bool alreadyManuallyAdded = anyOf(deviceSettings->mounts(), - [path](const FilePath &mount) { return mount == path; }); - - if (alreadyManuallyAdded) - return false; - - const TemporaryMountInfo newMount{path, containerPath}; - - const expected_str result = isValidMountInfo(newMount); - QTC_ASSERT_EXPECTED(result, return false); - - qCDebug(dockerDeviceLog) << "Adding temporary mount:" << path; - m_temporaryMounts.append(newMount); - stopCurrentContainer(); // Force re-start with new mounts. - return true; -} - expected_str DockerDevicePrivate::environment() { if (!m_cachedEnviroment) { @@ -1364,13 +1333,6 @@ void DockerDevicePrivate::changeMounts(QStringList newMounts) expected_str DockerDevicePrivate::localSource(const FilePath &other) const { const auto devicePath = FilePath::fromString(other.path()); - for (const TemporaryMountInfo &info : m_temporaryMounts) { - if (devicePath.isChildOf(info.containerPath)) { - const FilePath relativePath = devicePath.relativeChildPath(info.containerPath); - return info.path.pathAppended(relativePath.path()); - } - } - for (const FilePath &mount : deviceSettings->mounts()) { const FilePath mountPoint = mount; if (devicePath.isChildOf(mountPoint)) { @@ -1395,22 +1357,10 @@ bool DockerDevicePrivate::ensureReachable(const FilePath &other) return true; } - for (const auto &[path, containerPath] : m_temporaryMounts) { - if (path.path() != containerPath.path()) - continue; - - if (path == other) - return true; - - if (other.isChildOf(path)) - return true; - } - if (q->filePath(other.path()).exists()) return false; - addTemporaryMount(other, other); - return true; + return false; } bool DockerDevice::prepareForBuild(const Target *target) From 738a3bf76d7f4b0f49b795be7309a03794700329 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Tue, 2 Apr 2024 15:35:16 +0200 Subject: [PATCH 0097/1060] Update README to match the new requirements for building Amends ff04dc53ef94ff424789c1ff9a71a32417d4160b Change-Id: I3ec6dbdea4e9cfc5df6d94fbf37408b3d7e4145a Reviewed-by: Christian Stenger Reviewed-by: --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 71f02d884ec..7feacabd332 100644 --- a/README.md +++ b/README.md @@ -38,12 +38,12 @@ https://doc.qt.io/qtcreator-extending/coding-style.html Prerequisites: -* Qt 6.2 or later. The Qt version that you use to build Qt Creator defines the +* Qt 6.4.3 or later. The Qt version that you use to build Qt Creator defines the minimum platform versions that the result supports - (Windows 10, RHEL/CentOS 8.4, Ubuntu 20.04, macOS 10.15 for Qt 6.2). + (Windows 10, RHEL/CentOS 8.4, Ubuntu 20.04, macOS 10.15 for Qt 6.4.3). * Qt WebEngine module for QtWebEngine based help viewer * On Windows: - * MinGW with GCC 9 or Visual Studio 2019 or later + * MinGW with GCC 11.2 or Visual Studio 2019 or later * Python 3.8 or later (optional, needed for the python enabled debug helper) * Debugging Tools for Windows (optional, for MSVC debugging support with CDB) * On Mac OS X: latest Xcode From 0cca4b283b4a6daa1cad05b3dddd0010437f998c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20L=C3=B6hning?= Date: Thu, 21 Mar 2024 16:49:04 +0100 Subject: [PATCH 0098/1060] Debugger: Fix calls to calloc Change-Id: Id1ba0c4656eb611b6ac4269ebf9d141feb08d632 Reviewed-by: hjk Reviewed-by: Qt CI Bot Reviewed-by: --- share/qtcreator/debugger/gdbbridge.py | 4 ++-- share/qtcreator/debugger/python2/gdbbridge.py | 4 ++-- share/qtcreator/debugger/python2/stdtypes.py | 2 +- share/qtcreator/debugger/stdtypes.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/share/qtcreator/debugger/gdbbridge.py b/share/qtcreator/debugger/gdbbridge.py index d61160eed3b..9699e518fe3 100644 --- a/share/qtcreator/debugger/gdbbridge.py +++ b/share/qtcreator/debugger/gdbbridge.py @@ -772,7 +772,7 @@ class Dumper(DumperBase): def makeStdString(init): # Works only for small allocators, but they are usually empty. - gdb.execute('set $d=(std::string*)calloc(sizeof(std::string), 2)') + gdb.execute('set $d=(std::string*)calloc(2, sizeof(std::string))') gdb.execute('call($d->basic_string("' + init + '",*(std::allocator*)(1+$d)))') value = gdb.parse_and_eval('$d').dereference() @@ -787,7 +787,7 @@ class Dumper(DumperBase): h = self.hexencode(data) #DumperBase.warn('DATA: %s' % h) string = ''.join('\\x' + h[2 * i:2 * i + 2] for i in range(size)) - exp = '(%s*)memcpy(calloc(%d, 1), "%s", %d)' \ + exp = '(%s*)memcpy(calloc(1, %d), "%s", %d)' \ % (value.type.name, size, string, size) #DumperBase.warn('EXP: %s' % exp) res = gdb.parse_and_eval(exp) diff --git a/share/qtcreator/debugger/python2/gdbbridge.py b/share/qtcreator/debugger/python2/gdbbridge.py index d61160eed3b..9699e518fe3 100644 --- a/share/qtcreator/debugger/python2/gdbbridge.py +++ b/share/qtcreator/debugger/python2/gdbbridge.py @@ -772,7 +772,7 @@ class Dumper(DumperBase): def makeStdString(init): # Works only for small allocators, but they are usually empty. - gdb.execute('set $d=(std::string*)calloc(sizeof(std::string), 2)') + gdb.execute('set $d=(std::string*)calloc(2, sizeof(std::string))') gdb.execute('call($d->basic_string("' + init + '",*(std::allocator*)(1+$d)))') value = gdb.parse_and_eval('$d').dereference() @@ -787,7 +787,7 @@ class Dumper(DumperBase): h = self.hexencode(data) #DumperBase.warn('DATA: %s' % h) string = ''.join('\\x' + h[2 * i:2 * i + 2] for i in range(size)) - exp = '(%s*)memcpy(calloc(%d, 1), "%s", %d)' \ + exp = '(%s*)memcpy(calloc(1, %d), "%s", %d)' \ % (value.type.name, size, string, size) #DumperBase.warn('EXP: %s' % exp) res = gdb.parse_and_eval(exp) diff --git a/share/qtcreator/debugger/python2/stdtypes.py b/share/qtcreator/debugger/python2/stdtypes.py index c14812dee1d..8bc86671c69 100644 --- a/share/qtcreator/debugger/python2/stdtypes.py +++ b/share/qtcreator/debugger/python2/stdtypes.py @@ -850,7 +850,7 @@ def qedit__std__vector(d, value, data): values = data.split(',') n = len(values) innerType = value.type[0].name - cmd = "set $d = (%s*)calloc(sizeof(%s)*%s,1)" % (innerType, innerType, n) + cmd = "set $d = (%s*)calloc(%s,sizeof(%s))" % (innerType, n, innerType) gdb.execute(cmd) cmd = "set {void*[3]}%s = {$d, $d+%s, $d+%s}" % (value.address(), n, n) gdb.execute(cmd) diff --git a/share/qtcreator/debugger/stdtypes.py b/share/qtcreator/debugger/stdtypes.py index bc4bb84dcbb..dbe663ef631 100644 --- a/share/qtcreator/debugger/stdtypes.py +++ b/share/qtcreator/debugger/stdtypes.py @@ -909,7 +909,7 @@ def qedit__std__vector(d, value, data): values = data.split(',') n = len(values) innerType = value.type[0].name - cmd = "set $d = (%s*)calloc(sizeof(%s)*%s,1)" % (innerType, innerType, n) + cmd = "set $d = (%s*)calloc(%s,sizeof(%s))" % (innerType, n, innerType) gdb.execute(cmd) cmd = "set {void*[3]}%s = {$d, $d+%s, $d+%s}" % (value.address(), n, n) gdb.execute(cmd) From 24511d755f1cc94e5d30403782d7a48a8487509b Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 10:28:57 +0200 Subject: [PATCH 0099/1060] CMake: Add hint about missing docker mounts Change-Id: Id046496b1c9907dfdfedb36c6bec1b121428f37a Reviewed-by: Cristian Adam --- src/plugins/cmakeprojectmanager/cmakeprocess.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakeprocess.cpp b/src/plugins/cmakeprojectmanager/cmakeprocess.cpp index 40cc41d64a5..c0a41b817d1 100644 --- a/src/plugins/cmakeprojectmanager/cmakeprocess.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeprocess.cpp @@ -58,11 +58,15 @@ void CMakeProcess::run(const BuildDirParameters ¶meters, const QStringList & const FilePath cmakeExecutable = cmake->cmakeExecutable(); + const QString mountHint = ::CMakeProjectManager::Tr::tr( + "You may need to add the project directory to the list of directories that are mounted by " + "the build device."); + if (!cmakeExecutable.ensureReachable(parameters.sourceDirectory)) { const QString msg = ::CMakeProjectManager::Tr::tr( "The source directory %1 is not reachable by the CMake executable %2.") .arg(parameters.sourceDirectory.displayName()).arg(cmakeExecutable.displayName()); - BuildSystem::appendBuildSystemOutput(addCMakePrefix({QString(), msg}).join('\n')); + BuildSystem::appendBuildSystemOutput(addCMakePrefix({QString(), msg, mountHint}).join('\n')); emit finished(failedToStartExitCode); return; } @@ -71,7 +75,7 @@ void CMakeProcess::run(const BuildDirParameters ¶meters, const QStringList & const QString msg = ::CMakeProjectManager::Tr::tr( "The build directory %1 is not reachable by the CMake executable %2.") .arg(parameters.buildDirectory.displayName()).arg(cmakeExecutable.displayName()); - BuildSystem::appendBuildSystemOutput(addCMakePrefix({QString(), msg}).join('\n')); + BuildSystem::appendBuildSystemOutput(addCMakePrefix({QString(), msg, mountHint}).join('\n')); emit finished(failedToStartExitCode); return; } From cb29aeff50474cacbbe97448c5496d522f5e1ba5 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 10:29:55 +0200 Subject: [PATCH 0100/1060] CMake: Don't ignore writable test Change-Id: I49ba7a14f26eca0575b38a634124be5e53c0134f Reviewed-by: Cristian Adam --- src/plugins/cmakeprojectmanager/fileapireader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/fileapireader.cpp b/src/plugins/cmakeprojectmanager/fileapireader.cpp index d7dae6c8fcb..cb76705cdc7 100644 --- a/src/plugins/cmakeprojectmanager/fileapireader.cpp +++ b/src/plugins/cmakeprojectmanager/fileapireader.cpp @@ -332,7 +332,7 @@ void FileApiReader::makeBackupConfiguration(bool store) void FileApiReader::writeConfigurationIntoBuildDirectory(const QStringList &configurationArguments) { const FilePath buildDir = m_parameters.buildDirectory; - QTC_CHECK(buildDir.ensureWritableDir()); + QTC_ASSERT_EXPECTED(buildDir.ensureWritableDir(), return); QByteArray contents; QStringList unknownOptions; @@ -344,7 +344,7 @@ void FileApiReader::writeConfigurationIntoBuildDirectory(const QStringList &conf .toUtf8()); const FilePath settingsFile = buildDir / "qtcsettings.cmake"; - QTC_CHECK(settingsFile.writeFileContents(contents)); + QTC_ASSERT_EXPECTED(settingsFile.writeFileContents(contents), return); } std::unique_ptr FileApiReader::rootProjectNode() From 0e30918955eae566246b1bbd8deaef9f67ebaf07 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 10:30:21 +0200 Subject: [PATCH 0101/1060] CMake: Add hint about additional error messages Change-Id: I1eaeacb1fe67d534209ecef5a01fe6d41caddb62 Reviewed-by: Cristian Adam --- src/plugins/cmakeprojectmanager/fileapiparser.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/plugins/cmakeprojectmanager/fileapiparser.cpp b/src/plugins/cmakeprojectmanager/fileapiparser.cpp index 560b43617d0..f72bcd5a689 100644 --- a/src/plugins/cmakeprojectmanager/fileapiparser.cpp +++ b/src/plugins/cmakeprojectmanager/fileapiparser.cpp @@ -877,6 +877,7 @@ FileApiData FileApiParser::parseData(QPromise> & errorMessage = Tr::tr("CMake project configuration failed. No CMake configuration for " "build type \"%1\" found.") .arg(cmakeBuildType); + errorMessage += Tr::tr(" Check General messages for more information."); return result; } From 3067f57905738bc6575f9173d860e6ace2380c99 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Mon, 29 Jan 2024 17:25:13 +0100 Subject: [PATCH 0102/1060] Utils: Add QTC_CHECK_EXPECTED Change-Id: Ie25637d6800e1162b713c1db7ef07f87cc2a4041 Reviewed-by: hjk --- src/libs/utils/expected.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/libs/utils/expected.h b/src/libs/utils/expected.h index 33231c1246e..0e018eb8ab5 100644 --- a/src/libs/utils/expected.h +++ b/src/libs/utils/expected.h @@ -30,3 +30,12 @@ using expected_str = tl::expected; } \ do { \ } while (0) + +#define QTC_CHECK_EXPECTED(expected) \ + if (Q_LIKELY(expected)) { \ + } else { \ + ::Utils::writeAssertLocation( \ + QString("%1:%2: %3").arg(__FILE__).arg(__LINE__).arg(expected.error()).toUtf8().data()); \ + } \ + do { \ + } while (0) From c03fa4dbad40bee513da339af74ea7d99272b456 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 12:31:48 +0200 Subject: [PATCH 0103/1060] ProjectExplorer: Add Device::canMount Change-Id: Icde98f845c3fe303d9461a0cbb0946d1ce9c8b00 Reviewed-by: hjk --- src/plugins/docker/dockerdevice.h | 5 +++++ src/plugins/projectexplorer/devicesupport/idevice.cpp | 5 +++++ src/plugins/projectexplorer/devicesupport/idevice.h | 2 ++ 3 files changed, 12 insertions(+) diff --git a/src/plugins/docker/dockerdevice.h b/src/plugins/docker/dockerdevice.h index ee4334b55b6..e08a60cbc3c 100644 --- a/src/plugins/docker/dockerdevice.h +++ b/src/plugins/docker/dockerdevice.h @@ -68,6 +68,11 @@ public: Utils::FilePath rootPath() const override; Utils::FilePath filePath(const QString &pathOnDevice) const override; + bool canMount(const Utils::FilePath &filePath) const override + { + return !filePath.needsDevice() || filePath.isSameDevice(rootPath()); + } + bool handlesFile(const Utils::FilePath &filePath) const override; bool ensureReachable(const Utils::FilePath &other) const override; Utils::expected_str localSource(const Utils::FilePath &other) const override; diff --git a/src/plugins/projectexplorer/devicesupport/idevice.cpp b/src/plugins/projectexplorer/devicesupport/idevice.cpp index 0fcdae1c918..115fb0e5faf 100644 --- a/src/plugins/projectexplorer/devicesupport/idevice.cpp +++ b/src/plugins/projectexplorer/devicesupport/idevice.cpp @@ -442,6 +442,11 @@ DeviceTester *IDevice::createDeviceTester() const return nullptr; } +bool IDevice::canMount(const Utils::FilePath &) const +{ + return false; +} + OsType IDevice::osType() const { return d->osType; diff --git a/src/plugins/projectexplorer/devicesupport/idevice.h b/src/plugins/projectexplorer/devicesupport/idevice.h index 6434b5b6dde..b83c558e87b 100644 --- a/src/plugins/projectexplorer/devicesupport/idevice.h +++ b/src/plugins/projectexplorer/devicesupport/idevice.h @@ -151,6 +151,8 @@ public: virtual bool hasDeviceTester() const { return false; } virtual DeviceTester *createDeviceTester() const; + virtual bool canMount(const Utils::FilePath &filePath) const; + virtual DeviceProcessSignalOperation::Ptr signalOperation() const; enum DeviceState { DeviceReadyToUse, DeviceConnected, DeviceDisconnected, DeviceStateUnknown }; From 8e8a84908b6c32507f01f276370f6526a968c95f Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 12:33:15 +0200 Subject: [PATCH 0104/1060] ProjectExplorer: Add Default Issue Reporter Adds a base issue reporter that checks general comaptibility between build device and project / build dir location. Change-Id: I7bfe360f758e44fdad9f471d47f14ffdd5d61853 Reviewed-by: hjk --- .../projectexplorer/buildconfiguration.cpp | 49 ++++++++++++++++++- .../projectexplorer/buildconfiguration.h | 4 +- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/plugins/projectexplorer/buildconfiguration.cpp b/src/plugins/projectexplorer/buildconfiguration.cpp index f189cf0a9b9..ee2d8208eb7 100644 --- a/src/plugins/projectexplorer/buildconfiguration.cpp +++ b/src/plugins/projectexplorer/buildconfiguration.cpp @@ -656,12 +656,57 @@ BuildConfigurationFactory::~BuildConfigurationFactory() g_buildConfigurationFactories.removeOne(this); } +static Tasks defaultIssueReporter( + Kit *kit, const Utils::FilePath &projectDir, const Utils::FilePath &buildDirectory) +{ + auto buildDevice = BuildDeviceKitAspect::device(kit); + if (!buildDevice) { + return {Task( + Task::Error, + Tr::tr("No build device is set for the kit \"%1\".").arg(kit->displayName()), + {}, + 0, + ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)}; + } + + auto canMountHintFor = [&buildDevice](const FilePath &path) { + if (buildDevice->canMount(path)) + return Tr::tr("You can try mounting the folder in your device settings."); + return QString{}; + }; + + if (!buildDevice->ensureReachable(projectDir)) { + return {Task( + Task::Error, + Tr::tr("The build device \"%1\" cannot reach the project directory.") + .arg(buildDevice->displayName()) + + " " + canMountHintFor(projectDir), + {}, + 0, + ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)}; + } + + if (!buildDirectory.isEmpty() && !buildDevice->ensureReachable(buildDirectory)) { + return {Task( + Task::Error, + Tr::tr("The build device \"%1\" cannot reach the build directory.") + .arg(buildDevice->displayName()) + + " " + canMountHintFor(buildDirectory), + {}, + 0, + ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)}; + } + + return {}; +}; + const Tasks BuildConfigurationFactory::reportIssues(Kit *kit, const FilePath &projectPath, const FilePath &buildDir) const { + Tasks issues = defaultIssueReporter(kit, projectPath, buildDir); if (m_issueReporter) - return m_issueReporter(kit, projectPath, buildDir); - return {}; + issues += m_issueReporter(kit, projectPath, buildDir); + return issues; } const QList BuildConfigurationFactory::allAvailableBuilds(const Target *parent) const diff --git a/src/plugins/projectexplorer/buildconfiguration.h b/src/plugins/projectexplorer/buildconfiguration.h index 0b38b3b3a82..362c2605486 100644 --- a/src/plugins/projectexplorer/buildconfiguration.h +++ b/src/plugins/projectexplorer/buildconfiguration.h @@ -155,8 +155,8 @@ public: static BuildConfigurationFactory *find(const Kit *k, const Utils::FilePath &projectPath); static BuildConfigurationFactory *find(Target *parent); - using IssueReporter - = std::function; + using IssueReporter = std::function< + Tasks(Kit *, const Utils::FilePath &projectDir, const Utils::FilePath &buildDirectory)>; void setIssueReporter(const IssueReporter &issueReporter); const Tasks reportIssues(ProjectExplorer::Kit *kit, const Utils::FilePath &projectPath, From 56f0432c51931da87ab75b5c8a0417844d170add Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 4 Apr 2024 09:11:33 +0200 Subject: [PATCH 0105/1060] ProjectExplorer: Export summary page In preparation for other plugins to be able to use it. Change-Id: I36542e11dff5b0cc655ecee2439df6ea7c14858d Reviewed-by: Alessandro Portale --- .../jsonwizard/jsonsummarypage.cpp | 6 ++--- .../jsonwizard/jsonsummarypage.h | 2 +- .../projectfilewizardextension.cpp | 2 +- .../projectexplorer/projectwizardpage.cpp | 23 ++++++++++--------- .../projectexplorer/projectwizardpage.h | 5 ++-- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp index ec55e3218fd..8db6d46cac9 100644 --- a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp +++ b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp @@ -62,12 +62,12 @@ static IWizardFactory::WizardKind wizardKind(JsonWizard *wiz) // -------------------------------------------------------------------- JsonSummaryPage::JsonSummaryPage(QWidget *parent) : - Internal::ProjectWizardPage(parent), + ProjectWizardPage(parent), m_wizard(nullptr) { - connect(this, &Internal::ProjectWizardPage::projectNodeChanged, + connect(this, &ProjectWizardPage::projectNodeChanged, this, &JsonSummaryPage::summarySettingsHaveChanged); - connect(this, &Internal::ProjectWizardPage::versionControlChanged, + connect(this, &ProjectWizardPage::versionControlChanged, this, &JsonSummaryPage::summarySettingsHaveChanged); } diff --git a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.h b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.h index 95a971376df..c1b4578799e 100644 --- a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.h +++ b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.h @@ -14,7 +14,7 @@ class FolderNode; class Node; // Documentation inside. -class JsonSummaryPage : public Internal::ProjectWizardPage +class JsonSummaryPage : public ProjectWizardPage { Q_OBJECT diff --git a/src/plugins/projectexplorer/projectfilewizardextension.cpp b/src/plugins/projectexplorer/projectfilewizardextension.cpp index 76554563921..74a767cc989 100644 --- a/src/plugins/projectexplorer/projectfilewizardextension.cpp +++ b/src/plugins/projectexplorer/projectfilewizardextension.cpp @@ -49,7 +49,7 @@ using namespace Utils; managed) and do 'add' if the VCS supports it. \endlist - \sa ProjectExplorer::Internal::ProjectWizardPage + \sa ProjectExplorer::ProjectWizardPage */ enum { debugExtension = 0 }; diff --git a/src/plugins/projectexplorer/projectwizardpage.cpp b/src/plugins/projectexplorer/projectwizardpage.cpp index d3f60faeaeb..b3c0bd37d9f 100644 --- a/src/plugins/projectexplorer/projectwizardpage.cpp +++ b/src/plugins/projectexplorer/projectwizardpage.cpp @@ -32,7 +32,7 @@ #include /*! - \class ProjectExplorer::Internal::ProjectWizardPage + \class ProjectExplorer::ProjectWizardPage \brief The ProjectWizardPage class provides a wizard page showing projects and version control to add new files to. @@ -261,6 +261,8 @@ static AddNewTree *buildAddFilesTree(FolderNode *root, const FilePaths &files, return new AddNewTree(root, children, root->displayName()); } +} // namespace Internal + // -------------------------------------------------------------------- // ProjectWizardPage: // -------------------------------------------------------------------- @@ -302,7 +304,7 @@ ProjectWizardPage::ProjectWizardPage(QWidget *parent) setProperty(SHORT_TITLE_PROPERTY, Tr::tr("Summary")); connect(VcsManager::instance(), &VcsManager::configurationChanged, - this, &ProjectExplorer::Internal::ProjectWizardPage::initializeVersionControls); + this, &ProjectExplorer::ProjectWizardPage::initializeVersionControls); m_projectComboBox->setModel(&m_model); } @@ -333,14 +335,14 @@ bool ProjectWizardPage::expandTree(const QModelIndex &root) m_projectComboBox->view()->collapse(root); // if we are a high priority node, our *parent* needs to be expanded - auto tree = static_cast(root.internalPointer()); + auto tree = static_cast(root.internalPointer()); if (tree && tree->priority() >= 100) expand = true; return expand; } -void ProjectWizardPage::setBestNode(AddNewTree *tree) +void ProjectWizardPage::setBestNode(Internal::AddNewTree *tree) { QModelIndex index = tree ? m_model.indexForItem(tree) : QModelIndex(); m_projectComboBox->setCurrentIndex(index); @@ -458,29 +460,29 @@ void ProjectWizardPage::initializeProjectTree(Node *context, const FilePaths &pa ProjectAction action) { m_projectComboBox->disconnect(); - BestNodeSelector selector(m_commonDirectory, paths); + Internal::BestNodeSelector selector(m_commonDirectory, paths); TreeItem *root = m_model.rootItem(); root->removeChildren(); for (Project *project : ProjectManager::projects()) { if (ProjectNode *pn = project->rootProjectNode()) { if (kind == IWizardFactory::ProjectWizard) { - if (AddNewTree *child = buildAddProjectTree(pn, paths.first(), context, &selector)) + if (Internal::AddNewTree *child = buildAddProjectTree(pn, paths.first(), context, &selector)) root->appendChild(child); } else { - if (AddNewTree *child = buildAddFilesTree(pn, paths, context, &selector)) + if (Internal::AddNewTree *child = buildAddFilesTree(pn, paths, context, &selector)) root->appendChild(child); } } } root->sortChildren([](const TreeItem *ti1, const TreeItem *ti2) { - return compareNodes(static_cast(ti1)->node(), - static_cast(ti2)->node()); + return Internal::compareNodes(static_cast(ti1)->node(), + static_cast(ti2)->node()); }); root->prependChild(createNoneNode(&selector)); // Set combobox to context node if that appears in the tree: - auto predicate = [context](TreeItem *ti) { return static_cast(ti)->node() == context; }; + auto predicate = [context](TreeItem *ti) { return static_cast(ti)->node() == context; }; TreeItem *contextItem = root->findAnyChild(predicate); if (contextItem) m_projectComboBox->setCurrentIndex(m_model.indexForItem(contextItem)); @@ -600,5 +602,4 @@ void ProjectWizardPage::setProjectUiVisible(bool visible) m_projectComboBox->setVisible(visible); } -} // namespace Internal } // namespace ProjectExplorer diff --git a/src/plugins/projectexplorer/projectwizardpage.h b/src/plugins/projectexplorer/projectwizardpage.h index 90d17dee60d..cf5cf42788a 100644 --- a/src/plugins/projectexplorer/projectwizardpage.h +++ b/src/plugins/projectexplorer/projectwizardpage.h @@ -3,6 +3,7 @@ #pragma once +#include "projectexplorer_export.h" #include "projectnodes.h" #include @@ -25,9 +26,10 @@ namespace ProjectExplorer { namespace Internal { class AddNewTree; +} // Documentation inside. -class ProjectWizardPage : public Utils::WizardPage +class PROJECTEXPLORER_EXPORT ProjectWizardPage : public Utils::WizardPage { Q_OBJECT @@ -87,5 +89,4 @@ private: QLabel *m_filesLabel; }; -} // namespace Internal } // namespace ProjectExplorer From 5d4f2f095d6ebc1449747caffa6e6c3774716ac0 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Fri, 22 Mar 2024 08:25:57 +0100 Subject: [PATCH 0106/1060] Axivion: Do not present empty issue details It is not obvious how to fill the issue details with content - give at least a tiny hint. Change-Id: I3cde0a5711849c0c758c436e3c98255706c28026 Reviewed-by: Reviewed-by: Qt CI Bot Reviewed-by: Eike Ziller --- src/plugins/axivion/axivionplugin.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/plugins/axivion/axivionplugin.cpp b/src/plugins/axivion/axivionplugin.cpp index cd27cbbcb0c..ae5018c5bb7 100644 --- a/src/plugins/axivion/axivionplugin.cpp +++ b/src/plugins/axivion/axivionplugin.cpp @@ -993,6 +993,10 @@ public: { QTC_ASSERT(dd, return {}); QTextBrowser *browser = new QTextBrowser; + const QString text = Tr::tr( + "Search for issues inside the Axivion dashboard or request issue details for " + "Axivion inline annotations to see them here."); + browser->setText("

" + text + "

"); browser->setOpenLinks(false); NavigationView view; view.widget = browser; From 7335b738a9062f1db63b2c9fd7ee6ea43a356d3c Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Thu, 4 Apr 2024 15:59:49 +0200 Subject: [PATCH 0107/1060] German translation: Consistently use "Benutzer" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use "Benutzer" a lot already and it also is "benutzerdefiniert", "Benutzeroberfläche", and so on. As an aside, fix some missing dashes and just use "Port". Task-number: QTCREATORBUG-29370 Change-Id: Ic58913dba601fca9be6594640bae3ddd7f4f40b1 Reviewed-by: Robert Löhning Reviewed-by: Christian Stenger --- share/qtcreator/translations/qtcreator_de.ts | 68 ++++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 016b1faf771..7178987a31c 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -14636,15 +14636,15 @@ Lokale Commits werden nicht zum Master-Branch gepusht, bis ein normaler Commit e User - Nutzer + Benutzer Username to use by default on commit. - Nutzername für Commit. + Benutzername für Commit. Default username: - Vorgabe für Nutzernamen: + Vorgabe für Benutzernamen: Email to use by default on commit. @@ -18261,11 +18261,11 @@ Setzen Sie erst eine gültige ausführbare Datei. &Username: - &Nutzername: + &Benutzername: <Username> - <Nutzername> + <Benutzername> &Description: @@ -18293,7 +18293,7 @@ Setzen Sie erst eine gültige ausführbare Datei. Username: - Nutzername: + Benutzername: Default protocol: @@ -20970,7 +20970,7 @@ Sie werden wahrscheinlich auf weitere Probleme mit dieser Instanz von %3 stoßen %1 uses Google Crashpad for collecting crashes and sending them to our backend for processing. Crashpad may capture arbitrary contents from crashed process’ memory, including user sensitive information, URLs, and whatever other content users have trusted %1 with. The collected crash reports are however only used for the sole purpose of fixing bugs. - %1 nutzt Google Crashpad, um Absturzberichte zu sammeln und diese zur Verarbeitung an unsere Server zu senden. Crashpad kann beliebige Inhalte des Speichers des abgestürzten Prozesses erfassen. Dies beinhaltet persönliche Daten, URLs und welche Inhalte auch immer der Nutzer %1 anvertraut hat. Die gesammelten Absturzberichte werden allerdings nur zum Zweck der Fehlerbehebung genutzt. + %1 nutzt Google Crashpad, um Absturzberichte zu sammeln und diese zur Verarbeitung an unsere Server zu senden. Crashpad kann beliebige Inhalte des Speichers des abgestürzten Prozesses erfassen. Dies beinhaltet persönliche Daten, URLs und welche Inhalte auch immer der Benutzer %1 anvertraut hat. Die gesammelten Absturzberichte werden allerdings nur zum Zweck der Fehlerbehebung genutzt. More information: @@ -21824,7 +21824,7 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. The plugin will be available to all compatible %1 installations, but only for the current user. - Das Plugin wird für alle kompatiblen Installationen von %1 verfügbar sein, aber nur für den aktuellen Nutzer. + Das Plugin wird für alle kompatiblen Installationen von %1 verfügbar sein, aber nur für den aktuellen Benutzer. %1 installation @@ -21832,7 +21832,7 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. The plugin will be available only to this %1 installation, but for all users that can access it. - Das Plugin wird nur für diese Installation von %1 verfügbar sein, aber für alle Nutzer, die diese Ausführen können. + Das Plugin wird nur für diese Installation von %1 verfügbar sein, aber für alle Benutzer, die diese Ausführen können. Summary @@ -25529,7 +25529,7 @@ markers in the source code editor. Allows or inhibits reading the user's default .gdbinit file on debugger startup. - Gestattet oder unterdrückt das Lesen der Vorgabe-.gdbinit-Datei des Nutzers beim Starten des Debuggers. + Gestattet oder unterdrückt das Lesen der Vorgabe-.gdbinit-Datei des Benutzers beim Starten des Debuggers. Load system GDB pretty printers @@ -26595,7 +26595,7 @@ Sie werden möglicherweise gebeten, den Inhalt dieses Logs mitzuteilen, wenn Sie User commands are not accepted in the current state. - Die Eingabe von Nutzerkommandos ist in diesem Zustand nicht möglich. + Die Eingabe von Benutzerkommandos ist in diesem Zustand nicht möglich. Log File @@ -27151,7 +27151,7 @@ Soll es noch einmal versucht werden? &Username: - &Nutzername: + &Benutzername: &Password: @@ -28051,7 +28051,7 @@ Bitte wählen Sie einen 64-bit-Debugger in den Kit-Einstellungen für dieses Kit This debugger cannot handle user input. - Dieser Debugger kann keine Nutzereingaben verarbeiten. + Dieser Debugger kann keine Benutzereingaben verarbeiten. Stopped: "%1". @@ -30691,7 +30691,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: User: - Nutzer: + Benutzer: Repository Settings @@ -31103,7 +31103,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: User - Nutzer + Benutzer Miscellaneous @@ -32360,7 +32360,7 @@ Möchten Sie ihn beenden? &User: - &Nutzer: + &Benutzer: &ssh: @@ -32404,7 +32404,7 @@ nicht konfiguriert ist. Invalid Gerrit configuration. Host, user and ssh binary are mandatory. - Ungültige Gerrit-Konfiguration. Host, Nutzer und ausführbare SSH-Datei müssen angegeben werden. + Ungültige Gerrit-Konfiguration. Host, Benutzer und ausführbare SSH-Datei müssen angegeben werden. Git is not available. @@ -36492,15 +36492,15 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu User - Nutzer + Benutzer Username to use by default on commit. - Nutzername für Commit. + Benutzername für Commit. Default username: - Vorgabe für Nutzernamen: + Vorgabe für Benutzernamen: Email to use by default on commit. @@ -36540,7 +36540,7 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu Prompt for credentials - Nutzerdaten abfragen + Benutzerdaten abfragen For example: "https://[user[:pass]@]host[:port]/[path]". @@ -38316,15 +38316,15 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z P4 client: - P4 Client: + P4-Client: P4 user: - P4 Nutzer: + P4-Benutzer: P4 port: - P4 Port-Nummer: + P4-Port: Environment Variables @@ -38344,7 +38344,7 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z User: - Nutzer: + Benutzer: No executable specified @@ -44195,7 +44195,7 @@ fails because Clang does not understand the target architecture. User requested stop. Shutting down... - Abbruch auf Nutzeranforderung... + Abbruch auf Benutzeranforderung... Cannot run: No command given. @@ -49769,7 +49769,7 @@ Zusätzlich wird die Verbindung zum Gerät getestet. The username to log into the device: - Nutzername für Geräte-Login: + Benutzername für Geräte-Login: Authentication type: @@ -49810,7 +49810,7 @@ Zusätzlich wird die Verbindung zum Gerät getestet. &Username: - &Nutzername: + &Benutzername: QML runtime executable: @@ -53247,7 +53247,7 @@ Werte kleiner als 100% können überlappende und falsch ausgerichtete Darstellun Cannot create user snippet directory %1 - Das Snippet-Verzeichnis des Nutzers konnte nicht erstellt werden: %1 + Das Snippet-Verzeichnis des Benutzers konnte nicht erstellt werden: %1 Remove @@ -56448,7 +56448,7 @@ Die Trace-Daten sind verloren. Refusing to remove your home directory. - Das Nutzerverzeichnis (Home) kann nicht entfernt werden. + Das Benutzerverzeichnis (Home) kann nicht entfernt werden. Failed to remove directory "%1". @@ -57122,7 +57122,7 @@ in "%2" aus. User: - Nutzer: + Benutzer: Password: @@ -58807,17 +58807,17 @@ Check settings or ensure Valgrind is installed and available in PATH. User/&alias configuration file: - Nutzer/&Alias-Konfigurationsdatei: + Benutzer/&Alias-Konfigurationsdatei: A file listing nicknames in a 4-column mailmap format: 'name <email> alias <email>'. - Eine Datei, die Nutzernamen in einem vierspaltigen Format (mailmap) enthält: + Eine Datei, die Benutzernamen in einem vierspaltigen Format (mailmap) enthält: 'Name <E-Mail> Alias <E-Mail>'. User &fields configuration file: - Nutzer&feld-Konfigurationsdatei: + Benutzer&feld-Konfigurationsdatei: A simple file containing lines with field names like "Reviewed-By:" which will be added below the submit editor. From 352b6b8b773a0daf42d5a9dbe2619f325e90a8ac Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Fri, 5 Apr 2024 10:31:33 +0200 Subject: [PATCH 0108/1060] German translation: Consistently use "Array" for arrays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We used "Feld" in some instances. "Array" is probably more understandable for programmers (nowadays), and is also used in the MSVC documentation (https://learn.microsoft.com/de-de/cpp/cpp/arrays-cpp?view=msvc-170) Task-number: QTCREATORBUG-29370 Change-Id: I7a9dc424583900283c15b8fb0ab8497bf4f22085 Reviewed-by: Christian Stenger Reviewed-by: Robert Löhning --- share/qtcreator/translations/qtcreator_de.ts | 22 ++++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 7178987a31c..6a885e9340d 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -23054,7 +23054,7 @@ ausgerichtet werden würden int (*pa)[2] = ...; </pre></body></html> - <html><head/><body>Dies bezieht sich nicht auf die Stern- und Referenzsymbole in Zeigern auf / Referenzen zu Funktionen und Feldern, zum Beispiel: + <html><head/><body>Dies bezieht sich nicht auf die Stern- und Referenzsymbole in Zeigern auf / Referenzen zu Funktionen und Arrays, zum Beispiel: <pre> int (&rf)() = ...; int (*pf)() = ...; @@ -26381,8 +26381,8 @@ markers in the source code editor. Array of %n items - Feld aus einem Element - Feld aus %n Elementen + Array aus einem Element + Array aus %n Elementen @@ -30045,11 +30045,11 @@ Grund: %3 Value for key "%1" is not an array of objects - Wert des Schlüssels "%1" ist kein Feld von Objekten + Wert des Schlüssels "%1" ist kein Array von Objekten Value for key "%1" is not a string and not an array of strings - Wert des Schlüssels "%1" ist keine Zeichenkette und auch kein Feld von Zeichenketten + Wert des Schlüssels "%1" ist keine Zeichenkette und auch kein Array von Zeichenketten Value "%2" for key "%1" has invalid format @@ -46388,11 +46388,11 @@ Für CMake-Projekte stellen Sie sicher, dass die Variable QML_IMPORT_PATH in CMa Expected array of strings after colon. - Nach dem Doppelpunkt wird ein Feld von Zeichenketten erwartet. + Nach dem Doppelpunkt wird ein Array von Zeichenketten erwartet. Expected array literal with only string literal members. - Es wird ein nur aus Zeichenketten bestehendes Feldliteral erwartet. + Es wird ein nur aus Zeichenketten bestehendes Arrayliteral erwartet. Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'. @@ -46400,11 +46400,11 @@ Für CMake-Projekte stellen Sie sicher, dass die Variable QML_IMPORT_PATH in CMa Expected array of numbers after colon. - Nach dem Doppelpunkt wird ein aus Zahlen bestehendes Feld erwartet. + Nach dem Doppelpunkt wird ein aus Zahlen bestehendes Array erwartet. Expected array literal with only number literal members. - Es wird ein nur aus Zahlenliteralen bestehendes Feldliteral erwartet. + Es wird ein nur aus Zahlenliteralen bestehendes Arrayliteral erwartet. Meta object revision without matching export. @@ -46756,7 +46756,7 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code Array value expected. - Feld erwartet. + Array erwartet. %1 value expected. @@ -46792,7 +46792,7 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code %1 elements expected in array value. - Das Feld benötigt %1 Werte. + Das Array benötigt %1 Werte. Parsing QML Files From 8fa17f48863bc2144e8255dbe09e32c2624ac163 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Fri, 5 Apr 2024 10:40:08 +0200 Subject: [PATCH 0109/1060] German translation: Avoid "editieren" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use "bearbeiten" at most places. Task-number: QTCREATORBUG-29370 Change-Id: I09ae816da64c37fd30631f5f6668d16ec0c53f62 Reviewed-by: Christian Stenger Reviewed-by: Robert Löhning --- share/qtcreator/translations/qtcreator_de.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 6a885e9340d..06dd6e7d14c 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -9544,7 +9544,7 @@ Locked components cannot be modified or selected. Edit - Editieren + Bearbeiten Anchors @@ -18845,7 +18845,7 @@ Trotzdem fortfahren? Edit - Editieren + Bearbeiten <System Language> @@ -34090,7 +34090,7 @@ Hinweis: Dies macht Sie anfällig für Man-in-the-middle-Angriffe. Open in Edit Mode - Im Editieren-Modus öffnen + Im Bearbeiten-Modus öffnen Open in New Page @@ -37034,7 +37034,7 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt Edit Element Properties - Elementeigenschaften editieren + Elementeigenschaften bearbeiten Shift+Return @@ -37042,7 +37042,7 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt Edit Item on Diagram - Element auf Diagramm editieren + Element auf Diagramm bearbeiten Return @@ -37964,7 +37964,7 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z Edit File - Datei zum Editieren anfordern + Datei zum Bearbeiten anfordern Add @@ -59050,7 +59050,7 @@ should a repository require SSH-authentication (see documentation on SSH and the <p style="margin-top: 30px"><table><tr><td style="padding-right: 20px">Welcome:</td><td>Open examples, tutorials, and recent sessions and projects.</td></tr><tr><td>Edit:</td><td>Work with code and navigate your project.</td></tr><tr><td>Design:</td><td>Visually edit Widget-based user interfaces, state charts and UML models.</td></tr><tr><td>Debug:</td><td>Analyze your application with a debugger or other analyzers.</td></tr><tr><td>Projects:</td><td>Manage project settings.</td></tr><tr><td>Help:</td><td>Browse the help database.</td></tr></table></p> - <p style="margin-top: 30px"><table><tr><td style="padding-right: 20px">Willkommen:</td><td>Öffnen Sie Beispiele, Anleitungen, sowie kürzlich verwendete Sitzungen und Projekte.</td></tr><tr><td>Editieren:</td><td>Arbeiten Sie am Quelltext und navigieren Sie im Projekt.</td></tr><tr><td>Design:</td><td>Bearbeiten Sie Oberflächendesigns für Qt Widgets, State Charts und UML-Modelle.</td></tr><tr><td>Debug:</td><td>Analysieren Sie Ihre Anwendung mit einem Debugger oder anderen Werkzeugen.</td></tr><tr><td>Projekte:</td><td>Verwalten Sie Projekteinstellungen.</td></tr><tr><td>Hilfe:</td><td>Durchsuchen Sie die Hilfedatenbank.</td></tr></table></p> + <p style="margin-top: 30px"><table><tr><td style="padding-right: 20px">Willkommen:</td><td>Öffnen Sie Beispiele, Anleitungen, sowie kürzlich verwendete Sitzungen und Projekte.</td></tr><tr><td>Bearbeiten:</td><td>Arbeiten Sie am Quelltext und navigieren Sie im Projekt.</td></tr><tr><td>Design:</td><td>Bearbeiten Sie Oberflächendesigns für Qt Widgets, State Charts und UML-Modelle.</td></tr><tr><td>Debug:</td><td>Analysieren Sie Ihre Anwendung mit einem Debugger oder anderen Werkzeugen.</td></tr><tr><td>Projekte:</td><td>Verwalten Sie Projekteinstellungen.</td></tr><tr><td>Hilfe:</td><td>Durchsuchen Sie die Hilfedatenbank.</td></tr></table></p> Kit Selector From b96f5b83eaa4604189545d9b1359024145b11050 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Fri, 5 Apr 2024 15:20:11 +0200 Subject: [PATCH 0110/1060] German translation: Consistently use "scrollen" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This was the only place that was different Task-number: QTCREATORBUG-29370 Change-Id: I91fb2c291b26644b15aa7ea83fead0f76894ebcf Reviewed-by: Robert Löhning --- share/qtcreator/translations/qtcreator_de.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 06dd6e7d14c..3464a1379a1 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -61498,7 +61498,7 @@ This is used for calculating the total implicit size. Auto scroll - Automatisch rollen + Automatisch scrollen Toggles if the text scrolls when it exceeds its boundary. From 2a1d46bbfccf290afa6a81121f7b7c81b0aa79b5 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 8 Apr 2024 10:09:27 +0200 Subject: [PATCH 0111/1060] Debugger: Move python2 supporting files out of normal bridge directory They get in the way when working in that area. Change-Id: Id59c83472a6ce093ca9b31ad9e94ec638b4a1df8 Reviewed-by: Christian Stenger --- .../{debugger/python2 => debugger-with-python2}/README.txt | 0 .../python2 => debugger-with-python2}/android_stdtypes.py | 0 .../{debugger/python2 => debugger-with-python2}/boosttypes.py | 0 .../{debugger/python2 => debugger-with-python2}/cdbbridge.py | 0 .../{debugger/python2 => debugger-with-python2}/creatortypes.py | 0 .../{debugger/python2 => debugger-with-python2}/dumper.py | 0 .../{debugger/python2 => debugger-with-python2}/gdbbridge.py | 0 .../{debugger/python2 => debugger-with-python2}/gdbtracepoint.py | 0 .../python2 => debugger-with-python2}/libcpp_stdtypes.py | 0 .../{debugger/python2 => debugger-with-python2}/lldbbridge.py | 0 .../{debugger/python2 => debugger-with-python2}/misctypes.py | 0 .../{debugger/python2 => debugger-with-python2}/opencvtypes.py | 0 .../{debugger/python2 => debugger-with-python2}/pdbbridge.py | 0 .../{debugger/python2 => debugger-with-python2}/personaltypes.py | 0 .../{debugger/python2 => debugger-with-python2}/qttypes.py | 0 .../{debugger/python2 => debugger-with-python2}/stdtypes.py | 0 .../{debugger/python2 => debugger-with-python2}/utils.py | 0 17 files changed, 0 insertions(+), 0 deletions(-) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/README.txt (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/android_stdtypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/boosttypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/cdbbridge.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/creatortypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/dumper.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/gdbbridge.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/gdbtracepoint.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/libcpp_stdtypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/lldbbridge.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/misctypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/opencvtypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/pdbbridge.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/personaltypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/qttypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/stdtypes.py (100%) rename share/qtcreator/{debugger/python2 => debugger-with-python2}/utils.py (100%) diff --git a/share/qtcreator/debugger/python2/README.txt b/share/qtcreator/debugger-with-python2/README.txt similarity index 100% rename from share/qtcreator/debugger/python2/README.txt rename to share/qtcreator/debugger-with-python2/README.txt diff --git a/share/qtcreator/debugger/python2/android_stdtypes.py b/share/qtcreator/debugger-with-python2/android_stdtypes.py similarity index 100% rename from share/qtcreator/debugger/python2/android_stdtypes.py rename to share/qtcreator/debugger-with-python2/android_stdtypes.py diff --git a/share/qtcreator/debugger/python2/boosttypes.py b/share/qtcreator/debugger-with-python2/boosttypes.py similarity index 100% rename from share/qtcreator/debugger/python2/boosttypes.py rename to share/qtcreator/debugger-with-python2/boosttypes.py diff --git a/share/qtcreator/debugger/python2/cdbbridge.py b/share/qtcreator/debugger-with-python2/cdbbridge.py similarity index 100% rename from share/qtcreator/debugger/python2/cdbbridge.py rename to share/qtcreator/debugger-with-python2/cdbbridge.py diff --git a/share/qtcreator/debugger/python2/creatortypes.py b/share/qtcreator/debugger-with-python2/creatortypes.py similarity index 100% rename from share/qtcreator/debugger/python2/creatortypes.py rename to share/qtcreator/debugger-with-python2/creatortypes.py diff --git a/share/qtcreator/debugger/python2/dumper.py b/share/qtcreator/debugger-with-python2/dumper.py similarity index 100% rename from share/qtcreator/debugger/python2/dumper.py rename to share/qtcreator/debugger-with-python2/dumper.py diff --git a/share/qtcreator/debugger/python2/gdbbridge.py b/share/qtcreator/debugger-with-python2/gdbbridge.py similarity index 100% rename from share/qtcreator/debugger/python2/gdbbridge.py rename to share/qtcreator/debugger-with-python2/gdbbridge.py diff --git a/share/qtcreator/debugger/python2/gdbtracepoint.py b/share/qtcreator/debugger-with-python2/gdbtracepoint.py similarity index 100% rename from share/qtcreator/debugger/python2/gdbtracepoint.py rename to share/qtcreator/debugger-with-python2/gdbtracepoint.py diff --git a/share/qtcreator/debugger/python2/libcpp_stdtypes.py b/share/qtcreator/debugger-with-python2/libcpp_stdtypes.py similarity index 100% rename from share/qtcreator/debugger/python2/libcpp_stdtypes.py rename to share/qtcreator/debugger-with-python2/libcpp_stdtypes.py diff --git a/share/qtcreator/debugger/python2/lldbbridge.py b/share/qtcreator/debugger-with-python2/lldbbridge.py similarity index 100% rename from share/qtcreator/debugger/python2/lldbbridge.py rename to share/qtcreator/debugger-with-python2/lldbbridge.py diff --git a/share/qtcreator/debugger/python2/misctypes.py b/share/qtcreator/debugger-with-python2/misctypes.py similarity index 100% rename from share/qtcreator/debugger/python2/misctypes.py rename to share/qtcreator/debugger-with-python2/misctypes.py diff --git a/share/qtcreator/debugger/python2/opencvtypes.py b/share/qtcreator/debugger-with-python2/opencvtypes.py similarity index 100% rename from share/qtcreator/debugger/python2/opencvtypes.py rename to share/qtcreator/debugger-with-python2/opencvtypes.py diff --git a/share/qtcreator/debugger/python2/pdbbridge.py b/share/qtcreator/debugger-with-python2/pdbbridge.py similarity index 100% rename from share/qtcreator/debugger/python2/pdbbridge.py rename to share/qtcreator/debugger-with-python2/pdbbridge.py diff --git a/share/qtcreator/debugger/python2/personaltypes.py b/share/qtcreator/debugger-with-python2/personaltypes.py similarity index 100% rename from share/qtcreator/debugger/python2/personaltypes.py rename to share/qtcreator/debugger-with-python2/personaltypes.py diff --git a/share/qtcreator/debugger/python2/qttypes.py b/share/qtcreator/debugger-with-python2/qttypes.py similarity index 100% rename from share/qtcreator/debugger/python2/qttypes.py rename to share/qtcreator/debugger-with-python2/qttypes.py diff --git a/share/qtcreator/debugger/python2/stdtypes.py b/share/qtcreator/debugger-with-python2/stdtypes.py similarity index 100% rename from share/qtcreator/debugger/python2/stdtypes.py rename to share/qtcreator/debugger-with-python2/stdtypes.py diff --git a/share/qtcreator/debugger/python2/utils.py b/share/qtcreator/debugger-with-python2/utils.py similarity index 100% rename from share/qtcreator/debugger/python2/utils.py rename to share/qtcreator/debugger-with-python2/utils.py From bbcf5fa720ff6628ccdb91359267d93c9e93c36f Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Fri, 5 Apr 2024 11:25:25 +0200 Subject: [PATCH 0112/1060] =?UTF-8?q?German=20translation:=20Consistently?= =?UTF-8?q?=20use=20"Einf=C3=BCgemarke"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Task-number: QTCREATORBUG-29370 Change-Id: Ic90e0a21f64e3e4355c743185900463414504168 Reviewed-by: Robert Löhning Reviewed-by: Christian Stenger --- share/qtcreator/translations/qtcreator_de.ts | 22 ++++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 3464a1379a1..c5892b1228f 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -13387,7 +13387,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Run Test Under Cursor - Test unter Cursor ausführen + Test unter Einfügemarke ausführen &Run Test @@ -18532,7 +18532,7 @@ Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim a Request Copilot suggestion at the current editor's cursor position. - Fordert Vorschläge für die Cursorposition des aktuellen Editors von Copilot an. + Fordert Vorschläge für die Einfügemarke des aktuellen Editors von Copilot an. Show Next Copilot Suggestion @@ -18710,7 +18710,7 @@ Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim a Automatically request suggestions for the current text cursor position after changes to the document. - Fordert Vorschläge für die aktuelle Cursorposition nach Änderungen am Dokument automatisch an. + Fordert Vorschläge für die aktuelle Einfügemarke nach Änderungen am Dokument automatisch an. @@ -29731,7 +29731,7 @@ Versuchen Sie, das Projekt neu zu erstellen. Exchange Cursor and Mark - Textmarke und Markierung austauschen + Einfügemarke und Markierung austauschen Copy @@ -52544,11 +52544,11 @@ Die Datei "%1" konnte nicht geöffnet werden. Allow blinking cursor - Blinkenden Cursor erlauben + Blinkende Einfügemarke erlauben Allow the cursor to blink. - Erlaubt dem Cursor zu blinken. + Erlaubt der Einfügemarke zu blinken. Shell path: @@ -52688,11 +52688,11 @@ Die Datei "%1" konnte nicht geöffnet werden. Move Cursor Word Left - Cursor ein Wort nach links bewegen + Einfügemarke ein Wort nach links bewegen Move Cursor Word Right - Cursor ein Wort nach rechts bewegen + Einfügemarke ein Wort nach rechts bewegen Close Terminal @@ -53170,11 +53170,11 @@ Werte kleiner als 100% können überlappende und falsch ausgerichtete Darstellun Line number of the text cursor position in current document (starts with 1). - Zeilennummer der Cursorposition des aktuellen Dokuments (beginnend bei 1). + Zeilennummer der Einfügemarke des aktuellen Dokuments (beginnend bei 1). Column number of the text cursor position in current document (starts with 0). - Spaltennummer der Cursorposition des aktuellen Dokuments (beginnend bei 0). + Spaltennummer der Einfügemarke des aktuellen Dokuments (beginnend bei 0). Number of lines visible in current document. @@ -53648,7 +53648,7 @@ Gibt an, wie sich die Rücktaste bezüglich Einrückung verhält. Center &cursor on scroll - Cursor beim Scrollen in der &Mitte halten + Einfügemarke beim Scrollen in der &Mitte halten Enable text &wrapping From 740c3b7107e1c108d56240805d94210416d752bb Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Fri, 5 Apr 2024 15:06:36 +0200 Subject: [PATCH 0113/1060] German translation: Some more "erneut" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use "erneut" where we want to say "noch einmal", but keep "wieder" where we want to say "wieder zurück". Task-number: QTCREATORBUG-29370 Change-Id: I3d406604fbc8b7883e363a7ecf12c650280b6be0 Reviewed-by: Robert Löhning --- share/qtcreator/translations/qtcreator_de.ts | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index c5892b1228f..a95fcb53242 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -8393,7 +8393,7 @@ Locked components cannot be modified or selected. Do not show this dialog again - Diesen Dialog nicht noch einmal anzeigen + Diesen Dialog nicht erneut anzeigen Cancel @@ -10360,7 +10360,7 @@ Locked components cannot be modified or selected. Retype password: - Passwort noch einmal eingeben: + Passwort erneut eingeben: Show password @@ -14127,7 +14127,7 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? The following providers were already configured:<br>&nbsp;%1<br>They were not configured again. - Die folgenden Provider wurden bereits konfiguriert:<br>&nbsp;%1<br>Sie wurden nicht noch einmal konfiguriert. + Die folgenden Provider wurden bereits konfiguriert:<br>&nbsp;%1<br>Sie wurden nicht erneut konfiguriert. Add @@ -18580,7 +18580,7 @@ Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim a Do not ask again. This will disable Copilot for now. - Nicht noch einmal nachfragen. Dies deaktiviert Copilot. + Nicht erneut nachfragen. Dies deaktiviert Copilot. Enables the Copilot integration. @@ -18961,7 +18961,7 @@ Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrek Re-enable warnings that were suppressed by selecting "Do Not Show Again" (for example, missing highlighter). - Alle Warnungen wieder aktivieren, die durch "Nicht noch einmal anzeigen" unterdrückt wurden (zum Beispiel fehlende Syntaxhervorhebung). + Alle Warnungen wieder aktivieren, die durch "Nicht erneut anzeigen" unterdrückt wurden (zum Beispiel fehlende Syntaxhervorhebung). Theme: @@ -20261,7 +20261,7 @@ konnte nicht unter Versionsverwaltung (%2) gestellt werden Locates files from a custom set of directories. Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet Dateien aus vom Benutzer gewählten Pfaden. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet Dateien aus vom Benutzer gewählten Pfaden. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. Add... @@ -20588,7 +20588,7 @@ Um es abzurufen, tippen Sie das Kürzel im Locator, gefolgt von einem Leerzeiche &Search Again - Noch einmal &suchen + Erneut &suchen Repla&ce with: @@ -20838,7 +20838,7 @@ Möchten Sie es beenden? Do not ask again. - Nicht noch einmal nachfragen. + Nicht erneut nachfragen. No themes found in installation. @@ -21599,7 +21599,7 @@ provided they were unmodified before the refactoring. Locates files from a global file system index (Spotlight, Locate, Everything). Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet Dateien aus einem globalen Dateisystemindex (Spotlight, Locate, Everything). Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet Dateien aus einem globalen Dateisystemindex (Spotlight, Locate, Everything). Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. Sort results @@ -23664,7 +23664,7 @@ z.B. name = "m_test_foo_": Defines the amount of time %1 waits before sending document changes to the server. If the document changes again while waiting, this timeout resets. Bestimmt die Zeit, die %1 vor dem Senden von Dokumentänderungen an den Server wartet. -Falls sich das Dokument innerhalb dieser Zeit wieder ändert, wird erneut die volle Zeit gewartet. +Falls sich das Dokument innerhalb dieser Zeit erneut ändert, wird nochmal die volle Zeit gewartet. Files greater than this will not be opened as documents in clangd. @@ -24066,7 +24066,7 @@ Flags: %3 Locates files that are included by C++ files of any open project. Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet alle Dateien die von allen C++-Dateien aller Projekte eingebunden werden. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet alle Dateien die von allen C++-Dateien aller Projekte eingebunden werden. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. collecting overrides... @@ -27011,7 +27011,7 @@ Sie werden möglicherweise gebeten, den Inhalt dieses Logs mitzuteilen, wenn Sie Could not connect to the in-process QML debugger. Do you want to retry? Konnte keine Verbindung zur Debuggerkomponente im Prozess herstellen. -Soll es noch einmal versucht werden? +Soll es erneut versucht werden? Starting %1 @@ -27664,11 +27664,11 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve Reopen dialog when application finishes - Dialog nach Beendigung der Anwendung wieder öffnen + Dialog nach Beendigung der Anwendung erneut öffnen Reopens this dialog when application finishes. - Öffnet den Dialog nach Beendigung der Anwendung wieder. + Öffnet den Dialog nach Beendigung der Anwendung erneut. Continue on attach @@ -28034,7 +28034,7 @@ Bitte wählen Sie einen 64-bit-Debugger in den Kit-Einstellungen für dieses Kit Reverse-execution history exhausted. Going forward again. - Keine weiteren rückwärts ausführbaren Schritte vorhanden. Führe sie wieder vorwärts aus. + Keine weiteren rückwärts ausführbaren Schritte vorhanden. Führe sie erneut vorwärts aus. Attempting to interrupt. @@ -31341,7 +31341,7 @@ Jetzt Commit ausführen? Rebase, merge or am is in progress. Finish or abort it and then try again. - Es ist eine Rebase-, Merge- oder am-Operation aktiv. Bitte beenden oder brechen Sie sie ab und versuchen Sie es noch einmal. + Es ist eine Rebase-, Merge- oder am-Operation aktiv. Bitte beenden oder brechen Sie sie ab und versuchen Sie es erneut. Stash local changes and pop when %1 finishes. @@ -38601,7 +38601,7 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z Locates files of all open projects. Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet Dateien in allen geöffneten Projekten. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet Dateien in allen geöffneten Projekten. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. All Projects @@ -38701,7 +38701,7 @@ Außer: %2 Locates files from the current document's project. Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet Dateien im Projekt des aktuellen Dokuments. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet Dateien im Projekt des aktuellen Dokuments. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. Project "%1" @@ -39451,7 +39451,7 @@ Bitte versuchen Sie es erneut. Locates files from all project directories. Append "+<number>" or ":<number>" to jump to the given line number. Append another "+<number>" or ":<number>" to jump to the column number as well. - Findet Dateien in allen Projektverzeichnissen. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie noch einmal "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. + Findet Dateien in allen Projektverzeichnissen. Fügen Sie "+<Zahl>" oder ":<Zahl>" an, um zur angegebenen Zeile zu springen. Fügen Sie erneut "+<Zahl>" oder ":<Zahl>" an, um auch zur angegebenen Spalte zu springen. Run Run Configuration @@ -40249,11 +40249,11 @@ Aktivieren Sie dies, wenn Sie 32bit-x86-Binärdateien erstellen wollen, ohne ein The following compiler was already configured:<br>&nbsp;%1<br>It was not configured again. - Der folgende Compiler ist bereits konfiguriert:<br>&nbsp;%1<br>Er wurde nicht noch einmal konfiguriert. + Der folgende Compiler ist bereits konfiguriert:<br>&nbsp;%1<br>Er wurde nicht erneut konfiguriert. The following compilers were already configured:<br>&nbsp;%1<br>They were not configured again. - Die folgenden Compiler wurden bereits konfiguriert:<br>&nbsp;%1<br>Sie wurden nicht noch einmal konfiguriert. + Die folgenden Compiler wurden bereits konfiguriert:<br>&nbsp;%1<br>Sie wurden nicht erneut konfiguriert. Clone of %1 @@ -47313,7 +47313,7 @@ Sie können eine Annotation "// @uri My.Module.Uri" hinzufügen, um de Could not connect to the in-process QML profiler within %1 s. Do you want to retry and wait %2 s? Innerhalb von %1 s konnte keine Verbindung zum QML-Profiler im Prozess hergestellt werden. -Wollen Sie es noch einmal versuchen und %2 s warten? +Wollen Sie es erneut versuchen und %2 s warten? %1 s @@ -56033,11 +56033,11 @@ Die Trace-Daten sind verloren. QtC::Utils Do not &ask again - Nicht noch einmal nach&fragen + Nicht erneut nach&fragen Do not &show again - Nicht noch einmal an&zeigen + Nicht erneut an&zeigen The class name must not contain namespace delimiters. @@ -56899,7 +56899,7 @@ Um eine Variable zu deaktivieren, stellen Sie der Zeile "#" voran. Do Not Show Again - Nicht noch einmal anzeigen + Nicht erneut anzeigen Close @@ -57842,7 +57842,7 @@ Wird ein Problem gefunden, dann wird die Anwendung angehalten und kann untersuch Go back one step in history. This will select the previously selected item. - Gehe einen Schritt im Verlauf zurück. Das vorher ausgewählte Element wird wieder ausgewählt. + Gehe einen Schritt im Verlauf zurück. Das vorher ausgewählte Element wird erneut ausgewählt. Go forward one step in history. From 4e50e1d6577a831e005945c89633a76e3f55de31 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Thu, 4 Apr 2024 16:03:13 +0200 Subject: [PATCH 0114/1060] German translation: Consistently use "Ergebnis" instead of "Resultat" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use it most and it is the simpler word. Task-number: QTCREATORBUG-29370 Change-Id: I0b672ed990cca9f21ddff3782595847742f902a3 Reviewed-by: Robert Löhning --- share/qtcreator/translations/qtcreator_de.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index a95fcb53242..c78a6933286 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -12365,7 +12365,7 @@ und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlaube Limit result description: - Beschreibung der Resultate begrenzen: + Beschreibung der Ergebnisse begrenzen: Limit number of lines shown in test result tooltip and description. @@ -20654,7 +20654,7 @@ Um es abzurufen, tippen Sie das Kürzel im Locator, gefolgt von einem Leerzeiche Filter Results - Resultate filtern + Ergebnisse filtern %1 %2 @@ -23642,7 +23642,7 @@ z.B. name = "m_test_foo_": <p>If background indexing is enabled, global symbol searches will yield more accurate results, at the cost of additional CPU load when the project is first opened. The indexing result is persisted in the project's build directory. If you disable background indexing, a faster, but less accurate, built-in indexer is used instead. The thread priority for building the background index can be adjusted since clangd 15.</p><p>Background Priority: Minimum priority, runs on idle CPUs. May leave 'performance' cores unused.</p><p>Normal Priority: Reduced priority compared to interactive work.</p><p>Low Priority: Same priority as other clangd work.</p> - <p>Wenn sie das globale Indizieren aktivieren, liefert die globale Symbolsuche genauere Resultate, es erhöht aber die CPU-Last beim ersten Öffnen von Projekten. Das Resultat der Indizierung wird im Build-Verzeichnis des Projekts gespeichert. Wenn sie das globale Indizieren deaktivieren, wird stattdessen ein schnellerer, aber weniger genauer, integrierter Indexer benutzt. Seit Clangd 15 können Sie die Priorität für die Indizierungs-Threads anpassen.</p><p>Hintergrund-Priorität: Niedrigste Priorität, läuft nur auf leerlaufenden CPUs. Kann "Performance"-Kerne ungenutzt lassen.</p><p>Normale Priorität: Geringere Priorität im Vergleich zu interaktiven Aktivitäten.</p><p>Niedrige Priorität: Dieselbe Priorität wie andere Clangd-Aktivitäten.</p> + <p>Wenn sie das globale Indizieren aktivieren, liefert die globale Symbolsuche genauere Ergebnisse, es erhöht aber die CPU-Last beim ersten Öffnen von Projekten. Das Ergebnis der Indizierung wird im Build-Verzeichnis des Projekts gespeichert. Wenn sie das globale Indizieren deaktivieren, wird stattdessen ein schnellerer, aber weniger genauer, integrierter Indexer benutzt. Seit Clangd 15 können Sie die Priorität für die Indizierungs-Threads anpassen.</p><p>Hintergrund-Priorität: Niedrigste Priorität, läuft nur auf leerlaufenden CPUs. Kann "Performance"-Kerne ungenutzt lassen.</p><p>Normale Priorität: Geringere Priorität im Vergleich zu interaktiven Aktivitäten.</p><p>Niedrige Priorität: Dieselbe Priorität wie andere Clangd-Aktivitäten.</p> <p>The C/C++ backend to use for switching between header and source files.</p><p>While the clangd implementation has more capabilities than the built-in code model, it tends to find false positives.</p><p>When "Try Both" is selected, clangd is used only if the built-in variant does not find anything.</p> @@ -23674,7 +23674,7 @@ Das integrierte Codemodell übernimmt Syntaxhervorhebung, Code-Vervollständigun The maximum number of completion results returned by clangd. - Die maximale Anzahl Resultate die von Clangd für die Code-Vervollständigung zurück gegeben werden. + Die maximale Anzahl Ergebnisse, die von Clangd für die Code-Vervollständigung zurückgegeben werden. Use clangd @@ -23694,7 +23694,7 @@ Das integrierte Codemodell übernimmt Syntaxhervorhebung, Code-Vervollständigun Completion results: - Anzahl der Resultate der Code-Vervollständigung: + Anzahl der Ergebnisse der Code-Vervollständigung: No limit @@ -45976,7 +45976,7 @@ Bitte aktualisieren Sie Ihr Kit (%3) oder wählen Sie eine mkspec für qmake, di Checking this option avoids unwanted side effects, but may result in inexact parsing results. - Diese Einstellung verhindert ungewollte Nebeneffekte, kann aber zu ungenauen Resultaten beim Auswerten führen. + Diese Einstellung verhindert ungewollte Nebeneffekte, kann aber zu ungenauen Ergebnissen beim Auswerten führen. Qmake From 1c905c698004a3d16d87cd46b1c607fe63681109 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 12:58:17 +0200 Subject: [PATCH 0115/1060] Utils: Shortcut File reading If the device can point us to the local equivalent of a file we can read that one instead. Change-Id: I002b5babae13677d5814b639ca40a62f23a8b374 Reviewed-by: hjk --- src/libs/utils/devicefileaccess.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/libs/utils/devicefileaccess.cpp b/src/libs/utils/devicefileaccess.cpp index 50d1f276ef1..303ffa6bf50 100644 --- a/src/libs/utils/devicefileaccess.cpp +++ b/src/libs/utils/devicefileaccess.cpp @@ -1059,6 +1059,10 @@ expected_str UnixDeviceFileAccess::fileContents(const FilePath &file if (disconnected()) return make_unexpected_disconnected(); + expected_str localSource = filePath.localSource(); + if (localSource && *localSource != filePath) + return localSource->fileContents(limit, offset); + QStringList args = {"if=" + filePath.path()}; if (limit > 0 || offset > 0) { const qint64 gcd = std::gcd(limit, offset); @@ -1088,6 +1092,10 @@ expected_str UnixDeviceFileAccess::writeFileContents(const FilePath &fil if (disconnected()) return make_unexpected_disconnected(); + expected_str localSource = filePath.localSource(); + if (localSource && *localSource != filePath) + return localSource->writeFileContents(data); + QStringList args = {"of=" + filePath.path()}; RunResult result = runInShell({"dd", args, OsType::OsTypeLinux}, data); From d3279f1e0b2989a3ca9326d207b2b7432580b065 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 15:51:53 +0200 Subject: [PATCH 0116/1060] FilePath: Improve speed of ::relativePathFrom Change-Id: Ie7aef2aeb01251edd6825fcd56a73ab65b57cbf5 Reviewed-by: hjk --- src/libs/utils/filepath.cpp | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/libs/utils/filepath.cpp b/src/libs/utils/filepath.cpp index 1b9b6e943c3..b62f222475c 100644 --- a/src/libs/utils/filepath.cpp +++ b/src/libs/utils/filepath.cpp @@ -19,9 +19,11 @@ #include #include #include -#include -#include #include +#include + +#include +#include #ifdef Q_OS_WIN #ifdef QTCREATOR_PCH_H @@ -1497,21 +1499,28 @@ FilePath FilePath::relativePathFrom(const FilePath &anchor) const FilePath absPath; QString filename; - if (isFile()) { + + const QList infos + = QtConcurrent::blockingMapped(QList{*this, anchor}, [](const FilePath &path) { + return path.filePathInfo(); + }); + + if (infos.first().fileFlags.testFlag(FilePathInfo::FileFlag::FileType)) { absPath = absolutePath(); filename = fileName(); - } else if (isDir()) { + } else if (infos.first().fileFlags.testFlag(FilePathInfo::FileFlag::DirectoryType)) { absPath = absoluteFilePath(); } else { return {}; } FilePath absoluteAnchorPath; - if (anchor.isFile()) + if (infos.last().fileFlags.testFlag(FilePathInfo::FileFlag::FileType)) absoluteAnchorPath = anchor.absolutePath(); - else if (anchor.isDir()) + else if (infos.last().fileFlags.testFlag(FilePathInfo::FileFlag::DirectoryType)) absoluteAnchorPath = anchor.absoluteFilePath(); else return {}; + QString relativeFilePath = calcRelativePath(absPath.pathView(), absoluteAnchorPath.pathView()); if (!filename.isEmpty()) { if (relativeFilePath == ".") From 0be8e6ed0183285daf1781bcdd536a933ff82a2f Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 12:47:28 +0200 Subject: [PATCH 0117/1060] ProjectExplorer: Always return a build folder The error handling is done elsewhere. Change-Id: Ie5fa937faf6447458117d355f1c6044c2f2d88ac Reviewed-by: hjk --- src/plugins/projectexplorer/buildconfiguration.cpp | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/plugins/projectexplorer/buildconfiguration.cpp b/src/plugins/projectexplorer/buildconfiguration.cpp index ee2d8208eb7..d8b19767303 100644 --- a/src/plugins/projectexplorer/buildconfiguration.cpp +++ b/src/plugins/projectexplorer/buildconfiguration.cpp @@ -625,16 +625,8 @@ FilePath BuildConfiguration::buildDirectoryFromTemplate(const FilePath &projectD auto buildDevice = BuildDeviceKitAspect::device(kit); - if (buildDir.isAbsolutePath()) { - bool isReachable = buildDevice->ensureReachable(buildDir); - if (!isReachable) - return {}; + if (buildDir.isAbsolutePath()) return buildDevice->rootPath().withNewMappedPath(buildDir); - } - - bool isReachable = buildDevice->ensureReachable(projectDir); - if (!isReachable) - return {}; const FilePath baseDir = buildDevice->rootPath().withNewMappedPath(projectDir); return baseDir.resolvePath(buildDir); From e8d6e4fc3412bd4bd3c4ae30421240eadbbb24c2 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Wed, 3 Apr 2024 15:58:07 +0200 Subject: [PATCH 0118/1060] iOS: Remove simulator management from settings page Simulators can be managed via Xcode, which must be installed anyway. Re- implementing this functionality is not useful, error-prone, and a maintenance burden. Point users to the corresponding Xcode documentation instead. Add a button for updating the list of simulators in the run configuration settings (which didn't update when simulators were changed in Xcode). Change-Id: I5a861f21851bb866d45a703f46bb20ed5df960e8 Reviewed-by: Leena Miettinen Reviewed-by: Qt CI Bot Reviewed-by: Marcus Tillmanns --- src/plugins/ios/CMakeLists.txt | 3 - src/plugins/ios/createsimulatordialog.cpp | 172 ---------- src/plugins/ios/createsimulatordialog.h | 46 --- src/plugins/ios/iosconfigurations.cpp | 28 -- src/plugins/ios/iosconfigurations.h | 3 - src/plugins/ios/iosrunconfiguration.cpp | 20 +- src/plugins/ios/iosrunconfiguration.h | 9 +- src/plugins/ios/iossettingspage.cpp | 343 +------------------ src/plugins/ios/simulatorinfomodel.cpp | 142 -------- src/plugins/ios/simulatorinfomodel.h | 37 -- src/plugins/ios/simulatoroperationdialog.cpp | 125 ------- src/plugins/ios/simulatoroperationdialog.h | 47 --- 12 files changed, 35 insertions(+), 940 deletions(-) delete mode 100644 src/plugins/ios/createsimulatordialog.cpp delete mode 100644 src/plugins/ios/createsimulatordialog.h delete mode 100644 src/plugins/ios/simulatorinfomodel.cpp delete mode 100644 src/plugins/ios/simulatorinfomodel.h delete mode 100644 src/plugins/ios/simulatoroperationdialog.cpp delete mode 100644 src/plugins/ios/simulatoroperationdialog.h diff --git a/src/plugins/ios/CMakeLists.txt b/src/plugins/ios/CMakeLists.txt index e6ec1665b2c..1b7256e43e5 100644 --- a/src/plugins/ios/CMakeLists.txt +++ b/src/plugins/ios/CMakeLists.txt @@ -2,7 +2,6 @@ add_qtc_plugin(Ios DEPENDS QmlDebug Qt::Xml PLUGIN_DEPENDS Core Debugger ProjectExplorer QmakeProjectManager CMakeProjectManager SOURCES - createsimulatordialog.cpp createsimulatordialog.h devicectlutils.cpp devicectlutils.h ios.qrc @@ -23,8 +22,6 @@ add_qtc_plugin(Ios iostoolhandler.cpp iostoolhandler.h iostr.h simulatorcontrol.cpp simulatorcontrol.h - simulatorinfomodel.cpp simulatorinfomodel.h - simulatoroperationdialog.cpp simulatoroperationdialog.h ) extend_qtc_plugin(Ios diff --git a/src/plugins/ios/createsimulatordialog.cpp b/src/plugins/ios/createsimulatordialog.cpp deleted file mode 100644 index bacba246f27..00000000000 --- a/src/plugins/ios/createsimulatordialog.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "createsimulatordialog.h" - -#include "iostr.h" -#include "simulatorcontrol.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace Ios::Internal { - -CreateSimulatorDialog::CreateSimulatorDialog(QWidget *parent) - : QDialog(parent) -{ - resize(320, 160); - setWindowTitle(Tr::tr("Create Simulator")); - - m_nameEdit = new QLineEdit(this); - m_deviceTypeCombo = new QComboBox(this); - m_runtimeCombo = new QComboBox(this); - - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - - using namespace Layouting; - - Column { - Form { - Tr::tr("Simulator name:"), m_nameEdit, br, - Tr::tr("Device type:"), m_deviceTypeCombo, br, - Tr::tr("OS version:"), m_runtimeCombo, br, - }, - buttonBox - }.attachTo(this); - - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - const auto enableOk = [this, buttonBox] { - buttonBox->button(QDialogButtonBox::Ok)->setEnabled( - !m_nameEdit->text().isEmpty() && - m_deviceTypeCombo->currentIndex() > 0 && - m_runtimeCombo->currentIndex() > 0); - }; - - connect(m_nameEdit, &QLineEdit::textChanged, this, enableOk); - connect(m_runtimeCombo, &QComboBox::currentIndexChanged, this, enableOk); - connect(m_deviceTypeCombo, &QComboBox::currentIndexChanged, this, [this, enableOk] { - populateRuntimes(m_deviceTypeCombo->currentData().value()); - enableOk(); - }); - - m_futureSync.addFuture(Utils::onResultReady(SimulatorControl::updateDeviceTypes(), this, - &CreateSimulatorDialog::populateDeviceTypes)); - - QFuture> runtimesfuture = SimulatorControl::updateRuntimes(); - Utils::onResultReady(runtimesfuture, this, [this](const QList &runtimes) { - m_runtimes = runtimes; - }); - m_futureSync.addFuture(runtimesfuture); - populateRuntimes(DeviceTypeInfo()); -} - -CreateSimulatorDialog::~CreateSimulatorDialog() = default; - -/*! - Returns the simulator name entered by user. - */ -QString CreateSimulatorDialog::name() const -{ - return m_nameEdit->text(); -} - -/*! - Returns the simulator runtime (OS version) selected by user. - Though the runtimes are filtered by the selected device type but the runtime camppatibility is - not checked. i.e. User can select the Runtime iOS 10.2 for iPhone 4 but the combination is not - possible as iOS 10.2 is not compatible with iPhone 4. In this case the command to create - simulator shall fail with an error message describing the compatibility. - */ -RuntimeInfo CreateSimulatorDialog::runtime() const -{ - return m_runtimeCombo->currentData().value(); -} - -/*! - Returns the selected device type. - */ -DeviceTypeInfo CreateSimulatorDialog::deviceType() const -{ - return m_deviceTypeCombo->currentData().value(); -} - -/*! - Populates the devices types. Similar device types are grouped together. - */ -void CreateSimulatorDialog::populateDeviceTypes(const QList &deviceTypes) -{ - m_deviceTypeCombo->clear(); - m_deviceTypeCombo->addItem(Tr::tr("None")); - - if (deviceTypes.isEmpty()) - return; - - m_deviceTypeCombo->insertSeparator(1); - - auto addItems = [this, deviceTypes](const QString &filter) { - const auto filteredTypes = Utils::filtered(deviceTypes, [filter](const DeviceTypeInfo &type){ - return type.name.contains(filter, Qt::CaseInsensitive); - }); - for (auto type : filteredTypes) { - m_deviceTypeCombo->addItem(type.name, QVariant::fromValue(type)); - } - return filteredTypes.count(); - }; - - if (addItems(QStringLiteral("iPhone")) > 0) - m_deviceTypeCombo->insertSeparator(m_deviceTypeCombo->count()); - if (addItems(QStringLiteral("iPad")) > 0) - m_deviceTypeCombo->insertSeparator(m_deviceTypeCombo->count()); - if (addItems(QStringLiteral("TV")) > 0) - m_deviceTypeCombo->insertSeparator(m_deviceTypeCombo->count()); - addItems(QStringLiteral("Watch")); -} - -/*! - Populates the available runtimes. Though the runtimes are filtered by the selected device type - but the runtime camppatibility is not checked. i.e. User can select the Runtime iOS 10.2 for - iPhone 4 but the combination is not possible as iOS 10.2 is not compatible with iPhone 4. In - this case the command to create simulator shall fail with an error message describing the - compatibility issue. - */ -void CreateSimulatorDialog::populateRuntimes(const DeviceTypeInfo &deviceType) -{ - m_runtimeCombo->clear(); - m_runtimeCombo->addItem(Tr::tr("None")); - - if (deviceType.name.isEmpty()) - return; - - m_runtimeCombo->insertSeparator(1); - - auto addItems = [this](const QString &filter) { - const auto filteredTypes = Utils::filtered(m_runtimes, [filter](const RuntimeInfo &runtime){ - return runtime.name.contains(filter, Qt::CaseInsensitive); - }); - for (auto runtime : filteredTypes) { - m_runtimeCombo->addItem(runtime.name, QVariant::fromValue(runtime)); - } - }; - - if (deviceType.name.contains(QStringLiteral("iPhone"))) - addItems(QStringLiteral("iOS")); - else if (deviceType.name.contains(QStringLiteral("iPad"))) - addItems(QStringLiteral("iOS")); - else if (deviceType.name.contains(QStringLiteral("TV"))) - addItems(QStringLiteral("tvOS")); - else if (deviceType.name.contains(QStringLiteral("Watch"))) - addItems(QStringLiteral("watchOS")); -} - -} // Ios::Internal diff --git a/src/plugins/ios/createsimulatordialog.h b/src/plugins/ios/createsimulatordialog.h deleted file mode 100644 index 9f269cc636e..00000000000 --- a/src/plugins/ios/createsimulatordialog.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include - -#include - -QT_BEGIN_NAMESPACE -class QComboBox; -class QLineEdit; -QT_END_NAMESPACE - -namespace Ios::Internal { - -class DeviceTypeInfo; -class RuntimeInfo; - -/*! - A dialog to select the iOS Device type and the runtime for a new - iOS simulator device. - */ -class CreateSimulatorDialog : public QDialog -{ -public: - explicit CreateSimulatorDialog(QWidget *parent = nullptr); - ~CreateSimulatorDialog() override; - - QString name() const; - RuntimeInfo runtime() const; - DeviceTypeInfo deviceType() const; - -private: - void populateDeviceTypes(const QList &deviceTypes); - void populateRuntimes(const DeviceTypeInfo &deviceType); - - QList m_runtimes; - - QLineEdit *m_nameEdit; - QComboBox *m_deviceTypeCombo; - QComboBox *m_runtimeCombo; - Utils::FutureSynchronizer m_futureSync; // Keep me last -}; - -} // Ios::Internal diff --git a/src/plugins/ios/iosconfigurations.cpp b/src/plugins/ios/iosconfigurations.cpp index ff995c6c2c7..d7ad6bf3bee 100644 --- a/src/plugins/ios/iosconfigurations.cpp +++ b/src/plugins/ios/iosconfigurations.cpp @@ -69,7 +69,6 @@ const bool IgnoreAllDevicesDefault = false; const char SettingsGroup[] = "IosConfigurations"; const char ignoreAllDevicesKey[] = "IgnoreAllDevices"; -const char screenshotDirPathKey[] = "ScreeshotDirPath"; const char provisioningTeamsTag[] = "IDEProvisioningTeams"; const char freeTeamTag[] = "isFreeProvisioningTeam"; @@ -343,19 +342,6 @@ void IosConfigurations::setIgnoreAllDevices(bool ignoreDevices) } } -void IosConfigurations::setScreenshotDir(const FilePath &path) -{ - if (m_instance->m_screenshotDir != path) { - m_instance->m_screenshotDir = path; - m_instance->save(); - } -} - -FilePath IosConfigurations::screenshotDir() -{ - return m_instance->m_screenshotDir; -} - FilePath IosConfigurations::developerPath() { return m_instance->m_developerPath; @@ -366,20 +352,11 @@ QVersionNumber IosConfigurations::xcodeVersion() return m_instance->m_xcodeVersion; } -static FilePath defaultScreenshotDirPath() -{ - return FilePath::fromUserInput( - QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).constFirst()); -} - void IosConfigurations::save() { QtcSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->setValueWithDefault(ignoreAllDevicesKey, m_ignoreAllDevices, IgnoreAllDevicesDefault); - settings->setValueWithDefault(screenshotDirPathKey, - m_screenshotDir.toSettings(), - defaultScreenshotDirPath().toSettings()); settings->endGroup(); } @@ -396,11 +373,6 @@ void IosConfigurations::load() QtcSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); m_ignoreAllDevices = settings->value(ignoreAllDevicesKey, IgnoreAllDevicesDefault).toBool(); - m_screenshotDir = FilePath::fromSettings(settings->value(screenshotDirPathKey)); - - if (!m_screenshotDir.isWritableDir()) - m_screenshotDir = defaultScreenshotDirPath(); - settings->endGroup(); } diff --git a/src/plugins/ios/iosconfigurations.h b/src/plugins/ios/iosconfigurations.h index 7b65f2f8e6b..953b872cd07 100644 --- a/src/plugins/ios/iosconfigurations.h +++ b/src/plugins/ios/iosconfigurations.h @@ -78,8 +78,6 @@ public: static void initialize(); static bool ignoreAllDevices(); static void setIgnoreAllDevices(bool ignoreDevices); - static void setScreenshotDir(const Utils::FilePath &path); - static Utils::FilePath screenshotDir(); static Utils::FilePath developerPath(); static QVersionNumber xcodeVersion(); static Utils::FilePath lldbPath(); @@ -103,7 +101,6 @@ private: void loadProvisioningData(bool notify = true); Utils::FilePath m_developerPath; - Utils::FilePath m_screenshotDir; QVersionNumber m_xcodeVersion; bool m_ignoreAllDevices; QFileSystemWatcher *m_provisioningDataWatcher = nullptr; diff --git a/src/plugins/ios/iosrunconfiguration.cpp b/src/plugins/ios/iosrunconfiguration.cpp index 676fb68724a..23a27e85f6a 100644 --- a/src/plugins/ios/iosrunconfiguration.cpp +++ b/src/plugins/ios/iosrunconfiguration.cpp @@ -21,10 +21,11 @@ #include #include +#include #include #include -#include #include +#include #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #include #include @@ -342,12 +344,25 @@ void IosDeviceTypeAspect::addToLayout(Layouting::LayoutItem &parent) m_deviceTypeLabel = new QLabel(Tr::tr("Device type:")); - parent.addItems({m_deviceTypeLabel, m_deviceTypeComboBox}); + m_updateButton = new QPushButton(Tr::tr("Update")); + + parent.addItems({m_deviceTypeLabel, m_deviceTypeComboBox, m_updateButton, Layouting::st}); updateValues(); connect(m_deviceTypeComboBox, &QComboBox::currentIndexChanged, this, &IosDeviceTypeAspect::setDeviceTypeIndex); + connect(m_updateButton, &QPushButton::clicked, this, [this] { + m_updateButton->setEnabled(false); + Utils::onFinished( + QFuture(SimulatorControl::updateAvailableSimulators(this)), + this, + [this](QFuture) { + m_updateButton->setEnabled(true); + m_deviceTypeModel.clear(); + updateValues(); + }); + }); } void IosDeviceTypeAspect::setDeviceTypeIndex(int devIndex) @@ -363,6 +378,7 @@ void IosDeviceTypeAspect::updateValues() bool showDeviceSelector = deviceType().type != IosDeviceType::IosDevice; m_deviceTypeLabel->setVisible(showDeviceSelector); m_deviceTypeComboBox->setVisible(showDeviceSelector); + m_updateButton->setVisible(showDeviceSelector); if (showDeviceSelector && m_deviceTypeModel.rowCount() == 0) { const QList devices = SimulatorControl::availableSimulators(); for (const SimulatorInfo &device : devices) { diff --git a/src/plugins/ios/iosrunconfiguration.h b/src/plugins/ios/iosrunconfiguration.h index baef05cd1d2..524369605c6 100644 --- a/src/plugins/ios/iosrunconfiguration.h +++ b/src/plugins/ios/iosrunconfiguration.h @@ -3,8 +3,6 @@ #pragma once -#include "iosconstants.h" -#include "iosconfigurations.h" #include "iossimulator.h" #include @@ -12,9 +10,13 @@ #include -#include #include +QT_BEGIN_NAMESPACE +class QComboBox; +class QPushButton; +QT_END_NAMESPACE + namespace Ios::Internal { class IosRunConfiguration; @@ -58,6 +60,7 @@ private: QStandardItemModel m_deviceTypeModel; QLabel *m_deviceTypeLabel = nullptr; QComboBox *m_deviceTypeComboBox = nullptr; + QPushButton *m_updateButton = nullptr; }; class IosRunConfiguration : public ProjectExplorer::RunConfiguration diff --git a/src/plugins/ios/iossettingspage.cpp b/src/plugins/ios/iossettingspage.cpp index 042dfca9af6..8c699ebc033 100644 --- a/src/plugins/ios/iossettingspage.cpp +++ b/src/plugins/ios/iossettingspage.cpp @@ -3,34 +3,17 @@ #include "iossettingspage.h" -#include "createsimulatordialog.h" #include "iosconfigurations.h" #include "iosconstants.h" #include "iostr.h" -#include "simulatorcontrol.h" -#include "simulatorinfomodel.h" -#include "simulatoroperationdialog.h" #include #include -#include -#include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include using namespace std::placeholders; @@ -47,43 +30,10 @@ private: void saveSettings(); - void onStart(); - void onCreate(); - void onReset(); - void onRename(); - void onDelete(); - void onScreenshot(); - void onSelectionChanged(); - private: - Utils::PathChooser *m_pathWidget; - QPushButton *m_startButton; - QPushButton *m_renameButton; - QPushButton *m_deleteButton; - QPushButton *m_resetButton; - QTreeView *m_deviceView; QCheckBox *m_deviceAskCheckBox; }; -const int simStartWarnCount = 4; - -static SimulatorInfoList selectedSimulators(const QTreeView *deviceTreeView) -{ - SimulatorInfoList list; - QItemSelectionModel *selectionModel = deviceTreeView->selectionModel(); - for (QModelIndex index: selectionModel->selectedRows()) - list << deviceTreeView->model()->data(index, Qt::UserRole).value(); - return list; -} - -static void onSimOperation(const SimulatorInfo &simInfo, - SimulatorOperationDialog *dlg, - const QString &contextStr, - const SimulatorControl::Response &response) -{ - dlg->addMessage(simInfo, response, contextStr); -} - IosSettingsWidget::IosSettingsWidget() { setWindowTitle(Tr::tr("iOS Configuration")); @@ -91,43 +41,14 @@ IosSettingsWidget::IosSettingsWidget() m_deviceAskCheckBox = new QCheckBox(Tr::tr("Ask about devices not in developer mode")); m_deviceAskCheckBox->setChecked(!IosConfigurations::ignoreAllDevices()); - m_renameButton = new QPushButton(Tr::tr("Rename")); - m_renameButton->setEnabled(false); - m_renameButton->setToolTip(Tr::tr("Rename a simulator device.")); - - m_deleteButton = new QPushButton(Tr::tr("Delete")); - m_deleteButton->setEnabled(false); - m_deleteButton->setToolTip(Tr::tr("Delete simulator devices.")); - - m_resetButton = new QPushButton(Tr::tr("Reset")); - m_resetButton->setEnabled(false); - m_resetButton->setToolTip(Tr::tr("Reset contents and settings of simulator devices.")); - - auto createButton = new QPushButton(Tr::tr("Create")); - createButton->setToolTip(Tr::tr("Create a new simulator device.")); - - m_startButton = new QPushButton(Tr::tr("Start")); - m_startButton->setEnabled(false); - m_startButton->setToolTip(Tr::tr("Start simulator devices.")); - - auto proxyModel = new QSortFilterProxyModel(this); - proxyModel->setSourceModel(new SimulatorInfoModel(this)); - - m_deviceView = new QTreeView; - m_deviceView->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding); - m_deviceView->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_deviceView->setSelectionBehavior(QAbstractItemView::SelectRows); - m_deviceView->setSortingEnabled(true); - m_deviceView->setModel(proxyModel); - m_deviceView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); - - m_pathWidget = new Utils::PathChooser; - m_pathWidget->setExpectedKind(Utils::PathChooser::ExistingDirectory); - m_pathWidget->lineEdit()->setReadOnly(true); - m_pathWidget->setFilePath(IosConfigurations::screenshotDir()); - m_pathWidget->addButton(Tr::tr("Screenshot"), this, - std::bind(&IosSettingsWidget::onScreenshot, this)); + auto xcodeLabel = new QLabel( + Tr::tr("Configure available simulator devices in Xcode.") + .arg("https://developer.apple.com/documentation/xcode/" + "running-your-app-in-simulator-or-on-a-device/" + "#Configure-the-list-of-simulated-devices")); + xcodeLabel->setOpenExternalLinks(true); + // clang-format off using namespace Layouting; Column { Group { @@ -136,33 +57,11 @@ IosSettingsWidget::IosSettingsWidget() }, Group { title(Tr::tr("Simulator")), - Column { - Row { - m_deviceView, - Column { - createButton, - st, // FIXME: Better some fixed space? - m_startButton, - m_renameButton, - m_resetButton, - m_deleteButton, - st - }, - }, - hr, - Row { Tr::tr("Screenshot directory:"), m_pathWidget } - } - } + Row { xcodeLabel } + }, + st }.attachTo(this); - - connect(m_startButton, &QPushButton::clicked, this, &IosSettingsWidget::onStart); - connect(createButton, &QPushButton::clicked, this, &IosSettingsWidget::onCreate); - connect(m_renameButton, &QPushButton::clicked, this, &IosSettingsWidget::onRename); - connect(m_resetButton, &QPushButton::clicked, this, &IosSettingsWidget::onReset); - connect(m_deleteButton, &QPushButton::clicked, this, &IosSettingsWidget::onDelete); - - connect(m_deviceView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &IosSettingsWidget::onSelectionChanged); + // clang-format on } IosSettingsWidget::~IosSettingsWidget() = default; @@ -173,229 +72,9 @@ void IosSettingsWidget::apply() IosConfigurations::updateAutomaticKitList(); } -/*! - Called on start button click. Selected simulator devices are started. Multiple devices can be - started simultaneously provided they in shutdown state. - */ -void IosSettingsWidget::onStart() -{ - const SimulatorInfoList simulatorInfoList = selectedSimulators(m_deviceView); - if (simulatorInfoList.isEmpty()) - return; - - if (simulatorInfoList.count() > simStartWarnCount) { - const QString message = - Tr::tr("You are trying to launch %n simulators simultaneously. This " - "will take significant system resources. Do you really want to " - "continue?", "", simulatorInfoList.count()); - const int buttonCode = QMessageBox::warning(this, Tr::tr("Simulator Start"), message, - QMessageBox::Ok | QMessageBox::Abort, - QMessageBox::Abort); - - if (buttonCode == QMessageBox::Abort) - return; - } - - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Starting %n simulator device(s)...", "", simulatorInfoList.count()), - Utils::NormalMessageFormat); - - QList> futureList; - for (const SimulatorInfo &info : simulatorInfoList) { - if (!info.isShutdown()) { - statusDialog->addMessage(Tr::tr("Cannot start simulator (%1, %2) in current state: %3.") - .arg(info.name) - .arg(info.runtimeName) - .arg(info.state), - Utils::StdErrFormat); - } else { - futureList << QFuture(Utils::onResultReady( - SimulatorControl::startSimulator(info.identifier), this, - std::bind(onSimOperation, info, statusDialog, Tr::tr("simulator start"), _1))); - } - } - - statusDialog->addFutures(futureList); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. -} - -/*! - Called on create button click. User is presented with the create simulator dialog and with the - selected options a new device is created. - */ -void IosSettingsWidget::onCreate() -{ - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Creating simulator device..."), Utils::NormalMessageFormat); - const auto onSimulatorCreate = [statusDialog](const QString &name, - const SimulatorControl::Response &response) { - if (response) { - statusDialog->addMessage(Tr::tr("Simulator device (%1) created.\nUDID: %2") - .arg(name) - .arg(response->simUdid), - Utils::StdOutFormat); - } else { - statusDialog->addMessage(Tr::tr("Simulator device (%1) creation failed.\nError: %2") - .arg(name) - .arg(response.error()), - Utils::StdErrFormat); - } - }; - - CreateSimulatorDialog createDialog(this); - if (createDialog.exec() == QDialog::Accepted) { - QFuture f = QFuture(Utils::onResultReady(SimulatorControl::createSimulator( - createDialog.name(), createDialog.deviceType(), createDialog.runtime()), - this, std::bind(onSimulatorCreate, createDialog.name(), _1))); - statusDialog->addFutures({ f }); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. - } -} - -/*! - Called on reset button click. Contents and settings of the selected devices are erased. Multiple - devices can be erased simultaneously provided they in shutdown state. - */ -void IosSettingsWidget::onReset() -{ - const SimulatorInfoList simulatorInfoList = selectedSimulators(m_deviceView); - if (simulatorInfoList.isEmpty()) - return; - - const int userInput = QMessageBox::question(this, Tr::tr("Reset"), - Tr::tr("Do you really want to reset the contents and settings" - " of the %n selected device(s)?", "", - simulatorInfoList.count())); - if (userInput == QMessageBox::No) - return; - - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Resetting contents and settings..."), - Utils::NormalMessageFormat); - - QList> futureList; - for (const SimulatorInfo &info : simulatorInfoList) { - futureList << QFuture(Utils::onResultReady( - SimulatorControl::resetSimulator(info.identifier), this, - std::bind(onSimOperation, info, statusDialog, Tr::tr("simulator reset"), _1))); - } - - statusDialog->addFutures(futureList); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. -} - -/*! - Called on rename button click. Selected device is renamed. Only one device can be renamed at a - time. Rename button is disabled on multi-selection. - */ -void IosSettingsWidget::onRename() -{ - const SimulatorInfoList simulatorInfoList = selectedSimulators(m_deviceView); - if (simulatorInfoList.isEmpty() || simulatorInfoList.count() > 1) - return; - - const SimulatorInfo &simInfo = simulatorInfoList.at(0); - const QString newName = QInputDialog::getText(this, Tr::tr("Rename %1").arg(simInfo.name), - Tr::tr("Enter new name:")); - if (newName.isEmpty()) - return; - - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Renaming simulator device..."), Utils::NormalMessageFormat); - QFuture f = QFuture(Utils::onResultReady( - SimulatorControl::renameSimulator(simInfo.identifier, newName), this, - std::bind(onSimOperation, simInfo, statusDialog, Tr::tr("simulator rename"), _1))); - statusDialog->addFutures({f}); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. -} - -/*! - Called on delete button click. Selected devices are deleted. Multiple devices can be deleted - simultaneously provided they in shutdown state. - */ -void IosSettingsWidget::onDelete() -{ - const SimulatorInfoList simulatorInfoList = selectedSimulators(m_deviceView); - if (simulatorInfoList.isEmpty()) - return; - - const int userInput = - QMessageBox::question(this, Tr::tr("Delete Device"), - Tr::tr("Do you really want to delete the %n selected " - "device(s)?", "", simulatorInfoList.count())); - if (userInput == QMessageBox::No) - return; - - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Deleting %n simulator device(s)...", "", simulatorInfoList.count()), - Utils::NormalMessageFormat); - QList> futureList; - for (const SimulatorInfo &info : simulatorInfoList) { - futureList << QFuture(Utils::onResultReady( - SimulatorControl::deleteSimulator(info.identifier), this, - std::bind(onSimOperation, info, statusDialog, Tr::tr("simulator delete"), _1))); - } - - statusDialog->addFutures(futureList); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. -} - -/*! - Called on screenshot button click. Screenshot of the selected devices are saved to the selected - path. Screenshot from multiple devices can be taken simultaneously provided they in booted state. - */ -void IosSettingsWidget::onScreenshot() -{ - const SimulatorInfoList simulatorInfoList = selectedSimulators(m_deviceView); - if (simulatorInfoList.isEmpty()) - return; - - const auto generatePath = [this](const SimulatorInfo &info) { - const QString fileName = QString("%1_%2_%3.png").arg(info.name).arg(info.runtimeName) - .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss-z")).replace(' ', '_'); - return m_pathWidget->filePath().pathAppended(fileName).toString(); - }; - - QPointer statusDialog = new SimulatorOperationDialog(this); - statusDialog->setAttribute(Qt::WA_DeleteOnClose); - statusDialog->addMessage(Tr::tr("Capturing screenshots from %n device(s)...", "", - simulatorInfoList.count()), Utils::NormalMessageFormat); - QList> futureList; - for (const SimulatorInfo &info : simulatorInfoList) { - futureList << QFuture(Utils::onResultReady( - SimulatorControl::takeSceenshot(info.identifier, generatePath(info)), this, - std::bind(onSimOperation, info, statusDialog, Tr::tr("simulator screenshot"), _1))); - } - - statusDialog->addFutures(futureList); - statusDialog->exec(); // Modal dialog returns only when all the operations are done or cancelled. -} - -void IosSettingsWidget::onSelectionChanged() -{ - const SimulatorInfoList infoList = selectedSimulators(m_deviceView); - const bool hasRunning = Utils::anyOf(infoList, [](const SimulatorInfo &info) { - return info.isBooted(); - }); - const bool hasShutdown = Utils::anyOf(infoList, [](const SimulatorInfo &info) { - return info.isShutdown(); - }); - m_startButton->setEnabled(hasShutdown); - m_deleteButton->setEnabled(hasShutdown); - m_resetButton->setEnabled(hasShutdown); - m_renameButton->setEnabled(infoList.count() == 1 && hasShutdown); - m_pathWidget->buttonAtIndex(1)->setEnabled(hasRunning); // Screenshot button -} - void IosSettingsWidget::saveSettings() { IosConfigurations::setIgnoreAllDevices(!m_deviceAskCheckBox->isChecked()); - IosConfigurations::setScreenshotDir(m_pathWidget->filePath()); } // IosSettingsPage diff --git a/src/plugins/ios/simulatorinfomodel.cpp b/src/plugins/ios/simulatorinfomodel.cpp deleted file mode 100644 index dce56467134..00000000000 --- a/src/plugins/ios/simulatorinfomodel.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "simulatorinfomodel.h" - -#include "iostr.h" - -#include -#include - -#include - -namespace Ios::Internal { - -using namespace std::placeholders; - -const int colCount = 3; -const int nameCol = 0; -const int runtimeCol = 1; -const int stateCol = 2; -const int deviceUpdateInterval = 1000; // Update simulator state every 1 sec. - -SimulatorInfoModel::SimulatorInfoModel(QObject *parent) : - QAbstractItemModel(parent) -{ - requestSimulatorInfo(); - - auto updateTimer = new QTimer(this); - connect(updateTimer, &QTimer::timeout, this, &SimulatorInfoModel::requestSimulatorInfo); - updateTimer->setInterval(deviceUpdateInterval); - updateTimer->start(); -} - -QVariant SimulatorInfoModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return {}; - - const SimulatorInfo &simInfo = m_simList[index.row()]; - if (role == Qt::EditRole || role == Qt::DisplayRole) { - switch (index.column()) { - case nameCol: - return simInfo.name; - case runtimeCol: - return simInfo.runtimeName; - case stateCol: - return simInfo.state; - default: - return ""; - } - } else if (role == Qt::ToolTipRole) { - return Tr::tr("UDID: %1").arg(simInfo.identifier); - } else if (role == Qt::UserRole) { - return QVariant::fromValue(simInfo); - } - - return {}; -} - -int SimulatorInfoModel::rowCount(const QModelIndex &parent) const -{ - if (!parent.isValid()) - return m_simList.count(); - return 0; -} - -int SimulatorInfoModel::columnCount(const QModelIndex &parent) const -{ - Q_UNUSED(parent) - return colCount; -} - -QVariant SimulatorInfoModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (orientation == Qt::Vertical || section > colCount) - return {}; - - if (role == Qt::DisplayRole) { - switch (section) { - case nameCol: - return Tr::tr("Simulator Name"); - case runtimeCol: - return Tr::tr("Runtime"); - case stateCol: - return Tr::tr("Current State"); - default: - return {}; - } - } - - return {}; -} - -QModelIndex SimulatorInfoModel::index(int row, int column, const QModelIndex &parent) const -{ - return hasIndex(row, column, parent) ? createIndex(row, column) : QModelIndex(); -} - -QModelIndex SimulatorInfoModel::parent(const QModelIndex &) const -{ - return {}; -} - -void SimulatorInfoModel::requestSimulatorInfo() -{ - m_fetchFuture.flushFinishedFutures(); - if (!m_fetchFuture.isEmpty()) - return; // Ignore the request if the last request is still pending. - - m_fetchFuture.addFuture(Utils::onResultReady(SimulatorControl::updateAvailableSimulators(this), - this, &SimulatorInfoModel::populateSimulators)); -} - -void SimulatorInfoModel::populateSimulators(const SimulatorInfoList &simulatorList) -{ - if (m_simList.isEmpty() || m_simList.count() != simulatorList.count()) { - // Reset the model in case of addition or deletion. - beginResetModel(); - m_simList = simulatorList; - endResetModel(); - } else { - // update the rows with data chagne. e.g. state changes. - auto newItr = simulatorList.cbegin(); - int start = -1, end = -1; - std::list> updatedIndexes; - for (auto itr = m_simList.cbegin(); itr < m_simList.cend(); ++itr, ++newItr) { - if (*itr == *newItr) { - if (end != -1) - updatedIndexes.emplace_back(start, end - 1); - start = std::distance(m_simList.cbegin(), itr); - end = -1; - } else { - end = std::distance(m_simList.cbegin(), itr); - } - } - m_simList = simulatorList; - for (auto pair: updatedIndexes) - emit dataChanged(index(pair.first,0), index(pair.second, colCount - 1)); - } -} - -} // Ios::Internal diff --git a/src/plugins/ios/simulatorinfomodel.h b/src/plugins/ios/simulatorinfomodel.h deleted file mode 100644 index c5769000d32..00000000000 --- a/src/plugins/ios/simulatorinfomodel.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "simulatorcontrol.h" - -#include - -#include - -namespace Ios::Internal { - -using SimulatorInfoList = QList; - -class SimulatorInfoModel : public QAbstractItemModel -{ -public: - SimulatorInfoModel(QObject *parent = nullptr); - - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; - QModelIndex parent(const QModelIndex &) const override; - -private: - void requestSimulatorInfo(); - void populateSimulators(const SimulatorInfoList &simulatorList); - - Utils::FutureSynchronizer m_fetchFuture; - SimulatorInfoList m_simList; -}; - -} // Ios::Internal diff --git a/src/plugins/ios/simulatoroperationdialog.cpp b/src/plugins/ios/simulatoroperationdialog.cpp deleted file mode 100644 index b260f503101..00000000000 --- a/src/plugins/ios/simulatoroperationdialog.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "simulatoroperationdialog.h" - -#include "iostr.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace Ios::Internal { - -static Q_LOGGING_CATEGORY(iosCommon, "qtc.ios.common", QtWarningMsg) - -SimulatorOperationDialog::SimulatorOperationDialog(QWidget *parent) : - // TODO: Maximize buttong only because of QTBUG-41932 - QDialog(parent,Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint) -{ - resize(580, 320); - setModal(true); - setWindowTitle(Tr::tr("Simulator Operation Status")); - - auto messageEdit = new QPlainTextEdit; - messageEdit->setReadOnly(true); - - m_progressBar = new QProgressBar; - m_progressBar->setMaximum(0); - m_progressBar->setValue(-1); - - m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); - - m_formatter = new Utils::OutputFormatter; - m_formatter->setPlainTextEdit(messageEdit); - - using namespace Layouting; - - Column { - messageEdit, - m_progressBar, - m_buttonBox - }.attachTo(this); - - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); -} - -SimulatorOperationDialog::~SimulatorOperationDialog() -{ - // Cancel all pending futures. - const auto futureWatchList = m_futureWatchList; - for (auto watcher : futureWatchList) { - if (!watcher->isFinished()) - watcher->cancel(); - } - - // wait for futures to finish - for (auto watcher : futureWatchList) { - if (!watcher->isFinished()) - watcher->waitForFinished(); - delete watcher; - } - - delete m_formatter; -} - -void SimulatorOperationDialog::addFutures(const QList > &futureList) -{ - for (auto future : futureList) { - if (!future.isFinished() || !future.isCanceled()) { - auto watcher = new QFutureWatcher; - connect(watcher, &QFutureWatcherBase::finished, this, [this, watcher] { - m_futureWatchList.removeAll(watcher); - watcher->deleteLater(); - updateInputs(); - }); - watcher->setFuture(future); - m_futureWatchList << watcher; - } - } - updateInputs(); -} - -void SimulatorOperationDialog::addMessage(const QString &message, Utils::OutputFormat format) -{ - m_formatter->appendMessage(message + "\n\n", format); -} - -void SimulatorOperationDialog::addMessage(const SimulatorInfo &siminfo, - const SimulatorControl::Response &response, - const QString &context) -{ - if (response) { - QTC_CHECK(siminfo.identifier == response->simUdid); - addMessage(Tr::tr("%1, %2\nOperation %3 completed successfully.").arg(siminfo.name) - .arg(siminfo.runtimeName).arg(context), Utils::StdOutFormat); - } else { - QString erroMsg = response.error(); - QString message = Tr::tr("%1, %2\nOperation %3 failed.\nUDID: %4\nError: %5").arg(siminfo.name) - .arg(siminfo.runtimeName).arg(context).arg(siminfo.identifier) - .arg(erroMsg.isEmpty() ? Tr::tr("Unknown") : erroMsg); - addMessage(message, Utils::StdErrFormat); - qCDebug(iosCommon) << message; - } -} - -void SimulatorOperationDialog::updateInputs() -{ - bool enableOk = m_futureWatchList.isEmpty(); - m_buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(!enableOk); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enableOk); - if (enableOk) { - addMessage(Tr::tr("Done."), Utils::NormalMessageFormat); - m_progressBar->setMaximum(1); // Stop progress bar. - } -} - -} // Ios::Internal diff --git a/src/plugins/ios/simulatoroperationdialog.h b/src/plugins/ios/simulatoroperationdialog.h deleted file mode 100644 index 46cbb3f787e..00000000000 --- a/src/plugins/ios/simulatoroperationdialog.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2017 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "simulatorcontrol.h" - -#include - -#include -#include -#include - -QT_BEGIN_NAMESPACE -class QDialogButtonBox; -class QProgressBar; -QT_END_NAMESPACE - -namespace Utils { class OutputFormatter; } - -namespace Ios::Internal { - -class SimulatorOperationDialog : public QDialog -{ - -public: - explicit SimulatorOperationDialog(QWidget *parent = nullptr); - ~SimulatorOperationDialog() override; - -public: - void addFutures(const QList > &futureList); - void addMessage(const QString &message, Utils::OutputFormat format); - void addMessage(const SimulatorInfo &siminfo, - const SimulatorControl::Response &response, - const QString &context); - -private: - void updateInputs(); - - Utils::OutputFormatter *m_formatter = nullptr; - - QList *> m_futureWatchList; - QProgressBar *m_progressBar; - QDialogButtonBox *m_buttonBox; -}; - -} // Ios::Internal From 574ad7a4a20d03dbe5fcc668e9edb0c68bd7d955 Mon Sep 17 00:00:00 2001 From: Jussi Witick Date: Thu, 28 Mar 2024 09:38:12 +0200 Subject: [PATCH 0119/1060] Fix QSR wizard cmake-project template Latest changes to QSR tooling added limit checking for certain properties, so the cmake-project template needs to be updated slightly. Additionally remove the import versioning. Task-number: QSR-2398 Change-Id: I55542c9fd74ebd950b6aeb9b64a22dde177c5a4f Reviewed-by: Reviewed-by: Teemu Holappa --- src/plugins/saferenderer/wizards/qsrapp2_1/main.qml.tpl | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/plugins/saferenderer/wizards/qsrapp2_1/main.qml.tpl b/src/plugins/saferenderer/wizards/qsrapp2_1/main.qml.tpl index 94fccebcb2a..9f3130bbf0a 100644 --- a/src/plugins/saferenderer/wizards/qsrapp2_1/main.qml.tpl +++ b/src/plugins/saferenderer/wizards/qsrapp2_1/main.qml.tpl @@ -1,5 +1,5 @@ -import Qt.SafeRenderer 2.0 -import QtQuick.Window 2.15 +import Qt.SafeRenderer +import QtQuick.Window Window { id: window @@ -14,13 +14,12 @@ Window { x: 206 y: 208 width: 340 - height: 34 + height: 40 color: "#8ae234" fillColor: "black" text: "Hello Qt Safe Renderer!" font.family: "Lato" horizontalAlignment: Text.AlignLeft font.pixelSize: 32 - runtimeEditable: true } } From dd876dc4054b06638567afbdc3a849d56e99669d Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Tue, 9 Apr 2024 09:37:03 +0200 Subject: [PATCH 0120/1060] Doc: Adapt to removal of iOS Simulator management Amends e8d6e4fc3412bd4bd3c4ae30421240eadbbb24c2 Change-Id: Ia3cc2388ded5643aaaa129e9d11da4ac28d6d008 Reviewed-by: Leena Miettinen --- .../images/qtcreator-ios-preferences.png | Bin 51597 -> 0 bytes doc/qtcreator/src/ios/creator-ios-dev.qdoc | 43 +++--------------- 2 files changed, 6 insertions(+), 37 deletions(-) delete mode 100644 doc/qtcreator/images/qtcreator-ios-preferences.png diff --git a/doc/qtcreator/images/qtcreator-ios-preferences.png b/doc/qtcreator/images/qtcreator-ios-preferences.png deleted file mode 100644 index 935a528d6cba7971bced2ed52d86c29b46462054..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 51597 zcmeAS@N?(olHy`uVBq!ia0y~yU=?9tVEV?v%)r3FF8t~)0|S#!fKQ04wT-QwzJaNk zxr3tlw+7o?`8A3S)Fq5QRvuU}0~ zZFf&kKww~2cFwV5$9C@Ab?DHcsOXse`}a?qHoc*tamC7&#lVo40IPwQALl9Xl9uuQKFb>FDfSw{G2}$&*{#+NMsO#!!5pq4=S< zkME>OlNeIpY}~j>F)fcF<~l?2bH>O-hNgE57cJViZ=brl#;q5B7;-K1L zhE&{oGdJ2_+Fhg}S;=pi_*R9ewSubm*y5$)uS#9s!aCcR`;fq8rR}^+avOGRyyWou z!i4rc0h6@OhyHhIX~}72=MeO&k3RqAjNa_l-oq}lSxfd!pF7j`+l-CR9=|!GH-}U3 z;G~!DPKv6nx~TB;$Kw|tlg_#?%4fQNY>QRkiLWK;PA&BlM3~h+C$3v{dqcvHC&FcW ze%y1P!LFX}vwA20$*z5lK|B&Ak5;UkEaKVao;+pE3u%?33tqmv;@PEgRQa-J_=P&h zARZ}abxpZL*X<73SVSggO%SPVS|VX^*UEF^k`*rH9UoXHC2dH#r>Hqe5LQ?Jy{tGAfbYwAHzjM)j`lDN4UtceG&HVnd z^xU<1xd-1KkKXh2<+ayg?P@T(z#m``4pD@);lW0z_WjvNUx2HCw>dT(=&@!s%Y}UWkGc1 zZv}l%O{M7OaiuJtL;nR|2co_>q_eI*+o#J|YbE2VIr`fXC zy?!fqc7Ie_eQneAGnV(Pd*^$0Da2ioy|^mq&b^FLLBk%G1!pqs#G9SeMT9=|3ai z85JxmvRL@WvZ#~&8NxHB>Xnf2$|M$Gp!BvE>cM8ZC2;?%Nru zo0Lo2Pi-r0eraxcalK@lzND?d+oRsWN6yCA-!G;1(zCUKVpt-! z)vxAZiV?ccre#ojQPVYyxgqY|*@#fjF5WjMgbLTbSQorZLPO=KLZ-g!HFY%?O}3_p z&Q|3GGtCSy&2XC)BqBIzjkcWWl9N%pmZ%-glKOOv>wteym)Uk7#^sJmOEnBW9QMAp zdYZ`Hi*YueTD(7AT)cdS=q+FA9n(76pKEy8Torrfd1j~h7xh`u;`fiKblolRnpn#| z;rZcTYi~_*VRZ1WxaQf_=oG{=V7BmpP1gLRa+`?GO6RjS^!elX$DFE7K+ z^@pY(J-+O;#mZ7m*YYjm-)$ZS?J4hHFLldz_Vu&d)a166MSZ_@aL)_((@*CtYU2ES z+vCfUpBF5bM)Wc+_b#0~Ex(Arr)Sq|m7~cAyMt`%-@Qq{dt~;aUXfI;g_~#j{Nzeq zxA4)wqWZ&=l6>=~z0#PyM*H4{id$_H4{v|J%Ck^%LB=lAJkO8*Z3*$5mv2v$T+>>= zW$6x?)DxjQ9nAax#!m?wfYE543 zwX+|CtIq7HGrJ^UsH2&-cJD){y>TVS-OsG`{d)JgT%mRfldzxW(bHi}Gfmfj2tRUU z+tL|H9J?&kmJ|vn#CTnleS373dQ8{q+ZDx&7Qf|Or}jzt-Z|ZhJv(3Vetx8MKt$MM zWxuE9rbHW2(V!^|mjdK3-`T*X_OxyHzg0mt-o;nd&sog9@z?SD%wpLivls0ZaX;%L zxctchUq4rg3p^e(J7-LJq~On~d*@?B>!%A9o~2C5_4b`pkCudb6rQ{_`CW0zT6Z1I zS+=T-ZEsB*^b}pgw`>xrT=pX4@ytaUTg&9SatebTyDV;G&b|5MyRqxFNH&QguZ?ND zyuzm{U9vQnV07`8SuuNW*ff=9xgegs_Z@#UId?rjUstfLIpBc3=Cw1XMf78HPd`o$FfDtf1-2XN&GXZ`C&#%1(DmA zMhL!~c|0v1{))yCV_@Y9RrV|KV=>?#}mi>#dwB z%zj2VcHOzLw`}RL&u)sYmAn1yp6`*)dZos8X3sQ{r+@Ezmd{-xA(5v!@9zU2_Js}p zK~u`}{bvUoyu8IL=gD|wrtVSIeVj@YKfYVCgnO^WN~6a19XyuY5gI#|WR!)a6bW9` zJSu58{pqd66BcPl#de*adrO!vCf6)_Q=`7+DvyuWAK!TWcUl^B`TdD>?qnE))=3 zUCr!Wkrv;j&2Yc-rI|%U@zK|F=kDsc@~hvjk$1|=9^KwwjGA$qjSjKh2%6H}HZgE> z!{-aStDChP8w$UAp#+mC168JUlm>o?Cc;6GwoH2;RAmVVOC zaIcH!9xj>ZRawkYbR#Hy(xU|x!7~k(gKCR}9ZPTgEn{EUkRK!yJz=uQ+r>ve-q?Sn zSntWCIrF!P9Dh=E--RdsO;>+%m$2x{=*aM@UrCAoGxuxW)jhhSMlMh7(G(@427Qwc z7QJs(K@qe|Bz^u2H5VUyyFHDq%U^h2?z+8W#g7=*u3t+G78Z(H*nhKLdScVJ1&g0* zw`E)`(hBl<;GlL^?lr@O$Ll7G^s{+>6nUuWdZ%)ai9xELQ?tM5l!RZ`O6IEf86WcV zIHc(MO?95s3jU)3HEr7aX1Q6%diy?S%v+UeTHLpv+wlFgMRnZPyYFumVVo{9`G(Qf z9Tp1;jkz^G}9F?(@xaV)=m+7S-HIOUQfY?XX24#J6igF)LghxB7(>LZt0{)f{L2+l=!AU z>iBZ=O3}4x5v7KQX6N<4{a<@n)iT(0;{VqCPaP*79Cd!w&7HaC=szP7y{}p4G%ee% zPl-7kIg!h&P~?nsKYLNR!|G4jr%PsVKAPMxW%FO2NT#))9kz(uS2soLtWHZTPWR?0 zNWW}#y+$KyUQY5+;crG?eQIC;bLi}5csU&wv@<+JeB?%EH z?=CTwqrohEznZsubg?UFZhN|xeI}oiQ;<#Qp8uIIX0K>2FsS)c_@m-udw+|qg=g|F z-xtAN;KsR0#?kZo6F^P+s@Lb8OYHmdCx|e!ua&U+eYJJN6s5#Z_wVof82`g1Ip)W! z&jQanRb2NgXtJIEJ%8SDUhzk+azEUj9TB$j_xmC^Ny$-w#dD$pN7E7y0T#y~6^!5CJ&opzjtPm27S328peIx@ zS-jRkaz;gE#G~8)N_IcoqReKTwMFOt`=yb^llIo$ycOG_#PG*Ogi)bcgUNv{kfniV z5eI{$iy(thhY~}IfGfiZg)W8(j<^(vsC7B+RlguVg?~~Z9r=Wi>=DM!j#8PZ+*H10*l%hzAtc=rmYR4U_vnG=<}guPgImla*v z`@nhg(skc1@7g72v$j-z%9YO_j`_Xk+;sWg&(CMywlORa_~aJ&aG~uz+q`wR-rbp~ z)hWL+`<^sc(*3|!e;jju9}P`izVegn@@LbunHrc*$hzjAWP zvGqD%BR8k-X0@uX$~8=Z$z9sp7K|0?h0e^u@h{+7JdY)8Ixz$=)GKz$-<=pHyMD>6Z?P|zJ@(xC_Gq0*{_XWwrq2y~Te1FRcqW60 z>pzWYN%||^&HuJ!`L`WnvhII1>I!2nPE5YM{+-nhc@73Hg?bVD8`HmD_?9?bTufE= zN9Vpu@4p)NN@6Zee0=$>zU=aOoD5tF$2O& zS-T&JbFW|hic`$~_{Q`!=hD{I??S4UFRzVWdF`3oo0QeHHBt9{WsYB;&cfhoAaS%t zDlk@kh5OX|zRfF6`HC^P9=tEez!1p7u!w`fMUbIGi9x`X;m7tso>Ny>urVlWteV!G zxLCsN?KKI8o+V+{TO+!6CKitBQ*xdJAm@4|rtvxH`LRGz(*Dc>m_gM&2d|2G#(l%qMwb z<%u5JTrv#;V#XVPB~`b&-;;h6d+V>7D}yGJhoD0jLlDaZr3MkkB^)0VT^ke#p%33R zr^z!r*xyeCrj@X>zTN1csd?K8MCb=G%cB>_t)$0>O;H@PID#a5$7P)ze zuJoVyY0CMAPnWb71zlYgsDFRWyqhyqzdsPTv@0;?t$$#XZTdOO$0zomd6Vbl>kaey{{L!l0tq%f^Ze*+wdcDKpXME{ww9JHY-cAwVz0kbtyw>(Xtl(C zORK_J6Y9@j`SC(&Zin%tT(^a3A}^)idR)pjFtL(bYR-^vsPg2$!{sGE9=hvGHi15qVR;ln^UC+SFkt{_ph0i=cPTuwV9cx|f&pq#s zFt0rB|0igU+uWQdy3>^w{|vg)62!wH$Zcz<-L?ymUg6RaVe>jxaN}FeTM=t`D_z(A`t$R2VYzIzL;G9b z3$96J)~=UoYjXp+1omH=zFWrDsPC$E?Cfn%J93X-xxXN{ywcgHYuA?RGcM1Z9lz~I z(3gy)UCVY)(>=Po__Cs`}o++A4t>+^b=dJo2)iwP| zj`N&n#tysR8F+gi2wgQfqV>QVb+PkR;Y%8K^D9Q&P(L_nmc74=aluX1R;?h`X-{W$ z{e7}HH*DYbWj%|7*XmqtZxHgVYGAxSVVaV*uC(;*iD%D;{s?;V;vPqX@sbrx;ZJ@n z*s2!&JFi*4eY?a7Nuf)t{*(v(@sgXj|54DCv>6*Voe=j(NL_H_V$hWDDZ5W5Gj^>_ zlw72#cBiDv=g$lgUJss65-m=ihV9D!Pq%24H_E-qF1|DK|AXu|DNOEl{~@M>yqy3}~=*`gfHtSO#>h4Ol< z#ZI4$=6S}$nHe}s;T!2Haj<#tk>6 zcl=3zv+PoOSHs#R5pR9gu4PzVxJZ#9e0OkdAwWvVg6y!X5Aqq<3( z;aFAmafX;>-+8BaZeU$9W&NY*19x1q3S|t;B5D?t?-%(jTrPC|uJxObr3tmWE?r}k zFjJiyn{d8x67Q0T*nJnwG<{ZSo?%>ldFr`IMt()YH(ss(vYvUi;I6fH2h0+t@Oo-) zy5vOE^pCX@14g~9puI~ zAtA`7ZgFbt+)nGMBJK^d?&Nt%PrdWGm?z@;z9_acEdf8x3e+UdSAAciaeLCqUr+x$ zVl}L1-0^V##Y0Og3}5=qQ$8!YKtg#@$}!V(kqc~8|DD?8wEgX?KQ+ud4z*1YiF|1? zrO@8&h(WZMlv02HD(T#{O!r;x=zbG8eKI-)l*%Woc?a6GD6jqTx6#6;{`}Gv`(rPK z8Gc<7ckJW+sCA5+MY9~Zb|^YsahWAv*D0al?h)G_Q!`bheeVlC&7&T1o+q@rKGa>G zV!6Qo_bN7@2?tI-y%o9Vm90mVM5qD7l_!5Pg+zF2$|s4OpS*xa*{RF_>lM}O7P}qx z-+RZ`F;z0KvP#eG$Al?L`g7UNSa7am?9S0lD(RjfGJWN_d8dpR-fV&g@-mUH|2{0J zYx)-|KX0eV<7L&Rg>G***)by$>rrM0G9OFRxgE`9IQ)vWS@%}!N{UF)9O)`BJx{TI@o zJ%e;Af_*iQ&UWy;cJI9Fgqwk~=reu&4`@IcUUAg03I;}Bw-sG(( zirZSYsQ6BKBz*Avr7nNIrw@O2wohBMg=yc)$=Cl+Pd?DFz()Avl8SjuG4onoybEWm zuqL#&HF&$6TDLUZECjEMHif!w&>Qi71MTzRQg?0Ixi`7 zX_85FS3iFXU;V`P=f``OL@@ooXR%e6!%I-twYalMjd@e_?blIVvsG>~Y&%iCr7h^d zi`7eRaK;2LVl8`;eP{ZCJ@XYd9o@bAz@q1?OB3dc*x22uPS#w<6qx^bdX=u`y6WKV z4SF-Rl(X|6{gV)kZ4vaH6`=|ZruBQpj^7OOQ+Gv#&D2F(9({K2I;_sSWJe-{vMOVP zV^B$HAH#;FBEr!J%2_96^nT+o4BaB~S>>e|XVQUf&(F=8uqZK5R{Oq37pML%wWSim zN?(mTH%)Dv`K88G<5tjyifh%$n%_K@zc}5xUiGMSRn`%PT~A(%{63zvz;{Wqvsc%i z5~&E)_gU)Er(P~OQT$0P_1uIBV#`+sO_A}^es$P*`XgQcR=xy2;iHS!@#QgDChiF= z>Tl+QPHYtO4GiE*Eg+EI>Rf}bNahE_1fbvXCIerwAXE#E1Rf{*rJ>SXVq|Len& z9ei_Cr*}In|6zN7{Wn+VSC&Wf4u9try>;M5bn}0^7txiugSX^t zXUV45XEc{)tX}?CPb5}z8?&3aV5F^s-&9sFml_YRiPNX)hu~DJ^d19@TXCb4;Jvk*`EB-ZaVr3gAESj}< zmvQm!3(^sWM$f-r4Xtec`AcPjFWckD_q|I!njPv&o|j2#=>p735CxV$E`E-1O?#;mznS8U=nO+CBPD{B^fpYCZGboKLek3BJtbMIdEnE2>**0VX< zM?E~J7yD*Ry}Gy^9H4&8+N*v}Iy$Y$3l#CtYGjtk%enUZYc=clIqS`Kn5FXTmYC}M zX^b<(kN%Er+kLnrpOJgXPU9qoV{wNLl$t*|XU4GDx%6^vyw>Kli3>gyh#g4FlGR?v zYHZ->?$e!hbf2|TWYbeY%im#hR9g4crF>|57-uKFFGR#xEa}MO=Dn}ewuS`1njn2& z@bktAN}g|aWlAL-h+o3|Gf}ALP|t++%ZVJVx_2Gord7Y6#d%=GtD@;w+IskV5AHbN z?fv$qB*V|!touanZaa28h|fdw`1*}=_8d(BWw51{K{em+bWgYZcywp^OBF7^Gm9pB zSaovztUT{|r1tZ4rt4p2mv`43X`g&h)w)k~#k_(=B|_64TjkIhw=S^hSsYwb34vVwd^?hk-zuEpCiv#p4-_ty?_1B8}awWkKR~wulv!e z!n66WG$&O`dt;}_e)zH3xB%^nu#3U z(slM>%BS};Pd?dj@kngI+&Od74yY}jaWvw}!b-I(u2) zium@KC*jDmT1$nl%c)Ztdm^^Z;p<4c`z@8tAS(6#HReSUNms**t6dYOh(spX@@xkO!|pey1J~5cKgnjFUif$CxzF|wozpA-8Fd}~S=qq;?cKVqnFbAy zepnoxe9i1&(y8E!LFrecWJ9AeTdcynqte&vi?&p5RlK%}c{}H!b$?#j`KAXiEfXk^ zEUFVfdDc_!zskWk+R9tGd-Ui9M0 zI=izwH&p4L^t0|Sh|)3pko~6SjfjF$(V<7~g)VW2j?BKL^I={ zDQ)PsVX5nXG$A;RW54I>81}Z*wo}du2`jh+Ckl(%ckMLFEX(7QjR+KBk6fO1;_&-( zxu1?6(ztf=w&Sw~n*(oVFDmb?nREX3K~w#nN9~EHT02f~cFVi2F|#!MG3$7YNI2u0 ziFOTK$GI2Z(DQTio3DFjQG~+k8TS@8G{~&(P@2^7BhY2lw)BkL-+>~h`5MG!4(vLy zyL(YaW$UG5xu4|H0@qBmjIi9)*06_9aH7kR{zalOk@}OZ14Vvs*!NL#&9C@HJ2u6q zW$1PNHsRAbULemH+1%m5^vKO{l5vie_o58`YfE=(Z1ec`y{xYLkyS7IY2%o15myz> zkBeWtxo*u-s~CKGQO0D>l*Jm$c(fzMSDbO*C_L{_tb3ry#3e`i7yX|0mm$pH!MjP< zpQ}INWr$y_QKzz+Vbf;yqs9zXPx!?P>L=K`2D(fVvhUjA$7i+IJ%8KDSCcgICd`jd z=l2mgdSJuH+|tce%C-3Az}Nj536QxnYEbVK(j$R`<=F}=bR&=6TjNsjW>Q%cCCVK z#l|;G_qH!f{8>BKdc&paoPA6eq)U5W_Ej;2UE9GZI8o(D|DsZ}+NZm_A6JzBv3JXR zwx)gNfntGE=?Y4p`d^l_C@FO<>gZUcp|nV&t3#tpNh!E%QOAinE{k6*Gx`@PIPw1l z|FSnX*pdV|8Wbie3#chA;lEzO8}Q#-KGv%%t?NcYdhNZ-8htw#GskFtlSvPh(Y^JH z>p<(itBZOkYwR=5V%!nd`%}*4BsFSLiYgW8870t4iSL&A%=Wvf}5n2j=W$ zh*@hM$Rgm%fJ!vj2eNp$2r3A=Hn@l|3ZZhI9N+iz-;#+fg?EaL;!p8gS{fG1WUnZA z)hNAjk(;Zol%VJeSK;1IPQJ;}TRo#^e<@mDRsZWO--*5*uIqF++_9Z6p1S&no@^{Xu z_ck2g;dbo22zSGL!N1JyPAYy;IW@NIS{`{vcFQ!o=&;@}U+90ilHc-ut5aroDNk&d zqS%@m$*>wvFYRrruIDYvH6QPtu&A)v>T}$&eTNU>d9zPsKGV?{i<%$i0TX@i>-<*J)Z3!&x<^U#o3f>Xe82oWKL+D9 ztYv&P@BVzLVM^Kd_~FLT1s2EmNt*f|w_PG$dM~jRLiYvv+zI zmv=7|V}r3p{LMY#hnr)|pXP1R$SxaeG>xyj$5LH5digBZ8S zwV#Rv8-8SDSWa*ZTI#=>;hWoXUk2BuhbBzroN_%%k^~U#-lTjDl_cPyr);sbkT0oBfEmlS2J>z z7axi{-lBB!hU&W4FFo&i8um#ko!eySkreuKx}io=p|*Qh|E=p<(+?EIcKu@L+n)0H z>&A62&nBsV{QdU2`_dm$H#RLfG4qLXSJu?mPqxaeP-vYk_H{*`fNSg5hUwop?`NF6 zFY-Ey?P#d-_A-XK%U^D3-}1=&N<`ut6*dJi?NYVNyF{8#AO0S}_s>Jqjp0pi!AWk$ znxE^vJ}R(v9R0haFurT{*oNz3#EA)X*Ob5g5Z{IcUaV8iEOpsM`(sCCs zoWIcXVtC7q6`q0e2R=?yy!rji^Yu*XJuf8cE{C)|UiPv+q-&{!+6`yTeS9hRxnpiy zZdkfQOfQC6>AkK>gHCe#fj>K@A5RdA`0lBY_Tp`tX4<9J0_E*d46@5#?r4AWh;f1h zZ?Ej(Icw{e-&pDMI_OJC`}@GJe>^nh7Uj=Lg0hG64?USCd@-tP`Q*tHSsG3_YsN`$ z+St+4EMkA+_5H?~QJL)W+zfXweu{|Gow)BB# zY?th*EqX^S&ld>K+bOSp)I?!fQ{@>b$CmPw_hGLWSjWvuao<%KRA=WWSZ$P|1_|_L|=! z6Ejp@FP}hm7w7Q$)5h%H;oK;`QozA#;ai!JHdjUAx`gB_9YU^DkWy_H*iFk>Z2tL(`Iqm;Ltb3VpEl-n!H4YpQmizs|76$A7)U z-o`mBE+wC~Nii$gOz&dS4_&ma;m{@(K=%c0XMagD<1 znwtuRcW*zi!mMGli2cb!lb%R;N4k~prMgbGulx0f#ey$0$mZwwpgT+(QW}3oU#ksk zU}o2>E1R-N?!dI5E8i!?$_O`j=u9ouG)v!ge#sA^6?Rh|{p6S~b3Oa;0n_IbT^>#G z7Hjl=yTJARlQ>POt|&B%hudvq!;-_WYbB(i^Jkn#+)`Iqemr-@XWAiHm`M>aO*P z@UxWF8fiPpu8U2TSsIb4d6YZFYuaSLxSoygf(;s{a6Qac$UlB7unU@qq>f4_go)|D zTT*eyM&-4&<~@ds?Lj_8C+!+USsS)|dYD;Sm>E1dsaXBG*TlW-r(W8-iT5==6$|oV z>bz3nawCX`TSVOJ<=t5#<_(qal8?z5Y~C!)`i&=D)9a6a~q2% zCB46}^n_pbab9-=|6_c@8Pguc@y_>4UU3+E)r_14MlUB#L6dX}e-x0Pb=$iCgbJniR z%csiYY?-91WQ99iS4E^uIvjdr+LPC_GXgu3zVz;yV>&TKYIVmZsdxphUkvBAr>I(r z9SNEvX#1?Z!~V)qk%Da1B^-^fxMgmy)^T3=)PZef;4Yz4ZIKJ#B-= zb2Oj5m!G?bIqdS;`S3cug&uBO)cg*$$vdNRmc z)NAk7op*1>3eQ5J1BIsb>xK6Qt8h3i_FuZgpx?S|`A$7oIl&bl%UeH33wQmpJ{lu9 z>BU|@Py^iLS4h{K`C^HJzqKRlUuWoD(Y}3r>t(g8_w2E4)EI?J!l)9<-4_t%3jGZi}Qo?9<{5d~`Ce{tw) zzq9lWXt~9URU)Fz{yV)Tr9rLhi?y0^1=EWREF3_-za8|YVyE{pTvgh>8e~dIY}dhqmhZftu{DF7yGzTp^?79D?g@vC&og*VROoo;ZD{dD=X9+5 zx0?YImUsxbd|$d^jm7g#&x_`ri}X{`{CD`?&A&?~wkF;Qe|%W!P=c6|RH{b6G5tl} zM;CQO^!{j!3KW)p+iKc-^{>aTjh^2(?R_D?Z%%pIjE@!~;k{keb>glUi}~K~IsYd? z;+2L-*YD{{(SfJ=->6r~b9Vl1+;gp9(WFIA3wP9O8clTAKFvJm#X*CdPf_Ixm%iRu zTCvH}-0Au=cavR?+m-&9S^56caVx*gv)jMvY0hm?dpC8@!rkkPZ5KYRFu%*E{Nr@l zb>7E^cGmUW@#^wX5#lJnox$(6-Pb~(v&6Pcv#s>OlET@Hn|RCGmM4D^7HbIHC8~VD z;O8WURUv10t@+|{_}x@bg_-&Pt&^ARsJt%uxKfh$%c0*kcV|Ro3iI+^-!l71Yw=%+ zol8Y#dQ3jhEVxn7tL974ne@i+-rFiNMK814pa1E%=X;m){Q}=dzr~6b9g*I5`bC~D zTGsfU?eClqVn%G5d8$YM7|J~BDsjFvdxPfw3D-Zr|M=g%YwmGpdAsB8t7oYm-Mo48 zrG@9h_AC>rZoF%K+g9s<&c$OZeK{R2L_Mloq9HE2u17Dx+OMH7=#E#HJj0nDzn(aT zh@Xz;N=ulH>%)B~&f>1L{V%7jX&3iP{&?p!l}$Cb;~BX4m5w^Un0R`p?&W6BkGoio zUJJV8)|JUn%$T)dI`h5@ya^k{nyw@mu-AkJy(y53>e_f^Mxyt`O2g#SD=Px-&W%-Q z{}+FD?~kP)zASmx_%Ni4zp`heZE=#NLz9D6>Py{2@e#$Lmu%m?3-p=cZP>hL4O3vz z$^Fci-U)p&nEs(?t5HPGl)^mwRlQ!R$wy`>PnB9IF8wU0Bd6zcVX;lBMQgB1?mUT@ zQ!Y<$9(cN_=j|1SO0UoJH}U*g(0A-@Z~n%Od%ct{?Xb7YQ(NM-^&fAszDQo4ud->b z-rr|@vKBYydOW|o&RcfFPKIq=M`Rcxd-I&wBGjI7tnkpBEcEhQ#JR28>*S7DYAtgS zsK^QAYOwd}nyYs-G2w`^>po@Qlr>KkG`>Xqv~Nv#x6{2VJ|R%htD4=hs7Wfv;`kKr z13L4UY<;#${O#T3v$L!|O=i9r?r?Ln%jv}CYhOZ#G;*=r~WuF=W^Ec0N$oM z#nst;sTG&?rLJAr>N)S{?_JuiE1CQBz8W4s@n)N}*Tu>ppXJp{rg(OiRO>vAT2(J8 zvFZNxO5MDA)>T0ae*%JPnu2VYrghvqtakYPtm6d*OEV5VYI$*#D`#5Gl8i&oswX^t z6>#lDDj!Fz)$67y>78MRA6c5be8f=gBkMj{^*oiai?DcO3$*^oFv)jg|kob1y&X@nLo@Ws2*ut%_d5fOj-PjY+L1%j2 zuMg(9puKR1CG!#+?M)&}FFnz$JbyCa`6Ez@n(e)M@1oZy_g;M~HT&#CksTguzFpfH zyvHzU~MUq9w$crqJrJhrxw%O`eX(m}gF zH`pdI_PsW--}!lM^TNe$zFR~Up2i+3m(bs!Dp&i@-@7aIz!rOZiLKwxq+eNZ?);z3 z-%p+$5PSYp^@FAZZ;*ccr^B+W_jW`5!y1{gvUuke>G?@tcijCNFSXq;p>&ttfeZ_TZsDb@$he15i1_m~pPPXDWdpE|pzc+SWxgd`s}aVc+FXU&y=kA zo^oVaZ8Ld&`>wF_5!0FJ;vfILxWIZQaB}8@%THDRwCi@cAGc4_%(9e`+S8wt)Xf}I z?2`X!Vd;9~-#YJ)asK3aGDXF8r%9#Pz4c#gO0|OW*NIg-@^(2~+Yo>DvZ!C9ME=?D zDjHVKlNp!0?%gKxl+Pfz=Kfm4Rre3R$Y(B!iSi6Qw>9R!rGe&}xn~!gJN|S16NW!L zsz;YAxVBeq|8Q8+uvtl0QNim>%X*Q;2doTD6_i{H9C^wl3*THn&R6u}^FH(Ids&y< zQH|o?&5(3NhD-Asb40SjsxI#R+(C2R880|ze`dqGI40Lk24cs~Uc4?Tuj#eaGnnhy z5tF%HS7xt1s<+8%Zf^VzouiLFoqY00L`HL2XJs<~-i&#HahsQFlsEk333;JsaPGOW zl~jz&k{w$nEt-?Pvo4n{b?f;e+{eUx=W|Gq`5p_qWY&jm9baGytMOc%sI_>Yiy1&-fKK9 z^ZpoP(lql#W$!>e-&sKcOm&O>TwnG2Z(O@n!jk#&l%x%r*DQ7~zIkJM+3zQO2Ji3I z-J7@W9#cb?$n>zFDMh;1^;Oof|7vKq_`v;E!TAYi!=y#0FHe2s()>|CzGTPzJrC6{ zGbc=((Xw77+hL-NtB!}D%#(v}mq-Y|zQMBTz_+bSEZDzHUVL2dqeWoa1fBY+%zyY! zeBjp)i2LmEQB*3$xY!gFct76=r!FY|Z!z(T^vWCay$t`eHT+u^ljT)7b%xajzry9Q zk5=b{-M9bV+nKBW7!*|bYM$CT?e%h71ykO=+V;&y6%3XvxzVJqeN-nl=*s*j5{H-U zdnUa5rS?(&1D1x`7fb~Y3V*ME$J$s_t?Aa_pHh72bgX-q^8pslYm6naMz60j_!nM~ zjnTZ;xKi%_caf);o@hp@R6YOqK7FNm&_?^Ik0d5M@lSJ?)wEMr%jRDzxS4%M+3y|9 zcKnX<>a*`=nE071{CO4H!E$GtsHI+z(p)+3ozq@FKlt81P>lc22JstVK{*HiJ9QmX zOLP0tZLHwyCUjDKPqj#j<|pBQCikP_G(T)SA;`IpadXnTl%D6a^!Hwi^1S$9`?i?} z)C%#N?7H~vdAnCd_CPu?c7)80no@c&o)KOa$5NZjiGuECehqDNr!D(C)-yc~{m z5|gJj+ArC0qO+t*=Xuns{Rgc@Caw7JzTPP)7~<@Z=lpw%dM-MLY}+4uL{-!7IYUv< z51+j23qJ=Qkz6>_#G*-6L3qQnTPM8>OCuSX&fb0NU)d>km`O6>^N+ue_*z7MCSE`K zIL2Q|eeasb^{s;WoD{@5?sVaL2DGUiV(yU)d0 zbAFWV>p307!>BRa(5SER&dV1Uxi%=Noo2GW`tkZM(Sz$}A2_!t@_Hj@mgdn(pFbHK z(id5(8pSJpgK6?@mR%8TD|+iJFEu{aW;9#Y@ML?ID)Wnt%S0-cpIO9Sp=77t zJNIsHr>5)$=PP^cnXjxZ;|a3XaylfRe*F35hJ6Z4eY}?3PPV*W)EBwv&;Cfgmd{f~ zqCfthptQ8a;9KHx9UY_TOIGY{F5RRb-*ohumT5&A|2AcdY0XC?cWf0o-pKj9B<1fZ zA>H<`=NCFA{@3-Mc!;EF|wAcyadda~_G>+fu*W*n`b;G`(aC)E0e^l-aiJ*~MLfgQE; zJYR`UoOjXJL_=4gIN(C#lj(7{C2k*zscQSL;5)r9S?J3PotSpU=L>$y8kCiCR?ax> z@#jzbLHUz~@@3ytbXquPs6=eIf4WPD>;KE8JHD>$PPrkL9m)RX=Xxu<>ad=d5y~sK ztPW0F;J#vVVfE!r5xSikoX<9BZabg&X{lpM%^juyZ+$2E1Wi7kr$=NtkIUXZG-;>u zJ)1jrE1A!^r1b3H>|+w6a{ljSV`JXZtfwh!J>FWb*!X=?@f$r&aJE0ab6WA4R9>t6 zs7d||HGx5IN;J2rZIY5PJaJHhgN=8Wlbwvg8vUk&R~bw>S&}Q?$HcQA`eGcRZ{P7T z`q2FK%YJsT991cs<;~jtgx~(u47czLY`;wIi$1-SvX80w%EN;ETjH;iGW;T%ZKt1m z`aJod+~ML!`?Y^;y}h0JlgqJJ`kgKpCWu{FGkb&MbtRc9vm5IF*G=)*dE9T^(_iwu zUS0j(UEj~>7&!i)XeT>^Pk8OLpAp~x&19M8ndm*SaOsMGppc+FqHc`QjKBKlFkZ;c zFHw+O{(HGavz6u)k-Zw4TAKIzqThKOO^m2{znuL6$1g3oxa|72s+abYjoKG4kDsRe zMc@r@>9_fJ_gPo9t9^bFBqMc8t#uN(GY7IGL_@^PtIMm4tMyPbMD)XgB`cP!2+*(r zS)wJv#ZRpCqsbEAm|FYRWqO#1n4zp-0a_60NlW1o$rUbKGyxtrs*@2Arj zt9mpv?HWWrM>=R|akj_&>RU47UW@Nf)_8++Pg`s<+AGv2-3e}MwfpFB()R!3e&*kk z*52p+W%*Dy#p-+0`L{dmHJ|lAGzi}_d&9@7T&cB7epFPxIQ;xaM(E}x6=h{%R#$Fz zl`9^dz<1_Ptf@DH-ka4K({e67c@Vc?j$Xr^k0+1wH2nQNby3aJzXho!jkgM!dL}>m z7W9W9A+03o3)6v9{nnh)>#r}n=+)If{onDzMMrneimzwXxYH4kkSj6O75&41*$b<(?qVYz*8Lxmn`L`Ed#`NS`DM0s$%BM) zrMcxxU&v44PFU@6hH=8x7i=dICx4dqSgNGb(V>6G&HLh~Yv-FSe2z}>VD8uT(){4= zx$*K+jo9xq-+L6VxHgAdgFEcL7MN1CX8tvWiqF5F&av9$wY*wI^OsDU zUdU=!_pZ{{{CCd3VlcVnr#Pd!F0!lHIK#kLj&;X}g)&kv7QdBWXkB_@m-Y8K9s3vx z^nc#j_agQI=byW8`z<+Mx&Aksej!2C&LBNsO8ot{$G%q69=_e55#fAYt@7FX*KwMs z93Reqk=!@&X0Evd-|RW}d99PTu$-xqs@04t`g{7Ds;Jhtt@A;>KCYU;pqeUBug_(L z%&A!we|Ip=R_&{qtifK$E@nM%fed5ncgC&L9?1wO@gEZjczE}W)8b@{ilq|g7kY}P zUtf0Vo#3wE)_vq9vxm~Z9-=~64ToPF%|L517cy5q7Q-7VYWIr;3{=dxXM z7wNkGU$BQM>&b`Y#D{E>`=rb?_fHbJ>lWWNEvBA7U<30mRTq2KBTGeoEL!s8%aRC& zFw2l#lCP@Qe~#=w5buy%V{6FsLR0$_Ne1zDN9%7|?_RcLs|L^RS092xIQ$aJWV2TUEYMJ1xAddda~&_Po{(~Xt<9z-9EkxJRyONhQ0P`sIhy{A@us!?)}P!F z3(R)&X%_7r)zW*=A<8WkLA;8NOkUd=NS1Q_ut$ViNT*% zdtA)gBBi_aU#5beNu!x|%wBJ=Vw`maIx$BGsa2{WT{pkM335uu^i{4ZCZxTKg85sVc0Tt^ewz z%iXf#1CpLz*VY*Bzp6f8(e?X+Gat6Rcj28qE52NF)y1IK^~^rr+3La>9}E9Yn$@)a zq31_EkBf^+`<+u)WOaP+PfX~Y!6vY1g^0R)Uve?umM~S$X`Q|Q(i9ahJX1On$ zA{!)Aw9k0@&3!d{IXg<7yHvA`d0IMW7I}SS>JZqhzSM##VJhQ?700DMU0_=}{rKgp zk}*@0`WLBwE}9X2cG2g#hTFSVukq97agFYJwQV-@qa$x-Z;mTDr?FltsD%I2eTUwC z;-)!Sb$6GpaPwXpuf4$O3upUf0Y@tqyUDYd%56078EPI&duOS?kfUJ5D~Aa)lpn0D zUHy6aoF28DXP$`%!jD|nI~n;$r#cynw^~O#s-*h$&&=3zb}M&C=gbXDPiV;~diOJbS|5-ouzJt?jcwO1{H$e2 z+8X&)56^iSdYWaeh%47)UhSNbWt3*&$aQe((!@y{l3&Fxm0-Fz zF~#=z=Jo4uY&>gvr80D4kyjzl45gD&4U9+E+FqN`ZYJ0B@#@h;am{ZUvt*U>elDNS z?9iGMqg^(A(XO}88q|-doQ;$|@`gcE+5ep*Cqq)N&$h!4HDZ}nbMk_0)I85Bx|&91 z{k8dgQ&X$x==Yif)6|dZ{h1VWhH>?^g8_k_Y_He33F!)OOgd?>VY%>Up&yG^iB0XQ1q@w&w}ae!I_%{BeNU$}wp3<17_Sexxb@h7UFCKy4JA%9q>|DH_ z(W26Nc4P-*(nX8ke{Q9`KK=Zu^ygHjS;?EVmp@3o9n_Q7`1h3)tDoklqj^4M%n}Kb zize=~5jc>z-gHY_9shzon_?R^k0vrq4QW|=V|B(N&YhWgmha6Q(oC-k9heeS7_OPd z;4&rmc#z22)@EM?NrNvvFGIi|1adTM&&hK+9~@vKd)f3&(eto5kd zAMN|gXKcJDQxns0a^bTnN@ou#C{E5cHtIJ!dcQBCOGMm2qpfPq!rGL7f;|TO^S28B z-hAG+ds*g#w7Tfe^$#<}*q%EseY7sfhFKtV``tM?{K{vx-}}ZoV_M!b&&+010oL=0 z8+W>X`=WB;K`ejK6>d;jB+ngj=2mamqNUgTMb69;-@bgwa$C)^$Ll;l3OJpcc0|rn zLcl`hUysieqE-zbJ+sxc_R61MfT6EQP}Y2|Ey&+A9`{nswUXcyfn}0H;AjNm_>KBU} z8;s8U4$10NSt>CrMW9Mv<7<@j)QblcEKjii{k2{6uiT8~yB%Kq&DfBB)UU+%X4$pw z_cba8E3D7`<7c^dzc{zqYQnyn`Xr?V+T0gRlwGX8E-SzBr_m!WbBnC*)_>B?>PMw@ zkM1+%_PJP}=E1O2;bIZ%4+s0k%m=EK7E4du2>SA2$qUbqRWDp~;*#&z@Hv=#V-@JW z^xuDFgIHxn(4HoBSO2c-Pj=6DTv{kmBeih;0mdUna0&Z{rH1mc%_px^{P^-IwWE&B zI=TEo_V#+2eH&le+?;ak*tQdgCofWW<>%-3@0urKYh&YMqgfU7<->=92c8!vFKTaZ zXNF41R0Mrl^5WschX$}&) z)))Mef{cHgq{!8^4uGnARDk0|ZaQ@T~$pfzWn!g&}#yfQ>*4I=Y zFJFA)X5VjT^O&xlTJ!xAl>+`KuBu`aQR~$B&zLc>v-WrTTD6AX^F-=-_g#8w(NJl> z_2x;Y=_R}oYmPE(t(?JnuR3VU+!>$mS`_7K-^Qt>9z5A>k`?O^|vn4 zdG@6zPgYpwdv@-#Hh1s(H?ikE+a$@4_j5G0zSlnEEabbos#HAnypr-{9?)6 zR~IiQUwg ztvpj*U6mI-FP*XH!HIH?Vu9HP8CFd~tY*r~*#0YtYxXgn)eE}Posjp+@$6ki*2(^j z>$h0mY-l`xF+TDBjd@EYnh$=Q&Y3yQM{^f@Drd%oqtA~XeVsDHIlA!7$|vES;iuv* zI+u8?{>snfnq|zN<8|>oL!j!fb$1jr|GnG2u;)kqbdl}@M(tip+S<>te2|{_Uw^^G z$k`I?N0tcw%*jjnna|Mea*K6B#l~m9xiy}xJZ!n4&}QR5sRJ#uMIIlh5ZB~mKFO&& zi7Bc4LEUHb8R86aN9(G-mBR7X7aY~w>tTzJ3_^lA2@ns(|XoD#!EVWUHNci zqOJBZdH(e(jg@y_Y^n|j`g7v@CcU$B|M@C2tM2#O^Nuyk!BpUa2K$5e6(*v|nybEw z|ID2~fx*DZr8MV-*O%XITCVjG2mk8^eewU5r!jfEch}|vZRZxAnz{Rd%#i+X6VS@?%|ep*@B*Fnvq~eT zK0Xm?Bi(-R*v5aYBA4H)?mc;>F=t7)NO6tP#l`nCm}bw~cz1h$>2$OBfZ0M5p77;4 zT@dwaKjezTG(j9+!ow?6& z`O>YEEKxOc_AhbUpT8oAN4I7F0;ykOn)jl=|4k1QGTh=hZF)^@%HMms6BoI@mTS+N zr{cV)o`*U6h)IKhYvdfaC(C|X?A)s5$sm6sDM9|kwoB`!7>>p0-#d42xn7VAqe9fy z73H&*?$@!pFIk*jJoRd3>%t#PMZER(dv$G`Sv_r)3L{^rEQe4ri_O;j(tlGXUu-$M=kukF zdj%!0B{SNTPE2}iS2|hAR$#)F^Cq8O$a|mrJ2iXuZg0a9zGccs9geRFEOS4;yVz~| z-R7cWjK3XuesnQpfx2QZbnN+-T>Z85NNYXEjb5hjD?3>xD*yVwT7+Hsc_RDsi3k6A z7^*hB`Ew?a>A<`>6Ig2EpE4WNwJ)`}s%AV#eV5izwg9DNJUXjRS}+QUo@CWpow7*X zdiPz{2bVOD+U{J^Zj)fH8Kf|^Vae0Tjr}$(t5P1{ODorW_MNfguh&lHqp3+zo8AW+ z+viN|2f6JNgU5w_WqZCkb*n|nt)KdD5SjWblYPb+N1i9#E7%$~&R21*TRDT%`oszG zuD=r=SwFZu<?QP@QPnE zDm8bX-l+4T?2V6K#H~1ss;RS{vWFjAR%^Z5{qep#5!^c@q)-28LiCxcVSOfshV&yo z%#UrCNU-yHe3}^iTL0(T#WQk0y^#LJmL&Kub>Sbc;9Gx6HJ3Hi|2Q~9)AgO<`6&

zs~H>*w{RUa3r=lCt^`gyZOt6_`O zXS2*Lk&lC4In1b=CGvCYBZnsk4_&PI>ew>(hP>uE=HHU@k4|DxzU3!kAi%EU+Prje zd<3HVv{?J(h4h9S$EQXyos<2m({Q%+%16P5-bT5gB`OzUPVN!fur9bKw7mR0a^)o7ep{$ zv}}0x?bnqah9d^0%hVgh_H!I@e&y=x_2X?$nj%|=tLgr%Jrx(cw45&LY>1D2pmZtg zuTJ3S%R1t3{>)c(O)Du0sIyF3vG&MChy6=-Ff1@A-}%J&gs?G>=5QKN#d`>gJ!OsxsuqSOZWIjvT&)_nWbTalwez+LaV?qpOZDKI%EIa{+rOWeoaixHbEM8=qM?+E zU)n9Dl6kdt(>2nTsInf>@&5Sapsd}+qKrKf-bwv3JRCBUQUV?{Jf3*ZVfH7bt&$t{ zVq#7Bdz`N_F$DHantb%bvN^Ln*iSxV-0*JOlDmr-lBU}|epvm|s^Lb>6q{eCui1Qm z5wUz-?zJS2$tiNuE+RL(&%Si|6@Bxr+a4~%Q$aGar%!PTPqW^(M0GQ}qSEfuWdUy* zJ^gBjx1r+V*(*=8uJ76KXv(k7 z(^VOJGd=Y#zBku#om%HPai(XJ;8FH%BDq2bxc>Xxf4cen|4rrPwwX&3C64bkExst2 zXwvG_dpcl&L+B#eqppE9-T571YdYO*Hyq1&n>YEb_a(V)?0+9vpEowHxX!nGX|~Q< z-&oA>MADa)s|qupE&N!$ScBKxyfmV0dws{Fgxn?DEt$=`nq^#%-TJslqcSk1+^B2X zTmAbCJX>4}ck{ed>gu=b>M0ai|2WPiF!0&A#yR3gciJ%6?w|fx!{}JxpZs?vBI@71 z`-|Mx3HZLqf@jLF=WELUJ<>2Lv-SGF!E>Hh{eQNNyTy(QE3ChfbzqsSYvJ`riUunq zo_R9{t|=0cOwPUYQKO6P)_&uhO5uw9y}38+)8#hG&$lq=)bEP3vFz&EX!fp3gq^{p z&tBHVyCE(h<=>^r^QR~??3{SmHl{0y@xZ-@M(z_0#h$ElFWko&Ugf&+jkCaaRj;a( z@<)Fjv#psWpRBW`E?s2l$~Hdl%-YC_adpm|*KR*9Wayo$_C?WEbFs-ni)sJ$rk3<6 zCF@+c+rMa$&zv<^`b5q@?yPhbIN!);V*YW)`{0xw)?NI8f8PIK*X`M8<|KAhR&~iW zi>{uH_oZA{eqJdQw6b77*seVBqv2j2dtdQZbh~UA3teZ9nt7 z`R{~Q8}UDwwdMkE>g$3tJ%4NV=l}ba{an$-P|kSy)C)7sl0OExPn>i#^=#jxmoGC* z!^K1Ym8Z6xpe2N13#8ObrL=B^Zeo!4AK0G zU5mPs6{};;T{gUUq`*D!Q{370%Xy~Mdy2#}JeE{4+Rxyd#D7b)`V`ZQo(ZYDS!$L@ zTQZ;0ikvs4;k?YzXfKO*7uiZZYuIUG!SO>-?PQ$`$jPUDr!~3k`33 zs#_oZbpA2)!=J_&?jvT}P>_LFT&ix|)m1UcO!0TN-J0-LPO@RM4yg z)z)1RGF{8~_O4EPkXd5M?;}+v(%c>-Air~~Y2dp@+Pyg-N8VU@j>$CiYKF*x_MA-< zrUibHuaCUSy8+8cEOxu&HqayjsYxlrW2zsSYAckfQNVlGf{pK5k;(!}~Ku6HXQS(QCCx^}lo ztRs!FwI$Hf@_IMpjaTk}ERGgjDlswHEf($Wb|BME-JA7SLeGJ$@y&)cnqsK02e%_3Yo^fITLk%@1r?QD)b!cG1S*{rozC zzDKoPi&o#%bT{>M+WzO)4em9Qw(uR%)I6k_@+8Nv@mbdd=6w@ZC-ZBVcI#h1xSmla z?6QOY&L+QN-({C&oqrzJ2ovjT%T_K}JVQ0}{LWXFp4JDtWRE^rSi_L^GTh*v&(o5K zbC37^-PW7*<uUq5E({DqhO@P*_Oh8p$zUv59rxVKtknY&fAywk!{fx1kF zllU5+-}9bpKmGKLmh?$6=?C)qC0aD=t zznAX?e+ck9a-eQ1-%_50YuoQ{3;e=o&n@!zxW3Xl_g#&1RX%i>O;paBY3F{ixPGxk zie%3$m+6al@P&A+V!He-I40}x3;YOPYow5jz2EL(6?Ut=-lqZ{)|VxkNe+tNE4}Qx9pq6 z^`%(k_Kxj=XC@!FUuFD&*R%VA>3<`)BTavfHJIEiYtYY#C7iDmw?2O4(lmp)Cr zxi?Q_{=_Ne>vs8FG7H%7UBpI2^g{T_jaP5aULxIb_PqPaZ(dEcQY${{*o5ls6PB$qEGl8BaJ;l(hoP90 zo9xS$n)Fq_fN(<%>6D+;yZFYj=AI;> zqFYxsa{K(8ructldglon=4~gw^3Hgpboz2(!n6p9(8idSlyzpl_cQavkKQOKj*D@Q z%cyITcKs=vl`8xrh5y-BkGp~mcGdp-7Va?L!tfwuvgRcImJ z!MNeor)xZWG+v!u`Il`%_}e`RAHCn^%SIG_dm`Oc?Oei@P@J8c;lln!BQ|Cp^DLJ@ z2LBi7X|65*XG+ZRV*d4I>E9r^8!>V7nICA=pto+?alNfCE)+UAP4BC<>`#)N_R1u(s)32~ za#G~9id>n7INzYvFYmSOFbRJW&n_4zJ^7Q2tmKt%CfS)^CK+^E396P|u9tE-X3xv; z`li$uJISN_{!QAU@N`?UbI7JG^6HfmNThWLu-gyOo$cm?*E`I!Isg$d>H*Vql z+mX}ndi$$&Fn!w{e68_|J8Q(``Hv1)M2TOPjbRChf5+HXdtCo7r%mDeElV0+Za*Hl z=WyU2v*6I_O5wF83ook1<}Wu*S}6Aaj`;3(nbUaA%C5fU8fUANqIN~EdC&fU(iQWq z*GqL3emr++afp{`&3uQ=_mA-Gnilcp<>b8PTb(O7C)=dyBuzN_A~^K0`DcN@i>&*S zRxCadp`hP2PsP5wbMcA56n-i9iw6UrfZEGBU|LP%?_sq{t-pVzk63icxE_;mpSbvh zL~(%#sJSa9aEUG}{f9m^p^DZ4bWYPEg#gpkvy%q(}2yQnO(NH*X zLMfugwZz3Wd#csq#c?YxU);6MxOVo-xHA1;?fK_ClX7@&1>R<}ozI;+S#5%?|Nht9 zW=36;RAPm$Xk;-eF4pk8l;6K-*~-M|@A<;pR?bobi}Wm7w(7L@*6+=YA69PMv}V<; zo<%C2`?b4f-I{*?#PcYB=7m#@=bzcM>ZFF(q%YNrR;)bPJ55MqZSRs*tTtWjXFKg* zc73R;pZM;kL;Ux*^C#ZWC|x!C*~;bRcDH=XlUx2(TrEBQ^Y69$`<)z1rfYPmiA_DA zIV+T>MC9<9UB8pLJZ4`@KH5=j-L(6arPp#}6`t?Q8K<3EW&f?`kGa>}SGOvS;?5j6 zqLuGml09*yn$KVQh2 zE}M7OgZ6n7|GTXWjy3mRYHOjkYWuvcYB|Qq=I7t<-n@COyMU|jTJ1)Yby<#mO0JuE z?{+=<`0?Wvv&W%(rfa;4JkXgm>G_Ah2j!T}>R(9y%$@Sx^hM0|vzIv=ip=KQvTpd$ zo40g2T))#uBK}9{rk8AcJ^zm(qzcA?pk~xrL#kb zN5{eZz=T`BN&|hEW(YW6)MA+bBFwMBtHb9!*8y=!*X~&XOj?3(G~9#^x5>IDuHji0 z=^QG1>WnMTCW*sqed^*=*G=*GJHpP2~1?T_UZSFs~(cf!n>Gp~9TK7QO!$sT*=0 z5#s!~qSoJd?TU^?-+zVH@h;0!GE9(<{@Sx|{{ojl?(^D=rt;UCWL&@RJO8e2iNq?^ z0@2D zpPCmw^z56@;JUHeb?3RN$c$x4%BS?VUAh|?c!%}bj{wWG5+$kVhTL;fmG1i`j+91R zyX*M!+{+aAi&u{eT-SHKI5Do(b*G3c`|N3fe=?0W{1yMCQ@s0Yp^KzW&bh86nQ6`M z)l>FnxnHagcy&O_a-Xk%`NiBfOvcmuzMNUF-X;0H^W8(IYt?^k9ghB!|0%`)S3}@y z&%X5!Tmr+_g&t^~@u~aeT+yRk8#LOwQmf|gNj)H~^i?L}tS1xeBz^>gDapF7Q+uiL--}Y>u$fm}l-Sw||(!=U^ zIjz&Jf4ix7r`OpAzTvyta5KPTxl%*_$qY5UMKAXLi^zjeKr;#LsuF*Phn+rz84c>)wFEtGmzqd;Qp=vNA?>ksOp2iWe;G~{0QVWHx(BgXsZY3#b6VY&TzvA4^` z>c7eklQKA#u>~GU|595TAaa^(`f7&4r&awXT@|06c;3Ij*x7nY>$!*20%ccJyWjVJ?i#pqc_Xi@#Le6HtJib%9u!>qudKvmcCgOZ-jjc? z&-~au_i^*@^*Z@45x28$ zZ;#}n{~OGi#Fp7UkgjyQAO74ma3;eyk>Fh3m|e?e1RV%sT=v7gwL1H4%I0t9BH1pt zYzh}R9-(L>Bz^OAyXes$8Q-5y4`?|Opv#ab^sO=Rd)V{CNk-Qm&ic@~DBFrR#iraR zU*2`<4o=CV^Ov0qKk#t(nYW8q$R2*=VptM*ZN+WAdv~W_v-!z?D%vjL`%>?f3@a+1 zZO;|Cd)l8V^8MG(9mZcdH;A(STTr^BL$CKAbN8d{&#@ahy*F#@dY&M8&xMWq_TRkc zd^*`(nrzW;8eI(YPko)%vCgefbj2hCR-bD1#{wQ_3zpA_R9Y7+k}3B?VX=h7`G&}% zpZc5YMZB#UZk#)F#Z^Sy^9IYbp9?p3yZ*~MJNf?t8`hwbdN0EVFWeXJC@uWy?C|Z> z*I;fBk%POuQqQzC9Bh|58YWz^UgK+SLT&lu`>YAo=U&BSt(=(4lpe;mee>4(^Nr5d zUB>f`L}vskZ>?o8b)Cs-U}|(IUFo;Nq8V!4@gn{WA!yiceNJm zz2`k`e_m6=6P{p(H1`f5x1uwbj#p{?bTmIG>b$r!(nHZ3R1*W%;5BA#R2i%NnM5 zDTTjQ1yw=wKb%OLE3ara&F*lgQjtqY?DLHx=~hoxS~D0VoSmE=Fh}?-v&A*nt|Q!v zbKjcm-M!nx<>i!P0Q51yKwyPTd@nE&WnWBr?7h1L$ShELPnf19U2a4}4;_pw+sV_JoXIfD-; zLl?ho*D<*Oi&O9P7`W@>X7VJ9bkyfw31aB};Sy-W@$K_t?`(&}NH;@^eI|`xZ=O+O z{xmN&Z?~Q0#Dn?_%cP`@3l^U+Q!l^XP;%lFx7feAf7=9kmpcWsbNXakAg2 z;p?TN-$XWeUg3Tqd3VV%c=926;zD)hO)MUfG6MNH?x~_Sq8wqxaHO#%~StuC! z{%d!~E&H=Yr)K|WSX@z8SI6;S@*&fQRw8$+R~4*Q>RQVs!&|-FyleN4lqU<_Cwc{M zFcGg+bG~0v|LC-N*Q@XwmjWjR@=SQhq;ov+ywUd9`P&&5rQGm7^~g^oSYXEArQ2oM z5-)Ffe$rUuT&G42&+%K@McbD*hQ8i<*>zW^9k;vjOXL0LC0VSyekuBxE-H)&a=2Ff zH)cn|{vEc5t^a;l6cOh0+`;SNwT7>=c~un9SFiY!=OSVA-NCd*jkudYZYIHwbV~ zJZ#%5=f3~${%1#xZ@Js}+!1`V>xRaAhtI})W-%NHVrQ$Iw)5>Tmu-*rd6gdjm1?;9 zMCV3B$D;!YjrkHqw?1mIF4(YIaOdYId|lN_Mn&xpW^L4py%nc3{dvcinLo0o=55=0 zDxu5YrK9FqdH4DFKa-i(bhQ77=rgw4wUd?Mted>Sqn&jRRX?2hxk&YA&%do!DqS`| zn!7UDPH6Dui?}x&Quu%AQRHt8vxd#=ABA=8*NAZGuDbrV_eF_p?auY>OCDU@$J4U+ zbd9cad7J4K=RDgGEmtSoV@v&+b~(lGs%1Y~t(5$+f8oLj4=Wk&R*9RvXm6>WZ(p4h zV4bBAq!g~XM(WWY*23BN8}8B|cAt)x0Yx-DTs!HP`d{8G7nZSbS%^@!hRZ#Nx?swE|y}^NpXa>L>a$ zuF+epVVh^vwT-W5(I(C*$Jd^p&z-(_BWr`{o;Q( zul_kbi`EJ+o}nF~ziZw6!-wp&?rCVH3*0E3Z>QbNGwpwrQP(BqtErr-mYBZchC zigNxG)+~0Nv_!fjMC9+8r=NRwU2?OF56Qb?b>g|)+4A|Sp1T~6yKkI({A>RiuSp^i z<=u~_2?c0_dSibtX>i>=Kea)M>)YKwDxO?xcDsJ;6$;4T#awG#<2i}xwO?R}vzJ5b zA+X|K8m~TkDV%-13fwER>5BS3L&zifE~JxY($y3d6~>gYb4eMvclLVmidOH-UJrbx zAA%^b0}aJ9R>z+EYmLJt)1@FDrzho=@;(lcq0Q z`7m$xzuP6Z53O2O%4*vsa@MS5wg2(s$AfS8u)m61v?85Ry~}gn;qUC#JU3Kke|N0c z>5@NjF?2%U8wvdVI@KzP8{DR*UYIo#@dq+t-Lw1|Z{ z__oc9epkWz-TNnl3_KGobf86|D~$1n%l0Cs5T}%?Fou06G|G0|mp$r{bYsJBm7b{w zO|n<4a-O-f!%-}G$JCSOS09-w)M=lYqiTH5+w5_y-ehlyCtQplEq{wG&yqQt_eiZl z<>nrKt$Ey;C(krKw7WA^!*9}2i#;8SAf36BTTaZEyguE7<;6E=$FRFuS0>qB$(yOX z_SOWq6qn+e3-e13e!d^8Gk2m!+OvN}{IWN0oly7A6Zy;jR3u{cqz$Y~N_X{&82BI3 z3s8RlXH{p5+ni(d7bnkPN$PY7mF98K3_!iyx2Oi$V#UGt@}L*~Go#jDaE z?sSPc-yJCO_T&e%^9&}&wZR%vkCNY%uRI(ecVJ%morSBFt4^=K&ZIfZ@#D1{&if{A zy`AUuZ_nMimZ=rW`}r5@bg|BuV1Hn~?<}VhWVxCgcixlQs!{>-!kauzmjeAd)sHsF&CcweXTcs3Q)|e~Ko;*+F zaPuaP*N;A@m3>o_y!LbEZi7oF)+-)O`rz{2a(T+R{lZ!IxPP_@{gp`RdC@N9`SG3S zMz+&dA!QqPzh22}-+km-?wp2iADJ68XfPeNFPpDxnX3B6G7| zt^Z_UqH;iE)zTUI|M#R#;a+mW?8)6Lx8Ll!(A@X1B;jV(Vejv<5!?Lb4!wSH_cQwj z2Agw#W9~G(ykNFnY}#6#33ub_wyZnzEb-lUs|zykbceNYL*?5HjwXMzJ%$|ywf6^9bR7gll_aK;u2ex%M#DihKuC=RF3Xe zJIa}1X%!;+S7=RsvBA8sH0w4)^H26Gw&q4$$o?96cpvYKyP2b>!yXdZ4sG&)nCnZ$>n2yJ3i0c8GfMeo=rW6X~i2;Eott|&2tOmGk&U#@!A6Ig<5AmEWJGZAaKFxI^ zTg0Lj2abdWtyz%KTjJ3W81l+MA!$l=co*}#^03)G_llRkDCWsDUBc-bF}35h=gpiY zG0{1)R*JcHSJR~yJU9_;w&CdEJMT*?w7NXYS4>-zB&P#%qGa%CJGu0yrc%EZ)ZFUU zPf0qoZ04tWF0biD-(}pUY~`-JrPRG4!_9t*M_0K=m)%=F*;Sf>B?o7C=&$Kalbtjv zFfEAZ)r~n0)u9vH_phJy=+m`pHPR=RA33h0RXRh&@bq3~*YwY8d0n?i*J}Fd$@ZP; zf9Mrh#E`Dpxno}B3(@%-%+6<*{z_cI8f5alTDEA>&980qx}I^a*%idYf9m~(3I2_r zYpn8_=cx7miPJoq_rkV6?B%6D!H>^$?n$d>u~z*3!3~mJ&v_bJUsH_h5G|BlrKaLi z%;0=*>ACh2BQwq!ToaQH;?ojyCMpKKgL`l-;Y9rZ3&WH+j*_#zYZm)^+S{CdekwRIw^cQ@>{Hh=7WaVB$@&_~7^_Rm5Bx1JSf&icJ~UDd+O z!?RNU{8>@G{*Fy6`_t$Xr!|wk%kmAEp5DnloWS}!u5`{%i#z>GDpz|4oWJtS>t5D5*J!d~*~OT|pq_B8%=+DqvWqhmTsPlw)qIuJ{5|pFOHgBt{HZEco>h8Y# z=o7ce;UyIsUB|40-h5J5bJdvn`FitwIpgK?e)O^SD{00Z4A(r$wdPlTTh{bRhCIB1 zOCEi6nIR&c=x<_avCFS3&C|HC{5hu_hI|=YxUpmdmngsDnPE0E1R?^a@)qsMa;Vrj|-j^`ctL3-_pKe zeU0X;POHdG_Aj3YHwSsV>syhU`Qm-OrE@X}iPx+3Ly~|JtTCOr8>U(dtVz>y^WM_ofQ2 z?8yyXKlL}?o$I$fo+sWvvA)j2PBW@6s*8V%rR%dj=he%`=vhHf~&8tSf&YUiZcv{cX7te3`{7L{2;0y7RvDK%W2mTnEKKIcyZLF(u(`ro27re7|p^@ z_2>F`-8~Rvs5>+8#@zYWCTp}l(QE&nIW2gBjORzKeO{VgrEJr$6?qs1y?r1Yzc8q0 z@1eyLCca*hG0k|X#A&DK8cnNv%X0skt-F2fU19vM{zd;k|7GOqeN;4w1LVT_Op?j_ zy=6b$V|st#_PX9>Z!0Q|njYnQ2&w-^UURF$rVle*YP{}Xi zYWP}K#p_%@^EaPkHrF1zpRinW(_yo{9%EXdrNV3h!&9s^+`m4W@T|Da_N`y(TsLom zt$F|5=*LxnEOBe-?on#TpK>O_r=_N7BVd^(C4Di#4mo^-bwt9eRZL{K15gI z!`+V>{5|hfU7KuJ9XZWZ{C;w{uC5Q#(^=osuivrc*{0W%i){U`A9kJi-a@QemUR~@$S`!x%C%<4lSxTohY(DMzhY~YDJCZw|!e*PTA9c zCCdM~x>oun@%K|YW>5OFTL0tvZ@VWOecS!tyUtYheTmAC)>mz9a@3;QTTo9&$C8RhkFJR#%1R>F{!U!Q;&X5Re-9<7T*nd#PeUc8 zL&}qqRE~CZba3AZ(^Sjn1gTc~SFWixd1H(F@&9gzl&ATC&H5p~bVkq7YjS3BclL|^ z+4!kISIiqCv46>op07OlywkVu-z%Ck{l4AItr13(l3ZMl{8v7jqO*N#?p>{I+lw}) zfbIDo*LAB?^!2sC%50Ex1qJ^%izM5oz7`95*Xas!^pE#TXY}YsZJ*Q`0Wqas|7iT0 zXfOXaVcs7%n10eo6Cb!5W>p$6K8OO`P|#Zuq=(#t#Ws<#$H! z&rbfFz;|Gs?b=hlp69nPl!XPGpM0+~<%!uR!yq5EX=|cS1u0c_FOASWu&5*DqvY9I zEzM_K2exQz%Z>R|`zTSYcgNv9`u|q$n6yIg3@c&W4{kCm$ghhJS zR2;92pEr;3@zRHvG%wUBn=iWE_R&7P%lN>{uR&W9UTaTCI`vDur|{gd4PW0|+_l;C zPj+RruIuANRko%pYPmFzeR4QB`H_TAxNFLVV|}rqCXe2InrHL0K~uKtZQu{*yd%ad zjy~1B-+L&2qDa2lQKz+G*4d0}yS}d1I52loQdPl;kAIf@%#^Wy*_KtbV8?{ABS$4~ z>GA3BbX(2GSEp}ptK(PF-Trw`j1Iq*kU;yJrt;3q5!1rjHI^x;%cTYWjZvAYEoW7? zGrELzq4nt}lc&0^3tpF1T(#S9f=Hp!(?<;-vtw30Pb}PR{qVTQoP%D45058g+@HMm zVT|d7q>2E)#N;3o{{<5!&7RP%dhv~;^O--#*w`m8@>pd(xB2n~dy5sTztu$FIhUb1 z>vR7~%N4RF7B`;v&NW#ie@?*^Hy`@Kf|Ny&<^z$ zF0w1_Ds`@8sJ>U&zOL_u?*2ILB^hi-qm%i6x`pNKUMVuadztZap8O}@6{omvWDx$u z{$sPJ?BW?!464Qdyzi-sN`1Jo`_Q{C!M_IkDm0_|7p7%uUH<#`vgql>n{L^c?a!&~ zc_aU3{|1rzJMyjK-{;>;)O>faiEHZl7%!K)tVbIkxZPVG&R!@y{j7q9?9(X~K|C)u zo?LbW)O3pp5?0Nl2a;D;E8p6KwSSKBwvX)*9!|IvyjpFU~(7Esbbgv(#c6z`zIrI_SxqWe(clMn(ZlB>QTI-`hkLk*MI)I+N?8*Vl>;>m#(;0W5VC)^z!+X z9TGoHm)sD{KTu;cZxYvsYQ5kyOiR5#uYbw>z*G8#;6ydu;~jMt@w-IY6Jzdvd%Vzg zN3(lu<>prJ)k(UyGT!XgCcUSj_vmwA^YOUFn>J1`yDj-WK>mJ*ht#a1bDMviT+&f; z>jvlDT^I9AxA6Y0(pWFEHBow6tY#Z~s?@e8iwmCx_UwxZOcYbz-zL&5teYNZH=kjt z_fF}?IVTtnba_~*{90J^F-WFaxim*`hNR?7Mz3jKMUHuQYqJ~d%GG^$;Mu)v_kC|f zZqPdX*uW-cXLHb!)vH&hKakw8-g)ZP^-r6BEnoJcT`P0*;>jD|onE7HiNRY$bjA*^ zE>V%S6Ztp|y1ZoBT+S2;&hMRa*6q~Rqt_M+UwRf?yNr>mZ%-<7v|b@k=G|S(7tJVX z&pN5~>|oJS3ArhTTi-k`42xU5kv}Qv$#*YJwVYX+|CcW)(JVio=n}bm!gAeB9NlSO z4*$5c)WR@rw|Z3BLkHa#t?|0A4^&^7e}4Mf-}gAPQV&0hwYym4x7)cr%S$BIKLok&Y&E^l_DS=jVYip8nycQ_?jJE{oYwzn*;*O5 z`ZB-s+gMm{#M@APR&4%@l^OF6tkOREVZk3h-k%~C=a+vrJCJ$l#QUj1Z|vs(Gnk@x z*535ooD5W(W27}G*1cb5fR@E>Kw!zdH%?H#`J~{X6@b^cX8j?U2Ob3 zC`Qaz`kKn)=k9l_pFY#H(YWsvXD55L&f;Hyrk&;de+*Ofp65xkY2Wz1>hYQ55C6qZ zPkR04%^KGAx<}<$dLphROS`^Kxwt8cMdog*rkKhBo~y)zOM(?QNiC6p2y!*QJhl2@g{)=51+ZMh6Szox}`jO<- z+s&2D6*lg;p{uvw!Puv(eNo09<)eD_NkJ`>EbDE5yfiF+)%iZ+!;5v^fwI9ejPq6< zzkFa_+r_)ir3@bvgpb}_w3Tso)m6UT#__8~v^TukFS#n#>zILw%fznZ!ihmKEw&e* zJa|#1$@X+n|Nq*sIbt`r>@&9gY$1B-+3KYcE%sketdi^*3s>8+x51wk; zXjI`J?N%K} z*)bf87Ce#=RDYy)E`_aj;jtMyvpe?-eGmHo6GOX0WX^6Q_6 zifINU>B~H6vlZQR)$H)Ja35ytH#bz)pV~I}`;r|Oi-SzIF{ayJUc)f8yfH;0xS=vK zb`C>^je_e%7VEOQoqQJYR-PO8&VBN7#|p-H@5#JeHx8bb(R1z2{=jq~rnHuEpGfB7 z8*7*|uU_WXs`uKjxk2aC6*-YYr6P_8uYYyfx-$OScC~?DQMyK;Bk)qEtJ=fIdqPbZ zt>jPWd+ydcZwKIJP3PugABu{^SlX+xEB*D1~kdb@8cKj_H4 zE_-3qCibdTJ9HSHzmc1*cIVOM&g}uq`BJLT&$`)>t#7=3B`e4f~52H7JFI2az=xu*e-qWPKWX1c=^!cAZ%wRB5+<94M@mQhkfmaorB^};{8V@(fuAF9lZHDUHX9|jS z^ZqROp{~@n_4!Ne|($W=gn4h)n_6?|r**P^-oHg~3j(nqXTmMTf^qrG%DhmR%2jY_*g7?`ens%(qYem-!~c6UURu|7)jomG+vf|GkcNX6wF5ACV8( z8>Ij19aq=K_eU?i4)HR*CH3N-oAHUg7w+}-?%VnI#tf)O^+>wXu<{#hCMO4$( z^ZH^HyOhrJIZ7MdRQ`K+HSIH0U9@D;-^@CpPL)kIeqHycc6{2ae@ebhf1<~t(~Fl# z1W)Z)loiw^)cNG+(iQb#N+;88)s|{Z^!T?a`?wjyAp-^$XO}5jeG&{uxcp8te0gKf zvbIsRxfm3X}Je0fRMba7UKN)o`dlkuKwN-5q#{v7UOJ6h|%G_$vVEWLv zD728}chR?xCKEN7KJ+e{c&&8jHK8L_y0>PlEaEs|-Q||`Zr9A0#J8|{Mg9M+P<=a-~X&c?#xV&zcYH+orM#lt$&%5`8^Yhnp zM0G9_WVwBJ+4q#Q%eLQUJJ{U6=y~O~MHwvR(b-M&JQw{A^l=rvBySncsjFjS_~}|^ zmVe?G!JS+BTnf$Y(zUw&PkyTLOvvNwS%!t8e|D(rvix9@3~^fW<#jOUgE?C*E45Ab zEk7+fE9ai%*%HU?_t*IGZDC-QIl*ezCAR1U%ZH`;J&iikyOJ~+_Dn3C@*?H@leOn> z%!}xC6uo4_`L4^>_wm{7{flh#O6OaxjJCj^?ma;rGFbl0U`?o#bt0<3~x%{dn3u}p8g`Ato+angh>p0k$u zN_ll%@D2ZGb#~^-_QF46y`}S7uN$BAd1tWPKh0|A+xipXpEMaabj^C|^6zp`%!Sf9 zJU6m6|2_VbtGVmsvWZHG5hv1=I@4R@cdbd>|6#6^M6Y`1!JbR&)z&0#J|TWm{Vh}2 zR>7d2oQOGI;SPsPl9R%$>XK>-XB=+zfB59_`GY2X%a`t-(NTOj<^RW;$LpvoHqyStKHR z;C*>c_J+h0iZ4&S{obSD^Xi|I_s4dND$R3^U6L7<$6sGDRa~j@GU8-^YKqMd3E z&YY6uo^@F6_+mb(Mt;vXb*VGXGBj;^euSrKjZn}Q#Sbg9ylo~2g{XV6vdmSyT=FeD z=!tg2G&@TbM-!e(wnOi}-&aqMo{*vWkHcO6sII^yk{0=rLTZnE!ve3<3^$6dE!THFcepiFeSVrv2*b0JcIJ&ci)NfP($Sq|(>lB1%(VxM z?Mgbf59W3xSWVuQrMCLfk{K3i8y-1zy>dDE@`S!q(33gRo$lAOt<={2kIdMi_FxxV zGHb)jG-FoZz;wf}`(wa?t#_2mK(lk>gwJm6_jtC){Pc?Go}!-;aWU}ngwH)+yn|vE z9J}NvBO0Bc$9}3y58E$H5B+<#6q)PIH6v?~Q{Eg-vRGXHx& zA?b9Hnzh^OAA5OQ4sW=fVac#FXf-S4MxEBt$cN8& zn@VY_^>n0Ob>6+$Ml?u9<<$Fmno*VW-rESPY}@iSf^m<0%UqFQhG3?KgL}69pEm7L zf5DreE!Xz^=V5m9n0VSdpQidMfeXCXsY?g(%Hk zYa`V^ZPVQQxU(im-ODfipVnQs(;_F*_Vz73kR?zSwB|zc<=6imy+68J#A#Z|NBUSy ztL?GCoRk)+Ptlqox}YTR3O) zFWn*cZavS^7gl|@w`CihjVSp2UE{04>ZKl=HVfUW_uu$uOV$Oi^Ws03_=$+0xaCy8 zbIzYtBIOOi+jnKDAO5HCW{Cuocj*6}YnT2|{xdzOM2dUafoZ%;ZrJLdjx`VR+_12~MI`mm1iqK|b#m1DTF+X=`+tc9kyrlJq!77bpF{P z9ItwGChzVAY1>PSXI*^2=%}(psQ9SC>Ln6S<3g`5aI$k(cGdY6ntIrdA^h28gTNJv zLKh}Y?qas;KJ~i5ZvEa}5x@WZUMk^x(MGA{!6SyA#2bHKp7FA~HY4imAG3*n%hx7P zO8R^8_N3tY-p@_Hnz#46cIEKiIDPjHOH#6iYvq-X%nHS#K})(H99g+cEn&Hjv6K^c zNBO>V=DwsEQ-fkAJa=N4_gMadr(twp=w;EM7R&oFD*>Rnp9@N@xcb%ob@_+X04!L{(eq`R} zm%CS4oGG$r@Ba@6Z`MDsj@swnb*K3N*UjfaPqaBUP10N{p{r>4-N#tzn;DDxM37U? zFuuud6o}ki!{=~AI?(i-Lq*K9%L;)h&VQdY>`aW^$;pzW^s=U1#QNGJ#%Sp#%itE# ztY1%WM>Pd99O~+K?GisXZ}-0^zqY1}yC2+~Enh#AJ>C6(Ze8|`uODW2{9bA-ot@|& zo%MFFtEAn^<|#26MfaC4-u)}X%{}_px0HX^*aYUkI6p&Ha`vs@$Opj-fQ z^UF^1cATuQFN5PIXSHj~k6l^E-IeyhoROj0F8fpF1dUkd8bJ=xxe{x_-$jId{rJGz z+Th0a2#18VWlMFu?oCXqUB@FH9kJk3vqt}srT#_?s|#$W_3!vCsyRt`y-j6VRftV> z(bG21p82(!{LXRVC)ZN}zL;(e!l zvrh~ZdG~=S=1)i6!sKJq4{JQi{kbMwX4m5j57&E7oKx}m%ZnW!FLt>rx%RrbsvmtQ zGA4X@7F)2 zIDM;#>2W{Hvz7XDe3wfv`*}LZruyd>kDY6luDF=-Z-^>+G}N9ot1Hg+q8G>Tg#Il=cw6Ef9v}H!{*QL)*L9AdMt~( zq)vR(??><6q{!9lZRY+{qB-kW`J}_9@nQR;yM%AwHa;e6xK+ed$~W5EaHh|^r4|i0 zj(qp}Xs>XKF(^fZ6DZmgtI~XQj77$7e4#+T$j#} zzqxg_vhw4vn?T+Pd{Ln(wcDZ4QD;u^jSu42gF?FIKNQH-$kxmPH zW6?U1sgF8$--x&tbS1;Yw`8A4Z|;K=2G1Bm)YP;XjDotn3Js-M%QoLUx(sY?<`V8D z6|U+v?FTv|q*?4dG__nS7rJVKjdk1Q&=vULPQ()rNf#bhP1mIwOIJ+U?cB9o`m+DN zwQT-upWoEI^gQDH#`;5eaMtBd8m6+|t8KorPE*?Z=JP*HL^c{ z2K@WL}&Z6lT~4@y!v}JH&_d=%Q^5Y;p`soy7We#Z1=i-BKsNSdzDQL z6ql|LSt>HM$lPP&1SYY!$0cHlI)6_}QesVLi>l;ipO?P&1arI&#Jr~~3wWl#{4{s- zHb&2{m9PKo`~4v?-uq&3SGUZM+cOvoJQT_+wBY7VbTwMNO!;VcclRkqb?tlYB4>FX zco{N(SiJHwKZDX5)`LIKtoa_8Wi{>gr!Qg-hLg|6Fh%@3_0FY%`Dp*@ms|~}uLYSj z$m+WKYtCcX=$gFs=PXXoKwU4*pqC^f#C(bKSbCQU5ThKc` z&9=wM)21kW+`}PPQF=!n```FH{pCuA$r105U4C5Hef1;r z##UYTF6{&J-^n|yT$!o1FE{6IoF4!A=gewvv$XA&m?-uKeHNJVJ^Z=h#eU{ma#j557i3eXOZ^*#B#p^Ka{$E(`Ts-!F(^nw{$QhFNp+-By(i zM>>=f=B@ns_2^UAeG?*Hbf0IqSTQF`wqnk`?g=7S|NVB6&pGw+$AmlE);zg1``pw= z_f*)s4&~G{*6Vhy*0B5lN_ZJ(7;m>lz2nk!YgAt+a@VQJX)BxKNzcotBw04<^omUA zbP9M`Ja4UI!H<1`T}urn2i1hEPF;C}f6m72IEKTPH}-5g*1f?}!2Ofl5C6<2KCk%N zI)Q)Z95+ONlY7RMGfmm~vcQ?mY)t1CJfC-Rqm1{Vw)2tamSqcXd9MGuRCAT%#Pc5v zub+6b&D!gutnx3RLm#~A;+Y=%Y+&%&SkJiK{Fx=oC$V<@F>Mw(l53H3z4?-Lo{{EJtHTF8CyS_tTFi+I>hkr?(6p1u^w{?!U-DT9 zFCW`(wL=dNh|k&BbMWC7OU2u%ny&8`=rEZ+`&3%?O;2*!g)r%DA)i)z7{=OPNRF8t z`1`(k{52ou*-l?3JGh)&sy4yoM=c^9NPtwEGa)Svy= z{elOk$@}&<-1_k=L*zlB`lp?L4xF-QNRu?yZ+voSmqo9hXaw^rk+aSU_jQh*^mxEz z_Wb?5?lt?$m#i>Zxb#PW4nxJ%in;e#(rnr*lM{~$Z0mlzHs|Vz9KGiUp1$bX$Q^TX zW6U`=H~&|&m42CQn8mbASJU|D>up&PG^a`8xB7%%R*R0a1n}I>zGi9g(&eA#=9^3FS8`TfEyxJw>{4=lEwN&z zZ;;HEH$}WVgq|iRT%5S*Qp>bQ&VfvECmXwd+O*AdpR>}=M(A_f0i)f|-gb9yviSM< zfuq#v7>Ar)+%B2HHQSE#S#D5T`a*JwWJ3F2gKIJ@J6DHxbxw+R?fS~CTYs|V-DHug z|NI#^kGUmo)~b3hSgUUp&~@+4+_dA-BI3*BuAjbJ{Pky4*NgY>hh-~ zO-R03@}JA-{*gbj28x$vdL>Pdd#=A~=a)s*OMcjvJa0d9ZRv|mx4jq6N^7e7_1}VH zjqxJ3mI#-QV1eZ~Viv!5qo(QSSon;)VcB=}Cpwjj^o~AL+ae<0ar4+r!}W>t zluLIdYM6R&+*4v@XwDhl#pxz<%2$8=dX4p-npJF1<)ywL^6c6rNq7`t}aX&yBU?fMFGNS|v$%gzeE&u4>pVjYy0zSwV;?Xt_c z>U-;%$>{<20uH?Elv~V_5O;F@c9Ge;<}(;&{ck<8bG`hHeun-VW|P(!PJgR^bl$z? zZnKSU-Bt`bbE}7)DBhQ^zZVOzp4%VZ_51o=c~woVzvLiI>hj_4?ktz6nWQVtbbS5UY4T&!-^R_n3;RhvURYIXo4qnVQ?g z>lU1fxstdqwkz48=iM2(lBGX-1T}YN_6k-zL_IrctWnpn-uUFX2MH~A8y`GMY7o<~ zI~^Bfv-IjuHO+6`eS(<^i@(h`t1IqXW$}TT`Nk^~&0l}qW>!v$X0<^?HBn zbqtG*{O>t>GO;VVttt3mu$!6jfy1(F&L0b&OrKQhvU+~3W{~?@iKO!{E4&=sdUu|c z^fEki`F*@%TGL2CMxV7dv!;HX5j`o#Kbz7jCr<|XYbpSDdweT~Blq)lC zrzC9ln|`Iy@mgjO&sRJ1Ta%veU3hN#qEenG=ZxJ?ANVvme^R0^)5i0wKYKQ`?_DCX zim_v#YTxOouD6Gm^Cnd5?LFPN#^{W>SK%C!ADj-UrOUf^iTr$b=Azn!Pu5ijKh+o4 z7bW;U^W^QiBeZ}?ywhuS+Kb;Ob@a@$P zZNH$BvMAs7NELROb7uq8jk5l0PW*INXZoR^vg$|W;uG&?IA7!5H}BkZCGC(08#X?g z$Wy%iU!T6d<~}!O=BTdRBN2Rj;*O~^@~1qKW)MuPWjmO>PGs^Xh2{77EIVSoA+F($ zJCIu3ef72Gtm!hW6VlfjJb$oh;)fIOgZZ4iF4{0_kMX)`^T z+F^D5u}g-mp6~NX>K&|4_gCI}Yu!~pBiT2zsV}IW@oe)3Q{D!3f8Daj2D1$-t?!$d z9nrqhe1p5&@b!CNhOI|reh7FLW~iuhEna86twpuiUGZ4TyekV%$QownsuL1*VXg3 zXJE#~qu)<+c(w>_6*1k zZ~HwJQa8(?j3;qgCZVFkN1KF*r6^|NR2_0;mR^k=8r=iWW4 zd)F#kI$+BD`*ZGp{{H@ZkH~wy|KC4YPRfhu6FGnGoY;5P=#TCm7rmHY*k}dGoRi(p zF7R@jO#T-o{skFdRgd~VF`8f+^rv!%o_{{$lgq&`xf! z4YJBdcb`6ScgKZCc4zaKFo@K(h}3#A2=|G+l{zwSPB`1YJxM!{uQ|VpLGGKX>z>zt z(w6-AT;MxTh~ZgnQI`4Xk2`qt8=K<&Y)&%8_lVRN{ma*EdpvpDB&E+b{DMVJp=v{7a3ksklOG?L5!aM`ooTm^Y?=?YM09q5U_TMn+J|r2`W0 zxmtxZ>o&w>uHR_9eTnzP?&LRyV1&w>xpx&eYjIzR%5pHPj&j$i+ks;bXlhi>P;}rR!#cWz}cPWEL7om zMlnFucK^N|yH1Et5^ny;nqVWRUl=5}yi8fgb?-kr(Pcq4cB`)GW?uY$%;RJF^hMw9 zq|cl9AYiRiP{E}T`$iSBqqeL|jw?pWl*Hva6@6G2-PLNKscDyER%t86=C^0bkG|AM zmS-#s-EXe0+5FKlw(F;YVd0J-9*f)O>>jr-TanGl9i}niq`aQu(D(>`qs|kuH zjSSrDneuYim`^xk&wQ!sZ~O{(t&ppm=gTwm>i&w8(7flYDaUl$C`2#STh9L4f{14) z;y-mX?_h0T>lYxGq7xMK<^xN`Th*h13ElT2dR&(WsMLmw`7`Z4vWLxXgNX8?*FRtR ze?Fj7=y^NkMYD*={Xf@BKD!9>IWM^&6}PQ|hwpf}@TSn9pf7x#1G0($bVpzg1E5}NnyHN_gN+P#)A9bV2<;riq^gNbqW z#X^T8b5EqFyT6*xs3RCD?od>j`+_;(M4T0Q$PGp^Tdbmj;eP% zxa^%Oby?@=_M@AH1bMkS76i{d+Q`XaT=A}(X~SA8t!JNKqzOLsmwIj$A+chjQ~nR7 z3A`slqYvzuJYoGdod||fRoC+ibQr9^%-^UzA;sP_WrpYJ^=e1YwNB&LnqLh{&6gdT zG`h@q7j1C=vez(Zk9p9M4<9~we9>)C<_pzXe(r9r@X|Y=BY!O=eXlRjT(ru1%`Dbu z>n0|3`OC*nOxm^g;%6V;6Ky|xMVFdQbI^64WSH=`OJwn$@+qqotq%mfu`8HZ$#=Ek z+x}3aFO8}jGA*~=u-s<5>u1xgDGi*_emPDPK#nf(+OuJ^mUmbXW7`xF+h(J~pZ^(` zJ(iaEc*{Mit{QY2@a8+^j=y%#n9qFq(k)@nEfsV2FLJ-nt$g&iitF@i%zRgEJllSL z{wTP?%}1Cc&}EgU(DNH}7}th+3jNr)OvC3SZ5J6BpRM@1`Hyvuo#}S0#r7UU&q80#)Ie!`dpxGjbbN zEqNh1<-EhxI+kxgoq`seb@e!%@2|%Y?p$dXMgX>TX@% z{kk^JWWT#T;D=?1sX|3%WAdiYD?WSr9TT%U^L@%AZpI}iqPxzv-{lX9XS5SCX45lZi&|H4 zPU(nbnf4`R4#UY!Pne#D2E7RCNx%Ct@ATW#y><^bSqFuDcVE%}X?2i{h{cA(4vjLJ z&-fTRnm;YlcHPaR8SiXw!>ILSQTgYsL06>rX;?RBGG>buepX(-Zw9MpS{WI+25+?|C^x`Dm5cPp%0j>Z18=(N<#5I$MwCdcS^_y>x|n%|%`x7LQN= zAIXaE;cy9^x2Jg$%QxpES6E$UYZ zubeF`lC1x0*2Zneo11=8iJ@Q9m)Do;&?`aMxnf1RM8SuZd9(H;cp$ zEKqZ`<}4_S>?(S;=gyb-a~gW#3`RSb+|hNG*ID)Z@$!bXbFQ7;yF_A6-r5QGKDb&a zU%51Git6+drOGA`Qkg@8x8f8=dko` z`SWT0Poa%6kzMC+%yCH--NMzdMGkU8ulK71%0@wN4(e;V{^mHb&r|+d!>!BjCncU| z*totoOGqG5U$bo%!?F8D?n`Gc-7$@wPiw0Ek4rsjuBR6G-kADGoT0mS?xtClr|y65 z=HMt^yHtK(4ny?R5O0RyDD!IXz*2{Z?22iNGIV9~n1t)x^;i5o8@prGrzPyJqAuwS z+sdwit|ehAv9#yh@n;(Pj}%y$1yz_dPF) zGe8RHKYf4ko;mCala8BxeUqlW>>cBb<7|Sh-;-UVvnw=@Ufj55j$rBCk3msJ z)e=fUm6w_qaVc3BKLTAp68ky*^UqYJ)iT-BUZj1S^=9vlni(gQ_gAwr9{DE|w3DO$ z-0_y4yk%ZT)5J`k=G=(xg3$?n^5logdy+JNfhP*ZW?_@kW1P=DhmXKlfF4 z;C}_lJl_|mGdA4MOUv=juPB`|pZhm^?kkx9-XHsIKJawKO^B_R=>3(O%RKF~@{M$! zrpEj8c)rJ7d(QuS*LUR?k5k_U?!SL6sjhvWdH#}$opeO8Ts(96J^_>7d6&kBbQg5}Hz)|4#eKUS{B6VGwA3z`$5> zV87)w`8>tOUYoTYOwA%oIa);Qr$5@qBz*JS*K3ML*)^H!H=TKz+rcS`?rf(#; z_wk~)i!QjX(>|+qH}!g~VK?`p{D-S9q@QRuKcQ>e;-%YSA-w-RXPU)_!w(%4x)>TY zm{=BZ2uzVVDz<=Y5yuDj&tZW%3|SxC0&^HvJ-ER1;1`cV7sDbBg)WB06Cr9ll#n!1 zhZC?jW<~k;h4)}C)&pGFI&Az>O_My9Sy1#FlqzCF8IGnUmf}Q)`LUG|bi>pU|-u;%h_jkaOyT5)G z&Yp7KC+Ygv-v^f;;yoYpHTJt{df=WNX%PXZqGwf@>Oa3dC*x7k?%5)_+hdp2_zCmh ztqWUNTYe%^M1QU1_S{EZHticNFCO{r`SIQPl}UDAHhX<#58Sgu-E)uC+siNXFV)zt zJWw_7-_0X0v%=P1HR*oTT5CCPFWXhwH+36}x7lZ^6w1t(x%s}R==fEI$X=lvOBdL< z^mK999gxzE_{ivSuA+8f+m;12vWWM}8!t(c@xTc+&itGPwk@?nj>a|NMR{c@A z^L51w`EP%({Q0GH)IBZi>wb@qHy{7Xw>h1+=+!Czrn>1O_P^`0?Dl(ntlQ)9v6X$| zqW|T=J16@TZ;IS>*fHB~p$*%!_uHeLb$`EGvdaF(ro|UCc)tCL3yWX!V}*w%pE%dd z_iCrL|Hf&Sl-%VKb zo=@p$R73E}Uvf;w0v3{M4t0yji)$VYOt>_^^QhD|k?BbrJ-^y3b(LP0RyY%){`dDg znQKjEf(!zWw}eUU%zMwx?DdiVX<3)}21_rSSt6bGY?G2U2yQT}X)dbQH0$bm9~QUd z$BT%dIV^5}eH9YDKeEgS`>(tx!aSGZ_NG-&*4gEo%zA4!=Wv?omMftpH%{N&Yn#32 zgX~g`ITCR*;(iDpNPDI}ZBfA@p-;0S>#o$6fB3sJf{UeQ`zNKN?#CxR65a9;;$@q& ze>z`1`nHdu;AXBx`^*Deo*#ewsHo#R5b5{r+nSGuzE6H6(XgHI;;oAf>+RQzEZ@Ps zcah*47N+&J+duE0khC+YZv(s1<^YML@9BFt1Uxo3laEgAXY?!#bH4I_?-GlH-7A?N zOj2hyArKOKni^fLUHXf-udrSs31-TNPVy^rX6 zzvuLOvD8yfjvxO#^Z0~CavUOS!}g~AUYXU>BmB~5?pBO#4NevsWz3@Xe!6YBrWdN zwmVWU0Hii+qpGJ5(GyTPC7Q(!u*?BJT_p&2?uQ7t3n6 zI5s~x@3a2KvV}j&JYLTDwWam=#6?NwrE_`0OV${K{n&Vn`DU*{?U7E?RTWC^FVCf( z4Agd6BJy>Ohv}==R{~p%nI|n*I(ke-<@55M9}9#2NX71R?P@0-u%-Cl(} zE51xwlrF=x*7JF-`;>n?T?K3@Ci5h&C-5}An4~3eG(^^72h)YH<^z3NMRojhOl$u# zH7#3p%I;jsEWOFw>+-&qOU+G`<9)u$x$94jx7f>ju{)lvSh(uSKg zcG-)vH=5}@n(LN6L;T01DUYl+T+=k#!sfX(P~zRkPdqsyOH9n;t_=j68Q4d1&qF)f(jCCcFQuRwFsK`pntGrjMvy7*xE z>uK-0+`b-3=Q#dym*)0lk-}d`9yE(;9_@;|zEe~B&s+e~8U^rygl z|7$DVHi^_ubu`_~do)AuG9RV4?LilLbdEKddQ<3jCJ3G2G$xaqmJcX@Mzj zrCnC}{wKp93H%LKOw|;5>A2o;vDc$51-CfmUE7ppr)6;P_J(Lp6X`aYBEId_43m(U z=PPr!%wbk_t6|WSeCWGvawz}f3ZLS+tme1a@}Db7zvZ2Lvu0iFvaIE6j9+cJc22@) zQ=I49SYQ zKi)k?XBDrj&N%;NQ@r$BHEYAOGRjKJKI$)d!TRr==24LgVlO|v$#FAn+^Q&dE%^Ya zXJMt&Qv=?FKQF3Fx1Hi=yFM{h-t}q8(iJalQWJCgrZleY6M5b^rRJmFms=Sdm+s)` zu~_oLlF97Ny+DOG!vBBAGvvDSP8WHayHl+=m+Sn*#-%%WYIbTKEzFW(^jx_2tkO}Y z3FYppJT(C-d-RtHB%b*jp(zy1``h=%h9%Fp`nfBGUYhF{_`=U@(-*zmfKQ*=l10i@ z=4$&{md{tVTX|J8(tV!!yjddmnFKR;wxv#gV8`;XWrEoELpJ=$Jy+LWuD>R^F-f<) zHu2gD{dmP2i@7!zozzub8qpPa#z1L)+k&I*RSJo+HrxU+DV|-W3D4i{KA>d&P&y(e zZa2&ExTl|87*8)tO_=<8>ooJcsYzTKU#C1`6R-_c-Lu=R*IB_iXidPEd?x9-tIvcq zCe@z1`Z{QicqYq@B^wPh%H+LI^Yi{K?zpRTG)Br@%k$&uOP3~X+{n6Q`kQ+q1uMAx z^!0mhFR8efY-G~<{ExZ}`_x4y3x0>(7JIf(i2a#p5^F?(d#c=lJ2SW5-^0DYf#JlT z1Wh4F{mO}A;+3m!y;Qi%dh}yU`D~VamZK}UmMYo%E`GJ`M~2S(z7s~vbkAIm=~}e@ zp)$|E)63P4@*nuaQM_RvTa!#m$*lR--M%TaL}d7kE-XBdtjBdyebS=dWd`S@Jr*54 zv-qUkwM3~&>qLIvca@&>*68&crI`IJo)bSTY1ls_VfrdIhTIosntDw0tGx_49HMhx zm3)(kh!LFgd6mjh!KoFj3fm@6?G%^ZRAv$r^hYI#Z^wemYuAaqW(eb8aQ?e=MRa>; ziO2qTU-T|KUcF?$$jfbaCKviVoN2T{lXhCtW)Y}ctUA6C(7!!6ql)Wvq zSnbsG1NWbPYI!ZBa`eT*?WayjnHBdK^Goz_UZ1hu!%+O#zWvKZuJ*7UycXdXy8YtQ zrX>~&h4#BCUJ&Dvlh9A&%(;KcePxr6jUBLoEH7L(Bh{dPv1AUlgu~NC)~5IQPDgVx^LBu^p)QyE^_+t zcuGKIpxe{zsrf#cwqaAT+RmTnvl@~vAeU@Cgc~ijiV@8Ymx+RwDmWY{)KbDXZ*t7Fuk;m7_>sfyX-R<| z6N_hAvA26qf6aQazp1h&X5&(i4aa_47F=4qWbXcVnn#5i`dJRi*Zy6)gS}?kk{`KK zgJlZi9_Shr@oVlq{#-0(BEUD2g{!EwusOW++=dR6j z--X9&e%s55ppw|8B`XY+68GA#_gc))YP)@{=CQ_E^CvTib3ILiWhu$Q<)=I3$D4IsjvD-xuVG1P=e>yB;K7%Jbs&$?hfC+M54wi zC}rn~b357mvfDPYI;5LzIqJx}@x~PKIo!T;8BPc@TsyiVQ%!*`k)$LO*PF$2( z|L1XX=z;?sLLZ*CiG20@p6A|G``(FNEU#|T<6SJCg(prOPOPfmCsekt`gSs<`#urw=Hg>XZ z!nau>;VTMrH+HH%P`D&3s;IeXNla1oP^eN-g*}QwkQgs9Sjl657p6t|hm@Rleae1~EY zKd1K2mwWzB)3r44j-9<<>%?;xS65F_zxiUy4OXGQOCwsZ+U_~FTh_F!!TisI$USPV z*Hh*MS4^9Iq1k)lw|?{cPnSKSiL_^5bYgn7<&LFFYMlAF^fZ|gfNG=1q~$q6YDCeC+qzNl#S^?I~u zuQhu*Eve)C%(jaPZ+9-Om?TPhgO=Ee+F$fwE`VvUM?^2X7765IEe z@&9)(;&@lFbNxpV?I{|2H~u=dS!s_~`~44x-E?HPK5q87_;>r6X-c13G=sJos`9>^ z{DN!l^u|OWv z?sW@y-+e&U)aL0Yozty?n_Y}U?Di@ieWeKRo`1_Z=*;IQ`&xp#COZgK9RJrU(%-1M|Huxe!jK?N|GM7gA6oq~ zzfGR7Y@7Q_(Mxhy5AE<`z7cnF<)Vm4y@yLf7OhEKIy*8VZ&gf!-#1RT=Lb8FuI=)+ zez@V<8?y|F^#*=>B^6d%ZRoBDd&ZFSPB(VF;h(zT8{2+~{l0sCtK`LSQ zef-p>{<{)3dFH=D<;dbMvTDL*yF(_qTig9mw=9jl-h3`*{r4-+?cdyepMS|g;=o7s z33lcdJC@FDQQc&*yw7qv&nchM9Y-XeTh_Br(!Fdh^;qnYP{|&HeV<$Fchs&6@Y^uu z#jb+ScKO?uzTLX#C)>P35!rwDU5~2CynanB<;RolU(=tvo$gn#h~)SXT)O*-Ra<#Q zc7IbHPq9gRMBI``F`-Kr7mCY%eH3+};i3kc^7h+*pO?;F9JoYz`->ByJn_rrm8=ZD z?A`y9W2?ro*rU=%g3V)IPvkEM53PM8QYGT;am!)PtG#D`Xmr)q=(Snx=JuPtS#i5E zt8{~(Ba^gx%JIeXw@Ccf*3-Wd!Lmto;a{QJFDXV9F%>$;t_!sGoi(Bhelvf{iTwlZLUt#-$`3(Iol&*i+Jn zPhRR*I;msb7I8|&W#fU~vW4-5yFTpe$#Od8`0X_PN%^PT@&HnaWl zy8dufJIa8a(}+@PJEcUc;rDogZ)Z_dc?Asmlvoax_BA;*omV zQi-F}k~_lK)RHRmw$%Izys}f>chK527grRTfj`8g;1>Z;Z= z?P{8GYvalAhndo`;r2&&xX!ZX3sIQ%ytz2OfJpYgPGsA_O*9Yh?&0J)$|FuM7`8-vZiJo}|Cv!wDZ`k3xJ)uV0 zHT#uDSI={agQq!W^!&V&V8<+dR3t>Ou%309;`)gHvYhn?UR^S5SYzy=&}EsoCMNKP z#pn$;FdKv1wt;){`mc=PW6=| zE={7F-Oh=oZp&Dl5xLn}++S`TP2)X>?Z}-lg$*iVLGz*ECb(x{cY# z%>)iP2)J6ROK*JFAopVb&dI8$i#Tp7?Y(|b#eP=LwfEV-rWX2^=TGFHo^s^ovbdPp z=OlbZTs2fSCwYaLxEas;^~Z7WX-eFp34T2)Hspi5neC2i!y$ z%@%QN5On?b_KG4S0|Ue11^?FOhdXQHf diff --git a/doc/qtcreator/src/ios/creator-ios-dev.qdoc b/doc/qtcreator/src/ios/creator-ios-dev.qdoc index d1e15e58b55..d9f17dc6624 100644 --- a/doc/qtcreator/src/ios/creator-ios-dev.qdoc +++ b/doc/qtcreator/src/ios/creator-ios-dev.qdoc @@ -155,42 +155,11 @@ \image qtcreator-ios-simulator-deploy.png The simulator is started automatically when you run the application. - To start the simulator manually, select \uicontrol Preferences > - \uicontrol Devices > \uicontrol iOS > \uicontrol Start. - - To take screenshots of the simulator, select \uicontrol Preferences > - \uicontrol Devices > \uicontrol iOS > \uicontrol Screenshot. The screenshots - are stored in the directory specified in the - \uicontrol {Screenshot directory} field. - - \section2 Managing Simulators - - The available simulators are listed in \uicontrol Preferences > - \uicontrol Devices > \uicontrol iOS. - - \image qtcreator-ios-preferences.png - - To create a new simulator instance: - - \list - - \li Select \uicontrol Create. - - \li In the \uicontrol {Device type} field, select the device type from - a list of devices supported by the Xcode version set as current on - your local machine. - - \li In the \uicontrol {OS version} field, select an OS version from a - list of OS versions supported by the selected device and the current - Xcode version. - - \endlist - - To rename the selected simulator, select \uicontrol Rename. - - To reset the contents and settings of the selected simulators, select - \uicontrol Reset. - - To delete the selected simulator, select \uicontrol Delete. + To start the simulator manually, either start the Simulator application + directly with Spotlight, or go to \uicontrol Xcode > \uicontrol {Open Developer Tool} + in Xcode. + Manage the available simulator devices + \l{https://developer.apple.com/documentation/xcode/running-your-app-in-simulator-or-on-a-device/#Configure-the-list-of-simulated-devices} + {in Xcode}. */ From 42edb0dd61a05702370a02d3efcbd5ba32e05e6b Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 14 Mar 2024 10:24:46 +0100 Subject: [PATCH 0121/1060] CppEditor: Make renameIncludes() also work for moved files Task-number: QTCREATORBUG-26545 Change-Id: I0bfe203af8f091562cdd91411dbe502fc5a76956 Reviewed-by: David Schulz Reviewed-by: Reviewed-by: Qt CI Bot --- src/plugins/cppeditor/cppmodelmanager.cpp | 29 ++++-- .../cppeditor/cppmodelmanager_test.cpp | 97 ++++++++++++------- src/plugins/cppeditor/cppmodelmanager_test.h | 1 + src/plugins/projectexplorer/projectmodels.cpp | 4 + .../testdata_renameheaders/header.h | 0 .../testdata_renameheaders/main.cpp | 5 + .../testdata_renameheaders/subdir1/file1.cpp | 3 + .../testdata_renameheaders/subdir1/header1.h | 0 .../testdata_renameheaders/subdir2/file2.cpp | 3 + .../testdata_renameheaders/subdir2/header2.h | 0 .../testdata_renameheaders.pro | 7 ++ 11 files changed, 108 insertions(+), 41 deletions(-) create mode 100644 tests/cppmodelmanager/testdata_renameheaders/header.h create mode 100644 tests/cppmodelmanager/testdata_renameheaders/main.cpp create mode 100644 tests/cppmodelmanager/testdata_renameheaders/subdir1/file1.cpp create mode 100644 tests/cppmodelmanager/testdata_renameheaders/subdir1/header1.h create mode 100644 tests/cppmodelmanager/testdata_renameheaders/subdir2/file2.cpp create mode 100644 tests/cppmodelmanager/testdata_renameheaders/subdir2/header2.h create mode 100644 tests/cppmodelmanager/testdata_renameheaders/testdata_renameheaders.pro diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index 5ea954add45..d5d6842e00f 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -1878,16 +1878,15 @@ void CppModelManager::renameIncludes(const QList> if (oldFilePath.isEmpty() || newFilePath.isEmpty()) continue; - // We just want to handle renamings so return when the file was actually moved. - if (oldFilePath.absolutePath() != newFilePath.absolutePath()) - continue; - const TextEditor::PlainRefactoringFileFactory changes; QString oldFileName = oldFilePath.fileName(); QString newFileName = newFilePath.fileName(); const bool isUiFile = oldFilePath.suffix() == "ui" && newFilePath.suffix() == "ui"; + const bool moved = oldFilePath.absolutePath() != newFilePath.absolutePath(); if (isUiFile) { + if (moved) + return; // This is out of scope. oldFileName = "ui_" + oldFilePath.baseName() + ".h"; newFileName = "ui_" + newFilePath.baseName() + ".h"; } @@ -1925,12 +1924,26 @@ void CppModelManager::renameIncludes(const QList> TextEditor::RefactoringFilePtr file = changes.file(includingFileNew); const QTextBlock &block = file->document()->findBlockByNumber(loc.second - 1); - const int replaceStart = block.text().indexOf(oldFileName); - if (replaceStart > -1) { + const FilePath relPathOld = FilePath::fromString(FilePath::calcRelativePath( + oldFilePath.toString(), includingFileOld.parentDir().toString())); + const FilePath relPathNew = FilePath::fromString(FilePath::calcRelativePath( + newFilePath.toString(), includingFileNew.parentDir().toString())); + int replaceStart = block.text().indexOf(relPathOld.toString()); + QString oldString; + QString newString; + if (isUiFile || replaceStart == -1) { + replaceStart = block.text().indexOf(oldFileName); + oldString = oldFileName; + newString = newFileName; + } else { + oldString = relPathOld.toString(); + newString = relPathNew.toString(); + } + if (replaceStart > -1 && oldString != newString) { ChangeSet changeSet; changeSet.replace(block.position() + replaceStart, - block.position() + replaceStart + oldFileName.length(), - newFileName); + block.position() + replaceStart + oldString.length(), + newString); file->setChangeSet(changeSet); file->apply(); } diff --git a/src/plugins/cppeditor/cppmodelmanager_test.cpp b/src/plugins/cppeditor/cppmodelmanager_test.cpp index a896563a61f..4ac39de737a 100644 --- a/src/plugins/cppeditor/cppmodelmanager_test.cpp +++ b/src/plugins/cppeditor/cppmodelmanager_test.cpp @@ -17,6 +17,7 @@ #include +#include #include #include #include @@ -965,50 +966,80 @@ void ModelManagerTest::testUpdateEditorsAfterProjectUpdate() QCOMPARE(documentBProjectPart->topLevelProject, pi->projectFilePath()); } +void ModelManagerTest::testRenameIncludes_data() +{ + QTest::addColumn("oldRelPath"); + QTest::addColumn("newRelPath"); + QTest::addColumn("successExpected"); + + QTest::addRow("rename in place 1") + << "subdir1/header1.h" << "subdir1/header1_renamed.h" << true; + QTest::addRow("rename in place 2") + << "subdir2/header2.h" << "subdir2/header2_renamed.h" << true; + QTest::addRow("rename in place 3") << "header.h" << "header_renamed.h" << true; + QTest::addRow("move up") << "subdir1/header1.h" << "header1_moved.h" << true; + QTest::addRow("move up (breaks build)") << "subdir2/header2.h" << "header2_moved.h" << false; + QTest::addRow("move down") << "header.h" << "subdir1/header_moved.h" << true; + QTest::addRow("move across") << "subdir1/header1.h" << "subdir2/header1_moved.h" << true; + QTest::addRow("move across (breaks build)") + << "subdir2/header2.h" << "subdir1/header2_moved.h" << false; +} + void ModelManagerTest::testRenameIncludes() { - struct ModelManagerGCHelper { - ~ModelManagerGCHelper() { CppModelManager::GC(); } - } GCHelper; - Q_UNUSED(GCHelper) // do not warn about being unused - + // Set up project. TemporaryDir tmpDir; QVERIFY(tmpDir.isValid()); + const MyTestDataDir sourceDir("testdata_renameheaders"); + const FilePath srcFilePath = FilePath::fromString(sourceDir.path()); + const FilePath projectDir = tmpDir.filePath().pathAppended(srcFilePath.fileName()); + const auto copyResult = srcFilePath.copyRecursively(projectDir); + if (!copyResult) + qDebug() << copyResult.error(); + QVERIFY(copyResult); + Kit * const kit = Utils::findOr(KitManager::kits(), nullptr, [](const Kit *k) { + return k->isValid() && !k->hasWarning() && k->value("QtSupport.QtInformation").isValid(); + }); + if (!kit) + QSKIP("The test requires at least one valid kit with a valid Qt"); + const FilePath projectFile = projectDir.pathAppended(projectDir.fileName() + ".pro"); + ProjectOpenerAndCloser projectMgr; + QVERIFY(projectMgr.open(projectFile, true, kit)); - const QDir workingDir(tmpDir.path()); - const QStringList fileNames = {"foo.h", "foo.cpp", "main.cpp"}; - const FilePath oldHeader = FilePath::fromString(workingDir.filePath("foo.h")); - const FilePath newHeader = FilePath::fromString(workingDir.filePath("bar.h")); - const MyTestDataDir testDir(_("testdata_project1")); - - // Copy test files to a temporary directory - QSet sourceFiles; - for (const QString &fileName : std::as_const(fileNames)) { - const QString &file = workingDir.filePath(fileName); - QVERIFY(QFile::copy(testDir.file(fileName), file)); - // Saving source file names for the model manager update, - // so we can update just the relevant files. - if (ProjectFile::classify(file) == ProjectFile::CXXSource) - sourceFiles.insert(FilePath::fromString(file)); - } - - // Update the c++ model manager and check for the old includes - CppModelManager::updateSourceFiles(sourceFiles).waitForFinished(); - QCoreApplication::processEvents(); + // Verify initial code model state. + const auto makeAbs = [&](const QStringList &relPaths) { + return Utils::transform>(relPaths, [&](const QString &relPath) { + return projectDir.pathAppended(relPath); + }); + }; + const QSet allSources = makeAbs({"main.cpp", "subdir1/file1.cpp", "subdir2/file2.cpp"}); + const QSet allHeaders = makeAbs({"header.h", "subdir1/header1.h", "subdir2/header2.h"}); CPlusPlus::Snapshot snapshot = CppModelManager::snapshot(); - for (const FilePath &sourceFile : std::as_const(sourceFiles)) { - QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet{oldHeader}); + for (const FilePath &srcFile : allSources) { + QCOMPARE(snapshot.allIncludesForDocument(srcFile), allHeaders); } - // Renaming the header + // Rename the header. + QFETCH(QString, oldRelPath); + QFETCH(QString, newRelPath); + QFETCH(bool, successExpected); + const FilePath oldHeader = projectDir.pathAppended(oldRelPath); + const FilePath newHeader = projectDir.pathAppended(newRelPath); QVERIFY(ProjectExplorerPlugin::renameFile(oldHeader, newHeader)); - // Update the c++ model manager again and check for the new includes - CppModelManager::updateSourceFiles(sourceFiles).waitForFinished(); - QCoreApplication::processEvents(); + // Verify new code model state. + QVERIFY(::CppEditor::Tests::waitForSignalOrTimeout( + CppModelManager::instance(), &CppModelManager::sourceFilesRefreshed, 10000)); + QSet incompleteNewHeadersSet = allHeaders; + incompleteNewHeadersSet.remove(oldHeader); + QSet completeNewHeadersSet = incompleteNewHeadersSet; + completeNewHeadersSet << newHeader; + snapshot = CppModelManager::snapshot(); - for (const FilePath &sourceFile : std::as_const(sourceFiles)) { - QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet{newHeader}); + for (const FilePath &srcFile : allSources) { + const QSet &expectedHeaders = srcFile.fileName() == "main.cpp" && !successExpected + ? incompleteNewHeadersSet : completeNewHeadersSet; + QCOMPARE(snapshot.allIncludesForDocument(srcFile), expectedHeaders); } } diff --git a/src/plugins/cppeditor/cppmodelmanager_test.h b/src/plugins/cppeditor/cppmodelmanager_test.h index 26cbefd1c84..14e9c617de9 100644 --- a/src/plugins/cppeditor/cppmodelmanager_test.h +++ b/src/plugins/cppeditor/cppmodelmanager_test.h @@ -28,6 +28,7 @@ private slots: void testDefinesPerEditor(); void testUpdateEditorsAfterProjectUpdate(); void testPrecompiledHeaders(); + void testRenameIncludes_data(); void testRenameIncludes(); void testRenameIncludesInEditor(); void testDocumentsAndRevisions(); diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp index 9d603b47309..c8b7392bf9c 100644 --- a/src/plugins/projectexplorer/projectmodels.cpp +++ b/src/plugins/projectexplorer/projectmodels.cpp @@ -802,6 +802,10 @@ bool FlatModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int r if (vcsAddPossible && !targetVcs.vcs->vcsAdd(targetFile)) failedVcsOp << targetFile; } + QList> renameList; + for (int i = 0; i < filesToAdd.size(); ++i) + renameList.emplaceBack(filesToRemove.at(i), filesToAdd.at(i)); + emit ProjectExplorerPlugin::instance()->filesRenamed(renameList); const RemovedFilesFromProject result = sourceProjectNode->removeFiles(filesToRemove, &failedRemoveFromProject); if (result == RemovedFilesFromProject::Wildcard) diff --git a/tests/cppmodelmanager/testdata_renameheaders/header.h b/tests/cppmodelmanager/testdata_renameheaders/header.h new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/cppmodelmanager/testdata_renameheaders/main.cpp b/tests/cppmodelmanager/testdata_renameheaders/main.cpp new file mode 100644 index 00000000000..629f20001ff --- /dev/null +++ b/tests/cppmodelmanager/testdata_renameheaders/main.cpp @@ -0,0 +1,5 @@ +#include "header.h" +#include "subdir1/header1.h" +#include + +int main() {} diff --git a/tests/cppmodelmanager/testdata_renameheaders/subdir1/file1.cpp b/tests/cppmodelmanager/testdata_renameheaders/subdir1/file1.cpp new file mode 100644 index 00000000000..e22ce8100c9 --- /dev/null +++ b/tests/cppmodelmanager/testdata_renameheaders/subdir1/file1.cpp @@ -0,0 +1,3 @@ +#include "header1.h" +#include "../header.h" +#include "../subdir2/header2.h" diff --git a/tests/cppmodelmanager/testdata_renameheaders/subdir1/header1.h b/tests/cppmodelmanager/testdata_renameheaders/subdir1/header1.h new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/cppmodelmanager/testdata_renameheaders/subdir2/file2.cpp b/tests/cppmodelmanager/testdata_renameheaders/subdir2/file2.cpp new file mode 100644 index 00000000000..8c83d5ef036 --- /dev/null +++ b/tests/cppmodelmanager/testdata_renameheaders/subdir2/file2.cpp @@ -0,0 +1,3 @@ +#include "header2.h" +#include "../header.h" +#include "../subdir1/header1.h" diff --git a/tests/cppmodelmanager/testdata_renameheaders/subdir2/header2.h b/tests/cppmodelmanager/testdata_renameheaders/subdir2/header2.h new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/cppmodelmanager/testdata_renameheaders/testdata_renameheaders.pro b/tests/cppmodelmanager/testdata_renameheaders/testdata_renameheaders.pro new file mode 100644 index 00000000000..f5f09586fff --- /dev/null +++ b/tests/cppmodelmanager/testdata_renameheaders/testdata_renameheaders.pro @@ -0,0 +1,7 @@ +TEMPLATE = app +TARGET = testdata_renameheaders +INCLUDEPATH += subdir2 +CONFIG += no_include_pwd + +HEADERS = header.h subdir1/header1.h subdir2/header2.h +SOURCES = main.cpp subdir1/file1.cpp subdir2/file2.cpp From c459e8d49086903389b0e428e25608b1d68e275b Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Mon, 8 Apr 2024 18:02:45 +0200 Subject: [PATCH 0122/1060] CtfVisualizer: Avoid precision loss warning Change-Id: If0f97ec662350ab309219f6a740a7b3b77639262 Reviewed-by: Eike Ziller --- src/plugins/ctfvisualizer/ctftimelinemodel.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/ctfvisualizer/ctftimelinemodel.cpp b/src/plugins/ctfvisualizer/ctftimelinemodel.cpp index 01288772760..2a2a8860120 100644 --- a/src/plugins/ctfvisualizer/ctftimelinemodel.cpp +++ b/src/plugins/ctfvisualizer/ctftimelinemodel.cpp @@ -29,7 +29,7 @@ CtfTimelineModel::CtfTimelineModel(Timeline::TimelineModelAggregator *parent, { updateName(); setCollapsedRowCount(1); - setCategoryColor(colorByHue(qHash(pid))); + setCategoryColor(colorByHue(int(qHash(pid)))); setHasMixedTypesInExpandedState(true); } From 411100b0378202dc617acaa236f4730eb4cc43b2 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 27 Mar 2024 14:00:21 +0100 Subject: [PATCH 0123/1060] TextEditor: remove text editor action handler Give each editor a context and register editor actions individually for that context. This removes the need to tell the action handler the current editor. Additionally all actions are now available in editor widgets outside of the EditorManager. Change-Id: I0109866b180889762f8bd8aa07874d8d7c55bfa6 Reviewed-by: Marcus Tillmanns --- .../android/androidmanifesteditorfactory.cpp | 8 - .../android/androidmanifesteditorwidget.cpp | 4 +- src/plugins/android/javaeditor.cpp | 3 +- .../cmakeprojectmanager/cmakeeditor.cpp | 7 +- .../compilerexplorereditor.cpp | 75 +- .../compilerexplorer/compilerexplorereditor.h | 7 +- src/plugins/cppeditor/cppeditorplugin.cpp | 17 +- src/plugins/diffeditor/diffeditorfactory.cpp | 28 +- src/plugins/diffeditor/diffeditorfactory.h | 8 - .../genericprojectfileseditor.cpp | 3 +- src/plugins/glsleditor/glsleditor.cpp | 7 +- src/plugins/haskell/haskelleditorfactory.cpp | 5 +- src/plugins/languageclient/client.cpp | 13 +- src/plugins/nim/editor/nimeditorfactory.cpp | 9 +- src/plugins/python/pythoneditor.cpp | 9 +- .../qmakeprojectmanager/profileeditor.cpp | 5 +- .../qmakeprojectmanagerplugin.cpp | 1 - .../bindingeditor/bindingeditorwidget.cpp | 1 - src/plugins/qmljseditor/qmljseditor.cpp | 13 +- src/plugins/texteditor/CMakeLists.txt | 1 - src/plugins/texteditor/jsoneditor.cpp | 3 +- src/plugins/texteditor/markdowneditor.cpp | 15 +- .../texteditor/plaintexteditorfactory.cpp | 7 +- src/plugins/texteditor/texteditor.cpp | 511 ++++++++++++- src/plugins/texteditor/texteditor.h | 19 +- src/plugins/texteditor/texteditor.qbs | 2 - .../texteditor/texteditoractionhandler.cpp | 671 ------------------ .../texteditor/texteditoractionhandler.h | 69 -- src/plugins/texteditor/texteditorplugin.cpp | 355 +++++++++ src/plugins/vcsbase/vcsbaseeditor.cpp | 3 +- 30 files changed, 924 insertions(+), 955 deletions(-) delete mode 100644 src/plugins/texteditor/texteditoractionhandler.cpp delete mode 100644 src/plugins/texteditor/texteditoractionhandler.h diff --git a/src/plugins/android/androidmanifesteditorfactory.cpp b/src/plugins/android/androidmanifesteditorfactory.cpp index 7a900a687ec..41d6af0861d 100644 --- a/src/plugins/android/androidmanifesteditorfactory.cpp +++ b/src/plugins/android/androidmanifesteditorfactory.cpp @@ -9,7 +9,6 @@ #include -#include #include namespace Android::Internal { @@ -18,10 +17,6 @@ class AndroidManifestEditorFactory final : public Core::IEditorFactory { public: AndroidManifestEditorFactory() - : m_actionHandler(Constants::ANDROID_MANIFEST_EDITOR_ID, - Constants::ANDROID_MANIFEST_EDITOR_CONTEXT, - TextEditor::TextEditorActionHandler::UnCommentSelection, - [](Core::IEditor *editor) { return static_cast(editor)->textEditor(); }) { setId(Constants::ANDROID_MANIFEST_EDITOR_ID); setDisplayName(Tr::tr("Android Manifest editor")); @@ -31,9 +26,6 @@ public: return androidManifestEditorWidget->editor(); }); } - -private: - TextEditor::TextEditorActionHandler m_actionHandler; }; void setupAndroidManifestEditor() diff --git a/src/plugins/android/androidmanifesteditorwidget.cpp b/src/plugins/android/androidmanifesteditorwidget.cpp index c941f3f43fc..608f0b5262e 100644 --- a/src/plugins/android/androidmanifesteditorwidget.cpp +++ b/src/plugins/android/androidmanifesteditorwidget.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include @@ -114,6 +113,7 @@ private: AndroidManifestEditorWidget::AndroidManifestEditorWidget() { m_textEditorWidget = new AndroidManifestTextEditorWidget(this); + m_textEditorWidget->setOptionalActions(TextEditor::OptionalActions::UnCommentSelection); initializePage(); @@ -1406,7 +1406,7 @@ AndroidManifestTextEditorWidget::AndroidManifestTextEditorWidget(AndroidManifest setupGenericHighlighter(); setMarksVisible(false); - // this context is used by the TextEditorActionHandler registered for the text editor in + // this context is used by the OptionalActions registered for the text editor in // the AndroidManifestEditorFactory m_context = new Core::IContext(this); m_context->setWidget(this); diff --git a/src/plugins/android/javaeditor.cpp b/src/plugins/android/javaeditor.cpp index 27ced1b025a..8fa69e6e8b2 100644 --- a/src/plugins/android/javaeditor.cpp +++ b/src/plugins/android/javaeditor.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include @@ -48,7 +47,7 @@ public: setDocumentCreator(createJavaDocument); setUseGenericHighlighter(true); setCommentDefinition(Utils::CommentDefinition::CppStyle); - setEditorActionHandlers(TextEditor::TextEditorActionHandler::UnCommentSelection); + setOptionalActionMask(TextEditor::OptionalActions::UnCommentSelection); setCompletionAssistProvider(new TextEditor::KeywordsCompletionAssistProvider(keywords)); } }; diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp index 968d6260e70..27db33e14d2 100644 --- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include @@ -533,9 +532,9 @@ public: setCompletionAssistProvider(new CMakeFileCompletionAssistProvider); setAutoCompleterCreator([] { return new CMakeAutoCompleter; }); - setEditorActionHandlers(TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::FollowSymbolUnderCursor - | TextEditorActionHandler::Format); + setOptionalActionMask(OptionalActions::UnCommentSelection + | OptionalActions::FollowSymbolUnderCursor + | OptionalActions::Format); addHoverHandler(new CMakeHoverHandler); diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index 651ee596205..107968d9702 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include @@ -564,12 +563,10 @@ void CompilerWidget::doCompile() EditorWidget::EditorWidget(const std::shared_ptr &document, QUndoStack *undoStack, - TextEditorActionHandler &actionHandler, QWidget *parent) : Utils::FancyMainWindow(parent) , m_document(document) , m_undoStack(undoStack) - , m_actionHandler(actionHandler) { setContextMenuPolicy(Qt::NoContextMenu); setDockNestingEnabled(true); @@ -589,10 +586,6 @@ EditorWidget::EditorWidget(const std::shared_ptr &document this, &EditorWidget::recreateEditors); - connect(this, &EditorWidget::gotFocus, this, [&actionHandler] { - actionHandler.updateCurrentEditor(); - }); - setupHelpWidget(); } @@ -627,10 +620,6 @@ CompilerWidget *EditorWidget::addCompiler(const std::shared_ptr sourceSettings->compilers.removeItem(compilerSettings->shared_from_this()); }); - connect(compiler, &CompilerWidget::gotFocus, this, [this] { - m_actionHandler.updateCurrentEditor(); - }); - return compiler; } @@ -669,10 +658,6 @@ void EditorWidget::addSourceEditor(const std::shared_ptr &source setupHelpWidget(); }); - connect(sourceEditor, &SourceEditorWidget::gotFocus, this, [this] { - m_actionHandler.updateCurrentEditor(); - }); - dockWidget->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); addDockWidget(Qt::LeftDockWidgetArea, dockWidget); @@ -842,18 +827,11 @@ TextEditor::TextEditorWidget *EditorWidget::focusedEditorWidget() const return nullptr; } -Editor::Editor(TextEditorActionHandler &actionHandler) +Editor::Editor() : m_document(new JsonSettingsDocument(&m_undoStack)) { setContext(Core::Context(Constants::CE_EDITOR_ID)); - setWidget(new EditorWidget(m_document, &m_undoStack, actionHandler)); - - connect(&m_undoStack, &QUndoStack::canUndoChanged, this, [&actionHandler] { - actionHandler.updateActions(); - }); - connect(&m_undoStack, &QUndoStack::canRedoChanged, this, [&actionHandler] { - actionHandler.updateActions(); - }); + setWidget(new EditorWidget(m_document, &m_undoStack)); } Editor::~Editor() @@ -909,12 +887,6 @@ QWidget *Editor::toolBar() } EditorFactory::EditorFactory() - : m_actionHandler(Constants::CE_EDITOR_ID, - Constants::CE_EDITOR_ID, - TextEditor::TextEditorActionHandler::None, - [](Core::IEditor *editor) -> TextEditorWidget * { - return static_cast(editor->widget())->focusedEditorWidget(); - }) { setId(Constants::CE_EDITOR_ID); setDisplayName(Tr::tr("Compiler Explorer Editor")); @@ -926,48 +898,7 @@ EditorFactory::EditorFactory() return &static_cast(editor)->m_undoStack; }; - m_actionHandler.setCanUndoCallback([undoStackFromEditor](Core::IEditor *editor) { - if (auto undoStack = undoStackFromEditor(editor)) - return undoStack->canUndo(); - return false; - }); - - m_actionHandler.setCanRedoCallback([undoStackFromEditor](Core::IEditor *editor) { - if (auto undoStack = undoStackFromEditor(editor)) - return undoStack->canRedo(); - return false; - }); - - m_actionHandler.setUnhandledCallback( - [undoStackFromEditor](Utils::Id cmdId, Core::IEditor *editor) { - if (cmdId == TextEditor::Constants::INCREASE_FONT_SIZE) { - TextEditor::TextEditorSettings::instance()->increaseFontZoom(); - return true; - } else if (cmdId == TextEditor::Constants::DECREASE_FONT_SIZE) { - TextEditor::TextEditorSettings::instance()->decreaseFontZoom(); - return true; - } - - if (cmdId != Core::Constants::UNDO && cmdId != Core::Constants::REDO) - return false; - - if (!childHasFocus(editor->widget())) - return false; - - QUndoStack *undoStack = undoStackFromEditor(editor); - - if (!undoStack) - return false; - - if (cmdId == Core::Constants::UNDO) - undoStack->undo(); - else - undoStack->redo(); - - return true; - }); - - setEditorCreator([this]() { return new Editor(m_actionHandler); }); + setEditorCreator([this]() { return new Editor; }); } QList AsmDocument::setCompileResult( diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.h b/src/plugins/compilerexplorer/compilerexplorereditor.h index c9c02e5215f..56eef3fd36f 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.h +++ b/src/plugins/compilerexplorer/compilerexplorereditor.h @@ -11,7 +11,6 @@ #include #include -#include #include @@ -223,7 +222,6 @@ class EditorWidget : public Utils::FancyMainWindow public: EditorWidget(const std::shared_ptr &document, QUndoStack *undoStack, - TextEditor::TextEditorActionHandler &actionHandler, QWidget *parent = nullptr); ~EditorWidget() override; @@ -253,7 +251,6 @@ protected: private: std::shared_ptr m_document; QUndoStack *m_undoStack; - TextEditor::TextEditorActionHandler &m_actionHandler; QList m_compilerWidgets; QList m_sourceWidgets; @@ -262,7 +259,7 @@ private: class Editor : public Core::IEditor { public: - Editor(TextEditor::TextEditorActionHandler &actionHandler); + Editor(); ~Editor(); Core::IDocument *document() const override { return m_document.get(); } @@ -279,8 +276,6 @@ public: EditorFactory(); private: - TextEditor::TextEditorActionHandler m_actionHandler; - QAction m_undoAction; QAction m_redoAction; }; diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 4328c939707..9a110398760 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -75,7 +75,6 @@ #include #include #include -#include #include #include @@ -139,14 +138,14 @@ public: setCodeFoldingSupported(true); setParenthesesMatchingEnabled(true); - setEditorActionHandlers(TextEditorActionHandler::Format - | TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::UnCollapseAll - | TextEditorActionHandler::FollowSymbolUnderCursor - | TextEditorActionHandler::FollowTypeUnderCursor - | TextEditorActionHandler::RenameSymbol - | TextEditorActionHandler::TypeHierarchy - | TextEditorActionHandler::FindUsage); + setOptionalActionMask(OptionalActions::Format + | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll + | OptionalActions::FollowSymbolUnderCursor + | OptionalActions::FollowTypeUnderCursor + | OptionalActions::RenameSymbol + | OptionalActions::TypeHierarchy + | OptionalActions::FindUsage); } }; diff --git a/src/plugins/diffeditor/diffeditorfactory.cpp b/src/plugins/diffeditor/diffeditorfactory.cpp index 70537dd3f73..a3981ed49b1 100644 --- a/src/plugins/diffeditor/diffeditorfactory.cpp +++ b/src/plugins/diffeditor/diffeditorfactory.cpp @@ -7,8 +7,6 @@ #include "diffeditordocument.h" #include "diffeditortr.h" -#include "texteditor/texteditoractionhandler.h" - #include using namespace Core; @@ -17,31 +15,7 @@ using namespace Utils; namespace DiffEditor::Internal { -DiffEditorFactory::DiffEditorFactory() : - descriptionHandler { - Constants::DIFF_EDITOR_ID, - Constants::C_DIFF_EDITOR_DESCRIPTION, - TextEditorActionHandler::None, - [](IEditor *e) { return static_cast(e)->descriptionWidget(); } - }, - unifiedHandler { - Constants::DIFF_EDITOR_ID, - Constants::UNIFIED_VIEW_ID, - TextEditorActionHandler::None, - [](IEditor *e) { return static_cast(e)->unifiedEditorWidget(); } - }, - leftHandler { - Constants::DIFF_EDITOR_ID, - Id(Constants::SIDE_BY_SIDE_VIEW_ID).withSuffix(1), - TextEditorActionHandler::None, - [](IEditor *e) { return static_cast(e)->sideEditorWidget(LeftSide); } - }, - rightHandler { - Constants::DIFF_EDITOR_ID, - Id(Constants::SIDE_BY_SIDE_VIEW_ID).withSuffix(2), - TextEditorActionHandler::None, - [](Core::IEditor *e) { return static_cast(e)->sideEditorWidget(RightSide); } - } +DiffEditorFactory::DiffEditorFactory() { setId(Constants::DIFF_EDITOR_ID); setDisplayName(Tr::tr("Diff Editor")); diff --git a/src/plugins/diffeditor/diffeditorfactory.h b/src/plugins/diffeditor/diffeditorfactory.h index e39f0fc46fc..3c05e4af1ce 100644 --- a/src/plugins/diffeditor/diffeditorfactory.h +++ b/src/plugins/diffeditor/diffeditorfactory.h @@ -5,20 +5,12 @@ #include -#include - namespace DiffEditor::Internal { class DiffEditorFactory : public Core::IEditorFactory { public: DiffEditorFactory(); - -private: - TextEditor::TextEditorActionHandler descriptionHandler; - TextEditor::TextEditorActionHandler unifiedHandler; - TextEditor::TextEditorActionHandler leftHandler; - TextEditor::TextEditorActionHandler rightHandler; }; } // namespace DiffEditor::Internal diff --git a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp index eef322a1519..5070cf67cdd 100644 --- a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp +++ b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp @@ -9,7 +9,6 @@ #include #include -#include using namespace TextEditor; @@ -29,7 +28,7 @@ public: addMimeType("application/vnd.qtcreator.generic.cflags"); setDocumentCreator([]() { return new TextDocument(Constants::FILES_EDITOR_ID); }); - setEditorActionHandlers(TextEditorActionHandler::None); + setOptionalActionMask(OptionalActions::None); } }; diff --git a/src/plugins/glsleditor/glsleditor.cpp b/src/plugins/glsleditor/glsleditor.cpp index 36bba041372..a454057ce26 100644 --- a/src/plugins/glsleditor/glsleditor.cpp +++ b/src/plugins/glsleditor/glsleditor.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include @@ -466,9 +465,9 @@ public: setParenthesesMatchingEnabled(true); setCodeFoldingSupported(true); - setEditorActionHandlers(TextEditorActionHandler::Format - | TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::UnCollapseAll); + setOptionalActionMask(OptionalActions::Format + | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll); } }; diff --git a/src/plugins/haskell/haskelleditorfactory.cpp b/src/plugins/haskell/haskelleditorfactory.cpp index 89bf561b1f7..55f077a9f96 100644 --- a/src/plugins/haskell/haskelleditorfactory.cpp +++ b/src/plugins/haskell/haskelleditorfactory.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include @@ -42,8 +41,8 @@ public: setId(Constants::C_HASKELLEDITOR_ID); setDisplayName(::Core::Tr::tr("Haskell Editor")); addMimeType("text/x-haskell"); - setEditorActionHandlers(TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::FollowSymbolUnderCursor); + setOptionalActionMask( + OptionalActions::UnCommentSelection | OptionalActions::FollowSymbolUnderCursor); setDocumentCreator([] { return new TextDocument(Constants::C_HASKELLEDITOR_ID); }); setIndenterCreator([](QTextDocument *doc) { return new TextIndenter(doc); }); setEditorWidgetCreator(&createEditorWidget); diff --git a/src/plugins/languageclient/client.cpp b/src/plugins/languageclient/client.cpp index 5e3d240f8c1..0d7826307ab 100644 --- a/src/plugins/languageclient/client.cpp +++ b/src/plugins/languageclient/client.cpp @@ -49,7 +49,6 @@ #include #include #include -#include #include #include @@ -1005,17 +1004,17 @@ void Client::activateEditor(Core::IEditor *editor) d->requestDocumentHighlights(widget); uint optionalActions = widget->optionalActions(); if (symbolSupport().supportsFindUsages(widget->textDocument())) - optionalActions |= TextEditor::TextEditorActionHandler::FindUsage; + optionalActions |= TextEditor::OptionalActions::FindUsage; if (symbolSupport().supportsRename(widget->textDocument())) - optionalActions |= TextEditor::TextEditorActionHandler::RenameSymbol; + optionalActions |= TextEditor::OptionalActions::RenameSymbol; if (symbolSupport().supportsFindLink(widget->textDocument(), LinkTarget::SymbolDef)) - optionalActions |= TextEditor::TextEditorActionHandler::FollowSymbolUnderCursor; + optionalActions |= TextEditor::OptionalActions::FollowSymbolUnderCursor; if (symbolSupport().supportsFindLink(widget->textDocument(), LinkTarget::SymbolTypeDef)) - optionalActions |= TextEditor::TextEditorActionHandler::FollowTypeUnderCursor; + optionalActions |= TextEditor::OptionalActions::FollowTypeUnderCursor; if (supportsCallHierarchy(this, textEditor->document())) - optionalActions |= TextEditor::TextEditorActionHandler::CallHierarchy; + optionalActions |= TextEditor::OptionalActions::CallHierarchy; if (supportsTypeHierarchy(this, textEditor->document())) - optionalActions |= TextEditor::TextEditorActionHandler::TypeHierarchy; + optionalActions |= TextEditor::OptionalActions::TypeHierarchy; widget->setOptionalActions(optionalActions); } } diff --git a/src/plugins/nim/editor/nimeditorfactory.cpp b/src/plugins/nim/editor/nimeditorfactory.cpp index ac8aa6c9329..edd7bcea069 100644 --- a/src/plugins/nim/editor/nimeditorfactory.cpp +++ b/src/plugins/nim/editor/nimeditorfactory.cpp @@ -11,7 +11,6 @@ #include #include -#include #include using namespace TextEditor; @@ -26,10 +25,10 @@ NimEditorFactory::NimEditorFactory() addMimeType(QLatin1String(Nim::Constants::C_NIM_MIMETYPE)); addMimeType(QLatin1String(Nim::Constants::C_NIM_SCRIPT_MIMETYPE)); - setEditorActionHandlers(TextEditorActionHandler::Format - | TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::UnCollapseAll - | TextEditorActionHandler::FollowSymbolUnderCursor); + setOptionalActionMask(OptionalActions::Format + | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll + | OptionalActions::FollowSymbolUnderCursor); setEditorWidgetCreator([]{ return new NimTextEditorWidget(); }); diff --git a/src/plugins/python/pythoneditor.cpp b/src/plugins/python/pythoneditor.cpp index ddd30f2acf5..94a8e498eba 100644 --- a/src/plugins/python/pythoneditor.cpp +++ b/src/plugins/python/pythoneditor.cpp @@ -27,7 +27,6 @@ #include #include -#include #include @@ -317,10 +316,10 @@ public: setDisplayName(::Core::Tr::tr(Constants::C_EDITOR_DISPLAY_NAME)); addMimeType(Constants::C_PY_MIMETYPE); - setEditorActionHandlers(TextEditorActionHandler::Format - | TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::UnCollapseAll - | TextEditorActionHandler::FollowSymbolUnderCursor); + setOptionalActionMask(OptionalActions::Format + | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll + | OptionalActions::FollowSymbolUnderCursor); setDocumentCreator([]() { return new PythonDocument; }); setEditorWidgetCreator([]() { return new PythonEditorWidget; }); diff --git a/src/plugins/qmakeprojectmanager/profileeditor.cpp b/src/plugins/qmakeprojectmanager/profileeditor.cpp index c510e139012..8b86a58b4ba 100644 --- a/src/plugins/qmakeprojectmanager/profileeditor.cpp +++ b/src/plugins/qmakeprojectmanager/profileeditor.cpp @@ -19,7 +19,6 @@ #include #include -#include #include #include @@ -273,8 +272,8 @@ ProFileEditorFactory::ProFileEditorFactory() setCompletionAssistProvider(completionAssistProvider); setCommentDefinition(CommentDefinition::HashStyle); - setEditorActionHandlers(TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::JumpToFileUnderCursor); + setOptionalActionMask(OptionalActions::UnCommentSelection + | OptionalActions::JumpToFileUnderCursor); addHoverHandler(new ProFileHoverHandler); setSyntaxHighlighterCreator([]() { return new ProFileHighlighter; }); diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp index 9dd3fa079b2..c2f2d2c6e22 100644 --- a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp @@ -36,7 +36,6 @@ #include #include -#include #include #include diff --git a/src/plugins/qmldesigner/components/bindingeditor/bindingeditorwidget.cpp b/src/plugins/qmldesigner/components/bindingeditor/bindingeditorwidget.cpp index ff2361aa36c..b067dc8d46f 100644 --- a/src/plugins/qmldesigner/components/bindingeditor/bindingeditorwidget.cpp +++ b/src/plugins/qmldesigner/components/bindingeditor/bindingeditorwidget.cpp @@ -147,7 +147,6 @@ BindingEditorFactory::BindingEditorFactory() { setId(BINDINGEDITOR_CONTEXT_ID); setDisplayName(::Core::Tr::tr("Binding Editor")); - setEditorActionHandlers(0); addMimeType(BINDINGEDITOR_CONTEXT_ID); addMimeType(Utils::Constants::QML_MIMETYPE); addMimeType(Utils::Constants::QMLTYPES_MIMETYPE); diff --git a/src/plugins/qmljseditor/qmljseditor.cpp b/src/plugins/qmljseditor/qmljseditor.cpp index 79d24891c78..540e5559de6 100644 --- a/src/plugins/qmljseditor/qmljseditor.cpp +++ b/src/plugins/qmljseditor/qmljseditor.cpp @@ -52,7 +52,6 @@ #include #include #include -#include #include #include @@ -1169,12 +1168,12 @@ QmlJSEditorFactory::QmlJSEditorFactory(Utils::Id _id) addHoverHandler(new ColorPreviewHoverHandler); setCompletionAssistProvider(new QmlJSCompletionAssistProvider); - setEditorActionHandlers(TextEditorActionHandler::Format - | TextEditorActionHandler::UnCommentSelection - | TextEditorActionHandler::UnCollapseAll - | TextEditorActionHandler::FollowSymbolUnderCursor - | TextEditorActionHandler::RenameSymbol - | TextEditorActionHandler::FindUsage); + setOptionalActionMask(OptionalActions::Format + | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll + | OptionalActions::FollowSymbolUnderCursor + | OptionalActions::RenameSymbol + | OptionalActions::FindUsage); } static void decorateEditor(TextEditorWidget *editor) diff --git a/src/plugins/texteditor/CMakeLists.txt b/src/plugins/texteditor/CMakeLists.txt index e766ec06a10..978d0de86a7 100644 --- a/src/plugins/texteditor/CMakeLists.txt +++ b/src/plugins/texteditor/CMakeLists.txt @@ -104,7 +104,6 @@ add_qtc_plugin(TextEditor texteditor.qrc texteditor_global.h texteditortr.h - texteditoractionhandler.cpp texteditoractionhandler.h texteditorconstants.cpp texteditorconstants.h texteditoroverlay.cpp texteditoroverlay.h texteditorplugin.cpp diff --git a/src/plugins/texteditor/jsoneditor.cpp b/src/plugins/texteditor/jsoneditor.cpp index d06f215c688..7081394f9be 100644 --- a/src/plugins/texteditor/jsoneditor.cpp +++ b/src/plugins/texteditor/jsoneditor.cpp @@ -6,7 +6,6 @@ #include "autocompleter.h" #include "textdocument.h" #include "texteditor.h" -#include "texteditoractionhandler.h" #include "texteditortr.h" #include "textindenter.h" @@ -164,7 +163,7 @@ public: setDocumentCreator([] { return new TextDocument(JSON_EDITOR_ID); }); setAutoCompleterCreator([] { return new JsonAutoCompleter; }); setIndenterCreator([](QTextDocument *doc) { return new JsonIndenter(doc); }); - setEditorActionHandlers(TextEditorActionHandler::Format); + setOptionalActionMask(OptionalActions::Format); setUseGenericHighlighter(true); } }; diff --git a/src/plugins/texteditor/markdowneditor.cpp b/src/plugins/texteditor/markdowneditor.cpp index dbfdcda2b42..c08fedeb104 100644 --- a/src/plugins/texteditor/markdowneditor.cpp +++ b/src/plugins/texteditor/markdowneditor.cpp @@ -16,8 +16,6 @@ #include #include -#include - #include #include #include @@ -73,7 +71,7 @@ class MarkdownEditor : public IEditor { Q_OBJECT public: - MarkdownEditor(const TextEditor::TextEditorActionHandler *actionHandler) + MarkdownEditor() : m_document(new TextDocument(MARKDOWNVIEWER_ID)) { m_document->setMimeType(MARKDOWNVIEWER_MIME_TYPE); @@ -108,7 +106,7 @@ public: // editor m_textEditorWidget = new MarkdownEditorWidget; - m_textEditorWidget->setOptionalActions(actionHandler->optionalActions()); + m_textEditorWidget->setOptionalActions(OptionalActions::FollowSymbolUnderCursor); m_textEditorWidget->setTextDocument(m_document); m_textEditorWidget->setupGenericHighlighter(); m_textEditorWidget->setMarksVisible(false); @@ -501,7 +499,6 @@ public: MarkdownEditorFactory(); private: - TextEditorActionHandler m_actionHandler; Action m_emphasisAction; Action m_strongAction; Action m_inlineCodeAction; @@ -512,17 +509,11 @@ private: }; MarkdownEditorFactory::MarkdownEditorFactory() - : m_actionHandler(MARKDOWNVIEWER_ID, - MARKDOWNVIEWER_TEXT_CONTEXT, - TextEditor::TextEditorActionHandler::FollowSymbolUnderCursor, - [](IEditor *editor) { - return static_cast(editor)->textEditorWidget(); - }) { setId(MARKDOWNVIEWER_ID); setDisplayName(::Core::Tr::tr("Markdown Editor")); addMimeType(MARKDOWNVIEWER_MIME_TYPE); - setEditorCreator([this] { return new MarkdownEditor{&m_actionHandler}; }); + setEditorCreator([] { return new MarkdownEditor; }); const auto textContext = Context(MARKDOWNVIEWER_TEXT_CONTEXT); const auto context = Context(MARKDOWNVIEWER_ID); diff --git a/src/plugins/texteditor/plaintexteditorfactory.cpp b/src/plugins/texteditor/plaintexteditorfactory.cpp index fbaf430284d..ef989ee6216 100644 --- a/src/plugins/texteditor/plaintexteditorfactory.cpp +++ b/src/plugins/texteditor/plaintexteditorfactory.cpp @@ -5,7 +5,6 @@ #include "basehoverhandler.h" #include "textdocument.h" #include "texteditor.h" -#include "texteditoractionhandler.h" #include "texteditorconstants.h" #include @@ -40,9 +39,9 @@ public: setEditorWidgetCreator([]() { return new PlainTextEditorWidget; }); setUseGenericHighlighter(true); - setEditorActionHandlers(TextEditorActionHandler::Format | - TextEditorActionHandler::UnCommentSelection | - TextEditorActionHandler::UnCollapseAll); + setOptionalActionMask( + OptionalActions::Format | OptionalActions::UnCommentSelection + | OptionalActions::UnCollapseAll); } }; diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 85bd4732baa..9a7c0a2b267 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -21,6 +21,7 @@ #include "highlighterhelper.h" #include "highlightersettings.h" #include "icodestylepreferences.h" +#include "linenumberfilter.h" #include "marginsettings.h" #include "refactoroverlay.h" #include "snippets/snippetoverlay.h" @@ -28,11 +29,11 @@ #include "tabsettings.h" #include "textdocument.h" #include "textdocumentlayout.h" -#include "texteditoractionhandler.h" #include "texteditorconstants.h" #include "texteditoroverlay.h" #include "texteditorsettings.h" #include "texteditortr.h" +#include "typehierarchy.h" #include "typingsettings.h" #include @@ -45,7 +46,9 @@ #include #include #include +#include #include +#include #include #include @@ -738,6 +741,14 @@ public: void openTypeUnderCursor(bool openInNextSplit); qreal charWidth() const; + // actions + void registerActions(); + void updateActions(); + void updateOptionalActions(); + void updateRedoAction(bool on); + void updateUndoAction(bool on); + void updateCopyAction(bool on); + public: TextEditorWidget *q; QWidget *m_toolBarWidget = nullptr; @@ -753,7 +764,7 @@ public: QToolButton *m_fileLineEnding = nullptr; QAction *m_fileLineEndingAction = nullptr; - uint m_optionalActionMask = TextEditorActionHandler::None; + uint m_optionalActionMask = OptionalActions::None; bool m_contentsChanged = false; bool m_lastCursorChangeWasInteresting = false; std::shared_ptr m_suggestionBlocker; @@ -927,6 +938,30 @@ public: void updateSuggestion(); void clearCurrentSuggestion(); QTextBlock m_suggestionBlock; + + Context m_editorContext; + QAction *m_undoAction = nullptr; + QAction *m_redoAction = nullptr; + QAction *m_copyAction = nullptr; + QAction *m_copyHtmlAction = nullptr; + QAction *m_cutAction = nullptr; + QAction *m_autoIndentAction = nullptr; + QAction *m_autoFormatAction = nullptr; + QAction *m_visualizeWhitespaceAction = nullptr; + QAction *m_textWrappingAction = nullptr; + QAction *m_unCommentSelectionAction = nullptr; + QAction *m_unfoldAllAction = nullptr; + QAction *m_followSymbolAction = nullptr; + QAction *m_followSymbolInNextSplitAction = nullptr; + QAction *m_followToTypeAction = nullptr; + QAction *m_followToTypeInNextSplitAction = nullptr; + QAction *m_findUsageAction = nullptr; + QAction *m_openCallHierarchyAction = nullptr; + QAction *m_openTypeHierarchyAction = nullptr; + QAction *m_renameSymbolAction = nullptr; + QAction *m_jumpToFileAction = nullptr; + QAction *m_jumpToFileInNextSplitAction = nullptr; + QList m_modifyingActions; }; class TextEditorWidgetFind : public BaseTextFind @@ -1031,6 +1066,8 @@ TextEditorWidgetPrivate::TextEditorWidgetPrivate(TextEditorWidget *parent) , m_codeAssistant(parent) , m_hoverHandlerRunner(parent, m_hoverHandlers) , m_autoCompleter(new AutoCompleter) + , m_editorContext( + Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID).withSuffix(QUuid::createUuid().toString())) { m_selectionHighlightOverlay->show(); auto aggregate = new Aggregation::Aggregate; @@ -1095,6 +1132,15 @@ TextEditorWidgetPrivate::TextEditorWidgetPrivate(TextEditorWidget *parent) connect(q, &QPlainTextEdit::selectionChanged, this, &TextEditorWidgetPrivate::slotSelectionChanged); + connect(q, &QPlainTextEdit::undoAvailable, + this, &TextEditorWidgetPrivate::updateUndoAction); + + connect(q, &QPlainTextEdit::redoAvailable, + this, &TextEditorWidgetPrivate::updateRedoAction); + + connect(q, &QPlainTextEdit::copyAvailable, + this, &TextEditorWidgetPrivate::updateCopyAction); + m_parenthesesMatchingTimer.setSingleShot(true); m_parenthesesMatchingTimer.setInterval(50); connect(&m_parenthesesMatchingTimer, &QTimer::timeout, @@ -1141,6 +1187,14 @@ TextEditorWidgetPrivate::TextEditorWidgetPrivate(TextEditorWidget *parent) q, &TextEditorWidget::setCompletionSettings); connect(settings, &TextEditorSettings::extraEncodingSettingsChanged, q, &TextEditorWidget::setExtraEncodingSettings); + + auto context = new Core::IContext(this); + context->setWidget(q); + context->setContext(m_editorContext); + Core::ICore::addContextObject(context); + + registerActions(); + updateActions(); } TextEditorWidgetPrivate::~TextEditorWidgetPrivate() @@ -3810,6 +3864,434 @@ qreal TextEditorWidgetPrivate::charWidth() const return QFontMetricsF(q->font()).horizontalAdvance(QLatin1Char('x')); } +void TextEditorWidgetPrivate::registerActions() +{ + using namespace Core::Constants; + using namespace TextEditor::Constants; + + m_undoAction = ActionBuilder(this, UNDO) + .setContext(m_editorContext) + .addOnTriggered([this] { q->undo(); }) + .contextAction(); + m_redoAction = ActionBuilder(this, REDO) + .setContext(m_editorContext) + .addOnTriggered([this] { q->redo(); }) + .contextAction(); + m_copyAction = ActionBuilder(this, COPY) + .setContext(m_editorContext) + .addOnTriggered([this] { q->copy(); }) + .contextAction(); + m_cutAction = ActionBuilder(this, CUT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->cut(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, PASTE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->paste(); }) + .contextAction(); + ActionBuilder(this, SELECTALL) + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectAll(); }); + ActionBuilder(this, GOTO) + .setContext(m_editorContext) + .addOnTriggered([] { LocatorManager::showFilter(lineNumberFilter()); }); + ActionBuilder(this, PRINT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->print(ICore::printer()); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteLine(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_END_OF_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfLine(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_END_OF_WORD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfWord(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_END_OF_WORD_CAMEL_CASE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfWordCamelCase(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_START_OF_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfLine(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_START_OF_WORD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfWord(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DELETE_START_OF_WORD_CAMEL_CASE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfWordCamelCase(); }) + .contextAction(); + ActionBuilder(this, GOTO_BLOCK_START_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockStartWithSelection(); }); + ActionBuilder(this, GOTO_BLOCK_END_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockEndWithSelection(); }); + m_modifyingActions << ActionBuilder(this, MOVE_LINE_UP) + .setContext(m_editorContext) + .addOnTriggered([this] { q->moveLineUp(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, MOVE_LINE_DOWN) + .setContext(m_editorContext) + .addOnTriggered([this] { q->moveLineDown(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, COPY_LINE_UP) + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLineUp(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, COPY_LINE_DOWN) + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLineDown(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, JOIN_LINES) + .setContext(m_editorContext) + .addOnTriggered([this] { q->joinLines(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, INSERT_LINE_ABOVE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->insertLineAbove(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, INSERT_LINE_BELOW) + .setContext(m_editorContext) + .addOnTriggered([this] { q->insertLineBelow(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, SWITCH_UTF8BOM) + .setContext(m_editorContext) + .addOnTriggered([this] { q->switchUtf8bom(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, INDENT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->indent(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, UNINDENT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->unindent(); }) + .contextAction(); + m_followSymbolAction = ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursor(); }) + .contextAction(); + m_followSymbolInNextSplitAction = ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursorInNextSplit(); }) + .contextAction(); + m_followToTypeAction = ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openTypeUnderCursor(); }) + .contextAction(); + m_followToTypeInNextSplitAction = ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE_IN_NEXT_SPLIT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openTypeUnderCursorInNextSplit(); }) + .contextAction(); + m_findUsageAction = ActionBuilder(this, FIND_USAGES) + .setContext(m_editorContext) + .addOnTriggered([this] { q->findUsages(); }) + .contextAction(); + m_renameSymbolAction = ActionBuilder(this, RENAME_SYMBOL) + .setContext(m_editorContext) + .addOnTriggered([this] { q->renameSymbolUnderCursor(); }) + .contextAction(); + m_jumpToFileAction = ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursor(); }) + .contextAction(); + m_jumpToFileInNextSplitAction = ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursorInNextSplit(); }) + .contextAction(); + m_openCallHierarchyAction = ActionBuilder(this, OPEN_CALL_HIERARCHY) + .setContext(m_editorContext) + .addOnTriggered([this] { q->openCallHierarchy(); }) + .contextAction(); + m_openTypeHierarchyAction = ActionBuilder(this, OPEN_TYPE_HIERARCHY) + .setContext(m_editorContext) + .addOnTriggered([] { + updateTypeHierarchy(NavigationWidget::activateSubWidget( + Constants::TYPE_HIERARCHY_FACTORY_ID, Side::Left)); + }) + .contextAction(); + ActionBuilder(this, VIEW_PAGE_UP) + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewPageUp(); }); + ActionBuilder(this, VIEW_PAGE_DOWN) + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewPageDown(); }); + ActionBuilder(this, VIEW_LINE_UP) + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewLineUp(); }); + ActionBuilder(this, VIEW_LINE_DOWN) + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewLineDown(); }); + + ActionBuilder(this, SELECT_ENCODING) + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectEncoding(); }); + m_modifyingActions << ActionBuilder(this, CIRCULAR_PASTE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->circularPaste(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, NO_FORMAT_PASTE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->pasteWithoutFormat(); }) + .contextAction(); + + m_autoIndentAction = ActionBuilder(this, AUTO_INDENT_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->autoIndent(); }) + .contextAction(); + m_autoFormatAction = ActionBuilder(this, AUTO_FORMAT_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->autoFormat(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, REWRAP_PARAGRAPH) + .setContext(m_editorContext) + .addOnTriggered([this] { q->rewrapParagraph(); }) + .contextAction(); + m_visualizeWhitespaceAction = ActionBuilder(this, VISUALIZE_WHITESPACE) + .setContext(m_editorContext) + .addOnToggled( + this, + [this](bool checked) { + DisplaySettings ds = q->displaySettings(); + ds.m_visualizeWhitespace = checked; + q->setDisplaySettings(ds); + }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, CLEAN_WHITESPACE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->cleanWhitespace(); }) + .contextAction(); + m_textWrappingAction = ActionBuilder(this, TEXT_WRAPPING) + .setContext(m_editorContext) + .addOnToggled(this, [this] (bool checked) { + DisplaySettings ds = q->displaySettings(); + ds.m_textWrapping = checked; + q->setDisplaySettings(ds); + }) + .contextAction(); + m_unCommentSelectionAction = ActionBuilder(this, UN_COMMENT_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->unCommentSelection(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, CUT_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->cutLine(); }) + .contextAction(); + ActionBuilder(this, COPY_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLine(); }); + m_copyHtmlAction = ActionBuilder(this, COPY_WITH_HTML) + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyWithHtml(); }) + .contextAction(); + ActionBuilder(this, ADD_CURSORS_TO_LINE_ENDS) + .setContext(m_editorContext) + .addOnTriggered([this] { q->addCursorsToLineEnds(); }); + ActionBuilder(this, ADD_SELECT_NEXT_FIND_MATCH) + .setContext(m_editorContext) + .addOnTriggered([this] { q->addSelectionNextFindMatch(); }); + m_modifyingActions << ActionBuilder(this, DUPLICATE_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->duplicateSelection(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, DUPLICATE_SELECTION_AND_COMMENT) + .setContext(m_editorContext) + .addOnTriggered([this] { q->duplicateSelectionAndComment(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, UPPERCASE_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->uppercaseSelection(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, LOWERCASE_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->lowercaseSelection(); }) + .contextAction(); + m_modifyingActions << ActionBuilder(this, SORT_LINES) + .setContext(m_editorContext) + .addOnTriggered([this] { q->sortLines(); }) + .contextAction(); + ActionBuilder(this, FOLD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->foldCurrentBlock(); }); + ActionBuilder(this, UNFOLD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->unfoldCurrentBlock(); }); + m_unfoldAllAction = ActionBuilder(this, UNFOLD_ALL) + .setContext(m_editorContext) + .addOnTriggered([this] { q->unfoldAll(); }) + .contextAction(); + ActionBuilder(this, INCREASE_FONT_SIZE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->increaseFontZoom(); }); + ActionBuilder(this, DECREASE_FONT_SIZE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->decreaseFontZoom(); }); + ActionBuilder(this, RESET_FONT_SIZE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->zoomReset(); }); + ActionBuilder(this, GOTO_BLOCK_START) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockStart(); }); + ActionBuilder(this, GOTO_BLOCK_END) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockEnd(); }); + ActionBuilder(this, SELECT_BLOCK_UP) + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectBlockUp(); }); + ActionBuilder(this, SELECT_BLOCK_DOWN) + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectBlockDown(); }); + ActionBuilder(this, SELECT_WORD_UNDER_CURSOR) + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectWordUnderCursor(); }); + + ActionBuilder(this, GOTO_DOCUMENT_START) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoDocumentStart(); }); + ActionBuilder(this, GOTO_DOCUMENT_END) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoDocumentEnd(); }); + ActionBuilder(this, GOTO_LINE_START) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineStart(); }); + ActionBuilder(this, GOTO_LINE_END) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineEnd(); }); + ActionBuilder(this, GOTO_NEXT_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextLine(); }); + ActionBuilder(this, GOTO_PREVIOUS_LINE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousLine(); }); + ActionBuilder(this, GOTO_PREVIOUS_CHARACTER) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousCharacter(); }); + ActionBuilder(this, GOTO_NEXT_CHARACTER) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextCharacter(); }); + ActionBuilder(this, GOTO_PREVIOUS_WORD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWord(); }); + ActionBuilder(this, GOTO_NEXT_WORD) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWord(); }); + ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordCamelCase(); }); + ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordCamelCase(); }); + + ActionBuilder(this, GOTO_LINE_START_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineStartWithSelection(); }); + ActionBuilder(this, GOTO_LINE_END_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineEndWithSelection(); }); + ActionBuilder(this, GOTO_NEXT_LINE_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextLineWithSelection(); }); + ActionBuilder(this, GOTO_PREVIOUS_LINE_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousLineWithSelection(); }); + ActionBuilder(this, GOTO_PREVIOUS_CHARACTER_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousCharacterWithSelection(); }); + ActionBuilder(this, GOTO_NEXT_CHARACTER_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextCharacterWithSelection(); }); + ActionBuilder(this, GOTO_PREVIOUS_WORD_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordWithSelection(); }); + ActionBuilder(this, GOTO_NEXT_WORD_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordWithSelection(); }); + ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordCamelCaseWithSelection(); }); + ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION) + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordCamelCaseWithSelection(); }); + + // Collect additional modifying actions so we can check for them inside a readonly file + // and disable them + m_modifyingActions << m_autoIndentAction; + m_modifyingActions << m_autoFormatAction; + m_modifyingActions << m_unCommentSelectionAction; + + updateOptionalActions(); +} + +void TextEditorWidgetPrivate::updateActions() +{ + bool isWritable = !q->isReadOnly(); + for (QAction *a : std::as_const(m_modifyingActions)) + a->setEnabled(isWritable); + m_unCommentSelectionAction->setEnabled((m_optionalActionMask & OptionalActions::UnCommentSelection) && isWritable); + m_visualizeWhitespaceAction->setEnabled(q); + if (TextEditorSettings::fontSettings().relativeLineSpacing() == 100) { + m_textWrappingAction->setEnabled(q); + } else { + m_textWrappingAction->setEnabled(false); + m_textWrappingAction->setChecked(false); + } + m_visualizeWhitespaceAction->setChecked(m_displaySettings.m_visualizeWhitespace); + m_textWrappingAction->setChecked(m_displaySettings.m_textWrapping); + + updateRedoAction(q->document()->isRedoAvailable()); + updateUndoAction(q->document()->isUndoAvailable()); + updateCopyAction(q->textCursor().hasSelection()); + + updateOptionalActions(); +} + +void TextEditorWidgetPrivate::updateOptionalActions() +{ + using namespace OptionalActions; + m_followSymbolAction->setEnabled(m_optionalActionMask & FollowSymbolUnderCursor); + m_followSymbolInNextSplitAction->setEnabled(m_optionalActionMask & FollowSymbolUnderCursor); + m_followToTypeAction->setEnabled(m_optionalActionMask & FollowTypeUnderCursor); + m_followToTypeInNextSplitAction->setEnabled(m_optionalActionMask & FollowTypeUnderCursor); + m_findUsageAction->setEnabled(m_optionalActionMask & FindUsage); + m_jumpToFileAction->setEnabled(m_optionalActionMask & JumpToFileUnderCursor); + m_jumpToFileInNextSplitAction->setEnabled(m_optionalActionMask & JumpToFileUnderCursor); + m_unfoldAllAction->setEnabled(m_optionalActionMask & UnCollapseAll); + m_renameSymbolAction->setEnabled(m_optionalActionMask & RenameSymbol); + m_openCallHierarchyAction->setEnabled(m_optionalActionMask & CallHierarchy); + m_openTypeHierarchyAction->setEnabled(m_optionalActionMask & TypeHierarchy); + + bool formatEnabled = (m_optionalActionMask & OptionalActions::Format) + && !q->isReadOnly(); + m_autoIndentAction->setEnabled(formatEnabled); + m_autoFormatAction->setEnabled(formatEnabled); +} + +void TextEditorWidgetPrivate::updateRedoAction(bool on) +{ + m_redoAction->setEnabled(on); +} + +void TextEditorWidgetPrivate::updateUndoAction(bool on) +{ + m_undoAction->setEnabled(on); +} + +void TextEditorWidgetPrivate::updateCopyAction(bool hasCopyableText) +{ + if (m_cutAction) + m_cutAction->setEnabled(hasCopyableText && !q->isReadOnly()); + if (m_copyAction) + m_copyAction->setEnabled(hasCopyableText); + if (m_copyHtmlAction) + m_copyHtmlAction->setEnabled(hasCopyableText); +} + bool TextEditorWidget::codeFoldingVisible() const { return d->m_codeFoldingVisible; @@ -8103,6 +8585,7 @@ void TextEditorWidgetPrivate::applyFontSettingsDelayed() m_fontSettingsNeedsApply = true; if (q->isVisible()) q->triggerPendingUpdates(); + updateActions(); } void TextEditorWidgetPrivate::markRemoved(TextMark *mark) @@ -8338,6 +8821,7 @@ void TextEditorWidget::setReadOnly(bool b) emit readOnlyChanged(); if (b) setTextInteractionFlags(textInteractionFlags() | Qt::TextSelectableByKeyboard); + d->updateActions(); } void TextEditorWidget::cut() @@ -8735,32 +9219,32 @@ void TextEditorWidget::setupFallBackEditor(Id id) void TextEditorWidget::appendStandardContextMenuActions(QMenu *menu) { - if (optionalActions() & TextEditorActionHandler::FollowSymbolUnderCursor) { + if (optionalActions() & OptionalActions::FollowSymbolUnderCursor) { const auto action = ActionManager::command(Constants::FOLLOW_SYMBOL_UNDER_CURSOR)->action(); if (!menu->actions().contains(action)) menu->addAction(action); } - if (optionalActions() & TextEditorActionHandler::FollowTypeUnderCursor) { + if (optionalActions() & OptionalActions::FollowTypeUnderCursor) { const auto action = ActionManager::command(Constants::FOLLOW_SYMBOL_TO_TYPE)->action(); if (!menu->actions().contains(action)) menu->addAction(action); } - if (optionalActions() & TextEditorActionHandler::FindUsage) { + if (optionalActions() & OptionalActions::FindUsage) { const auto action = ActionManager::command(Constants::FIND_USAGES)->action(); if (!menu->actions().contains(action)) menu->addAction(action); } - if (optionalActions() & TextEditorActionHandler::RenameSymbol) { + if (optionalActions() & OptionalActions::RenameSymbol) { const auto action = ActionManager::command(Constants::RENAME_SYMBOL)->action(); if (!menu->actions().contains(action)) menu->addAction(action); } - if (optionalActions() & TextEditorActionHandler::CallHierarchy) { + if (optionalActions() & OptionalActions::CallHierarchy) { const auto action = ActionManager::command(Constants::OPEN_CALL_HIERARCHY)->action(); if (!menu->actions().contains(action)) menu->addAction(action); } - if (optionalActions() & TextEditorActionHandler::TypeHierarchy) { + if (optionalActions() & OptionalActions::TypeHierarchy) { const auto action = ActionManager::command(Constants::OPEN_TYPE_HIERARCHY)->action(); if (!menu->actions().contains(action)) menu->addAction(action); @@ -8792,7 +9276,7 @@ void TextEditorWidget::setOptionalActions(uint optionalActionMask) if (d->m_optionalActionMask == optionalActionMask) return; d->m_optionalActionMask = optionalActionMask; - emit optionalActionMaskChanged(); + d->updateOptionalActions(); } void TextEditorWidget::addOptionalActions( uint optionalActionMask) @@ -9492,7 +9976,7 @@ public: CommentDefinition m_commentDefinition; QList m_hoverHandlers; // owned std::unique_ptr m_completionAssistProvider; // owned - std::unique_ptr m_textEditorActionHandler; + int m_optionalActionMask = 0; bool m_useGenericHighlighter = false; bool m_duplicatedSupported = true; bool m_codeFoldingSupported = false; @@ -9565,9 +10049,9 @@ void TextEditorFactory::setAutoCompleterCreator(const AutoCompleterCreator &crea d->m_autoCompleterCreator = creator; } -void TextEditorFactory::setEditorActionHandlers(uint optionalActions) +void TextEditorFactory::setOptionalActionMask(int optionalActions) { - d->m_textEditorActionHandler.reset(new TextEditorActionHandler(id(), id(), optionalActions)); + d->m_optionalActionMask = optionalActions; } void TextEditorFactory::addHoverHandler(BaseHoverHandler *handler) @@ -9613,8 +10097,7 @@ BaseTextEditor *TextEditorFactoryPrivate::createEditorHelper(const TextDocumentP textEditorWidget->setMarksVisible(m_marksVisible); textEditorWidget->setParenthesesMatchingEnabled(m_paranthesesMatchinEnabled); textEditorWidget->setCodeFoldingSupported(m_codeFoldingSupported); - if (m_textEditorActionHandler) - textEditorWidget->setOptionalActions(m_textEditorActionHandler->optionalActions()); + textEditorWidget->setOptionalActions(m_optionalActionMask); BaseTextEditor *editor = m_editorCreator(); editor->setDuplicateSupported(m_duplicatedSupported); diff --git a/src/plugins/texteditor/texteditor.h b/src/plugins/texteditor/texteditor.h index 85344a8dbd0..2d54231b1c4 100644 --- a/src/plugins/texteditor/texteditor.h +++ b/src/plugins/texteditor/texteditor.h @@ -85,6 +85,22 @@ enum TextMarkRequestKind TaskMarkRequest }; +namespace OptionalActions { +enum Mask { + None = 0, + Format = 1, + UnCommentSelection = 2, + UnCollapseAll = 4, + FollowSymbolUnderCursor = 8, + FollowTypeUnderCursor = 16, + JumpToFileUnderCursor = 32, + RenameSymbol = 64, + FindUsage = 128, + CallHierarchy = 256, + TypeHierarchy = 512, +}; +} // namespace OptionalActions + class TEXTEDITOR_EXPORT BaseTextEditor : public Core::IEditor { Q_OBJECT @@ -511,7 +527,6 @@ signals: void requestUsages(const QTextCursor &cursor); void requestRename(const QTextCursor &cursor); void requestCallHierarchy(const QTextCursor &cursor); - void optionalActionMaskChanged(); void toolbarOutlineChanged(QWidget *newOutline); protected: @@ -689,7 +704,7 @@ public: void setSyntaxHighlighterCreator(const SyntaxHighLighterCreator &creator); void setUseGenericHighlighter(bool enabled); void setAutoCompleterCreator(const AutoCompleterCreator &creator); - void setEditorActionHandlers(uint optionalActions); + void setOptionalActionMask(int optionalActions); void addHoverHandler(BaseHoverHandler *handler); void setCompletionAssistProvider(CompletionAssistProvider *provider); diff --git a/src/plugins/texteditor/texteditor.qbs b/src/plugins/texteditor/texteditor.qbs index 30a4712b731..7c0ee120934 100644 --- a/src/plugins/texteditor/texteditor.qbs +++ b/src/plugins/texteditor/texteditor.qbs @@ -137,8 +137,6 @@ QtcPlugin { "texteditor.qrc", "texteditor_global.h", "texteditortr.h", - "texteditoractionhandler.cpp", - "texteditoractionhandler.h", "texteditorconstants.cpp", "texteditorconstants.h", "texteditoroverlay.cpp", diff --git a/src/plugins/texteditor/texteditoractionhandler.cpp b/src/plugins/texteditor/texteditoractionhandler.cpp deleted file mode 100644 index 2cf553689cc..00000000000 --- a/src/plugins/texteditor/texteditoractionhandler.cpp +++ /dev/null @@ -1,671 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "texteditoractionhandler.h" - -#include "texteditor.h" -#include "displaysettings.h" -#include "fontsettings.h" -#include "linenumberfilter.h" -#include "texteditortr.h" -#include "texteditorsettings.h" -#include "typehierarchy.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include - -using namespace Core; - -namespace TextEditor { -namespace Internal { - -class TextEditorActionHandlerPrivate : public QObject -{ -public: - TextEditorActionHandlerPrivate(Utils::Id editorId, Utils::Id contextId, uint optionalActions); - - QAction *registerActionHelper(Utils::Id id, - bool scriptable, - const QString &title, - const QKeySequence &keySequence, - Utils::Id menueGroup, - ActionContainer *container, - std::function slot) - { - auto result = new QAction(title, this); - Command *command - = ActionManager::registerAction(result, id, Context(m_contextId), scriptable); - if (!keySequence.isEmpty()) - command->setDefaultKeySequence(keySequence); - - if (container && menueGroup.isValid()) - container->addAction(command, menueGroup); - - connect(result, &QAction::triggered, slot); - return result; - } - - QAction *registerAction(Utils::Id id, - std::function slot, - bool scriptable = false, - const QString &title = QString(), - const QKeySequence &keySequence = QKeySequence(), - Utils::Id menueGroup = Utils::Id(), - ActionContainer *container = nullptr) - { - return registerActionHelper(id, - scriptable, - title, - keySequence, - menueGroup, - container, - [this, slot, id](bool) { - if (m_currentEditorWidget) - slot(m_currentEditorWidget); - else if (m_unhandledCallback) - m_unhandledCallback(id, m_currentEditor); - }); - } - - QAction *registerBoolAction(Utils::Id id, - std::function slot, - bool scriptable = false, - const QString &title = QString(), - const QKeySequence &keySequence = QKeySequence(), - Utils::Id menueGroup = Utils::Id(), - ActionContainer *container = nullptr) - { - return registerActionHelper(id, scriptable, title, keySequence, menueGroup, container, - [this, slot](bool on) { if (m_currentEditorWidget) slot(m_currentEditorWidget, on); }); - } - - QAction *registerIntAction(Utils::Id id, - std::function slot, - bool scriptable = false, - const QString &title = QString(), - const QKeySequence &keySequence = QKeySequence(), - Utils::Id menueGroup = Utils::Id(), - ActionContainer *container = nullptr) - { - return registerActionHelper(id, scriptable, title, keySequence, menueGroup, container, - [this, slot](bool on) { if (m_currentEditorWidget) slot(m_currentEditorWidget, on); }); - } - - void createActions(); - - void updateActions(); - void updateOptionalActions(); - void updateRedoAction(bool on); - void updateUndoAction(bool on); - void updateCopyAction(bool on); - - void updateCurrentEditor(IEditor *editor); - - void setCanUndoCallback(const TextEditorActionHandler::Predicate &callback); - void setCanRedoCallback(const TextEditorActionHandler::Predicate &callback); - -public: - TextEditorActionHandler::TextEditorWidgetResolver m_findTextWidget; - QAction *m_undoAction = nullptr; - QAction *m_redoAction = nullptr; - QAction *m_copyAction = nullptr; - QAction *m_copyHtmlAction = nullptr; - QAction *m_cutAction = nullptr; - QAction *m_autoIndentAction = nullptr; - QAction *m_autoFormatAction = nullptr; - QAction *m_visualizeWhitespaceAction = nullptr; - QAction *m_textWrappingAction = nullptr; - QAction *m_unCommentSelectionAction = nullptr; - QAction *m_unfoldAllAction = nullptr; - QAction *m_followSymbolAction = nullptr; - QAction *m_followSymbolInNextSplitAction = nullptr; - QAction *m_followToTypeAction = nullptr; - QAction *m_followToTypeInNextSplitAction = nullptr; - QAction *m_findUsageAction = nullptr; - QAction *m_openCallHierarchyAction = nullptr; - QAction *m_openTypeHierarchyAction = nullptr; - QAction *m_renameSymbolAction = nullptr; - QAction *m_jumpToFileAction = nullptr; - QAction *m_jumpToFileInNextSplitAction = nullptr; - QList m_modifyingActions; - - uint m_optionalActions = TextEditorActionHandler::None; - QPointer m_currentEditorWidget; - QPointer m_currentEditor; - Utils::Id m_editorId; - Utils::Id m_contextId; - - TextEditorActionHandler::Predicate m_canUndoCallback; - TextEditorActionHandler::Predicate m_canRedoCallback; - - TextEditorActionHandler::UnhandledCallback m_unhandledCallback; -}; - -TextEditorActionHandlerPrivate::TextEditorActionHandlerPrivate - (Utils::Id editorId, Utils::Id contextId, uint optionalActions) - : m_optionalActions(optionalActions) - , m_editorId(editorId) - , m_contextId(contextId) -{ - createActions(); - connect(EditorManager::instance(), - &EditorManager::currentEditorChanged, - this, - &TextEditorActionHandlerPrivate::updateCurrentEditor); - connect(TextEditorSettings::instance(), &TextEditorSettings::fontSettingsChanged, - this, &TextEditorActionHandlerPrivate::updateActions); -} - -void TextEditorActionHandlerPrivate::createActions() -{ - using namespace Core::Constants; - using namespace TextEditor::Constants; - - m_undoAction = registerAction(UNDO, - [] (TextEditorWidget *w) { w->undo(); }, true, Tr::tr("&Undo")); - m_redoAction = registerAction(REDO, - [] (TextEditorWidget *w) { w->redo(); }, true, Tr::tr("&Redo")); - m_copyAction = registerAction(COPY, - [] (TextEditorWidget *w) { w->copy(); }, true); - m_cutAction = registerAction(CUT, - [] (TextEditorWidget *w) { w->cut(); }, true); - m_modifyingActions << registerAction(PASTE, - [] (TextEditorWidget *w) { w->paste(); }, true); - registerAction(SELECTALL, - [] (TextEditorWidget *w) { w->selectAll(); }, true); - registerAction(GOTO, [](TextEditorWidget *) { - LocatorManager::showFilter(lineNumberFilter()); - }); - m_modifyingActions << registerAction(PRINT, [](TextEditorWidget *widget) { - widget->print(ICore::printer()); - }); - m_modifyingActions << registerAction(DELETE_LINE, - [] (TextEditorWidget *w) { w->deleteLine(); }, true, Tr::tr("Delete &Line")); - m_modifyingActions << registerAction(DELETE_END_OF_LINE, - [] (TextEditorWidget *w) { w->deleteEndOfLine(); }, true, Tr::tr("Delete Line from Cursor On")); - m_modifyingActions << registerAction(DELETE_END_OF_WORD, - [] (TextEditorWidget *w) { w->deleteEndOfWord(); }, true, Tr::tr("Delete Word from Cursor On")); - m_modifyingActions << registerAction(DELETE_END_OF_WORD_CAMEL_CASE, - [] (TextEditorWidget *w) { w->deleteEndOfWordCamelCase(); }, true, Tr::tr("Delete Word Camel Case from Cursor On")); - m_modifyingActions << registerAction( - DELETE_START_OF_LINE, - [](TextEditorWidget *w) { w->deleteStartOfLine(); }, - true, - Tr::tr("Delete Line up to Cursor"), - Core::useMacShortcuts ? QKeySequence(Tr::tr("Ctrl+Backspace")) : QKeySequence()); - m_modifyingActions << registerAction(DELETE_START_OF_WORD, - [] (TextEditorWidget *w) { w->deleteStartOfWord(); }, true, Tr::tr("Delete Word up to Cursor")); - m_modifyingActions << registerAction(DELETE_START_OF_WORD_CAMEL_CASE, - [] (TextEditorWidget *w) { w->deleteStartOfWordCamelCase(); }, true, Tr::tr("Delete Word Camel Case up to Cursor")); - registerAction(GOTO_BLOCK_START_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoBlockStartWithSelection(); }, true, Tr::tr("Go to Block Start with Selection"), - QKeySequence(Tr::tr("Ctrl+{"))); - registerAction(GOTO_BLOCK_END_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoBlockEndWithSelection(); }, true, Tr::tr("Go to Block End with Selection"), - QKeySequence(Tr::tr("Ctrl+}"))); - m_modifyingActions << registerAction(MOVE_LINE_UP, - [] (TextEditorWidget *w) { w->moveLineUp(); }, true, Tr::tr("Move Line Up"), - QKeySequence(Tr::tr("Ctrl+Shift+Up"))); - m_modifyingActions << registerAction(MOVE_LINE_DOWN, - [] (TextEditorWidget *w) { w->moveLineDown(); }, true, Tr::tr("Move Line Down"), - QKeySequence(Tr::tr("Ctrl+Shift+Down"))); - m_modifyingActions << registerAction(COPY_LINE_UP, - [] (TextEditorWidget *w) { w->copyLineUp(); }, true, Tr::tr("Copy Line Up"), - QKeySequence(Tr::tr("Ctrl+Alt+Up"))); - m_modifyingActions << registerAction(COPY_LINE_DOWN, - [] (TextEditorWidget *w) { w->copyLineDown(); }, true, Tr::tr("Copy Line Down"), - QKeySequence(Tr::tr("Ctrl+Alt+Down"))); - m_modifyingActions << registerAction(JOIN_LINES, - [] (TextEditorWidget *w) { w->joinLines(); }, true, Tr::tr("Join Lines"), - QKeySequence(Tr::tr("Ctrl+J"))); - m_modifyingActions << registerAction(INSERT_LINE_ABOVE, - [] (TextEditorWidget *w) { w->insertLineAbove(); }, true, Tr::tr("Insert Line Above Current Line"), - QKeySequence(Tr::tr("Ctrl+Shift+Return"))); - m_modifyingActions << registerAction(INSERT_LINE_BELOW, - [] (TextEditorWidget *w) { w->insertLineBelow(); }, true, Tr::tr("Insert Line Below Current Line"), - QKeySequence(Tr::tr("Ctrl+Return"))); - m_modifyingActions << registerAction(SWITCH_UTF8BOM, - [] (TextEditorWidget *w) { w->switchUtf8bom(); }, true, Tr::tr("Toggle UTF-8 BOM")); - m_modifyingActions << registerAction(INDENT, - [] (TextEditorWidget *w) { w->indent(); }, true, Tr::tr("Indent")); - m_modifyingActions << registerAction(UNINDENT, - [] (TextEditorWidget *w) { w->unindent(); }, true, Tr::tr("Unindent")); - m_followSymbolAction = registerAction(FOLLOW_SYMBOL_UNDER_CURSOR, - [] (TextEditorWidget *w) { w->openLinkUnderCursor(); }, true, Tr::tr("Follow Symbol Under Cursor"), - QKeySequence(Qt::Key_F2)); - m_followSymbolInNextSplitAction = registerAction(FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT, - [] (TextEditorWidget *w) { w->openLinkUnderCursorInNextSplit(); }, true, Tr::tr("Follow Symbol Under Cursor in Next Split"), - QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+E, F2") : Tr::tr("Ctrl+E, F2"))); - m_followToTypeAction = registerAction(FOLLOW_SYMBOL_TO_TYPE, - [] (TextEditorWidget *w) { w->openTypeUnderCursor(); }, true, Tr::tr("Follow Type Under Cursor"), - QKeySequence(Tr::tr("Ctrl+Shift+F2"))); - m_followToTypeInNextSplitAction = registerAction(FOLLOW_SYMBOL_TO_TYPE_IN_NEXT_SPLIT, - [] (TextEditorWidget *w) { w->openTypeUnderCursorInNextSplit(); }, true, Tr::tr("Follow Type Under Cursor in Next Split"), - QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+E, Shift+F2") : Tr::tr("Ctrl+E, Ctrl+Shift+F2"))); - m_findUsageAction = registerAction(FIND_USAGES, - [] (TextEditorWidget *w) { w->findUsages(); }, true, Tr::tr("Find References to Symbol Under Cursor"), - QKeySequence(Tr::tr("Ctrl+Shift+U"))); - m_renameSymbolAction = registerAction(RENAME_SYMBOL, - [] (TextEditorWidget *w) { w->renameSymbolUnderCursor(); }, true, Tr::tr("Rename Symbol Under Cursor"), - QKeySequence(Tr::tr("Ctrl+Shift+R"))); - m_jumpToFileAction = registerAction(JUMP_TO_FILE_UNDER_CURSOR, - [] (TextEditorWidget *w) { w->openLinkUnderCursor(); }, true, Tr::tr("Jump to File Under Cursor"), - QKeySequence(Qt::Key_F2)); - m_jumpToFileInNextSplitAction = registerAction(JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT, - [] (TextEditorWidget *w) { w->openLinkUnderCursorInNextSplit(); }, true, Tr::tr("Jump to File Under Cursor in Next Split"), - QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+E, F2") : Tr::tr("Ctrl+E, F2")).toString()); - m_openCallHierarchyAction = registerAction(OPEN_CALL_HIERARCHY, - [] (TextEditorWidget *w) { w->openCallHierarchy(); }, true, Tr::tr("Open Call Hierarchy")); - m_openTypeHierarchyAction = registerAction( - OPEN_TYPE_HIERARCHY, - [](TextEditorWidget *) { - updateTypeHierarchy( - NavigationWidget::activateSubWidget(Constants::TYPE_HIERARCHY_FACTORY_ID, - Side::Left)); - }, - true, - Tr::tr("Open Type Hierarchy"), - QKeySequence(Utils::HostOsInfo::isMacHost() ? Tr::tr("Meta+Shift+T") - : Tr::tr("Ctrl+Shift+T"))); - registerAction(VIEW_PAGE_UP, - [] (TextEditorWidget *w) { w->viewPageUp(); }, true, Tr::tr("Move the View a Page Up and Keep the Cursor Position"), - QKeySequence(Tr::tr("Ctrl+PgUp"))); - registerAction(VIEW_PAGE_DOWN, - [] (TextEditorWidget *w) { w->viewPageDown(); }, true, Tr::tr("Move the View a Page Down and Keep the Cursor Position"), - QKeySequence(Tr::tr("Ctrl+PgDown"))); - registerAction(VIEW_LINE_UP, - [] (TextEditorWidget *w) { w->viewLineUp(); }, true, Tr::tr("Move the View a Line Up and Keep the Cursor Position"), - QKeySequence(Tr::tr("Ctrl+Up"))); - registerAction(VIEW_LINE_DOWN, - [] (TextEditorWidget *w) { w->viewLineDown(); }, true, Tr::tr("Move the View a Line Down and Keep the Cursor Position"), - QKeySequence(Tr::tr("Ctrl+Down"))); - - // register "Edit" Menu Actions - ActionContainer *editMenu = ActionManager::actionContainer(M_EDIT); - registerAction(SELECT_ENCODING, - [] (TextEditorWidget *w) { w->selectEncoding(); }, false, Tr::tr("Select Encoding..."), - QKeySequence(), G_EDIT_OTHER, editMenu); - m_modifyingActions << registerAction(CIRCULAR_PASTE, - [] (TextEditorWidget *w) { w->circularPaste(); }, false, Tr::tr("Paste from Clipboard History"), - QKeySequence(Tr::tr("Ctrl+Shift+V")), G_EDIT_COPYPASTE, editMenu); - m_modifyingActions << registerAction(NO_FORMAT_PASTE, - [] (TextEditorWidget *w) { w->pasteWithoutFormat(); }, false, Tr::tr("Paste Without Formatting"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Ctrl+Alt+Shift+V") : QString()), G_EDIT_COPYPASTE, editMenu); - - // register "Edit -> Advanced" Menu Actions - ActionContainer *advancedEditMenu = ActionManager::actionContainer(M_EDIT_ADVANCED); - m_autoIndentAction = registerAction(AUTO_INDENT_SELECTION, - [] (TextEditorWidget *w) { w->autoIndent(); }, true, Tr::tr("Auto-&indent Selection"), - QKeySequence(Tr::tr("Ctrl+I")), - G_EDIT_FORMAT, advancedEditMenu); - m_autoFormatAction = registerAction(AUTO_FORMAT_SELECTION, - [] (TextEditorWidget *w) { w->autoFormat(); }, true, Tr::tr("Auto-&format Selection"), - QKeySequence(Tr::tr("Ctrl+;")), - G_EDIT_FORMAT, advancedEditMenu); - m_modifyingActions << registerAction(REWRAP_PARAGRAPH, - [] (TextEditorWidget *w) { w->rewrapParagraph(); }, true, Tr::tr("&Rewrap Paragraph"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+E, R") : Tr::tr("Ctrl+E, R")), - G_EDIT_FORMAT, advancedEditMenu); - m_visualizeWhitespaceAction = registerBoolAction(VISUALIZE_WHITESPACE, - [] (TextEditorWidget *widget, bool checked) { - if (widget) { - DisplaySettings ds = widget->displaySettings(); - ds.m_visualizeWhitespace = checked; - widget->setDisplaySettings(ds); - } - }, - false, Tr::tr("&Visualize Whitespace"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+E, Meta+V") : Tr::tr("Ctrl+E, Ctrl+V")), - G_EDIT_FORMAT, advancedEditMenu); - m_visualizeWhitespaceAction->setCheckable(true); - m_modifyingActions << registerAction(CLEAN_WHITESPACE, - [] (TextEditorWidget *w) { w->cleanWhitespace(); }, true, Tr::tr("Clean Whitespace"), - QKeySequence(), - G_EDIT_FORMAT, advancedEditMenu); - m_textWrappingAction = registerBoolAction(TEXT_WRAPPING, - [] (TextEditorWidget *widget, bool checked) { - if (widget) { - DisplaySettings ds = widget->displaySettings(); - ds.m_textWrapping = checked; - widget->setDisplaySettings(ds); - } - }, - false, Tr::tr("Enable Text &Wrapping"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+E, Meta+W") : Tr::tr("Ctrl+E, Ctrl+W")), - G_EDIT_FORMAT, advancedEditMenu); - m_textWrappingAction->setCheckable(true); - m_unCommentSelectionAction = registerAction(UN_COMMENT_SELECTION, - [] (TextEditorWidget *w) { w->unCommentSelection(); }, true, Tr::tr("Toggle Comment &Selection"), - QKeySequence(Tr::tr("Ctrl+/")), - G_EDIT_FORMAT, advancedEditMenu); - m_modifyingActions << registerAction(CUT_LINE, - [] (TextEditorWidget *w) { w->cutLine(); }, true, Tr::tr("Cut &Line"), - QKeySequence(Tr::tr("Shift+Del")), - G_EDIT_TEXT, advancedEditMenu); - registerAction(COPY_LINE, - [] (TextEditorWidget *w) { w->copyLine(); }, false, Tr::tr("Copy &Line"), - QKeySequence(Tr::tr("Ctrl+Ins")), - G_EDIT_TEXT, advancedEditMenu); - m_copyHtmlAction = registerAction(COPY_WITH_HTML, - [] (TextEditorWidget *w) { w->copyWithHtml(); }, true, Tr::tr("Copy With Highlighting"), - QKeySequence(), G_EDIT_TEXT, advancedEditMenu); - - registerAction(ADD_CURSORS_TO_LINE_ENDS, - [] (TextEditorWidget *w) { w->addCursorsToLineEnds(); }, false, Tr::tr("Create Cursors at Selected Line Ends"), - QKeySequence(Tr::tr("Alt+Shift+I")), - G_EDIT_TEXT, advancedEditMenu); - registerAction(ADD_SELECT_NEXT_FIND_MATCH, - [] (TextEditorWidget *w) { w->addSelectionNextFindMatch(); }, false, Tr::tr("Add Next Occurrence to Selection"), - QKeySequence(Tr::tr("Ctrl+D")), - G_EDIT_TEXT, advancedEditMenu); - m_modifyingActions << registerAction(DUPLICATE_SELECTION, - [] (TextEditorWidget *w) { w->duplicateSelection(); }, false, Tr::tr("&Duplicate Selection"), - QKeySequence(), - G_EDIT_TEXT, advancedEditMenu); - m_modifyingActions << registerAction(DUPLICATE_SELECTION_AND_COMMENT, - [] (TextEditorWidget *w) { w->duplicateSelectionAndComment(); }, false, Tr::tr("&Duplicate Selection and Comment"), - QKeySequence(), - G_EDIT_TEXT, advancedEditMenu); - m_modifyingActions << registerAction(UPPERCASE_SELECTION, - [] (TextEditorWidget *w) { w->uppercaseSelection(); }, true, Tr::tr("Uppercase Selection"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+Shift+U") : Tr::tr("Alt+Shift+U")), - G_EDIT_TEXT, advancedEditMenu); - m_modifyingActions << registerAction(LOWERCASE_SELECTION, - [] (TextEditorWidget *w) { w->lowercaseSelection(); }, true, Tr::tr("Lowercase Selection"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+U") : Tr::tr("Alt+U")), - G_EDIT_TEXT, advancedEditMenu); - m_modifyingActions << registerAction(SORT_LINES, - [] (TextEditorWidget *w) { w->sortLines(); }, false, Tr::tr("&Sort Lines"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+Shift+S") : Tr::tr("Alt+Shift+S")), - G_EDIT_TEXT, advancedEditMenu); - registerAction(FOLD, - [] (TextEditorWidget *w) { w->foldCurrentBlock(); }, true, Tr::tr("Fold"), - QKeySequence(Tr::tr("Ctrl+<")), - G_EDIT_COLLAPSING, advancedEditMenu); - registerAction(UNFOLD, - [] (TextEditorWidget *w) { w->unfoldCurrentBlock(); }, true, Tr::tr("Unfold"), - QKeySequence(Tr::tr("Ctrl+>")), - G_EDIT_COLLAPSING, advancedEditMenu); - m_unfoldAllAction = registerAction(UNFOLD_ALL, - [] (TextEditorWidget *w) { w->unfoldAll(); }, true, Tr::tr("Toggle &Fold All"), - QKeySequence(), - G_EDIT_COLLAPSING, advancedEditMenu); - registerAction(INCREASE_FONT_SIZE, - [] (TextEditorWidget *w) { w->increaseFontZoom(); }, false, Tr::tr("Increase Font Size"), - QKeySequence(Tr::tr("Ctrl++")), - G_EDIT_FONT, advancedEditMenu); - registerAction(DECREASE_FONT_SIZE, - [] (TextEditorWidget *w) { w->decreaseFontZoom(); }, false, Tr::tr("Decrease Font Size"), - QKeySequence(Tr::tr("Ctrl+-")), - G_EDIT_FONT, advancedEditMenu); - registerAction(RESET_FONT_SIZE, - [] (TextEditorWidget *w) { w->zoomReset(); }, false, Tr::tr("Reset Font Size"), - QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+0") : Tr::tr("Ctrl+0")), - G_EDIT_FONT, advancedEditMenu); - registerAction(GOTO_BLOCK_START, - [] (TextEditorWidget *w) { w->gotoBlockStart(); }, true, Tr::tr("Go to Block Start"), - QKeySequence(Tr::tr("Ctrl+[")), - G_EDIT_BLOCKS, advancedEditMenu); - registerAction(GOTO_BLOCK_END, - [] (TextEditorWidget *w) { w->gotoBlockEnd(); }, true, Tr::tr("Go to Block End"), - QKeySequence(Tr::tr("Ctrl+]")), - G_EDIT_BLOCKS, advancedEditMenu); - registerAction(SELECT_BLOCK_UP, - [] (TextEditorWidget *w) { w->selectBlockUp(); }, true, Tr::tr("Select Block Up"), - QKeySequence(Tr::tr("Ctrl+U")), - G_EDIT_BLOCKS, advancedEditMenu); - registerAction(SELECT_BLOCK_DOWN, - [] (TextEditorWidget *w) { w->selectBlockDown(); }, true, Tr::tr("Select Block Down"), - QKeySequence(Tr::tr("Ctrl+Shift+Alt+U")), - G_EDIT_BLOCKS, advancedEditMenu); - registerAction(SELECT_WORD_UNDER_CURSOR, - [] (TextEditorWidget *w) { w->selectWordUnderCursor(); }, true, - Tr::tr("Select Word Under Cursor")); - - // register GOTO Actions - registerAction(GOTO_DOCUMENT_START, - [] (TextEditorWidget *w) { w->gotoDocumentStart(); }, true, Tr::tr("Go to Document Start")); - registerAction(GOTO_DOCUMENT_END, - [] (TextEditorWidget *w) { w->gotoDocumentEnd(); }, true, Tr::tr("Go to Document End")); - registerAction(GOTO_LINE_START, - [] (TextEditorWidget *w) { w->gotoLineStart(); }, true, Tr::tr("Go to Line Start")); - registerAction(GOTO_LINE_END, - [] (TextEditorWidget *w) { w->gotoLineEnd(); }, true, Tr::tr("Go to Line End")); - registerAction(GOTO_NEXT_LINE, - [] (TextEditorWidget *w) { w->gotoNextLine(); }, true, Tr::tr("Go to Next Line")); - registerAction(GOTO_PREVIOUS_LINE, - [] (TextEditorWidget *w) { w->gotoPreviousLine(); }, true, Tr::tr("Go to Previous Line")); - registerAction(GOTO_PREVIOUS_CHARACTER, - [] (TextEditorWidget *w) { w->gotoPreviousCharacter(); }, true, Tr::tr("Go to Previous Character")); - registerAction(GOTO_NEXT_CHARACTER, - [] (TextEditorWidget *w) { w->gotoNextCharacter(); }, true, Tr::tr("Go to Next Character")); - registerAction(GOTO_PREVIOUS_WORD, - [] (TextEditorWidget *w) { w->gotoPreviousWord(); }, true, Tr::tr("Go to Previous Word")); - registerAction(GOTO_NEXT_WORD, - [] (TextEditorWidget *w) { w->gotoNextWord(); }, true, Tr::tr("Go to Next Word")); - registerAction(GOTO_PREVIOUS_WORD_CAMEL_CASE, - [] (TextEditorWidget *w) { w->gotoPreviousWordCamelCase(); }, false, Tr::tr("Go to Previous Word Camel Case")); - registerAction(GOTO_NEXT_WORD_CAMEL_CASE, - [] (TextEditorWidget *w) { w->gotoNextWordCamelCase(); }, false, Tr::tr("Go to Next Word Camel Case")); - - // register GOTO actions with selection - registerAction(GOTO_LINE_START_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoLineStartWithSelection(); }, true, Tr::tr("Go to Line Start with Selection")); - registerAction(GOTO_LINE_END_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoLineEndWithSelection(); }, true, Tr::tr("Go to Line End with Selection")); - registerAction(GOTO_NEXT_LINE_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoNextLineWithSelection(); }, true, Tr::tr("Go to Next Line with Selection")); - registerAction(GOTO_PREVIOUS_LINE_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoPreviousLineWithSelection(); }, true, Tr::tr("Go to Previous Line with Selection")); - registerAction(GOTO_PREVIOUS_CHARACTER_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoPreviousCharacterWithSelection(); }, true, Tr::tr("Go to Previous Character with Selection")); - registerAction(GOTO_NEXT_CHARACTER_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoNextCharacterWithSelection(); }, true, Tr::tr("Go to Next Character with Selection")); - registerAction(GOTO_PREVIOUS_WORD_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoPreviousWordWithSelection(); }, true, Tr::tr("Go to Previous Word with Selection")); - registerAction(GOTO_NEXT_WORD_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoNextWordWithSelection(); }, true, Tr::tr("Go to Next Word with Selection")); - registerAction(GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoPreviousWordCamelCaseWithSelection(); }, false, Tr::tr("Go to Previous Word Camel Case with Selection")); - registerAction(GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION, - [] (TextEditorWidget *w) { w->gotoNextWordCamelCaseWithSelection(); }, false, Tr::tr("Go to Next Word Camel Case with Selection")); - - // Collect additional modifying actions so we can check for them inside a readonly file - // and disable them - m_modifyingActions << m_autoIndentAction; - m_modifyingActions << m_autoFormatAction; - m_modifyingActions << m_unCommentSelectionAction; - - updateOptionalActions(); -} - -void TextEditorActionHandlerPrivate::updateActions() -{ - bool isWritable = m_currentEditorWidget && !m_currentEditorWidget->isReadOnly(); - for (QAction *a : std::as_const(m_modifyingActions)) - a->setEnabled(isWritable); - m_unCommentSelectionAction->setEnabled((m_optionalActions & TextEditorActionHandler::UnCommentSelection) && isWritable); - m_visualizeWhitespaceAction->setEnabled(m_currentEditorWidget); - if (TextEditorSettings::fontSettings().relativeLineSpacing() == 100) { - m_textWrappingAction->setEnabled(m_currentEditorWidget); - } else { - m_textWrappingAction->setEnabled(false); - m_textWrappingAction->setChecked(false); - } - if (m_currentEditorWidget) { - m_visualizeWhitespaceAction->setChecked( - m_currentEditorWidget->displaySettings().m_visualizeWhitespace); - m_textWrappingAction->setChecked(m_currentEditorWidget->displaySettings().m_textWrapping); - } - - bool canRedo = false; - bool canUndo = false; - bool canCopy = false; - - if (m_currentEditor && m_currentEditor->document() - && m_currentEditor->document()->id() == m_editorId) { - canRedo = m_canRedoCallback ? m_canRedoCallback(m_currentEditor) : false; - canUndo = m_canUndoCallback ? m_canUndoCallback(m_currentEditor) : false; - - if (m_currentEditorWidget) { - canRedo = m_canRedoCallback ? canRedo - : m_currentEditorWidget->document()->isRedoAvailable(); - canUndo = m_canUndoCallback ? canUndo - : m_currentEditorWidget->document()->isUndoAvailable(); - canCopy = m_currentEditorWidget->textCursor().hasSelection(); - } - } - - updateRedoAction(canRedo); - updateUndoAction(canUndo); - updateCopyAction(canCopy); - - updateOptionalActions(); -} - -void TextEditorActionHandlerPrivate::updateOptionalActions() -{ - const uint optionalActions = m_currentEditorWidget ? m_currentEditorWidget->optionalActions() - : m_optionalActions; - m_followSymbolAction->setEnabled( - optionalActions & TextEditorActionHandler::FollowSymbolUnderCursor); - m_followSymbolInNextSplitAction->setEnabled( - optionalActions & TextEditorActionHandler::FollowSymbolUnderCursor); - m_followToTypeAction->setEnabled( - optionalActions & TextEditorActionHandler::FollowTypeUnderCursor); - m_followToTypeInNextSplitAction->setEnabled( - optionalActions & TextEditorActionHandler::FollowTypeUnderCursor); - m_findUsageAction->setEnabled( - optionalActions & TextEditorActionHandler::FindUsage); - m_jumpToFileAction->setEnabled( - optionalActions & TextEditorActionHandler::JumpToFileUnderCursor); - m_jumpToFileInNextSplitAction->setEnabled( - optionalActions & TextEditorActionHandler::JumpToFileUnderCursor); - m_unfoldAllAction->setEnabled( - optionalActions & TextEditorActionHandler::UnCollapseAll); - m_renameSymbolAction->setEnabled( - optionalActions & TextEditorActionHandler::RenameSymbol); - m_openCallHierarchyAction->setEnabled( - optionalActions & TextEditorActionHandler::CallHierarchy); - m_openTypeHierarchyAction->setEnabled( - optionalActions & TextEditorActionHandler::TypeHierarchy); - - bool formatEnabled = (optionalActions & TextEditorActionHandler::Format) - && m_currentEditorWidget && !m_currentEditorWidget->isReadOnly(); - m_autoIndentAction->setEnabled(formatEnabled); - m_autoFormatAction->setEnabled(formatEnabled); -} - -void TextEditorActionHandlerPrivate::updateRedoAction(bool on) -{ - m_redoAction->setEnabled(on); -} - -void TextEditorActionHandlerPrivate::updateUndoAction(bool on) -{ - m_undoAction->setEnabled(on); -} - -void TextEditorActionHandlerPrivate::updateCopyAction(bool hasCopyableText) -{ - if (m_cutAction) - m_cutAction->setEnabled(hasCopyableText && m_currentEditorWidget - && !m_currentEditorWidget->isReadOnly()); - if (m_copyAction) - m_copyAction->setEnabled(hasCopyableText); - if (m_copyHtmlAction) - m_copyHtmlAction->setEnabled(hasCopyableText); -} - -void TextEditorActionHandlerPrivate::updateCurrentEditor(IEditor *editor) -{ - if (m_currentEditorWidget) - m_currentEditorWidget->disconnect(this); - m_currentEditorWidget = nullptr; - - m_currentEditor = editor; - - if (editor && editor->document()->id() == m_editorId) { - m_currentEditorWidget = m_findTextWidget(editor); - if (m_currentEditorWidget) { - connect(m_currentEditorWidget, &QPlainTextEdit::undoAvailable, - this, &TextEditorActionHandlerPrivate::updateUndoAction); - connect(m_currentEditorWidget, &QPlainTextEdit::redoAvailable, - this, &TextEditorActionHandlerPrivate::updateRedoAction); - connect(m_currentEditorWidget, &QPlainTextEdit::copyAvailable, - this, &TextEditorActionHandlerPrivate::updateCopyAction); - connect(m_currentEditorWidget, &TextEditorWidget::readOnlyChanged, - this, &TextEditorActionHandlerPrivate::updateActions); - connect(m_currentEditorWidget, &TextEditorWidget::optionalActionMaskChanged, - this, &TextEditorActionHandlerPrivate::updateOptionalActions); - } - } - updateActions(); -} - -} // namespace Internal - -TextEditorActionHandler::TextEditorActionHandler(Utils::Id editorId, - Utils::Id contextId, - uint optionalActions, - const TextEditorWidgetResolver &resolver) - : d(new Internal::TextEditorActionHandlerPrivate(editorId, contextId, optionalActions)) -{ - if (resolver) - d->m_findTextWidget = resolver; - else - d->m_findTextWidget = TextEditorWidget::fromEditor; -} - -uint TextEditorActionHandler::optionalActions() const -{ - return d->m_optionalActions; -} - -TextEditorActionHandler::~TextEditorActionHandler() -{ - delete d; -} - -void TextEditorActionHandler::updateCurrentEditor() -{ - d->updateCurrentEditor(EditorManager::currentEditor()); -} - -void TextEditorActionHandler::updateActions() -{ - d->updateActions(); -} - -void TextEditorActionHandler::setCanUndoCallback(const Predicate &callback) -{ - d->m_canUndoCallback = callback; -} - -void TextEditorActionHandler::setCanRedoCallback(const Predicate &callback) -{ - d->m_canRedoCallback = callback; -} - -void TextEditorActionHandler::setUnhandledCallback(const UnhandledCallback &callback) -{ - d->m_unhandledCallback = callback; -} - -} // namespace TextEditor diff --git a/src/plugins/texteditor/texteditoractionhandler.h b/src/plugins/texteditor/texteditoractionhandler.h deleted file mode 100644 index ce969b7b6f1..00000000000 --- a/src/plugins/texteditor/texteditoractionhandler.h +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "texteditor_global.h" - -#include - -#include - -#include - -namespace Core { -class IEditor; -} - -namespace TextEditor { -class TextEditorWidget; - -namespace Internal { class TextEditorActionHandlerPrivate; } - -// Redirects slots from global actions to the respective editor. - -class TEXTEDITOR_EXPORT TextEditorActionHandler final -{ - TextEditorActionHandler(const TextEditorActionHandler &) = delete; - TextEditorActionHandler &operator=(const TextEditorActionHandler &) = delete; - -public: - enum OptionalActionsMask { - None = 0, - Format = 1, - UnCommentSelection = 2, - UnCollapseAll = 4, - FollowSymbolUnderCursor = 8, - FollowTypeUnderCursor = 16, - JumpToFileUnderCursor = 32, - RenameSymbol = 64, - FindUsage = 128, - CallHierarchy = 256, - TypeHierarchy = 512, - }; - using TextEditorWidgetResolver = std::function; - - TextEditorActionHandler(Utils::Id editorId, - Utils::Id contextId, - uint optionalActions = None, - const TextEditorWidgetResolver &resolver = {}); - - uint optionalActions() const; - ~TextEditorActionHandler(); - - void updateCurrentEditor(); - void updateActions(); - - using Predicate = std::function; - - void setCanUndoCallback(const Predicate &callback); - void setCanRedoCallback(const Predicate &callback); - - using UnhandledCallback = std::function; - void setUnhandledCallback(const UnhandledCallback &callback); - -private: - Internal::TextEditorActionHandlerPrivate *d; -}; - -} // namespace TextEditor diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index d279b6254f4..0852da2ca82 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -85,6 +85,7 @@ public: void updateCurrentSelection(const QString &text); void createStandardContextMenu(); + void createEditorCommands(); }; void TextEditorPlugin::initialize() @@ -174,6 +175,7 @@ void TextEditorPlugin::initialize() Tr::tr("Text", "SnippetProvider")); createStandardContextMenu(); + createEditorCommands(); #ifdef WITH_TESTS addTestCreator(createCodeAssistTests); @@ -349,6 +351,359 @@ void TextEditorPlugin::createStandardContextMenu() add(Constants::SWITCH_UTF8BOM, Constants::G_BOM); } +void TextEditorPlugin::createEditorCommands() +{ + using namespace Core::Constants; + ActionBuilder(this, UNDO).setText(Tr::tr("&Undo")).setScriptable(true); + ActionBuilder(this, REDO).setText(Tr::tr("&Redo")).setScriptable(true); + ActionBuilder(this, COPY).setScriptable(true); + ActionBuilder(this, CUT).setScriptable(true); + ActionBuilder(this, PASTE).setScriptable(true); + ActionBuilder(this, SELECTALL).setScriptable(true); + ActionBuilder(this, GOTO); + ActionBuilder(this, PRINT); + ActionBuilder(this, DELETE_LINE).setText(Tr::tr("Delete &Line")).setScriptable(true); + ActionBuilder(this, DELETE_END_OF_LINE) + .setText(Tr::tr("Delete Line from Cursor On")) + .setScriptable(true); + ActionBuilder(this, DELETE_END_OF_WORD) + .setText(Tr::tr("Delete Word from Cursor On")) + .setScriptable(true); + ActionBuilder(this, DELETE_END_OF_WORD_CAMEL_CASE) + .setText(Tr::tr("Delete Word Camel Case from Cursor On")) + .setScriptable(true); + ActionBuilder(this, DELETE_START_OF_LINE) + .setText(Tr::tr("Delete Line up to Cursor")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Ctrl+Backspace"), {}); + ActionBuilder(this, DELETE_START_OF_WORD) + .setText(Tr::tr("Delete Word up to Cursor")) + .setScriptable(true); + ActionBuilder(this, DELETE_START_OF_WORD_CAMEL_CASE) + .setText(Tr::tr("Delete Word Camel Case up to Cursor")) + .setScriptable(true); + ActionBuilder(this, GOTO_BLOCK_START_WITH_SELECTION) + .setText(Tr::tr("Go to Block Start with Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+{"))); + ActionBuilder(this, GOTO_BLOCK_END_WITH_SELECTION) + .setText(Tr::tr("Go to Block End with Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+}"))); + ActionBuilder(this, MOVE_LINE_UP) + .setText(Tr::tr("Move Line Up")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Up"))); + ActionBuilder(this, MOVE_LINE_DOWN) + .setText(Tr::tr("Move Line Down")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Down"))); + ActionBuilder(this, COPY_LINE_UP) + .setText(Tr::tr("Copy Line Up")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Up"))); + ActionBuilder(this, COPY_LINE_DOWN) + .setText(Tr::tr("Copy Line Down")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Down"))); + ActionBuilder(this, JOIN_LINES) + .setText(Tr::tr("Join Lines")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+J"))); + ActionBuilder(this, INSERT_LINE_ABOVE) + .setText(Tr::tr("Insert Line Above Current Line")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Return"))); + ActionBuilder(this, INSERT_LINE_BELOW) + .setText(Tr::tr("Insert Line Below Current Line")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Return"))); + ActionBuilder(this, SWITCH_UTF8BOM) + .setText(Tr::tr("Delete Word up to Cursor")) + .setScriptable(true); + ActionBuilder(this, INDENT) + .setText(Tr::tr("Indent")) + .setScriptable(true); + ActionBuilder(this, UNINDENT) + .setText(Tr::tr("Unindent")) + .setScriptable(true); + ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR) + .setText(Tr::tr("Follow Symbol Under Cursor")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Qt::Key_F2)); + ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT) + .setText(Tr::tr("Follow Symbol Under Cursor in Next Split")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+E, F2"), Tr::tr("Ctrl+E, F2")); + ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE) + .setText(Tr::tr("Follow Type Under Cursor")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+F2"))); + ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE_IN_NEXT_SPLIT) + .setText(Tr::tr("Follow Type Under Cursor in Next Split")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+E, Shift+F2"), Tr::tr("Ctrl+E, Ctrl+Shift+F2")); + ActionBuilder(this, FIND_USAGES) + .setText(Tr::tr("Find References to Symbol Under Cursor")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+U"))); + ActionBuilder(this, RENAME_SYMBOL) + .setText(Tr::tr("Rename Symbol Under Cursor")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+R"))); + ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR) + .setText(Tr::tr("Jump to File Under Cursor")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Qt::Key_F2)); + ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT) + .setText(Tr::tr("Jump to File Under Cursor in Next Split")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+E, F2"), Tr::tr("Ctrl+E, F2")); + ActionBuilder(this, OPEN_CALL_HIERARCHY) + .setText(Tr::tr("Open Call Hierarchy")) + .setScriptable(true); + ActionBuilder(this, OPEN_TYPE_HIERARCHY) + .setText(Tr::tr("Open Type Hierarchy")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+Shift+T"), Tr::tr("Ctrl+Shift+T")); + ActionBuilder(this, VIEW_PAGE_UP) + .setText(Tr::tr("Move the View a Page Up and Keep the Cursor Position")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+PgUp"))); + ActionBuilder(this, VIEW_PAGE_DOWN) + .setText(Tr::tr("Move the View a Page Down and Keep the Cursor Position")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+PgDown"))); + ActionBuilder(this, VIEW_LINE_UP) + .setText(Tr::tr("Move the View a Line Up and Keep the Cursor Position")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Up"))); + ActionBuilder(this, VIEW_LINE_DOWN) + .setText(Tr::tr("Move the View a Line Down and Keep the Cursor Position")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Down"))); + + ActionManager::actionContainer(M_EDIT); + ActionBuilder(this, SELECT_ENCODING) + .setText(Tr::tr("Select Encoding...")) + .setScriptable(false) + .addToContainer(M_EDIT, G_EDIT_OTHER); + ActionBuilder(this, CIRCULAR_PASTE) + .setText(Tr::tr("Paste from Clipboard History")) + .setScriptable(false) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+V"))) + .addToContainer(M_EDIT, G_EDIT_COPYPASTE); + ActionBuilder(this, NO_FORMAT_PASTE) + .setText(Tr::tr("Paste Without Formatting")) + .setScriptable(false) + .setDefaultKeySequence(Tr::tr("Ctrl+Alt+Shift+V"), QString()) + .addToContainer(M_EDIT, G_EDIT_COPYPASTE); + + ActionManager::actionContainer(M_EDIT_ADVANCED); + ActionBuilder(this, AUTO_INDENT_SELECTION) + .setText(Tr::tr("Auto-&indent Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+I"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, AUTO_FORMAT_SELECTION) + .setText(Tr::tr("Auto-&format Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+;"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, REWRAP_PARAGRAPH) + .setText(Tr::tr("&Rewrap Paragraph")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+E, R"), Tr::tr("Ctrl+E, R")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, VISUALIZE_WHITESPACE) + .setText(Tr::tr("&Visualize Whitespace")) + .setScriptable(false) + .setDefaultKeySequence(Tr::tr("Meta+E, Meta+V"), Tr::tr("Ctrl+E, Ctrl+V")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, CLEAN_WHITESPACE) + .setText(Tr::tr("Clean Whitespace")) + .setScriptable(true) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, TEXT_WRAPPING) + .setText(Tr::tr("Enable Text &Wrapping")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+E, Meta+W"), Tr::tr("Ctrl+E, Ctrl+W")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT) + .setCheckable(true); + ActionBuilder(this, UN_COMMENT_SELECTION) + .setText(Tr::tr("Toggle Comment &Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+/"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); + ActionBuilder(this, CUT_LINE) + .setText(Tr::tr("Cut &Line")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Shift+Del"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, COPY_LINE) + .setText(Tr::tr("Copy &Line")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Ins"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, COPY_WITH_HTML) + .setText(Tr::tr("Copy With Highlighting")) + .setScriptable(true) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, ADD_CURSORS_TO_LINE_ENDS) + .setText(Tr::tr("Create Cursors at Selected Line Ends")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Alt+Shift+I"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, ADD_SELECT_NEXT_FIND_MATCH) + .setText(Tr::tr("Add Next Occurrence to Selection")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+D"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, DUPLICATE_SELECTION) + .setText(Tr::tr("&Duplicate Selection")) + .setScriptable(true) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, DUPLICATE_SELECTION_AND_COMMENT) + .setText(Tr::tr("&Duplicate Selection and Comment")) + .setScriptable(true) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, UPPERCASE_SELECTION) + .setText(Tr::tr("Uppercase Selection")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+Shift+U"), Tr::tr("Alt+Shift+U")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, LOWERCASE_SELECTION) + .setText(Tr::tr("Lowercase Selection")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+U"), Tr::tr("Alt+U")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, SORT_LINES) + .setText(Tr::tr("Sort Lines")) + .setScriptable(true) + .setDefaultKeySequence(Tr::tr("Meta+Shift+S"), Tr::tr("Alt+Shift+S")) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); + ActionBuilder(this, FOLD) + .setText(Tr::tr("Fold")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+<"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); + ActionBuilder(this, UNFOLD) + .setText(Tr::tr("Unfold")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+>"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); + ActionBuilder(this, UNFOLD_ALL) + .setText(Tr::tr("Toggle &Fold All")) + .setScriptable(true) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); + ActionBuilder(this, INCREASE_FONT_SIZE) + .setText(Tr::tr("Increase Font Size")) + .setScriptable(false) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl++"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); + ActionBuilder(this, DECREASE_FONT_SIZE) + .setText(Tr::tr("Decrease Font Size")) + .setScriptable(false) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+-"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); + ActionBuilder(this, RESET_FONT_SIZE) + .setText(Tr::tr("Reset Font Size")) + .setScriptable(false) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+0"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); + ActionBuilder(this, GOTO_BLOCK_START) + .setText(Tr::tr("Go to Block Start")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+["))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); + ActionBuilder(this, GOTO_BLOCK_END) + .setText(Tr::tr("Go to Block End")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+]"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); + ActionBuilder(this, SELECT_BLOCK_UP) + .setText(Tr::tr("Select Block Up")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+U"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); + ActionBuilder(this, SELECT_BLOCK_DOWN) + .setText(Tr::tr("Select Block Down")) + .setScriptable(true) + .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Alt+U"))) + .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); + ActionBuilder(this, SELECT_WORD_UNDER_CURSOR) + .setText(Tr::tr("Select Word Under Cursor")) + .setScriptable(true); + + ActionBuilder(this, GOTO_DOCUMENT_START) + .setText(Tr::tr("Go to Document Start")) + .setScriptable(true); + ActionBuilder(this, GOTO_DOCUMENT_END) + .setText(Tr::tr("Go to Document End")) + .setScriptable(true); + ActionBuilder(this, GOTO_LINE_START) + .setText(Tr::tr("Go to Line Start")) + .setScriptable(true); + ActionBuilder(this, GOTO_LINE_END) + .setText(Tr::tr("Go to Line End")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_LINE) + .setText(Tr::tr("Go to Next Line")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_LINE) + .setText(Tr::tr("Go to Previous Line")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_CHARACTER) + .setText(Tr::tr("Go to Previous Character")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_CHARACTER) + .setText(Tr::tr("Go to Next Character")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_WORD) + .setText(Tr::tr("Go to Previous Word")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_WORD) + .setText(Tr::tr("Go to Next Word")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE) + .setText(Tr::tr("Go to Previous Word (Camel Case)")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE) + .setText(Tr::tr("Go to Next Word (Camel Case)")) + .setScriptable(true); + + ActionBuilder(this, GOTO_LINE_START_WITH_SELECTION) + .setText(Tr::tr("Go to Line Start with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_LINE_END_WITH_SELECTION) + .setText(Tr::tr("Go to Line End with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_LINE_WITH_SELECTION) + .setText(Tr::tr("Go to Next Line with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_LINE_WITH_SELECTION) + .setText(Tr::tr("Go to Previous Line with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_CHARACTER_WITH_SELECTION) + .setText(Tr::tr("Go to Previous Character with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_CHARACTER_WITH_SELECTION) + .setText(Tr::tr("Go to Next Character with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_WORD_WITH_SELECTION) + .setText(Tr::tr("Go to Previous Word with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_WORD_WITH_SELECTION) + .setText(Tr::tr("Go to Next Word with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION) + .setText(Tr::tr("Go to Previous Word (Camel Case) with Selection")) + .setScriptable(true); + ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION) + .setText(Tr::tr("Go to Next Word (Camel Case) with Selection")) + .setScriptable(true); +} + } // namespace TextEditor::Internal #include "texteditorplugin.moc" diff --git a/src/plugins/vcsbase/vcsbaseeditor.cpp b/src/plugins/vcsbase/vcsbaseeditor.cpp index 13338584bf1..462412df06d 100644 --- a/src/plugins/vcsbase/vcsbaseeditor.cpp +++ b/src/plugins/vcsbase/vcsbaseeditor.cpp @@ -27,7 +27,6 @@ #include #include -#include #include #include #include @@ -1661,7 +1660,7 @@ VcsEditorFactory::VcsEditorFactory(const VcsBaseEditorParameters ¶meters) if (parameters.mimeType != DiffEditor::Constants::DIFF_EDITOR_MIMETYPE) addMimeType(parameters.mimeType); - setEditorActionHandlers(TextEditorActionHandler::None); + setOptionalActionMask(OptionalActions::None); setDuplicatedSupported(false); setDocumentCreator([parameters] { From cde3cfea4dab2368276b6e70269e5d1a81767e33 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Tue, 9 Apr 2024 13:45:57 +0200 Subject: [PATCH 0124/1060] ClangTools: Fix clang-tidy doc URL for versions >= 18 See https://github.com/llvm/llvm-project/commit/ 4532617ae420056bf32f6403dde07fb99d276a49. Fixes: QTCREATORBUG-30658 Change-Id: I4e171c52959d576ed752691d601ceb99691b207d Reviewed-by: Reviewed-by: Cristian Adam --- src/plugins/clangtools/clangtoolsutils.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/plugins/clangtools/clangtoolsutils.cpp b/src/plugins/clangtools/clangtoolsutils.cpp index 6a650e9c551..746e32754d6 100644 --- a/src/plugins/clangtools/clangtoolsutils.cpp +++ b/src/plugins/clangtools/clangtoolsutils.cpp @@ -310,7 +310,10 @@ QStringList extraClangToolsAppendOptions() static QVersionNumber fixupVersion(const VersionAndSuffix &versionAndSuffix) { // llvm.org only does document releases for the first released version - QVersionNumber version = QVersionNumber(versionAndSuffix.first.majorVersion(), 0, 0); + // Since LLVM 18, the releases start at minor version 1. + const int major = versionAndSuffix.first.majorVersion(); + const int minor = major >= 18 ? 1 : 0; + QVersionNumber version = QVersionNumber(major, minor, 0); if (version == QVersionNumber(0)) version = QVersionNumber(12); From fc3047fb1b021d9139c9502f363f877a394b0f53 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Tue, 9 Apr 2024 13:43:22 +0200 Subject: [PATCH 0125/1060] Ios: Fix qbs build Amends e8d6e4fc3412bd4bd3c4ae30421240eadbbb24c2. Change-Id: I67185c856a28071c2428ac593f54d31f99c3411d Reviewed-by: Eike Ziller --- src/plugins/ios/ios.qbs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/plugins/ios/ios.qbs b/src/plugins/ios/ios.qbs index fa81e1facd7..f07418443de 100644 --- a/src/plugins/ios/ios.qbs +++ b/src/plugins/ios/ios.qbs @@ -15,8 +15,6 @@ QtcPlugin { cpp.frameworks: base.concat(qbs.targetOS.contains("macos") ? ["CoreFoundation", "IOKit"] : []) files: [ - "createsimulatordialog.cpp", - "createsimulatordialog.h", "devicectlutils.cpp", "devicectlutils.h", "ios.qrc", @@ -51,9 +49,5 @@ QtcPlugin { "iostr.h", "simulatorcontrol.cpp", "simulatorcontrol.h", - "simulatorinfomodel.cpp", - "simulatorinfomodel.h", - "simulatoroperationdialog.cpp", - "simulatoroperationdialog.h", ] } From e43c8c178d2195361a7a41f861bbd0214424b67b Mon Sep 17 00:00:00 2001 From: Leena Miettinen Date: Thu, 28 Mar 2024 15:37:35 +0100 Subject: [PATCH 0126/1060] Doc: Split up "Using Squish" into how-to and reference topics - Move general information to "Developing with Qt Creator" Task-number: QTCREATORBUG-29361 Change-Id: Ia630346c6fc4e158215e1af77f4579f2a513a937 Reviewed-by: Christian Stenger --- doc/qtcreator/config/style/qt5-sidebar.html | 1 - .../howto/creator-only/creator-squish.qdoc | 295 ++++++++++-------- .../creator-only/creator-overview.qdoc | 28 +- .../creator-projects-creating.qdoc | 2 +- doc/qtcreator/src/qtcreator-toc.qdoc | 1 - doc/qtcreator/src/qtcreator.qdoc | 1 - 6 files changed, 183 insertions(+), 145 deletions(-) diff --git a/doc/qtcreator/config/style/qt5-sidebar.html b/doc/qtcreator/config/style/qt5-sidebar.html index 327bd27a293..6278363d3e1 100644 --- a/doc/qtcreator/config/style/qt5-sidebar.html +++ b/doc/qtcreator/config/style/qt5-sidebar.html @@ -18,7 +18,6 @@

  • Deploying to Devices
  • Debugging
  • Analyzing Code
  • -
  • Using Squish
  • diff --git a/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc b/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc index 4284085e721..9aaf0506f22 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc @@ -2,82 +2,66 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-autotest.html - \page creator-squish.html - \nextpage creator-advanced.html + \page creator-how-to-connect-squish-server.html + \previouspage creator-how-tos.html - \title Using Squish + \ingroup creator-how-to-test - \l{https://www.qt.io/product/quality-assurance/squish}{Squish} is an automated GUI - testing framework for testing Android, iOS, Java, \macos, Qt, Tk, Windows, and - XView applications, as well as HTML-based web applications running in - browsers, such as Apple Safari, Mozilla Firefox, Google Chrome, and - Microsoft Internet Explorer and Edge. + \title Connect to Squish Server - The experimental Squish plugin integrates Squish into \QC. You can: - - \list - \li Open existing Squish test suites. - \li Create new test suites and test cases. - \li Record test cases (in a very limited way compared to what you can do - inside the Squish IDE). - \li Use Squish Runner and Server to run test suites or cases and view - the results in the \uicontrol Squish \l{View output}{output}. - \li Set breakpoints before running tests to stop at certain locations and - inspect the local variables, similarly to when debugging a test. - \endlist - - When running test suites or cases, the Squish Runner instructs the Squish - Server to start the application under test (AUT). The server can be running - on multiple machines, and the AUT can be located on a different path on each - of them. Therefore, you must either map AUTs to their corresponding paths or - specify AUT paths to search from in the server settings. - - In addition, you can test an already running application by attaching to it. - This enables you to test your application using a Squish Server running on - another machine. However, you can have only one server attached to your - application at a time. Also, the attached application is not closed when the - test case is completed. - - To use the plugin, you must download and install Squish, create a connection - to the Squish Server, and specify AUTs to run. - - \note Enable the Squish plugin to use it. - - \section1 Specifying a Squish Server - - To specify a Squish Server to run: + To create a connection to Squish Server: \list 1 \li Select \preferences > \uicontrol Squish. - \image qtcreator-squish-preferences.png "Squish general preferences" - \li In the \uicontrol {Squish path} field, specify the path to the Squish + \image qtcreator-squish-preferences.png {Squish general preferences} + \li In \uicontrol {Squish path}, specify the path to the Squish installation directory. - \li In the \uicontrol {License path} field, specify the path to your + \li In \uicontrol {License path}, specify the path to your Squish license file if it is not located in your home folder. For example, if you have a global installation with several users, where the license key is installed in the global folder. - \li Select the \uicontrol {Local server} check box to use a locally - installed \c {squishserver.exe}. To use a server running in another - machine, deselect the check box and specify the server address in the - \uicontrol {Server host} field and the port number in the - \uicontrol {Server port} field. If no port is specified, \QC starts + \li Select \uicontrol {Local server} to use a locally + installed \c {squishserver.exe}. To use a server running on another + computer, clear the checkbox and specify the server address in the + \uicontrol {Server host} and the port number in the + \uicontrol {Server port}. If no port is specified, \QC starts \c squishserver in a way that enables it to automatically select an open port. - \li Select the \uicontrol {Verbose log} check box to include additional + \li Select \uicontrol {Verbose log} to include additional logging levels in the log output. - \li Select the \uicontrol {Minimize IDE} check box to automatically + \li Select \uicontrol {Minimize IDE} to automatically minimize \QC when running or recording test cases. \endlist - \section1 Specifying AUTs + \sa {Create Squish test suites}, {Enable and disable plugins}, + {Manage Squish test suites and cases}, {Select Squish AUTs}, {Squish} +*/ - To specify applications to test using Squish, select \uicontrol {Tools} > +/*! + \page creator-how-to-select-squish-auts.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-test + + \title Select Squish AUTs + + To select applications to test using Squish, go to \uicontrol {Tools} > \uicontrol {Squish} > \uicontrol {Server Settings}. - \image qtcreator-squish-server-settings.png "Squish Server Settings" + \image qtcreator-squish-server-settings.png {Squish Server Settings} - \section2 Mapping AUTs + When running test suites or cases, the Squish Runner instructs the Squish + Server to start the application under test (AUT). The server can be running + on multiple computers, and the AUT can be located on a different path on each + of them. Therefore, you must either map AUTs to their corresponding paths or + specify AUT paths to search from in the server settings. + + To test an already running application using a Squish Server running on + another computer, attach to the application. You can attach only one server + to your application at a time. The attached application is not closed when + the test case is completed. + + \section1 Map AUTs To specify the path to an AUT to run, select \uicontrol {Mapped AUTs} > \uicontrol Add and locate the AUT. @@ -88,13 +72,13 @@ Mapping AUTs prevents the server from accidentally executing the wrong AUT if two different executables have the same name, as the server executes the - first matching AUT it finds in the \uicontrol {AUT Paths} list. + first matching AUT it finds in \uicontrol {AUT Paths}. To change the path to the selected AUT, select \uicontrol {Edit}. To remove the mapping to the selected AUT, select \uicontrol {Remove}. - \section2 Specifying AUT Paths + \section1 Specify AUT paths To specify a path to search AUTs from, select \uicontrol {AUT Paths} > \uicontrol Add. @@ -107,32 +91,60 @@ To remove the selected AUT path, select \uicontrol {Remove}. - \section2 Adding Attachable AUTs + \section1 Add attachable AUTs To specify the path to a running AUT, select \uicontrol {Attachable AUTs} > \uicontrol Add. In the \uicontrol {Add Attachable AUT} dialog, specify a connection to a running application to register an attachable AUT. - \image qtcreator-squish-server-settings-add-attachable-aut.png "Add Attachable AUT dialog" + \image qtcreator-squish-server-settings-add-attachable-aut.png {Add Attachable AUT dialog} To change the connection to the selected AUT, select \uicontrol {Edit}. To remove the connection to the selected AUT, select \uicontrol {Remove}. - \section1 Managing Test Suites and Cases + \section1 Specify settings for running tests - You can manage Squish test suites and cases in the \uicontrol Squish - \l {Show and hide sidebars}{view}. + To specify settings for running tests: - \image qtcreator-squish-view.png "Squish sidebar view" + \list + \li In \uicontrol {Maximum startup time}, set the maximum time + to wait for the AUT to start before throwing an error. + \li In \uicontrol {Maximum response time}, set the maximum time + to wait for the AUT to respond before throwing an error. + \li In \uicontrol {Maximum post-mortem wait time}, set the + maximum time to wait after the main AUT has exited. This is useful + for AUTs invoked through launcher applications, such as shell scripts + or batch files. + \li Select \uicontrol {Animate mouse cursor} to animate + the mouse cursor when playing back a test. + \endlist + + \sa {Connect to Squish Server}, {Create Squish test suites}, + {Enable and disable plugins}, {Manage Squish test suites and cases}, + {Squish} +*/ + +/*! + \page creator-how-to-manage-squish-test-suites.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-test + + \title Manage Squish test suites and cases + + Manage Squish test suites and cases in the \uicontrol Squish + \l {Show and hide sidebars}{sidebar view}. + + \image qtcreator-squish-view.png {Squish sidebar view} To show existing test suites in \uicontrol {Test Suites}, select \uicontrol {Open Squish Suites} in the context menu. - \image qtcreator-squish-view-open-squish-suites.png "Open Squish Test Suites dialog" + \image qtcreator-squish-view-open-squish-suites.png {Open Squish Test Suites dialog} - You can open the \uicontrol {Squish Test Suite} wizard for creating a new - test suite by selecting \uicontrol {Create New Test Suite} in the context + To open the \uicontrol {Squish Test Suite} wizard for creating a new + test suite, select \uicontrol {Create New Test Suite} in the context menu. To add a test case to a test suite, select it and then select @@ -148,73 +160,40 @@ Double-click a test suite in \uicontrol {Test Suites} to open the \c {suite.conf} configuration file for editing. - \section2 Creating Test Suites - - To create a new test suite: - - \list 1 - \li Select \uicontrol File > \uicontrol {New Project} - > \uicontrol {Squish} > \uicontrol {Squish Test Suite} > - \uicontrol Choose. - \image qtcreator-squish-create-test-suite.png "Create Squish Test Suite wizard" - \li On the \uicontrol {Location} page, in \uicontrol {Test Suite Name}, - enter a name for the test suite. - \image qtcreator-squish-create-test-suite-location.png "Location page" - \li In \uicontrol {Test Suite folder's parent folder}, enter the path to - the folder to create the test suite folder, and then select - \uicontrol Next. - \li On the \uicontrol Setup page, select the GUI toolkit used by the AUT, - and then select \uicontrol Next. - \image qtcreator-squish-create-test-suite-setup.png "Setup page" - Currently, only desktop GUI toolkits are supported. - \li On the \uicontrol {Script Language} page, select the scripting - language to use for the test suite's test script, and then select - \uicontrol Next. - \image qtcreator-squish-create-test-suite-language.png "Languages page" - \li On the \uicontrol {AUT} page, select the AUT to test, and then select - \uicontrol Next. - \image qtcreator-squish-create-test-suite-aut.png "AUT page" - \li On the \uicontrol {Summary} page review the test suite settings, and - then select \uicontrol Finish to create the test suite. - \endlist - - The test suite is listed in \uicontrol {Test Suites} in the \uicontrol Squish - sidebar view. - - \section2 Recording Test Cases + \section1 Record test cases Squish records tests using the scripting language that you specified for the test suite. Recordings are made into existing test cases. In \uicontrol {Test Suites}, select the \inlineimage icons/recordfill.png - (\uicontrol {Record Test Case}) button next to the test case name. The AUT - that you selected for the test suite is displayed and you can start recording - the test case. + (\uicontrol {Record Test Case}) button next to the test case name. The + application under test (AUT) that you selected for the test suite is + displayed and you can start recording the test case. - \image qtcreator-squish-control-bar-record-test-case.png "Squish control bar for recording test cases" + \image qtcreator-squish-control-bar-record-test-case.png {Squish control bar for recording test cases} When you are done, select the \inlineimage icons/stop_small.png (\uicontrol {Stop}) button in the \uicontrol {Control Bar}. - You can edit recorded test scripts or copy parts of them into manually + Edit recorded test scripts or copy parts of them into manually created test scripts. - \image qtcreator-squish-test-script-edit.png "A test script open in the editor" + \image qtcreator-squish-test-script-edit.png {A test script open in the editor} - \section2 Running Test Suites + \section1 Run test suites - You can run a recorded test case to have Squish repeat all the actions that + Run a recorded test case to have Squish repeat all the actions that you applied when recording the test, but without the pauses that humans are prone to but which computers don't need. To run a test case, select the \inlineimage icons/run_small.png (\uicontrol {Run}) button next to the test case in \uicontrol {Test Suites}. - \image qtcreator-squish-control-bar-run-test-case.png "Squish control bar for running test cases" + \image qtcreator-squish-control-bar-run-test-case.png {Squish control bar for running test cases} While the test is running, you can view test results as well as interrupt and stop tests in the \uicontrol {Control Bar}. - \section2 Mapping Symbolic Names + \section1 Map symbolic names When Squish records a test, it uses \e {symbolic names} to identify the UI elements. Symbolic names are stored in an object map that can be either @@ -237,7 +216,7 @@ (\uicontrol {Object Map}) button next to the test suite in \uicontrol {Test Suites}. - \image qtcreator-squish-symbolic-names.png "Symbolic Names view" + \image qtcreator-squish-symbolic-names.png {Symbolic Names view} You can filter the symbolic names in the \uicontrol {Symbolic Names} view. To edit a symbolic name or the names or values of its properties, @@ -253,49 +232,87 @@ property, select \inlineimage icons/jumpto.png . - \section2 Inspecting Local Variables + \section1 Inspect local variables If you set breakpoints in the test code before running the test, the test execution is automatically interrupted when a breakpoint is hit. You can inspect the contents of local variables in the \uicontrol {Squish Locals} view. - \image qtcreator-squish-locals.png "Squish Locals view" + \image qtcreator-squish-locals.png {Squish Locals view} Use the \uicontrol {Step Into}, \uicontrol {Step Over}, and \uicontrol {Step Out} buttons in the \uicontrol Squish debugging view to step through the code. - \image qtcreator-squish-debugging-view.png "Squish debugging view" + \image qtcreator-squish-debugging-view.png {Squish debugging view} - \section2 Specifying Settings for Running Tests + \sa {Connect to Squish Server}, {Create Squish test suites}, + {Enable and disable plugins}, {Select Squish AUTs}, {Squish} +*/ - To specify settings for running tests, select \uicontrol Tools > - \uicontrol Squish > \uicontrol {Server Settings}: +/*! + \page creator-how-to-create-squish-test-suites.html + \previouspage creator-how-tos.html - \list - \li In the \uicontrol {Maximum startup time} field, set the maximum time - to wait for the AUT to start before throwing an error. - \li In the \uicontrol {Maximum response time} field, set the maximum time - to wait for the AUT to respond before throwing an error. - \li In the \uicontrol {Maximum post-mortem wait time} field, set the - maximum time to wait after the main AUT has exited. This is useful - for AUTs invoked through launcher applications, such as shell scripts - or batch files. - \li Select the \uicontrol {Animate mouse cursor} check box to animate - the mouse cursor when playing back a test. + \ingroup creator-how-to-test + + \title Create Squish test suites + + To create a new test suite: + + \list 1 + \li Go to \uicontrol File > \uicontrol {New Project}. + \li Select \uicontrol {Squish} > \uicontrol {Squish Test Suite} > + \uicontrol Choose. + \image qtcreator-squish-create-test-suite.png {Create Squish Test Suite wizard} + \li On the \uicontrol {Location} page, in \uicontrol {Test Suite Name}, + enter a name for the test suite. + \image qtcreator-squish-create-test-suite-location.png {Location page} + \li In \uicontrol {Test Suite folder's parent folder}, enter the path to + the folder to create the test suite folder, and then select + \uicontrol Next. + \li On the \uicontrol Setup page, select the GUI toolkit used by the + application under test (AUT), and then select \uicontrol Next. + \image qtcreator-squish-create-test-suite-setup.png {Setup page} + Currently, only desktop GUI toolkits are supported. + \li On the \uicontrol {Script Language} page, select the scripting + language to use for the test suite's test scripts, and then select + \uicontrol Next. + \image qtcreator-squish-create-test-suite-language.png {Languages page} + \li On the \uicontrol {AUT} page, select the AUT to test, and then select + \uicontrol Next. + \image qtcreator-squish-create-test-suite-aut.png {AUT page} + \li On the \uicontrol {Summary} page, review the test suite settings, and + then select \uicontrol Finish to create the test suite. \endlist - \section1 Viewing Test Results + The test suite is listed in \uicontrol {Test Suites} in the \uicontrol Squish + sidebar view. + + \sa {Connect to Squish Server}, {Manage Squish test suites and cases}, {Enable and disable plugins}, + {Select Squish AUTs}, {Squish} +*/ + +/*! + \page creator-reference-squish-output.html + \previouspage creator-reference.html + + \ingroup creator-reference-output-views + + \title Squish + + \brief View Squish test, runner, and server logs. Squish uses compare, verify, and exception functions to record the results of - tests applied to a running AUT in the test log as \e {passes} or \e {fails}. - In addition, any kind of test results can be recorded in the test log. + tests applied to a running application under test (AUT) in the test log as + \e {passes} or \e {fails}. In addition, any kind of test results can be + recorded in the test log. - You can view the test log in the \uicontrol Squish output, + To view the test log, go to the \uicontrol Squish output, \uicontrol {Test Results} tab. - \image qtcreator-squish-output-test-results.png "Test Results output" + \image qtcreator-squish-output-test-results.png {Test Results output} The \uicontrol Result column displays the time when each test run started and finished, log information and warnings, and test result status: @@ -314,12 +331,14 @@ the type of the operation that was performed: comparison, verification, or exception. - \section1 Viewing Squish Runner and Server Logs + \section1 View Squish runner and server logs - You can view the Squish Runner and Server logs in the \uicontrol Squish + To view the Squish Runner and Server logs, go to the \uicontrol Squish output, \uicontrol {Runner/Server Log} tab. - \image qtcreator-squish-output-runner-server-log.png "Runner and Server Log output" + \image qtcreator-squish-output-runner-server-log.png {Runner and Server Log output} - \sa {Enable and disable plugins} + \sa {Connect to Squish Server}, {Create Squish test suites}, + {Enable and disable plugins}, {Manage Squish test suites and cases}, + {Select Squish AUTs}, {View output} */ diff --git a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc index b164224e848..a1d755a3b65 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc @@ -287,10 +287,32 @@ \image qtcreator-autotests.png - Map AUTs (Application Under Test) to \QC and run Squish test suites - and cases from it. + \section2 Using Squish - For more information, see \l{Test}{How To: Test} and \l{Using Squish}. + \brief The experimental Squish plugin integrates Squish into \QC. + + \l{https://www.qt.io/product/quality-assurance/squish}{Squish} is an + automated GUI testing framework for testing Android, iOS, Java, \macos, + Qt, Tk, Windows, and XView applications, as well as HTML-based web + applications running in browsers. + + In \QC, you can: + + \list + \li Open existing Squish test suites. + \li Create new test suites and test cases. + \li Record test cases (in a very limited way compared to what you can do + inside the Squish IDE). + \li Use Squish Runner and Server to run test suites or cases and view + the results in the \uicontrol Squish \l{View output}{output}. + \li Set breakpoints before running tests to stop at certain locations and + inspect the local variables, similarly to when debugging a test. + \endlist + + To use the plugin, you must download and install Squish, create a connection + to the Squish Server, and specify the application under test (AUT) to run. + + For more information, see \l{Test}{How To: Test}. \section1 Publishing Applications diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc index 93fc8fc3987..83a1d745f71 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc @@ -146,7 +146,7 @@ launcher for debugging and analysis tools. \row \li Squish - \li Create new \l {Using Squish}{Squish test suites}. + \li Create new Squish test suites. \endtable diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index 0a60027451d..c462da8245a 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -87,7 +87,6 @@ \li \l{Analyzing Code with Cppcheck} \li \l{Visualizing Chrome Trace Events} \endlist - \li \l{Using Squish} \endlist \li \l{Tutorials} \generatelist creator-tutorials diff --git a/doc/qtcreator/src/qtcreator.qdoc b/doc/qtcreator/src/qtcreator.qdoc index cc3352dd108..3fb684ddba1 100644 --- a/doc/qtcreator/src/qtcreator.qdoc +++ b/doc/qtcreator/src/qtcreator.qdoc @@ -44,7 +44,6 @@ \li \l{Deploying to Devices} \li \l{Debugging} \li \l{Analyzing Code} - \li \l{Using Squish} \endlist \li \b {\l{Tutorials}} \generatelist creator-tutorials From af54306f821bc98c6bd3e3224050ee9c0fb79ef7 Mon Sep 17 00:00:00 2001 From: Jochen Becher Date: Mon, 1 Apr 2024 16:50:42 +0200 Subject: [PATCH 0127/1060] Add more visual attributes for relations Change-Id: I56af6a367c144e22c8113f69a2938080ddb2e750 Reviewed-by: Alessandro Portale Reviewed-by: --- src/libs/modelinglib/CMakeLists.txt | 1 + src/libs/modelinglib/modelinglib.qbs | 2 + .../qmt/config/stereotypedefinitionparser.cpp | 131 ++++++++++-- .../qmt/config/stereotypedefinitionparser.h | 3 +- .../modelinglib/qmt/diagram/drelation.cpp | 25 +++ src/libs/modelinglib/qmt/diagram/drelation.h | 32 +++ .../dflatassignmentvisitor.cpp | 2 + .../qmt/diagram_controller/dupdatevisitor.cpp | 2 +- .../qmt/diagram_scene/items/relationitem.cpp | 8 +- .../qmt/diagram_scene/parts/arrowitem.cpp | 24 ++- .../model_widgets_ui/propertiesviewmview.cpp | 153 ++++++++++++- .../model_widgets_ui/propertiesviewmview.h | 16 ++ .../qmt/serializer/diagramserializer.cpp | 3 + .../qmt/serializer/diagramserializer.h | 3 + .../qmt/stereotype/customrelation.cpp | 5 + .../qmt/stereotype/customrelation.h | 8 +- .../modelinglib/qmt/stereotype/shapevalue.cpp | 2 +- .../qmt/stereotype/stereotypecontroller.cpp | 9 + .../qmt/stereotype/stereotypecontroller.h | 1 + .../qmt/stereotype/stereotypeicon.cpp | 15 ++ .../qmt/stereotype/stereotypeicon.h | 25 ++- .../qmt/style/defaultstyleengine.cpp | 201 ++++++++++++++---- .../qmt/style/defaultstyleengine.h | 8 + .../modelinglib/qmt/style/relationvisuals.cpp | 58 +++++ .../modelinglib/qmt/style/relationvisuals.h | 42 ++++ .../modelinglib/qmt/style/stylecontroller.cpp | 6 + .../modelinglib/qmt/style/stylecontroller.h | 4 +- .../modelinglib/qmt/style/styledrelation.cpp | 6 +- .../modelinglib/qmt/style/styledrelation.h | 6 +- src/libs/modelinglib/qmt/style/styleengine.h | 4 + 30 files changed, 724 insertions(+), 81 deletions(-) create mode 100644 src/libs/modelinglib/qmt/style/relationvisuals.cpp create mode 100644 src/libs/modelinglib/qmt/style/relationvisuals.h diff --git a/src/libs/modelinglib/CMakeLists.txt b/src/libs/modelinglib/CMakeLists.txt index 27801f479a4..dcc810eb211 100644 --- a/src/libs/modelinglib/CMakeLists.txt +++ b/src/libs/modelinglib/CMakeLists.txt @@ -158,6 +158,7 @@ add_qtc_library(Modeling qmt/style/defaultstyle.h qmt/style/objectvisuals.cpp qmt/style/objectvisuals.h qmt/style/relationstarterstyle.cpp qmt/style/relationstarterstyle.h + qmt/style/relationvisuals.cpp qmt/style/relationvisuals.h qmt/style/stylecontroller.cpp qmt/style/stylecontroller.h qmt/style/style.cpp qmt/style/styledobject.cpp qmt/style/styledobject.h diff --git a/src/libs/modelinglib/modelinglib.qbs b/src/libs/modelinglib/modelinglib.qbs index 90fc1d0d982..409928d3cbf 100644 --- a/src/libs/modelinglib/modelinglib.qbs +++ b/src/libs/modelinglib/modelinglib.qbs @@ -295,6 +295,8 @@ QtcLibrary { "style/objectvisuals.h", "style/relationstarterstyle.cpp", "style/relationstarterstyle.h", + "style/relationvisuals.cpp", + "style/relationvisuals.h", "style/style.cpp", "style/style.h", "style/stylecontroller.cpp", diff --git a/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.cpp b/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.cpp index b3caebb1645..981641e0ad0 100644 --- a/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.cpp +++ b/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.cpp @@ -28,12 +28,15 @@ static const int KEYWORD_WIDTH = 6; static const int KEYWORD_HEIGHT = 7; static const int KEYWORD_MINWIDTH = 8; static const int KEYWORD_MINHEIGHT = 9; -static const int KEYWORD_LOCK_SIZE = 10; -static const int KEYWORD_DISPLAY = 11; -static const int KEYWORD_TEXTALIGN = 12; -static const int KEYWORD_BASECOLOR = 13; -static const int KEYWORD_SHAPE = 14; -static const int KEYWORD_OUTLINE = 15; +static const int KEYWORD_ICONWIDTH = 10; +static const int KEYWORD_ICONHEIGHT = 11; +static const int KEYWORD_LOCK_SIZE = 12; +static const int KEYWORD_DISPLAY = 13; +static const int KEYWORD_TEXTALIGN = 14; +static const int KEYWORD_BASECOLOR = 15; +static const int KEYWORD_SHAPE = 16; +static const int KEYWORD_OUTLINE = 17; +static const int KEYWORD_Z = 18; // Shape items static const int KEYWORD_CIRCLE = 30; @@ -102,8 +105,18 @@ static const int KEYWORD_DASH = 136; static const int KEYWORD_DASHDOT = 137; static const int KEYWORD_DASHDOTDOT = 138; static const int KEYWORD_COLOR = 139; +static const int KEYWORD_EMPHASIZED = 140; -// Operatoren +// Shape Value Units and Origin +static const int KEYWORD_ABS = 150; +static const int KEYWORD_FIX = 151; +static const int KEYWORD_SCALE = 152; +static const int KEYWORD_FRACT = 153; +static const int KEYWORD_ORIGIN = 154; +static const int KEYWORD_CENTER = 155; +static const int KEYWORD_SIZE = 156; + +// Operators static const int OPERATOR_SEMICOLON = 1; static const int OPERATOR_BRACE_OPEN = 2; static const int OPERATOR_BRACE_CLOSE = 3; @@ -111,6 +124,7 @@ static const int OPERATOR_COLON = 4; static const int OPERATOR_COMMA = 5; static const int OPERATOR_PERIOD = 6; static const int OPERATOR_MINUS = 7; +static const int OPERATOR_PERCENTAGE = 8; template QHash operator<<(QHash hash, QPair pair) { @@ -213,12 +227,15 @@ void StereotypeDefinitionParser::parse(ITextSource *source) {"height", KEYWORD_HEIGHT}, {"minwidth", KEYWORD_MINWIDTH}, {"minheight", KEYWORD_MINHEIGHT}, + {"iconwidth", KEYWORD_ICONWIDTH}, + {"iconheight", KEYWORD_ICONHEIGHT}, {"locksize", KEYWORD_LOCK_SIZE}, {"display", KEYWORD_DISPLAY}, {"textalignment", KEYWORD_TEXTALIGN}, {"basecolor", KEYWORD_BASECOLOR}, {"shape", KEYWORD_SHAPE}, {"outline", KEYWORD_OUTLINE}, + {"z", KEYWORD_Z}, {"circle", KEYWORD_CIRCLE}, {"ellipse", KEYWORD_ELLIPSE}, {"line", KEYWORD_LINE}, @@ -276,7 +293,15 @@ void StereotypeDefinitionParser::parse(ITextSource *source) {"dash", KEYWORD_DASH}, {"dashdot", KEYWORD_DASHDOT}, {"dashdotdot", KEYWORD_DASHDOTDOT}, - {"color", KEYWORD_COLOR}}); + {"color", KEYWORD_COLOR}, + {"emphasized", KEYWORD_EMPHASIZED}, + {"abs", KEYWORD_ABS}, + {"fix", KEYWORD_FIX}, + {"scale", KEYWORD_SCALE}, + {"fract", KEYWORD_FRACT}, + {"origin", KEYWORD_ORIGIN}, + {"center", KEYWORD_CENTER}, + {"size", KEYWORD_SIZE}}); textScanner.setOperators({{";", OPERATOR_SEMICOLON}, {"{", OPERATOR_BRACE_OPEN}, @@ -284,7 +309,8 @@ void StereotypeDefinitionParser::parse(ITextSource *source) {":", OPERATOR_COLON}, {",", OPERATOR_COMMA}, {".", OPERATOR_PERIOD}, - {"-", OPERATOR_MINUS}}); + {"-", OPERATOR_MINUS}, + {"%", OPERATOR_PERCENTAGE}}); textScanner.setSource(source); @@ -364,6 +390,23 @@ void StereotypeDefinitionParser::parseIcon() case KEYWORD_MINHEIGHT: stereotypeIcon.setMinHeight(parseFloatProperty()); break; + case KEYWORD_ICONWIDTH: + stereotypeIcon.setIconWith(parseFloatProperty()); + break; + case KEYWORD_ICONHEIGHT: + stereotypeIcon.setIconHeight(parseFloatProperty()); + break; + case KEYWORD_Z: + { + const static QHash zNames = QHash() + << qMakePair(QString("behinditems"), StereotypeIcon::DepthBehindItems) + << qMakePair(QString("amongitems"), StereotypeIcon::DepthAmongItems) + << qMakePair(QString("beforeitems"), StereotypeIcon::DepthBeforeItems); + parseEnum( + parseIdentifierProperty(), zNames, token.sourcePos(), + [&](StereotypeIcon::DepthLayer layer) { stereotypeIcon.setDepthLayer(layer); }); + break; + } case KEYWORD_LOCK_SIZE: { const static QHash lockNames @@ -577,7 +620,7 @@ QHash StereotypeDefinitio throw StereotypeDefinitionParserError("Property given twice.", token.sourcePos()); IconCommandParameter parameter = parameters.value(token.subtype()); if (parameter.type() == IconCommandParameter::ShapeValue) - parameter.setShapeValue(ShapeValueF(parseFloatProperty(), parameter.unit(), parameter.origin())); + parameter.setShapeValue(parseShapeValueProperty(parameter.unit(), parameter.origin())); else if (parameter.type() == IconCommandParameter::Boolean) parameter.setBoolean(parseBoolProperty()); else @@ -650,8 +693,6 @@ void StereotypeDefinitionParser::parseRelation(CustomRelation::Element element) } case KEYWORD_COLOR: { - if (element != CustomRelation::Element::Relation) - throwUnknownPropertyError(token); Value expression = parseProperty(); if (expression.type() == Color) { relation.setColorType(CustomRelation::ColorType::Custom); @@ -663,6 +704,10 @@ void StereotypeDefinitionParser::parseRelation(CustomRelation::Element element) relation.setColorType(CustomRelation::ColorType::EndA); } else if (colorName == "b") { relation.setColorType(CustomRelation::ColorType::EndB); + } else if (colorName == "warning") { + relation.setColorType(CustomRelation::ColorType::Warning); + } else if (colorName == "error") { + relation.setColorType(CustomRelation::ColorType::Error); } else if (QColor::isValidColor(colorName)) { relation.setColorType(CustomRelation::ColorType::Custom); relation.setColor(QColor(colorName)); @@ -674,6 +719,9 @@ void StereotypeDefinitionParser::parseRelation(CustomRelation::Element element) } break; } + case KEYWORD_EMPHASIZED: + relation.setEmphasized(parseBoolProperty()); + break; case KEYWORD_END: parseRelationEnd(&relation); break; @@ -976,6 +1024,65 @@ StereotypeDefinitionParser::Value StereotypeDefinitionParser::parseProperty() return parseExpression(); } +ShapeValueF StereotypeDefinitionParser::parseShapeValueProperty(ShapeValueF::Unit unit, ShapeValueF::Origin origin) +{ + expectColon(); + qreal value = parseFloatExpression(); + // unit + Token token = d->m_scanner->read(); + if (token.type() == Token::TokenOperator) { + switch (token.subtype()) { + case OPERATOR_PERCENTAGE: + unit = ShapeValueF::UnitPercentage; + break; + default: + d->m_scanner->unread(token); + break; + } + } else if (token.type() == Token::TokenKeyword) { + switch (token.subtype()) { + case KEYWORD_ABS: + unit = ShapeValueF::UnitAbsolute; + break; + case KEYWORD_FIX: + unit = ShapeValueF::UnitRelative; + break; + case KEYWORD_SCALE: + unit = ShapeValueF::UnitScaled; + break; + case KEYWORD_FRACT: + unit = ShapeValueF::UnitPercentage; + break; + default: + d->m_scanner->unread(token); + break; + } + } else { + d->m_scanner->unread(token); + } + // origin + token = d->m_scanner->read(); + if (token.type() == Token::TokenKeyword) { + switch (token.subtype()) { + case KEYWORD_ORIGIN: + origin = ShapeValueF::OriginTopOrLeft; + break; + case KEYWORD_CENTER: + origin = ShapeValueF::OriginCenter; + break; + case KEYWORD_SIZE: + origin = ShapeValueF::OriginBottomOrRight; + break; + default: + d->m_scanner->unread(token); + break; + } + } else { + d->m_scanner->unread(token); + } + return ShapeValueF(value, unit, origin); +} + QString StereotypeDefinitionParser::parseStringExpression() { Token token = d->m_scanner->read(); diff --git a/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.h b/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.h index e32126c7302..97b14211cac 100644 --- a/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.h +++ b/src/libs/modelinglib/qmt/config/stereotypedefinitionparser.h @@ -6,6 +6,7 @@ #include #include "qmt/infrastructure/exceptions.h" #include "qmt/stereotype/customrelation.h" +#include "qmt/stereotype/shapevalue.h" #include "qmt/stereotype/toolbar.h" #include "sourcepos.h" @@ -20,7 +21,6 @@ class ITextSource; class Token; class StereotypeIcon; class Toolbar; -class ShapeValueF; class QMT_EXPORT StereotypeDefinitionParserError : public Exception { @@ -97,6 +97,7 @@ private: bool parseBoolProperty(); QColor parseColorProperty(); Value parseProperty(); + ShapeValueF parseShapeValueProperty(ShapeValueF::Unit unit, ShapeValueF::Origin origin); QString parseStringExpression(); qreal parseFloatExpression(); diff --git a/src/libs/modelinglib/qmt/diagram/drelation.cpp b/src/libs/modelinglib/qmt/diagram/drelation.cpp index a21f61c7078..890bd275e4f 100644 --- a/src/libs/modelinglib/qmt/diagram/drelation.cpp +++ b/src/libs/modelinglib/qmt/diagram/drelation.cpp @@ -65,6 +65,31 @@ void DRelation::setIntermediatePoints(const QList m_intermediatePoints = intermediatePoints; } +void DRelation::setVisualPrimaryRole(VisualPrimaryRole visualPrimaryRole) +{ + m_visualPrimaryRole = visualPrimaryRole; +} + +void DRelation::setVisualSecondaryRole(VisualSecondaryRole visualSecondaryRole) +{ + m_visualSecondaryRole = visualSecondaryRole; +} + +void DRelation::setVisualEmphasized(bool visualEmphasized) +{ + m_isVisualEmphasized = visualEmphasized; +} + +void DRelation::setColor(const QColor &color) +{ + m_color = color; +} + +void DRelation::setThickness(qreal thickness) +{ + m_thickness = thickness; +} + void DRelation::accept(DVisitor *visitor) { visitor->visitDRelation(this); diff --git a/src/libs/modelinglib/qmt/diagram/drelation.h b/src/libs/modelinglib/qmt/diagram/drelation.h index 34bdaf1986d..ed5624ad9f0 100644 --- a/src/libs/modelinglib/qmt/diagram/drelation.h +++ b/src/libs/modelinglib/qmt/diagram/drelation.h @@ -5,6 +5,7 @@ #include "delement.h" +#include #include #include @@ -15,6 +16,22 @@ class DObject; class QMT_EXPORT DRelation : public DElement { public: + enum VisualPrimaryRole { + PrimaryRoleNormal, + PrimaryRoleCustom1, + PrimaryRoleCustom2, + PrimaryRoleCustom3, + PrimaryRoleCustom4, + PrimaryRoleCustom5 + }; + + enum VisualSecondaryRole { + SecondaryRoleNone, + SecondaryRoleWarning, + SecondaryRoleError, + SecondaryRoleSoften + }; + class IntermediatePoint { public: @@ -42,6 +59,16 @@ public: void setName(const QString &name); const QList intermediatePoints() const { return m_intermediatePoints; } void setIntermediatePoints(const QList &intermediatePoints); + VisualPrimaryRole visualPrimaryRole() const { return m_visualPrimaryRole; } + void setVisualPrimaryRole(VisualPrimaryRole visualPrimaryRole); + VisualSecondaryRole visualSecondaryRole() const { return m_visualSecondaryRole; } + void setVisualSecondaryRole(VisualSecondaryRole visualSecondaryRole); + bool isVisualEmphasized() const { return m_isVisualEmphasized; } + void setVisualEmphasized(bool visualEmphasized); + QColor color() const { return m_color; } + void setColor(const QColor &color); + qreal thickness() const { return m_thickness; } + void setThickness(qreal thickness); void accept(DVisitor *visitor) override; void accept(DConstVisitor *visitor) const override; @@ -53,6 +80,11 @@ private: Uid m_endBUid; QString m_name; QList m_intermediatePoints; + VisualPrimaryRole m_visualPrimaryRole = PrimaryRoleNormal; + VisualSecondaryRole m_visualSecondaryRole = SecondaryRoleNone; + bool m_isVisualEmphasized = false; + QColor m_color; + qreal m_thickness = 0; }; bool operator==(const DRelation::IntermediatePoint &lhs, const DRelation::IntermediatePoint &rhs); diff --git a/src/libs/modelinglib/qmt/diagram_controller/dflatassignmentvisitor.cpp b/src/libs/modelinglib/qmt/diagram_controller/dflatassignmentvisitor.cpp index 5e881758127..205c8fbb4db 100644 --- a/src/libs/modelinglib/qmt/diagram_controller/dflatassignmentvisitor.cpp +++ b/src/libs/modelinglib/qmt/diagram_controller/dflatassignmentvisitor.cpp @@ -100,6 +100,8 @@ void DFlatAssignmentVisitor::visitDRelation(const DRelation *relation) QMT_ASSERT(target, return); target->setStereotypes(relation->stereotypes()); target->setIntermediatePoints(relation->intermediatePoints()); + target->setVisualPrimaryRole(relation->visualPrimaryRole()); + target->setThickness(relation->thickness()); } void DFlatAssignmentVisitor::visitDInheritance(const DInheritance *inheritance) diff --git a/src/libs/modelinglib/qmt/diagram_controller/dupdatevisitor.cpp b/src/libs/modelinglib/qmt/diagram_controller/dupdatevisitor.cpp index 91a95438ad5..0866e6d9f5d 100644 --- a/src/libs/modelinglib/qmt/diagram_controller/dupdatevisitor.cpp +++ b/src/libs/modelinglib/qmt/diagram_controller/dupdatevisitor.cpp @@ -71,7 +71,7 @@ void DUpdateVisitor::visitMObject(const MObject *object) const MObject *owner = object->owner(); while (owner) { owner = owner->owner(); - depth += 1; + depth += 3; } if (isUpdating(depth != dobject->depth())) dobject->setDepth(depth); diff --git a/src/libs/modelinglib/qmt/diagram_scene/items/relationitem.cpp b/src/libs/modelinglib/qmt/diagram_scene/items/relationitem.cpp index a2f444f59e2..142955f8658 100644 --- a/src/libs/modelinglib/qmt/diagram_scene/items/relationitem.cpp +++ b/src/libs/modelinglib/qmt/diagram_scene/items/relationitem.cpp @@ -507,9 +507,11 @@ void RelationItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) const Style *RelationItem::adaptedStyle() { - DObject *endAObject = m_diagramSceneModel->diagramController()->findElement(m_relation->endAUid(), m_diagramSceneModel->diagram()); - DObject *endBObject = m_diagramSceneModel->diagramController()->findElement(m_relation->endBUid(), m_diagramSceneModel->diagram()); - StyledRelation styledRelation(m_relation, endAObject, endBObject); + const DObject *endAObject = m_diagramSceneModel->diagramController()->findElement(m_relation->endAUid(), m_diagramSceneModel->diagram()); + const DObject *endBObject = m_diagramSceneModel->diagramController()->findElement(m_relation->endBUid(), m_diagramSceneModel->diagram()); + const CustomRelation customRelation = m_diagramSceneModel->stereotypeController() + ->findCustomRelationByStereotype(m_relation->stereotypes().value(0)); + StyledRelation styledRelation(m_relation, endAObject, endBObject, &customRelation); return m_diagramSceneModel->styleController()->adaptRelationStyle(styledRelation); } diff --git a/src/libs/modelinglib/qmt/diagram_scene/parts/arrowitem.cpp b/src/libs/modelinglib/qmt/diagram_scene/parts/arrowitem.cpp index 3a14eb10d99..632da76f05a 100644 --- a/src/libs/modelinglib/qmt/diagram_scene/parts/arrowitem.cpp +++ b/src/libs/modelinglib/qmt/diagram_scene/parts/arrowitem.cpp @@ -384,27 +384,29 @@ void ArrowItem::updateShaft(const Style *style) QMT_ASSERT(m_shaftItem, return); QPen pen(style->linePen()); + pen.setCapStyle(Qt::FlatCap); + + auto scale = [&pen](qreal v) { + return v / ((pen.widthF() - 1.0) / 2.0 + 1.0); + }; + switch (m_shaft) { case ShaftSolid: break; case ShaftDashed: - pen.setDashPattern(QVector() - << (4.0 / pen.widthF()) << (4.0 / pen.widthF())); + pen.setDashPattern(QVector() << scale(5.0) << scale(3.0)); break; case ShaftDot: - pen.setDashPattern(QVector() - << (2.0 / pen.widthF()) << (2.0 / pen.widthF())); + pen.setDashPattern(QVector() << scale(3.0) << scale(3.0)); break; case ShaftDashDot: - pen.setDashPattern(QVector() - << (4.0 / pen.widthF()) << (2.0 / pen.widthF()) - << (2.0 / pen.widthF()) << (2.0 / pen.widthF())); + pen.setDashPattern(QVector() << scale(5.0) << scale(3.0) + << scale(3.0) << scale(3.0)); break; case ShaftDashDotDot: - pen.setDashPattern(QVector() - << (4.0 / pen.widthF()) << (2.0 / pen.widthF()) - << (2.0 / pen.widthF()) << (2.0 / pen.widthF()) - << (2.0 / pen.widthF()) << (2.0 / pen.widthF())); + pen.setDashPattern(QVector() << scale(5.0) << scale(3.0) + << scale(3.0) << scale(3.0) + << scale(3.0) << scale(3.0)); break; } m_shaftItem->setPen(pen); diff --git a/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.cpp b/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.cpp index 969313ca33f..28566d07ce3 100644 --- a/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.cpp +++ b/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.cpp @@ -43,6 +43,7 @@ #include "qmt/diagram_scene/items/stereotypedisplayvisitor.h" #include "qmt/stereotype/stereotypecontroller.h" #include "qmt/stereotype/customrelation.h" +#include "qmt/style/relationvisuals.h" #include "qmt/style/stylecontroller.h" #include "qmt/style/style.h" #include "qmt/style/objectvisuals.h" @@ -237,6 +238,61 @@ static DClass::TemplateDisplay translateIndexToTemplateDisplay(int index) return map[index]; } +static int translateRelationVisualPrimaryRoleToIndex(DRelation::VisualPrimaryRole visualRole) +{ + switch (visualRole) { + case DRelation::PrimaryRoleNormal: + return 0; + case DRelation::PrimaryRoleCustom1: + return 1; + case DRelation::PrimaryRoleCustom2: + return 2; + case DRelation::PrimaryRoleCustom3: + return 3; + case DRelation::PrimaryRoleCustom4: + return 4; + case DRelation::PrimaryRoleCustom5: + return 5; + } + return 0; +} + +static DRelation::VisualPrimaryRole translateIndexToRelationVisualPrimaryRole(int index) +{ + static const DRelation::VisualPrimaryRole map[] = { + DRelation::PrimaryRoleNormal, + DRelation::PrimaryRoleCustom1, DRelation::PrimaryRoleCustom2, DRelation::PrimaryRoleCustom3, + DRelation::PrimaryRoleCustom4, DRelation::PrimaryRoleCustom5 + }; + QMT_ASSERT(index >= 0 && index <= 5, return DRelation::PrimaryRoleNormal); + return map[index]; +} + +static int translateRelationVisualSecondaryRoleToIndex(DRelation::VisualSecondaryRole visualRole) +{ + switch (visualRole) { + case DRelation::SecondaryRoleNone: + return 0; + case DRelation::SecondaryRoleWarning: + return 1; + case DRelation::SecondaryRoleError: + return 2; + case DRelation::SecondaryRoleSoften: + return 3; + } + return 0; +} + +static DRelation::VisualSecondaryRole translateIndexToRelationVisualSecondaryRole(int index) +{ + static const DRelation::VisualSecondaryRole map[] = { + DRelation::SecondaryRoleNone, + DRelation::SecondaryRoleWarning, DRelation::SecondaryRoleError, DRelation::SecondaryRoleSoften + }; + QMT_ASSERT(index >= 0 && index <= 5, return DRelation::SecondaryRoleNone); + return map[index]; +} + static int translateAnnotationVisualRoleToIndex(DAnnotation::VisualRole visualRole) { switch (visualRole) { @@ -1057,6 +1113,52 @@ void PropertiesView::MView::visitDItem(const DItem *item) void PropertiesView::MView::visitDRelation(const DRelation *relation) { visitDElement(relation); + if (!m_relationVisualPrimaryRoleSelector) { + m_relationVisualPrimaryRoleSelector = new PaletteBox(m_topWidget); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleNormal); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleCustom1); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleCustom2); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleCustom3); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleCustom4); + setRelationPrimaryRolePalette(m_styleElementType, DRelation::PrimaryRoleCustom5); + addRow(Tr::tr("Color:"), m_relationVisualPrimaryRoleSelector, "color"); + connect(m_relationVisualPrimaryRoleSelector, &PaletteBox::activated, + this, &PropertiesView::MView::onRelationVisualPrimaryRoleChanged); + } + if (!m_relationVisualPrimaryRoleSelector->hasFocus()) { + DRelation::VisualPrimaryRole visualPrimaryRole; + if (haveSameValue(m_diagramElements, &DRelation::visualPrimaryRole, &visualPrimaryRole)) + m_relationVisualPrimaryRoleSelector->setCurrentIndex(translateRelationVisualPrimaryRoleToIndex(visualPrimaryRole)); + else + m_relationVisualPrimaryRoleSelector->setCurrentIndex(-1); + } + if (!m_relationVisualSecondaryRoleSelector) { + m_relationVisualSecondaryRoleSelector = new QComboBox(m_topWidget); + m_relationVisualSecondaryRoleSelector->addItems({ Tr::tr("Normal"), Tr::tr("Warning"), Tr::tr("Error"), Tr::tr("Soften") }); + addRow(Tr::tr("Role:"), m_relationVisualSecondaryRoleSelector, "role"); + connect(m_relationVisualSecondaryRoleSelector, QOverload::of(&QComboBox::activated), + this, &PropertiesView::MView::onRelationVisualSecondaryRoleChanged); + } + if (!m_relationVisualSecondaryRoleSelector->hasFocus()) { + DRelation::VisualSecondaryRole visualSecondaryRole; + if (haveSameValue(m_diagramElements, &DRelation::visualSecondaryRole, &visualSecondaryRole)) + m_relationVisualSecondaryRoleSelector->setCurrentIndex(translateRelationVisualSecondaryRoleToIndex(visualSecondaryRole)); + else + m_relationVisualSecondaryRoleSelector->setCurrentIndex(-1); + } + if (!m_relationVisualEmphasizedCheckbox) { + m_relationVisualEmphasizedCheckbox = new QCheckBox(Tr::tr("Emphasized"), m_topWidget); + addRow(QString(), m_relationVisualEmphasizedCheckbox, "emphasized"); + connect(m_relationVisualEmphasizedCheckbox, &QAbstractButton::clicked, + this, &PropertiesView::MView::onRelationVisualEmphasizedChanged); + } + if (!m_relationVisualEmphasizedCheckbox->hasFocus()) { + bool emphasized; + if (haveSameValue(m_diagramElements, &DRelation::isVisualEmphasized, &emphasized)) + m_relationVisualEmphasizedCheckbox->setChecked(emphasized); + else + m_relationVisualEmphasizedCheckbox->setChecked(false); + } #ifdef SHOW_DEBUG_PROPERTIES if (!m_pointsLabel) { m_pointsLabel = new QLabel(m_topWidget); @@ -1392,7 +1494,42 @@ void PropertiesView::MView::onAnnotationVisualRoleChanged(int visualRoleIndex) { DAnnotation::VisualRole visualRole = translateIndexToAnnotationVisualRole((visualRoleIndex)); assignModelElement( - m_diagramElements, SelectionMulti, visualRole, &DAnnotation::visualRole, &DAnnotation::setVisualRole); + m_diagramElements, SelectionMulti, visualRole, &DAnnotation::visualRole, &DAnnotation::setVisualRole); +} + + +void PropertiesView::MView::onRelationVisualPrimaryRoleChanged(int visualRoleIndex) +{ + DRelation::VisualPrimaryRole visualRole = translateIndexToRelationVisualPrimaryRole(visualRoleIndex); + assignModelElement( + m_diagramElements, SelectionMulti, visualRole, + &DRelation::visualPrimaryRole, &DRelation::setVisualPrimaryRole); +} + +void PropertiesView::MView::onRelationVisualSecondaryRoleChanged(int visualRoleIndex) +{ + DRelation::VisualSecondaryRole visualRole = translateIndexToRelationVisualSecondaryRole(visualRoleIndex); + assignModelElement( + m_diagramElements, SelectionMulti, visualRole, + &DRelation::visualSecondaryRole, &DRelation::setVisualSecondaryRole); +} + +void PropertiesView::MView::onRelationVisualEmphasizedChanged(bool visualEmphasized) +{ + assignModelElement(m_diagramElements, SelectionMulti, visualEmphasized, + &DRelation::isVisualEmphasized, &DRelation::setVisualEmphasized); +} + +void PropertiesView::MView::onRelationColorChanged(const QColor &color) +{ + assignModelElement(m_diagramElements, SelectionMulti, color, + &DRelation::color, &DRelation::setColor); +} + +void PropertiesView::MView::onRelationThicknessChanged(qreal thickness) +{ + assignModelElement(m_diagramElements, SelectionMulti, thickness, + &DRelation::thickness, &DRelation::setThickness); } void PropertiesView::MView::prepare() @@ -1553,7 +1690,8 @@ void PropertiesView::MView::setPrimaryRolePalette(StyleEngine::ElementType eleme DObject::VisualPrimaryRole visualPrimaryRole, const QColor &baseColor) { int index = translateVisualPrimaryRoleToIndex(visualPrimaryRole); - const Style *style = m_propertiesView->styleController()->adaptObjectStyle(elementType, ObjectVisuals(visualPrimaryRole, DObject::SecondaryRoleNone, false, baseColor, 0)); + const Style *style = m_propertiesView->styleController()->adaptObjectStyle( + elementType, ObjectVisuals(visualPrimaryRole, DObject::SecondaryRoleNone, false, baseColor, 0)); m_visualPrimaryRoleSelector->setBrush(index, style->fillBrush()); m_visualPrimaryRoleSelector->setLinePen(index, style->linePen()); } @@ -1595,6 +1733,17 @@ QString PropertiesView::MView::formatTemplateParameters(const QList &te return templateParamters; } +void PropertiesView::MView::setRelationPrimaryRolePalette(StyleEngine::ElementType elementType, + DRelation::VisualPrimaryRole visualPrimaryRole) +{ + int index = translateRelationVisualPrimaryRoleToIndex(visualPrimaryRole); + const Style *style = m_propertiesView->styleController()->adaptRelationStyle( + elementType, RelationVisuals(DObject::PrimaryRoleNormal, visualPrimaryRole, + DRelation::SecondaryRoleNone, false)); + m_relationVisualPrimaryRoleSelector->setBrush(index, style->fillBrush()); + m_relationVisualPrimaryRoleSelector->setLinePen(index, style->linePen()); +} + template QList PropertiesView::MView::filter(const QList &elements) { diff --git a/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.h b/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.h index 4762803a209..026f4f68578 100644 --- a/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.h +++ b/src/libs/modelinglib/qmt/model_widgets_ui/propertiesviewmview.h @@ -8,6 +8,8 @@ #include "qmt/model/mconstvisitor.h" #include "qmt/diagram/dconstvisitor.h" #include "qmt/diagram/dobject.h" +#include "qmt/diagram/drelation.h" +#include "qmt/infrastructure/qmtassert.h" #include "qmt/stereotype/stereotypeicon.h" #include "qmt/style/styleengine.h" @@ -110,6 +112,11 @@ protected: void onPlainShapeChanged(bool plainShape); void onItemShapeChanged(const QString &shape); void onAutoWidthChanged(bool autoWidthed); + void onRelationVisualPrimaryRoleChanged(int visualRoleIndex); + void onRelationVisualSecondaryRoleChanged(int visualRoleIndex); + void onRelationVisualEmphasizedChanged(bool visualEmphasized); + void onRelationColorChanged(const QColor &color); + void onRelationThicknessChanged(qreal thickness); void onAnnotationVisualRoleChanged(int visualRoleIndex); void prepare(); @@ -139,6 +146,9 @@ protected: QList splitTemplateParameters(const QString &templateParameters); QString formatTemplateParameters(const QList &templateParametersList); + void setRelationPrimaryRolePalette(StyleEngine::ElementType elementType, + DRelation::VisualPrimaryRole visualPrimaryRole); + enum SelectionType { SelectionSingle, SelectionMulti @@ -149,6 +159,9 @@ protected: template bool haveSameValue(const QList &baseElements, V (T::*getter)() const, V *value); template + bool isValueChanged(const QList &baseElements, SelectionType selectionType, + const V &value, V (T::*getter)() const); + template void assignModelElement(const QList &baseElements, SelectionType selectionType, const V &value, V (T::*getter)() const, void (T::*setter)(const V &)); template @@ -232,6 +245,9 @@ protected: QCheckBox *m_annotationAutoWidthCheckbox = nullptr; QComboBox *m_annotationVisualRoleSelector = nullptr; // DRelation + PaletteBox *m_relationVisualPrimaryRoleSelector = nullptr; + QComboBox *m_relationVisualSecondaryRoleSelector = nullptr; + QCheckBox *m_relationVisualEmphasizedCheckbox = nullptr; QLabel *m_pointsLabel = nullptr; }; diff --git a/src/libs/modelinglib/qmt/serializer/diagramserializer.cpp b/src/libs/modelinglib/qmt/serializer/diagramserializer.cpp index 5170d4fdc7e..5121a51f3d2 100644 --- a/src/libs/modelinglib/qmt/serializer/diagramserializer.cpp +++ b/src/libs/modelinglib/qmt/serializer/diagramserializer.cpp @@ -220,6 +220,9 @@ inline void Access::serialize(Archive &archive, DRelation &r || attr("b", relation, &DRelation::endBUid, &DRelation::setEndBUid) || attr("name", relation, &DRelation::name, &DRelation::setName) || attr("points", relation, &DRelation::intermediatePoints, &DRelation::setIntermediatePoints) + || attr("visualPrimaryRole", relation, &DRelation::visualPrimaryRole, &DRelation::setVisualPrimaryRole) + || attr("visualSecondaryRole", relation, &DRelation::visualSecondaryRole, &DRelation::setVisualSecondaryRole) + || attr("thickness", relation, &DRelation::thickness, &DRelation::setThickness) || end; } diff --git a/src/libs/modelinglib/qmt/serializer/diagramserializer.h b/src/libs/modelinglib/qmt/serializer/diagramserializer.h index a571ff94ef2..aa5d1adb526 100644 --- a/src/libs/modelinglib/qmt/serializer/diagramserializer.h +++ b/src/libs/modelinglib/qmt/serializer/diagramserializer.h @@ -6,6 +6,7 @@ #include "qmt/diagram/dannotation.h" #include "qmt/diagram/dobject.h" #include "qmt/diagram/dclass.h" +#include "qmt/diagram/drelation.h" #include "qark/serialize_enum.h" @@ -16,5 +17,7 @@ QARK_SERIALIZE_ENUM(qmt::DObject::VisualSecondaryRole) QARK_SERIALIZE_ENUM(qmt::DObject::StereotypeDisplay) QARK_SERIALIZE_ENUM(qmt::DClass::TemplateDisplay) QARK_SERIALIZE_ENUM(qmt::DAnnotation::VisualRole) +QARK_SERIALIZE_ENUM(qmt::DRelation::VisualPrimaryRole) +QARK_SERIALIZE_ENUM(qmt::DRelation::VisualSecondaryRole) } // namespace qark diff --git a/src/libs/modelinglib/qmt/stereotype/customrelation.cpp b/src/libs/modelinglib/qmt/stereotype/customrelation.cpp index fa9c80a1a0f..cc80da1b800 100644 --- a/src/libs/modelinglib/qmt/stereotype/customrelation.cpp +++ b/src/libs/modelinglib/qmt/stereotype/customrelation.cpp @@ -114,4 +114,9 @@ void CustomRelation::setColor(const QColor &color) m_color = color; } +void CustomRelation::setEmphasized(bool emphasized) +{ + m_emphasized = emphasized; +} + } // namespace qmt diff --git a/src/libs/modelinglib/qmt/stereotype/customrelation.h b/src/libs/modelinglib/qmt/stereotype/customrelation.h index 7125865aded..dd32c542c0c 100644 --- a/src/libs/modelinglib/qmt/stereotype/customrelation.h +++ b/src/libs/modelinglib/qmt/stereotype/customrelation.h @@ -55,7 +55,10 @@ public: enum class ColorType { EndA, EndB, - Custom + Custom, + Warning, + Error, + Soften, }; class End { @@ -113,6 +116,8 @@ public: void setColorType(ColorType colorType); QColor color() const { return m_color; } void setColor(const QColor &color); + bool emphasized() const { return m_emphasized; } + void setEmphasized(bool emphasized); friend auto qHash(CustomRelation::Relationship relationship) { return ::qHash(static_cast(relationship)); @@ -139,6 +144,7 @@ private: ShaftPattern m_shaftPattern = ShaftPattern::Solid; ColorType m_colorType = ColorType::EndA; QColor m_color; + bool m_emphasized = false; }; } // namespace qmt diff --git a/src/libs/modelinglib/qmt/stereotype/shapevalue.cpp b/src/libs/modelinglib/qmt/stereotype/shapevalue.cpp index 9e1ee46c156..cf8ea5ef65b 100644 --- a/src/libs/modelinglib/qmt/stereotype/shapevalue.cpp +++ b/src/libs/modelinglib/qmt/stereotype/shapevalue.cpp @@ -29,7 +29,7 @@ qreal ShapeValueF::mapScaledTo(qreal scaledOrigin, qreal originalSize, qreal bas v = originalSize != 0 ? (m_value * actualSize / originalSize) : m_value; break; case UnitPercentage: - v = m_value * actualSize; + v = m_value * actualSize / 100.0; break; } switch (m_origin) { diff --git a/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.cpp b/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.cpp index 030c9e12a51..f557e80c4b7 100644 --- a/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.cpp +++ b/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.cpp @@ -68,6 +68,7 @@ public: QHash, QString> m_stereotypeToIconIdMap; QHash m_iconIdToStereotypeIconsMap; QHash m_relationIdToCustomRelationMap; + QHash m_stereotypeToCustomRelationMap; QList m_toolbars; QList m_elementToolbars; QHash m_iconMap; @@ -150,6 +151,11 @@ CustomRelation StereotypeController::findCustomRelation(const QString &customRel return d->m_relationIdToCustomRelationMap.value(customRelationId); } +CustomRelation StereotypeController::findCustomRelationByStereotype(const QString &steoreotype) const +{ + return d->m_stereotypeToCustomRelationMap.value(steoreotype); +} + QIcon StereotypeController::createIcon(StereotypeIcon::Element element, const QList &stereotypes, const QString &defaultIconPath, const Style *style, const QSize &size, const QMarginsF &margins, qreal lineWidth) @@ -251,6 +257,9 @@ void StereotypeController::addStereotypeIcon(const StereotypeIcon &stereotypeIco void StereotypeController::addCustomRelation(const CustomRelation &customRelation) { d->m_relationIdToCustomRelationMap.insert(customRelation.id(), customRelation); + QString stereotype = Utils::toList(customRelation.stereotypes()).value(0); + if (!stereotype.isEmpty()) + d->m_stereotypeToCustomRelationMap.insert(stereotype, customRelation); } void StereotypeController::addToolbar(const Toolbar &toolbar) diff --git a/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.h b/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.h index 676f9a275a5..45bc3bbd18f 100644 --- a/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.h +++ b/src/libs/modelinglib/qmt/stereotype/stereotypecontroller.h @@ -33,6 +33,7 @@ public: const QList &stereotypes) const; StereotypeIcon findStereotypeIcon(const QString &stereotypeIconId) const; CustomRelation findCustomRelation(const QString &customRelationId) const; + CustomRelation findCustomRelationByStereotype(const QString &steoreotype) const; QIcon createIcon(StereotypeIcon::Element element, const QList &stereotypes, const QString &defaultIconPath, const Style *style, const QSize &size, const QMarginsF &margins, qreal lineWidth); diff --git a/src/libs/modelinglib/qmt/stereotype/stereotypeicon.cpp b/src/libs/modelinglib/qmt/stereotype/stereotypeicon.cpp index 8bcf5df170d..19e466c509c 100644 --- a/src/libs/modelinglib/qmt/stereotype/stereotypeicon.cpp +++ b/src/libs/modelinglib/qmt/stereotype/stereotypeicon.cpp @@ -62,6 +62,21 @@ void StereotypeIcon::setMinHeight(qreal minHeight) m_minHeight = minHeight; } +void StereotypeIcon::setIconWith(qreal iconWidth) +{ + m_iconWidth = iconWidth; +} + +void StereotypeIcon::setIconHeight(qreal iconHeight) +{ + m_iconHeight = iconHeight; +} + +void StereotypeIcon::setDepthLayer(DepthLayer depthLayer) +{ + m_depthLayer = depthLayer; +} + void StereotypeIcon::setSizeLock(StereotypeIcon::SizeLock sizeLock) { m_sizeLock = sizeLock; diff --git a/src/libs/modelinglib/qmt/stereotype/stereotypeicon.h b/src/libs/modelinglib/qmt/stereotype/stereotypeicon.h index be45245da5d..fcb5f1a15cd 100644 --- a/src/libs/modelinglib/qmt/stereotype/stereotypeicon.h +++ b/src/libs/modelinglib/qmt/stereotype/stereotypeicon.h @@ -31,6 +31,12 @@ public: DisplaySmart }; + enum DepthLayer { + DepthBehindItems, + DepthAmongItems, + DepthBeforeItems, + }; + enum SizeLock { LockNone, LockWidth, @@ -62,12 +68,20 @@ public: void setWidth(qreal width); qreal height() const { return m_height; } void setHeight(qreal height); - bool hasMinWidth() const { return m_minWidth > 0; } + bool hasMinWidth() const { return m_minWidth > 0.0; } qreal minWidth() const { return m_minWidth; } void setMinWidth(qreal minWidth); - bool hasMinHeight() const { return m_minHeight > 0; } + bool hasMinHeight() const { return m_minHeight > 0.0; } qreal minHeight() const { return m_minHeight; } void setMinHeight(qreal minHeight); + bool hasIconWidth() const { return m_iconWidth > 0.0; } + qreal iconWidth() const { return m_iconWidth; } + void setIconWith(qreal iconWidth); + bool hasIconHeight() const { return m_iconHeight > 0.0; } + qreal iconHeight() const { return m_iconHeight; } + void setIconHeight(qreal iconHeight); + DepthLayer depthLayer() const { return m_depthLayer; } + void setDepthLayer(DepthLayer depthLayer); SizeLock sizeLock() const { return m_sizeLock; } void setSizeLock(SizeLock sizeLock); Display display() const { return m_display; } @@ -90,8 +104,11 @@ private: QString m_name; qreal m_width = 100.0; qreal m_height = 100.0; - qreal m_minWidth = -1; - qreal m_minHeight = -1; + qreal m_minWidth = -1.0; + qreal m_minHeight = -1.0; + qreal m_iconWidth = -1.0; + qreal m_iconHeight = -1.0; + DepthLayer m_depthLayer = DepthAmongItems; SizeLock m_sizeLock = LockNone; Display m_display = DisplaySmart; TextAlignment m_textAlignment = TextalignBelow; diff --git a/src/libs/modelinglib/qmt/style/defaultstyleengine.cpp b/src/libs/modelinglib/qmt/style/defaultstyleengine.cpp index 74e91837dc9..bce1804892d 100644 --- a/src/libs/modelinglib/qmt/style/defaultstyleengine.cpp +++ b/src/libs/modelinglib/qmt/style/defaultstyleengine.cpp @@ -5,6 +5,7 @@ #include "defaultstyle.h" #include "objectvisuals.h" +#include "relationvisuals.h" #include "styledobject.h" #include "styledrelation.h" @@ -14,6 +15,7 @@ #include "qmt/diagram/ditem.h" #include "qmt/diagram/dannotation.h" #include "qmt/infrastructure/qmtassert.h" +#include "qmt/stereotype/customrelation.h" #include @@ -73,25 +75,29 @@ bool operator==(const ObjectStyleKey &lhs, const ObjectStyleKey &rhs) class RelationStyleKey { public: - RelationStyleKey(StyleEngine::ElementType elementType = StyleEngine::TypeOther, - DObject::VisualPrimaryRole visualPrimaryRole = DObject::PrimaryRoleNormal) + RelationStyleKey(StyleEngine::ElementType elementType, const RelationVisuals &relationVisuals, + bool withObject = false) : m_elementType(elementType), - m_visualPrimaryRole(visualPrimaryRole) + m_relationVisuals(relationVisuals), + m_withObject(withObject) { } StyleEngine::ElementType m_elementType = StyleEngine::TypeOther; - DObject::VisualPrimaryRole m_visualPrimaryRole = DObject::PrimaryRoleNormal; + RelationVisuals m_relationVisuals; + bool m_withObject = false; }; size_t qHash(const RelationStyleKey &styleKey) { - return ::qHash(styleKey.m_elementType) ^ ::qHash(styleKey.m_visualPrimaryRole); + return ::qHash(styleKey.m_elementType) ^ qHash(styleKey.m_relationVisuals); } bool operator==(const RelationStyleKey &lhs, const RelationStyleKey &rhs) { - return lhs.m_elementType == rhs.m_elementType && lhs.m_visualPrimaryRole == rhs.m_visualPrimaryRole; + return lhs.m_elementType == rhs.m_elementType + && lhs.m_relationVisuals == rhs.m_relationVisuals + && lhs.m_withObject == rhs.m_withObject; } class AnnotationStyleKey @@ -253,34 +259,6 @@ const Style *DefaultStyleEngine::applyObjectStyle(const Style *baseStyle, StyleE return derivedStyle; } -static bool areStackingRoles(DObject::VisualPrimaryRole rhsPrimaryRole, - DObject::VisualSecondaryRole rhsSecondaryRole, - DObject::VisualPrimaryRole lhsPrimaryRole, - DObject::VisualSecondaryRole lhsSecondaryRols) -{ - switch (rhsSecondaryRole) { - case DObject::SecondaryRoleNone: - case DObject::SecondaryRoleLighter: - case DObject::SecondaryRoleDarker: - case DObject::SecondaryRoleFlat: - switch (lhsSecondaryRols) { - case DObject::SecondaryRoleNone: - case DObject::SecondaryRoleLighter: - case DObject::SecondaryRoleDarker: - case DObject::SecondaryRoleFlat: - return lhsPrimaryRole == rhsPrimaryRole; - case DObject::SecondaryRoleSoften: - case DObject::SecondaryRoleOutline: - return false; - } - break; - case DObject::SecondaryRoleSoften: - case DObject::SecondaryRoleOutline: - return false; - } - return true; -} - const Style *DefaultStyleEngine::applyObjectStyle(const Style *baseStyle, const StyledObject &styledObject, const Parameters *parameters) { @@ -325,10 +303,12 @@ const Style *DefaultStyleEngine::applyObjectStyle(const Style *baseStyle, const } int depth = 0; if (!depths.isEmpty()) { - for (auto it = depths.cbegin(); it != depths.cend(); ++it) { - if (it->m_elementType == elementType - && areStackingRoles(it->m_visualPrimaryRole, it->m_visualSecondaryRole, - styledVisualPrimaryRole, styledVisualSecondaryRole)) { + const QList keys = Utils::sorted(depths.keys()); + for (int d : keys) { + DepthProperties properties = depths.value(d); + if (properties.m_elementType == elementType + && areStackingRoles(properties.m_visualPrimaryRole, properties.m_visualSecondaryRole, + styledVisualPrimaryRole, styledVisualSecondaryRole)) { ++depth; } else { depth = 0; @@ -345,13 +325,100 @@ const Style *DefaultStyleEngine::applyObjectStyle(const Style *baseStyle, const parameters); } +const Style *DefaultStyleEngine::applyRelationStyle(const Style *baseStyle, ElementType elementType, const RelationVisuals &relationVisuals, const Parameters *parameters) +{ + Q_UNUSED(parameters); + + RelationStyleKey key(elementType, relationVisuals); + const Style *derivedStyle = m_relationStyleMap.value(key); + if (!derivedStyle) { + auto style = new Style(baseStyle->type()); + static QColor customColors[] = { + QColor(0xEE, 0x8E, 0x99).darker(110), // ROLE_CUSTOM1, + QColor(0x80, 0xAF, 0x47).lighter(130), // ROLE_CUSTOM2, + QColor(0xFF, 0xA1, 0x5B).lighter(100), // ROLE_CUSTOM3, + QColor(0x55, 0xC4, 0xCF).lighter(120), // ROLE_CUSTOM4, + QColor(0xFF, 0xE1, 0x4B) // ROLE_CUSTOM5, + }; + + int index = static_cast(relationVisuals.visualPrimaryRole()) - static_cast(DRelation::PrimaryRoleCustom1); + QColor lineColor = index >= 0 && index <= 4 ? customColors[index] : Qt::black; + switch (relationVisuals.visualSecondaryRole()) { + case DRelation::SecondaryRoleNone: + break; + case DRelation::SecondaryRoleWarning: + lineColor = Qt::yellow; + break; + case DRelation::SecondaryRoleError: + lineColor = Qt::red; + break; + case DRelation::SecondaryRoleSoften: + lineColor = Qt::gray; + break; + } + + QColor fillColor = lineColor == Qt::black ? Qt::darkGray : lineColor.lighter(150); + QPen linePen = baseStyle->linePen(); + linePen.setWidth(1); + linePen.setColor(lineColor); + style->setLinePen(linePen); + QBrush textBrush = baseStyle->textBrush(); + textBrush.setColor(Qt::black); + style->setTextBrush(textBrush); + QBrush brush = baseStyle->fillBrush(); + brush.setColor(fillColor); + brush.setStyle(Qt::SolidPattern); + style->setFillBrush(brush); + style->setNormalFont(baseStyle->normalFont()); + style->setSmallFont(baseStyle->smallFont()); + style->setHeaderFont(baseStyle->headerFont()); + m_relationStyleMap.insert(key, style); + derivedStyle = style; + } + return derivedStyle; +} + const Style *DefaultStyleEngine::applyRelationStyle(const Style *baseStyle, const StyledRelation &styledRelation, const Parameters *parameters) { Q_UNUSED(parameters) ElementType elementType = objectType(styledRelation.endA()); - RelationStyleKey key(elementType, styledRelation.endA() ? styledRelation.endA()->visualPrimaryRole() : DObject::PrimaryRoleNormal); + RelationVisuals relationVisuals; + if (styledRelation.customRelation()) { + switch (styledRelation.customRelation()->colorType()) { + case CustomRelation::ColorType::EndA: + // TODO implement + break; + case CustomRelation::ColorType::EndB: + // TODO implement + break; + case CustomRelation::ColorType::Custom: + // TODO implement + break; + case CustomRelation::ColorType::Warning: + relationVisuals.setVisualSecondaryRole(DRelation::VisualSecondaryRole::SecondaryRoleWarning); + break; + case CustomRelation::ColorType::Error: + relationVisuals.setVisualSecondaryRole(DRelation::VisualSecondaryRole::SecondaryRoleError); + break; + case CustomRelation::ColorType::Soften: + relationVisuals.setVisualSecondaryRole(DRelation::VisualSecondaryRole::SecondaryRoleSoften); + break; + } + relationVisuals.setEmphasized(styledRelation.customRelation()->emphasized()); + } + if (styledRelation.endA()) + relationVisuals.setVisualObjectPrimaryRole(styledRelation.endA()->visualPrimaryRole()); + if (styledRelation.relation()) { + if (styledRelation.relation()->visualPrimaryRole() != DRelation::VisualPrimaryRole::PrimaryRoleNormal) + relationVisuals.setVisualPrimaryRole(styledRelation.relation()->visualPrimaryRole()); + if (styledRelation.relation()->visualSecondaryRole() != DRelation::VisualSecondaryRole::SecondaryRoleNone) + relationVisuals.setVisualSecondaryRole(styledRelation.relation()->visualSecondaryRole()); + if (styledRelation.relation()->isVisualEmphasized()) + relationVisuals.setEmphasized(styledRelation.relation()->isVisualEmphasized()); + } + RelationStyleKey key(elementType, relationVisuals, true); const Style *derivedStyle = m_relationStyleMap.value(key); if (!derivedStyle) { auto style = new Style(baseStyle->type()); @@ -365,12 +432,36 @@ const Style *DefaultStyleEngine::applyRelationStyle(const Style *baseStyle, cons QColor lineColor = DefaultStyleEngine::lineColor(objectType(object), objectVisuals); QColor fillColor = lineColor; + static QColor customColors[] = { + QColor(0xEE, 0x8E, 0x99).darker(110), // ROLE_CUSTOM1, + QColor(0x80, 0xAF, 0x47).lighter(130), // ROLE_CUSTOM2, + QColor(0xFF, 0xA1, 0x5B).lighter(100), // ROLE_CUSTOM3, + QColor(0x55, 0xC4, 0xCF).lighter(120), // ROLE_CUSTOM4, + QColor(0xFF, 0xE1, 0x4B) // ROLE_CUSTOM5, + }; + + int index = static_cast(relationVisuals.visualPrimaryRole()) - static_cast(DRelation::PrimaryRoleCustom1); + lineColor = (index >= 0 && index <= 4) ? customColors[index] : lineColor; + switch (relationVisuals.visualSecondaryRole()) { + case DRelation::SecondaryRoleNone: + break; + case DRelation::SecondaryRoleWarning: + lineColor = QColor(0xffc800); + break; + case DRelation::SecondaryRoleError: + lineColor = Qt::red; + break; + case DRelation::SecondaryRoleSoften: + lineColor = Qt::gray; + break; + } + QPen linePen = baseStyle->linePen(); - linePen.setWidth(1); + linePen.setWidth(relationVisuals.isEmphasized() ? 3 : 1); linePen.setColor(lineColor); style->setLinePen(linePen); QBrush textBrush = baseStyle->textBrush(); - textBrush.setColor(QColor("black")); + textBrush.setColor(Qt::black); style->setTextBrush(textBrush); QBrush brush = baseStyle->fillBrush(); brush.setColor(fillColor); @@ -497,6 +588,34 @@ DefaultStyleEngine::ElementType DefaultStyleEngine::objectType(const DObject *ob return elementType; } +bool DefaultStyleEngine::areStackingRoles(DObject::VisualPrimaryRole rhsPrimaryRole, + DObject::VisualSecondaryRole rhsSecondaryRole, + DObject::VisualPrimaryRole lhsPrimaryRole, + DObject::VisualSecondaryRole lhsSecondaryRols) +{ + switch (rhsSecondaryRole) { + case DObject::SecondaryRoleNone: + case DObject::SecondaryRoleLighter: + case DObject::SecondaryRoleDarker: + case DObject::SecondaryRoleFlat: + switch (lhsSecondaryRols) { + case DObject::SecondaryRoleNone: + case DObject::SecondaryRoleLighter: + case DObject::SecondaryRoleDarker: + case DObject::SecondaryRoleFlat: + return lhsPrimaryRole == rhsPrimaryRole; + case DObject::SecondaryRoleSoften: + case DObject::SecondaryRoleOutline: + return false; + } + break; + case DObject::SecondaryRoleSoften: + case DObject::SecondaryRoleOutline: + return false; + } + return true; +} + QColor DefaultStyleEngine::baseColor(ElementType elementType, ObjectVisuals objectVisuals) { if (objectVisuals.visualSecondaryRole() == DObject::SecondaryRoleOutline) diff --git a/src/libs/modelinglib/qmt/style/defaultstyleengine.h b/src/libs/modelinglib/qmt/style/defaultstyleengine.h index 67cdf9ed857..b5ebe557e0b 100644 --- a/src/libs/modelinglib/qmt/style/defaultstyleengine.h +++ b/src/libs/modelinglib/qmt/style/defaultstyleengine.h @@ -37,6 +37,9 @@ public: const Parameters *parameters) override; const Style *applyObjectStyle(const Style *baseStyle, const StyledObject &styledObject, const Parameters *parameters) override; + const Style *applyRelationStyle(const Style *baseStyle, ElementType elementType, + const RelationVisuals &relationVisuals, + const Parameters *parameters) override; const Style *applyRelationStyle(const Style *baseStyle, const StyledRelation &styledRelation, const Parameters *parameters) override; const Style *applyAnnotationStyle(const Style *baseStyle, const DAnnotation *annotation, @@ -54,6 +57,11 @@ private: ElementType objectType(const DObject *object); + bool areStackingRoles(DObject::VisualPrimaryRole rhsPrimaryRole, + DObject::VisualSecondaryRole rhsSecondaryRole, + DObject::VisualPrimaryRole lhsPrimaryRole, + DObject::VisualSecondaryRole lhsSecondaryRols); + QColor baseColor(ElementType elementType, ObjectVisuals objectVisuals); QColor lineColor(ElementType elementType, const ObjectVisuals &objectVisuals); QColor fillColor(ElementType elementType, const ObjectVisuals &objectVisuals); diff --git a/src/libs/modelinglib/qmt/style/relationvisuals.cpp b/src/libs/modelinglib/qmt/style/relationvisuals.cpp new file mode 100644 index 00000000000..d297047ae1d --- /dev/null +++ b/src/libs/modelinglib/qmt/style/relationvisuals.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2024 Jochen Becher +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "relationvisuals.h" + +namespace qmt { + +RelationVisuals::RelationVisuals() {} + +RelationVisuals::RelationVisuals(DObject::VisualPrimaryRole visualObjectPrimaryRole, + DRelation::VisualPrimaryRole visualPrimaryRole, + DRelation::VisualSecondaryRole visualSecondaryRole, + bool emphasized) + : m_visualObjectPrimaryRole(visualObjectPrimaryRole) + , m_visualPrimaryRole(visualPrimaryRole) + , m_visualSecondaryRole(visualSecondaryRole) + , m_isEmphasized(emphasized) +{} + +RelationVisuals::~RelationVisuals() {} + +void RelationVisuals::setVisualPrimaryRole(DRelation::VisualPrimaryRole VisualPrimaryRole) +{ + m_visualPrimaryRole = VisualPrimaryRole; +} + +void RelationVisuals::setVisualObjectPrimaryRole(DObject::VisualPrimaryRole visualPrimaryRole) +{ + m_visualObjectPrimaryRole = visualPrimaryRole; +} + +void RelationVisuals::setVisualSecondaryRole(DRelation::VisualSecondaryRole visualSecondaryRole) +{ + m_visualSecondaryRole = visualSecondaryRole; +} + +void RelationVisuals::setEmphasized(bool emphasized) +{ + m_isEmphasized = emphasized; +} + +bool operator==(const RelationVisuals &lhs, const RelationVisuals &rhs) +{ + return lhs.visualObjectPrimaryRole() == rhs.visualObjectPrimaryRole() + && lhs.visualPrimaryRole() == rhs.visualPrimaryRole() + && lhs.visualSecondaryRole() == rhs.visualSecondaryRole() + && lhs.isEmphasized() == rhs.isEmphasized(); +} + +size_t qHash(const RelationVisuals &relationVisuals) +{ + return ::qHash(static_cast(relationVisuals.visualObjectPrimaryRole())) + ^ ::qHash(static_cast(relationVisuals.visualPrimaryRole())) + ^ ::qHash(static_cast(relationVisuals.visualSecondaryRole())) + ^ ::qHash(relationVisuals.isEmphasized()); +} + +} // namespace qmt diff --git a/src/libs/modelinglib/qmt/style/relationvisuals.h b/src/libs/modelinglib/qmt/style/relationvisuals.h new file mode 100644 index 00000000000..be87a7d2917 --- /dev/null +++ b/src/libs/modelinglib/qmt/style/relationvisuals.h @@ -0,0 +1,42 @@ +// Copyright (C) 2024 Jochen Becher +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "qmt/diagram/drelation.h" +#include "qmt/diagram/dobject.h" + +#include + +namespace qmt { + +class QMT_EXPORT RelationVisuals +{ +public: + RelationVisuals(); + RelationVisuals(DObject::VisualPrimaryRole visualObjectPrimaryRole, + DRelation::VisualPrimaryRole visualPrimaryRole, + DRelation::VisualSecondaryRole visualSecondaryRole, + bool emphasized); + ~RelationVisuals(); + + DObject::VisualPrimaryRole visualObjectPrimaryRole() const { return m_visualObjectPrimaryRole; } + void setVisualObjectPrimaryRole(DObject::VisualPrimaryRole visualPrimaryRole); + DRelation::VisualPrimaryRole visualPrimaryRole() const { return m_visualPrimaryRole; } + void setVisualPrimaryRole(DRelation::VisualPrimaryRole visualPrimaryRole); + DRelation::VisualSecondaryRole visualSecondaryRole() const { return m_visualSecondaryRole; } + void setVisualSecondaryRole(DRelation::VisualSecondaryRole visualSecondaryRole); + bool isEmphasized() const { return m_isEmphasized; } + void setEmphasized(bool emphasized); + +private: + DObject::VisualPrimaryRole m_visualObjectPrimaryRole = DObject::PrimaryRoleNormal; + DRelation::VisualPrimaryRole m_visualPrimaryRole = DRelation::PrimaryRoleNormal; + DRelation::VisualSecondaryRole m_visualSecondaryRole = DRelation::SecondaryRoleNone; + bool m_isEmphasized = false; +}; + +bool operator==(const RelationVisuals &lhs, const RelationVisuals &rhs); +size_t qHash(const RelationVisuals &relationVisuals); + +} // namespace qmt diff --git a/src/libs/modelinglib/qmt/style/stylecontroller.cpp b/src/libs/modelinglib/qmt/style/stylecontroller.cpp index 5cd50c1738a..bbfc28622ed 100644 --- a/src/libs/modelinglib/qmt/style/stylecontroller.cpp +++ b/src/libs/modelinglib/qmt/style/stylecontroller.cpp @@ -63,6 +63,12 @@ const Style *StyleController::adaptObjectStyle(const StyledObject &object) return m_defaultStyleEngine->applyObjectStyle(m_defaultStyle.data(), object, ¶meters); } +const Style *StyleController::adaptRelationStyle(StyleEngine::ElementType elementType, const RelationVisuals &relationVisuals) +{ + Parameters parameters(this); + return m_defaultStyleEngine->applyRelationStyle(m_defaultStyle.data(), elementType, relationVisuals, ¶meters); +} + const Style *StyleController::adaptRelationStyle(const StyledRelation &relation) { Parameters parameters(this); diff --git a/src/libs/modelinglib/qmt/style/stylecontroller.h b/src/libs/modelinglib/qmt/style/stylecontroller.h index 2627bb2caa2..afa566460fc 100644 --- a/src/libs/modelinglib/qmt/style/stylecontroller.h +++ b/src/libs/modelinglib/qmt/style/stylecontroller.h @@ -4,7 +4,6 @@ #pragma once #include "styleengine.h" -#include "qmt/diagram/dobject.h" #include #include @@ -14,6 +13,7 @@ namespace qmt { class Style; class ObjectVisuals; class StyledObject; +class RelationVisuals; class StyledRelation; class DAnnotation; class DBoundary; @@ -33,6 +33,8 @@ public: const Style *adaptObjectStyle(StyleEngine::ElementType elementType, const ObjectVisuals &objectVisuals); const Style *adaptObjectStyle(const StyledObject &object); + const Style *adaptRelationStyle(StyleEngine::ElementType elementType, + const RelationVisuals &relationVisuals); const Style *adaptRelationStyle(const StyledRelation &relation); const Style *adaptAnnotationStyle(const DAnnotation *annotation); const Style *adaptBoundaryStyle(const DBoundary *boundary); diff --git a/src/libs/modelinglib/qmt/style/styledrelation.cpp b/src/libs/modelinglib/qmt/style/styledrelation.cpp index 3c78abf96df..144e5f22ac7 100644 --- a/src/libs/modelinglib/qmt/style/styledrelation.cpp +++ b/src/libs/modelinglib/qmt/style/styledrelation.cpp @@ -5,10 +5,12 @@ namespace qmt { -StyledRelation::StyledRelation(const DRelation *relation, const DObject *endA, const DObject *endB) +StyledRelation::StyledRelation(const DRelation *relation, const DObject *endA, const DObject *endB, + const CustomRelation *customRelation) : m_relation(relation), m_endA(endA), - m_endB(endB) + m_endB(endB), + m_customRelation(customRelation) { } diff --git a/src/libs/modelinglib/qmt/style/styledrelation.h b/src/libs/modelinglib/qmt/style/styledrelation.h index 422947908e2..27e8735463d 100644 --- a/src/libs/modelinglib/qmt/style/styledrelation.h +++ b/src/libs/modelinglib/qmt/style/styledrelation.h @@ -9,21 +9,25 @@ namespace qmt { class DRelation; class DObject; +class CustomRelation; class QMT_EXPORT StyledRelation { public: - StyledRelation(const DRelation *relation, const DObject *endA, const DObject *endB); + StyledRelation(const DRelation *relation, const DObject *endA, const DObject *endB, + const CustomRelation *customRelation); ~StyledRelation(); const DRelation *relation() const { return m_relation; } const DObject *endA() const { return m_endA; } const DObject *endB() const { return m_endB; } + const CustomRelation *customRelation() const { return m_customRelation; } private: const DRelation *m_relation = nullptr; const DObject *m_endA = nullptr; const DObject *m_endB = nullptr; + const CustomRelation *m_customRelation = nullptr; }; } // namespace qmt diff --git a/src/libs/modelinglib/qmt/style/styleengine.h b/src/libs/modelinglib/qmt/style/styleengine.h index e78f4303d93..463a62a194d 100644 --- a/src/libs/modelinglib/qmt/style/styleengine.h +++ b/src/libs/modelinglib/qmt/style/styleengine.h @@ -14,6 +14,7 @@ namespace qmt { class Style; class ObjectVisuals; class StyledObject; +class RelationVisuals; class StyledRelation; class DAnnotation; @@ -51,6 +52,9 @@ public: const Parameters *parameters) = 0; virtual const Style *applyObjectStyle(const Style *baseStyle, const StyledObject &, const Parameters *) = 0; + virtual const Style *applyRelationStyle(const Style *baseStyle, ElementType elementType, + const RelationVisuals &relationVisuals, + const Parameters *) = 0; virtual const Style *applyRelationStyle(const Style *baseStyle, const StyledRelation &, const Parameters *) = 0; virtual const Style *applyAnnotationStyle(const Style *baseStyle, const DAnnotation *, From 403f5daf317837c435ffbf0b9ac8cf82abcc73d9 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Mon, 8 Apr 2024 14:22:49 +0200 Subject: [PATCH 0128/1060] Editor: Open in different editor type after renaming or saving as After save as, and when we get notified about a file rename, check if it makes sense to open the document in a different editor type. This covers the File > Save As menu item, as well as renaming in the project tree and the file system view. In principle this can happen when the MIME type changes (this could even happen when the contents change, in special cases, but let's ignore this). Open the document in a different editor type if - the document previously was opened in the default editor, and the new file name would result in a different default editor type - the document was not opened in the default editor, but the available factories for the new name does not contain this Do not use a different editor type, if it was previously open in a non- default editor, and that is still valid for the new name. Uses the openEditorWith functionality that is also used when a user explicitly selects an editor type. This gives us all the details like what happens if the new editor type fails to handle the file (e.g. when renaming a text file to `.gif`). Fixes: QTCREATORBUG-30317 Change-Id: I4c0b46da1e05165ac4f157dfa15b1783e0a3f3db Reviewed-by: David Schulz Reviewed-by: --- .../editormanager/editormanager.cpp | 65 +++++++++++++++++-- .../editormanager/editormanager_p.h | 5 ++ 2 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp index 6ec37a6cb8c..a9b10b1bef1 100644 --- a/src/plugins/coreplugin/editormanager/editormanager.cpp +++ b/src/plugins/coreplugin/editormanager/editormanager.cpp @@ -723,6 +723,14 @@ void EditorManagerPrivate::init() IEditor *editor = EditorManager::currentEditor(); return editor ? editor->widget()->mapToGlobal(QPoint(0, 0)).y() : 0; }); + + connect( + DocumentManager::instance(), + &DocumentManager::allDocumentsRenamed, + d, + [](const FilePath &from, const FilePath &to) { + EditorManagerPrivate::handleFileRenamed(from, to); + }); } void EditorManagerPrivate::extensionsInitialized() @@ -1886,6 +1894,52 @@ void EditorManagerPrivate::updateAutoSave() d->m_autoSaveTimer->stop(); } +void EditorManagerPrivate::handleFileRenamed( + const Utils::FilePath &originalFilePath, const Utils::FilePath &newFilePath, Id originalType) +{ + if (!originalType.isValid()) { + // check if the file is open in an editor, if not, nothing to do + const QList editorsOpenForFile = DocumentModel::editorsForFilePath(newFilePath); + if (editorsOpenForFile.isEmpty()) + return; + originalType = editorsOpenForFile.first()->document()->id(); + } + + // If the MIME type changed, it might make more sense to re-open the file + // in a different editor type. (Things like undo history are not transferred then though.) + // If the original editor was not the default editor, try to stay with that, though. + // E.g. if a .md file is open in the base text editor, and then renamed to .cpp, + // just stay with the base text editor, because that was not the default editor and is + // still a valid editor for the new MIME type. + const MimeType originalMt = Utils::mimeTypeForFile(originalFilePath); + const MimeType newMt = Utils::mimeTypeForFile(newFilePath); + if (newMt != originalMt) { + const EditorFactories originalFactories = Utils::filtered( + IEditorFactory::preferredEditorTypes(originalFilePath), + &IEditorFactory::isInternalEditor); + const bool originalIsDefault = originalFactories.isEmpty() + ? true + : originalFactories.first()->id() == originalType; + + const EditorFactories newFactories = Utils::filtered( + IEditorFactory::preferredEditorTypes(newFilePath), &IEditorFactory::isInternalEditor); + const Id newDefault = newFactories.isEmpty() ? Id() : newFactories.first()->id(); + const bool defaultIsDifferent = newDefault != originalType; + const auto newContainsOriginal = [originalType, newFactories] { + return Utils::contains(newFactories, [originalType](IEditorFactory *f) { + return f->id() == originalType; + }); + }; + + if ((originalIsDefault && defaultIsDifferent) + || (!originalIsDefault && !newContainsOriginal())) { + QMetaObject::invokeMethod(m_instance, [newFilePath] { + EditorManagerPrivate::openEditorWith(newFilePath, {}); + }); + } + } +} + void EditorManagerPrivate::updateMakeWritableWarning() { IDocument *document = EditorManager::currentDocument(); @@ -2379,8 +2433,9 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document) if (!document) return false; - const FilePath absoluteFilePath = DocumentManager::getSaveAsFileName(document); + const FilePath originalFilePath = document->filePath(); + const FilePath absoluteFilePath = DocumentManager::getSaveAsFileName(document); if (absoluteFilePath.isEmpty()) return false; @@ -2396,12 +2451,6 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document) const bool success = DocumentManager::saveDocument(document, absoluteFilePath); document->checkPermissions(); - // TODO: There is an issue to be treated here. The new file might be of a different mime - // type than the original and thus require a different editor. An alternative strategy - // would be to close the current editor and open a new appropriate one, but this is not - // a good way out either (also the undo stack would be lost). Perhaps the best is to - // re-think part of the editors design. - if (success) { // if document had been temporary before (scratch buffer) - remove the temporary flag document->setTemporary(false); @@ -2411,6 +2460,8 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document) } updateActions(); + + handleFileRenamed(originalFilePath, document->filePath(), document->id()); return success; } diff --git a/src/plugins/coreplugin/editormanager/editormanager_p.h b/src/plugins/coreplugin/editormanager/editormanager_p.h index dba39035838..7e6430621a2 100644 --- a/src/plugins/coreplugin/editormanager/editormanager_p.h +++ b/src/plugins/coreplugin/editormanager/editormanager_p.h @@ -117,6 +117,11 @@ public: static void updateAutoSave(); + static void handleFileRenamed( + const Utils::FilePath &originalFilePath, + const Utils::FilePath &newFilePath, + Utils::Id originalType = {}); + public slots: static bool saveDocument(Core::IDocument *document); static bool saveDocumentAs(Core::IDocument *document); From 1e3750c5bed88ba85e2778ad8c8fc5c665e5c7f6 Mon Sep 17 00:00:00 2001 From: Sami Shalayel Date: Thu, 14 Mar 2024 16:36:38 +0100 Subject: [PATCH 0129/1060] qmlls: add checkbox for generating qmlls ini files Add a checkbox to the qmljseditingsettingspage that generates qmlls ini files by default for new projects. If this checkbox is checked, then initial CMake configurations (when enabling a kit for a project) and reconfigurations (when pressing the "Re-configure with Initial parameters"-button) will set QT_QML_GENERATE_QMLLS_INI to ON if QT_QML_GENERATE_QMLLS_INI was not set yet. Fixes: QTCREATORBUG-30394 Change-Id: I58f89558d25ef107e501bd67702f26554bd6aeaa Reviewed-by: hjk Reviewed-by: David Schulz Reviewed-by: Cristian Adam --- .../cmakebuildconfiguration.cpp | 18 ++++++++++++++++++ .../qmljseditor/qmljseditingsettingspage.cpp | 13 ++++++++++++- src/plugins/qmljseditor/qmllssettings.h | 4 +++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp index 762499aaf73..1b493a18aa9 100644 --- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp +++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp @@ -94,6 +94,7 @@ const char CMAKE_BUILD_TYPE[] = "CMake.Build.Type"; const char CLEAR_SYSTEM_ENVIRONMENT_KEY[] = "CMake.Configure.ClearSystemEnvironment"; const char USER_ENVIRONMENT_CHANGES_KEY[] = "CMake.Configure.UserEnvironmentChanges"; const char BASE_ENVIRONMENT_KEY[] = "CMake.Configure.BaseEnvironment"; +const char GENERATE_QMLLS_INI_SETTING[] = "J.QtQuick/QmlJSEditor.GenerateQmllsIniFiles"; namespace Internal { @@ -606,6 +607,18 @@ void CMakeBuildSettingsWidget::updateInitialCMakeArguments() { CMakeConfig initialList = m_buildConfig->initialCMakeArguments.cmakeConfiguration(); + // set QT_QML_GENERATE_QMLLS_INI if it is enabled via the settings checkbox and if its not part + // of the initial CMake arguments yet + if (Core::ICore::settings()->value(GENERATE_QMLLS_INI_SETTING).toBool()) { + if (std::none_of( + initialList.constBegin(), initialList.constEnd(), [](const CMakeConfigItem &item) { + return item.key == "QT_QML_GENERATE_QMLLS_INI"; + })) { + initialList.append( + CMakeConfigItem("QT_QML_GENERATE_QMLLS_INI", CMakeConfigItem::BOOL, "ON")); + } + } + for (const CMakeConfigItem &ci : m_buildConfig->cmakeBuildSystem()->configurationChanges()) { if (!ci.isInitial) continue; @@ -1544,6 +1557,11 @@ CMakeBuildConfiguration::CMakeBuildConfiguration(Target *target, Id id) if (qt && qt->isQmlDebuggingSupported()) cmd.addArg("-DCMAKE_CXX_FLAGS_INIT:STRING=%{" + QLatin1String(QT_QML_DEBUG_FLAG) + "}"); + // QT_QML_GENERATE_QMLLS_INI, if enabled via the settings checkbox: + if (Core::ICore::settings()->value(GENERATE_QMLLS_INI_SETTING).toBool()) { + cmd.addArg("-DQT_QML_GENERATE_QMLLS_INI:BOOL=ON"); + } + CMakeProject *cmakeProject = static_cast(target->project()); configureEnv.setUserEnvironmentChanges( getEnvironmentItemsFromCMakeConfigurePreset(cmakeProject, k)); diff --git a/src/plugins/qmljseditor/qmljseditingsettingspage.cpp b/src/plugins/qmljseditor/qmljseditingsettingspage.cpp index 11c7985fd1c..f12d1ea57ae 100644 --- a/src/plugins/qmljseditor/qmljseditingsettingspage.cpp +++ b/src/plugins/qmljseditor/qmljseditingsettingspage.cpp @@ -35,6 +35,7 @@ const char FOLD_AUX_DATA[] = "QmlJSEditor.FoldAuxData"; const char USE_QMLLS[] = "QmlJSEditor.UseQmlls"; const char USE_LATEST_QMLLS[] = "QmlJSEditor.UseLatestQmlls"; const char DISABLE_BUILTIN_CODEMODEL[] = "QmlJSEditor.DisableBuiltinCodemodel"; +const char GENERATE_QMLLS_INI_FILES[] = "QmlJSEditor.GenerateQmllsIniFiles"; const char UIQML_OPEN_MODE[] = "QmlJSEditor.openUiQmlMode"; const char FORMAT_COMMAND[] = "QmlJSEditor.formatCommand"; const char FORMAT_COMMAND_OPTIONS[] = "QmlJSEditor.formatCommandOptions"; @@ -107,6 +108,8 @@ void QmlJsEditingSettings::fromSettings(QtcSettings *settings) m_qmllsSettings.useLatestQmlls = settings->value(USE_LATEST_QMLLS, QVariant(false)).toBool(); m_qmllsSettings.disableBuiltinCodemodel = settings->value(DISABLE_BUILTIN_CODEMODEL, QVariant(false)).toBool(); + m_qmllsSettings.generateQmllsIniFiles + = settings->value(GENERATE_QMLLS_INI_FILES, QVariant(false)).toBool(); m_formatCommand = settings->value(FORMAT_COMMAND, {}).toString(); m_formatCommandOptions = settings->value(FORMAT_COMMAND_OPTIONS, {}).toString(); m_useCustomFormatCommand = settings->value(CUSTOM_COMMAND, QVariant(false)).toBool(); @@ -135,6 +138,7 @@ void QmlJsEditingSettings::toSettings(QtcSettings *settings) const settings->setValue(USE_QMLLS, m_qmllsSettings.useQmlls); settings->setValue(USE_LATEST_QMLLS, m_qmllsSettings.useLatestQmlls); settings->setValue(DISABLE_BUILTIN_CODEMODEL, m_qmllsSettings.disableBuiltinCodemodel); + settings->setValue(GENERATE_QMLLS_INI_FILES, m_qmllsSettings.generateQmllsIniFiles); settings->setValueWithDefault(FORMAT_COMMAND, m_formatCommand, {}); settings->setValueWithDefault(FORMAT_COMMAND_OPTIONS, m_formatCommandOptions, {}); settings->setValueWithDefault(CUSTOM_COMMAND, m_useCustomFormatCommand, false); @@ -402,9 +406,14 @@ public: useLatestQmlls = new QCheckBox(Tr::tr("Use QML Language Server from latest Qt version")); useLatestQmlls->setChecked(s.qmllsSettings().useLatestQmlls); useLatestQmlls->setEnabled(s.qmllsSettings().useQmlls); + generateQmllsIniFiles = new QCheckBox( + Tr::tr("Generate QML Language Server .qmlls.ini configurations for new projects.")); + generateQmllsIniFiles->setChecked(s.qmllsSettings().generateQmllsIniFiles); + generateQmllsIniFiles->setEnabled(s.qmllsSettings().useQmlls); QObject::connect(useQmlls, &QCheckBox::stateChanged, this, [this](int checked) { useLatestQmlls->setEnabled(checked != Qt::Unchecked); disableBuiltInCodemodel->setEnabled(checked != Qt::Unchecked); + generateQmllsIniFiles->setEnabled(checked != Qt::Unchecked); }); useCustomAnalyzer = new QCheckBox(Tr::tr("Use customized static analyzer")); @@ -457,7 +466,7 @@ public: }, Group{ title(Tr::tr("QML Language Server")), - Column{useQmlls, disableBuiltInCodemodel , useLatestQmlls}, + Column{useQmlls, disableBuiltInCodemodel , useLatestQmlls, generateQmllsIniFiles}, }, Group { title(Tr::tr("Static Analyzer")), @@ -503,6 +512,7 @@ public: s.qmllsSettings().useQmlls = useQmlls->isChecked(); s.qmllsSettings().disableBuiltinCodemodel = disableBuiltInCodemodel->isChecked(); s.qmllsSettings().useLatestQmlls = useLatestQmlls->isChecked(); + s.qmllsSettings().generateQmllsIniFiles = generateQmllsIniFiles->isChecked(); s.setUseCustomAnalyzer(useCustomAnalyzer->isChecked()); QSet disabled; QSet disabledForNonQuickUi; @@ -561,6 +571,7 @@ private: QCheckBox *useQmlls; QCheckBox *useLatestQmlls; QCheckBox *disableBuiltInCodemodel; + QCheckBox *generateQmllsIniFiles; QComboBox *uiQmlOpenComboBox; QCheckBox *useCustomAnalyzer; QTreeView *analyzerMessagesView; diff --git a/src/plugins/qmljseditor/qmllssettings.h b/src/plugins/qmljseditor/qmllssettings.h index 32890d3762a..90d8ff6ca8f 100644 --- a/src/plugins/qmljseditor/qmllssettings.h +++ b/src/plugins/qmljseditor/qmllssettings.h @@ -16,11 +16,13 @@ struct QmllsSettings bool useQmlls = true; bool useLatestQmlls = false; bool disableBuiltinCodemodel = false; + bool generateQmllsIniFiles = false; friend bool operator==(const QmllsSettings &s1, const QmllsSettings &s2) { return s1.useQmlls == s2.useQmlls && s1.useLatestQmlls == s2.useLatestQmlls - && s1.disableBuiltinCodemodel == s2.disableBuiltinCodemodel; + && s1.disableBuiltinCodemodel == s2.disableBuiltinCodemodel + && s1.generateQmllsIniFiles == s2.generateQmllsIniFiles; } friend bool operator!=(const QmllsSettings &s1, const QmllsSettings &s2) { return !(s1 == s2); } }; From a583436365d39778b86567f49a8efbb19f777f78 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Wed, 10 Apr 2024 17:04:05 +0200 Subject: [PATCH 0130/1060] TaskTree: Zero-initialize the Storage Change-Id: I9d5ee11285b377abafe21d472481c941f49a5ae1 Reviewed-by: Reviewed-by: Marcus Tillmanns --- src/libs/solutions/tasking/tasktree.h | 2 +- tests/auto/solutions/tasking/tst_tasking.cpp | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/libs/solutions/tasking/tasktree.h b/src/libs/solutions/tasking/tasktree.h index 8ea255303ba..ef41fa4b2b6 100644 --- a/src/libs/solutions/tasking/tasktree.h +++ b/src/libs/solutions/tasking/tasktree.h @@ -187,7 +187,7 @@ public: } private: - static StorageConstructor ctor() { return [] { return new StorageStruct; }; } + static StorageConstructor ctor() { return [] { return new StorageStruct(); }; } static StorageDestructor dtor() { return [](void *storage) { delete static_cast(storage); }; } diff --git a/tests/auto/solutions/tasking/tst_tasking.cpp b/tests/auto/solutions/tasking/tst_tasking.cpp index ee1972c0616..95de5b44b3f 100644 --- a/tests/auto/solutions/tasking/tst_tasking.cpp +++ b/tests/auto/solutions/tasking/tst_tasking.cpp @@ -117,6 +117,7 @@ private slots: void storageIO(); void storageOperators(); void storageDestructor(); + void storageZeroInitialization(); void restart(); void destructorOfTaskEmittingDone(); }; @@ -3380,7 +3381,7 @@ void tst_Tasking::storageDestructor() }; QCOMPARE(CustomStorage::instanceCount(), 0); { - Storage storage; + const Storage storage; const auto setupSleepingTask = [](TaskObject &taskObject) { taskObject = 1000ms; }; @@ -3401,6 +3402,21 @@ void tst_Tasking::storageDestructor() QVERIFY(!doneCalled); } +// This test ensures that the storage data is zero-initialized. +void tst_Tasking::storageZeroInitialization() +{ + const Storage storage; + std::optional defaultValue; + + const auto onSetup = [storage, &defaultValue] { defaultValue = *storage; }; + + TaskTree taskTree({ storage, onGroupSetup(onSetup) }); + taskTree.runBlocking(); + + QVERIFY(defaultValue); + QCOMPARE(defaultValue, 0); +} + void tst_Tasking::restart() { TaskTree taskTree({TestTask([](TaskObject &taskObject) { taskObject = 1000ms; })}); From 459cb8274407ea6d5d52a0ad27e969a542d3b664 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 10 Apr 2024 17:52:30 +0200 Subject: [PATCH 0131/1060] LanguageClient: Update call hierarchy on double click on item This seems sensible and is also consistent with how the type hierarchy widget behaves. Fixes: QTCREATORBUG-28843 Change-Id: I2423fda68ab2a9624206b8c93f2490e1a7196173 Reviewed-by: David Schulz --- src/plugins/languageclient/callandtypehierarchy.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/plugins/languageclient/callandtypehierarchy.cpp b/src/plugins/languageclient/callandtypehierarchy.cpp index 14e5935c6a3..d759ea35341 100644 --- a/src/plugins/languageclient/callandtypehierarchy.cpp +++ b/src/plugins/languageclient/callandtypehierarchy.cpp @@ -311,7 +311,11 @@ private: virtual void sendRequest(Client *client, const TextDocumentPositionParams ¶ms, const Core::IDocument *document) = 0; - virtual void onItemDoubleClicked(const QModelIndex &index) { Q_UNUSED(index) } + void onItemDoubleClicked(const QModelIndex &index) + { + if (const auto link = index.data(LinkRole).value(); link.hasValidTarget()) + updateHierarchyAtCursorPosition(); + } void onItemActivated(const QModelIndex &index) { @@ -392,12 +396,6 @@ private: client->sendMessage(request); } - void onItemDoubleClicked(const QModelIndex &index) override - { - if (const auto link = index.data(LinkRole).value(); link.hasValidTarget()) - reload(); - } - void handlePrepareResponse(Client *client, const PrepareTypeHierarchyRequest::Response &response) { From 4b29ad78e3f8f8917767818d97e29c7b9f8c4686 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 10 Apr 2024 16:22:48 +0200 Subject: [PATCH 0132/1060] CppEditor: Move ClangdSettingsPage alongside ClangdSettings Change-Id: Ib22438817ff3a14904decbb23f3c2288f355e378 Reviewed-by: David Schulz Reviewed-by: --- src/plugins/cppeditor/clangdsettings.cpp | 540 +++++++++++++++++- src/plugins/cppeditor/clangdsettings.h | 5 + .../cppeditor/cppcodemodelsettingspage.cpp | 527 +---------------- .../cppeditor/cppcodemodelsettingspage.h | 2 - src/plugins/cppeditor/cppeditorplugin.cpp | 1 + 5 files changed, 546 insertions(+), 529 deletions(-) diff --git a/src/plugins/cppeditor/clangdsettings.cpp b/src/plugins/cppeditor/clangdsettings.cpp index b5352af6d83..253914704a0 100644 --- a/src/plugins/cppeditor/clangdsettings.cpp +++ b/src/plugins/cppeditor/clangdsettings.cpp @@ -4,19 +4,41 @@ #include "clangdsettings.h" #include "clangdiagnosticconfigsmodel.h" +#include "clangdiagnosticconfigsselectionwidget.h" +#include "clangdiagnosticconfigswidget.h" #include "cppeditorconstants.h" #include "cppeditortr.h" #include "cpptoolsreuse.h" +#include #include #include #include +#include +#include #include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include #include +#include + +using namespace ProjectExplorer; using namespace Utils; namespace CppEditor { @@ -338,7 +360,7 @@ void ClangdSettings::setClangdFilePath(const FilePath &filePath) } #endif -ClangdProjectSettings::ClangdProjectSettings(ProjectExplorer::Project *project) : m_project(project) +ClangdProjectSettings::ClangdProjectSettings(Project *project) : m_project(project) { loadSettings(); } @@ -488,4 +510,520 @@ int ClangdSettings::Data::defaultCompletionResults() return ok ? userValue : 100; } +namespace Internal { +class ClangdSettingsWidget final : public QWidget +{ + Q_OBJECT + +public: + ClangdSettingsWidget(const ClangdSettings::Data &settingsData, bool isForProject); + + ClangdSettings::Data settingsData() const; + +signals: + void settingsDataChanged(); + +private: + QCheckBox m_useClangdCheckBox; + QComboBox m_indexingComboBox; + Utils::FancyLineEdit m_projectIndexPathTemplateLineEdit; + Utils::FancyLineEdit m_sessionIndexPathTemplateLineEdit; + QComboBox m_headerSourceSwitchComboBox; + QComboBox m_completionRankingModelComboBox; + QCheckBox m_autoIncludeHeadersCheckBox; + QCheckBox m_sizeThresholdCheckBox; + QSpinBox m_threadLimitSpinBox; + QSpinBox m_documentUpdateThreshold; + QSpinBox m_sizeThresholdSpinBox; + QSpinBox m_completionResults; + Utils::PathChooser m_clangdChooser; + Utils::InfoLabel m_versionWarningLabel; + ClangDiagnosticConfigsSelectionWidget *m_configSelectionWidget = nullptr; + QGroupBox *m_sessionsGroupBox = nullptr; + QStringListModel m_sessionsModel; +}; + +ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsData, + bool isForProject) +{ + const ClangdSettings settings(settingsData); + const QString indexingToolTip = Tr::tr( + "

    If background indexing is enabled, global symbol searches will yield more accurate " + "results, at the cost of additional CPU load when the project is first opened. The " + "indexing result is persisted in the project's build directory. If you disable background " + "indexing, a faster, but less accurate, built-in indexer is used instead. The thread " + "priority for building the background index can be adjusted since clangd 15.

    " + "

    Background Priority: Minimum priority, runs on idle CPUs. May leave 'performance' " + "cores unused.

    " + "

    Normal Priority: Reduced priority compared to interactive work.

    " + "

    Low Priority: Same priority as other clangd work.

    "); + const QString projectIndexPathToolTip = Tr::tr( + "The location of the per-project clangd index.

    " + "This is also where the compile_commands.json file will go."); + const QString sessionIndexPathToolTip = Tr::tr( + "The location of the per-session clangd index.

    " + "This is also where the compile_commands.json file will go."); + const QString headerSourceSwitchToolTip = Tr::tr( + "

    The C/C++ backend to use for switching between header and source files.

    " + "

    While the clangd implementation has more capabilities than the built-in " + "code model, it tends to find false positives.

    " + "

    When \"Try Both\" is selected, clangd is used only if the built-in variant " + "does not find anything.

    "); + using RankingModel = ClangdSettings::CompletionRankingModel; + const QString completionRankingModelToolTip = Tr::tr( + "

    Which model clangd should use to rank possible completions.

    " + "

    This determines the order of candidates in the combo box when doing code completion.

    " + "

    The \"%1\" model used by default results from (pre-trained) machine learning and " + "provides superior results on average.

    " + "

    If you feel that its suggestions stray too much from your expectations for your " + "code base, you can try switching to the hand-crafted \"%2\" model.

    ").arg( + ClangdSettings::rankingModelToDisplayString(RankingModel::DecisionForest), + ClangdSettings::rankingModelToDisplayString(RankingModel::Heuristics)); + const QString workerThreadsToolTip = Tr::tr( + "Number of worker threads used by clangd. Background indexing also uses this many " + "worker threads."); + const QString autoIncludeToolTip = Tr::tr( + "Controls whether clangd may insert header files as part of symbol completion."); + const QString documentUpdateToolTip + //: %1 is the application name (Qt Creator) + = Tr::tr("Defines the amount of time %1 waits before sending document changes to the " + "server.\n" + "If the document changes again while waiting, this timeout resets.") + .arg(QGuiApplication::applicationDisplayName()); + const QString sizeThresholdToolTip = Tr::tr( + "Files greater than this will not be opened as documents in clangd.\n" + "The built-in code model will handle highlighting, completion and so on."); + const QString completionResultToolTip = Tr::tr( + "The maximum number of completion results returned by clangd."); + + m_useClangdCheckBox.setText(Tr::tr("Use clangd")); + m_useClangdCheckBox.setChecked(settings.useClangd()); + m_clangdChooser.setExpectedKind(Utils::PathChooser::ExistingCommand); + m_clangdChooser.setFilePath(settings.clangdFilePath()); + m_clangdChooser.setAllowPathFromDevice(true); + m_clangdChooser.setEnabled(m_useClangdCheckBox.isChecked()); + m_clangdChooser.setCommandVersionArguments({"--version"}); + using Priority = ClangdSettings::IndexingPriority; + for (Priority prio : {Priority::Off, Priority::Background, Priority::Low, Priority::Normal}) { + m_indexingComboBox.addItem(ClangdSettings::priorityToDisplayString(prio), int(prio)); + if (prio == settings.indexingPriority()) + m_indexingComboBox.setCurrentIndex(m_indexingComboBox.count() - 1); + } + m_indexingComboBox.setToolTip(indexingToolTip); + m_projectIndexPathTemplateLineEdit.setText(settings.data().projectIndexPathTemplate); + m_sessionIndexPathTemplateLineEdit.setText(settings.data().sessionIndexPathTemplate); + using SwitchMode = ClangdSettings::HeaderSourceSwitchMode; + for (SwitchMode mode : {SwitchMode::BuiltinOnly, SwitchMode::ClangdOnly, SwitchMode::Both}) { + m_headerSourceSwitchComboBox.addItem( + ClangdSettings::headerSourceSwitchModeToDisplayString(mode), int(mode)); + if (mode == settings.headerSourceSwitchMode()) + m_headerSourceSwitchComboBox.setCurrentIndex( + m_headerSourceSwitchComboBox.count() - 1); + } + m_headerSourceSwitchComboBox.setToolTip(headerSourceSwitchToolTip); + for (RankingModel model : {RankingModel::Default, RankingModel::DecisionForest, + RankingModel::Heuristics}) { + m_completionRankingModelComboBox.addItem( + ClangdSettings::rankingModelToDisplayString(model), int(model)); + if (model == settings.completionRankingModel()) + m_completionRankingModelComboBox.setCurrentIndex( + m_completionRankingModelComboBox.count() - 1); + } + m_completionRankingModelComboBox.setToolTip(completionRankingModelToolTip); + + m_autoIncludeHeadersCheckBox.setText(Tr::tr("Insert header files on completion")); + m_autoIncludeHeadersCheckBox.setChecked(settings.autoIncludeHeaders()); + m_autoIncludeHeadersCheckBox.setToolTip(autoIncludeToolTip); + m_threadLimitSpinBox.setValue(settings.workerThreadLimit()); + m_threadLimitSpinBox.setSpecialValueText(Tr::tr("Automatic")); + m_threadLimitSpinBox.setToolTip(workerThreadsToolTip); + m_documentUpdateThreshold.setMinimum(50); + m_documentUpdateThreshold.setMaximum(10000); + m_documentUpdateThreshold.setValue(settings.documentUpdateThreshold()); + m_documentUpdateThreshold.setSingleStep(100); + m_documentUpdateThreshold.setSuffix(" ms"); + m_documentUpdateThreshold.setToolTip(documentUpdateToolTip); + m_sizeThresholdCheckBox.setText(Tr::tr("Ignore files greater than")); + m_sizeThresholdCheckBox.setChecked(settings.sizeThresholdEnabled()); + m_sizeThresholdCheckBox.setToolTip(sizeThresholdToolTip); + m_sizeThresholdSpinBox.setMinimum(1); + m_sizeThresholdSpinBox.setMaximum(std::numeric_limits::max()); + m_sizeThresholdSpinBox.setSuffix(" KB"); + m_sizeThresholdSpinBox.setValue(settings.sizeThresholdInKb()); + m_sizeThresholdSpinBox.setToolTip(sizeThresholdToolTip); + + const auto completionResultsLabel = new QLabel(Tr::tr("Completion results:")); + completionResultsLabel->setToolTip(completionResultToolTip); + m_completionResults.setMinimum(0); + m_completionResults.setMaximum(std::numeric_limits::max()); + m_completionResults.setValue(settings.completionResults()); + m_completionResults.setToolTip(completionResultToolTip); + m_completionResults.setSpecialValueText(Tr::tr("No limit")); + + const auto layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(&m_useClangdCheckBox); + + const auto formLayout = new QFormLayout; + const auto chooserLabel = new QLabel(Tr::tr("Path to executable:")); + formLayout->addRow(chooserLabel, &m_clangdChooser); + formLayout->addRow(QString(), &m_versionWarningLabel); + + const auto indexingPriorityLayout = new QHBoxLayout; + indexingPriorityLayout->addWidget(&m_indexingComboBox); + indexingPriorityLayout->addStretch(1); + const auto indexingPriorityLabel = new QLabel(Tr::tr("Background indexing:")); + indexingPriorityLabel->setToolTip(indexingToolTip); + formLayout->addRow(indexingPriorityLabel, indexingPriorityLayout); + + for (const auto &[text, edit, toolTip, defaultValue] : + {std::make_tuple(Tr::tr("Per-project index location:"), + &m_projectIndexPathTemplateLineEdit, + projectIndexPathToolTip, + ClangdSettings::defaultProjectIndexPathTemplate()), + std::make_tuple(Tr::tr("Per-session index location:"), + &m_sessionIndexPathTemplateLineEdit, + sessionIndexPathToolTip, + ClangdSettings::defaultSessionIndexPathTemplate())}) { + if (isForProject && edit == &m_sessionIndexPathTemplateLineEdit) + continue; + + const auto chooser = new Utils::VariableChooser(edit); + chooser->addSupportedWidget(edit); + chooser->addMacroExpanderProvider([] { return Utils::globalMacroExpander(); }); + + const auto resetButton = new QPushButton(Tr::tr("Reset")); + connect(resetButton, &QPushButton::clicked, [e = edit, v = defaultValue] { e->setText(v); }); + const auto layout = new QHBoxLayout; + const auto label = new QLabel(text); + label->setToolTip(toolTip); + edit->setToolTip(toolTip); + layout->addWidget(edit); + layout->addWidget(resetButton); + formLayout->addRow(label, layout); + } + + const auto headerSourceSwitchLayout = new QHBoxLayout; + headerSourceSwitchLayout->addWidget(&m_headerSourceSwitchComboBox); + headerSourceSwitchLayout->addStretch(1); + const auto headerSourceSwitchLabel = new QLabel(Tr::tr("Header/source switch mode:")); + headerSourceSwitchLabel->setToolTip(headerSourceSwitchToolTip); + formLayout->addRow(headerSourceSwitchLabel, headerSourceSwitchLayout); + + const auto threadLimitLayout = new QHBoxLayout; + threadLimitLayout->addWidget(&m_threadLimitSpinBox); + threadLimitLayout->addStretch(1); + const auto threadLimitLabel = new QLabel(Tr::tr("Worker thread count:")); + threadLimitLabel->setToolTip(workerThreadsToolTip); + formLayout->addRow(threadLimitLabel, threadLimitLayout); + + formLayout->addRow(QString(), &m_autoIncludeHeadersCheckBox); + const auto limitResultsLayout = new QHBoxLayout; + limitResultsLayout->addWidget(&m_completionResults); + limitResultsLayout->addStretch(1); + formLayout->addRow(completionResultsLabel, limitResultsLayout); + + const auto completionRankingModelLayout = new QHBoxLayout; + completionRankingModelLayout->addWidget(&m_completionRankingModelComboBox); + completionRankingModelLayout->addStretch(1); + const auto completionRankingModelLabel = new QLabel(Tr::tr("Completion ranking model:")); + completionRankingModelLabel->setToolTip(completionRankingModelToolTip); + formLayout->addRow(completionRankingModelLabel, completionRankingModelLayout); + + const auto documentUpdateThresholdLayout = new QHBoxLayout; + documentUpdateThresholdLayout->addWidget(&m_documentUpdateThreshold); + documentUpdateThresholdLayout->addStretch(1); + const auto documentUpdateThresholdLabel = new QLabel(Tr::tr("Document update threshold:")); + documentUpdateThresholdLabel->setToolTip(documentUpdateToolTip); + formLayout->addRow(documentUpdateThresholdLabel, documentUpdateThresholdLayout); + const auto sizeThresholdLayout = new QHBoxLayout; + sizeThresholdLayout->addWidget(&m_sizeThresholdSpinBox); + sizeThresholdLayout->addStretch(1); + formLayout->addRow(&m_sizeThresholdCheckBox, sizeThresholdLayout); + + m_configSelectionWidget = new ClangDiagnosticConfigsSelectionWidget(formLayout); + m_configSelectionWidget->refresh( + diagnosticConfigsModel(settings.customDiagnosticConfigs()), + settings.diagnosticConfigId(), + [](const ClangDiagnosticConfigs &configs, const Utils::Id &configToSelect) { + return new CppEditor::ClangDiagnosticConfigsWidget(configs, configToSelect); + }); + + layout->addLayout(formLayout); + if (!isForProject) { + m_sessionsModel.setStringList(settingsData.sessionsWithOneClangd); + m_sessionsModel.sort(0); + m_sessionsGroupBox = new QGroupBox(Tr::tr("Sessions with a single clangd instance")); + const auto sessionsView = new Utils::ListView; + sessionsView->setModel(&m_sessionsModel); + sessionsView->setToolTip( + Tr::tr("By default, Qt Creator runs one clangd process per project.\n" + "If you have sessions with tightly coupled projects that should be\n" + "managed by the same clangd process, add them here.")); + const auto outerSessionsLayout = new QHBoxLayout; + const auto innerSessionsLayout = new QHBoxLayout(m_sessionsGroupBox); + const auto buttonsLayout = new QVBoxLayout; + const auto addButton = new QPushButton(Tr::tr("Add ...")); + const auto removeButton = new QPushButton(Tr::tr("Remove")); + buttonsLayout->addWidget(addButton); + buttonsLayout->addWidget(removeButton); + buttonsLayout->addStretch(1); + innerSessionsLayout->addWidget(sessionsView); + innerSessionsLayout->addLayout(buttonsLayout); + outerSessionsLayout->addWidget(m_sessionsGroupBox); + outerSessionsLayout->addStretch(1); + + const auto separator = new QFrame; + separator->setFrameShape(QFrame::HLine); + layout->addWidget(separator); + layout->addLayout(outerSessionsLayout); + + const auto updateRemoveButtonState = [removeButton, sessionsView] { + removeButton->setEnabled(sessionsView->selectionModel()->hasSelection()); + }; + connect(sessionsView->selectionModel(), &QItemSelectionModel::selectionChanged, + this, updateRemoveButtonState); + updateRemoveButtonState(); + connect(removeButton, &QPushButton::clicked, this, [this, sessionsView] { + const QItemSelection selection = sessionsView->selectionModel()->selection(); + QTC_ASSERT(!selection.isEmpty(), return); + m_sessionsModel.removeRow(selection.indexes().first().row()); + }); + + connect(addButton, &QPushButton::clicked, this, [this, sessionsView] { + QInputDialog dlg(sessionsView); + QStringList sessions = Core::SessionManager::sessions(); + QStringList currentSessions = m_sessionsModel.stringList(); + for (const QString &s : std::as_const(currentSessions)) + sessions.removeOne(s); + if (sessions.isEmpty()) + return; + sessions.sort(); + dlg.setLabelText(Tr::tr("Choose a session:")); + dlg.setComboBoxItems(sessions); + if (dlg.exec() == QDialog::Accepted) { + currentSessions << dlg.textValue(); + m_sessionsModel.setStringList(currentSessions); + m_sessionsModel.sort(0); + } + }); + } + + const auto configFilesHelpLabel = new QLabel; + configFilesHelpLabel->setText(Tr::tr("Additional settings are available via " + " clangd configuration files.
    " + "User-specific settings go here, " + "project-specific settings can be configured by putting a .clangd file into " + "the project source tree.") + .arg(ClangdSettings::clangdUserConfigFilePath().toUserOutput())); + configFilesHelpLabel->setWordWrap(true); + connect(configFilesHelpLabel, &QLabel::linkHovered, configFilesHelpLabel, &QLabel::setToolTip); + connect(configFilesHelpLabel, &QLabel::linkActivated, [](const QString &link) { + if (link.startsWith("https")) + QDesktopServices::openUrl(link); + else + Core::EditorManager::openEditor(Utils::FilePath::fromString(link)); + }); + layout->addWidget(Layouting::createHr()); + layout->addWidget(configFilesHelpLabel); + + layout->addStretch(1); + + static const auto setWidgetsEnabled = [](QLayout *layout, bool enabled, const auto &f) -> void { + for (int i = 0; i < layout->count(); ++i) { + if (QWidget * const w = layout->itemAt(i)->widget()) + w->setEnabled(enabled); + else if (QLayout * const l = layout->itemAt(i)->layout()) + f(l, enabled, f); + } + }; + const auto toggleEnabled = [this, formLayout](const bool checked) { + setWidgetsEnabled(formLayout, checked, setWidgetsEnabled); + if (m_sessionsGroupBox) + m_sessionsGroupBox->setEnabled(checked); + }; + connect(&m_useClangdCheckBox, &QCheckBox::toggled, toggleEnabled); + toggleEnabled(m_useClangdCheckBox.isChecked()); + m_threadLimitSpinBox.setEnabled(m_useClangdCheckBox.isChecked()); + + m_versionWarningLabel.setType(Utils::InfoLabel::Warning); + const auto updateWarningLabel = [this] { + class WarningLabelSetter { + public: + WarningLabelSetter(QLabel &label) : m_label(label) { m_label.clear(); } + ~WarningLabelSetter() { m_label.setVisible(!m_label.text().isEmpty()); } + void setWarning(const QString &text) { m_label.setText(text); } + private: + QLabel &m_label; + }; + WarningLabelSetter labelSetter(m_versionWarningLabel); + + if (!m_clangdChooser.isValid()) + return; + const Utils::FilePath clangdPath = m_clangdChooser.filePath(); + QString errorMessage; + if (!Utils::checkClangdVersion(clangdPath, &errorMessage)) + labelSetter.setWarning(errorMessage); + }; + connect(&m_clangdChooser, &Utils::PathChooser::textChanged, this, updateWarningLabel); + connect(&m_clangdChooser, &Utils::PathChooser::validChanged, this, updateWarningLabel); + updateWarningLabel(); + + connect(&m_useClangdCheckBox, &QCheckBox::toggled, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_indexingComboBox, &QComboBox::currentIndexChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_projectIndexPathTemplateLineEdit, &QLineEdit::textChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_sessionIndexPathTemplateLineEdit, &QLineEdit::textChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_headerSourceSwitchComboBox, &QComboBox::currentIndexChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_completionRankingModelComboBox, &QComboBox::currentIndexChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_autoIncludeHeadersCheckBox, &QCheckBox::toggled, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_threadLimitSpinBox, &QSpinBox::valueChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_sizeThresholdCheckBox, &QCheckBox::toggled, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_sizeThresholdSpinBox, &QSpinBox::valueChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_documentUpdateThreshold, &QSpinBox::valueChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_clangdChooser, &Utils::PathChooser::textChanged, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(m_configSelectionWidget, &ClangDiagnosticConfigsSelectionWidget::changed, + this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_completionResults, &QSpinBox::valueChanged, + this, &ClangdSettingsWidget::settingsDataChanged); +} + +ClangdSettings::Data ClangdSettingsWidget::settingsData() const +{ + ClangdSettings::Data data; + data.useClangd = m_useClangdCheckBox.isChecked(); + data.executableFilePath = m_clangdChooser.filePath(); + data.indexingPriority = ClangdSettings::IndexingPriority( + m_indexingComboBox.currentData().toInt()); + data.projectIndexPathTemplate = m_projectIndexPathTemplateLineEdit.text(); + data.sessionIndexPathTemplate = m_sessionIndexPathTemplateLineEdit.text(); + data.headerSourceSwitchMode = ClangdSettings::HeaderSourceSwitchMode( + m_headerSourceSwitchComboBox.currentData().toInt()); + data.completionRankingModel = ClangdSettings::CompletionRankingModel( + m_completionRankingModelComboBox.currentData().toInt()); + data.autoIncludeHeaders = m_autoIncludeHeadersCheckBox.isChecked(); + data.workerThreadLimit = m_threadLimitSpinBox.value(); + data.documentUpdateThreshold = m_documentUpdateThreshold.value(); + data.sizeThresholdEnabled = m_sizeThresholdCheckBox.isChecked(); + data.sizeThresholdInKb = m_sizeThresholdSpinBox.value(); + data.sessionsWithOneClangd = m_sessionsModel.stringList(); + data.customDiagnosticConfigs = m_configSelectionWidget->customConfigs(); + data.diagnosticConfigId = m_configSelectionWidget->currentConfigId(); + data.completionResults = m_completionResults.value(); + return data; +} + +class ClangdSettingsPageWidget final : public Core::IOptionsPageWidget +{ +public: + ClangdSettingsPageWidget() : m_widget(ClangdSettings::instance().data(), false) + { + const auto layout = new QVBoxLayout(this); + layout->addWidget(&m_widget); + } + +private: + void apply() final { ClangdSettings::instance().setData(m_widget.settingsData()); } + + ClangdSettingsWidget m_widget; +}; + +class ClangdSettingsPage final : public Core::IOptionsPage +{ +public: + ClangdSettingsPage() + { + setId(Constants::CPP_CLANGD_SETTINGS_ID); + setDisplayName(Tr::tr("Clangd")); + setCategory(Constants::CPP_SETTINGS_CATEGORY); + setWidgetCreator([] { return new ClangdSettingsPageWidget; }); + } +}; + +void setupClangdSettingsPage() +{ + static ClangdSettingsPage theClangdSettingsPage; +} + +class ClangdProjectSettingsWidget : public ProjectSettingsWidget +{ +public: + ClangdProjectSettingsWidget(const ClangdProjectSettings &settings) + : m_settings(settings), m_widget(settings.settings(), true) + { + setGlobalSettingsId(Constants::CPP_CLANGD_SETTINGS_ID); + const auto layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(&m_widget); + + const auto updateGlobalSettingsCheckBox = [this] { + if (ClangdSettings::instance().granularity() == ClangdSettings::Granularity::Session) { + setUseGlobalSettingsCheckBoxEnabled(false); + setUseGlobalSettings(true); + } else { + setUseGlobalSettingsCheckBoxEnabled(true); + setUseGlobalSettings(m_settings.useGlobalSettings()); + } + m_widget.setEnabled(!useGlobalSettings()); + }; + + updateGlobalSettingsCheckBox(); + connect(&ClangdSettings::instance(), &ClangdSettings::changed, + this, updateGlobalSettingsCheckBox); + + connect(this, &ProjectSettingsWidget::useGlobalSettingsChanged, this, + [this](bool checked) { + m_widget.setEnabled(!checked); + m_settings.setUseGlobalSettings(checked); + if (!checked) + m_settings.setSettings(m_widget.settingsData()); + }); + + const auto timer = new QTimer(this); + timer->setSingleShot(true); + timer->setInterval(5000); + connect(timer, &QTimer::timeout, this, [this] { + m_settings.setSettings(m_widget.settingsData()); + }); + connect(&m_widget, &ClangdSettingsWidget::settingsDataChanged, + timer, qOverload<>(&QTimer::start)); + } + +private: + ClangdProjectSettings m_settings; + ClangdSettingsWidget m_widget; +}; + +class ClangdProjectSettingsPanelFactory final : public ProjectPanelFactory +{ +public: + ClangdProjectSettingsPanelFactory() + { + setPriority(100); + setDisplayName(Tr::tr("Clangd")); + setCreateWidgetFunction([](Project *project) { + return new ClangdProjectSettingsWidget(project); + }); + } +}; + +void setupClangdProjectSettingsPanel() +{ + static ClangdProjectSettingsPanelFactory theClangdProjectSettingsPanelFactory; +} + +} // namespace Internal } // namespace CppEditor + +#include diff --git a/src/plugins/cppeditor/clangdsettings.h b/src/plugins/cppeditor/clangdsettings.h index c1fb3b6ae86..f3e66fb9f6b 100644 --- a/src/plugins/cppeditor/clangdsettings.h +++ b/src/plugins/cppeditor/clangdsettings.h @@ -159,4 +159,9 @@ private: bool m_blockIndexing = false; }; +namespace Internal { +void setupClangdProjectSettingsPanel(); +void setupClangdSettingsPage(); +} + } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp index 0e880fcb55b..1b5872c7a3a 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp @@ -3,13 +3,10 @@ #include "cppcodemodelsettingspage.h" -#include "clangdiagnosticconfigsselectionwidget.h" -#include "clangdiagnosticconfigswidget.h" #include "clangdsettings.h" #include "cppcodemodelsettings.h" #include "cppeditorconstants.h" #include "cppeditortr.h" -#include "cpptoolsreuse.h" #include #include @@ -22,30 +19,20 @@ #include #include #include -#include #include #include #include -#include #include #include -#include -#include -#include -#include -#include -#include +#include #include -#include #include #include #include #include #include -#include - using namespace ProjectExplorer; namespace CppEditor::Internal { @@ -232,518 +219,6 @@ void setupCppCodeModelProjectSettingsPanel() static CppCodeModelProjectSettingsPanelFactory factory; } -class ClangdSettingsWidget final : public QWidget -{ - Q_OBJECT - -public: - ClangdSettingsWidget(const ClangdSettings::Data &settingsData, bool isForProject); - - ClangdSettings::Data settingsData() const; - -signals: - void settingsDataChanged(); - -private: - QCheckBox m_useClangdCheckBox; - QComboBox m_indexingComboBox; - Utils::FancyLineEdit m_projectIndexPathTemplateLineEdit; - Utils::FancyLineEdit m_sessionIndexPathTemplateLineEdit; - QComboBox m_headerSourceSwitchComboBox; - QComboBox m_completionRankingModelComboBox; - QCheckBox m_autoIncludeHeadersCheckBox; - QCheckBox m_sizeThresholdCheckBox; - QSpinBox m_threadLimitSpinBox; - QSpinBox m_documentUpdateThreshold; - QSpinBox m_sizeThresholdSpinBox; - QSpinBox m_completionResults; - Utils::PathChooser m_clangdChooser; - Utils::InfoLabel m_versionWarningLabel; - ClangDiagnosticConfigsSelectionWidget *m_configSelectionWidget = nullptr; - QGroupBox *m_sessionsGroupBox = nullptr; - QStringListModel m_sessionsModel; -}; - -ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsData, - bool isForProject) -{ - const ClangdSettings settings(settingsData); - const QString indexingToolTip = Tr::tr( - "

    If background indexing is enabled, global symbol searches will yield more accurate " - "results, at the cost of additional CPU load when the project is first opened. The " - "indexing result is persisted in the project's build directory. If you disable background " - "indexing, a faster, but less accurate, built-in indexer is used instead. The thread " - "priority for building the background index can be adjusted since clangd 15.

    " - "

    Background Priority: Minimum priority, runs on idle CPUs. May leave 'performance' " - "cores unused.

    " - "

    Normal Priority: Reduced priority compared to interactive work.

    " - "

    Low Priority: Same priority as other clangd work.

    "); - const QString projectIndexPathToolTip = Tr::tr( - "The location of the per-project clangd index.

    " - "This is also where the compile_commands.json file will go."); - const QString sessionIndexPathToolTip = Tr::tr( - "The location of the per-session clangd index.

    " - "This is also where the compile_commands.json file will go."); - const QString headerSourceSwitchToolTip = Tr::tr( - "

    The C/C++ backend to use for switching between header and source files.

    " - "

    While the clangd implementation has more capabilities than the built-in " - "code model, it tends to find false positives.

    " - "

    When \"Try Both\" is selected, clangd is used only if the built-in variant " - "does not find anything.

    "); - using RankingModel = ClangdSettings::CompletionRankingModel; - const QString completionRankingModelToolTip = Tr::tr( - "

    Which model clangd should use to rank possible completions.

    " - "

    This determines the order of candidates in the combo box when doing code completion.

    " - "

    The \"%1\" model used by default results from (pre-trained) machine learning and " - "provides superior results on average.

    " - "

    If you feel that its suggestions stray too much from your expectations for your " - "code base, you can try switching to the hand-crafted \"%2\" model.

    ").arg( - ClangdSettings::rankingModelToDisplayString(RankingModel::DecisionForest), - ClangdSettings::rankingModelToDisplayString(RankingModel::Heuristics)); - const QString workerThreadsToolTip = Tr::tr( - "Number of worker threads used by clangd. Background indexing also uses this many " - "worker threads."); - const QString autoIncludeToolTip = Tr::tr( - "Controls whether clangd may insert header files as part of symbol completion."); - const QString documentUpdateToolTip - //: %1 is the application name (Qt Creator) - = Tr::tr("Defines the amount of time %1 waits before sending document changes to the " - "server.\n" - "If the document changes again while waiting, this timeout resets.") - .arg(QGuiApplication::applicationDisplayName()); - const QString sizeThresholdToolTip = Tr::tr( - "Files greater than this will not be opened as documents in clangd.\n" - "The built-in code model will handle highlighting, completion and so on."); - const QString completionResultToolTip = Tr::tr( - "The maximum number of completion results returned by clangd."); - - m_useClangdCheckBox.setText(Tr::tr("Use clangd")); - m_useClangdCheckBox.setChecked(settings.useClangd()); - m_clangdChooser.setExpectedKind(Utils::PathChooser::ExistingCommand); - m_clangdChooser.setFilePath(settings.clangdFilePath()); - m_clangdChooser.setAllowPathFromDevice(true); - m_clangdChooser.setEnabled(m_useClangdCheckBox.isChecked()); - m_clangdChooser.setCommandVersionArguments({"--version"}); - using Priority = ClangdSettings::IndexingPriority; - for (Priority prio : {Priority::Off, Priority::Background, Priority::Low, Priority::Normal}) { - m_indexingComboBox.addItem(ClangdSettings::priorityToDisplayString(prio), int(prio)); - if (prio == settings.indexingPriority()) - m_indexingComboBox.setCurrentIndex(m_indexingComboBox.count() - 1); - } - m_indexingComboBox.setToolTip(indexingToolTip); - m_projectIndexPathTemplateLineEdit.setText(settings.data().projectIndexPathTemplate); - m_sessionIndexPathTemplateLineEdit.setText(settings.data().sessionIndexPathTemplate); - using SwitchMode = ClangdSettings::HeaderSourceSwitchMode; - for (SwitchMode mode : {SwitchMode::BuiltinOnly, SwitchMode::ClangdOnly, SwitchMode::Both}) { - m_headerSourceSwitchComboBox.addItem( - ClangdSettings::headerSourceSwitchModeToDisplayString(mode), int(mode)); - if (mode == settings.headerSourceSwitchMode()) - m_headerSourceSwitchComboBox.setCurrentIndex( - m_headerSourceSwitchComboBox.count() - 1); - } - m_headerSourceSwitchComboBox.setToolTip(headerSourceSwitchToolTip); - for (RankingModel model : {RankingModel::Default, RankingModel::DecisionForest, - RankingModel::Heuristics}) { - m_completionRankingModelComboBox.addItem( - ClangdSettings::rankingModelToDisplayString(model), int(model)); - if (model == settings.completionRankingModel()) - m_completionRankingModelComboBox.setCurrentIndex( - m_completionRankingModelComboBox.count() - 1); - } - m_completionRankingModelComboBox.setToolTip(completionRankingModelToolTip); - - m_autoIncludeHeadersCheckBox.setText(Tr::tr("Insert header files on completion")); - m_autoIncludeHeadersCheckBox.setChecked(settings.autoIncludeHeaders()); - m_autoIncludeHeadersCheckBox.setToolTip(autoIncludeToolTip); - m_threadLimitSpinBox.setValue(settings.workerThreadLimit()); - m_threadLimitSpinBox.setSpecialValueText(Tr::tr("Automatic")); - m_threadLimitSpinBox.setToolTip(workerThreadsToolTip); - m_documentUpdateThreshold.setMinimum(50); - m_documentUpdateThreshold.setMaximum(10000); - m_documentUpdateThreshold.setValue(settings.documentUpdateThreshold()); - m_documentUpdateThreshold.setSingleStep(100); - m_documentUpdateThreshold.setSuffix(" ms"); - m_documentUpdateThreshold.setToolTip(documentUpdateToolTip); - m_sizeThresholdCheckBox.setText(Tr::tr("Ignore files greater than")); - m_sizeThresholdCheckBox.setChecked(settings.sizeThresholdEnabled()); - m_sizeThresholdCheckBox.setToolTip(sizeThresholdToolTip); - m_sizeThresholdSpinBox.setMinimum(1); - m_sizeThresholdSpinBox.setMaximum(std::numeric_limits::max()); - m_sizeThresholdSpinBox.setSuffix(" KB"); - m_sizeThresholdSpinBox.setValue(settings.sizeThresholdInKb()); - m_sizeThresholdSpinBox.setToolTip(sizeThresholdToolTip); - - const auto completionResultsLabel = new QLabel(Tr::tr("Completion results:")); - completionResultsLabel->setToolTip(completionResultToolTip); - m_completionResults.setMinimum(0); - m_completionResults.setMaximum(std::numeric_limits::max()); - m_completionResults.setValue(settings.completionResults()); - m_completionResults.setToolTip(completionResultToolTip); - m_completionResults.setSpecialValueText(Tr::tr("No limit")); - - const auto layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(&m_useClangdCheckBox); - - const auto formLayout = new QFormLayout; - const auto chooserLabel = new QLabel(Tr::tr("Path to executable:")); - formLayout->addRow(chooserLabel, &m_clangdChooser); - formLayout->addRow(QString(), &m_versionWarningLabel); - - const auto indexingPriorityLayout = new QHBoxLayout; - indexingPriorityLayout->addWidget(&m_indexingComboBox); - indexingPriorityLayout->addStretch(1); - const auto indexingPriorityLabel = new QLabel(Tr::tr("Background indexing:")); - indexingPriorityLabel->setToolTip(indexingToolTip); - formLayout->addRow(indexingPriorityLabel, indexingPriorityLayout); - - for (const auto &[text, edit, toolTip, defaultValue] : - {std::make_tuple(Tr::tr("Per-project index location:"), - &m_projectIndexPathTemplateLineEdit, - projectIndexPathToolTip, - ClangdSettings::defaultProjectIndexPathTemplate()), - std::make_tuple(Tr::tr("Per-session index location:"), - &m_sessionIndexPathTemplateLineEdit, - sessionIndexPathToolTip, - ClangdSettings::defaultSessionIndexPathTemplate())}) { - if (isForProject && edit == &m_sessionIndexPathTemplateLineEdit) - continue; - - const auto chooser = new Utils::VariableChooser(edit); - chooser->addSupportedWidget(edit); - chooser->addMacroExpanderProvider([] { return Utils::globalMacroExpander(); }); - - const auto resetButton = new QPushButton(Tr::tr("Reset")); - connect(resetButton, &QPushButton::clicked, [e = edit, v = defaultValue] { e->setText(v); }); - const auto layout = new QHBoxLayout; - const auto label = new QLabel(text); - label->setToolTip(toolTip); - edit->setToolTip(toolTip); - layout->addWidget(edit); - layout->addWidget(resetButton); - formLayout->addRow(label, layout); - } - - const auto headerSourceSwitchLayout = new QHBoxLayout; - headerSourceSwitchLayout->addWidget(&m_headerSourceSwitchComboBox); - headerSourceSwitchLayout->addStretch(1); - const auto headerSourceSwitchLabel = new QLabel(Tr::tr("Header/source switch mode:")); - headerSourceSwitchLabel->setToolTip(headerSourceSwitchToolTip); - formLayout->addRow(headerSourceSwitchLabel, headerSourceSwitchLayout); - - const auto threadLimitLayout = new QHBoxLayout; - threadLimitLayout->addWidget(&m_threadLimitSpinBox); - threadLimitLayout->addStretch(1); - const auto threadLimitLabel = new QLabel(Tr::tr("Worker thread count:")); - threadLimitLabel->setToolTip(workerThreadsToolTip); - formLayout->addRow(threadLimitLabel, threadLimitLayout); - - formLayout->addRow(QString(), &m_autoIncludeHeadersCheckBox); - const auto limitResultsLayout = new QHBoxLayout; - limitResultsLayout->addWidget(&m_completionResults); - limitResultsLayout->addStretch(1); - formLayout->addRow(completionResultsLabel, limitResultsLayout); - - const auto completionRankingModelLayout = new QHBoxLayout; - completionRankingModelLayout->addWidget(&m_completionRankingModelComboBox); - completionRankingModelLayout->addStretch(1); - const auto completionRankingModelLabel = new QLabel(Tr::tr("Completion ranking model:")); - completionRankingModelLabel->setToolTip(completionRankingModelToolTip); - formLayout->addRow(completionRankingModelLabel, completionRankingModelLayout); - - const auto documentUpdateThresholdLayout = new QHBoxLayout; - documentUpdateThresholdLayout->addWidget(&m_documentUpdateThreshold); - documentUpdateThresholdLayout->addStretch(1); - const auto documentUpdateThresholdLabel = new QLabel(Tr::tr("Document update threshold:")); - documentUpdateThresholdLabel->setToolTip(documentUpdateToolTip); - formLayout->addRow(documentUpdateThresholdLabel, documentUpdateThresholdLayout); - const auto sizeThresholdLayout = new QHBoxLayout; - sizeThresholdLayout->addWidget(&m_sizeThresholdSpinBox); - sizeThresholdLayout->addStretch(1); - formLayout->addRow(&m_sizeThresholdCheckBox, sizeThresholdLayout); - - m_configSelectionWidget = new ClangDiagnosticConfigsSelectionWidget(formLayout); - m_configSelectionWidget->refresh( - diagnosticConfigsModel(settings.customDiagnosticConfigs()), - settings.diagnosticConfigId(), - [](const ClangDiagnosticConfigs &configs, const Utils::Id &configToSelect) { - return new CppEditor::ClangDiagnosticConfigsWidget(configs, configToSelect); - }); - - layout->addLayout(formLayout); - if (!isForProject) { - m_sessionsModel.setStringList(settingsData.sessionsWithOneClangd); - m_sessionsModel.sort(0); - m_sessionsGroupBox = new QGroupBox(Tr::tr("Sessions with a single clangd instance")); - const auto sessionsView = new Utils::ListView; - sessionsView->setModel(&m_sessionsModel); - sessionsView->setToolTip( - Tr::tr("By default, Qt Creator runs one clangd process per project.\n" - "If you have sessions with tightly coupled projects that should be\n" - "managed by the same clangd process, add them here.")); - const auto outerSessionsLayout = new QHBoxLayout; - const auto innerSessionsLayout = new QHBoxLayout(m_sessionsGroupBox); - const auto buttonsLayout = new QVBoxLayout; - const auto addButton = new QPushButton(Tr::tr("Add ...")); - const auto removeButton = new QPushButton(Tr::tr("Remove")); - buttonsLayout->addWidget(addButton); - buttonsLayout->addWidget(removeButton); - buttonsLayout->addStretch(1); - innerSessionsLayout->addWidget(sessionsView); - innerSessionsLayout->addLayout(buttonsLayout); - outerSessionsLayout->addWidget(m_sessionsGroupBox); - outerSessionsLayout->addStretch(1); - - const auto separator = new QFrame; - separator->setFrameShape(QFrame::HLine); - layout->addWidget(separator); - layout->addLayout(outerSessionsLayout); - - const auto updateRemoveButtonState = [removeButton, sessionsView] { - removeButton->setEnabled(sessionsView->selectionModel()->hasSelection()); - }; - connect(sessionsView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, updateRemoveButtonState); - updateRemoveButtonState(); - connect(removeButton, &QPushButton::clicked, this, [this, sessionsView] { - const QItemSelection selection = sessionsView->selectionModel()->selection(); - QTC_ASSERT(!selection.isEmpty(), return); - m_sessionsModel.removeRow(selection.indexes().first().row()); - }); - - connect(addButton, &QPushButton::clicked, this, [this, sessionsView] { - QInputDialog dlg(sessionsView); - QStringList sessions = Core::SessionManager::sessions(); - QStringList currentSessions = m_sessionsModel.stringList(); - for (const QString &s : std::as_const(currentSessions)) - sessions.removeOne(s); - if (sessions.isEmpty()) - return; - sessions.sort(); - dlg.setLabelText(Tr::tr("Choose a session:")); - dlg.setComboBoxItems(sessions); - if (dlg.exec() == QDialog::Accepted) { - currentSessions << dlg.textValue(); - m_sessionsModel.setStringList(currentSessions); - m_sessionsModel.sort(0); - } - }); - } - - const auto configFilesHelpLabel = new QLabel; - configFilesHelpLabel->setText(Tr::tr("Additional settings are available via " - " clangd configuration files.
    " - "User-specific settings go here, " - "project-specific settings can be configured by putting a .clangd file into " - "the project source tree.") - .arg(ClangdSettings::clangdUserConfigFilePath().toUserOutput())); - configFilesHelpLabel->setWordWrap(true); - connect(configFilesHelpLabel, &QLabel::linkHovered, configFilesHelpLabel, &QLabel::setToolTip); - connect(configFilesHelpLabel, &QLabel::linkActivated, [](const QString &link) { - if (link.startsWith("https")) - QDesktopServices::openUrl(link); - else - Core::EditorManager::openEditor(Utils::FilePath::fromString(link)); - }); - layout->addWidget(Layouting::createHr()); - layout->addWidget(configFilesHelpLabel); - - layout->addStretch(1); - - static const auto setWidgetsEnabled = [](QLayout *layout, bool enabled, const auto &f) -> void { - for (int i = 0; i < layout->count(); ++i) { - if (QWidget * const w = layout->itemAt(i)->widget()) - w->setEnabled(enabled); - else if (QLayout * const l = layout->itemAt(i)->layout()) - f(l, enabled, f); - } - }; - const auto toggleEnabled = [this, formLayout](const bool checked) { - setWidgetsEnabled(formLayout, checked, setWidgetsEnabled); - if (m_sessionsGroupBox) - m_sessionsGroupBox->setEnabled(checked); - }; - connect(&m_useClangdCheckBox, &QCheckBox::toggled, toggleEnabled); - toggleEnabled(m_useClangdCheckBox.isChecked()); - m_threadLimitSpinBox.setEnabled(m_useClangdCheckBox.isChecked()); - - m_versionWarningLabel.setType(Utils::InfoLabel::Warning); - const auto updateWarningLabel = [this] { - class WarningLabelSetter { - public: - WarningLabelSetter(QLabel &label) : m_label(label) { m_label.clear(); } - ~WarningLabelSetter() { m_label.setVisible(!m_label.text().isEmpty()); } - void setWarning(const QString &text) { m_label.setText(text); } - private: - QLabel &m_label; - }; - WarningLabelSetter labelSetter(m_versionWarningLabel); - - if (!m_clangdChooser.isValid()) - return; - const Utils::FilePath clangdPath = m_clangdChooser.filePath(); - QString errorMessage; - if (!Utils::checkClangdVersion(clangdPath, &errorMessage)) - labelSetter.setWarning(errorMessage); - }; - connect(&m_clangdChooser, &Utils::PathChooser::textChanged, this, updateWarningLabel); - connect(&m_clangdChooser, &Utils::PathChooser::validChanged, this, updateWarningLabel); - updateWarningLabel(); - - connect(&m_useClangdCheckBox, &QCheckBox::toggled, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_indexingComboBox, &QComboBox::currentIndexChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_projectIndexPathTemplateLineEdit, &QLineEdit::textChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_sessionIndexPathTemplateLineEdit, &QLineEdit::textChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_headerSourceSwitchComboBox, &QComboBox::currentIndexChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_completionRankingModelComboBox, &QComboBox::currentIndexChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_autoIncludeHeadersCheckBox, &QCheckBox::toggled, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_threadLimitSpinBox, &QSpinBox::valueChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_sizeThresholdCheckBox, &QCheckBox::toggled, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_sizeThresholdSpinBox, &QSpinBox::valueChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_documentUpdateThreshold, &QSpinBox::valueChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_clangdChooser, &Utils::PathChooser::textChanged, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(m_configSelectionWidget, &ClangDiagnosticConfigsSelectionWidget::changed, - this, &ClangdSettingsWidget::settingsDataChanged); - connect(&m_completionResults, &QSpinBox::valueChanged, - this, &ClangdSettingsWidget::settingsDataChanged); -} - -ClangdSettings::Data ClangdSettingsWidget::settingsData() const -{ - ClangdSettings::Data data; - data.useClangd = m_useClangdCheckBox.isChecked(); - data.executableFilePath = m_clangdChooser.filePath(); - data.indexingPriority = ClangdSettings::IndexingPriority( - m_indexingComboBox.currentData().toInt()); - data.projectIndexPathTemplate = m_projectIndexPathTemplateLineEdit.text(); - data.sessionIndexPathTemplate = m_sessionIndexPathTemplateLineEdit.text(); - data.headerSourceSwitchMode = ClangdSettings::HeaderSourceSwitchMode( - m_headerSourceSwitchComboBox.currentData().toInt()); - data.completionRankingModel = ClangdSettings::CompletionRankingModel( - m_completionRankingModelComboBox.currentData().toInt()); - data.autoIncludeHeaders = m_autoIncludeHeadersCheckBox.isChecked(); - data.workerThreadLimit = m_threadLimitSpinBox.value(); - data.documentUpdateThreshold = m_documentUpdateThreshold.value(); - data.sizeThresholdEnabled = m_sizeThresholdCheckBox.isChecked(); - data.sizeThresholdInKb = m_sizeThresholdSpinBox.value(); - data.sessionsWithOneClangd = m_sessionsModel.stringList(); - data.customDiagnosticConfigs = m_configSelectionWidget->customConfigs(); - data.diagnosticConfigId = m_configSelectionWidget->currentConfigId(); - data.completionResults = m_completionResults.value(); - return data; -} - -class ClangdSettingsPageWidget final : public Core::IOptionsPageWidget -{ -public: - ClangdSettingsPageWidget() : m_widget(ClangdSettings::instance().data(), false) - { - const auto layout = new QVBoxLayout(this); - layout->addWidget(&m_widget); - } - -private: - void apply() final { ClangdSettings::instance().setData(m_widget.settingsData()); } - - ClangdSettingsWidget m_widget; -}; - -class ClangdSettingsPage final : public Core::IOptionsPage -{ -public: - ClangdSettingsPage() - { - setId(Constants::CPP_CLANGD_SETTINGS_ID); - setDisplayName(Tr::tr("Clangd")); - setCategory(Constants::CPP_SETTINGS_CATEGORY); - setWidgetCreator([] { return new ClangdSettingsPageWidget; }); - } -}; - -void setupClangdSettingsPage() -{ - static ClangdSettingsPage theClangdSettingsPage; -} - -class ClangdProjectSettingsWidget : public ProjectSettingsWidget -{ -public: - ClangdProjectSettingsWidget(const ClangdProjectSettings &settings) - : m_settings(settings), m_widget(settings.settings(), true) - { - setGlobalSettingsId(Constants::CPP_CLANGD_SETTINGS_ID); - const auto layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(&m_widget); - - const auto updateGlobalSettingsCheckBox = [this] { - if (ClangdSettings::instance().granularity() == ClangdSettings::Granularity::Session) { - setUseGlobalSettingsCheckBoxEnabled(false); - setUseGlobalSettings(true); - } else { - setUseGlobalSettingsCheckBoxEnabled(true); - setUseGlobalSettings(m_settings.useGlobalSettings()); - } - m_widget.setEnabled(!useGlobalSettings()); - }; - - updateGlobalSettingsCheckBox(); - connect(&ClangdSettings::instance(), &ClangdSettings::changed, - this, updateGlobalSettingsCheckBox); - - connect(this, &ProjectSettingsWidget::useGlobalSettingsChanged, this, - [this](bool checked) { - m_widget.setEnabled(!checked); - m_settings.setUseGlobalSettings(checked); - if (!checked) - m_settings.setSettings(m_widget.settingsData()); - }); - - const auto timer = new QTimer(this); - timer->setSingleShot(true); - timer->setInterval(5000); - connect(timer, &QTimer::timeout, this, [this] { - m_settings.setSettings(m_widget.settingsData()); - }); - connect(&m_widget, &ClangdSettingsWidget::settingsDataChanged, - timer, qOverload<>(&QTimer::start)); - } - -private: - ClangdProjectSettings m_settings; - ClangdSettingsWidget m_widget; -}; - -class ClangdProjectSettingsPanelFactory final : public ProjectPanelFactory -{ -public: - ClangdProjectSettingsPanelFactory() - { - setPriority(100); - setDisplayName(Tr::tr("Clangd")); - setCreateWidgetFunction([](Project *project) { - return new ClangdProjectSettingsWidget(project); - }); - } -}; - -void setupClangdProjectSettingsPanel() -{ - static ClangdProjectSettingsPanelFactory theClangdProjectSettingsPanelFactory; -} - } // CppEditor::Internal #include "cppcodemodelsettingspage.moc" diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.h b/src/plugins/cppeditor/cppcodemodelsettingspage.h index 4c11b6251e2..36d47ff8751 100644 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.h +++ b/src/plugins/cppeditor/cppcodemodelsettingspage.h @@ -7,7 +7,5 @@ namespace CppEditor::Internal { void setupCppCodeModelSettingsPage(); void setupCppCodeModelProjectSettingsPanel(); -void setupClangdProjectSettingsPanel(); -void setupClangdSettingsPage(); } // CppEditor::Internal diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 9a110398760..77a9997244c 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -1,6 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +#include "clangdsettings.h" #include "cppautocompleter.h" #include "cppcodemodelinspectordialog.h" #include "cppcodemodelsettings.h" From 3e4f50aeb9feba4565fe689eb33bb0ea4a5fc2dd Mon Sep 17 00:00:00 2001 From: BogDan Vatra Date: Tue, 26 Mar 2024 14:42:17 +0200 Subject: [PATCH 0133/1060] Use SSH port forwarding for debugging This feature is needed to enable debugging on remote targes which can not expose gdbserver ports on the wild, and we must use ssh tunneling for that job. Change-Id: I6df712fd3b40790e89c79a7617a24430fde6805a Reviewed-by: Christian Kandeler --- src/plugins/debugger/debuggerruncontrol.cpp | 12 +++++++++++- .../devicesupport/deviceusedportsgatherer.cpp | 7 ++++++- src/plugins/projectexplorer/runcontrol.cpp | 5 +++++ src/plugins/projectexplorer/runcontrol.h | 1 + .../genericlinuxdeviceconfigurationwidget.cpp | 19 ++++++++++++++++++- .../genericlinuxdeviceconfigurationwidget.h | 2 ++ src/plugins/remotelinux/linuxdevice.cpp | 15 ++++++++++++++- .../remotelinux/remotelinux_constants.h | 3 +++ 8 files changed, 60 insertions(+), 4 deletions(-) diff --git a/src/plugins/debugger/debuggerruncontrol.cpp b/src/plugins/debugger/debuggerruncontrol.cpp index a46d34ccda1..503bad4bc23 100644 --- a/src/plugins/debugger/debuggerruncontrol.cpp +++ b/src/plugins/debugger/debuggerruncontrol.cpp @@ -30,6 +30,8 @@ #include #include +#include + #include #include #include @@ -1060,7 +1062,15 @@ DebugServerRunner::DebugServerRunner(RunControl *runControl, DebugServerPortsGat cmd.addArg("--multi"); if (m_pid.isValid()) cmd.addArg("--attach"); - cmd.addArg(QString(":%1").arg(portsGatherer->gdbServer().port())); + + const auto port = portsGatherer->gdbServer().port(); + cmd.addArg(QString(":%1").arg(port)); + + if (runControl->device()->extraData(RemoteLinux::Constants::SshForwardDebugServerPort).toBool()) { + addExtraData(RemoteLinux::Constants::SshForwardPort, port); + addExtraData(RemoteLinux::Constants::DisableSharing, true); + } + if (m_pid.isValid()) cmd.addArg(QString::number(m_pid.pid())); } diff --git a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp index 920d7f69c55..714d311a1ef 100644 --- a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp +++ b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp @@ -7,6 +7,8 @@ #include "sshparameters.h" #include "../projectexplorertr.h" +#include + #include #include #include @@ -179,7 +181,10 @@ public: void start() final { m_channel.setScheme(urlTcpScheme()); - m_channel.setHost(device()->toolControlChannel(IDevice::ControlChannelHint()).host()); + if (device()->extraData(RemoteLinux::Constants::SshForwardDebugServerPort).toBool()) + m_channel.setHost("localhost"); + else + m_channel.setHost(device()->toolControlChannel(IDevice::ControlChannelHint()).host()); if (m_portGatherer) m_channel.setPort(m_portGatherer->findEndPoint().port()); reportStarted(); diff --git a/src/plugins/projectexplorer/runcontrol.cpp b/src/plugins/projectexplorer/runcontrol.cpp index f5f24b05c79..3b601d45cbd 100644 --- a/src/plugins/projectexplorer/runcontrol.cpp +++ b/src/plugins/projectexplorer/runcontrol.cpp @@ -1580,6 +1580,11 @@ void SimpleTargetRunner::forceRunOnHost() } } +void SimpleTargetRunner::addExtraData(const QString &key, const QVariant &value) +{ + d->m_extraData[key] = value; +} + // RunWorkerPrivate RunWorkerPrivate::RunWorkerPrivate(RunWorker *runWorker, RunControl *runControl) diff --git a/src/plugins/projectexplorer/runcontrol.h b/src/plugins/projectexplorer/runcontrol.h index 629fff8346a..0c47ff18b6a 100644 --- a/src/plugins/projectexplorer/runcontrol.h +++ b/src/plugins/projectexplorer/runcontrol.h @@ -273,6 +273,7 @@ protected: void setProcessMode(Utils::ProcessMode processMode); void forceRunOnHost(); + void addExtraData(const QString &key, const QVariant &value); private: void start() final; diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp index 8afafabdeda..f89767de0a3 100644 --- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp +++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp @@ -105,6 +105,13 @@ GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget( auto sshPortLabel = new QLabel(Tr::tr("&SSH port:")); sshPortLabel->setBuddy(m_sshPortSpinBox); + m_useSshPortForwardingForDebugging = new QCheckBox; + m_useSshPortForwardingForDebugging->setText(Tr::tr("Use SSH port forwarding for debugging")); + m_useSshPortForwardingForDebugging + ->setToolTip(Tr::tr("Enable debugging on remote targes which cannot expose gdbserver ports.\n" + "The ssh tunneling is used to map the remote gdbserver port to localhost.\n" + "The local and remote ports are determined automatically.")); + using namespace Layouting; Form { @@ -117,7 +124,8 @@ GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget( Tr::tr("GDB server executable:"), m_gdbServerLineEdit, br, Tr::tr("QML runtime executable:"), m_qmlRuntimeLineEdit, br, QString(), m_sourceProfileCheckBox, br, - Tr::tr("Access via:"), m_linkDeviceComboBox + QString(), m_useSshPortForwardingForDebugging, br, + Tr::tr("Access via:"), m_linkDeviceComboBox, br, }.attachTo(this); connect(m_hostLineEdit, &QLineEdit::editingFinished, @@ -152,6 +160,8 @@ GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget( this, &GenericLinuxDeviceConfigurationWidget::sourceProfileCheckingChanged); connect(m_linkDeviceComboBox, &QComboBox::currentIndexChanged, this, &GenericLinuxDeviceConfigurationWidget::linkDeviceChanged); + connect(m_useSshPortForwardingForDebugging, &QCheckBox::toggled, + this, &GenericLinuxDeviceConfigurationWidget::sshPortForwardingForDebugging); initGui(); } @@ -253,6 +263,11 @@ void GenericLinuxDeviceConfigurationWidget::linkDeviceChanged(int index) device()->setExtraData(Constants::LinkDevice, deviceId); } +void GenericLinuxDeviceConfigurationWidget::sshPortForwardingForDebugging(bool on) +{ + device()->setExtraData(Constants::SshForwardDebugServerPort, on); +} + void GenericLinuxDeviceConfigurationWidget::updateDeviceFromUi() { hostNameEditingFinished(); @@ -266,6 +281,7 @@ void GenericLinuxDeviceConfigurationWidget::updateDeviceFromUi() timeoutEditingFinished(); sourceProfileCheckingChanged(m_sourceProfileCheckBox->isChecked()); linkDeviceChanged(m_linkDeviceComboBox->currentIndex()); + sshPortForwardingForDebugging(m_useSshPortForwardingForDebugging->isChecked()); qmlRuntimeEditingFinished(); } @@ -331,6 +347,7 @@ void GenericLinuxDeviceConfigurationWidget::initGui() sshParams.authenticationType == SshParameters::AuthenticationTypeSpecificKey); m_gdbServerLineEdit->setFilePath(device()->debugServerPath()); m_qmlRuntimeLineEdit->setFilePath(device()->qmlRunCommand()); + m_useSshPortForwardingForDebugging->setChecked(device()->extraData(Constants::SshForwardDebugServerPort).toBool()); updatePortsWarningLabel(); } diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h index aba251b969e..cc007ec6efa 100644 --- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h +++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h @@ -45,6 +45,7 @@ private: void hostKeyCheckingChanged(bool doCheck); void sourceProfileCheckingChanged(bool doCheck); void linkDeviceChanged(int index); + void sshPortForwardingForDebugging(bool on); void updateDeviceFromUi() override; void updatePortsWarningLabel(); @@ -66,6 +67,7 @@ private: Utils::PathChooser *m_qmlRuntimeLineEdit; QCheckBox *m_sourceProfileCheckBox; QComboBox *m_linkDeviceComboBox; + QCheckBox *m_useSshPortForwardingForDebugging; }; } // RemoteLinux::Internal diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp index 31195e8cfad..5fcb808a7cc 100644 --- a/src/plugins/remotelinux/linuxdevice.cpp +++ b/src/plugins/remotelinux/linuxdevice.cpp @@ -666,6 +666,12 @@ void SshProcessInterfacePrivate::start() cmd.addCommandLineAsSingleArg(inner); } + const auto forwardPort = q->m_setup.m_extraData.value(Constants::SshForwardPort).toString(); + if (!forwardPort.isEmpty()) { + cmd.addArg("-L"); + cmd.addArg(QString("%1:localhost:%1").arg(forwardPort)); + } + m_process.setProcessImpl(q->m_setup.m_processImpl); m_process.setProcessMode(q->m_setup.m_processMode); m_process.setTerminalMode(q->m_setup.m_terminalMode); @@ -680,11 +686,12 @@ void SshProcessInterfacePrivate::start() return; } - m_useConnectionSharing = SshSettings::connectionSharingEnabled(); + m_useConnectionSharing = SshSettings::connectionSharingEnabled() && !q->m_setup.m_extraData.value(Constants::DisableSharing).toBool(); // TODO: Do we really need it for master process? m_sshParameters.x11DisplayName = q->m_setup.m_extraData.value("Ssh.X11ForwardToDisplay").toString(); + if (m_useConnectionSharing) { m_connecting = true; m_connectionHandle.reset(new SshConnectionHandle(m_device)); @@ -769,6 +776,12 @@ CommandLine SshProcessInterfacePrivate::fullLocalCommandLine() const cmd.addArg("-q"); + const auto forwardPort = q->m_setup.m_extraData.value(Constants::SshForwardPort).toString(); + if (!forwardPort.isEmpty()) { + cmd.addArg("-L"); + cmd.addArg(QString("%1:localhost:%1").arg(forwardPort)); + } + cmd.addArgs(m_sshParameters.connectionOptions(sshBinary)); if (!m_socketFilePath.isEmpty()) cmd.addArgs({"-o", "ControlPath=" + m_socketFilePath}); diff --git a/src/plugins/remotelinux/remotelinux_constants.h b/src/plugins/remotelinux/remotelinux_constants.h index 90e34826469..a562164dfdc 100644 --- a/src/plugins/remotelinux/remotelinux_constants.h +++ b/src/plugins/remotelinux/remotelinux_constants.h @@ -21,6 +21,9 @@ const char KillAppStepId[] = "RemoteLinux.KillAppStep"; const char SourceProfile[] = "RemoteLinux.SourceProfile"; const char LinkDevice[] = "RemoteLinux.LinkDevice"; +const char SshForwardDebugServerPort[] = "RemoteLinux.SshForwardDebugServerPort"; +const char SshForwardPort[] = "RemoteLinux.SshForwardPort"; +const char DisableSharing[] = "RemoteLinux.DisableSharing"; const char RunConfigId[] = "RemoteLinuxRunConfiguration:"; const char CustomRunConfigId[] = "RemoteLinux.CustomRunConfig"; From 698488fc05001bfbe9df6944d90fe1bd18e9a450 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Thu, 11 Apr 2024 12:22:18 +0200 Subject: [PATCH 0134/1060] TaskTree: Add a test showing the parallel disorder In parallel mode the done handlers may be invoked in a different order than the corresponding setup handlers. Change-Id: Ib3df668491054501d250fef9c499d127fe98626d Reviewed-by: Marcus Tillmanns --- tests/auto/solutions/tasking/tst_tasking.cpp | 35 ++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/auto/solutions/tasking/tst_tasking.cpp b/tests/auto/solutions/tasking/tst_tasking.cpp index 95de5b44b3f..db293d4ebfb 100644 --- a/tests/auto/solutions/tasking/tst_tasking.cpp +++ b/tests/auto/solutions/tasking/tst_tasking.cpp @@ -3084,6 +3084,41 @@ void tst_Tasking::testTree_data() logErrorLong, 1, DoneWith::Error, 1}; } + { + // This tests ensures the task done handlers are invoked in a different order + // than the corresponding setup handlers. + + const QList tasks { 1000000ms, 0ms }; + const LoopList iterator(tasks); + + const auto onSetup = [storage, iterator](TaskObject &taskObject) { + taskObject = *iterator; + storage->m_log.append({iterator.iteration(), Handler::Setup}); + }; + + const auto onDone = [storage, iterator](DoneWith result) { + const Handler handler = result == DoneWith::Cancel ? Handler::Canceled : Handler::Error; + storage->m_log.append({iterator.iteration(), handler}); + return DoneResult::Error; + }; + + const Group root { + storage, + parallel, + iterator, + TestTask(onSetup, onDone) + }; + + const Log log { + {0, Handler::Setup}, + {1, Handler::Setup}, + {1, Handler::Error}, + {0, Handler::Canceled} + }; + + QTest::newRow("ParallelDisorder") << TestData{storage, root, log, 2, DoneWith::Error, 1}; + } + // This test checks if storage shadowing works OK. QTest::newRow("StorageShadowing") << storageShadowingData(); } From ec3a5b5fd04dd7381d14d2174a2b9e57a9a824fc Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 10 Apr 2024 11:24:32 +0200 Subject: [PATCH 0135/1060] Editor: move setScriptable to context actions The scriptable info is saved to the action registered for a specific context so we need to add this info to the action builder in the text editor that has the correct context. Also remove all action builder constructs for the global context that have been registered before in order to silence the add override action warning. Change-Id: I631d71ba5eb8e975190713b33827926e868da295 Reviewed-by: Reviewed-by: Christian Stenger --- src/plugins/texteditor/texteditor.cpp | 587 +++++++++++--------- src/plugins/texteditor/texteditorplugin.cpp | 178 ++---- 2 files changed, 367 insertions(+), 398 deletions(-) diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 9a7c0a2b267..e3d2c1c94e3 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -3870,354 +3870,435 @@ void TextEditorWidgetPrivate::registerActions() using namespace TextEditor::Constants; m_undoAction = ActionBuilder(this, UNDO) - .setContext(m_editorContext) - .addOnTriggered([this] { q->undo(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->undo(); }) + .setScriptable(true) + .contextAction(); m_redoAction = ActionBuilder(this, REDO) - .setContext(m_editorContext) - .addOnTriggered([this] { q->redo(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->redo(); }) + .setScriptable(true) + .contextAction(); m_copyAction = ActionBuilder(this, COPY) - .setContext(m_editorContext) - .addOnTriggered([this] { q->copy(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->copy(); }) + .setScriptable(true) + .contextAction(); m_cutAction = ActionBuilder(this, CUT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->cut(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->cut(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, PASTE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->paste(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->paste(); }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, SELECTALL) - .setContext(m_editorContext) - .addOnTriggered([this] { q->selectAll(); }); - ActionBuilder(this, GOTO) - .setContext(m_editorContext) - .addOnTriggered([] { LocatorManager::showFilter(lineNumberFilter()); }); + .setContext(m_editorContext) + .setScriptable(true) + .addOnTriggered([this] { q->selectAll(); }); + ActionBuilder(this, GOTO).setContext(m_editorContext).addOnTriggered([] { + LocatorManager::showFilter(lineNumberFilter()); + }); ActionBuilder(this, PRINT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->print(ICore::printer()); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->print(ICore::printer()); }) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteLine(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteLine(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_END_OF_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteEndOfLine(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfLine(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_END_OF_WORD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteEndOfWord(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfWord(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_END_OF_WORD_CAMEL_CASE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteEndOfWordCamelCase(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteEndOfWordCamelCase(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_START_OF_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteStartOfLine(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfLine(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_START_OF_WORD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteStartOfWord(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfWord(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DELETE_START_OF_WORD_CAMEL_CASE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->deleteStartOfWordCamelCase(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->deleteStartOfWordCamelCase(); }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, GOTO_BLOCK_START_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoBlockStartWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockStartWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_BLOCK_END_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoBlockEndWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockEndWithSelection(); }) + .setScriptable(true); m_modifyingActions << ActionBuilder(this, MOVE_LINE_UP) - .setContext(m_editorContext) - .addOnTriggered([this] { q->moveLineUp(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->moveLineUp(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, MOVE_LINE_DOWN) - .setContext(m_editorContext) - .addOnTriggered([this] { q->moveLineDown(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->moveLineDown(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, COPY_LINE_UP) - .setContext(m_editorContext) - .addOnTriggered([this] { q->copyLineUp(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLineUp(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, COPY_LINE_DOWN) - .setContext(m_editorContext) - .addOnTriggered([this] { q->copyLineDown(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLineDown(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, JOIN_LINES) - .setContext(m_editorContext) - .addOnTriggered([this] { q->joinLines(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->joinLines(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, INSERT_LINE_ABOVE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->insertLineAbove(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->insertLineAbove(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, INSERT_LINE_BELOW) - .setContext(m_editorContext) - .addOnTriggered([this] { q->insertLineBelow(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->insertLineBelow(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, SWITCH_UTF8BOM) - .setContext(m_editorContext) - .addOnTriggered([this] { q->switchUtf8bom(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->switchUtf8bom(); }) + .contextAction(); m_modifyingActions << ActionBuilder(this, INDENT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->indent(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->indent(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, UNINDENT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->unindent(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->unindent(); }) + .setScriptable(true) + .contextAction(); m_followSymbolAction = ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openLinkUnderCursor(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursor(); }) + .contextAction(); m_followSymbolInNextSplitAction = ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openLinkUnderCursorInNextSplit(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered( + [this] { q->openLinkUnderCursorInNextSplit(); }) + .contextAction(); m_followToTypeAction = ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openTypeUnderCursor(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->openTypeUnderCursor(); }) + .contextAction(); m_followToTypeInNextSplitAction = ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE_IN_NEXT_SPLIT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openTypeUnderCursorInNextSplit(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered( + [this] { q->openTypeUnderCursorInNextSplit(); }) + .contextAction(); m_findUsageAction = ActionBuilder(this, FIND_USAGES) - .setContext(m_editorContext) - .addOnTriggered([this] { q->findUsages(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->findUsages(); }) + .contextAction(); m_renameSymbolAction = ActionBuilder(this, RENAME_SYMBOL) - .setContext(m_editorContext) - .addOnTriggered([this] { q->renameSymbolUnderCursor(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->renameSymbolUnderCursor(); }) + .contextAction(); m_jumpToFileAction = ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openLinkUnderCursor(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->openLinkUnderCursor(); }) + .contextAction(); m_jumpToFileInNextSplitAction = ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openLinkUnderCursorInNextSplit(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered( + [this] { q->openLinkUnderCursorInNextSplit(); }) + .contextAction(); m_openCallHierarchyAction = ActionBuilder(this, OPEN_CALL_HIERARCHY) - .setContext(m_editorContext) - .addOnTriggered([this] { q->openCallHierarchy(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->openCallHierarchy(); }) + .setScriptable(true) + .contextAction(); m_openTypeHierarchyAction = ActionBuilder(this, OPEN_TYPE_HIERARCHY) - .setContext(m_editorContext) - .addOnTriggered([] { - updateTypeHierarchy(NavigationWidget::activateSubWidget( - Constants::TYPE_HIERARCHY_FACTORY_ID, Side::Left)); - }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([] { + updateTypeHierarchy(NavigationWidget::activateSubWidget( + Constants::TYPE_HIERARCHY_FACTORY_ID, Side::Left)); + }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, VIEW_PAGE_UP) - .setContext(m_editorContext) - .addOnTriggered([this] { q->viewPageUp(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewPageUp(); }) + .setScriptable(true); ActionBuilder(this, VIEW_PAGE_DOWN) - .setContext(m_editorContext) - .addOnTriggered([this] { q->viewPageDown(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewPageDown(); }) + .setScriptable(true); ActionBuilder(this, VIEW_LINE_UP) - .setContext(m_editorContext) - .addOnTriggered([this] { q->viewLineUp(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewLineUp(); }) + .setScriptable(true); ActionBuilder(this, VIEW_LINE_DOWN) - .setContext(m_editorContext) - .addOnTriggered([this] { q->viewLineDown(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->viewLineDown(); }) + .setScriptable(true); - ActionBuilder(this, SELECT_ENCODING) - .setContext(m_editorContext) - .addOnTriggered([this] { q->selectEncoding(); }); + ActionBuilder(this, SELECT_ENCODING).setContext(m_editorContext).addOnTriggered([this] { + q->selectEncoding(); + }); m_modifyingActions << ActionBuilder(this, CIRCULAR_PASTE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->circularPaste(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->circularPaste(); }) + .contextAction(); m_modifyingActions << ActionBuilder(this, NO_FORMAT_PASTE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->pasteWithoutFormat(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->pasteWithoutFormat(); }) + .setScriptable(true) + .contextAction(); m_autoIndentAction = ActionBuilder(this, AUTO_INDENT_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->autoIndent(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->autoIndent(); }) + .setScriptable(true) + .contextAction(); m_autoFormatAction = ActionBuilder(this, AUTO_FORMAT_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->autoFormat(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->autoFormat(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, REWRAP_PARAGRAPH) - .setContext(m_editorContext) - .addOnTriggered([this] { q->rewrapParagraph(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->rewrapParagraph(); }) + .setScriptable(true) + .contextAction(); m_visualizeWhitespaceAction = ActionBuilder(this, VISUALIZE_WHITESPACE) - .setContext(m_editorContext) - .addOnToggled( - this, - [this](bool checked) { - DisplaySettings ds = q->displaySettings(); - ds.m_visualizeWhitespace = checked; - q->setDisplaySettings(ds); - }) - .contextAction(); + .setContext(m_editorContext) + .addOnToggled( + this, + [this](bool checked) { + DisplaySettings ds = q->displaySettings(); + ds.m_visualizeWhitespace = checked; + q->setDisplaySettings(ds); + }) + .contextAction(); m_modifyingActions << ActionBuilder(this, CLEAN_WHITESPACE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->cleanWhitespace(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->cleanWhitespace(); }) + .setScriptable(true) + .contextAction(); m_textWrappingAction = ActionBuilder(this, TEXT_WRAPPING) - .setContext(m_editorContext) - .addOnToggled(this, [this] (bool checked) { - DisplaySettings ds = q->displaySettings(); - ds.m_textWrapping = checked; - q->setDisplaySettings(ds); - }) - .contextAction(); + .setContext(m_editorContext) + .addOnToggled( + this, + [this](bool checked) { + DisplaySettings ds = q->displaySettings(); + ds.m_textWrapping = checked; + q->setDisplaySettings(ds); + }) + .contextAction(); m_unCommentSelectionAction = ActionBuilder(this, UN_COMMENT_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->unCommentSelection(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->unCommentSelection(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, CUT_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->cutLine(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->cutLine(); }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, COPY_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->copyLine(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyLine(); }) + .setScriptable(true); m_copyHtmlAction = ActionBuilder(this, COPY_WITH_HTML) - .setContext(m_editorContext) - .addOnTriggered([this] { q->copyWithHtml(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->copyWithHtml(); }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, ADD_CURSORS_TO_LINE_ENDS) - .setContext(m_editorContext) - .addOnTriggered([this] { q->addCursorsToLineEnds(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->addCursorsToLineEnds(); }) + .setScriptable(true); ActionBuilder(this, ADD_SELECT_NEXT_FIND_MATCH) - .setContext(m_editorContext) - .addOnTriggered([this] { q->addSelectionNextFindMatch(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->addSelectionNextFindMatch(); }) + .setScriptable(true); m_modifyingActions << ActionBuilder(this, DUPLICATE_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->duplicateSelection(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->duplicateSelection(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, DUPLICATE_SELECTION_AND_COMMENT) - .setContext(m_editorContext) - .addOnTriggered([this] { q->duplicateSelectionAndComment(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->duplicateSelectionAndComment(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, UPPERCASE_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->uppercaseSelection(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->uppercaseSelection(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, LOWERCASE_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->lowercaseSelection(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->lowercaseSelection(); }) + .setScriptable(true) + .contextAction(); m_modifyingActions << ActionBuilder(this, SORT_LINES) - .setContext(m_editorContext) - .addOnTriggered([this] { q->sortLines(); }) - .contextAction(); + .setContext(m_editorContext) + .addOnTriggered([this] { q->sortLines(); }) + .setScriptable(true) + .contextAction(); ActionBuilder(this, FOLD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->foldCurrentBlock(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->foldCurrentBlock(); }) + .setScriptable(true); ActionBuilder(this, UNFOLD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->unfoldCurrentBlock(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->unfoldCurrentBlock(); }) + .setScriptable(true); m_unfoldAllAction = ActionBuilder(this, UNFOLD_ALL) .setContext(m_editorContext) .addOnTriggered([this] { q->unfoldAll(); }) + .setScriptable(true) .contextAction(); - ActionBuilder(this, INCREASE_FONT_SIZE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->increaseFontZoom(); }); - ActionBuilder(this, DECREASE_FONT_SIZE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->decreaseFontZoom(); }); - ActionBuilder(this, RESET_FONT_SIZE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->zoomReset(); }); + ActionBuilder(this, INCREASE_FONT_SIZE).setContext(m_editorContext).addOnTriggered([this] { + q->increaseFontZoom(); + }); + ActionBuilder(this, DECREASE_FONT_SIZE).setContext(m_editorContext).addOnTriggered([this] { + q->decreaseFontZoom(); + }); + ActionBuilder(this, RESET_FONT_SIZE).setContext(m_editorContext).addOnTriggered([this] { + q->zoomReset(); + }); ActionBuilder(this, GOTO_BLOCK_START) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoBlockStart(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockStart(); }) + .setScriptable(true); ActionBuilder(this, GOTO_BLOCK_END) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoBlockEnd(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoBlockEnd(); }) + .setScriptable(true); ActionBuilder(this, SELECT_BLOCK_UP) - .setContext(m_editorContext) - .addOnTriggered([this] { q->selectBlockUp(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectBlockUp(); }) + .setScriptable(true); ActionBuilder(this, SELECT_BLOCK_DOWN) - .setContext(m_editorContext) - .addOnTriggered([this] { q->selectBlockDown(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectBlockDown(); }) + .setScriptable(true); ActionBuilder(this, SELECT_WORD_UNDER_CURSOR) - .setContext(m_editorContext) - .addOnTriggered([this] { q->selectWordUnderCursor(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->selectWordUnderCursor(); }) + .setScriptable(true); ActionBuilder(this, GOTO_DOCUMENT_START) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoDocumentStart(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoDocumentStart(); }) + .setScriptable(true); ActionBuilder(this, GOTO_DOCUMENT_END) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoDocumentEnd(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoDocumentEnd(); }) + .setScriptable(true); ActionBuilder(this, GOTO_LINE_START) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoLineStart(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineStart(); }) + .setScriptable(true); ActionBuilder(this, GOTO_LINE_END) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoLineEnd(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineEnd(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextLine(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextLine(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_LINE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousLine(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousLine(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_CHARACTER) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousCharacter(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousCharacter(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_CHARACTER) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextCharacter(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextCharacter(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_WORD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousWord(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWord(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_WORD) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextWord(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWord(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousWordCamelCase(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordCamelCase(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextWordCamelCase(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordCamelCase(); }) + .setScriptable(true); ActionBuilder(this, GOTO_LINE_START_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoLineStartWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineStartWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_LINE_END_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoLineEndWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoLineEndWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_LINE_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextLineWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextLineWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_LINE_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousLineWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousLineWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_CHARACTER_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousCharacterWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousCharacterWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_CHARACTER_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextCharacterWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextCharacterWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_WORD_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousWordWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_WORD_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextWordWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoPreviousWordCamelCaseWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoPreviousWordCamelCaseWithSelection(); }) + .setScriptable(true); ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION) - .setContext(m_editorContext) - .addOnTriggered([this] { q->gotoNextWordCamelCaseWithSelection(); }); + .setContext(m_editorContext) + .addOnTriggered([this] { q->gotoNextWordCamelCaseWithSelection(); }) + .setScriptable(true); // Collect additional modifying actions so we can check for them inside a readonly file // and disable them diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index 0852da2ca82..e0f43e9a6fa 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -354,354 +354,242 @@ void TextEditorPlugin::createStandardContextMenu() void TextEditorPlugin::createEditorCommands() { using namespace Core::Constants; - ActionBuilder(this, UNDO).setText(Tr::tr("&Undo")).setScriptable(true); - ActionBuilder(this, REDO).setText(Tr::tr("&Redo")).setScriptable(true); - ActionBuilder(this, COPY).setScriptable(true); - ActionBuilder(this, CUT).setScriptable(true); - ActionBuilder(this, PASTE).setScriptable(true); - ActionBuilder(this, SELECTALL).setScriptable(true); - ActionBuilder(this, GOTO); - ActionBuilder(this, PRINT); - ActionBuilder(this, DELETE_LINE).setText(Tr::tr("Delete &Line")).setScriptable(true); - ActionBuilder(this, DELETE_END_OF_LINE) - .setText(Tr::tr("Delete Line from Cursor On")) - .setScriptable(true); - ActionBuilder(this, DELETE_END_OF_WORD) - .setText(Tr::tr("Delete Word from Cursor On")) - .setScriptable(true); + ActionBuilder(this, DELETE_LINE).setText(Tr::tr("Delete &Line")); + ActionBuilder(this, DELETE_END_OF_LINE).setText(Tr::tr("Delete Line from Cursor On")); + ActionBuilder(this, DELETE_END_OF_WORD).setText(Tr::tr("Delete Word from Cursor On")); ActionBuilder(this, DELETE_END_OF_WORD_CAMEL_CASE) - .setText(Tr::tr("Delete Word Camel Case from Cursor On")) - .setScriptable(true); + .setText(Tr::tr("Delete Word Camel Case from Cursor On")); ActionBuilder(this, DELETE_START_OF_LINE) .setText(Tr::tr("Delete Line up to Cursor")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Ctrl+Backspace"), {}); - ActionBuilder(this, DELETE_START_OF_WORD) - .setText(Tr::tr("Delete Word up to Cursor")) - .setScriptable(true); + ActionBuilder(this, DELETE_START_OF_WORD).setText(Tr::tr("Delete Word up to Cursor")); ActionBuilder(this, DELETE_START_OF_WORD_CAMEL_CASE) - .setText(Tr::tr("Delete Word Camel Case up to Cursor")) - .setScriptable(true); + .setText(Tr::tr("Delete Word Camel Case up to Cursor")); ActionBuilder(this, GOTO_BLOCK_START_WITH_SELECTION) .setText(Tr::tr("Go to Block Start with Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+{"))); ActionBuilder(this, GOTO_BLOCK_END_WITH_SELECTION) .setText(Tr::tr("Go to Block End with Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+}"))); ActionBuilder(this, MOVE_LINE_UP) .setText(Tr::tr("Move Line Up")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Up"))); ActionBuilder(this, MOVE_LINE_DOWN) .setText(Tr::tr("Move Line Down")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Down"))); ActionBuilder(this, COPY_LINE_UP) .setText(Tr::tr("Copy Line Up")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Up"))); ActionBuilder(this, COPY_LINE_DOWN) .setText(Tr::tr("Copy Line Down")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Down"))); ActionBuilder(this, JOIN_LINES) .setText(Tr::tr("Join Lines")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+J"))); ActionBuilder(this, INSERT_LINE_ABOVE) .setText(Tr::tr("Insert Line Above Current Line")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Return"))); ActionBuilder(this, INSERT_LINE_BELOW) .setText(Tr::tr("Insert Line Below Current Line")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Return"))); - ActionBuilder(this, SWITCH_UTF8BOM) - .setText(Tr::tr("Delete Word up to Cursor")) - .setScriptable(true); - ActionBuilder(this, INDENT) - .setText(Tr::tr("Indent")) - .setScriptable(true); - ActionBuilder(this, UNINDENT) - .setText(Tr::tr("Unindent")) - .setScriptable(true); + ActionBuilder(this, SWITCH_UTF8BOM).setText(Tr::tr("Delete Word up to Cursor")); + ActionBuilder(this, INDENT).setText(Tr::tr("Indent")); + ActionBuilder(this, UNINDENT).setText(Tr::tr("Unindent")); ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR) .setText(Tr::tr("Follow Symbol Under Cursor")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Qt::Key_F2)); ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT) .setText(Tr::tr("Follow Symbol Under Cursor in Next Split")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+E, F2"), Tr::tr("Ctrl+E, F2")); ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE) .setText(Tr::tr("Follow Type Under Cursor")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+F2"))); ActionBuilder(this, FOLLOW_SYMBOL_TO_TYPE_IN_NEXT_SPLIT) .setText(Tr::tr("Follow Type Under Cursor in Next Split")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+E, Shift+F2"), Tr::tr("Ctrl+E, Ctrl+Shift+F2")); ActionBuilder(this, FIND_USAGES) .setText(Tr::tr("Find References to Symbol Under Cursor")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+U"))); ActionBuilder(this, RENAME_SYMBOL) .setText(Tr::tr("Rename Symbol Under Cursor")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+R"))); ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR) .setText(Tr::tr("Jump to File Under Cursor")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Qt::Key_F2)); ActionBuilder(this, JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT) .setText(Tr::tr("Jump to File Under Cursor in Next Split")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+E, F2"), Tr::tr("Ctrl+E, F2")); - ActionBuilder(this, OPEN_CALL_HIERARCHY) - .setText(Tr::tr("Open Call Hierarchy")) - .setScriptable(true); + ActionBuilder(this, OPEN_CALL_HIERARCHY).setText(Tr::tr("Open Call Hierarchy")); ActionBuilder(this, OPEN_TYPE_HIERARCHY) .setText(Tr::tr("Open Type Hierarchy")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+Shift+T"), Tr::tr("Ctrl+Shift+T")); ActionBuilder(this, VIEW_PAGE_UP) .setText(Tr::tr("Move the View a Page Up and Keep the Cursor Position")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+PgUp"))); ActionBuilder(this, VIEW_PAGE_DOWN) .setText(Tr::tr("Move the View a Page Down and Keep the Cursor Position")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+PgDown"))); ActionBuilder(this, VIEW_LINE_UP) .setText(Tr::tr("Move the View a Line Up and Keep the Cursor Position")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Up"))); ActionBuilder(this, VIEW_LINE_DOWN) .setText(Tr::tr("Move the View a Line Down and Keep the Cursor Position")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Down"))); ActionManager::actionContainer(M_EDIT); ActionBuilder(this, SELECT_ENCODING) .setText(Tr::tr("Select Encoding...")) - .setScriptable(false) .addToContainer(M_EDIT, G_EDIT_OTHER); ActionBuilder(this, CIRCULAR_PASTE) .setText(Tr::tr("Paste from Clipboard History")) - .setScriptable(false) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+V"))) .addToContainer(M_EDIT, G_EDIT_COPYPASTE); ActionBuilder(this, NO_FORMAT_PASTE) .setText(Tr::tr("Paste Without Formatting")) - .setScriptable(false) .setDefaultKeySequence(Tr::tr("Ctrl+Alt+Shift+V"), QString()) .addToContainer(M_EDIT, G_EDIT_COPYPASTE); ActionManager::actionContainer(M_EDIT_ADVANCED); ActionBuilder(this, AUTO_INDENT_SELECTION) .setText(Tr::tr("Auto-&indent Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+I"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, AUTO_FORMAT_SELECTION) .setText(Tr::tr("Auto-&format Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+;"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, REWRAP_PARAGRAPH) .setText(Tr::tr("&Rewrap Paragraph")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+E, R"), Tr::tr("Ctrl+E, R")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, VISUALIZE_WHITESPACE) .setText(Tr::tr("&Visualize Whitespace")) - .setScriptable(false) .setDefaultKeySequence(Tr::tr("Meta+E, Meta+V"), Tr::tr("Ctrl+E, Ctrl+V")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, CLEAN_WHITESPACE) .setText(Tr::tr("Clean Whitespace")) - .setScriptable(true) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, TEXT_WRAPPING) .setText(Tr::tr("Enable Text &Wrapping")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+E, Meta+W"), Tr::tr("Ctrl+E, Ctrl+W")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT) .setCheckable(true); ActionBuilder(this, UN_COMMENT_SELECTION) .setText(Tr::tr("Toggle Comment &Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+/"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FORMAT); ActionBuilder(this, CUT_LINE) .setText(Tr::tr("Cut &Line")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Shift+Del"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, COPY_LINE) .setText(Tr::tr("Copy &Line")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Ins"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, COPY_WITH_HTML) .setText(Tr::tr("Copy With Highlighting")) - .setScriptable(true) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, ADD_CURSORS_TO_LINE_ENDS) .setText(Tr::tr("Create Cursors at Selected Line Ends")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Alt+Shift+I"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, ADD_SELECT_NEXT_FIND_MATCH) .setText(Tr::tr("Add Next Occurrence to Selection")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+D"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, DUPLICATE_SELECTION) .setText(Tr::tr("&Duplicate Selection")) - .setScriptable(true) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, DUPLICATE_SELECTION_AND_COMMENT) .setText(Tr::tr("&Duplicate Selection and Comment")) - .setScriptable(true) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, UPPERCASE_SELECTION) .setText(Tr::tr("Uppercase Selection")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+Shift+U"), Tr::tr("Alt+Shift+U")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, LOWERCASE_SELECTION) .setText(Tr::tr("Lowercase Selection")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+U"), Tr::tr("Alt+U")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, SORT_LINES) .setText(Tr::tr("Sort Lines")) - .setScriptable(true) .setDefaultKeySequence(Tr::tr("Meta+Shift+S"), Tr::tr("Alt+Shift+S")) .addToContainer(M_EDIT_ADVANCED, G_EDIT_TEXT); ActionBuilder(this, FOLD) .setText(Tr::tr("Fold")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+<"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); ActionBuilder(this, UNFOLD) .setText(Tr::tr("Unfold")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+>"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); ActionBuilder(this, UNFOLD_ALL) .setText(Tr::tr("Toggle &Fold All")) - .setScriptable(true) .addToContainer(M_EDIT_ADVANCED, G_EDIT_COLLAPSING); ActionBuilder(this, INCREASE_FONT_SIZE) .setText(Tr::tr("Increase Font Size")) - .setScriptable(false) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl++"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); ActionBuilder(this, DECREASE_FONT_SIZE) .setText(Tr::tr("Decrease Font Size")) - .setScriptable(false) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+-"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); ActionBuilder(this, RESET_FONT_SIZE) .setText(Tr::tr("Reset Font Size")) - .setScriptable(false) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+0"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_FONT); ActionBuilder(this, GOTO_BLOCK_START) .setText(Tr::tr("Go to Block Start")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+["))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); ActionBuilder(this, GOTO_BLOCK_END) .setText(Tr::tr("Go to Block End")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+]"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); ActionBuilder(this, SELECT_BLOCK_UP) .setText(Tr::tr("Select Block Up")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+U"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); ActionBuilder(this, SELECT_BLOCK_DOWN) .setText(Tr::tr("Select Block Down")) - .setScriptable(true) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Shift+Alt+U"))) .addToContainer(M_EDIT_ADVANCED, G_EDIT_BLOCKS); - ActionBuilder(this, SELECT_WORD_UNDER_CURSOR) - .setText(Tr::tr("Select Word Under Cursor")) - .setScriptable(true); + ActionBuilder(this, SELECT_WORD_UNDER_CURSOR).setText(Tr::tr("Select Word Under Cursor")); - ActionBuilder(this, GOTO_DOCUMENT_START) - .setText(Tr::tr("Go to Document Start")) - .setScriptable(true); - ActionBuilder(this, GOTO_DOCUMENT_END) - .setText(Tr::tr("Go to Document End")) - .setScriptable(true); - ActionBuilder(this, GOTO_LINE_START) - .setText(Tr::tr("Go to Line Start")) - .setScriptable(true); - ActionBuilder(this, GOTO_LINE_END) - .setText(Tr::tr("Go to Line End")) - .setScriptable(true); - ActionBuilder(this, GOTO_NEXT_LINE) - .setText(Tr::tr("Go to Next Line")) - .setScriptable(true); - ActionBuilder(this, GOTO_PREVIOUS_LINE) - .setText(Tr::tr("Go to Previous Line")) - .setScriptable(true); - ActionBuilder(this, GOTO_PREVIOUS_CHARACTER) - .setText(Tr::tr("Go to Previous Character")) - .setScriptable(true); - ActionBuilder(this, GOTO_NEXT_CHARACTER) - .setText(Tr::tr("Go to Next Character")) - .setScriptable(true); - ActionBuilder(this, GOTO_PREVIOUS_WORD) - .setText(Tr::tr("Go to Previous Word")) - .setScriptable(true); - ActionBuilder(this, GOTO_NEXT_WORD) - .setText(Tr::tr("Go to Next Word")) - .setScriptable(true); + ActionBuilder(this, GOTO_DOCUMENT_START).setText(Tr::tr("Go to Document Start")); + ActionBuilder(this, GOTO_DOCUMENT_END).setText(Tr::tr("Go to Document End")); + ActionBuilder(this, GOTO_LINE_START).setText(Tr::tr("Go to Line Start")); + ActionBuilder(this, GOTO_LINE_END).setText(Tr::tr("Go to Line End")); + ActionBuilder(this, GOTO_NEXT_LINE).setText(Tr::tr("Go to Next Line")); + ActionBuilder(this, GOTO_PREVIOUS_LINE).setText(Tr::tr("Go to Previous Line")); + ActionBuilder(this, GOTO_PREVIOUS_CHARACTER).setText(Tr::tr("Go to Previous Character")); + ActionBuilder(this, GOTO_NEXT_CHARACTER).setText(Tr::tr("Go to Next Character")); + ActionBuilder(this, GOTO_PREVIOUS_WORD).setText(Tr::tr("Go to Previous Word")); + ActionBuilder(this, GOTO_NEXT_WORD).setText(Tr::tr("Go to Next Word")); ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE) - .setText(Tr::tr("Go to Previous Word (Camel Case)")) - .setScriptable(true); - ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE) - .setText(Tr::tr("Go to Next Word (Camel Case)")) - .setScriptable(true); + .setText(Tr::tr("Go to Previous Word (Camel Case)")); + ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE).setText(Tr::tr("Go to Next Word (Camel Case)")); ActionBuilder(this, GOTO_LINE_START_WITH_SELECTION) - .setText(Tr::tr("Go to Line Start with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Line Start with Selection")); ActionBuilder(this, GOTO_LINE_END_WITH_SELECTION) - .setText(Tr::tr("Go to Line End with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Line End with Selection")); ActionBuilder(this, GOTO_NEXT_LINE_WITH_SELECTION) - .setText(Tr::tr("Go to Next Line with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Next Line with Selection")); ActionBuilder(this, GOTO_PREVIOUS_LINE_WITH_SELECTION) - .setText(Tr::tr("Go to Previous Line with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Previous Line with Selection")); ActionBuilder(this, GOTO_PREVIOUS_CHARACTER_WITH_SELECTION) - .setText(Tr::tr("Go to Previous Character with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Previous Character with Selection")); ActionBuilder(this, GOTO_NEXT_CHARACTER_WITH_SELECTION) - .setText(Tr::tr("Go to Next Character with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Next Character with Selection")); ActionBuilder(this, GOTO_PREVIOUS_WORD_WITH_SELECTION) - .setText(Tr::tr("Go to Previous Word with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Previous Word with Selection")); ActionBuilder(this, GOTO_NEXT_WORD_WITH_SELECTION) - .setText(Tr::tr("Go to Next Word with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Next Word with Selection")); ActionBuilder(this, GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION) - .setText(Tr::tr("Go to Previous Word (Camel Case) with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Previous Word (Camel Case) with Selection")); ActionBuilder(this, GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION) - .setText(Tr::tr("Go to Next Word (Camel Case) with Selection")) - .setScriptable(true); + .setText(Tr::tr("Go to Next Word (Camel Case) with Selection")); } } // namespace TextEditor::Internal From d7ed4f29cb5a919a410bb2f1d4918ec0f51ef95a Mon Sep 17 00:00:00 2001 From: Leena Miettinen Date: Tue, 9 Apr 2024 17:13:28 +0200 Subject: [PATCH 0136/1060] Doc: Turn Valgrind topics into how-tos and reference topics Remove obsolete overview topic. Task-number: QTCREATORBUG-29361 Change-Id: Ifecc868e9a04dd5f87b393d1dc1a75ca2b6c7db7 Reviewed-by: hjk --- .../images/qtcreator-valgrind-memcheck.png | Bin 2347 -> 0 bytes .../images/qtcreator-valgrind-memcheck.webp | Bin 0 -> 2034 bytes .../src/analyze/cpu-usage-analyzer.qdoc | 2 +- .../src/analyze/creator-analyze.qdoc | 6 +- .../analyze/creator-valgrind-overview.qdoc | 54 ----- .../src/analyze/creator-valgrind.qdoc | 226 +++++++++++------- .../external-resources.qdoc | 12 + ...creator-projects-settings-run-analyze.qdoc | 11 +- doc/qtcreator/src/qtcreator-toc.qdoc | 6 - .../src/qtquick/qtquick-profiler.qdoc | 4 +- 10 files changed, 159 insertions(+), 162 deletions(-) delete mode 100644 doc/qtcreator/images/qtcreator-valgrind-memcheck.png create mode 100644 doc/qtcreator/images/qtcreator-valgrind-memcheck.webp delete mode 100644 doc/qtcreator/src/analyze/creator-valgrind-overview.qdoc diff --git a/doc/qtcreator/images/qtcreator-valgrind-memcheck.png b/doc/qtcreator/images/qtcreator-valgrind-memcheck.png deleted file mode 100644 index 8131846ef53a06708367e77047b9557d9e9877e3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2347 zcmeAS@N?(olHy`uVBq!ia0y~yVBE*Rz)-=#%)r2~Yijy21_q`b0X`wFf`Wp=!ongV zB4T2qVq#)q;-cc>;t~?#5)u-Ul9EzVl2TGq($dm0GEy=!GP1HVva+&ra&mI=a&n5& z@*vE-JAcj@IW)dzt9 zef>OrGY$QKE&~wAGYIT5G&D3aGBP$cHZ?UhGc&WWu&{K|x3;#nwY9agvvY88aCCHZ zl9zXqPjqr}a;n?v0&=Sh2(;{Tb#--fb8`zfb9Z<5@bK{T^z@9e^z!oZ_4V~jwDZ@~ z^Y{1n?>Z0|7#I{36dW8J5)u*`8X6WB79JiR85tQB6%|$J8WR%}8yg!J7nhKbkSH&o zn3$M2`$AGuQc6lns=R!vOG|2MYU-kWsf%u8ghWn^SzwfpDl>E$lHm8Y+t zXJC-G>{dZRK|x`6%`e=wY7Cl@^wy5bxw(OiFI{bXV-1rTDSE= z)3Su-=H?a``4*SdmeiJ(eT!Q5?Q7Y0tFyDS%U`c6K))-{psQ(;FowqBUM^}>aHEiU^OrGgx|Z{NOKi}u~xx9`@i z16}?Hx&jW|T6*BtfdjX0U6`E+c1YcY3$rg=*m~i@g{lApF`(}_bIZ#Q(CXd3nE?AoR=!Otq-)T~&YPM;vp=od!M?!TzLKXY$d z*-cK4w2zf`^XDeso7tMU@AtoFwd_e=6JDHsY^cg4w3Si*hrkC}@0FcQcJD2V9&{zy zz3cq^Ugp=&k-lfY2bf2ud|CeYj=;~_ zIop=}_!0H(is4bgPdj7m_B+@u|J=ITqPeDTlF;$5KTURV>#y5co3*0Y`tdf?TfgV$ z-ZbaB_bxhj*|XCxmbc})-4hE4yyCxY{`*?<$ff^p87bLKKmA_(%=4P(4>$9E5?!r1 zMd#p?&06ngiT!%AZ0(vkqIV8O>(xyEH|u?;*u5(?nZH-HXv&96Rz^Fx2HM}O+t({U zh1+wsxzNNbd*>-X)zqE+t!kEdm5qz(%6pG9(|A*w-+nc_TG_pBR)wn7K2`6uGc#(g zt(+sc?~v@j$u+7UW~Z-h>f=T&B{FJb$vnxDPcw&0XHuhXr% zpYOFU3EsSJua-agsTps)&zeaRvhlI5nnw>7o^8dfQ+94BE}5mC>$r_w?hJi+x^ce{C@!v|MKPNXOovIZyk(m?$14{b^nxX z=dFdOW!>8K?Ck1JWG>0=%g7@?zJ+c)JKZko&nM<3o*I`#{k7)@sNJ0|(B;2i z>!iEq?i{SS=N0+<{_E^j1+V`;Y89yA+~`=Fe_~oeTc`8mJe zzS94?rQ(%P-J=iocAsmWlyK*p{`u3@-ThVdoY^7wYkQ_1__%EMSJsawy?A_Y|Glo( zC#`JPcW&=hd6{;5xtV__nljn3)EsA%7rOfYd8Cx)_qgD$8OAO7aZ9Gmv*$NV=eR$| zBhspvFX>zZe+|cv2@gM=z56voW#7)Zw-3t~ygc}J$E3$c)3-l=8%I9-{$F$b(?qw*<#*5VZLwE7UH_!kSNzn&C7SC$ zn@0X)onFfG)5Y-j>05Ug14V8s{a)?%YtiaEaTAxR1ZS$A?kh8Vo{$_idDG!)nOM#0 zP1bBj?kwJ_WMua7(^DBGrJRLTPbS<`;m`O{#3wMb^lgsomek4%r0S>nZ>>tDUN`gx;}=aq<$Xa0Upi_&B6dfpiI zp_gA?v&DTX>)Ou!!i-V2%w6g1E0^xwQn(@TX4d(vN&kN>3XDW2u42fs0nf2h8%I_`#_aiwWqDka~K#H7(8A5 KT-G@yGywpr9b47_ diff --git a/doc/qtcreator/images/qtcreator-valgrind-memcheck.webp b/doc/qtcreator/images/qtcreator-valgrind-memcheck.webp new file mode 100644 index 0000000000000000000000000000000000000000..c60fdbb72d404bd7e07a9a59ade90f93d6c3d91f GIT binary patch literal 2034 zcmWIYbaQ*f&cG1v>J$(bVBvF@oq<9Bu%iyc)qvgq<8yD@+8%({+n!upC{Op_x!WIP{C|*WyA6}C$@#Ip0zh=N1gJA?o^iqm&fOhJ?&o}Ui8AA zWqYoQ=cSmtE8c!xv}*mWlk9%kkbjSA<*Fi= zn;JY2NXu?A%eM4vJ}b$0)_Ahy5{8I#OCHw5E)BgJ5~jI2;-h(YCTjoD* z*Fqjm_qgvZCz=)XnpY->us*%9{+ue~Ql(R!l}p-rmOsCHs^&6NU2x(v-KA$^v^0`C zUKV9MI&bLqFsEqxr?8~gH=;LvMm39ZnpIuha#76m6sPXq}`~vY`aDGOU?0yB{pO_2jV{FV~^e){AlOao=N(NpKk5;tm!JY`S#& zOR!w!iW%*(OcDymHm$4NAGTprPn zX&YY5=yh~LERS*BSF5;C;ZWX^M|-0*j_Lo2UTO7`ze#a&hk1deuhg+mR z{@2={-Ga;h!=o<_?cWXVUoSWPR&i?aAHrzWlAT`b9|f=cb7x7S&id<1msfj6TN-uPh)yr|ZYf`; zCvGKSm(m=(dUfmN_fA)WR=V8W5w*jlzs$|sc+V6wQQuTYtyiq`*2z3=yB5S_nmuKc zqV0t0fIB<%k2*g&`m%B5SFO(PvYN&HvQ{RD z7_6Ih?%b^YvQs--lXB9e{rxRlCP!yCeLAyKqPCd(i_g=r6Sf-j8uC4_R*4>YaQx#v zoq&1Onmd%1CHpV#2;R2Wf9kX}>#s8LoA=ZNOCH*HKHBp94@*1QipSq4HdhDinIpgG z!R}xC7C3UZUHtH0=87Aq@r9Q$3eQxN&!jdSc}ve%+j{~VtrxatqnTOpm~15>%g8Y0*H_*AX-!TU?>yfDsbQI=#QCP5)pK7LJ;!%(U72anR*St}X^9S; zVXJie_cP4RDvmtJUOJs2KtAL{qHAN--wB<0k7U=)nV&w-+VbR$@Xq5sS_hdXewg5S z^8DGh56llPJV?6ox}9%_T9tEL{nIx(mv6o|bc=3sbUd4rW%XC&6(L2*XNyR*mdE( z?MAIO-ToTMU$SAs2<|C0~kWR7G|yvSpJtGuP6poZz~hlB&KU(bK`LRZ7FQu-=OyP&Nj0~1?x zxv=84xP4YH1n%frJE|0ITEATT$m?+Zv^gt&1fC8lIn})S=C#w}_rE*t-j?(C2mkux z(XXohe!6-5n#aZl6ANLhCkHqF{MujqW!GBy|E|1tw@MupCbV^Us$_9n{ayEM@xGU0 zLH{k>*Gqn^T{@S`SF%N5u9U{X3$Jen-v2HqGkcS&&vXHeXdxxRiHBN*8{OAjc&Kai z@Xyw>J~B*iC*9oj`oGOg+o?8mP??>M$N_wnq-HLuH*tR~-F?4l&x zujk2AF3u}>F@LLvQAXvHZrA-&jl91_%Kdzq#QJo40;}&2|3mdc|0aK!-|}DOkNQJ< O&i|eup>IlV{0sooa`Gnt literal 0 HcmV?d00001 diff --git a/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc b/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc index 9b746d03887..5bd12a859b5 100644 --- a/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc +++ b/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc @@ -506,5 +506,5 @@ The \l {Application Output} view shows some information even if the Performance Analyzer displays error messages. - \sa {Profiling Function Execution} + \sa {Profile function execution} */ diff --git a/doc/qtcreator/src/analyze/creator-analyze.qdoc b/doc/qtcreator/src/analyze/creator-analyze.qdoc index f57d97b8c02..75855716e71 100644 --- a/doc/qtcreator/src/analyze/creator-analyze.qdoc +++ b/doc/qtcreator/src/analyze/creator-analyze.qdoc @@ -49,11 +49,6 @@ Do static code analysis and architecture analysis to detect and eliminate unnecessary complexity of code. - \li \l{Using Valgrind Code Analysis Tools}{Valgrind Code Analysis Tools} - - Detect problems in memory management by using the Memcheck - tool and find cache misses in the code by using the Callgrind tool. - \li \l{Clang Tools} Detect problems in C, C++, and Objective-C programs by @@ -83,4 +78,5 @@ built-in trace-viewer (\c{chrome://tracing}). \endlist + \sa {Detect memory leaks with Memcheck}, {Profile function execution} */ diff --git a/doc/qtcreator/src/analyze/creator-valgrind-overview.qdoc b/doc/qtcreator/src/analyze/creator-valgrind-overview.qdoc deleted file mode 100644 index 61aca06cfd2..00000000000 --- a/doc/qtcreator/src/analyze/creator-valgrind-overview.qdoc +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2018 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -// ********************************************************************** -// NOTE: the sections are not ordered by their logical order to avoid -// reshuffling the file each time the index order changes (i.e., often). -// Run the fixnavi.pl script to adjust the links to the index order. -// ********************************************************************** - -/*! - \previouspage creator-axivion.html - \page creator-valgrind-overview.html - \nextpage creator-analyzer.html - - \title Using Valgrind Code Analysis Tools - - \QC integrates \l{http://valgrind.org/info/tools.html}{Valgrind code - analysis tools} for detecting memory leaks and - profiling function execution. You must download and install them separately - to use them from \QC. - - You can run the Valgrind tools either \e locally on the development host or - \e remotely on another host. You can use them to analyze both applications - for which you set up a project in \QC and applications for which you do not - have a project. - - Valgrind tools are supported locally only on Linux and \macos. However, - according to Valgrind.org, support on \macos 10.8 and 10.9 is experimental and - mostly broken. You can run the tools on a remote Linux machine or device - from any development host. - - To run the Valgrind tools to analyze an application for which you have a - project, open the project in \QC and select the kit to run the project. The - kit specifies whether the Valgrind tools are run locally or remotely. - - For more information about analyzing applications for which you do not have - a project, see \l{Running Valgrind Tools on External Applications}. - - To set preferences for the Valgrind tools, select \preferences > - \uicontrol Analyzer. You can override the general - settings for each project in the \uicontrol {Run Settings} for the project. - - The following sections describe how to use the Valgrind tools: - - \list - - \li \l{Detecting Memory Leaks with Memcheck} - - \li \l{Profiling Function Execution} - - \endlist - - \sa {Specify Valgrind settings for a project} -*/ diff --git a/doc/qtcreator/src/analyze/creator-valgrind.qdoc b/doc/qtcreator/src/analyze/creator-valgrind.qdoc index 47d4b8c1d6c..c46953803e9 100644 --- a/doc/qtcreator/src/analyze/creator-valgrind.qdoc +++ b/doc/qtcreator/src/analyze/creator-valgrind.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2021 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -8,92 +8,116 @@ // ********************************************************************** /*! - \previouspage creator-valgrind-overview.html - \page creator-analyzer.html - \nextpage creator-cache-profiler.html + \page creator-how-to-memcheck.html + \previouspage creator-how-tos.html - \title Detecting Memory Leaks with Memcheck + \ingroup creator-how-to-analyze - You can use the Memcheck tool included in the Valgrind tool suite to detect - problems that are related to memory management in applications. You can use + \title Detect memory leaks with Memcheck + + With the Memcheck tool in \l{Valgrind's Tool Suite}, you can detect + problems that are related to memory management in applications. Use the tool together with the GDB debugger. When a problem is detected, the application is interrupted and you can debug it. \note You can install and run Memcheck locally on Linux. You can run - it on a remote host or device from any development machine. On Windows, + it on a remote host or device from any computer. On Windows, you can use the \l{Detecting Memory Leaks with Heob}{Heob} heap observer to receive similar results. After you download and install Valgrind tools, you can use Memcheck from \QC. - To analyze applications: + To detect memory leaks in applications: \list 1 - \li In the \uicontrol Projects mode, select a debug build configuration. + \li Go to the \uicontrol Projects mode, and select a debug build + configuration. - \li Select \uicontrol Debug to open the \uicontrol Debug mode, and then - select \uicontrol Memcheck on the toolbar. + \li In the mode selector, select \uicontrol Debug > \uicontrol Memcheck. - \li Select the - \inlineimage icons/qtcreator-analyze-start-button.png "Start button" - button to start the application. + \image qtcreator-valgrind-memcheck.webp {Memcheck view} + + \li Select \inlineimage icons/qtcreator-analyze-start-button.png + to start the application. \li Use the application to analyze it. - \li Select the \inlineimage icons/stop_small.png "Stop button" - button to view the results of the analysis in the - \uicontrol {Analysis} view. + \li Select \inlineimage icons/stop_small.png to view the results of the + analysis in \uicontrol {Memory Issues}. \endlist - While the application is running, Memcheck checks all reads and writes of - memory and intercepts calls that allocate or free memory or create or - delete memory blocks. The results are displayed when you stop Memcheck. - Click a line to view where a memory leak - occurred and a stack trace that shows what caused it. + \section1 View memory issues - As an alternative to collecting data, you can select \inlineimage icons/open.png + While the application is running, Memcheck does the following: + + \list + \li Checks all reads and writes of memory. + \li Intercepts calls that allocate or free memory or create or + delete memory blocks. + \endlist + + You can see the results when you stop Memcheck. + + Select a line to see the place where a memory leak occurred and a stack trace + that shows what caused it. + + As an alternative to collecting data, select \inlineimage icons/open.png to load an external log file in XML format into the \uicontrol Memcheck view. - \image qtcreator-valgrind-memcheck.png "Memcheck view" - Move the mouse on a row to view more information about the function. To move between rows, select \inlineimage icons/prev.png - or \inlineimage icons/next.png - . + or \inlineimage icons/next.png. - To filter the results, select \inlineimage icons/filtericon.png - , and then select the types of issues to display in the view. You + To filter the results, select \inlineimage icons/filtericon.png, and + then select the types of issues to display in the view. You can view and hide definite and possible memory leaks, uninitialized values, invalid calls to \c free(), and external errors. For more information about using Memcheck, see - \l{http://valgrind.org/docs/manual/quick-start.html#quick-start.mcrun} - {Interpreting Memcheck's Output} in the Valgrind documentation. + \l{Interpreting Memcheck's Output} in the Valgrind documentation. - \section1 Selecting Options for Memory Analysis + \sa {Profile function execution}, + {Run Valgrind tools on external applications}, + {Specify Valgrind settings for a project}, {Valgrind Callgrind}, + {Valgrind Memcheck} +*/ - You can specify analyzer settings either globally for all projects or - separately for each project in the \l{Specifying Run Settings}{run settings} - of the project. +/*! + \page creator-preferences-memcheck.html + \previouspage creator-reference.html - To specify global settings for Valgrind, select \preferences > - \uicontrol Analyzer. The \uicontrol {Memcheck Memory Analysis Options} - group has Memcheck options. + \ingroup creator-reference-preferences-analyzer + + \title Valgrind Memcheck + + \brief Set preferences for Valgrind Memcheck. + + Set \l{Valgrind's Tool Suite}{Valgrind} preferences either globally for all + projects or separately for each project in the \l{Specifying Run Settings} + {run settings} of the project. + + To set global preferences for Valgrind, select \preferences > + \uicontrol Analyzer. Set Memcheck preferences in + \uicontrol {Memcheck Memory Analysis Options}. + + \image qtcreator-valgrind-memcheck-options.png {Memory Analysis options} In \uicontrol {Extra Memcheck arguments}, specify additional arguments for launching the executable. + \section1 Setting Stack Trace Length + Stack traces can get quite large and confusing, and therefore, reading them from the bottom up can help. If the stack trace is not big enough or it is too big, select \preferences > \uicontrol Analyzer and define the length of the stack trace in the \uicontrol {Backtrace frame count} field. - \image qtcreator-valgrind-memcheck-options.png "Memory Analysis options" + \section1 Tracking Origins of Uninitialized Memory Memcheck also reports uses of uninitialised values, most commonly with the message \uicontrol {Conditional jump or move depends on uninitialised value(s).} @@ -101,12 +125,14 @@ uninitialized memory} check box is selected by default. You can deselect it to make Memcheck run faster. + \section1 Viewing a Summary + Memcheck searches for memory leaks when the client application finishes. To view the amount of leaks that occurred, select \uicontrol {Summary Only} in the \uicontrol {Check for leaks on finish} field. To also view details of each leak, select \uicontrol Full. - \section2 Showing Reachable and Indirectly Lost Blocks + \section1 Showing Reachable and Indirectly Lost Blocks \e Reachable blocks are blocks that are pointed at by a pointer or chain of pointers and that might have been freed before the application exited. @@ -118,7 +144,7 @@ To have them reported, select the \uicontrol {Show reachable and indirectly lost blocks}. - \section2 Suppressing Errors + \section1 Suppressing Errors Memcheck detects numerous problems in the system libraries, such as the C library, which come pre-installed with your OS. As you cannot easily fix @@ -127,37 +153,40 @@ when the system is built. You can write your own suppression files if parts of your project have - errors you cannot fix and you do not want to be reminded of them. Click + errors you cannot fix and you do not want to be reminded of them. Select \uicontrol Add in the \uicontrol {MemCheck Memory Analysis} dialog to add the suppression files. - For more information about writing suppression files, see - \l{http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress} - {Suppressing Errors} in the Valgrind documentation. + For more information about writing suppression files, see + \l{Suppressing Errors} in the Valgrind documentation. + + \sa {Detect memory leaks with Memcheck}, {Profile function execution}, + {Run Valgrind tools on external applications}, + {Specify Valgrind settings for a project}, {Valgrind Callgrind} */ /*! - \previouspage creator-analyzer.html \page creator-cache-profiler.html - \nextpage creator-running-valgrind-remotely.html + \previouspage creator-how-tos.html - \title Profiling Function Execution + \ingroup creator-how-to-analyze - You can use the Callgrind tool included in the - \l{http://valgrind.org/info/tools.html}{Valgrind tool suite} to detect - problems that are related to executing functions. In addition, you - can load the data files generated by Callgrind into the - \l{https://kcachegrind.github.io/html/Home.html}{KCachegrind} - profile data visualization tool for browsing the performance results. + \title Profile function execution + + With the Callgrind tool in \l{Valgrind's Tool Suite}, you can detect problems + that are related to executing functions. Load the data files generated by + Callgrind into the \l{https://kcachegrind.github.io/html/Home.html} + {KCachegrind} profile data visualization tool to browse the performance + results. After you download and install Valgrind tools and KCachegrind, you can use Callgrind and KCachegrind from \QC. \note You can install and run Callgrind and KCachegrind locally on Linux. You can run Callgrind on a remote Linux machine or device from any - development machine. + computer. - \section1 Building Apps for Profiling + \section1 Build apps for profiling Callgrind records the call history of functions that are executed when the application is run. It collects the number of instructions that are @@ -181,28 +210,26 @@ options for GCC are: \c{-g -O2}. It is advisable to use such a setup for Callgrind profiling. - \section1 Collecting Data + \section1 Collect data To analyze applications: \list 1 - \li In the \uicontrol Projects mode, select a release build configuration. + \li Go to the \uicontrol Projects mode, and select a release build + configuration. - \li Select \uicontrol Debug to open the \uicontrol Debug mode, and then - select \uicontrol Callgrind on the toolbar. + \li In the mode selector, select \uicontrol Debug > \uicontrol Callgrind. - \image qtcreator-valgrind-callgrind-toolbar.png "Callgrind view toolbar" + \image qtcreator-valgrind-callgrind-toolbar.png {Callgrind view toolbar} - \li Select the - \inlineimage icons/qtcreator-analyze-start-button.png "Start button" - button to start the application. + \li Select \inlineimage icons/qtcreator-analyze-start-button.png + to start the application. \li Use the application to analyze it. - \li Select the \inlineimage icons/stop_small.png "Stop button" - button to view the results of the analysis in the - \uicontrol Functions view. + \li Select \inlineimage icons/stop_small.png to view the results of the + analysis in the \uicontrol Functions view. \endlist @@ -220,7 +247,7 @@ to view the data in KCachegrind. \QC launches KCachegrind and loads the data into it for visualization. - \section1 Viewing Collected Data + \section1 View collected data The results of the analysis are displayed in the \uicontrol Callgrind views. You can detach views and move them around. To revert the changes, select @@ -261,17 +288,31 @@ To remove template parameter lists when displaying function names, select \uicontrol <>. - \section1 Selecting Profiling Options + \sa {Detect memory leaks with Memcheck}, {Profile function execution}, + {Run Valgrind tools on external applications}, + {Specify Valgrind settings for a project}, {Valgrind Callgrind}, + {Valgrind Memcheck} +*/ - You can specify analyzer settings either globally for all projects or - separately for each project in the \l{Specifying Run Settings}{run settings} - of the project. +/*! + \page creator-preferences-callgrind.html + \previouspage creator-reference.html - To specify global settings for Valgrind, select \preferences > - \uicontrol Analyzer. The \uicontrol {Callgrind Profiling Options} - group has Callgrind options. + \ingroup creator-reference-preferences-analyzer - \image qtcreator-valgrind-callgrind-options.png "Valgrind options" + \title Valgrind Callgrind + + \brief Set preferences for Valgrind Callgrind. + + Set \l{Valgrind's Tool Suite}{Valgrind} preferences either globally for all + projects or separately for each project in the \l{Specifying Run Settings} + {run settings} of the project. + + To set global preferences for Valgrind, select \preferences > + \uicontrol Analyzer. Set Callgrind preferences in + \uicontrol {Callgrind Profiling Options}. + + \image qtcreator-valgrind-callgrind-options.png {Callgrind Profiling Options} In the \uicontrol {KCachegrind executable} field, enter the path to the KCachegrind executable to launch. @@ -292,7 +333,7 @@ global bus events of the event type \c Ge that are executed, select \uicontrol {Collect global bus events}. - \section2 Enabling Full Cache Simulation + \section1 Enabling Full Cache Simulation By default, only instruction read accesses (Ir) are counted. To fully simulate the cache, select the \uicontrol {Enable cache simulation} check box. @@ -308,7 +349,7 @@ \endlist - \section2 Enabling Branch Prediction Simulation + \section1 Enabling Branch Prediction Simulation To enable the following additional event counters, select the \uicontrol {Enable branch prediction simulation} check box: @@ -323,32 +364,39 @@ \endlist - \sa {Analyzing CPU Usage}, {Detach views} + \sa {Analyzing CPU Usage}, {Detect memory leaks with Memcheck}, + {Detach views}, {Run Valgrind tools on external applications}, + {Specify Valgrind settings for a project}, + {Valgrind Memcheck} */ /*! - \previouspage creator-cache-profiler.html \page creator-running-valgrind-remotely.html - \nextpage creator-clang-tools.html + \previouspage creator-how-tos.html - \title Running Valgrind Tools on External Applications + \ingroup creator-how-to-analyze - \QC integrates Valgrind code analysis tools for detecting memory - leaks and profiling function execution. + \title Run Valgrind tools on external applications + + With \l{Valgrind's Tool Suite}, you can detect memory leaks and profile + function execution. To run the Valgrind tools to analyze external applications for which you do not have a \QC project: \list 1 - \li Select \uicontrol Analyze > \uicontrol {Valgrind Memory Analyzer (External + \li Go to \uicontrol Analyze > \uicontrol {Valgrind Memory Analyzer (External Application)} or \uicontrol {Valgrind Function Profiler (External Application)}. - \image qtcreator-valgrind-remote-settings.png "Start Remote Analysis dialog" + \image qtcreator-valgrind-remote-settings.png {Start Remote Analysis dialog} - \li Specify the application to run and analyze, and the \l{glossary-buildandrun-kit}{kit} - to use. + \li Select the application to run and analyze, as well as the + \l{glossary-buildandrun-kit}{kit} to use. \endlist + \sa {Detect memory leaks with Memcheck}, {Profile function execution}, + {Kits}, {Specify Valgrind settings for a project}, {Valgrind Callgrind}, + {Valgrind Memcheck} */ diff --git a/doc/qtcreator/src/external-resources/external-resources.qdoc b/doc/qtcreator/src/external-resources/external-resources.qdoc index 3eceb28e568..ea624ab1326 100644 --- a/doc/qtcreator/src/external-resources/external-resources.qdoc +++ b/doc/qtcreator/src/external-resources/external-resources.qdoc @@ -185,3 +185,15 @@ \externalpage https://doc-snapshots.qt.io/applicationmanager-dev/cmake-qt6-am-create-installable-package.html \title qt6_am_create_installable_package */ +/*! + \externalpage https://valgrind.org/info/tools.html + \title Valgrind's Tool Suite +*/ +/*! + \externalpage https://valgrind.org/docs/manual/quick-start.html#quick-start.interpret + \title Interpreting Memcheck's Output +*/ +/*! + \externalpage https://valgrind.org/docs/manual/manual-core.html#manual-core.suppress + \title Suppressing Errors +*/ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-analyze.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-analyze.qdoc index 34233c90d83..99802a720b6 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-analyze.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-analyze.qdoc @@ -13,8 +13,8 @@ you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. - \QC integrates \l{Analyzing Code}{Valgrind code analysis tools} for - detecting memory leaks and profiling function execution. + With \l{Valgrind's Tool Suite}, you can detect memory leaks and profile + function execution. To specify Valgrind settings for the current project: @@ -38,11 +38,12 @@ \endlist - Click \uicontrol {Restore Global} to revert to the global settings. + Select \uicontrol {Restore Global} to revert to the global settings. To specify global Valgrind settings, select \preferences > \uicontrol Analyzer. - \sa {Configuring Projects}, {Selecting Options for Memory Analysis}, - {Selecting Profiling Options}, {Using Valgrind Code Analysis Tools} + \sa {Detect memory leaks with Memcheck}, {Profile function execution}, + {Run Valgrind tools on external applications}, {Configuring Projects}, + {Valgrind Callgrind}, {Valgrind Memcheck} */ diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index c462da8245a..0ce410b39e4 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -76,12 +76,6 @@ \list \li \l{Profiling QML Applications} \li \l{Checking Code Coverage} - \li \l{Using Valgrind Code Analysis Tools} - \list - \li \l{Detecting Memory Leaks with Memcheck} - \li \l{Profiling Function Execution} - \li \l{Running Valgrind Tools on External Applications} - \endlist \li \l{Detecting Memory Leaks with Heob} \li \l{Analyzing CPU Usage} \li \l{Analyzing Code with Cppcheck} diff --git a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc b/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc index 4acafaf42a1..4a9aa52da4e 100644 --- a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc +++ b/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc @@ -49,8 +49,8 @@ \if defined(qtcreator) If frames get dropped even though JavaScript is not being run, and there are large, unexplained gaps in the timeline, check your custom QQuickItem - implementations. You can use \l{Using Valgrind Code Analysis Tools} - {Valgrind} or other general purpose profilers to analyze C++ code. + implementations. You can use \l{Profile function execution} + {Valgrind Callgrind} or other general purpose profilers to analyze C++ code. You can use \e {full stack tracing} to trace from the top level QML or JavaScript down to the C++ and all the way to the kernel space. You can From 5b595f2cd12bade23b1b42c0986428615f51be58 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 2 Apr 2024 15:52:37 +0200 Subject: [PATCH 0137/1060] RemoteLinux: Parallelize Generic File copying Change-Id: I2774cfbab8cc073a268a6cbf038ea904cc70e3de Reviewed-by: Reviewed-by: Christian Kandeler Reviewed-by: Jarek Kobus --- src/plugins/remotelinux/linuxdevice.cpp | 138 ++++++++++++++++-------- 1 file changed, 94 insertions(+), 44 deletions(-) diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp index 5fcb808a7cc..5dd5f905599 100644 --- a/src/plugins/remotelinux/linuxdevice.cpp +++ b/src/plugins/remotelinux/linuxdevice.cpp @@ -15,6 +15,8 @@ #include #include +#include + #include #include #include @@ -23,7 +25,10 @@ #include #include +#include + #include +#include #include #include #include @@ -31,11 +36,12 @@ #include #include #include -#include #include #include +#include #include #include +#include #include #include @@ -1574,8 +1580,28 @@ private: QHash m_batches; }; +static void createDir(QPromise> &promise, const FilePath &pathToCreate) +{ + const expected_str result = pathToCreate.ensureWritableDir(); + promise.addResult(result); + + if (!result) + promise.future().cancel(); +}; + +static void copyFile(QPromise> &promise, const FileToTransfer &file) +{ + const expected_str result = file.m_source.copyFile(file.m_target); + promise.addResult(result); + + if (!result) + promise.future().cancel(); +}; + class GenericTransferImpl : public FileTransferInterface { + Tasking::TaskTreeRunner m_taskTree; + public: GenericTransferImpl(const FileTransferSetupData &setup) : FileTransferInterface(setup) @@ -1584,56 +1610,80 @@ public: private: void start() final { - m_fileCount = m_setup.m_files.size(); - m_currentIndex = 0; - m_checkedDirectories.clear(); - nextFile(); - } + using namespace Tasking; - void nextFile() - { - ProcessResultData result; - if (m_currentIndex >= m_fileCount) { - emit done(result); - return; - } + const QSet allParentDirs + = Utils::transform(m_setup.m_files, [](const FileToTransfer &f) { + return f.m_target.parentDir(); + }); - const FileToTransfer &file = m_setup.m_files.at(m_currentIndex); - const FilePath &source = file.m_source; - const FilePath &target = file.m_target; - ++m_currentIndex; + const LoopList iteratorParentDirs(QList(allParentDirs.cbegin(), allParentDirs.cend())); - const FilePath targetDir = target.parentDir(); - if (!m_checkedDirectories.contains(targetDir)) { - emit progress(Tr::tr("Creating directory: %1\n").arg(targetDir.toUserOutput())); - if (!targetDir.ensureWritableDir()) { - result.m_errorString = Tr::tr("Failed."); - result.m_exitCode = -1; // Random pick - emit done(result); - return; + const auto onCreateDirSetup = [iteratorParentDirs](Async> &async) { + async.setConcurrentCallData(createDir, *iteratorParentDirs); + if (Utils::isMainThread()) + async.setFutureSynchronizer(ExtensionSystem::PluginManager::futureSynchronizer()); + }; + + const auto onCreateDirDone = [this, + iteratorParentDirs](const Async> &async) { + const expected_str result = async.result(); + if (result) + emit progress( + Tr::tr("Created directory: %1\n").arg(iteratorParentDirs->toUserOutput())); + else + emit progress(result.error()); + }; + + const LoopList iterator(m_setup.m_files); + const Storage counterStorage; + + const auto onCopySetup = [iterator](Async> &async) { + async.setConcurrentCallData(copyFile, *iterator); + if (Utils::isMainThread()) + async.setFutureSynchronizer(ExtensionSystem::PluginManager::futureSynchronizer()); + }; + + const auto onCopyDone = [this, iterator, counterStorage]( + const Async> &async) { + const expected_str result = async.result(); + int &counter = *counterStorage; + ++counter; + + if (result) { + emit progress(Tr::tr("Copied %1/%2: %3 -> %4\n") + .arg(counter) + .arg(m_setup.m_files.size()) + .arg(iterator->m_source.toUserOutput()) + .arg(iterator->m_target.toUserOutput())); + } else { + emit progress(result.error() + "\n"); } - m_checkedDirectories.insert(targetDir); - } + }; - emit progress(Tr::tr("Copying %1/%2: %3 -> %4\n") - .arg(m_currentIndex) - .arg(m_fileCount) - .arg(source.toUserOutput(), target.toUserOutput())); - expected_str copyResult = source.copyFile(target); - if (!copyResult) { - result.m_errorString = Tr::tr("Failed: %1").arg(copyResult.error()); - result.m_exitCode = -1; // Random pick - emit done(result); - return; - } + const Group group{ + Group{ + parallelLimit(QThread::idealThreadCount() - 1), + iteratorParentDirs, + AsyncTask>(onCreateDirSetup, onCreateDirDone), + }, + Group{ + parallelLimit(2), + iterator, + counterStorage, + AsyncTask>(onCopySetup, onCopyDone), + }, + }; - // FIXME: Use asyncCopyFile instead - nextFile(); + m_taskTree.start(group, {}, [this](DoneWith result) { + ProcessResultData resultData; + if (result != DoneWith::Success) { + resultData.m_exitCode = -1; + resultData.m_errorString = Tr::tr("Failed to deploy files."); + } + emit done(resultData); + }); } - - int m_currentIndex = 0; - int m_fileCount = 0; - QSet m_checkedDirectories; }; FileTransferInterface *LinuxDevice::createFileTransferInterface( From 16362526773ddc6bc0fb6b49da837c4cbc0a64ec Mon Sep 17 00:00:00 2001 From: David Schulz Date: Wed, 10 Apr 2024 11:56:35 +0200 Subject: [PATCH 0138/1060] Editor: fix action text for switching utf8 bom Change-Id: I0be1f9527aa4b0681a2c1423031800eb170a3d9e Reviewed-by: Christian Stenger --- src/plugins/texteditor/texteditorplugin.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index e0f43e9a6fa..89384364eb3 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -392,7 +392,7 @@ void TextEditorPlugin::createEditorCommands() ActionBuilder(this, INSERT_LINE_BELOW) .setText(Tr::tr("Insert Line Below Current Line")) .setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Return"))); - ActionBuilder(this, SWITCH_UTF8BOM).setText(Tr::tr("Delete Word up to Cursor")); + ActionBuilder(this, SWITCH_UTF8BOM).setText(Tr::tr("Toggle UTF-8 BOM")); ActionBuilder(this, INDENT).setText(Tr::tr("Indent")); ActionBuilder(this, UNINDENT).setText(Tr::tr("Unindent")); ActionBuilder(this, FOLLOW_SYMBOL_UNDER_CURSOR) From 4c31b2ba6e6d2c8643919cf0f73beb226ec91beb Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 25 Mar 2024 19:08:19 -0400 Subject: [PATCH 0139/1060] Utils: explicitly search the ClientExtras child object by name only This class is missing the Q_OBJECT macro, so findChild was searching for a QObject with the appropriate name, then casting to ClientExtras. That means this change is a no-op. But it makes explicit what we meant. Plus, findChild() and findChildren() will enforce that the class they're searching for has the Q_OBJECT macro. Task-number: QTBUG-105023 Change-Id: I5f663c2f9f4149af84fefffd17c024995ef0c1af Reviewed-by: hjk Reviewed-by: David Schulz --- src/plugins/languageclient/languageclientutils.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/languageclient/languageclientutils.cpp b/src/plugins/languageclient/languageclientutils.cpp index 0428fd6a844..031b05c957f 100644 --- a/src/plugins/languageclient/languageclientutils.cpp +++ b/src/plugins/languageclient/languageclientutils.cpp @@ -235,8 +235,8 @@ void updateEditorToolBar(Core::IEditor *editor) TextDocument *document = textEditor->textDocument(); Client *client = LanguageClientManager::clientForDocument(textEditor->textDocument()); - ClientExtras *extras = widget->findChild(clientExtrasName, - Qt::FindDirectChildrenOnly); + ClientExtras *extras = static_cast( + widget->findChild(clientExtrasName, Qt::FindDirectChildrenOnly)); if (!extras) { if (!client) return; From 63cbe5078063bd549a954a73aaed3aeb414932dd Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 12 Apr 2024 09:28:59 +0200 Subject: [PATCH 0140/1060] CompilerExplorer: Remove unused lambda capture Amends 411100b037. Change-Id: I4835b9aed591f894943fb3625ee5b4eadd99bc0d Reviewed-by: Marcus Tillmanns --- src/plugins/compilerexplorer/compilerexplorereditor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index 107968d9702..0af2973b9b4 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -898,7 +898,7 @@ EditorFactory::EditorFactory() return &static_cast(editor)->m_undoStack; }; - setEditorCreator([this]() { return new Editor; }); + setEditorCreator([] { return new Editor; }); } QList AsmDocument::setCompileResult( From 3423309795e8373bc828db92c2cc0049e0e43d84 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Thu, 11 Apr 2024 11:28:27 +0200 Subject: [PATCH 0141/1060] CppEditor: Move CppCodeModelSettingsPage alongside CppCodeModelSettings The colocation will enable various improvements that we intend to do in follow-up patches. Change-Id: I1624396b953c80c327b971977a5fd6095ad1b5c0 Reviewed-by: David Schulz Reviewed-by: --- src/plugins/cppeditor/CMakeLists.txt | 1 - .../cppeditor/cppcodemodelsettings.cpp | 197 +++++++++++++++ src/plugins/cppeditor/cppcodemodelsettings.h | 5 + .../cppeditor/cppcodemodelsettingspage.cpp | 224 ------------------ .../cppeditor/cppcodemodelsettingspage.h | 11 - src/plugins/cppeditor/cppeditor.qbs | 2 - src/plugins/cppeditor/cppeditorplugin.cpp | 1 - 7 files changed, 202 insertions(+), 239 deletions(-) delete mode 100644 src/plugins/cppeditor/cppcodemodelsettingspage.cpp delete mode 100644 src/plugins/cppeditor/cppcodemodelsettingspage.h diff --git a/src/plugins/cppeditor/CMakeLists.txt b/src/plugins/cppeditor/CMakeLists.txt index 93c37beaca6..3a137a4d642 100644 --- a/src/plugins/cppeditor/CMakeLists.txt +++ b/src/plugins/cppeditor/CMakeLists.txt @@ -23,7 +23,6 @@ add_qtc_plugin(CppEditor cppcodemodelinspectordialog.cpp cppcodemodelinspectordialog.h cppcodemodelinspectordumper.cpp cppcodemodelinspectordumper.h cppcodemodelsettings.cpp cppcodemodelsettings.h - cppcodemodelsettingspage.cpp cppcodemodelsettingspage.h cppcodestylepreferences.cpp cppcodestylepreferences.h cppcodestylepreferencesfactory.cpp cppcodestylepreferencesfactory.h cppcodestylesettings.cpp cppcodestylesettings.h diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index d4a309363ac..4791fd528ee 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -5,24 +5,34 @@ #include "compileroptionsbuilder.h" #include "cppeditorconstants.h" +#include "cppeditortr.h" +#include #include #include #include +#include +#include #include #include +#include #include #include #include #include +#include #include #include #include #include +#include #include +#include +#include +#include using namespace ProjectExplorer; using namespace Utils; @@ -196,4 +206,191 @@ void CppCodeModelProjectSettings::saveSettings() m_project->setNamedSettings(Constants::CPPEDITOR_SETTINGSGROUP, variantFromStore(data)); } +namespace Internal { + +class CppCodeModelSettingsWidget final : public Core::IOptionsPageWidget +{ + Q_OBJECT +public: + CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); + + CppCodeModelSettings::Data data() const; + +signals: + void settingsDataChanged(); + +private: + void apply() final { CppCodeModelSettings::globalInstance().setGlobalData(data()); } + + QCheckBox *m_interpretAmbiguousHeadersAsCHeaders; + QCheckBox *m_ignorePchCheckBox; + QCheckBox *m_useBuiltinPreprocessorCheckBox; + QCheckBox *m_skipIndexingBigFilesCheckBox; + QSpinBox *m_bigFilesLimitSpinBox; + QCheckBox *m_ignoreFilesCheckBox; + QPlainTextEdit *m_ignorePatternTextEdit; +}; + +CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data) +{ + m_interpretAmbiguousHeadersAsCHeaders + = new QCheckBox(Tr::tr("Interpret ambiguous headers as C headers")); + + m_skipIndexingBigFilesCheckBox = new QCheckBox(Tr::tr("Do not index files greater than")); + m_skipIndexingBigFilesCheckBox->setChecked(data.skipIndexingBigFiles); + + m_bigFilesLimitSpinBox = new QSpinBox; + m_bigFilesLimitSpinBox->setSuffix(Tr::tr("MB")); + m_bigFilesLimitSpinBox->setRange(1, 500); + m_bigFilesLimitSpinBox->setValue(data.indexerFileSizeLimitInMb); + + m_ignoreFilesCheckBox = new QCheckBox(Tr::tr("Ignore files")); + m_ignoreFilesCheckBox->setToolTip( + "

    " + + Tr::tr("Ignore files that match these wildcard patterns, one wildcard per line.") + + "

    "); + + m_ignoreFilesCheckBox->setChecked(data.ignoreFiles); + m_ignorePatternTextEdit = new QPlainTextEdit(data.ignorePattern); + m_ignorePatternTextEdit->setToolTip(m_ignoreFilesCheckBox->toolTip()); + m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); + + connect(m_ignoreFilesCheckBox, &QCheckBox::stateChanged, this, [this] { + m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); + }); + + m_ignorePchCheckBox = new QCheckBox(Tr::tr("Ignore precompiled headers")); + m_ignorePchCheckBox->setToolTip(Tr::tr( + "

    When precompiled headers are not ignored, the parsing for code " + "completion and semantic highlighting will process the precompiled header before " + "processing any file.

    ")); + + m_useBuiltinPreprocessorCheckBox = new QCheckBox(Tr::tr("Use built-in preprocessor to show " + "pre-processed files")); + m_useBuiltinPreprocessorCheckBox->setToolTip + (Tr::tr("Uncheck this to invoke the actual compiler " + "to show a pre-processed source file in the editor.")); + + m_interpretAmbiguousHeadersAsCHeaders->setChecked(data.interpretAmbigiousHeadersAsC); + m_ignorePchCheckBox->setChecked(data.pchUsage == CppCodeModelSettings::PchUse_None); + m_useBuiltinPreprocessorCheckBox->setChecked(data.useBuiltinPreprocessor); + + using namespace Layouting; + + Column { + Group { + title(Tr::tr("General")), + Column { + m_interpretAmbiguousHeadersAsCHeaders, + m_ignorePchCheckBox, + m_useBuiltinPreprocessorCheckBox, + Row { m_skipIndexingBigFilesCheckBox, m_bigFilesLimitSpinBox, st }, + Row { Column { m_ignoreFilesCheckBox, st }, m_ignorePatternTextEdit }, + } + }, + st + }.attachTo(this); + + for (const QCheckBox *const b : {m_interpretAmbiguousHeadersAsCHeaders, + m_ignorePchCheckBox, + m_useBuiltinPreprocessorCheckBox, + m_skipIndexingBigFilesCheckBox, + m_ignoreFilesCheckBox}) { + connect(b, &QCheckBox::toggled, this, &CppCodeModelSettingsWidget::settingsDataChanged); + } + connect(m_bigFilesLimitSpinBox, &QSpinBox::valueChanged, + this, &CppCodeModelSettingsWidget::settingsDataChanged); + + const auto timer = new QTimer(this); + timer->setSingleShot(true); + timer->setInterval(1000); + connect(timer, &QTimer::timeout, this, &CppCodeModelSettingsWidget::settingsDataChanged); + connect(m_ignorePatternTextEdit, &QPlainTextEdit::textChanged, + timer, qOverload<>(&QTimer::start)); +} + +CppCodeModelSettings::Data CppCodeModelSettingsWidget::data() const +{ + CppCodeModelSettings::Data data; + data.interpretAmbigiousHeadersAsC = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); + data.skipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); + data.useBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); + data.ignoreFiles = m_ignoreFilesCheckBox->isChecked(); + data.ignorePattern = m_ignorePatternTextEdit->toPlainText(); + data.indexerFileSizeLimitInMb = m_bigFilesLimitSpinBox->value(); + data.pchUsage = m_ignorePchCheckBox->isChecked() ? CppCodeModelSettings::PchUse_None + : CppCodeModelSettings::PchUse_BuildSystem; + return data; +} + +class CppCodeModelSettingsPage final : public Core::IOptionsPage +{ +public: + CppCodeModelSettingsPage() + { + setId(Constants::CPP_CODE_MODEL_SETTINGS_ID); + setDisplayName(Tr::tr("Code Model")); + setCategory(Constants::CPP_SETTINGS_CATEGORY); + setDisplayCategory(Tr::tr("C++")); + setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); + setWidgetCreator( + [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::globalInstance().data()); }); + } +}; + +void setupCppCodeModelSettingsPage() +{ + static CppCodeModelSettingsPage theCppCodeModelSettingsPage; +} + +class CppCodeModelProjectSettingsWidget : public ProjectSettingsWidget +{ +public: + CppCodeModelProjectSettingsWidget(const CppCodeModelProjectSettings &settings) + : m_settings(settings), m_widget(settings.data()) + { + setGlobalSettingsId(Constants::CPP_CODE_MODEL_SETTINGS_ID); + const auto layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(&m_widget); + + setUseGlobalSettings(m_settings.useGlobalSettings()); + m_widget.setEnabled(!useGlobalSettings()); + connect(this, &ProjectSettingsWidget::useGlobalSettingsChanged, this, + [this](bool checked) { + m_widget.setEnabled(!checked); + m_settings.setUseGlobalSettings(checked); + if (!checked) + m_settings.setData(m_widget.data()); + }); + + connect(&m_widget, &CppCodeModelSettingsWidget::settingsDataChanged, + this, [this] { m_settings.setData(m_widget.data()); }); + } + +private: + CppCodeModelProjectSettings m_settings; + CppCodeModelSettingsWidget m_widget; +}; + +class CppCodeModelProjectSettingsPanelFactory final : public ProjectPanelFactory +{ +public: + CppCodeModelProjectSettingsPanelFactory() + { + setPriority(100); + setDisplayName(Tr::tr("C++ Code Model")); + setCreateWidgetFunction([](Project *project) { + return new CppCodeModelProjectSettingsWidget(project); + }); + } +}; +void setupCppCodeModelProjectSettingsPanel() +{ + static CppCodeModelProjectSettingsPanelFactory factory; +} + +} // namespace Internal } // namespace CppEditor + +#include diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index 0bd9b05fbd3..eedc01402bc 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -108,4 +108,9 @@ private: bool m_useGlobalSettings = true; }; +namespace Internal { +void setupCppCodeModelSettingsPage(); +void setupCppCodeModelProjectSettingsPanel(); +} // namespace Internal + } // namespace CppEditor diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp b/src/plugins/cppeditor/cppcodemodelsettingspage.cpp deleted file mode 100644 index 1b5872c7a3a..00000000000 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "cppcodemodelsettingspage.h" - -#include "clangdsettings.h" -#include "cppcodemodelsettings.h" -#include "cppeditorconstants.h" -#include "cppeditortr.h" - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace ProjectExplorer; - -namespace CppEditor::Internal { - -class CppCodeModelSettingsWidget final : public Core::IOptionsPageWidget -{ - Q_OBJECT -public: - CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); - - CppCodeModelSettings::Data data() const; - -signals: - void settingsDataChanged(); - -private: - void apply() final { CppCodeModelSettings::globalInstance().setGlobalData(data()); } - - QCheckBox *m_interpretAmbiguousHeadersAsCHeaders; - QCheckBox *m_ignorePchCheckBox; - QCheckBox *m_useBuiltinPreprocessorCheckBox; - QCheckBox *m_skipIndexingBigFilesCheckBox; - QSpinBox *m_bigFilesLimitSpinBox; - QCheckBox *m_ignoreFilesCheckBox; - QPlainTextEdit *m_ignorePatternTextEdit; -}; - -CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data) -{ - m_interpretAmbiguousHeadersAsCHeaders - = new QCheckBox(Tr::tr("Interpret ambiguous headers as C headers")); - - m_skipIndexingBigFilesCheckBox = new QCheckBox(Tr::tr("Do not index files greater than")); - m_skipIndexingBigFilesCheckBox->setChecked(data.skipIndexingBigFiles); - - m_bigFilesLimitSpinBox = new QSpinBox; - m_bigFilesLimitSpinBox->setSuffix(Tr::tr("MB")); - m_bigFilesLimitSpinBox->setRange(1, 500); - m_bigFilesLimitSpinBox->setValue(data.indexerFileSizeLimitInMb); - - m_ignoreFilesCheckBox = new QCheckBox(Tr::tr("Ignore files")); - m_ignoreFilesCheckBox->setToolTip( - "

    " - + Tr::tr("Ignore files that match these wildcard patterns, one wildcard per line.") - + "

    "); - - m_ignoreFilesCheckBox->setChecked(data.ignoreFiles); - m_ignorePatternTextEdit = new QPlainTextEdit(data.ignorePattern); - m_ignorePatternTextEdit->setToolTip(m_ignoreFilesCheckBox->toolTip()); - m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); - - connect(m_ignoreFilesCheckBox, &QCheckBox::stateChanged, this, [this] { - m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); - }); - - m_ignorePchCheckBox = new QCheckBox(Tr::tr("Ignore precompiled headers")); - m_ignorePchCheckBox->setToolTip(Tr::tr( - "

    When precompiled headers are not ignored, the parsing for code " - "completion and semantic highlighting will process the precompiled header before " - "processing any file.

    ")); - - m_useBuiltinPreprocessorCheckBox = new QCheckBox(Tr::tr("Use built-in preprocessor to show " - "pre-processed files")); - m_useBuiltinPreprocessorCheckBox->setToolTip - (Tr::tr("Uncheck this to invoke the actual compiler " - "to show a pre-processed source file in the editor.")); - - m_interpretAmbiguousHeadersAsCHeaders->setChecked(data.interpretAmbigiousHeadersAsC); - m_ignorePchCheckBox->setChecked(data.pchUsage == CppCodeModelSettings::PchUse_None); - m_useBuiltinPreprocessorCheckBox->setChecked(data.useBuiltinPreprocessor); - - using namespace Layouting; - - Column { - Group { - title(Tr::tr("General")), - Column { - m_interpretAmbiguousHeadersAsCHeaders, - m_ignorePchCheckBox, - m_useBuiltinPreprocessorCheckBox, - Row { m_skipIndexingBigFilesCheckBox, m_bigFilesLimitSpinBox, st }, - Row { Column { m_ignoreFilesCheckBox, st }, m_ignorePatternTextEdit }, - } - }, - st - }.attachTo(this); - - for (const QCheckBox *const b : {m_interpretAmbiguousHeadersAsCHeaders, - m_ignorePchCheckBox, - m_useBuiltinPreprocessorCheckBox, - m_skipIndexingBigFilesCheckBox, - m_ignoreFilesCheckBox}) { - connect(b, &QCheckBox::toggled, this, &CppCodeModelSettingsWidget::settingsDataChanged); - } - connect(m_bigFilesLimitSpinBox, &QSpinBox::valueChanged, - this, &CppCodeModelSettingsWidget::settingsDataChanged); - - const auto timer = new QTimer(this); - timer->setSingleShot(true); - timer->setInterval(1000); - connect(timer, &QTimer::timeout, this, &CppCodeModelSettingsWidget::settingsDataChanged); - connect(m_ignorePatternTextEdit, &QPlainTextEdit::textChanged, - timer, qOverload<>(&QTimer::start)); -} - -CppCodeModelSettings::Data CppCodeModelSettingsWidget::data() const -{ - CppCodeModelSettings::Data data; - data.interpretAmbigiousHeadersAsC = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); - data.skipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); - data.useBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); - data.ignoreFiles = m_ignoreFilesCheckBox->isChecked(); - data.ignorePattern = m_ignorePatternTextEdit->toPlainText(); - data.indexerFileSizeLimitInMb = m_bigFilesLimitSpinBox->value(); - data.pchUsage = m_ignorePchCheckBox->isChecked() ? CppCodeModelSettings::PchUse_None - : CppCodeModelSettings::PchUse_BuildSystem; - return data; -} - -class CppCodeModelSettingsPage final : public Core::IOptionsPage -{ -public: - CppCodeModelSettingsPage() - { - setId(Constants::CPP_CODE_MODEL_SETTINGS_ID); - setDisplayName(Tr::tr("Code Model")); - setCategory(Constants::CPP_SETTINGS_CATEGORY); - setDisplayCategory(Tr::tr("C++")); - setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); - setWidgetCreator( - [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::globalInstance().data()); }); - } -}; - -void setupCppCodeModelSettingsPage() -{ - static CppCodeModelSettingsPage theCppCodeModelSettingsPage; -} - -class CppCodeModelProjectSettingsWidget : public ProjectSettingsWidget -{ -public: - CppCodeModelProjectSettingsWidget(const CppCodeModelProjectSettings &settings) - : m_settings(settings), m_widget(settings.data()) - { - setGlobalSettingsId(Constants::CPP_CODE_MODEL_SETTINGS_ID); - const auto layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(&m_widget); - - setUseGlobalSettings(m_settings.useGlobalSettings()); - m_widget.setEnabled(!useGlobalSettings()); - connect(this, &ProjectSettingsWidget::useGlobalSettingsChanged, this, - [this](bool checked) { - m_widget.setEnabled(!checked); - m_settings.setUseGlobalSettings(checked); - if (!checked) - m_settings.setData(m_widget.data()); - }); - - connect(&m_widget, &CppCodeModelSettingsWidget::settingsDataChanged, - this, [this] { m_settings.setData(m_widget.data()); }); - } - -private: - CppCodeModelProjectSettings m_settings; - CppCodeModelSettingsWidget m_widget; -}; - -class CppCodeModelProjectSettingsPanelFactory final : public ProjectPanelFactory -{ -public: - CppCodeModelProjectSettingsPanelFactory() - { - setPriority(100); - setDisplayName(Tr::tr("C++ Code Model")); - setCreateWidgetFunction([](Project *project) { - return new CppCodeModelProjectSettingsWidget(project); - }); - } -}; -void setupCppCodeModelProjectSettingsPanel() -{ - static CppCodeModelProjectSettingsPanelFactory factory; -} - -} // CppEditor::Internal - -#include "cppcodemodelsettingspage.moc" diff --git a/src/plugins/cppeditor/cppcodemodelsettingspage.h b/src/plugins/cppeditor/cppcodemodelsettingspage.h deleted file mode 100644 index 36d47ff8751..00000000000 --- a/src/plugins/cppeditor/cppcodemodelsettingspage.h +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -namespace CppEditor::Internal { - -void setupCppCodeModelSettingsPage(); -void setupCppCodeModelProjectSettingsPanel(); - -} // CppEditor::Internal diff --git a/src/plugins/cppeditor/cppeditor.qbs b/src/plugins/cppeditor/cppeditor.qbs index b805e3fae9b..c535488de90 100644 --- a/src/plugins/cppeditor/cppeditor.qbs +++ b/src/plugins/cppeditor/cppeditor.qbs @@ -65,8 +65,6 @@ QtcPlugin { "cppcodemodelinspectordumper.h", "cppcodemodelsettings.cpp", "cppcodemodelsettings.h", - "cppcodemodelsettingspage.cpp", - "cppcodemodelsettingspage.h", "cppcodestylepreferences.cpp", "cppcodestylepreferences.h", "cppcodestylepreferencesfactory.cpp", diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 77a9997244c..96a476c5234 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -5,7 +5,6 @@ #include "cppautocompleter.h" #include "cppcodemodelinspectordialog.h" #include "cppcodemodelsettings.h" -#include "cppcodemodelsettingspage.h" #include "cppcodestylesettingspage.h" #include "cppeditorconstants.h" #include "cppeditordocument.h" From 56c388000a311649d768ed0f2ea75408beaf5a65 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Fri, 12 Apr 2024 09:06:46 +0200 Subject: [PATCH 0142/1060] Async: Re-enable onResultReady tests Enable them conditionally, since the fix went into Qt 6.6. Task-number: QTBUG-119169 Change-Id: I6b9f1a9da6a5b6337384f37d940195f09bd28bd4 Reviewed-by: Eike Ziller --- tests/auto/utils/async/tst_async.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/auto/utils/async/tst_async.cpp b/tests/auto/utils/async/tst_async.cpp index e25a443cce1..1c3f7a19f2d 100644 --- a/tests/auto/utils/async/tst_async.cpp +++ b/tests/auto/utils/async/tst_async.cpp @@ -392,8 +392,7 @@ public: void tst_Async::onResultReady() { -// TODO: Re-enable when QTBUG-119169 is fixed. -#if 0 +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) { // lambda QObject context; QFuture f = Utils::asyncRun([](QPromise &fi) { From cdc4a8e42b42d02cb8a268bb72a603499a208fb0 Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Thu, 11 Apr 2024 16:21:27 +0200 Subject: [PATCH 0143/1060] Themes: Fix reading "Includes" QSettings can already read QStringLists, no need to manually re-invent the wheel - and QSettings actually handles whitespace around the seperating comma correctly. Fixes `Includes=foo.inc, blah.inc` Change-Id: Id1849ac0cd5f3bcc8aaaa1c574ec2d086ef3e0f3 Reviewed-by: Reviewed-by: Alessandro Portale --- src/libs/utils/theme/theme.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/utils/theme/theme.cpp b/src/libs/utils/theme/theme.cpp index 9b24078f86a..3b1d1773cab 100644 --- a/src/libs/utils/theme/theme.cpp +++ b/src/libs/utils/theme/theme.cpp @@ -185,7 +185,7 @@ void Theme::setDisplayName(const QString &name) void Theme::readSettingsInternal(QSettings &settings) { - const QStringList includes = settings.value("Includes").toString().split(",", Qt::SkipEmptyParts); + const QStringList includes = settings.value("Includes").toStringList(); for (const QString &include : includes) { FilePath path = FilePath::fromString(d->fileName); From 41e581d0e1cbf6db6d3945989b005d10e0775370 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Thu, 11 Apr 2024 15:04:36 +0200 Subject: [PATCH 0144/1060] Editor: fix assist actions Amends 411100b0378202dc617acaa236f4730eb4cc43b2 Fixes: QTCREATORBUG-30673 Change-Id: Icc82b6f5526d229a13a7061cbc44904837c25f06 Reviewed-by: Christian Kandeler --- src/plugins/texteditor/texteditor.cpp | 16 +++++ src/plugins/texteditor/texteditorplugin.cpp | 72 +++++++-------------- 2 files changed, 41 insertions(+), 47 deletions(-) diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index e3d2c1c94e3..215f54aadcf 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -3869,6 +3869,22 @@ void TextEditorWidgetPrivate::registerActions() using namespace Core::Constants; using namespace TextEditor::Constants; + ActionBuilder(this, Constants::COMPLETE_THIS) + .setContext(m_editorContext) + .addOnTriggered(this, [this] { q->invokeAssist(Completion); }); + + ActionBuilder(this, Constants::FUNCTION_HINT) + .setContext(m_editorContext) + .addOnTriggered(this, [this] { q->invokeAssist(FunctionHint); }); + + ActionBuilder(this, Constants::QUICKFIX_THIS) + .setContext(m_editorContext) + .addOnTriggered(this, [this] { q->invokeAssist(QuickFix); }); + + ActionBuilder(this, Constants::SHOWCONTEXTMENU) + .setContext(m_editorContext) + .addOnTriggered(this, [this] { q->showContextMenu(); }); + m_undoAction = ActionBuilder(this, UNDO) .setContext(m_editorContext) .addOnTriggered([this] { q->undo(); }) diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index 89384364eb3..5db6a17e0d5 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -123,53 +123,6 @@ void TextEditorPlugin::initialize() setupMarkdownEditor(); setupJsonEditor(); - Context context(TextEditor::Constants::C_TEXTEDITOR); - - // Add shortcut for invoking automatic completion - Command *command = nullptr; - ActionBuilder(this, Constants::COMPLETE_THIS) - .setText(Tr::tr("Trigger Completion")) - .setContext(context) - .bindCommand(&command) - .setDefaultKeySequence(Tr::tr("Meta+Space"), Tr::tr("Ctrl+Space")) - .addOnTriggered(this, [] { - if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor()) - editor->editorWidget()->invokeAssist(Completion); - }); - - connect(command, &Command::keySequenceChanged, [command] { - FancyLineEdit::setCompletionShortcut(command->keySequence()); - }); - FancyLineEdit::setCompletionShortcut(command->keySequence()); - - // Add shortcut for invoking function hint completion - ActionBuilder(this, Constants::FUNCTION_HINT) - .setText(Tr::tr("Display Function Hint")) - .setContext(context) - .setDefaultKeySequence(Tr::tr("Meta+Shift+D"), Tr::tr("Ctrl+Shift+D")) - .addOnTriggered(this, [] { - if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor()) - editor->editorWidget()->invokeAssist(FunctionHint); - }); - - // Add shortcut for invoking quick fix options - ActionBuilder(this, Constants::QUICKFIX_THIS) - .setText(Tr::tr("Trigger Refactoring Action")) - .setContext(context) - .setDefaultKeySequence(Tr::tr("Alt+Return")) - .addOnTriggered(this, [] { - if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor()) - editor->editorWidget()->invokeAssist(QuickFix); - }); - - ActionBuilder(this, Constants::SHOWCONTEXTMENU) - .setText(Tr::tr("Show Context Menu")) - .setContext(context) - .addOnTriggered(this, [] { - if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor()) - editor->editorWidget()->showContextMenu(); - }); - // Add text snippet provider. SnippetProvider::registerGroup(Constants::TEXT_SNIPPET_GROUP_ID, Tr::tr("Text", "SnippetProvider")); @@ -354,6 +307,31 @@ void TextEditorPlugin::createStandardContextMenu() void TextEditorPlugin::createEditorCommands() { using namespace Core::Constants; + // Add shortcut for invoking automatic completion + Command *command = nullptr; + ActionBuilder(this, Constants::COMPLETE_THIS) + .setText(Tr::tr("Trigger Completion")) + .bindCommand(&command) + .setDefaultKeySequence(Tr::tr("Meta+Space"), Tr::tr("Ctrl+Space")); + + connect(command, &Command::keySequenceChanged, [command] { + FancyLineEdit::setCompletionShortcut(command->keySequence()); + }); + FancyLineEdit::setCompletionShortcut(command->keySequence()); + + // Add shortcut for invoking function hint completion + ActionBuilder(this, Constants::FUNCTION_HINT) + .setText(Tr::tr("Display Function Hint")) + .setDefaultKeySequence(Tr::tr("Meta+Shift+D"), Tr::tr("Ctrl+Shift+D")); + + // Add shortcut for invoking quick fix options + ActionBuilder(this, Constants::QUICKFIX_THIS) + .setText(Tr::tr("Trigger Refactoring Action")) + .setDefaultKeySequence(Tr::tr("Alt+Return")); + + ActionBuilder(this, Constants::SHOWCONTEXTMENU) + .setText(Tr::tr("Show Context Menu")); + ActionBuilder(this, DELETE_LINE).setText(Tr::tr("Delete &Line")); ActionBuilder(this, DELETE_END_OF_LINE).setText(Tr::tr("Delete Line from Cursor On")); ActionBuilder(this, DELETE_END_OF_WORD).setText(Tr::tr("Delete Word from Cursor On")); From 18a867aa237778a7e73b7fa8f67d67c82c987e8e Mon Sep 17 00:00:00 2001 From: David Schulz Date: Fri, 12 Apr 2024 12:48:34 +0200 Subject: [PATCH 0145/1060] Editor: use unique id without common part Otherwise we also got override action warnings after opening a second editor. Change-Id: Id600eaa120e32399a941768ae5d5e35ab969be49 Reviewed-by: Eike Ziller --- src/plugins/texteditor/texteditor.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 215f54aadcf..089c483d2eb 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -1066,8 +1066,7 @@ TextEditorWidgetPrivate::TextEditorWidgetPrivate(TextEditorWidget *parent) , m_codeAssistant(parent) , m_hoverHandlerRunner(parent, m_hoverHandlers) , m_autoCompleter(new AutoCompleter) - , m_editorContext( - Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID).withSuffix(QUuid::createUuid().toString())) + , m_editorContext(Id::fromString(QUuid::createUuid().toString())) { m_selectionHighlightOverlay->show(); auto aggregate = new Aggregation::Aggregate; From abd538507ac943e478fec1e23549aa5e986dacb5 Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 2 Feb 2024 11:16:21 +0100 Subject: [PATCH 0146/1060] ProjectExplorer: Make settings access more direct A step towards aspectification. Change-Id: Iabf5e56e993449dc482d1d2ab6eeb2885243ab3e Reviewed-by: Christian Kandeler --- src/plugins/android/androidrunner.cpp | 3 +- src/plugins/autotest/testrunner.cpp | 9 +- .../cmakeprojectmanager/cmakekitaspect.cpp | 2 +- src/plugins/debugger/debuggerplugin.cpp | 2 +- .../projectexplorer/abstractprocessstep.cpp | 2 +- src/plugins/projectexplorer/appoutputpane.cpp | 6 +- src/plugins/projectexplorer/buildaspects.cpp | 2 +- src/plugins/projectexplorer/buildmanager.cpp | 20 +- .../projectexplorer/environmentaspect.cpp | 4 +- src/plugins/projectexplorer/msvctoolchain.cpp | 2 +- .../projectexplorer/projectexplorer.cpp | 170 +--------- src/plugins/projectexplorer/projectexplorer.h | 4 - .../projectexplorersettings.cpp | 316 +++++++++++++++--- .../projectexplorer/projectexplorersettings.h | 34 +- .../runconfigurationaspects.cpp | 4 +- src/plugins/projectexplorer/target.cpp | 2 +- .../projectexplorer/userfileaccessor.cpp | 10 +- 17 files changed, 316 insertions(+), 276 deletions(-) diff --git a/src/plugins/android/androidrunner.cpp b/src/plugins/android/androidrunner.cpp index 152c5fa4c58..22bb64b0a4d 100644 --- a/src/plugins/android/androidrunner.cpp +++ b/src/plugins/android/androidrunner.cpp @@ -11,7 +11,6 @@ #include "androidtr.h" #include -#include #include #include #include @@ -88,7 +87,7 @@ AndroidRunner::~AndroidRunner() void AndroidRunner::start() { - if (!ProjectExplorerPlugin::projectExplorerSettings().deployBeforeRun) { + if (!projectExplorerSettings().deployBeforeRun) { qCDebug(androidRunnerLog) << "Run without deployment"; launchAVD(); if (!m_launchedAVDName.isEmpty()) { diff --git a/src/plugins/autotest/testrunner.cpp b/src/plugins/autotest/testrunner.cpp index 29b7898835b..7dbbb49cdca 100644 --- a/src/plugins/autotest/testrunner.cpp +++ b/src/plugins/autotest/testrunner.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -169,11 +168,9 @@ void TestRunner::runTests(TestRunMode mode, const QList &s m_skipTargetsCheck = false; m_runMode = mode; - const ProjectExplorerSettings projectExplorerSettings - = ProjectExplorerPlugin::projectExplorerSettings(); if (mode != TestRunMode::RunAfterBuild - && projectExplorerSettings.buildBeforeDeploy != BuildBeforeRunMode::Off - && !projectExplorerSettings.saveBeforeBuild) { + && projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off + && !projectExplorerSettings().saveBeforeBuild) { if (!ProjectExplorerPlugin::saveModifiedFiles()) return; } @@ -203,7 +200,7 @@ void TestRunner::runTests(TestRunMode mode, const QList &s m_targetConnect = connect(project, &Project::activeTargetChanged, this, [this] { cancelCurrent(KitChanged); }); - if (projectExplorerSettings.buildBeforeDeploy == BuildBeforeRunMode::Off + if (projectExplorerSettings().buildBeforeDeploy == BuildBeforeRunMode::Off || mode == TestRunMode::DebugWithoutDeploy || mode == TestRunMode::RunWithoutDeploy || mode == TestRunMode::RunAfterBuild) { runOrDebugTests(); diff --git a/src/plugins/cmakeprojectmanager/cmakekitaspect.cpp b/src/plugins/cmakeprojectmanager/cmakekitaspect.cpp index 00750f4d3c5..3d8aa654751 100644 --- a/src/plugins/cmakeprojectmanager/cmakekitaspect.cpp +++ b/src/plugins/cmakeprojectmanager/cmakekitaspect.cpp @@ -695,7 +695,7 @@ QVariant CMakeGeneratorKitAspectFactory::defaultValue(const Kit *k) const return g.matches("NMake Makefiles") || g.matches("NMake Makefiles JOM"); }); - if (ProjectExplorerPlugin::projectExplorerSettings().useJom) { + if (projectExplorerSettings().useJom) { it = std::find_if(known.constBegin(), known.constEnd(), [](const CMakeTool::Generator &g) { diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp index d2647f3d7b9..cc3c847b636 100644 --- a/src/plugins/debugger/debuggerplugin.cpp +++ b/src/plugins/debugger/debuggerplugin.cpp @@ -1993,7 +1993,7 @@ void DebuggerPluginPrivate::setInitialState() void DebuggerPluginPrivate::updateDebugWithoutDeployMenu() { - const bool state = ProjectExplorerPlugin::projectExplorerSettings().deployBeforeRun; + const bool state = projectExplorerSettings().deployBeforeRun; m_debugWithoutDeployAction.setVisible(state); } diff --git a/src/plugins/projectexplorer/abstractprocessstep.cpp b/src/plugins/projectexplorer/abstractprocessstep.cpp index 5cfb66e8114..fcdfdc6b631 100644 --- a/src/plugins/projectexplorer/abstractprocessstep.cpp +++ b/src/plugins/projectexplorer/abstractprocessstep.cpp @@ -189,7 +189,7 @@ bool AbstractProcessStep::setupProcess(Process &process) process.setEnvironment(envWithPwd); process.setCommand({d->m_param.effectiveCommand(), d->m_param.effectiveArguments(), CommandLine::Raw}); - if (d->m_lowPriority && ProjectExplorerPlugin::projectExplorerSettings().lowBuildPriority) + if (d->m_lowPriority && projectExplorerSettings().lowBuildPriority) process.setLowPriority(); process.setStdOutCodec(buildEnvironment().hasKey("VSLANG") diff --git a/src/plugins/projectexplorer/appoutputpane.cpp b/src/plugins/projectexplorer/appoutputpane.cpp index 94e2694acc2..742e6df5e4f 100644 --- a/src/plugins/projectexplorer/appoutputpane.cpp +++ b/src/plugins/projectexplorer/appoutputpane.cpp @@ -661,10 +661,10 @@ void AppOutputPane::closeTab(int tabIndex, CloseTabMode closeTabMode) bool AppOutputPane::optionallyPromptToStop(RunControl *runControl) { - ProjectExplorerSettings settings = ProjectExplorerPlugin::projectExplorerSettings(); - if (!runControl->promptToStop(&settings.prompToStopRunControl)) + bool promptToStop = projectExplorerSettings().prompToStopRunControl; + if (!runControl->promptToStop(&promptToStop)) return false; - ProjectExplorerPlugin::setProjectExplorerSettings(settings); + setPromptToStopSettings(promptToStop); return true; } diff --git a/src/plugins/projectexplorer/buildaspects.cpp b/src/plugins/projectexplorer/buildaspects.cpp index 0f9c025fce2..3872b7824a6 100644 --- a/src/plugins/projectexplorer/buildaspects.cpp +++ b/src/plugins/projectexplorer/buildaspects.cpp @@ -190,7 +190,7 @@ QString BuildDirectoryAspect::updateProblemLabelsHelper(const QString &value) QString genericProblem; QString genericProblemLabelString; - if (ProjectExplorerPlugin::projectExplorerSettings().warnAgainstNonAsciiBuildDir) { + if (projectExplorerSettings().warnAgainstNonAsciiBuildDir) { const auto isInvalid = [](QChar c) { return c.isSpace() || !isascii(c.toLatin1()); }; if (const auto invalidChar = Utils::findOr(value, std::nullopt, isInvalid)) { genericProblem = Tr::tr( diff --git a/src/plugins/projectexplorer/buildmanager.cpp b/src/plugins/projectexplorer/buildmanager.cpp index 1a32d340f2c..b65aa609f41 100644 --- a/src/plugins/projectexplorer/buildmanager.cpp +++ b/src/plugins/projectexplorer/buildmanager.cpp @@ -209,10 +209,10 @@ static int queue(const QList &projects, const QList &stepIds, if (!ProjectExplorerPlugin::saveModifiedFiles()) return -1; - const ProjectExplorerSettings &settings = ProjectExplorerPlugin::projectExplorerSettings(); - if (settings.stopBeforeBuild != StopBeforeBuild::None + const StopBeforeBuild stopBeforeBuild = projectExplorerSettings().stopBeforeBuild; + if (stopBeforeBuild != StopBeforeBuild::None && stepIds.contains(Constants::BUILDSTEPS_BUILD)) { - StopBeforeBuild stopCondition = settings.stopBeforeBuild; + StopBeforeBuild stopCondition = stopBeforeBuild; if (stopCondition == StopBeforeBuild::SameApp && !forRunConfig) stopCondition = StopBeforeBuild::SameBuildDir; const auto isStoppableRc = [&projects, stopCondition, configSelection, forRunConfig, @@ -258,7 +258,7 @@ static int queue(const QList &projects, const QList &stepIds, if (!toStop.isEmpty()) { bool stopThem = true; - if (settings.prompToStopRunControl) { + if (projectExplorerSettings().prompToStopRunControl) { QStringList names = Utils::transform(toStop, &RunControl::displayName); if (QMessageBox::question(ICore::dialogParent(), Tr::tr("Stop Applications"), @@ -516,7 +516,7 @@ void BuildManager::rebuildProjects(const QList &projects, void BuildManager::deployProjects(const QList &projects) { QList steps; - if (ProjectExplorerPlugin::projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off) + if (projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off) steps << Id(Constants::BUILDSTEPS_BUILD); steps << Id(Constants::BUILDSTEPS_DEPLOY); queue(projects, steps, ConfigSelection::Active); @@ -525,10 +525,9 @@ void BuildManager::deployProjects(const QList &projects) BuildForRunConfigStatus BuildManager::potentiallyBuildForRunConfig(RunConfiguration *rc) { QList stepIds; - const ProjectExplorerSettings &settings = ProjectExplorerPlugin::projectExplorerSettings(); - if (settings.deployBeforeRun) { + if (projectExplorerSettings().deployBeforeRun) { if (!isBuilding()) { - switch (settings.buildBeforeDeploy) { + switch (projectExplorerSettings().buildBeforeDeploy) { case BuildBeforeRunMode::AppOnly: if (rc->target()->activeBuildConfiguration()) rc->target()->activeBuildConfiguration()->restrictNextBuild(rc); @@ -721,8 +720,7 @@ void BuildManager::startBuildQueue() }; const GroupItem abortPolicy - = ProjectExplorerPlugin::projectExplorerSettings().abortBuildAllOnError - ? stopOnError : continueOnError; + = projectExplorerSettings().abortBuildAllOnError ? stopOnError : continueOnError; QList topLevel { abortPolicy, ParserAwaiterTask(onAwaiterSetup) }; Project *lastProject = nullptr; @@ -856,7 +854,7 @@ bool BuildManager::buildQueueAppend(const QList &items, const QString { if (!d->m_taskTreeRunner.isRunning()) { d->m_outputWindow->clearContents(); - if (ProjectExplorerPlugin::projectExplorerSettings().clearIssuesOnRebuild) { + if (projectExplorerSettings().clearIssuesOnRebuild) { TaskHub::clearTasks(Constants::TASK_CATEGORY_COMPILE); TaskHub::clearTasks(Constants::TASK_CATEGORY_BUILDSYSTEM); TaskHub::clearTasks(Constants::TASK_CATEGORY_DEPLOYMENT); diff --git a/src/plugins/projectexplorer/environmentaspect.cpp b/src/plugins/projectexplorer/environmentaspect.cpp index af4d8449d1c..fb5aaa2c243 100644 --- a/src/plugins/projectexplorer/environmentaspect.cpp +++ b/src/plugins/projectexplorer/environmentaspect.cpp @@ -31,9 +31,7 @@ EnvironmentAspect::EnvironmentAspect(AspectContainer *container) setConfigWidgetCreator([this] { return new EnvironmentAspectWidget(this); }); addDataExtractor(this, &EnvironmentAspect::environment, &Data::environment); if (qobject_cast(container)) { - addModifier([](Environment &env) { - env.modify(ProjectExplorerPlugin::projectExplorerSettings().appEnvChanges); - }); + addModifier([](Environment &env) { env.modify(projectExplorerSettings().appEnvChanges); }); connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::settingsChanged, this, &EnvironmentAspect::environmentChanged); } diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp index 5066d0969ae..310e170e5a5 100644 --- a/src/plugins/projectexplorer/msvctoolchain.cpp +++ b/src/plugins/projectexplorer/msvctoolchain.cpp @@ -1151,7 +1151,7 @@ static QString wrappedMakeCommand(const QString &command) FilePath MsvcToolchain::makeCommand(const Environment &environment) const { - bool useJom = ProjectExplorerPlugin::projectExplorerSettings().useJom; + const bool useJom = projectExplorerSettings().useJom; const QString jom("jom.exe"); const QString nmake("nmake.exe"); Utils::FilePath tmp; diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp index cf82aa6e739..a409de59cb2 100644 --- a/src/plugins/projectexplorer/projectexplorer.cpp +++ b/src/plugins/projectexplorer/projectexplorer.cpp @@ -262,27 +262,6 @@ const char PROJECT_OPEN_LOCATIONS_CONTEXT_MENU[] = "Project.P.OpenLocation.CtxM const char RECENTPROJECTS_FILE_NAMES_KEY[] = "ProjectExplorer/RecentProjects/FileNames"; const char RECENTPROJECTS_DISPLAY_NAMES_KEY[] = "ProjectExplorer/RecentProjects/DisplayNames"; -const char BUILD_BEFORE_DEPLOY_SETTINGS_KEY[] = "ProjectExplorer/Settings/BuildBeforeDeploy"; -const char DEPLOY_BEFORE_RUN_SETTINGS_KEY[] = "ProjectExplorer/Settings/DeployBeforeRun"; -const char SAVE_BEFORE_BUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/SaveBeforeBuild"; -const char USE_JOM_SETTINGS_KEY[] = "ProjectExplorer/Settings/UseJom"; -const char ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY[] = - "ProjectExplorer/Settings/AddLibraryPathsToRunEnv"; -const char PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY[] = - "ProjectExplorer/Settings/PromptToStopRunControl"; -const char AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY[] = - "ProjectExplorer/Settings/AutomaticallyCreateRunConfigurations"; -const char ENVIRONMENT_ID_SETTINGS_KEY[] = "ProjectExplorer/Settings/EnvironmentId"; -const char STOP_BEFORE_BUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/StopBeforeBuild"; -const char TERMINAL_MODE_SETTINGS_KEY[] = "ProjectExplorer/Settings/TerminalMode"; -const char CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY[] - = "ProjectExplorer/Settings/CloseFilesWithProject"; -const char CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/ClearIssuesOnRebuild"; -const char ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY[] - = "ProjectExplorer/Settings/AbortBuildAllOnError"; -const char LOW_BUILD_PRIORITY_SETTINGS_KEY[] = "ProjectExplorer/Settings/LowBuildPriority"; -const char WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY[] = "ProjectExplorer/Settings/LowBuildPriority"; -const char APP_ENV_CHANGES_SETTINGS_KEY[] = "ProjectExplorer/Settings/AppEnvChanges"; const char CUSTOM_PARSER_COUNT_KEY[] = "ProjectExplorer/Settings/CustomParserCount"; const char CUSTOM_PARSER_PREFIX_KEY[] = "ProjectExplorer/Settings/CustomParser"; @@ -640,7 +619,6 @@ public: QPointer m_defaultRunConfiguration; QPointer m_delayedRunConfiguration; MiniProjectTargetSelector * m_targetSelector; - ProjectExplorerSettings m_projectExplorerSettings; QList m_customParsers; bool m_shouldHaveRunConfiguration = false; Id m_runMode = Constants::NO_RUN_MODE; @@ -700,7 +678,6 @@ public: ProjectFileWizardExtension m_projectFileWizardExtension; // Settings pages - ProjectExplorerSettingsPage m_projectExplorerSettingsPage; AppOutputSettingsPage m_appOutputSettingsPage; DeviceSettingsPage m_deviceSettingsPage; SshSettingsPage m_sshSettingsPage; @@ -811,6 +788,8 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er setupProjectTreeWidgetFactory(); + setupProjectExplorerSettings(); + dd = new ProjectExplorerPluginPrivate; setupDesktopRunConfigurations(); @@ -1637,73 +1616,6 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er } } - const QVariant buildBeforeDeploy = s->value(Constants::BUILD_BEFORE_DEPLOY_SETTINGS_KEY); - const QString buildBeforeDeployString = buildBeforeDeploy.toString(); - if (buildBeforeDeployString == "true") { // backward compatibility with QtC < 4.12 - dd->m_projectExplorerSettings.buildBeforeDeploy = BuildBeforeRunMode::WholeProject; - } else if (buildBeforeDeployString == "false") { - dd->m_projectExplorerSettings.buildBeforeDeploy = BuildBeforeRunMode::Off; - } else if (buildBeforeDeploy.isValid()) { - dd->m_projectExplorerSettings.buildBeforeDeploy - = static_cast(buildBeforeDeploy.toInt()); - } - - static const ProjectExplorerSettings defaultSettings; - - dd->m_projectExplorerSettings.deployBeforeRun - = s->value(Constants::DEPLOY_BEFORE_RUN_SETTINGS_KEY, defaultSettings.deployBeforeRun) - .toBool(); - dd->m_projectExplorerSettings.saveBeforeBuild - = s->value(Constants::SAVE_BEFORE_BUILD_SETTINGS_KEY, defaultSettings.saveBeforeBuild) - .toBool(); - dd->m_projectExplorerSettings.useJom - = s->value(Constants::USE_JOM_SETTINGS_KEY, defaultSettings.useJom).toBool(); - dd->m_projectExplorerSettings.addLibraryPathsToRunEnv - = s->value(Constants::ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY, - defaultSettings.addLibraryPathsToRunEnv) - .toBool(); - dd->m_projectExplorerSettings.prompToStopRunControl - = s->value(Constants::PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY, - defaultSettings.prompToStopRunControl) - .toBool(); - dd->m_projectExplorerSettings.automaticallyCreateRunConfigurations - = s->value(Constants::AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY, - defaultSettings.automaticallyCreateRunConfigurations) - .toBool(); - dd->m_projectExplorerSettings.environmentId = - QUuid(s->value(Constants::ENVIRONMENT_ID_SETTINGS_KEY).toByteArray()); - if (dd->m_projectExplorerSettings.environmentId.isNull()) - dd->m_projectExplorerSettings.environmentId = QUuid::createUuid(); - int tmp = s->value(Constants::STOP_BEFORE_BUILD_SETTINGS_KEY, - int(defaultSettings.stopBeforeBuild)) - .toInt(); - if (tmp < 0 || tmp > int(StopBeforeBuild::SameApp)) - tmp = int(defaultSettings.stopBeforeBuild); - dd->m_projectExplorerSettings.stopBeforeBuild = StopBeforeBuild(tmp); - dd->m_projectExplorerSettings.terminalMode = static_cast( - s->value(Constants::TERMINAL_MODE_SETTINGS_KEY, int(defaultSettings.terminalMode)).toInt()); - dd->m_projectExplorerSettings.closeSourceFilesWithProject - = s->value(Constants::CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY, - defaultSettings.closeSourceFilesWithProject) - .toBool(); - dd->m_projectExplorerSettings.clearIssuesOnRebuild - = s->value(Constants::CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY, - defaultSettings.clearIssuesOnRebuild) - .toBool(); - dd->m_projectExplorerSettings.abortBuildAllOnError - = s->value(Constants::ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY, - defaultSettings.abortBuildAllOnError) - .toBool(); - dd->m_projectExplorerSettings.lowBuildPriority - = s->value(Constants::LOW_BUILD_PRIORITY_SETTINGS_KEY, defaultSettings.lowBuildPriority) - .toBool(); - dd->m_projectExplorerSettings.warnAgainstNonAsciiBuildDir - = s->value(Constants::WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY, - defaultSettings.warnAgainstNonAsciiBuildDir) - .toBool(); - dd->m_projectExplorerSettings.appEnvChanges = EnvironmentItem::fromStringList( - s->value(Constants::APP_ENV_CHANGES_SETTINGS_KEY).toStringList()); - const int customParserCount = s->value(Constants::CUSTOM_PARSER_COUNT_KEY).toInt(); for (int i = 0; i < customParserCount; ++i) { CustomParserSettings settings; @@ -2145,7 +2057,7 @@ bool ProjectExplorerPlugin::delayedInitialize() void ProjectExplorerPluginPrivate::updateRunWithoutDeployMenu() { - m_runWithoutDeployAction->setVisible(m_projectExplorerSettings.deployBeforeRun); + m_runWithoutDeployAction->setVisible(projectExplorerSettings().deployBeforeRun); } IPlugin::ShutdownFlag ProjectExplorerPlugin::aboutToShutdown() @@ -2228,55 +2140,6 @@ void ProjectExplorerPluginPrivate::savePersistentSettings() s->setValueWithDefault(Constants::RECENTPROJECTS_FILE_NAMES_KEY, fileNames); s->setValueWithDefault(Constants::RECENTPROJECTS_DISPLAY_NAMES_KEY, displayNames); - static const ProjectExplorerSettings defaultSettings; - - s->setValueWithDefault(Constants::BUILD_BEFORE_DEPLOY_SETTINGS_KEY, - int(dd->m_projectExplorerSettings.buildBeforeDeploy), - int(defaultSettings.buildBeforeDeploy)); - s->setValueWithDefault(Constants::DEPLOY_BEFORE_RUN_SETTINGS_KEY, - dd->m_projectExplorerSettings.deployBeforeRun, - defaultSettings.deployBeforeRun); - s->setValueWithDefault(Constants::SAVE_BEFORE_BUILD_SETTINGS_KEY, - dd->m_projectExplorerSettings.saveBeforeBuild, - defaultSettings.saveBeforeBuild); - s->setValueWithDefault(Constants::USE_JOM_SETTINGS_KEY, - dd->m_projectExplorerSettings.useJom, - defaultSettings.useJom); - s->setValueWithDefault(Constants::ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY, - dd->m_projectExplorerSettings.addLibraryPathsToRunEnv, - defaultSettings.addLibraryPathsToRunEnv); - s->setValueWithDefault(Constants::PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY, - dd->m_projectExplorerSettings.prompToStopRunControl, - defaultSettings.prompToStopRunControl); - s->setValueWithDefault(Constants::TERMINAL_MODE_SETTINGS_KEY, - int(dd->m_projectExplorerSettings.terminalMode), - int(defaultSettings.terminalMode)); - s->setValueWithDefault(Constants::CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY, - dd->m_projectExplorerSettings.closeSourceFilesWithProject, - defaultSettings.closeSourceFilesWithProject); - s->setValueWithDefault(Constants::CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY, - dd->m_projectExplorerSettings.clearIssuesOnRebuild, - defaultSettings.clearIssuesOnRebuild); - s->setValueWithDefault(Constants::ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY, - dd->m_projectExplorerSettings.abortBuildAllOnError, - defaultSettings.abortBuildAllOnError); - s->setValueWithDefault(Constants::LOW_BUILD_PRIORITY_SETTINGS_KEY, - dd->m_projectExplorerSettings.lowBuildPriority, - defaultSettings.lowBuildPriority); - s->setValueWithDefault(Constants::WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY, - dd->m_projectExplorerSettings.warnAgainstNonAsciiBuildDir, - defaultSettings.warnAgainstNonAsciiBuildDir); - s->setValueWithDefault(Constants::AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY, - dd->m_projectExplorerSettings.automaticallyCreateRunConfigurations, - defaultSettings.automaticallyCreateRunConfigurations); - s->setValueWithDefault(Constants::ENVIRONMENT_ID_SETTINGS_KEY, - dd->m_projectExplorerSettings.environmentId.toByteArray()); - s->setValueWithDefault(Constants::STOP_BEFORE_BUILD_SETTINGS_KEY, - int(dd->m_projectExplorerSettings.stopBeforeBuild), - int(defaultSettings.stopBeforeBuild)); - s->setValueWithDefault(Constants::APP_ENV_CHANGES_SETTINGS_KEY, - EnvironmentItem::toStringList(dd->m_projectExplorerSettings.appEnvChanges)); - buildPropertiesSettings().writeSettings(); // FIXME: Should not be needed. s->setValueWithDefault(Constants::CUSTOM_PARSER_COUNT_KEY, int(dd->m_customParsers.count()), 0); @@ -2723,7 +2586,7 @@ bool ProjectExplorerPlugin::saveModifiedFiles() { QList documentsToSave = DocumentManager::modifiedDocuments(); if (!documentsToSave.isEmpty()) { - if (dd->m_projectExplorerSettings.saveBeforeBuild) { + if (projectExplorerSettings().saveBeforeBuild) { bool cancelled = false; DocumentManager::saveModifiedDocumentsSilently(documentsToSave, &cancelled); if (cancelled) @@ -2738,7 +2601,7 @@ bool ProjectExplorerPlugin::saveModifiedFiles() } if (alwaysSave) - dd->m_projectExplorerSettings.saveBeforeBuild = true; + setSaveBeforeBuildSettings(true); } } return true; @@ -3054,7 +2917,7 @@ void ProjectExplorerPluginPrivate::updateDeployActions() && !BuildManager::isBuilding(currentProject) && hasDeploySettings(currentProject); - if (m_projectExplorerSettings.buildBeforeDeploy != BuildBeforeRunMode::Off) { + if (projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off) { if (hasBuildSettings(project) && !buildSettingsEnabled(project).first) enableDeployActions = false; @@ -3072,7 +2935,7 @@ void ProjectExplorerPluginPrivate::updateDeployActions() m_deployProjectOnlyAction->setEnabled(enableDeployActions); bool enableDeploySessionAction = true; - if (m_projectExplorerSettings.buildBeforeDeploy != BuildBeforeRunMode::Off) { + if (projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off) { auto hasDisabledBuildConfiguration = [](Project *project) { return project && project->activeTarget() && project->activeTarget()->activeBuildConfiguration() @@ -3116,8 +2979,8 @@ expected_str ProjectExplorerPlugin::canRunStartupProject(Utils::Id runMode if (!activeRC->isEnabled(runMode)) return make_unexpected(activeRC->disabledReason(runMode)); - if (dd->m_projectExplorerSettings.buildBeforeDeploy != BuildBeforeRunMode::Off - && dd->m_projectExplorerSettings.deployBeforeRun + if (projectExplorerSettings().buildBeforeDeploy != BuildBeforeRunMode::Off + && projectExplorerSettings().deployBeforeRun && !BuildManager::isBuilding(project) && hasBuildSettings(project)) { QPair buildState = dd->buildSettingsEnabled(project); @@ -3968,21 +3831,6 @@ void ProjectExplorerPluginPrivate::handleSetStartupProject() setStartupProject(ProjectTree::currentProject()); } -void ProjectExplorerPlugin::setProjectExplorerSettings(const ProjectExplorerSettings &pes) -{ - QTC_ASSERT(dd->m_projectExplorerSettings.environmentId == pes.environmentId, return); - - if (dd->m_projectExplorerSettings == pes) - return; - dd->m_projectExplorerSettings = pes; - emit m_instance->settingsChanged(); -} - -const ProjectExplorerSettings &ProjectExplorerPlugin::projectExplorerSettings() -{ - return dd->m_projectExplorerSettings; -} - void ProjectExplorerPlugin::setAppOutputSettings(const AppOutputSettings &settings) { dd->m_outputPane.setSettings(settings); diff --git a/src/plugins/projectexplorer/projectexplorer.h b/src/plugins/projectexplorer/projectexplorer.h index ffb5d1bcd3c..291734901a2 100644 --- a/src/plugins/projectexplorer/projectexplorer.h +++ b/src/plugins/projectexplorer/projectexplorer.h @@ -29,7 +29,6 @@ class CustomParserSettings; class FolderNode; class Node; class Project; -class ProjectExplorerSettings; class RunControl; class RunConfiguration; @@ -110,9 +109,6 @@ public: bool delayedInitialize() override; ShutdownFlag aboutToShutdown() override; - static void setProjectExplorerSettings(const ProjectExplorerSettings &pes); - static const ProjectExplorerSettings &projectExplorerSettings(); - static void setAppOutputSettings(const Internal::AppOutputSettings &settings); static const Internal::AppOutputSettings &appOutputSettings(); diff --git a/src/plugins/projectexplorer/projectexplorersettings.cpp b/src/plugins/projectexplorer/projectexplorersettings.cpp index b99a38d461d..54cbc57a8cc 100644 --- a/src/plugins/projectexplorer/projectexplorersettings.cpp +++ b/src/plugins/projectexplorer/projectexplorersettings.cpp @@ -9,7 +9,9 @@ #include "projectexplorertr.h" #include +#include #include +#include #include #include @@ -27,10 +29,203 @@ using namespace Core; using namespace Utils; -namespace ProjectExplorer::Internal { +namespace ProjectExplorer { +namespace Internal { + +namespace Constants { +const char BUILD_BEFORE_DEPLOY_SETTINGS_KEY[] = "ProjectExplorer/Settings/BuildBeforeDeploy"; +const char DEPLOY_BEFORE_RUN_SETTINGS_KEY[] = "ProjectExplorer/Settings/DeployBeforeRun"; +const char SAVE_BEFORE_BUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/SaveBeforeBuild"; +const char USE_JOM_SETTINGS_KEY[] = "ProjectExplorer/Settings/UseJom"; +const char ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY[] = + "ProjectExplorer/Settings/AddLibraryPathsToRunEnv"; +const char PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY[] = + "ProjectExplorer/Settings/PromptToStopRunControl"; +const char AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY[] = + "ProjectExplorer/Settings/AutomaticallyCreateRunConfigurations"; +const char ENVIRONMENT_ID_SETTINGS_KEY[] = "ProjectExplorer/Settings/EnvironmentId"; +const char STOP_BEFORE_BUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/StopBeforeBuild"; +const char TERMINAL_MODE_SETTINGS_KEY[] = "ProjectExplorer/Settings/TerminalMode"; +const char CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY[] + = "ProjectExplorer/Settings/CloseFilesWithProject"; +const char CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY[] = "ProjectExplorer/Settings/ClearIssuesOnRebuild"; +const char ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY[] + = "ProjectExplorer/Settings/AbortBuildAllOnError"; +const char LOW_BUILD_PRIORITY_SETTINGS_KEY[] = "ProjectExplorer/Settings/LowBuildPriority"; +const char APP_ENV_CHANGES_SETTINGS_KEY[] = "ProjectExplorer/Settings/AppEnvChanges"; +const char WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY[] = "ProjectExplorer/Settings/LowBuildPriority"; + +} // Constants enum { UseCurrentDirectory, UseProjectDirectory }; +void saveProjectExplorerSettings(); + +static bool operator==(const ProjectExplorerSettings &p1, const ProjectExplorerSettings &p2) +{ + return p1.buildBeforeDeploy == p2.buildBeforeDeploy + && p1.deployBeforeRun == p2.deployBeforeRun + && p1.saveBeforeBuild == p2.saveBeforeBuild + && p1.useJom == p2.useJom + && p1.prompToStopRunControl == p2.prompToStopRunControl + && p1.automaticallyCreateRunConfigurations == p2.automaticallyCreateRunConfigurations + && p1.addLibraryPathsToRunEnv == p2.addLibraryPathsToRunEnv + && p1.environmentId == p2.environmentId + && p1.stopBeforeBuild == p2.stopBeforeBuild + && p1.terminalMode == p2.terminalMode + && p1.closeSourceFilesWithProject == p2.closeSourceFilesWithProject + && p1.clearIssuesOnRebuild == p2.clearIssuesOnRebuild + && p1.abortBuildAllOnError == p2.abortBuildAllOnError + && p1.appEnvChanges == p2.appEnvChanges + && p1.lowBuildPriority == p2.lowBuildPriority; +} + +ProjectExplorerSettings &mutableProjectExplorerSettings() +{ + static ProjectExplorerSettings theProjectExplorerSettings; + return theProjectExplorerSettings; +} + +void setPromptToStopSettings(bool promptToStop) +{ + mutableProjectExplorerSettings().prompToStopRunControl = promptToStop; + saveProjectExplorerSettings(); + emit ProjectExplorerPlugin::instance()->settingsChanged(); +} + +void setSaveBeforeBuildSettings(bool saveBeforeBuild) +{ + mutableProjectExplorerSettings().saveBeforeBuild = saveBeforeBuild; + saveProjectExplorerSettings(); +} + +static void loadProjectExplorerSettings() +{ + QtcSettings *s = ICore::settings(); + + const QVariant buildBeforeDeploy = s->value(Constants::BUILD_BEFORE_DEPLOY_SETTINGS_KEY); + const QString buildBeforeDeployString = buildBeforeDeploy.toString(); + ProjectExplorerSettings &settings = mutableProjectExplorerSettings(); + if (buildBeforeDeployString == "true") { // backward compatibility with QtC < 4.12 + settings.buildBeforeDeploy = BuildBeforeRunMode::WholeProject; + } else if (buildBeforeDeployString == "false") { + settings.buildBeforeDeploy = BuildBeforeRunMode::Off; + } else if (buildBeforeDeploy.isValid()) { + settings.buildBeforeDeploy + = static_cast(buildBeforeDeploy.toInt()); + } + + static const ProjectExplorerSettings defaultSettings; + + settings.deployBeforeRun + = s->value(Constants::DEPLOY_BEFORE_RUN_SETTINGS_KEY, defaultSettings.deployBeforeRun) + .toBool(); + settings.saveBeforeBuild + = s->value(Constants::SAVE_BEFORE_BUILD_SETTINGS_KEY, defaultSettings.saveBeforeBuild) + .toBool(); + settings.useJom + = s->value(Constants::USE_JOM_SETTINGS_KEY, defaultSettings.useJom).toBool(); + settings.addLibraryPathsToRunEnv + = s->value(Constants::ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY, + defaultSettings.addLibraryPathsToRunEnv) + .toBool(); + settings.prompToStopRunControl + = s->value(Constants::PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY, + defaultSettings.prompToStopRunControl) + .toBool(); + settings.automaticallyCreateRunConfigurations + = s->value(Constants::AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY, + defaultSettings.automaticallyCreateRunConfigurations) + .toBool(); + settings.environmentId = + QUuid(s->value(Constants::ENVIRONMENT_ID_SETTINGS_KEY).toByteArray()); + if (settings.environmentId.isNull()) + settings.environmentId = QUuid::createUuid(); + int tmp = s->value(Constants::STOP_BEFORE_BUILD_SETTINGS_KEY, + int(defaultSettings.stopBeforeBuild)) + .toInt(); + if (tmp < 0 || tmp > int(StopBeforeBuild::SameApp)) + tmp = int(defaultSettings.stopBeforeBuild); + settings.stopBeforeBuild = StopBeforeBuild(tmp); + settings.terminalMode = static_cast( + s->value(Constants::TERMINAL_MODE_SETTINGS_KEY, int(defaultSettings.terminalMode)).toInt()); + settings.closeSourceFilesWithProject + = s->value(Constants::CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY, + defaultSettings.closeSourceFilesWithProject) + .toBool(); + settings.clearIssuesOnRebuild + = s->value(Constants::CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY, + defaultSettings.clearIssuesOnRebuild) + .toBool(); + settings.abortBuildAllOnError + = s->value(Constants::ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY, + defaultSettings.abortBuildAllOnError) + .toBool(); + settings.lowBuildPriority + = s->value(Constants::LOW_BUILD_PRIORITY_SETTINGS_KEY, defaultSettings.lowBuildPriority) + .toBool(); + settings.warnAgainstNonAsciiBuildDir + = s->value(Constants::WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY, + defaultSettings.warnAgainstNonAsciiBuildDir) + .toBool(); + settings.appEnvChanges = EnvironmentItem::fromStringList( + s->value(Constants::APP_ENV_CHANGES_SETTINGS_KEY).toStringList()); +} + +void saveProjectExplorerSettings() +{ + QtcSettings *s = ICore::settings(); + static const ProjectExplorerSettings defaultSettings; + + const ProjectExplorerSettings &settings = projectExplorerSettings(); + s->setValueWithDefault(Constants::BUILD_BEFORE_DEPLOY_SETTINGS_KEY, + int(settings.buildBeforeDeploy), + int(defaultSettings.buildBeforeDeploy)); + s->setValueWithDefault(Constants::DEPLOY_BEFORE_RUN_SETTINGS_KEY, + settings.deployBeforeRun, + defaultSettings.deployBeforeRun); + s->setValueWithDefault(Constants::SAVE_BEFORE_BUILD_SETTINGS_KEY, + settings.saveBeforeBuild, + defaultSettings.saveBeforeBuild); + s->setValueWithDefault(Constants::USE_JOM_SETTINGS_KEY, + settings.useJom, + defaultSettings.useJom); + s->setValueWithDefault(Constants::ADD_LIBRARY_PATHS_TO_RUN_ENV_SETTINGS_KEY, + settings.addLibraryPathsToRunEnv, + defaultSettings.addLibraryPathsToRunEnv); + s->setValueWithDefault(Constants::PROMPT_TO_STOP_RUN_CONTROL_SETTINGS_KEY, + settings.prompToStopRunControl, + defaultSettings.prompToStopRunControl); + s->setValueWithDefault(Constants::TERMINAL_MODE_SETTINGS_KEY, + int(settings.terminalMode), + int(defaultSettings.terminalMode)); + s->setValueWithDefault(Constants::CLOSE_FILES_WITH_PROJECT_SETTINGS_KEY, + settings.closeSourceFilesWithProject, + defaultSettings.closeSourceFilesWithProject); + s->setValueWithDefault(Constants::CLEAR_ISSUES_ON_REBUILD_SETTINGS_KEY, + settings.clearIssuesOnRebuild, + defaultSettings.clearIssuesOnRebuild); + s->setValueWithDefault(Constants::ABORT_BUILD_ALL_ON_ERROR_SETTINGS_KEY, + settings.abortBuildAllOnError, + defaultSettings.abortBuildAllOnError); + s->setValueWithDefault(Constants::LOW_BUILD_PRIORITY_SETTINGS_KEY, + settings.lowBuildPriority, + defaultSettings.lowBuildPriority); + s->setValueWithDefault(Constants::WARN_AGAINST_NON_ASCII_BUILD_DIR_SETTINGS_KEY, + settings.warnAgainstNonAsciiBuildDir, + defaultSettings.warnAgainstNonAsciiBuildDir); + s->setValueWithDefault(Constants::AUTO_CREATE_RUN_CONFIGS_SETTINGS_KEY, + settings.automaticallyCreateRunConfigurations, + defaultSettings.automaticallyCreateRunConfigurations); + s->setValueWithDefault(Constants::ENVIRONMENT_ID_SETTINGS_KEY, + settings.environmentId.toByteArray()); + s->setValueWithDefault(Constants::STOP_BEFORE_BUILD_SETTINGS_KEY, + int(settings.stopBeforeBuild), + int(defaultSettings.stopBeforeBuild)); + s->setValueWithDefault(Constants::APP_ENV_CHANGES_SETTINGS_KEY, + EnvironmentItem::toStringList(settings.appEnvChanges)); +} + class ProjectExplorerSettingsWidget : public IOptionsPageWidget { public: @@ -47,7 +242,15 @@ public: void apply() final { - ProjectExplorerPlugin::setProjectExplorerSettings(settings()); + ProjectExplorerSettings newSettings = settings(); + QTC_CHECK(projectExplorerSettings().environmentId == newSettings.environmentId); + + if (!(projectExplorerSettings() == newSettings)) { + mutableProjectExplorerSettings() = newSettings; + saveProjectExplorerSettings(); + emit ProjectExplorerPlugin::instance()->settingsChanged(); + } + DocumentManager::setProjectsDirectory(projectsDirectory()); DocumentManager::setUseProjectsDirectory(useProjectsDirectory()); } @@ -56,7 +259,6 @@ private: void slotDirectoryButtonGroupChanged(); void updateAppEnvChangesLabel(); - mutable ProjectExplorerSettings m_settings; Utils::EnvironmentItems m_appEnvChanges; QRadioButton *m_currentDirectoryRadioButton; QRadioButton *m_directoryRadioButton; @@ -204,7 +406,7 @@ ProjectExplorerSettingsWidget::ProjectExplorerSettingsWidget() connect(m_directoryButtonGroup, &QButtonGroup::buttonClicked, this, &ProjectExplorerSettingsWidget::slotDirectoryButtonGroupChanged); - setSettings(ProjectExplorerPlugin::projectExplorerSettings()); + setSettings(projectExplorerSettings()); setProjectsDirectory(DocumentManager::projectsDirectory()); setUseProjectsDirectory(DocumentManager::useProjectsDirectory()); updateAppEnvChangesLabel(); @@ -212,46 +414,46 @@ ProjectExplorerSettingsWidget::ProjectExplorerSettingsWidget() ProjectExplorerSettings ProjectExplorerSettingsWidget::settings() const { - m_settings.buildBeforeDeploy = static_cast( - m_buildBeforeDeployComboBox->currentData().toInt()); - m_settings.deployBeforeRun = m_deployProjectBeforeRunCheckBox->isChecked(); - m_settings.saveBeforeBuild = m_saveAllFilesCheckBox->isChecked(); - m_settings.useJom = m_jomCheckbox->isChecked(); - m_settings.addLibraryPathsToRunEnv = m_addLibraryPathsToRunEnvCheckBox->isChecked(); - m_settings.prompToStopRunControl = m_promptToStopRunControlCheckBox->isChecked(); - m_settings.automaticallyCreateRunConfigurations = m_automaticallyCreateRunConfiguration->isChecked(); - m_settings.stopBeforeBuild = static_cast( - m_stopBeforeBuildComboBox->currentData().toInt()); - m_settings.terminalMode = static_cast(m_terminalModeComboBox->currentIndex()); - m_settings.closeSourceFilesWithProject = m_closeSourceFilesCheckBox->isChecked(); - m_settings.clearIssuesOnRebuild = m_clearIssuesCheckBox->isChecked(); - m_settings.abortBuildAllOnError = m_abortBuildAllOnErrorCheckBox->isChecked(); - m_settings.lowBuildPriority = m_lowBuildPriorityCheckBox->isChecked(); - m_settings.warnAgainstNonAsciiBuildDir = m_warnAgainstNonAsciiBuildDirCheckBox->isChecked(); - m_settings.appEnvChanges = m_appEnvChanges; - return m_settings; + ProjectExplorerSettings s; + s.buildBeforeDeploy = static_cast( + m_buildBeforeDeployComboBox->currentData().toInt()); + s.deployBeforeRun = m_deployProjectBeforeRunCheckBox->isChecked(); + s.saveBeforeBuild = m_saveAllFilesCheckBox->isChecked(); + s.useJom = m_jomCheckbox->isChecked(); + s.addLibraryPathsToRunEnv = m_addLibraryPathsToRunEnvCheckBox->isChecked(); + s.prompToStopRunControl = m_promptToStopRunControlCheckBox->isChecked(); + s.automaticallyCreateRunConfigurations = m_automaticallyCreateRunConfiguration->isChecked(); + s.stopBeforeBuild = static_cast( + m_stopBeforeBuildComboBox->currentData().toInt()); + s.terminalMode = static_cast(m_terminalModeComboBox->currentIndex()); + s.closeSourceFilesWithProject = m_closeSourceFilesCheckBox->isChecked(); + s.clearIssuesOnRebuild = m_clearIssuesCheckBox->isChecked(); + s.abortBuildAllOnError = m_abortBuildAllOnErrorCheckBox->isChecked(); + s.lowBuildPriority = m_lowBuildPriorityCheckBox->isChecked(); + s.warnAgainstNonAsciiBuildDir = m_warnAgainstNonAsciiBuildDirCheckBox->isChecked(); + s.appEnvChanges = m_appEnvChanges; + return s; } -void ProjectExplorerSettingsWidget::setSettings(const ProjectExplorerSettings &pes) +void ProjectExplorerSettingsWidget::setSettings(const ProjectExplorerSettings &s) { - m_settings = pes; - m_appEnvChanges = pes.appEnvChanges; + m_appEnvChanges = s.appEnvChanges; m_buildBeforeDeployComboBox->setCurrentIndex( - m_buildBeforeDeployComboBox->findData(int(m_settings.buildBeforeDeploy))); - m_deployProjectBeforeRunCheckBox->setChecked(m_settings.deployBeforeRun); - m_saveAllFilesCheckBox->setChecked(m_settings.saveBeforeBuild); - m_jomCheckbox->setChecked(m_settings.useJom); - m_addLibraryPathsToRunEnvCheckBox->setChecked(m_settings.addLibraryPathsToRunEnv); - m_promptToStopRunControlCheckBox->setChecked(m_settings.prompToStopRunControl); - m_automaticallyCreateRunConfiguration->setChecked(m_settings.automaticallyCreateRunConfigurations); + m_buildBeforeDeployComboBox->findData(int(s.buildBeforeDeploy))); + m_deployProjectBeforeRunCheckBox->setChecked(s.deployBeforeRun); + m_saveAllFilesCheckBox->setChecked(s.saveBeforeBuild); + m_jomCheckbox->setChecked(s.useJom); + m_addLibraryPathsToRunEnvCheckBox->setChecked(s.addLibraryPathsToRunEnv); + m_promptToStopRunControlCheckBox->setChecked(s.prompToStopRunControl); + m_automaticallyCreateRunConfiguration->setChecked(s.automaticallyCreateRunConfigurations); m_stopBeforeBuildComboBox->setCurrentIndex( - m_stopBeforeBuildComboBox->findData(int(m_settings.stopBeforeBuild))); - m_terminalModeComboBox->setCurrentIndex(static_cast(m_settings.terminalMode)); - m_closeSourceFilesCheckBox->setChecked(m_settings.closeSourceFilesWithProject); - m_clearIssuesCheckBox->setChecked(m_settings.clearIssuesOnRebuild); - m_abortBuildAllOnErrorCheckBox->setChecked(m_settings.abortBuildAllOnError); - m_lowBuildPriorityCheckBox->setChecked(m_settings.lowBuildPriority); - m_warnAgainstNonAsciiBuildDirCheckBox->setChecked(m_settings.warnAgainstNonAsciiBuildDir); + m_stopBeforeBuildComboBox->findData(int(s.stopBeforeBuild))); + m_terminalModeComboBox->setCurrentIndex(static_cast(s.terminalMode)); + m_closeSourceFilesCheckBox->setChecked(s.closeSourceFilesWithProject); + m_clearIssuesCheckBox->setChecked(s.clearIssuesOnRebuild); + m_abortBuildAllOnErrorCheckBox->setChecked(s.abortBuildAllOnError); + m_lowBuildPriorityCheckBox->setChecked(s.lowBuildPriority); + m_warnAgainstNonAsciiBuildDirCheckBox->setChecked(s.warnAgainstNonAsciiBuildDir); } FilePath ProjectExplorerSettingsWidget::projectsDirectory() const @@ -292,14 +494,34 @@ void ProjectExplorerSettingsWidget::updateAppEnvChangesLabel() // ProjectExplorerSettingsPage -ProjectExplorerSettingsPage::ProjectExplorerSettingsPage() +class ProjectExplorerSettingsPage final : public IOptionsPage { - setId(Constants::BUILD_AND_RUN_SETTINGS_PAGE_ID); - setDisplayName(Tr::tr("General")); - setCategory(Constants::BUILD_AND_RUN_SETTINGS_CATEGORY); - setDisplayCategory(Tr::tr("Build & Run")); - setCategoryIconPath(":/projectexplorer/images/settingscategory_buildrun.png"); - setWidgetCreator([] { return new ProjectExplorerSettingsWidget; }); +public: + ProjectExplorerSettingsPage() + { + setId(ProjectExplorer::Constants::BUILD_AND_RUN_SETTINGS_PAGE_ID); + setDisplayName(Tr::tr("General")); + setCategory(ProjectExplorer::Constants::BUILD_AND_RUN_SETTINGS_CATEGORY); + setDisplayCategory(Tr::tr("Build & Run")); + setCategoryIconPath(":/projectexplorer/images/settingscategory_buildrun.png"); + setWidgetCreator([] { return new ProjectExplorerSettingsWidget; }); + } +}; + +void setupProjectExplorerSettings() +{ + static ProjectExplorerSettingsPage theProjectExplorerSettingsPage; + + loadProjectExplorerSettings(); } -} // ProjectExplorer::Internal + +} // Internal + +const ProjectExplorerSettings &projectExplorerSettings() +{ + return Internal::mutableProjectExplorerSettings(); +} + +} // ProjectExplorer + diff --git a/src/plugins/projectexplorer/projectexplorersettings.h b/src/plugins/projectexplorer/projectexplorersettings.h index dbec8ea2aef..51970eb290f 100644 --- a/src/plugins/projectexplorer/projectexplorersettings.h +++ b/src/plugins/projectexplorer/projectexplorersettings.h @@ -3,8 +3,9 @@ #pragma once +#include "projectexplorer_export.h" + #include -#include #include #include @@ -20,26 +21,6 @@ enum class StopBeforeBuild { None, SameProject, All, SameBuildDir, SameApp }; class ProjectExplorerSettings { public: - friend bool operator==(const ProjectExplorerSettings &p1, const ProjectExplorerSettings &p2) - { - return p1.buildBeforeDeploy == p2.buildBeforeDeploy - && p1.deployBeforeRun == p2.deployBeforeRun - && p1.saveBeforeBuild == p2.saveBeforeBuild - && p1.useJom == p2.useJom - && p1.prompToStopRunControl == p2.prompToStopRunControl - && p1.automaticallyCreateRunConfigurations == p2.automaticallyCreateRunConfigurations - && p1.addLibraryPathsToRunEnv == p2.addLibraryPathsToRunEnv - && p1.environmentId == p2.environmentId - && p1.stopBeforeBuild == p2.stopBeforeBuild - && p1.terminalMode == p2.terminalMode - && p1.closeSourceFilesWithProject == p2.closeSourceFilesWithProject - && p1.clearIssuesOnRebuild == p2.clearIssuesOnRebuild - && p1.abortBuildAllOnError == p2.abortBuildAllOnError - && p1.appEnvChanges == p2.appEnvChanges - && p1.warnAgainstNonAsciiBuildDir == p2.warnAgainstNonAsciiBuildDir - && p1.lowBuildPriority == p2.lowBuildPriority; - } - BuildBeforeRunMode buildBeforeDeploy = BuildBeforeRunMode::WholeProject; bool deployBeforeRun = true; bool saveBeforeBuild = false; @@ -64,8 +45,13 @@ public: QUuid environmentId; }; +PROJECTEXPLORER_EXPORT const ProjectExplorerSettings &projectExplorerSettings(); + namespace Internal { +void setPromptToStopSettings(bool promptToStop); // FIXME: Remove. +void setSaveBeforeBuildSettings(bool saveBeforeBuild); // FIXME: Remove. + enum class AppOutputPaneMode { FlashOnOutput, PopupOnOutput, PopupOnFirstOutput }; class AppOutputSettings @@ -79,11 +65,7 @@ public: int maxCharCount = Core::Constants::DEFAULT_MAX_CHAR_COUNT; }; -class ProjectExplorerSettingsPage : public Core::IOptionsPage -{ -public: - ProjectExplorerSettingsPage(); -}; +void setupProjectExplorerSettings(); } // namespace Internal } // namespace ProjectExplorer diff --git a/src/plugins/projectexplorer/runconfigurationaspects.cpp b/src/plugins/projectexplorer/runconfigurationaspects.cpp index 7b6c7f4f5d3..c042f081f1d 100644 --- a/src/plugins/projectexplorer/runconfigurationaspects.cpp +++ b/src/plugins/projectexplorer/runconfigurationaspects.cpp @@ -107,7 +107,7 @@ void TerminalAspect::calculateUseTerminal() if (m_userSet) return; bool useTerminal; - switch (ProjectExplorerPlugin::projectExplorerSettings().terminalMode) { + switch (projectExplorerSettings().terminalMode) { case TerminalMode::On: useTerminal = true; break; case TerminalMode::Off: useTerminal = false; break; default: useTerminal = m_useTerminalHint; @@ -737,7 +737,7 @@ UseLibraryPathsAspect::UseLibraryPathsAspect(AspectContainer *container) setLabel(Tr::tr("Add build library search path to LD_LIBRARY_PATH"), LabelPlacement::AtCheckBox); } - setValue(ProjectExplorerPlugin::projectExplorerSettings().addLibraryPathsToRunEnv); + setValue(projectExplorerSettings().addLibraryPathsToRunEnv); } diff --git a/src/plugins/projectexplorer/target.cpp b/src/plugins/projectexplorer/target.cpp index b4d8a776f89..cae9a01d02a 100644 --- a/src/plugins/projectexplorer/target.cpp +++ b/src/plugins/projectexplorer/target.cpp @@ -722,7 +722,7 @@ void Target::updateDefaultRunConfigurations() configuredCount -= toRemove.count(); bool removeExistingUnconfigured = false; - if (ProjectExplorerPlugin::projectExplorerSettings().automaticallyCreateRunConfigurations) { + if (projectExplorerSettings().automaticallyCreateRunConfigurations) { // Create new "automatic" RCs and put them into newConfigured/newUnconfigured for (const RunConfigurationCreationInfo &item : creators) { if (item.creationMode == RunConfigurationCreationInfo::ManualCreationOnly) diff --git a/src/plugins/projectexplorer/userfileaccessor.cpp b/src/plugins/projectexplorer/userfileaccessor.cpp index a370d80ff69..82e4d0edfbf 100644 --- a/src/plugins/projectexplorer/userfileaccessor.cpp +++ b/src/plugins/projectexplorer/userfileaccessor.cpp @@ -300,7 +300,7 @@ UserFileAccessor::UserFileAccessor(Project *project) secondary->setReadOnly(); setSecondaryAccessor(std::move(secondary)); - setSettingsId(ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray()); + setSettingsId(projectExplorerSettings().environmentId.toByteArray()); // Register Upgraders: addVersionUpgrader(std::make_unique()); @@ -990,7 +990,7 @@ void ProjectExplorerTest::testUserFileAccessor_prepareToWriteSettings() QCOMPARE(result.count(), data.count() + 3); QCOMPARE(result.value("EnvironmentId").toByteArray(), - ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray()); + projectExplorerSettings().environmentId.toByteArray()); QCOMPARE(result.value("UserStickyKeys"), QVariant(QStringList({"shared1"}))); QCOMPARE(result.value("Version").toInt(), accessor.currentVersion()); QCOMPARE(result.value("ProjectExplorer.Project.Updater.FileVersion").toInt(), accessor.currentVersion()); @@ -1013,7 +1013,7 @@ void ProjectExplorerTest::testUserFileAccessor_mergeSettings() Store data; data.insert("Version", accessor.currentVersion()); - data.insert("EnvironmentId", ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray()); + data.insert("EnvironmentId", projectExplorerSettings().environmentId.toByteArray()); data.insert("UserStickyKeys", QStringList({"shared1"})); data.insert("shared1", "bar1"); data.insert("unique1", 1234); @@ -1025,7 +1025,7 @@ void ProjectExplorerTest::testUserFileAccessor_mergeSettings() QCOMPARE(result.data.count(), data.count() + 1); // mergeSettings does not run updateSettings, so no OriginalVersion will be set QCOMPARE(result.data.value("EnvironmentId").toByteArray(), - ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray()); // unchanged + projectExplorerSettings().environmentId.toByteArray()); // unchanged QCOMPARE(result.data.value("UserStickyKeys"), QVariant(QStringList({"shared1"}))); // unchanged QCOMPARE(result.data.value("Version").toInt(), accessor.currentVersion()); // forced QCOMPARE(result.data.value("shared1"), data.value("shared1")); // from data @@ -1066,7 +1066,7 @@ void ProjectExplorerTest::testUserFileAccessor_mergeSettingsEmptyShared() Store data; data.insert("Version", accessor.currentVersion()); data.insert("OriginalVersion", accessor.currentVersion()); - data.insert("EnvironmentId", ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray()); + data.insert("EnvironmentId", projectExplorerSettings().environmentId.toByteArray()); data.insert("UserStickyKeys", QStringList({"shared1"})); data.insert("shared1", "bar1"); data.insert("unique1", 1234); From 22a1f11773afa42b7a7a54958dd8c6d098ad085d Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 18 Mar 2024 17:49:05 +0100 Subject: [PATCH 0147/1060] LanguageClient: Fix pre-selection of rename results ... for the case of aliased file paths. Task-number: QTCREATORBUG-30546 Change-Id: I2cce03529c45193c20bd3508e4dcb3dc051856fa Reviewed-by: David Schulz --- .../languageclientsymbolsupport.cpp | 33 ++++++++++++------- .../projectexplorer/projectmanager.cpp | 30 ++++++++++++----- src/plugins/projectexplorer/projectmanager.h | 1 + 3 files changed, 44 insertions(+), 20 deletions(-) diff --git a/src/plugins/languageclient/languageclientsymbolsupport.cpp b/src/plugins/languageclient/languageclientsymbolsupport.cpp index 3a9a1b09705..9bc7cd1027f 100644 --- a/src/plugins/languageclient/languageclientsymbolsupport.cpp +++ b/src/plugins/languageclient/languageclientsymbolsupport.cpp @@ -300,8 +300,9 @@ QStringList SymbolSupport::getFileContents(const Utils::FilePath &filePath) Utils::SearchResultItems generateSearchResultItems( const QMap> &rangesInDocument, - Core::SearchResult *search = nullptr, - bool limitToProjects = false) + Client *client, + Core::SearchResult *search, + bool limitToProjects) { Utils::SearchResultItems result; const bool renaming = search && search->supportsReplace(); @@ -321,8 +322,15 @@ Utils::SearchResultItems generateSearchResultItems( if (renaming && limitToProjects) { const ProjectExplorer::Node * const node = ProjectExplorer::ProjectTree::nodeForFile(filePath); - item.setSelectForReplacement(node && !node->isGenerated()); - if (node + if (node) { + item.setSelectForReplacement(!node->isGenerated()); + } else { + item.setSelectForReplacement( + client->project() + && ProjectExplorer::ProjectManager::isInProjectSourceDir( + filePath, *client->project())); + } + if (item.selectForReplacement() && filePath.baseName().compare(oldSymbolName, Qt::CaseInsensitive) == 0) { fileRenameCandidates << filePath; } @@ -362,17 +370,17 @@ void filterFileAliases(ItemDataPerPath &itemDataPerPath) } Utils::SearchResultItems generateSearchResultItems( - const LanguageClientArray &locations, const DocumentUri::PathMapper &pathMapper) + const LanguageClientArray &locations, Client *client) { if (locations.isNull()) return {}; ItemDataPerPath rangesInDocument; for (const Location &location : locations.toList()) { - rangesInDocument[location.uri().toFilePath(pathMapper)] + rangesInDocument[location.uri().toFilePath(client->hostPathMapper())] << ItemData{SymbolSupport::convertRange(location.range()), {}}; } filterFileAliases(rangesInDocument); - return generateSearchResultItems(rangesInDocument); + return generateSearchResultItems(rangesInDocument, client, nullptr, false); } void SymbolSupport::handleFindReferencesResponse(const FindReferencesRequest::Response &response, @@ -388,7 +396,7 @@ void SymbolSupport::handleFindReferencesResponse(const FindReferencesRequest::Re if (result) { Core::SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch( Tr::tr("Find References with %1 for:").arg(m_client->name()), "", wordUnderCursor); - search->addResults(generateSearchResultItems(*result, m_client->hostPathMapper()), + search->addResults(generateSearchResultItems(*result, m_client), Core::SearchResult::AddOrdered); connect(search, &Core::SearchResult::activated, [](const Utils::SearchResultItem &item) { Core::EditorManager::openEditorAtSearchResult(item); @@ -563,9 +571,9 @@ void SymbolSupport::requestRename(const TextDocumentPositionParams &positionPara } Utils::SearchResultItems generateReplaceItems(const WorkspaceEdit &edits, + Client *client, Core::SearchResult *search, - bool limitToProjects, - const DocumentUri::PathMapper &pathMapper) + bool limitToProjects) { Utils::SearchResultItems items; auto convertEdits = [](const QList &edits) { @@ -575,6 +583,7 @@ Utils::SearchResultItems generateReplaceItems(const WorkspaceEdit &edits, }; ItemDataPerPath rangesInDocument; auto documentChanges = edits.documentChanges().value_or(QList()); + const DocumentUri::PathMapper &pathMapper = client->hostPathMapper(); if (!documentChanges.isEmpty()) { for (const DocumentChange &documentChange : std::as_const(documentChanges)) { if (std::holds_alternative(documentChange)) { @@ -610,7 +619,7 @@ Utils::SearchResultItems generateReplaceItems(const WorkspaceEdit &edits, rangesInDocument[it.key().toFilePath(pathMapper)] = convertEdits(it.value()); } filterFileAliases(rangesInDocument); - items += generateSearchResultItems(rangesInDocument, search, limitToProjects); + items += generateSearchResultItems(rangesInDocument, client, search, limitToProjects); return items; } @@ -686,7 +695,7 @@ void SymbolSupport::handleRenameResponse(Core::SearchResult *search, const std::optional &edits = response.result(); if (edits.has_value()) { const Utils::SearchResultItems items = generateReplaceItems( - *edits, search, m_limitRenamingToProjects, m_client->hostPathMapper()); + *edits, m_client, search, m_limitRenamingToProjects); search->addResults(items, Core::SearchResult::AddOrdered); if (m_renameResultsEnhancer) { Utils::SearchResultItems additionalItems = m_renameResultsEnhancer(items); diff --git a/src/plugins/projectexplorer/projectmanager.cpp b/src/plugins/projectexplorer/projectmanager.cpp index e0cb5e2ca52..9da6ce358ed 100644 --- a/src/plugins/projectexplorer/projectmanager.cpp +++ b/src/plugins/projectexplorer/projectmanager.cpp @@ -502,16 +502,30 @@ Project *ProjectManager::projectForFile(const FilePath &fileName) [&fileName](const Project *p) { return p->isKnownFile(fileName); })) { return project; } - return Utils::findOrDefault(ProjectManager::projects(), - [&fileName](const Project *p) { - for (const Target * const target : p->targets()) { - for (const BuildConfiguration * const bc : target->buildConfigurations()) { - if (fileName.isChildOf(bc->buildDirectory())) - return false; + return Utils::findOrDefault(ProjectManager::projects(), [&fileName](const Project *p) { + return isInProjectSourceDir(fileName, *p); + }); +} + +bool ProjectManager::isInProjectSourceDir(const Utils::FilePath &filePath, const Project &project) +{ + for (const Target * const target : project.targets()) { + for (const BuildConfiguration * const bc : target->buildConfigurations()) { + if (filePath.isChildOf(bc->buildDirectory())) + return false; + if (const FilePath canonicalBuildDir = bc->buildDirectory().canonicalPath(); + canonicalBuildDir != bc->buildDirectory() && filePath.isChildOf(canonicalBuildDir)) { + return false; } } - return fileName.isChildOf(p->projectDirectory()); - }); + } + if (filePath.isChildOf(project.projectDirectory())) + return true; + if (const FilePath canonicalRoot = project.projectDirectory().canonicalPath(); + canonicalRoot != project.projectDirectory()) { + return filePath.isChildOf(canonicalRoot); + } + return false; } Project *ProjectManager::projectWithProjectFilePath(const FilePath &filePath) diff --git a/src/plugins/projectexplorer/projectmanager.h b/src/plugins/projectexplorer/projectmanager.h index 27913a00cd0..16ad8972813 100644 --- a/src/plugins/projectexplorer/projectmanager.h +++ b/src/plugins/projectexplorer/projectmanager.h @@ -77,6 +77,7 @@ public: static QList projectOrder(const Project *project = nullptr); static Project *projectForFile(const Utils::FilePath &fileName); + static bool isInProjectSourceDir(const Utils::FilePath &filePath, const Project &project); static Project *projectWithProjectFilePath(const Utils::FilePath &filePath); static Utils::FilePaths projectsForSessionName(const QString &session); From 77a2e2fdeeb275b6168edd68e31755ebc5c38047 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Fri, 12 Apr 2024 16:16:24 +0200 Subject: [PATCH 0148/1060] Compiler Explorer: Remove unused lambda Change-Id: Iabef84b8d778449aa0091f29b38e607ab3757b82 Reviewed-by: hjk --- src/plugins/compilerexplorer/compilerexplorereditor.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index 0af2973b9b4..706958da986 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -891,13 +891,6 @@ EditorFactory::EditorFactory() setId(Constants::CE_EDITOR_ID); setDisplayName(Tr::tr("Compiler Explorer Editor")); setMimeTypes({"application/compiler-explorer"}); - - auto undoStackFromEditor = [](Core::IEditor *editor) -> QUndoStack * { - if (!editor) - return nullptr; - return &static_cast(editor)->m_undoStack; - }; - setEditorCreator([] { return new Editor; }); } From a03974245a5ecab6b6e679678562df489ae1b8ec Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 26 Feb 2024 10:44:13 +0100 Subject: [PATCH 0149/1060] ProjectExplorer: De-QObject-ify ExtraCompilerFactory The QObject related features are not used any more and are not meant to be used again. Change-Id: I03ee7929e40c3cd9fd50af020dc4d38280c205d8 Reviewed-by: Christian Kandeler --- src/plugins/projectexplorer/extracompiler.cpp | 3 +-- src/plugins/projectexplorer/extracompiler.h | 7 +++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/plugins/projectexplorer/extracompiler.cpp b/src/plugins/projectexplorer/extracompiler.cpp index 0d281297339..932e5c1bd7d 100644 --- a/src/plugins/projectexplorer/extracompiler.cpp +++ b/src/plugins/projectexplorer/extracompiler.cpp @@ -301,8 +301,7 @@ void ExtraCompiler::setContent(const FilePath &file, const QByteArray &contents) } } -ExtraCompilerFactory::ExtraCompilerFactory(QObject *parent) - : QObject(parent) +ExtraCompilerFactory::ExtraCompilerFactory() { factories->append(this); } diff --git a/src/plugins/projectexplorer/extracompiler.h b/src/plugins/projectexplorer/extracompiler.h index 82bd9070f25..a8045d25b1e 100644 --- a/src/plugins/projectexplorer/extracompiler.h +++ b/src/plugins/projectexplorer/extracompiler.h @@ -108,12 +108,11 @@ private: const Utils::Environment &env); }; -class PROJECTEXPLORER_EXPORT ExtraCompilerFactory : public QObject +class PROJECTEXPLORER_EXPORT ExtraCompilerFactory { - Q_OBJECT public: - explicit ExtraCompilerFactory(QObject *parent = nullptr); - ~ExtraCompilerFactory() override; + ExtraCompilerFactory(); + virtual ~ExtraCompilerFactory(); virtual FileType sourceType() const = 0; virtual QString sourceTag() const = 0; From 559c57e29c7fd441f3f859c24f3e1483101ded5d Mon Sep 17 00:00:00 2001 From: Alessandro Portale Date: Fri, 5 Apr 2024 17:19:45 +0200 Subject: [PATCH 0150/1060] ExtensionSystem: Add "soft loadable" to PluginDetailsView Change-Id: Ifc9007f07c17dcc68f1b7c62b1027e66e653646f Reviewed-by: Eike Ziller Reviewed-by: hjk --- src/libs/extensionsystem/plugindetailsview.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/libs/extensionsystem/plugindetailsview.cpp b/src/libs/extensionsystem/plugindetailsview.cpp index 73fa2b1229d..291b3852198 100644 --- a/src/libs/extensionsystem/plugindetailsview.cpp +++ b/src/libs/extensionsystem/plugindetailsview.cpp @@ -8,6 +8,7 @@ #include "pluginspec.h" #include +#include #include #include @@ -54,6 +55,7 @@ public: , copyright(createContentsLabel()) , license(createTextEdit()) , dependencies(new QListWidget(q)) + , softLoadable(new Utils::InfoLabel) { using namespace Layouting; @@ -70,7 +72,8 @@ public: Tr::tr("Description:"), description, br, Tr::tr("Copyright:"), copyright, br, Tr::tr("License:"), license, br, - Tr::tr("Dependencies:"), dependencies, + Tr::tr("Dependencies:"), dependencies, br, + Tr::tr("Loadable without restart:"), softLoadable, br, noMargin }.attachTo(q); // clang-format on @@ -90,6 +93,7 @@ public: QLabel *copyright = nullptr; QTextEdit *license = nullptr; QListWidget *dependencies = nullptr; + Utils::InfoLabel *softLoadable = nullptr; private: QLabel *createContentsLabel() { @@ -157,6 +161,8 @@ void PluginDetailsView::update(PluginSpec *spec) d->license->setText(spec->license()); d->dependencies->addItems(Utils::transform(spec->dependencies(), &PluginDependency::toString)); + d->softLoadable->setType(spec->isSoftLoadable() ? Utils::InfoLabel::Ok + : Utils::InfoLabel::NotOk); } void PluginDetailsView::showModal(QWidget *parent, PluginSpec *spec) From ee8245d8aaa4e34d2773c572aa05a4ca5866f151 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Fri, 12 Apr 2024 12:53:27 +0200 Subject: [PATCH 0151/1060] Core: allow multiple contexts per widget This makes it possible to allow different sets of actions for a specific widget depending on the defined contexts for that widget. Fixes: QTCREATORBUG-30675 Fixes: QTCREATORBUG-30677 Change-Id: I408e0ae445b364d4f450ccdd2fbdfc81ece45015 Reviewed-by: Eike Ziller --- src/plugins/coreplugin/icore.cpp | 63 ++++++++++----------- src/plugins/coreplugin/icore.h | 4 +- src/plugins/coreplugin/statusbarmanager.cpp | 10 +--- src/plugins/help/helpplugin.cpp | 30 ++++++++-- 4 files changed, 61 insertions(+), 46 deletions(-) diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp index 8a727494c2d..85401aa8bc7 100644 --- a/src/plugins/coreplugin/icore.cpp +++ b/src/plugins/coreplugin/icore.cpp @@ -314,7 +314,7 @@ public: QList m_activeContext; - std::unordered_map m_contextWidgets; + std::unordered_map> m_contextWidgets; ShortcutSettings *m_shortcutSettings = nullptr; ToolSettings *m_toolSettings = nullptr; @@ -836,16 +836,18 @@ QString ICore::versionString() } /*! - Returns the top level IContext of the current context, or \c nullptr if + Returns a list IContexts for the current top level context widget, or an empty list if there is none. \sa updateAdditionalContexts() \sa addContextObject() \sa {The Action Manager and Commands} */ -IContext *ICore::currentContextObject() +QList ICore::currentContextObjects() { - return d->m_activeContext.isEmpty() ? nullptr : d->m_activeContext.first(); + if (d->m_activeContext.isEmpty()) + return {}; + return d->m_contextWidgets[d->m_activeContext.first()->widget()]; } /*! @@ -856,8 +858,7 @@ IContext *ICore::currentContextObject() */ QWidget *ICore::currentContextWidget() { - IContext *context = currentContextObject(); - return context ? context->widget() : nullptr; + return d->m_activeContext.isEmpty() ? nullptr : d->m_activeContext.first()->widget(); } /*! @@ -1525,8 +1526,10 @@ void ICore::extensionsInitialized() void ICore::aboutToShutdown() { disconnect(qApp, &QApplication::focusChanged, d, &ICorePrivate::updateFocusWidget); - for (auto contextPair : d->m_contextWidgets) - disconnect(contextPair.second, &QObject::destroyed, d->m_mainwindow, nullptr); + for (auto contextsPair : d->m_contextWidgets) { + for (auto context : contextsPair.second) + disconnect(context, &QObject::destroyed, d->m_mainwindow, nullptr); + } d->m_activeContext.clear(); d->m_mainwindow->hide(); } @@ -2281,13 +2284,14 @@ void ICore::openFileWith() } /*! - Returns the registered IContext instance for the specified \a widget, + Returns all registered IContext instance for the specified \a widget, if any. */ -IContext *ICore::contextObject(QWidget *widget) +QList ICore::contextObjects(QWidget *widget) { - const auto it = d->m_contextWidgets.find(widget); - return it == d->m_contextWidgets.end() ? nullptr : it->second; + if (auto it = d->m_contextWidgets.find(widget); it != d->m_contextWidgets.end()) + return it->second; + return {}; } /*! @@ -2306,11 +2310,7 @@ void ICore::addContextObject(IContext *context) { if (!context) return; - QWidget *widget = context->widget(); - if (d->m_contextWidgets.find(widget) != d->m_contextWidgets.end()) - return; - - d->m_contextWidgets.insert({widget, context}); + d->m_contextWidgets[context->widget()].append(context); connect(context, &QObject::destroyed, m_core, [context] { removeContextObject(context); }); } @@ -2331,15 +2331,19 @@ void ICore::removeContextObject(IContext *context) disconnect(context, &QObject::destroyed, m_core, nullptr); - const auto it = std::find_if(d->m_contextWidgets.cbegin(), - d->m_contextWidgets.cend(), - [context](const std::pair &v) { - return v.second == context; - }); - if (it == d->m_contextWidgets.cend()) + auto it = std::find_if( + d->m_contextWidgets.begin(), + d->m_contextWidgets.end(), + [context](const std::pair> &v) { + return v.second.contains(context); + }); + if (it == d->m_contextWidgets.end()) return; - d->m_contextWidgets.erase(it); + it->second.removeAll(context); + if (it->second.isEmpty()) + d->m_contextWidgets.erase(it); + if (d->m_activeContext.removeAll(context) > 0) d->updateContextObject(d->m_activeContext); } @@ -2355,15 +2359,8 @@ void ICorePrivate::updateFocusWidget(QWidget *old, QWidget *now) return; QList newContext; - if (QWidget *p = QApplication::focusWidget()) { - IContext *context = nullptr; - while (p) { - context = ICore::contextObject(p); - if (context) - newContext.append(context); - p = p->parentWidget(); - } - } + for (QWidget *p = QApplication::focusWidget(); p; p = p->parentWidget()) + newContext.append(ICore::contextObjects(p)); // ignore toplevels that define no context, like popups without parent if (!newContext.isEmpty() || QApplication::focusWidget() == m_mainwindow->focusWidget()) diff --git a/src/plugins/coreplugin/icore.h b/src/plugins/coreplugin/icore.h index 8c713e156f4..2c2dbc3c57a 100644 --- a/src/plugins/coreplugin/icore.h +++ b/src/plugins/coreplugin/icore.h @@ -87,9 +87,9 @@ public: static void raiseWindow(QWidget *widget); static void raiseMainWindow(); - static IContext *currentContextObject(); + static QList currentContextObjects(); static QWidget *currentContextWidget(); - static IContext *contextObject(QWidget *widget); + static QList contextObjects(QWidget *widget); static void updateAdditionalContexts(const Context &remove, const Context &add, ContextPriority priority = ContextPriority::Low); static void addAdditionalContext(const Context &context, diff --git a/src/plugins/coreplugin/statusbarmanager.cpp b/src/plugins/coreplugin/statusbarmanager.cpp index c590b3f29ef..e85996b053a 100644 --- a/src/plugins/coreplugin/statusbarmanager.cpp +++ b/src/plugins/coreplugin/statusbarmanager.cpp @@ -156,13 +156,9 @@ StatusBarContext::StatusBarContext(QObject *parent) Context StatusBarContext::context() const { - IMode *currentMode = ModeManager::currentMode(); - QWidget *modeWidget = currentMode ? currentMode->widget() : nullptr; - if (modeWidget) { - if (IContext *context = ICore::contextObject(modeWidget)) - return context->context(); - } - return Context(); + if (IMode *currentMode = ModeManager::currentMode()) + return currentMode->context(); + return {}; } } // Core diff --git a/src/plugins/help/helpplugin.cpp b/src/plugins/help/helpplugin.cpp index e9706a3db18..49b4624b269 100644 --- a/src/plugins/help/helpplugin.cpp +++ b/src/plugins/help/helpplugin.cpp @@ -102,6 +102,7 @@ public: void modeChanged(Id mode, Id old); void requestContextHelp(); + void requestContextHelpFor(QList> contexts); void showContextHelp(const HelpItem &contextHelp); void activateIndex(); void activateContents(); @@ -464,11 +465,32 @@ void HelpPluginPrivate::requestContextHelp() const HelpItem tipHelp = tipHelpValue.canConvert() ? tipHelpValue.value() : HelpItem(tipHelpValue.toString()); - IContext *context = ICore::currentContextObject(); - if (tipHelp.isEmpty() && context) - context->contextHelp([this](const HelpItem &item) { showContextHelp(item); }); - else + const QList contexts = ICore::currentContextObjects(); + if (contexts.isEmpty() && !tipHelp.isEmpty()) { showContextHelp(tipHelp); + } else { + requestContextHelpFor(Utils::transform(contexts, [](IContext *context) { + return QPointer(context); + })); + } +} + +void HelpPluginPrivate::requestContextHelpFor(QList> contexts) +{ + if (contexts.isEmpty()) + return; + QPointer context = contexts.takeFirst(); + while (!context) { + if (contexts.isEmpty()) + return; + context = contexts.takeFirst(); + } + context->contextHelp([contexts, this](const HelpItem &item) { + if (!item.isEmpty()) + showContextHelp(item); + else + requestContextHelpFor(contexts); + }); } void HelpPluginPrivate::showContextHelp(const HelpItem &contextHelp) From e1d90a7965e167287550dc39f9b941569b7d8a49 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Mon, 8 Apr 2024 15:30:05 +0200 Subject: [PATCH 0152/1060] QmlJS: Improve handling of user defined enums Improves handling of Qml based enums inside qml documents. * completion of enums * follow the enum * highlighting values inside the declaration * displaying the enum declaration inside the outline * minor static checks Task-number: QTCREATORBUG-19226 Change-Id: Ia07fd9a8b7fa3106f2ea53198bfdcc50eecb7307 Reviewed-by: Ulf Hermann --- src/libs/qmljs/qmljsbind.cpp | 10 ++++ src/libs/qmljs/qmljsbind.h | 1 + src/libs/qmljs/qmljscheck.cpp | 24 +++++++++ src/libs/qmljs/qmljscheck.h | 2 + src/libs/qmljs/qmljsicons.cpp | 5 ++ src/libs/qmljs/qmljsicons.h | 1 + src/libs/qmljs/qmljsinterpreter.cpp | 51 +++++++++++++++++++ src/libs/qmljs/qmljsinterpreter.h | 29 +++++++++++ .../qmljseditor/qmljsfindreferences.cpp | 11 ++++ src/plugins/qmljseditor/qmljshighlighter.cpp | 4 -- .../qmljseditor/qmljssemantichighlighter.cpp | 7 +++ src/plugins/qmljseditor/qmloutlinemodel.cpp | 40 +++++++++++++++ src/plugins/qmljseditor/qmloutlinemodel.h | 3 ++ 13 files changed, 184 insertions(+), 4 deletions(-) diff --git a/src/libs/qmljs/qmljsbind.cpp b/src/libs/qmljs/qmljsbind.cpp index 6ccddcbe630..73da878343a 100644 --- a/src/libs/qmljs/qmljsbind.cpp +++ b/src/libs/qmljs/qmljsbind.cpp @@ -333,6 +333,16 @@ bool Bind::visit(UiInlineComponent *ast) return true; } +bool Bind::visit(UiEnumDeclaration *ast) +{ + if (_currentObjectValue) { + UiEnumValue *value = new UiEnumValue(ast, &_valueOwner, _currentObjectValue->originId()); + _qmlObjects.insert(ast, value); + _currentObjectValue->setMember(ast->name, value); + } + return true; +} + bool Bind::visit(AST::TemplateLiteral *ast) { Node::accept(ast->expression, this); diff --git a/src/libs/qmljs/qmljsbind.h b/src/libs/qmljs/qmljsbind.h index 08a60c17cc1..d7096abdb28 100644 --- a/src/libs/qmljs/qmljsbind.h +++ b/src/libs/qmljs/qmljsbind.h @@ -57,6 +57,7 @@ protected: bool visit(AST::UiScriptBinding *ast) override; bool visit(AST::UiArrayBinding *ast) override; bool visit(AST::UiInlineComponent *ast) override; + bool visit(AST::UiEnumDeclaration *ast) override; // QML/JS bool visit(AST::TemplateLiteral *ast) override; diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index 7ceff0e78de..0d21fd4bdae 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -846,6 +846,30 @@ bool Check::visit(UiObjectInitializer *) return true; } +bool Check::visit(AST::UiEnumDeclaration *ast) +{ + const Value *localLookup = _scopeChain.lookup(ast->name.toString()); + Utils::FilePath fp; + int line, column; + if (localLookup->getSourceLocation(&fp, &line, &column)) { + // if it's not "us" we get shadowed by another enum declaration + if (ast->identifierToken.startLine != line || ast->identifierToken.startColumn != column) + addMessage(ErrDuplicateId, SourceLocation(0, 0, line, column)); + } + return true; +} + +bool Check::visit(AST::UiEnumMemberList *ast) +{ + QStringList names; + for (auto it = ast; it; it = it->next) { + if (names.contains(it->member)) // duplicate enum value + addMessage(ErrInvalidEnumValue, it->memberToken); // better a different message? + names.append(it->member.toString()); + } + return true; +} + bool Check::visit(AST::TemplateLiteral *ast) { Node::accept(ast->expression, this); diff --git a/src/libs/qmljs/qmljscheck.h b/src/libs/qmljs/qmljscheck.h index 1fb96d251b5..d7fc6cc4256 100644 --- a/src/libs/qmljs/qmljscheck.h +++ b/src/libs/qmljs/qmljscheck.h @@ -57,6 +57,8 @@ protected: bool visit(AST::FunctionDeclaration *ast) override; bool visit(AST::FunctionExpression *ast) override; bool visit(AST::UiObjectInitializer *) override; + bool visit(AST::UiEnumDeclaration *ast) override; + bool visit(AST::UiEnumMemberList *ast) override; bool visit(AST::TemplateLiteral *ast) override; bool visit(AST::BinaryExpression *ast) override; diff --git a/src/libs/qmljs/qmljsicons.cpp b/src/libs/qmljs/qmljsicons.cpp index 0086843553b..a0522ca726b 100644 --- a/src/libs/qmljs/qmljsicons.cpp +++ b/src/libs/qmljs/qmljsicons.cpp @@ -120,3 +120,8 @@ QIcon Icons::functionDeclarationIcon() { return Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::FuncPublic); } + +QIcon Icons::enumMemberIcon() +{ + return Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::Enum); +} diff --git a/src/libs/qmljs/qmljsicons.h b/src/libs/qmljs/qmljsicons.h index 4466d07a18e..1565ae5355c 100644 --- a/src/libs/qmljs/qmljsicons.h +++ b/src/libs/qmljs/qmljsicons.h @@ -28,6 +28,7 @@ public: static QIcon scriptBindingIcon(); static QIcon publicMemberIcon(); static QIcon functionDeclarationIcon(); + static QIcon enumMemberIcon(); private: Icons(); diff --git a/src/libs/qmljs/qmljsinterpreter.cpp b/src/libs/qmljs/qmljsinterpreter.cpp index 5d687d5cd74..09bc6aecdb8 100644 --- a/src/libs/qmljs/qmljsinterpreter.cpp +++ b/src/libs/qmljs/qmljsinterpreter.cpp @@ -635,6 +635,52 @@ const CppComponentValue *QmlEnumValue::owner() const return m_owner; } +UiEnumValue::UiEnumValue(AST::UiEnumDeclaration *ast, + ValueOwner *valueOwner, const QString &originId) + : ObjectValue(valueOwner, originId) + , m_name(ast->name.toString()) +{ + setClassName("enum"); + m_path = Utils::FilePath::fromUserInput(originId); + m_line = ast->identifierToken.startLine; + m_column = ast->identifierToken.startColumn; + + for (auto it = ast->members; it; it = it->next) { + const QString name = it->member.toString(); + setMember(name, valueOwner->intValue()); + setPropertyInfo(name, PropertyInfo(PropertyInfo::Readable|PropertyInfo::ValueType)); + m_keys.append(name); + m_values.append(it->value); + } +} + +UiEnumValue::~UiEnumValue() +{ +} + +const UiEnumValue *UiEnumValue::asUiEnumValue() const +{ + return this; +} + +bool UiEnumValue::getSourceLocation(Utils::FilePath *path, int *line, int *column) const +{ + *path = m_path; + *line = m_line; + *column = m_column; + return true; +} + +QString UiEnumValue::name() const +{ + return m_name; +} + +QStringList UiEnumValue::keys() const +{ + return m_keys; +} + //////////////////////////////////////////////////////////////////////////////// // ValueVisitor //////////////////////////////////////////////////////////////////////////////// @@ -791,6 +837,11 @@ const QmlEnumValue *Value::asQmlEnumValue() const return nullptr; } +const UiEnumValue *Value::asUiEnumValue() const +{ + return nullptr; +} + const QmlPrototypeReference *Value::asQmlPrototypeReference() const { return nullptr; diff --git a/src/libs/qmljs/qmljsinterpreter.h b/src/libs/qmljs/qmljsinterpreter.h index 8651196aefa..aeb3c9e4389 100644 --- a/src/libs/qmljs/qmljsinterpreter.h +++ b/src/libs/qmljs/qmljsinterpreter.h @@ -44,6 +44,7 @@ class NumberValue; class ModuleApiInfo; class ObjectValue; class QmlEnumValue; +class UiEnumValue; class QmlPrototypeReference; class RealValue; class Reference; @@ -115,6 +116,7 @@ public: virtual const CppComponentValue *asCppComponentValue() const; virtual const ASTObjectValue *asAstObjectValue() const; virtual const QmlEnumValue *asQmlEnumValue() const; + virtual const UiEnumValue *asUiEnumValue() const; virtual const QmlPrototypeReference *asQmlPrototypeReference() const; virtual const ASTPropertyReference *asAstPropertyReference() const; virtual const ASTVariableReference *asAstVariableReference() const; @@ -246,6 +248,12 @@ template <> Q_INLINE_TEMPLATE const QmlEnumValue *value_cast(const Value *v) else return nullptr; } +template <> Q_INLINE_TEMPLATE const UiEnumValue *value_cast(const Value *v) +{ + if (v) return v->asUiEnumValue(); + else return nullptr; +} + template <> Q_INLINE_TEMPLATE const QmlPrototypeReference *value_cast(const Value *v) { if (v) return v->asQmlPrototypeReference(); @@ -559,6 +567,27 @@ private: int m_enumIndex; }; +class QMLJS_EXPORT UiEnumValue : public ObjectValue +{ +public: + UiEnumValue(AST::UiEnumDeclaration *uiEnum, ValueOwner *valueOwner, + const QString &originId); + ~UiEnumValue(); + + const UiEnumValue *asUiEnumValue() const override; + bool getSourceLocation(Utils::FilePath *path, int *line, int *column) const override; + QString name() const; + QStringList keys() const; + +private: + const QString m_name; + Utils::FilePath m_path; + int m_line; + int m_column; + QStringList m_keys; + QList m_values; +}; + // A ObjectValue based on a FakeMetaObject. // May only have other CppComponentValue as ancestors. diff --git a/src/plugins/qmljseditor/qmljsfindreferences.cpp b/src/plugins/qmljseditor/qmljsfindreferences.cpp index 3f5d53d60f5..8934865783d 100644 --- a/src/plugins/qmljseditor/qmljsfindreferences.cpp +++ b/src/plugins/qmljseditor/qmljsfindreferences.cpp @@ -599,6 +599,17 @@ protected: return true; } + bool visit(UiEnumDeclaration *node) override + { + if (containsOffset(node->identifierToken)) { + _name = node->name.toString(); + _scope = _doc->bind()->findQmlObject(_objectNode); + _targetValue = _scopeChain->context()->lookupType(_doc.data(), QStringList(_name)); + return false; + } + return true; + } + bool visit(FunctionDeclaration *node) override { return visit(static_cast(node)); diff --git a/src/plugins/qmljseditor/qmljshighlighter.cpp b/src/plugins/qmljseditor/qmljshighlighter.cpp index 4fd1da274ee..8000baf57f8 100644 --- a/src/plugins/qmljseditor/qmljshighlighter.cpp +++ b/src/plugins/qmljseditor/qmljshighlighter.cpp @@ -108,10 +108,6 @@ void QmlJSHighlighter::highlightBlock(const QString &text) break; } } - if (QStringView(text).mid(token.offset, token.length) == QLatin1String("enum")) { - setFormat(token.offset, token.length, formatForCategory(C_KEYWORD)); - break; - } } else if (index > 0 && maybeQmlBuiltinType(spell)) { const Token &previousToken = tokens.at(index - 1); if (previousToken.is(Token::Identifier) diff --git a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp index 67e14dfbcd5..c8666b96053 100644 --- a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp +++ b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp @@ -348,6 +348,13 @@ protected: return visit(static_cast(ast)); } + bool visit(UiEnumMemberList *ast) override + { + for (auto it = ast; it; it = it->next) + addUse(it->memberToken, SemanticHighlighter::FieldType); + return true; + } + bool visit(PatternElement *ast) override { if (ast->isVariableDeclaration()) diff --git a/src/plugins/qmljseditor/qmloutlinemodel.cpp b/src/plugins/qmljseditor/qmloutlinemodel.cpp index 015e8a41eb1..456789f645b 100644 --- a/src/plugins/qmljseditor/qmloutlinemodel.cpp +++ b/src/plugins/qmljseditor/qmloutlinemodel.cpp @@ -233,6 +233,19 @@ private: m_model->leavePublicMember(); } + bool visit(AST::UiEnumDeclaration *enumDecl) override + { + QModelIndex index = m_model->enterEnumDeclaration(enumDecl); + m_nodeToIndex.insert(enumDecl, index); + + return true; + } + + void endVisit(AST::UiEnumDeclaration *) override + { + m_model->leavePublicMember(); + } + bool visit(AST::FunctionDeclaration *functionDeclaration) override { QModelIndex index = m_model->enterFunctionDeclaration(functionDeclaration); @@ -576,6 +589,33 @@ void QmlOutlineModel::leavePublicMember() leaveNode(); } +QModelIndex QmlOutlineModel::enterEnumDeclaration(AST::UiEnumDeclaration *enumDecl) +{ + QMap objectData; + if (!enumDecl->name.isEmpty()) + objectData.insert(Qt::DisplayRole, enumDecl->name.toString()); + objectData.insert(ItemTypeRole, ElementBindingType); + + QmlOutlineItem *item = enterNode(objectData, enumDecl, nullptr, Icons::enumMemberIcon()); + + for (auto member = enumDecl->members; member; member = member->next) { + QMap memberData; + if (!member->member.isEmpty()) + memberData.insert(Qt::DisplayRole, member->member.toString()); + memberData.insert(ItemTypeRole, ElementBindingType); + memberData.insert(AnnotationRole, QString::number(member->value)); + enterNode(memberData, member, nullptr, Icons::publicMemberIcon()); + leaveNode(); + } + + return item->index(); +} + +void QmlOutlineModel::leaveEnumDeclaration() +{ + leaveNode(); +} + static QString functionDisplayName(QStringView name, AST::FormalParameterList *formals) { QString display; diff --git a/src/plugins/qmljseditor/qmloutlinemodel.h b/src/plugins/qmljseditor/qmloutlinemodel.h index 886d1986e59..bacb041714d 100644 --- a/src/plugins/qmljseditor/qmloutlinemodel.h +++ b/src/plugins/qmljseditor/qmloutlinemodel.h @@ -91,6 +91,9 @@ private: QModelIndex enterPublicMember(QmlJS::AST::UiPublicMember *publicMember); void leavePublicMember(); + QModelIndex enterEnumDeclaration(QmlJS::AST::UiEnumDeclaration *enumDecl); + void leaveEnumDeclaration(); + QModelIndex enterFunctionDeclaration(QmlJS::AST::FunctionDeclaration *functionDeclaration); void leaveFunctionDeclaration(); From 9a32905bcc7662bcd33623599403e9cc9cf33ede Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Mon, 15 Apr 2024 10:20:30 +0200 Subject: [PATCH 0153/1060] QmlJS: Add another static check for enum values Task-number: QTCREATORBUG-19226 Change-Id: Ic995eee2e868bbe1953c0c33d1bab5793e07ebe2 Reviewed-by: Ulf Hermann --- src/libs/qmljs/qmljscheck.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index 0d21fd4bdae..5b9a83e4eb5 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -863,6 +863,8 @@ bool Check::visit(AST::UiEnumMemberList *ast) { QStringList names; for (auto it = ast; it; it = it->next) { + if (!it->member.first().isUpper()) + addMessage(ErrInvalidEnumValue, it->memberToken); // better a different message? if (names.contains(it->member)) // duplicate enum value addMessage(ErrInvalidEnumValue, it->memberToken); // better a different message? names.append(it->member.toString()); From d51128fb8a2d42cf70974356dcb95922f612d7c3 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Mon, 15 Apr 2024 10:51:03 +0200 Subject: [PATCH 0154/1060] QmlJs: Fix a warning about comparison of different signs Amends e1d90a7965e167287550dc39f9b941569b7d8a49 Change-Id: I7c49927cbe8db71e3571875b59b522d186a852df Reviewed-by: Christian Stenger --- src/libs/qmljs/qmljscheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index 5b9a83e4eb5..8cf85f11eda 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -853,7 +853,7 @@ bool Check::visit(AST::UiEnumDeclaration *ast) int line, column; if (localLookup->getSourceLocation(&fp, &line, &column)) { // if it's not "us" we get shadowed by another enum declaration - if (ast->identifierToken.startLine != line || ast->identifierToken.startColumn != column) + if (int(ast->identifierToken.startLine) != line || int(ast->identifierToken.startColumn) != column) addMessage(ErrDuplicateId, SourceLocation(0, 0, line, column)); } return true; From ac4bf6901b2902789b13c0534426e9edfbb06f5a Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 12 Apr 2024 12:30:30 +0200 Subject: [PATCH 0155/1060] CppEditor: Simplify CppCodeModelSettings We don't need the QObject wrapper. Change-Id: Ief0e1314db40cb403c56fe0e660c5dffa326f83c Reviewed-by: Reviewed-by: David Schulz --- src/plugins/clangtools/clangfileinfo.h | 4 +- .../cppeditor/baseeditordocumentprocessor.cpp | 4 +- .../builtineditordocumentprocessor.cpp | 2 +- .../cppeditor/cppcodemodelsettings.cpp | 117 +++++++++--------- src/plugins/cppeditor/cppcodemodelsettings.h | 66 ++++------ src/plugins/cppeditor/cppeditorplugin.cpp | 2 +- src/plugins/cppeditor/cppmodelmanager.cpp | 13 +- src/plugins/cppeditor/cppmodelmanager.h | 3 +- .../cppeditor/cppmodelmanager_test.cpp | 9 +- src/plugins/cppeditor/projectinfo.cpp | 8 +- 10 files changed, 103 insertions(+), 125 deletions(-) diff --git a/src/plugins/clangtools/clangfileinfo.h b/src/plugins/clangtools/clangfileinfo.h index deb53f60588..bc54de3dc20 100644 --- a/src/plugins/clangtools/clangfileinfo.h +++ b/src/plugins/clangtools/clangfileinfo.h @@ -24,7 +24,7 @@ public: CppEditor::ProjectPart::ConstPtr projectPart) : file(std::move(file)) , kind(kind) - , settings(settings.data()) + , settings(settings) , projectPart(projectPart) {} @@ -34,7 +34,7 @@ public: Utils::FilePath file; CppEditor::ProjectFile::Kind kind; - CppEditor::CppCodeModelSettings::Data settings; + CppEditor::CppCodeModelSettings settings; CppEditor::ProjectPart::ConstPtr projectPart; }; using FileInfos = std::vector; diff --git a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp index 786999223ec..e2c600681dd 100644 --- a/src/plugins/cppeditor/baseeditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/baseeditordocumentprocessor.cpp @@ -37,10 +37,10 @@ BaseEditorDocumentProcessor::~BaseEditorDocumentProcessor() = default; void BaseEditorDocumentProcessor::run(bool projectsUpdated) { if (projectsUpdated) - m_settings.setData(CppCodeModelSettings::settingsForFile(m_filePath).data()); + m_settings = CppCodeModelSettings::settingsForFile(m_filePath); const Utils::Language languagePreference - = m_settings.interpretAmbigiousHeadersAsC() ? Utils::Language::C : Utils::Language::Cxx; + = m_settings.interpretAmbigiousHeadersAsC ? Utils::Language::C : Utils::Language::Cxx; runImpl({CppModelManager::workingCopy(), ProjectExplorer::ProjectManager::startupProject(), diff --git a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp index 5f827c74ce9..33f415fe6be 100644 --- a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp @@ -151,7 +151,7 @@ BuiltinEditorDocumentProcessor::BuiltinEditorDocumentProcessor(TextEditor::TextD using namespace Internal; BaseEditorDocumentParser::Configuration config = m_parser->configuration(); - config.usePrecompiledHeaders = settings().pchUsage() != CppCodeModelSettings::PchUse_None; + config.usePrecompiledHeaders = settings().pchUsage != CppCodeModelSettings::PchUse_None; m_parser->setConfiguration(config); m_semanticHighlighter->setHighlightingRunner( diff --git a/src/plugins/cppeditor/cppcodemodelsettings.cpp b/src/plugins/cppeditor/cppcodemodelsettings.cpp index 4791fd528ee..f24baaf8be6 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.cpp +++ b/src/plugins/cppeditor/cppcodemodelsettings.cpp @@ -6,6 +6,7 @@ #include "compileroptionsbuilder.h" #include "cppeditorconstants.h" #include "cppeditortr.h" +#include "cppmodelmanager.h" #include #include @@ -49,19 +50,19 @@ static Key useBuiltinPreprocessorKey() { return Constants::CPPEDITOR_USE_BUILTIN static Key indexerFileSizeLimitKey() { return Constants::CPPEDITOR_INDEXER_FILE_SIZE_LIMIT; } static Key useGlobalSettingsKey() { return "useGlobalSettings"; } -bool operator==(const CppEditor::CppCodeModelSettings::Data &s1, - const CppEditor::CppCodeModelSettings::Data &s2) +bool operator==(const CppEditor::CppCodeModelSettings &s1, + const CppEditor::CppCodeModelSettings &s2) { return s1.pchUsage == s2.pchUsage && s1.interpretAmbigiousHeadersAsC == s2.interpretAmbigiousHeadersAsC && s1.skipIndexingBigFiles == s2.skipIndexingBigFiles && s1.useBuiltinPreprocessor == s2.useBuiltinPreprocessor && s1.indexerFileSizeLimitInMb == s2.indexerFileSizeLimitInMb - && s1.categorizeFindReferences == s2.categorizeFindReferences + && s1.m_categorizeFindReferences == s2.m_categorizeFindReferences && s1.ignoreFiles == s2.ignoreFiles && s1.ignorePattern == s2.ignorePattern; } -Store CppCodeModelSettings::Data::toMap() const +Store CppCodeModelSettings::toMap() const { Store store; store.insert(pchUsageKey(), pchUsage); @@ -74,15 +75,15 @@ Store CppCodeModelSettings::Data::toMap() const return store; } -void CppCodeModelSettings::Data::fromMap(const Utils::Store &store) +void CppCodeModelSettings::fromMap(const Utils::Store &store) { - const CppCodeModelSettings::Data def; + const CppCodeModelSettings def; pchUsage = static_cast(store.value(pchUsageKey(), def.pchUsage).toInt()); - interpretAmbigiousHeadersAsC = store - .value(interpretAmbiguousHeadersAsCHeadersKey(), - def.interpretAmbigiousHeadersAsC) - .toBool(); - skipIndexingBigFiles = store.value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles).toBool(); + interpretAmbigiousHeadersAsC + = store.value(interpretAmbiguousHeadersAsCHeadersKey(), def.interpretAmbigiousHeadersAsC) + .toBool(); + skipIndexingBigFiles + = store.value(skipIndexingBigFilesKey(), def.skipIndexingBigFiles).toBool(); ignoreFiles = store.value(ignoreFilesKey(), def.ignoreFiles).toBool(); ignorePattern = store.value(ignorePatternKey(), def.ignorePattern).toString(); useBuiltinPreprocessor @@ -93,12 +94,13 @@ void CppCodeModelSettings::Data::fromMap(const Utils::Store &store) void CppCodeModelSettings::fromSettings(QtcSettings *s) { - m_data.fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); + fromMap(storeFromSettings(Constants::CPPEDITOR_SETTINGSGROUP, s)); } void CppCodeModelSettings::toSettings(QtcSettings *s) { - storeToSettingsWithDefault(Constants::CPPEDITOR_SETTINGSGROUP, s, m_data.toMap(), Data().toMap()); + storeToSettingsWithDefault( + Constants::CPPEDITOR_SETTINGSGROUP, s, toMap(), CppCodeModelSettings().toMap()); } CppCodeModelSettings &CppCodeModelSettings::globalInstance() @@ -109,7 +111,7 @@ CppCodeModelSettings &CppCodeModelSettings::globalInstance() CppCodeModelSettings CppCodeModelSettings::settingsForProject(const ProjectExplorer::Project *project) { - return {CppCodeModelProjectSettings(const_cast(project)).data()}; + return {CppCodeModelProjectSettings(const_cast(project)).settings()}; } CppCodeModelSettings CppCodeModelSettings::settingsForProject(const Utils::FilePath &projectFile) @@ -122,25 +124,25 @@ CppCodeModelSettings CppCodeModelSettings::settingsForFile(const Utils::FilePath return settingsForProject(ProjectManager::projectForFile(file)); } -void CppCodeModelSettings::setGlobalData(const Data &data) +void CppCodeModelSettings::setGlobal(const CppCodeModelSettings &settings) { - if (globalInstance().m_data == data) + if (globalInstance() == settings) return; - globalInstance().m_data = data; + globalInstance() = settings; globalInstance().toSettings(Core::ICore::settings()); - emit globalInstance().changed(nullptr); + CppModelManager::handleSettingsChange(nullptr); } -CppCodeModelSettings::PCHUsage CppCodeModelSettings::pchUsage(const Project *project) +CppCodeModelSettings::PCHUsage CppCodeModelSettings::pchUsageForProject(const Project *project) { - return CppCodeModelSettings::settingsForProject(project).pchUsage(); + return CppCodeModelSettings::settingsForProject(project).pchUsage; } UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders() const { - return pchUsage() == CppCodeModelSettings::PchUse_None ? UsePrecompiledHeaders::No - : UsePrecompiledHeaders::Yes; + return pchUsage == CppCodeModelSettings::PchUse_None ? UsePrecompiledHeaders::No + : UsePrecompiledHeaders::Yes; } UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders(const Project *project) @@ -150,17 +152,17 @@ UsePrecompiledHeaders CppCodeModelSettings::usePrecompiledHeaders(const Project int CppCodeModelSettings::effectiveIndexerFileSizeLimitInMb() const { - return skipIndexingBigFiles() ? indexerFileSizeLimitInMb() : -1; + return skipIndexingBigFiles ? indexerFileSizeLimitInMb : -1; } bool CppCodeModelSettings::categorizeFindReferences() { - return globalInstance().m_data.categorizeFindReferences; + return globalInstance().m_categorizeFindReferences; } void CppCodeModelSettings::setCategorizeFindReferences(bool categorize) { - globalInstance().m_data.categorizeFindReferences = categorize; + globalInstance().m_categorizeFindReferences = categorize; } CppCodeModelProjectSettings::CppCodeModelProjectSettings(ProjectExplorer::Project *project) @@ -169,23 +171,23 @@ CppCodeModelProjectSettings::CppCodeModelProjectSettings(ProjectExplorer::Projec loadSettings(); } -CppCodeModelSettings::Data CppCodeModelProjectSettings::data() const +CppCodeModelSettings CppCodeModelProjectSettings::settings() const { - return m_useGlobalSettings ? CppCodeModelSettings::globalInstance().data() : m_customSettings; + return m_useGlobalSettings ? CppCodeModelSettings::globalInstance() : m_customSettings; } -void CppCodeModelProjectSettings::setData(const CppCodeModelSettings::Data &data) +void CppCodeModelProjectSettings::setSettings(const CppCodeModelSettings &settings) { - m_customSettings = data; + m_customSettings = settings; saveSettings(); - emit CppCodeModelSettings::globalInstance().changed(m_project); + CppModelManager::handleSettingsChange(m_project); } void CppCodeModelProjectSettings::setUseGlobalSettings(bool useGlobal) { m_useGlobalSettings = useGlobal; saveSettings(); - emit CppCodeModelSettings::globalInstance().changed(m_project); + CppModelManager::handleSettingsChange(m_project); } void CppCodeModelProjectSettings::loadSettings() @@ -212,15 +214,14 @@ class CppCodeModelSettingsWidget final : public Core::IOptionsPageWidget { Q_OBJECT public: - CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data); - - CppCodeModelSettings::Data data() const; + CppCodeModelSettingsWidget(const CppCodeModelSettings &settings); + CppCodeModelSettings settings() const; signals: void settingsDataChanged(); private: - void apply() final { CppCodeModelSettings::globalInstance().setGlobalData(data()); } + void apply() final { CppCodeModelSettings::globalInstance().setGlobal(settings()); } QCheckBox *m_interpretAmbiguousHeadersAsCHeaders; QCheckBox *m_ignorePchCheckBox; @@ -231,18 +232,18 @@ private: QPlainTextEdit *m_ignorePatternTextEdit; }; -CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSettings::Data &data) +CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSettings &settings) { m_interpretAmbiguousHeadersAsCHeaders = new QCheckBox(Tr::tr("Interpret ambiguous headers as C headers")); m_skipIndexingBigFilesCheckBox = new QCheckBox(Tr::tr("Do not index files greater than")); - m_skipIndexingBigFilesCheckBox->setChecked(data.skipIndexingBigFiles); + m_skipIndexingBigFilesCheckBox->setChecked(settings.skipIndexingBigFiles); m_bigFilesLimitSpinBox = new QSpinBox; m_bigFilesLimitSpinBox->setSuffix(Tr::tr("MB")); m_bigFilesLimitSpinBox->setRange(1, 500); - m_bigFilesLimitSpinBox->setValue(data.indexerFileSizeLimitInMb); + m_bigFilesLimitSpinBox->setValue(settings.indexerFileSizeLimitInMb); m_ignoreFilesCheckBox = new QCheckBox(Tr::tr("Ignore files")); m_ignoreFilesCheckBox->setToolTip( @@ -250,8 +251,8 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSetting + Tr::tr("Ignore files that match these wildcard patterns, one wildcard per line.") + "

    "); - m_ignoreFilesCheckBox->setChecked(data.ignoreFiles); - m_ignorePatternTextEdit = new QPlainTextEdit(data.ignorePattern); + m_ignoreFilesCheckBox->setChecked(settings.ignoreFiles); + m_ignorePatternTextEdit = new QPlainTextEdit(settings.ignorePattern); m_ignorePatternTextEdit->setToolTip(m_ignoreFilesCheckBox->toolTip()); m_ignorePatternTextEdit->setEnabled(m_ignoreFilesCheckBox->isChecked()); @@ -271,9 +272,9 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSetting (Tr::tr("Uncheck this to invoke the actual compiler " "to show a pre-processed source file in the editor.")); - m_interpretAmbiguousHeadersAsCHeaders->setChecked(data.interpretAmbigiousHeadersAsC); - m_ignorePchCheckBox->setChecked(data.pchUsage == CppCodeModelSettings::PchUse_None); - m_useBuiltinPreprocessorCheckBox->setChecked(data.useBuiltinPreprocessor); + m_interpretAmbiguousHeadersAsCHeaders->setChecked(settings.interpretAmbigiousHeadersAsC); + m_ignorePchCheckBox->setChecked(settings.pchUsage == CppCodeModelSettings::PchUse_None); + m_useBuiltinPreprocessorCheckBox->setChecked(settings.useBuiltinPreprocessor); using namespace Layouting; @@ -309,18 +310,18 @@ CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(const CppCodeModelSetting timer, qOverload<>(&QTimer::start)); } -CppCodeModelSettings::Data CppCodeModelSettingsWidget::data() const +CppCodeModelSettings CppCodeModelSettingsWidget::settings() const { - CppCodeModelSettings::Data data; - data.interpretAmbigiousHeadersAsC = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); - data.skipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); - data.useBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); - data.ignoreFiles = m_ignoreFilesCheckBox->isChecked(); - data.ignorePattern = m_ignorePatternTextEdit->toPlainText(); - data.indexerFileSizeLimitInMb = m_bigFilesLimitSpinBox->value(); - data.pchUsage = m_ignorePchCheckBox->isChecked() ? CppCodeModelSettings::PchUse_None - : CppCodeModelSettings::PchUse_BuildSystem; - return data; + CppCodeModelSettings settings; + settings.interpretAmbigiousHeadersAsC = m_interpretAmbiguousHeadersAsCHeaders->isChecked(); + settings.skipIndexingBigFiles = m_skipIndexingBigFilesCheckBox->isChecked(); + settings.useBuiltinPreprocessor = m_useBuiltinPreprocessorCheckBox->isChecked(); + settings.ignoreFiles = m_ignoreFilesCheckBox->isChecked(); + settings.ignorePattern = m_ignorePatternTextEdit->toPlainText(); + settings.indexerFileSizeLimitInMb = m_bigFilesLimitSpinBox->value(); + settings.pchUsage = m_ignorePchCheckBox->isChecked() ? CppCodeModelSettings::PchUse_None + : CppCodeModelSettings::PchUse_BuildSystem; + return settings; } class CppCodeModelSettingsPage final : public Core::IOptionsPage @@ -334,7 +335,7 @@ public: setDisplayCategory(Tr::tr("C++")); setCategoryIconPath(":/projectexplorer/images/settingscategory_cpp.png"); setWidgetCreator( - [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::globalInstance().data()); }); + [] { return new CppCodeModelSettingsWidget(CppCodeModelSettings::globalInstance()); }); } }; @@ -347,7 +348,7 @@ class CppCodeModelProjectSettingsWidget : public ProjectSettingsWidget { public: CppCodeModelProjectSettingsWidget(const CppCodeModelProjectSettings &settings) - : m_settings(settings), m_widget(settings.data()) + : m_settings(settings), m_widget(settings.settings()) { setGlobalSettingsId(Constants::CPP_CODE_MODEL_SETTINGS_ID); const auto layout = new QVBoxLayout(this); @@ -361,11 +362,11 @@ public: m_widget.setEnabled(!checked); m_settings.setUseGlobalSettings(checked); if (!checked) - m_settings.setData(m_widget.data()); + m_settings.setSettings(m_widget.settings()); }); connect(&m_widget, &CppCodeModelSettingsWidget::settingsDataChanged, - this, [this] { m_settings.setData(m_widget.data()); }); + this, [this] { m_settings.setSettings(m_widget.settings()); }); } private: diff --git a/src/plugins/cppeditor/cppcodemodelsettings.h b/src/plugins/cppeditor/cppcodemodelsettings.h index eedc01402bc..c7d414edce2 100644 --- a/src/plugins/cppeditor/cppcodemodelsettings.h +++ b/src/plugins/cppeditor/cppcodemodelsettings.h @@ -10,7 +10,6 @@ #include #include -#include #include namespace ProjectExplorer { class Project; } @@ -18,75 +17,56 @@ namespace ProjectExplorer { class Project; } namespace CppEditor { enum class UsePrecompiledHeaders; -class CPPEDITOR_EXPORT CppCodeModelSettings : public QObject +class CPPEDITOR_EXPORT CppCodeModelSettings { - Q_OBJECT - public: enum PCHUsage { PchUse_None = 1, PchUse_BuildSystem = 2 }; - class Data + CppCodeModelSettings() = default; + CppCodeModelSettings(const Utils::Store &store) { fromMap(store); } + + friend bool operator==(const CppCodeModelSettings &s1, const CppCodeModelSettings &s2); + friend bool operator!=(const CppCodeModelSettings &s1, const CppCodeModelSettings &s2) { - public: - Data() = default; - Data(const Utils::Store &store) { fromMap(store); } - Utils::Store toMap() const; - void fromMap(const Utils::Store &store); + return !(s1 == s2); + } - friend bool operator==(const Data &s1, const Data &s2); - friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } - - PCHUsage pchUsage = PchUse_BuildSystem; - bool interpretAmbigiousHeadersAsC = false; - bool skipIndexingBigFiles = true; - bool useBuiltinPreprocessor = true; - int indexerFileSizeLimitInMb = 5; - bool categorizeFindReferences = false; // Ephemeral! - bool ignoreFiles = false; - QString ignorePattern; - }; - - CppCodeModelSettings(const Data &data) : m_data(data) {} + Utils::Store toMap() const; + void fromMap(const Utils::Store &store); static CppCodeModelSettings &globalInstance(); // TODO: Make inaccessible. static CppCodeModelSettings settingsForProject(const ProjectExplorer::Project *project); static CppCodeModelSettings settingsForProject(const Utils::FilePath &projectFile); static CppCodeModelSettings settingsForFile(const Utils::FilePath &file); - static void setGlobalData(const Data &data); // TODO: Make inaccessible. - void setData(const Data &data) { m_data = data; } - Data data() const { return m_data; } + static void setGlobal(const CppCodeModelSettings &settings); // TODO: Make inaccessible. - PCHUsage pchUsage() const { return m_data.pchUsage; } - static PCHUsage pchUsage(const ProjectExplorer::Project *project); + static PCHUsage pchUsageForProject(const ProjectExplorer::Project *project); UsePrecompiledHeaders usePrecompiledHeaders() const; static UsePrecompiledHeaders usePrecompiledHeaders(const ProjectExplorer::Project *project); - bool interpretAmbigiousHeadersAsC() const { return m_data.interpretAmbigiousHeadersAsC; } - bool skipIndexingBigFiles() const { return m_data.skipIndexingBigFiles; } - bool useBuiltinPreprocessor() const { return m_data.useBuiltinPreprocessor; } - int indexerFileSizeLimitInMb() const { return m_data.indexerFileSizeLimitInMb; } int effectiveIndexerFileSizeLimitInMb() const; - bool ignoreFiles() const { return m_data.ignoreFiles; } - QString ignorePattern() const { return m_data.ignorePattern; } static bool categorizeFindReferences(); static void setCategorizeFindReferences(bool categorize); -signals: - void changed(ProjectExplorer::Project *project); + QString ignorePattern; + PCHUsage pchUsage = PchUse_BuildSystem; + int indexerFileSizeLimitInMb = 5; + bool interpretAmbigiousHeadersAsC = false; + bool skipIndexingBigFiles = true; + bool useBuiltinPreprocessor = true; + bool ignoreFiles = false; + bool m_categorizeFindReferences = false; // Ephemeral! private: - CppCodeModelSettings() = default; CppCodeModelSettings(Utils::QtcSettings *s) { fromSettings(s); } void toSettings(Utils::QtcSettings *s); void fromSettings(Utils::QtcSettings *s); - - Data m_data; }; class CppCodeModelProjectSettings @@ -94,8 +74,8 @@ class CppCodeModelProjectSettings public: CppCodeModelProjectSettings(ProjectExplorer::Project *project); - CppCodeModelSettings::Data data() const; - void setData(const CppCodeModelSettings::Data &data); + CppCodeModelSettings settings() const; + void setSettings(const CppCodeModelSettings &settings); bool useGlobalSettings() const { return m_useGlobalSettings; } void setUseGlobalSettings(bool useGlobal); @@ -104,7 +84,7 @@ private: void saveSettings(); ProjectExplorer::Project * const m_project; - CppCodeModelSettings::Data m_customSettings; + CppCodeModelSettings m_customSettings; bool m_useGlobalSettings = true; }; diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 96a476c5234..6718d4cbc85 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -204,7 +204,7 @@ void CppEditorPlugin::initialize() setupCppQuickFixSettings(); setupCppCodeModelSettingsPage(); provideCppSettingsRetriever([](const Project *p) { - return CppCodeModelSettings::settingsForProject(p).data().toMap(); + return CppCodeModelSettings::settingsForProject(p).toMap(); }); setupCppOutline(); setupCppCodeStyleSettings(); diff --git a/src/plugins/cppeditor/cppmodelmanager.cpp b/src/plugins/cppeditor/cppmodelmanager.cpp index d5d6842e00f..4a2d4778b9a 100644 --- a/src/plugins/cppeditor/cppmodelmanager.cpp +++ b/src/plugins/cppeditor/cppmodelmanager.cpp @@ -407,7 +407,7 @@ void CppModelManager::showPreprocessedFile(bool inNextSplit) saveAndOpen(outFilePath, content.append(preprocessedDoc->utf8Source()), inNextSplit); }; - if (CppCodeModelSettings::settingsForFile(filePath).useBuiltinPreprocessor()) { + if (CppCodeModelSettings::settingsForFile(filePath).useBuiltinPreprocessor) { useBuiltinPreprocessor(); return; } @@ -1023,9 +1023,6 @@ CppModelManager::CppModelManager() connect(ICore::instance(), &ICore::coreAboutToClose, this, &CppModelManager::onCoreAboutToClose); - connect(&CppCodeModelSettings::globalInstance(), &CppCodeModelSettings::changed, - this, &CppModelManager::onSettingsChange); - d->m_fallbackProjectPartTimer.setSingleShot(true); d->m_fallbackProjectPartTimer.setInterval(5000); connect(&d->m_fallbackProjectPartTimer, &QTimer::timeout, @@ -1360,8 +1357,8 @@ QFuture CppModelManager::updateSourceFiles(const QSet &sourceFil const CppCodeModelSettings settings = CppCodeModelSettings::settingsForProject(it.key()); filteredFiles.unite(filteredFilesRemoved(it.value(), settings.effectiveIndexerFileSizeLimitInMb(), - settings.ignoreFiles(), - settings.ignorePattern())); + settings.ignoreFiles, + settings.ignorePattern)); } return d->m_internalIndexingSupport->refreshSourceFiles(filteredFiles, mode); @@ -2013,7 +2010,7 @@ void CppModelManager::onCoreAboutToClose() d->m_enableGC = false; } -void CppModelManager::onSettingsChange(Project *project) +void CppModelManager::handleSettingsChange(Project *project) { ProjectInfoList info; if (project) @@ -2023,7 +2020,7 @@ void CppModelManager::onSettingsChange(Project *project) for (const ProjectInfo::ConstPtr &pi : std::as_const(info)) { const CppCodeModelSettings newSettings = CppCodeModelSettings::settingsForProject( pi->projectFilePath()); - if (pi->settings().data() != newSettings.data()) + if (pi->settings() != newSettings) updateProjectInfo(ProjectInfo::cloneWithNewSettings(pi, newSettings)); } } diff --git a/src/plugins/cppeditor/cppmodelmanager.h b/src/plugins/cppeditor/cppmodelmanager.h index d1a558ce9c9..c22a8a9da0b 100644 --- a/src/plugins/cppeditor/cppmodelmanager.h +++ b/src/plugins/cppeditor/cppmodelmanager.h @@ -110,6 +110,8 @@ public: static QFuture updateProjectInfo(const ProjectInfo::ConstPtr &newProjectInfo, const QSet &additionalFiles = {}); + static void handleSettingsChange(ProjectExplorer::Project *project); + /// \return The project part with the given project file static ProjectPart::ConstPtr projectPartForId(const QString &projectPartId); /// \return All project parts that mention the given file name as one of the sources/headers. @@ -288,7 +290,6 @@ private: static void onSourceFilesRefreshed(); static void onCurrentEditorChanged(Core::IEditor *editor); static void onCoreAboutToClose(); - static void onSettingsChange(ProjectExplorer::Project *project); static void setupFallbackProjectPart(); static void delayedGC(); diff --git a/src/plugins/cppeditor/cppmodelmanager_test.cpp b/src/plugins/cppeditor/cppmodelmanager_test.cpp index 4ac39de737a..dd0f07d80b2 100644 --- a/src/plugins/cppeditor/cppmodelmanager_test.cpp +++ b/src/plugins/cppeditor/cppmodelmanager_test.cpp @@ -1283,10 +1283,9 @@ void ModelManagerTest::testSettingsChanges() // Change global settings. Only the second project should get re-indexed, as the first one // has its own settings, which are still the same. - CppCodeModelSettings::Data globalSettings - = CppCodeModelSettings::settingsForProject(nullptr).data(); + CppCodeModelSettings globalSettings = CppCodeModelSettings::settingsForProject(nullptr); globalSettings.indexerFileSizeLimitInMb = 1; - CppCodeModelSettings::setGlobalData(globalSettings); + CppCodeModelSettings::setGlobal(globalSettings); if (refreshCount == 0) QVERIFY(waitForRefresh()); QVERIFY(!waitForRefresh()); @@ -1295,10 +1294,10 @@ void ModelManagerTest::testSettingsChanges() // Change first project's settings. Only this project should get re-indexed. refreshCount = 0; refreshedFiles.clear(); - CppCodeModelSettings::Data p1Data = p1Settings.data(); + CppCodeModelSettings p1Data = p1Settings.settings(); p1Data.ignoreFiles = true; p1Data.ignorePattern = "baz3.h"; - p1Settings.setData(p1Data); + p1Settings.setSettings(p1Data); if (refreshCount == 0) QVERIFY(waitForRefresh()); QVERIFY(!waitForRefresh()); diff --git a/src/plugins/cppeditor/projectinfo.cpp b/src/plugins/cppeditor/projectinfo.cpp index 8a393df6d35..9561310f323 100644 --- a/src/plugins/cppeditor/projectinfo.cpp +++ b/src/plugins/cppeditor/projectinfo.cpp @@ -33,7 +33,7 @@ bool ProjectInfo::operator ==(const ProjectInfo &other) const && m_projectParts == other.m_projectParts && m_headerPaths == other.m_headerPaths && m_sourceFiles == other.m_sourceFiles - && m_settings.data() == other.m_settings.data() + && m_settings == other.m_settings && m_defines == other.m_defines; } @@ -50,7 +50,7 @@ bool ProjectInfo::definesChanged(const ProjectInfo &other) const bool ProjectInfo::configurationChanged(const ProjectInfo &other) const { return definesChanged(other) || m_headerPaths != other.m_headerPaths - || m_settings.data() != other.settings().data(); + || m_settings != other.settings(); } bool ProjectInfo::configurationOrFilesChanged(const ProjectInfo &other) const @@ -98,7 +98,7 @@ ProjectInfo::ProjectInfo(const ProjectExplorer::ProjectUpdateInfo &updateInfo, m_headerPaths(getHeaderPaths(projectParts)), m_sourceFiles(getSourceFiles(projectParts)), m_defines(getDefines(projectParts)), - m_settings(CppCodeModelSettings::Data(updateInfo.cppSettings)) + m_settings(updateInfo.cppSettings) { } @@ -110,7 +110,7 @@ ProjectInfo::ProjectInfo(const ConstPtr &pi, const CppCodeModelSettings &setting m_headerPaths(pi->m_headerPaths), m_sourceFiles(pi->sourceFiles()), m_defines(pi->m_defines), - m_settings(settings.data()) + m_settings(settings) { } From 3b80da7117183235447ac2804c4e9c934fad89fa Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Wed, 13 Mar 2024 15:38:44 +0100 Subject: [PATCH 0156/1060] ClangCodeModel: Make "live update" of dependent sources opt-in Not everyone wants to invest the extra computing resources needed for this feature. Amends b33b99e2d9e4c343f7427bcf1ccdf652e7575557. See 6d805195f6d35df932d666f86af026c051c785f8 for the original motivation. Task-number: QTCREATORBUG-29943 Change-Id: I4c8cce5bb58b34d930a409ea3e0995377c90d4ab Reviewed-by: David Schulz Reviewed-by: --- .../clangeditordocumentprocessor.cpp | 9 ++++++- .../clangcodemodel/test/clangdtests.cpp | 16 ++++++++++++ src/plugins/cppeditor/clangdsettings.cpp | 26 ++++++++++++++++--- src/plugins/cppeditor/clangdsettings.h | 5 +++- 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp b/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp index 83667dde05e..71ed49549df 100644 --- a/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp +++ b/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp @@ -18,6 +18,8 @@ #include +#include + #include #include #include @@ -84,7 +86,12 @@ void ClangEditorDocumentProcessor::forceUpdate(TextEditor::TextDocument *doc) { if (const auto client = qobject_cast( LanguageClient::LanguageClientManager::clientForDocument(doc))) { - client->documentContentsChanged(doc, 0, 0, 0); + const CppEditor::ClangdSettings settings( + CppEditor::ClangdProjectSettings( + ProjectExplorer::ProjectManager::projectForFile(doc->filePath())) + .settings()); + if (settings.updateDependentSources()) + client->documentContentsChanged(doc, 0, 0, 0); } } diff --git a/src/plugins/clangcodemodel/test/clangdtests.cpp b/src/plugins/clangcodemodel/test/clangdtests.cpp index ae92afb45ff..f18c1641559 100644 --- a/src/plugins/clangcodemodel/test/clangdtests.cpp +++ b/src/plugins/clangcodemodel/test/clangdtests.cpp @@ -2240,6 +2240,8 @@ public: ClangdTestIndirectChanges(); private slots: + void initTestCase() override; + void cleanupTestCase(); void test(); }; @@ -2249,6 +2251,20 @@ ClangdTestIndirectChanges::ClangdTestIndirectChanges() setSourceFileNames({"main.cpp", "directheader.h", "indirectheader.h", "unrelatedheader.h"}); } +void ClangdTestIndirectChanges::initTestCase() +{ + CppEditor::ClangdSettings &settings = CppEditor::ClangdSettings::instance(); + CppEditor::ClangdSettings::Data settingsData = settings.data(); + settingsData.updateDependentSources = true; + settings.setData(settingsData, false); + ClangdTest::initTestCase(); +} + +void ClangdTestIndirectChanges::cleanupTestCase() +{ + CppEditor::ClangdSettings::instance().setData({}, false); +} + void ClangdTestIndirectChanges::test() { // Initially, everything is fine. diff --git a/src/plugins/cppeditor/clangdsettings.cpp b/src/plugins/cppeditor/clangdsettings.cpp index 253914704a0..fe3bc84b23b 100644 --- a/src/plugins/cppeditor/clangdsettings.cpp +++ b/src/plugins/cppeditor/clangdsettings.cpp @@ -73,6 +73,7 @@ static Key sessionsWithOneClangdKey() { return "SessionsWithOneClangd"; } static Key diagnosticConfigIdKey() { return "diagnosticConfigId"; } static Key checkedHardwareKey() { return "checkedHardware"; } static Key completionResultsKey() { return "completionResults"; } +static Key updateDependentSourcesKey() { return "updateDependentSources"; } QString ClangdSettings::priorityToString(const IndexingPriority &priority) { @@ -245,12 +246,14 @@ ClangdSettings::Granularity ClangdSettings::granularity() const return Granularity::Project; } -void ClangdSettings::setData(const Data &data) +void ClangdSettings::setData(const Data &data, bool saveAndEmitSignal) { if (this == &instance() && data != m_data) { m_data = data; - saveSettings(); - emit changed(); + if (saveAndEmitSignal) { + saveSettings(); + emit changed(); + } } } @@ -470,6 +473,7 @@ Store ClangdSettings::Data::toMap() const map.insert(diagnosticConfigIdKey(), diagnosticConfigId.toSetting()); map.insert(checkedHardwareKey(), haveCheckedHardwareReqirements); map.insert(completionResultsKey(), completionResults); + map.insert(updateDependentSourcesKey(), updateDependentSources); return map; } @@ -499,6 +503,7 @@ void ClangdSettings::Data::fromMap(const Store &map) diagnosticConfigId = Id::fromSetting(map.value(diagnosticConfigIdKey(), initialClangDiagnosticConfigId().toSetting())); haveCheckedHardwareReqirements = map.value(checkedHardwareKey(), false).toBool(); + updateDependentSources = map.value(updateDependentSourcesKey(), false).toBool(); completionResults = map.value(completionResultsKey(), defaultCompletionResults()).toInt(); } @@ -531,6 +536,7 @@ private: QComboBox m_headerSourceSwitchComboBox; QComboBox m_completionRankingModelComboBox; QCheckBox m_autoIncludeHeadersCheckBox; + QCheckBox m_updateDependentSourcesCheckBox; QCheckBox m_sizeThresholdCheckBox; QSpinBox m_threadLimitSpinBox; QSpinBox m_documentUpdateThreshold; @@ -584,6 +590,13 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD "worker threads."); const QString autoIncludeToolTip = Tr::tr( "Controls whether clangd may insert header files as part of symbol completion."); + const QString updateDependentSourcesToolTip = Tr::tr( + "

    Controls whether when editing a header file, clangd should re-parse all source files " + "including that header.

    " + "

    Note that enabling this option can cause considerable CPU load when editing widely " + "included headers.

    " + "

    If this option is disabled, the dependent source files are only re-parsed when the " + "header file is saved.

    "); const QString documentUpdateToolTip //: %1 is the application name (Qt Creator) = Tr::tr("Defines the amount of time %1 waits before sending document changes to the " @@ -634,6 +647,9 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD m_autoIncludeHeadersCheckBox.setText(Tr::tr("Insert header files on completion")); m_autoIncludeHeadersCheckBox.setChecked(settings.autoIncludeHeaders()); m_autoIncludeHeadersCheckBox.setToolTip(autoIncludeToolTip); + m_updateDependentSourcesCheckBox.setText(Tr::tr("Update dependent sources")); + m_updateDependentSourcesCheckBox.setChecked(settings.updateDependentSources()); + m_updateDependentSourcesCheckBox.setToolTip(updateDependentSourcesToolTip); m_threadLimitSpinBox.setValue(settings.workerThreadLimit()); m_threadLimitSpinBox.setSpecialValueText(Tr::tr("Automatic")); m_threadLimitSpinBox.setToolTip(workerThreadsToolTip); @@ -718,6 +734,7 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD formLayout->addRow(threadLimitLabel, threadLimitLayout); formLayout->addRow(QString(), &m_autoIncludeHeadersCheckBox); + formLayout->addRow(QString(), &m_updateDependentSourcesCheckBox); const auto limitResultsLayout = new QHBoxLayout; limitResultsLayout->addWidget(&m_completionResults); limitResultsLayout->addStretch(1); @@ -883,6 +900,8 @@ ClangdSettingsWidget::ClangdSettingsWidget(const ClangdSettings::Data &settingsD this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_autoIncludeHeadersCheckBox, &QCheckBox::toggled, this, &ClangdSettingsWidget::settingsDataChanged); + connect(&m_updateDependentSourcesCheckBox, &QCheckBox::toggled, + this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_threadLimitSpinBox, &QSpinBox::valueChanged, this, &ClangdSettingsWidget::settingsDataChanged); connect(&m_sizeThresholdCheckBox, &QCheckBox::toggled, @@ -913,6 +932,7 @@ ClangdSettings::Data ClangdSettingsWidget::settingsData() const data.completionRankingModel = ClangdSettings::CompletionRankingModel( m_completionRankingModelComboBox.currentData().toInt()); data.autoIncludeHeaders = m_autoIncludeHeadersCheckBox.isChecked(); + data.updateDependentSources = m_updateDependentSourcesCheckBox.isChecked(); data.workerThreadLimit = m_threadLimitSpinBox.value(); data.documentUpdateThreshold = m_documentUpdateThreshold.value(); data.sizeThresholdEnabled = m_sizeThresholdCheckBox.isChecked(); diff --git a/src/plugins/cppeditor/clangdsettings.h b/src/plugins/cppeditor/clangdsettings.h index f3e66fb9f6b..e4fb22f5527 100644 --- a/src/plugins/cppeditor/clangdsettings.h +++ b/src/plugins/cppeditor/clangdsettings.h @@ -55,6 +55,7 @@ public: && s1.sizeThresholdEnabled == s2.sizeThresholdEnabled && s1.sizeThresholdInKb == s2.sizeThresholdInKb && s1.haveCheckedHardwareReqirements == s2.haveCheckedHardwareReqirements + && s1.updateDependentSources == s2.updateDependentSources && s1.completionResults == s2.completionResults; } friend bool operator!=(const Data &s1, const Data &s2) { return !(s1 == s2); } @@ -76,6 +77,7 @@ public: bool autoIncludeHeaders = false; bool sizeThresholdEnabled = false; bool haveCheckedHardwareReqirements = false; + bool updateDependentSources = false; int completionResults = defaultCompletionResults(); private: @@ -101,6 +103,7 @@ public: HeaderSourceSwitchMode headerSourceSwitchMode() const { return m_data.headerSourceSwitchMode; } CompletionRankingModel completionRankingModel() const { return m_data.completionRankingModel; } bool autoIncludeHeaders() const { return m_data.autoIncludeHeaders; } + bool updateDependentSources() const { return m_data.updateDependentSources; } int workerThreadLimit() const { return m_data.workerThreadLimit; } int documentUpdateThreshold() const { return m_data.documentUpdateThreshold; } qint64 sizeThresholdInKb() const { return m_data.sizeThresholdInKb; } @@ -114,7 +117,7 @@ public: enum class Granularity { Project, Session }; Granularity granularity() const; - void setData(const Data &data); + void setData(const Data &data, bool saveAndEmitSignal = true); Data data() const { return m_data; } Utils::FilePath clangdIncludePath() const; From 20e332b1351677e4314491d0f18a7f0475496f03 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Mon, 15 Apr 2024 12:37:16 +0200 Subject: [PATCH 0157/1060] TaskTree: Introduce parallelIdealThreadCountLimit Reuse the new element. Fixes: QTCREATORBUG-30647 Change-Id: I79836a9243abcb1661c79842dcf6c33492342552 Reviewed-by: hjk --- src/libs/solutions/tasking/tasktree.cpp | 15 +++++++++++++++ src/libs/solutions/tasking/tasktree.h | 1 + src/plugins/remotelinux/linuxdevice.cpp | 2 +- tests/manual/tasking/dataexchange/recipe.cpp | 2 +- 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/libs/solutions/tasking/tasktree.cpp b/src/libs/solutions/tasking/tasktree.cpp index 7d37bf97587..8b8d1176c04 100644 --- a/src/libs/solutions/tasking/tasktree.cpp +++ b/src/libs/solutions/tasking/tasktree.cpp @@ -881,6 +881,20 @@ private: \sa sequential, parallelLimit() */ +/*! + \variable parallelIdealThreadCountLimit + A convenient global group's element describing the parallel execution mode with a limited + number of tasks running simultanously. The limit is equal to the ideal number of threads + excluding the calling thread. + + This is a shortcut to: + \code + parallelLimit(qMax(QThread::idealThreadCount() - 1, 1)) + \endcode + + \sa parallel, parallelLimit() +*/ + /*! \variable stopOnError A convenient global group's element describing the StopOnError workflow policy. @@ -1161,6 +1175,7 @@ const GroupItem nullItem = GroupItem({}); const GroupItem sequential = parallelLimit(1); const GroupItem parallel = parallelLimit(0); +const GroupItem parallelIdealThreadCountLimit = parallelLimit(qMax(QThread::idealThreadCount() - 1, 1)); const GroupItem stopOnError = workflowPolicy(WorkflowPolicy::StopOnError); const GroupItem continueOnError = workflowPolicy(WorkflowPolicy::ContinueOnError); diff --git a/src/libs/solutions/tasking/tasktree.h b/src/libs/solutions/tasking/tasktree.h index ef41fa4b2b6..29ec5548159 100644 --- a/src/libs/solutions/tasking/tasktree.h +++ b/src/libs/solutions/tasking/tasktree.h @@ -375,6 +375,7 @@ TASKING_EXPORT extern const GroupItem nullItem; TASKING_EXPORT extern const GroupItem sequential; TASKING_EXPORT extern const GroupItem parallel; +TASKING_EXPORT extern const GroupItem parallelIdealThreadCountLimit; TASKING_EXPORT extern const GroupItem stopOnError; TASKING_EXPORT extern const GroupItem continueOnError; diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp index 5dd5f905599..8d3b46eb1be 100644 --- a/src/plugins/remotelinux/linuxdevice.cpp +++ b/src/plugins/remotelinux/linuxdevice.cpp @@ -1663,7 +1663,7 @@ private: const Group group{ Group{ - parallelLimit(QThread::idealThreadCount() - 1), + parallelIdealThreadCountLimit, iteratorParentDirs, AsyncTask>(onCreateDirSetup, onCreateDirDone), }, diff --git a/tests/manual/tasking/dataexchange/recipe.cpp b/tests/manual/tasking/dataexchange/recipe.cpp index 445f246bbad..cb472eafd42 100644 --- a/tests/manual/tasking/dataexchange/recipe.cpp +++ b/tests/manual/tasking/dataexchange/recipe.cpp @@ -76,7 +76,7 @@ Group recipe(const Storage &externalStorage) ConcurrentCallTask(onReadSetup, onReadDone), Group { repeater, - parallelLimit(QThread::idealThreadCount() - 1), + parallelIdealThreadCountLimit, ConcurrentCallTask(onScaleSetup, onScaleDone) } }; From afc88165890cd34b38b7432eea5344dbd6ee125b Mon Sep 17 00:00:00 2001 From: Leena Miettinen Date: Mon, 15 Apr 2024 12:13:01 +0200 Subject: [PATCH 0158/1060] Doc: Restructure the "Analyzing Code" section - Turn the topics into how-to and reference topics. - Rewrite "Analyzing Code" as an overview topic. Task-number: QTCREATORBUG-29361 Change-Id: Id02253514cd1dcd808f040ced7f9f73f6db5e113 Reviewed-by: hjk --- .../images/qtcreator-heob-in-terminal.webp | Bin 0 -> 5216 bytes doc/qtcreator/images/qtcreator-heob.png | Bin 24282 -> 0 bytes .../src/analyze/cpu-usage-analyzer.qdoc | 274 +++++++++--------- .../src/analyze/creator-analyze.qdoc | 179 ++++++++---- .../src/analyze/creator-axivion.qdoc | 19 +- .../creator-clang-static-analyzer.qdoc | 19 +- doc/qtcreator/src/analyze/creator-coco.qdoc | 61 ++-- .../src/analyze/creator-cppcheck.qdoc | 62 ++-- .../src/analyze/creator-ctf-visualizer.qdoc | 11 +- doc/qtcreator/src/analyze/creator-heob.qdoc | 82 +++--- .../src/analyze/creator-valgrind.qdoc | 6 +- .../creator-how-to-profile-cmake-code.qdoc | 2 +- .../src/editors/creator-code-syntax.qdoc | 14 +- .../creator-only/creator-overview.qdoc | 10 +- .../creator-build-settings-qmake.qdoc | 2 +- .../creator-projects-settings-build-qbs.qdoc | 2 +- doc/qtcreator/src/qtcreator-toc.qdoc | 10 +- .../src/qtquick/qtquick-profiler.qdoc | 9 +- 18 files changed, 404 insertions(+), 358 deletions(-) create mode 100644 doc/qtcreator/images/qtcreator-heob-in-terminal.webp delete mode 100644 doc/qtcreator/images/qtcreator-heob.png diff --git a/doc/qtcreator/images/qtcreator-heob-in-terminal.webp b/doc/qtcreator/images/qtcreator-heob-in-terminal.webp new file mode 100644 index 0000000000000000000000000000000000000000..f36ac7014424b2ab54a2da97dcfca4c93724b864 GIT binary patch literal 5216 zcmWIYbaRUkVPFV%bqWXzu<-E~VPMc-?`+O+oNec}wW(+S6{a6a^0;HWQjs@h>4`7R zKKoOiz5Dd=0@Iya+d@OR%ggsmt`oGpdWo^uVb%TEdAA$0Z*O~*qPD~O$Yi0_EAH%T zTAy}d>9M<=r)@v4H_K&aTkp4%`J3t&)jz+T>+co=&FAN>_CH$fKWPM<4nE(!DS!Xz z*8JVt|7{c*@>n?T9O$hxwJ6F=+q2Y3^Kz^BO8$t7#`bg$rU}iS5lyTUHRYvN7%vq% z<#2YkkLC}{iF>Yk_zV4Vxahz3RjO7H|DW80+_4iDd*7eYntLPBsmf5PPgt1iaO4Tc zdF^xb=U(A^;&OqtQghu>2K^xZ^L|@BcLcsMH#xjJ#=*CN^=K25Dffdz)t1ZW%%76x zG`G?;EuqD}hPPAau#KI*)zyv8Q-t7puBDGJ%g_H8zOilcZFM(op4nj%g;9w&wjAoX z$i&#P`No`}DmS517I%7Ho92C8%`4vWZld;QuDm^S&2Pr9lF_qhcf9R3De2#a@B5Vn z1cfiK-@Q{{dC9|mDr0%v<^A8zPtbmPYunkaxzUzZle3j4-<_LnZJ8Zye{%=d^|Es_ z|JX)<{ad$s*W{Nc!`|+-{hRChC0P?Z{(=eKAXtA@<5W5C&#nx^X$)spG=6nwL<>=jbjH6 zU6HMu&+GZ`f>Z2)&KFmU{@a^q>Gn_4oz7*|m)rV6>&UOzR-x>^n`R5;Hv}%UKJ!o4 zG5eB}rR3RXT>Z}$_Q>WrzWJRtZ&Te7SzsQl#50cq8O=jxe%qnVy1rB%5(CB3%Q zY7pVEn&Z%*B=tnH7GATrQG|;DazEzgYle$ z{{apW&t{uuzS)mNdz*R+YF+bumo3nr-GA!oG;i7ZQ`V6|t{0q}4Q?uibWWYSLp-*2 zapZz2a{Z?w|1qxmd3yinPb&=tJjE{#5PCw#5?Y*7j zRr@+O`<91B_vhP1|0>YtG}m@Mc;{f{?=%q$1@?*UPkS!q4#PWZ%4cY9BJudVr(ut4l``f+FJpMNTj>^QV@t(NgS zfl|G*`}g>iuFlV2tDsr0f3z`n>79i|j%LS;w)c5i+C@xsta>rm?)V*t7g=^er{1pf zKK+rcC2xuO8s$F;s#m6k{7PbfZF{}F&|r7Z>+YCi`z00mbJyooHFXx8`_8@Y-E6@% z{>K<+M_Nt!ut=i(`QvX|6Vj)<$}KYf@JybU-I{&#>9mP^dh6w$n)S9@v(J0|^l;pl zZIOyGH`8Q}Oe>fzD)Rln^ULRaKj}&4I@{>)hz?SZvyXRppb&HOze4fCEgi?W=3u)y&}*15N5mhoSCcSQQc zn!B1M-g`4GKRNH$aJ6({XX|v z(#FJNh2REz{kjcvDql8s89d_Q7If$raGsER!efJ;VrlMPi;M@n2F4fse?1h~x_{Z< zRWG!6?vv?1k`?A4V)ID9;-`bz=6qwlCqA0LpS<%umMEn=$&-~SZo;X#)o=My=hqu= z`oOitLQ`zdf_#?!u`{mM{JOVqe*PPF>*?~&Q+7-3t+~>2MDO_wnJXq}VU}INn?5r#}ctT$A+juw|N^%J=#W!pT?a-IHUb7#@lwT`%vr6~FtB zYsCJB=byqYr>x&E!=LSX;-%tj)5i-EHq0+yw7gXAWOvdXp#!Tq4izPeRPbJU9F+PX zNvdP-zTnSJDbJKH&f3XqRHz#xV1By#R9fwWQr>Ovr`=3aiir^pzOOJpa*FYu_cn9? zIX5nSxHS*HIILxNMe8(P3BLBGF;4&Z^7OyM2br=Ucsh7wh;;5kI=4 zdm(@Ow3vG`$2(6&Pj0?*{LS$L^4kh0estTp%Hm0^#P&1RbvLeDvRc`taA@g?E9NJb zdn}22-~D0V=aM#uAl5l+m-n&XRG6lqoAKT*!tr&`<{f$IYP}ju_C1>;Jmuf4x*G>~ z%t^R^aBC3zbEmUW-(I>-y!B1{}*~jtP z`hB{AN}%A?X9r{-A1$?9mU3bD&X}GHOARm0dF)*MP4L9)PlvNP7Rbl==QzB~Z+Oyr zsk3Iz#3YV}w7DgU5puDg_VYRTzRlaS!K>ow*PEV7cPe`}w|{R5VvA9UJJ$V|=Z>O~ zw9sLXtDkPEZswRC>KHSl|GXa> zU0EjN!8AYO+?T)4;{`UY{5nn1%v6sfDfn?-u4YT-B%~xM3ZTBeM&7*d`PD@~^8G5KCu-htdjoDJ4iq4LIFCTawUHJdN_GurQ`1M-M4UcrY9o#kL&xSqP zs}k!&zPlb+8|H0ks++uGfGAO4+cvHW|)!(!ftuJU)bW&fyI^P79J zRl>iiej=tEl`Af|foY?IAZ0=F3laJ;)9a%5-Cna!CU027> z$jyEUA)7m8-8V<=`>%0ko@1flD)z0lDQ4PLQWs~uUv+}{tMAbt26Zv_r&MG=+~4)* z#b#?ctJd&-=YmCDDHp6X>NX0@fArY<+ViL@oiC3(%fH9ISy*QV^Oh+`b~bT2 zBD6j+h~4nrmuA)XZM!_Dg?&4&_4y?4Z?@-~gP$A@Ua;>?Uf80aFIWDX8Wya6Ci=~! zOViirU3#~U>Hozyv)y`6YkXO|bmqszrWx;7y_?&uTsbN>&0a_G-1qhpRo zUmy6BwA9D0xrk|n>s*QBv+d*RomISZt|zPsDlvS+p?^0>JLXue#f{ zzoDdT`=y$qvsT>Cx=VR(_HnHU=KQ)?H&DqsMfRpjPz+bF*3J4UITzLx2L2D}Uo%st z?7qn&^~5_dP=;!DEG z-L8*JcANcG^a{NDEPxq_MN#GcI&>N8n({cQMkbrDa$zV3tV7gx9K zobgWmQH_gO>j#ll$Lgmnu`yUTMd;&N*Z+qr4yaA7YuUHDMZPAOwOi@S;n2rx@70Sw z{;Kpm=yR=_E#HGLpLT}5R#0(U*5Uv8xcHvFrv*Tm=4FX2%8Bz!-lqyL9vv-~=_ z{ICC3AMno!W_@q|-nh<|@4=Mc7Sq323G9!MpMUna_&w*>E^aC-Cm*}2+MH0`{Z-|w z!~LiSs&+dHZeA16_j+q?n_&CCZP(AbWq;qsRu(y{@cxVKF%PJyytJvabNQ6^@Y6ln zKmXkMl_o29{L_)>y1yxN^HTCZP5R$>_}_;$Hg&5#esu-9{yW{5{q%?BI+6QlR99T? z(){UTegD1P#+IM^Pfolew%WR=b$LzSE0GiN)9dYZ{{4OSYMN*__ou(l>;IQ-Ucb5a z|Ih#WbCXYI+QmHes*B2hKY!K9w#wY)5C43&UcBsRT4{U)$DJGew%hAhsZDNr>A&Xt zH~*^%K?Z+2zn=TIQYwIJsr^PT8{PZMe=Z65CH#8n-(b`EC4c`NdG#pqrycJLkLmCI z*ZfO4fBO4Lw&IN-{lA{Z{Niup7hihjXe-?Q`&h1R^W3AZqTg@j zX3O1kuOjLpHqEk~Z8oFdiI)Y38AwQ%Q-xkoMRreE0pWns~@&oj@LiHY+U z$mmMGmpf9l|NJ9~+s>SNFMhrr{9;bs^fTl*wFbH z$R-v+_th#)T!nYmSg;9P__)(T%447CyVXgLZ=QRUbT~@3;7*S3+PXmh7n-V)X7k?a z=qVkr0Ez1Kon~bhHnI~}o_;faV&dYP=N>6-mgrmT`c{3}ij_-mNB6W`5&pQ7V}ZMt z0Z5zL`C9AC9A#1$%f!m%8RV5xU2aF-sZGdzm(VJin_l=)qo*?FLgpLB{&N1X10NLD zwSSdYerqk*FZgl#mB;2k9`NNK=u-TAud({{O}2>hfyPO4M|~%KR27U2f1dfrmgBae z!yO$?N%z%tY#${A{Uwj88s$CP%94NJQeg1x48{A0KTdbqqtdtdNa2iaIZq0vvPrS6 zy1w{_w^p3c@xVpzEpK!&zR%vt5HYV~zse)kLK)Sr!&_2XO}?g_b(F3DdGxZ2jB4NV zEyX(P4*ygS72Ov4ae9KUMc<^3!&~C!vtHC?>=D)i^S z$G`jE+b?G;+V|dm-~S)~KG(0=^>+X9(zVIff7ML)^oLgo2cO;bEbI5v=O3&Oel-7T z?Qm=9zT?a5Ui`DNNzsnpUw8J*y0S?szpI_U{ycVb|5c%zpWT@IfBhH!pSEPrKBXCv ze{0PH|K`Z@+b%!!^kBk$?=Quo-~Wrud%tzZv$ZD=YF|H|SaezX;BE64&3{X#UY`D^ z?CzBKdFvHoHFo$v{JTEs&J(*;XQWm4>{FQ$`TBRB(yfgh-yeGI{P8#TVDj1JhL8Vg zu3Fgk{PB;u)7R}*6AZpr87O?~e11J!Snq#%FAFKZU(Kfbb>bPViusnShfkQiBQ;CB ze}?skeW8W&XXE1qtL~Qz+bw-qyCX=?b=P0}s}EO&uitOB@7Gu9e@~BD?EAFz^_GAi zFOv%6{&c0B*MFkzF+ERpmVM9eyV2>hA1^$}{60FAsp4p4zSV1$-{oHSFMZ0E>x*(d z^>2PwGaqkKm$FFRt`n`nPT&4a+Wd0C_pg>}J-?qWR+roH@7S^UXKOiXYdu#4y$BZV zQkuN!|MJ#|mqkJ`LLpVIj1Lf(WQca z?MtnGPMW^1nCF)o* zzk~UUe!lyECGM!?m2dz2trhi7>^pYy_rK5o`@6l>!F4d9X$?ADibCI zoU=^t{j}uWJig1em2ML=76qs@zukKMUhVQ~ku*2XoDF+l|Ek-vCiInE>8p^?`CQBQ zecgQDC8qquj^?@x{J$LSU$Fo6`NVwgQM%sD@_&sDAYh<*Ao9-{O=e3T78Vwk7EOk8 zOb{l^69WMd*vH;p`2ODBxz^=*cXyS3es(td`ntPX5B~i8T>t;~{fQ4jY9<_(IJ&d= zx!)X%!jF%R-nkRAHEQmR88fC#*^+nH%HRLI{=OefH~APD85u2m6l*@8H4h97Og}d# za!W>FT-?09d;hY_*9geS@WiRu*!=l?-roJ0vx9@fk9Q4E=UljOLHSz4l-=d;_ucK` z;^LCCsYsalX~S-7d;9;o7CrCY>^zkD^4{rutj{LQM0t7~hWjX#Dv9a_EZ*5UL?>-Nn^c>DTwIB)p2AHROB zDfu4p^zCL-o!{?Pf0X}oJAVI<*VE$n2y+Km+-A6>e1Y5Q!!{a#z@YUAVQ|GfV1U)}$&j2o)H zh{>>7bk3L|@#Fiar>Es>zg#?D|F5`fk&&@+;>1;J*1UOeuvzSU9DnpaHTS=tz8Y<< z{PBAA){PH6cW!5wv#tF0O4{yWrSpo{`}gk;{{Lt8N7g@oU#r`iuaBSpX6|#DxFdIJ zF8qJWVmUD|eR9{j!}TF=?@E+ttpEJ$tN(6xyZ?{6r|ZZ6eLI`;>+0M4O;v*asb(GJ z;NZB=eZcU*sb1elD}$GNd3oKdipzZY^55(0_LZlSYaJZ2qHew3Z$0xc!~GAN=l|vT zBj;np#Kd&Kf5(m;F7ED!m9D<8`)*y}D|Wt4>iu?ID_#3HKTi7mS!JMKp>?*?PF5<+ z`F?Z!y!!{v%iEW|`BHh+`N!M5J?lSw*!cM6k+t=IY7JCBp80n`IsI_b#%%ou=lOej zJ*W5QaG%SOo>8;>N!^=OxkqoMADZ%{%FpG+%L^rEx9Vla2Ht*L|L5^WGc!A*glAhS zy|+JEz20oDg}}@-iJ}1g{K=*z_s#XKUrW6{y}3`;ex~u7;^0%Qj{^mlo4?sJ<;bD; z*EbxxaC!M;uC4KZAFp5bYSxt-DjUCOW!>T6;K&y@V6iWGF~RrI!^7?OfAJjd`P0Po zzky*!^pm~clCGriJm^;ZPtkzvdI?8Qre#Zu{SF zjJwU>%`1<2v_*51M&A8BOW951Z7x5Xe|t;X`PL76qy1Gcul4zIYbty4r%i{L&2zkW zel5-4a$0CPuXtC{p*`X6Qhk3-wzj=fb}Y?B_GZX-5p!6z+ApC-~VfVxPJV;i`|c{dv@)zx=?q2U+ukn_a;u9=;!Ch z$H%vI>sITsHxWCFQj3c}OIU7Kx_eFa)Wh3%RYpBXSsgm*JB|^m4ED2y=1+3#ixQBKZD|0+n4LLuK8T{nR{PIaOu(8 zwb^_hSKds%v-A^F*xD#rfxEvxWkE);GImtW4-~PT#jb=k>M&rmyW!Ufh(KZT@`KyoLXo8$L`vbUnVl_VKaa)yW1H z7C-!78903IooyyA!qjD!bH~KM;6tn|TTb5Lnxxy?a?8rf3=TK^SYcWGOrqBS`h_+4|+6$y?n>!uvv_G(*p>u#ndJ&&{X)i>iF?0+GwoTK!;aQSw& zV*hu?ckFgGJJfY;@r$pFPqRvEUVJS1b8))=iwVMw?fors))fi&`>x9WJ*ubD{x{3$ zX?|SE?HQ-{{y2VJmR)RZk8<_dmHzn}{=cl(-39mM0Kc94Mhs@c;kfRUpt=9j_yMCwZj@(nh z-xmLCZfN*$jWOHofn1J|V!)~uD_*=!W6?H!&1}~5CYs~7B%{FnFLPzw{Qdn`H0;>1 zLzt=T{XO2NGtKkwP1B7&keHI18oB@DOVR!QU7>%Do1e>1k9_^v-F($H3yZ45mHQ_g zdELA>;*FmAcT+pLf8kp1|Gkyp>$!UG-alsRK9=4n+Vbn7{l3aearH-zpU!Rd&agAq z+3@<%%Qv(2)$A2dq(>b&==1b+->YIh?l}tEb)P5ev*e#Y{BGmP<@}-(+Ex|wb<3RV z{CerbVnNTIn}7H0(YJe78ukBZv&sLti>=D{NL@*((%bs|_TJL7T<<#;UDKZz(|za3 z&LmL|+o;Il{YOS}!OB6sLOG|M_s(^jd>Rr^}}@<0jtLA1y4WMJ(dV9~@|W z|HOdd{Cs=%;|$&9mX?+e?9Fm-UAb{XLPA19NN7|2|GJqzX~y~0U!UB39{>05ANl#5 zjBfhB-^adv^XAW%-`sVNA8z(vUsiUvLgUD)y3ao^KWFC8FE5Lgzd5DiR_*IoU#s=q zw`u(Q_q6-@`hCCBirN)Zel7hucmMbMJNb6T?*7f7bnG7&XS{8##fMk3^W$uH6#soU zd3yZ5nvb8ZPERYW|Nm>fzTEyFuinSkf4dU)yz$-a*zI}tRi9pUpRaiS>1=xQ^@Tjw z?PP1d9u+@7kN0@KTUbLAg1_NP6XZOP+pQ~ix6O*)b3 zK=hUC*B5iSfolDg4@*z7Cx**DT9&Y_F;QZZ6cZB@Q;`G*7@SB{0E2c&>qUkQBzdU+ zSfWMxJ=Zn|5SVc*QOEDau8UXi-2^N8FxfdfTU(%op;f`N+dqKe?Gtd-tF7J ze|&sAT|Zt4;&y|5hkrck)=w~I&I>zx;zWbX=JO7G%%C>X!BdG1)fHb}T>Sa@dHBJ( zrK`ga-}MlXXMOS%>iZrmp3h&D)YOh$y}EVbLPcF&-gVKf+!2b8#Gp+#?RLi9;swca zJ~|KbqGseCm@2lx;OklQ`w9@N6Sk_bcKfSMe%Zmo zjm;8V>sl?@-+Mp>E9N#=>(8@whq%wO=l#Pa<_iNZ?6{*aS@Nlb^N0Pj9EE21^=%Z> zyw8{KeNK9M_kt-}Tf3BxpPUg8;ME)DI{AL!x&2lgPL7+cnlENtSuN3}PL3ysEQyhSSmQsn0o|aKK8#&v z(-*MMaqB~!wn)4Gxli|mscKu!oz^}pf8w?U66-cHkvO0}ypCu2s zuRgdjUo&#)4x_gR)EylicP}b_J;h5^bNy~1xhmE5(}MhdrB+9m%?sfB60pil-%fRR zh@aNU_ZQ3#up6!6s@mnZ{`$w-xWB)2FP=(jDrYr}`dr?es?e#TdDMEt4gMDf4fO#_ zgI=mNM6G>QU66hyQA0u|IQfHfz@DWCt*#J4!^cHx6_kNe|G=U+Xs z#UejK?6Be61HbFv-oD-S+92u2>;9SdrT%>po>r+TGQ(|M_r6Ngsgq|f7ZE<8IAwB{ zMa*`K_J?O&J_`k%EINDh;W|IQzP>)`{^OmTZY#39P8ND)`2M-zc6(Csk(0^ZiNYq# zrxsm`+`8~^KxN&uzqfWsNtRT51g<>TqvO#acGN-qiK@UJlWD1;yE>nI$p84>@WQhY zsa(e|_by!F(zOpsRLk;JIl7|dy2U=h!ws!rMkY@z<|HXfev!Ant9N?y{a}l zVp^>X@5#dK2{U}s`<5Q7=3e7$vOGV2;{n}-{|o=JCw+b$vDL5jx%K}4-0gck*YquJ z@!FDETp4?c+*|dk{Pct*gD1r*mTr6t8IC)IbLXpO zOV)%q`>tBhKjVo!^Gl1PQ&-(&n-!k+W`*O@JP*4Z`{Z}aE`Pi^Q}SZEpIZ3V3nm$g zYqfOOWlflnka3}1bpEIKeWr^zVi+`g^fUYxXJ~l(dHVD5{<%@-oHaLQ?NvvwpqiMZ zs*ODjg|tdT<>RC<=_MjOAYVNagWq&yH??pOcz`iAA2Sj&2JsSAYKVO=bBK zmFM9}1_c|}W;ZRdoVrNUSXI%^&TjLPX$q1~mo8{b?9S$TBs{6>mC6Nn3CB+p?6~d~ zAN&#%7JXp(k|*0WBBo85_I!EtGu7js60V-BxP=}+7MfH%yD;NDkKVS4KK)-~e}wG( zyf<{^%Yes<)_49M>gttx>Ty&3%7g}feUrMSTXrdQ>Sxr{r7AC!P@b8#Y}MR`DONtK zFGoz{Rypi`>{6S>%8U53x*$={eXSe+QR5Ty$p2N&?SlD1<{5b`<=@xU7#Mtxe7|n>6hUK|mz9QpuReCYTl+bV zC-3zlo}$Bnr>CsuX%*&aJUMl{8UH>0=dx^Pq)%{NetWg{{J&3c&Z%yF;8ehqY|Z>T zUgypG!uLC+vlJvP1K01hn{<7ipWCrAwsQO0|Lf=bR^NGi?Q-pcxr?5pOf3xQlTweE zqnTg(!0^WVYj@3`d%oYtcj-v>kD6zn8IQl)$9n$v_mT@LeVcbII{D$p^m^$Vce`F2 zM)x}!Ma}(jMeBFy?M0$(X1YC08m#Abr}pJ|MgKWnAHB(X;?>m}b!Mlos=STfQWI`^ z_FzR%N=QWPxoum^PS3TmeUtv@`7scXUFA(YmauX)dC#|)jES9xnrd}FbxpgJmHBk)SvhZ+J9}iG>qP8)zbN9imN);# zDRWenek@C0$j|ftNM`U8KLeebo1vd}+0Kr=*7AA2N0+|KyA?-|W$Y-rep4;X-8?lv zYVVzkHxFMv{5GM)?w};+>+KwE%sx@puZvQ>)>xg}6yv)ls{4BMtpGQzFBxhMpZpCDZ#;vnK{b zxz^rOu{u9vv)b}?zwX5Czqp<6=&2*ToX`1kK5eT1fBo~{^7pqke|KU%r@1P)Da_jE z_vtfdr)%{{^3yn%$%2xUcB9su4(+nGsW%y2WOh@(5Se3=dff%dm!)EhR&kDV{N&vTjsPEOfaK2Puc#qOs;lX)IlYnA)n-%%S^pDns`Bm3HOkMoyZ??x?i4ZHgF$kyn1_fOt&MN2goU5+@=xB0VU zG25bo$4=9AC%Ueg_qbQH=UMC46TezIKD01Rtke~H*0E(r#_ZXj-z{Nlo)s#&;)cU^ zQO4ybzuk`IHT1sAy!lDRBfjrTv-`ZZ#=2bGXeqx_#jNmaI8(ab?Et5jUe2}Cf4^OQ zBvi+G;vDPPuhYeM=lO^TzJ2@lWA*fP*0V3)y2i(ByRfTprpui}&Pwe1Ys{`3XFC`D zZm#aNtuq&-8u9!;Y4_vz{r{F9f_$r^&tAKE+V9C#)puXETv1===4kpXefpINv-ot9 z|F?g>BmCN9^&S(cxx0S;&^mtg_oI+-d(#IiwVzwIiBF8UHqpMvE3Qgmp;(&#v|ksr z{!ZB$zjDgKD{;2JI-gvrxf!c|^@6hNnu*Kb{Y}^von*W6vh)|Jt;ZaW<&;eAg1sT~Q~` zgnpiLF2#J)hPWo*wB8oBsXDpyU2i5nNLs9zV|>Xfd9`bHV53a-@1DiRZC)CScCQ%CeDdDySf%yl-wDMn zE^`DQJ=^@a=Yhc?af|#@Qwn#w$4twyShnwKzdGyL&v#?B)7MtZ7;llk6!Wk1{hL}( zUn@V$W1rS18b(+@E1C3VLZi<9+{R*+g`RZ zi8;5LYxRKI!?y>gwE|%-26lJf0}m zJ>_7u=Nk*Y=1p^o6K3$`-@SZ)|L*3HQ*C8eGiR{8c)!zD>fGw+`%5OQ-gs_-JHNk_ zfvVl6m$q8&`qNLAexLg*U$tNc-{CJ`c+b0U7mi5w@aKQASTH#?wtvoUU!|`5Cl?gF z4BZ&gu3d06qCGK0WbOR??RslGaswtG3TrOPkeryiyK1lRaiJdcXtKJo7*)o$^cKk3UqFWuo5xi9zU ztu3z>G25-S=R6&n75d~!QH;4-r@@WNex9fe&r-B>>OS4$7E{}BsX06LZAHcW^Xo2` zy%PGq=EFVNK26?dip)J9XHWiq{_EY)?t@lp_aZJk7;bg975`HgBLBR@XwKwkdBxF2 z^$&yCcfZ^}M|{H7B^yq4KkWGwQ?EY%FXz?`HEXY(_N&ypBYIooEQjROnAqDoizC*Y zahe}>?S@t8JHO}MM-8mx{<>tDR{7o)>|be;6Sg9wGRWh=9aipi-RN4q#rw`)FzHKK z8f4rVYP(H5EH$_6v$a8#-tOAYtt;7M!`b_970ijcb}NIUa_frH+>qEWU;h8Af1b~I zw3JQs4Uc&$Yu}3;@rcN|dkbR^eEhLzadoY^`*XK7^Ph{)npt?H`0qar%j?UohQ6Km zUTRXv>X!cBDc1^i1!#pDMtt(Pd3p8E&bdq5qIB1+J}C4vgLl%YjYY>^oeAVxz5PdO ze$@S2eb3w1$81`^Z}H;0E1t6doAR`0LUU}(lfUQwRqLNJjeWK0bJ@Dv#nE2;mcQT4 z-6HN1X1J-xdD`3Mo=ut>UZ2zUo>bk%$Nv4netoZV+cJ4ff4_SH*01GrPsRe-lumYImdtD{m#QPCSR?}zP)() zz3ZNfr|d3xf7N|&6zh9~s&Cr_=k`_{y?VU(*B2qh)bkl$*`lqPPlZI!FtfdjeH3-; z=^rnM!l0EX@_xa75oUk;uf9~$y2L=hATxk;G zyLx^;K5LM0{rZAEn`%EEFRtO{4BmaRBlMZLxrfHA#*FqK+=(B5E}EFZej_IJ)FPX^ zvFE26#j1Vm4ArY^pX3v}Yzp%_`~L-@imnH5B;LH0oV3*M=)pd9<(9bxFOSzUm&x+o z`s(S^%Cu~)@M*(kG9`c4XU5I^Ab7ptqP3X*ebLpKxz|@ubvEW%>2k)ItNY5Du(|b@ zem`dYw{*(Jt0@NO4Q5ULcJ|ZVz-wpn-yLL{b4vyns4SszG61+(JW4H2@TKP z&2=pP-D~};_gW@#K0bBQ)F<=6)u{;LaK4a%Jw<*G^>9xAK7F*`pDJ`Fo^*$sjlVjr~k=4OhogTbIojd(LjpWo-qe&vX9YF-<>^Sn=ci?h_?t#i9$lpRMUxKWXLG zw!V{V6eD`BMop=Wt>k9zz3AlJ8g?{)Rn!)-b7AK!tim%BW*pF3yymvVm7Lg5hR=UG z9<3=6*KPR-?}cV)ud{#s+N@Gv;M>F^jLSI=fN#{kfzKOg<;H^jqibnG@!> zVNF`r-0a)yGS{>0>U*pC{z&2(?_ATkeSa&?EtZ=we~Yw|_S{)Bh^ul5uow%{SM_8_q>koGLuWBi=ss-n#C({Td3ZTNls1^!M&_ z-QrIl3d*BvUuor=borFc70zkOe1^PVE1%1z*Kav=HTUYj z!fyr-W;=Fk^Zi~oBlZ1*XU}$hHQC>;=y%gTeZ@ph@9Z9__1;@AsIvvHbh)@&>|Er7 zhmUvOx?1;aQLbh04Bxn*DDBlE9U{qm{) zpR9iVYWH-@oPH1X>G4x*s)DjP#JugErU#ZuYUV^oO$k|c#X)-W8pmkM$1nDLNZA&$ zILtg^yWx*lSC-0@NA7SgkT3{I)0(7X+N0QF%Y0wfxtgs^Z+1}hlnBokPxd+-lTuyD zer(%(^EbYR2IA+ec71Zb*JjuKHautdgk@K@2t9o+e*V|y=FO|O-|mXk-X@yVwW+xM zj;u`0-|N4AuK8vybGPZ{HeSiaZFiNsRW)yITf1-G(I2)vtBWSSzml|N($QDSc0X?Z zx4ipX=h~{&<<}|?zO0#*cP_$y+wwh=Raf2!n-;o)`-{MdB`crYP@5I-_*nDaX6^S| zR9}9noYQnHh3!ttTqbF@lC`%cWL!wkD9x-X5niKwQE9bE&XCTbF;OAU4% zG;DjK^J$U6zaF_a^R>H6+gKJaOt7&O5L>D?BS@FSFlCjZU;FvJj8*(+_iHcTnI-l_ zV1m4h=Tu(_Rn?xyCSGgoj8zR46&1H{l1%#Xqn9TpDmE-Aw{MbE=94+obhy6X+n~RE zVvFk2TZ`5lIr3%JuVuU1+&12kSr|BlCrL;+nCr|%-w$SC(Ln(h6_&sBe7Z#JN_wk) z^iEUGX|ai7XD56;I@6Pr^CatIS5MC46D2Bh+a^SYt?cNZG|4RN%C*CPnq~S*QrCQ) zD12eb$4yONj{Im@bn4bGwT(Q79k-;$70pSydTQCFJx5x8EIA_-QPY$v(9y7Il1*I8 z`nSg0c7_Xz=n76gS8`7Axm?IcIPr1$ss$DcMY#5~mYtz$2e-bnRU5 zwZ22!VodfIXJk5e99LMIm0s_syztTrx6fK@+Gd7UCYDt$=4oFP%>;2xdR%yR}+GMGDE6lkgcFLh&9<|1bE~=qn z&LKiAS`&l6FtM)PkU8`IGV@T!cc0P%($V?<_E@iK6J^?%qqFS5)2~}ad4=YzFPgpW*DNvV;C1EMh8@C3 zqqRPDYq{#O`0kx{t~4m(+mx$)mxJ%M9?oc9=Y61RBG+SoGlPOU>HNEvH}>zHe90?8 zT*~gq47vQfsWXjAgqrLV68{;_pD!^vX{JR9U-OfGFP`VFJo6=FyygV(y{|sg`QwEp zPg=wRq3sizXY=>@6czca9#DD}Y0<8DrT40o*cskJ8FTry4_eG6?4)W`*zV}Kn^x65 z+WI7e=k2UZn~kTf>3lBBc62`9!<;8R>x|`h^TwCYZeRQLq4JhUMMkl|t*jp(PSy~s zJm}10{pGhu$d8DV$>$S&=IyTZuKe+R;+|!fF4U|j`oVenGH3D|o7A@vQ?nmcZJ(Gt zQT#uT{*fA)mIt=t$Ms!rL`}7qV|aa2z~lUf|Eo&WLjRmQ8h87!LGE9$CA6~zOn+@_*k8Lv)Dv{dwT!L4z(>^qz_+6sMiI%+yi?)4Sw)f;IsW}PG zM^8j=n8?yDrr@^l;gMUZmu3I($=cWEoM-cY-Y_F*<$@0uV$I?b-F`opiAgVyd4DVE z!kHiYFDrZbUo^@rYSO=CT_kZ$eQzRj!&!5w&7lSYGc}$rXS^hH>({iW9P0MTLUnu8 z?dvaX{Ty4#vf|bsbGxN~Y_opo2gDy@pB<*D`t*6Jo`Gq zFW1y|(>oTyfMeaVZBEk??!}#cz<=S|(qk^7Q?93}A5jy%rs?)gK0)q6kl_3|x|4*i zHH${HEqKK>+4$3`rz)Ry->^leZJKrFNKcL-o4e^x%LR-FF5k_FyWe^sd|LnX4Xkn5HZ;Q&R$WHuGe5TmE z_l+dSZ!UrDr~ZH7@teTmta(W5=$?%Sd+uf)NQ`fs?$cl7`LJr`noX}yZjuY;ZH=~O z_*XFBSkW`{ zb=x!kU$ggL5qmxL&4pEqHZbL#3tD~f9DBu@Te6;+C$3z!e)ucKTy9-nT;s{ZG3JLW zc{v50RxRv%z%OvmxiHH&@Xf*xU%Yz5j$giZAo4=jlDFA+V^~?*mT|k8>Vn+&r_HsS=v2$N=RZ{Lwj%Kti;e~u2(tdo>Q@!J^d5s>2$SCHcU*1 z`tKzkcs^r^>CCEx;!D%C6Pa20o(3vywPSUfYGU%oYoZVL;i(x{rq0>acKOMQ49TM% zy1`d?)IPXe<<3uCmDt6x`%cK@AkDOpNGp!YAg>3z57{ryc=TmvRP2wr%TMp({kn~> z`TwTRI-y;G)3j#9c}%%glKi{XELZis9_zi1ta%Pas~qPuw?8{Df9BG_oTXkjS@e5e z8#HV&&fa`^RmYm9%Z#hH&pFXx5WPS&*ko#Y+Ow3F_cQk8ICB{s$S9dGY2K_k)0j7N z`57N6Enc@|iG{B1Zb!dE#{+MLL|?z4bi`we!d;Z{ zz#4-Y2TGY8ZG0ac+q9s1{=VZ_S znIBS)o#;9j5FjmIvfz+3SJ|)Iy0PybZF;dd{tOeFL|>-nJ<$ynt&^WW+SzU1w!DDp z`q@8~oA2JWjd}ZQM-Es1g{({bJAc&*sktQ1kAJeua%pM-hw)t2* zFsyy}OzPMS;YYT~+v2yac=aal{mcFTzsLWr+_re~-w%{G0mqys0H9rE;^cirbNl5vtorn$P3eEl=k6P2gA{}p3=IR8N6nRZUc zM{mn3t}xPRG^S${v`WdHSh3SX04FK%6a znf-yzuAgtpvu}h3zf<|1#lf@L`9J&egD-cyeRuk=ztGzGWmjV39&I!A_EV{Sl)3-g zikSM?z>=JICEr5~S!2wLpINJzY$@INbG2QOMewQOyKCeupTA6bwyQ8!sGw!Qvb~&#car9$xyU ze4cTAsb1yT071SO^H!FbdoCAWnzT#RbXCQ=+28+d(Ok6YYRJ~gXGsa{n;!0(8TFi} zbEUWJ_Pd`Xx9`x}DbR0~RB5u)!Qn@Gfkd%!&vpJUU)lMM?G75+O21QE-#9z{_WNJ< zd&Kz7)xO^AyjGqo^X6Xd=XLepx3)Z-^0oiB)0Y`B#m9>uOuWmXE}FPZLNckQXz%*$ zi+76N?H69BX!XGPzU7Nw6PACekZm_?TgoMKY(>iS-&Phu`(C|VZEqvFMP4G}&ySz- z?CZrY{yEw2d1L9Z$jN)Rh0@u|JRMql@qAYS9uJ4JbIuJhUoUO#(PaNX>~HrLOp zsFrrDNP5C_-ItfI(Y~U#GIX(oaq)|+2BrRVg@k3-A|LFM{Cq~b;I4v#!k-A4V|z-H zkFT63UdA8N6LL$7S<7LkS7q|kg!77%|5O>@yL8L`cVKnb%XhQpNl*WJz5LtVUW1ss z20s*j9J_1EpMQjB`49U#iL{*GDIZ?0dOgLD%_dNP`S%RbmX87X`4>1Ek29~Gv3Fb5 z0`(&bd)2PCeyOut8-IU=#O`*-f}$OnkKHaDxT~>kr?Z`!>oMz|+SdPxVox1(!Im4+b=M1+$o!xJ|Hr#b$be;KSefNV;Wcg#P z>R)Qv%dbC>94e&BqR)8xxMBY9vlD;bDLC`P;QHA$d(+H(Z7VCgyItc%at^*&x$JTD z^|kkQ-#%XYaN&%of2Z^x?Ba~tqGaKB{T?IF0_Pa>?6U5HwT{aZ+jr!Z$Y#AMnBeX( z<;7(_+&%N{ZlK+fQsq1SEQ~^%UTH5s^mwxt z>$=%1OZwL4?_burv64;KQBmPf@Vmq#vn@JbP5Zuh`RQu;s&98JlNBr_V=vy^{-99) zPL$#M!tV>qIs$g>-xXdU@pn%(N5vIhzQgO?3nZLQ?K-}9InSB{o>%v7ldf14r?+E0 zo6uqB+S z-|o?#s_VSoZt)4ssL<2oKFQC^+p_53hYMdl=f6Ijx4xa<>6XSnHH|v{$0zISZ8v0Z zvgKLLTIqLnPIb-EH#6UzTODSp|Klvv|21NwS0^y3#P_XR9agzEM!1M|N1l~jJs#-t#?;e?AH5zqfYyLsc_wi!xvBLC)|~?kN=;%G03g| zxomvGe#7N~hEA3CPYl9lpS<{B@|uHLlifaB&2kW))O}m5HbFjSv8kzh{(Q^B?@Ic3 zcI3S(IyCJ((+LH7Tk^baryke{{HZpJM)%Z`{~2zY`Sb+sr1x8ZZYN@931vi z?TUAHET2%+W)Yn2qs??y5Q!9J@sU6~m_OZ1qoR#?*-)Mc@4W?ELmUZ0a; z(Mwmn(tOYv^jsoZe|y&HkQiGYWziDbfYWJD z>3fnKO-T=m_C`!rjLi2in5poD^TyJwHNg+sY^6^Y?U>5He6`848(|u)g7Y5UWcgwJ zBg9o|T^>`}%8xZ|K`U3B^X~2RT_<9C<;vCVCkl7`@rjx$E-ua7abA=Co@M(W_s->IN-!DmirhqTz##w8Y57yc?hFeXZw2O)b;N z$oAM1lPSn|#5nS#Yv|HHqOnZ*8b`u!osF=lYX7j3RLDxcTe$6 z6*b+k?a0R9DJ4BAn@>3$yA(5NZg|vPlS8G(OV4?2J>~UjHl#GmkZJqrmtXbbSdNe7 zk-JCaPd^Ag^W1=CpPIxL<3BUmoE9{0@_nf9soJJ@^BI3S$C`j1*2luxc5;q0R6j2_ zpYmge`rb~#)GK0dg3L6NRfQLSuS?dkvr3)$X4-qsZAL#N5wl2c-4E4KmPf!{n7!(FHv7aCZCk7WjprK>af7| zv-^3%Cspz-y2?1clkc5x-R#s~cG=I{w;r>;Ho<-#zu+yVhdg&;&YyQ@y`^_Gdt=w$ zZF2?dUhy?QFMq`I(rPKsHVzKfV-iWXz8pRE{>0su;!lFBK9}>pP-kPjwea`Gwf|3T z@J)TW^5@YRNoOW;oG*x87+8bXl`J-sjc%Sp~iNcwAAGXJTW#>OG{xL=RP#WtMGBSZT!luBE;VJXVvHLNzo$_ZA#z)90C~aA}L?=LM6mZ+nz>Yg7K`(|>oF#j<|T zTx)zk@L;^yfxmG;$N63jvb~RXD2p4dz9MC@(ZTE3Xg`$Nyh^%!`&>DGEB1#eHSg z3IF+e@68-mX#1@$=E)UwzT+!!!sXCkKM7CMqFXt<*L^Ev+&vMjzwr zZ_HYzQMxZ|`r6=dV}XTB)`Z;uR`FBi!7jD<#k%P~tv`lX+&u6x|LMvfpP6_PRd==? z$z)YdlH@#jzQSYD%EYNcij%q&rf$`_?9^K=Et7M|EPYD#sXGgsGV<~=1-nFH#X#`{0`+5U7;OIH*8e0w%)!f@?3eearV@iv+Ez^Pf>olh->wpgiyge?n&k$Pg2rTpHKCyobLYEY|?SQc2A-CR^N8Iealf{smJv~-oibp2MI zJql;0sJ&+mu)cETE&D_DhX#*)vJAh!Y&*#K``*6R^Obe#ntma(-&OJ0%>MS}Tk2FE zrll5^bL$r0U%dW$YC^)z$;F!eYas?-%DB+%4Yo!2Su>vfT3b-8-9W z`Tl-){`#P0SJ@Yv>i6sC*MC@Ye&Krc9n4B4C#??Ku0MEC)Rx(Jeu;eM;x9p3hn+V4 zUalosT>5tLzqxOhxHWa(`Zb-eW@NrUaT-CMomB){9TNJF% zGW8Og{Mh2m-;>L}r0)OO|FnA2nPhE=(9olAHx=K}PWrL=+5^XqWs@H8c2B=yZK*rw z*k{d7%cVCr>5zBY>E!^o_@IT}$OOec5 zyMJ5nPHUR=X|wfSyQ=s9e?Mj49A;s$<9%n2;r;8jOpdvt7i%)NpO1g0S5{JRqe4mW zdDPOG?y)v8v9WWe>CU#k|90}BG*R7c7oIz5t-Ume7LRT8Pk2`@RVO+k!@3-G_eI`uAE@NEWBKPrcHTA{i3z! zCTO2co$qs)d18{EcQ<$Wn%KnsXD(h$JUXv?CyPO(>GTNiXY3CqUpu!eh9f-BW3$fm z8Nu12VP;b%zS&Wv^UB0|ao~~n-)HQ!2v}nBRQ~f^%fs5ST*(uSxK|(B6jAxWZTZa2 z&(F>NIIns0^)>f>?PIl0Tfa@;o-pe#)AiKN%XYr$%31bM=6T4q2PI~y#~bjH;Yxld=tisk0SZwa|HMX z?|6u?OyJBNN0VQ=Uw)RiKPEL~bHOwF$1A=o?f$9v?cKLxyKgoXk>{jVO!KTh*c!qX zar9WW{fq41lZz#ajicAUe^tBZ9b0C`#4fA0A9F)yOj(%6Hf!f>miCEdub<}I?-pM- zP4dcJdHcOnSDUTf3ERJsb8(Pe?XE57L;6pCJ=D5piPO5tTiN;T zc&?u2F*5ePYC8YmzPq^<)!b@%Z)g8rv3ZKZ=DaA6x^J0mM^$QnU3ogMYg+apIh$Jr z%t@&~Yegh)*S)HWzE-g&z$80BB!5%!U8z8pzDALATpx_Ny24ImE%uY`J+*3CYje86 z>19!$wp;9eD>@wmCQ=;p5E86VX`Yij=K^oJOR zOK&Ya_NjNN$pnM7k+1fy_BqF>En>S)=JDBWx4g^FNejE~IGNJJ8@I_!#G|2CxpB!6 zgNn7GZOeYhex6pf>`Jkl?F6Tbf7Gqt9;n`5Yp<~9Ooqn&4<8>T@8s324vTy>S!L0Q zU2o0^C4Aex@Pw5??!M|IS99z z?w9Tao+r=0sBC?_PuKlYMc&%((4D6;GEcp${I=LEq-X6@Ln*Z@T0L1GSAKoRw{P`b z**ShoOjd1)stkR$;#`?s>(rmpvCn?Xc5{E5_jt$mLo0c^x5eqOTsk?k_|0SKsM1X- z{gvk)?(}^y_sWfwYaW?Fr-QylOqqNCwc1*fC*duoR(oBu6R)-zev@2mY!I2Hd+*YU zD?MA(eqC8tn%7qDJa688PQ44;o^(Hb;`3>( zx?Q=VWbmXMPWOqcq_yYotNMTP!KQ!zRQu!id|%=0!c-h`pF@3W~wLCpni<` z`MkS3leRkga(N%?`8g?TQts}mwZ6xNcKp1+w)A0#HapXu>+_HDs3{w`TUM~Qf2{Gc zdJtSB|17ww{@kNfhia4e=ilpc>mM{Nxv2KL^yQ*U0`cz`7)SPm`TFS{FHN4r(Y)G- z<=Ao&Qf;jhv*k+S#h&D-Zp zF0G0Q(^rh#bH+(tFgs_i(f18X9sFUvbxK=jDeA2}X_})L%JuPS!u`n4;^&G#?Vof1 zQeKYLqs*^j`jIF7(n9;+wuVN|zWax-XWHq!_(d9TH{5>pAW*t*W$I$j?A3`8iJPPD zyLB$I`?tP+_V&nx7fDmLEJ^s@ajvX!>eZXl*K;l8=9ibOfB)>oosO@c|2P>N^;N99 zf4;aQ^K0lq?ieSb?1Y#3TG<|nM{~BksrD>*#fAePI6{AD@PFt)=`t25Rblb-@NqTnGYHwMeYiG_2J+tWV zm8~Z(-aI{j+2I$v_OIIid_`Q9^D5hGpMM_z>u|mCWlB=-fx9ASH(P$>Q+|0(`2Oxy zX-v<}cNy;Vytpy*!N&W%s{cdVrg=S(@~L0*{ph3LbAq&TC!Y-6aWk=m#a8adZLQZ6 zPLveQTY9Q^gZdGT{TEw2eQS;9$7qLq;7blM+AqxaU#j0;Cg$4hy|1_JlRPf*&qKi_ z_vPbTB}*T>G`m@azz;sE@mQ^lGP&pnDpPq7|&yW(byBF5Z%;V%PF$OG@FA z_TAMfthZBh>|VXx^e&_7cW>XDDaV%v#T*V2KAm~qZriKrm-iaA^#53@5K-E3y}U%q)ai;?qpA6otDjbgHwTu! znv*=wSS){4(6+7HXKvYGaWGSN=j;ayX5Vvh%PoqtTE&0oomcF=eH9z8A5`-TFU-6A ze))R8Y?Uoi-Fr$3)&@CuEWbQ!LdxIX-BOuN&(FA~bBk{3aTc4@>cF5~o3Pa7{v4ai zcPwlvpS5b2v+;9&x+4%M@zbc9bt2j}Z*w!9i`TqbF{fzR-pSi^Sx-u36lPrb6}r2u zVz-`^)cqTkzS5g(FRnPZ`LFlt&E`MWT8d1rtymuJkn*hZe`WT$6vmfg7ChTlyGK{o zz05g(gKK3}`kPs2q*&N4%4zL&y~(WgV3EK*A7!Z^DbY9Uv~{Dpt7I&F}V!T$*DH~tUK&WfJrKhNS@$@;1a^)n3Bl?K6yo7dUS`nsn) z^!wk#xhlvhguifj} z)e~BqJ`}D|OWyrBewl93=g7Bv^$P0CY}t|%H))n$)c^PX=x!m4y;(E%cU~;kJ#KEf z-d4u_)$LiE`*mj9o<4mxed^;m@n>UatA6YNMuGLXTPgbW_A|0y z-8D?te(coySMYAx8@DrR`jU$Ur_YPEtZ!Vs{eRa_?mbP1k7h-mbapP}uKn@T_tHGi z;{ImtWm%UFnN?cUf4Eowx9Zs^-s9^%G;QOIcec&uUa~|(S?56Z)vWtlwddab)h~tX- zbNs0FYLjDa-O*`hB8t|{S+RFVZOHRh>s70b{?^v;yQRzCdib(lQMu-A&ixB#=1jJe z|6jSS{rs<|+F?01lMiHExf&eNygj1ymE`G7-Xc9SKV~mkVzIi>EG@8kdhXMn#h({l zh_T$z)w$-j1p6A>lkT$5^0XhxvK`&rwKO72f}MHhm0G@gx1FMQ=!JUTuxaPj)b+~z zxA9~(obKn(Z^aawXOT@+lg;;B@d*YyI;v}{cxFgO_yQ+%3MX=D9fdngesTYTw{A~5*Rggk&UsP z(I>CStt%Go63d&;9M(N;(;07ZWyXt=szpsAei^4vZMw{ry_Cmz=A7<}2P8_%c7`Vi zv8ZW1j9#U8|NN$cIgfB?LNIermLr;$LGxImI9GQOSdi96J>Vju8M(a zr)q5TsUYO{zbEUYlUQE|%!Na;0UTjQz)~NLJ zu2jveS#{^&>#ZTrj=9A3>=lwP{}~iw^~Cj7L{3keZ;{i*n3>|t^?e;XDpa|@{eL() zQ@Qep-Q;V1hnB_s3AlT#jq6mH-(sh=p}o(hMlL(Bq;+Oz<<_Jd8^b0}y3^D0N6P2$ ziO+5&Vh4G4EZww+Nl#NGbb6>+m$X(_*3*bviQiMt{Y%$B=C)iUso=DZyLqTjBJaVZ zZK?8?>l*qm?b>?dgrxiPBTZ5XqMLJ*F9dCzwrkR%td$9VGa_zhbOdjS2#Jb|<$stm zWzE7BON0*XwU{a9q++wuU?$@i@_Tzi2tu;>z%P|FBeX=G% zKy0bt0;!vQ%9>$I#U%ExJ-q6{si2iUeZq&BKd{;FmglTUZ&8t(GpR<{(ki%p+nYCE zRI?woc$8hp@VL}5N3%q1$Lt>g-mBBsd=-4h8p6H*v1Cw>vD{HWvS_1RhK>V>j% z6_avpBrHSU9nwqzs(Y@q{_Vq-f3qA9Upy>6)jy9n zySw+5O_=lSYe~B4F>}wZN!pe_^L?FqyYlv26O-4;`wC+@OyrY9XRi|9reaok#ZkU5SGRBC%GPCfE9pHdzG(6)6^ljh|6RO#u3Tj4 zlGU3RJ-Wn|c(wb_#i=5U50^hTIAhFtqp1CK(#QH!c}G6~$S~Dv3t6Du^zW#{hwDL^ zSLO&^)ji~YBauUW?^CxQZlC98&bue0o|x*HXR!RlndwU&W&OOczUrqm@1Mlf7~KgU zUWRxryzE%fF;D%;<&~{BBq9^+?#{m%AX3;+N8QYUQi*Q9XS=IiojeTIRK; z;Q@~i)5eKD$JcHb3bj&SIqJOM^NkG9aV20uD-vgBIW+~l*sp6 zwWA)~dyv0G;(FqXCq}xp*-tnBJIpr6-loxex7vg9N3v}yXUbbow`qi4pZj{*Dc;M| zWxdv=np!w3(AA4gKEp*NaXqd0F7@$`U*POF(<)>SM!nxwymMc1*qk#NhO0JyZp`c6^DSia+}O8OZTrtT zT%J;&^s(gkX;ZJ>Npioht^C4vq`MPzM8)C)i48CB?q57PZRv~yo_sceJ_}!N%YT3R ze$CIClZUOB_wJaq_vNoIPv88jj+W=qdA+~hhyRbvAD+W!-f!8QTT`dL)GbQz@y-v2 zQ&<1lJ9p0B?`~bCF*hau|9@WpH(uWISKf#C-DQ6_Drv4&%r3L^joxQGG3;}ASWo3^ zr@c*X?GL~aU(s%8zb{lhC|k?D-}*pd_Aa-}VizxpUA2>{4rS zVq)TRr689L+xyI)ELj#}s@=Ay>20)^*j;w8?~@B8{v5Qu@o3wgsT~h$*_KT`eb%0d zU8H{Dybsy|PLTx<1q8H@-k)mn(32-&eQ-8o8k^#r{r0rvn&BnHfI4X84?f>fSw`&J>G)Rk_RF_;V?o3uX3m))EGYKS!Fm)hbjjJDadN* zp%qX|K_cLTE+E2;&=WJB82p>+DA4jI*FkT(aadi zUq*+wEZDmBt9(AQe*C^825)XppM21em(AY7IK-?g@u%12j31x&=_UvDyz-4cw0ljo zhBEgmjR}ig9exyA^t2YnuGyhvsrJgN#w~R6oMmyRStp3-X0Om#yXqjvtM)IFDz2xb zy1Z6LIq-J{J$Q6!&zwuQ#3t2Qdo><5nCX*$G|?foCcB;So|EE3pTOL=;?bp{CXRw8 zi&a!YKL&~`>$^P<+xj83o_kx$hh?Xh+%V7Pe7_|xI?G#om2?4XYuW)04tuWl#OVdj zk&`!7_g-eN|M7X(=Tx=cq9dvocn)7M@zh!qB=OIC(G`jA!!@$ZW!Fw6)*Wh=+3r7C z#q}V+?U!3Dlh(TQ&o*e3amx*uK6n0mi3toP?AbJbh=yN3IXe7Cg5%U1n)qnZHJ|ChPx(>d^07Mfwslx%6$frQNKlUVn9Ujo;D` z?V0)3SDQOoPNZ`*JxUjkNPVTZ-#nXB`0BasEUFrZUpp6CnPskT{{GE4X=!J0-&)7w zuo~HD4Yxp*B0Ua{_j#UL%R<)%m1k`@?3h=V=<4>v$00v8qHV&p>z%Kpmwu3KnCE%P zt98%PxRB`k8fuwsmuGq%x^9twC)EALRg;T%E+`y4c9TP~Ktk3?MQz>c)zc3siPeN1 z^LTb$R>HN|d9H^_R?fsv*|A>JrgT62zN<}))y8=uOJA?{@`aJNrj+HZd))TKs%Pnk zW49jN`20M$`?aQ{!GAGN52;tLrDpvI)Z#RnBBHiZyi;mcR8-U~)uM>k59FtuPL=T6 zGxP9|SDW3No16Rp|1W#@MSGR;dFCH~I4>7Jb3H$2$?q>d%c>`>uw6TWgH=gSA#ozx z)U~OTkBZ)8Q4|or;1K1?y0C?5sQ}AOZ-K1cq2I&qt~K)#G3~gxU^%6ILHoHs6-|LWz; zH;$jqM@~;}{xUc0bIoJTwQh@-7H~2A*v)!upJUKQv8}PQA2BPHnN7OPa(2SzS0@i` z^;VtK`tF_gC4RGlMJHD5DqG%ORsDO{`ENe=>N?~ktm0&T1|}_=WjbXI|F;?Pd)~Lq zGL?$C_ixV5_%H!cadBa}2QMwpn`_gq!F($OT~Dr@Kd^4}M3-_}-2-+wG4 z?aJ{@i^Zxv#H#*GFApm0y_Xh#l52Tv-}2{8tawlbMZoX^5q(^Jr-gbUD(JCjj-hR*T+4c43|4xots?gyxUnk?7 z^})!{Ij!k&x(4s+tz+g&%ZdmIZ82E0 zr?aA#r)GE`3{TFh-}|!mb5`Hng_=cNVkURjm#PGa?Ot_lX?fICw#PhPO*~64e-am7 zcmLC#%FC~xJxyAjU>=go8Tsb@exnoho7hX6S_94f-p;?o78WTk`g{3Y_o-#Guj+jG zy}4;pcedwVzH&(hd;f%jJyRzyTOT1ZckQ;gC9jHAxWi6WMXuVqY0tjajl9`QX4mO+ zt_-_<%PUMje)5jg+?JG|QahWfDqmbZ5Iyx$Pkr_8aL1YLyd}9ecFS41`(1tJqFWYK zl)FDt{q(mFpKjOsxUO5KDXTooWOp)ivylDE$81~9x^~+-ecQ4*#CO~4qF=9yl*L-| z-z>?kx$L*TVMmu9ucX}55ZTvB(^~TF)675anY!NR`|Pj(7S-New9f3fuEoZ{^ehdI zuTeYqgmm%0EB;dAOHc zsQSB>ecLP+{qr1ew;tzzQ|cXDHt+AVliBQSxdl1DvzF(6=h9kvnLqvC_tN+8_x*o5 zS9)Q5y=-afg4MavZcFxmm%sP#X?3@=^WpH+)4w&3&pnZS>0?&&mq+Gt=IwokOXOT% z&*MwBU_GWS%NewE=BkskUd{dfEZ^?J(T~Tj$H_Y;+f@AQyS-v-f6#1M=j1)D)6-bb z%{0wV7hb;lY$>;2-a?aVp{C~f@8wT+X;prmwPMDa+TOQkgMNDEdM>KI^iFM>YXZX` zo5n=5$g^E{1kT^ztNxLjhv&oOKgai1iOB^=_r(6>eCYjm8msQF2jQQS`+}HbtA+2^ zzn=g9qi%n!>>*3(_4S!r+$%NbSWWqNP(C6jQel7HN~^AJ#Lz` z#J0NGZCfo*U2&^(h?ajWKd)@T;S}SUYfk-9IC*SSTVxua zs?S}DdL%3n{*Hqu?uynWAvOOp8_f(EuXwSkVT(-T4Yt1d6eU(3p(%HNV^W<*&E`u1 zlear<((3&)QTbWMwYsv7n1I)DtGs;WCHT)hKe{yZ#d`m?cAJ;|?Kc89>!fB^@@snc z*5BM~v+hE{--p@kZ4Z~`@=sZ#oqKKm;u*iV&1>|E)2DdNZcCEruAQ*zzT~6H*J_`g zk({0Bc39kMt!wuA9d^6wIufs19d=25*Lt90tMWp>+#vaLb6(ALZlAq7^bF6cpdP>b z$LII&{P?!%;>A$qX=RHqo|`1s zW(kQ-3#=-re)DP0Co`jcjhh(`+*dWQ`8IFc4Bh9tSEgNgy0Ka$o`-iv?ycBB?>)}u zr>%G0zHKdX*S6|lz{F?o{|0V~S-3{Kw1JvQ{k@z z5nH!C6>(-eW;wa?fZyH?DP9j&ZDz9j;BBkPH&@msSMfRHHsiO88?LsNe(Ro|>l6E= zJ?>{|RH^T`D@A9nT~>2Fwy8gfyMNB!l7~muU46f!-P1p4QR;&^k>7K)a}K#Atns;f z?>Il_@$NlLkFu}CJl^KA-LiN(E4yyw%&6Pz6g@rJa=uR4v~=OVrMu_Xy)-eeO|aP+ zHgQToK~2G0mosC1teFl^GqrkFK2vn+D#xvE3r<*c1a7c; zdpO)mXq7tiS-@L4|e4IUV zZ`s@3o*ngFb)C0Yk9XAf!n!<{7ms?M>e{-Mtupa)D?hP@ee=znsx})j7RLFVj59nF zD#GWyUVVS^OaasHf4A4a7M>TWbalhEe{G8nq}r{XY@T~-gWcXG(+rEhR%+Y-D7e`+ z=Zop-z4vFz7Eal;RistF(?2*Xr1GKsxlg>h*$X4CAL7vT{3>_Hz*=SD%IPz0Iwws2 zyRz!J>h%CO;k$~xAHPP)2u`0gY0B>B9dRb*UdGcrYr>bOt@-pl?$`1)dFR%xx$$C) z%q@*ixxcSho{yg(GF@g{#y9)3eCtCEZ9i=~^W#N&bfE9-qg}oG6ggR!|0qs+ysdKI z#n7x(8x4$YG)(MN4HXSdSNr&ReRG?(ym~43y37J=CAiEzxR#r)Cmr&b$>3I7ynNx zw`jTOXc^USFTPE5UFxyP00etAi^}1+%&OPP_c?l>UpuPM#{ zBsJw(-r4iFC+&Q?SxWTi2eo~hcbRA_&pq*Tv(M7!XG-#KuG{nF?92Lf7BSlSZ!a62 z`eyZVB3ti8rHotN+&x@ z@2m>v)2O`i!@H9Y_cqVwqxhco&GaSv%^wSRE`&#s6Ajhvp~gl+4P89 z|47%qvOC9LM;?6hi6_@2Qf9qTXOn|pa+T4;N#ZAOPMadcv*u=!D)X^j)6dmEx%@z_ zvAB+T|CW^F_Q?^6MXYC-tUt1xov9my?KQT2h+Eip_l6Rj@(8H>G%}V(*etci|yItw{!kbA-UjvG4qI~{vXEz>T_@T-C z`0P(TO``?gTSJ$*u(Jy`YH#ztE!p?`wzS_q@2)w8`~GQ8SU*|G`|!n|#>%d{zkMq! zs-7}+>Qvjr&(F>-(Q;)wCMdzc(X+o)&|BKFs4!=)Lcy`{pOchoqTl|1uXlWbIRg_j z1A~AB14F|B1_lNeHUN8-3=RnpHX{QA2M>tLz<{LOApxWoi&nUDkZu79 zEL!0{r&Bu&Ho=CAG`Ogw(;E+P`Mw`!_Q=K%(W2Jzzt9*kKT85(wWcIM{akM&A_e}7;7ys`lUL&B`gt^D$K zTW;nkD=Vw$8mtv#V5l=NIKgZ*!%-{n{QN>ro{I~Tzf?)_^78V&<;|Ab`s=iIxSUGjF-sb$_fdGT3v9?X8Tfk+Xxdv$J#c;aQDAy>WYu?Ebwtc=x^BJ?YuoCf@G; z*uMSm66OCNUOy^+qINi0UrI_!>X!8NXYVDyto%{a`K8-+s&ezopr04a*)wg3PC diff --git a/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc b/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc index 5bd12a859b5..85fdaf88840 100644 --- a/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc +++ b/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2022 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -8,136 +8,151 @@ // ********************************************************************** /*! - \previouspage creator-heob.html - \page creator-cpu-usage-analyzer.html - \nextpage creator-cppcheck.html + \page creator-how-to-analyze-cpu-usage.html + \previouspage creator-how-tos.html - \title Analyzing CPU Usage + \ingroup creator-how-to-analyze - \QC is integrated with the Linux Perf tool that can be - used to analyze the CPU and memory usage of an application on embedded - devices and, to a limited extent, on Linux desktop platforms. The - Performance Analyzer uses the Perf tool bundled with the Linux kernel to - take periodic snapshots of the call chain of an application and visualizes - them in a timeline view or as a flame graph. + \title Analyze CPU usage - \section1 Using the Performance Analyzer + With Perf, you can analyze the CPU and memory usage of an application + on Linux desktop and embedded devices. \l{Performance Analyzer} uses the + Perf tool bundled with the Linux kernel to take periodic snapshots of + the call chain of an application and visualizes them in a timeline view + or as a flame graph. - The Performance Analyzer usually needs to be able to locate debug symbols for - the binaries involved. + Usually, Performance Analyzer needs debug symbols for the profiled + binaries. Profile builds produce optimized binaries with separate debug + symbols, so use them for profiling. - Profile builds produce optimized binaries with separate debug symbols and - should generally be used for profiling. + \section1 Collect data - To manually set up a build configuration that generates separate debug - symbols, edit the project build settings: - - \list 1 - \li To generate debug symbols also for applications compiled in release - mode, select \uicontrol {Projects}, and then select - \uicontrol Enable in the \uicontrol {Separate debug info} field. - - \li Select \uicontrol Yes to recompile the project. - - \endlist - - You can start the Performance Analyzer in the following ways: + Start Performance Analyzer in the following ways to collect data: \list - \li Select \uicontrol Analyze > \uicontrol {Performance Analyzer} to + \li Go to \uicontrol Analyze > \uicontrol {Performance Analyzer} to profile the current application. - \li Select the - \inlineimage icons/qtcreator-analyze-start-button.png - (\uicontrol Start) button to start the application from the + \li Select \inlineimage icons/qtcreator-analyze-start-button.png + (\uicontrol Start) to start the application from the \uicontrol {Performance Analyzer}. \image qtcreator-performance-analyzer-toolbar.png {Performance Analyzer toolbar} \endlist - \note If data collection does not start automatically, select the + \note If data collection does not start automatically, select \inlineimage icons/recordfill.png - (\uicontrol {Collect profile data}) button. + (\uicontrol {Collect profile data}). When you start analyzing an application, the application is launched, and - the Performance Analyzer immediately begins to collect data. This is indicated - by the time running in the \uicontrol Recorded field. However, as the data + Performance Analyzer immediately begins to collect data. This is indicated + by the time running in \uicontrol Recorded. However, as the data is passed through the Perf tool and an extra helper program bundled with \QC, and both buffer and process it on the fly, data may arrive in \QC - several seconds after it was generated. An estimate for this delay is given - in the \uicontrol {Processing delay} field. + several seconds after it was generated. \uicontrol {Processing delay} shows + an estimate of the delay. - Data is collected until you select the - \uicontrol {Stop collecting profile data} button or terminate the - application. + Data is collected until you select \inlineimage icons/recordfill.png + (\uicontrol {Stop collecting profile data}) or close the application. - Select the \uicontrol {Stop collecting profile data} button to disable the + Select \uicontrol {Stop collecting profile data} to turn off the automatic start of the data collection when an application is launched. - Profile data will still be generated, but \QC will discard it until you + Profile data is still generated, but \QC discards it until you select the button again. - \section1 Profiling Memory Usage on Devices + \section1 Profile memory usage on devices - To create trace points for profiling memory usage on a target device, select - \uicontrol Analyze > \uicontrol {Performance Analyzer Options} > - \uicontrol {Create Memory Trace Points} or select - \inlineimage icons/create-tracepoint.png - on the \uicontrol {Performance Analyzer} toolbar. + To create trace points for profiling memory usage on a target device: - In the \uicontrol {Create Memory Trace Points} dialog, you can modify the + \list + \li Go to \uicontrol Analyze > \uicontrol {Performance Analyzer Options} + > \uicontrol {Create Memory Trace Points}. + \li Select \inlineimage icons/create-tracepoint.png + on the \uicontrol {Performance Analyzer} toolbar. + \endlist + + In the \uicontrol {Create Memory Trace Points} dialog, modify the script to run. - \image qtcreator-performance-analyzer-create-memory-trace-points.png "Create Memory Trace Points dialog" + \image qtcreator-performance-analyzer-create-memory-trace-points.png {Create Memory Trace Points dialog} If you need root privileges to run scripts as root, select the privileges to - use in the \uicontrol {Elevate privileges using} field. + use in \uicontrol {Elevate privileges using}. Select \uicontrol OK to run the script. To add events for the trace points, see \l{Choosing Event Types}. - You can record a memory trace to view usage graphs in the samples rows of + Record a memory trace to view usage graphs in the samples rows of the timeline and to view memory allocations, peaks, and releases in the flame graph. - \section1 Specifying Performance Analyzer Settings + \section1 Generate separate debug info for qmake projects - To specify global settings for the Performance Analyzer, select - \preferences > \uicontrol Analyzer > - \uicontrol {CPU Usage}. For each run configuration, you can also - use specialized settings. Select \uicontrol Projects > \uicontrol Run, and - then select \uicontrol Details next to - \uicontrol {Performance Analyzer Settings}. + To manually set up a build configuration that generates debug symbols also + for applications compiled for release, edit the build settings of a qmake + project: - \image qtcreator-performance-analyzer-settings.png + \list 1 + \li Go to \uicontrol {Projects} > \uicontrol {Build Settings}. + \li In \uicontrol {Separate debug info}, select \uicontrol Enable. + \li Select \uicontrol Yes to recompile the project. + \endlist - To edit the settings for the current run configuration, you can also select - the dropdown menu next to the \uicontrol {Collect profile data} button. + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Performance Analyzer}, + {Analyzing Code} +*/ - \section2 Choosing Event Types +/*! + \page creator-cpu-usage-analyzer.html + \previouspage creator-reference.html - In the \uicontrol Events table, you can specify which events should trigger - the Performance Analyzer to take a sample. The most common way of analyzing + \ingroup creator-reference-analyzer + + \title Performance Analyzer + + \brief Analyze the CPU and memory usage of an application on Linux desktop + and embedded devices. + + To set global preferences for Performance Analyzer, go to \preferences > + \uicontrol Analyzer > \uicontrol {CPU Usage}. + + To set preferences for a particular run configuration, go to + \uicontrol Projects > \uicontrol Run, and then select \uicontrol Details + next to \uicontrol {Performance Analyzer Settings}. + + \image qtcreator-performance-analyzer-settings.png {Performance Analyzer Settings} + + To edit the settings for the current run configuration, select the + drop down menu next to \inlineimage icons/recordfill.png on the + Performance Analyzer toolbar. + + \image qtcreator-performance-analyzer-toolbar.png {Performance Analyzer toolbar} + + \section1 Choosing Event Types + + The events table lists the events that trigger Performance Analyzer to take + a sample. The most common way of analyzing CPU usage involves periodic sampling, driven by hardware performance counters that react to the number of instructions or CPU cycles executed. - Alternatively, a software counter that uses the CPU clock can be chosen. + You can also select a software counter that uses the CPU clock. Select \uicontrol {Add Event} to add events to the table. - In the \uicontrol {Event Type} column, you can choose the general type of + In \uicontrol {Event Type}, select the general type of event to be sampled, most commonly \uicontrol {hardware} or - \uicontrol {software}. In the \uicontrol {Counter} column, you can choose - which specific counter should be used for the sampling. For example, + \uicontrol {software}. In \uicontrol {Counter}, select the counter + for the sampling. For example, \uicontrol {instructions} in the \uicontrol {hardware} group or \uicontrol {cpu-clock} in the \uicontrol {software} group. More specialized sampling, for example by cache misses or cache hits, is - possible. However, support for it depends on specific features of the CPU - involved. For those specialized events, you can give more detailed sampling - instructions in the \uicontrol {Operation} and \uicontrol {Result} columns. - For example, you can choose a \uicontrol {cache} event for + possible. However, support for it depends on specific features of the CPU. + For those specialized events, give more detailed sampling + instructions in \uicontrol {Operation} and \uicontrol {Result}. + For example, select a \uicontrol {cache} event for \uicontrol {L1-dcache} on the \uicontrol {load} operation with a result - of \uicontrol {misses}. That would sample L1-dcache misses on reading. + of \uicontrol {misses} to sample L1-dcache misses on reading. Select \uicontrol {Remove Event} to remove the selected event from the table. @@ -145,29 +160,28 @@ Select \uicontrol {Use Trace Points} to replace the current selection of events with trace points defined on the target device and set the \uicontrol {Sample mode} to \uicontrol {event count} and the - \uicontrol {Sample period} to \c {1}. If the trace points on the target - were defined using the \uicontrol {Create Trace Points} option, the - Performance Analyzer will automatically use them to profile memory usage. + \uicontrol {Sample period} to \c {1}. If \uicontrol {Create Trace Points} + defines the trace points on the target, Performance Analyzer automatically + uses them to profile memory usage. - Select \uicontrol {Reset} to revert the selection of events, as well as the + Select \uicontrol {Reset} to revert the selection of events, as well as \uicontrol {Sample mode} and \uicontrol {Sample period} to the default values. - \section2 Choosing a Sampling Mode and Period + \section1 Choosing a Sampling Mode and Period - In the \uicontrol {Sample mode} and \uicontrol {Sample period} fields, you - can specify how samples are triggered: + In \uicontrol {Sample mode} and \uicontrol {Sample period}, specify how + samples are triggered: \list \li Sampling by \uicontrol {event count} instructs the kernel to take a sample every \c n times one of the chosen events has occurred, - where \c n is specified in the \uicontrol {Sample period} field. + where \c n is set in \uicontrol {Sample period}. \li Sampling by \uicontrol {frequency (Hz)} instructs the kernel to try and take a sample \c n times per second, by automatically adjusting the - sampling period. Specify \c n in the \uicontrol {Sample period} - field. + sampling period. Set \c n in \uicontrol {Sample period}. \endlist @@ -178,15 +192,15 @@ There may be a significant difference between the sampling period you request and the actual result. - In general, if you configure the Performance Analyzer to collect more data + In general, if you configure Performance Analyzer to collect more data than it can transmit over the connection between the target and the host device, the application may get blocked while Perf is trying to send the data, and the processing delay may grow excessively. You should then change - the \uicontrol {Sample period} or the \uicontrol {Stack snapshot size}. + the value of \uicontrol {Sample period} or \uicontrol {Stack snapshot size}. - \section2 Selecting Call Graph Mode + \section1 Selecting Call Graph Mode - In the \uicontrol {Call graph mode} field, you can specify how the + In \uicontrol {Call graph mode}, you can specify how Performance Analyzer recovers call chains from your application: \list @@ -210,32 +224,32 @@ Qt and most system libraries are compiled without frame pointers by default, so the frame pointer mode is only useful with customized systems. - \section2 Setting Stack Snapshot Size + \section1 Setting Stack Snapshot Size - The Performance Analyzer will analyze and \e unwind the stack snapshots - generated by Perf in dwarf mode. Set the size of the stack snapshots in the - \uicontrol {Stack snapshot size} field. Large stack snapshots result in a + Performance Analyzer analyzes and \e unwinds the stack snapshots + generated by Perf in dwarf mode. Set the size of the stack snapshots in + \uicontrol {Stack snapshot size}. Large stack snapshots result in a larger volume of data to be transferred and processed. Small stack snapshots may fail to capture call chains of highly recursive applications or other intense stack usage. - \section2 Adding Command-Line Options for Perf + \section1 Adding Command-Line Options for Perf - You can specify additional command-line options to be passed to Perf when - recording data in the \uicontrol {Additional arguments} field. You may want - to specify \c{--no-delay} or \c{--no-buffering} to reduce the processing + Set additional command-line options to pass to Perf when + recording data in \uicontrol {Additional arguments}. Set \c{--no-delay} + or \c{--no-buffering} to reduce the processing delay. However, those options are not supported by all versions of Perf and Perf may not start if an unsupported option is given. - \section2 Resolving Names for JIT-compiled JavaScript Functions + \section1 Resolving Names for JIT-compiled JavaScript Functions Since version 5.6.0, Qt can generate perf.map files with information about - JavaScript functions. The Performance Analyzer will read them and show the + JavaScript functions. Performance Analyzer will read them and show the function names in the \uicontrol Timeline, \uicontrol Statistics, and \uicontrol {Flame Graph} views. This only works if the process being profiled is running on the host computer, not on the target device. To switch on the generation of perf.map files, add the environment variable - \c QV4_PROFILE_WRITE_PERF_MAP to the \uicontrol {Run Environment} and set + \c QV4_PROFILE_WRITE_PERF_MAP to \uicontrol {Run Environment} and set its value to \c 1. \section1 Analyzing Collected Data @@ -243,36 +257,35 @@ The \uicontrol Timeline view displays a graphical representation of CPU usage per thread and a condensed view of all recorded events. - \image qtcreator-performance-analyzer-timeline.png "Performance Analyzer" + \image qtcreator-performance-analyzer-timeline.png {Performance Analyzer} Each category in the timeline describes a thread in the application. Move the cursor on an event (5) on a row to see how long it takes and which function in the source it represents. To display the information only when - an event is selected, disable the - \uicontrol {View Event Information on Mouseover} button (4). + an event is selected, turn off + \uicontrol {View Event Information on Mouseover} (4). The outline (9) summarizes the period for which data was collected. Drag the zoom range (7) or click the outline to move on the outline. You can - also move between events by selecting the - \uicontrol {Jump to Previous Event} and \uicontrol {Jump to Next Event} - buttons (1). + also move between events by selecting \uicontrol {Jump to Previous Event} + and \uicontrol {Jump to Next Event} (1). - Select the \uicontrol {Show Zoom Slider} button (2) to open a slider that - you can use to set the zoom level. You can also drag the zoom handles (8). + Select \uicontrol {Show Zoom Slider} button (2) to open a slider that + sets the zoom level. You can also drag the zoom handles (8). To reset the default zoom level, right-click the timeline to open the context menu, and select \uicontrol {Reset Zoom}. \section2 Selecting Event Ranges - You can select an event range (6) to view the time it represents or to zoom - into a specific region of the trace. Select the \uicontrol {Select Range} - button (3) to activate the selection tool. Then click in the timeline to + Select an event range (6) to view the time it represents or to zoom + into a specific region of the trace. Select \uicontrol {Select Range} + (3) to activate the selection tool. Then click in the timeline to specify the beginning of the event range. Drag the selection handle to define the end of the range. - You can use event ranges also to measure delays between two subsequent + Use event ranges also to measure delays between two subsequent events. Place a range between the end of the first event and the beginning - of the second event. The \uicontrol Duration field displays the delay + of the second event. \uicontrol Duration shows the delay between the events in milliseconds. To zoom into an event range, double-click it. @@ -294,10 +307,10 @@ events to move the cursor in the code editor to the part of the code the event is associated with. - As the Perf tool only collects periodic samples, the Performance Analyzer + As the Perf tool only collects periodic samples, Performance Analyzer cannot determine the exact time when a function was called or when it returned. You can, however, see exactly when a sample was taken in the - second row of each thread. The Performance Analyzer assumes that if the same + second row of each thread. Performance Analyzer assumes that if the same function is present at the same place in the call chain in multiple consecutive samples, then this represents a single call to the respective function. This is, of course, a simplification. Also, there may be other @@ -369,7 +382,7 @@ taken for a certain function, relative to the same aspect of all samples together. The nesting shows which functions were called by which other ones. - The \uicontrol {Visualize} button lets you choose what aspect to show in the + The \uicontrol {Visualize} button lets you select what aspect to show in the \uicontrol {Flame Graph}. \list @@ -396,7 +409,7 @@ \uicontrol {Releases} modes will only show any data if samples from memory trace points have been recorded. - \section2 Interaction between the views + \section2 Interaction between the Views When you select a stack frame in either of the \uicontrol {Timeline}, \uicontrol {Flame Graph}, or \uicontrol {Statistics} views, information @@ -415,7 +428,7 @@ \image qtcreator-cpu-usage-analyzer-load-perf-trace.png - The Performance Analyzer needs to know the context in which the + Performance Analyzer needs to know the context in which the data was recorded to find the debug symbols. Therefore, you have to specify the kit that the application was built with and the folder where the application executable is located. @@ -423,11 +436,11 @@ The Perf data files are generated by calling \c {perf record}. Make sure to generate call graphs when recording data by starting Perf with the \c {--call-graph} option. Also check that the necessary debug symbols are - available to the Performance Analyzer, either at a standard location + available to Performance Analyzer, either at a standard location (\c /usr/lib/debug or next to the binaries), or as part of the Qt package you are using. - The Performance Analyzer can read Perf data files generated in either frame + Performance Analyzer can read Perf data files generated in either frame pointer or dwarf mode. However, to generate the files correctly, numerous preconditions have to be met. All system images for the \l{https://doc.qt.io/Boot2Qt/qtdc-supported-platforms.html} @@ -447,11 +460,11 @@ \section1 Troubleshooting - The Performance Analyzer might fail to record data for the following reasons: + Performance Analyzer might fail to record data for the following reasons: \list \li Perf events may be globally disabled on your system. - The preconfigured \l Boot2Qt images come with perf events enabled. + The preconfigured \l Boot2Qt images come with Perf events enabled. For a custom configuration you need to make sure that the file \c {/proc/sys/kernel/perf_event_paranoid} contains a value smaller than \c {2}. For maximum flexibility in recording traces you can @@ -471,16 +484,16 @@ the values of the \uicontrol {Stack snapshot size} or \uicontrol {Sample period} settings. \li Perf may be buffering the data forever, never sending it. Add - \c {--no-delay} or \c {--no-buffering} to the - \uicontrol {Additional arguments} field. + \c {--no-delay} or \c {--no-buffering} to + \uicontrol {Additional arguments}. \li Some versions of Perf will not start recording unless given a - certain minimum sampling frequency. Try with a - \uicontrol {Sample period} value of 1000. + certain minimum sampling frequency. Try setting + \uicontrol {Sample period} to 1000. \li On some devices, in particular various i.MX6 Boards, the hardware performance counters are dysfunctional and the Linux kernel may randomly fail to record data after some time. Perf can use different types of events to trigger samples. You can get a list of available - event types by running \c {perf list} on the device and then choose + event types by running \c {perf list} on the device and then select the respective event types in the settings. The choice of event type affects the performance and stability of the sampling. The \c {cpu-clock} \c {software} event is a safe but relatively slow @@ -489,8 +502,7 @@ reboot the device. The kernel may have disabled important parts of the performance counters system. \li Perf might not be installed. The way to install it depends on your - Linux distribution. For example, you might try the following - commands: + Linux distribution. For example, try the following commands: \list \li On Ubuntu 22.04: @@ -506,5 +518,5 @@ The \l {Application Output} view shows some information even if the Performance Analyzer displays error messages. - \sa {Profile function execution} + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code} */ diff --git a/doc/qtcreator/src/analyze/creator-analyze.qdoc b/doc/qtcreator/src/analyze/creator-analyze.qdoc index 75855716e71..d36ab81ab8f 100644 --- a/doc/qtcreator/src/analyze/creator-analyze.qdoc +++ b/doc/qtcreator/src/analyze/creator-analyze.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2023 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -17,66 +17,139 @@ To use a code analysis tool, select it in the \uicontrol {Analyze Menu} or in the pull-down menu of the \inlineimage icons/qtcreator-debug-button.png (\uicontrol {Start Debugging of Startup Project}) button. - When you are in the \uicontrol Debug mode, you can switch between tools by - selecting them in the menu on the debugger toolbar. + In the \uicontrol Debug mode, switch between tools by selecting them in the + menu on the debugger toolbar. - You can drag and drop the views in the \uicontrol Debug mode to new + \image qtcreator-performance-analyzer-toolbar.png {Performance Analyzer in Debug mode} + + Drag the views in the \uicontrol Debug mode to new positions on the screen. The size and position of views are saved for future sessions. Select \uicontrol View > \uicontrol Views > \uicontrol {Reset to Default Layout} to reset the views to their original sizes and positions. - You can use the following code analysis tools in the \uicontrol Debug - mode: + \section1 Improving QML Performance + + \QC comes with the \l{Profiling QML Applications}{QML Profiler} for + inspecting binding evaluations and signal handling when running QML code. + This is useful for identifying potential bottlenecks, especially in the + evaluation of bindings. + + \section1 Finding Issues in QML Code + + Run \l{JavaScript and QML Checks}{static checks} on the QML and JavaScript + code in your project to find common problems, similarly to using + \l{http://www.jslint.com}{JSLint}. + + \section1 Finding Issues in C++ Code with Clang Tools + + \QC comes with the following Clang tools for finding problems in C, C++, and + Objective-C source code by using static analysis: \list - - \li \l{Profiling QML Applications}{QML Profiler} - - Inspect binding evaluations, signal handling, and - painting operations when running QML code. This is useful for - identifying potential bottlenecks, especially in the evaluation - of bindings. - - \li \l{Checking Code Coverage}{Coco} - - Analyze the way an application runs as part of a test suite, for - example, and use the results to make the tests more efficient and - complete. - - \li \l{Prevent code erosion}{Axivion} - - Do static code analysis and architecture analysis to detect and - eliminate unnecessary complexity of code. - - \li \l{Clang Tools} - - Detect problems in C, C++, and Objective-C programs by - using Clang-Tidy and Clazy. - - \li \l{Detecting Memory Leaks with Heob}{Heob} - - Use the Heob heap observer on Windows to detect buffer - overruns and memory leaks. - - \li \l{Analyzing CPU Usage}{Performance Analyzer} - - Analyze the CPU usage of embedded applications and Linux - desktop applications with the Performance Analyzer that integrates - the Linux Perf tool. - - \li \l{Analyzing Code with Cppcheck}{Cppcheck} - - Use the experimental Cppcheck plugin to detect undefined - behavior and dangerous coding constructs. - - \li \l{Visualizing Chrome Trace Events}{Chrome Trace Format Visualizer} - - Use the Chrome Trace Format (CTF) Visualizer to view - Chrome trace events. This is especially useful when viewing - large trace files that are difficult to visualize using the - built-in trace-viewer (\c{chrome://tracing}). + \li \l{https://clang.llvm.org/extra/clang-tidy/}{Clang-Tidy}, which + has diagnostics and fixes for typical programming errors, + such as style violations or interface misuse. + \li \l{https://github.com/KDE/clazy/blob/master/README.md}{Clazy}, which + helps Clang understand Qt semantics. It displays Qt-related compiler + warnings, ranging from unnecessary memory allocation to misuse of + API and has refactoring actions for fixing some of the issues. \endlist - \sa {Detect memory leaks with Memcheck}, {Profile function execution} + \section1 Finding Issues in C++ Code with Cppcheck + + Install the \l{http://cppcheck.sourceforge.net/}{Cppcheck} static analysis + tool to detect undefined behavior and dangerous coding constructs in + C++ code. Cppcheck analyzes the source code without actually running the + application. + + \section1 Checking Code Coverage + + Install the \l{https://doc.qt.io/coco/}{Coco} code coverage tool chain for + Tcl, QML, C# and C/C++ programs on \macOS, Linux, or Windows to analyze the + way an application runs as part of a test suite, for example. Use the + results to make the tests more efficient and complete. + + You can: + + \list + \li Find untested code sections. + \li Find redundant tests which can then be eliminated. Coco can + identify portions of the source code that are covered by a test. It + can detect whether a new test covers lines in the source code that + the existing tests do not cover. + \li Find dead code by displaying code that is never executed. + \li Calculate the optimum test execution order so as to maximize + test coverage for each run. This is particularly useful for manual + testing. + \li Analyze two separate versions of an application and compare the + differences. This makes it possible to see which tests are affected + by source code modifications and also to get some measure of the + test coverage of a patch or hot fix. + \li Measure the execution time of applications and tests. + \endlist + + \section1 Preventing Code Erosion + + Install \l{https://www.axivion.com/en/products/axivion-suite/}{Axivion Suite} + to protect software from erosion. With static code analysis, + architecture analysis, and code-smells-detection, you can: + + \list + \li Check the source code for potential runtime errors. + \li Use metrics to generate quantitative information about the + internal quality of the source code. + \li Run style checks to achieve compliance with coding guidelines. + \li Detect both duplicates and similar pieces of code in the source code. + \li Recognize cyclical dependencies at different levels. + \li Detect unreachable code. + \endlist + + \section1 Profiling with Valgrind Tools + + Install Memcheck and Callgrind from \l{Valgrind's Tool Suite} to detect + memory leaks and profile function execution. + + You can run the Valgrind tools either \e locally on the development host or + \e remotely on another host. You can use them to analyze both applications + for which you set up a project in \QC and applications for which you do not + have a project. + + Valgrind tools are supported locally only on Linux and \macos. However, + according to Valgrind.org, support on \macos 10.8 and 10.9 is experimental and + mostly broken. You can run the tools on a remote Linux machine or device + from any development host. + + To run the Valgrind tools to analyze an application for which you have a + project, open the project in \QC and select the kit to run the project. The + kit specifies whether the Valgrind tools are run locally or remotely. + + For more information about analyzing applications for which you do not have + a project, see \l{Run Valgrind tools on external applications}. + + To set preferences for the Valgrind tools, select \preferences > + \uicontrol Analyzer. You can override the general + settings for each project in the \uicontrol {Run Settings} for the project. + + \section1 Detecting Memory Leaks with Heob + + On Windows, install the \l{https://github.com/ssbssa/heob}{Heob} + heap observer to detect buffer overruns and memory leaks. + + \section1 Analyzing CPU Usage + + On Linux, use Perf to analyze the CPU and memory usage of an application + on Linux desktop and embedded devices. + + \l{Performance Analyzer} uses the Perf tool bundled with the Linux kernel to + take periodic snapshots of the call chain of an application and visualizes + them in a timeline view or as a flame graph. + + \section1 Visualizing Chrome Trace Events + + Use the \l{Chrome Trace Format Visualizer} to view Chrome trace events. This + is especially useful when viewing large trace files that are difficult to + visualize using the built-in trace-viewer (\c{chrome://tracing}). + + \sa {Analyze}{How To: Analyze}, {Analyzers} */ diff --git a/doc/qtcreator/src/analyze/creator-axivion.qdoc b/doc/qtcreator/src/analyze/creator-axivion.qdoc index ddfbcdf288f..9a827f7bb4d 100644 --- a/doc/qtcreator/src/analyze/creator-axivion.qdoc +++ b/doc/qtcreator/src/analyze/creator-axivion.qdoc @@ -9,20 +9,6 @@ \title Prevent code erosion - \l{https://www.axivion.com/en/products/axivion-suite/}{Axivion Suite} is - a tool suite for protecting software from erosion. With static code analysis, - architecture analysis, and code-smells-detection, you can: - - \list - \li Check the source code for potential runtime errors. - \li Use metrics to generate quantitative information about the - internal quality of the source code. - \li Run style checks to achieve compliance with coding guidelines. - \li Detect both duplicates and similar pieces of code in the source code. - \li Recognize cyclical dependencies at different levels. - \li Detect unreachable code. - \endlist - Connect to an Axivion dashboard server from \QC to view results of code analysis. @@ -132,8 +118,9 @@ select the link in the details or in the \uicontrol {Right Path} or \uicontrol {Target Path} column. - \sa {Enable and disable plugins}, {Link projects to Axivion dashboards}, - {Axivion} + \sa {Enable and disable plugins}, {Analyze}{How To: Analyze}, + {Link projects to Axivion dashboards}, {Analyzers}, {Axivion}, + {Analyzing Code} */ /*! diff --git a/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc b/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc index c85fd7356de..be7eda671df 100644 --- a/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc +++ b/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc @@ -15,22 +15,6 @@ \title Analyze code with Clang-Tidy and Clazy - \QC comes with the following Clang tools for finding problems in C, C++, and - Objective-C source code by using static analysis: - - \list - - \li \l{https://clang.llvm.org/extra/clang-tidy/}{Clang-Tidy}, which - has diagnostics and fixes for typical programming errors, - such as style violations or interface misuse. - - \li \l{https://github.com/KDE/clazy/blob/master/README.md}{Clazy}, which - helps Clang understand Qt semantics. It displays Qt related compiler - warnings, ranging from unnecessary memory allocation to misuse of - API and has refactoring actions for fixing some of the issues. - - \endlist - \note The Clang static analyzer checks are a part of Clang-Tidy. To use the checks, you must create a custom configuration for the Clang tools and enable them for Clang-Tidy. @@ -107,7 +91,8 @@ using the \c {-export fixes} option. \sa {Check code syntax}, {Configure Clang Diagnostics}, - {Specify Clang tools settings}, {Clang Tools} + {Analyze}{How To: Analyze}, {Specify Clang tools settings}, {Analyzers}, + {Clang Tools} */ /*! diff --git a/doc/qtcreator/src/analyze/creator-coco.qdoc b/doc/qtcreator/src/analyze/creator-coco.qdoc index 341db9fc096..4b1337e1238 100644 --- a/doc/qtcreator/src/analyze/creator-coco.qdoc +++ b/doc/qtcreator/src/analyze/creator-coco.qdoc @@ -2,72 +2,46 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-qml-performance-monitor.html \page creator-coco.html - \nextpage creator-axivion.html + \previouspage creator-how-tos.html - \title Checking Code Coverage + \ingroup creator-how-to-analyze - \l{https://doc.qt.io/coco/}{Coco} is a complete code coverage tool chain for - Tcl, QML, C# and C/C++ programs, which runs on \macOS, Linux, and Windows. + \title Check code coverage - Coco analyzes the way an application runs, as part of a test suite, - for example. The results enable you to make the tests more efficient and - complete. - - You can: - - \list - \li Find untested code sections. - \li Find redundant tests which can then be eliminated. Coco can - identify portions of the source code that are covered by a test. It - can detect whether a new test covers lines in the source code that - the existing tests do not cover. - \li Find dead code by displaying code that is never executed. - \li Calculate the optimum test execution order so as to maximize - test coverage for each run. This is particularly useful for manual - testing. - \li Analyze two separate versions of an application and compare the - differences. This makes it possible to see which tests are affected - by source code modifications and also to get some measure of the - test coverage of a patch or hot fix. - \li Measure the execution time of applications and tests. - \endlist - - The experimental Coco plugin integrates Coco CoverageBrowser into \QC. - It enables you to analyze the test coverage by loading an instrumentation - database (a .csmes file), which was generated by Coco CoverageScanner. - It is currently supported only on Windows, with Coco version 6.0, - or later. + With Coco CoverageBrowser, you can analyze the test coverage by loading an + instrumentation database (a .csmes file), which was generated by Coco + CoverageScanner. The experimental Coco plugin is currently supported only on + Windows, with Coco version 6.0, or later. To use the plugin, you must download and install Coco. \note Enable the Coco plugin to use it. - \section1 Configuring Coco + \section1 Configure Coco \list 1 - \li Select \uicontrol Analyze > \uicontrol {Squish Coco}. - \image qtcreator-coco.png "Coco CoverageBrowser and CSMes file" + \li Go to \uicontrol Analyze > \uicontrol {Squish Coco}. + \image qtcreator-coco.png {Coco CoverageBrowser and CSMes file} \li In \uicontrol {CoverageBrowser}, enter the path to the Coco coverage browser to use for analyzing a .csmes file. \li In \uicontrol CSMes, select the instrumentation database to load. \li Select \uicontrol Open to start CoverageBrowser. - \li In CoverageBrowser, select \uicontrol File > + \li In CoverageBrowser, go to \uicontrol File > \uicontrol {Load Execution Report} and select the .csexe for the coverage scan. - \image coco-coveragebrowser-load-execution-report.png "Load Execution Report dialog" - \li If you want to reuse the execution report, deselect the - \uicontrol {Delete execution report after loading} check box. + \image coco-coveragebrowser-load-execution-report.png {Load Execution Report dialog} + \li To keep the execution report, clear + \uicontrol {Delete execution report after loading}. \endlist - Open the analyzed files in \QC. The results of the analysis are displayed + Open the analyzed files in \QC. You can see the results of the analysis after the code in \uicontrol Edit mode. You can change the fonts and colors used for different types of results. \section1 Changing Fonts and Colors - To change the default fonts and colors, select \preferences > + To change the default fonts and colors, go to \preferences > \uicontrol {Text Editor} > \uicontrol {Font & Colors}. Create your own color scheme and select new fonts and colors for the following results: @@ -85,5 +59,6 @@ \li Implicit Manual Coverage Validation \endlist - \sa {Enable and disable plugins}, {Font & Colors} + \sa {Enable and disable plugins}, {Analyze}{How To: Analyze}, {Analyzers}, + {Font & Colors}, {Analyzing Code} */ diff --git a/doc/qtcreator/src/analyze/creator-cppcheck.qdoc b/doc/qtcreator/src/analyze/creator-cppcheck.qdoc index e3cc393d705..6f34cd5180a 100644 --- a/doc/qtcreator/src/analyze/creator-cppcheck.qdoc +++ b/doc/qtcreator/src/analyze/creator-cppcheck.qdoc @@ -1,58 +1,51 @@ -// Copyright (C) 2020 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-cpu-usage-analyzer.html \page creator-cppcheck.html - \nextpage creator-ctf-visualizer.html + \previouspage creator-how-tos.html - \title Analyzing Code with Cppcheck + \ingroup creator-how-to-analyze - \l{http://cppcheck.sourceforge.net/}{Cppcheck} is a static analysis tool - that detects errors in C++ code. Static analysis is performed on the source - code without actually executing the application. + \title Detect errors in C++ code with Cppcheck - The experimental Cppcheck Diagnostics plugin integrates diagnostics - that are generated by the Cppcheck tool into the C++ editor. - - \note Enable the Cppcheck plugin to use it. + Enable the experimental Cppcheck plugin to view diagnostics that are + generated by the Cppcheck tool in the C++ editor. Cppcheck is automatically run on open files. To select the files to - check in the currently active project, select \uicontrol Analyze > + check in the currently active project, go to \uicontrol Analyze > \uicontrol Cppcheck. - - \section1 Running Cppcheck on Selected Files + \section1 Analyze selected files \list 1 - \li Select \uicontrol Analyze > \uicontrol Cppcheck. - \image qtcreator-cppcheck-run-configuration.png "Cppcheck run configuration" - \li In the \uicontrol Binary field, enter the path to the Cppcheck - executable file. - \li In the \uicontrol Checks group, select the checks to perform. + \li Go to \uicontrol Analyze > \uicontrol Cppcheck. + \image qtcreator-cppcheck-run-configuration.png {Cppcheck run configuration} + \li In uicontrol Binary, enter the path to the Cppcheck executable file. + \li In \uicontrol Checks, select the checks to perform. \note By default, Cppcheck uses multiple threads to perform checks. - Selecting the \uicontrol {Unused functions} option disables the - default behavior. - \li In the \uicontrol {Custom arguments} field, enter additional + Select \uicontrol {Unused functions} to turn off the default + behavior. + \li In \uicontrol {Custom arguments}, enter additional arguments for running Cppcheck. The arguments might be shadowed by automatically generated ones. To avoid possible conflicts in - configuration, select the \uicontrol {Show raw output} check box - to see the final arguments. - \li In the \uicontrol {Ignored file patterns} field, enter a filter + configuration, select \uicontrol {Show raw output} and check the + final arguments. + \li In \uicontrol {Ignored file patterns}, enter a filter for ignoring files that match the pattern (wildcard). You can enter multiple patterns separated by commas. Even though Cppcheck is not run on files that match the patterns, they might be implicitly checked if other files include them. - \li Select the \uicontrol {Inconclusive errors} check box to also - mark possible false positives. - \li Select the \uicontrol {Check all define combinations} check box to - check all define combinations. Enabling this option can significantly + \li Select \uicontrol {Inconclusive errors} to also mark possible false + positives. + \li Select \uicontrol {Check all define combinations} to + check all define combinations. This can significantly slow down analysis, but might help to find more issues. - \li Select the \uicontrol {Add include paths} check box to pass the - current project's include paths to Cppcheck. Enabling this option + \li Select \uicontrol {Add include paths} to pass the + current project's include paths to Cppcheck. This slows down checks on big projects, but can help Cppcheck to find missing includes. - \li Select the \uicontrol {Calculate additional arguments} check box to + \li Select \uicontrol {Calculate additional arguments} to calculate additional arguments based on current project's settings (such as the language used and standard version) and pass them to Cppcheck. @@ -64,8 +57,9 @@ marks or annotations. To specify the settings above for the automatically run checks, - select \preferences > \uicontrol Analyzer + go to \preferences > \uicontrol Analyzer > \uicontrol Cppcheck. - \sa {Enable and disable plugins} + \sa {Enable and disable plugins}, {Analyze}{How To: Analyze}, + {Analyzing Code}, {Analyzers} */ diff --git a/doc/qtcreator/src/analyze/creator-ctf-visualizer.qdoc b/doc/qtcreator/src/analyze/creator-ctf-visualizer.qdoc index a2bf118f3fb..16031b8f6ae 100644 --- a/doc/qtcreator/src/analyze/creator-ctf-visualizer.qdoc +++ b/doc/qtcreator/src/analyze/creator-ctf-visualizer.qdoc @@ -8,11 +8,14 @@ // ********************************************************************** /*! - \previouspage creator-cppcheck.html \page creator-ctf-visualizer.html - \nextpage creator-autotest.html + \previouspage creator-reference.html - \title Visualizing Chrome Trace Events + \ingroup creator-reference-analyzer + + \title Chrome Trace Format Visualizer + + \brief Visualize Chrome trace events generated in Chrome Trace Format (CTF). You can use \e {full stack tracing} to trace from the top level QML or JavaScript down to the C++ and all the way to the kernel space. This @@ -218,4 +221,6 @@ \code ctf2ctf -o trace.json path/to/lttng trace/ \endcode + + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code} */ diff --git a/doc/qtcreator/src/analyze/creator-heob.qdoc b/doc/qtcreator/src/analyze/creator-heob.qdoc index 449d3cc86ab..45f2b269ed6 100644 --- a/doc/qtcreator/src/analyze/creator-heob.qdoc +++ b/doc/qtcreator/src/analyze/creator-heob.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2020 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -8,17 +8,15 @@ // ********************************************************************** /*! + \page creator-how-to-use-heob.html \previouspage creator-clang-tools.html - \page creator-heob.html - \nextpage creator-cpu-usage-analyzer.html - \title Detecting Memory Leaks with Heob + \ingroup creator-how-to-analyze - \QC integrates the \l{https://github.com/ssbssa/heob}{Heob} heap observer - for detecting buffer overruns and memory leaks. You must download and - install Heob to run it from \QC. + \title Detect memory leaks with Heob - \image qtcreator-heob-settings.png + On Windows, use the Heob heap observer to detect buffer overruns and memory + leaks. To run Heob on the currently open project: @@ -26,35 +24,48 @@ \li Select \uicontrol Analyze > \uicontrol Heob. + \image qtcreator-heob-settings.png {Heob settings} + \li Select the Heob settings profile to use, or select \uicontrol New to create a new profile. - \li In the \uicontrol {Heob path} field, enter the path to the Heob + \li In \uicontrol {Heob path}, enter the path to the Heob executable. - \li Specify additional settings for running the checks. For more - information about the available options, see - \l{Specifying Heob Settings}. + \li Specify \l{Heob}{settings} for running the checks. \li Select \uicontrol OK to run Heob. \endlist - \QC runs the application, and then it runs Heob in a console window. + \QC runs the application, and then it runs Heob in a terminal. - \image qtcreator-heob.png + \image qtcreator-heob-in-terminal.webp {Heob running in a terminal} Heob raises an access violation on buffer overruns and records stack traces - of the offending instruction and buffer allocation. The results are - displayed when Heob exits normally. + of the offending instruction and buffer allocation. You can see the results + in the \uicontrol Memcheck view after Heob exits normally. - \image qtcreator-heob-output.png + \image qtcreator-heob-output.png {Results from Heob in the Memcheck view} - \section1 Specifying Heob Settings + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Heob}, {Analyzing Code} +*/ - To specify settings for Heob, select \uicontrol Analyze > \uicontrol Heob. +/*! + \page creator-heob.html + \previouspage creator-reference.html - In the \uicontrol {Extra arguments} field, enter additional arguments for + \ingroup creator-reference-analyzer + + \title Heob + + \brief Detect memory leaks with Heob. + + To specify settings for Heob, go to \uicontrol Analyze > \uicontrol Heob. + + \image qtcreator-heob-settings.png {Heob settings} + + In \uicontrol {Extra arguments}, enter additional arguments for running Heob. To list the available arguments in the Heob console, enter \c -H in this field and press \key Enter. @@ -63,19 +74,19 @@ leaks visually in the file and the \c -L1024 option to record leak contents up to 1024 bytes in the file. For example, \c {-oleaks.html -g2 -L1024} - To save the settings profile, select \uicontrol Save. + To save your changes as default settings, select + \inlineimage icons/savefile.png. To remove a customized settings profile, select the profile, and then select \uicontrol Delete. The following sections describe the available options in more detail. - \section2 Recording Results + \section1 Recording Results The results of the checks are displayed in the \uicontrol Memcheck view and - recorded in a file. You can specify the file name in the - \uicontrol {XML output file} field. Heob creates the file in the project - directory. + recorded in a file. Specify the file name in \uicontrol {XML output file}. + Heob creates the file in the project directory. You can use the process identifier (PID) as a variable in the file name. For example, \c leaks-%p.xml. This injects Heob into the child processes, @@ -87,9 +98,9 @@ If you use variables, \QC cannot open the file automatically, but you can open it from the project directory. - \section2 Handling Exceptions + \section1 Handling Exceptions - In the \uicontrol {Handle exceptions} list, select \uicontrol Off to use the + In \uicontrol {Handle exceptions}, select \uicontrol Off to use the standard exception handler and have the debugger automatically attached if the application crashes. This works only if you register \QC is as a post-mortem debugger by selecting \preferences > @@ -105,7 +116,7 @@ crash is displayed. Therefore, this option is mostly useful when using Heob on the console or running it for child processes, as well. - \section2 Raising Exceptions on Errors + \section1 Raising Exceptions on Errors Select the \uicontrol {Raise breakpoint exception on error} check box to display errors when the application runs. @@ -119,9 +130,9 @@ This is mostly useful when used with the \uicontrol {Run with debugger} option, which runs Heob under the debugger. - \section2 Protecting Pages + \section1 Protecting Pages - In the \uicontrol {Page protection} list, select \uicontrol Off to use + In \uicontrol {Page protection}, select \uicontrol Off to use standard memory allocation functions and enable only memory leak detection. Select \uicontrol After to place a protected page at the end of each @@ -135,9 +146,9 @@ useful for \e use-after-free and \e double-free detection. However, the available memory address space can run out fast for 32-bit programs. - \section2 Handling Leak Data + \section1 Handling Leak Data - In the \uicontrol {Leak details} list, determine how to handle the + In \uicontrol {Leak details}, determine how to handle the collected leak data when the process exits. Selecting \uicontrol None means that no leak data is collected. If you activate leak type detection, Heob might need more time to collect the data when the process exits. @@ -163,10 +174,10 @@ block. Select \uicontrol {Detect Leak Types (Show Reachable)} to also record the reachable blocks in the results file. - In the \uicontrol {Minimum leak size} list, select the size of + In \uicontrol {Minimum leak size}, select the size of leaks to detect in bytes. - In the \uicontrol {Control leak recording} list, select \uicontrol Off to + In \uicontrol {Control leak recording}, select \uicontrol Off to record all leaks. You cannot change leak recording while it is running. To start Heob without starting leak recording, select @@ -177,4 +188,7 @@ To start leak recording when Heob starts and still have the option to control the recording, select \uicontrol {On (Start Enabled)}. + + \sa {Detect memory leaks with Heob}, {Analyze}{How To: Analyze}, {Analyzers}, + {Analyzing Code} */ diff --git a/doc/qtcreator/src/analyze/creator-valgrind.qdoc b/doc/qtcreator/src/analyze/creator-valgrind.qdoc index c46953803e9..d044e581199 100644 --- a/doc/qtcreator/src/analyze/creator-valgrind.qdoc +++ b/doc/qtcreator/src/analyze/creator-valgrind.qdoc @@ -81,10 +81,10 @@ For more information about using Memcheck, see \l{Interpreting Memcheck's Output} in the Valgrind documentation. - \sa {Profile function execution}, + \sa {Analyze}{How To: Analyze}, {Profile function execution}, {Run Valgrind tools on external applications}, - {Specify Valgrind settings for a project}, {Valgrind Callgrind}, - {Valgrind Memcheck} + {Specify Valgrind settings for a project}, {Analyzers}, {Valgrind Callgrind}, + {Valgrind Memcheck}, {Analyzing Code} */ /*! diff --git a/doc/qtcreator/src/cmake/creator-how-to-profile-cmake-code.qdoc b/doc/qtcreator/src/cmake/creator-how-to-profile-cmake-code.qdoc index fc8cdd122cd..a0f7b06c250 100644 --- a/doc/qtcreator/src/cmake/creator-how-to-profile-cmake-code.qdoc +++ b/doc/qtcreator/src/cmake/creator-how-to-profile-cmake-code.qdoc @@ -19,5 +19,5 @@ \image qtcreator-cmake-profiler.webp {CMake profiling information in Chrome Trace Format Visualizer} - \sa {CMake}, {Visualizing Chrome Trace Events} + \sa {CMake}, {Chrome Trace Format Visualizer} */ diff --git a/doc/qtcreator/src/editors/creator-code-syntax.qdoc b/doc/qtcreator/src/editors/creator-code-syntax.qdoc index 5a383f9df8d..e2888c25ca3 100644 --- a/doc/qtcreator/src/editors/creator-code-syntax.qdoc +++ b/doc/qtcreator/src/editors/creator-code-syntax.qdoc @@ -9,7 +9,7 @@ \previouspage creator-how-tos.html \endif - \ingroup creator-how-to-edit + \ingroup creator-how-to-analyze \ingroup studio-how-to-code \title Check code syntax @@ -79,11 +79,11 @@ If you hide the annotations, you can move the mouse pointer over an icon to view them. - \if defined(qtcreator) - \sa {Analyze code with Clang-Tidy and Clazy} - \endif - \sa {JavaScript and QML Checks} + + \if defined(qtcreator) + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code} + \endif */ /*! @@ -766,6 +766,10 @@ \uicontrol {Reset Code Model}. \sa {Check code syntax}, {Using QML Modules with Plugins} + + \if defined(qtcreator) + \sa {Analyzing Code} + \endif */ /*! diff --git a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc index a1d755a3b65..79dd9aebed3 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc @@ -244,18 +244,18 @@ For more information, see \l{Debugging}. - \section1 Analyzing Source Code + \section1 Finding Issues in Source Code Devices have limited memory and CPU power, so you should use them carefully. \QC integrates code analysis tools for detecting memory leaks, profiling function execution, analyzing CPU use, and eliminating unnecessary complexity of code. Other tools provide code coverage and visualize trace events. - Install and configure the tools on your system to use them from \QC. - However, the QML Profiler is installed as part of \QC for profiling - Qt Quick applications. + Some tools, such as the QML Profiler and the Clang Tools, are installed with + \QC. Install and configure the other supported tools on the computer to use + them from \QC. - For more information, see \l{Analyzing Code}. + For more information, see \l{Analyzing Code} and \l{Analyze}{How To: Analyze}. \section1 Running Tests diff --git a/doc/qtcreator/src/projects/creator-only/creator-build-settings-qmake.qdoc b/doc/qtcreator/src/projects/creator-only/creator-build-settings-qmake.qdoc index 3f24273f09c..78eb3ecf689 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-build-settings-qmake.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-build-settings-qmake.qdoc @@ -51,7 +51,7 @@ If debug info is being generated, you can have it placed into separate files, rather than embedded into the binary, by selecting \uicontrol Enable in the \uicontrol {Separate debug info} field. For - more information, see \l{Using the Performance Analyzer}. To use default + more information, see \l{Analyze CPU usage}. To use default settings, select \uicontrol {Leave at Default}. \section1 Compiling QML diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build-qbs.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build-qbs.qdoc index f1b08ac048a..372a895f6e8 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build-qbs.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build-qbs.qdoc @@ -30,7 +30,7 @@ If debug info is being generated, you can have it placed into separate files, rather than embedded into the binary, by selecting \uicontrol Enable in the \uicontrol {Separate debug info} field. For - more information, see \l{Using the Performance Analyzer}. To use default + more information, see \l{Analyze CPU usage}. To use default settings, select \uicontrol {Leave at Default}. For more information about the QML debugging options, see diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index 0ce410b39e4..af45da8230b 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -73,14 +73,6 @@ \li \l{Troubleshooting Debugger} \endlist \li \l{Analyzing Code} - \list - \li \l{Profiling QML Applications} - \li \l{Checking Code Coverage} - \li \l{Detecting Memory Leaks with Heob} - \li \l{Analyzing CPU Usage} - \li \l{Analyzing Code with Cppcheck} - \li \l{Visualizing Chrome Trace Events} - \endlist \endlist \li \l{Tutorials} \generatelist creator-tutorials @@ -136,6 +128,8 @@ \li \l{Reference} \generatelist creator-reference \list + \li Analyzers + \generatelist creator-reference-analyzer \li Build Systems \generatelist creator-reference-build-systems \list diff --git a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc b/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc index 4a9aa52da4e..e776d47ba5d 100644 --- a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc +++ b/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc @@ -13,12 +13,15 @@ \previouspage creator-qml-debugging-example.html \nextpage studio-advanced.html \else - \previouspage creator-analyze-mode.html - \nextpage creator-coco.html + \previouspage creator-reference.html \endif + \ingroup creator-reference-analyzer + \title Profiling QML Applications + \brief Improve the performance of QML applications. + You can use the QML Profiler to find causes for typical performance problems in your applications, such as slowness and unresponsive, stuttering user interfaces. Typical causes include executing too much JavaScript in too few @@ -54,7 +57,7 @@ You can use \e {full stack tracing} to trace from the top level QML or JavaScript down to the C++ and all the way to the kernel space. You can - view the collected data in the \l{Visualizing Chrome Trace Events} + view the collected data in the \l{Chrome Trace Format Visualizer} {Chrome Trace Format Viewer}. \endif From f4d5eadcee79faedce501069700b9a3eae87468f Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Fri, 12 Apr 2024 14:33:16 +0200 Subject: [PATCH 0159/1060] Lua: Add Lua and sol2 3rdparty libraries Change-Id: I8960445bb579242a676daf9dcf7f99251de2b201 Reviewed-by: Alessandro Portale --- qt_attributions.json | 28 + src/libs/3rdparty/CMakeLists.txt | 2 + src/libs/3rdparty/lua/CMakeLists.txt | 40 + src/libs/3rdparty/lua/LICENSE | 16 + src/libs/3rdparty/lua/README | 6 + src/libs/3rdparty/lua/doc/contents.html | 678 + src/libs/3rdparty/lua/doc/index.css | 21 + src/libs/3rdparty/lua/doc/logo.gif | Bin 0 -> 9893 bytes src/libs/3rdparty/lua/doc/lua.1 | 155 + src/libs/3rdparty/lua/doc/lua.css | 161 + src/libs/3rdparty/lua/doc/luac.1 | 118 + src/libs/3rdparty/lua/doc/manual.css | 21 + src/libs/3rdparty/lua/doc/manual.html | 12046 +++++++ .../3rdparty/lua/doc/osi-certified-72x60.png | Bin 0 -> 3774 bytes src/libs/3rdparty/lua/doc/readme.html | 337 + src/libs/3rdparty/lua/src/lapi.c | 1463 + src/libs/3rdparty/lua/src/lapi.h | 52 + src/libs/3rdparty/lua/src/lauxlib.c | 1112 + src/libs/3rdparty/lua/src/lauxlib.h | 301 + src/libs/3rdparty/lua/src/lbaselib.c | 549 + src/libs/3rdparty/lua/src/lcode.c | 1871 + src/libs/3rdparty/lua/src/lcode.h | 104 + src/libs/3rdparty/lua/src/lcorolib.c | 210 + src/libs/3rdparty/lua/src/lctype.c | 64 + src/libs/3rdparty/lua/src/lctype.h | 101 + src/libs/3rdparty/lua/src/ldblib.c | 483 + src/libs/3rdparty/lua/src/ldebug.c | 924 + src/libs/3rdparty/lua/src/ldebug.h | 63 + src/libs/3rdparty/lua/src/ldo.c | 1024 + src/libs/3rdparty/lua/src/ldo.h | 88 + src/libs/3rdparty/lua/src/ldump.c | 230 + src/libs/3rdparty/lua/src/lfunc.c | 294 + src/libs/3rdparty/lua/src/lfunc.h | 64 + src/libs/3rdparty/lua/src/lgc.c | 1739 + src/libs/3rdparty/lua/src/lgc.h | 202 + src/libs/3rdparty/lua/src/linit.c | 65 + src/libs/3rdparty/lua/src/liolib.c | 828 + src/libs/3rdparty/lua/src/ljumptab.h | 112 + src/libs/3rdparty/lua/src/llex.c | 581 + src/libs/3rdparty/lua/src/llex.h | 91 + src/libs/3rdparty/lua/src/llimits.h | 380 + src/libs/3rdparty/lua/src/lmathlib.c | 764 + src/libs/3rdparty/lua/src/lmem.c | 215 + src/libs/3rdparty/lua/src/lmem.h | 93 + src/libs/3rdparty/lua/src/loadlib.c | 767 + src/libs/3rdparty/lua/src/lobject.c | 602 + src/libs/3rdparty/lua/src/lobject.h | 815 + src/libs/3rdparty/lua/src/lopcodes.c | 104 + src/libs/3rdparty/lua/src/lopcodes.h | 405 + src/libs/3rdparty/lua/src/lopnames.h | 103 + src/libs/3rdparty/lua/src/loslib.c | 428 + src/libs/3rdparty/lua/src/lparser.c | 1967 ++ src/libs/3rdparty/lua/src/lparser.h | 171 + src/libs/3rdparty/lua/src/lprefix.h | 45 + src/libs/3rdparty/lua/src/lstate.c | 445 + src/libs/3rdparty/lua/src/lstate.h | 409 + src/libs/3rdparty/lua/src/lstring.c | 273 + src/libs/3rdparty/lua/src/lstring.h | 57 + src/libs/3rdparty/lua/src/lstrlib.c | 1874 + src/libs/3rdparty/lua/src/ltable.c | 980 + src/libs/3rdparty/lua/src/ltable.h | 65 + src/libs/3rdparty/lua/src/ltablib.c | 430 + src/libs/3rdparty/lua/src/ltm.c | 271 + src/libs/3rdparty/lua/src/ltm.h | 104 + src/libs/3rdparty/lua/src/lua.c | 679 + src/libs/3rdparty/lua/src/lua.h | 523 + src/libs/3rdparty/lua/src/lua.hpp | 9 + src/libs/3rdparty/lua/src/luac.c | 723 + src/libs/3rdparty/lua/src/luaconf.h | 793 + src/libs/3rdparty/lua/src/lualib.h | 52 + src/libs/3rdparty/lua/src/lundump.c | 335 + src/libs/3rdparty/lua/src/lundump.h | 36 + src/libs/3rdparty/lua/src/lutf8lib.c | 291 + src/libs/3rdparty/lua/src/lvm.c | 1901 + src/libs/3rdparty/lua/src/lvm.h | 141 + src/libs/3rdparty/lua/src/lzio.c | 68 + src/libs/3rdparty/lua/src/lzio.h | 66 + src/libs/3rdparty/sol2/CMakeLists.txt | 12 + src/libs/3rdparty/sol2/LICENSE.txt | 20 + src/libs/3rdparty/sol2/include/sol/config.hpp | 57 + .../3rdparty/sol2/include/sol/forward.hpp | 1340 + src/libs/3rdparty/sol2/include/sol/sol.hpp | 29202 ++++++++++++++++ 82 files changed, 74259 insertions(+) create mode 100644 src/libs/3rdparty/lua/CMakeLists.txt create mode 100644 src/libs/3rdparty/lua/LICENSE create mode 100644 src/libs/3rdparty/lua/README create mode 100644 src/libs/3rdparty/lua/doc/contents.html create mode 100644 src/libs/3rdparty/lua/doc/index.css create mode 100644 src/libs/3rdparty/lua/doc/logo.gif create mode 100644 src/libs/3rdparty/lua/doc/lua.1 create mode 100644 src/libs/3rdparty/lua/doc/lua.css create mode 100644 src/libs/3rdparty/lua/doc/luac.1 create mode 100644 src/libs/3rdparty/lua/doc/manual.css create mode 100644 src/libs/3rdparty/lua/doc/manual.html create mode 100644 src/libs/3rdparty/lua/doc/osi-certified-72x60.png create mode 100644 src/libs/3rdparty/lua/doc/readme.html create mode 100644 src/libs/3rdparty/lua/src/lapi.c create mode 100644 src/libs/3rdparty/lua/src/lapi.h create mode 100644 src/libs/3rdparty/lua/src/lauxlib.c create mode 100644 src/libs/3rdparty/lua/src/lauxlib.h create mode 100644 src/libs/3rdparty/lua/src/lbaselib.c create mode 100644 src/libs/3rdparty/lua/src/lcode.c create mode 100644 src/libs/3rdparty/lua/src/lcode.h create mode 100644 src/libs/3rdparty/lua/src/lcorolib.c create mode 100644 src/libs/3rdparty/lua/src/lctype.c create mode 100644 src/libs/3rdparty/lua/src/lctype.h create mode 100644 src/libs/3rdparty/lua/src/ldblib.c create mode 100644 src/libs/3rdparty/lua/src/ldebug.c create mode 100644 src/libs/3rdparty/lua/src/ldebug.h create mode 100644 src/libs/3rdparty/lua/src/ldo.c create mode 100644 src/libs/3rdparty/lua/src/ldo.h create mode 100644 src/libs/3rdparty/lua/src/ldump.c create mode 100644 src/libs/3rdparty/lua/src/lfunc.c create mode 100644 src/libs/3rdparty/lua/src/lfunc.h create mode 100644 src/libs/3rdparty/lua/src/lgc.c create mode 100644 src/libs/3rdparty/lua/src/lgc.h create mode 100644 src/libs/3rdparty/lua/src/linit.c create mode 100644 src/libs/3rdparty/lua/src/liolib.c create mode 100644 src/libs/3rdparty/lua/src/ljumptab.h create mode 100644 src/libs/3rdparty/lua/src/llex.c create mode 100644 src/libs/3rdparty/lua/src/llex.h create mode 100644 src/libs/3rdparty/lua/src/llimits.h create mode 100644 src/libs/3rdparty/lua/src/lmathlib.c create mode 100644 src/libs/3rdparty/lua/src/lmem.c create mode 100644 src/libs/3rdparty/lua/src/lmem.h create mode 100644 src/libs/3rdparty/lua/src/loadlib.c create mode 100644 src/libs/3rdparty/lua/src/lobject.c create mode 100644 src/libs/3rdparty/lua/src/lobject.h create mode 100644 src/libs/3rdparty/lua/src/lopcodes.c create mode 100644 src/libs/3rdparty/lua/src/lopcodes.h create mode 100644 src/libs/3rdparty/lua/src/lopnames.h create mode 100644 src/libs/3rdparty/lua/src/loslib.c create mode 100644 src/libs/3rdparty/lua/src/lparser.c create mode 100644 src/libs/3rdparty/lua/src/lparser.h create mode 100644 src/libs/3rdparty/lua/src/lprefix.h create mode 100644 src/libs/3rdparty/lua/src/lstate.c create mode 100644 src/libs/3rdparty/lua/src/lstate.h create mode 100644 src/libs/3rdparty/lua/src/lstring.c create mode 100644 src/libs/3rdparty/lua/src/lstring.h create mode 100644 src/libs/3rdparty/lua/src/lstrlib.c create mode 100644 src/libs/3rdparty/lua/src/ltable.c create mode 100644 src/libs/3rdparty/lua/src/ltable.h create mode 100644 src/libs/3rdparty/lua/src/ltablib.c create mode 100644 src/libs/3rdparty/lua/src/ltm.c create mode 100644 src/libs/3rdparty/lua/src/ltm.h create mode 100644 src/libs/3rdparty/lua/src/lua.c create mode 100644 src/libs/3rdparty/lua/src/lua.h create mode 100644 src/libs/3rdparty/lua/src/lua.hpp create mode 100644 src/libs/3rdparty/lua/src/luac.c create mode 100644 src/libs/3rdparty/lua/src/luaconf.h create mode 100644 src/libs/3rdparty/lua/src/lualib.h create mode 100644 src/libs/3rdparty/lua/src/lundump.c create mode 100644 src/libs/3rdparty/lua/src/lundump.h create mode 100644 src/libs/3rdparty/lua/src/lutf8lib.c create mode 100644 src/libs/3rdparty/lua/src/lvm.c create mode 100644 src/libs/3rdparty/lua/src/lvm.h create mode 100644 src/libs/3rdparty/lua/src/lzio.c create mode 100644 src/libs/3rdparty/lua/src/lzio.h create mode 100644 src/libs/3rdparty/sol2/CMakeLists.txt create mode 100644 src/libs/3rdparty/sol2/LICENSE.txt create mode 100644 src/libs/3rdparty/sol2/include/sol/config.hpp create mode 100644 src/libs/3rdparty/sol2/include/sol/forward.hpp create mode 100644 src/libs/3rdparty/sol2/include/sol/sol.hpp diff --git a/qt_attributions.json b/qt_attributions.json index 65a92cecc88..2e6f2661276 100644 --- a/qt_attributions.json +++ b/qt_attributions.json @@ -556,5 +556,33 @@ "License": "BSD 3-Clause \"New\" or \"Revised\" License", "LicenseFile": "src/libs/3rdparty/qtkeychain/COPYING", "Copyright": "Copyright (C) 2011-2015 Frank Osterfeld, Copyright (C) 2016 Mathias Hasselmann" + }, + { + "Id": "lua", + "Name": "Lua", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for scripting plugins.", + "Path": "src/libs/3rdparty/lua", + "Description": "Lua is a powerful, efficient, lightweight, embeddable scripting language.", + "Homepage": "https://www.lua.org/", + "License": "MIT License", + "LicenseFile": "src/libs/3rdparty/lua/LICENSE", + "Copyright": "Copyright © 1994-2023 Lua.org, PUC-Rio.", + "Version": "5.4.6" + }, + { + "Id": "sol2", + "Name": "sol2", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for binding C++ and Lua.", + "Path": "src/libs/3rdparty/sol2", + "Description": "sol2 is a C++ library binding to Lua.", + "Homepage": "https://github.com/ThePhD/sol2", + "License": "MIT License", + "LicenseFile": "src/libs/3rdparty/sol2/LICENSE.txt", + "Copyright": "Copyright (c) 2008 Paul Evans", + "Version": "3.3.1 (revision 9c882a28)" } ] diff --git a/src/libs/3rdparty/CMakeLists.txt b/src/libs/3rdparty/CMakeLists.txt index 8445a0d01b1..364c9a425eb 100644 --- a/src/libs/3rdparty/CMakeLists.txt +++ b/src/libs/3rdparty/CMakeLists.txt @@ -4,6 +4,8 @@ add_subdirectory(libvterm) add_subdirectory(libptyqt) add_subdirectory(qrcodegen) add_subdirectory(qtkeychain) +add_subdirectory(lua) +add_subdirectory(sol2) if(WIN32) add_subdirectory(winpty) diff --git a/src/libs/3rdparty/lua/CMakeLists.txt b/src/libs/3rdparty/lua/CMakeLists.txt new file mode 100644 index 00000000000..121e063f19f --- /dev/null +++ b/src/libs/3rdparty/lua/CMakeLists.txt @@ -0,0 +1,40 @@ + +add_qtc_library(lua546 + PUBLIC_INCLUDES src + STATIC + SOURCES + src/lapi.c + src/lauxlib.c + src/lbaselib.c + src/lcode.c + src/lcorolib.c + src/lctype.c + src/ldblib.c + src/ldebug.c + src/ldo.c + src/ldump.c + src/lfunc.c + src/lgc.c + src/linit.c + src/liolib.c + src/llex.c + src/lmathlib.c + src/lmem.c + src/loadlib.c + src/lobject.c + src/lopcodes.c + src/loslib.c + src/lparser.c + src/lstate.c + src/lstring.c + src/lstrlib.c + src/ltable.c + src/ltablib.c + src/ltm.c + src/lua.c + src/lundump.c + src/lutf8lib.c + src/lvm.c + src/lzio.c +) + diff --git a/src/libs/3rdparty/lua/LICENSE b/src/libs/3rdparty/lua/LICENSE new file mode 100644 index 00000000000..441cc1981c0 --- /dev/null +++ b/src/libs/3rdparty/lua/LICENSE @@ -0,0 +1,16 @@ +Copyright © 1994–2023 Lua.org, PUC-Rio. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/src/libs/3rdparty/lua/README b/src/libs/3rdparty/lua/README new file mode 100644 index 00000000000..1ae97165bab --- /dev/null +++ b/src/libs/3rdparty/lua/README @@ -0,0 +1,6 @@ + +This is Lua 5.4.6, released on 02 May 2023. + +For installation instructions, license details, and +further information about Lua, see doc/readme.html. + diff --git a/src/libs/3rdparty/lua/doc/contents.html b/src/libs/3rdparty/lua/doc/contents.html new file mode 100644 index 00000000000..1231e6d2481 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/contents.html @@ -0,0 +1,678 @@ + + + +Lua 5.4 Reference Manual - contents + + + + + + + +

    +Lua +Lua 5.4 Reference Manual +

    + +

    +The reference manual is the official definition of the Lua language. +
    +For a complete introduction to Lua programming, see the book +Programming in Lua. + +

    + +

    + +Copyright © 2020–2023 Lua.org, PUC-Rio. +Freely available under the terms of the +Lua license. + + +

    Contents

    + + +

    Index

    + + + + + + + + + + + + + + diff --git a/src/libs/3rdparty/lua/doc/index.css b/src/libs/3rdparty/lua/doc/index.css new file mode 100644 index 00000000000..c9618357319 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/index.css @@ -0,0 +1,21 @@ +ul { + list-style-type: none ; +} + +ul.contents { + padding: 0 ; +} + +table { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +td { + vertical-align: top ; + padding: 0 ; + text-align: left ; + line-height: 1.25 ; + width: 15% ; +} diff --git a/src/libs/3rdparty/lua/doc/logo.gif b/src/libs/3rdparty/lua/doc/logo.gif new file mode 100644 index 0000000000000000000000000000000000000000..5c77eacc3b8f397fb2e87d2aaecd89128e53a117 GIT binary patch literal 9893 zcmeAS@N?(olHy`uVBq!ia0y~yU}ykg4mJh`hQoG=rx_R+SkfJR9T^xl_H+M9WMyDr zU@Q)DcVbv~PUa;81A{`cN02WALzNl>LqiJ#!!MBL7Yq!g1`G_Z5*Qe)W-u^_7tGle zXv4t3z?S6g?!xdN1Q+aGKAC}mfivIDt(bva$bHyIdI3p`yMLn>~)om*KkPov4HYQ~@Ueed^VQWQR+BPsOid*!DC#-GnwKDXU}|L5G|y44DvlaA zQQ3XPiWLhMFK+JZ<9kzPZD?p{^Wgw93p@LFyVoUFm9N)s*U;8h*3s#?a3R1%inp+^ z@X3=W3qrK=zrAKq@Dx%DRu2tLlajt|IMa%gYm%_wLM1!9IX`|B96Hn_*m7{|@*Owz zpPY8Nkz+P%_Ux5w*DhVXy8Gqj<=+*j_^2)3x^?QcYhg}KP7_(irrhUNiM0Ws$8v1bN$-AmP&p4ZaO@S$tvVB-WA>&@aHfyL$|-`9E0t7TPv6;j@=j&C*v*@ZIr#S3b+%4aV^r}x zlwc4L6XTPbs;V}*bKN?ppD)w}Hc=iJ;}292p+B3!IZ3JQ}?-r1(xr8G(9 zVS&Yl+iy$C%9sR1MX$Cet_jn&E_<_J-@bV-USzoS%lUeFaee&w@$awiqGq!v*Z*DJ zl0MJ!*vH3HOG<9++Ap~4|F1KC-{mv5E?g61+2$@c^X!+GA5Wybb3N3N%+PS>PRysz zpF2A{6%7q19y#KYl$?C=^;c%0>+=h&=1!S1CBZ;q#i~_{Hf|K$efQjxlanL&R&Bk1 zEFk{=vHZH?mg#Y)majd_RdH!ux8$QoNvg-F zA8KlDp1d{c;_I(0tgLsh6yC})>v2Y zM{89MZm?vrn(Noq-Tm{;=JPAotZ`Wz_TBH6hnu%IH(PV#=jZ2*tG;9u6&0O0aYAB( zpq2I8Kaa%O|9aFgFz$|hax=Yu;*1p!FS_UN{&corB7@oN-thQZ(a9%W%F4_ptNC)> zm}fUdz;)uWV{Yf>SRS5foNh4tY>%wZTtWGe(?_%oU1q7oa1aD)%l}> z_x+w?`}ki$Oa?s?3=6hx6I&Y88Mpp@xv%ug2`Zh>o~8NCv+306(uvx#;{MJB+pZm2 z6}mnkAfPv$-OgWOQ{v%}xSEf0P0dfu+ZoTK88_Tt@1x8(Nky@1(QW64-uh2BXI|cI zG1u8sh;y!9%lG^B4UwBCwe_66bLeGB(YH5|Wp8dA{P*{Fp;f!n8Qy%3rU%o0gspDg zeou?*z#NVlK5yULt!CtSpm-r^>)XMOrqS48aE!~MY)X>aav~lCy0|pHZ2QT>K zu2nVQN!WgSJ8J8E`{?!N1}Kw`ntqh7wfmIgc%X3RLz#w*Ri z&AmJGx|Qdo4Yys_gt0HuQ0x-Q&5dPfX=PQM%y}Y(Noy+8(jc)9Z&z--iO}tXg*LCeDal*)no+mh9X)v!|!0 zVePkbe%90VW}Y~|{^4bRZOiIy^FDn_^I7JXW5zy7h3~^@xvX9DYaAyC%B*o%9z1!{ zB30{Z5#ux!quMH)moKfh9}~?lRNlOHzo3YU^YY-|(-~K-UVU?OI=|WMUS4T40Z~!Y z6#ay)RvKDa4-WHtTa=tQ@bYr0M6Yak?BaE1)9-Z%-qp|cEczN8oV;w=vZ?;|y3g0w zmwI-dob0|a!BI;)EX63%iAQT{ez2stcwda3bds#Y``LnGVm>}TEB=c(UcGvC&*yX2 zTefW3kaAL}sHn(hTf^Og8$wsEMxHpU`|zy!`NB65s&2{F>qOt2v$HD^zHxbZocyUb zH$B%x8qa%r+E~(5>(1)jM^8>hP1E~p?UwA$aL+mASdWU`kA%hbDh{EcqVMgC#jq|HS6Zi&m!yh$GH?1GV{5g@3frI^8VmdyWV4E-`?4tZX+^LcoX zefgwWt7Jp8rF;$I|9y(E`?)0Pgu9H?t5@8AQh2hmvlnmNIPuAol>KXK7H@2xYwiDW z`u-Zf!ouc$Kf%Vf76pf}FrNGWzWKb{TW(}E_gCBgT@@QUt>0D5++=iFVBhK!kB&<2 z`FgE3!{p%M(^4D{3OZ!0QXZJ^w>&ganN5bTkV8Frh2p}16En>9r_TSABF8PZWKlp& zeWT6KCy8~xF8}4>4UK8vKiB$t;q}6@-dtbMG&H{z&jCYgSUKDm-%i7w~ z-u^o`<9L7grqt7ReDY=`+OBS|R>^Y+8O=Pf$n~Yo$0I^%XFOy+oc!}g$}F#@x%m03 zkMhDEYoewe?bg5No0Ajqe!1NCxVX4;_WytS_sLi`*|)UcefMN)IM>hq|2NLM%f~v2 zJiMm7@AX_4!Ef*NAFhtC?VW4wUz(r)*RZzA=Kt^g<;Hb2Ito?SdZRto#8^&yK7apa z{*MQp*$if%m9Z#bXg_@L#>V8@Yty%HFaLN%xc%myN`6sM-FbZJElzH(uH3WD-#_eB z=evCG-qUX@Z|6y$J*~e!_2VO+nCDsfVzWI8Hq2RHZ`&>&7vUQetPqVu-jf23S8m9qYE@B6?0@HkDGMVIpy6sQUvXJvF;@O$o(d*|03zthCPZ!_WS zW&itz3c?iOf6cp$m!%cxudg8g(G$r@e~$b zw_naXi}Boid;hpNIqzvYih6qIUTf|)?Rc+LzY6Fy8DEglCDKX zDp_A2l+-k*F-*6;+ZVL*OVxY%pGV4ht#p0Q&oX_y^ZC5O9(no4K`VC56yAN;)3>+v zaQo?-`~IrTuL){A`|QA6mk%wRe>xjpGTyqqyW-8p|BsJ~e|FRPc=&Mh%^ihW_kW(# zIo8wp>BNgQ?ZfT+dXHDf&+Q0$xp(U3HEU+BjsE`eeEqza`#ybZ4bn`0eT_Be zuGRmxDChbIyKGBJN`4&mt^EGZ*yisS^}EaePGsv`vc%)xuj^Ou)c+Tm-@!j&+OnrV zpTB>S9Y4FxdUNO9cTZj}@84AYeP+X+yA3=ETcbe5F+0E9mrl+;+0`kpuhq^tYvy(@ z)L+TWtmpas{gbC^AOEp7bZyvK`F|UlzP?t!_`gm+!R+>ro9Dkxo*w?TINogb+TRSX zZ*-(`O&LGH|O3K z+O+v`!EqM0=1$${Z>77ts@refii)fK8mbqw!{C8&p5%e7t&^rtZ+Ba)Xl;Fa^|`rz zouC$=yS${tOewpGN4qcoIRAf+U5f3J<*$GI`~IBg0l!A_|9{>#pU)Vszk6hg7pN(E z-tITg>Z`B5Np7FAv*e}F)TvW_=GjQ@je8&ZoSlE#$3xune;d#>u>dSbtQdzaxx?=EGX>RzTP^X3&Q)C2d(^- zx?4i0=NR9-s#hM{J@yr>Y_3_KrteLt0 z-`CH1wqHGB{_1_SuPzHZ@TZR8-G1f#1xwb|6{KDW;Lot%Un!uWYq}|WdU<+ddhlj_D$=p5kb^bpjS8E7r``aOU=GGQY30Xz9|)2lW*?nc4L!OZ_~3e3qkB+HWjV zr>?Cqt7r1{mA$*Kb)KS@Ru`|dnL+L?lLP#-4xG1J?Ie=ld$~TIBP4wLr_=FrUruU1 zuBv#u)%eYgzz*|ncagbsEFM}GpGq-0bog+!_k$lt7{t2QTJL_kmP>NyPSrmz-2X4y zdGl3uarnb#e!WelulF%JA7*O~UjC{o_-^IjwzA!_tFOMA`q(XZZR@8`6JNeFjp$I? z^QVaM|JV5c&&53zJcX*iiG04`T)kq|r;so4yp5YSrM-GpbD8VZr%#`5Y|Wk?E_I-* zYg(Q=>-*C)zxs=9IK&dK+6fnD)_OC?ZEaX}=AOHFJ zFvovFU~uxYkH_sFy|1@F`RHh-PTZVhKRy~BIo9@d+03m`vNO(_@wBD&$*xv0-`+A= zJ$pmc+q=b2*MAq@yh8|2HTBfvQ!{KWfA4WE*wEC%;;YZR;_9h) zTT~C*T6Z+4IEIFD-`@WG^C|7t43mQ|N)%h#v;tR(%s6YNBPOjDoNj(mHKyhJ{_dF2 zsgjt`+qRb{ZtOYIaNgnI-Bn+{$8eUETJ9~1e{K1hclN1;|J?uo zv29jv*uI}xK#+xTt5wGd57Wd%M~i0|T2^szTX}ag@wVl%6 z#KpwUtcmml4Rd5(e&p%F@qVqrrJI?{ci!~!?3{SGo%hMJX>pT(-1_~UhilUBDVrTW zp3+`FVdBJtO|0B)9TMiuLYvc6HvFYhg0zG~;9 zg$o-eOb~Dh{PIFgVLCUXezDOXg^f9pZ2Ef&%uk-2_;>$Q6&22uP1-DCER9=CbZ>9d zRn*p=)h>Up`)1D3Xf+PLFoo&W-=YIWe!f`TZ!ptGV~Urm-}1}J*$cduN`!EIi56ey zbf({a-xmIly~p_Yv-8W3 z@UYcW&zc&D{QOLD^2t3~Unk95=ejhg;;pd3q=zM4Z|+pi>bEme;8=IdZC%Eq z*ZL}s4E0wp2dx&3Yu|YM$Poc~`Tj%F{tx6-)ZG_dUb%9m;r$Os^Gzex^8NcXT{y;G zb4$tD{RWvqHj~x+KON>!DcL2keS5#O<<4$ybu%-bwPC&)83I~U z@4RPSx!gz6HDX5o)ElA?c8Qggl~sk_t$udKWnO)p+=oZU4>Jp8W?Jq0x>j;ctaanX z#madvly6+S)*7StBc?n;ZL)E3+9Lm42Xp2p&z}be1RS`vHM_I3^W%y}&EQ8JU0e$n zF6^yepL-xR|HtL|`_5ch`R=uP$0C>X<#VrvNl%@+w&vH%R8Ybc-yh-O=hx(4d;Ca? zVQ$o(n~s(a++U@|CG=(r&$6(k#pe zn)&_SI@fd`JtqJEho=7CDgLEff6hvg4FApc>oK3khMdS{;kP|1D=m3>d25{yZ;8^i zn%np4RaTDK?Bl(9@$)=ON;D2z?no{WVB5M%N$HAC{5|tYzx?a1&aJPnop5@3^sd+~ z>#niHC2Gv{`EaA+vbfO2iwkvPX1w~SpKB(4_3Bj@SJ$sB%yy7r-S@q>n9|Ln4W-zVuTP(0Z$Gt#h4-G*!U>x}I&>QzoMKMheDl|n z##eJEUbzx7O*h&tC1puCbMz*axrL9DKKOEV*!}tXcKfbdcb40n{qmCY?ltf7$DrE(5f4*&RfBEWF_U;QAS8D$ME{@oob||50@xFb$%?o#ytG+JD zGRvLiSXd~Wn;ULjzC%Ju!{g+ipD%N6Z)@?Kobptd&{RMx})Uek&ln3 z-YGu+<6e5*m&H3(R5C!F+^j4e7WUJU_I98#txXw$QeI1YK7A5%>*dXKmZ27ZtsB?-^k^ zxg&3Go}6(u_C`+M>m|!4pEz-0bKTx@%|F!zYZskg&og1-!sq{fFaNMQUiQn6?M)5- zdT9p_ezGeooPGA-=JWFs&dqu9PMWKwMdRl)^Wq=3t}nZEGt*sfx}Z?e(|hqDR}L7T zuQ~O;e*d4g>Nnrssz>fD^2zsYT%cfCe&4oFRNE*s>(zmmBAp!pf^u?qv@hPez5B+t zw*p>EdydP;U$V_(^|#;4w7F98|7ZK-m9JJF<|zr=`Tw70N=ilefnPI~!CyMMO@&5nXDYn&Jn)>-K z|N2%`7;tjVVwClAO#1Uf!YpsjtM8Gojz3$wcCCzM5zFF>9!^e8$J3j)nCQ+nKmX*S z`~Bk&B|11+w6vou-|ZBxTiL5VoqLY;^&9#wULp_k>rXFVv7#}*&bZyOIH;qS*L7)- zf~VfzJqItG+5LXr^Za`41-o{&UR=EO&(HJo7lvt1IN9=!WyZVv3pZ?-_Vso7=E}{d z#U@Nx@N#OB-|~)|Ig5Af==^?9JMH?q%X^P*J~wCO^NH^F(qCWuxn%k42`6JtYVxvu zzZoXNB{|#t{FfbJ4cUAyTwGiiGE7p^(!MQD-+yQ#UwiZQ`1-l4R%yxAd~oa!J^a9{ zV?*8Fyl-!{AN~s0ulMe3oDu4>aDuS3^tl%o1zp@$3A#@F^{Y%vD=H)N<&IZkX0Kl>e}(sH)RpVkH`o3yn>2ZH%wJ=>+a6ZynkWD+b2i^(rmxo^8mHXD6-0;v%S}HEZPxgPnix z#a2&x;`Q;-toe;zhrC~WUHIpP`{zAMb~{$>i(VV1<~QfXwU^i5e)945R@T()Jaouu z)~s23UR7LNWCE(!>b5ujZj+1MQ*FBT|LuK&zr$~{-?=Izc4JE>+vn%i>%OrXNcGOK ztDUuEiOQwRcVF|}F>3Hynsls3@$ye0K)FLFa?-iQ z{pY^jDhr5+=(w4qrmmiTK*WLhUg@zuS#LMDw(ygSs|93bPfhmMTe{_n#RJCY+&h|G zvR3t}&yTrP-TGC;Z@F-wh@^Gdo6=wg_9az6&dptZV^8IIjWzZ|2OFJb>sPNT-fq2aQU1=2Q+HiL0MCMp88giD z<#Ka#Wvoh8Y`@W9{-cTW*P-|$?_a%obYh}%NJvPH4mQK$G5m$o}B&SKI^*G_s-Yv>#+Zm*n0kmzOL@m6BCtHR8$Po z&&izsWK(fzqTAxctE)n9ye-?_+F|ROv0{?^{|dd8D<}SWlm6RK!spJfhtHH&uC&^g z8-3{4*U2?@Z@niSIod5As3D>gw@0G)m~s8#28|}R<~@6|w&mPB-pD+?>h7*Q-5qP% zy2Y1&elpp+wuk2xclS{zZ*T6-&Q7`8ac#WJ3?`aAX(SoV?C9zFvg*~1tpye?pmD7$!ScmF3L>}H)-3U2zV4WR zu*szE)8wCL=FXNeU_GDk(3m-9PsK!jyB`gao6`)FkMXQG>fPb&-90sSx8KJ%o7FY+ z@;*2R9d&SW5>U|AZflpHce3`oucFbV&rLG#9+X(ET(LsI%IcQ>bAzAy^*>L?|GLzm z(FHQH`1!eomtS`D_I_QuGj2r)*S;@HUBcGMIHxR`wMxraSJ(C{XPdV24vzWr);+hr zKl3bT&LQ=*(H^cx5*+F0=RJM9{r<7M?ca+(eq*b%WDW@r|9sB+{e^4Sj-8sSJ<}ku z>Ani%4!>Q~^-MQcf0rzKZ+H0TXI={#z3=a5pXXV3=MY!xoWjRR5&P?eUSIcDvWgw?CoF6`j)mgKAGibb-llJ%5*Ck7r{(Sp%J!o{}?{EE& zzh1k_SeHpI-nchfQ`94^KrmK-<;$-CP_J%Rsc^(5mAkJO^u9j$vSiZq>Bs;5{oUEq z^W@#`_iBma}8c1&`N(VH$TD|>2+W}!~}yn}~YGgDGse}DdA`B^!p+R%2^k9)ENBx}*V5Ekb2uU6SjwvdS)~e|_hxQnb-XrL$h_rB zi0;jsi)UCGcY^x4zP(>8&z??D>{42~bZN%cs6~ry`?>bLvu1PR7w}j%K_#5UFE&U(z_OC*E)EJ*P=3GJJxw&)$sPvC&?HOY-2sA`z~ezS7Gz zy0&cHS~+#YX=$Fyecz`|6FWE8`uNMs%V(PB%UN1l%84)kz|P|6u=2~=9ftxIuU_4~ zXO9gRH+SULEYZd8{c@k|+UFddG-*=A?lRrLz`!@RxA$+qUpIT#uIQbQc9gGJz54On z?f28}@2l0A>ebI(S=HTelc{Q3)1EyxLBYY1`|JMtPGmXEyGWzx(-TiVc{`u#YU|6( z{nOvw*;#k-6E7R1_D?}MxpSYMp7!+ea#EXI>-ZE(59Fm>mU;mzVn+r=Ai~^PA%l5)yJ?s@K0ZjV_5^ z(0Typ#6(4_xqa2|_g-Hgv_2Po6$4{P@V#%G%n~%L`ODrKF~^mdxKT*Vf9y5bpBnNT=}06DJ;ATIvm&h3e?& zm~E>wKOivBF)&bY<;s;Q>FJYa&9X|E^6u=R4HFrzA9`7`Yi(9sP*Bsw3>8aD$-Qy) zm-B^fZ%_AH>a_ap>_bPBHeR@O>(q+C#eW{@nud?C>HcXMNV`t&JiiXb4sp|sRgQ&Y26V!`t(yzAb&t_)cepmE1*s@#_;!KD^5 zdpix+nPzX_zWwtt>HG^9E;s}P2w2VSd-Ep8$awt~O*v1AZP5pMF9>sF8qF-QkWo=p z{W`N|_0?1BVs~fcZ~{2IPZ>y zl9JMf2%Rn4w+DxZyL)(e?B8G(D6+HQp;Nxx-w6{0l$4Y@IyzpYp9<5OdS;gC>$Ls* z?tl32c|V1B-^F#Z3=9maC9V-ADTyViR>?)Fi6yBFMh1pvx`sx&1|}hf23AIcptHiCrWP%w70|Nttr>mdKI;Vst0O#=zMF0Q* literal 0 HcmV?d00001 diff --git a/src/libs/3rdparty/lua/doc/lua.1 b/src/libs/3rdparty/lua/doc/lua.1 new file mode 100644 index 00000000000..3f472fd81f6 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/lua.1 @@ -0,0 +1,155 @@ +.\" $Id: lua.man,v 1.14 2022/09/23 09:06:36 lhf Exp $ +.TH LUA 1 "$Date: 2022/09/23 09:06:36 $" +.SH NAME +lua \- Lua interpreter +.SH SYNOPSIS +.B lua +[ +.I options +] +[ +.I script +[ +.I args +] +] +.SH DESCRIPTION +.B lua +is the standalone Lua interpreter. +It loads and executes Lua programs, +either in textual source form or +in precompiled binary form. +(Precompiled binaries are output by +.BR luac , +the Lua compiler.) +.B lua +can be used as a batch interpreter and also interactively. +.LP +After handling the +.IR options , +the Lua program in file +.I script +is loaded and executed. +The +.I args +are available to +.I script +as strings in a global table named +.B arg +and also as arguments to its main function. +When called without arguments, +.B lua +behaves as +.B "lua \-v \-i" +if the standard input is a terminal, +and as +.B "lua \-" +otherwise. +.LP +In interactive mode, +.B lua +prompts the user, +reads lines from the standard input, +and executes them as they are read. +If the line contains an expression, +then the line is evaluated and the result is printed. +If a line does not contain a complete statement, +then a secondary prompt is displayed and +lines are read until a complete statement is formed or +a syntax error is found. +.LP +Before handling command line options and scripts, +.B lua +checks the contents of the environment variables +.B LUA_INIT_5_4 +and +.BR LUA_INIT , +in that order. +If the contents are of the form +.RI '@ filename ', +then +.I filename +is executed. +Otherwise, the contents are assumed to be a Lua statement and is executed. +When +.B LUA_INIT_5_4 +is defined, +.B LUA_INIT +is ignored. +.SH OPTIONS +.TP +.BI \-e " stat" +execute statement +.IR stat . +.TP +.B \-i +enter interactive mode after executing +.IR script . +.TP +.BI \-l " mod" +require library +.I mod +into global +.IR mod . +.TP +.BI \-l " g=mod" +require library +.I mod +into global +.IR g . +.TP +.B \-v +show version information. +.TP +.B \-E +ignore environment variables. +.TP +.B \-W +turn warnings on. +.TP +.B \-\- +stop handling options. +.TP +.B \- +stop handling options and execute the standard input as a file. +.SH ENVIRONMENT VARIABLES +The following environment variables affect the execution of +.BR lua . +When defined, +the version-specific variants take priority +and the version-neutral variants are ignored. +.TP +.B LUA_INIT, LUA_INIT_5_4 +Code to be executed before command line options and scripts. +.TP +.B LUA_PATH, LUA_PATH_5_4 +Initial value of package.cpath, +the path used by require to search for Lua loaders. +.TP +.B LUA_CPATH, LUA_CPATH_5_4 +Initial value of package.cpath, +the path used by require to search for C loaders. +.SH EXIT STATUS +If a script calls os.exit, +then +.B lua +exits with the given exit status. +Otherwise, +.B lua +exits +with EXIT_SUCCESS (0 on POSIX systems) if there were no errors +and +with EXIT_FAILURE (1 on POSIX systems) if there were errors. +Errors raised in interactive mode do not cause exits. +.SH DIAGNOSTICS +Error messages should be self explanatory. +.SH "SEE ALSO" +.BR luac (1) +.br +The documentation at lua.org, +especially section 7 of the reference manual. +.SH AUTHORS +R. Ierusalimschy, +L. H. de Figueiredo, +W. Celes +.\" EOF diff --git a/src/libs/3rdparty/lua/doc/lua.css b/src/libs/3rdparty/lua/doc/lua.css new file mode 100644 index 00000000000..cbd0799d152 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/lua.css @@ -0,0 +1,161 @@ +html { + background-color: #F8F8F8 ; +} + +body { + background-color: #FFFFFF ; + color: #000000 ; + font-family: Helvetica, Arial, sans-serif ; + text-align: justify ; + line-height: 1.25 ; + margin: 16px auto ; + padding: 32px ; + border: solid #ccc 1px ; + border-radius: 20px ; + max-width: 70em ; + width: 90% ; +} + +h1, h2, h3, h4 { + color: #000080 ; + font-family: Verdana, Geneva, sans-serif ; + font-weight: normal ; + font-style: normal ; + text-align: left ; +} + +h1 { + font-size: 28pt ; +} + +h1 img { + vertical-align: text-bottom ; +} + +h2:before { + content: "\2756" ; + padding-right: 0.5em ; +} + +a { + text-decoration: none ; +} + +a:link { + color: #000080 ; +} + +a:link:hover, a:visited:hover { + background-color: #D0D0FF ; + color: #000080 ; + border-radius: 4px ; +} + +a:link:active, a:visited:active { + color: #FF0000 ; +} + +div.menubar { + padding-bottom: 0.5em ; +} + +p.menubar { + margin-left: 2.5em ; +} + +.menubar a:hover { + margin: -3px -3px -3px -3px ; + padding: 3px 3px 3px 3px ; + border-radius: 4px ; +} + +:target { + background-color: #F0F0F0 ; + margin: -8px ; + padding: 8px ; + border-radius: 8px ; + outline: none ; +} + +hr { + display: none ; +} + +table hr { + background-color: #a0a0a0 ; + color: #a0a0a0 ; + border: 0 ; + height: 1px ; + display: block ; +} + +.footer { + color: gray ; + font-size: x-small ; + text-transform: lowercase ; +} + +input[type=text] { + border: solid #a0a0a0 2px ; + border-radius: 2em ; + background-image: url('images/search.png') ; + background-repeat: no-repeat ; + background-position: 4px center ; + padding-left: 20px ; + height: 2em ; +} + +pre.session { + background-color: #F8F8F8 ; + padding: 1em ; + border-radius: 8px ; +} + +table { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +td { + padding: 0 ; + margin: 0 ; +} + +td.gutter { + width: 4% ; +} + +table.columns td { + vertical-align: top ; + padding-bottom: 1em ; + text-align: justify ; + line-height: 1.25 ; +} + +table.book td { + vertical-align: top ; +} + +table.book td.cover { + padding-right: 1em ; +} + +table.book img { + border: solid #000080 1px ; +} + +table.book span { + font-size: small ; + text-align: left ; + display: block ; + margin-top: 0.25em ; +} + +p.logos a:link:hover, p.logos a:visited:hover { + background-color: inherit ; +} + +img { + background-color: white ; +} diff --git a/src/libs/3rdparty/lua/doc/luac.1 b/src/libs/3rdparty/lua/doc/luac.1 new file mode 100644 index 00000000000..33a4ed00ace --- /dev/null +++ b/src/libs/3rdparty/lua/doc/luac.1 @@ -0,0 +1,118 @@ +.\" $Id: luac.man,v 1.29 2011/11/16 13:53:40 lhf Exp $ +.TH LUAC 1 "$Date: 2011/11/16 13:53:40 $" +.SH NAME +luac \- Lua compiler +.SH SYNOPSIS +.B luac +[ +.I options +] [ +.I filenames +] +.SH DESCRIPTION +.B luac +is the Lua compiler. +It translates programs written in the Lua programming language +into binary files containing precompiled chunks +that can be later loaded and executed. +.LP +The main advantages of precompiling chunks are: +faster loading, +protecting source code from accidental user changes, +and +off-line syntax checking. +Precompiling does not imply faster execution +because in Lua chunks are always compiled into bytecodes before being executed. +.B luac +simply allows those bytecodes to be saved in a file for later execution. +Precompiled chunks are not necessarily smaller than the corresponding source. +The main goal in precompiling is faster loading. +.LP +In the command line, +you can mix +text files containing Lua source and +binary files containing precompiled chunks. +.B luac +produces a single output file containing the combined bytecodes +for all files given. +Executing the combined file is equivalent to executing the given files. +By default, +the output file is named +.BR luac.out , +but you can change this with the +.B \-o +option. +.LP +Precompiled chunks are +.I not +portable across different architectures. +Moreover, +the internal format of precompiled chunks +is likely to change when a new version of Lua is released. +Make sure you save the source files of all Lua programs that you precompile. +.LP +.SH OPTIONS +.TP +.B \-l +produce a listing of the compiled bytecode for Lua's virtual machine. +Listing bytecodes is useful to learn about Lua's virtual machine. +If no files are given, then +.B luac +loads +.B luac.out +and lists its contents. +Use +.B \-l \-l +for a full listing. +.TP +.BI \-o " file" +output to +.IR file , +instead of the default +.BR luac.out . +(You can use +.B "'\-'" +for standard output, +but not on platforms that open standard output in text mode.) +The output file may be one of the given files because +all files are loaded before the output file is written. +Be careful not to overwrite precious files. +.TP +.B \-p +load files but do not generate any output file. +Used mainly for syntax checking and for testing precompiled chunks: +corrupted files will probably generate errors when loaded. +If no files are given, then +.B luac +loads +.B luac.out +and tests its contents. +No messages are displayed if the file loads without errors. +.TP +.B \-s +strip debug information before writing the output file. +This saves some space in very large chunks, +but if errors occur when running a stripped chunk, +then the error messages may not contain the full information they usually do. +In particular, +line numbers and names of local variables are lost. +.TP +.B \-v +show version information. +.TP +.B \-\- +stop handling options. +.TP +.B \- +stop handling options and process standard input. +.SH "SEE ALSO" +.BR lua (1) +.br +The documentation at lua.org. +.SH DIAGNOSTICS +Error messages should be self explanatory. +.SH AUTHORS +R. Ierusalimschy, +L. H. de Figueiredo, +W. Celes +.\" EOF diff --git a/src/libs/3rdparty/lua/doc/manual.css b/src/libs/3rdparty/lua/doc/manual.css new file mode 100644 index 00000000000..aa0e677dd52 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/manual.css @@ -0,0 +1,21 @@ +h3 code { + font-family: inherit ; + font-size: inherit ; +} + +pre, code { + font-size: 12pt ; +} + +span.apii { + color: gray ; + float: right ; + font-family: inherit ; + font-style: normal ; + font-size: small ; +} + +h2:before { + content: "" ; + padding-right: 0em ; +} diff --git a/src/libs/3rdparty/lua/doc/manual.html b/src/libs/3rdparty/lua/doc/manual.html new file mode 100644 index 00000000000..0af688b343c --- /dev/null +++ b/src/libs/3rdparty/lua/doc/manual.html @@ -0,0 +1,12046 @@ + + + +Lua 5.4 Reference Manual + + + + + + + +

    +Lua +Lua 5.4 Reference Manual +

    + +

    +by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes + +

    + +Copyright © 2020–2023 Lua.org, PUC-Rio. +Freely available under the terms of the +Lua license. + + +

    + + +

    + + + + + + +

    1 – Introduction

    + +

    +Lua is a powerful, efficient, lightweight, embeddable scripting language. +It supports procedural programming, +object-oriented programming, functional programming, +data-driven programming, and data description. + + +

    +Lua combines simple procedural syntax with powerful data description +constructs based on associative arrays and extensible semantics. +Lua is dynamically typed, +runs by interpreting bytecode with a register-based +virtual machine, +and has automatic memory management with +a generational garbage collection, +making it ideal for configuration, scripting, +and rapid prototyping. + + +

    +Lua is implemented as a library, written in clean C, +the common subset of standard C and C++. +The Lua distribution includes a host program called lua, +which uses the Lua library to offer a complete, +standalone Lua interpreter, +for interactive or batch use. +Lua is intended to be used both as a powerful, lightweight, +embeddable scripting language for any program that needs one, +and as a powerful but lightweight and efficient stand-alone language. + + +

    +As an extension language, Lua has no notion of a "main" program: +it works embedded in a host client, +called the embedding program or simply the host. +(Frequently, this host is the stand-alone lua program.) +The host program can invoke functions to execute a piece of Lua code, +can write and read Lua variables, +and can register C functions to be called by Lua code. +Through the use of C functions, Lua can be augmented to cope with +a wide range of different domains, +thus creating customized programming languages sharing a syntactical framework. + + +

    +Lua is free software, +and is provided as usual with no guarantees, +as stated in its license. +The implementation described in this manual is available +at Lua's official web site, www.lua.org. + + +

    +Like any other reference manual, +this document is dry in places. +For a discussion of the decisions behind the design of Lua, +see the technical papers available at Lua's web site. +For a detailed introduction to programming in Lua, +see Roberto's book, Programming in Lua. + + + +

    2 – Basic Concepts

    + + + +

    +This section describes the basic concepts of the language. + + + + + +

    2.1 – Values and Types

    + +

    +Lua is a dynamically typed language. +This means that +variables do not have types; only values do. +There are no type definitions in the language. +All values carry their own type. + + +

    +All values in Lua are first-class values. +This means that all values can be stored in variables, +passed as arguments to other functions, and returned as results. + + +

    +There are eight basic types in Lua: +nil, boolean, number, +string, function, userdata, +thread, and table. +The type nil has one single value, nil, +whose main property is to be different from any other value; +it often represents the absence of a useful value. +The type boolean has two values, false and true. +Both nil and false make a condition false; +they are collectively called false values. +Any other value makes a condition true. +Despite its name, +false is frequently used as an alternative to nil, +with the key difference that false behaves +like a regular value in a table, +while a nil in a table represents an absent key. + + +

    +The type number represents both +integer numbers and real (floating-point) numbers, +using two subtypes: integer and float. +Standard Lua uses 64-bit integers and double-precision (64-bit) floats, +but you can also compile Lua so that it +uses 32-bit integers and/or single-precision (32-bit) floats. +The option with 32 bits for both integers and floats +is particularly attractive +for small machines and embedded systems. +(See macro LUA_32BITS in file luaconf.h.) + + +

    +Unless stated otherwise, +any overflow when manipulating integer values wrap around, +according to the usual rules of two-complement arithmetic. +(In other words, +the actual result is the unique representable integer +that is equal modulo 2n to the mathematical result, +where n is the number of bits of the integer type.) + + +

    +Lua has explicit rules about when each subtype is used, +but it also converts between them automatically as needed (see §3.4.3). +Therefore, +the programmer may choose to mostly ignore the difference +between integers and floats +or to assume complete control over the representation of each number. + + +

    +The type string represents immutable sequences of bytes. + +Lua is 8-bit clean: +strings can contain any 8-bit value, +including embedded zeros ('\0'). +Lua is also encoding-agnostic; +it makes no assumptions about the contents of a string. +The length of any string in Lua must fit in a Lua integer. + + +

    +Lua can call (and manipulate) functions written in Lua and +functions written in C (see §3.4.10). +Both are represented by the type function. + + +

    +The type userdata is provided to allow arbitrary C data to +be stored in Lua variables. +A userdata value represents a block of raw memory. +There are two kinds of userdata: +full userdata, +which is an object with a block of memory managed by Lua, +and light userdata, +which is simply a C pointer value. +Userdata has no predefined operations in Lua, +except assignment and identity test. +By using metatables, +the programmer can define operations for full userdata values +(see §2.4). +Userdata values cannot be created or modified in Lua, +only through the C API. +This guarantees the integrity of data owned by +the host program and C libraries. + + +

    +The type thread represents independent threads of execution +and it is used to implement coroutines (see §2.6). +Lua threads are not related to operating-system threads. +Lua supports coroutines on all systems, +even those that do not support threads natively. + + +

    +The type table implements associative arrays, +that is, arrays that can have as indices not only numbers, +but any Lua value except nil and NaN. +(Not a Number is a special floating-point value +used by the IEEE 754 standard to represent +undefined numerical results, such as 0/0.) +Tables can be heterogeneous; +that is, they can contain values of all types (except nil). +Any key associated to the value nil is not considered part of the table. +Conversely, any key that is not part of a table has +an associated value nil. + + +

    +Tables are the sole data-structuring mechanism in Lua; +they can be used to represent ordinary arrays, lists, +symbol tables, sets, records, graphs, trees, etc. +To represent records, Lua uses the field name as an index. +The language supports this representation by +providing a.name as syntactic sugar for a["name"]. +There are several convenient ways to create tables in Lua +(see §3.4.9). + + +

    +Like indices, +the values of table fields can be of any type. +In particular, +because functions are first-class values, +table fields can contain functions. +Thus tables can also carry methods (see §3.4.11). + + +

    +The indexing of tables follows +the definition of raw equality in the language. +The expressions a[i] and a[j] +denote the same table element +if and only if i and j are raw equal +(that is, equal without metamethods). +In particular, floats with integral values +are equal to their respective integers +(e.g., 1.0 == 1). +To avoid ambiguities, +any float used as a key that is equal to an integer +is converted to that integer. +For instance, if you write a[2.0] = true, +the actual key inserted into the table will be the integer 2. + + +

    +Tables, functions, threads, and (full) userdata values are objects: +variables do not actually contain these values, +only references to them. +Assignment, parameter passing, and function returns +always manipulate references to such values; +these operations do not imply any kind of copy. + + +

    +The library function type returns a string describing the type +of a given value (see type). + + + + + +

    2.2 – Environments and the Global Environment

    + +

    +As we will discuss further in §3.2 and §3.3.3, +any reference to a free name +(that is, a name not bound to any declaration) var +is syntactically translated to _ENV.var. +Moreover, every chunk is compiled in the scope of +an external local variable named _ENV (see §3.3.2), +so _ENV itself is never a free name in a chunk. + + +

    +Despite the existence of this external _ENV variable and +the translation of free names, +_ENV is a completely regular name. +In particular, +you can define new variables and parameters with that name. +Each reference to a free name uses the _ENV that is +visible at that point in the program, +following the usual visibility rules of Lua (see §3.5). + + +

    +Any table used as the value of _ENV is called an environment. + + +

    +Lua keeps a distinguished environment called the global environment. +This value is kept at a special index in the C registry (see §4.3). +In Lua, the global variable _G is initialized with this same value. +(_G is never used internally, +so changing its value will affect only your own code.) + + +

    +When Lua loads a chunk, +the default value for its _ENV variable +is the global environment (see load). +Therefore, by default, +free names in Lua code refer to entries in the global environment +and, therefore, they are also called global variables. +Moreover, all standard libraries are loaded in the global environment +and some functions there operate on that environment. +You can use load (or loadfile) +to load a chunk with a different environment. +(In C, you have to load the chunk and then change the value +of its first upvalue; see lua_setupvalue.) + + + + + +

    2.3 – Error Handling

    + +

    +Several operations in Lua can raise an error. +An error interrupts the normal flow of the program, +which can continue by catching the error. + + +

    +Lua code can explicitly raise an error by calling the +error function. +(This function never returns.) + + +

    +To catch errors in Lua, +you can do a protected call, +using pcall (or xpcall). +The function pcall calls a given function in protected mode. +Any error while running the function stops its execution, +and control returns immediately to pcall, +which returns a status code. + + +

    +Because Lua is an embedded extension language, +Lua code starts running by a call +from C code in the host program. +(When you use Lua standalone, +the lua application is the host program.) +Usually, this call is protected; +so, when an otherwise unprotected error occurs during +the compilation or execution of a Lua chunk, +control returns to the host, +which can take appropriate measures, +such as printing an error message. + + +

    +Whenever there is an error, +an error object +is propagated with information about the error. +Lua itself only generates errors whose error object is a string, +but programs may generate errors with +any value as the error object. +It is up to the Lua program or its host to handle such error objects. +For historical reasons, +an error object is often called an error message, +even though it does not have to be a string. + + +

    +When you use xpcall (or lua_pcall, in C) +you may give a message handler +to be called in case of errors. +This function is called with the original error object +and returns a new error object. +It is called before the error unwinds the stack, +so that it can gather more information about the error, +for instance by inspecting the stack and creating a stack traceback. +This message handler is still protected by the protected call; +so, an error inside the message handler +will call the message handler again. +If this loop goes on for too long, +Lua breaks it and returns an appropriate message. +The message handler is called only for regular runtime errors. +It is not called for memory-allocation errors +nor for errors while running finalizers or other message handlers. + + +

    +Lua also offers a system of warnings (see warn). +Unlike errors, warnings do not interfere +in any way with program execution. +They typically only generate a message to the user, +although this behavior can be adapted from C (see lua_setwarnf). + + + + + +

    2.4 – Metatables and Metamethods

    + +

    +Every value in Lua can have a metatable. +This metatable is an ordinary Lua table +that defines the behavior of the original value +under certain events. +You can change several aspects of the behavior +of a value by setting specific fields in its metatable. +For instance, when a non-numeric value is the operand of an addition, +Lua checks for a function in the field __add of the value's metatable. +If it finds one, +Lua calls this function to perform the addition. + + +

    +The key for each event in a metatable is a string +with the event name prefixed by two underscores; +the corresponding value is called a metavalue. +For most events, the metavalue must be a function, +which is then called a metamethod. +In the previous example, the key is the string "__add" +and the metamethod is the function that performs the addition. +Unless stated otherwise, +a metamethod may in fact be any callable value, +which is either a function or a value with a __call metamethod. + + +

    +You can query the metatable of any value +using the getmetatable function. +Lua queries metamethods in metatables using a raw access (see rawget). + + +

    +You can replace the metatable of tables +using the setmetatable function. +You cannot change the metatable of other types from Lua code, +except by using the debug library (§6.10). + + +

    +Tables and full userdata have individual metatables, +although multiple tables and userdata can share their metatables. +Values of all other types share one single metatable per type; +that is, there is one single metatable for all numbers, +one for all strings, etc. +By default, a value has no metatable, +but the string library sets a metatable for the string type (see §6.4). + + +

    +A detailed list of operations controlled by metatables is given next. +Each event is identified by its corresponding key. +By convention, all metatable keys used by Lua are composed by +two underscores followed by lowercase Latin letters. + + + +

      + +
    • __add: +the addition (+) operation. +If any operand for an addition is not a number, +Lua will try to call a metamethod. +It starts by checking the first operand (even if it is a number); +if that operand does not define a metamethod for __add, +then Lua will check the second operand. +If Lua can find a metamethod, +it calls the metamethod with the two operands as arguments, +and the result of the call +(adjusted to one value) +is the result of the operation. +Otherwise, if no metamethod is found, +Lua raises an error. +
    • + +
    • __sub: +the subtraction (-) operation. +Behavior similar to the addition operation. +
    • + +
    • __mul: +the multiplication (*) operation. +Behavior similar to the addition operation. +
    • + +
    • __div: +the division (/) operation. +Behavior similar to the addition operation. +
    • + +
    • __mod: +the modulo (%) operation. +Behavior similar to the addition operation. +
    • + +
    • __pow: +the exponentiation (^) operation. +Behavior similar to the addition operation. +
    • + +
    • __unm: +the negation (unary -) operation. +Behavior similar to the addition operation. +
    • + +
    • __idiv: +the floor division (//) operation. +Behavior similar to the addition operation. +
    • + +
    • __band: +the bitwise AND (&) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod +if any operand is neither an integer +nor a float coercible to an integer (see §3.4.3). +
    • + +
    • __bor: +the bitwise OR (|) operation. +Behavior similar to the bitwise AND operation. +
    • + +
    • __bxor: +the bitwise exclusive OR (binary ~) operation. +Behavior similar to the bitwise AND operation. +
    • + +
    • __bnot: +the bitwise NOT (unary ~) operation. +Behavior similar to the bitwise AND operation. +
    • + +
    • __shl: +the bitwise left shift (<<) operation. +Behavior similar to the bitwise AND operation. +
    • + +
    • __shr: +the bitwise right shift (>>) operation. +Behavior similar to the bitwise AND operation. +
    • + +
    • __concat: +the concatenation (..) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod +if any operand is neither a string nor a number +(which is always coercible to a string). +
    • + +
    • __len: +the length (#) operation. +If the object is not a string, +Lua will try its metamethod. +If there is a metamethod, +Lua calls it with the object as argument, +and the result of the call +(always adjusted to one value) +is the result of the operation. +If there is no metamethod but the object is a table, +then Lua uses the table length operation (see §3.4.7). +Otherwise, Lua raises an error. +
    • + +
    • __eq: +the equal (==) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod only when the values +being compared are either both tables or both full userdata +and they are not primitively equal. +The result of the call is always converted to a boolean. +
    • + +
    • __lt: +the less than (<) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod only when the values +being compared are neither both numbers nor both strings. +Moreover, the result of the call is always converted to a boolean. +
    • + +
    • __le: +the less equal (<=) operation. +Behavior similar to the less than operation. +
    • + +
    • __index: +The indexing access operation table[key]. +This event happens when table is not a table or +when key is not present in table. +The metavalue is looked up in the metatable of table. + + +

      +The metavalue for this event can be either a function, a table, +or any value with an __index metavalue. +If it is a function, +it is called with table and key as arguments, +and the result of the call +(adjusted to one value) +is the result of the operation. +Otherwise, +the final result is the result of indexing this metavalue with key. +This indexing is regular, not raw, +and therefore can trigger another __index metavalue. +

    • + +
    • __newindex: +The indexing assignment table[key] = value. +Like the index event, +this event happens when table is not a table or +when key is not present in table. +The metavalue is looked up in the metatable of table. + + +

      +Like with indexing, +the metavalue for this event can be either a function, a table, +or any value with an __newindex metavalue. +If it is a function, +it is called with table, key, and value as arguments. +Otherwise, +Lua repeats the indexing assignment over this metavalue +with the same key and value. +This assignment is regular, not raw, +and therefore can trigger another __newindex metavalue. + + +

      +Whenever a __newindex metavalue is invoked, +Lua does not perform the primitive assignment. +If needed, +the metamethod itself can call rawset +to do the assignment. +

    • + +
    • __call: +The call operation func(args). +This event happens when Lua tries to call a non-function value +(that is, func is not a function). +The metamethod is looked up in func. +If present, +the metamethod is called with func as its first argument, +followed by the arguments of the original call (args). +All results of the call +are the results of the operation. +This is the only metamethod that allows multiple results. +
    • + +
    + +

    +In addition to the previous list, +the interpreter also respects the following keys in metatables: +__gc (see §2.5.3), +__close (see §3.3.8), +__mode (see §2.5.4), +and __name. +(The entry __name, +when it contains a string, +may be used by tostring and in error messages.) + + +

    +For the unary operators (negation, length, and bitwise NOT), +the metamethod is computed and called with a dummy second operand, +equal to the first one. +This extra operand is only to simplify Lua's internals +(by making these operators behave like a binary operation) +and may be removed in future versions. +For most uses this extra operand is irrelevant. + + +

    +Because metatables are regular tables, +they can contain arbitrary fields, +not only the event names defined above. +Some functions in the standard library +(e.g., tostring) +use other fields in metatables for their own purposes. + + +

    +It is a good practice to add all needed metamethods to a table +before setting it as a metatable of some object. +In particular, the __gc metamethod works only when this order +is followed (see §2.5.3). +It is also a good practice to set the metatable of an object +right after its creation. + + + + + +

    2.5 – Garbage Collection

    + + + +

    +Lua performs automatic memory management. +This means that +you do not have to worry about allocating memory for new objects +or freeing it when the objects are no longer needed. +Lua manages memory automatically by running +a garbage collector to collect all dead objects. +All memory used by Lua is subject to automatic management: +strings, tables, userdata, functions, threads, internal structures, etc. + + +

    +An object is considered dead +as soon as the collector can be sure the object +will not be accessed again in the normal execution of the program. +("Normal execution" here excludes finalizers, +which can resurrect dead objects (see §2.5.3), +and excludes also operations using the debug library.) +Note that the time when the collector can be sure that an object +is dead may not coincide with the programmer's expectations. +The only guarantees are that Lua will not collect an object +that may still be accessed in the normal execution of the program, +and it will eventually collect an object +that is inaccessible from Lua. +(Here, +inaccessible from Lua means that neither a variable nor +another live object refer to the object.) +Because Lua has no knowledge about C code, +it never collects objects accessible through the registry (see §4.3), +which includes the global environment (see §2.2). + + +

    +The garbage collector (GC) in Lua can work in two modes: +incremental and generational. + + +

    +The default GC mode with the default parameters +are adequate for most uses. +However, programs that waste a large proportion of their time +allocating and freeing memory can benefit from other settings. +Keep in mind that the GC behavior is non-portable +both across platforms and across different Lua releases; +therefore, optimal settings are also non-portable. + + +

    +You can change the GC mode and parameters by calling +lua_gc in C +or collectgarbage in Lua. +You can also use these functions to control +the collector directly (e.g., to stop and restart it). + + + + + +

    2.5.1 – Incremental Garbage Collection

    + +

    +In incremental mode, +each GC cycle performs a mark-and-sweep collection in small steps +interleaved with the program's execution. +In this mode, +the collector uses three numbers to control its garbage-collection cycles: +the garbage-collector pause, +the garbage-collector step multiplier, +and the garbage-collector step size. + + +

    +The garbage-collector pause +controls how long the collector waits before starting a new cycle. +The collector starts a new cycle when the use of memory +hits n% of the use after the previous collection. +Larger values make the collector less aggressive. +Values equal to or less than 100 mean the collector will not wait to +start a new cycle. +A value of 200 means that the collector waits for the total memory in use +to double before starting a new cycle. +The default value is 200; the maximum value is 1000. + + +

    +The garbage-collector step multiplier +controls the speed of the collector relative to +memory allocation, +that is, +how many elements it marks or sweeps for each +kilobyte of memory allocated. +Larger values make the collector more aggressive but also increase +the size of each incremental step. +You should not use values less than 100, +because they make the collector too slow and +can result in the collector never finishing a cycle. +The default value is 100; the maximum value is 1000. + + +

    +The garbage-collector step size controls the +size of each incremental step, +specifically how many bytes the interpreter allocates +before performing a step. +This parameter is logarithmic: +A value of n means the interpreter will allocate 2n +bytes between steps and perform equivalent work during the step. +A large value (e.g., 60) makes the collector a stop-the-world +(non-incremental) collector. +The default value is 13, +which means steps of approximately 8 Kbytes. + + + + + +

    2.5.2 – Generational Garbage Collection

    + +

    +In generational mode, +the collector does frequent minor collections, +which traverses only objects recently created. +If after a minor collection the use of memory is still above a limit, +the collector does a stop-the-world major collection, +which traverses all objects. +The generational mode uses two parameters: +the minor multiplier and the the major multiplier. + + +

    +The minor multiplier controls the frequency of minor collections. +For a minor multiplier x, +a new minor collection will be done when memory +grows x% larger than the memory in use after the previous major +collection. +For instance, for a multiplier of 20, +the collector will do a minor collection when the use of memory +gets 20% larger than the use after the previous major collection. +The default value is 20; the maximum value is 200. + + +

    +The major multiplier controls the frequency of major collections. +For a major multiplier x, +a new major collection will be done when memory +grows x% larger than the memory in use after the previous major +collection. +For instance, for a multiplier of 100, +the collector will do a major collection when the use of memory +gets larger than twice the use after the previous collection. +The default value is 100; the maximum value is 1000. + + + + + +

    2.5.3 – Garbage-Collection Metamethods

    + +

    +You can set garbage-collector metamethods for tables +and, using the C API, +for full userdata (see §2.4). +These metamethods, called finalizers, +are called when the garbage collector detects that the +corresponding table or userdata is dead. +Finalizers allow you to coordinate Lua's garbage collection +with external resource management such as closing files, +network or database connections, +or freeing your own memory. + + +

    +For an object (table or userdata) to be finalized when collected, +you must mark it for finalization. + +You mark an object for finalization when you set its metatable +and the metatable has a __gc metamethod. +Note that if you set a metatable without a __gc field +and later create that field in the metatable, +the object will not be marked for finalization. + + +

    +When a marked object becomes dead, +it is not collected immediately by the garbage collector. +Instead, Lua puts it in a list. +After the collection, +Lua goes through that list. +For each object in the list, +it checks the object's __gc metamethod: +If it is present, +Lua calls it with the object as its single argument. + + +

    +At the end of each garbage-collection cycle, +the finalizers are called in +the reverse order that the objects were marked for finalization, +among those collected in that cycle; +that is, the first finalizer to be called is the one associated +with the object marked last in the program. +The execution of each finalizer may occur at any point during +the execution of the regular code. + + +

    +Because the object being collected must still be used by the finalizer, +that object (and other objects accessible only through it) +must be resurrected by Lua. +Usually, this resurrection is transient, +and the object memory is freed in the next garbage-collection cycle. +However, if the finalizer stores the object in some global place +(e.g., a global variable), +then the resurrection is permanent. +Moreover, if the finalizer marks a finalizing object for finalization again, +its finalizer will be called again in the next cycle where the +object is dead. +In any case, +the object memory is freed only in a GC cycle where +the object is dead and not marked for finalization. + + +

    +When you close a state (see lua_close), +Lua calls the finalizers of all objects marked for finalization, +following the reverse order that they were marked. +If any finalizer marks objects for collection during that phase, +these marks have no effect. + + +

    +Finalizers cannot yield nor run the garbage collector. +Because they can run in unpredictable times, +it is good practice to restrict each finalizer +to the minimum necessary to properly release +its associated resource. + + +

    +Any error while running a finalizer generates a warning; +the error is not propagated. + + + + + +

    2.5.4 – Weak Tables

    + +

    +A weak table is a table whose elements are +weak references. +A weak reference is ignored by the garbage collector. +In other words, +if the only references to an object are weak references, +then the garbage collector will collect that object. + + +

    +A weak table can have weak keys, weak values, or both. +A table with weak values allows the collection of its values, +but prevents the collection of its keys. +A table with both weak keys and weak values allows the collection of +both keys and values. +In any case, if either the key or the value is collected, +the whole pair is removed from the table. +The weakness of a table is controlled by the +__mode field of its metatable. +This metavalue, if present, must be one of the following strings: +"k", for a table with weak keys; +"v", for a table with weak values; +or "kv", for a table with both weak keys and values. + + +

    +A table with weak keys and strong values +is also called an ephemeron table. +In an ephemeron table, +a value is considered reachable only if its key is reachable. +In particular, +if the only reference to a key comes through its value, +the pair is removed. + + +

    +Any change in the weakness of a table may take effect only +at the next collect cycle. +In particular, if you change the weakness to a stronger mode, +Lua may still collect some items from that table +before the change takes effect. + + +

    +Only objects that have an explicit construction +are removed from weak tables. +Values, such as numbers and light C functions, +are not subject to garbage collection, +and therefore are not removed from weak tables +(unless their associated values are collected). +Although strings are subject to garbage collection, +they do not have an explicit construction and +their equality is by value; +they behave more like values than like objects. +Therefore, they are not removed from weak tables. + + +

    +Resurrected objects +(that is, objects being finalized +and objects accessible only through objects being finalized) +have a special behavior in weak tables. +They are removed from weak values before running their finalizers, +but are removed from weak keys only in the next collection +after running their finalizers, when such objects are actually freed. +This behavior allows the finalizer to access properties +associated with the object through weak tables. + + +

    +If a weak table is among the resurrected objects in a collection cycle, +it may not be properly cleared until the next cycle. + + + + + + + +

    2.6 – Coroutines

    + +

    +Lua supports coroutines, +also called collaborative multithreading. +A coroutine in Lua represents an independent thread of execution. +Unlike threads in multithread systems, however, +a coroutine only suspends its execution by explicitly calling +a yield function. + + +

    +You create a coroutine by calling coroutine.create. +Its sole argument is a function +that is the main function of the coroutine. +The create function only creates a new coroutine and +returns a handle to it (an object of type thread); +it does not start the coroutine. + + +

    +You execute a coroutine by calling coroutine.resume. +When you first call coroutine.resume, +passing as its first argument +a thread returned by coroutine.create, +the coroutine starts its execution by +calling its main function. +Extra arguments passed to coroutine.resume are passed +as arguments to that function. +After the coroutine starts running, +it runs until it terminates or yields. + + +

    +A coroutine can terminate its execution in two ways: +normally, when its main function returns +(explicitly or implicitly, after the last instruction); +and abnormally, if there is an unprotected error. +In case of normal termination, +coroutine.resume returns true, +plus any values returned by the coroutine main function. +In case of errors, coroutine.resume returns false +plus the error object. +In this case, the coroutine does not unwind its stack, +so that it is possible to inspect it after the error +with the debug API. + + +

    +A coroutine yields by calling coroutine.yield. +When a coroutine yields, +the corresponding coroutine.resume returns immediately, +even if the yield happens inside nested function calls +(that is, not in the main function, +but in a function directly or indirectly called by the main function). +In the case of a yield, coroutine.resume also returns true, +plus any values passed to coroutine.yield. +The next time you resume the same coroutine, +it continues its execution from the point where it yielded, +with the call to coroutine.yield returning any extra +arguments passed to coroutine.resume. + + +

    +Like coroutine.create, +the coroutine.wrap function also creates a coroutine, +but instead of returning the coroutine itself, +it returns a function that, when called, resumes the coroutine. +Any arguments passed to this function +go as extra arguments to coroutine.resume. +coroutine.wrap returns all the values returned by coroutine.resume, +except the first one (the boolean error code). +Unlike coroutine.resume, +the function created by coroutine.wrap +propagates any error to the caller. +In this case, +the function also closes the coroutine (see coroutine.close). + + +

    +As an example of how coroutines work, +consider the following code: + +

    +     function foo (a)
    +       print("foo", a)
    +       return coroutine.yield(2*a)
    +     end
    +     
    +     co = coroutine.create(function (a,b)
    +           print("co-body", a, b)
    +           local r = foo(a+1)
    +           print("co-body", r)
    +           local r, s = coroutine.yield(a+b, a-b)
    +           print("co-body", r, s)
    +           return b, "end"
    +     end)
    +     
    +     print("main", coroutine.resume(co, 1, 10))
    +     print("main", coroutine.resume(co, "r"))
    +     print("main", coroutine.resume(co, "x", "y"))
    +     print("main", coroutine.resume(co, "x", "y"))
    +

    +When you run it, it produces the following output: + +

    +     co-body 1       10
    +     foo     2
    +     main    true    4
    +     co-body r
    +     main    true    11      -9
    +     co-body x       y
    +     main    true    10      end
    +     main    false   cannot resume dead coroutine
    +
    + +

    +You can also create and manipulate coroutines through the C API: +see functions lua_newthread, lua_resume, +and lua_yield. + + + + + +

    3 – The Language

    + + + +

    +This section describes the lexis, the syntax, and the semantics of Lua. +In other words, +this section describes +which tokens are valid, +how they can be combined, +and what their combinations mean. + + +

    +Language constructs will be explained using the usual extended BNF notation, +in which +{a} means 0 or more a's, and +[a] means an optional a. +Non-terminals are shown like non-terminal, +keywords are shown like kword, +and other terminal symbols are shown like ‘=’. +The complete syntax of Lua can be found in §9 +at the end of this manual. + + + + + +

    3.1 – Lexical Conventions

    + +

    +Lua is a free-form language. +It ignores spaces and comments between lexical elements (tokens), +except as delimiters between two tokens. +In source code, +Lua recognizes as spaces the standard ASCII whitespace +characters space, form feed, newline, +carriage return, horizontal tab, and vertical tab. + + +

    +Names +(also called identifiers) +in Lua can be any string of Latin letters, +Arabic-Indic digits, and underscores, +not beginning with a digit and +not being a reserved word. +Identifiers are used to name variables, table fields, and labels. + + +

    +The following keywords are reserved +and cannot be used as names: + + +

    +     and       break     do        else      elseif    end
    +     false     for       function  goto      if        in
    +     local     nil       not       or        repeat    return
    +     then      true      until     while
    +
    + +

    +Lua is a case-sensitive language: +and is a reserved word, but And and AND +are two different, valid names. +As a convention, +programs should avoid creating +names that start with an underscore followed by +one or more uppercase letters (such as _VERSION). + + +

    +The following strings denote other tokens: + +

    +     +     -     *     /     %     ^     #
    +     &     ~     |     <<    >>    //
    +     ==    ~=    <=    >=    <     >     =
    +     (     )     {     }     [     ]     ::
    +     ;     :     ,     .     ..    ...
    +
    + +

    +A short literal string +can be delimited by matching single or double quotes, +and can contain the following C-like escape sequences: +'\a' (bell), +'\b' (backspace), +'\f' (form feed), +'\n' (newline), +'\r' (carriage return), +'\t' (horizontal tab), +'\v' (vertical tab), +'\\' (backslash), +'\"' (quotation mark [double quote]), +and '\'' (apostrophe [single quote]). +A backslash followed by a line break +results in a newline in the string. +The escape sequence '\z' skips the following span +of whitespace characters, +including line breaks; +it is particularly useful to break and indent a long literal string +into multiple lines without adding the newlines and spaces +into the string contents. +A short literal string cannot contain unescaped line breaks +nor escapes not forming a valid escape sequence. + + +

    +We can specify any byte in a short literal string, +including embedded zeros, +by its numeric value. +This can be done +with the escape sequence \xXX, +where XX is a sequence of exactly two hexadecimal digits, +or with the escape sequence \ddd, +where ddd is a sequence of up to three decimal digits. +(Note that if a decimal escape sequence is to be followed by a digit, +it must be expressed using exactly three digits.) + + +

    +The UTF-8 encoding of a Unicode character +can be inserted in a literal string with +the escape sequence \u{XXX} +(with mandatory enclosing braces), +where XXX is a sequence of one or more hexadecimal digits +representing the character code point. +This code point can be any value less than 231. +(Lua uses the original UTF-8 specification here, +which is not restricted to valid Unicode code points.) + + +

    +Literal strings can also be defined using a long format +enclosed by long brackets. +We define an opening long bracket of level n as an opening +square bracket followed by n equal signs followed by another +opening square bracket. +So, an opening long bracket of level 0 is written as [[, +an opening long bracket of level 1 is written as [=[, +and so on. +A closing long bracket is defined similarly; +for instance, +a closing long bracket of level 4 is written as ]====]. +A long literal starts with an opening long bracket of any level and +ends at the first closing long bracket of the same level. +It can contain any text except a closing bracket of the same level. +Literals in this bracketed form can run for several lines, +do not interpret any escape sequences, +and ignore long brackets of any other level. +Any kind of end-of-line sequence +(carriage return, newline, carriage return followed by newline, +or newline followed by carriage return) +is converted to a simple newline. +When the opening long bracket is immediately followed by a newline, +the newline is not included in the string. + + +

    +As an example, in a system using ASCII +(in which 'a' is coded as 97, +newline is coded as 10, and '1' is coded as 49), +the five literal strings below denote the same string: + +

    +     a = 'alo\n123"'
    +     a = "alo\n123\""
    +     a = '\97lo\10\04923"'
    +     a = [[alo
    +     123"]]
    +     a = [==[
    +     alo
    +     123"]==]
    +
    + +

    +Any byte in a literal string not +explicitly affected by the previous rules represents itself. +However, Lua opens files for parsing in text mode, +and the system's file functions may have problems with +some control characters. +So, it is safer to represent +binary data as a quoted literal with +explicit escape sequences for the non-text characters. + + +

    +A numeric constant (or numeral) +can be written with an optional fractional part +and an optional decimal exponent, +marked by a letter 'e' or 'E'. +Lua also accepts hexadecimal constants, +which start with 0x or 0X. +Hexadecimal constants also accept an optional fractional part +plus an optional binary exponent, +marked by a letter 'p' or 'P' and written in decimal. +(For instance, 0x1.fp10 denotes 1984, +which is 0x1f / 16 multiplied by 210.) + + +

    +A numeric constant with a radix point or an exponent +denotes a float; +otherwise, +if its value fits in an integer or it is a hexadecimal constant, +it denotes an integer; +otherwise (that is, a decimal integer numeral that overflows), +it denotes a float. +Hexadecimal numerals with neither a radix point nor an exponent +always denote an integer value; +if the value overflows, it wraps around +to fit into a valid integer. + + +

    +Examples of valid integer constants are + +

    +     3   345   0xff   0xBEBADA
    +

    +Examples of valid float constants are + +

    +     3.0     3.1416     314.16e-2     0.31416E1     34e1
    +     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
    +
    + +

    +A comment starts with a double hyphen (--) +anywhere outside a string. +If the text immediately after -- is not an opening long bracket, +the comment is a short comment, +which runs until the end of the line. +Otherwise, it is a long comment, +which runs until the corresponding closing long bracket. + + + + + +

    3.2 – Variables

    + +

    +Variables are places that store values. +There are three kinds of variables in Lua: +global variables, local variables, and table fields. + + +

    +A single name can denote a global variable or a local variable +(or a function's formal parameter, +which is a particular kind of local variable): + +

    +	var ::= Name
    +

    +Name denotes identifiers (see §3.1). + + +

    +Any variable name is assumed to be global unless explicitly declared +as a local (see §3.3.7). +Local variables are lexically scoped: +local variables can be freely accessed by functions +defined inside their scope (see §3.5). + + +

    +Before the first assignment to a variable, its value is nil. + + +

    +Square brackets are used to index a table: + +

    +	var ::= prefixexp ‘[’ exp ‘]’
    +

    +The meaning of accesses to table fields can be changed via metatables +(see §2.4). + + +

    +The syntax var.Name is just syntactic sugar for +var["Name"]: + +

    +	var ::= prefixexp ‘.’ Name
    +
    + +

    +An access to a global variable x +is equivalent to _ENV.x. +Due to the way that chunks are compiled, +the variable _ENV itself is never global (see §2.2). + + + + + +

    3.3 – Statements

    + + + +

    +Lua supports an almost conventional set of statements, +similar to those in other conventional languages. +This set includes +blocks, assignments, control structures, function calls, +and variable declarations. + + + + + +

    3.3.1 – Blocks

    + +

    +A block is a list of statements, +which are executed sequentially: + +

    +	block ::= {stat}
    +

    +Lua has empty statements +that allow you to separate statements with semicolons, +start a block with a semicolon +or write two semicolons in sequence: + +

    +	stat ::= ‘;’
    +
    + +

    +Both function calls and assignments +can start with an open parenthesis. +This possibility leads to an ambiguity in Lua's grammar. +Consider the following fragment: + +

    +     a = b + c
    +     (print or io.write)('done')
    +

    +The grammar could see this fragment in two ways: + +

    +     a = b + c(print or io.write)('done')
    +     
    +     a = b + c; (print or io.write)('done')
    +

    +The current parser always sees such constructions +in the first way, +interpreting the open parenthesis +as the start of the arguments to a call. +To avoid this ambiguity, +it is a good practice to always precede with a semicolon +statements that start with a parenthesis: + +

    +     ;(print or io.write)('done')
    +
    + +

    +A block can be explicitly delimited to produce a single statement: + +

    +	stat ::= do block end
    +

    +Explicit blocks are useful +to control the scope of variable declarations. +Explicit blocks are also sometimes used to +add a return statement in the middle +of another block (see §3.3.4). + + + + + +

    3.3.2 – Chunks

    + +

    +The unit of compilation of Lua is called a chunk. +Syntactically, +a chunk is simply a block: + +

    +	chunk ::= block
    +
    + +

    +Lua handles a chunk as the body of an anonymous function +with a variable number of arguments +(see §3.4.11). +As such, chunks can define local variables, +receive arguments, and return values. +Moreover, such anonymous function is compiled as in the +scope of an external local variable called _ENV (see §2.2). +The resulting function always has _ENV as its only external variable, +even if it does not use that variable. + + +

    +A chunk can be stored in a file or in a string inside the host program. +To execute a chunk, +Lua first loads it, +precompiling the chunk's code into instructions for a virtual machine, +and then Lua executes the compiled code +with an interpreter for the virtual machine. + + +

    +Chunks can also be precompiled into binary form; +see the program luac and the function string.dump for details. +Programs in source and compiled forms are interchangeable; +Lua automatically detects the file type and acts accordingly (see load). + + + + + +

    3.3.3 – Assignment

    + +

    +Lua allows multiple assignments. +Therefore, the syntax for assignment +defines a list of variables on the left side +and a list of expressions on the right side. +The elements in both lists are separated by commas: + +

    +	stat ::= varlist ‘=’ explist
    +	varlist ::= var {‘,’ var}
    +	explist ::= exp {‘,’ exp}
    +

    +Expressions are discussed in §3.4. + + +

    +Before the assignment, +the list of values is adjusted to the length of +the list of variables (see §3.4.12). + + +

    +If a variable is both assigned and read +inside a multiple assignment, +Lua ensures that all reads get the value of the variable +before the assignment. +Thus the code + +

    +     i = 3
    +     i, a[i] = i+1, 20
    +

    +sets a[3] to 20, without affecting a[4] +because the i in a[i] is evaluated (to 3) +before it is assigned 4. +Similarly, the line + +

    +     x, y = y, x
    +

    +exchanges the values of x and y, +and + +

    +     x, y, z = y, z, x
    +

    +cyclically permutes the values of x, y, and z. + + +

    +Note that this guarantee covers only accesses +syntactically inside the assignment statement. +If a function or a metamethod called during the assignment +changes the value of a variable, +Lua gives no guarantees about the order of that access. + + +

    +An assignment to a global name x = val +is equivalent to the assignment +_ENV.x = val (see §2.2). + + +

    +The meaning of assignments to table fields and +global variables (which are actually table fields, too) +can be changed via metatables (see §2.4). + + + + + +

    3.3.4 – Control Structures

    +The control structures +if, while, and repeat have the usual meaning and +familiar syntax: + + + + +

    +	stat ::= while exp do block end
    +	stat ::= repeat block until exp
    +	stat ::= if exp then block {elseif exp then block} [else block] end
    +

    +Lua also has a for statement, in two flavors (see §3.3.5). + + +

    +The condition expression of a +control structure can return any value. +Both false and nil test false. +All values different from nil and false test true. +In particular, the number 0 and the empty string also test true. + + +

    +In the repeatuntil loop, +the inner block does not end at the until keyword, +but only after the condition. +So, the condition can refer to local variables +declared inside the loop block. + + +

    +The goto statement transfers the program control to a label. +For syntactical reasons, +labels in Lua are considered statements too: + + + +

    +	stat ::= goto Name
    +	stat ::= label
    +	label ::= ‘::’ Name ‘::’
    +
    + +

    +A label is visible in the entire block where it is defined, +except inside nested functions. +A goto may jump to any visible label as long as it does not +enter into the scope of a local variable. +A label should not be declared +where a label with the same name is visible, +even if this other label has been declared in an enclosing block. + + +

    +The break statement terminates the execution of a +while, repeat, or for loop, +skipping to the next statement after the loop: + + +

    +	stat ::= break
    +

    +A break ends the innermost enclosing loop. + + +

    +The return statement is used to return values +from a function or a chunk +(which is handled as an anonymous function). + +Functions can return more than one value, +so the syntax for the return statement is + +

    +	stat ::= return [explist] [‘;’]
    +
    + +

    +The return statement can only be written +as the last statement of a block. +If it is necessary to return in the middle of a block, +then an explicit inner block can be used, +as in the idiom do return end, +because now return is the last statement in its (inner) block. + + + + + +

    3.3.5 – For Statement

    + +

    + +The for statement has two forms: +one numerical and one generic. + + + +

    The numerical for loop

    + +

    +The numerical for loop repeats a block of code while a +control variable goes through an arithmetic progression. +It has the following syntax: + +

    +	stat ::= for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end
    +

    +The given identifier (Name) defines the control variable, +which is a new variable local to the loop body (block). + + +

    +The loop starts by evaluating once the three control expressions. +Their values are called respectively +the initial value, the limit, and the step. +If the step is absent, it defaults to 1. + + +

    +If both the initial value and the step are integers, +the loop is done with integers; +note that the limit may not be an integer. +Otherwise, the three values are converted to +floats and the loop is done with floats. +Beware of floating-point accuracy in this case. + + +

    +After that initialization, +the loop body is repeated with the value of the control variable +going through an arithmetic progression, +starting at the initial value, +with a common difference given by the step. +A negative step makes a decreasing sequence; +a step equal to zero raises an error. +The loop continues while the value is less than +or equal to the limit +(greater than or equal to for a negative step). +If the initial value is already greater than the limit +(or less than, if the step is negative), +the body is not executed. + + +

    +For integer loops, +the control variable never wraps around; +instead, the loop ends in case of an overflow. + + +

    +You should not change the value of the control variable +during the loop. +If you need its value after the loop, +assign it to another variable before exiting the loop. + + + + + +

    The generic for loop

    + +

    +The generic for statement works over functions, +called iterators. +On each iteration, the iterator function is called to produce a new value, +stopping when this new value is nil. +The generic for loop has the following syntax: + +

    +	stat ::= for namelist in explist do block end
    +	namelist ::= Name {‘,’ Name}
    +

    +A for statement like + +

    +     for var_1, ···, var_n in explist do body end
    +

    +works as follows. + + +

    +The names var_i declare loop variables local to the loop body. +The first of these variables is the control variable. + + +

    +The loop starts by evaluating explist +to produce four values: +an iterator function, +a state, +an initial value for the control variable, +and a closing value. + + +

    +Then, at each iteration, +Lua calls the iterator function with two arguments: +the state and the control variable. +The results from this call are then assigned to the loop variables, +following the rules of multiple assignments (see §3.3.3). +If the control variable becomes nil, +the loop terminates. +Otherwise, the body is executed and the loop goes +to the next iteration. + + +

    +The closing value behaves like a +to-be-closed variable (see §3.3.8), +which can be used to release resources when the loop ends. +Otherwise, it does not interfere with the loop. + + +

    +You should not change the value of the control variable +during the loop. + + + + + + + +

    3.3.6 – Function Calls as Statements

    +To allow possible side-effects, +function calls can be executed as statements: + +

    +	stat ::= functioncall
    +

    +In this case, all returned values are thrown away. +Function calls are explained in §3.4.10. + + + + + +

    3.3.7 – Local Declarations

    +Local variables can be declared anywhere inside a block. +The declaration can include an initialization: + +

    +	stat ::= local attnamelist [‘=’ explist]
    +	attnamelist ::=  Name attrib {‘,’ Name attrib}
    +

    +If present, an initial assignment has the same semantics +of a multiple assignment (see §3.3.3). +Otherwise, all variables are initialized with nil. + + +

    +Each variable name may be postfixed by an attribute +(a name between angle brackets): + +

    +	attrib ::= [‘<’ Name ‘>’]
    +

    +There are two possible attributes: +const, which declares a constant variable, +that is, a variable that cannot be assigned to +after its initialization; +and close, which declares a to-be-closed variable (see §3.3.8). +A list of variables can contain at most one to-be-closed variable. + + +

    +A chunk is also a block (see §3.3.2), +and so local variables can be declared in a chunk outside any explicit block. + + +

    +The visibility rules for local variables are explained in §3.5. + + + + + +

    3.3.8 – To-be-closed Variables

    + +

    +A to-be-closed variable behaves like a constant local variable, +except that its value is closed whenever the variable +goes out of scope, including normal block termination, +exiting its block by break/goto/return, +or exiting by an error. + + +

    +Here, to close a value means +to call its __close metamethod. +When calling the metamethod, +the value itself is passed as the first argument +and the error object that caused the exit (if any) +is passed as a second argument; +if there was no error, the second argument is nil. + + +

    +The value assigned to a to-be-closed variable +must have a __close metamethod +or be a false value. +(nil and false are ignored as to-be-closed values.) + + +

    +If several to-be-closed variables go out of scope at the same event, +they are closed in the reverse order that they were declared. + + +

    +If there is any error while running a closing method, +that error is handled like an error in the regular code +where the variable was defined. +After an error, +the other pending closing methods will still be called. + + +

    +If a coroutine yields and is never resumed again, +some variables may never go out of scope, +and therefore they will never be closed. +(These variables are the ones created inside the coroutine +and in scope at the point where the coroutine yielded.) +Similarly, if a coroutine ends with an error, +it does not unwind its stack, +so it does not close any variable. +In both cases, +you can either use finalizers +or call coroutine.close to close the variables. +However, if the coroutine was created +through coroutine.wrap, +then its corresponding function will close the coroutine +in case of errors. + + + + + + + +

    3.4 – Expressions

    + + + +

    +The basic expressions in Lua are the following: + +

    +	exp ::= prefixexp
    +	exp ::= nil | false | true
    +	exp ::= Numeral
    +	exp ::= LiteralString
    +	exp ::= functiondef
    +	exp ::= tableconstructor
    +	exp ::= ‘...’
    +	exp ::= exp binop exp
    +	exp ::= unop exp
    +	prefixexp ::= var | functioncall | ‘(’ exp ‘)’
    +
    + +

    +Numerals and literal strings are explained in §3.1; +variables are explained in §3.2; +function definitions are explained in §3.4.11; +function calls are explained in §3.4.10; +table constructors are explained in §3.4.9. +Vararg expressions, +denoted by three dots ('...'), can only be used when +directly inside a variadic function; +they are explained in §3.4.11. + + +

    +Binary operators comprise arithmetic operators (see §3.4.1), +bitwise operators (see §3.4.2), +relational operators (see §3.4.4), logical operators (see §3.4.5), +and the concatenation operator (see §3.4.6). +Unary operators comprise the unary minus (see §3.4.1), +the unary bitwise NOT (see §3.4.2), +the unary logical not (see §3.4.5), +and the unary length operator (see §3.4.7). + + + + + +

    3.4.1 – Arithmetic Operators

    +Lua supports the following arithmetic operators: + +

      +
    • +: addition
    • +
    • -: subtraction
    • +
    • *: multiplication
    • +
    • /: float division
    • +
    • //: floor division
    • +
    • %: modulo
    • +
    • ^: exponentiation
    • +
    • -: unary minus
    • +
    + +

    +With the exception of exponentiation and float division, +the arithmetic operators work as follows: +If both operands are integers, +the operation is performed over integers and the result is an integer. +Otherwise, if both operands are numbers, +then they are converted to floats, +the operation is performed following the machine's rules +for floating-point arithmetic +(usually the IEEE 754 standard), +and the result is a float. +(The string library coerces strings to numbers in +arithmetic operations; see §3.4.3 for details.) + + +

    +Exponentiation and float division (/) +always convert their operands to floats +and the result is always a float. +Exponentiation uses the ISO C function pow, +so that it works for non-integer exponents too. + + +

    +Floor division (//) is a division +that rounds the quotient towards minus infinity, +resulting in the floor of the division of its operands. + + +

    +Modulo is defined as the remainder of a division +that rounds the quotient towards minus infinity (floor division). + + +

    +In case of overflows in integer arithmetic, +all operations wrap around. + + + +

    3.4.2 – Bitwise Operators

    +Lua supports the following bitwise operators: + +

      +
    • &: bitwise AND
    • +
    • |: bitwise OR
    • +
    • ~: bitwise exclusive OR
    • +
    • >>: right shift
    • +
    • <<: left shift
    • +
    • ~: unary bitwise NOT
    • +
    + +

    +All bitwise operations convert its operands to integers +(see §3.4.3), +operate on all bits of those integers, +and result in an integer. + + +

    +Both right and left shifts fill the vacant bits with zeros. +Negative displacements shift to the other direction; +displacements with absolute values equal to or higher than +the number of bits in an integer +result in zero (as all bits are shifted out). + + + + + +

    3.4.3 – Coercions and Conversions

    +Lua provides some automatic conversions between some +types and representations at run time. +Bitwise operators always convert float operands to integers. +Exponentiation and float division +always convert integer operands to floats. +All other arithmetic operations applied to mixed numbers +(integers and floats) convert the integer operand to a float. +The C API also converts both integers to floats and +floats to integers, as needed. +Moreover, string concatenation accepts numbers as arguments, +besides strings. + + +

    +In a conversion from integer to float, +if the integer value has an exact representation as a float, +that is the result. +Otherwise, +the conversion gets the nearest higher or +the nearest lower representable value. +This kind of conversion never fails. + + +

    +The conversion from float to integer +checks whether the float has an exact representation as an integer +(that is, the float has an integral value and +it is in the range of integer representation). +If it does, that representation is the result. +Otherwise, the conversion fails. + + +

    +Several places in Lua coerce strings to numbers when necessary. +In particular, +the string library sets metamethods that try to coerce +strings to numbers in all arithmetic operations. +If the conversion fails, +the library calls the metamethod of the other operand +(if present) or it raises an error. +Note that bitwise operators do not do this coercion. + + +

    +It is always a good practice not to rely on the +implicit coercions from strings to numbers, +as they are not always applied; +in particular, "1"==1 is false and "1"<1 raises an error +(see §3.4.4). +These coercions exist mainly for compatibility and may be removed +in future versions of the language. + + +

    +A string is converted to an integer or a float +following its syntax and the rules of the Lua lexer. +The string may have also leading and trailing whitespaces and a sign. +All conversions from strings to numbers +accept both a dot and the current locale mark +as the radix character. +(The Lua lexer, however, accepts only a dot.) +If the string is not a valid numeral, +the conversion fails. +If necessary, the result of this first step is then converted +to a specific number subtype following the previous rules +for conversions between floats and integers. + + +

    +The conversion from numbers to strings uses a +non-specified human-readable format. +To convert numbers to strings in any specific way, +use the function string.format. + + + + + +

    3.4.4 – Relational Operators

    +Lua supports the following relational operators: + +

      +
    • ==: equality
    • +
    • ~=: inequality
    • +
    • <: less than
    • +
    • >: greater than
    • +
    • <=: less or equal
    • +
    • >=: greater or equal
    • +

    +These operators always result in false or true. + + +

    +Equality (==) first compares the type of its operands. +If the types are different, then the result is false. +Otherwise, the values of the operands are compared. +Strings are equal if they have the same byte content. +Numbers are equal if they denote the same mathematical value. + + +

    +Tables, userdata, and threads +are compared by reference: +two objects are considered equal only if they are the same object. +Every time you create a new object +(a table, a userdata, or a thread), +this new object is different from any previously existing object. +A function is always equal to itself. +Functions with any detectable difference +(different behavior, different definition) are always different. +Functions created at different times but with no detectable differences +may be classified as equal or not +(depending on internal caching details). + + +

    +You can change the way that Lua compares tables and userdata +by using the __eq metamethod (see §2.4). + + +

    +Equality comparisons do not convert strings to numbers +or vice versa. +Thus, "0"==0 evaluates to false, +and t[0] and t["0"] denote different +entries in a table. + + +

    +The operator ~= is exactly the negation of equality (==). + + +

    +The order operators work as follows. +If both arguments are numbers, +then they are compared according to their mathematical values, +regardless of their subtypes. +Otherwise, if both arguments are strings, +then their values are compared according to the current locale. +Otherwise, Lua tries to call the __lt or the __le +metamethod (see §2.4). +A comparison a > b is translated to b < a +and a >= b is translated to b <= a. + + +

    +Following the IEEE 754 standard, +the special value NaN is considered neither less than, +nor equal to, nor greater than any value, including itself. + + + + + +

    3.4.5 – Logical Operators

    +The logical operators in Lua are +and, or, and not. +Like the control structures (see §3.3.4), +all logical operators consider both false and nil as false +and anything else as true. + + +

    +The negation operator not always returns false or true. +The conjunction operator and returns its first argument +if this value is false or nil; +otherwise, and returns its second argument. +The disjunction operator or returns its first argument +if this value is different from nil and false; +otherwise, or returns its second argument. +Both and and or use short-circuit evaluation; +that is, +the second operand is evaluated only if necessary. +Here are some examples: + +

    +     10 or 20            --> 10
    +     10 or error()       --> 10
    +     nil or "a"          --> "a"
    +     nil and 10          --> nil
    +     false and error()   --> false
    +     false and nil       --> false
    +     false or nil        --> nil
    +     10 and 20           --> 20
    +
    + + + + +

    3.4.6 – Concatenation

    +The string concatenation operator in Lua is +denoted by two dots ('..'). +If both operands are strings or numbers, +then the numbers are converted to strings +in a non-specified format (see §3.4.3). +Otherwise, the __concat metamethod is called (see §2.4). + + + + + +

    3.4.7 – The Length Operator

    + +

    +The length operator is denoted by the unary prefix operator #. + + +

    +The length of a string is its number of bytes. +(That is the usual meaning of string length when each +character is one byte.) + + +

    +The length operator applied on a table +returns a border in that table. +A border in a table t is any non-negative integer +that satisfies the following condition: + +

    +     (border == 0 or t[border] ~= nil) and
    +     (t[border + 1] == nil or border == math.maxinteger)
    +

    +In words, +a border is any positive integer index present in the table +that is followed by an absent index, +plus two limit cases: +zero, when index 1 is absent; +and the maximum value for an integer, when that index is present. +Note that keys that are not positive integers +do not interfere with borders. + + +

    +A table with exactly one border is called a sequence. +For instance, the table {10, 20, 30, 40, 50} is a sequence, +as it has only one border (5). +The table {10, 20, 30, nil, 50} has two borders (3 and 5), +and therefore it is not a sequence. +(The nil at index 4 is called a hole.) +The table {nil, 20, 30, nil, nil, 60, nil} +has three borders (0, 3, and 6), +so it is not a sequence, too. +The table {} is a sequence with border 0. + + +

    +When t is a sequence, +#t returns its only border, +which corresponds to the intuitive notion of the length of the sequence. +When t is not a sequence, +#t can return any of its borders. +(The exact one depends on details of +the internal representation of the table, +which in turn can depend on how the table was populated and +the memory addresses of its non-numeric keys.) + + +

    +The computation of the length of a table +has a guaranteed worst time of O(log n), +where n is the largest integer key in the table. + + +

    +A program can modify the behavior of the length operator for +any value but strings through the __len metamethod (see §2.4). + + + + + +

    3.4.8 – Precedence

    +Operator precedence in Lua follows the table below, +from lower to higher priority: + +

    +     or
    +     and
    +     <     >     <=    >=    ~=    ==
    +     |
    +     ~
    +     &
    +     <<    >>
    +     ..
    +     +     -
    +     *     /     //    %
    +     unary operators (not   #     -     ~)
    +     ^
    +

    +As usual, +you can use parentheses to change the precedences of an expression. +The concatenation ('..') and exponentiation ('^') +operators are right associative. +All other binary operators are left associative. + + + + + +

    3.4.9 – Table Constructors

    +Table constructors are expressions that create tables. +Every time a constructor is evaluated, a new table is created. +A constructor can be used to create an empty table +or to create a table and initialize some of its fields. +The general syntax for constructors is + +

    +	tableconstructor ::= ‘{’ [fieldlist] ‘}’
    +	fieldlist ::= field {fieldsep field} [fieldsep]
    +	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
    +	fieldsep ::= ‘,’ | ‘;’
    +
    + +

    +Each field of the form [exp1] = exp2 adds to the new table an entry +with key exp1 and value exp2. +A field of the form name = exp is equivalent to +["name"] = exp. +Fields of the form exp are equivalent to +[i] = exp, where i are consecutive integers +starting with 1; +fields in the other formats do not affect this counting. +For example, + +

    +     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
    +

    +is equivalent to + +

    +     do
    +       local t = {}
    +       t[f(1)] = g
    +       t[1] = "x"         -- 1st exp
    +       t[2] = "y"         -- 2nd exp
    +       t.x = 1            -- t["x"] = 1
    +       t[3] = f(x)        -- 3rd exp
    +       t[30] = 23
    +       t[4] = 45          -- 4th exp
    +       a = t
    +     end
    +
    + +

    +The order of the assignments in a constructor is undefined. +(This order would be relevant only when there are repeated keys.) + + +

    +If the last field in the list has the form exp +and the expression is a multires expression, +then all values returned by this expression enter the list consecutively +(see §3.4.12). + + +

    +The field list can have an optional trailing separator, +as a convenience for machine-generated code. + + + + + +

    3.4.10 – Function Calls

    +A function call in Lua has the following syntax: + +

    +	functioncall ::= prefixexp args
    +

    +In a function call, +first prefixexp and args are evaluated. +If the value of prefixexp has type function, +then this function is called +with the given arguments. +Otherwise, if present, +the prefixexp __call metamethod is called: +its first argument is the value of prefixexp, +followed by the original call arguments +(see §2.4). + + +

    +The form + +

    +	functioncall ::= prefixexp ‘:’ Name args
    +

    +can be used to emulate methods. +A call v:name(args) +is syntactic sugar for v.name(v,args), +except that v is evaluated only once. + + +

    +Arguments have the following syntax: + +

    +	args ::= ‘(’ [explist] ‘)’
    +	args ::= tableconstructor
    +	args ::= LiteralString
    +

    +All argument expressions are evaluated before the call. +A call of the form f{fields} is +syntactic sugar for f({fields}); +that is, the argument list is a single new table. +A call of the form f'string' +(or f"string" or f[[string]]) +is syntactic sugar for f('string'); +that is, the argument list is a single literal string. + + +

    +A call of the form return functioncall not in the +scope of a to-be-closed variable is called a tail call. +Lua implements proper tail calls +(or proper tail recursion): +In a tail call, +the called function reuses the stack entry of the calling function. +Therefore, there is no limit on the number of nested tail calls that +a program can execute. +However, a tail call erases any debug information about the +calling function. +Note that a tail call only happens with a particular syntax, +where the return has one single function call as argument, +and it is outside the scope of any to-be-closed variable. +This syntax makes the calling function return exactly +the returns of the called function, +without any intervening action. +So, none of the following examples are tail calls: + +

    +     return (f(x))        -- results adjusted to 1
    +     return 2 * f(x)      -- result multiplied by 2
    +     return x, f(x)       -- additional results
    +     f(x); return         -- results discarded
    +     return x or f(x)     -- results adjusted to 1
    +
    + + + + +

    3.4.11 – Function Definitions

    + +

    +The syntax for function definition is + +

    +	functiondef ::= function funcbody
    +	funcbody ::= ‘(’ [parlist] ‘)’ block end
    +
    + +

    +The following syntactic sugar simplifies function definitions: + +

    +	stat ::= function funcname funcbody
    +	stat ::= local function Name funcbody
    +	funcname ::= Name {‘.’ Name} [‘:’ Name]
    +

    +The statement + +

    +     function f () body end
    +

    +translates to + +

    +     f = function () body end
    +

    +The statement + +

    +     function t.a.b.c.f () body end
    +

    +translates to + +

    +     t.a.b.c.f = function () body end
    +

    +The statement + +

    +     local function f () body end
    +

    +translates to + +

    +     local f; f = function () body end
    +

    +not to + +

    +     local f = function () body end
    +

    +(This only makes a difference when the body of the function +contains references to f.) + + +

    +A function definition is an executable expression, +whose value has type function. +When Lua precompiles a chunk, +all its function bodies are precompiled too, +but they are not created yet. +Then, whenever Lua executes the function definition, +the function is instantiated (or closed). +This function instance, or closure, +is the final value of the expression. + + +

    +Parameters act as local variables that are +initialized with the argument values: + +

    +	parlist ::= namelist [‘,’ ‘...’] | ‘...’
    +

    +When a Lua function is called, +it adjusts its list of arguments to +the length of its list of parameters (see §3.4.12), +unless the function is a variadic function, +which is indicated by three dots ('...') +at the end of its parameter list. +A variadic function does not adjust its argument list; +instead, it collects all extra arguments and supplies them +to the function through a vararg expression, +which is also written as three dots. +The value of this expression is a list of all actual extra arguments, +similar to a function with multiple results (see §3.4.12). + + +

    +As an example, consider the following definitions: + +

    +     function f(a, b) end
    +     function g(a, b, ...) end
    +     function r() return 1,2,3 end
    +

    +Then, we have the following mapping from arguments to parameters and +to the vararg expression: + +

    +     CALL             PARAMETERS
    +     
    +     f(3)             a=3, b=nil
    +     f(3, 4)          a=3, b=4
    +     f(3, 4, 5)       a=3, b=4
    +     f(r(), 10)       a=1, b=10
    +     f(r())           a=1, b=2
    +     
    +     g(3)             a=3, b=nil, ... -->  (nothing)
    +     g(3, 4)          a=3, b=4,   ... -->  (nothing)
    +     g(3, 4, 5, 8)    a=3, b=4,   ... -->  5  8
    +     g(5, r())        a=5, b=1,   ... -->  2  3
    +
    + +

    +Results are returned using the return statement (see §3.3.4). +If control reaches the end of a function +without encountering a return statement, +then the function returns with no results. + + +

    + +There is a system-dependent limit on the number of values +that a function may return. +This limit is guaranteed to be greater than 1000. + + +

    +The colon syntax +is used to emulate methods, +adding an implicit extra parameter self to the function. +Thus, the statement + +

    +     function t.a.b.c:f (params) body end
    +

    +is syntactic sugar for + +

    +     t.a.b.c.f = function (self, params) body end
    +
    + + + + +

    3.4.12 – Lists of expressions, multiple results, +and adjustment

    + +

    +Both function calls and vararg expressions can result in multiple values. +These expressions are called multires expressions. + + +

    +When a multires expression is used as the last element +of a list of expressions, +all results from the expression are added to the +list of values produced by the list of expressions. +Note that a single expression +in a place that expects a list of expressions +is the last expression in that (singleton) list. + + +

    +These are the places where Lua expects a list of expressions: + +

      + +
    • A return statement, +for instance return e1, e2, e3 (see §3.3.4).
    • + +
    • A table constructor, +for instance {e1, e2, e3} (see §3.4.9).
    • + +
    • The arguments of a function call, +for instance foo(e1, e2, e3) (see §3.4.10).
    • + +
    • A multiple assignment, +for instance a , b, c = e1, e2, e3 (see §3.3.3).
    • + +
    • A local declaration, +for instance local a , b, c = e1, e2, e3 (see §3.3.7).
    • + +
    • The initial values in a generic for loop, +for instance for k in e1, e2, e3 do ... end (see §3.3.5).
    • + +

    +In the last four cases, +the list of values from the list of expressions +must be adjusted to a specific length: +the number of parameters in a call to a non-variadic function +(see §3.4.11), +the number of variables in a multiple assignment or +a local declaration, +and exactly four values for a generic for loop. +The adjustment follows these rules: +If there are more values than needed, +the extra values are thrown away; +if there are fewer values than needed, +the list is extended with nil's. +When the list of expressions ends with a multires expression, +all results from that expression enter the list of values +before the adjustment. + + +

    +When a multires expression is used +in a list of expressions without being the last element, +or in a place where the syntax expects a single expression, +Lua adjusts the result list of that expression to one element. +As a particular case, +the syntax expects a single expression inside a parenthesized expression; +therefore, adding parentheses around a multires expression +forces it to produce exactly one result. + + +

    +We seldom need to use a vararg expression in a place +where the syntax expects a single expression. +(Usually it is simpler to add a regular parameter before +the variadic part and use that parameter.) +When there is such a need, +we recommend assigning the vararg expression +to a single variable and using that variable +in its place. + + +

    +Here are some examples of uses of mutlres expressions. +In all cases, when the construction needs +"the n-th result" and there is no such result, +it uses a nil. + +

    +     print(x, f())      -- prints x and all results from f().
    +     print(x, (f()))    -- prints x and the first result from f().
    +     print(f(), x)      -- prints the first result from f() and x.
    +     print(1 + f())     -- prints 1 added to the first result from f().
    +     local x = ...      -- x gets the first vararg argument.
    +     x,y = ...          -- x gets the first vararg argument,
    +                        -- y gets the second vararg argument.
    +     x,y,z = w, f()     -- x gets w, y gets the first result from f(),
    +                        -- z gets the second result from f().
    +     x,y,z = f()        -- x gets the first result from f(),
    +                        -- y gets the second result from f(),
    +                        -- z gets the third result from f().
    +     x,y,z = f(), g()   -- x gets the first result from f(),
    +                        -- y gets the first result from g(),
    +                        -- z gets the second result from g().
    +     x,y,z = (f())      -- x gets the first result from f(), y and z get nil.
    +     return f()         -- returns all results from f().
    +     return x, ...      -- returns x and all received vararg arguments.
    +     return x,y,f()     -- returns x, y, and all results from f().
    +     {f()}              -- creates a list with all results from f().
    +     {...}              -- creates a list with all vararg arguments.
    +     {f(), 5}           -- creates a list with the first result from f() and 5.
    +
    + + + + + + +

    3.5 – Visibility Rules

    + +

    + +Lua is a lexically scoped language. +The scope of a local variable begins at the first statement after +its declaration and lasts until the last non-void statement +of the innermost block that includes the declaration. +(Void statements are labels and empty statements.) +Consider the following example: + +

    +     x = 10                -- global variable
    +     do                    -- new block
    +       local x = x         -- new 'x', with value 10
    +       print(x)            --> 10
    +       x = x+1
    +       do                  -- another block
    +         local x = x+1     -- another 'x'
    +         print(x)          --> 12
    +       end
    +       print(x)            --> 11
    +     end
    +     print(x)              --> 10  (the global one)
    +
    + +

    +Notice that, in a declaration like local x = x, +the new x being declared is not in scope yet, +and so the second x refers to the outside variable. + + +

    +Because of the lexical scoping rules, +local variables can be freely accessed by functions +defined inside their scope. +A local variable used by an inner function is called an upvalue +(or external local variable, or simply external variable) +inside the inner function. + + +

    +Notice that each execution of a local statement +defines new local variables. +Consider the following example: + +

    +     a = {}
    +     local x = 20
    +     for i = 1, 10 do
    +       local y = 0
    +       a[i] = function () y = y + 1; return x + y end
    +     end
    +

    +The loop creates ten closures +(that is, ten instances of the anonymous function). +Each of these closures uses a different y variable, +while all of them share the same x. + + + + + +

    4 – The Application Program Interface

    + + + +

    + +This section describes the C API for Lua, that is, +the set of C functions available to the host program to communicate +with Lua. +All API functions and related types and constants +are declared in the header file lua.h. + + +

    +Even when we use the term "function", +any facility in the API may be provided as a macro instead. +Except where stated otherwise, +all such macros use each of their arguments exactly once +(except for the first argument, which is always a Lua state), +and so do not generate any hidden side-effects. + + +

    +As in most C libraries, +the Lua API functions do not check their arguments +for validity or consistency. +However, you can change this behavior by compiling Lua +with the macro LUA_USE_APICHECK defined. + + +

    +The Lua library is fully reentrant: +it has no global variables. +It keeps all information it needs in a dynamic structure, +called the Lua state. + + +

    +Each Lua state has one or more threads, +which correspond to independent, cooperative lines of execution. +The type lua_State (despite its name) refers to a thread. +(Indirectly, through the thread, it also refers to the +Lua state associated to the thread.) + + +

    +A pointer to a thread must be passed as the first argument to +every function in the library, except to lua_newstate, +which creates a Lua state from scratch and returns a pointer +to the main thread in the new state. + + + + + +

    4.1 – The Stack

    + + + +

    +Lua uses a virtual stack to pass values to and from C. +Each element in this stack represents a Lua value +(nil, number, string, etc.). +Functions in the API can access this stack through the +Lua state parameter that they receive. + + +

    +Whenever Lua calls C, the called function gets a new stack, +which is independent of previous stacks and of stacks of +C functions that are still active. +This stack initially contains any arguments to the C function +and it is where the C function can store temporary +Lua values and must push its results +to be returned to the caller (see lua_CFunction). + + +

    +For convenience, +most query operations in the API do not follow a strict stack discipline. +Instead, they can refer to any element in the stack +by using an index: +A positive index represents an absolute stack position, +starting at 1 as the bottom of the stack; +a negative index represents an offset relative to the top of the stack. +More specifically, if the stack has n elements, +then index 1 represents the first element +(that is, the element that was pushed onto the stack first) +and +index n represents the last element; +index -1 also represents the last element +(that is, the element at the top) +and index -n represents the first element. + + + + + +

    4.1.1 – Stack Size

    + +

    +When you interact with the Lua API, +you are responsible for ensuring consistency. +In particular, +you are responsible for controlling stack overflow. +When you call any API function, +you must ensure the stack has enough room to accommodate the results. + + +

    +There is one exception to the above rule: +When you call a Lua function +without a fixed number of results (see lua_call), +Lua ensures that the stack has enough space for all results. +However, it does not ensure any extra space. +So, before pushing anything on the stack after such a call +you should use lua_checkstack. + + +

    +Whenever Lua calls C, +it ensures that the stack has space for +at least LUA_MINSTACK extra elements; +that is, you can safely push up to LUA_MINSTACK values into it. +LUA_MINSTACK is defined as 20, +so that usually you do not have to worry about stack space +unless your code has loops pushing elements onto the stack. +Whenever necessary, +you can use the function lua_checkstack +to ensure that the stack has enough space for pushing new elements. + + + + + +

    4.1.2 – Valid and Acceptable Indices

    + +

    +Any function in the API that receives stack indices +works only with valid indices or acceptable indices. + + +

    +A valid index is an index that refers to a +position that stores a modifiable Lua value. +It comprises stack indices between 1 and the stack top +(1 ≤ abs(index) ≤ top) + +plus pseudo-indices, +which represent some positions that are accessible to C code +but that are not in the stack. +Pseudo-indices are used to access the registry (see §4.3) +and the upvalues of a C function (see §4.2). + + +

    +Functions that do not need a specific mutable position, +but only a value (e.g., query functions), +can be called with acceptable indices. +An acceptable index can be any valid index, +but it also can be any positive index after the stack top +within the space allocated for the stack, +that is, indices up to the stack size. +(Note that 0 is never an acceptable index.) +Indices to upvalues (see §4.2) greater than the real number +of upvalues in the current C function are also acceptable (but invalid). +Except when noted otherwise, +functions in the API work with acceptable indices. + + +

    +Acceptable indices serve to avoid extra tests +against the stack top when querying the stack. +For instance, a C function can query its third argument +without the need to check whether there is a third argument, +that is, without the need to check whether 3 is a valid index. + + +

    +For functions that can be called with acceptable indices, +any non-valid index is treated as if it +contains a value of a virtual type LUA_TNONE, +which behaves like a nil value. + + + + + +

    4.1.3 – Pointers to strings

    + +

    +Several functions in the API return pointers (const char*) +to Lua strings in the stack. +(See lua_pushfstring, lua_pushlstring, +lua_pushstring, and lua_tolstring. +See also luaL_checklstring, luaL_checkstring, +and luaL_tolstring in the auxiliary library.) + + +

    +In general, +Lua's garbage collection can free or move internal memory +and then invalidate pointers to internal strings. +To allow a safe use of these pointers, +the API guarantees that any pointer to a string in a stack index +is valid while the string value at that index is not removed from the stack. +(It can be moved to another index, though.) +When the index is a pseudo-index (referring to an upvalue), +the pointer is valid while the corresponding call is active and +the corresponding upvalue is not modified. + + +

    +Some functions in the debug interface +also return pointers to strings, +namely lua_getlocal, lua_getupvalue, +lua_setlocal, and lua_setupvalue. +For these functions, the pointer is guaranteed to +be valid while the caller function is active and +the given closure (if one was given) is in the stack. + + +

    +Except for these guarantees, +the garbage collector is free to invalidate +any pointer to internal strings. + + + + + + + +

    4.2 – C Closures

    + +

    +When a C function is created, +it is possible to associate some values with it, +thus creating a C closure +(see lua_pushcclosure); +these values are called upvalues and are +accessible to the function whenever it is called. + + +

    +Whenever a C function is called, +its upvalues are located at specific pseudo-indices. +These pseudo-indices are produced by the macro +lua_upvalueindex. +The first upvalue associated with a function is at index +lua_upvalueindex(1), and so on. +Any access to lua_upvalueindex(n), +where n is greater than the number of upvalues of the +current function +(but not greater than 256, +which is one plus the maximum number of upvalues in a closure), +produces an acceptable but invalid index. + + +

    +A C closure can also change the values +of its corresponding upvalues. + + + + + +

    4.3 – Registry

    + +

    +Lua provides a registry, +a predefined table that can be used by any C code to +store whatever Lua values it needs to store. +The registry table is always accessible at pseudo-index +LUA_REGISTRYINDEX. +Any C library can store data into this table, +but it must take care to choose keys +that are different from those used +by other libraries, to avoid collisions. +Typically, you should use as key a string containing your library name, +or a light userdata with the address of a C object in your code, +or any Lua object created by your code. +As with variable names, +string keys starting with an underscore followed by +uppercase letters are reserved for Lua. + + +

    +The integer keys in the registry are used +by the reference mechanism (see luaL_ref) +and by some predefined values. +Therefore, integer keys in the registry +must not be used for other purposes. + + +

    +When you create a new Lua state, +its registry comes with some predefined values. +These predefined values are indexed with integer keys +defined as constants in lua.h. +The following constants are defined: + +

      +
    • LUA_RIDX_MAINTHREAD: At this index the registry has +the main thread of the state. +(The main thread is the one created together with the state.) +
    • + +
    • LUA_RIDX_GLOBALS: At this index the registry has +the global environment. +
    • +
    + + + + +

    4.4 – Error Handling in C

    + + + +

    +Internally, Lua uses the C longjmp facility to handle errors. +(Lua will use exceptions if you compile it as C++; +search for LUAI_THROW in the source code for details.) +When Lua faces any error, +such as a memory allocation error or a type error, +it raises an error; +that is, it does a long jump. +A protected environment uses setjmp +to set a recovery point; +any error jumps to the most recent active recovery point. + + +

    +Inside a C function you can raise an error explicitly +by calling lua_error. + + +

    +Most functions in the API can raise an error, +for instance due to a memory allocation error. +The documentation for each function indicates whether +it can raise errors. + + +

    +If an error happens outside any protected environment, +Lua calls a panic function (see lua_atpanic) +and then calls abort, +thus exiting the host application. +Your panic function can avoid this exit by +never returning +(e.g., doing a long jump to your own recovery point outside Lua). + + +

    +The panic function, +as its name implies, +is a mechanism of last resort. +Programs should avoid it. +As a general rule, +when a C function is called by Lua with a Lua state, +it can do whatever it wants on that Lua state, +as it should be already protected. +However, +when C code operates on other Lua states +(e.g., a Lua-state argument to the function, +a Lua state stored in the registry, or +the result of lua_newthread), +it should use them only in API calls that cannot raise errors. + + +

    +The panic function runs as if it were a message handler (see §2.3); +in particular, the error object is on the top of the stack. +However, there is no guarantee about stack space. +To push anything on the stack, +the panic function must first check the available space (see §4.1.1). + + + + + +

    4.4.1 – Status Codes

    + +

    +Several functions that report errors in the API use the following +status codes to indicate different kinds of errors or other conditions: + +

      + +
    • LUA_OK (0): no errors.
    • + +
    • LUA_ERRRUN: a runtime error.
    • + +
    • LUA_ERRMEM: +memory allocation error. +For such errors, Lua does not call the message handler. +
    • + +
    • LUA_ERRERR: error while running the message handler.
    • + +
    • LUA_ERRSYNTAX: syntax error during precompilation.
    • + +
    • LUA_YIELD: the thread (coroutine) yields.
    • + +
    • LUA_ERRFILE: a file-related error; +e.g., it cannot open or read the file.
    • + +

    +These constants are defined in the header file lua.h. + + + + + + + +

    4.5 – Handling Yields in C

    + +

    +Internally, Lua uses the C longjmp facility to yield a coroutine. +Therefore, if a C function foo calls an API function +and this API function yields +(directly or indirectly by calling another function that yields), +Lua cannot return to foo any more, +because the longjmp removes its frame from the C stack. + + +

    +To avoid this kind of problem, +Lua raises an error whenever it tries to yield across an API call, +except for three functions: +lua_yieldk, lua_callk, and lua_pcallk. +All those functions receive a continuation function +(as a parameter named k) to continue execution after a yield. + + +

    +We need to set some terminology to explain continuations. +We have a C function called from Lua which we will call +the original function. +This original function then calls one of those three functions in the C API, +which we will call the callee function, +that then yields the current thread. +This can happen when the callee function is lua_yieldk, +or when the callee function is either lua_callk or lua_pcallk +and the function called by them yields. + + +

    +Suppose the running thread yields while executing the callee function. +After the thread resumes, +it eventually will finish running the callee function. +However, +the callee function cannot return to the original function, +because its frame in the C stack was destroyed by the yield. +Instead, Lua calls a continuation function, +which was given as an argument to the callee function. +As the name implies, +the continuation function should continue the task +of the original function. + + +

    +As an illustration, consider the following function: + +

    +     int original_function (lua_State *L) {
    +       ...     /* code 1 */
    +       status = lua_pcall(L, n, m, h);  /* calls Lua */
    +       ...     /* code 2 */
    +     }
    +

    +Now we want to allow +the Lua code being run by lua_pcall to yield. +First, we can rewrite our function like here: + +

    +     int k (lua_State *L, int status, lua_KContext ctx) {
    +       ...  /* code 2 */
    +     }
    +     
    +     int original_function (lua_State *L) {
    +       ...     /* code 1 */
    +       return k(L, lua_pcall(L, n, m, h), ctx);
    +     }
    +

    +In the above code, +the new function k is a +continuation function (with type lua_KFunction), +which should do all the work that the original function +was doing after calling lua_pcall. +Now, we must inform Lua that it must call k if the Lua code +being executed by lua_pcall gets interrupted in some way +(errors or yielding), +so we rewrite the code as here, +replacing lua_pcall by lua_pcallk: + +

    +     int original_function (lua_State *L) {
    +       ...     /* code 1 */
    +       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
    +     }
    +

    +Note the external, explicit call to the continuation: +Lua will call the continuation only if needed, that is, +in case of errors or resuming after a yield. +If the called function returns normally without ever yielding, +lua_pcallk (and lua_callk) will also return normally. +(Of course, instead of calling the continuation in that case, +you can do the equivalent work directly inside the original function.) + + +

    +Besides the Lua state, +the continuation function has two other parameters: +the final status of the call and the context value (ctx) that +was passed originally to lua_pcallk. +Lua does not use this context value; +it only passes this value from the original function to the +continuation function. +For lua_pcallk, +the status is the same value that would be returned by lua_pcallk, +except that it is LUA_YIELD when being executed after a yield +(instead of LUA_OK). +For lua_yieldk and lua_callk, +the status is always LUA_YIELD when Lua calls the continuation. +(For these two functions, +Lua will not call the continuation in case of errors, +because they do not handle errors.) +Similarly, when using lua_callk, +you should call the continuation function +with LUA_OK as the status. +(For lua_yieldk, there is not much point in calling +directly the continuation function, +because lua_yieldk usually does not return.) + + +

    +Lua treats the continuation function as if it were the original function. +The continuation function receives the same Lua stack +from the original function, +in the same state it would be if the callee function had returned. +(For instance, +after a lua_callk the function and its arguments are +removed from the stack and replaced by the results from the call.) +It also has the same upvalues. +Whatever it returns is handled by Lua as if it were the return +of the original function. + + + + + +

    4.6 – Functions and Types

    + +

    +Here we list all functions and types from the C API in +alphabetical order. +Each function has an indicator like this: +[-o, +p, x] + + +

    +The first field, o, +is how many elements the function pops from the stack. +The second field, p, +is how many elements the function pushes onto the stack. +(Any function always pushes its results after popping its arguments.) +A field in the form x|y means the function can push (or pop) +x or y elements, +depending on the situation; +an interrogation mark '?' means that +we cannot know how many elements the function pops/pushes +by looking only at its arguments. +(For instance, they may depend on what is in the stack.) +The third field, x, +tells whether the function may raise errors: +'-' means the function never raises any error; +'m' means the function may raise only out-of-memory errors; +'v' means the function may raise the errors explained in the text; +'e' means the function can run arbitrary Lua code, +either directly or through metamethods, +and therefore may raise any errors. + + + +


    lua_absindex

    +[-0, +0, –] +

    int lua_absindex (lua_State *L, int idx);
    + +

    +Converts the acceptable index idx +into an equivalent absolute index +(that is, one that does not depend on the stack size). + + + + + +


    lua_Alloc

    +
    typedef void * (*lua_Alloc) (void *ud,
    +                             void *ptr,
    +                             size_t osize,
    +                             size_t nsize);
    + +

    +The type of the memory-allocation function used by Lua states. +The allocator function must provide a +functionality similar to realloc, +but not exactly the same. +Its arguments are +ud, an opaque pointer passed to lua_newstate; +ptr, a pointer to the block being allocated/reallocated/freed; +osize, the original size of the block or some code about what +is being allocated; +and nsize, the new size of the block. + + +

    +When ptr is not NULL, +osize is the size of the block pointed by ptr, +that is, the size given when it was allocated or reallocated. + + +

    +When ptr is NULL, +osize encodes the kind of object that Lua is allocating. +osize is any of +LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, +LUA_TUSERDATA, or LUA_TTHREAD when (and only when) +Lua is creating a new object of that type. +When osize is some other value, +Lua is allocating memory for something else. + + +

    +Lua assumes the following behavior from the allocator function: + + +

    +When nsize is zero, +the allocator must behave like free +and then return NULL. + + +

    +When nsize is not zero, +the allocator must behave like realloc. +In particular, the allocator returns NULL +if and only if it cannot fulfill the request. + + +

    +Here is a simple implementation for the allocator function. +It is used in the auxiliary library by luaL_newstate. + +

    +     static void *l_alloc (void *ud, void *ptr, size_t osize,
    +                                                size_t nsize) {
    +       (void)ud;  (void)osize;  /* not used */
    +       if (nsize == 0) {
    +         free(ptr);
    +         return NULL;
    +       }
    +       else
    +         return realloc(ptr, nsize);
    +     }
    +

    +Note that ISO C ensures +that free(NULL) has no effect and that +realloc(NULL,size) is equivalent to malloc(size). + + + + + +


    lua_arith

    +[-(2|1), +1, e] +

    void lua_arith (lua_State *L, int op);
    + +

    +Performs an arithmetic or bitwise operation over the two values +(or one, in the case of negations) +at the top of the stack, +with the value on the top being the second operand, +pops these values, and pushes the result of the operation. +The function follows the semantics of the corresponding Lua operator +(that is, it may call metamethods). + + +

    +The value of op must be one of the following constants: + +

    + + + + +

    lua_atpanic

    +[-0, +0, –] +

    lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
    + +

    +Sets a new panic function and returns the old one (see §4.4). + + + + + +


    lua_call

    +[-(nargs+1), +nresults, e] +

    void lua_call (lua_State *L, int nargs, int nresults);
    + +

    +Calls a function. +Like regular Lua calls, +lua_call respects the __call metamethod. +So, here the word "function" +means any callable value. + + +

    +To do a call you must use the following protocol: +first, the function to be called is pushed onto the stack; +then, the arguments to the call are pushed +in direct order; +that is, the first argument is pushed first. +Finally you call lua_call; +nargs is the number of arguments that you pushed onto the stack. +When the function returns, +all arguments and the function value are popped +and the call results are pushed onto the stack. +The number of results is adjusted to nresults, +unless nresults is LUA_MULTRET. +In this case, all results from the function are pushed; +Lua takes care that the returned values fit into the stack space, +but it does not ensure any extra space in the stack. +The function results are pushed onto the stack in direct order +(the first result is pushed first), +so that after the call the last result is on the top of the stack. + + +

    +Any error while calling and running the function is propagated upwards +(with a longjmp). + + +

    +The following example shows how the host program can do the +equivalent to this Lua code: + +

    +     a = f("how", t.x, 14)
    +

    +Here it is in C: + +

    +     lua_getglobal(L, "f");                  /* function to be called */
    +     lua_pushliteral(L, "how");                       /* 1st argument */
    +     lua_getglobal(L, "t");                    /* table to be indexed */
    +     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
    +     lua_remove(L, -2);                  /* remove 't' from the stack */
    +     lua_pushinteger(L, 14);                          /* 3rd argument */
    +     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
    +     lua_setglobal(L, "a");                         /* set global 'a' */
    +

    +Note that the code above is balanced: +at its end, the stack is back to its original configuration. +This is considered good programming practice. + + + + + +


    lua_callk

    +[-(nargs + 1), +nresults, e] +

    void lua_callk (lua_State *L,
    +                int nargs,
    +                int nresults,
    +                lua_KContext ctx,
    +                lua_KFunction k);
    + +

    +This function behaves exactly like lua_call, +but allows the called function to yield (see §4.5). + + + + + +


    lua_CFunction

    +
    typedef int (*lua_CFunction) (lua_State *L);
    + +

    +Type for C functions. + + +

    +In order to communicate properly with Lua, +a C function must use the following protocol, +which defines the way parameters and results are passed: +a C function receives its arguments from Lua in its stack +in direct order (the first argument is pushed first). +So, when the function starts, +lua_gettop(L) returns the number of arguments received by the function. +The first argument (if any) is at index 1 +and its last argument is at index lua_gettop(L). +To return values to Lua, a C function just pushes them onto the stack, +in direct order (the first result is pushed first), +and returns in C the number of results. +Any other value in the stack below the results will be properly +discarded by Lua. +Like a Lua function, a C function called by Lua can also return +many results. + + +

    +As an example, the following function receives a variable number +of numeric arguments and returns their average and their sum: + +

    +     static int foo (lua_State *L) {
    +       int n = lua_gettop(L);    /* number of arguments */
    +       lua_Number sum = 0.0;
    +       int i;
    +       for (i = 1; i <= n; i++) {
    +         if (!lua_isnumber(L, i)) {
    +           lua_pushliteral(L, "incorrect argument");
    +           lua_error(L);
    +         }
    +         sum += lua_tonumber(L, i);
    +       }
    +       lua_pushnumber(L, sum/n);        /* first result */
    +       lua_pushnumber(L, sum);         /* second result */
    +       return 2;                   /* number of results */
    +     }
    +
    + + + + +

    lua_checkstack

    +[-0, +0, –] +

    int lua_checkstack (lua_State *L, int n);
    + +

    +Ensures that the stack has space for at least n extra elements, +that is, that you can safely push up to n values into it. +It returns false if it cannot fulfill the request, +either because it would cause the stack +to be greater than a fixed maximum size +(typically at least several thousand elements) or +because it cannot allocate memory for the extra space. +This function never shrinks the stack; +if the stack already has space for the extra elements, +it is left unchanged. + + + + + +


    lua_close

    +[-0, +0, –] +

    void lua_close (lua_State *L);
    + +

    +Close all active to-be-closed variables in the main thread, +release all objects in the given Lua state +(calling the corresponding garbage-collection metamethods, if any), +and frees all dynamic memory used by this state. + + +

    +On several platforms, you may not need to call this function, +because all resources are naturally released when the host program ends. +On the other hand, long-running programs that create multiple states, +such as daemons or web servers, +will probably need to close states as soon as they are not needed. + + + + + +


    lua_closeslot

    +[-0, +0, e] +

    void lua_closeslot (lua_State *L, int index);
    + +

    +Close the to-be-closed slot at the given index and set its value to nil. +The index must be the last index previously marked to be closed +(see lua_toclose) that is still active (that is, not closed yet). + + +

    +A __close metamethod cannot yield +when called through this function. + + +

    +(This function was introduced in release 5.4.3.) + + + + + +


    lua_closethread

    +[-0, +?, –] +

    int lua_closethread (lua_State *L, lua_State *from);
    + +

    +Resets a thread, cleaning its call stack and closing all pending +to-be-closed variables. +Returns a status code: +LUA_OK for no errors in the thread +(either the original error that stopped the thread or +errors in closing methods), +or an error status otherwise. +In case of error, +leaves the error object on the top of the stack. + + +

    +The parameter from represents the coroutine that is resetting L. +If there is no such coroutine, +this parameter can be NULL. + + +

    +(This function was introduced in release 5.4.6.) + + + + + +


    lua_compare

    +[-0, +0, e] +

    int lua_compare (lua_State *L, int index1, int index2, int op);
    + +

    +Compares two Lua values. +Returns 1 if the value at index index1 satisfies op +when compared with the value at index index2, +following the semantics of the corresponding Lua operator +(that is, it may call metamethods). +Otherwise returns 0. +Also returns 0 if any of the indices is not valid. + + +

    +The value of op must be one of the following constants: + +

      + +
    • LUA_OPEQ: compares for equality (==)
    • +
    • LUA_OPLT: compares for less than (<)
    • +
    • LUA_OPLE: compares for less or equal (<=)
    • + +
    + + + + +

    lua_concat

    +[-n, +1, e] +

    void lua_concat (lua_State *L, int n);
    + +

    +Concatenates the n values at the top of the stack, +pops them, and leaves the result on the top. +If n is 1, the result is the single value on the stack +(that is, the function does nothing); +if n is 0, the result is the empty string. +Concatenation is performed following the usual semantics of Lua +(see §3.4.6). + + + + + +


    lua_copy

    +[-0, +0, –] +

    void lua_copy (lua_State *L, int fromidx, int toidx);
    + +

    +Copies the element at index fromidx +into the valid index toidx, +replacing the value at that position. +Values at other positions are not affected. + + + + + +


    lua_createtable

    +[-0, +1, m] +

    void lua_createtable (lua_State *L, int narr, int nrec);
    + +

    +Creates a new empty table and pushes it onto the stack. +Parameter narr is a hint for how many elements the table +will have as a sequence; +parameter nrec is a hint for how many other elements +the table will have. +Lua may use these hints to preallocate memory for the new table. +This preallocation may help performance when you know in advance +how many elements the table will have. +Otherwise you can use the function lua_newtable. + + + + + +


    lua_dump

    +[-0, +0, –] +

    int lua_dump (lua_State *L,
    +                        lua_Writer writer,
    +                        void *data,
    +                        int strip);
    + +

    +Dumps a function as a binary chunk. +Receives a Lua function on the top of the stack +and produces a binary chunk that, +if loaded again, +results in a function equivalent to the one dumped. +As it produces parts of the chunk, +lua_dump calls function writer (see lua_Writer) +with the given data +to write them. + + +

    +If strip is true, +the binary representation may not include all debug information +about the function, +to save space. + + +

    +The value returned is the error code returned by the last +call to the writer; +0 means no errors. + + +

    +This function does not pop the Lua function from the stack. + + + + + +


    lua_error

    +[-1, +0, v] +

    int lua_error (lua_State *L);
    + +

    +Raises a Lua error, +using the value on the top of the stack as the error object. +This function does a long jump, +and therefore never returns +(see luaL_error). + + + + + +


    lua_gc

    +[-0, +0, –] +

    int lua_gc (lua_State *L, int what, ...);
    + +

    +Controls the garbage collector. + + +

    +This function performs several tasks, +according to the value of the parameter what. +For options that need extra arguments, +they are listed after the option. + +

      + +
    • LUA_GCCOLLECT: +Performs a full garbage-collection cycle. +
    • + +
    • LUA_GCSTOP: +Stops the garbage collector. +
    • + +
    • LUA_GCRESTART: +Restarts the garbage collector. +
    • + +
    • LUA_GCCOUNT: +Returns the current amount of memory (in Kbytes) in use by Lua. +
    • + +
    • LUA_GCCOUNTB: +Returns the remainder of dividing the current amount of bytes of +memory in use by Lua by 1024. +
    • + +
    • LUA_GCSTEP (int stepsize): +Performs an incremental step of garbage collection, +corresponding to the allocation of stepsize Kbytes. +
    • + +
    • LUA_GCISRUNNING: +Returns a boolean that tells whether the collector is running +(i.e., not stopped). +
    • + +
    • LUA_GCINC (int pause, int stepmul, stepsize): +Changes the collector to incremental mode +with the given parameters (see §2.5.1). +Returns the previous mode (LUA_GCGEN or LUA_GCINC). +
    • + +
    • LUA_GCGEN (int minormul, int majormul): +Changes the collector to generational mode +with the given parameters (see §2.5.2). +Returns the previous mode (LUA_GCGEN or LUA_GCINC). +
    • + +

    +For more details about these options, +see collectgarbage. + + +

    +This function should not be called by a finalizer. + + + + + +


    lua_getallocf

    +[-0, +0, –] +

    lua_Alloc lua_getallocf (lua_State *L, void **ud);
    + +

    +Returns the memory-allocation function of a given state. +If ud is not NULL, Lua stores in *ud the +opaque pointer given when the memory-allocator function was set. + + + + + +


    lua_getfield

    +[-0, +1, e] +

    int lua_getfield (lua_State *L, int index, const char *k);
    + +

    +Pushes onto the stack the value t[k], +where t is the value at the given index. +As in Lua, this function may trigger a metamethod +for the "index" event (see §2.4). + + +

    +Returns the type of the pushed value. + + + + + +


    lua_getextraspace

    +[-0, +0, –] +

    void *lua_getextraspace (lua_State *L);
    + +

    +Returns a pointer to a raw memory area associated with the +given Lua state. +The application can use this area for any purpose; +Lua does not use it for anything. + + +

    +Each new thread has this area initialized with a copy +of the area of the main thread. + + +

    +By default, this area has the size of a pointer to void, +but you can recompile Lua with a different size for this area. +(See LUA_EXTRASPACE in luaconf.h.) + + + + + +


    lua_getglobal

    +[-0, +1, e] +

    int lua_getglobal (lua_State *L, const char *name);
    + +

    +Pushes onto the stack the value of the global name. +Returns the type of that value. + + + + + +


    lua_geti

    +[-0, +1, e] +

    int lua_geti (lua_State *L, int index, lua_Integer i);
    + +

    +Pushes onto the stack the value t[i], +where t is the value at the given index. +As in Lua, this function may trigger a metamethod +for the "index" event (see §2.4). + + +

    +Returns the type of the pushed value. + + + + + +


    lua_getmetatable

    +[-0, +(0|1), –] +

    int lua_getmetatable (lua_State *L, int index);
    + +

    +If the value at the given index has a metatable, +the function pushes that metatable onto the stack and returns 1. +Otherwise, +the function returns 0 and pushes nothing on the stack. + + + + + +


    lua_gettable

    +[-1, +1, e] +

    int lua_gettable (lua_State *L, int index);
    + +

    +Pushes onto the stack the value t[k], +where t is the value at the given index +and k is the value on the top of the stack. + + +

    +This function pops the key from the stack, +pushing the resulting value in its place. +As in Lua, this function may trigger a metamethod +for the "index" event (see §2.4). + + +

    +Returns the type of the pushed value. + + + + + +


    lua_gettop

    +[-0, +0, –] +

    int lua_gettop (lua_State *L);
    + +

    +Returns the index of the top element in the stack. +Because indices start at 1, +this result is equal to the number of elements in the stack; +in particular, 0 means an empty stack. + + + + + +


    lua_getiuservalue

    +[-0, +1, –] +

    int lua_getiuservalue (lua_State *L, int index, int n);
    + +

    +Pushes onto the stack the n-th user value associated with the +full userdata at the given index and +returns the type of the pushed value. + + +

    +If the userdata does not have that value, +pushes nil and returns LUA_TNONE. + + + + + +


    lua_insert

    +[-1, +1, –] +

    void lua_insert (lua_State *L, int index);
    + +

    +Moves the top element into the given valid index, +shifting up the elements above this index to open space. +This function cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + + + + + +


    lua_Integer

    +
    typedef ... lua_Integer;
    + +

    +The type of integers in Lua. + + +

    +By default this type is long long, +(usually a 64-bit two-complement integer), +but that can be changed to long or int +(usually a 32-bit two-complement integer). +(See LUA_INT_TYPE in luaconf.h.) + + +

    +Lua also defines the constants +LUA_MININTEGER and LUA_MAXINTEGER, +with the minimum and the maximum values that fit in this type. + + + + + +


    lua_isboolean

    +[-0, +0, –] +

    int lua_isboolean (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a boolean, +and 0 otherwise. + + + + + +


    lua_iscfunction

    +[-0, +0, –] +

    int lua_iscfunction (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a C function, +and 0 otherwise. + + + + + +


    lua_isfunction

    +[-0, +0, –] +

    int lua_isfunction (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a function +(either C or Lua), and 0 otherwise. + + + + + +


    lua_isinteger

    +[-0, +0, –] +

    int lua_isinteger (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is an integer +(that is, the value is a number and is represented as an integer), +and 0 otherwise. + + + + + +


    lua_islightuserdata

    +[-0, +0, –] +

    int lua_islightuserdata (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a light userdata, +and 0 otherwise. + + + + + +


    lua_isnil

    +[-0, +0, –] +

    int lua_isnil (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is nil, +and 0 otherwise. + + + + + +


    lua_isnone

    +[-0, +0, –] +

    int lua_isnone (lua_State *L, int index);
    + +

    +Returns 1 if the given index is not valid, +and 0 otherwise. + + + + + +


    lua_isnoneornil

    +[-0, +0, –] +

    int lua_isnoneornil (lua_State *L, int index);
    + +

    +Returns 1 if the given index is not valid +or if the value at this index is nil, +and 0 otherwise. + + + + + +


    lua_isnumber

    +[-0, +0, –] +

    int lua_isnumber (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a number +or a string convertible to a number, +and 0 otherwise. + + + + + +


    lua_isstring

    +[-0, +0, –] +

    int lua_isstring (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a string +or a number (which is always convertible to a string), +and 0 otherwise. + + + + + +


    lua_istable

    +[-0, +0, –] +

    int lua_istable (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a table, +and 0 otherwise. + + + + + +


    lua_isthread

    +[-0, +0, –] +

    int lua_isthread (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a thread, +and 0 otherwise. + + + + + +


    lua_isuserdata

    +[-0, +0, –] +

    int lua_isuserdata (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is a userdata +(either full or light), and 0 otherwise. + + + + + +


    lua_isyieldable

    +[-0, +0, –] +

    int lua_isyieldable (lua_State *L);
    + +

    +Returns 1 if the given coroutine can yield, +and 0 otherwise. + + + + + +


    lua_KContext

    +
    typedef ... lua_KContext;
    + +

    +The type for continuation-function contexts. +It must be a numeric type. +This type is defined as intptr_t +when intptr_t is available, +so that it can store pointers too. +Otherwise, it is defined as ptrdiff_t. + + + + + +


    lua_KFunction

    +
    typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
    + +

    +Type for continuation functions (see §4.5). + + + + + +


    lua_len

    +[-0, +1, e] +

    void lua_len (lua_State *L, int index);
    + +

    +Returns the length of the value at the given index. +It is equivalent to the '#' operator in Lua (see §3.4.7) and +may trigger a metamethod for the "length" event (see §2.4). +The result is pushed on the stack. + + + + + +


    lua_load

    +[-0, +1, –] +

    int lua_load (lua_State *L,
    +              lua_Reader reader,
    +              void *data,
    +              const char *chunkname,
    +              const char *mode);
    + +

    +Loads a Lua chunk without running it. +If there are no errors, +lua_load pushes the compiled chunk as a Lua +function on top of the stack. +Otherwise, it pushes an error message. + + +

    +The lua_load function uses a user-supplied reader function +to read the chunk (see lua_Reader). +The data argument is an opaque value passed to the reader function. + + +

    +The chunkname argument gives a name to the chunk, +which is used for error messages and in debug information (see §4.7). + + +

    +lua_load automatically detects whether the chunk is text or binary +and loads it accordingly (see program luac). +The string mode works as in function load, +with the addition that +a NULL value is equivalent to the string "bt". + + +

    +lua_load uses the stack internally, +so the reader function must always leave the stack +unmodified when returning. + + +

    +lua_load can return +LUA_OK, LUA_ERRSYNTAX, or LUA_ERRMEM. +The function may also return other values corresponding to +errors raised by the read function (see §4.4.1). + + +

    +If the resulting function has upvalues, +its first upvalue is set to the value of the global environment +stored at index LUA_RIDX_GLOBALS in the registry (see §4.3). +When loading main chunks, +this upvalue will be the _ENV variable (see §2.2). +Other upvalues are initialized with nil. + + + + + +


    lua_newstate

    +[-0, +0, –] +

    lua_State *lua_newstate (lua_Alloc f, void *ud);
    + +

    +Creates a new independent state and returns its main thread. +Returns NULL if it cannot create the state +(due to lack of memory). +The argument f is the allocator function; +Lua will do all memory allocation for this state +through this function (see lua_Alloc). +The second argument, ud, is an opaque pointer that Lua +passes to the allocator in every call. + + + + + +


    lua_newtable

    +[-0, +1, m] +

    void lua_newtable (lua_State *L);
    + +

    +Creates a new empty table and pushes it onto the stack. +It is equivalent to lua_createtable(L, 0, 0). + + + + + +


    lua_newthread

    +[-0, +1, m] +

    lua_State *lua_newthread (lua_State *L);
    + +

    +Creates a new thread, pushes it on the stack, +and returns a pointer to a lua_State that represents this new thread. +The new thread returned by this function shares with the original thread +its global environment, +but has an independent execution stack. + + +

    +Threads are subject to garbage collection, +like any Lua object. + + + + + +


    lua_newuserdatauv

    +[-0, +1, m] +

    void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);
    + +

    +This function creates and pushes on the stack a new full userdata, +with nuvalue associated Lua values, called user values, +plus an associated block of raw memory with size bytes. +(The user values can be set and read with the functions +lua_setiuservalue and lua_getiuservalue.) + + +

    +The function returns the address of the block of memory. +Lua ensures that this address is valid as long as +the corresponding userdata is alive (see §2.5). +Moreover, if the userdata is marked for finalization (see §2.5.3), +its address is valid at least until the call to its finalizer. + + + + + +


    lua_next

    +[-1, +(2|0), v] +

    int lua_next (lua_State *L, int index);
    + +

    +Pops a key from the stack, +and pushes a key–value pair from the table at the given index, +the "next" pair after the given key. +If there are no more elements in the table, +then lua_next returns 0 and pushes nothing. + + +

    +A typical table traversal looks like this: + +

    +     /* table is in the stack at index 't' */
    +     lua_pushnil(L);  /* first key */
    +     while (lua_next(L, t) != 0) {
    +       /* uses 'key' (at index -2) and 'value' (at index -1) */
    +       printf("%s - %s\n",
    +              lua_typename(L, lua_type(L, -2)),
    +              lua_typename(L, lua_type(L, -1)));
    +       /* removes 'value'; keeps 'key' for next iteration */
    +       lua_pop(L, 1);
    +     }
    +
    + +

    +While traversing a table, +avoid calling lua_tolstring directly on a key, +unless you know that the key is actually a string. +Recall that lua_tolstring may change +the value at the given index; +this confuses the next call to lua_next. + + +

    +This function may raise an error if the given key +is neither nil nor present in the table. +See function next for the caveats of modifying +the table during its traversal. + + + + + +


    lua_Number

    +
    typedef ... lua_Number;
    + +

    +The type of floats in Lua. + + +

    +By default this type is double, +but that can be changed to a single float or a long double. +(See LUA_FLOAT_TYPE in luaconf.h.) + + + + + +


    lua_numbertointeger

    +
    int lua_numbertointeger (lua_Number n, lua_Integer *p);
    + +

    +Tries to convert a Lua float to a Lua integer; +the float n must have an integral value. +If that value is within the range of Lua integers, +it is converted to an integer and assigned to *p. +The macro results in a boolean indicating whether the +conversion was successful. +(Note that this range test can be tricky to do +correctly without this macro, due to rounding.) + + +

    +This macro may evaluate its arguments more than once. + + + + + +


    lua_pcall

    +[-(nargs + 1), +(nresults|1), –] +

    int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);
    + +

    +Calls a function (or a callable object) in protected mode. + + +

    +Both nargs and nresults have the same meaning as +in lua_call. +If there are no errors during the call, +lua_pcall behaves exactly like lua_call. +However, if there is any error, +lua_pcall catches it, +pushes a single value on the stack (the error object), +and returns an error code. +Like lua_call, +lua_pcall always removes the function +and its arguments from the stack. + + +

    +If msgh is 0, +then the error object returned on the stack +is exactly the original error object. +Otherwise, msgh is the stack index of a +message handler. +(This index cannot be a pseudo-index.) +In case of runtime errors, +this handler will be called with the error object +and its return value will be the object +returned on the stack by lua_pcall. + + +

    +Typically, the message handler is used to add more debug +information to the error object, such as a stack traceback. +Such information cannot be gathered after the return of lua_pcall, +since by then the stack has unwound. + + +

    +The lua_pcall function returns one of the following status codes: +LUA_OK, LUA_ERRRUN, LUA_ERRMEM, or LUA_ERRERR. + + + + + +


    lua_pcallk

    +[-(nargs + 1), +(nresults|1), –] +

    int lua_pcallk (lua_State *L,
    +                int nargs,
    +                int nresults,
    +                int msgh,
    +                lua_KContext ctx,
    +                lua_KFunction k);
    + +

    +This function behaves exactly like lua_pcall, +except that it allows the called function to yield (see §4.5). + + + + + +


    lua_pop

    +[-n, +0, e] +

    void lua_pop (lua_State *L, int n);
    + +

    +Pops n elements from the stack. +It is implemented as a macro over lua_settop. + + + + + +


    lua_pushboolean

    +[-0, +1, –] +

    void lua_pushboolean (lua_State *L, int b);
    + +

    +Pushes a boolean value with value b onto the stack. + + + + + +


    lua_pushcclosure

    +[-n, +1, m] +

    void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
    + +

    +Pushes a new C closure onto the stack. +This function receives a pointer to a C function +and pushes onto the stack a Lua value of type function that, +when called, invokes the corresponding C function. +The parameter n tells how many upvalues this function will have +(see §4.2). + + +

    +Any function to be callable by Lua must +follow the correct protocol to receive its parameters +and return its results (see lua_CFunction). + + +

    +When a C function is created, +it is possible to associate some values with it, +the so called upvalues; +these upvalues are then accessible to the function whenever it is called. +This association is called a C closure (see §4.2). +To create a C closure, +first the initial values for its upvalues must be pushed onto the stack. +(When there are multiple upvalues, the first value is pushed first.) +Then lua_pushcclosure +is called to create and push the C function onto the stack, +with the argument n telling how many values will be +associated with the function. +lua_pushcclosure also pops these values from the stack. + + +

    +The maximum value for n is 255. + + +

    +When n is zero, +this function creates a light C function, +which is just a pointer to the C function. +In that case, it never raises a memory error. + + + + + +


    lua_pushcfunction

    +[-0, +1, –] +

    void lua_pushcfunction (lua_State *L, lua_CFunction f);
    + +

    +Pushes a C function onto the stack. +This function is equivalent to lua_pushcclosure with no upvalues. + + + + + +


    lua_pushfstring

    +[-0, +1, v] +

    const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
    + +

    +Pushes onto the stack a formatted string +and returns a pointer to this string (see §4.1.3). +It is similar to the ISO C function sprintf, +but has two important differences. +First, +you do not have to allocate space for the result; +the result is a Lua string and Lua takes care of memory allocation +(and deallocation, through garbage collection). +Second, +the conversion specifiers are quite restricted. +There are no flags, widths, or precisions. +The conversion specifiers can only be +'%%' (inserts the character '%'), +'%s' (inserts a zero-terminated string, with no size restrictions), +'%f' (inserts a lua_Number), +'%I' (inserts a lua_Integer), +'%p' (inserts a pointer), +'%d' (inserts an int), +'%c' (inserts an int as a one-byte character), and +'%U' (inserts a long int as a UTF-8 byte sequence). + + +

    +This function may raise errors due to memory overflow +or an invalid conversion specifier. + + + + + +


    lua_pushglobaltable

    +[-0, +1, –] +

    void lua_pushglobaltable (lua_State *L);
    + +

    +Pushes the global environment onto the stack. + + + + + +


    lua_pushinteger

    +[-0, +1, –] +

    void lua_pushinteger (lua_State *L, lua_Integer n);
    + +

    +Pushes an integer with value n onto the stack. + + + + + +


    lua_pushlightuserdata

    +[-0, +1, –] +

    void lua_pushlightuserdata (lua_State *L, void *p);
    + +

    +Pushes a light userdata onto the stack. + + +

    +Userdata represent C values in Lua. +A light userdata represents a pointer, a void*. +It is a value (like a number): +you do not create it, it has no individual metatable, +and it is not collected (as it was never created). +A light userdata is equal to "any" +light userdata with the same C address. + + + + + +


    lua_pushliteral

    +[-0, +1, m] +

    const char *lua_pushliteral (lua_State *L, const char *s);
    + +

    +This macro is equivalent to lua_pushstring, +but should be used only when s is a literal string. +(Lua may optimize this case.) + + + + + +


    lua_pushlstring

    +[-0, +1, m] +

    const char *lua_pushlstring (lua_State *L, const char *s, size_t len);
    + +

    +Pushes the string pointed to by s with size len +onto the stack. +Lua will make or reuse an internal copy of the given string, +so the memory at s can be freed or reused immediately after +the function returns. +The string can contain any binary data, +including embedded zeros. + + +

    +Returns a pointer to the internal copy of the string (see §4.1.3). + + + + + +


    lua_pushnil

    +[-0, +1, –] +

    void lua_pushnil (lua_State *L);
    + +

    +Pushes a nil value onto the stack. + + + + + +


    lua_pushnumber

    +[-0, +1, –] +

    void lua_pushnumber (lua_State *L, lua_Number n);
    + +

    +Pushes a float with value n onto the stack. + + + + + +


    lua_pushstring

    +[-0, +1, m] +

    const char *lua_pushstring (lua_State *L, const char *s);
    + +

    +Pushes the zero-terminated string pointed to by s +onto the stack. +Lua will make or reuse an internal copy of the given string, +so the memory at s can be freed or reused immediately after +the function returns. + + +

    +Returns a pointer to the internal copy of the string (see §4.1.3). + + +

    +If s is NULL, pushes nil and returns NULL. + + + + + +


    lua_pushthread

    +[-0, +1, –] +

    int lua_pushthread (lua_State *L);
    + +

    +Pushes the thread represented by L onto the stack. +Returns 1 if this thread is the main thread of its state. + + + + + +


    lua_pushvalue

    +[-0, +1, –] +

    void lua_pushvalue (lua_State *L, int index);
    + +

    +Pushes a copy of the element at the given index +onto the stack. + + + + + +


    lua_pushvfstring

    +[-0, +1, v] +

    const char *lua_pushvfstring (lua_State *L,
    +                              const char *fmt,
    +                              va_list argp);
    + +

    +Equivalent to lua_pushfstring, except that it receives a va_list +instead of a variable number of arguments. + + + + + +


    lua_rawequal

    +[-0, +0, –] +

    int lua_rawequal (lua_State *L, int index1, int index2);
    + +

    +Returns 1 if the two values in indices index1 and +index2 are primitively equal +(that is, equal without calling the __eq metamethod). +Otherwise returns 0. +Also returns 0 if any of the indices are not valid. + + + + + +


    lua_rawget

    +[-1, +1, –] +

    int lua_rawget (lua_State *L, int index);
    + +

    +Similar to lua_gettable, but does a raw access +(i.e., without metamethods). +The value at index must be a table. + + + + + +


    lua_rawgeti

    +[-0, +1, –] +

    int lua_rawgeti (lua_State *L, int index, lua_Integer n);
    + +

    +Pushes onto the stack the value t[n], +where t is the table at the given index. +The access is raw, +that is, it does not use the __index metavalue. + + +

    +Returns the type of the pushed value. + + + + + +


    lua_rawgetp

    +[-0, +1, –] +

    int lua_rawgetp (lua_State *L, int index, const void *p);
    + +

    +Pushes onto the stack the value t[k], +where t is the table at the given index and +k is the pointer p represented as a light userdata. +The access is raw; +that is, it does not use the __index metavalue. + + +

    +Returns the type of the pushed value. + + + + + +


    lua_rawlen

    +[-0, +0, –] +

    lua_Unsigned lua_rawlen (lua_State *L, int index);
    + +

    +Returns the raw "length" of the value at the given index: +for strings, this is the string length; +for tables, this is the result of the length operator ('#') +with no metamethods; +for userdata, this is the size of the block of memory allocated +for the userdata. +For other values, this call returns 0. + + + + + +


    lua_rawset

    +[-2, +0, m] +

    void lua_rawset (lua_State *L, int index);
    + +

    +Similar to lua_settable, but does a raw assignment +(i.e., without metamethods). +The value at index must be a table. + + + + + +


    lua_rawseti

    +[-1, +0, m] +

    void lua_rawseti (lua_State *L, int index, lua_Integer i);
    + +

    +Does the equivalent of t[i] = v, +where t is the table at the given index +and v is the value on the top of the stack. + + +

    +This function pops the value from the stack. +The assignment is raw, +that is, it does not use the __newindex metavalue. + + + + + +


    lua_rawsetp

    +[-1, +0, m] +

    void lua_rawsetp (lua_State *L, int index, const void *p);
    + +

    +Does the equivalent of t[p] = v, +where t is the table at the given index, +p is encoded as a light userdata, +and v is the value on the top of the stack. + + +

    +This function pops the value from the stack. +The assignment is raw, +that is, it does not use the __newindex metavalue. + + + + + +


    lua_Reader

    +
    typedef const char * (*lua_Reader) (lua_State *L,
    +                                    void *data,
    +                                    size_t *size);
    + +

    +The reader function used by lua_load. +Every time lua_load needs another piece of the chunk, +it calls the reader, +passing along its data parameter. +The reader must return a pointer to a block of memory +with a new piece of the chunk +and set size to the block size. +The block must exist until the reader function is called again. +To signal the end of the chunk, +the reader must return NULL or set size to zero. +The reader function may return pieces of any size greater than zero. + + + + + +


    lua_register

    +[-0, +0, e] +

    void lua_register (lua_State *L, const char *name, lua_CFunction f);
    + +

    +Sets the C function f as the new value of global name. +It is defined as a macro: + +

    +     #define lua_register(L,n,f) \
    +            (lua_pushcfunction(L, f), lua_setglobal(L, n))
    +
    + + + + +

    lua_remove

    +[-1, +0, –] +

    void lua_remove (lua_State *L, int index);
    + +

    +Removes the element at the given valid index, +shifting down the elements above this index to fill the gap. +This function cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + + + + + +


    lua_replace

    +[-1, +0, –] +

    void lua_replace (lua_State *L, int index);
    + +

    +Moves the top element into the given valid index +without shifting any element +(therefore replacing the value at that given index), +and then pops the top element. + + + + + +


    lua_resetthread

    +[-0, +?, –] +

    int lua_resetthread (lua_State *L);
    + +

    +This function is deprecated; +it is equivalent to lua_closethread with +from being NULL. + + + + + +


    lua_resume

    +[-?, +?, –] +

    int lua_resume (lua_State *L, lua_State *from, int nargs,
    +                          int *nresults);
    + +

    +Starts and resumes a coroutine in the given thread L. + + +

    +To start a coroutine, +you push the main function plus any arguments +onto the empty stack of the thread. +then you call lua_resume, +with nargs being the number of arguments. +This call returns when the coroutine suspends or finishes its execution. +When it returns, +*nresults is updated and +the top of the stack contains +the *nresults values passed to lua_yield +or returned by the body function. +lua_resume returns +LUA_YIELD if the coroutine yields, +LUA_OK if the coroutine finishes its execution +without errors, +or an error code in case of errors (see §4.4.1). +In case of errors, +the error object is on the top of the stack. + + +

    +To resume a coroutine, +you remove the *nresults yielded values from its stack, +push the values to be passed as results from yield, +and then call lua_resume. + + +

    +The parameter from represents the coroutine that is resuming L. +If there is no such coroutine, +this parameter can be NULL. + + + + + +


    lua_rotate

    +[-0, +0, –] +

    void lua_rotate (lua_State *L, int idx, int n);
    + +

    +Rotates the stack elements between the valid index idx +and the top of the stack. +The elements are rotated n positions in the direction of the top, +for a positive n, +or -n positions in the direction of the bottom, +for a negative n. +The absolute value of n must not be greater than the size +of the slice being rotated. +This function cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + + + + + +


    lua_setallocf

    +[-0, +0, –] +

    void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
    + +

    +Changes the allocator function of a given state to f +with user data ud. + + + + + +


    lua_setfield

    +[-1, +0, e] +

    void lua_setfield (lua_State *L, int index, const char *k);
    + +

    +Does the equivalent to t[k] = v, +where t is the value at the given index +and v is the value on the top of the stack. + + +

    +This function pops the value from the stack. +As in Lua, this function may trigger a metamethod +for the "newindex" event (see §2.4). + + + + + +


    lua_setglobal

    +[-1, +0, e] +

    void lua_setglobal (lua_State *L, const char *name);
    + +

    +Pops a value from the stack and +sets it as the new value of global name. + + + + + +


    lua_seti

    +[-1, +0, e] +

    void lua_seti (lua_State *L, int index, lua_Integer n);
    + +

    +Does the equivalent to t[n] = v, +where t is the value at the given index +and v is the value on the top of the stack. + + +

    +This function pops the value from the stack. +As in Lua, this function may trigger a metamethod +for the "newindex" event (see §2.4). + + + + + +


    lua_setiuservalue

    +[-1, +0, –] +

    int lua_setiuservalue (lua_State *L, int index, int n);
    + +

    +Pops a value from the stack and sets it as +the new n-th user value associated to the +full userdata at the given index. +Returns 0 if the userdata does not have that value. + + + + + +


    lua_setmetatable

    +[-1, +0, –] +

    int lua_setmetatable (lua_State *L, int index);
    + +

    +Pops a table or nil from the stack and +sets that value as the new metatable for the value at the given index. +(nil means no metatable.) + + +

    +(For historical reasons, this function returns an int, +which now is always 1.) + + + + + +


    lua_settable

    +[-2, +0, e] +

    void lua_settable (lua_State *L, int index);
    + +

    +Does the equivalent to t[k] = v, +where t is the value at the given index, +v is the value on the top of the stack, +and k is the value just below the top. + + +

    +This function pops both the key and the value from the stack. +As in Lua, this function may trigger a metamethod +for the "newindex" event (see §2.4). + + + + + +


    lua_settop

    +[-?, +?, e] +

    void lua_settop (lua_State *L, int index);
    + +

    +Accepts any index, or 0, +and sets the stack top to this index. +If the new top is greater than the old one, +then the new elements are filled with nil. +If index is 0, then all stack elements are removed. + + +

    +This function can run arbitrary code when removing an index +marked as to-be-closed from the stack. + + + + + +


    lua_setwarnf

    +[-0, +0, –] +

    void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);
    + +

    +Sets the warning function to be used by Lua to emit warnings +(see lua_WarnFunction). +The ud parameter sets the value ud passed to +the warning function. + + + + + +


    lua_State

    +
    typedef struct lua_State lua_State;
    + +

    +An opaque structure that points to a thread and indirectly +(through the thread) to the whole state of a Lua interpreter. +The Lua library is fully reentrant: +it has no global variables. +All information about a state is accessible through this structure. + + +

    +A pointer to this structure must be passed as the first argument to +every function in the library, except to lua_newstate, +which creates a Lua state from scratch. + + + + + +


    lua_status

    +[-0, +0, –] +

    int lua_status (lua_State *L);
    + +

    +Returns the status of the thread L. + + +

    +The status can be LUA_OK for a normal thread, +an error code if the thread finished the execution +of a lua_resume with an error, +or LUA_YIELD if the thread is suspended. + + +

    +You can call functions only in threads with status LUA_OK. +You can resume threads with status LUA_OK +(to start a new coroutine) or LUA_YIELD +(to resume a coroutine). + + + + + +


    lua_stringtonumber

    +[-0, +1, –] +

    size_t lua_stringtonumber (lua_State *L, const char *s);
    + +

    +Converts the zero-terminated string s to a number, +pushes that number into the stack, +and returns the total size of the string, +that is, its length plus one. +The conversion can result in an integer or a float, +according to the lexical conventions of Lua (see §3.1). +The string may have leading and trailing whitespaces and a sign. +If the string is not a valid numeral, +returns 0 and pushes nothing. +(Note that the result can be used as a boolean, +true if the conversion succeeds.) + + + + + +


    lua_toboolean

    +[-0, +0, –] +

    int lua_toboolean (lua_State *L, int index);
    + +

    +Converts the Lua value at the given index to a C boolean +value (0 or 1). +Like all tests in Lua, +lua_toboolean returns true for any Lua value +different from false and nil; +otherwise it returns false. +(If you want to accept only actual boolean values, +use lua_isboolean to test the value's type.) + + + + + +


    lua_tocfunction

    +[-0, +0, –] +

    lua_CFunction lua_tocfunction (lua_State *L, int index);
    + +

    +Converts a value at the given index to a C function. +That value must be a C function; +otherwise, returns NULL. + + + + + +


    lua_toclose

    +[-0, +0, m] +

    void lua_toclose (lua_State *L, int index);
    + +

    +Marks the given index in the stack as a +to-be-closed slot (see §3.3.8). +Like a to-be-closed variable in Lua, +the value at that slot in the stack will be closed +when it goes out of scope. +Here, in the context of a C function, +to go out of scope means that the running function returns to Lua, +or there is an error, +or the slot is removed from the stack through +lua_settop or lua_pop, +or there is a call to lua_closeslot. +A slot marked as to-be-closed should not be removed from the stack +by any other function in the API except lua_settop or lua_pop, +unless previously deactivated by lua_closeslot. + + +

    +This function should not be called for an index +that is equal to or below an active to-be-closed slot. + + +

    +Note that, both in case of errors and of a regular return, +by the time the __close metamethod runs, +the C stack was already unwound, +so that any automatic C variable declared in the calling function +(e.g., a buffer) will be out of scope. + + + + + +


    lua_tointeger

    +[-0, +0, –] +

    lua_Integer lua_tointeger (lua_State *L, int index);
    + +

    +Equivalent to lua_tointegerx with isnum equal to NULL. + + + + + +


    lua_tointegerx

    +[-0, +0, –] +

    lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);
    + +

    +Converts the Lua value at the given index +to the signed integral type lua_Integer. +The Lua value must be an integer, +or a number or string convertible to an integer (see §3.4.3); +otherwise, lua_tointegerx returns 0. + + +

    +If isnum is not NULL, +its referent is assigned a boolean value that +indicates whether the operation succeeded. + + + + + +


    lua_tolstring

    +[-0, +0, m] +

    const char *lua_tolstring (lua_State *L, int index, size_t *len);
    + +

    +Converts the Lua value at the given index to a C string. +If len is not NULL, +it sets *len with the string length. +The Lua value must be a string or a number; +otherwise, the function returns NULL. +If the value is a number, +then lua_tolstring also +changes the actual value in the stack to a string. +(This change confuses lua_next +when lua_tolstring is applied to keys during a table traversal.) + + +

    +lua_tolstring returns a pointer +to a string inside the Lua state (see §4.1.3). +This string always has a zero ('\0') +after its last character (as in C), +but can contain other zeros in its body. + + + + + +


    lua_tonumber

    +[-0, +0, –] +

    lua_Number lua_tonumber (lua_State *L, int index);
    + +

    +Equivalent to lua_tonumberx with isnum equal to NULL. + + + + + +


    lua_tonumberx

    +[-0, +0, –] +

    lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);
    + +

    +Converts the Lua value at the given index +to the C type lua_Number (see lua_Number). +The Lua value must be a number or a string convertible to a number +(see §3.4.3); +otherwise, lua_tonumberx returns 0. + + +

    +If isnum is not NULL, +its referent is assigned a boolean value that +indicates whether the operation succeeded. + + + + + +


    lua_topointer

    +[-0, +0, –] +

    const void *lua_topointer (lua_State *L, int index);
    + +

    +Converts the value at the given index to a generic +C pointer (void*). +The value can be a userdata, a table, a thread, a string, or a function; +otherwise, lua_topointer returns NULL. +Different objects will give different pointers. +There is no way to convert the pointer back to its original value. + + +

    +Typically this function is used only for hashing and debug information. + + + + + +


    lua_tostring

    +[-0, +0, m] +

    const char *lua_tostring (lua_State *L, int index);
    + +

    +Equivalent to lua_tolstring with len equal to NULL. + + + + + +


    lua_tothread

    +[-0, +0, –] +

    lua_State *lua_tothread (lua_State *L, int index);
    + +

    +Converts the value at the given index to a Lua thread +(represented as lua_State*). +This value must be a thread; +otherwise, the function returns NULL. + + + + + +


    lua_touserdata

    +[-0, +0, –] +

    void *lua_touserdata (lua_State *L, int index);
    + +

    +If the value at the given index is a full userdata, +returns its memory-block address. +If the value is a light userdata, +returns its value (a pointer). +Otherwise, returns NULL. + + + + + +


    lua_type

    +[-0, +0, –] +

    int lua_type (lua_State *L, int index);
    + +

    +Returns the type of the value in the given valid index, +or LUA_TNONE for a non-valid but acceptable index. +The types returned by lua_type are coded by the following constants +defined in lua.h: +LUA_TNIL, +LUA_TNUMBER, +LUA_TBOOLEAN, +LUA_TSTRING, +LUA_TTABLE, +LUA_TFUNCTION, +LUA_TUSERDATA, +LUA_TTHREAD, +and +LUA_TLIGHTUSERDATA. + + + + + +


    lua_typename

    +[-0, +0, –] +

    const char *lua_typename (lua_State *L, int tp);
    + +

    +Returns the name of the type encoded by the value tp, +which must be one the values returned by lua_type. + + + + + +


    lua_Unsigned

    +
    typedef ... lua_Unsigned;
    + +

    +The unsigned version of lua_Integer. + + + + + +


    lua_upvalueindex

    +[-0, +0, –] +

    int lua_upvalueindex (int i);
    + +

    +Returns the pseudo-index that represents the i-th upvalue of +the running function (see §4.2). +i must be in the range [1,256]. + + + + + +


    lua_version

    +[-0, +0, –] +

    lua_Number lua_version (lua_State *L);
    + +

    +Returns the version number of this core. + + + + + +


    lua_WarnFunction

    +
    typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);
    + +

    +The type of warning functions, called by Lua to emit warnings. +The first parameter is an opaque pointer +set by lua_setwarnf. +The second parameter is the warning message. +The third parameter is a boolean that +indicates whether the message is +to be continued by the message in the next call. + + +

    +See warn for more details about warnings. + + + + + +


    lua_warning

    +[-0, +0, –] +

    void lua_warning (lua_State *L, const char *msg, int tocont);
    + +

    +Emits a warning with the given message. +A message in a call with tocont true should be +continued in another call to this function. + + +

    +See warn for more details about warnings. + + + + + +


    lua_Writer

    +
    typedef int (*lua_Writer) (lua_State *L,
    +                           const void* p,
    +                           size_t sz,
    +                           void* ud);
    + +

    +The type of the writer function used by lua_dump. +Every time lua_dump produces another piece of chunk, +it calls the writer, +passing along the buffer to be written (p), +its size (sz), +and the ud parameter supplied to lua_dump. + + +

    +The writer returns an error code: +0 means no errors; +any other value means an error and stops lua_dump from +calling the writer again. + + + + + +


    lua_xmove

    +[-?, +?, –] +

    void lua_xmove (lua_State *from, lua_State *to, int n);
    + +

    +Exchange values between different threads of the same state. + + +

    +This function pops n values from the stack from, +and pushes them onto the stack to. + + + + + +


    lua_yield

    +[-?, +?, v] +

    int lua_yield (lua_State *L, int nresults);
    + +

    +This function is equivalent to lua_yieldk, +but it has no continuation (see §4.5). +Therefore, when the thread resumes, +it continues the function that called +the function calling lua_yield. +To avoid surprises, +this function should be called only in a tail call. + + + + + +


    lua_yieldk

    +[-?, +?, v] +

    int lua_yieldk (lua_State *L,
    +                int nresults,
    +                lua_KContext ctx,
    +                lua_KFunction k);
    + +

    +Yields a coroutine (thread). + + +

    +When a C function calls lua_yieldk, +the running coroutine suspends its execution, +and the call to lua_resume that started this coroutine returns. +The parameter nresults is the number of values from the stack +that will be passed as results to lua_resume. + + +

    +When the coroutine is resumed again, +Lua calls the given continuation function k to continue +the execution of the C function that yielded (see §4.5). +This continuation function receives the same stack +from the previous function, +with the n results removed and +replaced by the arguments passed to lua_resume. +Moreover, +the continuation function receives the value ctx +that was passed to lua_yieldk. + + +

    +Usually, this function does not return; +when the coroutine eventually resumes, +it continues executing the continuation function. +However, there is one special case, +which is when this function is called +from inside a line or a count hook (see §4.7). +In that case, lua_yieldk should be called with no continuation +(probably in the form of lua_yield) and no results, +and the hook should return immediately after the call. +Lua will yield and, +when the coroutine resumes again, +it will continue the normal execution +of the (Lua) function that triggered the hook. + + +

    +This function can raise an error if it is called from a thread +with a pending C call with no continuation function +(what is called a C-call boundary), +or it is called from a thread that is not running inside a resume +(typically the main thread). + + + + + + + +

    4.7 – The Debug Interface

    + +

    +Lua has no built-in debugging facilities. +Instead, it offers a special interface +by means of functions and hooks. +This interface allows the construction of different +kinds of debuggers, profilers, and other tools +that need "inside information" from the interpreter. + + + +


    lua_Debug

    +
    typedef struct lua_Debug {
    +  int event;
    +  const char *name;           /* (n) */
    +  const char *namewhat;       /* (n) */
    +  const char *what;           /* (S) */
    +  const char *source;         /* (S) */
    +  size_t srclen;              /* (S) */
    +  int currentline;            /* (l) */
    +  int linedefined;            /* (S) */
    +  int lastlinedefined;        /* (S) */
    +  unsigned char nups;         /* (u) number of upvalues */
    +  unsigned char nparams;      /* (u) number of parameters */
    +  char isvararg;              /* (u) */
    +  char istailcall;            /* (t) */
    +  unsigned short ftransfer;   /* (r) index of first value transferred */
    +  unsigned short ntransfer;   /* (r) number of transferred values */
    +  char short_src[LUA_IDSIZE]; /* (S) */
    +  /* private part */
    +  other fields
    +} lua_Debug;
    + +

    +A structure used to carry different pieces of +information about a function or an activation record. +lua_getstack fills only the private part +of this structure, for later use. +To fill the other fields of lua_Debug with useful information, +you must call lua_getinfo with an appropriate parameter. +(Specifically, to get a field, +you must add the letter between parentheses in the field's comment +to the parameter what of lua_getinfo.) + + +

    +The fields of lua_Debug have the following meaning: + +

      + +
    • source: +the source of the chunk that created the function. +If source starts with a '@', +it means that the function was defined in a file where +the file name follows the '@'. +If source starts with a '=', +the remainder of its contents describes the source in a user-dependent manner. +Otherwise, +the function was defined in a string where +source is that string. +
    • + +
    • srclen: +The length of the string source. +
    • + +
    • short_src: +a "printable" version of source, to be used in error messages. +
    • + +
    • linedefined: +the line number where the definition of the function starts. +
    • + +
    • lastlinedefined: +the line number where the definition of the function ends. +
    • + +
    • what: +the string "Lua" if the function is a Lua function, +"C" if it is a C function, +"main" if it is the main part of a chunk. +
    • + +
    • currentline: +the current line where the given function is executing. +When no line information is available, +currentline is set to -1. +
    • + +
    • name: +a reasonable name for the given function. +Because functions in Lua are first-class values, +they do not have a fixed name: +some functions can be the value of multiple global variables, +while others can be stored only in a table field. +The lua_getinfo function checks how the function was +called to find a suitable name. +If it cannot find a name, +then name is set to NULL. +
    • + +
    • namewhat: +explains the name field. +The value of namewhat can be +"global", "local", "method", +"field", "upvalue", or "" (the empty string), +according to how the function was called. +(Lua uses the empty string when no other option seems to apply.) +
    • + +
    • istailcall: +true if this function invocation was called by a tail call. +In this case, the caller of this level is not in the stack. +
    • + +
    • nups: +the number of upvalues of the function. +
    • + +
    • nparams: +the number of parameters of the function +(always 0 for C functions). +
    • + +
    • isvararg: +true if the function is a variadic function +(always true for C functions). +
    • + +
    • ftransfer: +the index in the stack of the first value being "transferred", +that is, parameters in a call or return values in a return. +(The other values are in consecutive indices.) +Using this index, you can access and modify these values +through lua_getlocal and lua_setlocal. +This field is only meaningful during a +call hook, denoting the first parameter, +or a return hook, denoting the first value being returned. +(For call hooks, this value is always 1.) +
    • + +
    • ntransfer: +The number of values being transferred (see previous item). +(For calls of Lua functions, +this value is always equal to nparams.) +
    • + +
    + + + + +

    lua_gethook

    +[-0, +0, –] +

    lua_Hook lua_gethook (lua_State *L);
    + +

    +Returns the current hook function. + + + + + +


    lua_gethookcount

    +[-0, +0, –] +

    int lua_gethookcount (lua_State *L);
    + +

    +Returns the current hook count. + + + + + +


    lua_gethookmask

    +[-0, +0, –] +

    int lua_gethookmask (lua_State *L);
    + +

    +Returns the current hook mask. + + + + + +


    lua_getinfo

    +[-(0|1), +(0|1|2), m] +

    int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
    + +

    +Gets information about a specific function or function invocation. + + +

    +To get information about a function invocation, +the parameter ar must be a valid activation record that was +filled by a previous call to lua_getstack or +given as argument to a hook (see lua_Hook). + + +

    +To get information about a function, you push it onto the stack +and start the what string with the character '>'. +(In that case, +lua_getinfo pops the function from the top of the stack.) +For instance, to know in which line a function f was defined, +you can write the following code: + +

    +     lua_Debug ar;
    +     lua_getglobal(L, "f");  /* get global 'f' */
    +     lua_getinfo(L, ">S", &ar);
    +     printf("%d\n", ar.linedefined);
    +
    + +

    +Each character in the string what +selects some fields of the structure ar to be filled or +a value to be pushed on the stack. +(These characters are also documented in the declaration of +the structure lua_Debug, +between parentheses in the comments following each field.) + +

      + +
    • 'f': +pushes onto the stack the function that is +running at the given level; +
    • + +
    • 'l': fills in the field currentline; +
    • + +
    • 'n': fills in the fields name and namewhat; +
    • + +
    • 'r': fills in the fields ftransfer and ntransfer; +
    • + +
    • 'S': +fills in the fields source, short_src, +linedefined, lastlinedefined, and what; +
    • + +
    • 't': fills in the field istailcall; +
    • + +
    • 'u': fills in the fields +nups, nparams, and isvararg; +
    • + +
    • 'L': +pushes onto the stack a table whose indices are +the lines on the function with some associated code, +that is, the lines where you can put a break point. +(Lines with no code include empty lines and comments.) +If this option is given together with option 'f', +its table is pushed after the function. +This is the only option that can raise a memory error. +
    • + +
    + +

    +This function returns 0 to signal an invalid option in what; +even then the valid options are handled correctly. + + + + + +


    lua_getlocal

    +[-0, +(0|1), –] +

    const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
    + +

    +Gets information about a local variable or a temporary value +of a given activation record or a given function. + + +

    +In the first case, +the parameter ar must be a valid activation record that was +filled by a previous call to lua_getstack or +given as argument to a hook (see lua_Hook). +The index n selects which local variable to inspect; +see debug.getlocal for details about variable indices +and names. + + +

    +lua_getlocal pushes the variable's value onto the stack +and returns its name. + + +

    +In the second case, ar must be NULL and the function +to be inspected must be on the top of the stack. +In this case, only parameters of Lua functions are visible +(as there is no information about what variables are active) +and no values are pushed onto the stack. + + +

    +Returns NULL (and pushes nothing) +when the index is greater than +the number of active local variables. + + + + + +


    lua_getstack

    +[-0, +0, –] +

    int lua_getstack (lua_State *L, int level, lua_Debug *ar);
    + +

    +Gets information about the interpreter runtime stack. + + +

    +This function fills parts of a lua_Debug structure with +an identification of the activation record +of the function executing at a given level. +Level 0 is the current running function, +whereas level n+1 is the function that has called level n +(except for tail calls, which do not count in the stack). +When called with a level greater than the stack depth, +lua_getstack returns 0; +otherwise it returns 1. + + + + + +


    lua_getupvalue

    +[-0, +(0|1), –] +

    const char *lua_getupvalue (lua_State *L, int funcindex, int n);
    + +

    +Gets information about the n-th upvalue +of the closure at index funcindex. +It pushes the upvalue's value onto the stack +and returns its name. +Returns NULL (and pushes nothing) +when the index n is greater than the number of upvalues. + + +

    +See debug.getupvalue for more information about upvalues. + + + + + +


    lua_Hook

    +
    typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
    + +

    +Type for debugging hook functions. + + +

    +Whenever a hook is called, its ar argument has its field +event set to the specific event that triggered the hook. +Lua identifies these events with the following constants: +LUA_HOOKCALL, LUA_HOOKRET, +LUA_HOOKTAILCALL, LUA_HOOKLINE, +and LUA_HOOKCOUNT. +Moreover, for line events, the field currentline is also set. +To get the value of any other field in ar, +the hook must call lua_getinfo. + + +

    +For call events, event can be LUA_HOOKCALL, +the normal value, or LUA_HOOKTAILCALL, for a tail call; +in this case, there will be no corresponding return event. + + +

    +While Lua is running a hook, it disables other calls to hooks. +Therefore, if a hook calls back Lua to execute a function or a chunk, +this execution occurs without any calls to hooks. + + +

    +Hook functions cannot have continuations, +that is, they cannot call lua_yieldk, +lua_pcallk, or lua_callk with a non-null k. + + +

    +Hook functions can yield under the following conditions: +Only count and line events can yield; +to yield, a hook function must finish its execution +calling lua_yield with nresults equal to zero +(that is, with no values). + + + + + +


    lua_sethook

    +[-0, +0, –] +

    void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
    + +

    +Sets the debugging hook function. + + +

    +Argument f is the hook function. +mask specifies on which events the hook will be called: +it is formed by a bitwise OR of the constants +LUA_MASKCALL, +LUA_MASKRET, +LUA_MASKLINE, +and LUA_MASKCOUNT. +The count argument is only meaningful when the mask +includes LUA_MASKCOUNT. +For each event, the hook is called as explained below: + +

      + +
    • The call hook: is called when the interpreter calls a function. +The hook is called just after Lua enters the new function. +
    • + +
    • The return hook: is called when the interpreter returns from a function. +The hook is called just before Lua leaves the function. +
    • + +
    • The line hook: is called when the interpreter is about to +start the execution of a new line of code, +or when it jumps back in the code (even to the same line). +This event only happens while Lua is executing a Lua function. +
    • + +
    • The count hook: is called after the interpreter executes every +count instructions. +This event only happens while Lua is executing a Lua function. +
    • + +
    + +

    +Hooks are disabled by setting mask to zero. + + + + + +


    lua_setlocal

    +[-(0|1), +0, –] +

    const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
    + +

    +Sets the value of a local variable of a given activation record. +It assigns the value on the top of the stack +to the variable and returns its name. +It also pops the value from the stack. + + +

    +Returns NULL (and pops nothing) +when the index is greater than +the number of active local variables. + + +

    +Parameters ar and n are as in the function lua_getlocal. + + + + + +


    lua_setupvalue

    +[-(0|1), +0, –] +

    const char *lua_setupvalue (lua_State *L, int funcindex, int n);
    + +

    +Sets the value of a closure's upvalue. +It assigns the value on the top of the stack +to the upvalue and returns its name. +It also pops the value from the stack. + + +

    +Returns NULL (and pops nothing) +when the index n is greater than the number of upvalues. + + +

    +Parameters funcindex and n are as in +the function lua_getupvalue. + + + + + +


    lua_upvalueid

    +[-0, +0, –] +

    void *lua_upvalueid (lua_State *L, int funcindex, int n);
    + +

    +Returns a unique identifier for the upvalue numbered n +from the closure at index funcindex. + + +

    +These unique identifiers allow a program to check whether different +closures share upvalues. +Lua closures that share an upvalue +(that is, that access a same external local variable) +will return identical ids for those upvalue indices. + + +

    +Parameters funcindex and n are as in +the function lua_getupvalue, +but n cannot be greater than the number of upvalues. + + + + + +


    lua_upvaluejoin

    +[-0, +0, –] +

    void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
    +                                    int funcindex2, int n2);
    + +

    +Make the n1-th upvalue of the Lua closure at index funcindex1 +refer to the n2-th upvalue of the Lua closure at index funcindex2. + + + + + + + +

    5 – The Auxiliary Library

    + + + +

    + +The auxiliary library provides several convenient functions +to interface C with Lua. +While the basic API provides the primitive functions for all +interactions between C and Lua, +the auxiliary library provides higher-level functions for some +common tasks. + + +

    +All functions and types from the auxiliary library +are defined in header file lauxlib.h and +have a prefix luaL_. + + +

    +All functions in the auxiliary library are built on +top of the basic API, +and so they provide nothing that cannot be done with that API. +Nevertheless, the use of the auxiliary library ensures +more consistency to your code. + + +

    +Several functions in the auxiliary library use internally some +extra stack slots. +When a function in the auxiliary library uses less than five slots, +it does not check the stack size; +it simply assumes that there are enough slots. + + +

    +Several functions in the auxiliary library are used to +check C function arguments. +Because the error message is formatted for arguments +(e.g., "bad argument #1"), +you should not use these functions for other stack values. + + +

    +Functions called luaL_check* +always raise an error if the check is not satisfied. + + + + + +

    5.1 – Functions and Types

    + +

    +Here we list all functions and types from the auxiliary library +in alphabetical order. + + + +


    luaL_addchar

    +[-?, +?, m] +

    void luaL_addchar (luaL_Buffer *B, char c);
    + +

    +Adds the byte c to the buffer B +(see luaL_Buffer). + + + + + +


    luaL_addgsub

    +[-?, +?, m] +

    const void luaL_addgsub (luaL_Buffer *B, const char *s,
    +                         const char *p, const char *r);
    + +

    +Adds a copy of the string s to the buffer B (see luaL_Buffer), +replacing any occurrence of the string p +with the string r. + + + + + +


    luaL_addlstring

    +[-?, +?, m] +

    void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
    + +

    +Adds the string pointed to by s with length l to +the buffer B +(see luaL_Buffer). +The string can contain embedded zeros. + + + + + +


    luaL_addsize

    +[-?, +?, –] +

    void luaL_addsize (luaL_Buffer *B, size_t n);
    + +

    +Adds to the buffer B +a string of length n previously copied to the +buffer area (see luaL_prepbuffer). + + + + + +


    luaL_addstring

    +[-?, +?, m] +

    void luaL_addstring (luaL_Buffer *B, const char *s);
    + +

    +Adds the zero-terminated string pointed to by s +to the buffer B +(see luaL_Buffer). + + + + + +


    luaL_addvalue

    +[-?, +?, m] +

    void luaL_addvalue (luaL_Buffer *B);
    + +

    +Adds the value on the top of the stack +to the buffer B +(see luaL_Buffer). +Pops the value. + + +

    +This is the only function on string buffers that can (and must) +be called with an extra element on the stack, +which is the value to be added to the buffer. + + + + + +


    luaL_argcheck

    +[-0, +0, v] +

    void luaL_argcheck (lua_State *L,
    +                    int cond,
    +                    int arg,
    +                    const char *extramsg);
    + +

    +Checks whether cond is true. +If it is not, raises an error with a standard message (see luaL_argerror). + + + + + +


    luaL_argerror

    +[-0, +0, v] +

    int luaL_argerror (lua_State *L, int arg, const char *extramsg);
    + +

    +Raises an error reporting a problem with argument arg +of the C function that called it, +using a standard message +that includes extramsg as a comment: + +

    +     bad argument #arg to 'funcname' (extramsg)
    +

    +This function never returns. + + + + + +


    luaL_argexpected

    +[-0, +0, v] +

    void luaL_argexpected (lua_State *L,
    +                       int cond,
    +                       int arg,
    +                       const char *tname);
    + +

    +Checks whether cond is true. +If it is not, raises an error about the type of the argument arg +with a standard message (see luaL_typeerror). + + + + + +


    luaL_Buffer

    +
    typedef struct luaL_Buffer luaL_Buffer;
    + +

    +Type for a string buffer. + + +

    +A string buffer allows C code to build Lua strings piecemeal. +Its pattern of use is as follows: + +

      + +
    • First declare a variable b of type luaL_Buffer.
    • + +
    • Then initialize it with a call luaL_buffinit(L, &b).
    • + +
    • +Then add string pieces to the buffer calling any of +the luaL_add* functions. +
    • + +
    • +Finish by calling luaL_pushresult(&b). +This call leaves the final string on the top of the stack. +
    • + +
    + +

    +If you know beforehand the maximum size of the resulting string, +you can use the buffer like this: + +

      + +
    • First declare a variable b of type luaL_Buffer.
    • + +
    • Then initialize it and preallocate a space of +size sz with a call luaL_buffinitsize(L, &b, sz).
    • + +
    • Then produce the string into that space.
    • + +
    • +Finish by calling luaL_pushresultsize(&b, sz), +where sz is the total size of the resulting string +copied into that space (which may be less than or +equal to the preallocated size). +
    • + +
    + +

    +During its normal operation, +a string buffer uses a variable number of stack slots. +So, while using a buffer, you cannot assume that you know where +the top of the stack is. +You can use the stack between successive calls to buffer operations +as long as that use is balanced; +that is, +when you call a buffer operation, +the stack is at the same level +it was immediately after the previous buffer operation. +(The only exception to this rule is luaL_addvalue.) +After calling luaL_pushresult, +the stack is back to its level when the buffer was initialized, +plus the final string on its top. + + + + + +


    luaL_buffaddr

    +[-0, +0, –] +

    char *luaL_buffaddr (luaL_Buffer *B);
    + +

    +Returns the address of the current content of buffer B +(see luaL_Buffer). +Note that any addition to the buffer may invalidate this address. + + + + + +


    luaL_buffinit

    +[-0, +?, –] +

    void luaL_buffinit (lua_State *L, luaL_Buffer *B);
    + +

    +Initializes a buffer B +(see luaL_Buffer). +This function does not allocate any space; +the buffer must be declared as a variable. + + + + + +


    luaL_bufflen

    +[-0, +0, –] +

    size_t luaL_bufflen (luaL_Buffer *B);
    + +

    +Returns the length of the current content of buffer B +(see luaL_Buffer). + + + + + +


    luaL_buffinitsize

    +[-?, +?, m] +

    char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);
    + +

    +Equivalent to the sequence +luaL_buffinit, luaL_prepbuffsize. + + + + + +


    luaL_buffsub

    +[-?, +?, –] +

    void luaL_buffsub (luaL_Buffer *B, int n);
    + +

    +Removes n bytes from the buffer B +(see luaL_Buffer). +The buffer must have at least that many bytes. + + + + + +


    luaL_callmeta

    +[-0, +(0|1), e] +

    int luaL_callmeta (lua_State *L, int obj, const char *e);
    + +

    +Calls a metamethod. + + +

    +If the object at index obj has a metatable and this +metatable has a field e, +this function calls this field passing the object as its only argument. +In this case this function returns true and pushes onto the +stack the value returned by the call. +If there is no metatable or no metamethod, +this function returns false without pushing any value on the stack. + + + + + +


    luaL_checkany

    +[-0, +0, v] +

    void luaL_checkany (lua_State *L, int arg);
    + +

    +Checks whether the function has an argument +of any type (including nil) at position arg. + + + + + +


    luaL_checkinteger

    +[-0, +0, v] +

    lua_Integer luaL_checkinteger (lua_State *L, int arg);
    + +

    +Checks whether the function argument arg is an integer +(or can be converted to an integer) +and returns this integer. + + + + + +


    luaL_checklstring

    +[-0, +0, v] +

    const char *luaL_checklstring (lua_State *L, int arg, size_t *l);
    + +

    +Checks whether the function argument arg is a string +and returns this string; +if l is not NULL fills its referent +with the string's length. + + +

    +This function uses lua_tolstring to get its result, +so all conversions and caveats of that function apply here. + + + + + +


    luaL_checknumber

    +[-0, +0, v] +

    lua_Number luaL_checknumber (lua_State *L, int arg);
    + +

    +Checks whether the function argument arg is a number +and returns this number converted to a lua_Number. + + + + + +


    luaL_checkoption

    +[-0, +0, v] +

    int luaL_checkoption (lua_State *L,
    +                      int arg,
    +                      const char *def,
    +                      const char *const lst[]);
    + +

    +Checks whether the function argument arg is a string and +searches for this string in the array lst +(which must be NULL-terminated). +Returns the index in the array where the string was found. +Raises an error if the argument is not a string or +if the string cannot be found. + + +

    +If def is not NULL, +the function uses def as a default value when +there is no argument arg or when this argument is nil. + + +

    +This is a useful function for mapping strings to C enums. +(The usual convention in Lua libraries is +to use strings instead of numbers to select options.) + + + + + +


    luaL_checkstack

    +[-0, +0, v] +

    void luaL_checkstack (lua_State *L, int sz, const char *msg);
    + +

    +Grows the stack size to top + sz elements, +raising an error if the stack cannot grow to that size. +msg is an additional text to go into the error message +(or NULL for no additional text). + + + + + +


    luaL_checkstring

    +[-0, +0, v] +

    const char *luaL_checkstring (lua_State *L, int arg);
    + +

    +Checks whether the function argument arg is a string +and returns this string. + + +

    +This function uses lua_tolstring to get its result, +so all conversions and caveats of that function apply here. + + + + + +


    luaL_checktype

    +[-0, +0, v] +

    void luaL_checktype (lua_State *L, int arg, int t);
    + +

    +Checks whether the function argument arg has type t. +See lua_type for the encoding of types for t. + + + + + +


    luaL_checkudata

    +[-0, +0, v] +

    void *luaL_checkudata (lua_State *L, int arg, const char *tname);
    + +

    +Checks whether the function argument arg is a userdata +of the type tname (see luaL_newmetatable) and +returns the userdata's memory-block address (see lua_touserdata). + + + + + +


    luaL_checkversion

    +[-0, +0, v] +

    void luaL_checkversion (lua_State *L);
    + +

    +Checks whether the code making the call and the Lua library being called +are using the same version of Lua and the same numeric types. + + + + + +


    luaL_dofile

    +[-0, +?, m] +

    int luaL_dofile (lua_State *L, const char *filename);
    + +

    +Loads and runs the given file. +It is defined as the following macro: + +

    +     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
    +

    +It returns 0 (LUA_OK) if there are no errors, +or 1 in case of errors. + + + + + +


    luaL_dostring

    +[-0, +?, –] +

    int luaL_dostring (lua_State *L, const char *str);
    + +

    +Loads and runs the given string. +It is defined as the following macro: + +

    +     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
    +

    +It returns 0 (LUA_OK) if there are no errors, +or 1 in case of errors. + + + + + +


    luaL_error

    +[-0, +0, v] +

    int luaL_error (lua_State *L, const char *fmt, ...);
    + +

    +Raises an error. +The error message format is given by fmt +plus any extra arguments, +following the same rules of lua_pushfstring. +It also adds at the beginning of the message the file name and +the line number where the error occurred, +if this information is available. + + +

    +This function never returns, +but it is an idiom to use it in C functions +as return luaL_error(args). + + + + + +


    luaL_execresult

    +[-0, +3, m] +

    int luaL_execresult (lua_State *L, int stat);
    + +

    +This function produces the return values for +process-related functions in the standard library +(os.execute and io.close). + + + + + +


    luaL_fileresult

    +[-0, +(1|3), m] +

    int luaL_fileresult (lua_State *L, int stat, const char *fname);
    + +

    +This function produces the return values for +file-related functions in the standard library +(io.open, os.rename, file:seek, etc.). + + + + + +


    luaL_getmetafield

    +[-0, +(0|1), m] +

    int luaL_getmetafield (lua_State *L, int obj, const char *e);
    + +

    +Pushes onto the stack the field e from the metatable +of the object at index obj and returns the type of the pushed value. +If the object does not have a metatable, +or if the metatable does not have this field, +pushes nothing and returns LUA_TNIL. + + + + + +


    luaL_getmetatable

    +[-0, +1, m] +

    int luaL_getmetatable (lua_State *L, const char *tname);
    + +

    +Pushes onto the stack the metatable associated with the name tname +in the registry (see luaL_newmetatable), +or nil if there is no metatable associated with that name. +Returns the type of the pushed value. + + + + + +


    luaL_getsubtable

    +[-0, +1, e] +

    int luaL_getsubtable (lua_State *L, int idx, const char *fname);
    + +

    +Ensures that the value t[fname], +where t is the value at index idx, +is a table, +and pushes that table onto the stack. +Returns true if it finds a previous table there +and false if it creates a new table. + + + + + +


    luaL_gsub

    +[-0, +1, m] +

    const char *luaL_gsub (lua_State *L,
    +                       const char *s,
    +                       const char *p,
    +                       const char *r);
    + +

    +Creates a copy of string s, +replacing any occurrence of the string p +with the string r. +Pushes the resulting string on the stack and returns it. + + + + + +


    luaL_len

    +[-0, +0, e] +

    lua_Integer luaL_len (lua_State *L, int index);
    + +

    +Returns the "length" of the value at the given index +as a number; +it is equivalent to the '#' operator in Lua (see §3.4.7). +Raises an error if the result of the operation is not an integer. +(This case can only happen through metamethods.) + + + + + +


    luaL_loadbuffer

    +[-0, +1, –] +

    int luaL_loadbuffer (lua_State *L,
    +                     const char *buff,
    +                     size_t sz,
    +                     const char *name);
    + +

    +Equivalent to luaL_loadbufferx with mode equal to NULL. + + + + + +


    luaL_loadbufferx

    +[-0, +1, –] +

    int luaL_loadbufferx (lua_State *L,
    +                      const char *buff,
    +                      size_t sz,
    +                      const char *name,
    +                      const char *mode);
    + +

    +Loads a buffer as a Lua chunk. +This function uses lua_load to load the chunk in the +buffer pointed to by buff with size sz. + + +

    +This function returns the same results as lua_load. +name is the chunk name, +used for debug information and error messages. +The string mode works as in the function lua_load. + + + + + +


    luaL_loadfile

    +[-0, +1, m] +

    int luaL_loadfile (lua_State *L, const char *filename);
    + +

    +Equivalent to luaL_loadfilex with mode equal to NULL. + + + + + +


    luaL_loadfilex

    +[-0, +1, m] +

    int luaL_loadfilex (lua_State *L, const char *filename,
    +                                            const char *mode);
    + +

    +Loads a file as a Lua chunk. +This function uses lua_load to load the chunk in the file +named filename. +If filename is NULL, +then it loads from the standard input. +The first line in the file is ignored if it starts with a #. + + +

    +The string mode works as in the function lua_load. + + +

    +This function returns the same results as lua_load +or LUA_ERRFILE for file-related errors. + + +

    +As lua_load, this function only loads the chunk; +it does not run it. + + + + + +


    luaL_loadstring

    +[-0, +1, –] +

    int luaL_loadstring (lua_State *L, const char *s);
    + +

    +Loads a string as a Lua chunk. +This function uses lua_load to load the chunk in +the zero-terminated string s. + + +

    +This function returns the same results as lua_load. + + +

    +Also as lua_load, this function only loads the chunk; +it does not run it. + + + + + +


    luaL_newlib

    +[-0, +1, m] +

    void luaL_newlib (lua_State *L, const luaL_Reg l[]);
    + +

    +Creates a new table and registers there +the functions in the list l. + + +

    +It is implemented as the following macro: + +

    +     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
    +

    +The array l must be the actual array, +not a pointer to it. + + + + + +


    luaL_newlibtable

    +[-0, +1, m] +

    void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);
    + +

    +Creates a new table with a size optimized +to store all entries in the array l +(but does not actually store them). +It is intended to be used in conjunction with luaL_setfuncs +(see luaL_newlib). + + +

    +It is implemented as a macro. +The array l must be the actual array, +not a pointer to it. + + + + + +


    luaL_newmetatable

    +[-0, +1, m] +

    int luaL_newmetatable (lua_State *L, const char *tname);
    + +

    +If the registry already has the key tname, +returns 0. +Otherwise, +creates a new table to be used as a metatable for userdata, +adds to this new table the pair __name = tname, +adds to the registry the pair [tname] = new table, +and returns 1. + + +

    +In both cases, +the function pushes onto the stack the final value associated +with tname in the registry. + + + + + +


    luaL_newstate

    +[-0, +0, –] +

    lua_State *luaL_newstate (void);
    + +

    +Creates a new Lua state. +It calls lua_newstate with an +allocator based on the ISO C allocation functions +and then sets a warning function and a panic function (see §4.4) +that print messages to the standard error output. + + +

    +Returns the new state, +or NULL if there is a memory allocation error. + + + + + +


    luaL_openlibs

    +[-0, +0, e] +

    void luaL_openlibs (lua_State *L);
    + +

    +Opens all standard Lua libraries into the given state. + + + + + +


    luaL_opt

    +[-0, +0, –] +

    T luaL_opt (L, func, arg, dflt);
    + +

    +This macro is defined as follows: + +

    +     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
    +

    +In words, if the argument arg is nil or absent, +the macro results in the default dflt. +Otherwise, it results in the result of calling func +with the state L and the argument index arg as +arguments. +Note that it evaluates the expression dflt only if needed. + + + + + +


    luaL_optinteger

    +[-0, +0, v] +

    lua_Integer luaL_optinteger (lua_State *L,
    +                             int arg,
    +                             lua_Integer d);
    + +

    +If the function argument arg is an integer +(or it is convertible to an integer), +returns this integer. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + + + + + +


    luaL_optlstring

    +[-0, +0, v] +

    const char *luaL_optlstring (lua_State *L,
    +                             int arg,
    +                             const char *d,
    +                             size_t *l);
    + +

    +If the function argument arg is a string, +returns this string. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + + +

    +If l is not NULL, +fills its referent with the result's length. +If the result is NULL +(only possible when returning d and d == NULL), +its length is considered zero. + + +

    +This function uses lua_tolstring to get its result, +so all conversions and caveats of that function apply here. + + + + + +


    luaL_optnumber

    +[-0, +0, v] +

    lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);
    + +

    +If the function argument arg is a number, +returns this number as a lua_Number. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + + + + + +


    luaL_optstring

    +[-0, +0, v] +

    const char *luaL_optstring (lua_State *L,
    +                            int arg,
    +                            const char *d);
    + +

    +If the function argument arg is a string, +returns this string. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + + + + + +


    luaL_prepbuffer

    +[-?, +?, m] +

    char *luaL_prepbuffer (luaL_Buffer *B);
    + +

    +Equivalent to luaL_prepbuffsize +with the predefined size LUAL_BUFFERSIZE. + + + + + +


    luaL_prepbuffsize

    +[-?, +?, m] +

    char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);
    + +

    +Returns an address to a space of size sz +where you can copy a string to be added to buffer B +(see luaL_Buffer). +After copying the string into this space you must call +luaL_addsize with the size of the string to actually add +it to the buffer. + + + + + +


    luaL_pushfail

    +[-0, +1, –] +

    void luaL_pushfail (lua_State *L);
    + +

    +Pushes the fail value onto the stack (see §6). + + + + + +


    luaL_pushresult

    +[-?, +1, m] +

    void luaL_pushresult (luaL_Buffer *B);
    + +

    +Finishes the use of buffer B leaving the final string on +the top of the stack. + + + + + +


    luaL_pushresultsize

    +[-?, +1, m] +

    void luaL_pushresultsize (luaL_Buffer *B, size_t sz);
    + +

    +Equivalent to the sequence luaL_addsize, luaL_pushresult. + + + + + +


    luaL_ref

    +[-1, +0, m] +

    int luaL_ref (lua_State *L, int t);
    + +

    +Creates and returns a reference, +in the table at index t, +for the object on the top of the stack (and pops the object). + + +

    +A reference is a unique integer key. +As long as you do not manually add integer keys into the table t, +luaL_ref ensures the uniqueness of the key it returns. +You can retrieve an object referred by the reference r +by calling lua_rawgeti(L, t, r). +The function luaL_unref frees a reference. + + +

    +If the object on the top of the stack is nil, +luaL_ref returns the constant LUA_REFNIL. +The constant LUA_NOREF is guaranteed to be different +from any reference returned by luaL_ref. + + + + + +


    luaL_Reg

    +
    typedef struct luaL_Reg {
    +  const char *name;
    +  lua_CFunction func;
    +} luaL_Reg;
    + +

    +Type for arrays of functions to be registered by +luaL_setfuncs. +name is the function name and func is a pointer to +the function. +Any array of luaL_Reg must end with a sentinel entry +in which both name and func are NULL. + + + + + +


    luaL_requiref

    +[-0, +1, e] +

    void luaL_requiref (lua_State *L, const char *modname,
    +                    lua_CFunction openf, int glb);
    + +

    +If package.loaded[modname] is not true, +calls the function openf with the string modname as an argument +and sets the call result to package.loaded[modname], +as if that function has been called through require. + + +

    +If glb is true, +also stores the module into the global modname. + + +

    +Leaves a copy of the module on the stack. + + + + + +


    luaL_setfuncs

    +[-nup, +0, m] +

    void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);
    + +

    +Registers all functions in the array l +(see luaL_Reg) into the table on the top of the stack +(below optional upvalues, see next). + + +

    +When nup is not zero, +all functions are created with nup upvalues, +initialized with copies of the nup values +previously pushed on the stack +on top of the library table. +These values are popped from the stack after the registration. + + +

    +A function with a NULL value represents a placeholder, +which is filled with false. + + + + + +


    luaL_setmetatable

    +[-0, +0, –] +

    void luaL_setmetatable (lua_State *L, const char *tname);
    + +

    +Sets the metatable of the object on the top of the stack +as the metatable associated with name tname +in the registry (see luaL_newmetatable). + + + + + +


    luaL_Stream

    +
    typedef struct luaL_Stream {
    +  FILE *f;
    +  lua_CFunction closef;
    +} luaL_Stream;
    + +

    +The standard representation for file handles +used by the standard I/O library. + + +

    +A file handle is implemented as a full userdata, +with a metatable called LUA_FILEHANDLE +(where LUA_FILEHANDLE is a macro with the actual metatable's name). +The metatable is created by the I/O library +(see luaL_newmetatable). + + +

    +This userdata must start with the structure luaL_Stream; +it can contain other data after this initial structure. +The field f points to the corresponding C stream +(or it can be NULL to indicate an incompletely created handle). +The field closef points to a Lua function +that will be called to close the stream +when the handle is closed or collected; +this function receives the file handle as its sole argument and +must return either a true value, in case of success, +or a false value plus an error message, in case of error. +Once Lua calls this field, +it changes the field value to NULL +to signal that the handle is closed. + + + + + +


    luaL_testudata

    +[-0, +0, m] +

    void *luaL_testudata (lua_State *L, int arg, const char *tname);
    + +

    +This function works like luaL_checkudata, +except that, when the test fails, +it returns NULL instead of raising an error. + + + + + +


    luaL_tolstring

    +[-0, +1, e] +

    const char *luaL_tolstring (lua_State *L, int idx, size_t *len);
    + +

    +Converts any Lua value at the given index to a C string +in a reasonable format. +The resulting string is pushed onto the stack and also +returned by the function (see §4.1.3). +If len is not NULL, +the function also sets *len with the string length. + + +

    +If the value has a metatable with a __tostring field, +then luaL_tolstring calls the corresponding metamethod +with the value as argument, +and uses the result of the call as its result. + + + + + +


    luaL_traceback

    +[-0, +1, m] +

    void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
    +                     int level);
    + +

    +Creates and pushes a traceback of the stack L1. +If msg is not NULL, it is appended +at the beginning of the traceback. +The level parameter tells at which level +to start the traceback. + + + + + +


    luaL_typeerror

    +[-0, +0, v] +

    int luaL_typeerror (lua_State *L, int arg, const char *tname);
    + +

    +Raises a type error for the argument arg +of the C function that called it, +using a standard message; +tname is a "name" for the expected type. +This function never returns. + + + + + +


    luaL_typename

    +[-0, +0, –] +

    const char *luaL_typename (lua_State *L, int index);
    + +

    +Returns the name of the type of the value at the given index. + + + + + +


    luaL_unref

    +[-0, +0, –] +

    void luaL_unref (lua_State *L, int t, int ref);
    + +

    +Releases the reference ref from the table at index t +(see luaL_ref). +The entry is removed from the table, +so that the referred object can be collected. +The reference ref is also freed to be used again. + + +

    +If ref is LUA_NOREF or LUA_REFNIL, +luaL_unref does nothing. + + + + + +


    luaL_where

    +[-0, +1, m] +

    void luaL_where (lua_State *L, int lvl);
    + +

    +Pushes onto the stack a string identifying the current position +of the control at level lvl in the call stack. +Typically this string has the following format: + +

    +     chunkname:currentline:
    +

    +Level 0 is the running function, +level 1 is the function that called the running function, +etc. + + +

    +This function is used to build a prefix for error messages. + + + + + + + +

    6 – The Standard Libraries

    + + + +

    +The standard Lua libraries provide useful functions +that are implemented in C through the C API. +Some of these functions provide essential services to the language +(e.g., type and getmetatable); +others provide access to outside services (e.g., I/O); +and others could be implemented in Lua itself, +but that for different reasons +deserve an implementation in C (e.g., table.sort). + + +

    +All libraries are implemented through the official C API +and are provided as separate C modules. +Unless otherwise noted, +these library functions do not adjust its number of arguments +to its expected parameters. +For instance, a function documented as foo(arg) +should not be called without an argument. + + +

    +The notation fail means a false value representing +some kind of failure. +(Currently, fail is equal to nil, +but that may change in future versions. +The recommendation is to always test the success of these functions +with (not status), instead of (status == nil).) + + +

    +Currently, Lua has the following standard libraries: + +

      + +
    • basic library (§6.1);
    • + +
    • coroutine library (§6.2);
    • + +
    • package library (§6.3);
    • + +
    • string manipulation (§6.4);
    • + +
    • basic UTF-8 support (§6.5);
    • + +
    • table manipulation (§6.6);
    • + +
    • mathematical functions (§6.7) (sin, log, etc.);
    • + +
    • input and output (§6.8);
    • + +
    • operating system facilities (§6.9);
    • + +
    • debug facilities (§6.10).
    • + +

    +Except for the basic and the package libraries, +each library provides all its functions as fields of a global table +or as methods of its objects. + + +

    +To have access to these libraries, +the C host program should call the luaL_openlibs function, +which opens all standard libraries. +Alternatively, +the host program can open them individually by using +luaL_requiref to call +luaopen_base (for the basic library), +luaopen_package (for the package library), +luaopen_coroutine (for the coroutine library), +luaopen_string (for the string library), +luaopen_utf8 (for the UTF-8 library), +luaopen_table (for the table library), +luaopen_math (for the mathematical library), +luaopen_io (for the I/O library), +luaopen_os (for the operating system library), +and luaopen_debug (for the debug library). +These functions are declared in lualib.h. + + + + + +

    6.1 – Basic Functions

    + +

    +The basic library provides core functions to Lua. +If you do not include this library in your application, +you should check carefully whether you need to provide +implementations for some of its facilities. + + +

    +


    assert (v [, message])

    + + +

    +Raises an error if +the value of its argument v is false (i.e., nil or false); +otherwise, returns all its arguments. +In case of error, +message is the error object; +when absent, it defaults to "assertion failed!" + + + + +

    +


    collectgarbage ([opt [, arg]])

    + + +

    +This function is a generic interface to the garbage collector. +It performs different functions according to its first argument, opt: + +

      + +
    • "collect": +Performs a full garbage-collection cycle. +This is the default option. +
    • + +
    • "stop": +Stops automatic execution of the garbage collector. +The collector will run only when explicitly invoked, +until a call to restart it. +
    • + +
    • "restart": +Restarts automatic execution of the garbage collector. +
    • + +
    • "count": +Returns the total memory in use by Lua in Kbytes. +The value has a fractional part, +so that it multiplied by 1024 +gives the exact number of bytes in use by Lua. +
    • + +
    • "step": +Performs a garbage-collection step. +The step "size" is controlled by arg. +With a zero value, +the collector will perform one basic (indivisible) step. +For non-zero values, +the collector will perform as if that amount of memory +(in Kbytes) had been allocated by Lua. +Returns true if the step finished a collection cycle. +
    • + +
    • "isrunning": +Returns a boolean that tells whether the collector is running +(i.e., not stopped). +
    • + +
    • "incremental": +Change the collector mode to incremental. +This option can be followed by three numbers: +the garbage-collector pause, +the step multiplier, +and the step size (see §2.5.1). +A zero means to not change that value. +
    • + +
    • "generational": +Change the collector mode to generational. +This option can be followed by two numbers: +the garbage-collector minor multiplier +and the major multiplier (see §2.5.2). +A zero means to not change that value. +
    • + +

    +See §2.5 for more details about garbage collection +and some of these options. + + +

    +This function should not be called by a finalizer. + + + + +

    +


    dofile ([filename])

    +Opens the named file and executes its content as a Lua chunk. +When called without arguments, +dofile executes the content of the standard input (stdin). +Returns all values returned by the chunk. +In case of errors, dofile propagates the error +to its caller. +(That is, dofile does not run in protected mode.) + + + + +

    +


    error (message [, level])

    +Raises an error (see §2.3) with message as the error object. +This function never returns. + + +

    +Usually, error adds some information about the error position +at the beginning of the message, if the message is a string. +The level argument specifies how to get the error position. +With level 1 (the default), the error position is where the +error function was called. +Level 2 points the error to where the function +that called error was called; and so on. +Passing a level 0 avoids the addition of error position information +to the message. + + + + +

    +


    _G

    +A global variable (not a function) that +holds the global environment (see §2.2). +Lua itself does not use this variable; +changing its value does not affect any environment, +nor vice versa. + + + + +

    +


    getmetatable (object)

    + + +

    +If object does not have a metatable, returns nil. +Otherwise, +if the object's metatable has a __metatable field, +returns the associated value. +Otherwise, returns the metatable of the given object. + + + + +

    +


    ipairs (t)

    + + +

    +Returns three values (an iterator function, the table t, and 0) +so that the construction + +

    +     for i,v in ipairs(t) do body end
    +

    +will iterate over the key–value pairs +(1,t[1]), (2,t[2]), ..., +up to the first absent index. + + + + +

    +


    load (chunk [, chunkname [, mode [, env]]])

    + + +

    +Loads a chunk. + + +

    +If chunk is a string, the chunk is this string. +If chunk is a function, +load calls it repeatedly to get the chunk pieces. +Each call to chunk must return a string that concatenates +with previous results. +A return of an empty string, nil, or no value signals the end of the chunk. + + +

    +If there are no syntactic errors, +load returns the compiled chunk as a function; +otherwise, it returns fail plus the error message. + + +

    +When you load a main chunk, +the resulting function will always have exactly one upvalue, +the _ENV variable (see §2.2). +However, +when you load a binary chunk created from a function (see string.dump), +the resulting function can have an arbitrary number of upvalues, +and there is no guarantee that its first upvalue will be +the _ENV variable. +(A non-main function may not even have an _ENV upvalue.) + + +

    +Regardless, if the resulting function has any upvalues, +its first upvalue is set to the value of env, +if that parameter is given, +or to the value of the global environment. +Other upvalues are initialized with nil. +All upvalues are fresh, that is, +they are not shared with any other function. + + +

    +chunkname is used as the name of the chunk for error messages +and debug information (see §4.7). +When absent, +it defaults to chunk, if chunk is a string, +or to "=(load)" otherwise. + + +

    +The string mode controls whether the chunk can be text or binary +(that is, a precompiled chunk). +It may be the string "b" (only binary chunks), +"t" (only text chunks), +or "bt" (both binary and text). +The default is "bt". + + +

    +It is safe to load malformed binary chunks; +load signals an appropriate error. +However, +Lua does not check the consistency of the code inside binary chunks; +running maliciously crafted bytecode can crash the interpreter. + + + + +

    +


    loadfile ([filename [, mode [, env]]])

    + + +

    +Similar to load, +but gets the chunk from file filename +or from the standard input, +if no file name is given. + + + + +

    +


    next (table [, index])

    + + +

    +Allows a program to traverse all fields of a table. +Its first argument is a table and its second argument +is an index in this table. +A call to next returns the next index of the table +and its associated value. +When called with nil as its second argument, +next returns an initial index +and its associated value. +When called with the last index, +or with nil in an empty table, +next returns nil. +If the second argument is absent, then it is interpreted as nil. +In particular, +you can use next(t) to check whether a table is empty. + + +

    +The order in which the indices are enumerated is not specified, +even for numeric indices. +(To traverse a table in numerical order, +use a numerical for.) + + +

    +You should not assign any value to a non-existent field in a table +during its traversal. +You may however modify existing fields. +In particular, you may set existing fields to nil. + + + + +

    +


    pairs (t)

    + + +

    +If t has a metamethod __pairs, +calls it with t as argument and returns the first three +results from the call. + + +

    +Otherwise, +returns three values: the next function, the table t, and nil, +so that the construction + +

    +     for k,v in pairs(t) do body end
    +

    +will iterate over all key–value pairs of table t. + + +

    +See function next for the caveats of modifying +the table during its traversal. + + + + +

    +


    pcall (f [, arg1, ···])

    + + +

    +Calls the function f with +the given arguments in protected mode. +This means that any error inside f is not propagated; +instead, pcall catches the error +and returns a status code. +Its first result is the status code (a boolean), +which is true if the call succeeds without errors. +In such case, pcall also returns all results from the call, +after this first result. +In case of any error, pcall returns false plus the error object. +Note that errors caught by pcall do not call a message handler. + + + + +

    +


    print (···)

    +Receives any number of arguments +and prints their values to stdout, +converting each argument to a string +following the same rules of tostring. + + +

    +The function print is not intended for formatted output, +but only as a quick way to show a value, +for instance for debugging. +For complete control over the output, +use string.format and io.write. + + + + +

    +


    rawequal (v1, v2)

    +Checks whether v1 is equal to v2, +without invoking the __eq metamethod. +Returns a boolean. + + + + +

    +


    rawget (table, index)

    +Gets the real value of table[index], +without using the __index metavalue. +table must be a table; +index may be any value. + + + + +

    +


    rawlen (v)

    +Returns the length of the object v, +which must be a table or a string, +without invoking the __len metamethod. +Returns an integer. + + + + +

    +


    rawset (table, index, value)

    +Sets the real value of table[index] to value, +without using the __newindex metavalue. +table must be a table, +index any value different from nil and NaN, +and value any Lua value. + + +

    +This function returns table. + + + + +

    +


    select (index, ···)

    + + +

    +If index is a number, +returns all arguments after argument number index; +a negative number indexes from the end (-1 is the last argument). +Otherwise, index must be the string "#", +and select returns the total number of extra arguments it received. + + + + +

    +


    setmetatable (table, metatable)

    + + +

    +Sets the metatable for the given table. +If metatable is nil, +removes the metatable of the given table. +If the original metatable has a __metatable field, +raises an error. + + +

    +This function returns table. + + +

    +To change the metatable of other types from Lua code, +you must use the debug library (§6.10). + + + + +

    +


    tonumber (e [, base])

    + + +

    +When called with no base, +tonumber tries to convert its argument to a number. +If the argument is already a number or +a string convertible to a number, +then tonumber returns this number; +otherwise, it returns fail. + + +

    +The conversion of strings can result in integers or floats, +according to the lexical conventions of Lua (see §3.1). +The string may have leading and trailing spaces and a sign. + + +

    +When called with base, +then e must be a string to be interpreted as +an integer numeral in that base. +The base may be any integer between 2 and 36, inclusive. +In bases above 10, the letter 'A' (in either upper or lower case) +represents 10, 'B' represents 11, and so forth, +with 'Z' representing 35. +If the string e is not a valid numeral in the given base, +the function returns fail. + + + + +

    +


    tostring (v)

    + + +

    +Receives a value of any type and +converts it to a string in a human-readable format. + + +

    +If the metatable of v has a __tostring field, +then tostring calls the corresponding value +with v as argument, +and uses the result of the call as its result. +Otherwise, if the metatable of v has a __name field +with a string value, +tostring may use that string in its final result. + + +

    +For complete control of how numbers are converted, +use string.format. + + + + +

    +


    type (v)

    + + +

    +Returns the type of its only argument, coded as a string. +The possible results of this function are +"nil" (a string, not the value nil), +"number", +"string", +"boolean", +"table", +"function", +"thread", +and "userdata". + + + + +

    +


    _VERSION

    + + +

    +A global variable (not a function) that +holds a string containing the running Lua version. +The current value of this variable is "Lua 5.4". + + + + +

    +


    warn (msg1, ···)

    + + +

    +Emits a warning with a message composed by the concatenation +of all its arguments (which should be strings). + + +

    +By convention, +a one-piece message starting with '@' +is intended to be a control message, +which is a message to the warning system itself. +In particular, the standard warning function in Lua +recognizes the control messages "@off", +to stop the emission of warnings, +and "@on", to (re)start the emission; +it ignores unknown control messages. + + + + +

    +


    xpcall (f, msgh [, arg1, ···])

    + + +

    +This function is similar to pcall, +except that it sets a new message handler msgh. + + + + + + + +

    6.2 – Coroutine Manipulation

    + +

    +This library comprises the operations to manipulate coroutines, +which come inside the table coroutine. +See §2.6 for a general description of coroutines. + + +

    +


    coroutine.close (co)

    + + +

    +Closes coroutine co, +that is, +closes all its pending to-be-closed variables +and puts the coroutine in a dead state. +The given coroutine must be dead or suspended. +In case of error +(either the original error that stopped the coroutine or +errors in closing methods), +returns false plus the error object; +otherwise returns true. + + + + +

    +


    coroutine.create (f)

    + + +

    +Creates a new coroutine, with body f. +f must be a function. +Returns this new coroutine, +an object with type "thread". + + + + +

    +


    coroutine.isyieldable ([co])

    + + +

    +Returns true when the coroutine co can yield. +The default for co is the running coroutine. + + +

    +A coroutine is yieldable if it is not the main thread and +it is not inside a non-yieldable C function. + + + + +

    +


    coroutine.resume (co [, val1, ···])

    + + +

    +Starts or continues the execution of coroutine co. +The first time you resume a coroutine, +it starts running its body. +The values val1, ... are passed +as the arguments to the body function. +If the coroutine has yielded, +resume restarts it; +the values val1, ... are passed +as the results from the yield. + + +

    +If the coroutine runs without any errors, +resume returns true plus any values passed to yield +(when the coroutine yields) or any values returned by the body function +(when the coroutine terminates). +If there is any error, +resume returns false plus the error message. + + + + +

    +


    coroutine.running ()

    + + +

    +Returns the running coroutine plus a boolean, +true when the running coroutine is the main one. + + + + +

    +


    coroutine.status (co)

    + + +

    +Returns the status of the coroutine co, as a string: +"running", +if the coroutine is running +(that is, it is the one that called status); +"suspended", if the coroutine is suspended in a call to yield, +or if it has not started running yet; +"normal" if the coroutine is active but not running +(that is, it has resumed another coroutine); +and "dead" if the coroutine has finished its body function, +or if it has stopped with an error. + + + + +

    +


    coroutine.wrap (f)

    + + +

    +Creates a new coroutine, with body f; +f must be a function. +Returns a function that resumes the coroutine each time it is called. +Any arguments passed to this function behave as the +extra arguments to resume. +The function returns the same values returned by resume, +except the first boolean. +In case of error, +the function closes the coroutine and propagates the error. + + + + +

    +


    coroutine.yield (···)

    + + +

    +Suspends the execution of the calling coroutine. +Any arguments to yield are passed as extra results to resume. + + + + + + + +

    6.3 – Modules

    + +

    +The package library provides basic +facilities for loading modules in Lua. +It exports one function directly in the global environment: +require. +Everything else is exported in the table package. + + +

    +


    require (modname)

    + + +

    +Loads the given module. +The function starts by looking into the package.loaded table +to determine whether modname is already loaded. +If it is, then require returns the value stored +at package.loaded[modname]. +(The absence of a second result in this case +signals that this call did not have to load the module.) +Otherwise, it tries to find a loader for the module. + + +

    +To find a loader, +require is guided by the table package.searchers. +Each item in this table is a search function, +that searches for the module in a particular way. +By changing this table, +we can change how require looks for a module. +The following explanation is based on the default configuration +for package.searchers. + + +

    +First require queries package.preload[modname]. +If it has a value, +this value (which must be a function) is the loader. +Otherwise require searches for a Lua loader using the +path stored in package.path. +If that also fails, it searches for a C loader using the +path stored in package.cpath. +If that also fails, +it tries an all-in-one loader (see package.searchers). + + +

    +Once a loader is found, +require calls the loader with two arguments: +modname and an extra value, +a loader data, +also returned by the searcher. +The loader data can be any value useful to the module; +for the default searchers, +it indicates where the loader was found. +(For instance, if the loader came from a file, +this extra value is the file path.) +If the loader returns any non-nil value, +require assigns the returned value to package.loaded[modname]. +If the loader does not return a non-nil value and +has not assigned any value to package.loaded[modname], +then require assigns true to this entry. +In any case, require returns the +final value of package.loaded[modname]. +Besides that value, require also returns as a second result +the loader data returned by the searcher, +which indicates how require found the module. + + +

    +If there is any error loading or running the module, +or if it cannot find any loader for the module, +then require raises an error. + + + + +

    +


    package.config

    + + +

    +A string describing some compile-time configurations for packages. +This string is a sequence of lines: + +

      + +
    • The first line is the directory separator string. +Default is '\' for Windows and '/' for all other systems.
    • + +
    • The second line is the character that separates templates in a path. +Default is ';'.
    • + +
    • The third line is the string that marks the +substitution points in a template. +Default is '?'.
    • + +
    • The fourth line is a string that, in a path in Windows, +is replaced by the executable's directory. +Default is '!'.
    • + +
    • The fifth line is a mark to ignore all text after it +when building the luaopen_ function name. +Default is '-'.
    • + +
    + + + +

    +


    package.cpath

    + + +

    +A string with the path used by require +to search for a C loader. + + +

    +Lua initializes the C path package.cpath in the same way +it initializes the Lua path package.path, +using the environment variable LUA_CPATH_5_4, +or the environment variable LUA_CPATH, +or a default path defined in luaconf.h. + + + + +

    +


    package.loaded

    + + +

    +A table used by require to control which +modules are already loaded. +When you require a module modname and +package.loaded[modname] is not false, +require simply returns the value stored there. + + +

    +This variable is only a reference to the real table; +assignments to this variable do not change the +table used by require. +The real table is stored in the C registry (see §4.3), +indexed by the key LUA_LOADED_TABLE, a string. + + + + +

    +


    package.loadlib (libname, funcname)

    + + +

    +Dynamically links the host program with the C library libname. + + +

    +If funcname is "*", +then it only links with the library, +making the symbols exported by the library +available to other dynamically linked libraries. +Otherwise, +it looks for a function funcname inside the library +and returns this function as a C function. +So, funcname must follow the lua_CFunction prototype +(see lua_CFunction). + + +

    +This is a low-level function. +It completely bypasses the package and module system. +Unlike require, +it does not perform any path searching and +does not automatically adds extensions. +libname must be the complete file name of the C library, +including if necessary a path and an extension. +funcname must be the exact name exported by the C library +(which may depend on the C compiler and linker used). + + +

    +This functionality is not supported by ISO C. +As such, it is only available on some platforms +(Windows, Linux, Mac OS X, Solaris, BSD, +plus other Unix systems that support the dlfcn standard). + + +

    +This function is inherently insecure, +as it allows Lua to call any function in any readable dynamic +library in the system. +(Lua calls any function assuming the function +has a proper prototype and respects a proper protocol +(see lua_CFunction). +Therefore, +calling an arbitrary function in an arbitrary dynamic library +more often than not results in an access violation.) + + + + +

    +


    package.path

    + + +

    +A string with the path used by require +to search for a Lua loader. + + +

    +At start-up, Lua initializes this variable with +the value of the environment variable LUA_PATH_5_4 or +the environment variable LUA_PATH or +with a default path defined in luaconf.h, +if those environment variables are not defined. +A ";;" in the value of the environment variable +is replaced by the default path. + + + + +

    +


    package.preload

    + + +

    +A table to store loaders for specific modules +(see require). + + +

    +This variable is only a reference to the real table; +assignments to this variable do not change the +table used by require. +The real table is stored in the C registry (see §4.3), +indexed by the key LUA_PRELOAD_TABLE, a string. + + + + +

    +


    package.searchers

    + + +

    +A table used by require to control how to find modules. + + +

    +Each entry in this table is a searcher function. +When looking for a module, +require calls each of these searchers in ascending order, +with the module name (the argument given to require) as its +sole argument. +If the searcher finds the module, +it returns another function, the module loader, +plus an extra value, a loader data, +that will be passed to that loader and +returned as a second result by require. +If it cannot find the module, +it returns a string explaining why +(or nil if it has nothing to say). + + +

    +Lua initializes this table with four searcher functions. + + +

    +The first searcher simply looks for a loader in the +package.preload table. + + +

    +The second searcher looks for a loader as a Lua library, +using the path stored at package.path. +The search is done as described in function package.searchpath. + + +

    +The third searcher looks for a loader as a C library, +using the path given by the variable package.cpath. +Again, +the search is done as described in function package.searchpath. +For instance, +if the C path is the string + +

    +     "./?.so;./?.dll;/usr/local/?/init.so"
    +

    +the searcher for module foo +will try to open the files ./foo.so, ./foo.dll, +and /usr/local/foo/init.so, in that order. +Once it finds a C library, +this searcher first uses a dynamic link facility to link the +application with the library. +Then it tries to find a C function inside the library to +be used as the loader. +The name of this C function is the string "luaopen_" +concatenated with a copy of the module name where each dot +is replaced by an underscore. +Moreover, if the module name has a hyphen, +its suffix after (and including) the first hyphen is removed. +For instance, if the module name is a.b.c-v2.1, +the function name will be luaopen_a_b_c. + + +

    +The fourth searcher tries an all-in-one loader. +It searches the C path for a library for +the root name of the given module. +For instance, when requiring a.b.c, +it will search for a C library for a. +If found, it looks into it for an open function for +the submodule; +in our example, that would be luaopen_a_b_c. +With this facility, a package can pack several C submodules +into one single library, +with each submodule keeping its original open function. + + +

    +All searchers except the first one (preload) return as the extra value +the file path where the module was found, +as returned by package.searchpath. +The first searcher always returns the string ":preload:". + + +

    +Searchers should raise no errors and have no side effects in Lua. +(They may have side effects in C, +for instance by linking the application with a library.) + + + + +

    +


    package.searchpath (name, path [, sep [, rep]])

    + + +

    +Searches for the given name in the given path. + + +

    +A path is a string containing a sequence of +templates separated by semicolons. +For each template, +the function replaces each interrogation mark (if any) +in the template with a copy of name +wherein all occurrences of sep +(a dot, by default) +were replaced by rep +(the system's directory separator, by default), +and then tries to open the resulting file name. + + +

    +For instance, if the path is the string + +

    +     "./?.lua;./?.lc;/usr/local/?/init.lua"
    +

    +the search for the name foo.a +will try to open the files +./foo/a.lua, ./foo/a.lc, and +/usr/local/foo/a/init.lua, in that order. + + +

    +Returns the resulting name of the first file that it can +open in read mode (after closing the file), +or fail plus an error message if none succeeds. +(This error message lists all file names it tried to open.) + + + + + + + +

    6.4 – String Manipulation

    + + + +

    +This library provides generic functions for string manipulation, +such as finding and extracting substrings, and pattern matching. +When indexing a string in Lua, the first character is at position 1 +(not at 0, as in C). +Indices are allowed to be negative and are interpreted as indexing backwards, +from the end of the string. +Thus, the last character is at position -1, and so on. + + +

    +The string library provides all its functions inside the table +string. +It also sets a metatable for strings +where the __index field points to the string table. +Therefore, you can use the string functions in object-oriented style. +For instance, string.byte(s,i) +can be written as s:byte(i). + + +

    +The string library assumes one-byte character encodings. + + +

    +


    string.byte (s [, i [, j]])

    +Returns the internal numeric codes of the characters s[i], +s[i+1], ..., s[j]. +The default value for i is 1; +the default value for j is i. +These indices are corrected +following the same rules of function string.sub. + + +

    +Numeric codes are not necessarily portable across platforms. + + + + +

    +


    string.char (···)

    +Receives zero or more integers. +Returns a string with length equal to the number of arguments, +in which each character has the internal numeric code equal +to its corresponding argument. + + +

    +Numeric codes are not necessarily portable across platforms. + + + + +

    +


    string.dump (function [, strip])

    + + +

    +Returns a string containing a binary representation +(a binary chunk) +of the given function, +so that a later load on this string returns +a copy of the function (but with new upvalues). +If strip is a true value, +the binary representation may not include all debug information +about the function, +to save space. + + +

    +Functions with upvalues have only their number of upvalues saved. +When (re)loaded, +those upvalues receive fresh instances. +(See the load function for details about +how these upvalues are initialized. +You can use the debug library to serialize +and reload the upvalues of a function +in a way adequate to your needs.) + + + + +

    +


    string.find (s, pattern [, init [, plain]])

    + + +

    +Looks for the first match of +pattern (see §6.4.1) in the string s. +If it finds a match, then find returns the indices of s +where this occurrence starts and ends; +otherwise, it returns fail. +A third, optional numeric argument init specifies +where to start the search; +its default value is 1 and can be negative. +A true as a fourth, optional argument plain +turns off the pattern matching facilities, +so the function does a plain "find substring" operation, +with no characters in pattern being considered magic. + + +

    +If the pattern has captures, +then in a successful match +the captured values are also returned, +after the two indices. + + + + +

    +


    string.format (formatstring, ···)

    + + +

    +Returns a formatted version of its variable number of arguments +following the description given in its first argument, +which must be a string. +The format string follows the same rules as the ISO C function sprintf. +The only differences are that the conversion specifiers and modifiers +F, n, *, h, L, and l are not supported +and that there is an extra specifier, q. +Both width and precision, when present, +are limited to two digits. + + +

    +The specifier q formats booleans, nil, numbers, and strings +in a way that the result is a valid constant in Lua source code. +Booleans and nil are written in the obvious way +(true, false, nil). +Floats are written in hexadecimal, +to preserve full precision. +A string is written between double quotes, +using escape sequences when necessary to ensure that +it can safely be read back by the Lua interpreter. +For instance, the call + +

    +     string.format('%q', 'a string with "quotes" and \n new line')
    +

    +may produce the string: + +

    +     "a string with \"quotes\" and \
    +      new line"
    +

    +This specifier does not support modifiers (flags, width, precision). + + +

    +The conversion specifiers +A, a, E, e, f, +G, and g all expect a number as argument. +The specifiers c, d, +i, o, u, X, and x +expect an integer. +When Lua is compiled with a C89 compiler, +the specifiers A and a (hexadecimal floats) +do not support modifiers. + + +

    +The specifier s expects a string; +if its argument is not a string, +it is converted to one following the same rules of tostring. +If the specifier has any modifier, +the corresponding string argument should not contain embedded zeros. + + +

    +The specifier p formats the pointer +returned by lua_topointer. +That gives a unique string identifier for tables, userdata, +threads, strings, and functions. +For other values (numbers, nil, booleans), +this specifier results in a string representing +the pointer NULL. + + + + +

    +


    string.gmatch (s, pattern [, init])

    +Returns an iterator function that, +each time it is called, +returns the next captures from pattern (see §6.4.1) +over the string s. +If pattern specifies no captures, +then the whole match is produced in each call. +A third, optional numeric argument init specifies +where to start the search; +its default value is 1 and can be negative. + + +

    +As an example, the following loop +will iterate over all the words from string s, +printing one per line: + +

    +     s = "hello world from Lua"
    +     for w in string.gmatch(s, "%a+") do
    +       print(w)
    +     end
    +

    +The next example collects all pairs key=value from the +given string into a table: + +

    +     t = {}
    +     s = "from=world, to=Lua"
    +     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
    +       t[k] = v
    +     end
    +
    + +

    +For this function, a caret '^' at the start of a pattern does not +work as an anchor, as this would prevent the iteration. + + + + +

    +


    string.gsub (s, pattern, repl [, n])

    +Returns a copy of s +in which all (or the first n, if given) +occurrences of the pattern (see §6.4.1) have been +replaced by a replacement string specified by repl, +which can be a string, a table, or a function. +gsub also returns, as its second value, +the total number of matches that occurred. +The name gsub comes from Global SUBstitution. + + +

    +If repl is a string, then its value is used for replacement. +The character % works as an escape character: +any sequence in repl of the form %d, +with d between 1 and 9, +stands for the value of the d-th captured substring; +the sequence %0 stands for the whole match; +the sequence %% stands for a single %. + + +

    +If repl is a table, then the table is queried for every match, +using the first capture as the key. + + +

    +If repl is a function, then this function is called every time a +match occurs, with all captured substrings passed as arguments, +in order. + + +

    +In any case, +if the pattern specifies no captures, +then it behaves as if the whole pattern was inside a capture. + + +

    +If the value returned by the table query or by the function call +is a string or a number, +then it is used as the replacement string; +otherwise, if it is false or nil, +then there is no replacement +(that is, the original match is kept in the string). + + +

    +Here are some examples: + +

    +     x = string.gsub("hello world", "(%w+)", "%1 %1")
    +     --> x="hello hello world world"
    +     
    +     x = string.gsub("hello world", "%w+", "%0 %0", 1)
    +     --> x="hello hello world"
    +     
    +     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
    +     --> x="world hello Lua from"
    +     
    +     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
    +     --> x="home = /home/roberto, user = roberto"
    +     
    +     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
    +           return load(s)()
    +         end)
    +     --> x="4+5 = 9"
    +     
    +     local t = {name="lua", version="5.4"}
    +     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
    +     --> x="lua-5.4.tar.gz"
    +
    + + + +

    +


    string.len (s)

    + + +

    +Receives a string and returns its length. +The empty string "" has length 0. +Embedded zeros are counted, +so "a\000bc\000" has length 5. + + + + +

    +


    string.lower (s)

    + + +

    +Receives a string and returns a copy of this string with all +uppercase letters changed to lowercase. +All other characters are left unchanged. +The definition of what an uppercase letter is depends on the current locale. + + + + +

    +


    string.match (s, pattern [, init])

    + + +

    +Looks for the first match of +the pattern (see §6.4.1) in the string s. +If it finds one, then match returns +the captures from the pattern; +otherwise it returns fail. +If pattern specifies no captures, +then the whole match is returned. +A third, optional numeric argument init specifies +where to start the search; +its default value is 1 and can be negative. + + + + +

    +


    string.pack (fmt, v1, v2, ···)

    + + +

    +Returns a binary string containing the values v1, v2, etc. +serialized in binary form (packed) +according to the format string fmt (see §6.4.2). + + + + +

    +


    string.packsize (fmt)

    + + +

    +Returns the length of a string resulting from string.pack +with the given format. +The format string cannot have the variable-length options +'s' or 'z' (see §6.4.2). + + + + +

    +


    string.rep (s, n [, sep])

    + + +

    +Returns a string that is the concatenation of n copies of +the string s separated by the string sep. +The default value for sep is the empty string +(that is, no separator). +Returns the empty string if n is not positive. + + +

    +(Note that it is very easy to exhaust the memory of your machine +with a single call to this function.) + + + + +

    +


    string.reverse (s)

    + + +

    +Returns a string that is the string s reversed. + + + + +

    +


    string.sub (s, i [, j])

    + + +

    +Returns the substring of s that +starts at i and continues until j; +i and j can be negative. +If j is absent, then it is assumed to be equal to -1 +(which is the same as the string length). +In particular, +the call string.sub(s,1,j) returns a prefix of s +with length j, +and string.sub(s, -i) (for a positive i) +returns a suffix of s +with length i. + + +

    +If, after the translation of negative indices, +i is less than 1, +it is corrected to 1. +If j is greater than the string length, +it is corrected to that length. +If, after these corrections, +i is greater than j, +the function returns the empty string. + + + + +

    +


    string.unpack (fmt, s [, pos])

    + + +

    +Returns the values packed in string s (see string.pack) +according to the format string fmt (see §6.4.2). +An optional pos marks where +to start reading in s (default is 1). +After the read values, +this function also returns the index of the first unread byte in s. + + + + +

    +


    string.upper (s)

    + + +

    +Receives a string and returns a copy of this string with all +lowercase letters changed to uppercase. +All other characters are left unchanged. +The definition of what a lowercase letter is depends on the current locale. + + + + + + + +

    6.4.1 – Patterns

    + + + +

    +Patterns in Lua are described by regular strings, +which are interpreted as patterns by the pattern-matching functions +string.find, +string.gmatch, +string.gsub, +and string.match. +This section describes the syntax and the meaning +(that is, what they match) of these strings. + + + + + +

    Character Class:

    +A character class is used to represent a set of characters. +The following combinations are allowed in describing a character class: + +

      + +
    • x: +(where x is not one of the magic characters +^$()%.[]*+-?) +represents the character x itself. +
    • + +
    • .: (a dot) represents all characters.
    • + +
    • %a: represents all letters.
    • + +
    • %c: represents all control characters.
    • + +
    • %d: represents all digits.
    • + +
    • %g: represents all printable characters except space.
    • + +
    • %l: represents all lowercase letters.
    • + +
    • %p: represents all punctuation characters.
    • + +
    • %s: represents all space characters.
    • + +
    • %u: represents all uppercase letters.
    • + +
    • %w: represents all alphanumeric characters.
    • + +
    • %x: represents all hexadecimal digits.
    • + +
    • %x: (where x is any non-alphanumeric character) +represents the character x. +This is the standard way to escape the magic characters. +Any non-alphanumeric character +(including all punctuation characters, even the non-magical) +can be preceded by a '%' to represent itself in a pattern. +
    • + +
    • [set]: +represents the class which is the union of all +characters in set. +A range of characters can be specified by +separating the end characters of the range, +in ascending order, with a '-'. +All classes %x described above can also be used as +components in set. +All other characters in set represent themselves. +For example, [%w_] (or [_%w]) +represents all alphanumeric characters plus the underscore, +[0-7] represents the octal digits, +and [0-7%l%-] represents the octal digits plus +the lowercase letters plus the '-' character. + + +

      +You can put a closing square bracket in a set +by positioning it as the first character in the set. +You can put a hyphen in a set +by positioning it as the first or the last character in the set. +(You can also use an escape for both cases.) + + +

      +The interaction between ranges and classes is not defined. +Therefore, patterns like [%a-z] or [a-%%] +have no meaning. +

    • + +
    • [^set]: +represents the complement of set, +where set is interpreted as above. +
    • + +

    +For all classes represented by single letters (%a, %c, etc.), +the corresponding uppercase letter represents the complement of the class. +For instance, %S represents all non-space characters. + + +

    +The definitions of letter, space, and other character groups +depend on the current locale. +In particular, the class [a-z] may not be equivalent to %l. + + + + + +

    Pattern Item:

    +A pattern item can be + +

      + +
    • +a single character class, +which matches any single character in the class; +
    • + +
    • +a single character class followed by '*', +which matches sequences of zero or more characters in the class. +These repetition items will always match the longest possible sequence; +
    • + +
    • +a single character class followed by '+', +which matches sequences of one or more characters in the class. +These repetition items will always match the longest possible sequence; +
    • + +
    • +a single character class followed by '-', +which also matches sequences of zero or more characters in the class. +Unlike '*', +these repetition items will always match the shortest possible sequence; +
    • + +
    • +a single character class followed by '?', +which matches zero or one occurrence of a character in the class. +It always matches one occurrence if possible; +
    • + +
    • +%n, for n between 1 and 9; +such item matches a substring equal to the n-th captured string +(see below); +
    • + +
    • +%bxy, where x and y are two distinct characters; +such item matches strings that start with x, end with y, +and where the x and y are balanced. +This means that, if one reads the string from left to right, +counting +1 for an x and -1 for a y, +the ending y is the first y where the count reaches 0. +For instance, the item %b() matches expressions with +balanced parentheses. +
    • + +
    • +%f[set], a frontier pattern; +such item matches an empty string at any position such that +the next character belongs to set +and the previous character does not belong to set. +The set set is interpreted as previously described. +The beginning and the end of the subject are handled as if +they were the character '\0'. +
    • + +
    + + + + +

    Pattern:

    +A pattern is a sequence of pattern items. +A caret '^' at the beginning of a pattern anchors the match at the +beginning of the subject string. +A '$' at the end of a pattern anchors the match at the +end of the subject string. +At other positions, +'^' and '$' have no special meaning and represent themselves. + + + + + +

    Captures:

    +A pattern can contain sub-patterns enclosed in parentheses; +they describe captures. +When a match succeeds, the substrings of the subject string +that match captures are stored (captured) for future use. +Captures are numbered according to their left parentheses. +For instance, in the pattern "(a*(.)%w(%s*))", +the part of the string matching "a*(.)%w(%s*)" is +stored as the first capture, and therefore has number 1; +the character matching "." is captured with number 2, +and the part matching "%s*" has number 3. + + +

    +As a special case, the capture () captures +the current string position (a number). +For instance, if we apply the pattern "()aa()" on the +string "flaaap", there will be two captures: 3 and 5. + + + + + +

    Multiple matches:

    +The function string.gsub and the iterator string.gmatch +match multiple occurrences of the given pattern in the subject. +For these functions, +a new match is considered valid only +if it ends at least one byte after the end of the previous match. +In other words, the pattern machine never accepts the +empty string as a match immediately after another match. +As an example, +consider the results of the following code: + +

    +     > string.gsub("abc", "()a*()", print);
    +     --> 1   2
    +     --> 3   3
    +     --> 4   4
    +

    +The second and third results come from Lua matching an empty +string after 'b' and another one after 'c'. +Lua does not match an empty string after 'a', +because it would end at the same position of the previous match. + + + + + + + +

    6.4.2 – Format Strings for Pack and Unpack

    + +

    +The first argument to string.pack, +string.packsize, and string.unpack +is a format string, +which describes the layout of the structure being created or read. + + +

    +A format string is a sequence of conversion options. +The conversion options are as follows: + +

      +
    • <: sets little endian
    • +
    • >: sets big endian
    • +
    • =: sets native endian
    • +
    • ![n]: sets maximum alignment to n +(default is native alignment)
    • +
    • b: a signed byte (char)
    • +
    • B: an unsigned byte (char)
    • +
    • h: a signed short (native size)
    • +
    • H: an unsigned short (native size)
    • +
    • l: a signed long (native size)
    • +
    • L: an unsigned long (native size)
    • +
    • j: a lua_Integer
    • +
    • J: a lua_Unsigned
    • +
    • T: a size_t (native size)
    • +
    • i[n]: a signed int with n bytes +(default is native size)
    • +
    • I[n]: an unsigned int with n bytes +(default is native size)
    • +
    • f: a float (native size)
    • +
    • d: a double (native size)
    • +
    • n: a lua_Number
    • +
    • cn: a fixed-sized string with n bytes
    • +
    • z: a zero-terminated string
    • +
    • s[n]: a string preceded by its length +coded as an unsigned integer with n bytes +(default is a size_t)
    • +
    • x: one byte of padding
    • +
    • Xop: an empty item that aligns +according to option op +(which is otherwise ignored)
    • +
    • ' ': (space) ignored
    • +

    +(A "[n]" means an optional integral numeral.) +Except for padding, spaces, and configurations +(options "xX <=>!"), +each option corresponds to an argument in string.pack +or a result in string.unpack. + + +

    +For options "!n", "sn", "in", and "In", +n can be any integer between 1 and 16. +All integral options check overflows; +string.pack checks whether the given value fits in the given size; +string.unpack checks whether the read value fits in a Lua integer. +For the unsigned options, +Lua integers are treated as unsigned values too. + + +

    +Any format string starts as if prefixed by "!1=", +that is, +with maximum alignment of 1 (no alignment) +and native endianness. + + +

    +Native endianness assumes that the whole system is +either big or little endian. +The packing functions will not emulate correctly the behavior +of mixed-endian formats. + + +

    +Alignment works as follows: +For each option, +the format gets extra padding until the data starts +at an offset that is a multiple of the minimum between the +option size and the maximum alignment; +this minimum must be a power of 2. +Options "c" and "z" are not aligned; +option "s" follows the alignment of its starting integer. + + +

    +All padding is filled with zeros by string.pack +and ignored by string.unpack. + + + + + + + +

    6.5 – UTF-8 Support

    + +

    +This library provides basic support for UTF-8 encoding. +It provides all its functions inside the table utf8. +This library does not provide any support for Unicode other +than the handling of the encoding. +Any operation that needs the meaning of a character, +such as character classification, is outside its scope. + + +

    +Unless stated otherwise, +all functions that expect a byte position as a parameter +assume that the given position is either the start of a byte sequence +or one plus the length of the subject string. +As in the string library, +negative indices count from the end of the string. + + +

    +Functions that create byte sequences +accept all values up to 0x7FFFFFFF, +as defined in the original UTF-8 specification; +that implies byte sequences of up to six bytes. + + +

    +Functions that interpret byte sequences only accept +valid sequences (well formed and not overlong). +By default, they only accept byte sequences +that result in valid Unicode code points, +rejecting values greater than 10FFFF and surrogates. +A boolean argument lax, when available, +lifts these checks, +so that all values up to 0x7FFFFFFF are accepted. +(Not well formed and overlong sequences are still rejected.) + + +

    +


    utf8.char (···)

    + + +

    +Receives zero or more integers, +converts each one to its corresponding UTF-8 byte sequence +and returns a string with the concatenation of all these sequences. + + + + +

    +


    utf8.charpattern

    + + +

    +The pattern (a string, not a function) "[\0-\x7F\xC2-\xFD][\x80-\xBF]*" +(see §6.4.1), +which matches exactly one UTF-8 byte sequence, +assuming that the subject is a valid UTF-8 string. + + + + +

    +


    utf8.codes (s [, lax])

    + + +

    +Returns values so that the construction + +

    +     for p, c in utf8.codes(s) do body end
    +

    +will iterate over all UTF-8 characters in string s, +with p being the position (in bytes) and c the code point +of each character. +It raises an error if it meets any invalid byte sequence. + + + + +

    +


    utf8.codepoint (s [, i [, j [, lax]]])

    + + +

    +Returns the code points (as integers) from all characters in s +that start between byte position i and j (both included). +The default for i is 1 and for j is i. +It raises an error if it meets any invalid byte sequence. + + + + +

    +


    utf8.len (s [, i [, j [, lax]]])

    + + +

    +Returns the number of UTF-8 characters in string s +that start between positions i and j (both inclusive). +The default for i is 1 and for j is -1. +If it finds any invalid byte sequence, +returns fail plus the position of the first invalid byte. + + + + +

    +


    utf8.offset (s, n [, i])

    + + +

    +Returns the position (in bytes) where the encoding of the +n-th character of s +(counting from position i) starts. +A negative n gets characters before position i. +The default for i is 1 when n is non-negative +and #s + 1 otherwise, +so that utf8.offset(s, -n) gets the offset of the +n-th character from the end of the string. +If the specified character is neither in the subject +nor right after its end, +the function returns fail. + + +

    +As a special case, +when n is 0 the function returns the start of the encoding +of the character that contains the i-th byte of s. + + +

    +This function assumes that s is a valid UTF-8 string. + + + + + + + +

    6.6 – Table Manipulation

    + +

    +This library provides generic functions for table manipulation. +It provides all its functions inside the table table. + + +

    +Remember that, whenever an operation needs the length of a table, +all caveats about the length operator apply (see §3.4.7). +All functions ignore non-numeric keys +in the tables given as arguments. + + +

    +


    table.concat (list [, sep [, i [, j]]])

    + + +

    +Given a list where all elements are strings or numbers, +returns the string list[i]..sep..list[i+1] ··· sep..list[j]. +The default value for sep is the empty string, +the default for i is 1, +and the default for j is #list. +If i is greater than j, returns the empty string. + + + + +

    +


    table.insert (list, [pos,] value)

    + + +

    +Inserts element value at position pos in list, +shifting up the elements +list[pos], list[pos+1], ···, list[#list]. +The default value for pos is #list+1, +so that a call table.insert(t,x) inserts x at the end +of the list t. + + + + +

    +


    table.move (a1, f, e, t [,a2])

    + + +

    +Moves elements from the table a1 to the table a2, +performing the equivalent to the following +multiple assignment: +a2[t],··· = a1[f],···,a1[e]. +The default for a2 is a1. +The destination range can overlap with the source range. +The number of elements to be moved must fit in a Lua integer. + + +

    +Returns the destination table a2. + + + + +

    +


    table.pack (···)

    + + +

    +Returns a new table with all arguments stored into keys 1, 2, etc. +and with a field "n" with the total number of arguments. +Note that the resulting table may not be a sequence, +if some arguments are nil. + + + + +

    +


    table.remove (list [, pos])

    + + +

    +Removes from list the element at position pos, +returning the value of the removed element. +When pos is an integer between 1 and #list, +it shifts down the elements +list[pos+1], list[pos+2], ···, list[#list] +and erases element list[#list]; +The index pos can also be 0 when #list is 0, +or #list + 1. + + +

    +The default value for pos is #list, +so that a call table.remove(l) removes the last element +of the list l. + + + + +

    +


    table.sort (list [, comp])

    + + +

    +Sorts the list elements in a given order, in-place, +from list[1] to list[#list]. +If comp is given, +then it must be a function that receives two list elements +and returns true when the first element must come +before the second in the final order, +so that, after the sort, +i <= j implies not comp(list[j],list[i]). +If comp is not given, +then the standard Lua operator < is used instead. + + +

    +The comp function must define a consistent order; +more formally, the function must define a strict weak order. +(A weak order is similar to a total order, +but it can equate different elements for comparison purposes.) + + +

    +The sort algorithm is not stable: +Different elements considered equal by the given order +may have their relative positions changed by the sort. + + + + +

    +


    table.unpack (list [, i [, j]])

    + + +

    +Returns the elements from the given list. +This function is equivalent to + +

    +     return list[i], list[i+1], ···, list[j]
    +

    +By default, i is 1 and j is #list. + + + + + + + +

    6.7 – Mathematical Functions

    + +

    +This library provides basic mathematical functions. +It provides all its functions and constants inside the table math. +Functions with the annotation "integer/float" give +integer results for integer arguments +and float results for non-integer arguments. +The rounding functions +math.ceil, math.floor, and math.modf +return an integer when the result fits in the range of an integer, +or a float otherwise. + + +

    +


    math.abs (x)

    + + +

    +Returns the maximum value between x and -x. (integer/float) + + + + +

    +


    math.acos (x)

    + + +

    +Returns the arc cosine of x (in radians). + + + + +

    +


    math.asin (x)

    + + +

    +Returns the arc sine of x (in radians). + + + + +

    +


    math.atan (y [, x])

    + + +

    + +Returns the arc tangent of y/x (in radians), +using the signs of both arguments to find the +quadrant of the result. +It also handles correctly the case of x being zero. + + +

    +The default value for x is 1, +so that the call math.atan(y) +returns the arc tangent of y. + + + + +

    +


    math.ceil (x)

    + + +

    +Returns the smallest integral value greater than or equal to x. + + + + +

    +


    math.cos (x)

    + + +

    +Returns the cosine of x (assumed to be in radians). + + + + +

    +


    math.deg (x)

    + + +

    +Converts the angle x from radians to degrees. + + + + +

    +


    math.exp (x)

    + + +

    +Returns the value ex +(where e is the base of natural logarithms). + + + + +

    +


    math.floor (x)

    + + +

    +Returns the largest integral value less than or equal to x. + + + + +

    +


    math.fmod (x, y)

    + + +

    +Returns the remainder of the division of x by y +that rounds the quotient towards zero. (integer/float) + + + + +

    +


    math.huge

    + + +

    +The float value HUGE_VAL, +a value greater than any other numeric value. + + + + +

    +


    math.log (x [, base])

    + + +

    +Returns the logarithm of x in the given base. +The default for base is e +(so that the function returns the natural logarithm of x). + + + + +

    +


    math.max (x, ···)

    + + +

    +Returns the argument with the maximum value, +according to the Lua operator <. + + + + +

    +


    math.maxinteger

    +An integer with the maximum value for an integer. + + + + +

    +


    math.min (x, ···)

    + + +

    +Returns the argument with the minimum value, +according to the Lua operator <. + + + + +

    +


    math.mininteger

    +An integer with the minimum value for an integer. + + + + +

    +


    math.modf (x)

    + + +

    +Returns the integral part of x and the fractional part of x. +Its second result is always a float. + + + + +

    +


    math.pi

    + + +

    +The value of π. + + + + +

    +


    math.rad (x)

    + + +

    +Converts the angle x from degrees to radians. + + + + +

    +


    math.random ([m [, n]])

    + + +

    +When called without arguments, +returns a pseudo-random float with uniform distribution +in the range [0,1). +When called with two integers m and n, +math.random returns a pseudo-random integer +with uniform distribution in the range [m, n]. +The call math.random(n), for a positive n, +is equivalent to math.random(1,n). +The call math.random(0) produces an integer with +all bits (pseudo)random. + + +

    +This function uses the xoshiro256** algorithm to produce +pseudo-random 64-bit integers, +which are the results of calls with argument 0. +Other results (ranges and floats) +are unbiased extracted from these integers. + + +

    +Lua initializes its pseudo-random generator with the equivalent of +a call to math.randomseed with no arguments, +so that math.random should generate +different sequences of results each time the program runs. + + + + +

    +


    math.randomseed ([x [, y]])

    + + +

    +When called with at least one argument, +the integer parameters x and y are +joined into a 128-bit seed that +is used to reinitialize the pseudo-random generator; +equal seeds produce equal sequences of numbers. +The default for y is zero. + + +

    +When called with no arguments, +Lua generates a seed with +a weak attempt for randomness. + + +

    +This function returns the two seed components +that were effectively used, +so that setting them again repeats the sequence. + + +

    +To ensure a required level of randomness to the initial state +(or contrarily, to have a deterministic sequence, +for instance when debugging a program), +you should call math.randomseed with explicit arguments. + + + + +

    +


    math.sin (x)

    + + +

    +Returns the sine of x (assumed to be in radians). + + + + +

    +


    math.sqrt (x)

    + + +

    +Returns the square root of x. +(You can also use the expression x^0.5 to compute this value.) + + + + +

    +


    math.tan (x)

    + + +

    +Returns the tangent of x (assumed to be in radians). + + + + +

    +


    math.tointeger (x)

    + + +

    +If the value x is convertible to an integer, +returns that integer. +Otherwise, returns fail. + + + + +

    +


    math.type (x)

    + + +

    +Returns "integer" if x is an integer, +"float" if it is a float, +or fail if x is not a number. + + + + +

    +


    math.ult (m, n)

    + + +

    +Returns a boolean, +true if and only if integer m is below integer n when +they are compared as unsigned integers. + + + + + + + +

    6.8 – Input and Output Facilities

    + +

    +The I/O library provides two different styles for file manipulation. +The first one uses implicit file handles; +that is, there are operations to set a default input file and a +default output file, +and all input/output operations are done over these default files. +The second style uses explicit file handles. + + +

    +When using implicit file handles, +all operations are supplied by table io. +When using explicit file handles, +the operation io.open returns a file handle +and then all operations are supplied as methods of the file handle. + + +

    +The metatable for file handles provides metamethods +for __gc and __close that try +to close the file when called. + + +

    +The table io also provides +three predefined file handles with their usual meanings from C: +io.stdin, io.stdout, and io.stderr. +The I/O library never closes these files. + + +

    +Unless otherwise stated, +all I/O functions return fail on failure, +plus an error message as a second result and +a system-dependent error code as a third result, +and some non-false value on success. +On non-POSIX systems, +the computation of the error message and error code +in case of errors +may be not thread safe, +because they rely on the global C variable errno. + + +

    +


    io.close ([file])

    + + +

    +Equivalent to file:close(). +Without a file, closes the default output file. + + + + +

    +


    io.flush ()

    + + +

    +Equivalent to io.output():flush(). + + + + +

    +


    io.input ([file])

    + + +

    +When called with a file name, it opens the named file (in text mode), +and sets its handle as the default input file. +When called with a file handle, +it simply sets this file handle as the default input file. +When called without arguments, +it returns the current default input file. + + +

    +In case of errors this function raises the error, +instead of returning an error code. + + + + +

    +


    io.lines ([filename, ···])

    + + +

    +Opens the given file name in read mode +and returns an iterator function that +works like file:lines(···) over the opened file. +When the iterator function fails to read any value, +it automatically closes the file. +Besides the iterator function, +io.lines returns three other values: +two nil values as placeholders, +plus the created file handle. +Therefore, when used in a generic for loop, +the file is closed also if the loop is interrupted by an +error or a break. + + +

    +The call io.lines() (with no file name) is equivalent +to io.input():lines("l"); +that is, it iterates over the lines of the default input file. +In this case, the iterator does not close the file when the loop ends. + + +

    +In case of errors opening the file, +this function raises the error, +instead of returning an error code. + + + + +

    +


    io.open (filename [, mode])

    + + +

    +This function opens a file, +in the mode specified in the string mode. +In case of success, +it returns a new file handle. + + +

    +The mode string can be any of the following: + +

      +
    • "r": read mode (the default);
    • +
    • "w": write mode;
    • +
    • "a": append mode;
    • +
    • "r+": update mode, all previous data is preserved;
    • +
    • "w+": update mode, all previous data is erased;
    • +
    • "a+": append update mode, previous data is preserved, + writing is only allowed at the end of file.
    • +

    +The mode string can also have a 'b' at the end, +which is needed in some systems to open the file in binary mode. + + + + +

    +


    io.output ([file])

    + + +

    +Similar to io.input, but operates over the default output file. + + + + +

    +


    io.popen (prog [, mode])

    + + +

    +This function is system dependent and is not available +on all platforms. + + +

    +Starts the program prog in a separated process and returns +a file handle that you can use to read data from this program +(if mode is "r", the default) +or to write data to this program +(if mode is "w"). + + + + +

    +


    io.read (···)

    + + +

    +Equivalent to io.input():read(···). + + + + +

    +


    io.tmpfile ()

    + + +

    +In case of success, +returns a handle for a temporary file. +This file is opened in update mode +and it is automatically removed when the program ends. + + + + +

    +


    io.type (obj)

    + + +

    +Checks whether obj is a valid file handle. +Returns the string "file" if obj is an open file handle, +"closed file" if obj is a closed file handle, +or fail if obj is not a file handle. + + + + +

    +


    io.write (···)

    + + +

    +Equivalent to io.output():write(···). + + + + +

    +


    file:close ()

    + + +

    +Closes file. +Note that files are automatically closed when +their handles are garbage collected, +but that takes an unpredictable amount of time to happen. + + +

    +When closing a file handle created with io.popen, +file:close returns the same values +returned by os.execute. + + + + +

    +


    file:flush ()

    + + +

    +Saves any written data to file. + + + + +

    +


    file:lines (···)

    + + +

    +Returns an iterator function that, +each time it is called, +reads the file according to the given formats. +When no format is given, +uses "l" as a default. +As an example, the construction + +

    +     for c in file:lines(1) do body end
    +

    +will iterate over all characters of the file, +starting at the current position. +Unlike io.lines, this function does not close the file +when the loop ends. + + + + +

    +


    file:read (···)

    + + +

    +Reads the file file, +according to the given formats, which specify what to read. +For each format, +the function returns a string or a number with the characters read, +or fail if it cannot read data with the specified format. +(In this latter case, +the function does not read subsequent formats.) +When called without arguments, +it uses a default format that reads the next line +(see below). + + +

    +The available formats are + +

      + +
    • "n": +reads a numeral and returns it as a float or an integer, +following the lexical conventions of Lua. +(The numeral may have leading whitespaces and a sign.) +This format always reads the longest input sequence that +is a valid prefix for a numeral; +if that prefix does not form a valid numeral +(e.g., an empty string, "0x", or "3.4e-") +or it is too long (more than 200 characters), +it is discarded and the format returns fail. +
    • + +
    • "a": +reads the whole file, starting at the current position. +On end of file, it returns the empty string; +this format never fails. +
    • + +
    • "l": +reads the next line skipping the end of line, +returning fail on end of file. +This is the default format. +
    • + +
    • "L": +reads the next line keeping the end-of-line character (if present), +returning fail on end of file. +
    • + +
    • number: +reads a string with up to this number of bytes, +returning fail on end of file. +If number is zero, +it reads nothing and returns an empty string, +or fail on end of file. +
    • + +

    +The formats "l" and "L" should be used only for text files. + + + + +

    +


    file:seek ([whence [, offset]])

    + + +

    +Sets and gets the file position, +measured from the beginning of the file, +to the position given by offset plus a base +specified by the string whence, as follows: + +

      +
    • "set": base is position 0 (beginning of the file);
    • +
    • "cur": base is current position;
    • +
    • "end": base is end of file;
    • +

    +In case of success, seek returns the final file position, +measured in bytes from the beginning of the file. +If seek fails, it returns fail, +plus a string describing the error. + + +

    +The default value for whence is "cur", +and for offset is 0. +Therefore, the call file:seek() returns the current +file position, without changing it; +the call file:seek("set") sets the position to the +beginning of the file (and returns 0); +and the call file:seek("end") sets the position to the +end of the file, and returns its size. + + + + +

    +


    file:setvbuf (mode [, size])

    + + +

    +Sets the buffering mode for a file. +There are three available modes: + +

      +
    • "no": no buffering.
    • +
    • "full": full buffering.
    • +
    • "line": line buffering.
    • +
    + +

    +For the last two cases, +size is a hint for the size of the buffer, in bytes. +The default is an appropriate size. + + +

    +The specific behavior of each mode is non portable; +check the underlying ISO C function setvbuf in your platform for +more details. + + + + +

    +


    file:write (···)

    + + +

    +Writes the value of each of its arguments to file. +The arguments must be strings or numbers. + + +

    +In case of success, this function returns file. + + + + + + + +

    6.9 – Operating System Facilities

    + +

    +This library is implemented through table os. + + +

    +


    os.clock ()

    + + +

    +Returns an approximation of the amount in seconds of CPU time +used by the program, +as returned by the underlying ISO C function clock. + + + + +

    +


    os.date ([format [, time]])

    + + +

    +Returns a string or a table containing date and time, +formatted according to the given string format. + + +

    +If the time argument is present, +this is the time to be formatted +(see the os.time function for a description of this value). +Otherwise, date formats the current time. + + +

    +If format starts with '!', +then the date is formatted in Coordinated Universal Time. +After this optional character, +if format is the string "*t", +then date returns a table with the following fields: +year, month (1–12), day (1–31), +hour (0–23), min (0–59), +sec (0–61, due to leap seconds), +wday (weekday, 1–7, Sunday is 1), +yday (day of the year, 1–366), +and isdst (daylight saving flag, a boolean). +This last field may be absent +if the information is not available. + + +

    +If format is not "*t", +then date returns the date as a string, +formatted according to the same rules as the ISO C function strftime. + + +

    +If format is absent, it defaults to "%c", +which gives a human-readable date and time representation +using the current locale. + + +

    +On non-POSIX systems, +this function may be not thread safe +because of its reliance on C function gmtime and C function localtime. + + + + +

    +


    os.difftime (t2, t1)

    + + +

    +Returns the difference, in seconds, +from time t1 to time t2 +(where the times are values returned by os.time). +In POSIX, Windows, and some other systems, +this value is exactly t2-t1. + + + + +

    +


    os.execute ([command])

    + + +

    +This function is equivalent to the ISO C function system. +It passes command to be executed by an operating system shell. +Its first result is true +if the command terminated successfully, +or fail otherwise. +After this first result +the function returns a string plus a number, +as follows: + +

      + +
    • "exit": +the command terminated normally; +the following number is the exit status of the command. +
    • + +
    • "signal": +the command was terminated by a signal; +the following number is the signal that terminated the command. +
    • + +
    + +

    +When called without a command, +os.execute returns a boolean that is true if a shell is available. + + + + +

    +


    os.exit ([code [, close]])

    + + +

    +Calls the ISO C function exit to terminate the host program. +If code is true, +the returned status is EXIT_SUCCESS; +if code is false, +the returned status is EXIT_FAILURE; +if code is a number, +the returned status is this number. +The default value for code is true. + + +

    +If the optional second argument close is true, +the function closes the Lua state before exiting (see lua_close). + + + + +

    +


    os.getenv (varname)

    + + +

    +Returns the value of the process environment variable varname +or fail if the variable is not defined. + + + + +

    +


    os.remove (filename)

    + + +

    +Deletes the file (or empty directory, on POSIX systems) +with the given name. +If this function fails, it returns fail +plus a string describing the error and the error code. +Otherwise, it returns true. + + + + +

    +


    os.rename (oldname, newname)

    + + +

    +Renames the file or directory named oldname to newname. +If this function fails, it returns fail, +plus a string describing the error and the error code. +Otherwise, it returns true. + + + + +

    +


    os.setlocale (locale [, category])

    + + +

    +Sets the current locale of the program. +locale is a system-dependent string specifying a locale; +category is an optional string describing which category to change: +"all", "collate", "ctype", +"monetary", "numeric", or "time"; +the default category is "all". +The function returns the name of the new locale, +or fail if the request cannot be honored. + + +

    +If locale is the empty string, +the current locale is set to an implementation-defined native locale. +If locale is the string "C", +the current locale is set to the standard C locale. + + +

    +When called with nil as the first argument, +this function only returns the name of the current locale +for the given category. + + +

    +This function may be not thread safe +because of its reliance on C function setlocale. + + + + +

    +


    os.time ([table])

    + + +

    +Returns the current time when called without arguments, +or a time representing the local date and time specified by the given table. +This table must have fields year, month, and day, +and may have fields +hour (default is 12), +min (default is 0), +sec (default is 0), +and isdst (default is nil). +Other fields are ignored. +For a description of these fields, see the os.date function. + + +

    +When the function is called, +the values in these fields do not need to be inside their valid ranges. +For instance, if sec is -10, +it means 10 seconds before the time specified by the other fields; +if hour is 1000, +it means 1000 hours after the time specified by the other fields. + + +

    +The returned value is a number, whose meaning depends on your system. +In POSIX, Windows, and some other systems, +this number counts the number +of seconds since some given start time (the "epoch"). +In other systems, the meaning is not specified, +and the number returned by time can be used only as an argument to +os.date and os.difftime. + + +

    +When called with a table, +os.time also normalizes all the fields +documented in the os.date function, +so that they represent the same time as before the call +but with values inside their valid ranges. + + + + +

    +


    os.tmpname ()

    + + +

    +Returns a string with a file name that can +be used for a temporary file. +The file must be explicitly opened before its use +and explicitly removed when no longer needed. + + +

    +In POSIX systems, +this function also creates a file with that name, +to avoid security risks. +(Someone else might create the file with wrong permissions +in the time between getting the name and creating the file.) +You still have to open the file to use it +and to remove it (even if you do not use it). + + +

    +When possible, +you may prefer to use io.tmpfile, +which automatically removes the file when the program ends. + + + + + + + +

    6.10 – The Debug Library

    + +

    +This library provides +the functionality of the debug interface (§4.7) to Lua programs. +You should exert care when using this library. +Several of its functions +violate basic assumptions about Lua code +(e.g., that variables local to a function +cannot be accessed from outside; +that userdata metatables cannot be changed by Lua code; +that Lua programs do not crash) +and therefore can compromise otherwise secure code. +Moreover, some functions in this library may be slow. + + +

    +All functions in this library are provided +inside the debug table. +All functions that operate over a thread +have an optional first argument which is the +thread to operate over. +The default is always the current thread. + + +

    +


    debug.debug ()

    + + +

    +Enters an interactive mode with the user, +running each string that the user enters. +Using simple commands and other debug facilities, +the user can inspect global and local variables, +change their values, evaluate expressions, and so on. +A line containing only the word cont finishes this function, +so that the caller continues its execution. + + +

    +Note that commands for debug.debug are not lexically nested +within any function and so have no direct access to local variables. + + + + +

    +


    debug.gethook ([thread])

    + + +

    +Returns the current hook settings of the thread, as three values: +the current hook function, the current hook mask, +and the current hook count, +as set by the debug.sethook function. + + +

    +Returns fail if there is no active hook. + + + + +

    +


    debug.getinfo ([thread,] f [, what])

    + + +

    +Returns a table with information about a function. +You can give the function directly +or you can give a number as the value of f, +which means the function running at level f of the call stack +of the given thread: +level 0 is the current function (getinfo itself); +level 1 is the function that called getinfo +(except for tail calls, which do not count in the stack); +and so on. +If f is a number greater than the number of active functions, +then getinfo returns fail. + + +

    +The returned table can contain all the fields returned by lua_getinfo, +with the string what describing which fields to fill in. +The default for what is to get all information available, +except the table of valid lines. +If present, +the option 'f' +adds a field named func with the function itself. +If present, +the option 'L' +adds a field named activelines with the table of +valid lines. + + +

    +For instance, the expression debug.getinfo(1,"n").name returns +a name for the current function, +if a reasonable name can be found, +and the expression debug.getinfo(print) +returns a table with all available information +about the print function. + + + + +

    +


    debug.getlocal ([thread,] f, local)

    + + +

    +This function returns the name and the value of the local variable +with index local of the function at level f of the stack. +This function accesses not only explicit local variables, +but also parameters and temporary values. + + +

    +The first parameter or local variable has index 1, and so on, +following the order that they are declared in the code, +counting only the variables that are active +in the current scope of the function. +Compile-time constants may not appear in this listing, +if they were optimized away by the compiler. +Negative indices refer to vararg arguments; +-1 is the first vararg argument. +The function returns fail +if there is no variable with the given index, +and raises an error when called with a level out of range. +(You can call debug.getinfo to check whether the level is valid.) + + +

    +Variable names starting with '(' (open parenthesis) +represent variables with no known names +(internal variables such as loop control variables, +and variables from chunks saved without debug information). + + +

    +The parameter f may also be a function. +In that case, getlocal returns only the name of function parameters. + + + + +

    +


    debug.getmetatable (value)

    + + +

    +Returns the metatable of the given value +or nil if it does not have a metatable. + + + + +

    +


    debug.getregistry ()

    + + +

    +Returns the registry table (see §4.3). + + + + +

    +


    debug.getupvalue (f, up)

    + + +

    +This function returns the name and the value of the upvalue +with index up of the function f. +The function returns fail +if there is no upvalue with the given index. + + +

    +(For Lua functions, +upvalues are the external local variables that the function uses, +and that are consequently included in its closure.) + + +

    +For C functions, this function uses the empty string "" +as a name for all upvalues. + + +

    +Variable name '?' (interrogation mark) +represents variables with no known names +(variables from chunks saved without debug information). + + + + +

    +


    debug.getuservalue (u, n)

    + + +

    +Returns the n-th user value associated +to the userdata u plus a boolean, +false if the userdata does not have that value. + + + + +

    +


    debug.sethook ([thread,] hook, mask [, count])

    + + +

    +Sets the given function as the debug hook. +The string mask and the number count describe +when the hook will be called. +The string mask may have any combination of the following characters, +with the given meaning: + +

      +
    • 'c': the hook is called every time Lua calls a function;
    • +
    • 'r': the hook is called every time Lua returns from a function;
    • +
    • 'l': the hook is called every time Lua enters a new line of code.
    • +

    +Moreover, +with a count different from zero, +the hook is called also after every count instructions. + + +

    +When called without arguments, +debug.sethook turns off the hook. + + +

    +When the hook is called, its first parameter is a string +describing the event that has triggered its call: +"call", "tail call", "return", +"line", and "count". +For line events, +the hook also gets the new line number as its second parameter. +Inside a hook, +you can call getinfo with level 2 to get more information about +the running function. +(Level 0 is the getinfo function, +and level 1 is the hook function.) + + + + +

    +


    debug.setlocal ([thread,] level, local, value)

    + + +

    +This function assigns the value value to the local variable +with index local of the function at level level of the stack. +The function returns fail if there is no local +variable with the given index, +and raises an error when called with a level out of range. +(You can call getinfo to check whether the level is valid.) +Otherwise, it returns the name of the local variable. + + +

    +See debug.getlocal for more information about +variable indices and names. + + + + +

    +


    debug.setmetatable (value, table)

    + + +

    +Sets the metatable for the given value to the given table +(which can be nil). +Returns value. + + + + +

    +


    debug.setupvalue (f, up, value)

    + + +

    +This function assigns the value value to the upvalue +with index up of the function f. +The function returns fail if there is no upvalue +with the given index. +Otherwise, it returns the name of the upvalue. + + +

    +See debug.getupvalue for more information about upvalues. + + + + +

    +


    debug.setuservalue (udata, value, n)

    + + +

    +Sets the given value as +the n-th user value associated to the given udata. +udata must be a full userdata. + + +

    +Returns udata, +or fail if the userdata does not have that value. + + + + +

    +


    debug.traceback ([thread,] [message [, level]])

    + + +

    +If message is present but is neither a string nor nil, +this function returns message without further processing. +Otherwise, +it returns a string with a traceback of the call stack. +The optional message string is appended +at the beginning of the traceback. +An optional level number tells at which level +to start the traceback +(default is 1, the function calling traceback). + + + + +

    +


    debug.upvalueid (f, n)

    + + +

    +Returns a unique identifier (as a light userdata) +for the upvalue numbered n +from the given function. + + +

    +These unique identifiers allow a program to check whether different +closures share upvalues. +Lua closures that share an upvalue +(that is, that access a same external local variable) +will return identical ids for those upvalue indices. + + + + +

    +


    debug.upvaluejoin (f1, n1, f2, n2)

    + + +

    +Make the n1-th upvalue of the Lua closure f1 +refer to the n2-th upvalue of the Lua closure f2. + + + + + + + +

    7 – Lua Standalone

    + +

    +Although Lua has been designed as an extension language, +to be embedded in a host C program, +it is also frequently used as a standalone language. +An interpreter for Lua as a standalone language, +called simply lua, +is provided with the standard distribution. +The standalone interpreter includes +all standard libraries. +Its usage is: + +

    +     lua [options] [script [args]]
    +

    +The options are: + +

      +
    • -e stat: execute string stat;
    • +
    • -i: enter interactive mode after running script;
    • +
    • -l mod: "require" mod and assign the + result to global mod;
    • +
    • -l g=mod: "require" mod and assign the + result to global g;
    • +
    • -v: print version information;
    • +
    • -E: ignore environment variables;
    • +
    • -W: turn warnings on;
    • +
    • --: stop handling options;
    • +
    • -: execute stdin as a file and stop handling options.
    • +

    +(The form -l g=mod was introduced in release 5.4.4.) + + +

    +After handling its options, lua runs the given script. +When called without arguments, +lua behaves as lua -v -i +when the standard input (stdin) is a terminal, +and as lua - otherwise. + + +

    +When called without the option -E, +the interpreter checks for an environment variable LUA_INIT_5_4 +(or LUA_INIT if the versioned name is not defined) +before running any argument. +If the variable content has the format @filename, +then lua executes the file. +Otherwise, lua executes the string itself. + + +

    +When called with the option -E, +Lua does not consult any environment variables. +In particular, +the values of package.path and package.cpath +are set with the default paths defined in luaconf.h. + + +

    +The options -e, -l, and -W are handled in +the order they appear. +For instance, an invocation like + +

    +     $ lua -e 'a=1' -llib1 script.lua
    +

    +will first set a to 1, then require the library lib1, +and finally run the file script.lua with no arguments. +(Here $ is the shell prompt. Your prompt may be different.) + + +

    +Before running any code, +lua collects all command-line arguments +in a global table called arg. +The script name goes to index 0, +the first argument after the script name goes to index 1, +and so on. +Any arguments before the script name +(that is, the interpreter name plus its options) +go to negative indices. +For instance, in the call + +

    +     $ lua -la b.lua t1 t2
    +

    +the table is like this: + +

    +     arg = { [-2] = "lua", [-1] = "-la",
    +             [0] = "b.lua",
    +             [1] = "t1", [2] = "t2" }
    +

    +If there is no script in the call, +the interpreter name goes to index 0, +followed by the other arguments. +For instance, the call + +

    +     $ lua -e "print(arg[1])"
    +

    +will print "-e". +If there is a script, +the script is called with arguments +arg[1], ···, arg[#arg]. +Like all chunks in Lua, +the script is compiled as a variadic function. + + +

    +In interactive mode, +Lua repeatedly prompts and waits for a line. +After reading a line, +Lua first try to interpret the line as an expression. +If it succeeds, it prints its value. +Otherwise, it interprets the line as a statement. +If you write an incomplete statement, +the interpreter waits for its completion +by issuing a different prompt. + + +

    +If the global variable _PROMPT contains a string, +then its value is used as the prompt. +Similarly, if the global variable _PROMPT2 contains a string, +its value is used as the secondary prompt +(issued during incomplete statements). + + +

    +In case of unprotected errors in the script, +the interpreter reports the error to the standard error stream. +If the error object is not a string but +has a metamethod __tostring, +the interpreter calls this metamethod to produce the final message. +Otherwise, the interpreter converts the error object to a string +and adds a stack traceback to it. +When warnings are on, +they are simply printed in the standard error output. + + +

    +When finishing normally, +the interpreter closes its main Lua state +(see lua_close). +The script can avoid this step by +calling os.exit to terminate. + + +

    +To allow the use of Lua as a +script interpreter in Unix systems, +Lua skips the first line of a file chunk if it starts with #. +Therefore, Lua scripts can be made into executable programs +by using chmod +x and the #! form, +as in + +

    +     #!/usr/local/bin/lua
    +

    +Of course, +the location of the Lua interpreter may be different in your machine. +If lua is in your PATH, +then + +

    +     #!/usr/bin/env lua
    +

    +is a more portable solution. + + + +

    8 – Incompatibilities with the Previous Version

    + + + +

    +Here we list the incompatibilities that you may find when moving a program +from Lua 5.3 to Lua 5.4. + + +

    +You can avoid some incompatibilities by compiling Lua with +appropriate options (see file luaconf.h). +However, +all these compatibility options will be removed in the future. +More often than not, +compatibility issues arise when these compatibility options +are removed. +So, whenever you have the chance, +you should try to test your code with a version of Lua compiled +with all compatibility options turned off. +That will ease transitions to newer versions of Lua. + + +

    +Lua versions can always change the C API in ways that +do not imply source-code changes in a program, +such as the numeric values for constants +or the implementation of functions as macros. +Therefore, +you should never assume that binaries are compatible between +different Lua versions. +Always recompile clients of the Lua API when +using a new version. + + +

    +Similarly, Lua versions can always change the internal representation +of precompiled chunks; +precompiled chunks are not compatible between different Lua versions. + + +

    +The standard paths in the official distribution may +change between versions. + + + + + +

    8.1 – Incompatibilities in the Language

    +
      + +
    • +The coercion of strings to numbers in +arithmetic and bitwise operations +has been removed from the core language. +The string library does a similar job +for arithmetic (but not for bitwise) operations +using the string metamethods. +However, unlike in previous versions, +the new implementation preserves the implicit type of the numeral +in the string. +For instance, the result of "1" + "2" now is an integer, +not a float. +
    • + +
    • +Literal decimal integer constants that overflow are read as floats, +instead of wrapping around. +You can use hexadecimal notation for such constants if you +want the old behavior +(reading them as integers with wrap around). +
    • + +
    • +The use of the __lt metamethod to emulate __le +has been removed. +When needed, this metamethod must be explicitly defined. +
    • + +
    • +The semantics of the numerical for loop +over integers changed in some details. +In particular, the control variable never wraps around. +
    • + +
    • +A label for a goto cannot be declared where a label with the same +name is visible, even if this other label is declared in an enclosing +block. +
    • + +
    • +When finalizing an object, +Lua does not ignore __gc metamethods that are not functions. +Any value will be called, if present. +(Non-callable values will generate a warning, +like any other error when calling a finalizer.) +
    • + +
    + + + + +

    8.2 – Incompatibilities in the Libraries

    +
      + +
    • +The function print does not call tostring +to format its arguments; +instead, it has this functionality hardwired. +You should use __tostring to modify how values are printed. +
    • + +
    • +The pseudo-random number generator used by the function math.random +now starts with a somewhat random seed. +Moreover, it uses a different algorithm. +
    • + +
    • +By default, the decoding functions in the utf8 library +do not accept surrogates as valid code points. +An extra parameter in these functions makes them more permissive. +
    • + +
    • +The options "setpause" and "setstepmul" +of the function collectgarbage are deprecated. +You should use the new option "incremental" to set them. +
    • + +
    • +The function io.lines now returns four values, +instead of just one. +That can be a problem when it is used as the sole +argument to another function that has optional parameters, +such as in load(io.lines(filename, "L")). +To fix that issue, +you can wrap the call into parentheses, +to adjust its number of results to one. +
    • + +
    + + + + +

    8.3 – Incompatibilities in the API

    + + +
      + +
    • +Full userdata now has an arbitrary number of associated user values. +Therefore, the functions lua_newuserdata, +lua_setuservalue, and lua_getuservalue were +replaced by lua_newuserdatauv, +lua_setiuservalue, and lua_getiuservalue, +which have an extra argument. + + +

      +For compatibility, the old names still work as macros assuming +one single user value. +Note, however, that userdata with zero user values +are more efficient memory-wise. +

    • + +
    • +The function lua_resume has an extra parameter. +This out parameter returns the number of values on +the top of the stack that were yielded or returned by the coroutine. +(In previous versions, +those values were the entire stack.) +
    • + +
    • +The function lua_version returns the version number, +instead of an address of the version number. +The Lua core should work correctly with libraries using their +own static copies of the same core, +so there is no need to check whether they are using the same +address space. +
    • + +
    • +The constant LUA_ERRGCMM was removed. +Errors in finalizers are never propagated; +instead, they generate a warning. +
    • + +
    • +The options LUA_GCSETPAUSE and LUA_GCSETSTEPMUL +of the function lua_gc are deprecated. +You should use the new option LUA_GCINC to set them. +
    • + +
    + + + + +

    9 – The Complete Syntax of Lua

    + +

    +Here is the complete syntax of Lua in extended BNF. +As usual in extended BNF, +{A} means 0 or more As, +and [A] means an optional A. +(For operator precedences, see §3.4.8; +for a description of the terminals +Name, Numeral, +and LiteralString, see §3.1.) + + + + +

    +
    +	chunk ::= block
    +
    +	block ::= {stat} [retstat]
    +
    +	stat ::=  ‘;’ | 
    +		 varlist ‘=’ explist | 
    +		 functioncall | 
    +		 label | 
    +		 break | 
    +		 goto Name | 
    +		 do block end | 
    +		 while exp do block end | 
    +		 repeat block until exp | 
    +		 if exp then block {elseif exp then block} [else block] end | 
    +		 for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | 
    +		 for namelist in explist do block end | 
    +		 function funcname funcbody | 
    +		 local function Name funcbody | 
    +		 local attnamelist [‘=’ explist] 
    +
    +	attnamelist ::=  Name attrib {‘,’ Name attrib}
    +
    +	attrib ::= [‘<’ Name ‘>’]
    +
    +	retstat ::= return [explist] [‘;’]
    +
    +	label ::= ‘::’ Name ‘::’
    +
    +	funcname ::= Name {‘.’ Name} [‘:’ Name]
    +
    +	varlist ::= var {‘,’ var}
    +
    +	var ::=  Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name 
    +
    +	namelist ::= Name {‘,’ Name}
    +
    +	explist ::= exp {‘,’ exp}
    +
    +	exp ::=  nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | 
    +		 prefixexp | tableconstructor | exp binop exp | unop exp 
    +
    +	prefixexp ::= var | functioncall | ‘(’ exp ‘)’
    +
    +	functioncall ::=  prefixexp args | prefixexp ‘:’ Name args 
    +
    +	args ::=  ‘(’ [explist] ‘)’ | tableconstructor | LiteralString 
    +
    +	functiondef ::= function funcbody
    +
    +	funcbody ::= ‘(’ [parlist] ‘)’ block end
    +
    +	parlist ::= namelist [‘,’ ‘...’] | ‘...’
    +
    +	tableconstructor ::= ‘{’ [fieldlist] ‘}’
    +
    +	fieldlist ::= field {fieldsep field} [fieldsep]
    +
    +	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
    +
    +	fieldsep ::= ‘,’ | ‘;’
    +
    +	binop ::=  ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | 
    +		 ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | 
    +		 ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | 
    +		 and | or
    +
    +	unop ::= ‘-’ | not | ‘#’ | ‘~’
    +
    +
    + +

    + + + + + + + +

    + + + + diff --git a/src/libs/3rdparty/lua/doc/osi-certified-72x60.png b/src/libs/3rdparty/lua/doc/osi-certified-72x60.png new file mode 100644 index 0000000000000000000000000000000000000000..07df5f6ee7a7a8b2108025dcd815f73f145a83af GIT binary patch literal 3774 zcmeAS@N?(olHy`uVBq!ia0y~yVDMmIV6fp}VqjqKvdKQqz`(#>;_2(keu<5RUq>!F zDW#c#fv?EZ#WAE}&fBQUkSXEQ_P_s~rC+AOEuv8-cyJkmc!74*Q8AyMq$?^+f$m2y zo|$>XbHW^#W^a>a#>sEq?Ko-{=wIwteXe7fw4h6X=jw}0t|2}f#YH>>GkL4TIrdCnn%wFYk7Uix=3XZva#tg$ ze0xAg(hrjl4G$E07=tBl3T8g%n2@kZ=hs!s^~+S3dfKQY_c8Xa-JO5oiu{THn?5{? z?_F}y_{8DTJu{x4Q{KViDB!@5z`&z(_>$SNYq`c-zI<8fD;)E8vsh|wMQ*c)f|RpL zvfG)o?RCLF-pc>`{5|T*OKH<{NAI^jnLOj@jH3(;f14E;7+M6B7z7seOxbsELG_aV zQ}3_8SO2=1^|DwGr-X!dlI*T;XZPPNdYZU1zUhkg9pQ-wE=kNgY@j5dB$%6MwMtGp zwD$j=lFxlxt=;j*wP6@R3yg!?+`K?mpFAqzj0Hk(8AoTZeorv(YxsP8(qo;|Z|-jC zKmD+e?Z%2nGj3+x+ERZx_U_yZtOr@Qwe#MXWFL6q&jNcf`Tt7)yD!dY3KX&~ zd-r<()zB6dcEK7ZJoXqKLGI|zEYL>|KYCi9@&8Yd%-gMu8hGFCLbB7m4 zuReGvXpQ>{YeU8|nY(!#Bj;>;Y_qXe{rk+LYUdNmr&aAMZhf%x5)Y3=vi;8Yy}zWF zcl%lMp7%`JE`LvNcknA|+jlb~1f5u>JIFjKn94F;!Q#Bf5`*TQ>tfb-#@+w-ReJK( zCo)dzdz0!u&X+KEd!wE9a^f`ZLV@JOs#jIjx2h$$xjBC1+3?qwPyeXb;b4FC-9i@Q z8`gK6Lsw|+i`-N4E=XO#%GoFX%5*L7y~=w8*%PxO3Obx;+&YtMZqlf?Y0Hi9CUurz zk<#`1mi-BfoZfAxkZE(g)p*Y7gF4T4fBx}!hpM@Eon;dLY`IstRrc{OIp$4xAmFxj zyUqD6Hzg7IS@#|LqUA%lAo~;bKT~O7?p`x9@B3v%2>B%m*ZXQ zHL?sYN^OTTzD9u*pGh$lzB6%BNL$hl5&a-B%T04VH+fEzJI%3AQ1OUB&itk4IVYSu zYWU}jM>oR-V`rHK&v)InP(3Fg{K=K)XwL$NB2Vk~UmKrFrayN7syuPFfZ$<2hGR1h zv_xo>F)cAZvLr5O_f5XTJ2QD$+6!d$?aH?v$lA`AzGT_LXU7&xzhiu-e1vCOqGy-P zbIWs_6V3@t{>iqfcE-Y+4~>-1Y`B*gSAOf=o4?O4D~eY6*jn!Y-SBOJi_pV@BLYra zW@%t!Wc>g9)PDKD+e)e5-%b#bJfC}G3KxUHv9@dTUObSn>jxWAxwBIBxN7;;mj=!5 zCoUWI-gSzp6+UKapZBn^jw{1#_tx9X_~*PnU;4bS;ISLaqAJbb$){eHYpbu<)qb|0 zkL}Q(8%`6HBM;u3 z_S}dszhZOD;LjpKhnX7H?0a=A_wGM?`K+<3ooo1YTPGH0l}*x`cNf1i?Y_RND`u|q z3l&2q!JU!vpQ>5*`tD^(&roLZ{IW%&`A*ZM$CKH&>(83mwfkV&2L5sv!A7fhWoj&H zDa+EV*!kT)n+S-?Z2fq(_top%DHEOMC@Lhem7ABSA64P}dFbHVj}t#KzGK{bcCT|= zT9f-1ldnN%L+-WBb(;4fv-SCuz`a4K`gf;D7;WCTX6D9C{yz3f6GQWzZCzfS*`i+6 z$@*x^k}dDpn3L1z-8k0KedeuLsq5=$snJTQ6GK<6vMw!;vW{jvkhYzP;q<1mTmKGq z?(B-`&#^YTSQ?a^DeS$m`8u!SmDu(Dd>!*_Q@>r7oqj%AZ;{KhzWG1pCb>sgul=gp zyINGzQu21m-d)D2>Hlp1bLaMN+x70<#n0}H3j4qKAGH_RUy#ILa4-E&XTP6Ihx)3n zS1aSX9tiba*En|Ui`jR*d0S^3mV7ixPP2QCl;PIhp6^#EF$u;j+I}-4{?eCccea1a z|0%=J^tVaeFIJ;}!s)|LuYSE+zw_VpWqr&3O!~9Cw7i}(i9z6r_?NfeCU5?eeqGe; zmE23lh9{HL*4~`_CB`QEqruz@K}U^VCu`>}=9D{lW5zb=S>Lkf&JH%0|8br9ujBa~ zW9v<4k9|89`Z?_H>BjPD=OVp?T6#Cx3XA?csXo7F-t67ozk`k%h0l9^|J1s2ld=y- z|E#mR+tjHkxnJ_y+MnLc=cbCzSa5#TX0!NE_G0J%kLNPKj{B?5#CvAz#gr!#Qd}M! zVe@^ws&aKk+qoaUY32FfSvvm<^JQ`zOxEI;dcXemX1#=&`(Ha1KKy!U;?!ckrv;NO zC*SY7_4%ya-az{~Qr$Pxx7p|>`vtal3EW?(ad zLxyLrpSX}vP((zBVVKs`ix)4>oH_I6&6`}UP0Ls9TmJohH#es+V8RqM~)t?{dzV0c%Q7duWxC=VF`K5A{K^iIX8`@ z?5?ki-Cgl<(c(2%voyOFWm>7Ks_N_WC+BRwSz>k9xOYv|)>nJK-+R5DFX!l|PeoI` zmIi2?n`g_-AZ?a2;q=q+buob}L&Dd`u{L~teLX!ro!P<7?by4!yPuz*fB*h;g}Sn^ zt65)Lxy3VPg=vTc1_m-*xNspLBt%85d%8~KqlXVKUb(`;khF2frcIO1Ki~iF*K6bS zb14#O_x4ow_Vx-23MOsbv2^Lv&*$yg8PS2OM2oe--~MmO^K)~L9zE)|xbXVA z*y88sO5Z$D|5oMe+v~J2Kx?Y0sp-j+C-2w)uPrStjf#qLc6N@8jP&yA@>{;Up6C%36*a|c>B*E+r%tU}zg}Nc^J0d{?d|#Y_5W%T6BGUX_!yo% zeVTiFoA2tYbw3`qM{mz#ZO{&1cV?#X^D{Gz=huFl8MIP_gXOOQTi6-L>4|J|Jdx8_ z8CGANHFaueNJz=cOG{;~%NQDV@BY0h^>o>r8;X-pKG3wR`BC8G)05o2@8dCPK|#Tr zH*ac(tvPY}G;>2Mx44{bm5GVTmv3)xPuGi`Wt7V0IZ0Pnm#Oi=;(ohVuU{uiv?WS( zx+n>796EGpNzh8S#fqLmi!aL9*X>!fNXfvU;PbPyMLTQm?kfHL?QQkvv*zF5+)Or* zNINsbuwoi}hh-G|Zb$c{rnuu z%g2wWe|>dzA8M3xo>FB(_2uQ|N}GE(H>dm0wF(Un-(LPcZfTI_RIkU6AM?xEXiPtCY-D62)q5~O zLtA_E?Y9#rPW*8HcIgK>0S=b4XV3N(B_}Vwn4#hsq#$tQ7zh+u$ZU-0F)S-7=?Kuc zl3~)9`O4gMM}whQr;FO;%u7o=i+0**X>ln&dG+el!-7?-SIcI7e|J~9##KtgcaBBj z|9^jX?%X+Zrv1_CLx36A( z+QDTX{Z0MOt-HI+&(F19el?4kiRsei%g)ZuvTv*Q?pv_n!MVBCCcdXrHi>G7v9Pi- zHh3-FRrWTjq~yz%%*(%e@9eMte`cn!iSP1d%hc4=lv=d3w79srTb&ZCs;WXlLUMC+ zv$J16Xb6mqjEsxhSNQnYrAwEN9C4ACpa1#!d39A)PnAixZbfa4+M95YY4_c_S64Kr zdWlL&?J9ceWo~ZHuww06U2W~zR;8=DySs1Z^mTVj&${8Qte-3Nhd-%4|I;O*-}`a=uu)|U|{fc^>bP0l+XkKXSYs} literal 0 HcmV?d00001 diff --git a/src/libs/3rdparty/lua/doc/readme.html b/src/libs/3rdparty/lua/doc/readme.html new file mode 100644 index 00000000000..918ec8ed937 --- /dev/null +++ b/src/libs/3rdparty/lua/doc/readme.html @@ -0,0 +1,337 @@ + + + +Lua 5.4 readme + + + + + + + +

    +Lua +Welcome to Lua 5.4 +

    + + + +

    About Lua

    +

    +Lua is a powerful, efficient, lightweight, embeddable scripting language +developed by a +team +at +PUC-Rio, +the Pontifical Catholic University of Rio de Janeiro in Brazil. +Lua is +free software +used in +many products and projects +around the world. + +

    +Lua's +official web site +provides complete information +about Lua, +including +an +executive summary +and +updated +documentation, +especially the +reference manual, +which may differ slightly from the +local copy +distributed in this package. + +

    Installing Lua

    +

    +Lua is distributed in +source +form. +You need to build it before using it. +Building Lua should be straightforward +because +Lua is implemented in pure ANSI C and compiles unmodified in all known +platforms that have an ANSI C compiler. +Lua also compiles unmodified as C++. +The instructions given below for building Lua are for Unix-like platforms, +such as Linux and Mac OS X. +See also +instructions for other systems +and +customization options. + +

    +If you don't have the time or the inclination to compile Lua yourself, +get a binary from +LuaBinaries. + +

    Building Lua

    +

    +In most common Unix-like platforms, simply do "make". +Here are the details. + +

      +
    1. +Open a terminal window and move to +the top-level directory, which is named lua-5.4.6. +The Makefile there controls both the build process and the installation process. +

      +

    2. + Do "make". The Makefile will guess your platform and build Lua for it. +

      +

    3. + If the guess failed, do "make help" and see if your platform is listed. + The platforms currently supported are: +

      +

      + guess aix bsd c89 freebsd generic ios linux linux-readline macosx mingw posix solaris +

      +

      + If your platform is listed, just do "make xxx", where xxx + is your platform name. +

      + If your platform is not listed, try the closest one or posix, generic, + c89, in this order. +

      +

    4. +The compilation takes only a few moments +and produces three files in the src directory: +lua (the interpreter), +luac (the compiler), +and liblua.a (the library). +

      +

    5. + To check that Lua has been built correctly, do "make test" + after building Lua. This will run the interpreter and print its version. +
    +

    +If you're running Linux, try "make linux-readline" to build the interactive Lua interpreter with handy line-editing and history capabilities. +If you get compilation errors, +make sure you have installed the readline development package +(which is probably named libreadline-dev or readline-devel). +If you get link errors after that, +then try "make linux-readline MYLIBS=-ltermcap". + +

    Installing Lua

    +

    + Once you have built Lua, you may want to install it in an official + place in your system. In this case, do "make install". The official + place and the way to install files are defined in the Makefile. You'll + probably need the right permissions to install files, and so may need to do "sudo make install". + +

    + To build and install Lua in one step, do "make all install", + or "make xxx install", + where xxx is your platform name. + +

    + To install Lua locally after building it, do "make local". + This will create a directory install with subdirectories + bin, include, lib, man, share, + and install Lua as listed below. + + To install Lua locally, but in some other directory, do + "make install INSTALL_TOP=xxx", where xxx is your chosen directory. + The installation starts in the src and doc directories, + so take care if INSTALL_TOP is not an absolute path. + +

    +
    + bin: +
    + lua luac +
    + include: +
    + lua.h luaconf.h lualib.h lauxlib.h lua.hpp +
    + lib: +
    + liblua.a +
    + man/man1: +
    + lua.1 luac.1 +
    + +

    + These are the only directories you need for development. + If you only want to run Lua programs, + you only need the files in bin and man. + The files in include and lib are needed for + embedding Lua in C or C++ programs. + +

    Customization

    +

    + Three kinds of things can be customized by editing a file: +

      +
    • Where and how to install Lua — edit Makefile. +
    • How to build Lua — edit src/Makefile. +
    • Lua features — edit src/luaconf.h. +
    + +

    + You don't actually need to edit the Makefiles because you may set the + relevant variables in the command line when invoking make. + Nevertheless, it's probably best to edit and save the Makefiles to + record the changes you've made. + +

    + On the other hand, if you need to customize some Lua features, you'll need + to edit src/luaconf.h before building and installing Lua. + The edited file will be the one installed, and + it will be used by any Lua clients that you build, to ensure consistency. + Further customization is available to experts by editing the Lua sources. + +

    Building Lua on other systems

    +

    + If you're not using the usual Unix tools, then the instructions for + building Lua depend on the compiler you use. You'll need to create + projects (or whatever your compiler uses) for building the library, + the interpreter, and the compiler, as follows: + +

    +
    +library: +
    +lapi.c lcode.c lctype.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c ltm.c lundump.c lvm.c lzio.c +lauxlib.c lbaselib.c lcorolib.c ldblib.c liolib.c lmathlib.c loadlib.c loslib.c lstrlib.c ltablib.c lutf8lib.c linit.c +
    +interpreter: +
    + library, lua.c +
    +compiler: +
    + library, luac.c +
    + +

    + To use Lua as a library in your own programs, you'll need to know how to + create and use libraries with your compiler. Moreover, to dynamically load + C libraries for Lua, you'll need to know how to create dynamic libraries + and you'll need to make sure that the Lua API functions are accessible to + those dynamic libraries — but don't link the Lua library + into each dynamic library. For Unix, we recommend that the Lua library + be linked statically into the host program and its symbols exported for + dynamic linking; src/Makefile does this for the Lua interpreter. + For Windows, we recommend that the Lua library be a DLL. + In all cases, the compiler luac should be linked statically. + +

    + As mentioned above, you may edit src/luaconf.h to customize + some features before building Lua. + +

    Changes since Lua 5.3

    +

    +Here are the main changes introduced in Lua 5.4. +The +reference manual +lists the +incompatibilities that had to be introduced. + +

    Main changes

    +
      +
    • new generational mode for garbage collection +
    • to-be-closed variables +
    • const variables +
    • userdata can have multiple user values +
    • new implementation for math.random +
    • warning system +
    • debug information about function arguments and returns +
    • new semantics for the integer 'for' loop +
    • optional 'init' argument to 'string.gmatch' +
    • new functions 'lua_resetthread' and 'coroutine.close' +
    • string-to-number coercions moved to the string library +
    • allocation function allowed to fail when shrinking a memory block +
    • new format '%p' in 'string.format' +
    • utf8 library accepts codepoints up to 2^31 +
    + +

    License

    +

    + +[osi certified] + +Lua is free software distributed under the terms of the +MIT license +reproduced below; +it may be used for any purpose, including commercial purposes, +at absolutely no cost without having to ask us. + +The only requirement is that if you do use Lua, +then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation. + +For details, see +this. + +

    +Copyright © 1994–2023 Lua.org, PUC-Rio. + +

    +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +

    +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +

    +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +

    +

    + +

    + + + + diff --git a/src/libs/3rdparty/lua/src/lapi.c b/src/libs/3rdparty/lua/src/lapi.c new file mode 100644 index 00000000000..34e64af1428 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lapi.c @@ -0,0 +1,1463 @@ +/* +** $Id: lapi.c $ +** Lua API +** See Copyright Notice in lua.h +*/ + +#define lapi_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" + + + +const char lua_ident[] = + "$LuaVersion: " LUA_COPYRIGHT " $" + "$LuaAuthors: " LUA_AUTHORS " $"; + + + +/* +** Test for a valid index (one that is not the 'nilvalue'). +** '!ttisnil(o)' implies 'o != &G(L)->nilvalue', so it is not needed. +** However, it covers the most common cases in a faster way. +*/ +#define isvalid(L, o) (!ttisnil(o) || o != &G(L)->nilvalue) + + +/* test for pseudo index */ +#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) + +/* test for upvalue */ +#define isupvalue(i) ((i) < LUA_REGISTRYINDEX) + + +/* +** Convert an acceptable index to a pointer to its respective value. +** Non-valid indices return the special nil value 'G(L)->nilvalue'. +*/ +static TValue *index2value (lua_State *L, int idx) { + CallInfo *ci = L->ci; + if (idx > 0) { + StkId o = ci->func.p + idx; + api_check(L, idx <= ci->top.p - (ci->func.p + 1), "unacceptable index"); + if (o >= L->top.p) return &G(L)->nilvalue; + else return s2v(o); + } + else if (!ispseudo(idx)) { /* negative index */ + api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1), + "invalid index"); + return s2v(L->top.p + idx); + } + else if (idx == LUA_REGISTRYINDEX) + return &G(L)->l_registry; + else { /* upvalues */ + idx = LUA_REGISTRYINDEX - idx; + api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); + if (ttisCclosure(s2v(ci->func.p))) { /* C closure? */ + CClosure *func = clCvalue(s2v(ci->func.p)); + return (idx <= func->nupvalues) ? &func->upvalue[idx-1] + : &G(L)->nilvalue; + } + else { /* light C function or Lua function (through a hook)?) */ + api_check(L, ttislcf(s2v(ci->func.p)), "caller not a C function"); + return &G(L)->nilvalue; /* no upvalues */ + } + } +} + + + +/* +** Convert a valid actual index (not a pseudo-index) to its address. +*/ +l_sinline StkId index2stack (lua_State *L, int idx) { + CallInfo *ci = L->ci; + if (idx > 0) { + StkId o = ci->func.p + idx; + api_check(L, o < L->top.p, "invalid index"); + return o; + } + else { /* non-positive index */ + api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1), + "invalid index"); + api_check(L, !ispseudo(idx), "invalid index"); + return L->top.p + idx; + } +} + + +LUA_API int lua_checkstack (lua_State *L, int n) { + int res; + CallInfo *ci; + lua_lock(L); + ci = L->ci; + api_check(L, n >= 0, "negative 'n'"); + if (L->stack_last.p - L->top.p > n) /* stack large enough? */ + res = 1; /* yes; check is OK */ + else /* need to grow stack */ + res = luaD_growstack(L, n, 0); + if (res && ci->top.p < L->top.p + n) + ci->top.p = L->top.p + n; /* adjust frame top */ + lua_unlock(L); + return res; +} + + +LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { + int i; + if (from == to) return; + lua_lock(to); + api_checknelems(from, n); + api_check(from, G(from) == G(to), "moving among independent states"); + api_check(from, to->ci->top.p - to->top.p >= n, "stack overflow"); + from->top.p -= n; + for (i = 0; i < n; i++) { + setobjs2s(to, to->top.p, from->top.p + i); + to->top.p++; /* stack already checked by previous 'api_check' */ + } + lua_unlock(to); +} + + +LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { + lua_CFunction old; + lua_lock(L); + old = G(L)->panic; + G(L)->panic = panicf; + lua_unlock(L); + return old; +} + + +LUA_API lua_Number lua_version (lua_State *L) { + UNUSED(L); + return LUA_VERSION_NUM; +} + + + +/* +** basic stack manipulation +*/ + + +/* +** convert an acceptable stack index into an absolute index +*/ +LUA_API int lua_absindex (lua_State *L, int idx) { + return (idx > 0 || ispseudo(idx)) + ? idx + : cast_int(L->top.p - L->ci->func.p) + idx; +} + + +LUA_API int lua_gettop (lua_State *L) { + return cast_int(L->top.p - (L->ci->func.p + 1)); +} + + +LUA_API void lua_settop (lua_State *L, int idx) { + CallInfo *ci; + StkId func, newtop; + ptrdiff_t diff; /* difference for new top */ + lua_lock(L); + ci = L->ci; + func = ci->func.p; + if (idx >= 0) { + api_check(L, idx <= ci->top.p - (func + 1), "new top too large"); + diff = ((func + 1) + idx) - L->top.p; + for (; diff > 0; diff--) + setnilvalue(s2v(L->top.p++)); /* clear new slots */ + } + else { + api_check(L, -(idx+1) <= (L->top.p - (func + 1)), "invalid new top"); + diff = idx + 1; /* will "subtract" index (as it is negative) */ + } + api_check(L, L->tbclist.p < L->top.p, "previous pop of an unclosed slot"); + newtop = L->top.p + diff; + if (diff < 0 && L->tbclist.p >= newtop) { + lua_assert(hastocloseCfunc(ci->nresults)); + newtop = luaF_close(L, newtop, CLOSEKTOP, 0); + } + L->top.p = newtop; /* correct top only after closing any upvalue */ + lua_unlock(L); +} + + +LUA_API void lua_closeslot (lua_State *L, int idx) { + StkId level; + lua_lock(L); + level = index2stack(L, idx); + api_check(L, hastocloseCfunc(L->ci->nresults) && L->tbclist.p == level, + "no variable to close at given level"); + level = luaF_close(L, level, CLOSEKTOP, 0); + setnilvalue(s2v(level)); + lua_unlock(L); +} + + +/* +** Reverse the stack segment from 'from' to 'to' +** (auxiliary to 'lua_rotate') +** Note that we move(copy) only the value inside the stack. +** (We do not move additional fields that may exist.) +*/ +l_sinline void reverse (lua_State *L, StkId from, StkId to) { + for (; from < to; from++, to--) { + TValue temp; + setobj(L, &temp, s2v(from)); + setobjs2s(L, from, to); + setobj2s(L, to, &temp); + } +} + + +/* +** Let x = AB, where A is a prefix of length 'n'. Then, +** rotate x n == BA. But BA == (A^r . B^r)^r. +*/ +LUA_API void lua_rotate (lua_State *L, int idx, int n) { + StkId p, t, m; + lua_lock(L); + t = L->top.p - 1; /* end of stack segment being rotated */ + p = index2stack(L, idx); /* start of segment */ + api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'"); + m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */ + reverse(L, p, m); /* reverse the prefix with length 'n' */ + reverse(L, m + 1, t); /* reverse the suffix */ + reverse(L, p, t); /* reverse the entire segment */ + lua_unlock(L); +} + + +LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { + TValue *fr, *to; + lua_lock(L); + fr = index2value(L, fromidx); + to = index2value(L, toidx); + api_check(L, isvalid(L, to), "invalid index"); + setobj(L, to, fr); + if (isupvalue(toidx)) /* function upvalue? */ + luaC_barrier(L, clCvalue(s2v(L->ci->func.p)), fr); + /* LUA_REGISTRYINDEX does not need gc barrier + (collector revisits it before finishing collection) */ + lua_unlock(L); +} + + +LUA_API void lua_pushvalue (lua_State *L, int idx) { + lua_lock(L); + setobj2s(L, L->top.p, index2value(L, idx)); + api_incr_top(L); + lua_unlock(L); +} + + + +/* +** access functions (stack -> C) +*/ + + +LUA_API int lua_type (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return (isvalid(L, o) ? ttype(o) : LUA_TNONE); +} + + +LUA_API const char *lua_typename (lua_State *L, int t) { + UNUSED(L); + api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type"); + return ttypename(t); +} + + +LUA_API int lua_iscfunction (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return (ttislcf(o) || (ttisCclosure(o))); +} + + +LUA_API int lua_isinteger (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return ttisinteger(o); +} + + +LUA_API int lua_isnumber (lua_State *L, int idx) { + lua_Number n; + const TValue *o = index2value(L, idx); + return tonumber(o, &n); +} + + +LUA_API int lua_isstring (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return (ttisstring(o) || cvt2str(o)); +} + + +LUA_API int lua_isuserdata (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return (ttisfulluserdata(o) || ttislightuserdata(o)); +} + + +LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { + const TValue *o1 = index2value(L, index1); + const TValue *o2 = index2value(L, index2); + return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0; +} + + +LUA_API void lua_arith (lua_State *L, int op) { + lua_lock(L); + if (op != LUA_OPUNM && op != LUA_OPBNOT) + api_checknelems(L, 2); /* all other operations expect two operands */ + else { /* for unary operations, add fake 2nd operand */ + api_checknelems(L, 1); + setobjs2s(L, L->top.p, L->top.p - 1); + api_incr_top(L); + } + /* first operand at top - 2, second at top - 1; result go to top - 2 */ + luaO_arith(L, op, s2v(L->top.p - 2), s2v(L->top.p - 1), L->top.p - 2); + L->top.p--; /* remove second operand */ + lua_unlock(L); +} + + +LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { + const TValue *o1; + const TValue *o2; + int i = 0; + lua_lock(L); /* may call tag method */ + o1 = index2value(L, index1); + o2 = index2value(L, index2); + if (isvalid(L, o1) && isvalid(L, o2)) { + switch (op) { + case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break; + case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; + case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; + default: api_check(L, 0, "invalid option"); + } + } + lua_unlock(L); + return i; +} + + +LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) { + size_t sz = luaO_str2num(s, s2v(L->top.p)); + if (sz != 0) + api_incr_top(L); + return sz; +} + + +LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { + lua_Number n = 0; + const TValue *o = index2value(L, idx); + int isnum = tonumber(o, &n); + if (pisnum) + *pisnum = isnum; + return n; +} + + +LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) { + lua_Integer res = 0; + const TValue *o = index2value(L, idx); + int isnum = tointeger(o, &res); + if (pisnum) + *pisnum = isnum; + return res; +} + + +LUA_API int lua_toboolean (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return !l_isfalse(o); +} + + +LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { + TValue *o; + lua_lock(L); + o = index2value(L, idx); + if (!ttisstring(o)) { + if (!cvt2str(o)) { /* not convertible? */ + if (len != NULL) *len = 0; + lua_unlock(L); + return NULL; + } + luaO_tostring(L, o); + luaC_checkGC(L); + o = index2value(L, idx); /* previous call may reallocate the stack */ + } + if (len != NULL) + *len = vslen(o); + lua_unlock(L); + return svalue(o); +} + + +LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + switch (ttypetag(o)) { + case LUA_VSHRSTR: return tsvalue(o)->shrlen; + case LUA_VLNGSTR: return tsvalue(o)->u.lnglen; + case LUA_VUSERDATA: return uvalue(o)->len; + case LUA_VTABLE: return luaH_getn(hvalue(o)); + default: return 0; + } +} + + +LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + if (ttislcf(o)) return fvalue(o); + else if (ttisCclosure(o)) + return clCvalue(o)->f; + else return NULL; /* not a C function */ +} + + +l_sinline void *touserdata (const TValue *o) { + switch (ttype(o)) { + case LUA_TUSERDATA: return getudatamem(uvalue(o)); + case LUA_TLIGHTUSERDATA: return pvalue(o); + default: return NULL; + } +} + + +LUA_API void *lua_touserdata (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return touserdata(o); +} + + +LUA_API lua_State *lua_tothread (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + return (!ttisthread(o)) ? NULL : thvalue(o); +} + + +/* +** Returns a pointer to the internal representation of an object. +** Note that ANSI C does not allow the conversion of a pointer to +** function to a 'void*', so the conversion here goes through +** a 'size_t'. (As the returned pointer is only informative, this +** conversion should not be a problem.) +*/ +LUA_API const void *lua_topointer (lua_State *L, int idx) { + const TValue *o = index2value(L, idx); + switch (ttypetag(o)) { + case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o))); + case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA: + return touserdata(o); + default: { + if (iscollectable(o)) + return gcvalue(o); + else + return NULL; + } + } +} + + + +/* +** push functions (C -> stack) +*/ + + +LUA_API void lua_pushnil (lua_State *L) { + lua_lock(L); + setnilvalue(s2v(L->top.p)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { + lua_lock(L); + setfltvalue(s2v(L->top.p), n); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { + lua_lock(L); + setivalue(s2v(L->top.p), n); + api_incr_top(L); + lua_unlock(L); +} + + +/* +** Pushes on the stack a string with given length. Avoid using 's' when +** 'len' == 0 (as 's' can be NULL in that case), due to later use of +** 'memcmp' and 'memcpy'. +*/ +LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { + TString *ts; + lua_lock(L); + ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); + setsvalue2s(L, L->top.p, ts); + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return getstr(ts); +} + + +LUA_API const char *lua_pushstring (lua_State *L, const char *s) { + lua_lock(L); + if (s == NULL) + setnilvalue(s2v(L->top.p)); + else { + TString *ts; + ts = luaS_new(L, s); + setsvalue2s(L, L->top.p, ts); + s = getstr(ts); /* internal copy's address */ + } + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return s; +} + + +LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, + va_list argp) { + const char *ret; + lua_lock(L); + ret = luaO_pushvfstring(L, fmt, argp); + luaC_checkGC(L); + lua_unlock(L); + return ret; +} + + +LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { + const char *ret; + va_list argp; + lua_lock(L); + va_start(argp, fmt); + ret = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + luaC_checkGC(L); + lua_unlock(L); + return ret; +} + + +LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { + lua_lock(L); + if (n == 0) { + setfvalue(s2v(L->top.p), fn); + api_incr_top(L); + } + else { + CClosure *cl; + api_checknelems(L, n); + api_check(L, n <= MAXUPVAL, "upvalue index too large"); + cl = luaF_newCclosure(L, n); + cl->f = fn; + L->top.p -= n; + while (n--) { + setobj2n(L, &cl->upvalue[n], s2v(L->top.p + n)); + /* does not need barrier because closure is white */ + lua_assert(iswhite(cl)); + } + setclCvalue(L, s2v(L->top.p), cl); + api_incr_top(L); + luaC_checkGC(L); + } + lua_unlock(L); +} + + +LUA_API void lua_pushboolean (lua_State *L, int b) { + lua_lock(L); + if (b) + setbtvalue(s2v(L->top.p)); + else + setbfvalue(s2v(L->top.p)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { + lua_lock(L); + setpvalue(s2v(L->top.p), p); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API int lua_pushthread (lua_State *L) { + lua_lock(L); + setthvalue(L, s2v(L->top.p), L); + api_incr_top(L); + lua_unlock(L); + return (G(L)->mainthread == L); +} + + + +/* +** get functions (Lua -> stack) +*/ + + +l_sinline int auxgetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *slot; + TString *str = luaS_new(L, k); + if (luaV_fastget(L, t, str, slot, luaH_getstr)) { + setobj2s(L, L->top.p, slot); + api_incr_top(L); + } + else { + setsvalue2s(L, L->top.p, str); + api_incr_top(L); + luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, slot); + } + lua_unlock(L); + return ttype(s2v(L->top.p - 1)); +} + + +/* +** Get the global table in the registry. Since all predefined +** indices in the registry were inserted right when the registry +** was created and never removed, they must always be in the array +** part of the registry. +*/ +#define getGtable(L) \ + (&hvalue(&G(L)->l_registry)->array[LUA_RIDX_GLOBALS - 1]) + + +LUA_API int lua_getglobal (lua_State *L, const char *name) { + const TValue *G; + lua_lock(L); + G = getGtable(L); + return auxgetstr(L, G, name); +} + + +LUA_API int lua_gettable (lua_State *L, int idx) { + const TValue *slot; + TValue *t; + lua_lock(L); + t = index2value(L, idx); + if (luaV_fastget(L, t, s2v(L->top.p - 1), slot, luaH_get)) { + setobj2s(L, L->top.p - 1, slot); + } + else + luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, slot); + lua_unlock(L); + return ttype(s2v(L->top.p - 1)); +} + + +LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { + lua_lock(L); + return auxgetstr(L, index2value(L, idx), k); +} + + +LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { + TValue *t; + const TValue *slot; + lua_lock(L); + t = index2value(L, idx); + if (luaV_fastgeti(L, t, n, slot)) { + setobj2s(L, L->top.p, slot); + } + else { + TValue aux; + setivalue(&aux, n); + luaV_finishget(L, t, &aux, L->top.p, slot); + } + api_incr_top(L); + lua_unlock(L); + return ttype(s2v(L->top.p - 1)); +} + + +l_sinline int finishrawget (lua_State *L, const TValue *val) { + if (isempty(val)) /* avoid copying empty items to the stack */ + setnilvalue(s2v(L->top.p)); + else + setobj2s(L, L->top.p, val); + api_incr_top(L); + lua_unlock(L); + return ttype(s2v(L->top.p - 1)); +} + + +static Table *gettable (lua_State *L, int idx) { + TValue *t = index2value(L, idx); + api_check(L, ttistable(t), "table expected"); + return hvalue(t); +} + + +LUA_API int lua_rawget (lua_State *L, int idx) { + Table *t; + const TValue *val; + lua_lock(L); + api_checknelems(L, 1); + t = gettable(L, idx); + val = luaH_get(t, s2v(L->top.p - 1)); + L->top.p--; /* remove key */ + return finishrawget(L, val); +} + + +LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) { + Table *t; + lua_lock(L); + t = gettable(L, idx); + return finishrawget(L, luaH_getint(t, n)); +} + + +LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { + Table *t; + TValue k; + lua_lock(L); + t = gettable(L, idx); + setpvalue(&k, cast_voidp(p)); + return finishrawget(L, luaH_get(t, &k)); +} + + +LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { + Table *t; + lua_lock(L); + t = luaH_new(L); + sethvalue2s(L, L->top.p, t); + api_incr_top(L); + if (narray > 0 || nrec > 0) + luaH_resize(L, t, narray, nrec); + luaC_checkGC(L); + lua_unlock(L); +} + + +LUA_API int lua_getmetatable (lua_State *L, int objindex) { + const TValue *obj; + Table *mt; + int res = 0; + lua_lock(L); + obj = index2value(L, objindex); + switch (ttype(obj)) { + case LUA_TTABLE: + mt = hvalue(obj)->metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(obj)->metatable; + break; + default: + mt = G(L)->mt[ttype(obj)]; + break; + } + if (mt != NULL) { + sethvalue2s(L, L->top.p, mt); + api_incr_top(L); + res = 1; + } + lua_unlock(L); + return res; +} + + +LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) { + TValue *o; + int t; + lua_lock(L); + o = index2value(L, idx); + api_check(L, ttisfulluserdata(o), "full userdata expected"); + if (n <= 0 || n > uvalue(o)->nuvalue) { + setnilvalue(s2v(L->top.p)); + t = LUA_TNONE; + } + else { + setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv); + t = ttype(s2v(L->top.p)); + } + api_incr_top(L); + lua_unlock(L); + return t; +} + + +/* +** set functions (stack -> Lua) +*/ + +/* +** t[k] = value at the top of the stack (where 'k' is a string) +*/ +static void auxsetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *slot; + TString *str = luaS_new(L, k); + api_checknelems(L, 1); + if (luaV_fastget(L, t, str, slot, luaH_getstr)) { + luaV_finishfastset(L, t, slot, s2v(L->top.p - 1)); + L->top.p--; /* pop value */ + } + else { + setsvalue2s(L, L->top.p, str); /* push 'str' (to make it a TValue) */ + api_incr_top(L); + luaV_finishset(L, t, s2v(L->top.p - 1), s2v(L->top.p - 2), slot); + L->top.p -= 2; /* pop value and key */ + } + lua_unlock(L); /* lock done by caller */ +} + + +LUA_API void lua_setglobal (lua_State *L, const char *name) { + const TValue *G; + lua_lock(L); /* unlock done in 'auxsetstr' */ + G = getGtable(L); + auxsetstr(L, G, name); +} + + +LUA_API void lua_settable (lua_State *L, int idx) { + TValue *t; + const TValue *slot; + lua_lock(L); + api_checknelems(L, 2); + t = index2value(L, idx); + if (luaV_fastget(L, t, s2v(L->top.p - 2), slot, luaH_get)) { + luaV_finishfastset(L, t, slot, s2v(L->top.p - 1)); + } + else + luaV_finishset(L, t, s2v(L->top.p - 2), s2v(L->top.p - 1), slot); + L->top.p -= 2; /* pop index and value */ + lua_unlock(L); +} + + +LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { + lua_lock(L); /* unlock done in 'auxsetstr' */ + auxsetstr(L, index2value(L, idx), k); +} + + +LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { + TValue *t; + const TValue *slot; + lua_lock(L); + api_checknelems(L, 1); + t = index2value(L, idx); + if (luaV_fastgeti(L, t, n, slot)) { + luaV_finishfastset(L, t, slot, s2v(L->top.p - 1)); + } + else { + TValue aux; + setivalue(&aux, n); + luaV_finishset(L, t, &aux, s2v(L->top.p - 1), slot); + } + L->top.p--; /* pop value */ + lua_unlock(L); +} + + +static void aux_rawset (lua_State *L, int idx, TValue *key, int n) { + Table *t; + lua_lock(L); + api_checknelems(L, n); + t = gettable(L, idx); + luaH_set(L, t, key, s2v(L->top.p - 1)); + invalidateTMcache(t); + luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1)); + L->top.p -= n; + lua_unlock(L); +} + + +LUA_API void lua_rawset (lua_State *L, int idx) { + aux_rawset(L, idx, s2v(L->top.p - 2), 2); +} + + +LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { + TValue k; + setpvalue(&k, cast_voidp(p)); + aux_rawset(L, idx, &k, 1); +} + + +LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { + Table *t; + lua_lock(L); + api_checknelems(L, 1); + t = gettable(L, idx); + luaH_setint(L, t, n, s2v(L->top.p - 1)); + luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1)); + L->top.p--; + lua_unlock(L); +} + + +LUA_API int lua_setmetatable (lua_State *L, int objindex) { + TValue *obj; + Table *mt; + lua_lock(L); + api_checknelems(L, 1); + obj = index2value(L, objindex); + if (ttisnil(s2v(L->top.p - 1))) + mt = NULL; + else { + api_check(L, ttistable(s2v(L->top.p - 1)), "table expected"); + mt = hvalue(s2v(L->top.p - 1)); + } + switch (ttype(obj)) { + case LUA_TTABLE: { + hvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrier(L, gcvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + case LUA_TUSERDATA: { + uvalue(obj)->metatable = mt; + if (mt) { + luaC_objbarrier(L, uvalue(obj), mt); + luaC_checkfinalizer(L, gcvalue(obj), mt); + } + break; + } + default: { + G(L)->mt[ttype(obj)] = mt; + break; + } + } + L->top.p--; + lua_unlock(L); + return 1; +} + + +LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) { + TValue *o; + int res; + lua_lock(L); + api_checknelems(L, 1); + o = index2value(L, idx); + api_check(L, ttisfulluserdata(o), "full userdata expected"); + if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue))) + res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */ + else { + setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top.p - 1)); + luaC_barrierback(L, gcvalue(o), s2v(L->top.p - 1)); + res = 1; + } + L->top.p--; + lua_unlock(L); + return res; +} + + +/* +** 'load' and 'call' functions (run Lua code) +*/ + + +#define checkresults(L,na,nr) \ + api_check(L, (nr) == LUA_MULTRET \ + || (L->ci->top.p - L->top.p >= (nr) - (na)), \ + "results from function overflow current stack size") + + +LUA_API void lua_callk (lua_State *L, int nargs, int nresults, + lua_KContext ctx, lua_KFunction k) { + StkId func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + func = L->top.p - (nargs+1); + if (k != NULL && yieldable(L)) { /* need to prepare continuation? */ + L->ci->u.c.k = k; /* save continuation */ + L->ci->u.c.ctx = ctx; /* save context */ + luaD_call(L, func, nresults); /* do the call */ + } + else /* no continuation or no yieldable */ + luaD_callnoyield(L, func, nresults); /* just do the call */ + adjustresults(L, nresults); + lua_unlock(L); +} + + + +/* +** Execute a protected call. +*/ +struct CallS { /* data to 'f_call' */ + StkId func; + int nresults; +}; + + +static void f_call (lua_State *L, void *ud) { + struct CallS *c = cast(struct CallS *, ud); + luaD_callnoyield(L, c->func, c->nresults); +} + + + +LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, + lua_KContext ctx, lua_KFunction k) { + struct CallS c; + int status; + ptrdiff_t func; + lua_lock(L); + api_check(L, k == NULL || !isLua(L->ci), + "cannot use continuations inside hooks"); + api_checknelems(L, nargs+1); + api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); + checkresults(L, nargs, nresults); + if (errfunc == 0) + func = 0; + else { + StkId o = index2stack(L, errfunc); + api_check(L, ttisfunction(s2v(o)), "error handler must be a function"); + func = savestack(L, o); + } + c.func = L->top.p - (nargs+1); /* function to be called */ + if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */ + c.nresults = nresults; /* do a 'conventional' protected call */ + status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); + } + else { /* prepare continuation (call is already protected by 'resume') */ + CallInfo *ci = L->ci; + ci->u.c.k = k; /* save continuation */ + ci->u.c.ctx = ctx; /* save context */ + /* save information for error recovery */ + ci->u2.funcidx = cast_int(savestack(L, c.func)); + ci->u.c.old_errfunc = L->errfunc; + L->errfunc = func; + setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */ + ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ + luaD_call(L, c.func, nresults); /* do the call */ + ci->callstatus &= ~CIST_YPCALL; + L->errfunc = ci->u.c.old_errfunc; + status = LUA_OK; /* if it is here, there were no errors */ + } + adjustresults(L, nresults); + lua_unlock(L); + return status; +} + + +LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, + const char *chunkname, const char *mode) { + ZIO z; + int status; + lua_lock(L); + if (!chunkname) chunkname = "?"; + luaZ_init(L, &z, reader, data); + status = luaD_protectedparser(L, &z, chunkname, mode); + if (status == LUA_OK) { /* no errors? */ + LClosure *f = clLvalue(s2v(L->top.p - 1)); /* get new function */ + if (f->nupvalues >= 1) { /* does it have an upvalue? */ + /* get global table from registry */ + const TValue *gt = getGtable(L); + /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ + setobj(L, f->upvals[0]->v.p, gt); + luaC_barrier(L, f->upvals[0], gt); + } + } + lua_unlock(L); + return status; +} + + +LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) { + int status; + TValue *o; + lua_lock(L); + api_checknelems(L, 1); + o = s2v(L->top.p - 1); + if (isLfunction(o)) + status = luaU_dump(L, getproto(o), writer, data, strip); + else + status = 1; + lua_unlock(L); + return status; +} + + +LUA_API int lua_status (lua_State *L) { + return L->status; +} + + +/* +** Garbage-collection function +*/ +LUA_API int lua_gc (lua_State *L, int what, ...) { + va_list argp; + int res = 0; + global_State *g = G(L); + if (g->gcstp & GCSTPGC) /* internal stop? */ + return -1; /* all options are invalid when stopped */ + lua_lock(L); + va_start(argp, what); + switch (what) { + case LUA_GCSTOP: { + g->gcstp = GCSTPUSR; /* stopped by the user */ + break; + } + case LUA_GCRESTART: { + luaE_setdebt(g, 0); + g->gcstp = 0; /* (GCSTPGC must be already zero here) */ + break; + } + case LUA_GCCOLLECT: { + luaC_fullgc(L, 0); + break; + } + case LUA_GCCOUNT: { + /* GC values are expressed in Kbytes: #bytes/2^10 */ + res = cast_int(gettotalbytes(g) >> 10); + break; + } + case LUA_GCCOUNTB: { + res = cast_int(gettotalbytes(g) & 0x3ff); + break; + } + case LUA_GCSTEP: { + int data = va_arg(argp, int); + l_mem debt = 1; /* =1 to signal that it did an actual step */ + lu_byte oldstp = g->gcstp; + g->gcstp = 0; /* allow GC to run (GCSTPGC must be zero here) */ + if (data == 0) { + luaE_setdebt(g, 0); /* do a basic step */ + luaC_step(L); + } + else { /* add 'data' to total debt */ + debt = cast(l_mem, data) * 1024 + g->GCdebt; + luaE_setdebt(g, debt); + luaC_checkGC(L); + } + g->gcstp = oldstp; /* restore previous state */ + if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */ + res = 1; /* signal it */ + break; + } + case LUA_GCSETPAUSE: { + int data = va_arg(argp, int); + res = getgcparam(g->gcpause); + setgcparam(g->gcpause, data); + break; + } + case LUA_GCSETSTEPMUL: { + int data = va_arg(argp, int); + res = getgcparam(g->gcstepmul); + setgcparam(g->gcstepmul, data); + break; + } + case LUA_GCISRUNNING: { + res = gcrunning(g); + break; + } + case LUA_GCGEN: { + int minormul = va_arg(argp, int); + int majormul = va_arg(argp, int); + res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC; + if (minormul != 0) + g->genminormul = minormul; + if (majormul != 0) + setgcparam(g->genmajormul, majormul); + luaC_changemode(L, KGC_GEN); + break; + } + case LUA_GCINC: { + int pause = va_arg(argp, int); + int stepmul = va_arg(argp, int); + int stepsize = va_arg(argp, int); + res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC; + if (pause != 0) + setgcparam(g->gcpause, pause); + if (stepmul != 0) + setgcparam(g->gcstepmul, stepmul); + if (stepsize != 0) + g->gcstepsize = stepsize; + luaC_changemode(L, KGC_INC); + break; + } + default: res = -1; /* invalid option */ + } + va_end(argp); + lua_unlock(L); + return res; +} + + + +/* +** miscellaneous functions +*/ + + +LUA_API int lua_error (lua_State *L) { + TValue *errobj; + lua_lock(L); + errobj = s2v(L->top.p - 1); + api_checknelems(L, 1); + /* error object is the memory error message? */ + if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg)) + luaM_error(L); /* raise a memory error */ + else + luaG_errormsg(L); /* raise a regular error */ + /* code unreachable; will unlock when control actually leaves the kernel */ + return 0; /* to avoid warnings */ +} + + +LUA_API int lua_next (lua_State *L, int idx) { + Table *t; + int more; + lua_lock(L); + api_checknelems(L, 1); + t = gettable(L, idx); + more = luaH_next(L, t, L->top.p - 1); + if (more) { + api_incr_top(L); + } + else /* no more elements */ + L->top.p -= 1; /* remove key */ + lua_unlock(L); + return more; +} + + +LUA_API void lua_toclose (lua_State *L, int idx) { + int nresults; + StkId o; + lua_lock(L); + o = index2stack(L, idx); + nresults = L->ci->nresults; + api_check(L, L->tbclist.p < o, "given index below or equal a marked one"); + luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */ + if (!hastocloseCfunc(nresults)) /* function not marked yet? */ + L->ci->nresults = codeNresults(nresults); /* mark it */ + lua_assert(hastocloseCfunc(L->ci->nresults)); + lua_unlock(L); +} + + +LUA_API void lua_concat (lua_State *L, int n) { + lua_lock(L); + api_checknelems(L, n); + if (n > 0) + luaV_concat(L, n); + else { /* nothing to concatenate */ + setsvalue2s(L, L->top.p, luaS_newlstr(L, "", 0)); /* push empty string */ + api_incr_top(L); + } + luaC_checkGC(L); + lua_unlock(L); +} + + +LUA_API void lua_len (lua_State *L, int idx) { + TValue *t; + lua_lock(L); + t = index2value(L, idx); + luaV_objlen(L, L->top.p, t); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { + lua_Alloc f; + lua_lock(L); + if (ud) *ud = G(L)->ud; + f = G(L)->frealloc; + lua_unlock(L); + return f; +} + + +LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { + lua_lock(L); + G(L)->ud = ud; + G(L)->frealloc = f; + lua_unlock(L); +} + + +void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) { + lua_lock(L); + G(L)->ud_warn = ud; + G(L)->warnf = f; + lua_unlock(L); +} + + +void lua_warning (lua_State *L, const char *msg, int tocont) { + lua_lock(L); + luaE_warning(L, msg, tocont); + lua_unlock(L); +} + + + +LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) { + Udata *u; + lua_lock(L); + api_check(L, 0 <= nuvalue && nuvalue < USHRT_MAX, "invalid value"); + u = luaS_newudata(L, size, nuvalue); + setuvalue(L, s2v(L->top.p), u); + api_incr_top(L); + luaC_checkGC(L); + lua_unlock(L); + return getudatamem(u); +} + + + +static const char *aux_upvalue (TValue *fi, int n, TValue **val, + GCObject **owner) { + switch (ttypetag(fi)) { + case LUA_VCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues))) + return NULL; /* 'n' not in [1, f->nupvalues] */ + *val = &f->upvalue[n-1]; + if (owner) *owner = obj2gco(f); + return ""; + } + case LUA_VLCL: { /* Lua closure */ + LClosure *f = clLvalue(fi); + TString *name; + Proto *p = f->p; + if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues))) + return NULL; /* 'n' not in [1, p->sizeupvalues] */ + *val = f->upvals[n-1]->v.p; + if (owner) *owner = obj2gco(f->upvals[n - 1]); + name = p->upvalues[n-1].name; + return (name == NULL) ? "(no name)" : getstr(name); + } + default: return NULL; /* not a closure */ + } +} + + +LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + lua_lock(L); + name = aux_upvalue(index2value(L, funcindex), n, &val, NULL); + if (name) { + setobj2s(L, L->top.p, val); + api_incr_top(L); + } + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val = NULL; /* to avoid warnings */ + GCObject *owner = NULL; /* to avoid warnings */ + TValue *fi; + lua_lock(L); + fi = index2value(L, funcindex); + api_checknelems(L, 1); + name = aux_upvalue(fi, n, &val, &owner); + if (name) { + L->top.p--; + setobj(L, val, s2v(L->top.p)); + luaC_barrier(L, owner, val); + } + lua_unlock(L); + return name; +} + + +static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { + static const UpVal *const nullup = NULL; + LClosure *f; + TValue *fi = index2value(L, fidx); + api_check(L, ttisLclosure(fi), "Lua function expected"); + f = clLvalue(fi); + if (pf) *pf = f; + if (1 <= n && n <= f->p->sizeupvalues) + return &f->upvals[n - 1]; /* get its upvalue pointer */ + else + return (UpVal**)&nullup; +} + + +LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { + TValue *fi = index2value(L, fidx); + switch (ttypetag(fi)) { + case LUA_VLCL: { /* lua closure */ + return *getupvalref(L, fidx, n, NULL); + } + case LUA_VCCL: { /* C closure */ + CClosure *f = clCvalue(fi); + if (1 <= n && n <= f->nupvalues) + return &f->upvalue[n - 1]; + /* else */ + } /* FALLTHROUGH */ + case LUA_VLCF: + return NULL; /* light C functions have no upvalues */ + default: { + api_check(L, 0, "function expected"); + return NULL; + } + } +} + + +LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, + int fidx2, int n2) { + LClosure *f1; + UpVal **up1 = getupvalref(L, fidx1, n1, &f1); + UpVal **up2 = getupvalref(L, fidx2, n2, NULL); + api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index"); + *up1 = *up2; + luaC_objbarrier(L, f1, *up1); +} + + diff --git a/src/libs/3rdparty/lua/src/lapi.h b/src/libs/3rdparty/lua/src/lapi.h new file mode 100644 index 00000000000..a742427cdc7 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lapi.h @@ -0,0 +1,52 @@ +/* +** $Id: lapi.h $ +** Auxiliary functions from Lua API +** See Copyright Notice in lua.h +*/ + +#ifndef lapi_h +#define lapi_h + + +#include "llimits.h" +#include "lstate.h" + + +/* Increments 'L->top.p', checking for stack overflows */ +#define api_incr_top(L) {L->top.p++; \ + api_check(L, L->top.p <= L->ci->top.p, \ + "stack overflow");} + + +/* +** If a call returns too many multiple returns, the callee may not have +** stack space to accommodate all results. In this case, this macro +** increases its stack space ('L->ci->top.p'). +*/ +#define adjustresults(L,nres) \ + { if ((nres) <= LUA_MULTRET && L->ci->top.p < L->top.p) \ + L->ci->top.p = L->top.p; } + + +/* Ensure the stack has at least 'n' elements */ +#define api_checknelems(L,n) \ + api_check(L, (n) < (L->top.p - L->ci->func.p), \ + "not enough elements in the stack") + + +/* +** To reduce the overhead of returning from C functions, the presence of +** to-be-closed variables in these functions is coded in the CallInfo's +** field 'nresults', in a way that functions with no to-be-closed variables +** with zero, one, or "all" wanted results have no overhead. Functions +** with other number of wanted results, as well as functions with +** variables to be closed, have an extra check. +*/ + +#define hastocloseCfunc(n) ((n) < LUA_MULTRET) + +/* Map [-1, inf) (range of 'nresults') into (-inf, -2] */ +#define codeNresults(n) (-(n) - 3) +#define decodeNresults(n) (-(n) - 3) + +#endif diff --git a/src/libs/3rdparty/lua/src/lauxlib.c b/src/libs/3rdparty/lua/src/lauxlib.c new file mode 100644 index 00000000000..4ca6c654889 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lauxlib.c @@ -0,0 +1,1112 @@ +/* +** $Id: lauxlib.c $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + +#define lauxlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include + + +/* +** This file uses only the official API of Lua. +** Any function declared here could be written as an application function. +*/ + +#include "lua.h" + +#include "lauxlib.h" + + +#if !defined(MAX_SIZET) +/* maximum value for size_t */ +#define MAX_SIZET ((size_t)(~(size_t)0)) +#endif + + +/* +** {====================================================== +** Traceback +** ======================================================= +*/ + + +#define LEVELS1 10 /* size of the first part of the stack */ +#define LEVELS2 11 /* size of the second part of the stack */ + + + +/* +** Search for 'objidx' in table at index -1. ('objidx' must be an +** absolute index.) Return 1 + string at top if it found a good name. +*/ +static int findfield (lua_State *L, int objidx, int level) { + if (level == 0 || !lua_istable(L, -1)) + return 0; /* not found */ + lua_pushnil(L); /* start 'next' loop */ + while (lua_next(L, -2)) { /* for each pair in table */ + if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ + if (lua_rawequal(L, objidx, -1)) { /* found object? */ + lua_pop(L, 1); /* remove value (but keep name) */ + return 1; + } + else if (findfield(L, objidx, level - 1)) { /* try recursively */ + /* stack: lib_name, lib_table, field_name (top) */ + lua_pushliteral(L, "."); /* place '.' between the two names */ + lua_replace(L, -3); /* (in the slot occupied by table) */ + lua_concat(L, 3); /* lib_name.field_name */ + return 1; + } + } + lua_pop(L, 1); /* remove value */ + } + return 0; /* not found */ +} + + +/* +** Search for a name for a function in all loaded modules +*/ +static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { + int top = lua_gettop(L); + lua_getinfo(L, "f", ar); /* push function */ + lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + if (findfield(L, top + 1, 2)) { + const char *name = lua_tostring(L, -1); + if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */ + lua_pushstring(L, name + 3); /* push name without prefix */ + lua_remove(L, -2); /* remove original name */ + } + lua_copy(L, -1, top + 1); /* copy name to proper place */ + lua_settop(L, top + 1); /* remove table "loaded" and name copy */ + return 1; + } + else { + lua_settop(L, top); /* remove function and global table */ + return 0; + } +} + + +static void pushfuncname (lua_State *L, lua_Debug *ar) { + if (pushglobalfuncname(L, ar)) { /* try first a global name */ + lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); + lua_remove(L, -2); /* remove name */ + } + else if (*ar->namewhat != '\0') /* is there a name from code? */ + lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ + else if (*ar->what == 'm') /* main? */ + lua_pushliteral(L, "main chunk"); + else if (*ar->what != 'C') /* for Lua functions, use */ + lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); + else /* nothing left... */ + lua_pushliteral(L, "?"); +} + + +static int lastlevel (lua_State *L) { + lua_Debug ar; + int li = 1, le = 1; + /* find an upper bound */ + while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } + /* do a binary search */ + while (li < le) { + int m = (li + le)/2; + if (lua_getstack(L, m, &ar)) li = m + 1; + else le = m; + } + return le - 1; +} + + +LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, + const char *msg, int level) { + luaL_Buffer b; + lua_Debug ar; + int last = lastlevel(L1); + int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; + luaL_buffinit(L, &b); + if (msg) { + luaL_addstring(&b, msg); + luaL_addchar(&b, '\n'); + } + luaL_addstring(&b, "stack traceback:"); + while (lua_getstack(L1, level++, &ar)) { + if (limit2show-- == 0) { /* too many levels? */ + int n = last - level - LEVELS2 + 1; /* number of levels to skip */ + lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n); + luaL_addvalue(&b); /* add warning about skip */ + level += n; /* and skip to last levels */ + } + else { + lua_getinfo(L1, "Slnt", &ar); + if (ar.currentline <= 0) + lua_pushfstring(L, "\n\t%s: in ", ar.short_src); + else + lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline); + luaL_addvalue(&b); + pushfuncname(L, &ar); + luaL_addvalue(&b); + if (ar.istailcall) + luaL_addstring(&b, "\n\t(...tail calls...)"); + } + } + luaL_pushresult(&b); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Error-report functions +** ======================================================= +*/ + +LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { + lua_Debug ar; + if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ + return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); + lua_getinfo(L, "n", &ar); + if (strcmp(ar.namewhat, "method") == 0) { + arg--; /* do not count 'self' */ + if (arg == 0) /* error is in the self argument itself? */ + return luaL_error(L, "calling '%s' on bad self (%s)", + ar.name, extramsg); + } + if (ar.name == NULL) + ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; + return luaL_error(L, "bad argument #%d to '%s' (%s)", + arg, ar.name, extramsg); +} + + +LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) { + const char *msg; + const char *typearg; /* name for the type of the actual argument */ + if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) + typearg = lua_tostring(L, -1); /* use the given type name */ + else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) + typearg = "light userdata"; /* special name for messages */ + else + typearg = luaL_typename(L, arg); /* standard name */ + msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); + return luaL_argerror(L, arg, msg); +} + + +static void tag_error (lua_State *L, int arg, int tag) { + luaL_typeerror(L, arg, lua_typename(L, tag)); +} + + +/* +** The use of 'lua_pushfstring' ensures this function does not +** need reserved stack space when called. +*/ +LUALIB_API void luaL_where (lua_State *L, int level) { + lua_Debug ar; + if (lua_getstack(L, level, &ar)) { /* check function at level */ + lua_getinfo(L, "Sl", &ar); /* get info about it */ + if (ar.currentline > 0) { /* is there info? */ + lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); + return; + } + } + lua_pushfstring(L, ""); /* else, no information available... */ +} + + +/* +** Again, the use of 'lua_pushvfstring' ensures this function does +** not need reserved stack space when called. (At worst, it generates +** an error with "stack overflow" instead of the given message.) +*/ +LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); + return lua_error(L); +} + + +LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { + int en = errno; /* calls to Lua API may change this value */ + if (stat) { + lua_pushboolean(L, 1); + return 1; + } + else { + luaL_pushfail(L); + if (fname) + lua_pushfstring(L, "%s: %s", fname, strerror(en)); + else + lua_pushstring(L, strerror(en)); + lua_pushinteger(L, en); + return 3; + } +} + + +#if !defined(l_inspectstat) /* { */ + +#if defined(LUA_USE_POSIX) + +#include + +/* +** use appropriate macros to interpret 'pclose' return status +*/ +#define l_inspectstat(stat,what) \ + if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ + else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } + +#else + +#define l_inspectstat(stat,what) /* no op */ + +#endif + +#endif /* } */ + + +LUALIB_API int luaL_execresult (lua_State *L, int stat) { + if (stat != 0 && errno != 0) /* error with an 'errno'? */ + return luaL_fileresult(L, 0, NULL); + else { + const char *what = "exit"; /* type of termination */ + l_inspectstat(stat, what); /* interpret result */ + if (*what == 'e' && stat == 0) /* successful termination? */ + lua_pushboolean(L, 1); + else + luaL_pushfail(L); + lua_pushstring(L, what); + lua_pushinteger(L, stat); + return 3; /* return true/fail,what,code */ + } +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Userdata's metatable manipulation +** ======================================================= +*/ + +LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { + if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + lua_createtable(L, 0, 2); /* create metatable */ + lua_pushstring(L, tname); + lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ + return 1; +} + + +LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { + luaL_getmetatable(L, tname); + lua_setmetatable(L, -2); +} + + +LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { + void *p = lua_touserdata(L, ud); + if (p != NULL) { /* value is a userdata? */ + if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ + luaL_getmetatable(L, tname); /* get correct metatable */ + if (!lua_rawequal(L, -1, -2)) /* not the same? */ + p = NULL; /* value is a userdata with wrong metatable */ + lua_pop(L, 2); /* remove both metatables */ + return p; + } + } + return NULL; /* value is not a userdata with a metatable */ +} + + +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = luaL_testudata(L, ud, tname); + luaL_argexpected(L, p != NULL, ud, tname); + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Argument check functions +** ======================================================= +*/ + +LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, + const char *const lst[]) { + const char *name = (def) ? luaL_optstring(L, arg, def) : + luaL_checkstring(L, arg); + int i; + for (i=0; lst[i]; i++) + if (strcmp(lst[i], name) == 0) + return i; + return luaL_argerror(L, arg, + lua_pushfstring(L, "invalid option '%s'", name)); +} + + +/* +** Ensures the stack has at least 'space' extra slots, raising an error +** if it cannot fulfill the request. (The error handling needs a few +** extra slots to format the error message. In case of an error without +** this extra space, Lua will generate the same 'stack overflow' error, +** but without 'msg'.) +*/ +LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { + if (l_unlikely(!lua_checkstack(L, space))) { + if (msg) + luaL_error(L, "stack overflow (%s)", msg); + else + luaL_error(L, "stack overflow"); + } +} + + +LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { + if (l_unlikely(lua_type(L, arg) != t)) + tag_error(L, arg, t); +} + + +LUALIB_API void luaL_checkany (lua_State *L, int arg) { + if (l_unlikely(lua_type(L, arg) == LUA_TNONE)) + luaL_argerror(L, arg, "value expected"); +} + + +LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { + const char *s = lua_tolstring(L, arg, len); + if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING); + return s; +} + + +LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, + const char *def, size_t *len) { + if (lua_isnoneornil(L, arg)) { + if (len) + *len = (def ? strlen(def) : 0); + return def; + } + else return luaL_checklstring(L, arg, len); +} + + +LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { + int isnum; + lua_Number d = lua_tonumberx(L, arg, &isnum); + if (l_unlikely(!isnum)) + tag_error(L, arg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { + return luaL_opt(L, luaL_checknumber, arg, def); +} + + +static void interror (lua_State *L, int arg) { + if (lua_isnumber(L, arg)) + luaL_argerror(L, arg, "number has no integer representation"); + else + tag_error(L, arg, LUA_TNUMBER); +} + + +LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { + int isnum; + lua_Integer d = lua_tointegerx(L, arg, &isnum); + if (l_unlikely(!isnum)) { + interror(L, arg); + } + return d; +} + + +LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, + lua_Integer def) { + return luaL_opt(L, luaL_checkinteger, arg, def); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +/* userdata to box arbitrary data */ +typedef struct UBox { + void *box; + size_t bsize; +} UBox; + + +static void *resizebox (lua_State *L, int idx, size_t newsize) { + void *ud; + lua_Alloc allocf = lua_getallocf(L, &ud); + UBox *box = (UBox *)lua_touserdata(L, idx); + void *temp = allocf(ud, box->box, box->bsize, newsize); + if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */ + lua_pushliteral(L, "not enough memory"); + lua_error(L); /* raise a memory error */ + } + box->box = temp; + box->bsize = newsize; + return temp; +} + + +static int boxgc (lua_State *L) { + resizebox(L, 1, 0); + return 0; +} + + +static const luaL_Reg boxmt[] = { /* box metamethods */ + {"__gc", boxgc}, + {"__close", boxgc}, + {NULL, NULL} +}; + + +static void newbox (lua_State *L) { + UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0); + box->box = NULL; + box->bsize = 0; + if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */ + luaL_setfuncs(L, boxmt, 0); /* set its metamethods */ + lua_setmetatable(L, -2); +} + + +/* +** check whether buffer is using a userdata on the stack as a temporary +** buffer +*/ +#define buffonstack(B) ((B)->b != (B)->init.b) + + +/* +** Whenever buffer is accessed, slot 'idx' must either be a box (which +** cannot be NULL) or it is a placeholder for the buffer. +*/ +#define checkbufferlevel(B,idx) \ + lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \ + : lua_touserdata(B->L, idx) == (void*)B) + + +/* +** Compute new size for buffer 'B', enough to accommodate extra 'sz' +** bytes. (The test for "not big enough" also gets the case when the +** computation of 'newsize' overflows.) +*/ +static size_t newbuffsize (luaL_Buffer *B, size_t sz) { + size_t newsize = (B->size / 2) * 3; /* buffer size * 1.5 */ + if (l_unlikely(MAX_SIZET - sz < B->n)) /* overflow in (B->n + sz)? */ + return luaL_error(B->L, "buffer too large"); + if (newsize < B->n + sz) /* not big enough? */ + newsize = B->n + sz; + return newsize; +} + + +/* +** Returns a pointer to a free area with at least 'sz' bytes in buffer +** 'B'. 'boxidx' is the relative position in the stack where is the +** buffer's box or its placeholder. +*/ +static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) { + checkbufferlevel(B, boxidx); + if (B->size - B->n >= sz) /* enough space? */ + return B->b + B->n; + else { + lua_State *L = B->L; + char *newbuff; + size_t newsize = newbuffsize(B, sz); + /* create larger buffer */ + if (buffonstack(B)) /* buffer already has a box? */ + newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */ + else { /* no box yet */ + lua_remove(L, boxidx); /* remove placeholder */ + newbox(L); /* create a new box */ + lua_insert(L, boxidx); /* move box to its intended position */ + lua_toclose(L, boxidx); + newbuff = (char *)resizebox(L, boxidx, newsize); + memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ + } + B->b = newbuff; + B->size = newsize; + return newbuff + B->n; + } +} + +/* +** returns a pointer to a free area with at least 'sz' bytes +*/ +LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { + return prepbuffsize(B, sz, -1); +} + + +LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { + if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ + char *b = prepbuffsize(B, l, -1); + memcpy(b, s, l * sizeof(char)); + luaL_addsize(B, l); + } +} + + +LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { + luaL_addlstring(B, s, strlen(s)); +} + + +LUALIB_API void luaL_pushresult (luaL_Buffer *B) { + lua_State *L = B->L; + checkbufferlevel(B, -1); + lua_pushlstring(L, B->b, B->n); + if (buffonstack(B)) + lua_closeslot(L, -2); /* close the box */ + lua_remove(L, -2); /* remove box or placeholder from the stack */ +} + + +LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { + luaL_addsize(B, sz); + luaL_pushresult(B); +} + + +/* +** 'luaL_addvalue' is the only function in the Buffer system where the +** box (if existent) is not on the top of the stack. So, instead of +** calling 'luaL_addlstring', it replicates the code using -2 as the +** last argument to 'prepbuffsize', signaling that the box is (or will +** be) below the string being added to the buffer. (Box creation can +** trigger an emergency GC, so we should not remove the string from the +** stack before we have the space guaranteed.) +*/ +LUALIB_API void luaL_addvalue (luaL_Buffer *B) { + lua_State *L = B->L; + size_t len; + const char *s = lua_tolstring(L, -1, &len); + char *b = prepbuffsize(B, len, -2); + memcpy(b, s, len * sizeof(char)); + luaL_addsize(B, len); + lua_pop(L, 1); /* pop string */ +} + + +LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { + B->L = L; + B->b = B->init.b; + B->n = 0; + B->size = LUAL_BUFFERSIZE; + lua_pushlightuserdata(L, (void*)B); /* push placeholder */ +} + + +LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { + luaL_buffinit(L, B); + return prepbuffsize(B, sz, -1); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Reference system +** ======================================================= +*/ + +/* index of free-list header (after the predefined values) */ +#define freelist (LUA_RIDX_LAST + 1) + +/* +** The previously freed references form a linked list: +** t[freelist] is the index of a first free index, or zero if list is +** empty; t[t[freelist]] is the index of the second element; etc. +*/ +LUALIB_API int luaL_ref (lua_State *L, int t) { + int ref; + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* remove from stack */ + return LUA_REFNIL; /* 'nil' has a unique fixed reference */ + } + t = lua_absindex(L, t); + if (lua_rawgeti(L, t, freelist) == LUA_TNIL) { /* first access? */ + ref = 0; /* list is empty */ + lua_pushinteger(L, 0); /* initialize as an empty list */ + lua_rawseti(L, t, freelist); /* ref = t[freelist] = 0 */ + } + else { /* already initialized */ + lua_assert(lua_isinteger(L, -1)); + ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ + } + lua_pop(L, 1); /* remove element from stack */ + if (ref != 0) { /* any free element? */ + lua_rawgeti(L, t, ref); /* remove it from list */ + lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ + } + else /* no free elements */ + ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ + lua_rawseti(L, t, ref); + return ref; +} + + +LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { + if (ref >= 0) { + t = lua_absindex(L, t); + lua_rawgeti(L, t, freelist); + lua_assert(lua_isinteger(L, -1)); + lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ + lua_pushinteger(L, ref); + lua_rawseti(L, t, freelist); /* t[freelist] = ref */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Load functions +** ======================================================= +*/ + +typedef struct LoadF { + int n; /* number of pre-read characters */ + FILE *f; /* file being read */ + char buff[BUFSIZ]; /* area for reading file */ +} LoadF; + + +static const char *getF (lua_State *L, void *ud, size_t *size) { + LoadF *lf = (LoadF *)ud; + (void)L; /* not used */ + if (lf->n > 0) { /* are there pre-read characters to be read? */ + *size = lf->n; /* return them (chars already in buffer) */ + lf->n = 0; /* no more pre-read characters */ + } + else { /* read a block from file */ + /* 'fread' can return > 0 *and* set the EOF flag. If next call to + 'getF' called 'fread', it might still wait for user input. + The next check avoids this problem. */ + if (feof(lf->f)) return NULL; + *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ + } + return lf->buff; +} + + +static int errfile (lua_State *L, const char *what, int fnameindex) { + const char *serr = strerror(errno); + const char *filename = lua_tostring(L, fnameindex) + 1; + lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); + lua_remove(L, fnameindex); + return LUA_ERRFILE; +} + + +/* +** Skip an optional BOM at the start of a stream. If there is an +** incomplete BOM (the first character is correct but the rest is +** not), returns the first character anyway to force an error +** (as no chunk can start with 0xEF). +*/ +static int skipBOM (FILE *f) { + int c = getc(f); /* read first character */ + if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */ + return getc(f); /* ignore BOM and return next char */ + else /* no (valid) BOM */ + return c; /* return first character */ +} + + +/* +** reads the first character of file 'f' and skips an optional BOM mark +** in its beginning plus its first line if it starts with '#'. Returns +** true if it skipped the first line. In any case, '*cp' has the +** first "valid" character of the file (after the optional BOM and +** a first-line comment). +*/ +static int skipcomment (FILE *f, int *cp) { + int c = *cp = skipBOM(f); + if (c == '#') { /* first line is a comment (Unix exec. file)? */ + do { /* skip first line */ + c = getc(f); + } while (c != EOF && c != '\n'); + *cp = getc(f); /* next character after comment, if present */ + return 1; /* there was a comment */ + } + else return 0; /* no comment */ +} + + +LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, + const char *mode) { + LoadF lf; + int status, readstatus; + int c; + int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ + if (filename == NULL) { + lua_pushliteral(L, "=stdin"); + lf.f = stdin; + } + else { + lua_pushfstring(L, "@%s", filename); + lf.f = fopen(filename, "r"); + if (lf.f == NULL) return errfile(L, "open", fnameindex); + } + lf.n = 0; + if (skipcomment(lf.f, &c)) /* read initial portion */ + lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */ + if (c == LUA_SIGNATURE[0]) { /* binary file? */ + lf.n = 0; /* remove possible newline */ + if (filename) { /* "real" file? */ + lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ + if (lf.f == NULL) return errfile(L, "reopen", fnameindex); + skipcomment(lf.f, &c); /* re-read initial portion */ + } + } + if (c != EOF) + lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ + status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); + readstatus = ferror(lf.f); + if (filename) fclose(lf.f); /* close file (even in case of errors) */ + if (readstatus) { + lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ + return errfile(L, "read", fnameindex); + } + lua_remove(L, fnameindex); + return status; +} + + +typedef struct LoadS { + const char *s; + size_t size; +} LoadS; + + +static const char *getS (lua_State *L, void *ud, size_t *size) { + LoadS *ls = (LoadS *)ud; + (void)L; /* not used */ + if (ls->size == 0) return NULL; + *size = ls->size; + ls->size = 0; + return ls->s; +} + + +LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, + const char *name, const char *mode) { + LoadS ls; + ls.s = buff; + ls.size = size; + return lua_load(L, getS, &ls, name, mode); +} + + +LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { + return luaL_loadbuffer(L, s, strlen(s), s); +} + +/* }====================================================== */ + + + +LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { + if (!lua_getmetatable(L, obj)) /* no metatable? */ + return LUA_TNIL; + else { + int tt; + lua_pushstring(L, event); + tt = lua_rawget(L, -2); + if (tt == LUA_TNIL) /* is metafield nil? */ + lua_pop(L, 2); /* remove metatable and metafield */ + else + lua_remove(L, -2); /* remove only metatable */ + return tt; /* return metafield type */ + } +} + + +LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { + obj = lua_absindex(L, obj); + if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ + return 0; + lua_pushvalue(L, obj); + lua_call(L, 1, 1); + return 1; +} + + +LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { + lua_Integer l; + int isnum; + lua_len(L, idx); + l = lua_tointegerx(L, -1, &isnum); + if (l_unlikely(!isnum)) + luaL_error(L, "object length is not an integer"); + lua_pop(L, 1); /* remove object */ + return l; +} + + +LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { + idx = lua_absindex(L,idx); + if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ + if (!lua_isstring(L, -1)) + luaL_error(L, "'__tostring' must return a string"); + } + else { + switch (lua_type(L, idx)) { + case LUA_TNUMBER: { + if (lua_isinteger(L, idx)) + lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx)); + else + lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx)); + break; + } + case LUA_TSTRING: + lua_pushvalue(L, idx); + break; + case LUA_TBOOLEAN: + lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); + break; + case LUA_TNIL: + lua_pushliteral(L, "nil"); + break; + default: { + int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ + const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : + luaL_typename(L, idx); + lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); + if (tt != LUA_TNIL) + lua_remove(L, -2); /* remove '__name' */ + break; + } + } + } + return lua_tolstring(L, -1, len); +} + + +/* +** set functions from list 'l' into table at top - 'nup'; each +** function gets the 'nup' elements at the top as upvalues. +** Returns with only the table at the stack. +*/ +LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { + luaL_checkstack(L, nup, "too many upvalues"); + for (; l->name != NULL; l++) { /* fill the table with given functions */ + if (l->func == NULL) /* place holder? */ + lua_pushboolean(L, 0); + else { + int i; + for (i = 0; i < nup; i++) /* copy upvalues to the top */ + lua_pushvalue(L, -nup); + lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ + } + lua_setfield(L, -(nup + 2), l->name); + } + lua_pop(L, nup); /* remove upvalues */ +} + + +/* +** ensure that stack[idx][fname] has a table and push that table +** into the stack +*/ +LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { + if (lua_getfield(L, idx, fname) == LUA_TTABLE) + return 1; /* table already there */ + else { + lua_pop(L, 1); /* remove previous result */ + idx = lua_absindex(L, idx); + lua_newtable(L); + lua_pushvalue(L, -1); /* copy to be left at top */ + lua_setfield(L, idx, fname); /* assign new table to field */ + return 0; /* false, because did not find table there */ + } +} + + +/* +** Stripped-down 'require': After checking "loaded" table, calls 'openf' +** to open a module, registers the result in 'package.loaded' table and, +** if 'glb' is true, also registers the result in the global table. +** Leaves resulting module on the top. +*/ +LUALIB_API void luaL_requiref (lua_State *L, const char *modname, + lua_CFunction openf, int glb) { + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_getfield(L, -1, modname); /* LOADED[modname] */ + if (!lua_toboolean(L, -1)) { /* package not already loaded? */ + lua_pop(L, 1); /* remove field */ + lua_pushcfunction(L, openf); + lua_pushstring(L, modname); /* argument to open function */ + lua_call(L, 1, 1); /* call 'openf' to open module */ + lua_pushvalue(L, -1); /* make copy of module (call result) */ + lua_setfield(L, -3, modname); /* LOADED[modname] = module */ + } + lua_remove(L, -2); /* remove LOADED table */ + if (glb) { + lua_pushvalue(L, -1); /* copy of module */ + lua_setglobal(L, modname); /* _G[modname] = module */ + } +} + + +LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, + const char *p, const char *r) { + const char *wild; + size_t l = strlen(p); + while ((wild = strstr(s, p)) != NULL) { + luaL_addlstring(b, s, wild - s); /* push prefix */ + luaL_addstring(b, r); /* push replacement in place of pattern */ + s = wild + l; /* continue after 'p' */ + } + luaL_addstring(b, s); /* push last suffix */ +} + + +LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, + const char *p, const char *r) { + luaL_Buffer b; + luaL_buffinit(L, &b); + luaL_addgsub(&b, s, p, r); + luaL_pushresult(&b); + return lua_tostring(L, -1); +} + + +static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { + (void)ud; (void)osize; /* not used */ + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); +} + + +static int panic (lua_State *L) { + const char *msg = lua_tostring(L, -1); + if (msg == NULL) msg = "error object is not a string"; + lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", + msg); + return 0; /* return to Lua to abort */ +} + + +/* +** Warning functions: +** warnfoff: warning system is off +** warnfon: ready to start a new message +** warnfcont: previous message is to be continued +*/ +static void warnfoff (void *ud, const char *message, int tocont); +static void warnfon (void *ud, const char *message, int tocont); +static void warnfcont (void *ud, const char *message, int tocont); + + +/* +** Check whether message is a control message. If so, execute the +** control or ignore it if unknown. +*/ +static int checkcontrol (lua_State *L, const char *message, int tocont) { + if (tocont || *(message++) != '@') /* not a control message? */ + return 0; + else { + if (strcmp(message, "off") == 0) + lua_setwarnf(L, warnfoff, L); /* turn warnings off */ + else if (strcmp(message, "on") == 0) + lua_setwarnf(L, warnfon, L); /* turn warnings on */ + return 1; /* it was a control message */ + } +} + + +static void warnfoff (void *ud, const char *message, int tocont) { + checkcontrol((lua_State *)ud, message, tocont); +} + + +/* +** Writes the message and handle 'tocont', finishing the message +** if needed and setting the next warn function. +*/ +static void warnfcont (void *ud, const char *message, int tocont) { + lua_State *L = (lua_State *)ud; + lua_writestringerror("%s", message); /* write message */ + if (tocont) /* not the last part? */ + lua_setwarnf(L, warnfcont, L); /* to be continued */ + else { /* last part */ + lua_writestringerror("%s", "\n"); /* finish message with end-of-line */ + lua_setwarnf(L, warnfon, L); /* next call is a new message */ + } +} + + +static void warnfon (void *ud, const char *message, int tocont) { + if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */ + return; /* nothing else to be done */ + lua_writestringerror("%s", "Lua warning: "); /* start a new warning */ + warnfcont(ud, message, tocont); /* finish processing */ +} + + +LUALIB_API lua_State *luaL_newstate (void) { + lua_State *L = lua_newstate(l_alloc, NULL); + if (l_likely(L)) { + lua_atpanic(L, &panic); + lua_setwarnf(L, warnfoff, L); /* default is warnings off */ + } + return L; +} + + +LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { + lua_Number v = lua_version(L); + if (sz != LUAL_NUMSIZES) /* check numeric types */ + luaL_error(L, "core and library have incompatible numeric types"); + else if (v != ver) + luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", + (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v); +} + diff --git a/src/libs/3rdparty/lua/src/lauxlib.h b/src/libs/3rdparty/lua/src/lauxlib.h new file mode 100644 index 00000000000..5b977e2a39f --- /dev/null +++ b/src/libs/3rdparty/lua/src/lauxlib.h @@ -0,0 +1,301 @@ +/* +** $Id: lauxlib.h $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lauxlib_h +#define lauxlib_h + + +#include +#include + +#include "luaconf.h" +#include "lua.h" + + +/* global table */ +#define LUA_GNAME "_G" + + +typedef struct luaL_Buffer luaL_Buffer; + + +/* extra error code for 'luaL_loadfilex' */ +#define LUA_ERRFILE (LUA_ERRERR+1) + + +/* key, in the registry, for table of loaded modules */ +#define LUA_LOADED_TABLE "_LOADED" + + +/* key, in the registry, for table of preloaded loaders */ +#define LUA_PRELOAD_TABLE "_PRELOAD" + + +typedef struct luaL_Reg { + const char *name; + lua_CFunction func; +} luaL_Reg; + + +#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) + +LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz); +#define luaL_checkversion(L) \ + luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) + +LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); +LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); +LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len); +LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg); +LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname); +LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg, + size_t *l); +LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg, + const char *def, size_t *l); +LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg); +LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def); + +LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg); +LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg, + lua_Integer def); + +LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); +LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t); +LUALIB_API void (luaL_checkany) (lua_State *L, int arg); + +LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); +LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); +LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); + +LUALIB_API void (luaL_where) (lua_State *L, int lvl); +LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); + +LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, + const char *const lst[]); + +LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); +LUALIB_API int (luaL_execresult) (lua_State *L, int stat); + + +/* predefined references */ +#define LUA_NOREF (-2) +#define LUA_REFNIL (-1) + +LUALIB_API int (luaL_ref) (lua_State *L, int t); +LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); + +LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, + const char *mode); + +#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) + +LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, + const char *name, const char *mode); +LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); + +LUALIB_API lua_State *(luaL_newstate) (void); + +LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx); + +LUALIB_API void (luaL_addgsub) (luaL_Buffer *b, const char *s, + const char *p, const char *r); +LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, + const char *p, const char *r); + +LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); + +LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname); + +LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1, + const char *msg, int level); + +LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, + lua_CFunction openf, int glb); + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + + +#define luaL_newlibtable(L,l) \ + lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) + +#define luaL_newlib(L,l) \ + (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) + +#define luaL_argcheck(L, cond,arg,extramsg) \ + ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg)))) + +#define luaL_argexpected(L,cond,arg,tname) \ + ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname)))) + +#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) + +#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) + +#define luaL_dofile(L, fn) \ + (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_dostring(L, s) \ + (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) + +#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) + +#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) + +#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) + + +/* +** Perform arithmetic operations on lua_Integer values with wrap-around +** semantics, as the Lua core does. +*/ +#define luaL_intop(op,v1,v2) \ + ((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2))) + + +/* push the value used to represent failure/error */ +#define luaL_pushfail(L) lua_pushnil(L) + + +/* +** Internal assertions for in-house debugging +*/ +#if !defined(lua_assert) + +#if defined LUAI_ASSERT + #include + #define lua_assert(c) assert(c) +#else + #define lua_assert(c) ((void)0) +#endif + +#endif + + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + +struct luaL_Buffer { + char *b; /* buffer address */ + size_t size; /* buffer size */ + size_t n; /* number of characters in buffer */ + lua_State *L; + union { + LUAI_MAXALIGN; /* ensure maximum alignment for buffer */ + char b[LUAL_BUFFERSIZE]; /* initial buffer */ + } init; +}; + + +#define luaL_bufflen(bf) ((bf)->n) +#define luaL_buffaddr(bf) ((bf)->b) + + +#define luaL_addchar(B,c) \ + ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ + ((B)->b[(B)->n++] = (c))) + +#define luaL_addsize(B,s) ((B)->n += (s)) + +#define luaL_buffsub(B,s) ((B)->n -= (s)) + +LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); +LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz); +LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); +LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); +LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); +LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz); +LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz); + +#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) + +/* }====================================================== */ + + + +/* +** {====================================================== +** File handles for IO library +** ======================================================= +*/ + +/* +** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and +** initial structure 'luaL_Stream' (it may contain other fields +** after that initial structure). +*/ + +#define LUA_FILEHANDLE "FILE*" + + +typedef struct luaL_Stream { + FILE *f; /* stream (NULL for incompletely created streams) */ + lua_CFunction closef; /* to close stream (NULL for closed streams) */ +} luaL_Stream; + +/* }====================================================== */ + +/* +** {================================================================== +** "Abstraction Layer" for basic report of messages and errors +** =================================================================== +*/ + +/* print a string */ +#if !defined(lua_writestring) +#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +#endif + +/* print a newline and flush the output */ +#if !defined(lua_writeline) +#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) +#endif + +/* print an error message */ +#if !defined(lua_writestringerror) +#define lua_writestringerror(s,p) \ + (fprintf(stderr, (s), (p)), fflush(stderr)) +#endif + +/* }================================================================== */ + + +/* +** {============================================================ +** Compatibility with deprecated conversions +** ============================================================= +*/ +#if defined(LUA_COMPAT_APIINTCASTS) + +#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) +#define luaL_optunsigned(L,a,d) \ + ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) + +#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) +#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) + +#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) + +#endif +/* }============================================================ */ + + + +#endif + + diff --git a/src/libs/3rdparty/lua/src/lbaselib.c b/src/libs/3rdparty/lua/src/lbaselib.c new file mode 100644 index 00000000000..1d60c9dede5 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lbaselib.c @@ -0,0 +1,549 @@ +/* +** $Id: lbaselib.c $ +** Basic library +** See Copyright Notice in lua.h +*/ + +#define lbaselib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static int luaB_print (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + for (i = 1; i <= n; i++) { /* for each argument */ + size_t l; + const char *s = luaL_tolstring(L, i, &l); /* convert it to string */ + if (i > 1) /* not the first element? */ + lua_writestring("\t", 1); /* add a tab before it */ + lua_writestring(s, l); /* print it */ + lua_pop(L, 1); /* pop result */ + } + lua_writeline(); + return 0; +} + + +/* +** Creates a warning with all given arguments. +** Check first for errors; otherwise an error may interrupt +** the composition of a warning, leaving it unfinished. +*/ +static int luaB_warn (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + luaL_checkstring(L, 1); /* at least one argument */ + for (i = 2; i <= n; i++) + luaL_checkstring(L, i); /* make sure all arguments are strings */ + for (i = 1; i < n; i++) /* compose warning */ + lua_warning(L, lua_tostring(L, i), 1); + lua_warning(L, lua_tostring(L, n), 0); /* close warning */ + return 0; +} + + +#define SPACECHARS " \f\n\r\t\v" + +static const char *b_str2int (const char *s, int base, lua_Integer *pn) { + lua_Unsigned n = 0; + int neg = 0; + s += strspn(s, SPACECHARS); /* skip initial spaces */ + if (*s == '-') { s++; neg = 1; } /* handle sign */ + else if (*s == '+') s++; + if (!isalnum((unsigned char)*s)) /* no digit? */ + return NULL; + do { + int digit = (isdigit((unsigned char)*s)) ? *s - '0' + : (toupper((unsigned char)*s) - 'A') + 10; + if (digit >= base) return NULL; /* invalid numeral */ + n = n * base + digit; + s++; + } while (isalnum((unsigned char)*s)); + s += strspn(s, SPACECHARS); /* skip trailing spaces */ + *pn = (lua_Integer)((neg) ? (0u - n) : n); + return s; +} + + +static int luaB_tonumber (lua_State *L) { + if (lua_isnoneornil(L, 2)) { /* standard conversion? */ + if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ + lua_settop(L, 1); /* yes; return it */ + return 1; + } + else { + size_t l; + const char *s = lua_tolstring(L, 1, &l); + if (s != NULL && lua_stringtonumber(L, s) == l + 1) + return 1; /* successful conversion to number */ + /* else not a number */ + luaL_checkany(L, 1); /* (but there must be some parameter) */ + } + } + else { + size_t l; + const char *s; + lua_Integer n = 0; /* to avoid warnings */ + lua_Integer base = luaL_checkinteger(L, 2); + luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ + s = lua_tolstring(L, 1, &l); + luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); + if (b_str2int(s, (int)base, &n) == s + l) { + lua_pushinteger(L, n); + return 1; + } /* else not a number */ + } /* else not a number */ + luaL_pushfail(L); /* not a number */ + return 1; +} + + +static int luaB_error (lua_State *L) { + int level = (int)luaL_optinteger(L, 2, 1); + lua_settop(L, 1); + if (lua_type(L, 1) == LUA_TSTRING && level > 0) { + luaL_where(L, level); /* add extra information */ + lua_pushvalue(L, 1); + lua_concat(L, 2); + } + return lua_error(L); +} + + +static int luaB_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); + return 1; /* no metatable */ + } + luaL_getmetafield(L, 1, "__metatable"); + return 1; /* returns either __metatable field (if present) or metatable */ +} + + +static int luaB_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_checktype(L, 1, LUA_TTABLE); + luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); + if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)) + return luaL_error(L, "cannot change a protected metatable"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; +} + + +static int luaB_rawequal (lua_State *L) { + luaL_checkany(L, 1); + luaL_checkany(L, 2); + lua_pushboolean(L, lua_rawequal(L, 1, 2)); + return 1; +} + + +static int luaB_rawlen (lua_State *L) { + int t = lua_type(L, 1); + luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, + "table or string"); + lua_pushinteger(L, lua_rawlen(L, 1)); + return 1; +} + + +static int luaB_rawget (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + lua_settop(L, 2); + lua_rawget(L, 1); + return 1; +} + +static int luaB_rawset (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checkany(L, 2); + luaL_checkany(L, 3); + lua_settop(L, 3); + lua_rawset(L, 1); + return 1; +} + + +static int pushmode (lua_State *L, int oldmode) { + if (oldmode == -1) + luaL_pushfail(L); /* invalid call to 'lua_gc' */ + else + lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental" + : "generational"); + return 1; +} + + +/* +** check whether call to 'lua_gc' was valid (not inside a finalizer) +*/ +#define checkvalres(res) { if (res == -1) break; } + +static int luaB_collectgarbage (lua_State *L) { + static const char *const opts[] = {"stop", "restart", "collect", + "count", "step", "setpause", "setstepmul", + "isrunning", "generational", "incremental", NULL}; + static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, + LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, + LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; + int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; + switch (o) { + case LUA_GCCOUNT: { + int k = lua_gc(L, o); + int b = lua_gc(L, LUA_GCCOUNTB); + checkvalres(k); + lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024)); + return 1; + } + case LUA_GCSTEP: { + int step = (int)luaL_optinteger(L, 2, 0); + int res = lua_gc(L, o, step); + checkvalres(res); + lua_pushboolean(L, res); + return 1; + } + case LUA_GCSETPAUSE: + case LUA_GCSETSTEPMUL: { + int p = (int)luaL_optinteger(L, 2, 0); + int previous = lua_gc(L, o, p); + checkvalres(previous); + lua_pushinteger(L, previous); + return 1; + } + case LUA_GCISRUNNING: { + int res = lua_gc(L, o); + checkvalres(res); + lua_pushboolean(L, res); + return 1; + } + case LUA_GCGEN: { + int minormul = (int)luaL_optinteger(L, 2, 0); + int majormul = (int)luaL_optinteger(L, 3, 0); + return pushmode(L, lua_gc(L, o, minormul, majormul)); + } + case LUA_GCINC: { + int pause = (int)luaL_optinteger(L, 2, 0); + int stepmul = (int)luaL_optinteger(L, 3, 0); + int stepsize = (int)luaL_optinteger(L, 4, 0); + return pushmode(L, lua_gc(L, o, pause, stepmul, stepsize)); + } + default: { + int res = lua_gc(L, o); + checkvalres(res); + lua_pushinteger(L, res); + return 1; + } + } + luaL_pushfail(L); /* invalid call (inside a finalizer) */ + return 1; +} + + +static int luaB_type (lua_State *L) { + int t = lua_type(L, 1); + luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); + lua_pushstring(L, lua_typename(L, t)); + return 1; +} + + +static int luaB_next (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_settop(L, 2); /* create a 2nd argument if there isn't one */ + if (lua_next(L, 1)) + return 2; + else { + lua_pushnil(L); + return 1; + } +} + + +static int pairscont (lua_State *L, int status, lua_KContext k) { + (void)L; (void)status; (void)k; /* unused */ + return 3; +} + +static int luaB_pairs (lua_State *L) { + luaL_checkany(L, 1); + if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */ + lua_pushcfunction(L, luaB_next); /* will return generator, */ + lua_pushvalue(L, 1); /* state, */ + lua_pushnil(L); /* and initial value */ + } + else { + lua_pushvalue(L, 1); /* argument 'self' to metamethod */ + lua_callk(L, 1, 3, 0, pairscont); /* get 3 values from metamethod */ + } + return 3; +} + + +/* +** Traversal function for 'ipairs' +*/ +static int ipairsaux (lua_State *L) { + lua_Integer i = luaL_checkinteger(L, 2); + i = luaL_intop(+, i, 1); + lua_pushinteger(L, i); + return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; +} + + +/* +** 'ipairs' function. Returns 'ipairsaux', given "table", 0. +** (The given "table" may not be a table.) +*/ +static int luaB_ipairs (lua_State *L) { + luaL_checkany(L, 1); + lua_pushcfunction(L, ipairsaux); /* iteration function */ + lua_pushvalue(L, 1); /* state */ + lua_pushinteger(L, 0); /* initial value */ + return 3; +} + + +static int load_aux (lua_State *L, int status, int envidx) { + if (l_likely(status == LUA_OK)) { + if (envidx != 0) { /* 'env' parameter? */ + lua_pushvalue(L, envidx); /* environment for loaded function */ + if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ + lua_pop(L, 1); /* remove 'env' if not used by previous call */ + } + return 1; + } + else { /* error (message is on top of the stack) */ + luaL_pushfail(L); + lua_insert(L, -2); /* put before error message */ + return 2; /* return fail plus error message */ + } +} + + +static int luaB_loadfile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + const char *mode = luaL_optstring(L, 2, NULL); + int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ + int status = luaL_loadfilex(L, fname, mode); + return load_aux(L, status, env); +} + + +/* +** {====================================================== +** Generic Read function +** ======================================================= +*/ + + +/* +** reserved slot, above all arguments, to hold a copy of the returned +** string to avoid it being collected while parsed. 'load' has four +** optional arguments (chunk, source name, mode, and environment). +*/ +#define RESERVEDSLOT 5 + + +/* +** Reader for generic 'load' function: 'lua_load' uses the +** stack for internal stuff, so the reader cannot change the +** stack top. Instead, it keeps its resulting string in a +** reserved slot inside the stack. +*/ +static const char *generic_reader (lua_State *L, void *ud, size_t *size) { + (void)(ud); /* not used */ + luaL_checkstack(L, 2, "too many nested functions"); + lua_pushvalue(L, 1); /* get function */ + lua_call(L, 0, 1); /* call it */ + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* pop result */ + *size = 0; + return NULL; + } + else if (l_unlikely(!lua_isstring(L, -1))) + luaL_error(L, "reader function must return a string"); + lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ + return lua_tolstring(L, RESERVEDSLOT, size); +} + + +static int luaB_load (lua_State *L) { + int status; + size_t l; + const char *s = lua_tolstring(L, 1, &l); + const char *mode = luaL_optstring(L, 3, "bt"); + int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ + if (s != NULL) { /* loading a string? */ + const char *chunkname = luaL_optstring(L, 2, s); + status = luaL_loadbufferx(L, s, l, chunkname, mode); + } + else { /* loading from a reader function */ + const char *chunkname = luaL_optstring(L, 2, "=(load)"); + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, RESERVEDSLOT); /* create reserved slot */ + status = lua_load(L, generic_reader, NULL, chunkname, mode); + } + return load_aux(L, status, env); +} + +/* }====================================================== */ + + +static int dofilecont (lua_State *L, int d1, lua_KContext d2) { + (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ + return lua_gettop(L) - 1; +} + + +static int luaB_dofile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + lua_settop(L, 1); + if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK)) + return lua_error(L); + lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); + return dofilecont(L, 0, 0); +} + + +static int luaB_assert (lua_State *L) { + if (l_likely(lua_toboolean(L, 1))) /* condition is true? */ + return lua_gettop(L); /* return all arguments */ + else { /* error */ + luaL_checkany(L, 1); /* there must be a condition */ + lua_remove(L, 1); /* remove it */ + lua_pushliteral(L, "assertion failed!"); /* default message */ + lua_settop(L, 1); /* leave only message (default if no other one) */ + return luaB_error(L); /* call 'error' */ + } +} + + +static int luaB_select (lua_State *L) { + int n = lua_gettop(L); + if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { + lua_pushinteger(L, n-1); + return 1; + } + else { + lua_Integer i = luaL_checkinteger(L, 1); + if (i < 0) i = n + i; + else if (i > n) i = n; + luaL_argcheck(L, 1 <= i, 1, "index out of range"); + return n - (int)i; + } +} + + +/* +** Continuation function for 'pcall' and 'xpcall'. Both functions +** already pushed a 'true' before doing the call, so in case of success +** 'finishpcall' only has to return everything in the stack minus +** 'extra' values (where 'extra' is exactly the number of items to be +** ignored). +*/ +static int finishpcall (lua_State *L, int status, lua_KContext extra) { + if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */ + lua_pushboolean(L, 0); /* first result (false) */ + lua_pushvalue(L, -2); /* error message */ + return 2; /* return false, msg */ + } + else + return lua_gettop(L) - (int)extra; /* return all results */ +} + + +static int luaB_pcall (lua_State *L) { + int status; + luaL_checkany(L, 1); + lua_pushboolean(L, 1); /* first result if no errors */ + lua_insert(L, 1); /* put it in place */ + status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); + return finishpcall(L, status, 0); +} + + +/* +** Do a protected call with error handling. After 'lua_rotate', the +** stack will have ; so, the function passes +** 2 to 'finishpcall' to skip the 2 first values when returning results. +*/ +static int luaB_xpcall (lua_State *L) { + int status; + int n = lua_gettop(L); + luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ + lua_pushboolean(L, 1); /* first result */ + lua_pushvalue(L, 1); /* function */ + lua_rotate(L, 3, 2); /* move them below function's arguments */ + status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); + return finishpcall(L, status, 2); +} + + +static int luaB_tostring (lua_State *L) { + luaL_checkany(L, 1); + luaL_tolstring(L, 1, NULL); + return 1; +} + + +static const luaL_Reg base_funcs[] = { + {"assert", luaB_assert}, + {"collectgarbage", luaB_collectgarbage}, + {"dofile", luaB_dofile}, + {"error", luaB_error}, + {"getmetatable", luaB_getmetatable}, + {"ipairs", luaB_ipairs}, + {"loadfile", luaB_loadfile}, + {"load", luaB_load}, + {"next", luaB_next}, + {"pairs", luaB_pairs}, + {"pcall", luaB_pcall}, + {"print", luaB_print}, + {"warn", luaB_warn}, + {"rawequal", luaB_rawequal}, + {"rawlen", luaB_rawlen}, + {"rawget", luaB_rawget}, + {"rawset", luaB_rawset}, + {"select", luaB_select}, + {"setmetatable", luaB_setmetatable}, + {"tonumber", luaB_tonumber}, + {"tostring", luaB_tostring}, + {"type", luaB_type}, + {"xpcall", luaB_xpcall}, + /* placeholders */ + {LUA_GNAME, NULL}, + {"_VERSION", NULL}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_base (lua_State *L) { + /* open lib into global table */ + lua_pushglobaltable(L); + luaL_setfuncs(L, base_funcs, 0); + /* set global _G */ + lua_pushvalue(L, -1); + lua_setfield(L, -2, LUA_GNAME); + /* set global _VERSION */ + lua_pushliteral(L, LUA_VERSION); + lua_setfield(L, -2, "_VERSION"); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/lcode.c b/src/libs/3rdparty/lua/src/lcode.c new file mode 100644 index 00000000000..1a371ca943b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lcode.c @@ -0,0 +1,1871 @@ +/* +** $Id: lcode.c $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + +#define lcode_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include +#include + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +/* Maximum number of registers in a Lua function (must fit in 8 bits) */ +#define MAXREGS 255 + + +#define hasjumps(e) ((e)->t != (e)->f) + + +static int codesJ (FuncState *fs, OpCode o, int sj, int k); + + + +/* semantic error */ +l_noret luaK_semerror (LexState *ls, const char *msg) { + ls->t.token = 0; /* remove "near " from final message */ + luaX_syntaxerror(ls, msg); +} + + +/* +** If expression is a numeric constant, fills 'v' with its value +** and returns 1. Otherwise, returns 0. +*/ +static int tonumeral (const expdesc *e, TValue *v) { + if (hasjumps(e)) + return 0; /* not a numeral */ + switch (e->k) { + case VKINT: + if (v) setivalue(v, e->u.ival); + return 1; + case VKFLT: + if (v) setfltvalue(v, e->u.nval); + return 1; + default: return 0; + } +} + + +/* +** Get the constant value from a constant expression +*/ +static TValue *const2val (FuncState *fs, const expdesc *e) { + lua_assert(e->k == VCONST); + return &fs->ls->dyd->actvar.arr[e->u.info].k; +} + + +/* +** If expression is a constant, fills 'v' with its value +** and returns 1. Otherwise, returns 0. +*/ +int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) { + if (hasjumps(e)) + return 0; /* not a constant */ + switch (e->k) { + case VFALSE: + setbfvalue(v); + return 1; + case VTRUE: + setbtvalue(v); + return 1; + case VNIL: + setnilvalue(v); + return 1; + case VKSTR: { + setsvalue(fs->ls->L, v, e->u.strval); + return 1; + } + case VCONST: { + setobj(fs->ls->L, v, const2val(fs, e)); + return 1; + } + default: return tonumeral(e, v); + } +} + + +/* +** Return the previous instruction of the current code. If there +** may be a jump target between the current instruction and the +** previous one, return an invalid instruction (to avoid wrong +** optimizations). +*/ +static Instruction *previousinstruction (FuncState *fs) { + static const Instruction invalidinstruction = ~(Instruction)0; + if (fs->pc > fs->lasttarget) + return &fs->f->code[fs->pc - 1]; /* previous instruction */ + else + return cast(Instruction*, &invalidinstruction); +} + + +/* +** Create a OP_LOADNIL instruction, but try to optimize: if the previous +** instruction is also OP_LOADNIL and ranges are compatible, adjust +** range of previous instruction instead of emitting a new one. (For +** instance, 'local a; local b' will generate a single opcode.) +*/ +void luaK_nil (FuncState *fs, int from, int n) { + int l = from + n - 1; /* last register to set nil */ + Instruction *previous = previousinstruction(fs); + if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ + int pfrom = GETARG_A(*previous); /* get previous range */ + int pl = pfrom + GETARG_B(*previous); + if ((pfrom <= from && from <= pl + 1) || + (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ + if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ + if (pl > l) l = pl; /* l = max(l, pl) */ + SETARG_A(*previous, from); + SETARG_B(*previous, l - from); + return; + } /* else go through */ + } + luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ +} + + +/* +** Gets the destination address of a jump instruction. Used to traverse +** a list of jumps. +*/ +static int getjump (FuncState *fs, int pc) { + int offset = GETARG_sJ(fs->f->code[pc]); + if (offset == NO_JUMP) /* point to itself represents end of list */ + return NO_JUMP; /* end of list */ + else + return (pc+1)+offset; /* turn offset into absolute position */ +} + + +/* +** Fix jump instruction at position 'pc' to jump to 'dest'. +** (Jump addresses are relative in Lua) +*/ +static void fixjump (FuncState *fs, int pc, int dest) { + Instruction *jmp = &fs->f->code[pc]; + int offset = dest - (pc + 1); + lua_assert(dest != NO_JUMP); + if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ)) + luaX_syntaxerror(fs->ls, "control structure too long"); + lua_assert(GET_OPCODE(*jmp) == OP_JMP); + SETARG_sJ(*jmp, offset); +} + + +/* +** Concatenate jump-list 'l2' into jump-list 'l1' +*/ +void luaK_concat (FuncState *fs, int *l1, int l2) { + if (l2 == NO_JUMP) return; /* nothing to concatenate? */ + else if (*l1 == NO_JUMP) /* no original list? */ + *l1 = l2; /* 'l1' points to 'l2' */ + else { + int list = *l1; + int next; + while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ + list = next; + fixjump(fs, list, l2); /* last element links to 'l2' */ + } +} + + +/* +** Create a jump instruction and return its position, so its destination +** can be fixed later (with 'fixjump'). +*/ +int luaK_jump (FuncState *fs) { + return codesJ(fs, OP_JMP, NO_JUMP, 0); +} + + +/* +** Code a 'return' instruction +*/ +void luaK_ret (FuncState *fs, int first, int nret) { + OpCode op; + switch (nret) { + case 0: op = OP_RETURN0; break; + case 1: op = OP_RETURN1; break; + default: op = OP_RETURN; break; + } + luaK_codeABC(fs, op, first, nret + 1, 0); +} + + +/* +** Code a "conditional jump", that is, a test or comparison opcode +** followed by a jump. Return jump position. +*/ +static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) { + luaK_codeABCk(fs, op, A, B, C, k); + return luaK_jump(fs); +} + + +/* +** returns current 'pc' and marks it as a jump target (to avoid wrong +** optimizations with consecutive instructions not in the same basic block). +*/ +int luaK_getlabel (FuncState *fs) { + fs->lasttarget = fs->pc; + return fs->pc; +} + + +/* +** Returns the position of the instruction "controlling" a given +** jump (that is, its condition), or the jump itself if it is +** unconditional. +*/ +static Instruction *getjumpcontrol (FuncState *fs, int pc) { + Instruction *pi = &fs->f->code[pc]; + if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) + return pi-1; + else + return pi; +} + + +/* +** Patch destination register for a TESTSET instruction. +** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). +** Otherwise, if 'reg' is not 'NO_REG', set it as the destination +** register. Otherwise, change instruction to a simple 'TEST' (produces +** no register value) +*/ +static int patchtestreg (FuncState *fs, int node, int reg) { + Instruction *i = getjumpcontrol(fs, node); + if (GET_OPCODE(*i) != OP_TESTSET) + return 0; /* cannot patch other instructions */ + if (reg != NO_REG && reg != GETARG_B(*i)) + SETARG_A(*i, reg); + else { + /* no register to put value or register already has the value; + change instruction to simple test */ + *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i)); + } + return 1; +} + + +/* +** Traverse a list of tests ensuring no one produces a value +*/ +static void removevalues (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) + patchtestreg(fs, list, NO_REG); +} + + +/* +** Traverse a list of tests, patching their destination address and +** registers: tests producing values jump to 'vtarget' (and put their +** values in 'reg'), other tests jump to 'dtarget'. +*/ +static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, + int dtarget) { + while (list != NO_JUMP) { + int next = getjump(fs, list); + if (patchtestreg(fs, list, reg)) + fixjump(fs, list, vtarget); + else + fixjump(fs, list, dtarget); /* jump to default target */ + list = next; + } +} + + +/* +** Path all jumps in 'list' to jump to 'target'. +** (The assert means that we cannot fix a jump to a forward address +** because we only know addresses once code is generated.) +*/ +void luaK_patchlist (FuncState *fs, int list, int target) { + lua_assert(target <= fs->pc); + patchlistaux(fs, list, target, NO_REG, target); +} + + +void luaK_patchtohere (FuncState *fs, int list) { + int hr = luaK_getlabel(fs); /* mark "here" as a jump target */ + luaK_patchlist(fs, list, hr); +} + + +/* limit for difference between lines in relative line info. */ +#define LIMLINEDIFF 0x80 + + +/* +** Save line info for a new instruction. If difference from last line +** does not fit in a byte, of after that many instructions, save a new +** absolute line info; (in that case, the special value 'ABSLINEINFO' +** in 'lineinfo' signals the existence of this absolute information.) +** Otherwise, store the difference from last line in 'lineinfo'. +*/ +static void savelineinfo (FuncState *fs, Proto *f, int line) { + int linedif = line - fs->previousline; + int pc = fs->pc - 1; /* last instruction coded */ + if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) { + luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo, + f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines"); + f->abslineinfo[fs->nabslineinfo].pc = pc; + f->abslineinfo[fs->nabslineinfo++].line = line; + linedif = ABSLINEINFO; /* signal that there is absolute information */ + fs->iwthabs = 1; /* restart counter */ + } + luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte, + MAX_INT, "opcodes"); + f->lineinfo[pc] = linedif; + fs->previousline = line; /* last line saved */ +} + + +/* +** Remove line information from the last instruction. +** If line information for that instruction is absolute, set 'iwthabs' +** above its max to force the new (replacing) instruction to have +** absolute line info, too. +*/ +static void removelastlineinfo (FuncState *fs) { + Proto *f = fs->f; + int pc = fs->pc - 1; /* last instruction coded */ + if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */ + fs->previousline -= f->lineinfo[pc]; /* correct last line saved */ + fs->iwthabs--; /* undo previous increment */ + } + else { /* absolute line information */ + lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc); + fs->nabslineinfo--; /* remove it */ + fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */ + } +} + + +/* +** Remove the last instruction created, correcting line information +** accordingly. +*/ +static void removelastinstruction (FuncState *fs) { + removelastlineinfo(fs); + fs->pc--; +} + + +/* +** Emit instruction 'i', checking for array sizes and saving also its +** line information. Return 'i' position. +*/ +int luaK_code (FuncState *fs, Instruction i) { + Proto *f = fs->f; + /* put new instruction in code array */ + luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, + MAX_INT, "opcodes"); + f->code[fs->pc++] = i; + savelineinfo(fs, f, fs->ls->lastline); + return fs->pc - 1; /* index of new instruction */ +} + + +/* +** Format and emit an 'iABC' instruction. (Assertions check consistency +** of parameters versus opcode.) +*/ +int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) { + lua_assert(getOpMode(o) == iABC); + lua_assert(a <= MAXARG_A && b <= MAXARG_B && + c <= MAXARG_C && (k & ~1) == 0); + return luaK_code(fs, CREATE_ABCk(o, a, b, c, k)); +} + + +/* +** Format and emit an 'iABx' instruction. +*/ +int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { + lua_assert(getOpMode(o) == iABx); + lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); + return luaK_code(fs, CREATE_ABx(o, a, bc)); +} + + +/* +** Format and emit an 'iAsBx' instruction. +*/ +int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) { + unsigned int b = bc + OFFSET_sBx; + lua_assert(getOpMode(o) == iAsBx); + lua_assert(a <= MAXARG_A && b <= MAXARG_Bx); + return luaK_code(fs, CREATE_ABx(o, a, b)); +} + + +/* +** Format and emit an 'isJ' instruction. +*/ +static int codesJ (FuncState *fs, OpCode o, int sj, int k) { + unsigned int j = sj + OFFSET_sJ; + lua_assert(getOpMode(o) == isJ); + lua_assert(j <= MAXARG_sJ && (k & ~1) == 0); + return luaK_code(fs, CREATE_sJ(o, j, k)); +} + + +/* +** Emit an "extra argument" instruction (format 'iAx') +*/ +static int codeextraarg (FuncState *fs, int a) { + lua_assert(a <= MAXARG_Ax); + return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); +} + + +/* +** Emit a "load constant" instruction, using either 'OP_LOADK' +** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' +** instruction with "extra argument". +*/ +static int luaK_codek (FuncState *fs, int reg, int k) { + if (k <= MAXARG_Bx) + return luaK_codeABx(fs, OP_LOADK, reg, k); + else { + int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); + codeextraarg(fs, k); + return p; + } +} + + +/* +** Check register-stack level, keeping track of its maximum size +** in field 'maxstacksize' +*/ +void luaK_checkstack (FuncState *fs, int n) { + int newstack = fs->freereg + n; + if (newstack > fs->f->maxstacksize) { + if (newstack >= MAXREGS) + luaX_syntaxerror(fs->ls, + "function or expression needs too many registers"); + fs->f->maxstacksize = cast_byte(newstack); + } +} + + +/* +** Reserve 'n' registers in register stack +*/ +void luaK_reserveregs (FuncState *fs, int n) { + luaK_checkstack(fs, n); + fs->freereg += n; +} + + +/* +** Free register 'reg', if it is neither a constant index nor +** a local variable. +) +*/ +static void freereg (FuncState *fs, int reg) { + if (reg >= luaY_nvarstack(fs)) { + fs->freereg--; + lua_assert(reg == fs->freereg); + } +} + + +/* +** Free two registers in proper order +*/ +static void freeregs (FuncState *fs, int r1, int r2) { + if (r1 > r2) { + freereg(fs, r1); + freereg(fs, r2); + } + else { + freereg(fs, r2); + freereg(fs, r1); + } +} + + +/* +** Free register used by expression 'e' (if any) +*/ +static void freeexp (FuncState *fs, expdesc *e) { + if (e->k == VNONRELOC) + freereg(fs, e->u.info); +} + + +/* +** Free registers used by expressions 'e1' and 'e2' (if any) in proper +** order. +*/ +static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { + int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; + int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; + freeregs(fs, r1, r2); +} + + +/* +** Add constant 'v' to prototype's list of constants (field 'k'). +** Use scanner's table to cache position of constants in constant list +** and try to reuse constants. Because some values should not be used +** as keys (nil cannot be a key, integer keys can collapse with float +** keys), the caller must provide a useful 'key' for indexing the cache. +** Note that all functions share the same table, so entering or exiting +** a function can make some indices wrong. +*/ +static int addk (FuncState *fs, TValue *key, TValue *v) { + TValue val; + lua_State *L = fs->ls->L; + Proto *f = fs->f; + const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */ + int k, oldsize; + if (ttisinteger(idx)) { /* is there an index there? */ + k = cast_int(ivalue(idx)); + /* correct value? (warning: must distinguish floats from integers!) */ + if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) && + luaV_rawequalobj(&f->k[k], v)) + return k; /* reuse index */ + } + /* constant not found; create a new entry */ + oldsize = f->sizek; + k = fs->nk; + /* numerical value does not need GC barrier; + table has no metatable, so it does not need to invalidate cache */ + setivalue(&val, k); + luaH_finishset(L, fs->ls->h, key, idx, &val); + luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); + while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); + setobj(L, &f->k[k], v); + fs->nk++; + luaC_barrier(L, f, v); + return k; +} + + +/* +** Add a string to list of constants and return its index. +*/ +static int stringK (FuncState *fs, TString *s) { + TValue o; + setsvalue(fs->ls->L, &o, s); + return addk(fs, &o, &o); /* use string itself as key */ +} + + +/* +** Add an integer to list of constants and return its index. +*/ +static int luaK_intK (FuncState *fs, lua_Integer n) { + TValue o; + setivalue(&o, n); + return addk(fs, &o, &o); /* use integer itself as key */ +} + +/* +** Add a float to list of constants and return its index. Floats +** with integral values need a different key, to avoid collision +** with actual integers. To that, we add to the number its smaller +** power-of-two fraction that is still significant in its scale. +** For doubles, that would be 1/2^52. +** (This method is not bulletproof: there may be another float +** with that value, and for floats larger than 2^53 the result is +** still an integer. At worst, this only wastes an entry with +** a duplicate.) +*/ +static int luaK_numberK (FuncState *fs, lua_Number r) { + TValue o; + lua_Integer ik; + setfltvalue(&o, r); + if (!luaV_flttointeger(r, &ik, F2Ieq)) /* not an integral value? */ + return addk(fs, &o, &o); /* use number itself as key */ + else { /* must build an alternative key */ + const int nbm = l_floatatt(MANT_DIG); + const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1); + const lua_Number k = (ik == 0) ? q : r + r*q; /* new key */ + TValue kv; + setfltvalue(&kv, k); + /* result is not an integral value, unless value is too large */ + lua_assert(!luaV_flttointeger(k, &ik, F2Ieq) || + l_mathop(fabs)(r) >= l_mathop(1e6)); + return addk(fs, &kv, &o); + } +} + + +/* +** Add a false to list of constants and return its index. +*/ +static int boolF (FuncState *fs) { + TValue o; + setbfvalue(&o); + return addk(fs, &o, &o); /* use boolean itself as key */ +} + + +/* +** Add a true to list of constants and return its index. +*/ +static int boolT (FuncState *fs) { + TValue o; + setbtvalue(&o); + return addk(fs, &o, &o); /* use boolean itself as key */ +} + + +/* +** Add nil to list of constants and return its index. +*/ +static int nilK (FuncState *fs) { + TValue k, v; + setnilvalue(&v); + /* cannot use nil as key; instead use table itself to represent nil */ + sethvalue(fs->ls->L, &k, fs->ls->h); + return addk(fs, &k, &v); +} + + +/* +** Check whether 'i' can be stored in an 'sC' operand. Equivalent to +** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of +** overflows in the hidden addition inside 'int2sC'. +*/ +static int fitsC (lua_Integer i) { + return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C)); +} + + +/* +** Check whether 'i' can be stored in an 'sBx' operand. +*/ +static int fitsBx (lua_Integer i) { + return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx); +} + + +void luaK_int (FuncState *fs, int reg, lua_Integer i) { + if (fitsBx(i)) + luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i)); + else + luaK_codek(fs, reg, luaK_intK(fs, i)); +} + + +static void luaK_float (FuncState *fs, int reg, lua_Number f) { + lua_Integer fi; + if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi)) + luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi)); + else + luaK_codek(fs, reg, luaK_numberK(fs, f)); +} + + +/* +** Convert a constant in 'v' into an expression description 'e' +*/ +static void const2exp (TValue *v, expdesc *e) { + switch (ttypetag(v)) { + case LUA_VNUMINT: + e->k = VKINT; e->u.ival = ivalue(v); + break; + case LUA_VNUMFLT: + e->k = VKFLT; e->u.nval = fltvalue(v); + break; + case LUA_VFALSE: + e->k = VFALSE; + break; + case LUA_VTRUE: + e->k = VTRUE; + break; + case LUA_VNIL: + e->k = VNIL; + break; + case LUA_VSHRSTR: case LUA_VLNGSTR: + e->k = VKSTR; e->u.strval = tsvalue(v); + break; + default: lua_assert(0); + } +} + + +/* +** Fix an expression to return the number of results 'nresults'. +** 'e' must be a multi-ret expression (function call or vararg). +*/ +void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { + Instruction *pc = &getinstruction(fs, e); + if (e->k == VCALL) /* expression is an open function call? */ + SETARG_C(*pc, nresults + 1); + else { + lua_assert(e->k == VVARARG); + SETARG_C(*pc, nresults + 1); + SETARG_A(*pc, fs->freereg); + luaK_reserveregs(fs, 1); + } +} + + +/* +** Convert a VKSTR to a VK +*/ +static void str2K (FuncState *fs, expdesc *e) { + lua_assert(e->k == VKSTR); + e->u.info = stringK(fs, e->u.strval); + e->k = VK; +} + + +/* +** Fix an expression to return one result. +** If expression is not a multi-ret expression (function call or +** vararg), it already returns one result, so nothing needs to be done. +** Function calls become VNONRELOC expressions (as its result comes +** fixed in the base register of the call), while vararg expressions +** become VRELOC (as OP_VARARG puts its results where it wants). +** (Calls are created returning one result, so that does not need +** to be fixed.) +*/ +void luaK_setoneret (FuncState *fs, expdesc *e) { + if (e->k == VCALL) { /* expression is an open function call? */ + /* already returns 1 value */ + lua_assert(GETARG_C(getinstruction(fs, e)) == 2); + e->k = VNONRELOC; /* result has fixed position */ + e->u.info = GETARG_A(getinstruction(fs, e)); + } + else if (e->k == VVARARG) { + SETARG_C(getinstruction(fs, e), 2); + e->k = VRELOC; /* can relocate its simple result */ + } +} + + +/* +** Ensure that expression 'e' is not a variable (nor a ). +** (Expression still may have jump lists.) +*/ +void luaK_dischargevars (FuncState *fs, expdesc *e) { + switch (e->k) { + case VCONST: { + const2exp(const2val(fs, e), e); + break; + } + case VLOCAL: { /* already in a register */ + e->u.info = e->u.var.ridx; + e->k = VNONRELOC; /* becomes a non-relocatable value */ + break; + } + case VUPVAL: { /* move value to some (pending) register */ + e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); + e->k = VRELOC; + break; + } + case VINDEXUP: { + e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOC; + break; + } + case VINDEXI: { + freereg(fs, e->u.ind.t); + e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOC; + break; + } + case VINDEXSTR: { + freereg(fs, e->u.ind.t); + e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOC; + break; + } + case VINDEXED: { + freeregs(fs, e->u.ind.t, e->u.ind.idx); + e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx); + e->k = VRELOC; + break; + } + case VVARARG: case VCALL: { + luaK_setoneret(fs, e); + break; + } + default: break; /* there is one value available (somewhere) */ + } +} + + +/* +** Ensure expression value is in register 'reg', making 'e' a +** non-relocatable expression. +** (Expression still may have jump lists.) +*/ +static void discharge2reg (FuncState *fs, expdesc *e, int reg) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: { + luaK_nil(fs, reg, 1); + break; + } + case VFALSE: { + luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0); + break; + } + case VTRUE: { + luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0); + break; + } + case VKSTR: { + str2K(fs, e); + } /* FALLTHROUGH */ + case VK: { + luaK_codek(fs, reg, e->u.info); + break; + } + case VKFLT: { + luaK_float(fs, reg, e->u.nval); + break; + } + case VKINT: { + luaK_int(fs, reg, e->u.ival); + break; + } + case VRELOC: { + Instruction *pc = &getinstruction(fs, e); + SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ + break; + } + case VNONRELOC: { + if (reg != e->u.info) + luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); + break; + } + default: { + lua_assert(e->k == VJMP); + return; /* nothing to do... */ + } + } + e->u.info = reg; + e->k = VNONRELOC; +} + + +/* +** Ensure expression value is in a register, making 'e' a +** non-relocatable expression. +** (Expression still may have jump lists.) +*/ +static void discharge2anyreg (FuncState *fs, expdesc *e) { + if (e->k != VNONRELOC) { /* no fixed register yet? */ + luaK_reserveregs(fs, 1); /* get a register */ + discharge2reg(fs, e, fs->freereg-1); /* put value there */ + } +} + + +static int code_loadbool (FuncState *fs, int A, OpCode op) { + luaK_getlabel(fs); /* those instructions may be jump targets */ + return luaK_codeABC(fs, op, A, 0, 0); +} + + +/* +** check whether list has any jump that do not produce a value +** or produce an inverted value +*/ +static int need_value (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) { + Instruction i = *getjumpcontrol(fs, list); + if (GET_OPCODE(i) != OP_TESTSET) return 1; + } + return 0; /* not found */ +} + + +/* +** Ensures final expression result (which includes results from its +** jump lists) is in register 'reg'. +** If expression has jumps, need to patch these jumps either to +** its final position or to "load" instructions (for those tests +** that do not produce values). +*/ +static void exp2reg (FuncState *fs, expdesc *e, int reg) { + discharge2reg(fs, e, reg); + if (e->k == VJMP) /* expression itself is a test? */ + luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ + if (hasjumps(e)) { + int final; /* position after whole expression */ + int p_f = NO_JUMP; /* position of an eventual LOAD false */ + int p_t = NO_JUMP; /* position of an eventual LOAD true */ + if (need_value(fs, e->t) || need_value(fs, e->f)) { + int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); + p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */ + p_t = code_loadbool(fs, reg, OP_LOADTRUE); + /* jump around these booleans if 'e' is not a test */ + luaK_patchtohere(fs, fj); + } + final = luaK_getlabel(fs); + patchlistaux(fs, e->f, final, reg, p_f); + patchlistaux(fs, e->t, final, reg, p_t); + } + e->f = e->t = NO_JUMP; + e->u.info = reg; + e->k = VNONRELOC; +} + + +/* +** Ensures final expression result is in next available register. +*/ +void luaK_exp2nextreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + freeexp(fs, e); + luaK_reserveregs(fs, 1); + exp2reg(fs, e, fs->freereg - 1); +} + + +/* +** Ensures final expression result is in some (any) register +** and return that register. +*/ +int luaK_exp2anyreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + if (e->k == VNONRELOC) { /* expression already has a register? */ + if (!hasjumps(e)) /* no jumps? */ + return e->u.info; /* result is already in a register */ + if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */ + exp2reg(fs, e, e->u.info); /* put final result in it */ + return e->u.info; + } + /* else expression has jumps and cannot change its register + to hold the jump values, because it is a local variable. + Go through to the default case. */ + } + luaK_exp2nextreg(fs, e); /* default: use next available register */ + return e->u.info; +} + + +/* +** Ensures final expression result is either in a register +** or in an upvalue. +*/ +void luaK_exp2anyregup (FuncState *fs, expdesc *e) { + if (e->k != VUPVAL || hasjumps(e)) + luaK_exp2anyreg(fs, e); +} + + +/* +** Ensures final expression result is either in a register +** or it is a constant. +*/ +void luaK_exp2val (FuncState *fs, expdesc *e) { + if (hasjumps(e)) + luaK_exp2anyreg(fs, e); + else + luaK_dischargevars(fs, e); +} + + +/* +** Try to make 'e' a K expression with an index in the range of R/K +** indices. Return true iff succeeded. +*/ +static int luaK_exp2K (FuncState *fs, expdesc *e) { + if (!hasjumps(e)) { + int info; + switch (e->k) { /* move constants to 'k' */ + case VTRUE: info = boolT(fs); break; + case VFALSE: info = boolF(fs); break; + case VNIL: info = nilK(fs); break; + case VKINT: info = luaK_intK(fs, e->u.ival); break; + case VKFLT: info = luaK_numberK(fs, e->u.nval); break; + case VKSTR: info = stringK(fs, e->u.strval); break; + case VK: info = e->u.info; break; + default: return 0; /* not a constant */ + } + if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */ + e->k = VK; /* make expression a 'K' expression */ + e->u.info = info; + return 1; + } + } + /* else, expression doesn't fit; leave it unchanged */ + return 0; +} + + +/* +** Ensures final expression result is in a valid R/K index +** (that is, it is either in a register or in 'k' with an index +** in the range of R/K indices). +** Returns 1 iff expression is K. +*/ +int luaK_exp2RK (FuncState *fs, expdesc *e) { + if (luaK_exp2K(fs, e)) + return 1; + else { /* not a constant in the right range: put it in a register */ + luaK_exp2anyreg(fs, e); + return 0; + } +} + + +static void codeABRK (FuncState *fs, OpCode o, int a, int b, + expdesc *ec) { + int k = luaK_exp2RK(fs, ec); + luaK_codeABCk(fs, o, a, b, ec->u.info, k); +} + + +/* +** Generate code to store result of expression 'ex' into variable 'var'. +*/ +void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { + switch (var->k) { + case VLOCAL: { + freeexp(fs, ex); + exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */ + return; + } + case VUPVAL: { + int e = luaK_exp2anyreg(fs, ex); + luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); + break; + } + case VINDEXUP: { + codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex); + break; + } + case VINDEXI: { + codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex); + break; + } + case VINDEXSTR: { + codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex); + break; + } + case VINDEXED: { + codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex); + break; + } + default: lua_assert(0); /* invalid var kind to store */ + } + freeexp(fs, ex); +} + + +/* +** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). +*/ +void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { + int ereg; + luaK_exp2anyreg(fs, e); + ereg = e->u.info; /* register where 'e' was placed */ + freeexp(fs, e); + e->u.info = fs->freereg; /* base register for op_self */ + e->k = VNONRELOC; /* self expression has a fixed register */ + luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ + codeABRK(fs, OP_SELF, e->u.info, ereg, key); + freeexp(fs, key); +} + + +/* +** Negate condition 'e' (where 'e' is a comparison). +*/ +static void negatecondition (FuncState *fs, expdesc *e) { + Instruction *pc = getjumpcontrol(fs, e->u.info); + lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && + GET_OPCODE(*pc) != OP_TEST); + SETARG_k(*pc, (GETARG_k(*pc) ^ 1)); +} + + +/* +** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' +** is true, code will jump if 'e' is true.) Return jump position. +** Optimize when 'e' is 'not' something, inverting the condition +** and removing the 'not'. +*/ +static int jumponcond (FuncState *fs, expdesc *e, int cond) { + if (e->k == VRELOC) { + Instruction ie = getinstruction(fs, e); + if (GET_OPCODE(ie) == OP_NOT) { + removelastinstruction(fs); /* remove previous OP_NOT */ + return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond); + } + /* else go through */ + } + discharge2anyreg(fs, e); + freeexp(fs, e); + return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond); +} + + +/* +** Emit code to go through if 'e' is true, jump otherwise. +*/ +void luaK_goiftrue (FuncState *fs, expdesc *e) { + int pc; /* pc of new jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { /* condition? */ + negatecondition(fs, e); /* jump when it is false */ + pc = e->u.info; /* save jump position */ + break; + } + case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { + pc = NO_JUMP; /* always true; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 0); /* jump when false */ + break; + } + } + luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ + luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ + e->t = NO_JUMP; +} + + +/* +** Emit code to go through if 'e' is false, jump otherwise. +*/ +void luaK_goiffalse (FuncState *fs, expdesc *e) { + int pc; /* pc of new jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VJMP: { + pc = e->u.info; /* already jump if true */ + break; + } + case VNIL: case VFALSE: { + pc = NO_JUMP; /* always false; do nothing */ + break; + } + default: { + pc = jumponcond(fs, e, 1); /* jump if true */ + break; + } + } + luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ + luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ + e->f = NO_JUMP; +} + + +/* +** Code 'not e', doing constant folding. +*/ +static void codenot (FuncState *fs, expdesc *e) { + switch (e->k) { + case VNIL: case VFALSE: { + e->k = VTRUE; /* true == not nil == not false */ + break; + } + case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { + e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ + break; + } + case VJMP: { + negatecondition(fs, e); + break; + } + case VRELOC: + case VNONRELOC: { + discharge2anyreg(fs, e); + freeexp(fs, e); + e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); + e->k = VRELOC; + break; + } + default: lua_assert(0); /* cannot happen */ + } + /* interchange true and false lists */ + { int temp = e->f; e->f = e->t; e->t = temp; } + removevalues(fs, e->f); /* values are useless when negated */ + removevalues(fs, e->t); +} + + +/* +** Check whether expression 'e' is a small literal string +*/ +static int isKstr (FuncState *fs, expdesc *e) { + return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B && + ttisshrstring(&fs->f->k[e->u.info])); +} + +/* +** Check whether expression 'e' is a literal integer. +*/ +int luaK_isKint (expdesc *e) { + return (e->k == VKINT && !hasjumps(e)); +} + + +/* +** Check whether expression 'e' is a literal integer in +** proper range to fit in register C +*/ +static int isCint (expdesc *e) { + return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C)); +} + + +/* +** Check whether expression 'e' is a literal integer in +** proper range to fit in register sC +*/ +static int isSCint (expdesc *e) { + return luaK_isKint(e) && fitsC(e->u.ival); +} + + +/* +** Check whether expression 'e' is a literal integer or float in +** proper range to fit in a register (sB or sC). +*/ +static int isSCnumber (expdesc *e, int *pi, int *isfloat) { + lua_Integer i; + if (e->k == VKINT) + i = e->u.ival; + else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq)) + *isfloat = 1; + else + return 0; /* not a number */ + if (!hasjumps(e) && fitsC(i)) { + *pi = int2sC(cast_int(i)); + return 1; + } + else + return 0; +} + + +/* +** Create expression 't[k]'. 't' must have its final result already in a +** register or upvalue. Upvalues can only be indexed by literal strings. +** Keys can be literal strings in the constant table or arbitrary +** values in registers. +*/ +void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { + if (k->k == VKSTR) + str2K(fs, k); + lua_assert(!hasjumps(t) && + (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL)); + if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */ + luaK_exp2anyreg(fs, t); /* put it in a register */ + if (t->k == VUPVAL) { + t->u.ind.t = t->u.info; /* upvalue index */ + t->u.ind.idx = k->u.info; /* literal string */ + t->k = VINDEXUP; + } + else { + /* register index of the table */ + t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info; + if (isKstr(fs, k)) { + t->u.ind.idx = k->u.info; /* literal string */ + t->k = VINDEXSTR; + } + else if (isCint(k)) { + t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */ + t->k = VINDEXI; + } + else { + t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */ + t->k = VINDEXED; + } + } +} + + +/* +** Return false if folding can raise an error. +** Bitwise operations need operands convertible to integers; division +** operations cannot have 0 as divisor. +*/ +static int validop (int op, TValue *v1, TValue *v2) { + switch (op) { + case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: + case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ + lua_Integer i; + return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) && + luaV_tointegerns(v2, &i, LUA_FLOORN2I)); + } + case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ + return (nvalue(v2) != 0); + default: return 1; /* everything else is valid */ + } +} + + +/* +** Try to "constant-fold" an operation; return 1 iff successful. +** (In this case, 'e1' has the final result.) +*/ +static int constfolding (FuncState *fs, int op, expdesc *e1, + const expdesc *e2) { + TValue v1, v2, res; + if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) + return 0; /* non-numeric operands or not safe to fold */ + luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ + if (ttisinteger(&res)) { + e1->k = VKINT; + e1->u.ival = ivalue(&res); + } + else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ + lua_Number n = fltvalue(&res); + if (luai_numisnan(n) || n == 0) + return 0; + e1->k = VKFLT; + e1->u.nval = n; + } + return 1; +} + + +/* +** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP) +*/ +l_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) { + lua_assert(baser <= opr && + ((baser == OPR_ADD && opr <= OPR_SHR) || + (baser == OPR_LT && opr <= OPR_LE))); + return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base)); +} + + +/* +** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP) +*/ +l_sinline OpCode unopr2op (UnOpr opr) { + return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) + + cast_int(OP_UNM)); +} + + +/* +** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM) +*/ +l_sinline TMS binopr2TM (BinOpr opr) { + lua_assert(OPR_ADD <= opr && opr <= OPR_SHR); + return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD)); +} + + +/* +** Emit code for unary expressions that "produce values" +** (everything but 'not'). +** Expression to produce final result will be encoded in 'e'. +*/ +static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { + int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ + freeexp(fs, e); + e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ + e->k = VRELOC; /* all those operations are relocatable */ + luaK_fixline(fs, line); +} + + +/* +** Emit code for binary expressions that "produce values" +** (everything but logical operators 'and'/'or' and comparison +** operators). +** Expression to produce final result will be encoded in 'e1'. +*/ +static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2, + OpCode op, int v2, int flip, int line, + OpCode mmop, TMS event) { + int v1 = luaK_exp2anyreg(fs, e1); + int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0); + freeexps(fs, e1, e2); + e1->u.info = pc; + e1->k = VRELOC; /* all those operations are relocatable */ + luaK_fixline(fs, line); + luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */ + luaK_fixline(fs, line); +} + + +/* +** Emit code for binary expressions that "produce values" over +** two registers. +*/ +static void codebinexpval (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int line) { + OpCode op = binopr2op(opr, OPR_ADD, OP_ADD); + int v2 = luaK_exp2anyreg(fs, e2); /* make sure 'e2' is in a register */ + /* 'e1' must be already in a register or it is a constant */ + lua_assert((VNIL <= e1->k && e1->k <= VKSTR) || + e1->k == VNONRELOC || e1->k == VRELOC); + lua_assert(OP_ADD <= op && op <= OP_SHR); + finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr)); +} + + +/* +** Code binary operators with immediate operands. +*/ +static void codebini (FuncState *fs, OpCode op, + expdesc *e1, expdesc *e2, int flip, int line, + TMS event) { + int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */ + lua_assert(e2->k == VKINT); + finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event); +} + + +/* +** Code binary operators with K operand. +*/ +static void codebinK (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int flip, int line) { + TMS event = binopr2TM(opr); + int v2 = e2->u.info; /* K index */ + OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK); + finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event); +} + + +/* Try to code a binary operator negating its second operand. +** For the metamethod, 2nd operand must keep its original value. +*/ +static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, + OpCode op, int line, TMS event) { + if (!luaK_isKint(e2)) + return 0; /* not an integer constant */ + else { + lua_Integer i2 = e2->u.ival; + if (!(fitsC(i2) && fitsC(-i2))) + return 0; /* not in the proper range */ + else { /* operating a small integer constant */ + int v2 = cast_int(i2); + finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); + /* correct metamethod argument */ + SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2)); + return 1; /* successfully coded */ + } + } +} + + +static void swapexps (expdesc *e1, expdesc *e2) { + expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */ +} + + +/* +** Code binary operators with no constant operand. +*/ +static void codebinNoK (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int flip, int line) { + if (flip) + swapexps(e1, e2); /* back to original order */ + codebinexpval(fs, opr, e1, e2, line); /* use standard operators */ +} + + +/* +** Code arithmetic operators ('+', '-', ...). If second operand is a +** constant in the proper range, use variant opcodes with K operands. +*/ +static void codearith (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int flip, int line) { + if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) /* K operand? */ + codebinK(fs, opr, e1, e2, flip, line); + else /* 'e2' is neither an immediate nor a K operand */ + codebinNoK(fs, opr, e1, e2, flip, line); +} + + +/* +** Code commutative operators ('+', '*'). If first operand is a +** numeric constant, change order of operands to try to use an +** immediate or K operator. +*/ +static void codecommutative (FuncState *fs, BinOpr op, + expdesc *e1, expdesc *e2, int line) { + int flip = 0; + if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */ + swapexps(e1, e2); /* change order */ + flip = 1; + } + if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */ + codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD); + else + codearith(fs, op, e1, e2, flip, line); +} + + +/* +** Code bitwise operations; they are all commutative, so the function +** tries to put an integer constant as the 2nd operand (a K operand). +*/ +static void codebitwise (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int line) { + int flip = 0; + if (e1->k == VKINT) { + swapexps(e1, e2); /* 'e2' will be the constant operand */ + flip = 1; + } + if (e2->k == VKINT && luaK_exp2K(fs, e2)) /* K operand? */ + codebinK(fs, opr, e1, e2, flip, line); + else /* no constants */ + codebinNoK(fs, opr, e1, e2, flip, line); +} + + +/* +** Emit code for order comparisons. When using an immediate operand, +** 'isfloat' tells whether the original value was a float. +*/ +static void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { + int r1, r2; + int im; + int isfloat = 0; + OpCode op; + if (isSCnumber(e2, &im, &isfloat)) { + /* use immediate operand */ + r1 = luaK_exp2anyreg(fs, e1); + r2 = im; + op = binopr2op(opr, OPR_LT, OP_LTI); + } + else if (isSCnumber(e1, &im, &isfloat)) { + /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */ + r1 = luaK_exp2anyreg(fs, e2); + r2 = im; + op = binopr2op(opr, OPR_LT, OP_GTI); + } + else { /* regular case, compare two registers */ + r1 = luaK_exp2anyreg(fs, e1); + r2 = luaK_exp2anyreg(fs, e2); + op = binopr2op(opr, OPR_LT, OP_LT); + } + freeexps(fs, e1, e2); + e1->u.info = condjump(fs, op, r1, r2, isfloat, 1); + e1->k = VJMP; +} + + +/* +** Emit code for equality comparisons ('==', '~='). +** 'e1' was already put as RK by 'luaK_infix'. +*/ +static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { + int r1, r2; + int im; + int isfloat = 0; /* not needed here, but kept for symmetry */ + OpCode op; + if (e1->k != VNONRELOC) { + lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT); + swapexps(e1, e2); + } + r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */ + if (isSCnumber(e2, &im, &isfloat)) { + op = OP_EQI; + r2 = im; /* immediate operand */ + } + else if (luaK_exp2RK(fs, e2)) { /* 2nd expression is constant? */ + op = OP_EQK; + r2 = e2->u.info; /* constant index */ + } + else { + op = OP_EQ; /* will compare two registers */ + r2 = luaK_exp2anyreg(fs, e2); + } + freeexps(fs, e1, e2); + e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ)); + e1->k = VJMP; +} + + +/* +** Apply prefix operation 'op' to expression 'e'. +*/ +void luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) { + static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; + luaK_dischargevars(fs, e); + switch (opr) { + case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ + if (constfolding(fs, opr + LUA_OPUNM, e, &ef)) + break; + /* else */ /* FALLTHROUGH */ + case OPR_LEN: + codeunexpval(fs, unopr2op(opr), e, line); + break; + case OPR_NOT: codenot(fs, e); break; + default: lua_assert(0); + } +} + + +/* +** Process 1st operand 'v' of binary operation 'op' before reading +** 2nd operand. +*/ +void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { + luaK_dischargevars(fs, v); + switch (op) { + case OPR_AND: { + luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ + break; + } + case OPR_OR: { + luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ + break; + } + case OPR_CONCAT: { + luaK_exp2nextreg(fs, v); /* operand must be on the stack */ + break; + } + case OPR_ADD: case OPR_SUB: + case OPR_MUL: case OPR_DIV: case OPR_IDIV: + case OPR_MOD: case OPR_POW: + case OPR_BAND: case OPR_BOR: case OPR_BXOR: + case OPR_SHL: case OPR_SHR: { + if (!tonumeral(v, NULL)) + luaK_exp2anyreg(fs, v); + /* else keep numeral, which may be folded or used as an immediate + operand */ + break; + } + case OPR_EQ: case OPR_NE: { + if (!tonumeral(v, NULL)) + luaK_exp2RK(fs, v); + /* else keep numeral, which may be an immediate operand */ + break; + } + case OPR_LT: case OPR_LE: + case OPR_GT: case OPR_GE: { + int dummy, dummy2; + if (!isSCnumber(v, &dummy, &dummy2)) + luaK_exp2anyreg(fs, v); + /* else keep numeral, which may be an immediate operand */ + break; + } + default: lua_assert(0); + } +} + +/* +** Create code for '(e1 .. e2)'. +** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))', +** because concatenation is right associative), merge both CONCATs. +*/ +static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) { + Instruction *ie2 = previousinstruction(fs); + if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */ + int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */ + lua_assert(e1->u.info + 1 == GETARG_A(*ie2)); + freeexp(fs, e2); + SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */ + SETARG_B(*ie2, n + 1); /* will concatenate one more element */ + } + else { /* 'e2' is not a concatenation */ + luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */ + freeexp(fs, e2); + luaK_fixline(fs, line); + } +} + + +/* +** Finalize code for binary operation, after reading 2nd operand. +*/ +void luaK_posfix (FuncState *fs, BinOpr opr, + expdesc *e1, expdesc *e2, int line) { + luaK_dischargevars(fs, e2); + if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2)) + return; /* done by folding */ + switch (opr) { + case OPR_AND: { + lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */ + luaK_concat(fs, &e2->f, e1->f); + *e1 = *e2; + break; + } + case OPR_OR: { + lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */ + luaK_concat(fs, &e2->t, e1->t); + *e1 = *e2; + break; + } + case OPR_CONCAT: { /* e1 .. e2 */ + luaK_exp2nextreg(fs, e2); + codeconcat(fs, e1, e2, line); + break; + } + case OPR_ADD: case OPR_MUL: { + codecommutative(fs, opr, e1, e2, line); + break; + } + case OPR_SUB: { + if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB)) + break; /* coded as (r1 + -I) */ + /* ELSE */ + } /* FALLTHROUGH */ + case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: { + codearith(fs, opr, e1, e2, 0, line); + break; + } + case OPR_BAND: case OPR_BOR: case OPR_BXOR: { + codebitwise(fs, opr, e1, e2, line); + break; + } + case OPR_SHL: { + if (isSCint(e1)) { + swapexps(e1, e2); + codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */ + } + else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) { + /* coded as (r1 >> -I) */; + } + else /* regular case (two registers) */ + codebinexpval(fs, opr, e1, e2, line); + break; + } + case OPR_SHR: { + if (isSCint(e2)) + codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */ + else /* regular case (two registers) */ + codebinexpval(fs, opr, e1, e2, line); + break; + } + case OPR_EQ: case OPR_NE: { + codeeq(fs, opr, e1, e2); + break; + } + case OPR_GT: case OPR_GE: { + /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */ + swapexps(e1, e2); + opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT); + } /* FALLTHROUGH */ + case OPR_LT: case OPR_LE: { + codeorder(fs, opr, e1, e2); + break; + } + default: lua_assert(0); + } +} + + +/* +** Change line information associated with current position, by removing +** previous info and adding it again with new line. +*/ +void luaK_fixline (FuncState *fs, int line) { + removelastlineinfo(fs); + savelineinfo(fs, fs->f, line); +} + + +void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) { + Instruction *inst = &fs->f->code[pc]; + int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */ + int extra = asize / (MAXARG_C + 1); /* higher bits of array size */ + int rc = asize % (MAXARG_C + 1); /* lower bits of array size */ + int k = (extra > 0); /* true iff needs extra argument */ + *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k); + *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra); +} + + +/* +** Emit a SETLIST instruction. +** 'base' is register that keeps table; +** 'nelems' is #table plus those to be stored now; +** 'tostore' is number of values (in registers 'base + 1',...) to add to +** table (or LUA_MULTRET to add up to stack top). +*/ +void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { + lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); + if (tostore == LUA_MULTRET) + tostore = 0; + if (nelems <= MAXARG_C) + luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems); + else { + int extra = nelems / (MAXARG_C + 1); + nelems %= (MAXARG_C + 1); + luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1); + codeextraarg(fs, extra); + } + fs->freereg = base + 1; /* free registers with list values */ +} + + +/* +** return the final target of a jump (skipping jumps to jumps) +*/ +static int finaltarget (Instruction *code, int i) { + int count; + for (count = 0; count < 100; count++) { /* avoid infinite loops */ + Instruction pc = code[i]; + if (GET_OPCODE(pc) != OP_JMP) + break; + else + i += GETARG_sJ(pc) + 1; + } + return i; +} + + +/* +** Do a final pass over the code of a function, doing small peephole +** optimizations and adjustments. +*/ +void luaK_finish (FuncState *fs) { + int i; + Proto *p = fs->f; + for (i = 0; i < fs->pc; i++) { + Instruction *pc = &p->code[i]; + lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc)); + switch (GET_OPCODE(*pc)) { + case OP_RETURN0: case OP_RETURN1: { + if (!(fs->needclose || p->is_vararg)) + break; /* no extra work */ + /* else use OP_RETURN to do the extra work */ + SET_OPCODE(*pc, OP_RETURN); + } /* FALLTHROUGH */ + case OP_RETURN: case OP_TAILCALL: { + if (fs->needclose) + SETARG_k(*pc, 1); /* signal that it needs to close */ + if (p->is_vararg) + SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */ + break; + } + case OP_JMP: { + int target = finaltarget(p->code, i); + fixjump(fs, i, target); + break; + } + default: break; + } + } +} diff --git a/src/libs/3rdparty/lua/src/lcode.h b/src/libs/3rdparty/lua/src/lcode.h new file mode 100644 index 00000000000..32658244526 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lcode.h @@ -0,0 +1,104 @@ +/* +** $Id: lcode.h $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lcode_h +#define lcode_h + +#include "llex.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" + + +/* +** Marks the end of a patch list. It is an invalid value both as an absolute +** address, and as a list link (would link an element to itself). +*/ +#define NO_JUMP (-1) + + +/* +** grep "ORDER OPR" if you change these enums (ORDER OP) +*/ +typedef enum BinOpr { + /* arithmetic operators */ + OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, + OPR_DIV, OPR_IDIV, + /* bitwise operators */ + OPR_BAND, OPR_BOR, OPR_BXOR, + OPR_SHL, OPR_SHR, + /* string operator */ + OPR_CONCAT, + /* comparison operators */ + OPR_EQ, OPR_LT, OPR_LE, + OPR_NE, OPR_GT, OPR_GE, + /* logical operators */ + OPR_AND, OPR_OR, + OPR_NOBINOPR +} BinOpr; + + +/* true if operation is foldable (that is, it is arithmetic or bitwise) */ +#define foldbinop(op) ((op) <= OPR_SHR) + + +#define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0) + + +typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; + + +/* get (pointer to) instruction of given 'expdesc' */ +#define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) + + +#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) + +#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) + +LUAI_FUNC int luaK_code (FuncState *fs, Instruction i); +LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); +LUAI_FUNC int luaK_codeAsBx (FuncState *fs, OpCode o, int A, int Bx); +LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A, + int B, int C, int k); +LUAI_FUNC int luaK_isKint (expdesc *e); +LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v); +LUAI_FUNC void luaK_fixline (FuncState *fs, int line); +LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); +LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); +LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); +LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n); +LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); +LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); +LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); +LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); +LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); +LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_jump (FuncState *fs); +LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); +LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); +LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); +LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); +LUAI_FUNC int luaK_getlabel (FuncState *fs); +LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); +LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); +LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, + expdesc *v2, int line); +LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc, + int ra, int asize, int hsize); +LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); +LUAI_FUNC void luaK_finish (FuncState *fs); +LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *msg); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lcorolib.c b/src/libs/3rdparty/lua/src/lcorolib.c new file mode 100644 index 00000000000..c64adf08a8e --- /dev/null +++ b/src/libs/3rdparty/lua/src/lcorolib.c @@ -0,0 +1,210 @@ +/* +** $Id: lcorolib.c $ +** Coroutine Library +** See Copyright Notice in lua.h +*/ + +#define lcorolib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static lua_State *getco (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argexpected(L, co, 1, "thread"); + return co; +} + + +/* +** Resumes a coroutine. Returns the number of results for non-error +** cases or -1 for errors. +*/ +static int auxresume (lua_State *L, lua_State *co, int narg) { + int status, nres; + if (l_unlikely(!lua_checkstack(co, narg))) { + lua_pushliteral(L, "too many arguments to resume"); + return -1; /* error flag */ + } + lua_xmove(L, co, narg); + status = lua_resume(co, L, narg, &nres); + if (l_likely(status == LUA_OK || status == LUA_YIELD)) { + if (l_unlikely(!lua_checkstack(L, nres + 1))) { + lua_pop(co, nres); /* remove results anyway */ + lua_pushliteral(L, "too many results to resume"); + return -1; /* error flag */ + } + lua_xmove(co, L, nres); /* move yielded values */ + return nres; + } + else { + lua_xmove(co, L, 1); /* move error message */ + return -1; /* error flag */ + } +} + + +static int luaB_coresume (lua_State *L) { + lua_State *co = getco(L); + int r; + r = auxresume(L, co, lua_gettop(L) - 1); + if (l_unlikely(r < 0)) { + lua_pushboolean(L, 0); + lua_insert(L, -2); + return 2; /* return false + error message */ + } + else { + lua_pushboolean(L, 1); + lua_insert(L, -(r + 1)); + return r + 1; /* return true + 'resume' returns */ + } +} + + +static int luaB_auxwrap (lua_State *L) { + lua_State *co = lua_tothread(L, lua_upvalueindex(1)); + int r = auxresume(L, co, lua_gettop(L)); + if (l_unlikely(r < 0)) { /* error? */ + int stat = lua_status(co); + if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */ + stat = lua_closethread(co, L); /* close its tbc variables */ + lua_assert(stat != LUA_OK); + lua_xmove(co, L, 1); /* move error message to the caller */ + } + if (stat != LUA_ERRMEM && /* not a memory error and ... */ + lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */ + luaL_where(L, 1); /* add extra info, if available */ + lua_insert(L, -2); + lua_concat(L, 2); + } + return lua_error(L); /* propagate error */ + } + return r; +} + + +static int luaB_cocreate (lua_State *L) { + lua_State *NL; + luaL_checktype(L, 1, LUA_TFUNCTION); + NL = lua_newthread(L); + lua_pushvalue(L, 1); /* move function to top */ + lua_xmove(L, NL, 1); /* move function from L to NL */ + return 1; +} + + +static int luaB_cowrap (lua_State *L) { + luaB_cocreate(L); + lua_pushcclosure(L, luaB_auxwrap, 1); + return 1; +} + + +static int luaB_yield (lua_State *L) { + return lua_yield(L, lua_gettop(L)); +} + + +#define COS_RUN 0 +#define COS_DEAD 1 +#define COS_YIELD 2 +#define COS_NORM 3 + + +static const char *const statname[] = + {"running", "dead", "suspended", "normal"}; + + +static int auxstatus (lua_State *L, lua_State *co) { + if (L == co) return COS_RUN; + else { + switch (lua_status(co)) { + case LUA_YIELD: + return COS_YIELD; + case LUA_OK: { + lua_Debug ar; + if (lua_getstack(co, 0, &ar)) /* does it have frames? */ + return COS_NORM; /* it is running */ + else if (lua_gettop(co) == 0) + return COS_DEAD; + else + return COS_YIELD; /* initial state */ + } + default: /* some error occurred */ + return COS_DEAD; + } + } +} + + +static int luaB_costatus (lua_State *L) { + lua_State *co = getco(L); + lua_pushstring(L, statname[auxstatus(L, co)]); + return 1; +} + + +static int luaB_yieldable (lua_State *L) { + lua_State *co = lua_isnone(L, 1) ? L : getco(L); + lua_pushboolean(L, lua_isyieldable(co)); + return 1; +} + + +static int luaB_corunning (lua_State *L) { + int ismain = lua_pushthread(L); + lua_pushboolean(L, ismain); + return 2; +} + + +static int luaB_close (lua_State *L) { + lua_State *co = getco(L); + int status = auxstatus(L, co); + switch (status) { + case COS_DEAD: case COS_YIELD: { + status = lua_closethread(co, L); + if (status == LUA_OK) { + lua_pushboolean(L, 1); + return 1; + } + else { + lua_pushboolean(L, 0); + lua_xmove(co, L, 1); /* move error message */ + return 2; + } + } + default: /* normal or running coroutine */ + return luaL_error(L, "cannot close a %s coroutine", statname[status]); + } +} + + +static const luaL_Reg co_funcs[] = { + {"create", luaB_cocreate}, + {"resume", luaB_coresume}, + {"running", luaB_corunning}, + {"status", luaB_costatus}, + {"wrap", luaB_cowrap}, + {"yield", luaB_yield}, + {"isyieldable", luaB_yieldable}, + {"close", luaB_close}, + {NULL, NULL} +}; + + + +LUAMOD_API int luaopen_coroutine (lua_State *L) { + luaL_newlib(L, co_funcs); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/lctype.c b/src/libs/3rdparty/lua/src/lctype.c new file mode 100644 index 00000000000..95422809423 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lctype.c @@ -0,0 +1,64 @@ +/* +** $Id: lctype.c $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#define lctype_c +#define LUA_CORE + +#include "lprefix.h" + + +#include "lctype.h" + +#if !LUA_USE_CTYPE /* { */ + +#include + + +#if defined (LUA_UCID) /* accept UniCode IDentifiers? */ +/* consider all non-ascii codepoints to be alphabetic */ +#define NONA 0x01 +#else +#define NONA 0x00 /* default */ +#endif + + +LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { + 0x00, /* EOZ */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ + 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ + 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, + 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ + 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + 0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */ + NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, + NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +#endif /* } */ diff --git a/src/libs/3rdparty/lua/src/lctype.h b/src/libs/3rdparty/lua/src/lctype.h new file mode 100644 index 00000000000..864e1901885 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lctype.h @@ -0,0 +1,101 @@ +/* +** $Id: lctype.h $ +** 'ctype' functions for Lua +** See Copyright Notice in lua.h +*/ + +#ifndef lctype_h +#define lctype_h + +#include "lua.h" + + +/* +** WARNING: the functions defined here do not necessarily correspond +** to the similar functions in the standard C ctype.h. They are +** optimized for the specific needs of Lua. +*/ + +#if !defined(LUA_USE_CTYPE) + +#if 'A' == 65 && '0' == 48 +/* ASCII case: can use its own tables; faster and fixed */ +#define LUA_USE_CTYPE 0 +#else +/* must use standard C ctype */ +#define LUA_USE_CTYPE 1 +#endif + +#endif + + +#if !LUA_USE_CTYPE /* { */ + +#include + +#include "llimits.h" + + +#define ALPHABIT 0 +#define DIGITBIT 1 +#define PRINTBIT 2 +#define SPACEBIT 3 +#define XDIGITBIT 4 + + +#define MASK(B) (1 << (B)) + + +/* +** add 1 to char to allow index -1 (EOZ) +*/ +#define testprop(c,p) (luai_ctype_[(c)+1] & (p)) + +/* +** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' +*/ +#define lislalpha(c) testprop(c, MASK(ALPHABIT)) +#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) +#define lisdigit(c) testprop(c, MASK(DIGITBIT)) +#define lisspace(c) testprop(c, MASK(SPACEBIT)) +#define lisprint(c) testprop(c, MASK(PRINTBIT)) +#define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) + + +/* +** In ASCII, this 'ltolower' is correct for alphabetic characters and +** for '.'. That is enough for Lua needs. ('check_exp' ensures that +** the character either is an upper-case letter or is unchanged by +** the transformation, which holds for lower-case letters and '.'.) +*/ +#define ltolower(c) \ + check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \ + (c) | ('A' ^ 'a')) + + +/* one entry for each character and for -1 (EOZ) */ +LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];) + + +#else /* }{ */ + +/* +** use standard C ctypes +*/ + +#include + + +#define lislalpha(c) (isalpha(c) || (c) == '_') +#define lislalnum(c) (isalnum(c) || (c) == '_') +#define lisdigit(c) (isdigit(c)) +#define lisspace(c) (isspace(c)) +#define lisprint(c) (isprint(c)) +#define lisxdigit(c) (isxdigit(c)) + +#define ltolower(c) (tolower(c)) + +#endif /* } */ + +#endif + diff --git a/src/libs/3rdparty/lua/src/ldblib.c b/src/libs/3rdparty/lua/src/ldblib.c new file mode 100644 index 00000000000..6dcbaa9824b --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldblib.c @@ -0,0 +1,483 @@ +/* +** $Id: ldblib.c $ +** Interface from Lua to its debug API +** See Copyright Notice in lua.h +*/ + +#define ldblib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** The hook table at registry[HOOKKEY] maps threads to their current +** hook function. +*/ +static const char *const HOOKKEY = "_HOOKKEY"; + + +/* +** If L1 != L, L1 can be in any state, and therefore there are no +** guarantees about its stack space; any push in L1 must be +** checked. +*/ +static void checkstack (lua_State *L, lua_State *L1, int n) { + if (l_unlikely(L != L1 && !lua_checkstack(L1, n))) + luaL_error(L, "stack overflow"); +} + + +static int db_getregistry (lua_State *L) { + lua_pushvalue(L, LUA_REGISTRYINDEX); + return 1; +} + + +static int db_getmetatable (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_getmetatable(L, 1)) { + lua_pushnil(L); /* no metatable */ + } + return 1; +} + + +static int db_setmetatable (lua_State *L) { + int t = lua_type(L, 2); + luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; /* return 1st argument */ +} + + +static int db_getuservalue (lua_State *L) { + int n = (int)luaL_optinteger(L, 2, 1); + if (lua_type(L, 1) != LUA_TUSERDATA) + luaL_pushfail(L); + else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) { + lua_pushboolean(L, 1); + return 2; + } + return 1; +} + + +static int db_setuservalue (lua_State *L) { + int n = (int)luaL_optinteger(L, 3, 1); + luaL_checktype(L, 1, LUA_TUSERDATA); + luaL_checkany(L, 2); + lua_settop(L, 2); + if (!lua_setiuservalue(L, 1, n)) + luaL_pushfail(L); + return 1; +} + + +/* +** Auxiliary function used by several library functions: check for +** an optional thread as function's first argument and set 'arg' with +** 1 if this argument is present (so that functions can skip it to +** access their other arguments) +*/ +static lua_State *getthread (lua_State *L, int *arg) { + if (lua_isthread(L, 1)) { + *arg = 1; + return lua_tothread(L, 1); + } + else { + *arg = 0; + return L; /* function will operate over current thread */ + } +} + + +/* +** Variations of 'lua_settable', used by 'db_getinfo' to put results +** from 'lua_getinfo' into result table. Key is always a string; +** value can be a string, an int, or a boolean. +*/ +static void settabss (lua_State *L, const char *k, const char *v) { + lua_pushstring(L, v); + lua_setfield(L, -2, k); +} + +static void settabsi (lua_State *L, const char *k, int v) { + lua_pushinteger(L, v); + lua_setfield(L, -2, k); +} + +static void settabsb (lua_State *L, const char *k, int v) { + lua_pushboolean(L, v); + lua_setfield(L, -2, k); +} + + +/* +** In function 'db_getinfo', the call to 'lua_getinfo' may push +** results on the stack; later it creates the result table to put +** these objects. Function 'treatstackoption' puts the result from +** 'lua_getinfo' on top of the result table so that it can call +** 'lua_setfield'. +*/ +static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { + if (L == L1) + lua_rotate(L, -2, 1); /* exchange object and table */ + else + lua_xmove(L1, L, 1); /* move object to the "main" stack */ + lua_setfield(L, -2, fname); /* put object into table */ +} + + +/* +** Calls 'lua_getinfo' and collects all results in a new table. +** L1 needs stack space for an optional input (function) plus +** two optional outputs (function and line table) from function +** 'lua_getinfo'. +*/ +static int db_getinfo (lua_State *L) { + lua_Debug ar; + int arg; + lua_State *L1 = getthread(L, &arg); + const char *options = luaL_optstring(L, arg+2, "flnSrtu"); + checkstack(L, L1, 3); + luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'"); + if (lua_isfunction(L, arg + 1)) { /* info about a function? */ + options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */ + lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */ + lua_xmove(L, L1, 1); + } + else { /* stack level */ + if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) { + luaL_pushfail(L); /* level out of range */ + return 1; + } + } + if (!lua_getinfo(L1, options, &ar)) + return luaL_argerror(L, arg+2, "invalid option"); + lua_newtable(L); /* table to collect results */ + if (strchr(options, 'S')) { + lua_pushlstring(L, ar.source, ar.srclen); + lua_setfield(L, -2, "source"); + settabss(L, "short_src", ar.short_src); + settabsi(L, "linedefined", ar.linedefined); + settabsi(L, "lastlinedefined", ar.lastlinedefined); + settabss(L, "what", ar.what); + } + if (strchr(options, 'l')) + settabsi(L, "currentline", ar.currentline); + if (strchr(options, 'u')) { + settabsi(L, "nups", ar.nups); + settabsi(L, "nparams", ar.nparams); + settabsb(L, "isvararg", ar.isvararg); + } + if (strchr(options, 'n')) { + settabss(L, "name", ar.name); + settabss(L, "namewhat", ar.namewhat); + } + if (strchr(options, 'r')) { + settabsi(L, "ftransfer", ar.ftransfer); + settabsi(L, "ntransfer", ar.ntransfer); + } + if (strchr(options, 't')) + settabsb(L, "istailcall", ar.istailcall); + if (strchr(options, 'L')) + treatstackoption(L, L1, "activelines"); + if (strchr(options, 'f')) + treatstackoption(L, L1, "func"); + return 1; /* return table */ +} + + +static int db_getlocal (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */ + if (lua_isfunction(L, arg + 1)) { /* function argument? */ + lua_pushvalue(L, arg + 1); /* push function */ + lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ + return 1; /* return only name (there is no value) */ + } + else { /* stack-level argument */ + lua_Debug ar; + const char *name; + int level = (int)luaL_checkinteger(L, arg + 1); + if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + checkstack(L, L1, 1); + name = lua_getlocal(L1, &ar, nvar); + if (name) { + lua_xmove(L1, L, 1); /* move local value */ + lua_pushstring(L, name); /* push name */ + lua_rotate(L, -2, 1); /* re-order */ + return 2; + } + else { + luaL_pushfail(L); /* no name (nor value) */ + return 1; + } + } +} + + +static int db_setlocal (lua_State *L) { + int arg; + const char *name; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + int level = (int)luaL_checkinteger(L, arg + 1); + int nvar = (int)luaL_checkinteger(L, arg + 2); + if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + luaL_checkany(L, arg+3); + lua_settop(L, arg+3); + checkstack(L, L1, 1); + lua_xmove(L, L1, 1); + name = lua_setlocal(L1, &ar, nvar); + if (name == NULL) + lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */ + lua_pushstring(L, name); + return 1; +} + + +/* +** get (if 'get' is true) or set an upvalue from a closure +*/ +static int auxupvalue (lua_State *L, int get) { + const char *name; + int n = (int)luaL_checkinteger(L, 2); /* upvalue index */ + luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */ + name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); + if (name == NULL) return 0; + lua_pushstring(L, name); + lua_insert(L, -(get+1)); /* no-op if get is false */ + return get + 1; +} + + +static int db_getupvalue (lua_State *L) { + return auxupvalue(L, 1); +} + + +static int db_setupvalue (lua_State *L) { + luaL_checkany(L, 3); + return auxupvalue(L, 0); +} + + +/* +** Check whether a given upvalue from a given closure exists and +** returns its index +*/ +static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) { + void *id; + int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */ + luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */ + id = lua_upvalueid(L, argf, nup); + if (pnup) { + luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index"); + *pnup = nup; + } + return id; +} + + +static int db_upvalueid (lua_State *L) { + void *id = checkupval(L, 1, 2, NULL); + if (id != NULL) + lua_pushlightuserdata(L, id); + else + luaL_pushfail(L); + return 1; +} + + +static int db_upvaluejoin (lua_State *L) { + int n1, n2; + checkupval(L, 1, 2, &n1); + checkupval(L, 3, 4, &n2); + luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); + luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); + lua_upvaluejoin(L, 1, n1, 3, n2); + return 0; +} + + +/* +** Call hook function registered at hook table for the current +** thread (if there is one) +*/ +static void hookf (lua_State *L, lua_Debug *ar) { + static const char *const hooknames[] = + {"call", "return", "line", "count", "tail call"}; + lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); + lua_pushthread(L); + if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */ + lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */ + if (ar->currentline >= 0) + lua_pushinteger(L, ar->currentline); /* push current line */ + else lua_pushnil(L); + lua_assert(lua_getinfo(L, "lS", ar)); + lua_call(L, 2, 0); /* call hook function */ + } +} + + +/* +** Convert a string mask (for 'sethook') into a bit mask +*/ +static int makemask (const char *smask, int count) { + int mask = 0; + if (strchr(smask, 'c')) mask |= LUA_MASKCALL; + if (strchr(smask, 'r')) mask |= LUA_MASKRET; + if (strchr(smask, 'l')) mask |= LUA_MASKLINE; + if (count > 0) mask |= LUA_MASKCOUNT; + return mask; +} + + +/* +** Convert a bit mask (for 'gethook') into a string mask +*/ +static char *unmakemask (int mask, char *smask) { + int i = 0; + if (mask & LUA_MASKCALL) smask[i++] = 'c'; + if (mask & LUA_MASKRET) smask[i++] = 'r'; + if (mask & LUA_MASKLINE) smask[i++] = 'l'; + smask[i] = '\0'; + return smask; +} + + +static int db_sethook (lua_State *L) { + int arg, mask, count; + lua_Hook func; + lua_State *L1 = getthread(L, &arg); + if (lua_isnoneornil(L, arg+1)) { /* no hook? */ + lua_settop(L, arg+1); + func = NULL; mask = 0; count = 0; /* turn off hooks */ + } + else { + const char *smask = luaL_checkstring(L, arg+2); + luaL_checktype(L, arg+1, LUA_TFUNCTION); + count = (int)luaL_optinteger(L, arg + 3, 0); + func = hookf; mask = makemask(smask, count); + } + if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) { + /* table just created; initialize it */ + lua_pushliteral(L, "k"); + lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ + lua_pushvalue(L, -1); + lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */ + } + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */ + lua_pushvalue(L, arg + 1); /* value (hook function) */ + lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */ + lua_sethook(L1, func, mask, count); + return 0; +} + + +static int db_gethook (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + char buff[5]; + int mask = lua_gethookmask(L1); + lua_Hook hook = lua_gethook(L1); + if (hook == NULL) { /* no hook? */ + luaL_pushfail(L); + return 1; + } + else if (hook != hookf) /* external hook? */ + lua_pushliteral(L, "external hook"); + else { /* hook table must exist */ + lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); + checkstack(L, L1, 1); + lua_pushthread(L1); lua_xmove(L1, L, 1); + lua_rawget(L, -2); /* 1st result = hooktable[L1] */ + lua_remove(L, -2); /* remove hook table */ + } + lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */ + lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */ + return 3; +} + + +static int db_debug (lua_State *L) { + for (;;) { + char buffer[250]; + lua_writestringerror("%s", "lua_debug> "); + if (fgets(buffer, sizeof(buffer), stdin) == NULL || + strcmp(buffer, "cont\n") == 0) + return 0; + if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || + lua_pcall(L, 0, 0, 0)) + lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL)); + lua_settop(L, 0); /* remove eventual returns */ + } +} + + +static int db_traceback (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + const char *msg = lua_tostring(L, arg + 1); + if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ + lua_pushvalue(L, arg + 1); /* return it untouched */ + else { + int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0); + luaL_traceback(L, L1, msg, level); + } + return 1; +} + + +static int db_setcstacklimit (lua_State *L) { + int limit = (int)luaL_checkinteger(L, 1); + int res = lua_setcstacklimit(L, limit); + lua_pushinteger(L, res); + return 1; +} + + +static const luaL_Reg dblib[] = { + {"debug", db_debug}, + {"getuservalue", db_getuservalue}, + {"gethook", db_gethook}, + {"getinfo", db_getinfo}, + {"getlocal", db_getlocal}, + {"getregistry", db_getregistry}, + {"getmetatable", db_getmetatable}, + {"getupvalue", db_getupvalue}, + {"upvaluejoin", db_upvaluejoin}, + {"upvalueid", db_upvalueid}, + {"setuservalue", db_setuservalue}, + {"sethook", db_sethook}, + {"setlocal", db_setlocal}, + {"setmetatable", db_setmetatable}, + {"setupvalue", db_setupvalue}, + {"traceback", db_traceback}, + {"setcstacklimit", db_setcstacklimit}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_debug (lua_State *L) { + luaL_newlib(L, dblib); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/ldebug.c b/src/libs/3rdparty/lua/src/ldebug.c new file mode 100644 index 00000000000..28b1caabf77 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldebug.c @@ -0,0 +1,924 @@ +/* +** $Id: ldebug.c $ +** Debug Interface +** See Copyright Notice in lua.h +*/ + +#define ldebug_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + + +#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_VCCL) + + +static const char *funcnamefromcall (lua_State *L, CallInfo *ci, + const char **name); + + +static int currentpc (CallInfo *ci) { + lua_assert(isLua(ci)); + return pcRel(ci->u.l.savedpc, ci_func(ci)->p); +} + + +/* +** Get a "base line" to find the line corresponding to an instruction. +** Base lines are regularly placed at MAXIWTHABS intervals, so usually +** an integer division gets the right place. When the source file has +** large sequences of empty/comment lines, it may need extra entries, +** so the original estimate needs a correction. +** If the original estimate is -1, the initial 'if' ensures that the +** 'while' will run at least once. +** The assertion that the estimate is a lower bound for the correct base +** is valid as long as the debug info has been generated with the same +** value for MAXIWTHABS or smaller. (Previous releases use a little +** smaller value.) +*/ +static int getbaseline (const Proto *f, int pc, int *basepc) { + if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) { + *basepc = -1; /* start from the beginning */ + return f->linedefined; + } + else { + int i = cast_uint(pc) / MAXIWTHABS - 1; /* get an estimate */ + /* estimate must be a lower bound of the correct base */ + lua_assert(i < 0 || + (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc)); + while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc) + i++; /* low estimate; adjust it */ + *basepc = f->abslineinfo[i].pc; + return f->abslineinfo[i].line; + } +} + + +/* +** Get the line corresponding to instruction 'pc' in function 'f'; +** first gets a base line and from there does the increments until +** the desired instruction. +*/ +int luaG_getfuncline (const Proto *f, int pc) { + if (f->lineinfo == NULL) /* no debug information? */ + return -1; + else { + int basepc; + int baseline = getbaseline(f, pc, &basepc); + while (basepc++ < pc) { /* walk until given instruction */ + lua_assert(f->lineinfo[basepc] != ABSLINEINFO); + baseline += f->lineinfo[basepc]; /* correct line */ + } + return baseline; + } +} + + +static int getcurrentline (CallInfo *ci) { + return luaG_getfuncline(ci_func(ci)->p, currentpc(ci)); +} + + +/* +** Set 'trap' for all active Lua frames. +** This function can be called during a signal, under "reasonable" +** assumptions. A new 'ci' is completely linked in the list before it +** becomes part of the "active" list, and we assume that pointers are +** atomic; see comment in next function. +** (A compiler doing interprocedural optimizations could, theoretically, +** reorder memory writes in such a way that the list could be +** temporarily broken while inserting a new element. We simply assume it +** has no good reasons to do that.) +*/ +static void settraps (CallInfo *ci) { + for (; ci != NULL; ci = ci->previous) + if (isLua(ci)) + ci->u.l.trap = 1; +} + + +/* +** This function can be called during a signal, under "reasonable" +** assumptions. +** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount') +** are for debug only, and it is no problem if they get arbitrary +** values (causes at most one wrong hook call). 'hookmask' is an atomic +** value. We assume that pointers are atomic too (e.g., gcc ensures that +** for all platforms where it runs). Moreover, 'hook' is always checked +** before being called (see 'luaD_hook'). +*/ +LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { + if (func == NULL || mask == 0) { /* turn off hooks? */ + mask = 0; + func = NULL; + } + L->hook = func; + L->basehookcount = count; + resethookcount(L); + L->hookmask = cast_byte(mask); + if (mask) + settraps(L->ci); /* to trace inside 'luaV_execute' */ +} + + +LUA_API lua_Hook lua_gethook (lua_State *L) { + return L->hook; +} + + +LUA_API int lua_gethookmask (lua_State *L) { + return L->hookmask; +} + + +LUA_API int lua_gethookcount (lua_State *L) { + return L->basehookcount; +} + + +LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { + int status; + CallInfo *ci; + if (level < 0) return 0; /* invalid (negative) level */ + lua_lock(L); + for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) + level--; + if (level == 0 && ci != &L->base_ci) { /* level found? */ + status = 1; + ar->i_ci = ci; + } + else status = 0; /* no such level */ + lua_unlock(L); + return status; +} + + +static const char *upvalname (const Proto *p, int uv) { + TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); + if (s == NULL) return "?"; + else return getstr(s); +} + + +static const char *findvararg (CallInfo *ci, int n, StkId *pos) { + if (clLvalue(s2v(ci->func.p))->p->is_vararg) { + int nextra = ci->u.l.nextraargs; + if (n >= -nextra) { /* 'n' is negative */ + *pos = ci->func.p - nextra - (n + 1); + return "(vararg)"; /* generic name for any vararg */ + } + } + return NULL; /* no such vararg */ +} + + +const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { + StkId base = ci->func.p + 1; + const char *name = NULL; + if (isLua(ci)) { + if (n < 0) /* access to vararg values? */ + return findvararg(ci, n, pos); + else + name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); + } + if (name == NULL) { /* no 'standard' name? */ + StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p; + if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */ + /* generic name for any valid slot */ + name = isLua(ci) ? "(temporary)" : "(C temporary)"; + } + else + return NULL; /* no name */ + } + if (pos) + *pos = base + (n - 1); + return name; +} + + +LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { + const char *name; + lua_lock(L); + if (ar == NULL) { /* information about non-active function? */ + if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */ + name = NULL; + else /* consider live variables at function start (parameters) */ + name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0); + } + else { /* active function; get information through 'ar' */ + StkId pos = NULL; /* to avoid warnings */ + name = luaG_findlocal(L, ar->i_ci, n, &pos); + if (name) { + setobjs2s(L, L->top.p, pos); + api_incr_top(L); + } + } + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { + StkId pos = NULL; /* to avoid warnings */ + const char *name; + lua_lock(L); + name = luaG_findlocal(L, ar->i_ci, n, &pos); + if (name) { + setobjs2s(L, pos, L->top.p - 1); + L->top.p--; /* pop value */ + } + lua_unlock(L); + return name; +} + + +static void funcinfo (lua_Debug *ar, Closure *cl) { + if (noLuaClosure(cl)) { + ar->source = "=[C]"; + ar->srclen = LL("=[C]"); + ar->linedefined = -1; + ar->lastlinedefined = -1; + ar->what = "C"; + } + else { + const Proto *p = cl->l.p; + if (p->source) { + ar->source = getstr(p->source); + ar->srclen = tsslen(p->source); + } + else { + ar->source = "=?"; + ar->srclen = LL("=?"); + } + ar->linedefined = p->linedefined; + ar->lastlinedefined = p->lastlinedefined; + ar->what = (ar->linedefined == 0) ? "main" : "Lua"; + } + luaO_chunkid(ar->short_src, ar->source, ar->srclen); +} + + +static int nextline (const Proto *p, int currentline, int pc) { + if (p->lineinfo[pc] != ABSLINEINFO) + return currentline + p->lineinfo[pc]; + else + return luaG_getfuncline(p, pc); +} + + +static void collectvalidlines (lua_State *L, Closure *f) { + if (noLuaClosure(f)) { + setnilvalue(s2v(L->top.p)); + api_incr_top(L); + } + else { + int i; + TValue v; + const Proto *p = f->l.p; + int currentline = p->linedefined; + Table *t = luaH_new(L); /* new table to store active lines */ + sethvalue2s(L, L->top.p, t); /* push it on stack */ + api_incr_top(L); + setbtvalue(&v); /* boolean 'true' to be the value of all indices */ + if (!p->is_vararg) /* regular function? */ + i = 0; /* consider all instructions */ + else { /* vararg function */ + lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP); + currentline = nextline(p, currentline, 0); + i = 1; /* skip first instruction (OP_VARARGPREP) */ + } + for (; i < p->sizelineinfo; i++) { /* for each instruction */ + currentline = nextline(p, currentline, i); /* get its line */ + luaH_setint(L, t, currentline, &v); /* table[line] = true */ + } + } +} + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { + /* calling function is a known function? */ + if (ci != NULL && !(ci->callstatus & CIST_TAIL)) + return funcnamefromcall(L, ci->previous, name); + else return NULL; /* no way to find a name */ +} + + +static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, + Closure *f, CallInfo *ci) { + int status = 1; + for (; *what; what++) { + switch (*what) { + case 'S': { + funcinfo(ar, f); + break; + } + case 'l': { + ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1; + break; + } + case 'u': { + ar->nups = (f == NULL) ? 0 : f->c.nupvalues; + if (noLuaClosure(f)) { + ar->isvararg = 1; + ar->nparams = 0; + } + else { + ar->isvararg = f->l.p->is_vararg; + ar->nparams = f->l.p->numparams; + } + break; + } + case 't': { + ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; + break; + } + case 'n': { + ar->namewhat = getfuncname(L, ci, &ar->name); + if (ar->namewhat == NULL) { + ar->namewhat = ""; /* not found */ + ar->name = NULL; + } + break; + } + case 'r': { + if (ci == NULL || !(ci->callstatus & CIST_TRAN)) + ar->ftransfer = ar->ntransfer = 0; + else { + ar->ftransfer = ci->u2.transferinfo.ftransfer; + ar->ntransfer = ci->u2.transferinfo.ntransfer; + } + break; + } + case 'L': + case 'f': /* handled by lua_getinfo */ + break; + default: status = 0; /* invalid option */ + } + } + return status; +} + + +LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { + int status; + Closure *cl; + CallInfo *ci; + TValue *func; + lua_lock(L); + if (*what == '>') { + ci = NULL; + func = s2v(L->top.p - 1); + api_check(L, ttisfunction(func), "function expected"); + what++; /* skip the '>' */ + L->top.p--; /* pop function */ + } + else { + ci = ar->i_ci; + func = s2v(ci->func.p); + lua_assert(ttisfunction(func)); + } + cl = ttisclosure(func) ? clvalue(func) : NULL; + status = auxgetinfo(L, what, ar, cl, ci); + if (strchr(what, 'f')) { + setobj2s(L, L->top.p, func); + api_incr_top(L); + } + if (strchr(what, 'L')) + collectvalidlines(L, cl); + lua_unlock(L); + return status; +} + + +/* +** {====================================================== +** Symbolic Execution +** ======================================================= +*/ + +static const char *getobjname (const Proto *p, int lastpc, int reg, + const char **name); + + +/* +** Find a "name" for the constant 'c'. +*/ +static void kname (const Proto *p, int c, const char **name) { + TValue *kvalue = &p->k[c]; + *name = (ttisstring(kvalue)) ? svalue(kvalue) : "?"; +} + + +/* +** Find a "name" for the register 'c'. +*/ +static void rname (const Proto *p, int pc, int c, const char **name) { + const char *what = getobjname(p, pc, c, name); /* search for 'c' */ + if (!(what && *what == 'c')) /* did not find a constant name? */ + *name = "?"; +} + + +/* +** Find a "name" for a 'C' value in an RK instruction. +*/ +static void rkname (const Proto *p, int pc, Instruction i, const char **name) { + int c = GETARG_C(i); /* key index */ + if (GETARG_k(i)) /* is 'c' a constant? */ + kname(p, c, name); + else /* 'c' is a register */ + rname(p, pc, c, name); +} + + +static int filterpc (int pc, int jmptarget) { + if (pc < jmptarget) /* is code conditional (inside a jump)? */ + return -1; /* cannot know who sets that register */ + else return pc; /* current position sets that register */ +} + + +/* +** Try to find last instruction before 'lastpc' that modified register 'reg'. +*/ +static int findsetreg (const Proto *p, int lastpc, int reg) { + int pc; + int setreg = -1; /* keep last instruction that changed 'reg' */ + int jmptarget = 0; /* any code before this address is conditional */ + if (testMMMode(GET_OPCODE(p->code[lastpc]))) + lastpc--; /* previous instruction was not actually executed */ + for (pc = 0; pc < lastpc; pc++) { + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + int a = GETARG_A(i); + int change; /* true if current instruction changed 'reg' */ + switch (op) { + case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */ + int b = GETARG_B(i); + change = (a <= reg && reg <= a + b); + break; + } + case OP_TFORCALL: { /* affect all regs above its base */ + change = (reg >= a + 2); + break; + } + case OP_CALL: + case OP_TAILCALL: { /* affect all registers above base */ + change = (reg >= a); + break; + } + case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */ + int b = GETARG_sJ(i); + int dest = pc + 1 + b; + /* jump does not skip 'lastpc' and is larger than current one? */ + if (dest <= lastpc && dest > jmptarget) + jmptarget = dest; /* update 'jmptarget' */ + change = 0; + break; + } + default: /* any instruction that sets A */ + change = (testAMode(op) && reg == a); + break; + } + if (change) + setreg = filterpc(pc, jmptarget); + } + return setreg; +} + + +/* +** Check whether table being indexed by instruction 'i' is the +** environment '_ENV' +*/ +static const char *gxf (const Proto *p, int pc, Instruction i, int isup) { + int t = GETARG_B(i); /* table index */ + const char *name; /* name of indexed variable */ + if (isup) /* is an upvalue? */ + name = upvalname(p, t); + else + getobjname(p, pc, t, &name); + return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field"; +} + + +static const char *getobjname (const Proto *p, int lastpc, int reg, + const char **name) { + int pc; + *name = luaF_getlocalname(p, reg + 1, lastpc); + if (*name) /* is a local? */ + return "local"; + /* else try symbolic execution */ + pc = findsetreg(p, lastpc, reg); + if (pc != -1) { /* could find instruction? */ + Instruction i = p->code[pc]; + OpCode op = GET_OPCODE(i); + switch (op) { + case OP_MOVE: { + int b = GETARG_B(i); /* move from 'b' to 'a' */ + if (b < GETARG_A(i)) + return getobjname(p, pc, b, name); /* get name for 'b' */ + break; + } + case OP_GETTABUP: { + int k = GETARG_C(i); /* key index */ + kname(p, k, name); + return gxf(p, pc, i, 1); + } + case OP_GETTABLE: { + int k = GETARG_C(i); /* key index */ + rname(p, pc, k, name); + return gxf(p, pc, i, 0); + } + case OP_GETI: { + *name = "integer index"; + return "field"; + } + case OP_GETFIELD: { + int k = GETARG_C(i); /* key index */ + kname(p, k, name); + return gxf(p, pc, i, 0); + } + case OP_GETUPVAL: { + *name = upvalname(p, GETARG_B(i)); + return "upvalue"; + } + case OP_LOADK: + case OP_LOADKX: { + int b = (op == OP_LOADK) ? GETARG_Bx(i) + : GETARG_Ax(p->code[pc + 1]); + if (ttisstring(&p->k[b])) { + *name = svalue(&p->k[b]); + return "constant"; + } + break; + } + case OP_SELF: { + rkname(p, pc, i, name); + return "method"; + } + default: break; /* go through to return NULL */ + } + } + return NULL; /* could not find reasonable name */ +} + + +/* +** Try to find a name for a function based on the code that called it. +** (Only works when function was called by a Lua function.) +** Returns what the name is (e.g., "for iterator", "method", +** "metamethod") and sets '*name' to point to the name. +*/ +static const char *funcnamefromcode (lua_State *L, const Proto *p, + int pc, const char **name) { + TMS tm = (TMS)0; /* (initial value avoids warnings) */ + Instruction i = p->code[pc]; /* calling instruction */ + switch (GET_OPCODE(i)) { + case OP_CALL: + case OP_TAILCALL: + return getobjname(p, pc, GETARG_A(i), name); /* get function name */ + case OP_TFORCALL: { /* for iterator */ + *name = "for iterator"; + return "for iterator"; + } + /* other instructions can do calls through metamethods */ + case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: + case OP_GETI: case OP_GETFIELD: + tm = TM_INDEX; + break; + case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD: + tm = TM_NEWINDEX; + break; + case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { + tm = cast(TMS, GETARG_C(i)); + break; + } + case OP_UNM: tm = TM_UNM; break; + case OP_BNOT: tm = TM_BNOT; break; + case OP_LEN: tm = TM_LEN; break; + case OP_CONCAT: tm = TM_CONCAT; break; + case OP_EQ: tm = TM_EQ; break; + /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */ + case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break; + case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break; + case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break; + default: + return NULL; /* cannot find a reasonable name */ + } + *name = getstr(G(L)->tmname[tm]) + 2; + return "metamethod"; +} + + +/* +** Try to find a name for a function based on how it was called. +*/ +static const char *funcnamefromcall (lua_State *L, CallInfo *ci, + const char **name) { + if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ + *name = "?"; + return "hook"; + } + else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */ + *name = "__gc"; + return "metamethod"; /* report it as such */ + } + else if (isLua(ci)) + return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name); + else + return NULL; +} + +/* }====================================================== */ + + + +/* +** Check whether pointer 'o' points to some value in the stack frame of +** the current function and, if so, returns its index. Because 'o' may +** not point to a value in this stack, we cannot compare it with the +** region boundaries (undefined behavior in ISO C). +*/ +static int instack (CallInfo *ci, const TValue *o) { + int pos; + StkId base = ci->func.p + 1; + for (pos = 0; base + pos < ci->top.p; pos++) { + if (o == s2v(base + pos)) + return pos; + } + return -1; /* not found */ +} + + +/* +** Checks whether value 'o' came from an upvalue. (That can only happen +** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on +** upvalues.) +*/ +static const char *getupvalname (CallInfo *ci, const TValue *o, + const char **name) { + LClosure *c = ci_func(ci); + int i; + for (i = 0; i < c->nupvalues; i++) { + if (c->upvals[i]->v.p == o) { + *name = upvalname(c->p, i); + return "upvalue"; + } + } + return NULL; +} + + +static const char *formatvarinfo (lua_State *L, const char *kind, + const char *name) { + if (kind == NULL) + return ""; /* no information */ + else + return luaO_pushfstring(L, " (%s '%s')", kind, name); +} + +/* +** Build a string with a "description" for the value 'o', such as +** "variable 'x'" or "upvalue 'y'". +*/ +static const char *varinfo (lua_State *L, const TValue *o) { + CallInfo *ci = L->ci; + const char *name = NULL; /* to avoid warnings */ + const char *kind = NULL; + if (isLua(ci)) { + kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ + if (!kind) { /* not an upvalue? */ + int reg = instack(ci, o); /* try a register */ + if (reg >= 0) /* is 'o' a register? */ + kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name); + } + } + return formatvarinfo(L, kind, name); +} + + +/* +** Raise a type error +*/ +static l_noret typeerror (lua_State *L, const TValue *o, const char *op, + const char *extra) { + const char *t = luaT_objtypename(L, o); + luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra); +} + + +/* +** Raise a type error with "standard" information about the faulty +** object 'o' (using 'varinfo'). +*/ +l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { + typeerror(L, o, op, varinfo(L, o)); +} + + +/* +** Raise an error for calling a non-callable object. Try to find a name +** for the object based on how it was called ('funcnamefromcall'); if it +** cannot get a name there, try 'varinfo'. +*/ +l_noret luaG_callerror (lua_State *L, const TValue *o) { + CallInfo *ci = L->ci; + const char *name = NULL; /* to avoid warnings */ + const char *kind = funcnamefromcall(L, ci, &name); + const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o); + typeerror(L, o, "call", extra); +} + + +l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) { + luaG_runerror(L, "bad 'for' %s (number expected, got %s)", + what, luaT_objtypename(L, o)); +} + + +l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { + if (ttisstring(p1) || cvt2str(p1)) p1 = p2; + luaG_typeerror(L, p1, "concatenate"); +} + + +l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, const char *msg) { + if (!ttisnumber(p1)) /* first operand is wrong? */ + p2 = p1; /* now second is wrong */ + luaG_typeerror(L, p2, msg); +} + + +/* +** Error when both values are convertible to numbers, but not to integers +*/ +l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { + lua_Integer temp; + if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I)) + p2 = p1; + luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); +} + + +l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { + const char *t1 = luaT_objtypename(L, p1); + const char *t2 = luaT_objtypename(L, p2); + if (strcmp(t1, t2) == 0) + luaG_runerror(L, "attempt to compare two %s values", t1); + else + luaG_runerror(L, "attempt to compare %s with %s", t1, t2); +} + + +/* add src:line information to 'msg' */ +const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, + int line) { + char buff[LUA_IDSIZE]; + if (src) + luaO_chunkid(buff, getstr(src), tsslen(src)); + else { /* no source available; use "?" instead */ + buff[0] = '?'; buff[1] = '\0'; + } + return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); +} + + +l_noret luaG_errormsg (lua_State *L) { + if (L->errfunc != 0) { /* is there an error handling function? */ + StkId errfunc = restorestack(L, L->errfunc); + lua_assert(ttisfunction(s2v(errfunc))); + setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */ + setobjs2s(L, L->top.p - 1, errfunc); /* push function */ + L->top.p++; /* assume EXTRA_STACK */ + luaD_callnoyield(L, L->top.p - 2, 1); /* call it */ + } + luaD_throw(L, LUA_ERRRUN); +} + + +l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { + CallInfo *ci = L->ci; + const char *msg; + va_list argp; + luaC_checkGC(L); /* error message uses memory */ + va_start(argp, fmt); + msg = luaO_pushvfstring(L, fmt, argp); /* format message */ + va_end(argp); + if (isLua(ci)) { /* if Lua function, add source:line information */ + luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci)); + setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */ + L->top.p--; + } + luaG_errormsg(L); +} + + +/* +** Check whether new instruction 'newpc' is in a different line from +** previous instruction 'oldpc'. More often than not, 'newpc' is only +** one or a few instructions after 'oldpc' (it must be after, see +** caller), so try to avoid calling 'luaG_getfuncline'. If they are +** too far apart, there is a good chance of a ABSLINEINFO in the way, +** so it goes directly to 'luaG_getfuncline'. +*/ +static int changedline (const Proto *p, int oldpc, int newpc) { + if (p->lineinfo == NULL) /* no debug information? */ + return 0; + if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */ + int delta = 0; /* line difference */ + int pc = oldpc; + for (;;) { + int lineinfo = p->lineinfo[++pc]; + if (lineinfo == ABSLINEINFO) + break; /* cannot compute delta; fall through */ + delta += lineinfo; + if (pc == newpc) + return (delta != 0); /* delta computed successfully */ + } + } + /* either instructions are too far apart or there is an absolute line + info in the way; compute line difference explicitly */ + return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc)); +} + + +/* +** Traces the execution of a Lua function. Called before the execution +** of each opcode, when debug is on. 'L->oldpc' stores the last +** instruction traced, to detect line changes. When entering a new +** function, 'npci' will be zero and will test as a new line whatever +** the value of 'oldpc'. Some exceptional conditions may return to +** a function without setting 'oldpc'. In that case, 'oldpc' may be +** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc' +** at most causes an extra call to a line hook.) +** This function is not "Protected" when called, so it should correct +** 'L->top.p' before calling anything that can run the GC. +*/ +int luaG_traceexec (lua_State *L, const Instruction *pc) { + CallInfo *ci = L->ci; + lu_byte mask = L->hookmask; + const Proto *p = ci_func(ci)->p; + int counthook; + if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */ + ci->u.l.trap = 0; /* don't need to stop again */ + return 0; /* turn off 'trap' */ + } + pc++; /* reference is always next instruction */ + ci->u.l.savedpc = pc; /* save 'pc' */ + counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); + if (counthook) + resethookcount(L); /* reset count */ + else if (!(mask & LUA_MASKLINE)) + return 1; /* no line hook and count != 0; nothing to be done now */ + if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ + ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ + return 1; /* do not call hook again (VM yielded, so it did not move) */ + } + if (!isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */ + L->top.p = ci->top.p; /* correct top */ + if (counthook) + luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */ + if (mask & LUA_MASKLINE) { + /* 'L->oldpc' may be invalid; use zero in this case */ + int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0; + int npci = pcRel(pc, p); + if (npci <= oldpc || /* call hook when jump back (loop), */ + changedline(p, oldpc, npci)) { /* or when enter new line */ + int newline = luaG_getfuncline(p, npci); + luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */ + } + L->oldpc = npci; /* 'pc' of last call to line hook */ + } + if (L->status == LUA_YIELD) { /* did hook yield? */ + if (counthook) + L->hookcount = 1; /* undo decrement to zero */ + ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ + ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ + luaD_throw(L, LUA_YIELD); + } + return 1; /* keep 'trap' on */ +} + diff --git a/src/libs/3rdparty/lua/src/ldebug.h b/src/libs/3rdparty/lua/src/ldebug.h new file mode 100644 index 00000000000..2c3074c61b6 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldebug.h @@ -0,0 +1,63 @@ +/* +** $Id: ldebug.h $ +** Auxiliary functions from Debug Interface module +** See Copyright Notice in lua.h +*/ + +#ifndef ldebug_h +#define ldebug_h + + +#include "lstate.h" + + +#define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1) + + +/* Active Lua function (given call info) */ +#define ci_func(ci) (clLvalue(s2v((ci)->func.p))) + + +#define resethookcount(L) (L->hookcount = L->basehookcount) + +/* +** mark for entries in 'lineinfo' array that has absolute information in +** 'abslineinfo' array +*/ +#define ABSLINEINFO (-0x80) + + +/* +** MAXimum number of successive Instructions WiTHout ABSolute line +** information. (A power of two allows fast divisions.) +*/ +#if !defined(MAXIWTHABS) +#define MAXIWTHABS 128 +#endif + + +LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc); +LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, + StkId *pos); +LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, + const char *opname); +LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o); +LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o, + const char *what); +LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, + const char *msg); +LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); +LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, + TString *src, int line); +LUAI_FUNC l_noret luaG_errormsg (lua_State *L); +LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc); + + +#endif diff --git a/src/libs/3rdparty/lua/src/ldo.c b/src/libs/3rdparty/lua/src/ldo.c new file mode 100644 index 00000000000..2a0017ca62a --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldo.c @@ -0,0 +1,1024 @@ +/* +** $Id: ldo.c $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#define ldo_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lundump.h" +#include "lvm.h" +#include "lzio.h" + + + +#define errorstatus(s) ((s) > LUA_YIELD) + + +/* +** {====================================================== +** Error-recovery functions +** ======================================================= +*/ + +/* +** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By +** default, Lua handles errors with exceptions when compiling as +** C++ code, with _longjmp/_setjmp when asked to use them, and with +** longjmp/setjmp otherwise. +*/ +#if !defined(LUAI_THROW) /* { */ + +#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */ + +/* C++ exceptions */ +#define LUAI_THROW(L,c) throw(c) +#define LUAI_TRY(L,c,a) \ + try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; } +#define luai_jmpbuf int /* dummy variable */ + +#elif defined(LUA_USE_POSIX) /* }{ */ + +/* in POSIX, try _longjmp/_setjmp (more efficient) */ +#define LUAI_THROW(L,c) _longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#else /* }{ */ + +/* ISO C handling with long jumps */ +#define LUAI_THROW(L,c) longjmp((c)->b, 1) +#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } +#define luai_jmpbuf jmp_buf + +#endif /* } */ + +#endif /* } */ + + + +/* chain list of long jump buffers */ +struct lua_longjmp { + struct lua_longjmp *previous; + luai_jmpbuf b; + volatile int status; /* error code */ +}; + + +void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { + switch (errcode) { + case LUA_ERRMEM: { /* memory error? */ + setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ + break; + } + case LUA_ERRERR: { + setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); + break; + } + case LUA_OK: { /* special case only for closing upvalues */ + setnilvalue(s2v(oldtop)); /* no error message */ + break; + } + default: { + lua_assert(errorstatus(errcode)); /* real error */ + setobjs2s(L, oldtop, L->top.p - 1); /* error message on current top */ + break; + } + } + L->top.p = oldtop + 1; +} + + +l_noret luaD_throw (lua_State *L, int errcode) { + if (L->errorJmp) { /* thread has an error handler? */ + L->errorJmp->status = errcode; /* set status */ + LUAI_THROW(L, L->errorJmp); /* jump to it */ + } + else { /* thread has no error handler */ + global_State *g = G(L); + errcode = luaE_resetthread(L, errcode); /* close all upvalues */ + if (g->mainthread->errorJmp) { /* main thread has a handler? */ + setobjs2s(L, g->mainthread->top.p++, L->top.p - 1); /* copy error obj. */ + luaD_throw(g->mainthread, errcode); /* re-throw in main thread */ + } + else { /* no handler at all; abort */ + if (g->panic) { /* panic function? */ + lua_unlock(L); + g->panic(L); /* call panic function (last chance to jump out) */ + } + abort(); + } + } +} + + +int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { + l_uint32 oldnCcalls = L->nCcalls; + struct lua_longjmp lj; + lj.status = LUA_OK; + lj.previous = L->errorJmp; /* chain new error handler */ + L->errorJmp = &lj; + LUAI_TRY(L, &lj, + (*f)(L, ud); + ); + L->errorJmp = lj.previous; /* restore old error handler */ + L->nCcalls = oldnCcalls; + return lj.status; +} + +/* }====================================================== */ + + +/* +** {================================================================== +** Stack reallocation +** =================================================================== +*/ + + +/* +** Change all pointers to the stack into offsets. +*/ +static void relstack (lua_State *L) { + CallInfo *ci; + UpVal *up; + L->top.offset = savestack(L, L->top.p); + L->tbclist.offset = savestack(L, L->tbclist.p); + for (up = L->openupval; up != NULL; up = up->u.open.next) + up->v.offset = savestack(L, uplevel(up)); + for (ci = L->ci; ci != NULL; ci = ci->previous) { + ci->top.offset = savestack(L, ci->top.p); + ci->func.offset = savestack(L, ci->func.p); + } +} + + +/* +** Change back all offsets into pointers. +*/ +static void correctstack (lua_State *L) { + CallInfo *ci; + UpVal *up; + L->top.p = restorestack(L, L->top.offset); + L->tbclist.p = restorestack(L, L->tbclist.offset); + for (up = L->openupval; up != NULL; up = up->u.open.next) + up->v.p = s2v(restorestack(L, up->v.offset)); + for (ci = L->ci; ci != NULL; ci = ci->previous) { + ci->top.p = restorestack(L, ci->top.offset); + ci->func.p = restorestack(L, ci->func.offset); + if (isLua(ci)) + ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */ + } +} + + +/* some space for error handling */ +#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) + +/* +** Reallocate the stack to a new size, correcting all pointers into it. +** In ISO C, any pointer use after the pointer has been deallocated is +** undefined behavior. So, before the reallocation, all pointers are +** changed to offsets, and after the reallocation they are changed back +** to pointers. As during the reallocation the pointers are invalid, the +** reallocation cannot run emergency collections. +** +** In case of allocation error, raise an error or return false according +** to 'raiseerror'. +*/ +int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) { + int oldsize = stacksize(L); + int i; + StkId newstack; + int oldgcstop = G(L)->gcstopem; + lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); + relstack(L); /* change pointers to offsets */ + G(L)->gcstopem = 1; /* stop emergency collection */ + newstack = luaM_reallocvector(L, L->stack.p, oldsize + EXTRA_STACK, + newsize + EXTRA_STACK, StackValue); + G(L)->gcstopem = oldgcstop; /* restore emergency collection */ + if (l_unlikely(newstack == NULL)) { /* reallocation failed? */ + correctstack(L); /* change offsets back to pointers */ + if (raiseerror) + luaM_error(L); + else return 0; /* do not raise an error */ + } + L->stack.p = newstack; + correctstack(L); /* change offsets back to pointers */ + L->stack_last.p = L->stack.p + newsize; + for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++) + setnilvalue(s2v(newstack + i)); /* erase new segment */ + return 1; +} + + +/* +** Try to grow the stack by at least 'n' elements. When 'raiseerror' +** is true, raises any error; otherwise, return 0 in case of errors. +*/ +int luaD_growstack (lua_State *L, int n, int raiseerror) { + int size = stacksize(L); + if (l_unlikely(size > LUAI_MAXSTACK)) { + /* if stack is larger than maximum, thread is already using the + extra space reserved for errors, that is, thread is handling + a stack error; cannot grow further than that. */ + lua_assert(stacksize(L) == ERRORSTACKSIZE); + if (raiseerror) + luaD_throw(L, LUA_ERRERR); /* error inside message handler */ + return 0; /* if not 'raiseerror', just signal it */ + } + else if (n < LUAI_MAXSTACK) { /* avoids arithmetic overflows */ + int newsize = 2 * size; /* tentative new size */ + int needed = cast_int(L->top.p - L->stack.p) + n; + if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */ + newsize = LUAI_MAXSTACK; + if (newsize < needed) /* but must respect what was asked for */ + newsize = needed; + if (l_likely(newsize <= LUAI_MAXSTACK)) + return luaD_reallocstack(L, newsize, raiseerror); + } + /* else stack overflow */ + /* add extra size to be able to handle the error message */ + luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror); + if (raiseerror) + luaG_runerror(L, "stack overflow"); + return 0; +} + + +/* +** Compute how much of the stack is being used, by computing the +** maximum top of all call frames in the stack and the current top. +*/ +static int stackinuse (lua_State *L) { + CallInfo *ci; + int res; + StkId lim = L->top.p; + for (ci = L->ci; ci != NULL; ci = ci->previous) { + if (lim < ci->top.p) lim = ci->top.p; + } + lua_assert(lim <= L->stack_last.p + EXTRA_STACK); + res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */ + if (res < LUA_MINSTACK) + res = LUA_MINSTACK; /* ensure a minimum size */ + return res; +} + + +/* +** If stack size is more than 3 times the current use, reduce that size +** to twice the current use. (So, the final stack size is at most 2/3 the +** previous size, and half of its entries are empty.) +** As a particular case, if stack was handling a stack overflow and now +** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than +** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack +** will be reduced to a "regular" size. +*/ +void luaD_shrinkstack (lua_State *L) { + int inuse = stackinuse(L); + int max = (inuse > LUAI_MAXSTACK / 3) ? LUAI_MAXSTACK : inuse * 3; + /* if thread is currently not handling a stack overflow and its + size is larger than maximum "reasonable" size, shrink it */ + if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) { + int nsize = (inuse > LUAI_MAXSTACK / 2) ? LUAI_MAXSTACK : inuse * 2; + luaD_reallocstack(L, nsize, 0); /* ok if that fails */ + } + else /* don't change stack */ + condmovestack(L,{},{}); /* (change only for debugging) */ + luaE_shrinkCI(L); /* shrink CI list */ +} + + +void luaD_inctop (lua_State *L) { + luaD_checkstack(L, 1); + L->top.p++; +} + +/* }================================================================== */ + + +/* +** Call a hook for the given event. Make sure there is a hook to be +** called. (Both 'L->hook' and 'L->hookmask', which trigger this +** function, can be changed asynchronously by signals.) +*/ +void luaD_hook (lua_State *L, int event, int line, + int ftransfer, int ntransfer) { + lua_Hook hook = L->hook; + if (hook && L->allowhook) { /* make sure there is a hook */ + int mask = CIST_HOOKED; + CallInfo *ci = L->ci; + ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */ + ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */ + lua_Debug ar; + ar.event = event; + ar.currentline = line; + ar.i_ci = ci; + if (ntransfer != 0) { + mask |= CIST_TRAN; /* 'ci' has transfer information */ + ci->u2.transferinfo.ftransfer = ftransfer; + ci->u2.transferinfo.ntransfer = ntransfer; + } + if (isLua(ci) && L->top.p < ci->top.p) + L->top.p = ci->top.p; /* protect entire activation register */ + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + if (ci->top.p < L->top.p + LUA_MINSTACK) + ci->top.p = L->top.p + LUA_MINSTACK; + L->allowhook = 0; /* cannot call hooks inside a hook */ + ci->callstatus |= mask; + lua_unlock(L); + (*hook)(L, &ar); + lua_lock(L); + lua_assert(!L->allowhook); + L->allowhook = 1; + ci->top.p = restorestack(L, ci_top); + L->top.p = restorestack(L, top); + ci->callstatus &= ~mask; + } +} + + +/* +** Executes a call hook for Lua functions. This function is called +** whenever 'hookmask' is not zero, so it checks whether call hooks are +** active. +*/ +void luaD_hookcall (lua_State *L, CallInfo *ci) { + L->oldpc = 0; /* set 'oldpc' for new function */ + if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */ + int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL + : LUA_HOOKCALL; + Proto *p = ci_func(ci)->p; + ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ + luaD_hook(L, event, -1, 1, p->numparams); + ci->u.l.savedpc--; /* correct 'pc' */ + } +} + + +/* +** Executes a return hook for Lua and C functions and sets/corrects +** 'oldpc'. (Note that this correction is needed by the line hook, so it +** is done even when return hooks are off.) +*/ +static void rethook (lua_State *L, CallInfo *ci, int nres) { + if (L->hookmask & LUA_MASKRET) { /* is return hook on? */ + StkId firstres = L->top.p - nres; /* index of first result */ + int delta = 0; /* correction for vararg functions */ + int ftransfer; + if (isLua(ci)) { + Proto *p = ci_func(ci)->p; + if (p->is_vararg) + delta = ci->u.l.nextraargs + p->numparams + 1; + } + ci->func.p += delta; /* if vararg, back to virtual 'func' */ + ftransfer = cast(unsigned short, firstres - ci->func.p); + luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */ + ci->func.p -= delta; + } + if (isLua(ci = ci->previous)) + L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */ +} + + +/* +** Check whether 'func' has a '__call' metafield. If so, put it in the +** stack, below original 'func', so that 'luaD_precall' can call it. Raise +** an error if there is no '__call' metafield. +*/ +StkId luaD_tryfuncTM (lua_State *L, StkId func) { + const TValue *tm; + StkId p; + checkstackGCp(L, 1, func); /* space for metamethod */ + tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */ + if (l_unlikely(ttisnil(tm))) + luaG_callerror(L, s2v(func)); /* nothing to call */ + for (p = L->top.p; p > func; p--) /* open space for metamethod */ + setobjs2s(L, p, p-1); + L->top.p++; /* stack space pre-allocated by the caller */ + setobj2s(L, func, tm); /* metamethod is the new function to be called */ + return func; +} + + +/* +** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'. +** Handle most typical cases (zero results for commands, one result for +** expressions, multiple results for tail calls/single parameters) +** separated. +*/ +l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) { + StkId firstresult; + int i; + switch (wanted) { /* handle typical cases separately */ + case 0: /* no values needed */ + L->top.p = res; + return; + case 1: /* one value needed */ + if (nres == 0) /* no results? */ + setnilvalue(s2v(res)); /* adjust with nil */ + else /* at least one result */ + setobjs2s(L, res, L->top.p - nres); /* move it to proper place */ + L->top.p = res + 1; + return; + case LUA_MULTRET: + wanted = nres; /* we want all results */ + break; + default: /* two/more results and/or to-be-closed variables */ + if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */ + L->ci->callstatus |= CIST_CLSRET; /* in case of yields */ + L->ci->u2.nres = nres; + res = luaF_close(L, res, CLOSEKTOP, 1); + L->ci->callstatus &= ~CIST_CLSRET; + if (L->hookmask) { /* if needed, call hook after '__close's */ + ptrdiff_t savedres = savestack(L, res); + rethook(L, L->ci, nres); + res = restorestack(L, savedres); /* hook can move stack */ + } + wanted = decodeNresults(wanted); + if (wanted == LUA_MULTRET) + wanted = nres; /* we want all results */ + } + break; + } + /* generic case */ + firstresult = L->top.p - nres; /* index of first result */ + if (nres > wanted) /* extra results? */ + nres = wanted; /* don't need them */ + for (i = 0; i < nres; i++) /* move all results to correct place */ + setobjs2s(L, res + i, firstresult + i); + for (; i < wanted; i++) /* complete wanted number of results */ + setnilvalue(s2v(res + i)); + L->top.p = res + wanted; /* top points after the last result */ +} + + +/* +** Finishes a function call: calls hook if necessary, moves current +** number of results to proper place, and returns to previous call +** info. If function has to close variables, hook must be called after +** that. +*/ +void luaD_poscall (lua_State *L, CallInfo *ci, int nres) { + int wanted = ci->nresults; + if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted))) + rethook(L, ci, nres); + /* move results to proper place */ + moveresults(L, ci->func.p, nres, wanted); + /* function cannot be in any of these cases when returning */ + lua_assert(!(ci->callstatus & + (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET))); + L->ci = ci->previous; /* back to caller (after closing variables) */ +} + + + +#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L)) + + +l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret, + int mask, StkId top) { + CallInfo *ci = L->ci = next_ci(L); /* new frame */ + ci->func.p = func; + ci->nresults = nret; + ci->callstatus = mask; + ci->top.p = top; + return ci; +} + + +/* +** precall for C functions +*/ +l_sinline int precallC (lua_State *L, StkId func, int nresults, + lua_CFunction f) { + int n; /* number of returns */ + CallInfo *ci; + checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ + L->ci = ci = prepCallInfo(L, func, nresults, CIST_C, + L->top.p + LUA_MINSTACK); + lua_assert(ci->top.p <= L->stack_last.p); + if (l_unlikely(L->hookmask & LUA_MASKCALL)) { + int narg = cast_int(L->top.p - func) - 1; + luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); + } + lua_unlock(L); + n = (*f)(L); /* do the actual call */ + lua_lock(L); + api_checknelems(L, n); + luaD_poscall(L, ci, n); + return n; +} + + +/* +** Prepare a function for a tail call, building its call info on top +** of the current call info. 'narg1' is the number of arguments plus 1 +** (so that it includes the function itself). Return the number of +** results, if it was a C function, or -1 for a Lua function. +*/ +int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, + int narg1, int delta) { + retry: + switch (ttypetag(s2v(func))) { + case LUA_VCCL: /* C closure */ + return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f); + case LUA_VLCF: /* light C function */ + return precallC(L, func, LUA_MULTRET, fvalue(s2v(func))); + case LUA_VLCL: { /* Lua function */ + Proto *p = clLvalue(s2v(func))->p; + int fsize = p->maxstacksize; /* frame size */ + int nfixparams = p->numparams; + int i; + checkstackGCp(L, fsize - delta, func); + ci->func.p -= delta; /* restore 'func' (if vararg) */ + for (i = 0; i < narg1; i++) /* move down function and arguments */ + setobjs2s(L, ci->func.p + i, func + i); + func = ci->func.p; /* moved-down function */ + for (; narg1 <= nfixparams; narg1++) + setnilvalue(s2v(func + narg1)); /* complete missing arguments */ + ci->top.p = func + 1 + fsize; /* top for new function */ + lua_assert(ci->top.p <= L->stack_last.p); + ci->u.l.savedpc = p->code; /* starting point */ + ci->callstatus |= CIST_TAIL; + L->top.p = func + narg1; /* set top */ + return -1; + } + default: { /* not a function */ + func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ + /* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */ + narg1++; + goto retry; /* try again */ + } + } +} + + +/* +** Prepares the call to a function (C or Lua). For C functions, also do +** the call. The function to be called is at '*func'. The arguments +** are on the stack, right after the function. Returns the CallInfo +** to be executed, if it was a Lua function. Otherwise (a C function) +** returns NULL, with all the results on the stack, starting at the +** original function position. +*/ +CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) { + retry: + switch (ttypetag(s2v(func))) { + case LUA_VCCL: /* C closure */ + precallC(L, func, nresults, clCvalue(s2v(func))->f); + return NULL; + case LUA_VLCF: /* light C function */ + precallC(L, func, nresults, fvalue(s2v(func))); + return NULL; + case LUA_VLCL: { /* Lua function */ + CallInfo *ci; + Proto *p = clLvalue(s2v(func))->p; + int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */ + int nfixparams = p->numparams; + int fsize = p->maxstacksize; /* frame size */ + checkstackGCp(L, fsize, func); + L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize); + ci->u.l.savedpc = p->code; /* starting point */ + for (; narg < nfixparams; narg++) + setnilvalue(s2v(L->top.p++)); /* complete missing arguments */ + lua_assert(ci->top.p <= L->stack_last.p); + return ci; + } + default: { /* not a function */ + func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ + /* return luaD_precall(L, func, nresults); */ + goto retry; /* try again with metamethod */ + } + } +} + + +/* +** Call a function (C or Lua) through C. 'inc' can be 1 (increment +** number of recursive invocations in the C stack) or nyci (the same +** plus increment number of non-yieldable calls). +** This function can be called with some use of EXTRA_STACK, so it should +** check the stack before doing anything else. 'luaD_precall' already +** does that. +*/ +l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) { + CallInfo *ci; + L->nCcalls += inc; + if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) { + checkstackp(L, 0, func); /* free any use of EXTRA_STACK */ + luaE_checkcstack(L); + } + if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */ + ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */ + luaV_execute(L, ci); /* call it */ + } + L->nCcalls -= inc; +} + + +/* +** External interface for 'ccall' +*/ +void luaD_call (lua_State *L, StkId func, int nResults) { + ccall(L, func, nResults, 1); +} + + +/* +** Similar to 'luaD_call', but does not allow yields during the call. +*/ +void luaD_callnoyield (lua_State *L, StkId func, int nResults) { + ccall(L, func, nResults, nyci); +} + + +/* +** Finish the job of 'lua_pcallk' after it was interrupted by an yield. +** (The caller, 'finishCcall', does the final call to 'adjustresults'.) +** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'. +** If a '__close' method yields here, eventually control will be back +** to 'finishCcall' (when that '__close' method finally returns) and +** 'finishpcallk' will run again and close any still pending '__close' +** methods. Similarly, if a '__close' method errs, 'precover' calls +** 'unroll' which calls ''finishCcall' and we are back here again, to +** close any pending '__close' methods. +** Note that, up to the call to 'luaF_close', the corresponding +** 'CallInfo' is not modified, so that this repeated run works like the +** first one (except that it has at least one less '__close' to do). In +** particular, field CIST_RECST preserves the error status across these +** multiple runs, changing only if there is a new error. +*/ +static int finishpcallk (lua_State *L, CallInfo *ci) { + int status = getcistrecst(ci); /* get original status */ + if (l_likely(status == LUA_OK)) /* no error? */ + status = LUA_YIELD; /* was interrupted by an yield */ + else { /* error */ + StkId func = restorestack(L, ci->u2.funcidx); + L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */ + func = luaF_close(L, func, status, 1); /* can yield or raise an error */ + luaD_seterrorobj(L, status, func); + luaD_shrinkstack(L); /* restore stack size in case of overflow */ + setcistrecst(ci, LUA_OK); /* clear original status */ + } + ci->callstatus &= ~CIST_YPCALL; + L->errfunc = ci->u.c.old_errfunc; + /* if it is here, there were errors or yields; unlike 'lua_pcallk', + do not change status */ + return status; +} + + +/* +** Completes the execution of a C function interrupted by an yield. +** The interruption must have happened while the function was either +** closing its tbc variables in 'moveresults' or executing +** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes +** 'luaD_poscall'. In the second case, the call to 'finishpcallk' +** finishes the interrupted execution of 'lua_pcallk'. After that, it +** calls the continuation of the interrupted function and finally it +** completes the job of the 'luaD_call' that called the function. In +** the call to 'adjustresults', we do not know the number of results +** of the function called by 'lua_callk'/'lua_pcallk', so we are +** conservative and use LUA_MULTRET (always adjust). +*/ +static void finishCcall (lua_State *L, CallInfo *ci) { + int n; /* actual number of results from C function */ + if (ci->callstatus & CIST_CLSRET) { /* was returning? */ + lua_assert(hastocloseCfunc(ci->nresults)); + n = ci->u2.nres; /* just redo 'luaD_poscall' */ + /* don't need to reset CIST_CLSRET, as it will be set again anyway */ + } + else { + int status = LUA_YIELD; /* default if there were no errors */ + /* must have a continuation and must be able to call it */ + lua_assert(ci->u.c.k != NULL && yieldable(L)); + if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */ + status = finishpcallk(L, ci); /* finish it */ + adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */ + lua_unlock(L); + n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */ + lua_lock(L); + api_checknelems(L, n); + } + luaD_poscall(L, ci, n); /* finish 'luaD_call' */ +} + + +/* +** Executes "full continuation" (everything in the stack) of a +** previously interrupted coroutine until the stack is empty (or another +** interruption long-jumps out of the loop). +*/ +static void unroll (lua_State *L, void *ud) { + CallInfo *ci; + UNUSED(ud); + while ((ci = L->ci) != &L->base_ci) { /* something in the stack */ + if (!isLua(ci)) /* C function? */ + finishCcall(L, ci); /* complete its execution */ + else { /* Lua function */ + luaV_finishOp(L); /* finish interrupted instruction */ + luaV_execute(L, ci); /* execute down to higher C 'boundary' */ + } + } +} + + +/* +** Try to find a suspended protected call (a "recover point") for the +** given thread. +*/ +static CallInfo *findpcall (lua_State *L) { + CallInfo *ci; + for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ + if (ci->callstatus & CIST_YPCALL) + return ci; + } + return NULL; /* no pending pcall */ +} + + +/* +** Signal an error in the call to 'lua_resume', not in the execution +** of the coroutine itself. (Such errors should not be handled by any +** coroutine error handler and should not kill the coroutine.) +*/ +static int resume_error (lua_State *L, const char *msg, int narg) { + L->top.p -= narg; /* remove args from the stack */ + setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */ + api_incr_top(L); + lua_unlock(L); + return LUA_ERRRUN; +} + + +/* +** Do the work for 'lua_resume' in protected mode. Most of the work +** depends on the status of the coroutine: initial state, suspended +** inside a hook, or regularly suspended (optionally with a continuation +** function), plus erroneous cases: non-suspended coroutine or dead +** coroutine. +*/ +static void resume (lua_State *L, void *ud) { + int n = *(cast(int*, ud)); /* number of arguments */ + StkId firstArg = L->top.p - n; /* first argument */ + CallInfo *ci = L->ci; + if (L->status == LUA_OK) /* starting a coroutine? */ + ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */ + else { /* resuming from previous yield */ + lua_assert(L->status == LUA_YIELD); + L->status = LUA_OK; /* mark that it is running (again) */ + if (isLua(ci)) { /* yielded inside a hook? */ + L->top.p = firstArg; /* discard arguments */ + luaV_execute(L, ci); /* just continue running Lua code */ + } + else { /* 'common' yield */ + if (ci->u.c.k != NULL) { /* does it have a continuation function? */ + lua_unlock(L); + n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */ + lua_lock(L); + api_checknelems(L, n); + } + luaD_poscall(L, ci, n); /* finish 'luaD_call' */ + } + unroll(L, NULL); /* run continuation */ + } +} + + +/* +** Unrolls a coroutine in protected mode while there are recoverable +** errors, that is, errors inside a protected call. (Any error +** interrupts 'unroll', and this loop protects it again so it can +** continue.) Stops with a normal end (status == LUA_OK), an yield +** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't +** find a recover point). +*/ +static int precover (lua_State *L, int status) { + CallInfo *ci; + while (errorstatus(status) && (ci = findpcall(L)) != NULL) { + L->ci = ci; /* go down to recovery functions */ + setcistrecst(ci, status); /* status to finish 'pcall' */ + status = luaD_rawrunprotected(L, unroll, NULL); + } + return status; +} + + +LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs, + int *nresults) { + int status; + lua_lock(L); + if (L->status == LUA_OK) { /* may be starting a coroutine */ + if (L->ci != &L->base_ci) /* not in base level? */ + return resume_error(L, "cannot resume non-suspended coroutine", nargs); + else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */ + return resume_error(L, "cannot resume dead coroutine", nargs); + } + else if (L->status != LUA_YIELD) /* ended with errors? */ + return resume_error(L, "cannot resume dead coroutine", nargs); + L->nCcalls = (from) ? getCcalls(from) : 0; + if (getCcalls(L) >= LUAI_MAXCCALLS) + return resume_error(L, "C stack overflow", nargs); + L->nCcalls++; + luai_userstateresume(L, nargs); + api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); + status = luaD_rawrunprotected(L, resume, &nargs); + /* continue running after recoverable errors */ + status = precover(L, status); + if (l_likely(!errorstatus(status))) + lua_assert(status == L->status); /* normal end or yield */ + else { /* unrecoverable error */ + L->status = cast_byte(status); /* mark thread as 'dead' */ + luaD_seterrorobj(L, status, L->top.p); /* push error message */ + L->ci->top.p = L->top.p; + } + *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield + : cast_int(L->top.p - (L->ci->func.p + 1)); + lua_unlock(L); + return status; +} + + +LUA_API int lua_isyieldable (lua_State *L) { + return yieldable(L); +} + + +LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, + lua_KFunction k) { + CallInfo *ci; + luai_userstateyield(L, nresults); + lua_lock(L); + ci = L->ci; + api_checknelems(L, nresults); + if (l_unlikely(!yieldable(L))) { + if (L != G(L)->mainthread) + luaG_runerror(L, "attempt to yield across a C-call boundary"); + else + luaG_runerror(L, "attempt to yield from outside a coroutine"); + } + L->status = LUA_YIELD; + ci->u2.nyield = nresults; /* save number of results */ + if (isLua(ci)) { /* inside a hook? */ + lua_assert(!isLuacode(ci)); + api_check(L, nresults == 0, "hooks cannot yield values"); + api_check(L, k == NULL, "hooks cannot continue after yielding"); + } + else { + if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ + ci->u.c.ctx = ctx; /* save context */ + luaD_throw(L, LUA_YIELD); + } + lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ + lua_unlock(L); + return 0; /* return to 'luaD_hook' */ +} + + +/* +** Auxiliary structure to call 'luaF_close' in protected mode. +*/ +struct CloseP { + StkId level; + int status; +}; + + +/* +** Auxiliary function to call 'luaF_close' in protected mode. +*/ +static void closepaux (lua_State *L, void *ud) { + struct CloseP *pcl = cast(struct CloseP *, ud); + luaF_close(L, pcl->level, pcl->status, 0); +} + + +/* +** Calls 'luaF_close' in protected mode. Return the original status +** or, in case of errors, the new status. +*/ +int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) { + CallInfo *old_ci = L->ci; + lu_byte old_allowhooks = L->allowhook; + for (;;) { /* keep closing upvalues until no more errors */ + struct CloseP pcl; + pcl.level = restorestack(L, level); pcl.status = status; + status = luaD_rawrunprotected(L, &closepaux, &pcl); + if (l_likely(status == LUA_OK)) /* no more errors? */ + return pcl.status; + else { /* an error occurred; restore saved state and repeat */ + L->ci = old_ci; + L->allowhook = old_allowhooks; + } + } +} + + +/* +** Call the C function 'func' in protected mode, restoring basic +** thread information ('allowhook', etc.) and in particular +** its stack level in case of errors. +*/ +int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t old_top, ptrdiff_t ef) { + int status; + CallInfo *old_ci = L->ci; + lu_byte old_allowhooks = L->allowhook; + ptrdiff_t old_errfunc = L->errfunc; + L->errfunc = ef; + status = luaD_rawrunprotected(L, func, u); + if (l_unlikely(status != LUA_OK)) { /* an error occurred? */ + L->ci = old_ci; + L->allowhook = old_allowhooks; + status = luaD_closeprotected(L, old_top, status); + luaD_seterrorobj(L, status, restorestack(L, old_top)); + luaD_shrinkstack(L); /* restore stack size in case of overflow */ + } + L->errfunc = old_errfunc; + return status; +} + + + +/* +** Execute a protected parser. +*/ +struct SParser { /* data to 'f_parser' */ + ZIO *z; + Mbuffer buff; /* dynamic structure used by the scanner */ + Dyndata dyd; /* dynamic structures used by the parser */ + const char *mode; + const char *name; +}; + + +static void checkmode (lua_State *L, const char *mode, const char *x) { + if (mode && strchr(mode, x[0]) == NULL) { + luaO_pushfstring(L, + "attempt to load a %s chunk (mode is '%s')", x, mode); + luaD_throw(L, LUA_ERRSYNTAX); + } +} + + +static void f_parser (lua_State *L, void *ud) { + LClosure *cl; + struct SParser *p = cast(struct SParser *, ud); + int c = zgetc(p->z); /* read first character */ + if (c == LUA_SIGNATURE[0]) { + checkmode(L, p->mode, "binary"); + cl = luaU_undump(L, p->z, p->name); + } + else { + checkmode(L, p->mode, "text"); + cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); + } + lua_assert(cl->nupvalues == cl->p->sizeupvalues); + luaF_initupvals(L, cl); +} + + +int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode) { + struct SParser p; + int status; + incnny(L); /* cannot yield during parsing */ + p.z = z; p.name = name; p.mode = mode; + p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; + p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; + p.dyd.label.arr = NULL; p.dyd.label.size = 0; + luaZ_initbuffer(L, &p.buff); + status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc); + luaZ_freebuffer(L, &p.buff); + luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); + luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); + luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); + decnny(L); + return status; +} + + diff --git a/src/libs/3rdparty/lua/src/ldo.h b/src/libs/3rdparty/lua/src/ldo.h new file mode 100644 index 00000000000..1aa446ad09e --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldo.h @@ -0,0 +1,88 @@ +/* +** $Id: ldo.h $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#ifndef ldo_h +#define ldo_h + + +#include "llimits.h" +#include "lobject.h" +#include "lstate.h" +#include "lzio.h" + + +/* +** Macro to check stack size and grow stack if needed. Parameters +** 'pre'/'pos' allow the macro to preserve a pointer into the +** stack across reallocations, doing the work only when needed. +** It also allows the running of one GC step when the stack is +** reallocated. +** 'condmovestack' is used in heavy tests to force a stack reallocation +** at every check. +*/ +#define luaD_checkstackaux(L,n,pre,pos) \ + if (l_unlikely(L->stack_last.p - L->top.p <= (n))) \ + { pre; luaD_growstack(L, n, 1); pos; } \ + else { condmovestack(L,pre,pos); } + +/* In general, 'pre'/'pos' are empty (nothing to save) */ +#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) + + + +#define savestack(L,pt) (cast_charp(pt) - cast_charp(L->stack.p)) +#define restorestack(L,n) cast(StkId, cast_charp(L->stack.p) + (n)) + + +/* macro to check stack size, preserving 'p' */ +#define checkstackp(L,n,p) \ + luaD_checkstackaux(L, n, \ + ptrdiff_t t__ = savestack(L, p), /* save 'p' */ \ + p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ + + +/* macro to check stack size and GC, preserving 'p' */ +#define checkstackGCp(L,n,p) \ + luaD_checkstackaux(L, n, \ + ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ + luaC_checkGC(L), /* stack grow uses memory */ \ + p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ + + +/* macro to check stack size and GC */ +#define checkstackGC(L,fsize) \ + luaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0) + + +/* type of protected functions, to be ran by 'runprotected' */ +typedef void (*Pfunc) (lua_State *L, void *ud); + +LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); +LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, + const char *mode); +LUAI_FUNC void luaD_hook (lua_State *L, int event, int line, + int fTransfer, int nTransfer); +LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci); +LUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, + int narg1, int delta); +LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults); +LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); +LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); +LUAI_FUNC StkId luaD_tryfuncTM (lua_State *L, StkId func); +LUAI_FUNC int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status); +LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t oldtop, ptrdiff_t ef); +LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres); +LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror); +LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror); +LUAI_FUNC void luaD_shrinkstack (lua_State *L); +LUAI_FUNC void luaD_inctop (lua_State *L); + +LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); +LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); + +#endif + diff --git a/src/libs/3rdparty/lua/src/ldump.c b/src/libs/3rdparty/lua/src/ldump.c new file mode 100644 index 00000000000..f231691b779 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ldump.c @@ -0,0 +1,230 @@ +/* +** $Id: ldump.c $ +** save precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#define ldump_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lobject.h" +#include "lstate.h" +#include "lundump.h" + + +typedef struct { + lua_State *L; + lua_Writer writer; + void *data; + int strip; + int status; +} DumpState; + + +/* +** All high-level dumps go through dumpVector; you can change it to +** change the endianness of the result +*/ +#define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0])) + +#define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char)) + + +static void dumpBlock (DumpState *D, const void *b, size_t size) { + if (D->status == 0 && size > 0) { + lua_unlock(D->L); + D->status = (*D->writer)(D->L, b, size, D->data); + lua_lock(D->L); + } +} + + +#define dumpVar(D,x) dumpVector(D,&x,1) + + +static void dumpByte (DumpState *D, int y) { + lu_byte x = (lu_byte)y; + dumpVar(D, x); +} + + +/* +** 'dumpSize' buffer size: each byte can store up to 7 bits. (The "+6" +** rounds up the division.) +*/ +#define DIBS ((sizeof(size_t) * CHAR_BIT + 6) / 7) + +static void dumpSize (DumpState *D, size_t x) { + lu_byte buff[DIBS]; + int n = 0; + do { + buff[DIBS - (++n)] = x & 0x7f; /* fill buffer in reverse order */ + x >>= 7; + } while (x != 0); + buff[DIBS - 1] |= 0x80; /* mark last byte */ + dumpVector(D, buff + DIBS - n, n); +} + + +static void dumpInt (DumpState *D, int x) { + dumpSize(D, x); +} + + +static void dumpNumber (DumpState *D, lua_Number x) { + dumpVar(D, x); +} + + +static void dumpInteger (DumpState *D, lua_Integer x) { + dumpVar(D, x); +} + + +static void dumpString (DumpState *D, const TString *s) { + if (s == NULL) + dumpSize(D, 0); + else { + size_t size = tsslen(s); + const char *str = getstr(s); + dumpSize(D, size + 1); + dumpVector(D, str, size); + } +} + + +static void dumpCode (DumpState *D, const Proto *f) { + dumpInt(D, f->sizecode); + dumpVector(D, f->code, f->sizecode); +} + + +static void dumpFunction(DumpState *D, const Proto *f, TString *psource); + +static void dumpConstants (DumpState *D, const Proto *f) { + int i; + int n = f->sizek; + dumpInt(D, n); + for (i = 0; i < n; i++) { + const TValue *o = &f->k[i]; + int tt = ttypetag(o); + dumpByte(D, tt); + switch (tt) { + case LUA_VNUMFLT: + dumpNumber(D, fltvalue(o)); + break; + case LUA_VNUMINT: + dumpInteger(D, ivalue(o)); + break; + case LUA_VSHRSTR: + case LUA_VLNGSTR: + dumpString(D, tsvalue(o)); + break; + default: + lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE); + } + } +} + + +static void dumpProtos (DumpState *D, const Proto *f) { + int i; + int n = f->sizep; + dumpInt(D, n); + for (i = 0; i < n; i++) + dumpFunction(D, f->p[i], f->source); +} + + +static void dumpUpvalues (DumpState *D, const Proto *f) { + int i, n = f->sizeupvalues; + dumpInt(D, n); + for (i = 0; i < n; i++) { + dumpByte(D, f->upvalues[i].instack); + dumpByte(D, f->upvalues[i].idx); + dumpByte(D, f->upvalues[i].kind); + } +} + + +static void dumpDebug (DumpState *D, const Proto *f) { + int i, n; + n = (D->strip) ? 0 : f->sizelineinfo; + dumpInt(D, n); + dumpVector(D, f->lineinfo, n); + n = (D->strip) ? 0 : f->sizeabslineinfo; + dumpInt(D, n); + for (i = 0; i < n; i++) { + dumpInt(D, f->abslineinfo[i].pc); + dumpInt(D, f->abslineinfo[i].line); + } + n = (D->strip) ? 0 : f->sizelocvars; + dumpInt(D, n); + for (i = 0; i < n; i++) { + dumpString(D, f->locvars[i].varname); + dumpInt(D, f->locvars[i].startpc); + dumpInt(D, f->locvars[i].endpc); + } + n = (D->strip) ? 0 : f->sizeupvalues; + dumpInt(D, n); + for (i = 0; i < n; i++) + dumpString(D, f->upvalues[i].name); +} + + +static void dumpFunction (DumpState *D, const Proto *f, TString *psource) { + if (D->strip || f->source == psource) + dumpString(D, NULL); /* no debug info or same source as its parent */ + else + dumpString(D, f->source); + dumpInt(D, f->linedefined); + dumpInt(D, f->lastlinedefined); + dumpByte(D, f->numparams); + dumpByte(D, f->is_vararg); + dumpByte(D, f->maxstacksize); + dumpCode(D, f); + dumpConstants(D, f); + dumpUpvalues(D, f); + dumpProtos(D, f); + dumpDebug(D, f); +} + + +static void dumpHeader (DumpState *D) { + dumpLiteral(D, LUA_SIGNATURE); + dumpByte(D, LUAC_VERSION); + dumpByte(D, LUAC_FORMAT); + dumpLiteral(D, LUAC_DATA); + dumpByte(D, sizeof(Instruction)); + dumpByte(D, sizeof(lua_Integer)); + dumpByte(D, sizeof(lua_Number)); + dumpInteger(D, LUAC_INT); + dumpNumber(D, LUAC_NUM); +} + + +/* +** dump Lua function as precompiled chunk +*/ +int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data, + int strip) { + DumpState D; + D.L = L; + D.writer = w; + D.data = data; + D.strip = strip; + D.status = 0; + dumpHeader(&D); + dumpByte(&D, f->sizeupvalues); + dumpFunction(&D, f, NULL); + return D.status; +} + diff --git a/src/libs/3rdparty/lua/src/lfunc.c b/src/libs/3rdparty/lua/src/lfunc.c new file mode 100644 index 00000000000..0945f241de2 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lfunc.c @@ -0,0 +1,294 @@ +/* +** $Id: lfunc.c $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + +#define lfunc_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +CClosure *luaF_newCclosure (lua_State *L, int nupvals) { + GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals)); + CClosure *c = gco2ccl(o); + c->nupvalues = cast_byte(nupvals); + return c; +} + + +LClosure *luaF_newLclosure (lua_State *L, int nupvals) { + GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals)); + LClosure *c = gco2lcl(o); + c->p = NULL; + c->nupvalues = cast_byte(nupvals); + while (nupvals--) c->upvals[nupvals] = NULL; + return c; +} + + +/* +** fill a closure with new closed upvalues +*/ +void luaF_initupvals (lua_State *L, LClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) { + GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); + UpVal *uv = gco2upv(o); + uv->v.p = &uv->u.value; /* make it closed */ + setnilvalue(uv->v.p); + cl->upvals[i] = uv; + luaC_objbarrier(L, cl, uv); + } +} + + +/* +** Create a new upvalue at the given level, and link it to the list of +** open upvalues of 'L' after entry 'prev'. +**/ +static UpVal *newupval (lua_State *L, StkId level, UpVal **prev) { + GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); + UpVal *uv = gco2upv(o); + UpVal *next = *prev; + uv->v.p = s2v(level); /* current value lives in the stack */ + uv->u.open.next = next; /* link it to list of open upvalues */ + uv->u.open.previous = prev; + if (next) + next->u.open.previous = &uv->u.open.next; + *prev = uv; + if (!isintwups(L)) { /* thread not in list of threads with upvalues? */ + L->twups = G(L)->twups; /* link it to the list */ + G(L)->twups = L; + } + return uv; +} + + +/* +** Find and reuse, or create if it does not exist, an upvalue +** at the given level. +*/ +UpVal *luaF_findupval (lua_State *L, StkId level) { + UpVal **pp = &L->openupval; + UpVal *p; + lua_assert(isintwups(L) || L->openupval == NULL); + while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */ + lua_assert(!isdead(G(L), p)); + if (uplevel(p) == level) /* corresponding upvalue? */ + return p; /* return it */ + pp = &p->u.open.next; + } + /* not found: create a new upvalue after 'pp' */ + return newupval(L, level, pp); +} + + +/* +** Call closing method for object 'obj' with error message 'err'. The +** boolean 'yy' controls whether the call is yieldable. +** (This function assumes EXTRA_STACK.) +*/ +static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) { + StkId top = L->top.p; + const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE); + setobj2s(L, top, tm); /* will call metamethod... */ + setobj2s(L, top + 1, obj); /* with 'self' as the 1st argument */ + setobj2s(L, top + 2, err); /* and error msg. as 2nd argument */ + L->top.p = top + 3; /* add function and arguments */ + if (yy) + luaD_call(L, top, 0); + else + luaD_callnoyield(L, top, 0); +} + + +/* +** Check whether object at given level has a close metamethod and raise +** an error if not. +*/ +static void checkclosemth (lua_State *L, StkId level) { + const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE); + if (ttisnil(tm)) { /* no metamethod? */ + int idx = cast_int(level - L->ci->func.p); /* variable index */ + const char *vname = luaG_findlocal(L, L->ci, idx, NULL); + if (vname == NULL) vname = "?"; + luaG_runerror(L, "variable '%s' got a non-closable value", vname); + } +} + + +/* +** Prepare and call a closing method. +** If status is CLOSEKTOP, the call to the closing method will be pushed +** at the top of the stack. Otherwise, values can be pushed right after +** the 'level' of the upvalue being closed, as everything after that +** won't be used again. +*/ +static void prepcallclosemth (lua_State *L, StkId level, int status, int yy) { + TValue *uv = s2v(level); /* value being closed */ + TValue *errobj; + if (status == CLOSEKTOP) + errobj = &G(L)->nilvalue; /* error object is nil */ + else { /* 'luaD_seterrorobj' will set top to level + 2 */ + errobj = s2v(level + 1); /* error object goes after 'uv' */ + luaD_seterrorobj(L, status, level + 1); /* set error object */ + } + callclosemethod(L, uv, errobj, yy); +} + + +/* +** Maximum value for deltas in 'tbclist', dependent on the type +** of delta. (This macro assumes that an 'L' is in scope where it +** is used.) +*/ +#define MAXDELTA \ + ((256ul << ((sizeof(L->stack.p->tbclist.delta) - 1) * 8)) - 1) + + +/* +** Insert a variable in the list of to-be-closed variables. +*/ +void luaF_newtbcupval (lua_State *L, StkId level) { + lua_assert(level > L->tbclist.p); + if (l_isfalse(s2v(level))) + return; /* false doesn't need to be closed */ + checkclosemth(L, level); /* value must have a close method */ + while (cast_uint(level - L->tbclist.p) > MAXDELTA) { + L->tbclist.p += MAXDELTA; /* create a dummy node at maximum delta */ + L->tbclist.p->tbclist.delta = 0; + } + level->tbclist.delta = cast(unsigned short, level - L->tbclist.p); + L->tbclist.p = level; +} + + +void luaF_unlinkupval (UpVal *uv) { + lua_assert(upisopen(uv)); + *uv->u.open.previous = uv->u.open.next; + if (uv->u.open.next) + uv->u.open.next->u.open.previous = uv->u.open.previous; +} + + +/* +** Close all upvalues up to the given stack level. +*/ +void luaF_closeupval (lua_State *L, StkId level) { + UpVal *uv; + StkId upl; /* stack index pointed by 'uv' */ + while ((uv = L->openupval) != NULL && (upl = uplevel(uv)) >= level) { + TValue *slot = &uv->u.value; /* new position for value */ + lua_assert(uplevel(uv) < L->top.p); + luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */ + setobj(L, slot, uv->v.p); /* move value to upvalue slot */ + uv->v.p = slot; /* now current value lives here */ + if (!iswhite(uv)) { /* neither white nor dead? */ + nw2black(uv); /* closed upvalues cannot be gray */ + luaC_barrier(L, uv, slot); + } + } +} + + +/* +** Remove first element from the tbclist plus its dummy nodes. +*/ +static void poptbclist (lua_State *L) { + StkId tbc = L->tbclist.p; + lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */ + tbc -= tbc->tbclist.delta; + while (tbc > L->stack.p && tbc->tbclist.delta == 0) + tbc -= MAXDELTA; /* remove dummy nodes */ + L->tbclist.p = tbc; +} + + +/* +** Close all upvalues and to-be-closed variables up to the given stack +** level. Return restored 'level'. +*/ +StkId luaF_close (lua_State *L, StkId level, int status, int yy) { + ptrdiff_t levelrel = savestack(L, level); + luaF_closeupval(L, level); /* first, close the upvalues */ + while (L->tbclist.p >= level) { /* traverse tbc's down to that level */ + StkId tbc = L->tbclist.p; /* get variable index */ + poptbclist(L); /* remove it from list */ + prepcallclosemth(L, tbc, status, yy); /* close variable */ + level = restorestack(L, levelrel); + } + return level; +} + + +Proto *luaF_newproto (lua_State *L) { + GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto)); + Proto *f = gco2p(o); + f->k = NULL; + f->sizek = 0; + f->p = NULL; + f->sizep = 0; + f->code = NULL; + f->sizecode = 0; + f->lineinfo = NULL; + f->sizelineinfo = 0; + f->abslineinfo = NULL; + f->sizeabslineinfo = 0; + f->upvalues = NULL; + f->sizeupvalues = 0; + f->numparams = 0; + f->is_vararg = 0; + f->maxstacksize = 0; + f->locvars = NULL; + f->sizelocvars = 0; + f->linedefined = 0; + f->lastlinedefined = 0; + f->source = NULL; + return f; +} + + +void luaF_freeproto (lua_State *L, Proto *f) { + luaM_freearray(L, f->code, f->sizecode); + luaM_freearray(L, f->p, f->sizep); + luaM_freearray(L, f->k, f->sizek); + luaM_freearray(L, f->lineinfo, f->sizelineinfo); + luaM_freearray(L, f->abslineinfo, f->sizeabslineinfo); + luaM_freearray(L, f->locvars, f->sizelocvars); + luaM_freearray(L, f->upvalues, f->sizeupvalues); + luaM_free(L, f); +} + + +/* +** Look for n-th local variable at line 'line' in function 'func'. +** Returns NULL if not found. +*/ +const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { + int i; + for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { + if (pc < f->locvars[i].endpc) { /* is variable active? */ + local_number--; + if (local_number == 0) + return getstr(f->locvars[i].varname); + } + } + return NULL; /* not found */ +} + diff --git a/src/libs/3rdparty/lua/src/lfunc.h b/src/libs/3rdparty/lua/src/lfunc.h new file mode 100644 index 00000000000..3be265efb58 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lfunc.h @@ -0,0 +1,64 @@ +/* +** $Id: lfunc.h $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + +#ifndef lfunc_h +#define lfunc_h + + +#include "lobject.h" + + +#define sizeCclosure(n) (cast_int(offsetof(CClosure, upvalue)) + \ + cast_int(sizeof(TValue)) * (n)) + +#define sizeLclosure(n) (cast_int(offsetof(LClosure, upvals)) + \ + cast_int(sizeof(TValue *)) * (n)) + + +/* test whether thread is in 'twups' list */ +#define isintwups(L) (L->twups != L) + + +/* +** maximum number of upvalues in a closure (both C and Lua). (Value +** must fit in a VM register.) +*/ +#define MAXUPVAL 255 + + +#define upisopen(up) ((up)->v.p != &(up)->u.value) + + +#define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v.p)) + + +/* +** maximum number of misses before giving up the cache of closures +** in prototypes +*/ +#define MAXMISS 10 + + + +/* special status to close upvalues preserving the top of the stack */ +#define CLOSEKTOP (-1) + + +LUAI_FUNC Proto *luaF_newproto (lua_State *L); +LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals); +LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals); +LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); +LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); +LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level); +LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level); +LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, int status, int yy); +LUAI_FUNC void luaF_unlinkupval (UpVal *uv); +LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); +LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, + int pc); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lgc.c b/src/libs/3rdparty/lua/src/lgc.c new file mode 100644 index 00000000000..a3094ff5712 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lgc.c @@ -0,0 +1,1739 @@ +/* +** $Id: lgc.c $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#define lgc_c +#define LUA_CORE + +#include "lprefix.h" + +#include +#include + + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + +/* +** Maximum number of elements to sweep in each single step. +** (Large enough to dissipate fixed overheads but small enough +** to allow small steps for the collector.) +*/ +#define GCSWEEPMAX 100 + +/* +** Maximum number of finalizers to call in each single step. +*/ +#define GCFINMAX 10 + + +/* +** Cost of calling one finalizer. +*/ +#define GCFINALIZECOST 50 + + +/* +** The equivalent, in bytes, of one unit of "work" (visiting a slot, +** sweeping an object, etc.) +*/ +#define WORK2MEM sizeof(TValue) + + +/* +** macro to adjust 'pause': 'pause' is actually used like +** 'pause / PAUSEADJ' (value chosen by tests) +*/ +#define PAUSEADJ 100 + + +/* mask with all color bits */ +#define maskcolors (bitmask(BLACKBIT) | WHITEBITS) + +/* mask with all GC bits */ +#define maskgcbits (maskcolors | AGEBITS) + + +/* macro to erase all color bits then set only the current white bit */ +#define makewhite(g,x) \ + (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g))) + +/* make an object gray (neither white nor black) */ +#define set2gray(x) resetbits(x->marked, maskcolors) + + +/* make an object black (coming from any color) */ +#define set2black(x) \ + (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT))) + + +#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) + +#define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) + + +/* +** Protected access to objects in values +*/ +#define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) + + +#define markvalue(g,o) { checkliveness(g->mainthread,o); \ + if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } + +#define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } + +#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } + +/* +** mark an object that can be NULL (either because it is really optional, +** or it was stripped as debug info, or inside an uncompleted structure) +*/ +#define markobjectN(g,t) { if (t) markobject(g,t); } + +static void reallymarkobject (global_State *g, GCObject *o); +static lu_mem atomic (lua_State *L); +static void entersweep (lua_State *L); + + +/* +** {====================================================== +** Generic functions +** ======================================================= +*/ + + +/* +** one after last element in a hash array +*/ +#define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) + + +static GCObject **getgclist (GCObject *o) { + switch (o->tt) { + case LUA_VTABLE: return &gco2t(o)->gclist; + case LUA_VLCL: return &gco2lcl(o)->gclist; + case LUA_VCCL: return &gco2ccl(o)->gclist; + case LUA_VTHREAD: return &gco2th(o)->gclist; + case LUA_VPROTO: return &gco2p(o)->gclist; + case LUA_VUSERDATA: { + Udata *u = gco2u(o); + lua_assert(u->nuvalue > 0); + return &u->gclist; + } + default: lua_assert(0); return 0; + } +} + + +/* +** Link a collectable object 'o' with a known type into the list 'p'. +** (Must be a macro to access the 'gclist' field in different types.) +*/ +#define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p)) + +static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) { + lua_assert(!isgray(o)); /* cannot be in a gray list */ + *pnext = *list; + *list = o; + set2gray(o); /* now it is */ +} + + +/* +** Link a generic collectable object 'o' into the list 'p'. +*/ +#define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p)) + + + +/* +** Clear keys for empty entries in tables. If entry is empty, mark its +** entry as dead. This allows the collection of the key, but keeps its +** entry in the table: its removal could break a chain and could break +** a table traversal. Other places never manipulate dead keys, because +** its associated empty value is enough to signal that the entry is +** logically empty. +*/ +static void clearkey (Node *n) { + lua_assert(isempty(gval(n))); + if (keyiscollectable(n)) + setdeadkey(n); /* unused key; remove it */ +} + + +/* +** tells whether a key or value can be cleared from a weak +** table. Non-collectable objects are never removed from weak +** tables. Strings behave as 'values', so are never removed too. for +** other objects: if really collected, cannot keep them; for objects +** being finalized, keep them in keys, but not in values +*/ +static int iscleared (global_State *g, const GCObject *o) { + if (o == NULL) return 0; /* non-collectable value */ + else if (novariant(o->tt) == LUA_TSTRING) { + markobject(g, o); /* strings are 'values', so are never weak */ + return 0; + } + else return iswhite(o); +} + + +/* +** Barrier that moves collector forward, that is, marks the white object +** 'v' being pointed by the black object 'o'. In the generational +** mode, 'v' must also become old, if 'o' is old; however, it cannot +** be changed directly to OLD, because it may still point to non-old +** objects. So, it is marked as OLD0. In the next cycle it will become +** OLD1, and in the next it will finally become OLD (regular old). By +** then, any object it points to will also be old. If called in the +** incremental sweep phase, it clears the black object to white (sweep +** it) to avoid other barrier calls for this same object. (That cannot +** be done is generational mode, as its sweep does not distinguish +** whites from deads.) +*/ +void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { + global_State *g = G(L); + lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); + if (keepinvariant(g)) { /* must keep invariant? */ + reallymarkobject(g, v); /* restore invariant */ + if (isold(o)) { + lua_assert(!isold(v)); /* white object could not be old */ + setage(v, G_OLD0); /* restore generational invariant */ + } + } + else { /* sweep phase */ + lua_assert(issweepphase(g)); + if (g->gckind == KGC_INC) /* incremental mode? */ + makewhite(g, o); /* mark 'o' as white to avoid other barriers */ + } +} + + +/* +** barrier that moves collector backward, that is, mark the black object +** pointing to a white object as gray again. +*/ +void luaC_barrierback_ (lua_State *L, GCObject *o) { + global_State *g = G(L); + lua_assert(isblack(o) && !isdead(g, o)); + lua_assert((g->gckind == KGC_GEN) == (isold(o) && getage(o) != G_TOUCHED1)); + if (getage(o) == G_TOUCHED2) /* already in gray list? */ + set2gray(o); /* make it gray to become touched1 */ + else /* link it in 'grayagain' and paint it gray */ + linkobjgclist(o, g->grayagain); + if (isold(o)) /* generational mode? */ + setage(o, G_TOUCHED1); /* touched in current cycle */ +} + + +void luaC_fix (lua_State *L, GCObject *o) { + global_State *g = G(L); + lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ + set2gray(o); /* they will be gray forever */ + setage(o, G_OLD); /* and old forever */ + g->allgc = o->next; /* remove object from 'allgc' list */ + o->next = g->fixedgc; /* link it to 'fixedgc' list */ + g->fixedgc = o; +} + + +/* +** create a new collectable object (with given type, size, and offset) +** and link it to 'allgc' list. +*/ +GCObject *luaC_newobjdt (lua_State *L, int tt, size_t sz, size_t offset) { + global_State *g = G(L); + char *p = cast_charp(luaM_newobject(L, novariant(tt), sz)); + GCObject *o = cast(GCObject *, p + offset); + o->marked = luaC_white(g); + o->tt = tt; + o->next = g->allgc; + g->allgc = o; + return o; +} + + +GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { + return luaC_newobjdt(L, tt, sz, 0); +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Mark functions +** ======================================================= +*/ + + +/* +** Mark an object. Userdata with no user values, strings, and closed +** upvalues are visited and turned black here. Open upvalues are +** already indirectly linked through their respective threads in the +** 'twups' list, so they don't go to the gray list; nevertheless, they +** are kept gray to avoid barriers, as their values will be revisited +** by the thread or by 'remarkupvals'. Other objects are added to the +** gray list to be visited (and turned black) later. Both userdata and +** upvalues can call this function recursively, but this recursion goes +** for at most two levels: An upvalue cannot refer to another upvalue +** (only closures can), and a userdata's metatable must be a table. +*/ +static void reallymarkobject (global_State *g, GCObject *o) { + switch (o->tt) { + case LUA_VSHRSTR: + case LUA_VLNGSTR: { + set2black(o); /* nothing to visit */ + break; + } + case LUA_VUPVAL: { + UpVal *uv = gco2upv(o); + if (upisopen(uv)) + set2gray(uv); /* open upvalues are kept gray */ + else + set2black(uv); /* closed upvalues are visited here */ + markvalue(g, uv->v.p); /* mark its content */ + break; + } + case LUA_VUSERDATA: { + Udata *u = gco2u(o); + if (u->nuvalue == 0) { /* no user values? */ + markobjectN(g, u->metatable); /* mark its metatable */ + set2black(u); /* nothing else to mark */ + break; + } + /* else... */ + } /* FALLTHROUGH */ + case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: + case LUA_VTHREAD: case LUA_VPROTO: { + linkobjgclist(o, g->gray); /* to be visited later */ + break; + } + default: lua_assert(0); break; + } +} + + +/* +** mark metamethods for basic types +*/ +static void markmt (global_State *g) { + int i; + for (i=0; i < LUA_NUMTAGS; i++) + markobjectN(g, g->mt[i]); +} + + +/* +** mark all objects in list of being-finalized +*/ +static lu_mem markbeingfnz (global_State *g) { + GCObject *o; + lu_mem count = 0; + for (o = g->tobefnz; o != NULL; o = o->next) { + count++; + markobject(g, o); + } + return count; +} + + +/* +** For each non-marked thread, simulates a barrier between each open +** upvalue and its value. (If the thread is collected, the value will be +** assigned to the upvalue, but then it can be too late for the barrier +** to act. The "barrier" does not need to check colors: A non-marked +** thread must be young; upvalues cannot be older than their threads; so +** any visited upvalue must be young too.) Also removes the thread from +** the list, as it was already visited. Removes also threads with no +** upvalues, as they have nothing to be checked. (If the thread gets an +** upvalue later, it will be linked in the list again.) +*/ +static int remarkupvals (global_State *g) { + lua_State *thread; + lua_State **p = &g->twups; + int work = 0; /* estimate of how much work was done here */ + while ((thread = *p) != NULL) { + work++; + if (!iswhite(thread) && thread->openupval != NULL) + p = &thread->twups; /* keep marked thread with upvalues in the list */ + else { /* thread is not marked or without upvalues */ + UpVal *uv; + lua_assert(!isold(thread) || thread->openupval == NULL); + *p = thread->twups; /* remove thread from the list */ + thread->twups = thread; /* mark that it is out of list */ + for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { + lua_assert(getage(uv) <= getage(thread)); + work++; + if (!iswhite(uv)) { /* upvalue already visited? */ + lua_assert(upisopen(uv) && isgray(uv)); + markvalue(g, uv->v.p); /* mark its value */ + } + } + } + } + return work; +} + + +static void cleargraylists (global_State *g) { + g->gray = g->grayagain = NULL; + g->weak = g->allweak = g->ephemeron = NULL; +} + + +/* +** mark root set and reset all gray lists, to start a new collection +*/ +static void restartcollection (global_State *g) { + cleargraylists(g); + markobject(g, g->mainthread); + markvalue(g, &g->l_registry); + markmt(g); + markbeingfnz(g); /* mark any finalizing object left from previous cycle */ +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Traverse functions +** ======================================================= +*/ + + +/* +** Check whether object 'o' should be kept in the 'grayagain' list for +** post-processing by 'correctgraylist'. (It could put all old objects +** in the list and leave all the work to 'correctgraylist', but it is +** more efficient to avoid adding elements that will be removed.) Only +** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go +** back to a gray list, but then it must become OLD. (That is what +** 'correctgraylist' does when it finds a TOUCHED2 object.) +*/ +static void genlink (global_State *g, GCObject *o) { + lua_assert(isblack(o)); + if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */ + linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */ + } /* everything else do not need to be linked back */ + else if (getage(o) == G_TOUCHED2) + changeage(o, G_TOUCHED2, G_OLD); /* advance age */ +} + + +/* +** Traverse a table with weak values and link it to proper list. During +** propagate phase, keep it in 'grayagain' list, to be revisited in the +** atomic phase. In the atomic phase, if table has any white value, +** put it in 'weak' list, to be cleared. +*/ +static void traverseweakvalue (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + /* if there is array part, assume it may have white values (it is not + worth traversing it now just to check) */ + int hasclears = (h->alimit > 0); + for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ + if (isempty(gval(n))) /* entry is empty? */ + clearkey(n); /* clear its key */ + else { + lua_assert(!keyisnil(n)); + markkey(g, n); + if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ + hasclears = 1; /* table will have to be cleared */ + } + } + if (g->gcstate == GCSatomic && hasclears) + linkgclist(h, g->weak); /* has to be cleared later */ + else + linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ +} + + +/* +** Traverse an ephemeron table and link it to proper list. Returns true +** iff any object was marked during this traversal (which implies that +** convergence has to continue). During propagation phase, keep table +** in 'grayagain' list, to be visited again in the atomic phase. In +** the atomic phase, if table has any white->white entry, it has to +** be revisited during ephemeron convergence (as that key may turn +** black). Otherwise, if it has any white key, table has to be cleared +** (in the atomic phase). In generational mode, some tables +** must be kept in some gray list for post-processing; this is done +** by 'genlink'. +*/ +static int traverseephemeron (global_State *g, Table *h, int inv) { + int marked = 0; /* true if an object is marked in this traversal */ + int hasclears = 0; /* true if table has white keys */ + int hasww = 0; /* true if table has entry "white-key -> white-value" */ + unsigned int i; + unsigned int asize = luaH_realasize(h); + unsigned int nsize = sizenode(h); + /* traverse array part */ + for (i = 0; i < asize; i++) { + if (valiswhite(&h->array[i])) { + marked = 1; + reallymarkobject(g, gcvalue(&h->array[i])); + } + } + /* traverse hash part; if 'inv', traverse descending + (see 'convergeephemerons') */ + for (i = 0; i < nsize; i++) { + Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); + if (isempty(gval(n))) /* entry is empty? */ + clearkey(n); /* clear its key */ + else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ + hasclears = 1; /* table must be cleared */ + if (valiswhite(gval(n))) /* value not marked yet? */ + hasww = 1; /* white-white entry */ + } + else if (valiswhite(gval(n))) { /* value not marked yet? */ + marked = 1; + reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ + } + } + /* link table into proper list */ + if (g->gcstate == GCSpropagate) + linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ + else if (hasww) /* table has white->white entries? */ + linkgclist(h, g->ephemeron); /* have to propagate again */ + else if (hasclears) /* table has white keys? */ + linkgclist(h, g->allweak); /* may have to clean white keys */ + else + genlink(g, obj2gco(h)); /* check whether collector still needs to see it */ + return marked; +} + + +static void traversestrongtable (global_State *g, Table *h) { + Node *n, *limit = gnodelast(h); + unsigned int i; + unsigned int asize = luaH_realasize(h); + for (i = 0; i < asize; i++) /* traverse array part */ + markvalue(g, &h->array[i]); + for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ + if (isempty(gval(n))) /* entry is empty? */ + clearkey(n); /* clear its key */ + else { + lua_assert(!keyisnil(n)); + markkey(g, n); + markvalue(g, gval(n)); + } + } + genlink(g, obj2gco(h)); +} + + +static lu_mem traversetable (global_State *g, Table *h) { + const char *weakkey, *weakvalue; + const TValue *mode = gfasttm(g, h->metatable, TM_MODE); + markobjectN(g, h->metatable); + if (mode && ttisstring(mode) && /* is there a weak mode? */ + (cast_void(weakkey = strchr(svalue(mode), 'k')), + cast_void(weakvalue = strchr(svalue(mode), 'v')), + (weakkey || weakvalue))) { /* is really weak? */ + if (!weakkey) /* strong keys? */ + traverseweakvalue(g, h); + else if (!weakvalue) /* strong values? */ + traverseephemeron(g, h, 0); + else /* all weak */ + linkgclist(h, g->allweak); /* nothing to traverse now */ + } + else /* not weak */ + traversestrongtable(g, h); + return 1 + h->alimit + 2 * allocsizenode(h); +} + + +static int traverseudata (global_State *g, Udata *u) { + int i; + markobjectN(g, u->metatable); /* mark its metatable */ + for (i = 0; i < u->nuvalue; i++) + markvalue(g, &u->uv[i].uv); + genlink(g, obj2gco(u)); + return 1 + u->nuvalue; +} + + +/* +** Traverse a prototype. (While a prototype is being build, its +** arrays can be larger than needed; the extra slots are filled with +** NULL, so the use of 'markobjectN') +*/ +static int traverseproto (global_State *g, Proto *f) { + int i; + markobjectN(g, f->source); + for (i = 0; i < f->sizek; i++) /* mark literals */ + markvalue(g, &f->k[i]); + for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ + markobjectN(g, f->upvalues[i].name); + for (i = 0; i < f->sizep; i++) /* mark nested protos */ + markobjectN(g, f->p[i]); + for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ + markobjectN(g, f->locvars[i].varname); + return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; +} + + +static int traverseCclosure (global_State *g, CClosure *cl) { + int i; + for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ + markvalue(g, &cl->upvalue[i]); + return 1 + cl->nupvalues; +} + +/* +** Traverse a Lua closure, marking its prototype and its upvalues. +** (Both can be NULL while closure is being created.) +*/ +static int traverseLclosure (global_State *g, LClosure *cl) { + int i; + markobjectN(g, cl->p); /* mark its prototype */ + for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ + UpVal *uv = cl->upvals[i]; + markobjectN(g, uv); /* mark upvalue */ + } + return 1 + cl->nupvalues; +} + + +/* +** Traverse a thread, marking the elements in the stack up to its top +** and cleaning the rest of the stack in the final traversal. That +** ensures that the entire stack have valid (non-dead) objects. +** Threads have no barriers. In gen. mode, old threads must be visited +** at every cycle, because they might point to young objects. In inc. +** mode, the thread can still be modified before the end of the cycle, +** and therefore it must be visited again in the atomic phase. To ensure +** these visits, threads must return to a gray list if they are not new +** (which can only happen in generational mode) or if the traverse is in +** the propagate phase (which can only happen in incremental mode). +*/ +static int traversethread (global_State *g, lua_State *th) { + UpVal *uv; + StkId o = th->stack.p; + if (isold(th) || g->gcstate == GCSpropagate) + linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ + if (o == NULL) + return 1; /* stack not completely built yet */ + lua_assert(g->gcstate == GCSatomic || + th->openupval == NULL || isintwups(th)); + for (; o < th->top.p; o++) /* mark live elements in the stack */ + markvalue(g, s2v(o)); + for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) + markobject(g, uv); /* open upvalues cannot be collected */ + if (g->gcstate == GCSatomic) { /* final traversal? */ + for (; o < th->stack_last.p + EXTRA_STACK; o++) + setnilvalue(s2v(o)); /* clear dead stack slice */ + /* 'remarkupvals' may have removed thread from 'twups' list */ + if (!isintwups(th) && th->openupval != NULL) { + th->twups = g->twups; /* link it back to the list */ + g->twups = th; + } + } + else if (!g->gcemergency) + luaD_shrinkstack(th); /* do not change stack in emergency cycle */ + return 1 + stacksize(th); +} + + +/* +** traverse one gray object, turning it to black. +*/ +static lu_mem propagatemark (global_State *g) { + GCObject *o = g->gray; + nw2black(o); + g->gray = *getgclist(o); /* remove from 'gray' list */ + switch (o->tt) { + case LUA_VTABLE: return traversetable(g, gco2t(o)); + case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); + case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); + case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); + case LUA_VPROTO: return traverseproto(g, gco2p(o)); + case LUA_VTHREAD: return traversethread(g, gco2th(o)); + default: lua_assert(0); return 0; + } +} + + +static lu_mem propagateall (global_State *g) { + lu_mem tot = 0; + while (g->gray) + tot += propagatemark(g); + return tot; +} + + +/* +** Traverse all ephemeron tables propagating marks from keys to values. +** Repeat until it converges, that is, nothing new is marked. 'dir' +** inverts the direction of the traversals, trying to speed up +** convergence on chains in the same table. +** +*/ +static void convergeephemerons (global_State *g) { + int changed; + int dir = 0; + do { + GCObject *w; + GCObject *next = g->ephemeron; /* get ephemeron list */ + g->ephemeron = NULL; /* tables may return to this list when traversed */ + changed = 0; + while ((w = next) != NULL) { /* for each ephemeron table */ + Table *h = gco2t(w); + next = h->gclist; /* list is rebuilt during loop */ + nw2black(h); /* out of the list (for now) */ + if (traverseephemeron(g, h, dir)) { /* marked some value? */ + propagateall(g); /* propagate changes */ + changed = 1; /* will have to revisit all ephemeron tables */ + } + } + dir = !dir; /* invert direction next time */ + } while (changed); /* repeat until no more changes */ +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Sweep Functions +** ======================================================= +*/ + + +/* +** clear entries with unmarked keys from all weaktables in list 'l' +*/ +static void clearbykeys (global_State *g, GCObject *l) { + for (; l; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *limit = gnodelast(h); + Node *n; + for (n = gnode(h, 0); n < limit; n++) { + if (iscleared(g, gckeyN(n))) /* unmarked key? */ + setempty(gval(n)); /* remove entry */ + if (isempty(gval(n))) /* is entry empty? */ + clearkey(n); /* clear its key */ + } + } +} + + +/* +** clear entries with unmarked values from all weaktables in list 'l' up +** to element 'f' +*/ +static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { + for (; l != f; l = gco2t(l)->gclist) { + Table *h = gco2t(l); + Node *n, *limit = gnodelast(h); + unsigned int i; + unsigned int asize = luaH_realasize(h); + for (i = 0; i < asize; i++) { + TValue *o = &h->array[i]; + if (iscleared(g, gcvalueN(o))) /* value was collected? */ + setempty(o); /* remove entry */ + } + for (n = gnode(h, 0); n < limit; n++) { + if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ + setempty(gval(n)); /* remove entry */ + if (isempty(gval(n))) /* is entry empty? */ + clearkey(n); /* clear its key */ + } + } +} + + +static void freeupval (lua_State *L, UpVal *uv) { + if (upisopen(uv)) + luaF_unlinkupval(uv); + luaM_free(L, uv); +} + + +static void freeobj (lua_State *L, GCObject *o) { + switch (o->tt) { + case LUA_VPROTO: + luaF_freeproto(L, gco2p(o)); + break; + case LUA_VUPVAL: + freeupval(L, gco2upv(o)); + break; + case LUA_VLCL: { + LClosure *cl = gco2lcl(o); + luaM_freemem(L, cl, sizeLclosure(cl->nupvalues)); + break; + } + case LUA_VCCL: { + CClosure *cl = gco2ccl(o); + luaM_freemem(L, cl, sizeCclosure(cl->nupvalues)); + break; + } + case LUA_VTABLE: + luaH_free(L, gco2t(o)); + break; + case LUA_VTHREAD: + luaE_freethread(L, gco2th(o)); + break; + case LUA_VUSERDATA: { + Udata *u = gco2u(o); + luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); + break; + } + case LUA_VSHRSTR: { + TString *ts = gco2ts(o); + luaS_remove(L, ts); /* remove it from hash table */ + luaM_freemem(L, ts, sizelstring(ts->shrlen)); + break; + } + case LUA_VLNGSTR: { + TString *ts = gco2ts(o); + luaM_freemem(L, ts, sizelstring(ts->u.lnglen)); + break; + } + default: lua_assert(0); + } +} + + +/* +** sweep at most 'countin' elements from a list of GCObjects erasing dead +** objects, where a dead object is one marked with the old (non current) +** white; change all non-dead objects back to white, preparing for next +** collection cycle. Return where to continue the traversal or NULL if +** list is finished. ('*countout' gets the number of elements traversed.) +*/ +static GCObject **sweeplist (lua_State *L, GCObject **p, int countin, + int *countout) { + global_State *g = G(L); + int ow = otherwhite(g); + int i; + int white = luaC_white(g); /* current white */ + for (i = 0; *p != NULL && i < countin; i++) { + GCObject *curr = *p; + int marked = curr->marked; + if (isdeadm(ow, marked)) { /* is 'curr' dead? */ + *p = curr->next; /* remove 'curr' from list */ + freeobj(L, curr); /* erase 'curr' */ + } + else { /* change mark to 'white' */ + curr->marked = cast_byte((marked & ~maskgcbits) | white); + p = &curr->next; /* go to next element */ + } + } + if (countout) + *countout = i; /* number of elements traversed */ + return (*p == NULL) ? NULL : p; +} + + +/* +** sweep a list until a live object (or end of list) +*/ +static GCObject **sweeptolive (lua_State *L, GCObject **p) { + GCObject **old = p; + do { + p = sweeplist(L, p, 1, NULL); + } while (p == old); + return p; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Finalization +** ======================================================= +*/ + +/* +** If possible, shrink string table. +*/ +static void checkSizes (lua_State *L, global_State *g) { + if (!g->gcemergency) { + if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */ + l_mem olddebt = g->GCdebt; + luaS_resize(L, g->strt.size / 2); + g->GCestimate += g->GCdebt - olddebt; /* correct estimate */ + } + } +} + + +/* +** Get the next udata to be finalized from the 'tobefnz' list, and +** link it back into the 'allgc' list. +*/ +static GCObject *udata2finalize (global_State *g) { + GCObject *o = g->tobefnz; /* get first element */ + lua_assert(tofinalize(o)); + g->tobefnz = o->next; /* remove it from 'tobefnz' list */ + o->next = g->allgc; /* return it to 'allgc' list */ + g->allgc = o; + resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ + if (issweepphase(g)) + makewhite(g, o); /* "sweep" object */ + else if (getage(o) == G_OLD1) + g->firstold1 = o; /* it is the first OLD1 object in the list */ + return o; +} + + +static void dothecall (lua_State *L, void *ud) { + UNUSED(ud); + luaD_callnoyield(L, L->top.p - 2, 0); +} + + +static void GCTM (lua_State *L) { + global_State *g = G(L); + const TValue *tm; + TValue v; + lua_assert(!g->gcemergency); + setgcovalue(L, &v, udata2finalize(g)); + tm = luaT_gettmbyobj(L, &v, TM_GC); + if (!notm(tm)) { /* is there a finalizer? */ + int status; + lu_byte oldah = L->allowhook; + int oldgcstp = g->gcstp; + g->gcstp |= GCSTPGC; /* avoid GC steps */ + L->allowhook = 0; /* stop debug hooks during GC metamethod */ + setobj2s(L, L->top.p++, tm); /* push finalizer... */ + setobj2s(L, L->top.p++, &v); /* ... and its argument */ + L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ + status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0); + L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ + L->allowhook = oldah; /* restore hooks */ + g->gcstp = oldgcstp; /* restore state */ + if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */ + luaE_warnerror(L, "__gc"); + L->top.p--; /* pops error object */ + } + } +} + + +/* +** Call a few finalizers +*/ +static int runafewfinalizers (lua_State *L, int n) { + global_State *g = G(L); + int i; + for (i = 0; i < n && g->tobefnz; i++) + GCTM(L); /* call one finalizer */ + return i; +} + + +/* +** call all pending finalizers +*/ +static void callallpendingfinalizers (lua_State *L) { + global_State *g = G(L); + while (g->tobefnz) + GCTM(L); +} + + +/* +** find last 'next' field in list 'p' list (to add elements in its end) +*/ +static GCObject **findlast (GCObject **p) { + while (*p != NULL) + p = &(*p)->next; + return p; +} + + +/* +** Move all unreachable objects (or 'all' objects) that need +** finalization from list 'finobj' to list 'tobefnz' (to be finalized). +** (Note that objects after 'finobjold1' cannot be white, so they +** don't need to be traversed. In incremental mode, 'finobjold1' is NULL, +** so the whole list is traversed.) +*/ +static void separatetobefnz (global_State *g, int all) { + GCObject *curr; + GCObject **p = &g->finobj; + GCObject **lastnext = findlast(&g->tobefnz); + while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */ + lua_assert(tofinalize(curr)); + if (!(iswhite(curr) || all)) /* not being collected? */ + p = &curr->next; /* don't bother with it */ + else { + if (curr == g->finobjsur) /* removing 'finobjsur'? */ + g->finobjsur = curr->next; /* correct it */ + *p = curr->next; /* remove 'curr' from 'finobj' list */ + curr->next = *lastnext; /* link at the end of 'tobefnz' list */ + *lastnext = curr; + lastnext = &curr->next; + } + } +} + + +/* +** If pointer 'p' points to 'o', move it to the next element. +*/ +static void checkpointer (GCObject **p, GCObject *o) { + if (o == *p) + *p = o->next; +} + + +/* +** Correct pointers to objects inside 'allgc' list when +** object 'o' is being removed from the list. +*/ +static void correctpointers (global_State *g, GCObject *o) { + checkpointer(&g->survival, o); + checkpointer(&g->old1, o); + checkpointer(&g->reallyold, o); + checkpointer(&g->firstold1, o); +} + + +/* +** if object 'o' has a finalizer, remove it from 'allgc' list (must +** search the list to find it) and link it in 'finobj' list. +*/ +void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { + global_State *g = G(L); + if (tofinalize(o) || /* obj. is already marked... */ + gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */ + (g->gcstp & GCSTPCLS)) /* or closing state? */ + return; /* nothing to be done */ + else { /* move 'o' to 'finobj' list */ + GCObject **p; + if (issweepphase(g)) { + makewhite(g, o); /* "sweep" object 'o' */ + if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ + g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ + } + else + correctpointers(g, o); + /* search for pointer pointing to 'o' */ + for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } + *p = o->next; /* remove 'o' from 'allgc' list */ + o->next = g->finobj; /* link it in 'finobj' list */ + g->finobj = o; + l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ + } +} + +/* }====================================================== */ + + +/* +** {====================================================== +** Generational Collector +** ======================================================= +*/ + + +/* +** Set the "time" to wait before starting a new GC cycle; cycle will +** start when memory use hits the threshold of ('estimate' * pause / +** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero, +** because Lua cannot even start with less than PAUSEADJ bytes). +*/ +static void setpause (global_State *g) { + l_mem threshold, debt; + int pause = getgcparam(g->gcpause); + l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ + lua_assert(estimate > 0); + threshold = (pause < MAX_LMEM / estimate) /* overflow? */ + ? estimate * pause /* no overflow */ + : MAX_LMEM; /* overflow; truncate to maximum */ + debt = gettotalbytes(g) - threshold; + if (debt > 0) debt = 0; + luaE_setdebt(g, debt); +} + + +/* +** Sweep a list of objects to enter generational mode. Deletes dead +** objects and turns the non dead to old. All non-dead threads---which +** are now old---must be in a gray list. Everything else is not in a +** gray list. Open upvalues are also kept gray. +*/ +static void sweep2old (lua_State *L, GCObject **p) { + GCObject *curr; + global_State *g = G(L); + while ((curr = *p) != NULL) { + if (iswhite(curr)) { /* is 'curr' dead? */ + lua_assert(isdead(g, curr)); + *p = curr->next; /* remove 'curr' from list */ + freeobj(L, curr); /* erase 'curr' */ + } + else { /* all surviving objects become old */ + setage(curr, G_OLD); + if (curr->tt == LUA_VTHREAD) { /* threads must be watched */ + lua_State *th = gco2th(curr); + linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ + } + else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr))) + set2gray(curr); /* open upvalues are always gray */ + else /* everything else is black */ + nw2black(curr); + p = &curr->next; /* go to next element */ + } + } +} + + +/* +** Sweep for generational mode. Delete dead objects. (Because the +** collection is not incremental, there are no "new white" objects +** during the sweep. So, any white object must be dead.) For +** non-dead objects, advance their ages and clear the color of +** new objects. (Old objects keep their colors.) +** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced +** here, because these old-generation objects are usually not swept +** here. They will all be advanced in 'correctgraylist'. That function +** will also remove objects turned white here from any gray list. +*/ +static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, + GCObject *limit, GCObject **pfirstold1) { + static const lu_byte nextage[] = { + G_SURVIVAL, /* from G_NEW */ + G_OLD1, /* from G_SURVIVAL */ + G_OLD1, /* from G_OLD0 */ + G_OLD, /* from G_OLD1 */ + G_OLD, /* from G_OLD (do not change) */ + G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ + G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ + }; + int white = luaC_white(g); + GCObject *curr; + while ((curr = *p) != limit) { + if (iswhite(curr)) { /* is 'curr' dead? */ + lua_assert(!isold(curr) && isdead(g, curr)); + *p = curr->next; /* remove 'curr' from list */ + freeobj(L, curr); /* erase 'curr' */ + } + else { /* correct mark and age */ + if (getage(curr) == G_NEW) { /* new objects go back to white */ + int marked = curr->marked & ~maskgcbits; /* erase GC bits */ + curr->marked = cast_byte(marked | G_SURVIVAL | white); + } + else { /* all other objects will be old, and so keep their color */ + setage(curr, nextage[getage(curr)]); + if (getage(curr) == G_OLD1 && *pfirstold1 == NULL) + *pfirstold1 = curr; /* first OLD1 object in the list */ + } + p = &curr->next; /* go to next element */ + } + } + return p; +} + + +/* +** Traverse a list making all its elements white and clearing their +** age. In incremental mode, all objects are 'new' all the time, +** except for fixed strings (which are always old). +*/ +static void whitelist (global_State *g, GCObject *p) { + int white = luaC_white(g); + for (; p != NULL; p = p->next) + p->marked = cast_byte((p->marked & ~maskgcbits) | white); +} + + +/* +** Correct a list of gray objects. Return pointer to where rest of the +** list should be linked. +** Because this correction is done after sweeping, young objects might +** be turned white and still be in the list. They are only removed. +** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list; +** Non-white threads also remain on the list; 'TOUCHED2' objects become +** regular old; they and anything else are removed from the list. +*/ +static GCObject **correctgraylist (GCObject **p) { + GCObject *curr; + while ((curr = *p) != NULL) { + GCObject **next = getgclist(curr); + if (iswhite(curr)) + goto remove; /* remove all white objects */ + else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ + lua_assert(isgray(curr)); + nw2black(curr); /* make it black, for next barrier */ + changeage(curr, G_TOUCHED1, G_TOUCHED2); + goto remain; /* keep it in the list and go to next element */ + } + else if (curr->tt == LUA_VTHREAD) { + lua_assert(isgray(curr)); + goto remain; /* keep non-white threads on the list */ + } + else { /* everything else is removed */ + lua_assert(isold(curr)); /* young objects should be white here */ + if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */ + changeage(curr, G_TOUCHED2, G_OLD); /* ... to OLD */ + nw2black(curr); /* make object black (to be removed) */ + goto remove; + } + remove: *p = *next; continue; + remain: p = next; continue; + } + return p; +} + + +/* +** Correct all gray lists, coalescing them into 'grayagain'. +*/ +static void correctgraylists (global_State *g) { + GCObject **list = correctgraylist(&g->grayagain); + *list = g->weak; g->weak = NULL; + list = correctgraylist(list); + *list = g->allweak; g->allweak = NULL; + list = correctgraylist(list); + *list = g->ephemeron; g->ephemeron = NULL; + correctgraylist(list); +} + + +/* +** Mark black 'OLD1' objects when starting a new young collection. +** Gray objects are already in some gray list, and so will be visited +** in the atomic step. +*/ +static void markold (global_State *g, GCObject *from, GCObject *to) { + GCObject *p; + for (p = from; p != to; p = p->next) { + if (getage(p) == G_OLD1) { + lua_assert(!iswhite(p)); + changeage(p, G_OLD1, G_OLD); /* now they are old */ + if (isblack(p)) + reallymarkobject(g, p); + } + } +} + + +/* +** Finish a young-generation collection. +*/ +static void finishgencycle (lua_State *L, global_State *g) { + correctgraylists(g); + checkSizes(L, g); + g->gcstate = GCSpropagate; /* skip restart */ + if (!g->gcemergency) + callallpendingfinalizers(L); +} + + +/* +** Does a young collection. First, mark 'OLD1' objects. Then does the +** atomic step. Then, sweep all lists and advance pointers. Finally, +** finish the collection. +*/ +static void youngcollection (lua_State *L, global_State *g) { + GCObject **psurvival; /* to point to first non-dead survival object */ + GCObject *dummy; /* dummy out parameter to 'sweepgen' */ + lua_assert(g->gcstate == GCSpropagate); + if (g->firstold1) { /* are there regular OLD1 objects? */ + markold(g, g->firstold1, g->reallyold); /* mark them */ + g->firstold1 = NULL; /* no more OLD1 objects (for now) */ + } + markold(g, g->finobj, g->finobjrold); + markold(g, g->tobefnz, NULL); + atomic(L); + + /* sweep nursery and get a pointer to its last live element */ + g->gcstate = GCSswpallgc; + psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1); + /* sweep 'survival' */ + sweepgen(L, g, psurvival, g->old1, &g->firstold1); + g->reallyold = g->old1; + g->old1 = *psurvival; /* 'survival' survivals are old now */ + g->survival = g->allgc; /* all news are survivals */ + + /* repeat for 'finobj' lists */ + dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */ + psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy); + /* sweep 'survival' */ + sweepgen(L, g, psurvival, g->finobjold1, &dummy); + g->finobjrold = g->finobjold1; + g->finobjold1 = *psurvival; /* 'survival' survivals are old now */ + g->finobjsur = g->finobj; /* all news are survivals */ + + sweepgen(L, g, &g->tobefnz, NULL, &dummy); + finishgencycle(L, g); +} + + +/* +** Clears all gray lists, sweeps objects, and prepare sublists to enter +** generational mode. The sweeps remove dead objects and turn all +** surviving objects to old. Threads go back to 'grayagain'; everything +** else is turned black (not in any gray list). +*/ +static void atomic2gen (lua_State *L, global_State *g) { + cleargraylists(g); + /* sweep all elements making them old */ + g->gcstate = GCSswpallgc; + sweep2old(L, &g->allgc); + /* everything alive now is old */ + g->reallyold = g->old1 = g->survival = g->allgc; + g->firstold1 = NULL; /* there are no OLD1 objects anywhere */ + + /* repeat for 'finobj' lists */ + sweep2old(L, &g->finobj); + g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj; + + sweep2old(L, &g->tobefnz); + + g->gckind = KGC_GEN; + g->lastatomic = 0; + g->GCestimate = gettotalbytes(g); /* base for memory control */ + finishgencycle(L, g); +} + + +/* +** Set debt for the next minor collection, which will happen when +** memory grows 'genminormul'%. +*/ +static void setminordebt (global_State *g) { + luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul)); +} + + +/* +** Enter generational mode. Must go until the end of an atomic cycle +** to ensure that all objects are correctly marked and weak tables +** are cleared. Then, turn all objects into old and finishes the +** collection. +*/ +static lu_mem entergen (lua_State *L, global_State *g) { + lu_mem numobjs; + luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */ + luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ + numobjs = atomic(L); /* propagates all and then do the atomic stuff */ + atomic2gen(L, g); + setminordebt(g); /* set debt assuming next cycle will be minor */ + return numobjs; +} + + +/* +** Enter incremental mode. Turn all objects white, make all +** intermediate lists point to NULL (to avoid invalid pointers), +** and go to the pause state. +*/ +static void enterinc (global_State *g) { + whitelist(g, g->allgc); + g->reallyold = g->old1 = g->survival = NULL; + whitelist(g, g->finobj); + whitelist(g, g->tobefnz); + g->finobjrold = g->finobjold1 = g->finobjsur = NULL; + g->gcstate = GCSpause; + g->gckind = KGC_INC; + g->lastatomic = 0; +} + + +/* +** Change collector mode to 'newmode'. +*/ +void luaC_changemode (lua_State *L, int newmode) { + global_State *g = G(L); + if (newmode != g->gckind) { + if (newmode == KGC_GEN) /* entering generational mode? */ + entergen(L, g); + else + enterinc(g); /* entering incremental mode */ + } + g->lastatomic = 0; +} + + +/* +** Does a full collection in generational mode. +*/ +static lu_mem fullgen (lua_State *L, global_State *g) { + enterinc(g); + return entergen(L, g); +} + + +/* +** Does a major collection after last collection was a "bad collection". +** +** When the program is building a big structure, it allocates lots of +** memory but generates very little garbage. In those scenarios, +** the generational mode just wastes time doing small collections, and +** major collections are frequently what we call a "bad collection", a +** collection that frees too few objects. To avoid the cost of switching +** between generational mode and the incremental mode needed for full +** (major) collections, the collector tries to stay in incremental mode +** after a bad collection, and to switch back to generational mode only +** after a "good" collection (one that traverses less than 9/8 objects +** of the previous one). +** The collector must choose whether to stay in incremental mode or to +** switch back to generational mode before sweeping. At this point, it +** does not know the real memory in use, so it cannot use memory to +** decide whether to return to generational mode. Instead, it uses the +** number of objects traversed (returned by 'atomic') as a proxy. The +** field 'g->lastatomic' keeps this count from the last collection. +** ('g->lastatomic != 0' also means that the last collection was bad.) +*/ +static void stepgenfull (lua_State *L, global_State *g) { + lu_mem newatomic; /* count of traversed objects */ + lu_mem lastatomic = g->lastatomic; /* count from last collection */ + if (g->gckind == KGC_GEN) /* still in generational mode? */ + enterinc(g); /* enter incremental mode */ + luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ + newatomic = atomic(L); /* mark everybody */ + if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */ + atomic2gen(L, g); /* return to generational mode */ + setminordebt(g); + } + else { /* another bad collection; stay in incremental mode */ + g->GCestimate = gettotalbytes(g); /* first estimate */; + entersweep(L); + luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ + setpause(g); + g->lastatomic = newatomic; + } +} + + +/* +** Does a generational "step". +** Usually, this means doing a minor collection and setting the debt to +** make another collection when memory grows 'genminormul'% larger. +** +** However, there are exceptions. If memory grows 'genmajormul'% +** larger than it was at the end of the last major collection (kept +** in 'g->GCestimate'), the function does a major collection. At the +** end, it checks whether the major collection was able to free a +** decent amount of memory (at least half the growth in memory since +** previous major collection). If so, the collector keeps its state, +** and the next collection will probably be minor again. Otherwise, +** we have what we call a "bad collection". In that case, set the field +** 'g->lastatomic' to signal that fact, so that the next collection will +** go to 'stepgenfull'. +** +** 'GCdebt <= 0' means an explicit call to GC step with "size" zero; +** in that case, do a minor collection. +*/ +static void genstep (lua_State *L, global_State *g) { + if (g->lastatomic != 0) /* last collection was a bad one? */ + stepgenfull(L, g); /* do a full step */ + else { + lu_mem majorbase = g->GCestimate; /* memory after last major collection */ + lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul); + if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) { + lu_mem numobjs = fullgen(L, g); /* do a major collection */ + if (gettotalbytes(g) < majorbase + (majorinc / 2)) { + /* collected at least half of memory growth since last major + collection; keep doing minor collections. */ + lua_assert(g->lastatomic == 0); + } + else { /* bad collection */ + g->lastatomic = numobjs; /* signal that last collection was bad */ + setpause(g); /* do a long wait for next (major) collection */ + } + } + else { /* regular case; do a minor collection */ + youngcollection(L, g); + setminordebt(g); + g->GCestimate = majorbase; /* preserve base value */ + } + } + lua_assert(isdecGCmodegen(g)); +} + +/* }====================================================== */ + + +/* +** {====================================================== +** GC control +** ======================================================= +*/ + + +/* +** Enter first sweep phase. +** The call to 'sweeptolive' makes the pointer point to an object +** inside the list (instead of to the header), so that the real sweep do +** not need to skip objects created between "now" and the start of the +** real sweep. +*/ +static void entersweep (lua_State *L) { + global_State *g = G(L); + g->gcstate = GCSswpallgc; + lua_assert(g->sweepgc == NULL); + g->sweepgc = sweeptolive(L, &g->allgc); +} + + +/* +** Delete all objects in list 'p' until (but not including) object +** 'limit'. +*/ +static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { + while (p != limit) { + GCObject *next = p->next; + freeobj(L, p); + p = next; + } +} + + +/* +** Call all finalizers of the objects in the given Lua state, and +** then free all objects, except for the main thread. +*/ +void luaC_freeallobjects (lua_State *L) { + global_State *g = G(L); + g->gcstp = GCSTPCLS; /* no extra finalizers after here */ + luaC_changemode(L, KGC_INC); + separatetobefnz(g, 1); /* separate all objects with finalizers */ + lua_assert(g->finobj == NULL); + callallpendingfinalizers(L); + deletelist(L, g->allgc, obj2gco(g->mainthread)); + lua_assert(g->finobj == NULL); /* no new finalizers */ + deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ + lua_assert(g->strt.nuse == 0); +} + + +static lu_mem atomic (lua_State *L) { + global_State *g = G(L); + lu_mem work = 0; + GCObject *origweak, *origall; + GCObject *grayagain = g->grayagain; /* save original list */ + g->grayagain = NULL; + lua_assert(g->ephemeron == NULL && g->weak == NULL); + lua_assert(!iswhite(g->mainthread)); + g->gcstate = GCSatomic; + markobject(g, L); /* mark running thread */ + /* registry and global metatables may be changed by API */ + markvalue(g, &g->l_registry); + markmt(g); /* mark global metatables */ + work += propagateall(g); /* empties 'gray' list */ + /* remark occasional upvalues of (maybe) dead threads */ + work += remarkupvals(g); + work += propagateall(g); /* propagate changes */ + g->gray = grayagain; + work += propagateall(g); /* traverse 'grayagain' list */ + convergeephemerons(g); + /* at this point, all strongly accessible objects are marked. */ + /* Clear values from weak tables, before checking finalizers */ + clearbyvalues(g, g->weak, NULL); + clearbyvalues(g, g->allweak, NULL); + origweak = g->weak; origall = g->allweak; + separatetobefnz(g, 0); /* separate objects to be finalized */ + work += markbeingfnz(g); /* mark objects that will be finalized */ + work += propagateall(g); /* remark, to propagate 'resurrection' */ + convergeephemerons(g); + /* at this point, all resurrected objects are marked. */ + /* remove dead objects from weak tables */ + clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */ + clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */ + /* clear values from resurrected weak tables */ + clearbyvalues(g, g->weak, origweak); + clearbyvalues(g, g->allweak, origall); + luaS_clearcache(g); + g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ + lua_assert(g->gray == NULL); + return work; /* estimate of slots marked by 'atomic' */ +} + + +static int sweepstep (lua_State *L, global_State *g, + int nextstate, GCObject **nextlist) { + if (g->sweepgc) { + l_mem olddebt = g->GCdebt; + int count; + g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count); + g->GCestimate += g->GCdebt - olddebt; /* update estimate */ + return count; + } + else { /* enter next state */ + g->gcstate = nextstate; + g->sweepgc = nextlist; + return 0; /* no work done */ + } +} + + +static lu_mem singlestep (lua_State *L) { + global_State *g = G(L); + lu_mem work; + lua_assert(!g->gcstopem); /* collector is not reentrant */ + g->gcstopem = 1; /* no emergency collections while collecting */ + switch (g->gcstate) { + case GCSpause: { + restartcollection(g); + g->gcstate = GCSpropagate; + work = 1; + break; + } + case GCSpropagate: { + if (g->gray == NULL) { /* no more gray objects? */ + g->gcstate = GCSenteratomic; /* finish propagate phase */ + work = 0; + } + else + work = propagatemark(g); /* traverse one gray object */ + break; + } + case GCSenteratomic: { + work = atomic(L); /* work is what was traversed by 'atomic' */ + entersweep(L); + g->GCestimate = gettotalbytes(g); /* first estimate */; + break; + } + case GCSswpallgc: { /* sweep "regular" objects */ + work = sweepstep(L, g, GCSswpfinobj, &g->finobj); + break; + } + case GCSswpfinobj: { /* sweep objects with finalizers */ + work = sweepstep(L, g, GCSswptobefnz, &g->tobefnz); + break; + } + case GCSswptobefnz: { /* sweep objects to be finalized */ + work = sweepstep(L, g, GCSswpend, NULL); + break; + } + case GCSswpend: { /* finish sweeps */ + checkSizes(L, g); + g->gcstate = GCScallfin; + work = 0; + break; + } + case GCScallfin: { /* call remaining finalizers */ + if (g->tobefnz && !g->gcemergency) { + g->gcstopem = 0; /* ok collections during finalizers */ + work = runafewfinalizers(L, GCFINMAX) * GCFINALIZECOST; + } + else { /* emergency mode or no more finalizers */ + g->gcstate = GCSpause; /* finish collection */ + work = 0; + } + break; + } + default: lua_assert(0); return 0; + } + g->gcstopem = 0; + return work; +} + + +/* +** advances the garbage collector until it reaches a state allowed +** by 'statemask' +*/ +void luaC_runtilstate (lua_State *L, int statesmask) { + global_State *g = G(L); + while (!testbit(statesmask, g->gcstate)) + singlestep(L); +} + + + +/* +** Performs a basic incremental step. The debt and step size are +** converted from bytes to "units of work"; then the function loops +** running single steps until adding that many units of work or +** finishing a cycle (pause state). Finally, it sets the debt that +** controls when next step will be performed. +*/ +static void incstep (lua_State *L, global_State *g) { + int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */ + l_mem debt = (g->GCdebt / WORK2MEM) * stepmul; + l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem)) + ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul + : MAX_LMEM; /* overflow; keep maximum value */ + do { /* repeat until pause or enough "credit" (negative debt) */ + lu_mem work = singlestep(L); /* perform one single step */ + debt -= work; + } while (debt > -stepsize && g->gcstate != GCSpause); + if (g->gcstate == GCSpause) + setpause(g); /* pause until next cycle */ + else { + debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */ + luaE_setdebt(g, debt); + } +} + +/* +** Performs a basic GC step if collector is running. (If collector is +** not running, set a reasonable debt to avoid it being called at +** every single check.) +*/ +void luaC_step (lua_State *L) { + global_State *g = G(L); + if (!gcrunning(g)) /* not running? */ + luaE_setdebt(g, -2000); + else { + if(isdecGCmodegen(g)) + genstep(L, g); + else + incstep(L, g); + } +} + + +/* +** Perform a full collection in incremental mode. +** Before running the collection, check 'keepinvariant'; if it is true, +** there may be some objects marked as black, so the collector has +** to sweep all objects to turn them back to white (as white has not +** changed, nothing will be collected). +*/ +static void fullinc (lua_State *L, global_State *g) { + if (keepinvariant(g)) /* black objects? */ + entersweep(L); /* sweep everything to turn them back to white */ + /* finish any pending sweep phase to start a new cycle */ + luaC_runtilstate(L, bitmask(GCSpause)); + luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ + /* estimate must be correct after a full GC cycle */ + lua_assert(g->GCestimate == gettotalbytes(g)); + luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ + setpause(g); +} + + +/* +** Performs a full GC cycle; if 'isemergency', set a flag to avoid +** some operations which could change the interpreter state in some +** unexpected ways (running finalizers and shrinking some structures). +*/ +void luaC_fullgc (lua_State *L, int isemergency) { + global_State *g = G(L); + lua_assert(!g->gcemergency); + g->gcemergency = isemergency; /* set flag */ + if (g->gckind == KGC_INC) + fullinc(L, g); + else + fullgen(L, g); + g->gcemergency = 0; +} + +/* }====================================================== */ + + diff --git a/src/libs/3rdparty/lua/src/lgc.h b/src/libs/3rdparty/lua/src/lgc.h new file mode 100644 index 00000000000..538f6edcccf --- /dev/null +++ b/src/libs/3rdparty/lua/src/lgc.h @@ -0,0 +1,202 @@ +/* +** $Id: lgc.h $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#ifndef lgc_h +#define lgc_h + + +#include "lobject.h" +#include "lstate.h" + +/* +** Collectable objects may have one of three colors: white, which means +** the object is not marked; gray, which means the object is marked, but +** its references may be not marked; and black, which means that the +** object and all its references are marked. The main invariant of the +** garbage collector, while marking objects, is that a black object can +** never point to a white one. Moreover, any gray object must be in a +** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it +** can be visited again before finishing the collection cycle. (Open +** upvalues are an exception to this rule.) These lists have no meaning +** when the invariant is not being enforced (e.g., sweep phase). +*/ + + +/* +** Possible states of the Garbage Collector +*/ +#define GCSpropagate 0 +#define GCSenteratomic 1 +#define GCSatomic 2 +#define GCSswpallgc 3 +#define GCSswpfinobj 4 +#define GCSswptobefnz 5 +#define GCSswpend 6 +#define GCScallfin 7 +#define GCSpause 8 + + +#define issweepphase(g) \ + (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) + + +/* +** macro to tell when main invariant (white objects cannot point to black +** ones) must be kept. During a collection, the sweep +** phase may break the invariant, as objects turned white may point to +** still-black objects. The invariant is restored when sweep ends and +** all objects are white again. +*/ + +#define keepinvariant(g) ((g)->gcstate <= GCSatomic) + + +/* +** some useful bit tricks +*/ +#define resetbits(x,m) ((x) &= cast_byte(~(m))) +#define setbits(x,m) ((x) |= (m)) +#define testbits(x,m) ((x) & (m)) +#define bitmask(b) (1<<(b)) +#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) +#define l_setbit(x,b) setbits(x, bitmask(b)) +#define resetbit(x,b) resetbits(x, bitmask(b)) +#define testbit(x,b) testbits(x, bitmask(b)) + + +/* +** Layout for bit use in 'marked' field. First three bits are +** used for object "age" in generational mode. Last bit is used +** by tests. +*/ +#define WHITE0BIT 3 /* object is white (type 0) */ +#define WHITE1BIT 4 /* object is white (type 1) */ +#define BLACKBIT 5 /* object is black */ +#define FINALIZEDBIT 6 /* object has been marked for finalization */ + +#define TESTBIT 7 + + + +#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) + + +#define iswhite(x) testbits((x)->marked, WHITEBITS) +#define isblack(x) testbit((x)->marked, BLACKBIT) +#define isgray(x) /* neither white nor black */ \ + (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) + +#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) + +#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) +#define isdeadm(ow,m) ((m) & (ow)) +#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) + +#define changewhite(x) ((x)->marked ^= WHITEBITS) +#define nw2black(x) \ + check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT)) + +#define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS) + + +/* object age in generational mode */ +#define G_NEW 0 /* created in current cycle */ +#define G_SURVIVAL 1 /* created in previous cycle */ +#define G_OLD0 2 /* marked old by frw. barrier in this cycle */ +#define G_OLD1 3 /* first full cycle as old */ +#define G_OLD 4 /* really old object (not to be visited) */ +#define G_TOUCHED1 5 /* old object touched this cycle */ +#define G_TOUCHED2 6 /* old object touched in previous cycle */ + +#define AGEBITS 7 /* all age bits (111) */ + +#define getage(o) ((o)->marked & AGEBITS) +#define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a)) +#define isold(o) (getage(o) > G_SURVIVAL) + +#define changeage(o,f,t) \ + check_exp(getage(o) == (f), (o)->marked ^= ((f)^(t))) + + +/* Default Values for GC parameters */ +#define LUAI_GENMAJORMUL 100 +#define LUAI_GENMINORMUL 20 + +/* wait memory to double before starting new cycle */ +#define LUAI_GCPAUSE 200 + +/* +** some gc parameters are stored divided by 4 to allow a maximum value +** up to 1023 in a 'lu_byte'. +*/ +#define getgcparam(p) ((p) * 4) +#define setgcparam(p,v) ((p) = (v) / 4) + +#define LUAI_GCMUL 100 + +/* how much to allocate before next GC step (log2) */ +#define LUAI_GCSTEPSIZE 13 /* 8 KB */ + + +/* +** Check whether the declared GC mode is generational. While in +** generational mode, the collector can go temporarily to incremental +** mode to improve performance. This is signaled by 'g->lastatomic != 0'. +*/ +#define isdecGCmodegen(g) (g->gckind == KGC_GEN || g->lastatomic != 0) + + +/* +** Control when GC is running: +*/ +#define GCSTPUSR 1 /* bit true when GC stopped by user */ +#define GCSTPGC 2 /* bit true when GC stopped by itself */ +#define GCSTPCLS 4 /* bit true when closing Lua state */ +#define gcrunning(g) ((g)->gcstp == 0) + + +/* +** Does one step of collection when debt becomes positive. 'pre'/'pos' +** allows some adjustments to be done only when needed. macro +** 'condchangemem' is used only for heavy tests (forcing a full +** GC cycle on every opportunity) +*/ +#define luaC_condGC(L,pre,pos) \ + { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ + condchangemem(L,pre,pos); } + +/* more often than not, 'pre'/'pos' are empty */ +#define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) + + +#define luaC_objbarrier(L,p,o) ( \ + (isblack(p) && iswhite(o)) ? \ + luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) + +#define luaC_barrier(L,p,v) ( \ + iscollectable(v) ? luaC_objbarrier(L,p,gcvalue(v)) : cast_void(0)) + +#define luaC_objbarrierback(L,p,o) ( \ + (isblack(p) && iswhite(o)) ? luaC_barrierback_(L,p) : cast_void(0)) + +#define luaC_barrierback(L,p,v) ( \ + iscollectable(v) ? luaC_objbarrierback(L, p, gcvalue(v)) : cast_void(0)) + +LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); +LUAI_FUNC void luaC_freeallobjects (lua_State *L); +LUAI_FUNC void luaC_step (lua_State *L); +LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); +LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); +LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); +LUAI_FUNC GCObject *luaC_newobjdt (lua_State *L, int tt, size_t sz, + size_t offset); +LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); +LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); +LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); +LUAI_FUNC void luaC_changemode (lua_State *L, int newmode); + + +#endif diff --git a/src/libs/3rdparty/lua/src/linit.c b/src/libs/3rdparty/lua/src/linit.c new file mode 100644 index 00000000000..69808f84f48 --- /dev/null +++ b/src/libs/3rdparty/lua/src/linit.c @@ -0,0 +1,65 @@ +/* +** $Id: linit.c $ +** Initialization of libraries for lua.c and other clients +** See Copyright Notice in lua.h +*/ + + +#define linit_c +#define LUA_LIB + +/* +** If you embed Lua in your program and need to open the standard +** libraries, call luaL_openlibs in your program. If you need a +** different set of libraries, copy this file to your project and edit +** it to suit your needs. +** +** You can also *preload* libraries, so that a later 'require' can +** open the library, which is already linked to the application. +** For that, do the following code: +** +** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); +** lua_pushcfunction(L, luaopen_modname); +** lua_setfield(L, -2, modname); +** lua_pop(L, 1); // remove PRELOAD table +*/ + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "lualib.h" +#include "lauxlib.h" + + +/* +** these libs are loaded by lua.c and are readily available to any Lua +** program +*/ +static const luaL_Reg loadedlibs[] = { + {LUA_GNAME, luaopen_base}, + {LUA_LOADLIBNAME, luaopen_package}, + {LUA_COLIBNAME, luaopen_coroutine}, + {LUA_TABLIBNAME, luaopen_table}, + {LUA_IOLIBNAME, luaopen_io}, + {LUA_OSLIBNAME, luaopen_os}, + {LUA_STRLIBNAME, luaopen_string}, + {LUA_MATHLIBNAME, luaopen_math}, + {LUA_UTF8LIBNAME, luaopen_utf8}, + {LUA_DBLIBNAME, luaopen_debug}, + {NULL, NULL} +}; + + +LUALIB_API void luaL_openlibs (lua_State *L) { + const luaL_Reg *lib; + /* "require" functions from 'loadedlibs' and set results to global table */ + for (lib = loadedlibs; lib->func; lib++) { + luaL_requiref(L, lib->name, lib->func, 1); + lua_pop(L, 1); /* remove lib */ + } +} + diff --git a/src/libs/3rdparty/lua/src/liolib.c b/src/libs/3rdparty/lua/src/liolib.c new file mode 100644 index 00000000000..b08397da45d --- /dev/null +++ b/src/libs/3rdparty/lua/src/liolib.c @@ -0,0 +1,828 @@ +/* +** $Id: liolib.c $ +** Standard I/O (and system) library +** See Copyright Notice in lua.h +*/ + +#define liolib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + + + +/* +** Change this macro to accept other modes for 'fopen' besides +** the standard ones. +*/ +#if !defined(l_checkmode) + +/* accepted extensions to 'mode' in 'fopen' */ +#if !defined(L_MODEEXT) +#define L_MODEEXT "b" +#endif + +/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */ +static int l_checkmode (const char *mode) { + return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && + (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */ + (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */ +} + +#endif + +/* +** {====================================================== +** l_popen spawns a new process connected to the current +** one through the file streams. +** ======================================================= +*/ + +#if !defined(l_popen) /* { */ + +#if defined(LUA_USE_POSIX) /* { */ + +#define l_popen(L,c,m) (fflush(NULL), popen(c,m)) +#define l_pclose(L,file) (pclose(file)) + +#elif defined(LUA_USE_WINDOWS) /* }{ */ + +#define l_popen(L,c,m) (_popen(c,m)) +#define l_pclose(L,file) (_pclose(file)) + +#if !defined(l_checkmodep) +/* Windows accepts "[rw][bt]?" as valid modes */ +#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \ + (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0'))) +#endif + +#else /* }{ */ + +/* ISO C definitions */ +#define l_popen(L,c,m) \ + ((void)c, (void)m, \ + luaL_error(L, "'popen' not supported"), \ + (FILE*)0) +#define l_pclose(L,file) ((void)L, (void)file, -1) + +#endif /* } */ + +#endif /* } */ + + +#if !defined(l_checkmodep) +/* By default, Lua accepts only "r" or "w" as valid modes */ +#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0') +#endif + +/* }====================================================== */ + + +#if !defined(l_getc) /* { */ + +#if defined(LUA_USE_POSIX) +#define l_getc(f) getc_unlocked(f) +#define l_lockfile(f) flockfile(f) +#define l_unlockfile(f) funlockfile(f) +#else +#define l_getc(f) getc(f) +#define l_lockfile(f) ((void)0) +#define l_unlockfile(f) ((void)0) +#endif + +#endif /* } */ + + +/* +** {====================================================== +** l_fseek: configuration for longer offsets +** ======================================================= +*/ + +#if !defined(l_fseek) /* { */ + +#if defined(LUA_USE_POSIX) /* { */ + +#include + +#define l_fseek(f,o,w) fseeko(f,o,w) +#define l_ftell(f) ftello(f) +#define l_seeknum off_t + +#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \ + && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ + +/* Windows (but not DDK) and Visual C++ 2005 or higher */ +#define l_fseek(f,o,w) _fseeki64(f,o,w) +#define l_ftell(f) _ftelli64(f) +#define l_seeknum __int64 + +#else /* }{ */ + +/* ISO C definitions */ +#define l_fseek(f,o,w) fseek(f,o,w) +#define l_ftell(f) ftell(f) +#define l_seeknum long + +#endif /* } */ + +#endif /* } */ + +/* }====================================================== */ + + + +#define IO_PREFIX "_IO_" +#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1) +#define IO_INPUT (IO_PREFIX "input") +#define IO_OUTPUT (IO_PREFIX "output") + + +typedef luaL_Stream LStream; + + +#define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) + +#define isclosed(p) ((p)->closef == NULL) + + +static int io_type (lua_State *L) { + LStream *p; + luaL_checkany(L, 1); + p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); + if (p == NULL) + luaL_pushfail(L); /* not a file */ + else if (isclosed(p)) + lua_pushliteral(L, "closed file"); + else + lua_pushliteral(L, "file"); + return 1; +} + + +static int f_tostring (lua_State *L) { + LStream *p = tolstream(L); + if (isclosed(p)) + lua_pushliteral(L, "file (closed)"); + else + lua_pushfstring(L, "file (%p)", p->f); + return 1; +} + + +static FILE *tofile (lua_State *L) { + LStream *p = tolstream(L); + if (l_unlikely(isclosed(p))) + luaL_error(L, "attempt to use a closed file"); + lua_assert(p->f); + return p->f; +} + + +/* +** When creating file handles, always creates a 'closed' file handle +** before opening the actual file; so, if there is a memory error, the +** handle is in a consistent state. +*/ +static LStream *newprefile (lua_State *L) { + LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0); + p->closef = NULL; /* mark file handle as 'closed' */ + luaL_setmetatable(L, LUA_FILEHANDLE); + return p; +} + + +/* +** Calls the 'close' function from a file handle. The 'volatile' avoids +** a bug in some versions of the Clang compiler (e.g., clang 3.0 for +** 32 bits). +*/ +static int aux_close (lua_State *L) { + LStream *p = tolstream(L); + volatile lua_CFunction cf = p->closef; + p->closef = NULL; /* mark stream as closed */ + return (*cf)(L); /* close it */ +} + + +static int f_close (lua_State *L) { + tofile(L); /* make sure argument is an open stream */ + return aux_close(L); +} + + +static int io_close (lua_State *L) { + if (lua_isnone(L, 1)) /* no argument? */ + lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */ + return f_close(L); +} + + +static int f_gc (lua_State *L) { + LStream *p = tolstream(L); + if (!isclosed(p) && p->f != NULL) + aux_close(L); /* ignore closed and incompletely open files */ + return 0; +} + + +/* +** function to close regular files +*/ +static int io_fclose (lua_State *L) { + LStream *p = tolstream(L); + int res = fclose(p->f); + return luaL_fileresult(L, (res == 0), NULL); +} + + +static LStream *newfile (lua_State *L) { + LStream *p = newprefile(L); + p->f = NULL; + p->closef = &io_fclose; + return p; +} + + +static void opencheck (lua_State *L, const char *fname, const char *mode) { + LStream *p = newfile(L); + p->f = fopen(fname, mode); + if (l_unlikely(p->f == NULL)) + luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno)); +} + + +static int io_open (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + const char *mode = luaL_optstring(L, 2, "r"); + LStream *p = newfile(L); + const char *md = mode; /* to traverse/check mode */ + luaL_argcheck(L, l_checkmode(md), 2, "invalid mode"); + p->f = fopen(filename, mode); + return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; +} + + +/* +** function to close 'popen' files +*/ +static int io_pclose (lua_State *L) { + LStream *p = tolstream(L); + errno = 0; + return luaL_execresult(L, l_pclose(L, p->f)); +} + + +static int io_popen (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + const char *mode = luaL_optstring(L, 2, "r"); + LStream *p = newprefile(L); + luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode"); + p->f = l_popen(L, filename, mode); + p->closef = &io_pclose; + return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; +} + + +static int io_tmpfile (lua_State *L) { + LStream *p = newfile(L); + p->f = tmpfile(); + return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; +} + + +static FILE *getiofile (lua_State *L, const char *findex) { + LStream *p; + lua_getfield(L, LUA_REGISTRYINDEX, findex); + p = (LStream *)lua_touserdata(L, -1); + if (l_unlikely(isclosed(p))) + luaL_error(L, "default %s file is closed", findex + IOPREF_LEN); + return p->f; +} + + +static int g_iofile (lua_State *L, const char *f, const char *mode) { + if (!lua_isnoneornil(L, 1)) { + const char *filename = lua_tostring(L, 1); + if (filename) + opencheck(L, filename, mode); + else { + tofile(L); /* check that it's a valid file handle */ + lua_pushvalue(L, 1); + } + lua_setfield(L, LUA_REGISTRYINDEX, f); + } + /* return current value */ + lua_getfield(L, LUA_REGISTRYINDEX, f); + return 1; +} + + +static int io_input (lua_State *L) { + return g_iofile(L, IO_INPUT, "r"); +} + + +static int io_output (lua_State *L) { + return g_iofile(L, IO_OUTPUT, "w"); +} + + +static int io_readline (lua_State *L); + + +/* +** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit +** in the limit for upvalues of a closure) +*/ +#define MAXARGLINE 250 + +/* +** Auxiliary function to create the iteration function for 'lines'. +** The iteration function is a closure over 'io_readline', with +** the following upvalues: +** 1) The file being read (first value in the stack) +** 2) the number of arguments to read +** 3) a boolean, true iff file has to be closed when finished ('toclose') +** *) a variable number of format arguments (rest of the stack) +*/ +static void aux_lines (lua_State *L, int toclose) { + int n = lua_gettop(L) - 1; /* number of arguments to read */ + luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments"); + lua_pushvalue(L, 1); /* file */ + lua_pushinteger(L, n); /* number of arguments to read */ + lua_pushboolean(L, toclose); /* close/not close file when finished */ + lua_rotate(L, 2, 3); /* move the three values to their positions */ + lua_pushcclosure(L, io_readline, 3 + n); +} + + +static int f_lines (lua_State *L) { + tofile(L); /* check that it's a valid file handle */ + aux_lines(L, 0); + return 1; +} + + +/* +** Return an iteration function for 'io.lines'. If file has to be +** closed, also returns the file itself as a second result (to be +** closed as the state at the exit of a generic for). +*/ +static int io_lines (lua_State *L) { + int toclose; + if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ + if (lua_isnil(L, 1)) { /* no file name? */ + lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ + lua_replace(L, 1); /* put it at index 1 */ + tofile(L); /* check that it's a valid file handle */ + toclose = 0; /* do not close it after iteration */ + } + else { /* open a new file */ + const char *filename = luaL_checkstring(L, 1); + opencheck(L, filename, "r"); + lua_replace(L, 1); /* put file at index 1 */ + toclose = 1; /* close it after iteration */ + } + aux_lines(L, toclose); /* push iteration function */ + if (toclose) { + lua_pushnil(L); /* state */ + lua_pushnil(L); /* control */ + lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */ + return 4; + } + else + return 1; +} + + +/* +** {====================================================== +** READ +** ======================================================= +*/ + + +/* maximum length of a numeral */ +#if !defined (L_MAXLENNUM) +#define L_MAXLENNUM 200 +#endif + + +/* auxiliary structure used by 'read_number' */ +typedef struct { + FILE *f; /* file being read */ + int c; /* current character (look ahead) */ + int n; /* number of elements in buffer 'buff' */ + char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */ +} RN; + + +/* +** Add current char to buffer (if not out of space) and read next one +*/ +static int nextc (RN *rn) { + if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */ + rn->buff[0] = '\0'; /* invalidate result */ + return 0; /* fail */ + } + else { + rn->buff[rn->n++] = rn->c; /* save current char */ + rn->c = l_getc(rn->f); /* read next one */ + return 1; + } +} + + +/* +** Accept current char if it is in 'set' (of size 2) +*/ +static int test2 (RN *rn, const char *set) { + if (rn->c == set[0] || rn->c == set[1]) + return nextc(rn); + else return 0; +} + + +/* +** Read a sequence of (hex)digits +*/ +static int readdigits (RN *rn, int hex) { + int count = 0; + while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn)) + count++; + return count; +} + + +/* +** Read a number: first reads a valid prefix of a numeral into a buffer. +** Then it calls 'lua_stringtonumber' to check whether the format is +** correct and to convert it to a Lua number. +*/ +static int read_number (lua_State *L, FILE *f) { + RN rn; + int count = 0; + int hex = 0; + char decp[2]; + rn.f = f; rn.n = 0; + decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */ + decp[1] = '.'; /* always accept a dot */ + l_lockfile(rn.f); + do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */ + test2(&rn, "-+"); /* optional sign */ + if (test2(&rn, "00")) { + if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */ + else count = 1; /* count initial '0' as a valid digit */ + } + count += readdigits(&rn, hex); /* integral part */ + if (test2(&rn, decp)) /* decimal point? */ + count += readdigits(&rn, hex); /* fractional part */ + if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */ + test2(&rn, "-+"); /* exponent sign */ + readdigits(&rn, 0); /* exponent digits */ + } + ungetc(rn.c, rn.f); /* unread look-ahead char */ + l_unlockfile(rn.f); + rn.buff[rn.n] = '\0'; /* finish string */ + if (l_likely(lua_stringtonumber(L, rn.buff))) + return 1; /* ok, it is a valid number */ + else { /* invalid format */ + lua_pushnil(L); /* "result" to be removed */ + return 0; /* read fails */ + } +} + + +static int test_eof (lua_State *L, FILE *f) { + int c = getc(f); + ungetc(c, f); /* no-op when c == EOF */ + lua_pushliteral(L, ""); + return (c != EOF); +} + + +static int read_line (lua_State *L, FILE *f, int chop) { + luaL_Buffer b; + int c; + luaL_buffinit(L, &b); + do { /* may need to read several chunks to get whole line */ + char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */ + int i = 0; + l_lockfile(f); /* no memory errors can happen inside the lock */ + while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') + buff[i++] = c; /* read up to end of line or buffer limit */ + l_unlockfile(f); + luaL_addsize(&b, i); + } while (c != EOF && c != '\n'); /* repeat until end of line */ + if (!chop && c == '\n') /* want a newline and have one? */ + luaL_addchar(&b, c); /* add ending newline to result */ + luaL_pushresult(&b); /* close buffer */ + /* return ok if read something (either a newline or something else) */ + return (c == '\n' || lua_rawlen(L, -1) > 0); +} + + +static void read_all (lua_State *L, FILE *f) { + size_t nr; + luaL_Buffer b; + luaL_buffinit(L, &b); + do { /* read file in chunks of LUAL_BUFFERSIZE bytes */ + char *p = luaL_prepbuffer(&b); + nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f); + luaL_addsize(&b, nr); + } while (nr == LUAL_BUFFERSIZE); + luaL_pushresult(&b); /* close buffer */ +} + + +static int read_chars (lua_State *L, FILE *f, size_t n) { + size_t nr; /* number of chars actually read */ + char *p; + luaL_Buffer b; + luaL_buffinit(L, &b); + p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ + nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ + luaL_addsize(&b, nr); + luaL_pushresult(&b); /* close buffer */ + return (nr > 0); /* true iff read something */ +} + + +static int g_read (lua_State *L, FILE *f, int first) { + int nargs = lua_gettop(L) - 1; + int n, success; + clearerr(f); + if (nargs == 0) { /* no arguments? */ + success = read_line(L, f, 1); + n = first + 1; /* to return 1 result */ + } + else { + /* ensure stack space for all results and for auxlib's buffer */ + luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); + success = 1; + for (n = first; nargs-- && success; n++) { + if (lua_type(L, n) == LUA_TNUMBER) { + size_t l = (size_t)luaL_checkinteger(L, n); + success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); + } + else { + const char *p = luaL_checkstring(L, n); + if (*p == '*') p++; /* skip optional '*' (for compatibility) */ + switch (*p) { + case 'n': /* number */ + success = read_number(L, f); + break; + case 'l': /* line */ + success = read_line(L, f, 1); + break; + case 'L': /* line with end-of-line */ + success = read_line(L, f, 0); + break; + case 'a': /* file */ + read_all(L, f); /* read entire file */ + success = 1; /* always success */ + break; + default: + return luaL_argerror(L, n, "invalid format"); + } + } + } + } + if (ferror(f)) + return luaL_fileresult(L, 0, NULL); + if (!success) { + lua_pop(L, 1); /* remove last result */ + luaL_pushfail(L); /* push nil instead */ + } + return n - first; +} + + +static int io_read (lua_State *L) { + return g_read(L, getiofile(L, IO_INPUT), 1); +} + + +static int f_read (lua_State *L) { + return g_read(L, tofile(L), 2); +} + + +/* +** Iteration function for 'lines'. +*/ +static int io_readline (lua_State *L) { + LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); + int i; + int n = (int)lua_tointeger(L, lua_upvalueindex(2)); + if (isclosed(p)) /* file is already closed? */ + return luaL_error(L, "file is already closed"); + lua_settop(L , 1); + luaL_checkstack(L, n, "too many arguments"); + for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ + lua_pushvalue(L, lua_upvalueindex(3 + i)); + n = g_read(L, p->f, 2); /* 'n' is number of results */ + lua_assert(n > 0); /* should return at least a nil */ + if (lua_toboolean(L, -n)) /* read at least one value? */ + return n; /* return them */ + else { /* first result is false: EOF or error */ + if (n > 1) { /* is there error information? */ + /* 2nd result is error message */ + return luaL_error(L, "%s", lua_tostring(L, -n + 1)); + } + if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ + lua_settop(L, 0); /* clear stack */ + lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */ + aux_close(L); /* close it */ + } + return 0; + } +} + +/* }====================================================== */ + + +static int g_write (lua_State *L, FILE *f, int arg) { + int nargs = lua_gettop(L) - arg; + int status = 1; + for (; nargs--; arg++) { + if (lua_type(L, arg) == LUA_TNUMBER) { + /* optimization: could be done exactly as for strings */ + int len = lua_isinteger(L, arg) + ? fprintf(f, LUA_INTEGER_FMT, + (LUAI_UACINT)lua_tointeger(L, arg)) + : fprintf(f, LUA_NUMBER_FMT, + (LUAI_UACNUMBER)lua_tonumber(L, arg)); + status = status && (len > 0); + } + else { + size_t l; + const char *s = luaL_checklstring(L, arg, &l); + status = status && (fwrite(s, sizeof(char), l, f) == l); + } + } + if (l_likely(status)) + return 1; /* file handle already on stack top */ + else return luaL_fileresult(L, status, NULL); +} + + +static int io_write (lua_State *L) { + return g_write(L, getiofile(L, IO_OUTPUT), 1); +} + + +static int f_write (lua_State *L) { + FILE *f = tofile(L); + lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ + return g_write(L, f, 2); +} + + +static int f_seek (lua_State *L) { + static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; + static const char *const modenames[] = {"set", "cur", "end", NULL}; + FILE *f = tofile(L); + int op = luaL_checkoption(L, 2, "cur", modenames); + lua_Integer p3 = luaL_optinteger(L, 3, 0); + l_seeknum offset = (l_seeknum)p3; + luaL_argcheck(L, (lua_Integer)offset == p3, 3, + "not an integer in proper range"); + op = l_fseek(f, offset, mode[op]); + if (l_unlikely(op)) + return luaL_fileresult(L, 0, NULL); /* error */ + else { + lua_pushinteger(L, (lua_Integer)l_ftell(f)); + return 1; + } +} + + +static int f_setvbuf (lua_State *L) { + static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; + static const char *const modenames[] = {"no", "full", "line", NULL}; + FILE *f = tofile(L); + int op = luaL_checkoption(L, 2, NULL, modenames); + lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); + int res = setvbuf(f, NULL, mode[op], (size_t)sz); + return luaL_fileresult(L, res == 0, NULL); +} + + + +static int io_flush (lua_State *L) { + return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); +} + + +static int f_flush (lua_State *L) { + return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL); +} + + +/* +** functions for 'io' library +*/ +static const luaL_Reg iolib[] = { + {"close", io_close}, + {"flush", io_flush}, + {"input", io_input}, + {"lines", io_lines}, + {"open", io_open}, + {"output", io_output}, + {"popen", io_popen}, + {"read", io_read}, + {"tmpfile", io_tmpfile}, + {"type", io_type}, + {"write", io_write}, + {NULL, NULL} +}; + + +/* +** methods for file handles +*/ +static const luaL_Reg meth[] = { + {"read", f_read}, + {"write", f_write}, + {"lines", f_lines}, + {"flush", f_flush}, + {"seek", f_seek}, + {"close", f_close}, + {"setvbuf", f_setvbuf}, + {NULL, NULL} +}; + + +/* +** metamethods for file handles +*/ +static const luaL_Reg metameth[] = { + {"__index", NULL}, /* place holder */ + {"__gc", f_gc}, + {"__close", f_gc}, + {"__tostring", f_tostring}, + {NULL, NULL} +}; + + +static void createmeta (lua_State *L) { + luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */ + luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */ + luaL_newlibtable(L, meth); /* create method table */ + luaL_setfuncs(L, meth, 0); /* add file methods to method table */ + lua_setfield(L, -2, "__index"); /* metatable.__index = method table */ + lua_pop(L, 1); /* pop metatable */ +} + + +/* +** function to (not) close the standard files stdin, stdout, and stderr +*/ +static int io_noclose (lua_State *L) { + LStream *p = tolstream(L); + p->closef = &io_noclose; /* keep file opened */ + luaL_pushfail(L); + lua_pushliteral(L, "cannot close standard file"); + return 2; +} + + +static void createstdfile (lua_State *L, FILE *f, const char *k, + const char *fname) { + LStream *p = newprefile(L); + p->f = f; + p->closef = &io_noclose; + if (k != NULL) { + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ + } + lua_setfield(L, -2, fname); /* add file to module */ +} + + +LUAMOD_API int luaopen_io (lua_State *L) { + luaL_newlib(L, iolib); /* new module */ + createmeta(L); + /* create (and set) default files */ + createstdfile(L, stdin, IO_INPUT, "stdin"); + createstdfile(L, stdout, IO_OUTPUT, "stdout"); + createstdfile(L, stderr, NULL, "stderr"); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/ljumptab.h b/src/libs/3rdparty/lua/src/ljumptab.h new file mode 100644 index 00000000000..8306f250ccb --- /dev/null +++ b/src/libs/3rdparty/lua/src/ljumptab.h @@ -0,0 +1,112 @@ +/* +** $Id: ljumptab.h $ +** Jump Table for the Lua interpreter +** See Copyright Notice in lua.h +*/ + + +#undef vmdispatch +#undef vmcase +#undef vmbreak + +#define vmdispatch(x) goto *disptab[x]; + +#define vmcase(l) L_##l: + +#define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i)); + + +static const void *const disptab[NUM_OPCODES] = { + +#if 0 +** you can update the following list with this command: +** +** sed -n '/^OP_/\!d; s/OP_/\&\&L_OP_/ ; s/,.*/,/ ; s/\/.*// ; p' lopcodes.h +** +#endif + +&&L_OP_MOVE, +&&L_OP_LOADI, +&&L_OP_LOADF, +&&L_OP_LOADK, +&&L_OP_LOADKX, +&&L_OP_LOADFALSE, +&&L_OP_LFALSESKIP, +&&L_OP_LOADTRUE, +&&L_OP_LOADNIL, +&&L_OP_GETUPVAL, +&&L_OP_SETUPVAL, +&&L_OP_GETTABUP, +&&L_OP_GETTABLE, +&&L_OP_GETI, +&&L_OP_GETFIELD, +&&L_OP_SETTABUP, +&&L_OP_SETTABLE, +&&L_OP_SETI, +&&L_OP_SETFIELD, +&&L_OP_NEWTABLE, +&&L_OP_SELF, +&&L_OP_ADDI, +&&L_OP_ADDK, +&&L_OP_SUBK, +&&L_OP_MULK, +&&L_OP_MODK, +&&L_OP_POWK, +&&L_OP_DIVK, +&&L_OP_IDIVK, +&&L_OP_BANDK, +&&L_OP_BORK, +&&L_OP_BXORK, +&&L_OP_SHRI, +&&L_OP_SHLI, +&&L_OP_ADD, +&&L_OP_SUB, +&&L_OP_MUL, +&&L_OP_MOD, +&&L_OP_POW, +&&L_OP_DIV, +&&L_OP_IDIV, +&&L_OP_BAND, +&&L_OP_BOR, +&&L_OP_BXOR, +&&L_OP_SHL, +&&L_OP_SHR, +&&L_OP_MMBIN, +&&L_OP_MMBINI, +&&L_OP_MMBINK, +&&L_OP_UNM, +&&L_OP_BNOT, +&&L_OP_NOT, +&&L_OP_LEN, +&&L_OP_CONCAT, +&&L_OP_CLOSE, +&&L_OP_TBC, +&&L_OP_JMP, +&&L_OP_EQ, +&&L_OP_LT, +&&L_OP_LE, +&&L_OP_EQK, +&&L_OP_EQI, +&&L_OP_LTI, +&&L_OP_LEI, +&&L_OP_GTI, +&&L_OP_GEI, +&&L_OP_TEST, +&&L_OP_TESTSET, +&&L_OP_CALL, +&&L_OP_TAILCALL, +&&L_OP_RETURN, +&&L_OP_RETURN0, +&&L_OP_RETURN1, +&&L_OP_FORLOOP, +&&L_OP_FORPREP, +&&L_OP_TFORPREP, +&&L_OP_TFORCALL, +&&L_OP_TFORLOOP, +&&L_OP_SETLIST, +&&L_OP_CLOSURE, +&&L_OP_VARARG, +&&L_OP_VARARGPREP, +&&L_OP_EXTRAARG + +}; diff --git a/src/libs/3rdparty/lua/src/llex.c b/src/libs/3rdparty/lua/src/llex.c new file mode 100644 index 00000000000..5fc39a5cdec --- /dev/null +++ b/src/libs/3rdparty/lua/src/llex.c @@ -0,0 +1,581 @@ +/* +** $Id: llex.c $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#define llex_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "llex.h" +#include "lobject.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lzio.h" + + + +#define next(ls) (ls->current = zgetc(ls->z)) + + + +#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') + + +/* ORDER RESERVED */ +static const char *const luaX_tokens [] = { + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "goto", "if", + "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "//", "..", "...", "==", ">=", "<=", "~=", + "<<", ">>", "::", "", + "", "", "", "" +}; + + +#define save_and_next(ls) (save(ls, ls->current), next(ls)) + + +static l_noret lexerror (LexState *ls, const char *msg, int token); + + +static void save (LexState *ls, int c) { + Mbuffer *b = ls->buff; + if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { + size_t newsize; + if (luaZ_sizebuffer(b) >= MAX_SIZE/2) + lexerror(ls, "lexical element too long", 0); + newsize = luaZ_sizebuffer(b) * 2; + luaZ_resizebuffer(ls->L, b, newsize); + } + b->buffer[luaZ_bufflen(b)++] = cast_char(c); +} + + +void luaX_init (lua_State *L) { + int i; + TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ + luaC_fix(L, obj2gco(e)); /* never collect this name */ + for (i=0; iextra = cast_byte(i+1); /* reserved word */ + } +} + + +const char *luaX_token2str (LexState *ls, int token) { + if (token < FIRST_RESERVED) { /* single-byte symbols? */ + if (lisprint(token)) + return luaO_pushfstring(ls->L, "'%c'", token); + else /* control character */ + return luaO_pushfstring(ls->L, "'<\\%d>'", token); + } + else { + const char *s = luaX_tokens[token - FIRST_RESERVED]; + if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ + return luaO_pushfstring(ls->L, "'%s'", s); + else /* names, strings, and numerals */ + return s; + } +} + + +static const char *txtToken (LexState *ls, int token) { + switch (token) { + case TK_NAME: case TK_STRING: + case TK_FLT: case TK_INT: + save(ls, '\0'); + return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); + default: + return luaX_token2str(ls, token); + } +} + + +static l_noret lexerror (LexState *ls, const char *msg, int token) { + msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); + if (token) + luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); + luaD_throw(ls->L, LUA_ERRSYNTAX); +} + + +l_noret luaX_syntaxerror (LexState *ls, const char *msg) { + lexerror(ls, msg, ls->t.token); +} + + +/* +** Creates a new string and anchors it in scanner's table so that it +** will not be collected until the end of the compilation; by that time +** it should be anchored somewhere. It also internalizes long strings, +** ensuring there is only one copy of each unique string. The table +** here is used as a set: the string enters as the key, while its value +** is irrelevant. We use the string itself as the value only because it +** is a TValue readily available. Later, the code generation can change +** this value. +*/ +TString *luaX_newstring (LexState *ls, const char *str, size_t l) { + lua_State *L = ls->L; + TString *ts = luaS_newlstr(L, str, l); /* create new string */ + const TValue *o = luaH_getstr(ls->h, ts); + if (!ttisnil(o)) /* string already present? */ + ts = keystrval(nodefromval(o)); /* get saved copy */ + else { /* not in use yet */ + TValue *stv = s2v(L->top.p++); /* reserve stack space for string */ + setsvalue(L, stv, ts); /* temporarily anchor the string */ + luaH_finishset(L, ls->h, stv, o, stv); /* t[string] = string */ + /* table is not a metatable, so it does not need to invalidate cache */ + luaC_checkGC(L); + L->top.p--; /* remove string from stack */ + } + return ts; +} + + +/* +** increment line number and skips newline sequence (any of +** \n, \r, \n\r, or \r\n) +*/ +static void inclinenumber (LexState *ls) { + int old = ls->current; + lua_assert(currIsNewline(ls)); + next(ls); /* skip '\n' or '\r' */ + if (currIsNewline(ls) && ls->current != old) + next(ls); /* skip '\n\r' or '\r\n' */ + if (++ls->linenumber >= MAX_INT) + lexerror(ls, "chunk has too many lines", 0); +} + + +void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, + int firstchar) { + ls->t.token = 0; + ls->L = L; + ls->current = firstchar; + ls->lookahead.token = TK_EOS; /* no look-ahead token */ + ls->z = z; + ls->fs = NULL; + ls->linenumber = 1; + ls->lastline = 1; + ls->source = source; + ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */ + luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ +} + + + +/* +** ======================================================= +** LEXICAL ANALYZER +** ======================================================= +*/ + + +static int check_next1 (LexState *ls, int c) { + if (ls->current == c) { + next(ls); + return 1; + } + else return 0; +} + + +/* +** Check whether current char is in set 'set' (with two chars) and +** saves it +*/ +static int check_next2 (LexState *ls, const char *set) { + lua_assert(set[2] == '\0'); + if (ls->current == set[0] || ls->current == set[1]) { + save_and_next(ls); + return 1; + } + else return 0; +} + + +/* LUA_NUMBER */ +/* +** This function is quite liberal in what it accepts, as 'luaO_str2num' +** will reject ill-formed numerals. Roughly, it accepts the following +** pattern: +** +** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))* +** +** The only tricky part is to accept [+-] only after a valid exponent +** mark, to avoid reading '3-4' or '0xe+1' as a single number. +** +** The caller might have already read an initial dot. +*/ +static int read_numeral (LexState *ls, SemInfo *seminfo) { + TValue obj; + const char *expo = "Ee"; + int first = ls->current; + lua_assert(lisdigit(ls->current)); + save_and_next(ls); + if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ + expo = "Pp"; + for (;;) { + if (check_next2(ls, expo)) /* exponent mark? */ + check_next2(ls, "-+"); /* optional exponent sign */ + else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */ + save_and_next(ls); + else break; + } + if (lislalpha(ls->current)) /* is numeral touching a letter? */ + save_and_next(ls); /* force an error */ + save(ls, '\0'); + if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ + lexerror(ls, "malformed number", TK_FLT); + if (ttisinteger(&obj)) { + seminfo->i = ivalue(&obj); + return TK_INT; + } + else { + lua_assert(ttisfloat(&obj)); + seminfo->r = fltvalue(&obj); + return TK_FLT; + } +} + + +/* +** read a sequence '[=*[' or ']=*]', leaving the last bracket. If +** sequence is well formed, return its number of '='s + 2; otherwise, +** return 1 if it is a single bracket (no '='s and no 2nd bracket); +** otherwise (an unfinished '[==...') return 0. +*/ +static size_t skip_sep (LexState *ls) { + size_t count = 0; + int s = ls->current; + lua_assert(s == '[' || s == ']'); + save_and_next(ls); + while (ls->current == '=') { + save_and_next(ls); + count++; + } + return (ls->current == s) ? count + 2 + : (count == 0) ? 1 + : 0; +} + + +static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) { + int line = ls->linenumber; /* initial line (for error message) */ + save_and_next(ls); /* skip 2nd '[' */ + if (currIsNewline(ls)) /* string starts with a newline? */ + inclinenumber(ls); /* skip it */ + for (;;) { + switch (ls->current) { + case EOZ: { /* error */ + const char *what = (seminfo ? "string" : "comment"); + const char *msg = luaO_pushfstring(ls->L, + "unfinished long %s (starting at line %d)", what, line); + lexerror(ls, msg, TK_EOS); + break; /* to avoid warnings */ + } + case ']': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd ']' */ + goto endloop; + } + break; + } + case '\n': case '\r': { + save(ls, '\n'); + inclinenumber(ls); + if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ + break; + } + default: { + if (seminfo) save_and_next(ls); + else next(ls); + } + } + } endloop: + if (seminfo) + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep, + luaZ_bufflen(ls->buff) - 2 * sep); +} + + +static void esccheck (LexState *ls, int c, const char *msg) { + if (!c) { + if (ls->current != EOZ) + save_and_next(ls); /* add current to buffer for error message */ + lexerror(ls, msg, TK_STRING); + } +} + + +static int gethexa (LexState *ls) { + save_and_next(ls); + esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected"); + return luaO_hexavalue(ls->current); +} + + +static int readhexaesc (LexState *ls) { + int r = gethexa(ls); + r = (r << 4) + gethexa(ls); + luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ + return r; +} + + +static unsigned long readutf8esc (LexState *ls) { + unsigned long r; + int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */ + save_and_next(ls); /* skip 'u' */ + esccheck(ls, ls->current == '{', "missing '{'"); + r = gethexa(ls); /* must have at least one digit */ + while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) { + i++; + esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large"); + r = (r << 4) + luaO_hexavalue(ls->current); + } + esccheck(ls, ls->current == '}', "missing '}'"); + next(ls); /* skip '}' */ + luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ + return r; +} + + +static void utf8esc (LexState *ls) { + char buff[UTF8BUFFSZ]; + int n = luaO_utf8esc(buff, readutf8esc(ls)); + for (; n > 0; n--) /* add 'buff' to string */ + save(ls, buff[UTF8BUFFSZ - n]); +} + + +static int readdecesc (LexState *ls) { + int i; + int r = 0; /* result accumulator */ + for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ + r = 10*r + ls->current - '0'; + save_and_next(ls); + } + esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); + luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ + return r; +} + + +static void read_string (LexState *ls, int del, SemInfo *seminfo) { + save_and_next(ls); /* keep delimiter (for error messages) */ + while (ls->current != del) { + switch (ls->current) { + case EOZ: + lexerror(ls, "unfinished string", TK_EOS); + break; /* to avoid warnings */ + case '\n': + case '\r': + lexerror(ls, "unfinished string", TK_STRING); + break; /* to avoid warnings */ + case '\\': { /* escape sequences */ + int c; /* final character to be saved */ + save_and_next(ls); /* keep '\\' for error messages */ + switch (ls->current) { + case 'a': c = '\a'; goto read_save; + case 'b': c = '\b'; goto read_save; + case 'f': c = '\f'; goto read_save; + case 'n': c = '\n'; goto read_save; + case 'r': c = '\r'; goto read_save; + case 't': c = '\t'; goto read_save; + case 'v': c = '\v'; goto read_save; + case 'x': c = readhexaesc(ls); goto read_save; + case 'u': utf8esc(ls); goto no_save; + case '\n': case '\r': + inclinenumber(ls); c = '\n'; goto only_save; + case '\\': case '\"': case '\'': + c = ls->current; goto read_save; + case EOZ: goto no_save; /* will raise an error next loop */ + case 'z': { /* zap following span of spaces */ + luaZ_buffremove(ls->buff, 1); /* remove '\\' */ + next(ls); /* skip the 'z' */ + while (lisspace(ls->current)) { + if (currIsNewline(ls)) inclinenumber(ls); + else next(ls); + } + goto no_save; + } + default: { + esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); + c = readdecesc(ls); /* digital escape '\ddd' */ + goto only_save; + } + } + read_save: + next(ls); + /* go through */ + only_save: + luaZ_buffremove(ls->buff, 1); /* remove '\\' */ + save(ls, c); + /* go through */ + no_save: break; + } + default: + save_and_next(ls); + } + } + save_and_next(ls); /* skip delimiter */ + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, + luaZ_bufflen(ls->buff) - 2); +} + + +static int llex (LexState *ls, SemInfo *seminfo) { + luaZ_resetbuffer(ls->buff); + for (;;) { + switch (ls->current) { + case '\n': case '\r': { /* line breaks */ + inclinenumber(ls); + break; + } + case ' ': case '\f': case '\t': case '\v': { /* spaces */ + next(ls); + break; + } + case '-': { /* '-' or '--' (comment) */ + next(ls); + if (ls->current != '-') return '-'; + /* else is a comment */ + next(ls); + if (ls->current == '[') { /* long comment? */ + size_t sep = skip_sep(ls); + luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ + if (sep >= 2) { + read_long_string(ls, NULL, sep); /* skip long comment */ + luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ + break; + } + } + /* else short comment */ + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); /* skip until end of line (or end of file) */ + break; + } + case '[': { /* long string or simply '[' */ + size_t sep = skip_sep(ls); + if (sep >= 2) { + read_long_string(ls, seminfo, sep); + return TK_STRING; + } + else if (sep == 0) /* '[=...' missing second bracket? */ + lexerror(ls, "invalid long string delimiter", TK_STRING); + return '['; + } + case '=': { + next(ls); + if (check_next1(ls, '=')) return TK_EQ; /* '==' */ + else return '='; + } + case '<': { + next(ls); + if (check_next1(ls, '=')) return TK_LE; /* '<=' */ + else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */ + else return '<'; + } + case '>': { + next(ls); + if (check_next1(ls, '=')) return TK_GE; /* '>=' */ + else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */ + else return '>'; + } + case '/': { + next(ls); + if (check_next1(ls, '/')) return TK_IDIV; /* '//' */ + else return '/'; + } + case '~': { + next(ls); + if (check_next1(ls, '=')) return TK_NE; /* '~=' */ + else return '~'; + } + case ':': { + next(ls); + if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */ + else return ':'; + } + case '"': case '\'': { /* short literal strings */ + read_string(ls, ls->current, seminfo); + return TK_STRING; + } + case '.': { /* '.', '..', '...', or number */ + save_and_next(ls); + if (check_next1(ls, '.')) { + if (check_next1(ls, '.')) + return TK_DOTS; /* '...' */ + else return TK_CONCAT; /* '..' */ + } + else if (!lisdigit(ls->current)) return '.'; + else return read_numeral(ls, seminfo); + } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + return read_numeral(ls, seminfo); + } + case EOZ: { + return TK_EOS; + } + default: { + if (lislalpha(ls->current)) { /* identifier or reserved word? */ + TString *ts; + do { + save_and_next(ls); + } while (lislalnum(ls->current)); + ts = luaX_newstring(ls, luaZ_buffer(ls->buff), + luaZ_bufflen(ls->buff)); + seminfo->ts = ts; + if (isreserved(ts)) /* reserved word? */ + return ts->extra - 1 + FIRST_RESERVED; + else { + return TK_NAME; + } + } + else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */ + int c = ls->current; + next(ls); + return c; + } + } + } + } +} + + +void luaX_next (LexState *ls) { + ls->lastline = ls->linenumber; + if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ + ls->t = ls->lookahead; /* use this one */ + ls->lookahead.token = TK_EOS; /* and discharge it */ + } + else + ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ +} + + +int luaX_lookahead (LexState *ls) { + lua_assert(ls->lookahead.token == TK_EOS); + ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); + return ls->lookahead.token; +} + diff --git a/src/libs/3rdparty/lua/src/llex.h b/src/libs/3rdparty/lua/src/llex.h new file mode 100644 index 00000000000..389d2f86359 --- /dev/null +++ b/src/libs/3rdparty/lua/src/llex.h @@ -0,0 +1,91 @@ +/* +** $Id: llex.h $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#ifndef llex_h +#define llex_h + +#include + +#include "lobject.h" +#include "lzio.h" + + +/* +** Single-char tokens (terminal symbols) are represented by their own +** numeric code. Other tokens start at the following value. +*/ +#define FIRST_RESERVED (UCHAR_MAX + 1) + + +#if !defined(LUA_ENV) +#define LUA_ENV "_ENV" +#endif + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER RESERVED" +*/ +enum RESERVED { + /* terminal symbols denoted by reserved words */ + TK_AND = FIRST_RESERVED, TK_BREAK, + TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, + TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, + TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, + /* other terminal symbols */ + TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, + TK_SHL, TK_SHR, + TK_DBCOLON, TK_EOS, + TK_FLT, TK_INT, TK_NAME, TK_STRING +}; + +/* number of reserved words */ +#define NUM_RESERVED (cast_int(TK_WHILE-FIRST_RESERVED + 1)) + + +typedef union { + lua_Number r; + lua_Integer i; + TString *ts; +} SemInfo; /* semantics information */ + + +typedef struct Token { + int token; + SemInfo seminfo; +} Token; + + +/* state of the lexer plus state of the parser when shared by all + functions */ +typedef struct LexState { + int current; /* current character (charint) */ + int linenumber; /* input line counter */ + int lastline; /* line of last token 'consumed' */ + Token t; /* current token */ + Token lookahead; /* look ahead token */ + struct FuncState *fs; /* current function (parser) */ + struct lua_State *L; + ZIO *z; /* input stream */ + Mbuffer *buff; /* buffer for tokens */ + Table *h; /* to avoid collection/reuse strings */ + struct Dyndata *dyd; /* dynamic structures used by the parser */ + TString *source; /* current source name */ + TString *envn; /* environment variable name */ +} LexState; + + +LUAI_FUNC void luaX_init (lua_State *L); +LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, + TString *source, int firstchar); +LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); +LUAI_FUNC void luaX_next (LexState *ls); +LUAI_FUNC int luaX_lookahead (LexState *ls); +LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); +LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); + + +#endif diff --git a/src/libs/3rdparty/lua/src/llimits.h b/src/libs/3rdparty/lua/src/llimits.h new file mode 100644 index 00000000000..1c826f7be20 --- /dev/null +++ b/src/libs/3rdparty/lua/src/llimits.h @@ -0,0 +1,380 @@ +/* +** $Id: llimits.h $ +** Limits, basic types, and some other 'installation-dependent' definitions +** See Copyright Notice in lua.h +*/ + +#ifndef llimits_h +#define llimits_h + + +#include +#include + + +#include "lua.h" + + +/* +** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count +** the total memory used by Lua (in bytes). Usually, 'size_t' and +** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. +*/ +#if defined(LUAI_MEM) /* { external definitions? */ +typedef LUAI_UMEM lu_mem; +typedef LUAI_MEM l_mem; +#elif LUAI_IS32INT /* }{ */ +typedef size_t lu_mem; +typedef ptrdiff_t l_mem; +#else /* 16-bit ints */ /* }{ */ +typedef unsigned long lu_mem; +typedef long l_mem; +#endif /* } */ + + +/* chars used as small naturals (so that 'char' is reserved for characters) */ +typedef unsigned char lu_byte; +typedef signed char ls_byte; + + +/* maximum value for size_t */ +#define MAX_SIZET ((size_t)(~(size_t)0)) + +/* maximum size visible for Lua (must be representable in a lua_Integer) */ +#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \ + : (size_t)(LUA_MAXINTEGER)) + + +#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)) + +#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1)) + + +#define MAX_INT INT_MAX /* maximum value of an int */ + + +/* +** floor of the log2 of the maximum signed value for integral type 't'. +** (That is, maximum 'n' such that '2^n' fits in the given signed type.) +*/ +#define log2maxs(t) (sizeof(t) * 8 - 2) + + +/* +** test whether an unsigned value is a power of 2 (or zero) +*/ +#define ispow2(x) (((x) & ((x) - 1)) == 0) + + +/* number of chars of a literal string without the ending \0 */ +#define LL(x) (sizeof(x)/sizeof(char) - 1) + + +/* +** conversion of pointer to unsigned integer: this is for hashing only; +** there is no problem if the integer cannot hold the whole pointer +** value. (In strict ISO C this may cause undefined behavior, but no +** actual machine seems to bother.) +*/ +#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 199901L +#include +#if defined(UINTPTR_MAX) /* even in C99 this type is optional */ +#define L_P2I uintptr_t +#else /* no 'intptr'? */ +#define L_P2I uintmax_t /* use the largest available integer */ +#endif +#else /* C89 option */ +#define L_P2I size_t +#endif + +#define point2uint(p) ((unsigned int)((L_P2I)(p) & UINT_MAX)) + + + +/* types of 'usual argument conversions' for lua_Number and lua_Integer */ +typedef LUAI_UACNUMBER l_uacNumber; +typedef LUAI_UACINT l_uacInt; + + +/* +** Internal assertions for in-house debugging +*/ +#if defined LUAI_ASSERT +#undef NDEBUG +#include +#define lua_assert(c) assert(c) +#endif + +#if defined(lua_assert) +#define check_exp(c,e) (lua_assert(c), (e)) +/* to avoid problems with conditions too long */ +#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0)) +#else +#define lua_assert(c) ((void)0) +#define check_exp(c,e) (e) +#define lua_longassert(c) ((void)0) +#endif + +/* +** assertion for checking API calls +*/ +#if !defined(luai_apicheck) +#define luai_apicheck(l,e) ((void)l, lua_assert(e)) +#endif + +#define api_check(l,e,msg) luai_apicheck(l,(e) && msg) + + +/* macro to avoid warnings about unused variables */ +#if !defined(UNUSED) +#define UNUSED(x) ((void)(x)) +#endif + + +/* type casts (a macro highlights casts in the code) */ +#define cast(t, exp) ((t)(exp)) + +#define cast_void(i) cast(void, (i)) +#define cast_voidp(i) cast(void *, (i)) +#define cast_num(i) cast(lua_Number, (i)) +#define cast_int(i) cast(int, (i)) +#define cast_uint(i) cast(unsigned int, (i)) +#define cast_byte(i) cast(lu_byte, (i)) +#define cast_uchar(i) cast(unsigned char, (i)) +#define cast_char(i) cast(char, (i)) +#define cast_charp(i) cast(char *, (i)) +#define cast_sizet(i) cast(size_t, (i)) + + +/* cast a signed lua_Integer to lua_Unsigned */ +#if !defined(l_castS2U) +#define l_castS2U(i) ((lua_Unsigned)(i)) +#endif + +/* +** cast a lua_Unsigned to a signed lua_Integer; this cast is +** not strict ISO C, but two-complement architectures should +** work fine. +*/ +#if !defined(l_castU2S) +#define l_castU2S(i) ((lua_Integer)(i)) +#endif + + +/* +** non-return type +*/ +#if !defined(l_noret) + +#if defined(__GNUC__) +#define l_noret void __attribute__((noreturn)) +#elif defined(_MSC_VER) && _MSC_VER >= 1200 +#define l_noret void __declspec(noreturn) +#else +#define l_noret void +#endif + +#endif + + +/* +** Inline functions +*/ +#if !defined(LUA_USE_C89) +#define l_inline inline +#elif defined(__GNUC__) +#define l_inline __inline__ +#else +#define l_inline /* empty */ +#endif + +#define l_sinline static l_inline + + +/* +** type for virtual-machine instructions; +** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) +*/ +#if LUAI_IS32INT +typedef unsigned int l_uint32; +#else +typedef unsigned long l_uint32; +#endif + +typedef l_uint32 Instruction; + + + +/* +** Maximum length for short strings, that is, strings that are +** internalized. (Cannot be smaller than reserved words or tags for +** metamethods, as these strings must be internalized; +** #("function") = 8, #("__newindex") = 10.) +*/ +#if !defined(LUAI_MAXSHORTLEN) +#define LUAI_MAXSHORTLEN 40 +#endif + + +/* +** Initial size for the string table (must be power of 2). +** The Lua core alone registers ~50 strings (reserved words + +** metaevent keys + a few others). Libraries would typically add +** a few dozens more. +*/ +#if !defined(MINSTRTABSIZE) +#define MINSTRTABSIZE 128 +#endif + + +/* +** Size of cache for strings in the API. 'N' is the number of +** sets (better be a prime) and "M" is the size of each set (M == 1 +** makes a direct cache.) +*/ +#if !defined(STRCACHE_N) +#define STRCACHE_N 53 +#define STRCACHE_M 2 +#endif + + +/* minimum size for string buffer */ +#if !defined(LUA_MINBUFFER) +#define LUA_MINBUFFER 32 +#endif + + +/* +** Maximum depth for nested C calls, syntactical nested non-terminals, +** and other features implemented through recursion in C. (Value must +** fit in a 16-bit unsigned integer. It must also be compatible with +** the size of the C stack.) +*/ +#if !defined(LUAI_MAXCCALLS) +#define LUAI_MAXCCALLS 200 +#endif + + +/* +** macros that are executed whenever program enters the Lua core +** ('lua_lock') and leaves the core ('lua_unlock') +*/ +#if !defined(lua_lock) +#define lua_lock(L) ((void) 0) +#define lua_unlock(L) ((void) 0) +#endif + +/* +** macro executed during Lua functions at points where the +** function can yield. +*/ +#if !defined(luai_threadyield) +#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} +#endif + + +/* +** these macros allow user-specific actions when a thread is +** created/deleted/resumed/yielded. +*/ +#if !defined(luai_userstateopen) +#define luai_userstateopen(L) ((void)L) +#endif + +#if !defined(luai_userstateclose) +#define luai_userstateclose(L) ((void)L) +#endif + +#if !defined(luai_userstatethread) +#define luai_userstatethread(L,L1) ((void)L) +#endif + +#if !defined(luai_userstatefree) +#define luai_userstatefree(L,L1) ((void)L) +#endif + +#if !defined(luai_userstateresume) +#define luai_userstateresume(L,n) ((void)L) +#endif + +#if !defined(luai_userstateyield) +#define luai_userstateyield(L,n) ((void)L) +#endif + + + +/* +** The luai_num* macros define the primitive operations over numbers. +*/ + +/* floor division (defined as 'floor(a/b)') */ +#if !defined(luai_numidiv) +#define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b))) +#endif + +/* float division */ +#if !defined(luai_numdiv) +#define luai_numdiv(L,a,b) ((a)/(b)) +#endif + +/* +** modulo: defined as 'a - floor(a/b)*b'; the direct computation +** using this definition has several problems with rounding errors, +** so it is better to use 'fmod'. 'fmod' gives the result of +** 'a - trunc(a/b)*b', and therefore must be corrected when +** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a +** non-integer negative result: non-integer result is equivalent to +** a non-zero remainder 'm'; negative result is equivalent to 'a' and +** 'b' with different signs, or 'm' and 'b' with different signs +** (as the result 'm' of 'fmod' has the same sign of 'a'). +*/ +#if !defined(luai_nummod) +#define luai_nummod(L,a,b,m) \ + { (void)L; (m) = l_mathop(fmod)(a,b); \ + if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); } +#endif + +/* exponentiation */ +#if !defined(luai_numpow) +#define luai_numpow(L,a,b) \ + ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b)) +#endif + +/* the others are quite standard operations */ +#if !defined(luai_numadd) +#define luai_numadd(L,a,b) ((a)+(b)) +#define luai_numsub(L,a,b) ((a)-(b)) +#define luai_nummul(L,a,b) ((a)*(b)) +#define luai_numunm(L,a) (-(a)) +#define luai_numeq(a,b) ((a)==(b)) +#define luai_numlt(a,b) ((a)<(b)) +#define luai_numle(a,b) ((a)<=(b)) +#define luai_numgt(a,b) ((a)>(b)) +#define luai_numge(a,b) ((a)>=(b)) +#define luai_numisnan(a) (!luai_numeq((a), (a))) +#endif + + + + + +/* +** macro to control inclusion of some hard tests on stack reallocation +*/ +#if !defined(HARDSTACKTESTS) +#define condmovestack(L,pre,pos) ((void)0) +#else +/* realloc stack keeping its size */ +#define condmovestack(L,pre,pos) \ + { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; } +#endif + +#if !defined(HARDMEMTESTS) +#define condchangemem(L,pre,pos) ((void)0) +#else +#define condchangemem(L,pre,pos) \ + { if (gcrunning(G(L))) { pre; luaC_fullgc(L, 0); pos; } } +#endif + +#endif diff --git a/src/libs/3rdparty/lua/src/lmathlib.c b/src/libs/3rdparty/lua/src/lmathlib.c new file mode 100644 index 00000000000..d0b1e1e5d6f --- /dev/null +++ b/src/libs/3rdparty/lua/src/lmathlib.c @@ -0,0 +1,764 @@ +/* +** $Id: lmathlib.c $ +** Standard mathematical library +** See Copyright Notice in lua.h +*/ + +#define lmathlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#undef PI +#define PI (l_mathop(3.141592653589793238462643383279502884)) + + +static int math_abs (lua_State *L) { + if (lua_isinteger(L, 1)) { + lua_Integer n = lua_tointeger(L, 1); + if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n); + lua_pushinteger(L, n); + } + else + lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sin (lua_State *L) { + lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_cos (lua_State *L) { + lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tan (lua_State *L) { + lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_asin (lua_State *L) { + lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_acos (lua_State *L) { + lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_atan (lua_State *L) { + lua_Number y = luaL_checknumber(L, 1); + lua_Number x = luaL_optnumber(L, 2, 1); + lua_pushnumber(L, l_mathop(atan2)(y, x)); + return 1; +} + + +static int math_toint (lua_State *L) { + int valid; + lua_Integer n = lua_tointegerx(L, 1, &valid); + if (l_likely(valid)) + lua_pushinteger(L, n); + else { + luaL_checkany(L, 1); + luaL_pushfail(L); /* value is not convertible to integer */ + } + return 1; +} + + +static void pushnumint (lua_State *L, lua_Number d) { + lua_Integer n; + if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */ + lua_pushinteger(L, n); /* result is integer */ + else + lua_pushnumber(L, d); /* result is float */ +} + + +static int math_floor (lua_State *L) { + if (lua_isinteger(L, 1)) + lua_settop(L, 1); /* integer is its own floor */ + else { + lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1)); + pushnumint(L, d); + } + return 1; +} + + +static int math_ceil (lua_State *L) { + if (lua_isinteger(L, 1)) + lua_settop(L, 1); /* integer is its own ceil */ + else { + lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1)); + pushnumint(L, d); + } + return 1; +} + + +static int math_fmod (lua_State *L) { + if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) { + lua_Integer d = lua_tointeger(L, 2); + if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */ + luaL_argcheck(L, d != 0, 2, "zero"); + lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */ + } + else + lua_pushinteger(L, lua_tointeger(L, 1) % d); + } + else + lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1), + luaL_checknumber(L, 2))); + return 1; +} + + +/* +** next function does not use 'modf', avoiding problems with 'double*' +** (which is not compatible with 'float*') when lua_Number is not +** 'double'. +*/ +static int math_modf (lua_State *L) { + if (lua_isinteger(L ,1)) { + lua_settop(L, 1); /* number is its own integer part */ + lua_pushnumber(L, 0); /* no fractional part */ + } + else { + lua_Number n = luaL_checknumber(L, 1); + /* integer part (rounds toward zero) */ + lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n); + pushnumint(L, ip); + /* fractional part (test needed for inf/-inf) */ + lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip)); + } + return 2; +} + + +static int math_sqrt (lua_State *L) { + lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1))); + return 1; +} + + +static int math_ult (lua_State *L) { + lua_Integer a = luaL_checkinteger(L, 1); + lua_Integer b = luaL_checkinteger(L, 2); + lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b); + return 1; +} + +static int math_log (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + lua_Number res; + if (lua_isnoneornil(L, 2)) + res = l_mathop(log)(x); + else { + lua_Number base = luaL_checknumber(L, 2); +#if !defined(LUA_USE_C89) + if (base == l_mathop(2.0)) + res = l_mathop(log2)(x); + else +#endif + if (base == l_mathop(10.0)) + res = l_mathop(log10)(x); + else + res = l_mathop(log)(x)/l_mathop(log)(base); + } + lua_pushnumber(L, res); + return 1; +} + +static int math_exp (lua_State *L) { + lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_deg (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI)); + return 1; +} + +static int math_rad (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0))); + return 1; +} + + +static int math_min (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int imin = 1; /* index of current minimum value */ + int i; + luaL_argcheck(L, n >= 1, 1, "value expected"); + for (i = 2; i <= n; i++) { + if (lua_compare(L, i, imin, LUA_OPLT)) + imin = i; + } + lua_pushvalue(L, imin); + return 1; +} + + +static int math_max (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int imax = 1; /* index of current maximum value */ + int i; + luaL_argcheck(L, n >= 1, 1, "value expected"); + for (i = 2; i <= n; i++) { + if (lua_compare(L, imax, i, LUA_OPLT)) + imax = i; + } + lua_pushvalue(L, imax); + return 1; +} + + +static int math_type (lua_State *L) { + if (lua_type(L, 1) == LUA_TNUMBER) + lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float"); + else { + luaL_checkany(L, 1); + luaL_pushfail(L); + } + return 1; +} + + + +/* +** {================================================================== +** Pseudo-Random Number Generator based on 'xoshiro256**'. +** =================================================================== +*/ + +/* number of binary digits in the mantissa of a float */ +#define FIGS l_floatatt(MANT_DIG) + +#if FIGS > 64 +/* there are only 64 random bits; use them all */ +#undef FIGS +#define FIGS 64 +#endif + + +/* +** LUA_RAND32 forces the use of 32-bit integers in the implementation +** of the PRN generator (mainly for testing). +*/ +#if !defined(LUA_RAND32) && !defined(Rand64) + +/* try to find an integer type with at least 64 bits */ + +#if ((ULONG_MAX >> 31) >> 31) >= 3 + +/* 'long' has at least 64 bits */ +#define Rand64 unsigned long + +#elif !defined(LUA_USE_C89) && defined(LLONG_MAX) + +/* there is a 'long long' type (which must have at least 64 bits) */ +#define Rand64 unsigned long long + +#elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3 + +/* 'lua_Unsigned' has at least 64 bits */ +#define Rand64 lua_Unsigned + +#endif + +#endif + + +#if defined(Rand64) /* { */ + +/* +** Standard implementation, using 64-bit integers. +** If 'Rand64' has more than 64 bits, the extra bits do not interfere +** with the 64 initial bits, except in a right shift. Moreover, the +** final result has to discard the extra bits. +*/ + +/* avoid using extra bits when needed */ +#define trim64(x) ((x) & 0xffffffffffffffffu) + + +/* rotate left 'x' by 'n' bits */ +static Rand64 rotl (Rand64 x, int n) { + return (x << n) | (trim64(x) >> (64 - n)); +} + +static Rand64 nextrand (Rand64 *state) { + Rand64 state0 = state[0]; + Rand64 state1 = state[1]; + Rand64 state2 = state[2] ^ state0; + Rand64 state3 = state[3] ^ state1; + Rand64 res = rotl(state1 * 5, 7) * 9; + state[0] = state0 ^ state3; + state[1] = state1 ^ state2; + state[2] = state2 ^ (state1 << 17); + state[3] = rotl(state3, 45); + return res; +} + + +/* must take care to not shift stuff by more than 63 slots */ + + +/* +** Convert bits from a random integer into a float in the +** interval [0,1), getting the higher FIG bits from the +** random unsigned integer and converting that to a float. +*/ + +/* must throw out the extra (64 - FIGS) bits */ +#define shift64_FIG (64 - FIGS) + +/* to scale to [0, 1), multiply by scaleFIG = 2^(-FIGS) */ +#define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1))) + +static lua_Number I2d (Rand64 x) { + return (lua_Number)(trim64(x) >> shift64_FIG) * scaleFIG; +} + +/* convert a 'Rand64' to a 'lua_Unsigned' */ +#define I2UInt(x) ((lua_Unsigned)trim64(x)) + +/* convert a 'lua_Unsigned' to a 'Rand64' */ +#define Int2I(x) ((Rand64)(x)) + + +#else /* no 'Rand64' }{ */ + +/* get an integer with at least 32 bits */ +#if LUAI_IS32INT +typedef unsigned int lu_int32; +#else +typedef unsigned long lu_int32; +#endif + + +/* +** Use two 32-bit integers to represent a 64-bit quantity. +*/ +typedef struct Rand64 { + lu_int32 h; /* higher half */ + lu_int32 l; /* lower half */ +} Rand64; + + +/* +** If 'lu_int32' has more than 32 bits, the extra bits do not interfere +** with the 32 initial bits, except in a right shift and comparisons. +** Moreover, the final result has to discard the extra bits. +*/ + +/* avoid using extra bits when needed */ +#define trim32(x) ((x) & 0xffffffffu) + + +/* +** basic operations on 'Rand64' values +*/ + +/* build a new Rand64 value */ +static Rand64 packI (lu_int32 h, lu_int32 l) { + Rand64 result; + result.h = h; + result.l = l; + return result; +} + +/* return i << n */ +static Rand64 Ishl (Rand64 i, int n) { + lua_assert(n > 0 && n < 32); + return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n); +} + +/* i1 ^= i2 */ +static void Ixor (Rand64 *i1, Rand64 i2) { + i1->h ^= i2.h; + i1->l ^= i2.l; +} + +/* return i1 + i2 */ +static Rand64 Iadd (Rand64 i1, Rand64 i2) { + Rand64 result = packI(i1.h + i2.h, i1.l + i2.l); + if (trim32(result.l) < trim32(i1.l)) /* carry? */ + result.h++; + return result; +} + +/* return i * 5 */ +static Rand64 times5 (Rand64 i) { + return Iadd(Ishl(i, 2), i); /* i * 5 == (i << 2) + i */ +} + +/* return i * 9 */ +static Rand64 times9 (Rand64 i) { + return Iadd(Ishl(i, 3), i); /* i * 9 == (i << 3) + i */ +} + +/* return 'i' rotated left 'n' bits */ +static Rand64 rotl (Rand64 i, int n) { + lua_assert(n > 0 && n < 32); + return packI((i.h << n) | (trim32(i.l) >> (32 - n)), + (trim32(i.h) >> (32 - n)) | (i.l << n)); +} + +/* for offsets larger than 32, rotate right by 64 - offset */ +static Rand64 rotl1 (Rand64 i, int n) { + lua_assert(n > 32 && n < 64); + n = 64 - n; + return packI((trim32(i.h) >> n) | (i.l << (32 - n)), + (i.h << (32 - n)) | (trim32(i.l) >> n)); +} + +/* +** implementation of 'xoshiro256**' algorithm on 'Rand64' values +*/ +static Rand64 nextrand (Rand64 *state) { + Rand64 res = times9(rotl(times5(state[1]), 7)); + Rand64 t = Ishl(state[1], 17); + Ixor(&state[2], state[0]); + Ixor(&state[3], state[1]); + Ixor(&state[1], state[2]); + Ixor(&state[0], state[3]); + Ixor(&state[2], t); + state[3] = rotl1(state[3], 45); + return res; +} + + +/* +** Converts a 'Rand64' into a float. +*/ + +/* an unsigned 1 with proper type */ +#define UONE ((lu_int32)1) + + +#if FIGS <= 32 + +/* 2^(-FIGS) */ +#define scaleFIG (l_mathop(0.5) / (UONE << (FIGS - 1))) + +/* +** get up to 32 bits from higher half, shifting right to +** throw out the extra bits. +*/ +static lua_Number I2d (Rand64 x) { + lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS)); + return h * scaleFIG; +} + +#else /* 32 < FIGS <= 64 */ + +/* must take care to not shift stuff by more than 31 slots */ + +/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */ +#define scaleFIG \ + (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33))) + +/* +** use FIGS - 32 bits from lower half, throwing out the other +** (32 - (FIGS - 32)) = (64 - FIGS) bits +*/ +#define shiftLOW (64 - FIGS) + +/* +** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32) +*/ +#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0)) + + +static lua_Number I2d (Rand64 x) { + lua_Number h = (lua_Number)trim32(x.h) * shiftHI; + lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW); + return (h + l) * scaleFIG; +} + +#endif + + +/* convert a 'Rand64' to a 'lua_Unsigned' */ +static lua_Unsigned I2UInt (Rand64 x) { + return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l); +} + +/* convert a 'lua_Unsigned' to a 'Rand64' */ +static Rand64 Int2I (lua_Unsigned n) { + return packI((lu_int32)((n >> 31) >> 1), (lu_int32)n); +} + +#endif /* } */ + + +/* +** A state uses four 'Rand64' values. +*/ +typedef struct { + Rand64 s[4]; +} RanState; + + +/* +** Project the random integer 'ran' into the interval [0, n]. +** Because 'ran' has 2^B possible values, the projection can only be +** uniform when the size of the interval is a power of 2 (exact +** division). Otherwise, to get a uniform projection into [0, n], we +** first compute 'lim', the smallest Mersenne number not smaller than +** 'n'. We then project 'ran' into the interval [0, lim]. If the result +** is inside [0, n], we are done. Otherwise, we try with another 'ran', +** until we have a result inside the interval. +*/ +static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n, + RanState *state) { + if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */ + return ran & n; /* no bias */ + else { + lua_Unsigned lim = n; + /* compute the smallest (2^b - 1) not smaller than 'n' */ + lim |= (lim >> 1); + lim |= (lim >> 2); + lim |= (lim >> 4); + lim |= (lim >> 8); + lim |= (lim >> 16); +#if (LUA_MAXUNSIGNED >> 31) >= 3 + lim |= (lim >> 32); /* integer type has more than 32 bits */ +#endif + lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */ + && lim >= n /* not smaller than 'n', */ + && (lim >> 1) < n); /* and it is the smallest one */ + while ((ran &= lim) > n) /* project 'ran' into [0..lim] */ + ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */ + return ran; + } +} + + +static int math_random (lua_State *L) { + lua_Integer low, up; + lua_Unsigned p; + RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); + Rand64 rv = nextrand(state->s); /* next pseudo-random value */ + switch (lua_gettop(L)) { /* check number of arguments */ + case 0: { /* no arguments */ + lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */ + return 1; + } + case 1: { /* only upper limit */ + low = 1; + up = luaL_checkinteger(L, 1); + if (up == 0) { /* single 0 as argument? */ + lua_pushinteger(L, I2UInt(rv)); /* full random integer */ + return 1; + } + break; + } + case 2: { /* lower and upper limits */ + low = luaL_checkinteger(L, 1); + up = luaL_checkinteger(L, 2); + break; + } + default: return luaL_error(L, "wrong number of arguments"); + } + /* random integer in the interval [low, up] */ + luaL_argcheck(L, low <= up, 1, "interval is empty"); + /* project random integer into the interval [0, up - low] */ + p = project(I2UInt(rv), (lua_Unsigned)up - (lua_Unsigned)low, state); + lua_pushinteger(L, p + (lua_Unsigned)low); + return 1; +} + + +static void setseed (lua_State *L, Rand64 *state, + lua_Unsigned n1, lua_Unsigned n2) { + int i; + state[0] = Int2I(n1); + state[1] = Int2I(0xff); /* avoid a zero state */ + state[2] = Int2I(n2); + state[3] = Int2I(0); + for (i = 0; i < 16; i++) + nextrand(state); /* discard initial values to "spread" seed */ + lua_pushinteger(L, n1); + lua_pushinteger(L, n2); +} + + +/* +** Set a "random" seed. To get some randomness, use the current time +** and the address of 'L' (in case the machine does address space layout +** randomization). +*/ +static void randseed (lua_State *L, RanState *state) { + lua_Unsigned seed1 = (lua_Unsigned)time(NULL); + lua_Unsigned seed2 = (lua_Unsigned)(size_t)L; + setseed(L, state->s, seed1, seed2); +} + + +static int math_randomseed (lua_State *L) { + RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); + if (lua_isnone(L, 1)) { + randseed(L, state); + } + else { + lua_Integer n1 = luaL_checkinteger(L, 1); + lua_Integer n2 = luaL_optinteger(L, 2, 0); + setseed(L, state->s, n1, n2); + } + return 2; /* return seeds */ +} + + +static const luaL_Reg randfuncs[] = { + {"random", math_random}, + {"randomseed", math_randomseed}, + {NULL, NULL} +}; + + +/* +** Register the random functions and initialize their state. +*/ +static void setrandfunc (lua_State *L) { + RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); + randseed(L, state); /* initialize with a "random" seed */ + lua_pop(L, 2); /* remove pushed seeds */ + luaL_setfuncs(L, randfuncs, 1); +} + +/* }================================================================== */ + + +/* +** {================================================================== +** Deprecated functions (for compatibility only) +** =================================================================== +*/ +#if defined(LUA_COMPAT_MATHLIB) + +static int math_cosh (lua_State *L) { + lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sinh (lua_State *L) { + lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tanh (lua_State *L) { + lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1))); + return 1; +} + +static int math_pow (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + lua_Number y = luaL_checknumber(L, 2); + lua_pushnumber(L, l_mathop(pow)(x, y)); + return 1; +} + +static int math_frexp (lua_State *L) { + int e; + lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e)); + lua_pushinteger(L, e); + return 2; +} + +static int math_ldexp (lua_State *L) { + lua_Number x = luaL_checknumber(L, 1); + int ep = (int)luaL_checkinteger(L, 2); + lua_pushnumber(L, l_mathop(ldexp)(x, ep)); + return 1; +} + +static int math_log10 (lua_State *L) { + lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1))); + return 1; +} + +#endif +/* }================================================================== */ + + + +static const luaL_Reg mathlib[] = { + {"abs", math_abs}, + {"acos", math_acos}, + {"asin", math_asin}, + {"atan", math_atan}, + {"ceil", math_ceil}, + {"cos", math_cos}, + {"deg", math_deg}, + {"exp", math_exp}, + {"tointeger", math_toint}, + {"floor", math_floor}, + {"fmod", math_fmod}, + {"ult", math_ult}, + {"log", math_log}, + {"max", math_max}, + {"min", math_min}, + {"modf", math_modf}, + {"rad", math_rad}, + {"sin", math_sin}, + {"sqrt", math_sqrt}, + {"tan", math_tan}, + {"type", math_type}, +#if defined(LUA_COMPAT_MATHLIB) + {"atan2", math_atan}, + {"cosh", math_cosh}, + {"sinh", math_sinh}, + {"tanh", math_tanh}, + {"pow", math_pow}, + {"frexp", math_frexp}, + {"ldexp", math_ldexp}, + {"log10", math_log10}, +#endif + /* placeholders */ + {"random", NULL}, + {"randomseed", NULL}, + {"pi", NULL}, + {"huge", NULL}, + {"maxinteger", NULL}, + {"mininteger", NULL}, + {NULL, NULL} +}; + + +/* +** Open math library +*/ +LUAMOD_API int luaopen_math (lua_State *L) { + luaL_newlib(L, mathlib); + lua_pushnumber(L, PI); + lua_setfield(L, -2, "pi"); + lua_pushnumber(L, (lua_Number)HUGE_VAL); + lua_setfield(L, -2, "huge"); + lua_pushinteger(L, LUA_MAXINTEGER); + lua_setfield(L, -2, "maxinteger"); + lua_pushinteger(L, LUA_MININTEGER); + lua_setfield(L, -2, "mininteger"); + setrandfunc(L); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/lmem.c b/src/libs/3rdparty/lua/src/lmem.c new file mode 100644 index 00000000000..9800a86fc02 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lmem.c @@ -0,0 +1,215 @@ +/* +** $Id: lmem.c $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#define lmem_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +/* +** About the realloc function: +** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize); +** ('osize' is the old size, 'nsize' is the new size) +** +** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL. +** Particularly, frealloc(ud, NULL, 0, 0) does nothing, +** which is equivalent to free(NULL) in ISO C. +** +** - frealloc(ud, NULL, x, s) creates a new block of size 's' +** (no matter 'x'). Returns NULL if it cannot create the new block. +** +** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from +** size 'x' to size 'y'. Returns NULL if it cannot reallocate the +** block to the new size. +*/ + + +/* +** Macro to call the allocation function. +*/ +#define callfrealloc(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns)) + + +/* +** When an allocation fails, it will try again after an emergency +** collection, except when it cannot run a collection. The GC should +** not be called while the state is not fully built, as the collector +** is not yet fully initialized. Also, it should not be called when +** 'gcstopem' is true, because then the interpreter is in the middle of +** a collection step. +*/ +#define cantryagain(g) (completestate(g) && !g->gcstopem) + + + + +#if defined(EMERGENCYGCTESTS) +/* +** First allocation will fail except when freeing a block (frees never +** fail) and when it cannot try again; this fail will trigger 'tryagain' +** and a full GC cycle at every allocation. +*/ +static void *firsttry (global_State *g, void *block, size_t os, size_t ns) { + if (ns > 0 && cantryagain(g)) + return NULL; /* fail */ + else /* normal allocation */ + return callfrealloc(g, block, os, ns); +} +#else +#define firsttry(g,block,os,ns) callfrealloc(g, block, os, ns) +#endif + + + + + +/* +** {================================================================== +** Functions to allocate/deallocate arrays for the Parser +** =================================================================== +*/ + +/* +** Minimum size for arrays during parsing, to avoid overhead of +** reallocating to size 1, then 2, and then 4. All these arrays +** will be reallocated to exact sizes or erased when parsing ends. +*/ +#define MINSIZEARRAY 4 + + +void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize, + int size_elems, int limit, const char *what) { + void *newblock; + int size = *psize; + if (nelems + 1 <= size) /* does one extra element still fit? */ + return block; /* nothing to be done */ + if (size >= limit / 2) { /* cannot double it? */ + if (l_unlikely(size >= limit)) /* cannot grow even a little? */ + luaG_runerror(L, "too many %s (limit is %d)", what, limit); + size = limit; /* still have at least one free place */ + } + else { + size *= 2; + if (size < MINSIZEARRAY) + size = MINSIZEARRAY; /* minimum size */ + } + lua_assert(nelems + 1 <= size && size <= limit); + /* 'limit' ensures that multiplication will not overflow */ + newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems, + cast_sizet(size) * size_elems); + *psize = size; /* update only when everything else is OK */ + return newblock; +} + + +/* +** In prototypes, the size of the array is also its number of +** elements (to save memory). So, if it cannot shrink an array +** to its number of elements, the only option is to raise an +** error. +*/ +void *luaM_shrinkvector_ (lua_State *L, void *block, int *size, + int final_n, int size_elem) { + void *newblock; + size_t oldsize = cast_sizet((*size) * size_elem); + size_t newsize = cast_sizet(final_n * size_elem); + lua_assert(newsize <= oldsize); + newblock = luaM_saferealloc_(L, block, oldsize, newsize); + *size = final_n; + return newblock; +} + +/* }================================================================== */ + + +l_noret luaM_toobig (lua_State *L) { + luaG_runerror(L, "memory allocation error: block too big"); +} + + +/* +** Free memory +*/ +void luaM_free_ (lua_State *L, void *block, size_t osize) { + global_State *g = G(L); + lua_assert((osize == 0) == (block == NULL)); + callfrealloc(g, block, osize, 0); + g->GCdebt -= osize; +} + + +/* +** In case of allocation fail, this function will do an emergency +** collection to free some memory and then try the allocation again. +*/ +static void *tryagain (lua_State *L, void *block, + size_t osize, size_t nsize) { + global_State *g = G(L); + if (cantryagain(g)) { + luaC_fullgc(L, 1); /* try to free some memory... */ + return callfrealloc(g, block, osize, nsize); /* try again */ + } + else return NULL; /* cannot run an emergency collection */ +} + + +/* +** Generic allocation routine. +*/ +void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { + void *newblock; + global_State *g = G(L); + lua_assert((osize == 0) == (block == NULL)); + newblock = firsttry(g, block, osize, nsize); + if (l_unlikely(newblock == NULL && nsize > 0)) { + newblock = tryagain(L, block, osize, nsize); + if (newblock == NULL) /* still no memory? */ + return NULL; /* do not update 'GCdebt' */ + } + lua_assert((nsize == 0) == (newblock == NULL)); + g->GCdebt = (g->GCdebt + nsize) - osize; + return newblock; +} + + +void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize, + size_t nsize) { + void *newblock = luaM_realloc_(L, block, osize, nsize); + if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */ + luaM_error(L); + return newblock; +} + + +void *luaM_malloc_ (lua_State *L, size_t size, int tag) { + if (size == 0) + return NULL; /* that's all */ + else { + global_State *g = G(L); + void *newblock = firsttry(g, NULL, tag, size); + if (l_unlikely(newblock == NULL)) { + newblock = tryagain(L, NULL, tag, size); + if (newblock == NULL) + luaM_error(L); + } + g->GCdebt += size; + return newblock; + } +} diff --git a/src/libs/3rdparty/lua/src/lmem.h b/src/libs/3rdparty/lua/src/lmem.h new file mode 100644 index 00000000000..8c75a44beb4 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lmem.h @@ -0,0 +1,93 @@ +/* +** $Id: lmem.h $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#ifndef lmem_h +#define lmem_h + + +#include + +#include "llimits.h" +#include "lua.h" + + +#define luaM_error(L) luaD_throw(L, LUA_ERRMEM) + + +/* +** This macro tests whether it is safe to multiply 'n' by the size of +** type 't' without overflows. Because 'e' is always constant, it avoids +** the runtime division MAX_SIZET/(e). +** (The macro is somewhat complex to avoid warnings: The 'sizeof' +** comparison avoids a runtime comparison when overflow cannot occur. +** The compiler should be able to optimize the real test by itself, but +** when it does it, it may give a warning about "comparison is always +** false due to limited range of data type"; the +1 tricks the compiler, +** avoiding this warning but also this optimization.) +*/ +#define luaM_testsize(n,e) \ + (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e)) + +#define luaM_checksize(L,n,e) \ + (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0)) + + +/* +** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that +** the result is not larger than 'n' and cannot overflow a 'size_t' +** when multiplied by the size of type 't'. (Assumes that 'n' is an +** 'int' or 'unsigned int' and that 'int' is not larger than 'size_t'.) +*/ +#define luaM_limitN(n,t) \ + ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \ + cast_uint((MAX_SIZET/sizeof(t)))) + + +/* +** Arrays of chars do not need any test +*/ +#define luaM_reallocvchar(L,b,on,n) \ + cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) + +#define luaM_freemem(L, b, s) luaM_free_(L, (b), (s)) +#define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b))) +#define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b))) + +#define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0)) +#define luaM_newvector(L,n,t) cast(t*, luaM_malloc_(L, (n)*sizeof(t), 0)) +#define luaM_newvectorchecked(L,n,t) \ + (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t)) + +#define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag) + +#define luaM_growvector(L,v,nelems,size,t,limit,e) \ + ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \ + luaM_limitN(limit,t),e))) + +#define luaM_reallocvector(L, v,oldn,n,t) \ + (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \ + cast_sizet(n) * sizeof(t)))) + +#define luaM_shrinkvector(L,v,size,fs,t) \ + ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t)))) + +LUAI_FUNC l_noret luaM_toobig (lua_State *L); + +/* not to be called directly */ +LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, + size_t size); +LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize, + size_t size); +LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize); +LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems, + int *size, int size_elem, int limit, + const char *what); +LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem, + int final_n, int size_elem); +LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag); + +#endif + diff --git a/src/libs/3rdparty/lua/src/loadlib.c b/src/libs/3rdparty/lua/src/loadlib.c new file mode 100644 index 00000000000..d792dffaa03 --- /dev/null +++ b/src/libs/3rdparty/lua/src/loadlib.c @@ -0,0 +1,767 @@ +/* +** $Id: loadlib.c $ +** Dynamic library loader for Lua +** See Copyright Notice in lua.h +** +** This module contains an implementation of loadlib for Unix systems +** that have dlfcn, an implementation for Windows, and a stub for other +** systems. +*/ + +#define loadlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** LUA_IGMARK is a mark to ignore all before it when building the +** luaopen_ function name. +*/ +#if !defined (LUA_IGMARK) +#define LUA_IGMARK "-" +#endif + + +/* +** LUA_CSUBSEP is the character that replaces dots in submodule names +** when searching for a C loader. +** LUA_LSUBSEP is the character that replaces dots in submodule names +** when searching for a Lua loader. +*/ +#if !defined(LUA_CSUBSEP) +#define LUA_CSUBSEP LUA_DIRSEP +#endif + +#if !defined(LUA_LSUBSEP) +#define LUA_LSUBSEP LUA_DIRSEP +#endif + + +/* prefix for open functions in C libraries */ +#define LUA_POF "luaopen_" + +/* separator for open functions in C libraries */ +#define LUA_OFSEP "_" + + +/* +** key for table in the registry that keeps handles +** for all loaded C libraries +*/ +static const char *const CLIBS = "_CLIBS"; + +#define LIB_FAIL "open" + + +#define setprogdir(L) ((void)0) + + +/* +** Special type equivalent to '(void*)' for functions in gcc +** (to suppress warnings when converting function pointers) +*/ +typedef void (*voidf)(void); + + +/* +** system-dependent functions +*/ + +/* +** unload library 'lib' +*/ +static void lsys_unloadlib (void *lib); + +/* +** load C library in file 'path'. If 'seeglb', load with all names in +** the library global. +** Returns the library; in case of error, returns NULL plus an +** error string in the stack. +*/ +static void *lsys_load (lua_State *L, const char *path, int seeglb); + +/* +** Try to find a function named 'sym' in library 'lib'. +** Returns the function; in case of error, returns NULL plus an +** error string in the stack. +*/ +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); + + + + +#if defined(LUA_USE_DLOPEN) /* { */ +/* +** {======================================================================== +** This is an implementation of loadlib based on the dlfcn interface. +** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, +** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least +** as an emulation layer on top of native functions. +** ========================================================================= +*/ + +#include + +/* +** Macro to convert pointer-to-void* to pointer-to-function. This cast +** is undefined according to ISO C, but POSIX assumes that it works. +** (The '__extension__' in gnu compilers is only to avoid warnings.) +*/ +#if defined(__GNUC__) +#define cast_func(p) (__extension__ (lua_CFunction)(p)) +#else +#define cast_func(p) ((lua_CFunction)(p)) +#endif + + +static void lsys_unloadlib (void *lib) { + dlclose(lib); +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); + if (l_unlikely(lib == NULL)) + lua_pushstring(L, dlerror()); + return lib; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = cast_func(dlsym(lib, sym)); + if (l_unlikely(f == NULL)) + lua_pushstring(L, dlerror()); + return f; +} + +/* }====================================================== */ + + + +#elif defined(LUA_DL_DLL) /* }{ */ +/* +** {====================================================================== +** This is an implementation of loadlib for Windows using native functions. +** ======================================================================= +*/ + +#include + + +/* +** optional flags for LoadLibraryEx +*/ +#if !defined(LUA_LLE_FLAGS) +#define LUA_LLE_FLAGS 0 +#endif + + +#undef setprogdir + + +/* +** Replace in the path (on the top of the stack) any occurrence +** of LUA_EXEC_DIR with the executable's path. +*/ +static void setprogdir (lua_State *L) { + char buff[MAX_PATH + 1]; + char *lb; + DWORD nsize = sizeof(buff)/sizeof(char); + DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ + if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) + luaL_error(L, "unable to get ModuleFileName"); + else { + *lb = '\0'; /* cut name on the last '\\' to get the path */ + luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); + lua_remove(L, -2); /* remove original string */ + } +} + + + + +static void pusherror (lua_State *L) { + int error = GetLastError(); + char buffer[128]; + if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) + lua_pushstring(L, buffer); + else + lua_pushfstring(L, "system error %d\n", error); +} + +static void lsys_unloadlib (void *lib) { + FreeLibrary((HMODULE)lib); +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); + (void)(seeglb); /* not used: symbols are 'global' by default */ + if (lib == NULL) pusherror(L); + return lib; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)(voidf)GetProcAddress((HMODULE)lib, sym); + if (f == NULL) pusherror(L); + return f; +} + +/* }====================================================== */ + + +#else /* }{ */ +/* +** {====================================================== +** Fallback for other systems +** ======================================================= +*/ + +#undef LIB_FAIL +#define LIB_FAIL "absent" + + +#define DLMSG "dynamic libraries not enabled; check your Lua installation" + + +static void lsys_unloadlib (void *lib) { + (void)(lib); /* not used */ +} + + +static void *lsys_load (lua_State *L, const char *path, int seeglb) { + (void)(path); (void)(seeglb); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + + +static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { + (void)(lib); (void)(sym); /* not used */ + lua_pushliteral(L, DLMSG); + return NULL; +} + +/* }====================================================== */ +#endif /* } */ + + +/* +** {================================================================== +** Set Paths +** =================================================================== +*/ + +/* +** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment +** variables that Lua check to set its paths. +*/ +#if !defined(LUA_PATH_VAR) +#define LUA_PATH_VAR "LUA_PATH" +#endif + +#if !defined(LUA_CPATH_VAR) +#define LUA_CPATH_VAR "LUA_CPATH" +#endif + + + +/* +** return registry.LUA_NOENV as a boolean +*/ +static int noenv (lua_State *L) { + int b; + lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); + b = lua_toboolean(L, -1); + lua_pop(L, 1); /* remove value */ + return b; +} + + +/* +** Set a path +*/ +static void setpath (lua_State *L, const char *fieldname, + const char *envname, + const char *dft) { + const char *dftmark; + const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); + const char *path = getenv(nver); /* try versioned name */ + if (path == NULL) /* no versioned environment variable? */ + path = getenv(envname); /* try unversioned name */ + if (path == NULL || noenv(L)) /* no environment variable? */ + lua_pushstring(L, dft); /* use default */ + else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL) + lua_pushstring(L, path); /* nothing to change */ + else { /* path contains a ";;": insert default path in its place */ + size_t len = strlen(path); + luaL_Buffer b; + luaL_buffinit(L, &b); + if (path < dftmark) { /* is there a prefix before ';;'? */ + luaL_addlstring(&b, path, dftmark - path); /* add it */ + luaL_addchar(&b, *LUA_PATH_SEP); + } + luaL_addstring(&b, dft); /* add default */ + if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */ + luaL_addchar(&b, *LUA_PATH_SEP); + luaL_addlstring(&b, dftmark + 2, (path + len - 2) - dftmark); + } + luaL_pushresult(&b); + } + setprogdir(L); + lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ + lua_pop(L, 1); /* pop versioned variable name ('nver') */ +} + +/* }================================================================== */ + + +/* +** return registry.CLIBS[path] +*/ +static void *checkclib (lua_State *L, const char *path) { + void *plib; + lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_getfield(L, -1, path); + plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ + lua_pop(L, 2); /* pop CLIBS table and 'plib' */ + return plib; +} + + +/* +** registry.CLIBS[path] = plib -- for queries +** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries +*/ +static void addtoclib (lua_State *L, const char *path, void *plib) { + lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_pushlightuserdata(L, plib); + lua_pushvalue(L, -1); + lua_setfield(L, -3, path); /* CLIBS[path] = plib */ + lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ + lua_pop(L, 1); /* pop CLIBS table */ +} + + +/* +** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib +** handles in list CLIBS +*/ +static int gctm (lua_State *L) { + lua_Integer n = luaL_len(L, 1); + for (; n >= 1; n--) { /* for each handle, in reverse order */ + lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ + lsys_unloadlib(lua_touserdata(L, -1)); + lua_pop(L, 1); /* pop handle */ + } + return 0; +} + + + +/* error codes for 'lookforfunc' */ +#define ERRLIB 1 +#define ERRFUNC 2 + +/* +** Look for a C function named 'sym' in a dynamically loaded library +** 'path'. +** First, check whether the library is already loaded; if not, try +** to load it. +** Then, if 'sym' is '*', return true (as library has been loaded). +** Otherwise, look for symbol 'sym' in the library and push a +** C function with that symbol. +** Return 0 and 'true' or a function in the stack; in case of +** errors, return an error code and an error message in the stack. +*/ +static int lookforfunc (lua_State *L, const char *path, const char *sym) { + void *reg = checkclib(L, path); /* check loaded C libraries */ + if (reg == NULL) { /* must load library? */ + reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ + if (reg == NULL) return ERRLIB; /* unable to load library */ + addtoclib(L, path, reg); + } + if (*sym == '*') { /* loading only library (no function)? */ + lua_pushboolean(L, 1); /* return 'true' */ + return 0; /* no errors */ + } + else { + lua_CFunction f = lsys_sym(L, reg, sym); + if (f == NULL) + return ERRFUNC; /* unable to find function */ + lua_pushcfunction(L, f); /* else create new function */ + return 0; /* no errors */ + } +} + + +static int ll_loadlib (lua_State *L) { + const char *path = luaL_checkstring(L, 1); + const char *init = luaL_checkstring(L, 2); + int stat = lookforfunc(L, path, init); + if (l_likely(stat == 0)) /* no errors? */ + return 1; /* return the loaded function */ + else { /* error; error message is on stack top */ + luaL_pushfail(L); + lua_insert(L, -2); + lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); + return 3; /* return fail, error message, and where */ + } +} + + + +/* +** {====================================================== +** 'require' function +** ======================================================= +*/ + + +static int readable (const char *filename) { + FILE *f = fopen(filename, "r"); /* try to open file */ + if (f == NULL) return 0; /* open failed */ + fclose(f); + return 1; +} + + +/* +** Get the next name in '*path' = 'name1;name2;name3;...', changing +** the ending ';' to '\0' to create a zero-terminated string. Return +** NULL when list ends. +*/ +static const char *getnextfilename (char **path, char *end) { + char *sep; + char *name = *path; + if (name == end) + return NULL; /* no more names */ + else if (*name == '\0') { /* from previous iteration? */ + *name = *LUA_PATH_SEP; /* restore separator */ + name++; /* skip it */ + } + sep = strchr(name, *LUA_PATH_SEP); /* find next separator */ + if (sep == NULL) /* separator not found? */ + sep = end; /* name goes until the end */ + *sep = '\0'; /* finish file name */ + *path = sep; /* will start next search from here */ + return name; +} + + +/* +** Given a path such as ";blabla.so;blublu.so", pushes the string +** +** no file 'blabla.so' +** no file 'blublu.so' +*/ +static void pusherrornotfound (lua_State *L, const char *path) { + luaL_Buffer b; + luaL_buffinit(L, &b); + luaL_addstring(&b, "no file '"); + luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '"); + luaL_addstring(&b, "'"); + luaL_pushresult(&b); +} + + +static const char *searchpath (lua_State *L, const char *name, + const char *path, + const char *sep, + const char *dirsep) { + luaL_Buffer buff; + char *pathname; /* path with name inserted */ + char *endpathname; /* its end */ + const char *filename; + /* separator is non-empty and appears in 'name'? */ + if (*sep != '\0' && strchr(name, *sep) != NULL) + name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ + luaL_buffinit(L, &buff); + /* add path to the buffer, replacing marks ('?') with the file name */ + luaL_addgsub(&buff, path, LUA_PATH_MARK, name); + luaL_addchar(&buff, '\0'); + pathname = luaL_buffaddr(&buff); /* writable list of file names */ + endpathname = pathname + luaL_bufflen(&buff) - 1; + while ((filename = getnextfilename(&pathname, endpathname)) != NULL) { + if (readable(filename)) /* does file exist and is readable? */ + return lua_pushstring(L, filename); /* save and return name */ + } + luaL_pushresult(&buff); /* push path to create error message */ + pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */ + return NULL; /* not found */ +} + + +static int ll_searchpath (lua_State *L) { + const char *f = searchpath(L, luaL_checkstring(L, 1), + luaL_checkstring(L, 2), + luaL_optstring(L, 3, "."), + luaL_optstring(L, 4, LUA_DIRSEP)); + if (f != NULL) return 1; + else { /* error message is on top of the stack */ + luaL_pushfail(L); + lua_insert(L, -2); + return 2; /* return fail + error message */ + } +} + + +static const char *findfile (lua_State *L, const char *name, + const char *pname, + const char *dirsep) { + const char *path; + lua_getfield(L, lua_upvalueindex(1), pname); + path = lua_tostring(L, -1); + if (l_unlikely(path == NULL)) + luaL_error(L, "'package.%s' must be a string", pname); + return searchpath(L, name, path, ".", dirsep); +} + + +static int checkload (lua_State *L, int stat, const char *filename) { + if (l_likely(stat)) { /* module loaded successfully? */ + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; /* return open function and file name */ + } + else + return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", + lua_tostring(L, 1), filename, lua_tostring(L, -1)); +} + + +static int searcher_Lua (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + filename = findfile(L, name, "path", LUA_LSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); +} + + +/* +** Try to find a load function for module 'modname' at file 'filename'. +** First, change '.' to '_' in 'modname'; then, if 'modname' has +** the form X-Y (that is, it has an "ignore mark"), build a function +** name "luaopen_X" and look for it. (For compatibility, if that +** fails, it also tries "luaopen_Y".) If there is no ignore mark, +** look for a function named "luaopen_modname". +*/ +static int loadfunc (lua_State *L, const char *filename, const char *modname) { + const char *openfunc; + const char *mark; + modname = luaL_gsub(L, modname, ".", LUA_OFSEP); + mark = strchr(modname, *LUA_IGMARK); + if (mark) { + int stat; + openfunc = lua_pushlstring(L, modname, mark - modname); + openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); + stat = lookforfunc(L, filename, openfunc); + if (stat != ERRFUNC) return stat; + modname = mark + 1; /* else go ahead and try old-style name */ + } + openfunc = lua_pushfstring(L, LUA_POF"%s", modname); + return lookforfunc(L, filename, openfunc); +} + + +static int searcher_C (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* module not found in this path */ + return checkload(L, (loadfunc(L, filename, name) == 0), filename); +} + + +static int searcher_Croot (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + const char *p = strchr(name, '.'); + int stat; + if (p == NULL) return 0; /* is root */ + lua_pushlstring(L, name, p - name); + filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); + if (filename == NULL) return 1; /* root not found */ + if ((stat = loadfunc(L, filename, name)) != 0) { + if (stat != ERRFUNC) + return checkload(L, 0, filename); /* real error */ + else { /* open function not found */ + lua_pushfstring(L, "no module '%s' in file '%s'", name, filename); + return 1; + } + } + lua_pushstring(L, filename); /* will be 2nd argument to module */ + return 2; +} + + +static int searcher_preload (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); + if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */ + lua_pushfstring(L, "no field package.preload['%s']", name); + return 1; + } + else { + lua_pushliteral(L, ":preload:"); + return 2; + } +} + + +static void findloader (lua_State *L, const char *name) { + int i; + luaL_Buffer msg; /* to build error message */ + /* push 'package.searchers' to index 3 in the stack */ + if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers") + != LUA_TTABLE)) + luaL_error(L, "'package.searchers' must be a table"); + luaL_buffinit(L, &msg); + /* iterate over available searchers to find a loader */ + for (i = 1; ; i++) { + luaL_addstring(&msg, "\n\t"); /* error-message prefix */ + if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */ + lua_pop(L, 1); /* remove nil */ + luaL_buffsub(&msg, 2); /* remove prefix */ + luaL_pushresult(&msg); /* create error message */ + luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); + } + lua_pushstring(L, name); + lua_call(L, 1, 2); /* call it */ + if (lua_isfunction(L, -2)) /* did it find a loader? */ + return; /* module loader found */ + else if (lua_isstring(L, -2)) { /* searcher returned error message? */ + lua_pop(L, 1); /* remove extra return */ + luaL_addvalue(&msg); /* concatenate error message */ + } + else { /* no error message */ + lua_pop(L, 2); /* remove both returns */ + luaL_buffsub(&msg, 2); /* remove prefix */ + } + } +} + + +static int ll_require (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_settop(L, 1); /* LOADED table will be at index 2 */ + lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_getfield(L, 2, name); /* LOADED[name] */ + if (lua_toboolean(L, -1)) /* is it there? */ + return 1; /* package is already loaded */ + /* else must load package */ + lua_pop(L, 1); /* remove 'getfield' result */ + findloader(L, name); + lua_rotate(L, -2, 1); /* function <-> loader data */ + lua_pushvalue(L, 1); /* name is 1st argument to module loader */ + lua_pushvalue(L, -3); /* loader data is 2nd argument */ + /* stack: ...; loader data; loader function; mod. name; loader data */ + lua_call(L, 2, 1); /* run loader to load module */ + /* stack: ...; loader data; result from loader */ + if (!lua_isnil(L, -1)) /* non-nil return? */ + lua_setfield(L, 2, name); /* LOADED[name] = returned value */ + else + lua_pop(L, 1); /* pop nil */ + if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ + lua_pushboolean(L, 1); /* use true as result */ + lua_copy(L, -1, -2); /* replace loader result */ + lua_setfield(L, 2, name); /* LOADED[name] = true */ + } + lua_rotate(L, -2, 1); /* loader data <-> module result */ + return 2; /* return module result and loader data */ +} + +/* }====================================================== */ + + + + +static const luaL_Reg pk_funcs[] = { + {"loadlib", ll_loadlib}, + {"searchpath", ll_searchpath}, + /* placeholders */ + {"preload", NULL}, + {"cpath", NULL}, + {"path", NULL}, + {"searchers", NULL}, + {"loaded", NULL}, + {NULL, NULL} +}; + + +static const luaL_Reg ll_funcs[] = { + {"require", ll_require}, + {NULL, NULL} +}; + + +static void createsearcherstable (lua_State *L) { + static const lua_CFunction searchers[] = { + searcher_preload, + searcher_Lua, + searcher_C, + searcher_Croot, + NULL + }; + int i; + /* create 'searchers' table */ + lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); + /* fill it with predefined searchers */ + for (i=0; searchers[i] != NULL; i++) { + lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ + lua_pushcclosure(L, searchers[i], 1); + lua_rawseti(L, -2, i+1); + } + lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ +} + + +/* +** create table CLIBS to keep track of loaded C libraries, +** setting a finalizer to close all libraries when closing state. +*/ +static void createclibstable (lua_State *L) { + luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ + lua_createtable(L, 0, 1); /* create metatable for CLIBS */ + lua_pushcfunction(L, gctm); + lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ + lua_setmetatable(L, -2); +} + + +LUAMOD_API int luaopen_package (lua_State *L) { + createclibstable(L); + luaL_newlib(L, pk_funcs); /* create 'package' table */ + createsearcherstable(L); + /* set paths */ + setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); + setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); + /* store config information */ + lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" + LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); + lua_setfield(L, -2, "config"); + /* set field 'loaded' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); + lua_setfield(L, -2, "loaded"); + /* set field 'preload' */ + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); + lua_setfield(L, -2, "preload"); + lua_pushglobaltable(L); + lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ + luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ + lua_pop(L, 1); /* pop global table */ + return 1; /* return 'package' table */ +} + diff --git a/src/libs/3rdparty/lua/src/lobject.c b/src/libs/3rdparty/lua/src/lobject.c new file mode 100644 index 00000000000..f73ffc6d92b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lobject.c @@ -0,0 +1,602 @@ +/* +** $Id: lobject.c $ +** Some generic functions over Lua objects +** See Copyright Notice in lua.h +*/ + +#define lobject_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lctype.h" +#include "ldebug.h" +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "lvm.h" + + +/* +** Computes ceil(log2(x)) +*/ +int luaO_ceillog2 (unsigned int x) { + static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 + }; + int l = 0; + x--; + while (x >= 256) { l += 8; x >>= 8; } + return l + log_2[x]; +} + + +static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, + lua_Integer v2) { + switch (op) { + case LUA_OPADD: return intop(+, v1, v2); + case LUA_OPSUB:return intop(-, v1, v2); + case LUA_OPMUL:return intop(*, v1, v2); + case LUA_OPMOD: return luaV_mod(L, v1, v2); + case LUA_OPIDIV: return luaV_idiv(L, v1, v2); + case LUA_OPBAND: return intop(&, v1, v2); + case LUA_OPBOR: return intop(|, v1, v2); + case LUA_OPBXOR: return intop(^, v1, v2); + case LUA_OPSHL: return luaV_shiftl(v1, v2); + case LUA_OPSHR: return luaV_shiftr(v1, v2); + case LUA_OPUNM: return intop(-, 0, v1); + case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1); + default: lua_assert(0); return 0; + } +} + + +static lua_Number numarith (lua_State *L, int op, lua_Number v1, + lua_Number v2) { + switch (op) { + case LUA_OPADD: return luai_numadd(L, v1, v2); + case LUA_OPSUB: return luai_numsub(L, v1, v2); + case LUA_OPMUL: return luai_nummul(L, v1, v2); + case LUA_OPDIV: return luai_numdiv(L, v1, v2); + case LUA_OPPOW: return luai_numpow(L, v1, v2); + case LUA_OPIDIV: return luai_numidiv(L, v1, v2); + case LUA_OPUNM: return luai_numunm(L, v1); + case LUA_OPMOD: return luaV_modf(L, v1, v2); + default: lua_assert(0); return 0; + } +} + + +int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, + TValue *res) { + switch (op) { + case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: + case LUA_OPSHL: case LUA_OPSHR: + case LUA_OPBNOT: { /* operate only on integers */ + lua_Integer i1; lua_Integer i2; + if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) { + setivalue(res, intarith(L, op, i1, i2)); + return 1; + } + else return 0; /* fail */ + } + case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */ + lua_Number n1; lua_Number n2; + if (tonumberns(p1, n1) && tonumberns(p2, n2)) { + setfltvalue(res, numarith(L, op, n1, n2)); + return 1; + } + else return 0; /* fail */ + } + default: { /* other operations */ + lua_Number n1; lua_Number n2; + if (ttisinteger(p1) && ttisinteger(p2)) { + setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2))); + return 1; + } + else if (tonumberns(p1, n1) && tonumberns(p2, n2)) { + setfltvalue(res, numarith(L, op, n1, n2)); + return 1; + } + else return 0; /* fail */ + } + } +} + + +void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, + StkId res) { + if (!luaO_rawarith(L, op, p1, p2, s2v(res))) { + /* could not perform raw operation; try metamethod */ + luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD)); + } +} + + +int luaO_hexavalue (int c) { + if (lisdigit(c)) return c - '0'; + else return (ltolower(c) - 'a') + 10; +} + + +static int isneg (const char **s) { + if (**s == '-') { (*s)++; return 1; } + else if (**s == '+') (*s)++; + return 0; +} + + + +/* +** {================================================================== +** Lua's implementation for 'lua_strx2number' +** =================================================================== +*/ + +#if !defined(lua_strx2number) + +/* maximum number of significant digits to read (to avoid overflows + even with single floats) */ +#define MAXSIGDIG 30 + +/* +** convert a hexadecimal numeric string to a number, following +** C99 specification for 'strtod' +*/ +static lua_Number lua_strx2number (const char *s, char **endptr) { + int dot = lua_getlocaledecpoint(); + lua_Number r = l_mathop(0.0); /* result (accumulator) */ + int sigdig = 0; /* number of significant digits */ + int nosigdig = 0; /* number of non-significant digits */ + int e = 0; /* exponent correction */ + int neg; /* 1 if number is negative */ + int hasdot = 0; /* true after seen a dot */ + *endptr = cast_charp(s); /* nothing is valid yet */ + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); /* check sign */ + if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ + return l_mathop(0.0); /* invalid format (no '0x') */ + for (s += 2; ; s++) { /* skip '0x' and read numeral */ + if (*s == dot) { + if (hasdot) break; /* second dot? stop loop */ + else hasdot = 1; + } + else if (lisxdigit(cast_uchar(*s))) { + if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ + nosigdig++; + else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ + r = (r * l_mathop(16.0)) + luaO_hexavalue(*s); + else e++; /* too many digits; ignore, but still count for exponent */ + if (hasdot) e--; /* decimal digit? correct exponent */ + } + else break; /* neither a dot nor a digit */ + } + if (nosigdig + sigdig == 0) /* no digits? */ + return l_mathop(0.0); /* invalid format */ + *endptr = cast_charp(s); /* valid up to here */ + e *= 4; /* each digit multiplies/divides value by 2^4 */ + if (*s == 'p' || *s == 'P') { /* exponent part? */ + int exp1 = 0; /* exponent value */ + int neg1; /* exponent sign */ + s++; /* skip 'p' */ + neg1 = isneg(&s); /* sign */ + if (!lisdigit(cast_uchar(*s))) + return l_mathop(0.0); /* invalid; must have at least one digit */ + while (lisdigit(cast_uchar(*s))) /* read exponent */ + exp1 = exp1 * 10 + *(s++) - '0'; + if (neg1) exp1 = -exp1; + e += exp1; + *endptr = cast_charp(s); /* valid up to here */ + } + if (neg) r = -r; + return l_mathop(ldexp)(r, e); +} + +#endif +/* }====================================================== */ + + +/* maximum length of a numeral to be converted to a number */ +#if !defined (L_MAXLENNUM) +#define L_MAXLENNUM 200 +#endif + +/* +** Convert string 's' to a Lua number (put in 'result'). Return NULL on +** fail or the address of the ending '\0' on success. ('mode' == 'x') +** means a hexadecimal numeral. +*/ +static const char *l_str2dloc (const char *s, lua_Number *result, int mode) { + char *endptr; + *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */ + : lua_str2number(s, &endptr); + if (endptr == s) return NULL; /* nothing recognized? */ + while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */ + return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */ +} + + +/* +** Convert string 's' to a Lua number (put in 'result') handling the +** current locale. +** This function accepts both the current locale or a dot as the radix +** mark. If the conversion fails, it may mean number has a dot but +** locale accepts something else. In that case, the code copies 's' +** to a buffer (because 's' is read-only), changes the dot to the +** current locale radix mark, and tries to convert again. +** The variable 'mode' checks for special characters in the string: +** - 'n' means 'inf' or 'nan' (which should be rejected) +** - 'x' means a hexadecimal numeral +** - '.' just optimizes the search for the common case (no special chars) +*/ +static const char *l_str2d (const char *s, lua_Number *result) { + const char *endptr; + const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */ + int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0; + if (mode == 'n') /* reject 'inf' and 'nan' */ + return NULL; + endptr = l_str2dloc(s, result, mode); /* try to convert */ + if (endptr == NULL) { /* failed? may be a different locale */ + char buff[L_MAXLENNUM + 1]; + const char *pdot = strchr(s, '.'); + if (pdot == NULL || strlen(s) > L_MAXLENNUM) + return NULL; /* string too long or no dot; fail */ + strcpy(buff, s); /* copy string to buffer */ + buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */ + endptr = l_str2dloc(buff, result, mode); /* try again */ + if (endptr != NULL) + endptr = s + (endptr - buff); /* make relative to 's' */ + } + return endptr; +} + + +#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10) +#define MAXLASTD cast_int(LUA_MAXINTEGER % 10) + +static const char *l_str2int (const char *s, lua_Integer *result) { + lua_Unsigned a = 0; + int empty = 1; + int neg; + while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ + neg = isneg(&s); + if (s[0] == '0' && + (s[1] == 'x' || s[1] == 'X')) { /* hex? */ + s += 2; /* skip '0x' */ + for (; lisxdigit(cast_uchar(*s)); s++) { + a = a * 16 + luaO_hexavalue(*s); + empty = 0; + } + } + else { /* decimal */ + for (; lisdigit(cast_uchar(*s)); s++) { + int d = *s - '0'; + if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */ + return NULL; /* do not accept it (as integer) */ + a = a * 10 + d; + empty = 0; + } + } + while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */ + if (empty || *s != '\0') return NULL; /* something wrong in the numeral */ + else { + *result = l_castU2S((neg) ? 0u - a : a); + return s; + } +} + + +size_t luaO_str2num (const char *s, TValue *o) { + lua_Integer i; lua_Number n; + const char *e; + if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */ + setivalue(o, i); + } + else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */ + setfltvalue(o, n); + } + else + return 0; /* conversion failed */ + return (e - s) + 1; /* success; return string size */ +} + + +int luaO_utf8esc (char *buff, unsigned long x) { + int n = 1; /* number of bytes put in buffer (backwards) */ + lua_assert(x <= 0x7FFFFFFFu); + if (x < 0x80) /* ascii? */ + buff[UTF8BUFFSZ - 1] = cast_char(x); + else { /* need continuation bytes */ + unsigned int mfb = 0x3f; /* maximum that fits in first byte */ + do { /* add continuation bytes */ + buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f)); + x >>= 6; /* remove added bits */ + mfb >>= 1; /* now there is one less bit available in first byte */ + } while (x > mfb); /* still needs continuation byte? */ + buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */ + } + return n; +} + + +/* +** Maximum length of the conversion of a number to a string. Must be +** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT. +** (For a long long int, this is 19 digits plus a sign and a final '\0', +** adding to 21. For a long double, it can go to a sign, 33 digits, +** the dot, an exponent letter, an exponent sign, 5 exponent digits, +** and a final '\0', adding to 43.) +*/ +#define MAXNUMBER2STR 44 + + +/* +** Convert a number object to a string, adding it to a buffer +*/ +static int tostringbuff (TValue *obj, char *buff) { + int len; + lua_assert(ttisnumber(obj)); + if (ttisinteger(obj)) + len = lua_integer2str(buff, MAXNUMBER2STR, ivalue(obj)); + else { + len = lua_number2str(buff, MAXNUMBER2STR, fltvalue(obj)); + if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */ + buff[len++] = lua_getlocaledecpoint(); + buff[len++] = '0'; /* adds '.0' to result */ + } + } + return len; +} + + +/* +** Convert a number object to a Lua string, replacing the value at 'obj' +*/ +void luaO_tostring (lua_State *L, TValue *obj) { + char buff[MAXNUMBER2STR]; + int len = tostringbuff(obj, buff); + setsvalue(L, obj, luaS_newlstr(L, buff, len)); +} + + + + +/* +** {================================================================== +** 'luaO_pushvfstring' +** =================================================================== +*/ + +/* +** Size for buffer space used by 'luaO_pushvfstring'. It should be +** (LUA_IDSIZE + MAXNUMBER2STR) + a minimal space for basic messages, +** so that 'luaG_addinfo' can work directly on the buffer. +*/ +#define BUFVFS (LUA_IDSIZE + MAXNUMBER2STR + 95) + +/* buffer used by 'luaO_pushvfstring' */ +typedef struct BuffFS { + lua_State *L; + int pushed; /* true if there is a part of the result on the stack */ + int blen; /* length of partial string in 'space' */ + char space[BUFVFS]; /* holds last part of the result */ +} BuffFS; + + +/* +** Push given string to the stack, as part of the result, and +** join it to previous partial result if there is one. +** It may call 'luaV_concat' while using one slot from EXTRA_STACK. +** This call cannot invoke metamethods, as both operands must be +** strings. It can, however, raise an error if the result is too +** long. In that case, 'luaV_concat' frees the extra slot before +** raising the error. +*/ +static void pushstr (BuffFS *buff, const char *str, size_t lstr) { + lua_State *L = buff->L; + setsvalue2s(L, L->top.p, luaS_newlstr(L, str, lstr)); + L->top.p++; /* may use one slot from EXTRA_STACK */ + if (!buff->pushed) /* no previous string on the stack? */ + buff->pushed = 1; /* now there is one */ + else /* join previous string with new one */ + luaV_concat(L, 2); +} + + +/* +** empty the buffer space into the stack +*/ +static void clearbuff (BuffFS *buff) { + pushstr(buff, buff->space, buff->blen); /* push buffer contents */ + buff->blen = 0; /* space now is empty */ +} + + +/* +** Get a space of size 'sz' in the buffer. If buffer has not enough +** space, empty it. 'sz' must fit in an empty buffer. +*/ +static char *getbuff (BuffFS *buff, int sz) { + lua_assert(buff->blen <= BUFVFS); lua_assert(sz <= BUFVFS); + if (sz > BUFVFS - buff->blen) /* not enough space? */ + clearbuff(buff); + return buff->space + buff->blen; +} + + +#define addsize(b,sz) ((b)->blen += (sz)) + + +/* +** Add 'str' to the buffer. If string is larger than the buffer space, +** push the string directly to the stack. +*/ +static void addstr2buff (BuffFS *buff, const char *str, size_t slen) { + if (slen <= BUFVFS) { /* does string fit into buffer? */ + char *bf = getbuff(buff, cast_int(slen)); + memcpy(bf, str, slen); /* add string to buffer */ + addsize(buff, cast_int(slen)); + } + else { /* string larger than buffer */ + clearbuff(buff); /* string comes after buffer's content */ + pushstr(buff, str, slen); /* push string */ + } +} + + +/* +** Add a numeral to the buffer. +*/ +static void addnum2buff (BuffFS *buff, TValue *num) { + char *numbuff = getbuff(buff, MAXNUMBER2STR); + int len = tostringbuff(num, numbuff); /* format number into 'numbuff' */ + addsize(buff, len); +} + + +/* +** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%' + conventional formats, plus Lua-specific '%I' and '%U' +*/ +const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { + BuffFS buff; /* holds last part of the result */ + const char *e; /* points to next '%' */ + buff.pushed = buff.blen = 0; + buff.L = L; + while ((e = strchr(fmt, '%')) != NULL) { + addstr2buff(&buff, fmt, e - fmt); /* add 'fmt' up to '%' */ + switch (*(e + 1)) { /* conversion specifier */ + case 's': { /* zero-terminated string */ + const char *s = va_arg(argp, char *); + if (s == NULL) s = "(null)"; + addstr2buff(&buff, s, strlen(s)); + break; + } + case 'c': { /* an 'int' as a character */ + char c = cast_uchar(va_arg(argp, int)); + addstr2buff(&buff, &c, sizeof(char)); + break; + } + case 'd': { /* an 'int' */ + TValue num; + setivalue(&num, va_arg(argp, int)); + addnum2buff(&buff, &num); + break; + } + case 'I': { /* a 'lua_Integer' */ + TValue num; + setivalue(&num, cast(lua_Integer, va_arg(argp, l_uacInt))); + addnum2buff(&buff, &num); + break; + } + case 'f': { /* a 'lua_Number' */ + TValue num; + setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber))); + addnum2buff(&buff, &num); + break; + } + case 'p': { /* a pointer */ + const int sz = 3 * sizeof(void*) + 8; /* enough space for '%p' */ + char *bf = getbuff(&buff, sz); + void *p = va_arg(argp, void *); + int len = lua_pointer2str(bf, sz, p); + addsize(&buff, len); + break; + } + case 'U': { /* a 'long' as a UTF-8 sequence */ + char bf[UTF8BUFFSZ]; + int len = luaO_utf8esc(bf, va_arg(argp, long)); + addstr2buff(&buff, bf + UTF8BUFFSZ - len, len); + break; + } + case '%': { + addstr2buff(&buff, "%", 1); + break; + } + default: { + luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'", + *(e + 1)); + } + } + fmt = e + 2; /* skip '%' and the specifier */ + } + addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */ + clearbuff(&buff); /* empty buffer into the stack */ + lua_assert(buff.pushed == 1); + return svalue(s2v(L->top.p - 1)); +} + + +const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { + const char *msg; + va_list argp; + va_start(argp, fmt); + msg = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + return msg; +} + +/* }================================================================== */ + + +#define RETS "..." +#define PRE "[string \"" +#define POS "\"]" + +#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) + +void luaO_chunkid (char *out, const char *source, size_t srclen) { + size_t bufflen = LUA_IDSIZE; /* free space in buffer */ + if (*source == '=') { /* 'literal' source */ + if (srclen <= bufflen) /* small enough? */ + memcpy(out, source + 1, srclen * sizeof(char)); + else { /* truncate it */ + addstr(out, source + 1, bufflen - 1); + *out = '\0'; + } + } + else if (*source == '@') { /* file name */ + if (srclen <= bufflen) /* small enough? */ + memcpy(out, source + 1, srclen * sizeof(char)); + else { /* add '...' before rest of name */ + addstr(out, RETS, LL(RETS)); + bufflen -= LL(RETS); + memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char)); + } + } + else { /* string; format as [string "source"] */ + const char *nl = strchr(source, '\n'); /* find first new line (if any) */ + addstr(out, PRE, LL(PRE)); /* add prefix */ + bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ + if (srclen < bufflen && nl == NULL) { /* small one-line source? */ + addstr(out, source, srclen); /* keep it */ + } + else { + if (nl != NULL) srclen = nl - source; /* stop at first newline */ + if (srclen > bufflen) srclen = bufflen; + addstr(out, source, srclen); + addstr(out, RETS, LL(RETS)); + } + memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); + } +} + diff --git a/src/libs/3rdparty/lua/src/lobject.h b/src/libs/3rdparty/lua/src/lobject.h new file mode 100644 index 00000000000..556608e4aa2 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lobject.h @@ -0,0 +1,815 @@ +/* +** $Id: lobject.h $ +** Type definitions for Lua objects +** See Copyright Notice in lua.h +*/ + + +#ifndef lobject_h +#define lobject_h + + +#include + + +#include "llimits.h" +#include "lua.h" + + +/* +** Extra types for collectable non-values +*/ +#define LUA_TUPVAL LUA_NUMTYPES /* upvalues */ +#define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */ +#define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */ + + + +/* +** number of all possible types (including LUA_TNONE but excluding DEADKEY) +*/ +#define LUA_TOTALTYPES (LUA_TPROTO + 2) + + +/* +** tags for Tagged Values have the following use of bits: +** bits 0-3: actual tag (a LUA_T* constant) +** bits 4-5: variant bits +** bit 6: whether value is collectable +*/ + +/* add variant bits to a type */ +#define makevariant(t,v) ((t) | ((v) << 4)) + + + +/* +** Union of all Lua values +*/ +typedef union Value { + struct GCObject *gc; /* collectable objects */ + void *p; /* light userdata */ + lua_CFunction f; /* light C functions */ + lua_Integer i; /* integer numbers */ + lua_Number n; /* float numbers */ + /* not used, but may avoid warnings for uninitialized value */ + lu_byte ub; +} Value; + + +/* +** Tagged Values. This is the basic representation of values in Lua: +** an actual value plus a tag with its type. +*/ + +#define TValuefields Value value_; lu_byte tt_ + +typedef struct TValue { + TValuefields; +} TValue; + + +#define val_(o) ((o)->value_) +#define valraw(o) (val_(o)) + + +/* raw type tag of a TValue */ +#define rawtt(o) ((o)->tt_) + +/* tag with no variants (bits 0-3) */ +#define novariant(t) ((t) & 0x0F) + +/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ +#define withvariant(t) ((t) & 0x3F) +#define ttypetag(o) withvariant(rawtt(o)) + +/* type of a TValue */ +#define ttype(o) (novariant(rawtt(o))) + + +/* Macros to test type */ +#define checktag(o,t) (rawtt(o) == (t)) +#define checktype(o,t) (ttype(o) == (t)) + + +/* Macros for internal tests */ + +/* collectable object has the same tag as the original value */ +#define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt) + +/* +** Any value being manipulated by the program either is non +** collectable, or the collectable object has the right tag +** and it is not dead. The option 'L == NULL' allows other +** macros using this one to be used where L is not available. +*/ +#define checkliveness(L,obj) \ + ((void)L, lua_longassert(!iscollectable(obj) || \ + (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))) + + +/* Macros to set values */ + +/* set a value's tag */ +#define settt_(o,t) ((o)->tt_=(t)) + + +/* main macro to copy values (from 'obj2' to 'obj1') */ +#define setobj(L,obj1,obj2) \ + { TValue *io1=(obj1); const TValue *io2=(obj2); \ + io1->value_ = io2->value_; settt_(io1, io2->tt_); \ + checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); } + +/* +** Different types of assignments, according to source and destination. +** (They are mostly equal now, but may be different in the future.) +*/ + +/* from stack to stack */ +#define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2)) +/* to stack (not from same stack) */ +#define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2) +/* from table to same table */ +#define setobjt2t setobj +/* to new object */ +#define setobj2n setobj +/* to table */ +#define setobj2t setobj + + +/* +** Entries in a Lua stack. Field 'tbclist' forms a list of all +** to-be-closed variables active in this stack. Dummy entries are +** used when the distance between two tbc variables does not fit +** in an unsigned short. They are represented by delta==0, and +** their real delta is always the maximum value that fits in +** that field. +*/ +typedef union StackValue { + TValue val; + struct { + TValuefields; + unsigned short delta; + } tbclist; +} StackValue; + + +/* index to stack elements */ +typedef StackValue *StkId; + + +/* +** When reallocating the stack, change all pointers to the stack into +** proper offsets. +*/ +typedef union { + StkId p; /* actual pointer */ + ptrdiff_t offset; /* used while the stack is being reallocated */ +} StkIdRel; + + +/* convert a 'StackValue' to a 'TValue' */ +#define s2v(o) (&(o)->val) + + + +/* +** {================================================================== +** Nil +** =================================================================== +*/ + +/* Standard nil */ +#define LUA_VNIL makevariant(LUA_TNIL, 0) + +/* Empty slot (which might be different from a slot containing nil) */ +#define LUA_VEMPTY makevariant(LUA_TNIL, 1) + +/* Value returned for a key not found in a table (absent key) */ +#define LUA_VABSTKEY makevariant(LUA_TNIL, 2) + + +/* macro to test for (any kind of) nil */ +#define ttisnil(v) checktype((v), LUA_TNIL) + + +/* macro to test for a standard nil */ +#define ttisstrictnil(o) checktag((o), LUA_VNIL) + + +#define setnilvalue(obj) settt_(obj, LUA_VNIL) + + +#define isabstkey(v) checktag((v), LUA_VABSTKEY) + + +/* +** macro to detect non-standard nils (used only in assertions) +*/ +#define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v)) + + +/* +** By default, entries with any kind of nil are considered empty. +** (In any definition, values associated with absent keys must also +** be accepted as empty.) +*/ +#define isempty(v) ttisnil(v) + + +/* macro defining a value corresponding to an absent key */ +#define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY + + +/* mark an entry as empty */ +#define setempty(v) settt_(v, LUA_VEMPTY) + + + +/* }================================================================== */ + + +/* +** {================================================================== +** Booleans +** =================================================================== +*/ + + +#define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0) +#define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1) + +#define ttisboolean(o) checktype((o), LUA_TBOOLEAN) +#define ttisfalse(o) checktag((o), LUA_VFALSE) +#define ttistrue(o) checktag((o), LUA_VTRUE) + + +#define l_isfalse(o) (ttisfalse(o) || ttisnil(o)) + + +#define setbfvalue(obj) settt_(obj, LUA_VFALSE) +#define setbtvalue(obj) settt_(obj, LUA_VTRUE) + +/* }================================================================== */ + + +/* +** {================================================================== +** Threads +** =================================================================== +*/ + +#define LUA_VTHREAD makevariant(LUA_TTHREAD, 0) + +#define ttisthread(o) checktag((o), ctb(LUA_VTHREAD)) + +#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc)) + +#define setthvalue(L,obj,x) \ + { TValue *io = (obj); lua_State *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \ + checkliveness(L,io); } + +#define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t) + +/* }================================================================== */ + + +/* +** {================================================================== +** Collectable Objects +** =================================================================== +*/ + +/* +** Common Header for all collectable objects (in macro form, to be +** included in other objects) +*/ +#define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked + + +/* Common type for all collectable objects */ +typedef struct GCObject { + CommonHeader; +} GCObject; + + +/* Bit mark for collectable types */ +#define BIT_ISCOLLECTABLE (1 << 6) + +#define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE) + +/* mark a tag as collectable */ +#define ctb(t) ((t) | BIT_ISCOLLECTABLE) + +#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) + +#define gcvalueraw(v) ((v).gc) + +#define setgcovalue(L,obj,x) \ + { TValue *io = (obj); GCObject *i_g=(x); \ + val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); } + +/* }================================================================== */ + + +/* +** {================================================================== +** Numbers +** =================================================================== +*/ + +/* Variant tags for numbers */ +#define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */ +#define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */ + +#define ttisnumber(o) checktype((o), LUA_TNUMBER) +#define ttisfloat(o) checktag((o), LUA_VNUMFLT) +#define ttisinteger(o) checktag((o), LUA_VNUMINT) + +#define nvalue(o) check_exp(ttisnumber(o), \ + (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o))) +#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n) +#define ivalue(o) check_exp(ttisinteger(o), val_(o).i) + +#define fltvalueraw(v) ((v).n) +#define ivalueraw(v) ((v).i) + +#define setfltvalue(obj,x) \ + { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); } + +#define chgfltvalue(obj,x) \ + { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); } + +#define setivalue(obj,x) \ + { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); } + +#define chgivalue(obj,x) \ + { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); } + +/* }================================================================== */ + + +/* +** {================================================================== +** Strings +** =================================================================== +*/ + +/* Variant tags for strings */ +#define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */ +#define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */ + +#define ttisstring(o) checktype((o), LUA_TSTRING) +#define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR)) +#define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR)) + +#define tsvalueraw(v) (gco2ts((v).gc)) + +#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc)) + +#define setsvalue(L,obj,x) \ + { TValue *io = (obj); TString *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \ + checkliveness(L,io); } + +/* set a string to the stack */ +#define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s) + +/* set a string to a new object */ +#define setsvalue2n setsvalue + + +/* +** Header for a string value. +*/ +typedef struct TString { + CommonHeader; + lu_byte extra; /* reserved words for short strings; "has hash" for longs */ + lu_byte shrlen; /* length for short strings */ + unsigned int hash; + union { + size_t lnglen; /* length for long strings */ + struct TString *hnext; /* linked list for hash table */ + } u; + char contents[1]; +} TString; + + + +/* +** Get the actual string (array of bytes) from a 'TString'. +*/ +#define getstr(ts) ((ts)->contents) + + +/* get the actual string (array of bytes) from a Lua value */ +#define svalue(o) getstr(tsvalue(o)) + +/* get string length from 'TString *s' */ +#define tsslen(s) ((s)->tt == LUA_VSHRSTR ? (s)->shrlen : (s)->u.lnglen) + +/* get string length from 'TValue *o' */ +#define vslen(o) tsslen(tsvalue(o)) + +/* }================================================================== */ + + +/* +** {================================================================== +** Userdata +** =================================================================== +*/ + + +/* +** Light userdata should be a variant of userdata, but for compatibility +** reasons they are also different types. +*/ +#define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0) + +#define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0) + +#define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA) +#define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA)) + +#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) +#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc)) + +#define pvalueraw(v) ((v).p) + +#define setpvalue(obj,x) \ + { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); } + +#define setuvalue(L,obj,x) \ + { TValue *io = (obj); Udata *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \ + checkliveness(L,io); } + + +/* Ensures that addresses after this type are always fully aligned. */ +typedef union UValue { + TValue uv; + LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */ +} UValue; + + +/* +** Header for userdata with user values; +** memory area follows the end of this structure. +*/ +typedef struct Udata { + CommonHeader; + unsigned short nuvalue; /* number of user values */ + size_t len; /* number of bytes */ + struct Table *metatable; + GCObject *gclist; + UValue uv[1]; /* user values */ +} Udata; + + +/* +** Header for userdata with no user values. These userdata do not need +** to be gray during GC, and therefore do not need a 'gclist' field. +** To simplify, the code always use 'Udata' for both kinds of userdata, +** making sure it never accesses 'gclist' on userdata with no user values. +** This structure here is used only to compute the correct size for +** this representation. (The 'bindata' field in its end ensures correct +** alignment for binary data following this header.) +*/ +typedef struct Udata0 { + CommonHeader; + unsigned short nuvalue; /* number of user values */ + size_t len; /* number of bytes */ + struct Table *metatable; + union {LUAI_MAXALIGN;} bindata; +} Udata0; + + +/* compute the offset of the memory area of a userdata */ +#define udatamemoffset(nuv) \ + ((nuv) == 0 ? offsetof(Udata0, bindata) \ + : offsetof(Udata, uv) + (sizeof(UValue) * (nuv))) + +/* get the address of the memory block inside 'Udata' */ +#define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue)) + +/* compute the size of a userdata */ +#define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb)) + +/* }================================================================== */ + + +/* +** {================================================================== +** Prototypes +** =================================================================== +*/ + +#define LUA_VPROTO makevariant(LUA_TPROTO, 0) + + +/* +** Description of an upvalue for function prototypes +*/ +typedef struct Upvaldesc { + TString *name; /* upvalue name (for debug information) */ + lu_byte instack; /* whether it is in stack (register) */ + lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ + lu_byte kind; /* kind of corresponding variable */ +} Upvaldesc; + + +/* +** Description of a local variable for function prototypes +** (used for debug information) +*/ +typedef struct LocVar { + TString *varname; + int startpc; /* first point where variable is active */ + int endpc; /* first point where variable is dead */ +} LocVar; + + +/* +** Associates the absolute line source for a given instruction ('pc'). +** The array 'lineinfo' gives, for each instruction, the difference in +** lines from the previous instruction. When that difference does not +** fit into a byte, Lua saves the absolute line for that instruction. +** (Lua also saves the absolute line periodically, to speed up the +** computation of a line number: we can use binary search in the +** absolute-line array, but we must traverse the 'lineinfo' array +** linearly to compute a line.) +*/ +typedef struct AbsLineInfo { + int pc; + int line; +} AbsLineInfo; + +/* +** Function Prototypes +*/ +typedef struct Proto { + CommonHeader; + lu_byte numparams; /* number of fixed (named) parameters */ + lu_byte is_vararg; + lu_byte maxstacksize; /* number of registers needed by this function */ + int sizeupvalues; /* size of 'upvalues' */ + int sizek; /* size of 'k' */ + int sizecode; + int sizelineinfo; + int sizep; /* size of 'p' */ + int sizelocvars; + int sizeabslineinfo; /* size of 'abslineinfo' */ + int linedefined; /* debug information */ + int lastlinedefined; /* debug information */ + TValue *k; /* constants used by the function */ + Instruction *code; /* opcodes */ + struct Proto **p; /* functions defined inside the function */ + Upvaldesc *upvalues; /* upvalue information */ + ls_byte *lineinfo; /* information about source lines (debug information) */ + AbsLineInfo *abslineinfo; /* idem */ + LocVar *locvars; /* information about local variables (debug information) */ + TString *source; /* used for debug information */ + GCObject *gclist; +} Proto; + +/* }================================================================== */ + + +/* +** {================================================================== +** Functions +** =================================================================== +*/ + +#define LUA_VUPVAL makevariant(LUA_TUPVAL, 0) + + +/* Variant tags for functions */ +#define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */ +#define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */ +#define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */ + +#define ttisfunction(o) checktype(o, LUA_TFUNCTION) +#define ttisLclosure(o) checktag((o), ctb(LUA_VLCL)) +#define ttislcf(o) checktag((o), LUA_VLCF) +#define ttisCclosure(o) checktag((o), ctb(LUA_VCCL)) +#define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o)) + + +#define isLfunction(o) ttisLclosure(o) + +#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) +#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) +#define fvalue(o) check_exp(ttislcf(o), val_(o).f) +#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) + +#define fvalueraw(v) ((v).f) + +#define setclLvalue(L,obj,x) \ + { TValue *io = (obj); LClosure *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \ + checkliveness(L,io); } + +#define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl) + +#define setfvalue(obj,x) \ + { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); } + +#define setclCvalue(L,obj,x) \ + { TValue *io = (obj); CClosure *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \ + checkliveness(L,io); } + + +/* +** Upvalues for Lua closures +*/ +typedef struct UpVal { + CommonHeader; + union { + TValue *p; /* points to stack or to its own value */ + ptrdiff_t offset; /* used while the stack is being reallocated */ + } v; + union { + struct { /* (when open) */ + struct UpVal *next; /* linked list */ + struct UpVal **previous; + } open; + TValue value; /* the value (when closed) */ + } u; +} UpVal; + + + +#define ClosureHeader \ + CommonHeader; lu_byte nupvalues; GCObject *gclist + +typedef struct CClosure { + ClosureHeader; + lua_CFunction f; + TValue upvalue[1]; /* list of upvalues */ +} CClosure; + + +typedef struct LClosure { + ClosureHeader; + struct Proto *p; + UpVal *upvals[1]; /* list of upvalues */ +} LClosure; + + +typedef union Closure { + CClosure c; + LClosure l; +} Closure; + + +#define getproto(o) (clLvalue(o)->p) + +/* }================================================================== */ + + +/* +** {================================================================== +** Tables +** =================================================================== +*/ + +#define LUA_VTABLE makevariant(LUA_TTABLE, 0) + +#define ttistable(o) checktag((o), ctb(LUA_VTABLE)) + +#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc)) + +#define sethvalue(L,obj,x) \ + { TValue *io = (obj); Table *x_ = (x); \ + val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \ + checkliveness(L,io); } + +#define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h) + + +/* +** Nodes for Hash tables: A pack of two TValue's (key-value pairs) +** plus a 'next' field to link colliding entries. The distribution +** of the key's fields ('key_tt' and 'key_val') not forming a proper +** 'TValue' allows for a smaller size for 'Node' both in 4-byte +** and 8-byte alignments. +*/ +typedef union Node { + struct NodeKey { + TValuefields; /* fields for value */ + lu_byte key_tt; /* key type */ + int next; /* for chaining */ + Value key_val; /* key value */ + } u; + TValue i_val; /* direct access to node's value as a proper 'TValue' */ +} Node; + + +/* copy a value into a key */ +#define setnodekey(L,node,obj) \ + { Node *n_=(node); const TValue *io_=(obj); \ + n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; \ + checkliveness(L,io_); } + + +/* copy a value from a key */ +#define getnodekey(L,obj,node) \ + { TValue *io_=(obj); const Node *n_=(node); \ + io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \ + checkliveness(L,io_); } + + +/* +** About 'alimit': if 'isrealasize(t)' is true, then 'alimit' is the +** real size of 'array'. Otherwise, the real size of 'array' is the +** smallest power of two not smaller than 'alimit' (or zero iff 'alimit' +** is zero); 'alimit' is then used as a hint for #t. +*/ + +#define BITRAS (1 << 7) +#define isrealasize(t) (!((t)->flags & BITRAS)) +#define setrealasize(t) ((t)->flags &= cast_byte(~BITRAS)) +#define setnorealasize(t) ((t)->flags |= BITRAS) + + +typedef struct Table { + CommonHeader; + lu_byte flags; /* 1<

    u.key_tt) +#define keyval(node) ((node)->u.key_val) + +#define keyisnil(node) (keytt(node) == LUA_TNIL) +#define keyisinteger(node) (keytt(node) == LUA_VNUMINT) +#define keyival(node) (keyval(node).i) +#define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR)) +#define keystrval(node) (gco2ts(keyval(node).gc)) + +#define setnilkey(node) (keytt(node) = LUA_TNIL) + +#define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE) + +#define gckey(n) (keyval(n).gc) +#define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL) + + +/* +** Dead keys in tables have the tag DEADKEY but keep their original +** gcvalue. This distinguishes them from regular keys but allows them to +** be found when searched in a special way. ('next' needs that to find +** keys removed from a table during a traversal.) +*/ +#define setdeadkey(node) (keytt(node) = LUA_TDEADKEY) +#define keyisdead(node) (keytt(node) == LUA_TDEADKEY) + +/* }================================================================== */ + + + +/* +** 'module' operation for hashing (size is always a power of 2) +*/ +#define lmod(s,size) \ + (check_exp((size&(size-1))==0, (cast_int((s) & ((size)-1))))) + + +#define twoto(x) (1<<(x)) +#define sizenode(t) (twoto((t)->lsizenode)) + + +/* size of buffer for 'luaO_utf8esc' function */ +#define UTF8BUFFSZ 8 + +LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x); +LUAI_FUNC int luaO_ceillog2 (unsigned int x); +LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1, + const TValue *p2, TValue *res); +LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1, + const TValue *p2, StkId res); +LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o); +LUAI_FUNC int luaO_hexavalue (int c); +LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj); +LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, + va_list argp); +LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); +LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen); + + +#endif + diff --git a/src/libs/3rdparty/lua/src/lopcodes.c b/src/libs/3rdparty/lua/src/lopcodes.c new file mode 100644 index 00000000000..c67aa227c58 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lopcodes.c @@ -0,0 +1,104 @@ +/* +** $Id: lopcodes.c $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#define lopcodes_c +#define LUA_CORE + +#include "lprefix.h" + + +#include "lopcodes.h" + + +/* ORDER OP */ + +LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { +/* MM OT IT T A mode opcode */ + opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */ + ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */ + ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NEWTABLE */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */ + ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */ + ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI*/ + ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK*/ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */ + ,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */ + ,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */ + ,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */ + ,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */ + ,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */ + ,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */ + ,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */ + ,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */ + ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */ + ,opmode(0, 0, 1, 0, 0, iABC) /* OP_SETLIST */ + ,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */ + ,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */ + ,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */ + ,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */ +}; + diff --git a/src/libs/3rdparty/lua/src/lopcodes.h b/src/libs/3rdparty/lua/src/lopcodes.h new file mode 100644 index 00000000000..4c55145399f --- /dev/null +++ b/src/libs/3rdparty/lua/src/lopcodes.h @@ -0,0 +1,405 @@ +/* +** $Id: lopcodes.h $ +** Opcodes for Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lopcodes_h +#define lopcodes_h + +#include "llimits.h" + + +/*=========================================================================== + We assume that instructions are unsigned 32-bit integers. + All instructions have an opcode in the first 7 bits. + Instructions can have the following formats: + + 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 + 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +iABC C(8) | B(8) |k| A(8) | Op(7) | +iABx Bx(17) | A(8) | Op(7) | +iAsBx sBx (signed)(17) | A(8) | Op(7) | +iAx Ax(25) | Op(7) | +isJ sJ (signed)(25) | Op(7) | + + A signed argument is represented in excess K: the represented value is + the written unsigned value minus K, where K is half the maximum for the + corresponding unsigned argument. +===========================================================================*/ + + +enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */ + + +/* +** size and position of opcode arguments. +*/ +#define SIZE_C 8 +#define SIZE_B 8 +#define SIZE_Bx (SIZE_C + SIZE_B + 1) +#define SIZE_A 8 +#define SIZE_Ax (SIZE_Bx + SIZE_A) +#define SIZE_sJ (SIZE_Bx + SIZE_A) + +#define SIZE_OP 7 + +#define POS_OP 0 + +#define POS_A (POS_OP + SIZE_OP) +#define POS_k (POS_A + SIZE_A) +#define POS_B (POS_k + 1) +#define POS_C (POS_B + SIZE_B) + +#define POS_Bx POS_k + +#define POS_Ax POS_A + +#define POS_sJ POS_A + + +/* +** limits for opcode arguments. +** we use (signed) 'int' to manipulate most arguments, +** so they must fit in ints. +*/ + +/* Check whether type 'int' has at least 'b' bits ('b' < 32) */ +#define L_INTHASBITS(b) ((UINT_MAX >> ((b) - 1)) >= 1) + + +#if L_INTHASBITS(SIZE_Bx) +#define MAXARG_Bx ((1<>1) /* 'sBx' is signed */ + + +#if L_INTHASBITS(SIZE_Ax) +#define MAXARG_Ax ((1<> 1) + + +#define MAXARG_A ((1<> 1) + +#define int2sC(i) ((i) + OFFSET_sC) +#define sC2int(i) ((i) - OFFSET_sC) + + +/* creates a mask with 'n' 1 bits at position 'p' */ +#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p)) + +/* creates a mask with 'n' 0 bits at position 'p' */ +#define MASK0(n,p) (~MASK1(n,p)) + +/* +** the following macros help to manipulate instructions +*/ + +#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0))) +#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ + ((cast(Instruction, o)<>(pos)) & MASK1(size,0))) +#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \ + ((cast(Instruction, v)<> sC */ +OP_SHLI,/* A B sC R[A] := sC << R[B] */ + +OP_ADD,/* A B C R[A] := R[B] + R[C] */ +OP_SUB,/* A B C R[A] := R[B] - R[C] */ +OP_MUL,/* A B C R[A] := R[B] * R[C] */ +OP_MOD,/* A B C R[A] := R[B] % R[C] */ +OP_POW,/* A B C R[A] := R[B] ^ R[C] */ +OP_DIV,/* A B C R[A] := R[B] / R[C] */ +OP_IDIV,/* A B C R[A] := R[B] // R[C] */ + +OP_BAND,/* A B C R[A] := R[B] & R[C] */ +OP_BOR,/* A B C R[A] := R[B] | R[C] */ +OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */ +OP_SHL,/* A B C R[A] := R[B] << R[C] */ +OP_SHR,/* A B C R[A] := R[B] >> R[C] */ + +OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] (*) */ +OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */ +OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */ + +OP_UNM,/* A B R[A] := -R[B] */ +OP_BNOT,/* A B R[A] := ~R[B] */ +OP_NOT,/* A B R[A] := not R[B] */ +OP_LEN,/* A B R[A] := #R[B] (length operator) */ + +OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */ + +OP_CLOSE,/* A close all upvalues >= R[A] */ +OP_TBC,/* A mark variable A "to be closed" */ +OP_JMP,/* sJ pc += sJ */ +OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */ +OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */ +OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */ + +OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */ +OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */ +OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */ +OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */ +OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */ +OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */ + +OP_TEST,/* A k if (not R[A] == k) then pc++ */ +OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] (*) */ + +OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */ +OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */ + +OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] (see note) */ +OP_RETURN0,/* return */ +OP_RETURN1,/* A return R[A] */ + +OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */ +OP_FORPREP,/* A Bx ; + if not to run then pc+=Bx+1; */ + +OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */ +OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */ +OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */ + +OP_SETLIST,/* A B C k R[A][C+i] := R[A+i], 1 <= i <= B */ + +OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */ + +OP_VARARG,/* A C R[A], R[A+1], ..., R[A+C-2] = vararg */ + +OP_VARARGPREP,/*A (adjust vararg parameters) */ + +OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ +} OpCode; + + +#define NUM_OPCODES ((int)(OP_EXTRAARG) + 1) + + + +/*=========================================================================== + Notes: + + (*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean + value, in a code equivalent to (not cond ? false : true). (It + produces false and skips the next instruction producing true.) + + (*) Opcodes OP_MMBIN and variants follow each arithmetic and + bitwise opcode. If the operation succeeds, it skips this next + opcode. Otherwise, this opcode calls the corresponding metamethod. + + (*) Opcode OP_TESTSET is used in short-circuit expressions that need + both to jump and to produce a value, such as (a = b or c). + + (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then + 'top' is set to last_result+1, so next open instruction (OP_CALL, + OP_RETURN*, OP_SETLIST) may use 'top'. + + (*) In OP_VARARG, if (C == 0) then use actual number of varargs and + set top (like in OP_CALL with C == 0). + + (*) In OP_RETURN, if (B == 0) then return up to 'top'. + + (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always + OP_EXTRAARG. + + (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then + real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the + bits of C). + + (*) In OP_NEWTABLE, B is log2 of the hash size (which is always a + power of 2) plus 1, or zero for size zero. If not k, the array size + is C. Otherwise, the array size is EXTRAARG _ C. + + (*) For comparisons, k specifies what condition the test should accept + (true or false). + + (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped + (the constant is the first operand). + + (*) All 'skips' (pc++) assume that next instruction is a jump. + + (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the + function builds upvalues, which may need to be closed. C > 0 means + the function is vararg, so that its 'func' must be corrected before + returning; in this case, (C - 1) is its number of fixed parameters. + + (*) In comparisons with an immediate operand, C signals whether the + original operand was a float. (It must be corrected in case of + metamethods.) + +===========================================================================*/ + + +/* +** masks for instruction properties. The format is: +** bits 0-2: op mode +** bit 3: instruction set register A +** bit 4: operator is a test (next instruction must be a jump) +** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0) +** bit 6: instruction sets 'L->top' for next instruction (when C == 0) +** bit 7: instruction is an MM instruction (call a metamethod) +*/ + +LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];) + +#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7)) +#define testAMode(m) (luaP_opmodes[m] & (1 << 3)) +#define testTMode(m) (luaP_opmodes[m] & (1 << 4)) +#define testITMode(m) (luaP_opmodes[m] & (1 << 5)) +#define testOTMode(m) (luaP_opmodes[m] & (1 << 6)) +#define testMMMode(m) (luaP_opmodes[m] & (1 << 7)) + +/* "out top" (set top for next instruction) */ +#define isOT(i) \ + ((testOTMode(GET_OPCODE(i)) && GETARG_C(i) == 0) || \ + GET_OPCODE(i) == OP_TAILCALL) + +/* "in top" (uses top from previous instruction) */ +#define isIT(i) (testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0) + +#define opmode(mm,ot,it,t,a,m) \ + (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m)) + + +/* number of list items to accumulate before a SETLIST instruction */ +#define LFIELDS_PER_FLUSH 50 + +#endif diff --git a/src/libs/3rdparty/lua/src/lopnames.h b/src/libs/3rdparty/lua/src/lopnames.h new file mode 100644 index 00000000000..965cec9bf2f --- /dev/null +++ b/src/libs/3rdparty/lua/src/lopnames.h @@ -0,0 +1,103 @@ +/* +** $Id: lopnames.h $ +** Opcode names +** See Copyright Notice in lua.h +*/ + +#if !defined(lopnames_h) +#define lopnames_h + +#include + + +/* ORDER OP */ + +static const char *const opnames[] = { + "MOVE", + "LOADI", + "LOADF", + "LOADK", + "LOADKX", + "LOADFALSE", + "LFALSESKIP", + "LOADTRUE", + "LOADNIL", + "GETUPVAL", + "SETUPVAL", + "GETTABUP", + "GETTABLE", + "GETI", + "GETFIELD", + "SETTABUP", + "SETTABLE", + "SETI", + "SETFIELD", + "NEWTABLE", + "SELF", + "ADDI", + "ADDK", + "SUBK", + "MULK", + "MODK", + "POWK", + "DIVK", + "IDIVK", + "BANDK", + "BORK", + "BXORK", + "SHRI", + "SHLI", + "ADD", + "SUB", + "MUL", + "MOD", + "POW", + "DIV", + "IDIV", + "BAND", + "BOR", + "BXOR", + "SHL", + "SHR", + "MMBIN", + "MMBINI", + "MMBINK", + "UNM", + "BNOT", + "NOT", + "LEN", + "CONCAT", + "CLOSE", + "TBC", + "JMP", + "EQ", + "LT", + "LE", + "EQK", + "EQI", + "LTI", + "LEI", + "GTI", + "GEI", + "TEST", + "TESTSET", + "CALL", + "TAILCALL", + "RETURN", + "RETURN0", + "RETURN1", + "FORLOOP", + "FORPREP", + "TFORPREP", + "TFORCALL", + "TFORLOOP", + "SETLIST", + "CLOSURE", + "VARARG", + "VARARGPREP", + "EXTRAARG", + NULL +}; + +#endif + diff --git a/src/libs/3rdparty/lua/src/loslib.c b/src/libs/3rdparty/lua/src/loslib.c new file mode 100644 index 00000000000..ad5a9276885 --- /dev/null +++ b/src/libs/3rdparty/lua/src/loslib.c @@ -0,0 +1,428 @@ +/* +** $Id: loslib.c $ +** Standard Operating System library +** See Copyright Notice in lua.h +*/ + +#define loslib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** {================================================================== +** List of valid conversion specifiers for the 'strftime' function; +** options are grouped by length; group of length 2 start with '||'. +** =================================================================== +*/ +#if !defined(LUA_STRFTIMEOPTIONS) /* { */ + +#if defined(LUA_USE_WINDOWS) +#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYzZ%" \ + "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */ +#elif defined(LUA_USE_C89) /* ANSI C 89 (only 1-char options) */ +#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYZ%" +#else /* C99 specification */ +#define LUA_STRFTIMEOPTIONS "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ + "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ +#endif + +#endif /* } */ +/* }================================================================== */ + + +/* +** {================================================================== +** Configuration for time-related stuff +** =================================================================== +*/ + +/* +** type to represent time_t in Lua +*/ +#if !defined(LUA_NUMTIME) /* { */ + +#define l_timet lua_Integer +#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) +#define l_gettime(L,arg) luaL_checkinteger(L, arg) + +#else /* }{ */ + +#define l_timet lua_Number +#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t)) +#define l_gettime(L,arg) luaL_checknumber(L, arg) + +#endif /* } */ + + +#if !defined(l_gmtime) /* { */ +/* +** By default, Lua uses gmtime/localtime, except when POSIX is available, +** where it uses gmtime_r/localtime_r +*/ + +#if defined(LUA_USE_POSIX) /* { */ + +#define l_gmtime(t,r) gmtime_r(t,r) +#define l_localtime(t,r) localtime_r(t,r) + +#else /* }{ */ + +/* ISO C definitions */ +#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t)) +#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t)) + +#endif /* } */ + +#endif /* } */ + +/* }================================================================== */ + + +/* +** {================================================================== +** Configuration for 'tmpnam': +** By default, Lua uses tmpnam except when POSIX is available, where +** it uses mkstemp. +** =================================================================== +*/ +#if !defined(lua_tmpnam) /* { */ + +#if defined(LUA_USE_POSIX) /* { */ + +#include + +#define LUA_TMPNAMBUFSIZE 32 + +#if !defined(LUA_TMPNAMTEMPLATE) +#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX" +#endif + +#define lua_tmpnam(b,e) { \ + strcpy(b, LUA_TMPNAMTEMPLATE); \ + e = mkstemp(b); \ + if (e != -1) close(e); \ + e = (e == -1); } + +#else /* }{ */ + +/* ISO C definitions */ +#define LUA_TMPNAMBUFSIZE L_tmpnam +#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } + +#endif /* } */ + +#endif /* } */ +/* }================================================================== */ + + +#if !defined(l_system) +#if defined(LUA_USE_IOS) +/* Despite claiming to be ISO C, iOS does not implement 'system'. */ +#define l_system(cmd) ((cmd) == NULL ? 0 : -1) +#else +#define l_system(cmd) system(cmd) /* default definition */ +#endif +#endif + + +static int os_execute (lua_State *L) { + const char *cmd = luaL_optstring(L, 1, NULL); + int stat; + errno = 0; + stat = l_system(cmd); + if (cmd != NULL) + return luaL_execresult(L, stat); + else { + lua_pushboolean(L, stat); /* true if there is a shell */ + return 1; + } +} + + +static int os_remove (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + return luaL_fileresult(L, remove(filename) == 0, filename); +} + + +static int os_rename (lua_State *L) { + const char *fromname = luaL_checkstring(L, 1); + const char *toname = luaL_checkstring(L, 2); + return luaL_fileresult(L, rename(fromname, toname) == 0, NULL); +} + + +static int os_tmpname (lua_State *L) { + char buff[LUA_TMPNAMBUFSIZE]; + int err; + lua_tmpnam(buff, err); + if (l_unlikely(err)) + return luaL_error(L, "unable to generate a unique filename"); + lua_pushstring(L, buff); + return 1; +} + + +static int os_getenv (lua_State *L) { + lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ + return 1; +} + + +static int os_clock (lua_State *L) { + lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); + return 1; +} + + +/* +** {====================================================== +** Time/Date operations +** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, +** wday=%w+1, yday=%j, isdst=? } +** ======================================================= +*/ + +/* +** About the overflow check: an overflow cannot occur when time +** is represented by a lua_Integer, because either lua_Integer is +** large enough to represent all int fields or it is not large enough +** to represent a time that cause a field to overflow. However, if +** times are represented as doubles and lua_Integer is int, then the +** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900 +** to compute the year. +*/ +static void setfield (lua_State *L, const char *key, int value, int delta) { + #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX) + if (l_unlikely(value > LUA_MAXINTEGER - delta)) + luaL_error(L, "field '%s' is out-of-bound", key); + #endif + lua_pushinteger(L, (lua_Integer)value + delta); + lua_setfield(L, -2, key); +} + + +static void setboolfield (lua_State *L, const char *key, int value) { + if (value < 0) /* undefined? */ + return; /* does not set field */ + lua_pushboolean(L, value); + lua_setfield(L, -2, key); +} + + +/* +** Set all fields from structure 'tm' in the table on top of the stack +*/ +static void setallfields (lua_State *L, struct tm *stm) { + setfield(L, "year", stm->tm_year, 1900); + setfield(L, "month", stm->tm_mon, 1); + setfield(L, "day", stm->tm_mday, 0); + setfield(L, "hour", stm->tm_hour, 0); + setfield(L, "min", stm->tm_min, 0); + setfield(L, "sec", stm->tm_sec, 0); + setfield(L, "yday", stm->tm_yday, 1); + setfield(L, "wday", stm->tm_wday, 1); + setboolfield(L, "isdst", stm->tm_isdst); +} + + +static int getboolfield (lua_State *L, const char *key) { + int res; + res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1); + lua_pop(L, 1); + return res; +} + + +static int getfield (lua_State *L, const char *key, int d, int delta) { + int isnum; + int t = lua_getfield(L, -1, key); /* get field and its type */ + lua_Integer res = lua_tointegerx(L, -1, &isnum); + if (!isnum) { /* field is not an integer? */ + if (l_unlikely(t != LUA_TNIL)) /* some other value? */ + return luaL_error(L, "field '%s' is not an integer", key); + else if (l_unlikely(d < 0)) /* absent field; no default? */ + return luaL_error(L, "field '%s' missing in date table", key); + res = d; + } + else { + if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res)) + return luaL_error(L, "field '%s' is out-of-bound", key); + res -= delta; + } + lua_pop(L, 1); + return (int)res; +} + + +static const char *checkoption (lua_State *L, const char *conv, + ptrdiff_t convlen, char *buff) { + const char *option = LUA_STRFTIMEOPTIONS; + int oplen = 1; /* length of options being checked */ + for (; *option != '\0' && oplen <= convlen; option += oplen) { + if (*option == '|') /* next block? */ + oplen++; /* will check options with next length (+1) */ + else if (memcmp(conv, option, oplen) == 0) { /* match? */ + memcpy(buff, conv, oplen); /* copy valid option to buffer */ + buff[oplen] = '\0'; + return conv + oplen; /* return next item */ + } + } + luaL_argerror(L, 1, + lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv)); + return conv; /* to avoid warnings */ +} + + +static time_t l_checktime (lua_State *L, int arg) { + l_timet t = l_gettime(L, arg); + luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); + return (time_t)t; +} + + +/* maximum size for an individual 'strftime' item */ +#define SIZETIMEFMT 250 + + +static int os_date (lua_State *L) { + size_t slen; + const char *s = luaL_optlstring(L, 1, "%c", &slen); + time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); + const char *se = s + slen; /* 's' end */ + struct tm tmr, *stm; + if (*s == '!') { /* UTC? */ + stm = l_gmtime(&t, &tmr); + s++; /* skip '!' */ + } + else + stm = l_localtime(&t, &tmr); + if (stm == NULL) /* invalid date? */ + return luaL_error(L, + "date result cannot be represented in this installation"); + if (strcmp(s, "*t") == 0) { + lua_createtable(L, 0, 9); /* 9 = number of fields */ + setallfields(L, stm); + } + else { + char cc[4]; /* buffer for individual conversion specifiers */ + luaL_Buffer b; + cc[0] = '%'; + luaL_buffinit(L, &b); + while (s < se) { + if (*s != '%') /* not a conversion specifier? */ + luaL_addchar(&b, *s++); + else { + size_t reslen; + char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); + s++; /* skip '%' */ + s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ + reslen = strftime(buff, SIZETIMEFMT, cc, stm); + luaL_addsize(&b, reslen); + } + } + luaL_pushresult(&b); + } + return 1; +} + + +static int os_time (lua_State *L) { + time_t t; + if (lua_isnoneornil(L, 1)) /* called without args? */ + t = time(NULL); /* get current time */ + else { + struct tm ts; + luaL_checktype(L, 1, LUA_TTABLE); + lua_settop(L, 1); /* make sure table is at the top */ + ts.tm_year = getfield(L, "year", -1, 1900); + ts.tm_mon = getfield(L, "month", -1, 1); + ts.tm_mday = getfield(L, "day", -1, 0); + ts.tm_hour = getfield(L, "hour", 12, 0); + ts.tm_min = getfield(L, "min", 0, 0); + ts.tm_sec = getfield(L, "sec", 0, 0); + ts.tm_isdst = getboolfield(L, "isdst"); + t = mktime(&ts); + setallfields(L, &ts); /* update fields with normalized values */ + } + if (t != (time_t)(l_timet)t || t == (time_t)(-1)) + return luaL_error(L, + "time result cannot be represented in this installation"); + l_pushtime(L, t); + return 1; +} + + +static int os_difftime (lua_State *L) { + time_t t1 = l_checktime(L, 1); + time_t t2 = l_checktime(L, 2); + lua_pushnumber(L, (lua_Number)difftime(t1, t2)); + return 1; +} + +/* }====================================================== */ + + +static int os_setlocale (lua_State *L) { + static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, + LC_NUMERIC, LC_TIME}; + static const char *const catnames[] = {"all", "collate", "ctype", "monetary", + "numeric", "time", NULL}; + const char *l = luaL_optstring(L, 1, NULL); + int op = luaL_checkoption(L, 2, "all", catnames); + lua_pushstring(L, setlocale(cat[op], l)); + return 1; +} + + +static int os_exit (lua_State *L) { + int status; + if (lua_isboolean(L, 1)) + status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); + else + status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); + if (lua_toboolean(L, 2)) + lua_close(L); + if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ + return 0; +} + + +static const luaL_Reg syslib[] = { + {"clock", os_clock}, + {"date", os_date}, + {"difftime", os_difftime}, + {"execute", os_execute}, + {"exit", os_exit}, + {"getenv", os_getenv}, + {"remove", os_remove}, + {"rename", os_rename}, + {"setlocale", os_setlocale}, + {"time", os_time}, + {"tmpname", os_tmpname}, + {NULL, NULL} +}; + +/* }====================================================== */ + + + +LUAMOD_API int luaopen_os (lua_State *L) { + luaL_newlib(L, syslib); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/lparser.c b/src/libs/3rdparty/lua/src/lparser.c new file mode 100644 index 00000000000..b745f236f06 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lparser.c @@ -0,0 +1,1967 @@ +/* +** $Id: lparser.c $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#define lparser_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lcode.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "llex.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" + + + +/* maximum number of local variables per function (must be smaller + than 250, due to the bytecode format) */ +#define MAXVARS 200 + + +#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) + + +/* because all strings are unified by the scanner, the parser + can use pointer equality for string equality */ +#define eqstr(a,b) ((a) == (b)) + + +/* +** nodes for block list (list of active blocks) +*/ +typedef struct BlockCnt { + struct BlockCnt *previous; /* chain */ + int firstlabel; /* index of first label in this block */ + int firstgoto; /* index of first pending goto in this block */ + lu_byte nactvar; /* # active locals outside the block */ + lu_byte upval; /* true if some variable in the block is an upvalue */ + lu_byte isloop; /* true if 'block' is a loop */ + lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */ +} BlockCnt; + + + +/* +** prototypes for recursive non-terminal functions +*/ +static void statement (LexState *ls); +static void expr (LexState *ls, expdesc *v); + + +static l_noret error_expected (LexState *ls, int token) { + luaX_syntaxerror(ls, + luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); +} + + +static l_noret errorlimit (FuncState *fs, int limit, const char *what) { + lua_State *L = fs->ls->L; + const char *msg; + int line = fs->f->linedefined; + const char *where = (line == 0) + ? "main function" + : luaO_pushfstring(L, "function at line %d", line); + msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", + what, limit, where); + luaX_syntaxerror(fs->ls, msg); +} + + +static void checklimit (FuncState *fs, int v, int l, const char *what) { + if (v > l) errorlimit(fs, l, what); +} + + +/* +** Test whether next token is 'c'; if so, skip it. +*/ +static int testnext (LexState *ls, int c) { + if (ls->t.token == c) { + luaX_next(ls); + return 1; + } + else return 0; +} + + +/* +** Check that next token is 'c'. +*/ +static void check (LexState *ls, int c) { + if (ls->t.token != c) + error_expected(ls, c); +} + + +/* +** Check that next token is 'c' and skip it. +*/ +static void checknext (LexState *ls, int c) { + check(ls, c); + luaX_next(ls); +} + + +#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } + + +/* +** Check that next token is 'what' and skip it. In case of error, +** raise an error that the expected 'what' should match a 'who' +** in line 'where' (if that is not the current line). +*/ +static void check_match (LexState *ls, int what, int who, int where) { + if (l_unlikely(!testnext(ls, what))) { + if (where == ls->linenumber) /* all in the same line? */ + error_expected(ls, what); /* do not need a complex message */ + else { + luaX_syntaxerror(ls, luaO_pushfstring(ls->L, + "%s expected (to close %s at line %d)", + luaX_token2str(ls, what), luaX_token2str(ls, who), where)); + } + } +} + + +static TString *str_checkname (LexState *ls) { + TString *ts; + check(ls, TK_NAME); + ts = ls->t.seminfo.ts; + luaX_next(ls); + return ts; +} + + +static void init_exp (expdesc *e, expkind k, int i) { + e->f = e->t = NO_JUMP; + e->k = k; + e->u.info = i; +} + + +static void codestring (expdesc *e, TString *s) { + e->f = e->t = NO_JUMP; + e->k = VKSTR; + e->u.strval = s; +} + + +static void codename (LexState *ls, expdesc *e) { + codestring(e, str_checkname(ls)); +} + + +/* +** Register a new local variable in the active 'Proto' (for debug +** information). +*/ +static int registerlocalvar (LexState *ls, FuncState *fs, TString *varname) { + Proto *f = fs->f; + int oldsize = f->sizelocvars; + luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars, + LocVar, SHRT_MAX, "local variables"); + while (oldsize < f->sizelocvars) + f->locvars[oldsize++].varname = NULL; + f->locvars[fs->ndebugvars].varname = varname; + f->locvars[fs->ndebugvars].startpc = fs->pc; + luaC_objbarrier(ls->L, f, varname); + return fs->ndebugvars++; +} + + +/* +** Create a new local variable with the given 'name'. Return its index +** in the function. +*/ +static int new_localvar (LexState *ls, TString *name) { + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Dyndata *dyd = ls->dyd; + Vardesc *var; + checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, + MAXVARS, "local variables"); + luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1, + dyd->actvar.size, Vardesc, USHRT_MAX, "local variables"); + var = &dyd->actvar.arr[dyd->actvar.n++]; + var->vd.kind = VDKREG; /* default */ + var->vd.name = name; + return dyd->actvar.n - 1 - fs->firstlocal; +} + +#define new_localvarliteral(ls,v) \ + new_localvar(ls, \ + luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1)); + + + +/* +** Return the "variable description" (Vardesc) of a given variable. +** (Unless noted otherwise, all variables are referred to by their +** compiler indices.) +*/ +static Vardesc *getlocalvardesc (FuncState *fs, int vidx) { + return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx]; +} + + +/* +** Convert 'nvar', a compiler index level, to its corresponding +** register. For that, search for the highest variable below that level +** that is in a register and uses its register index ('ridx') plus one. +*/ +static int reglevel (FuncState *fs, int nvar) { + while (nvar-- > 0) { + Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */ + if (vd->vd.kind != RDKCTC) /* is in a register? */ + return vd->vd.ridx + 1; + } + return 0; /* no variables in registers */ +} + + +/* +** Return the number of variables in the register stack for the given +** function. +*/ +int luaY_nvarstack (FuncState *fs) { + return reglevel(fs, fs->nactvar); +} + + +/* +** Get the debug-information entry for current variable 'vidx'. +*/ +static LocVar *localdebuginfo (FuncState *fs, int vidx) { + Vardesc *vd = getlocalvardesc(fs, vidx); + if (vd->vd.kind == RDKCTC) + return NULL; /* no debug info. for constants */ + else { + int idx = vd->vd.pidx; + lua_assert(idx < fs->ndebugvars); + return &fs->f->locvars[idx]; + } +} + + +/* +** Create an expression representing variable 'vidx' +*/ +static void init_var (FuncState *fs, expdesc *e, int vidx) { + e->f = e->t = NO_JUMP; + e->k = VLOCAL; + e->u.var.vidx = vidx; + e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx; +} + + +/* +** Raises an error if variable described by 'e' is read only +*/ +static void check_readonly (LexState *ls, expdesc *e) { + FuncState *fs = ls->fs; + TString *varname = NULL; /* to be set if variable is const */ + switch (e->k) { + case VCONST: { + varname = ls->dyd->actvar.arr[e->u.info].vd.name; + break; + } + case VLOCAL: { + Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx); + if (vardesc->vd.kind != VDKREG) /* not a regular variable? */ + varname = vardesc->vd.name; + break; + } + case VUPVAL: { + Upvaldesc *up = &fs->f->upvalues[e->u.info]; + if (up->kind != VDKREG) + varname = up->name; + break; + } + default: + return; /* other cases cannot be read-only */ + } + if (varname) { + const char *msg = luaO_pushfstring(ls->L, + "attempt to assign to const variable '%s'", getstr(varname)); + luaK_semerror(ls, msg); /* error */ + } +} + + +/* +** Start the scope for the last 'nvars' created variables. +*/ +static void adjustlocalvars (LexState *ls, int nvars) { + FuncState *fs = ls->fs; + int reglevel = luaY_nvarstack(fs); + int i; + for (i = 0; i < nvars; i++) { + int vidx = fs->nactvar++; + Vardesc *var = getlocalvardesc(fs, vidx); + var->vd.ridx = reglevel++; + var->vd.pidx = registerlocalvar(ls, fs, var->vd.name); + } +} + + +/* +** Close the scope for all variables up to level 'tolevel'. +** (debug info.) +*/ +static void removevars (FuncState *fs, int tolevel) { + fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); + while (fs->nactvar > tolevel) { + LocVar *var = localdebuginfo(fs, --fs->nactvar); + if (var) /* does it have debug information? */ + var->endpc = fs->pc; + } +} + + +/* +** Search the upvalues of the function 'fs' for one +** with the given 'name'. +*/ +static int searchupvalue (FuncState *fs, TString *name) { + int i; + Upvaldesc *up = fs->f->upvalues; + for (i = 0; i < fs->nups; i++) { + if (eqstr(up[i].name, name)) return i; + } + return -1; /* not found */ +} + + +static Upvaldesc *allocupvalue (FuncState *fs) { + Proto *f = fs->f; + int oldsize = f->sizeupvalues; + checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); + luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, + Upvaldesc, MAXUPVAL, "upvalues"); + while (oldsize < f->sizeupvalues) + f->upvalues[oldsize++].name = NULL; + return &f->upvalues[fs->nups++]; +} + + +static int newupvalue (FuncState *fs, TString *name, expdesc *v) { + Upvaldesc *up = allocupvalue(fs); + FuncState *prev = fs->prev; + if (v->k == VLOCAL) { + up->instack = 1; + up->idx = v->u.var.ridx; + up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind; + lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name)); + } + else { + up->instack = 0; + up->idx = cast_byte(v->u.info); + up->kind = prev->f->upvalues[v->u.info].kind; + lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name)); + } + up->name = name; + luaC_objbarrier(fs->ls->L, fs->f, name); + return fs->nups - 1; +} + + +/* +** Look for an active local variable with the name 'n' in the +** function 'fs'. If found, initialize 'var' with it and return +** its expression kind; otherwise return -1. +*/ +static int searchvar (FuncState *fs, TString *n, expdesc *var) { + int i; + for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { + Vardesc *vd = getlocalvardesc(fs, i); + if (eqstr(n, vd->vd.name)) { /* found? */ + if (vd->vd.kind == RDKCTC) /* compile-time constant? */ + init_exp(var, VCONST, fs->firstlocal + i); + else /* real variable */ + init_var(fs, var, i); + return var->k; + } + } + return -1; /* not found */ +} + + +/* +** Mark block where variable at given level was defined +** (to emit close instructions later). +*/ +static void markupval (FuncState *fs, int level) { + BlockCnt *bl = fs->bl; + while (bl->nactvar > level) + bl = bl->previous; + bl->upval = 1; + fs->needclose = 1; +} + + +/* +** Mark that current block has a to-be-closed variable. +*/ +static void marktobeclosed (FuncState *fs) { + BlockCnt *bl = fs->bl; + bl->upval = 1; + bl->insidetbc = 1; + fs->needclose = 1; +} + + +/* +** Find a variable with the given name 'n'. If it is an upvalue, add +** this upvalue into all intermediate functions. If it is a global, set +** 'var' as 'void' as a flag. +*/ +static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { + if (fs == NULL) /* no more levels? */ + init_exp(var, VVOID, 0); /* default is global */ + else { + int v = searchvar(fs, n, var); /* look up locals at current level */ + if (v >= 0) { /* found? */ + if (v == VLOCAL && !base) + markupval(fs, var->u.var.vidx); /* local will be used as an upval */ + } + else { /* not found as local at current level; try upvalues */ + int idx = searchupvalue(fs, n); /* try existing upvalues */ + if (idx < 0) { /* not found? */ + singlevaraux(fs->prev, n, var, 0); /* try upper levels */ + if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */ + idx = newupvalue(fs, n, var); /* will be a new upvalue */ + else /* it is a global or a constant */ + return; /* don't need to do anything at this level */ + } + init_exp(var, VUPVAL, idx); /* new or old upvalue */ + } + } +} + + +/* +** Find a variable with the given name 'n', handling global variables +** too. +*/ +static void singlevar (LexState *ls, expdesc *var) { + TString *varname = str_checkname(ls); + FuncState *fs = ls->fs; + singlevaraux(fs, varname, var, 1); + if (var->k == VVOID) { /* global name? */ + expdesc key; + singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ + lua_assert(var->k != VVOID); /* this one must exist */ + luaK_exp2anyregup(fs, var); /* but could be a constant */ + codestring(&key, varname); /* key is variable name */ + luaK_indexed(fs, var, &key); /* env[varname] */ + } +} + + +/* +** Adjust the number of results from an expression list 'e' with 'nexps' +** expressions to 'nvars' values. +*/ +static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { + FuncState *fs = ls->fs; + int needed = nvars - nexps; /* extra values needed */ + if (hasmultret(e->k)) { /* last expression has multiple returns? */ + int extra = needed + 1; /* discount last expression itself */ + if (extra < 0) + extra = 0; + luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ + } + else { + if (e->k != VVOID) /* at least one expression? */ + luaK_exp2nextreg(fs, e); /* close last expression */ + if (needed > 0) /* missing values? */ + luaK_nil(fs, fs->freereg, needed); /* complete with nils */ + } + if (needed > 0) + luaK_reserveregs(fs, needed); /* registers for extra values */ + else /* adding 'needed' is actually a subtraction */ + fs->freereg += needed; /* remove extra values */ +} + + +#define enterlevel(ls) luaE_incCstack(ls->L) + + +#define leavelevel(ls) ((ls)->L->nCcalls--) + + +/* +** Generates an error that a goto jumps into the scope of some +** local variable. +*/ +static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) { + const char *varname = getstr(getlocalvardesc(ls->fs, gt->nactvar)->vd.name); + const char *msg = " at line %d jumps into the scope of local '%s'"; + msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname); + luaK_semerror(ls, msg); /* raise the error */ +} + + +/* +** Solves the goto at index 'g' to given 'label' and removes it +** from the list of pending gotos. +** If it jumps into the scope of some variable, raises an error. +*/ +static void solvegoto (LexState *ls, int g, Labeldesc *label) { + int i; + Labellist *gl = &ls->dyd->gt; /* list of gotos */ + Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */ + lua_assert(eqstr(gt->name, label->name)); + if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */ + jumpscopeerror(ls, gt); + luaK_patchlist(ls->fs, gt->pc, label->pc); + for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */ + gl->arr[i] = gl->arr[i + 1]; + gl->n--; +} + + +/* +** Search for an active label with the given name. +*/ +static Labeldesc *findlabel (LexState *ls, TString *name) { + int i; + Dyndata *dyd = ls->dyd; + /* check labels in current function for a match */ + for (i = ls->fs->firstlabel; i < dyd->label.n; i++) { + Labeldesc *lb = &dyd->label.arr[i]; + if (eqstr(lb->name, name)) /* correct label? */ + return lb; + } + return NULL; /* label not found */ +} + + +/* +** Adds a new label/goto in the corresponding list. +*/ +static int newlabelentry (LexState *ls, Labellist *l, TString *name, + int line, int pc) { + int n = l->n; + luaM_growvector(ls->L, l->arr, n, l->size, + Labeldesc, SHRT_MAX, "labels/gotos"); + l->arr[n].name = name; + l->arr[n].line = line; + l->arr[n].nactvar = ls->fs->nactvar; + l->arr[n].close = 0; + l->arr[n].pc = pc; + l->n = n + 1; + return n; +} + + +static int newgotoentry (LexState *ls, TString *name, int line, int pc) { + return newlabelentry(ls, &ls->dyd->gt, name, line, pc); +} + + +/* +** Solves forward jumps. Check whether new label 'lb' matches any +** pending gotos in current block and solves them. Return true +** if any of the gotos need to close upvalues. +*/ +static int solvegotos (LexState *ls, Labeldesc *lb) { + Labellist *gl = &ls->dyd->gt; + int i = ls->fs->bl->firstgoto; + int needsclose = 0; + while (i < gl->n) { + if (eqstr(gl->arr[i].name, lb->name)) { + needsclose |= gl->arr[i].close; + solvegoto(ls, i, lb); /* will remove 'i' from the list */ + } + else + i++; + } + return needsclose; +} + + +/* +** Create a new label with the given 'name' at the given 'line'. +** 'last' tells whether label is the last non-op statement in its +** block. Solves all pending gotos to this new label and adds +** a close instruction if necessary. +** Returns true iff it added a close instruction. +*/ +static int createlabel (LexState *ls, TString *name, int line, + int last) { + FuncState *fs = ls->fs; + Labellist *ll = &ls->dyd->label; + int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs)); + if (last) { /* label is last no-op statement in the block? */ + /* assume that locals are already out of scope */ + ll->arr[l].nactvar = fs->bl->nactvar; + } + if (solvegotos(ls, &ll->arr[l])) { /* need close? */ + luaK_codeABC(fs, OP_CLOSE, luaY_nvarstack(fs), 0, 0); + return 1; + } + return 0; +} + + +/* +** Adjust pending gotos to outer level of a block. +*/ +static void movegotosout (FuncState *fs, BlockCnt *bl) { + int i; + Labellist *gl = &fs->ls->dyd->gt; + /* correct pending gotos to current block */ + for (i = bl->firstgoto; i < gl->n; i++) { /* for each pending goto */ + Labeldesc *gt = &gl->arr[i]; + /* leaving a variable scope? */ + if (reglevel(fs, gt->nactvar) > reglevel(fs, bl->nactvar)) + gt->close |= bl->upval; /* jump may need a close */ + gt->nactvar = bl->nactvar; /* update goto level */ + } +} + + +static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { + bl->isloop = isloop; + bl->nactvar = fs->nactvar; + bl->firstlabel = fs->ls->dyd->label.n; + bl->firstgoto = fs->ls->dyd->gt.n; + bl->upval = 0; + bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc); + bl->previous = fs->bl; + fs->bl = bl; + lua_assert(fs->freereg == luaY_nvarstack(fs)); +} + + +/* +** generates an error for an undefined 'goto'. +*/ +static l_noret undefgoto (LexState *ls, Labeldesc *gt) { + const char *msg; + if (eqstr(gt->name, luaS_newliteral(ls->L, "break"))) { + msg = "break outside loop at line %d"; + msg = luaO_pushfstring(ls->L, msg, gt->line); + } + else { + msg = "no visible label '%s' for at line %d"; + msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); + } + luaK_semerror(ls, msg); +} + + +static void leaveblock (FuncState *fs) { + BlockCnt *bl = fs->bl; + LexState *ls = fs->ls; + int hasclose = 0; + int stklevel = reglevel(fs, bl->nactvar); /* level outside the block */ + removevars(fs, bl->nactvar); /* remove block locals */ + lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */ + if (bl->isloop) /* has to fix pending breaks? */ + hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0); + if (!hasclose && bl->previous && bl->upval) /* still need a 'close'? */ + luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0); + fs->freereg = stklevel; /* free registers */ + ls->dyd->label.n = bl->firstlabel; /* remove local labels */ + fs->bl = bl->previous; /* current block now is previous one */ + if (bl->previous) /* was it a nested block? */ + movegotosout(fs, bl); /* update pending gotos to enclosing block */ + else { + if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */ + undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ + } +} + + +/* +** adds a new prototype into list of prototypes +*/ +static Proto *addprototype (LexState *ls) { + Proto *clp; + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; /* prototype of current function */ + if (fs->np >= f->sizep) { + int oldsize = f->sizep; + luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); + while (oldsize < f->sizep) + f->p[oldsize++] = NULL; + } + f->p[fs->np++] = clp = luaF_newproto(L); + luaC_objbarrier(L, f, clp); + return clp; +} + + +/* +** codes instruction to create new closure in parent function. +** The OP_CLOSURE instruction uses the last available register, +** so that, if it invokes the GC, the GC knows which registers +** are in use at that time. + +*/ +static void codeclosure (LexState *ls, expdesc *v) { + FuncState *fs = ls->fs->prev; + init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); + luaK_exp2nextreg(fs, v); /* fix it at the last register */ +} + + +static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { + Proto *f = fs->f; + fs->prev = ls->fs; /* linked list of funcstates */ + fs->ls = ls; + ls->fs = fs; + fs->pc = 0; + fs->previousline = f->linedefined; + fs->iwthabs = 0; + fs->lasttarget = 0; + fs->freereg = 0; + fs->nk = 0; + fs->nabslineinfo = 0; + fs->np = 0; + fs->nups = 0; + fs->ndebugvars = 0; + fs->nactvar = 0; + fs->needclose = 0; + fs->firstlocal = ls->dyd->actvar.n; + fs->firstlabel = ls->dyd->label.n; + fs->bl = NULL; + f->source = ls->source; + luaC_objbarrier(ls->L, f, f->source); + f->maxstacksize = 2; /* registers 0/1 are always valid */ + enterblock(fs, bl, 0); +} + + +static void close_func (LexState *ls) { + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; + luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */ + leaveblock(fs); + lua_assert(fs->bl == NULL); + luaK_finish(fs); + luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction); + luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte); + luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo, + fs->nabslineinfo, AbsLineInfo); + luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue); + luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *); + luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar); + luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); + ls->fs = fs->prev; + luaC_checkGC(L); +} + + + +/*============================================================*/ +/* GRAMMAR RULES */ +/*============================================================*/ + + +/* +** check whether current token is in the follow set of a block. +** 'until' closes syntactical blocks, but do not close scope, +** so it is handled in separate. +*/ +static int block_follow (LexState *ls, int withuntil) { + switch (ls->t.token) { + case TK_ELSE: case TK_ELSEIF: + case TK_END: case TK_EOS: + return 1; + case TK_UNTIL: return withuntil; + default: return 0; + } +} + + +static void statlist (LexState *ls) { + /* statlist -> { stat [';'] } */ + while (!block_follow(ls, 1)) { + if (ls->t.token == TK_RETURN) { + statement(ls); + return; /* 'return' must be last statement */ + } + statement(ls); + } +} + + +static void fieldsel (LexState *ls, expdesc *v) { + /* fieldsel -> ['.' | ':'] NAME */ + FuncState *fs = ls->fs; + expdesc key; + luaK_exp2anyregup(fs, v); + luaX_next(ls); /* skip the dot or colon */ + codename(ls, &key); + luaK_indexed(fs, v, &key); +} + + +static void yindex (LexState *ls, expdesc *v) { + /* index -> '[' expr ']' */ + luaX_next(ls); /* skip the '[' */ + expr(ls, v); + luaK_exp2val(ls->fs, v); + checknext(ls, ']'); +} + + +/* +** {====================================================================== +** Rules for Constructors +** ======================================================================= +*/ + + +typedef struct ConsControl { + expdesc v; /* last list item read */ + expdesc *t; /* table descriptor */ + int nh; /* total number of 'record' elements */ + int na; /* number of array elements already stored */ + int tostore; /* number of array elements pending to be stored */ +} ConsControl; + + +static void recfield (LexState *ls, ConsControl *cc) { + /* recfield -> (NAME | '['exp']') = exp */ + FuncState *fs = ls->fs; + int reg = ls->fs->freereg; + expdesc tab, key, val; + if (ls->t.token == TK_NAME) { + checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); + codename(ls, &key); + } + else /* ls->t.token == '[' */ + yindex(ls, &key); + cc->nh++; + checknext(ls, '='); + tab = *cc->t; + luaK_indexed(fs, &tab, &key); + expr(ls, &val); + luaK_storevar(fs, &tab, &val); + fs->freereg = reg; /* free registers */ +} + + +static void closelistfield (FuncState *fs, ConsControl *cc) { + if (cc->v.k == VVOID) return; /* there is no list item */ + luaK_exp2nextreg(fs, &cc->v); + cc->v.k = VVOID; + if (cc->tostore == LFIELDS_PER_FLUSH) { + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ + cc->na += cc->tostore; + cc->tostore = 0; /* no more items pending */ + } +} + + +static void lastlistfield (FuncState *fs, ConsControl *cc) { + if (cc->tostore == 0) return; + if (hasmultret(cc->v.k)) { + luaK_setmultret(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); + cc->na--; /* do not count last expression (unknown number of elements) */ + } + else { + if (cc->v.k != VVOID) + luaK_exp2nextreg(fs, &cc->v); + luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); + } + cc->na += cc->tostore; +} + + +static void listfield (LexState *ls, ConsControl *cc) { + /* listfield -> exp */ + expr(ls, &cc->v); + cc->tostore++; +} + + +static void field (LexState *ls, ConsControl *cc) { + /* field -> listfield | recfield */ + switch(ls->t.token) { + case TK_NAME: { /* may be 'listfield' or 'recfield' */ + if (luaX_lookahead(ls) != '=') /* expression? */ + listfield(ls, cc); + else + recfield(ls, cc); + break; + } + case '[': { + recfield(ls, cc); + break; + } + default: { + listfield(ls, cc); + break; + } + } +} + + +static void constructor (LexState *ls, expdesc *t) { + /* constructor -> '{' [ field { sep field } [sep] ] '}' + sep -> ',' | ';' */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); + ConsControl cc; + luaK_code(fs, 0); /* space for extra arg. */ + cc.na = cc.nh = cc.tostore = 0; + cc.t = t; + init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */ + luaK_reserveregs(fs, 1); + init_exp(&cc.v, VVOID, 0); /* no value (yet) */ + checknext(ls, '{'); + do { + lua_assert(cc.v.k == VVOID || cc.tostore > 0); + if (ls->t.token == '}') break; + closelistfield(fs, &cc); + field(ls, &cc); + } while (testnext(ls, ',') || testnext(ls, ';')); + check_match(ls, '}', '{', line); + lastlistfield(fs, &cc); + luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh); +} + +/* }====================================================================== */ + + +static void setvararg (FuncState *fs, int nparams) { + fs->f->is_vararg = 1; + luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0); +} + + +static void parlist (LexState *ls) { + /* parlist -> [ {NAME ','} (NAME | '...') ] */ + FuncState *fs = ls->fs; + Proto *f = fs->f; + int nparams = 0; + int isvararg = 0; + if (ls->t.token != ')') { /* is 'parlist' not empty? */ + do { + switch (ls->t.token) { + case TK_NAME: { + new_localvar(ls, str_checkname(ls)); + nparams++; + break; + } + case TK_DOTS: { + luaX_next(ls); + isvararg = 1; + break; + } + default: luaX_syntaxerror(ls, " or '...' expected"); + } + } while (!isvararg && testnext(ls, ',')); + } + adjustlocalvars(ls, nparams); + f->numparams = cast_byte(fs->nactvar); + if (isvararg) + setvararg(fs, f->numparams); /* declared vararg */ + luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */ +} + + +static void body (LexState *ls, expdesc *e, int ismethod, int line) { + /* body -> '(' parlist ')' block END */ + FuncState new_fs; + BlockCnt bl; + new_fs.f = addprototype(ls); + new_fs.f->linedefined = line; + open_func(ls, &new_fs, &bl); + checknext(ls, '('); + if (ismethod) { + new_localvarliteral(ls, "self"); /* create 'self' parameter */ + adjustlocalvars(ls, 1); + } + parlist(ls); + checknext(ls, ')'); + statlist(ls); + new_fs.f->lastlinedefined = ls->linenumber; + check_match(ls, TK_END, TK_FUNCTION, line); + codeclosure(ls, e); + close_func(ls); +} + + +static int explist (LexState *ls, expdesc *v) { + /* explist -> expr { ',' expr } */ + int n = 1; /* at least one expression */ + expr(ls, v); + while (testnext(ls, ',')) { + luaK_exp2nextreg(ls->fs, v); + expr(ls, v); + n++; + } + return n; +} + + +static void funcargs (LexState *ls, expdesc *f, int line) { + FuncState *fs = ls->fs; + expdesc args; + int base, nparams; + switch (ls->t.token) { + case '(': { /* funcargs -> '(' [ explist ] ')' */ + luaX_next(ls); + if (ls->t.token == ')') /* arg list is empty? */ + args.k = VVOID; + else { + explist(ls, &args); + if (hasmultret(args.k)) + luaK_setmultret(fs, &args); + } + check_match(ls, ')', '(', line); + break; + } + case '{': { /* funcargs -> constructor */ + constructor(ls, &args); + break; + } + case TK_STRING: { /* funcargs -> STRING */ + codestring(&args, ls->t.seminfo.ts); + luaX_next(ls); /* must use 'seminfo' before 'next' */ + break; + } + default: { + luaX_syntaxerror(ls, "function arguments expected"); + } + } + lua_assert(f->k == VNONRELOC); + base = f->u.info; /* base register for call */ + if (hasmultret(args.k)) + nparams = LUA_MULTRET; /* open call */ + else { + if (args.k != VVOID) + luaK_exp2nextreg(fs, &args); /* close last argument */ + nparams = fs->freereg - (base+1); + } + init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); + luaK_fixline(fs, line); + fs->freereg = base+1; /* call remove function and arguments and leaves + (unless changed) one result */ +} + + + + +/* +** {====================================================================== +** Expression parsing +** ======================================================================= +*/ + + +static void primaryexp (LexState *ls, expdesc *v) { + /* primaryexp -> NAME | '(' expr ')' */ + switch (ls->t.token) { + case '(': { + int line = ls->linenumber; + luaX_next(ls); + expr(ls, v); + check_match(ls, ')', '(', line); + luaK_dischargevars(ls->fs, v); + return; + } + case TK_NAME: { + singlevar(ls, v); + return; + } + default: { + luaX_syntaxerror(ls, "unexpected symbol"); + } + } +} + + +static void suffixedexp (LexState *ls, expdesc *v) { + /* suffixedexp -> + primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + primaryexp(ls, v); + for (;;) { + switch (ls->t.token) { + case '.': { /* fieldsel */ + fieldsel(ls, v); + break; + } + case '[': { /* '[' exp ']' */ + expdesc key; + luaK_exp2anyregup(fs, v); + yindex(ls, &key); + luaK_indexed(fs, v, &key); + break; + } + case ':': { /* ':' NAME funcargs */ + expdesc key; + luaX_next(ls); + codename(ls, &key); + luaK_self(fs, v, &key); + funcargs(ls, v, line); + break; + } + case '(': case TK_STRING: case '{': { /* funcargs */ + luaK_exp2nextreg(fs, v); + funcargs(ls, v, line); + break; + } + default: return; + } + } +} + + +static void simpleexp (LexState *ls, expdesc *v) { + /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | + constructor | FUNCTION body | suffixedexp */ + switch (ls->t.token) { + case TK_FLT: { + init_exp(v, VKFLT, 0); + v->u.nval = ls->t.seminfo.r; + break; + } + case TK_INT: { + init_exp(v, VKINT, 0); + v->u.ival = ls->t.seminfo.i; + break; + } + case TK_STRING: { + codestring(v, ls->t.seminfo.ts); + break; + } + case TK_NIL: { + init_exp(v, VNIL, 0); + break; + } + case TK_TRUE: { + init_exp(v, VTRUE, 0); + break; + } + case TK_FALSE: { + init_exp(v, VFALSE, 0); + break; + } + case TK_DOTS: { /* vararg */ + FuncState *fs = ls->fs; + check_condition(ls, fs->f->is_vararg, + "cannot use '...' outside a vararg function"); + init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1)); + break; + } + case '{': { /* constructor */ + constructor(ls, v); + return; + } + case TK_FUNCTION: { + luaX_next(ls); + body(ls, v, 0, ls->linenumber); + return; + } + default: { + suffixedexp(ls, v); + return; + } + } + luaX_next(ls); +} + + +static UnOpr getunopr (int op) { + switch (op) { + case TK_NOT: return OPR_NOT; + case '-': return OPR_MINUS; + case '~': return OPR_BNOT; + case '#': return OPR_LEN; + default: return OPR_NOUNOPR; + } +} + + +static BinOpr getbinopr (int op) { + switch (op) { + case '+': return OPR_ADD; + case '-': return OPR_SUB; + case '*': return OPR_MUL; + case '%': return OPR_MOD; + case '^': return OPR_POW; + case '/': return OPR_DIV; + case TK_IDIV: return OPR_IDIV; + case '&': return OPR_BAND; + case '|': return OPR_BOR; + case '~': return OPR_BXOR; + case TK_SHL: return OPR_SHL; + case TK_SHR: return OPR_SHR; + case TK_CONCAT: return OPR_CONCAT; + case TK_NE: return OPR_NE; + case TK_EQ: return OPR_EQ; + case '<': return OPR_LT; + case TK_LE: return OPR_LE; + case '>': return OPR_GT; + case TK_GE: return OPR_GE; + case TK_AND: return OPR_AND; + case TK_OR: return OPR_OR; + default: return OPR_NOBINOPR; + } +} + + +/* +** Priority table for binary operators. +*/ +static const struct { + lu_byte left; /* left priority for each binary operator */ + lu_byte right; /* right priority */ +} priority[] = { /* ORDER OPR */ + {10, 10}, {10, 10}, /* '+' '-' */ + {11, 11}, {11, 11}, /* '*' '%' */ + {14, 13}, /* '^' (right associative) */ + {11, 11}, {11, 11}, /* '/' '//' */ + {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ + {7, 7}, {7, 7}, /* '<<' '>>' */ + {9, 8}, /* '..' (right associative) */ + {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ + {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ + {2, 2}, {1, 1} /* and, or */ +}; + +#define UNARY_PRIORITY 12 /* priority for unary operators */ + + +/* +** subexpr -> (simpleexp | unop subexpr) { binop subexpr } +** where 'binop' is any binary operator with a priority higher than 'limit' +*/ +static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { + BinOpr op; + UnOpr uop; + enterlevel(ls); + uop = getunopr(ls->t.token); + if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */ + int line = ls->linenumber; + luaX_next(ls); /* skip operator */ + subexpr(ls, v, UNARY_PRIORITY); + luaK_prefix(ls->fs, uop, v, line); + } + else simpleexp(ls, v); + /* expand while operators have priorities higher than 'limit' */ + op = getbinopr(ls->t.token); + while (op != OPR_NOBINOPR && priority[op].left > limit) { + expdesc v2; + BinOpr nextop; + int line = ls->linenumber; + luaX_next(ls); /* skip operator */ + luaK_infix(ls->fs, op, v); + /* read sub-expression with higher priority */ + nextop = subexpr(ls, &v2, priority[op].right); + luaK_posfix(ls->fs, op, v, &v2, line); + op = nextop; + } + leavelevel(ls); + return op; /* return first untreated operator */ +} + + +static void expr (LexState *ls, expdesc *v) { + subexpr(ls, v, 0); +} + +/* }==================================================================== */ + + + +/* +** {====================================================================== +** Rules for Statements +** ======================================================================= +*/ + + +static void block (LexState *ls) { + /* block -> statlist */ + FuncState *fs = ls->fs; + BlockCnt bl; + enterblock(fs, &bl, 0); + statlist(ls); + leaveblock(fs); +} + + +/* +** structure to chain all variables in the left-hand side of an +** assignment +*/ +struct LHS_assign { + struct LHS_assign *prev; + expdesc v; /* variable (global, local, upvalue, or indexed) */ +}; + + +/* +** check whether, in an assignment to an upvalue/local variable, the +** upvalue/local variable is begin used in a previous assignment to a +** table. If so, save original upvalue/local value in a safe place and +** use this safe copy in the previous assignment. +*/ +static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { + FuncState *fs = ls->fs; + int extra = fs->freereg; /* eventual position to save local variable */ + int conflict = 0; + for (; lh; lh = lh->prev) { /* check all previous assignments */ + if (vkisindexed(lh->v.k)) { /* assignment to table field? */ + if (lh->v.k == VINDEXUP) { /* is table an upvalue? */ + if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) { + conflict = 1; /* table is the upvalue being assigned now */ + lh->v.k = VINDEXSTR; + lh->v.u.ind.t = extra; /* assignment will use safe copy */ + } + } + else { /* table is a register */ + if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) { + conflict = 1; /* table is the local being assigned now */ + lh->v.u.ind.t = extra; /* assignment will use safe copy */ + } + /* is index the local being assigned? */ + if (lh->v.k == VINDEXED && v->k == VLOCAL && + lh->v.u.ind.idx == v->u.var.ridx) { + conflict = 1; + lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ + } + } + } + } + if (conflict) { + /* copy upvalue/local value to a temporary (in position 'extra') */ + if (v->k == VLOCAL) + luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0); + else + luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0); + luaK_reserveregs(fs, 1); + } +} + +/* +** Parse and compile a multiple assignment. The first "variable" +** (a 'suffixedexp') was already read by the caller. +** +** assignment -> suffixedexp restassign +** restassign -> ',' suffixedexp restassign | '=' explist +*/ +static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) { + expdesc e; + check_condition(ls, vkisvar(lh->v.k), "syntax error"); + check_readonly(ls, &lh->v); + if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */ + struct LHS_assign nv; + nv.prev = lh; + suffixedexp(ls, &nv.v); + if (!vkisindexed(nv.v.k)) + check_conflict(ls, lh, &nv.v); + enterlevel(ls); /* control recursion depth */ + restassign(ls, &nv, nvars+1); + leavelevel(ls); + } + else { /* restassign -> '=' explist */ + int nexps; + checknext(ls, '='); + nexps = explist(ls, &e); + if (nexps != nvars) + adjust_assign(ls, nvars, nexps, &e); + else { + luaK_setoneret(ls->fs, &e); /* close last expression */ + luaK_storevar(ls->fs, &lh->v, &e); + return; /* avoid default */ + } + } + init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ + luaK_storevar(ls->fs, &lh->v, &e); +} + + +static int cond (LexState *ls) { + /* cond -> exp */ + expdesc v; + expr(ls, &v); /* read condition */ + if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ + luaK_goiftrue(ls->fs, &v); + return v.f; +} + + +static void gotostat (LexState *ls) { + FuncState *fs = ls->fs; + int line = ls->linenumber; + TString *name = str_checkname(ls); /* label's name */ + Labeldesc *lb = findlabel(ls, name); + if (lb == NULL) /* no label? */ + /* forward jump; will be resolved when the label is declared */ + newgotoentry(ls, name, line, luaK_jump(fs)); + else { /* found a label */ + /* backward jump; will be resolved here */ + int lblevel = reglevel(fs, lb->nactvar); /* label level */ + if (luaY_nvarstack(fs) > lblevel) /* leaving the scope of a variable? */ + luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0); + /* create jump and link it to the label */ + luaK_patchlist(fs, luaK_jump(fs), lb->pc); + } +} + + +/* +** Break statement. Semantically equivalent to "goto break". +*/ +static void breakstat (LexState *ls) { + int line = ls->linenumber; + luaX_next(ls); /* skip break */ + newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs)); +} + + +/* +** Check whether there is already a label with the given 'name'. +*/ +static void checkrepeated (LexState *ls, TString *name) { + Labeldesc *lb = findlabel(ls, name); + if (l_unlikely(lb != NULL)) { /* already defined? */ + const char *msg = "label '%s' already defined on line %d"; + msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line); + luaK_semerror(ls, msg); /* error */ + } +} + + +static void labelstat (LexState *ls, TString *name, int line) { + /* label -> '::' NAME '::' */ + checknext(ls, TK_DBCOLON); /* skip double colon */ + while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) + statement(ls); /* skip other no-op statements */ + checkrepeated(ls, name); /* check for repeated labels */ + createlabel(ls, name, line, block_follow(ls, 0)); +} + + +static void whilestat (LexState *ls, int line) { + /* whilestat -> WHILE cond DO block END */ + FuncState *fs = ls->fs; + int whileinit; + int condexit; + BlockCnt bl; + luaX_next(ls); /* skip WHILE */ + whileinit = luaK_getlabel(fs); + condexit = cond(ls); + enterblock(fs, &bl, 1); + checknext(ls, TK_DO); + block(ls); + luaK_jumpto(fs, whileinit); + check_match(ls, TK_END, TK_WHILE, line); + leaveblock(fs); + luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ +} + + +static void repeatstat (LexState *ls, int line) { + /* repeatstat -> REPEAT block UNTIL cond */ + int condexit; + FuncState *fs = ls->fs; + int repeat_init = luaK_getlabel(fs); + BlockCnt bl1, bl2; + enterblock(fs, &bl1, 1); /* loop block */ + enterblock(fs, &bl2, 0); /* scope block */ + luaX_next(ls); /* skip REPEAT */ + statlist(ls); + check_match(ls, TK_UNTIL, TK_REPEAT, line); + condexit = cond(ls); /* read condition (inside scope block) */ + leaveblock(fs); /* finish scope */ + if (bl2.upval) { /* upvalues? */ + int exit = luaK_jump(fs); /* normal exit must jump over fix */ + luaK_patchtohere(fs, condexit); /* repetition must close upvalues */ + luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0); + condexit = luaK_jump(fs); /* repeat after closing upvalues */ + luaK_patchtohere(fs, exit); /* normal exit comes to here */ + } + luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ + leaveblock(fs); /* finish loop */ +} + + +/* +** Read an expression and generate code to put its results in next +** stack slot. +** +*/ +static void exp1 (LexState *ls) { + expdesc e; + expr(ls, &e); + luaK_exp2nextreg(ls->fs, &e); + lua_assert(e.k == VNONRELOC); +} + + +/* +** Fix for instruction at position 'pc' to jump to 'dest'. +** (Jump addresses are relative in Lua). 'back' true means +** a back jump. +*/ +static void fixforjump (FuncState *fs, int pc, int dest, int back) { + Instruction *jmp = &fs->f->code[pc]; + int offset = dest - (pc + 1); + if (back) + offset = -offset; + if (l_unlikely(offset > MAXARG_Bx)) + luaX_syntaxerror(fs->ls, "control structure too long"); + SETARG_Bx(*jmp, offset); +} + + +/* +** Generate code for a 'for' loop. +*/ +static void forbody (LexState *ls, int base, int line, int nvars, int isgen) { + /* forbody -> DO block */ + static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP}; + static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP}; + BlockCnt bl; + FuncState *fs = ls->fs; + int prep, endfor; + checknext(ls, TK_DO); + prep = luaK_codeABx(fs, forprep[isgen], base, 0); + enterblock(fs, &bl, 0); /* scope for declared variables */ + adjustlocalvars(ls, nvars); + luaK_reserveregs(fs, nvars); + block(ls); + leaveblock(fs); /* end of scope for declared variables */ + fixforjump(fs, prep, luaK_getlabel(fs), 0); + if (isgen) { /* generic for? */ + luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); + luaK_fixline(fs, line); + } + endfor = luaK_codeABx(fs, forloop[isgen], base, 0); + fixforjump(fs, endfor, prep + 1, 1); + luaK_fixline(fs, line); +} + + +static void fornum (LexState *ls, TString *varname, int line) { + /* fornum -> NAME = exp,exp[,exp] forbody */ + FuncState *fs = ls->fs; + int base = fs->freereg; + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for state)"); + new_localvar(ls, varname); + checknext(ls, '='); + exp1(ls); /* initial value */ + checknext(ls, ','); + exp1(ls); /* limit */ + if (testnext(ls, ',')) + exp1(ls); /* optional step */ + else { /* default step = 1 */ + luaK_int(fs, fs->freereg, 1); + luaK_reserveregs(fs, 1); + } + adjustlocalvars(ls, 3); /* control variables */ + forbody(ls, base, line, 1, 0); +} + + +static void forlist (LexState *ls, TString *indexname) { + /* forlist -> NAME {,NAME} IN explist forbody */ + FuncState *fs = ls->fs; + expdesc e; + int nvars = 5; /* gen, state, control, toclose, 'indexname' */ + int line; + int base = fs->freereg; + /* create control variables */ + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for state)"); + new_localvarliteral(ls, "(for state)"); + /* create declared variables */ + new_localvar(ls, indexname); + while (testnext(ls, ',')) { + new_localvar(ls, str_checkname(ls)); + nvars++; + } + checknext(ls, TK_IN); + line = ls->linenumber; + adjust_assign(ls, 4, explist(ls, &e), &e); + adjustlocalvars(ls, 4); /* control variables */ + marktobeclosed(fs); /* last control var. must be closed */ + luaK_checkstack(fs, 3); /* extra space to call generator */ + forbody(ls, base, line, nvars - 4, 1); +} + + +static void forstat (LexState *ls, int line) { + /* forstat -> FOR (fornum | forlist) END */ + FuncState *fs = ls->fs; + TString *varname; + BlockCnt bl; + enterblock(fs, &bl, 1); /* scope for loop and control variables */ + luaX_next(ls); /* skip 'for' */ + varname = str_checkname(ls); /* first variable name */ + switch (ls->t.token) { + case '=': fornum(ls, varname, line); break; + case ',': case TK_IN: forlist(ls, varname); break; + default: luaX_syntaxerror(ls, "'=' or 'in' expected"); + } + check_match(ls, TK_END, TK_FOR, line); + leaveblock(fs); /* loop scope ('break' jumps to this point) */ +} + + +static void test_then_block (LexState *ls, int *escapelist) { + /* test_then_block -> [IF | ELSEIF] cond THEN block */ + BlockCnt bl; + FuncState *fs = ls->fs; + expdesc v; + int jf; /* instruction to skip 'then' code (if condition is false) */ + luaX_next(ls); /* skip IF or ELSEIF */ + expr(ls, &v); /* read condition */ + checknext(ls, TK_THEN); + if (ls->t.token == TK_BREAK) { /* 'if x then break' ? */ + int line = ls->linenumber; + luaK_goiffalse(ls->fs, &v); /* will jump if condition is true */ + luaX_next(ls); /* skip 'break' */ + enterblock(fs, &bl, 0); /* must enter block before 'goto' */ + newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, v.t); + while (testnext(ls, ';')) {} /* skip semicolons */ + if (block_follow(ls, 0)) { /* jump is the entire block? */ + leaveblock(fs); + return; /* and that is it */ + } + else /* must skip over 'then' part if condition is false */ + jf = luaK_jump(fs); + } + else { /* regular case (not a break) */ + luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ + enterblock(fs, &bl, 0); + jf = v.f; + } + statlist(ls); /* 'then' part */ + leaveblock(fs); + if (ls->t.token == TK_ELSE || + ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ + luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ + luaK_patchtohere(fs, jf); +} + + +static void ifstat (LexState *ls, int line) { + /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ + FuncState *fs = ls->fs; + int escapelist = NO_JUMP; /* exit list for finished parts */ + test_then_block(ls, &escapelist); /* IF cond THEN block */ + while (ls->t.token == TK_ELSEIF) + test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ + if (testnext(ls, TK_ELSE)) + block(ls); /* 'else' part */ + check_match(ls, TK_END, TK_IF, line); + luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ +} + + +static void localfunc (LexState *ls) { + expdesc b; + FuncState *fs = ls->fs; + int fvar = fs->nactvar; /* function's variable index */ + new_localvar(ls, str_checkname(ls)); /* new local variable */ + adjustlocalvars(ls, 1); /* enter its scope */ + body(ls, &b, 0, ls->linenumber); /* function created in next register */ + /* debug information will only see the variable after this point! */ + localdebuginfo(fs, fvar)->startpc = fs->pc; +} + + +static int getlocalattribute (LexState *ls) { + /* ATTRIB -> ['<' Name '>'] */ + if (testnext(ls, '<')) { + const char *attr = getstr(str_checkname(ls)); + checknext(ls, '>'); + if (strcmp(attr, "const") == 0) + return RDKCONST; /* read-only variable */ + else if (strcmp(attr, "close") == 0) + return RDKTOCLOSE; /* to-be-closed variable */ + else + luaK_semerror(ls, + luaO_pushfstring(ls->L, "unknown attribute '%s'", attr)); + } + return VDKREG; /* regular variable */ +} + + +static void checktoclose (FuncState *fs, int level) { + if (level != -1) { /* is there a to-be-closed variable? */ + marktobeclosed(fs); + luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0); + } +} + + +static void localstat (LexState *ls) { + /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */ + FuncState *fs = ls->fs; + int toclose = -1; /* index of to-be-closed variable (if any) */ + Vardesc *var; /* last variable */ + int vidx, kind; /* index and kind of last variable */ + int nvars = 0; + int nexps; + expdesc e; + do { + vidx = new_localvar(ls, str_checkname(ls)); + kind = getlocalattribute(ls); + getlocalvardesc(fs, vidx)->vd.kind = kind; + if (kind == RDKTOCLOSE) { /* to-be-closed? */ + if (toclose != -1) /* one already present? */ + luaK_semerror(ls, "multiple to-be-closed variables in local list"); + toclose = fs->nactvar + nvars; + } + nvars++; + } while (testnext(ls, ',')); + if (testnext(ls, '=')) + nexps = explist(ls, &e); + else { + e.k = VVOID; + nexps = 0; + } + var = getlocalvardesc(fs, vidx); /* get last variable */ + if (nvars == nexps && /* no adjustments? */ + var->vd.kind == RDKCONST && /* last variable is const? */ + luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */ + var->vd.kind = RDKCTC; /* variable is a compile-time constant */ + adjustlocalvars(ls, nvars - 1); /* exclude last variable */ + fs->nactvar++; /* but count it */ + } + else { + adjust_assign(ls, nvars, nexps, &e); + adjustlocalvars(ls, nvars); + } + checktoclose(fs, toclose); +} + + +static int funcname (LexState *ls, expdesc *v) { + /* funcname -> NAME {fieldsel} [':' NAME] */ + int ismethod = 0; + singlevar(ls, v); + while (ls->t.token == '.') + fieldsel(ls, v); + if (ls->t.token == ':') { + ismethod = 1; + fieldsel(ls, v); + } + return ismethod; +} + + +static void funcstat (LexState *ls, int line) { + /* funcstat -> FUNCTION funcname body */ + int ismethod; + expdesc v, b; + luaX_next(ls); /* skip FUNCTION */ + ismethod = funcname(ls, &v); + body(ls, &b, ismethod, line); + check_readonly(ls, &v); + luaK_storevar(ls->fs, &v, &b); + luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ +} + + +static void exprstat (LexState *ls) { + /* stat -> func | assignment */ + FuncState *fs = ls->fs; + struct LHS_assign v; + suffixedexp(ls, &v.v); + if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ + v.prev = NULL; + restassign(ls, &v, 1); + } + else { /* stat -> func */ + Instruction *inst; + check_condition(ls, v.v.k == VCALL, "syntax error"); + inst = &getinstruction(fs, &v.v); + SETARG_C(*inst, 1); /* call statement uses no results */ + } +} + + +static void retstat (LexState *ls) { + /* stat -> RETURN [explist] [';'] */ + FuncState *fs = ls->fs; + expdesc e; + int nret; /* number of values being returned */ + int first = luaY_nvarstack(fs); /* first slot to be returned */ + if (block_follow(ls, 1) || ls->t.token == ';') + nret = 0; /* return no values */ + else { + nret = explist(ls, &e); /* optional return values */ + if (hasmultret(e.k)) { + luaK_setmultret(fs, &e); + if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */ + SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); + lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs)); + } + nret = LUA_MULTRET; /* return all values */ + } + else { + if (nret == 1) /* only one single value? */ + first = luaK_exp2anyreg(fs, &e); /* can use original slot */ + else { /* values must go to the top of the stack */ + luaK_exp2nextreg(fs, &e); + lua_assert(nret == fs->freereg - first); + } + } + } + luaK_ret(fs, first, nret); + testnext(ls, ';'); /* skip optional semicolon */ +} + + +static void statement (LexState *ls) { + int line = ls->linenumber; /* may be needed for error messages */ + enterlevel(ls); + switch (ls->t.token) { + case ';': { /* stat -> ';' (empty statement) */ + luaX_next(ls); /* skip ';' */ + break; + } + case TK_IF: { /* stat -> ifstat */ + ifstat(ls, line); + break; + } + case TK_WHILE: { /* stat -> whilestat */ + whilestat(ls, line); + break; + } + case TK_DO: { /* stat -> DO block END */ + luaX_next(ls); /* skip DO */ + block(ls); + check_match(ls, TK_END, TK_DO, line); + break; + } + case TK_FOR: { /* stat -> forstat */ + forstat(ls, line); + break; + } + case TK_REPEAT: { /* stat -> repeatstat */ + repeatstat(ls, line); + break; + } + case TK_FUNCTION: { /* stat -> funcstat */ + funcstat(ls, line); + break; + } + case TK_LOCAL: { /* stat -> localstat */ + luaX_next(ls); /* skip LOCAL */ + if (testnext(ls, TK_FUNCTION)) /* local function? */ + localfunc(ls); + else + localstat(ls); + break; + } + case TK_DBCOLON: { /* stat -> label */ + luaX_next(ls); /* skip double colon */ + labelstat(ls, str_checkname(ls), line); + break; + } + case TK_RETURN: { /* stat -> retstat */ + luaX_next(ls); /* skip RETURN */ + retstat(ls); + break; + } + case TK_BREAK: { /* stat -> breakstat */ + breakstat(ls); + break; + } + case TK_GOTO: { /* stat -> 'goto' NAME */ + luaX_next(ls); /* skip 'goto' */ + gotostat(ls); + break; + } + default: { /* stat -> func | assignment */ + exprstat(ls); + break; + } + } + lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && + ls->fs->freereg >= luaY_nvarstack(ls->fs)); + ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */ + leavelevel(ls); +} + +/* }====================================================================== */ + + +/* +** compiles the main function, which is a regular vararg function with an +** upvalue named LUA_ENV +*/ +static void mainfunc (LexState *ls, FuncState *fs) { + BlockCnt bl; + Upvaldesc *env; + open_func(ls, fs, &bl); + setvararg(fs, 0); /* main function is always declared vararg */ + env = allocupvalue(fs); /* ...set environment upvalue */ + env->instack = 1; + env->idx = 0; + env->kind = VDKREG; + env->name = ls->envn; + luaC_objbarrier(ls->L, fs->f, env->name); + luaX_next(ls); /* read first token */ + statlist(ls); /* parse main body */ + check(ls, TK_EOS); + close_func(ls); +} + + +LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar) { + LexState lexstate; + FuncState funcstate; + LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ + setclLvalue2s(L, L->top.p, cl); /* anchor it (to avoid being collected) */ + luaD_inctop(L); + lexstate.h = luaH_new(L); /* create table for scanner */ + sethvalue2s(L, L->top.p, lexstate.h); /* anchor it */ + luaD_inctop(L); + funcstate.f = cl->p = luaF_newproto(L); + luaC_objbarrier(L, cl, cl->p); + funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ + luaC_objbarrier(L, funcstate.f, funcstate.f->source); + lexstate.buff = buff; + lexstate.dyd = dyd; + dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; + luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); + mainfunc(&lexstate, &funcstate); + lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); + /* all scopes should be correctly finished */ + lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); + L->top.p--; /* remove scanner's table */ + return cl; /* closure is on the stack, too */ +} + diff --git a/src/libs/3rdparty/lua/src/lparser.h b/src/libs/3rdparty/lua/src/lparser.h new file mode 100644 index 00000000000..5e4500f181a --- /dev/null +++ b/src/libs/3rdparty/lua/src/lparser.h @@ -0,0 +1,171 @@ +/* +** $Id: lparser.h $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#ifndef lparser_h +#define lparser_h + +#include "llimits.h" +#include "lobject.h" +#include "lzio.h" + + +/* +** Expression and variable descriptor. +** Code generation for variables and expressions can be delayed to allow +** optimizations; An 'expdesc' structure describes a potentially-delayed +** variable/expression. It has a description of its "main" value plus a +** list of conditional jumps that can also produce its value (generated +** by short-circuit operators 'and'/'or'). +*/ + +/* kinds of variables/expressions */ +typedef enum { + VVOID, /* when 'expdesc' describes the last expression of a list, + this kind means an empty list (so, no expression) */ + VNIL, /* constant nil */ + VTRUE, /* constant true */ + VFALSE, /* constant false */ + VK, /* constant in 'k'; info = index of constant in 'k' */ + VKFLT, /* floating constant; nval = numerical float value */ + VKINT, /* integer constant; ival = numerical integer value */ + VKSTR, /* string constant; strval = TString address; + (string is fixed by the lexer) */ + VNONRELOC, /* expression has its value in a fixed register; + info = result register */ + VLOCAL, /* local variable; var.ridx = register index; + var.vidx = relative index in 'actvar.arr' */ + VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ + VCONST, /* compile-time variable; + info = absolute index in 'actvar.arr' */ + VINDEXED, /* indexed variable; + ind.t = table register; + ind.idx = key's R index */ + VINDEXUP, /* indexed upvalue; + ind.t = table upvalue; + ind.idx = key's K index */ + VINDEXI, /* indexed variable with constant integer; + ind.t = table register; + ind.idx = key's value */ + VINDEXSTR, /* indexed variable with literal string; + ind.t = table register; + ind.idx = key's K index */ + VJMP, /* expression is a test/comparison; + info = pc of corresponding jump instruction */ + VRELOC, /* expression can put result in any register; + info = instruction pc */ + VCALL, /* expression is a function call; info = instruction pc */ + VVARARG /* vararg expression; info = instruction pc */ +} expkind; + + +#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXSTR) +#define vkisindexed(k) (VINDEXED <= (k) && (k) <= VINDEXSTR) + + +typedef struct expdesc { + expkind k; + union { + lua_Integer ival; /* for VKINT */ + lua_Number nval; /* for VKFLT */ + TString *strval; /* for VKSTR */ + int info; /* for generic use */ + struct { /* for indexed variables */ + short idx; /* index (R or "long" K) */ + lu_byte t; /* table (register or upvalue) */ + } ind; + struct { /* for local variables */ + lu_byte ridx; /* register holding the variable */ + unsigned short vidx; /* compiler index (in 'actvar.arr') */ + } var; + } u; + int t; /* patch list of 'exit when true' */ + int f; /* patch list of 'exit when false' */ +} expdesc; + + +/* kinds of variables */ +#define VDKREG 0 /* regular */ +#define RDKCONST 1 /* constant */ +#define RDKTOCLOSE 2 /* to-be-closed */ +#define RDKCTC 3 /* compile-time constant */ + +/* description of an active local variable */ +typedef union Vardesc { + struct { + TValuefields; /* constant value (if it is a compile-time constant) */ + lu_byte kind; + lu_byte ridx; /* register holding the variable */ + short pidx; /* index of the variable in the Proto's 'locvars' array */ + TString *name; /* variable name */ + } vd; + TValue k; /* constant value (if any) */ +} Vardesc; + + + +/* description of pending goto statements and label statements */ +typedef struct Labeldesc { + TString *name; /* label identifier */ + int pc; /* position in code */ + int line; /* line where it appeared */ + lu_byte nactvar; /* number of active variables in that position */ + lu_byte close; /* goto that escapes upvalues */ +} Labeldesc; + + +/* list of labels or gotos */ +typedef struct Labellist { + Labeldesc *arr; /* array */ + int n; /* number of entries in use */ + int size; /* array size */ +} Labellist; + + +/* dynamic structures used by the parser */ +typedef struct Dyndata { + struct { /* list of all active local variables */ + Vardesc *arr; + int n; + int size; + } actvar; + Labellist gt; /* list of pending gotos */ + Labellist label; /* list of active labels */ +} Dyndata; + + +/* control of blocks */ +struct BlockCnt; /* defined in lparser.c */ + + +/* state needed to generate code for a given function */ +typedef struct FuncState { + Proto *f; /* current function header */ + struct FuncState *prev; /* enclosing function */ + struct LexState *ls; /* lexical state */ + struct BlockCnt *bl; /* chain of current blocks */ + int pc; /* next position to code (equivalent to 'ncode') */ + int lasttarget; /* 'label' of last 'jump label' */ + int previousline; /* last line that was saved in 'lineinfo' */ + int nk; /* number of elements in 'k' */ + int np; /* number of elements in 'p' */ + int nabslineinfo; /* number of elements in 'abslineinfo' */ + int firstlocal; /* index of first local var (in Dyndata array) */ + int firstlabel; /* index of first label (in 'dyd->label->arr') */ + short ndebugvars; /* number of elements in 'f->locvars' */ + lu_byte nactvar; /* number of active local variables */ + lu_byte nups; /* number of upvalues */ + lu_byte freereg; /* first free register */ + lu_byte iwthabs; /* instructions issued since last absolute line info */ + lu_byte needclose; /* function needs to close upvalues when returning */ +} FuncState; + + +LUAI_FUNC int luaY_nvarstack (FuncState *fs); +LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + Dyndata *dyd, const char *name, int firstchar); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lprefix.h b/src/libs/3rdparty/lua/src/lprefix.h new file mode 100644 index 00000000000..484f2ad6fbf --- /dev/null +++ b/src/libs/3rdparty/lua/src/lprefix.h @@ -0,0 +1,45 @@ +/* +** $Id: lprefix.h $ +** Definitions for Lua code that must come before any other header file +** See Copyright Notice in lua.h +*/ + +#ifndef lprefix_h +#define lprefix_h + + +/* +** Allows POSIX/XSI stuff +*/ +#if !defined(LUA_USE_C89) /* { */ + +#if !defined(_XOPEN_SOURCE) +#define _XOPEN_SOURCE 600 +#elif _XOPEN_SOURCE == 0 +#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */ +#endif + +/* +** Allows manipulation of large files in gcc and some other compilers +*/ +#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS) +#define _LARGEFILE_SOURCE 1 +#define _FILE_OFFSET_BITS 64 +#endif + +#endif /* } */ + + +/* +** Windows stuff +*/ +#if defined(_WIN32) /* { */ + +#if !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ +#endif + +#endif /* } */ + +#endif + diff --git a/src/libs/3rdparty/lua/src/lstate.c b/src/libs/3rdparty/lua/src/lstate.c new file mode 100644 index 00000000000..1e925e5ad4c --- /dev/null +++ b/src/libs/3rdparty/lua/src/lstate.c @@ -0,0 +1,445 @@ +/* +** $Id: lstate.c $ +** Global State +** See Copyright Notice in lua.h +*/ + +#define lstate_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "lapi.h" +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "llex.h" +#include "lmem.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + + +/* +** thread state + extra space +*/ +typedef struct LX { + lu_byte extra_[LUA_EXTRASPACE]; + lua_State l; +} LX; + + +/* +** Main thread combines a thread state and the global state +*/ +typedef struct LG { + LX l; + global_State g; +} LG; + + + +#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) + + +/* +** A macro to create a "random" seed when a state is created; +** the seed is used to randomize string hashes. +*/ +#if !defined(luai_makeseed) + +#include + +/* +** Compute an initial seed with some level of randomness. +** Rely on Address Space Layout Randomization (if present) and +** current time. +*/ +#define addbuff(b,p,e) \ + { size_t t = cast_sizet(e); \ + memcpy(b + p, &t, sizeof(t)); p += sizeof(t); } + +static unsigned int luai_makeseed (lua_State *L) { + char buff[3 * sizeof(size_t)]; + unsigned int h = cast_uint(time(NULL)); + int p = 0; + addbuff(buff, p, L); /* heap variable */ + addbuff(buff, p, &h); /* local variable */ + addbuff(buff, p, &lua_newstate); /* public function */ + lua_assert(p == sizeof(buff)); + return luaS_hash(buff, p, h); +} + +#endif + + +/* +** set GCdebt to a new value keeping the value (totalbytes + GCdebt) +** invariant (and avoiding underflows in 'totalbytes') +*/ +void luaE_setdebt (global_State *g, l_mem debt) { + l_mem tb = gettotalbytes(g); + lua_assert(tb > 0); + if (debt < tb - MAX_LMEM) + debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */ + g->totalbytes = tb - debt; + g->GCdebt = debt; +} + + +LUA_API int lua_setcstacklimit (lua_State *L, unsigned int limit) { + UNUSED(L); UNUSED(limit); + return LUAI_MAXCCALLS; /* warning?? */ +} + + +CallInfo *luaE_extendCI (lua_State *L) { + CallInfo *ci; + lua_assert(L->ci->next == NULL); + ci = luaM_new(L, CallInfo); + lua_assert(L->ci->next == NULL); + L->ci->next = ci; + ci->previous = L->ci; + ci->next = NULL; + ci->u.l.trap = 0; + L->nci++; + return ci; +} + + +/* +** free all CallInfo structures not in use by a thread +*/ +void luaE_freeCI (lua_State *L) { + CallInfo *ci = L->ci; + CallInfo *next = ci->next; + ci->next = NULL; + while ((ci = next) != NULL) { + next = ci->next; + luaM_free(L, ci); + L->nci--; + } +} + + +/* +** free half of the CallInfo structures not in use by a thread, +** keeping the first one. +*/ +void luaE_shrinkCI (lua_State *L) { + CallInfo *ci = L->ci->next; /* first free CallInfo */ + CallInfo *next; + if (ci == NULL) + return; /* no extra elements */ + while ((next = ci->next) != NULL) { /* two extra elements? */ + CallInfo *next2 = next->next; /* next's next */ + ci->next = next2; /* remove next from the list */ + L->nci--; + luaM_free(L, next); /* free next */ + if (next2 == NULL) + break; /* no more elements */ + else { + next2->previous = ci; + ci = next2; /* continue */ + } + } +} + + +/* +** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS. +** If equal, raises an overflow error. If value is larger than +** LUAI_MAXCCALLS (which means it is handling an overflow) but +** not much larger, does not report an error (to allow overflow +** handling to work). +*/ +void luaE_checkcstack (lua_State *L) { + if (getCcalls(L) == LUAI_MAXCCALLS) + luaG_runerror(L, "C stack overflow"); + else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11)) + luaD_throw(L, LUA_ERRERR); /* error while handling stack error */ +} + + +LUAI_FUNC void luaE_incCstack (lua_State *L) { + L->nCcalls++; + if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) + luaE_checkcstack(L); +} + + +static void stack_init (lua_State *L1, lua_State *L) { + int i; CallInfo *ci; + /* initialize stack array */ + L1->stack.p = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue); + L1->tbclist.p = L1->stack.p; + for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++) + setnilvalue(s2v(L1->stack.p + i)); /* erase new stack */ + L1->top.p = L1->stack.p; + L1->stack_last.p = L1->stack.p + BASIC_STACK_SIZE; + /* initialize first ci */ + ci = &L1->base_ci; + ci->next = ci->previous = NULL; + ci->callstatus = CIST_C; + ci->func.p = L1->top.p; + ci->u.c.k = NULL; + ci->nresults = 0; + setnilvalue(s2v(L1->top.p)); /* 'function' entry for this 'ci' */ + L1->top.p++; + ci->top.p = L1->top.p + LUA_MINSTACK; + L1->ci = ci; +} + + +static void freestack (lua_State *L) { + if (L->stack.p == NULL) + return; /* stack not completely built yet */ + L->ci = &L->base_ci; /* free the entire 'ci' list */ + luaE_freeCI(L); + lua_assert(L->nci == 0); + luaM_freearray(L, L->stack.p, stacksize(L) + EXTRA_STACK); /* free stack */ +} + + +/* +** Create registry table and its predefined values +*/ +static void init_registry (lua_State *L, global_State *g) { + /* create registry */ + Table *registry = luaH_new(L); + sethvalue(L, &g->l_registry, registry); + luaH_resize(L, registry, LUA_RIDX_LAST, 0); + /* registry[LUA_RIDX_MAINTHREAD] = L */ + setthvalue(L, ®istry->array[LUA_RIDX_MAINTHREAD - 1], L); + /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */ + sethvalue(L, ®istry->array[LUA_RIDX_GLOBALS - 1], luaH_new(L)); +} + + +/* +** open parts of the state that may cause memory-allocation errors. +*/ +static void f_luaopen (lua_State *L, void *ud) { + global_State *g = G(L); + UNUSED(ud); + stack_init(L, L); /* init stack */ + init_registry(L, g); + luaS_init(L); + luaT_init(L); + luaX_init(L); + g->gcstp = 0; /* allow gc */ + setnilvalue(&g->nilvalue); /* now state is complete */ + luai_userstateopen(L); +} + + +/* +** preinitialize a thread with consistent values without allocating +** any memory (to avoid errors) +*/ +static void preinit_thread (lua_State *L, global_State *g) { + G(L) = g; + L->stack.p = NULL; + L->ci = NULL; + L->nci = 0; + L->twups = L; /* thread has no upvalues */ + L->nCcalls = 0; + L->errorJmp = NULL; + L->hook = NULL; + L->hookmask = 0; + L->basehookcount = 0; + L->allowhook = 1; + resethookcount(L); + L->openupval = NULL; + L->status = LUA_OK; + L->errfunc = 0; + L->oldpc = 0; +} + + +static void close_state (lua_State *L) { + global_State *g = G(L); + if (!completestate(g)) /* closing a partially built state? */ + luaC_freeallobjects(L); /* just collect its objects */ + else { /* closing a fully built state */ + L->ci = &L->base_ci; /* unwind CallInfo list */ + luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */ + luaC_freeallobjects(L); /* collect all objects */ + luai_userstateclose(L); + } + luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); + freestack(L); + lua_assert(gettotalbytes(g) == sizeof(LG)); + (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ +} + + +LUA_API lua_State *lua_newthread (lua_State *L) { + global_State *g = G(L); + GCObject *o; + lua_State *L1; + lua_lock(L); + luaC_checkGC(L); + /* create new thread */ + o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l)); + L1 = gco2th(o); + /* anchor it on L stack */ + setthvalue2s(L, L->top.p, L1); + api_incr_top(L); + preinit_thread(L1, g); + L1->hookmask = L->hookmask; + L1->basehookcount = L->basehookcount; + L1->hook = L->hook; + resethookcount(L1); + /* initialize L1 extra space */ + memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread), + LUA_EXTRASPACE); + luai_userstatethread(L, L1); + stack_init(L1, L); /* init stack */ + lua_unlock(L); + return L1; +} + + +void luaE_freethread (lua_State *L, lua_State *L1) { + LX *l = fromstate(L1); + luaF_closeupval(L1, L1->stack.p); /* close all upvalues */ + lua_assert(L1->openupval == NULL); + luai_userstatefree(L, L1); + freestack(L1); + luaM_free(L, l); +} + + +int luaE_resetthread (lua_State *L, int status) { + CallInfo *ci = L->ci = &L->base_ci; /* unwind CallInfo list */ + setnilvalue(s2v(L->stack.p)); /* 'function' entry for basic 'ci' */ + ci->func.p = L->stack.p; + ci->callstatus = CIST_C; + if (status == LUA_YIELD) + status = LUA_OK; + L->status = LUA_OK; /* so it can run __close metamethods */ + status = luaD_closeprotected(L, 1, status); + if (status != LUA_OK) /* errors? */ + luaD_seterrorobj(L, status, L->stack.p + 1); + else + L->top.p = L->stack.p + 1; + ci->top.p = L->top.p + LUA_MINSTACK; + luaD_reallocstack(L, cast_int(ci->top.p - L->stack.p), 0); + return status; +} + + +LUA_API int lua_closethread (lua_State *L, lua_State *from) { + int status; + lua_lock(L); + L->nCcalls = (from) ? getCcalls(from) : 0; + status = luaE_resetthread(L, L->status); + lua_unlock(L); + return status; +} + + +/* +** Deprecated! Use 'lua_closethread' instead. +*/ +LUA_API int lua_resetthread (lua_State *L) { + return lua_closethread(L, NULL); +} + + +LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { + int i; + lua_State *L; + global_State *g; + LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG))); + if (l == NULL) return NULL; + L = &l->l.l; + g = &l->g; + L->tt = LUA_VTHREAD; + g->currentwhite = bitmask(WHITE0BIT); + L->marked = luaC_white(g); + preinit_thread(L, g); + g->allgc = obj2gco(L); /* by now, only object is the main thread */ + L->next = NULL; + incnny(L); /* main thread is always non yieldable */ + g->frealloc = f; + g->ud = ud; + g->warnf = NULL; + g->ud_warn = NULL; + g->mainthread = L; + g->seed = luai_makeseed(L); + g->gcstp = GCSTPGC; /* no GC while building state */ + g->strt.size = g->strt.nuse = 0; + g->strt.hash = NULL; + setnilvalue(&g->l_registry); + g->panic = NULL; + g->gcstate = GCSpause; + g->gckind = KGC_INC; + g->gcstopem = 0; + g->gcemergency = 0; + g->finobj = g->tobefnz = g->fixedgc = NULL; + g->firstold1 = g->survival = g->old1 = g->reallyold = NULL; + g->finobjsur = g->finobjold1 = g->finobjrold = NULL; + g->sweepgc = NULL; + g->gray = g->grayagain = NULL; + g->weak = g->ephemeron = g->allweak = NULL; + g->twups = NULL; + g->totalbytes = sizeof(LG); + g->GCdebt = 0; + g->lastatomic = 0; + setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */ + setgcparam(g->gcpause, LUAI_GCPAUSE); + setgcparam(g->gcstepmul, LUAI_GCMUL); + g->gcstepsize = LUAI_GCSTEPSIZE; + setgcparam(g->genmajormul, LUAI_GENMAJORMUL); + g->genminormul = LUAI_GENMINORMUL; + for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL; + if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { + /* memory allocation error: free partial state */ + close_state(L); + L = NULL; + } + return L; +} + + +LUA_API void lua_close (lua_State *L) { + lua_lock(L); + L = G(L)->mainthread; /* only the main thread can be closed */ + close_state(L); +} + + +void luaE_warning (lua_State *L, const char *msg, int tocont) { + lua_WarnFunction wf = G(L)->warnf; + if (wf != NULL) + wf(G(L)->ud_warn, msg, tocont); +} + + +/* +** Generate a warning from an error message +*/ +void luaE_warnerror (lua_State *L, const char *where) { + TValue *errobj = s2v(L->top.p - 1); /* error object */ + const char *msg = (ttisstring(errobj)) + ? svalue(errobj) + : "error object is not a string"; + /* produce warning "error in %s (%s)" (where, msg) */ + luaE_warning(L, "error in ", 1); + luaE_warning(L, where, 1); + luaE_warning(L, " (", 1); + luaE_warning(L, msg, 1); + luaE_warning(L, ")", 0); +} + diff --git a/src/libs/3rdparty/lua/src/lstate.h b/src/libs/3rdparty/lua/src/lstate.h new file mode 100644 index 00000000000..8bf6600e344 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lstate.h @@ -0,0 +1,409 @@ +/* +** $Id: lstate.h $ +** Global State +** See Copyright Notice in lua.h +*/ + +#ifndef lstate_h +#define lstate_h + +#include "lua.h" + + +/* Some header files included here need this definition */ +typedef struct CallInfo CallInfo; + + +#include "lobject.h" +#include "ltm.h" +#include "lzio.h" + + +/* +** Some notes about garbage-collected objects: All objects in Lua must +** be kept somehow accessible until being freed, so all objects always +** belong to one (and only one) of these lists, using field 'next' of +** the 'CommonHeader' for the link: +** +** 'allgc': all objects not marked for finalization; +** 'finobj': all objects marked for finalization; +** 'tobefnz': all objects ready to be finalized; +** 'fixedgc': all objects that are not to be collected (currently +** only small strings, such as reserved words). +** +** For the generational collector, some of these lists have marks for +** generations. Each mark points to the first element in the list for +** that particular generation; that generation goes until the next mark. +** +** 'allgc' -> 'survival': new objects; +** 'survival' -> 'old': objects that survived one collection; +** 'old1' -> 'reallyold': objects that became old in last collection; +** 'reallyold' -> NULL: objects old for more than one cycle. +** +** 'finobj' -> 'finobjsur': new objects marked for finalization; +** 'finobjsur' -> 'finobjold1': survived """"; +** 'finobjold1' -> 'finobjrold': just old """"; +** 'finobjrold' -> NULL: really old """". +** +** All lists can contain elements older than their main ages, due +** to 'luaC_checkfinalizer' and 'udata2finalize', which move +** objects between the normal lists and the "marked for finalization" +** lists. Moreover, barriers can age young objects in young lists as +** OLD0, which then become OLD1. However, a list never contains +** elements younger than their main ages. +** +** The generational collector also uses a pointer 'firstold1', which +** points to the first OLD1 object in the list. It is used to optimize +** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc' +** and 'reallyold', but often the list has no OLD1 objects or they are +** after 'old1'.) Note the difference between it and 'old1': +** 'firstold1': no OLD1 objects before this point; there can be all +** ages after it. +** 'old1': no objects younger than OLD1 after this point. +*/ + +/* +** Moreover, there is another set of lists that control gray objects. +** These lists are linked by fields 'gclist'. (All objects that +** can become gray have such a field. The field is not the same +** in all objects, but it always has this name.) Any gray object +** must belong to one of these lists, and all objects in these lists +** must be gray (with two exceptions explained below): +** +** 'gray': regular gray objects, still waiting to be visited. +** 'grayagain': objects that must be revisited at the atomic phase. +** That includes +** - black objects got in a write barrier; +** - all kinds of weak tables during propagation phase; +** - all threads. +** 'weak': tables with weak values to be cleared; +** 'ephemeron': ephemeron tables with white->white entries; +** 'allweak': tables with weak keys and/or weak values to be cleared. +** +** The exceptions to that "gray rule" are: +** - TOUCHED2 objects in generational mode stay in a gray list (because +** they must be visited again at the end of the cycle), but they are +** marked black because assignments to them must activate barriers (to +** move them back to TOUCHED1). +** - Open upvales are kept gray to avoid barriers, but they stay out +** of gray lists. (They don't even have a 'gclist' field.) +*/ + + + +/* +** About 'nCcalls': This count has two parts: the lower 16 bits counts +** the number of recursive invocations in the C stack; the higher +** 16 bits counts the number of non-yieldable calls in the stack. +** (They are together so that we can change and save both with one +** instruction.) +*/ + + +/* true if this thread does not have non-yieldable calls in the stack */ +#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0) + +/* real number of C calls */ +#define getCcalls(L) ((L)->nCcalls & 0xffff) + + +/* Increment the number of non-yieldable calls */ +#define incnny(L) ((L)->nCcalls += 0x10000) + +/* Decrement the number of non-yieldable calls */ +#define decnny(L) ((L)->nCcalls -= 0x10000) + +/* Non-yieldable call increment */ +#define nyci (0x10000 | 1) + + + + +struct lua_longjmp; /* defined in ldo.c */ + + +/* +** Atomic type (relative to signals) to better ensure that 'lua_sethook' +** is thread safe +*/ +#if !defined(l_signalT) +#include +#define l_signalT sig_atomic_t +#endif + + +/* +** Extra stack space to handle TM calls and some other extras. This +** space is not included in 'stack_last'. It is used only to avoid stack +** checks, either because the element will be promptly popped or because +** there will be a stack check soon after the push. Function frames +** never use this extra space, so it does not need to be kept clean. +*/ +#define EXTRA_STACK 5 + + +#define BASIC_STACK_SIZE (2*LUA_MINSTACK) + +#define stacksize(th) cast_int((th)->stack_last.p - (th)->stack.p) + + +/* kinds of Garbage Collection */ +#define KGC_INC 0 /* incremental gc */ +#define KGC_GEN 1 /* generational gc */ + + +typedef struct stringtable { + TString **hash; + int nuse; /* number of elements */ + int size; +} stringtable; + + +/* +** Information about a call. +** About union 'u': +** - field 'l' is used only for Lua functions; +** - field 'c' is used only for C functions. +** About union 'u2': +** - field 'funcidx' is used only by C functions while doing a +** protected call; +** - field 'nyield' is used only while a function is "doing" an +** yield (from the yield until the next resume); +** - field 'nres' is used only while closing tbc variables when +** returning from a function; +** - field 'transferinfo' is used only during call/returnhooks, +** before the function starts or after it ends. +*/ +struct CallInfo { + StkIdRel func; /* function index in the stack */ + StkIdRel top; /* top for this function */ + struct CallInfo *previous, *next; /* dynamic call link */ + union { + struct { /* only for Lua functions */ + const Instruction *savedpc; + volatile l_signalT trap; + int nextraargs; /* # of extra arguments in vararg functions */ + } l; + struct { /* only for C functions */ + lua_KFunction k; /* continuation in case of yields */ + ptrdiff_t old_errfunc; + lua_KContext ctx; /* context info. in case of yields */ + } c; + } u; + union { + int funcidx; /* called-function index */ + int nyield; /* number of values yielded */ + int nres; /* number of values returned */ + struct { /* info about transferred values (for call/return hooks) */ + unsigned short ftransfer; /* offset of first value transferred */ + unsigned short ntransfer; /* number of values transferred */ + } transferinfo; + } u2; + short nresults; /* expected number of results from this function */ + unsigned short callstatus; +}; + + +/* +** Bits in CallInfo status +*/ +#define CIST_OAH (1<<0) /* original value of 'allowhook' */ +#define CIST_C (1<<1) /* call is running a C function */ +#define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */ +#define CIST_HOOKED (1<<3) /* call is running a debug hook */ +#define CIST_YPCALL (1<<4) /* doing a yieldable protected call */ +#define CIST_TAIL (1<<5) /* call was tail called */ +#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */ +#define CIST_FIN (1<<7) /* function "called" a finalizer */ +#define CIST_TRAN (1<<8) /* 'ci' has transfer information */ +#define CIST_CLSRET (1<<9) /* function is closing tbc variables */ +/* Bits 10-12 are used for CIST_RECST (see below) */ +#define CIST_RECST 10 +#if defined(LUA_COMPAT_LT_LE) +#define CIST_LEQ (1<<13) /* using __lt for __le */ +#endif + + +/* +** Field CIST_RECST stores the "recover status", used to keep the error +** status while closing to-be-closed variables in coroutines, so that +** Lua can correctly resume after an yield from a __close method called +** because of an error. (Three bits are enough for error status.) +*/ +#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7) +#define setcistrecst(ci,st) \ + check_exp(((st) & 7) == (st), /* status must fit in three bits */ \ + ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \ + | ((st) << CIST_RECST))) + + +/* active function is a Lua function */ +#define isLua(ci) (!((ci)->callstatus & CIST_C)) + +/* call is running Lua code (not a hook) */ +#define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED))) + +/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */ +#define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v)) +#define getoah(st) ((st) & CIST_OAH) + + +/* +** 'global state', shared by all threads of this state +*/ +typedef struct global_State { + lua_Alloc frealloc; /* function to reallocate memory */ + void *ud; /* auxiliary data to 'frealloc' */ + l_mem totalbytes; /* number of bytes currently allocated - GCdebt */ + l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ + lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ + lu_mem lastatomic; /* see function 'genstep' in file 'lgc.c' */ + stringtable strt; /* hash table for strings */ + TValue l_registry; + TValue nilvalue; /* a nil value */ + unsigned int seed; /* randomized seed for hashes */ + lu_byte currentwhite; + lu_byte gcstate; /* state of garbage collector */ + lu_byte gckind; /* kind of GC running */ + lu_byte gcstopem; /* stops emergency collections */ + lu_byte genminormul; /* control for minor generational collections */ + lu_byte genmajormul; /* control for major generational collections */ + lu_byte gcstp; /* control whether GC is running */ + lu_byte gcemergency; /* true if this is an emergency collection */ + lu_byte gcpause; /* size of pause between successive GCs */ + lu_byte gcstepmul; /* GC "speed" */ + lu_byte gcstepsize; /* (log2 of) GC granularity */ + GCObject *allgc; /* list of all collectable objects */ + GCObject **sweepgc; /* current position of sweep in list */ + GCObject *finobj; /* list of collectable objects with finalizers */ + GCObject *gray; /* list of gray objects */ + GCObject *grayagain; /* list of objects to be traversed atomically */ + GCObject *weak; /* list of tables with weak values */ + GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ + GCObject *allweak; /* list of all-weak tables */ + GCObject *tobefnz; /* list of userdata to be GC */ + GCObject *fixedgc; /* list of objects not to be collected */ + /* fields for generational collector */ + GCObject *survival; /* start of objects that survived one GC cycle */ + GCObject *old1; /* start of old1 objects */ + GCObject *reallyold; /* objects more than one cycle old ("really old") */ + GCObject *firstold1; /* first OLD1 object in the list (if any) */ + GCObject *finobjsur; /* list of survival objects with finalizers */ + GCObject *finobjold1; /* list of old1 objects with finalizers */ + GCObject *finobjrold; /* list of really old objects with finalizers */ + struct lua_State *twups; /* list of threads with open upvalues */ + lua_CFunction panic; /* to be called in unprotected errors */ + struct lua_State *mainthread; + TString *memerrmsg; /* message for memory-allocation errors */ + TString *tmname[TM_N]; /* array with tag-method names */ + struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */ + TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */ + lua_WarnFunction warnf; /* warning function */ + void *ud_warn; /* auxiliary data to 'warnf' */ +} global_State; + + +/* +** 'per thread' state +*/ +struct lua_State { + CommonHeader; + lu_byte status; + lu_byte allowhook; + unsigned short nci; /* number of items in 'ci' list */ + StkIdRel top; /* first free slot in the stack */ + global_State *l_G; + CallInfo *ci; /* call info for current function */ + StkIdRel stack_last; /* end of stack (last element + 1) */ + StkIdRel stack; /* stack base */ + UpVal *openupval; /* list of open upvalues in this stack */ + StkIdRel tbclist; /* list of to-be-closed variables */ + GCObject *gclist; + struct lua_State *twups; /* list of threads with open upvalues */ + struct lua_longjmp *errorJmp; /* current error recover point */ + CallInfo base_ci; /* CallInfo for first level (C calling Lua) */ + volatile lua_Hook hook; + ptrdiff_t errfunc; /* current error handling function (stack index) */ + l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */ + int oldpc; /* last pc traced */ + int basehookcount; + int hookcount; + volatile l_signalT hookmask; +}; + + +#define G(L) (L->l_G) + +/* +** 'g->nilvalue' being a nil value flags that the state was completely +** build. +*/ +#define completestate(g) ttisnil(&g->nilvalue) + + +/* +** Union of all collectable objects (only for conversions) +** ISO C99, 6.5.2.3 p.5: +** "if a union contains several structures that share a common initial +** sequence [...], and if the union object currently contains one +** of these structures, it is permitted to inspect the common initial +** part of any of them anywhere that a declaration of the complete type +** of the union is visible." +*/ +union GCUnion { + GCObject gc; /* common header */ + struct TString ts; + struct Udata u; + union Closure cl; + struct Table h; + struct Proto p; + struct lua_State th; /* thread */ + struct UpVal upv; +}; + + +/* +** ISO C99, 6.7.2.1 p.14: +** "A pointer to a union object, suitably converted, points to each of +** its members [...], and vice versa." +*/ +#define cast_u(o) cast(union GCUnion *, (o)) + +/* macros to convert a GCObject into a specific value */ +#define gco2ts(o) \ + check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts)) +#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u)) +#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l)) +#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c)) +#define gco2cl(o) \ + check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl)) +#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h)) +#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p)) +#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th)) +#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv)) + + +/* +** macro to convert a Lua object into a GCObject +** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.) +*/ +#define obj2gco(v) check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc)) + + +/* actual number of total bytes allocated */ +#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt) + +LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); +LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); +LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); +LUAI_FUNC void luaE_freeCI (lua_State *L); +LUAI_FUNC void luaE_shrinkCI (lua_State *L); +LUAI_FUNC void luaE_checkcstack (lua_State *L); +LUAI_FUNC void luaE_incCstack (lua_State *L); +LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont); +LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where); +LUAI_FUNC int luaE_resetthread (lua_State *L, int status); + + +#endif + diff --git a/src/libs/3rdparty/lua/src/lstring.c b/src/libs/3rdparty/lua/src/lstring.c new file mode 100644 index 00000000000..13dcaf4259b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lstring.c @@ -0,0 +1,273 @@ +/* +** $Id: lstring.c $ +** String table (keeps all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + +#define lstring_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" + + +/* +** Maximum size for string table. +*/ +#define MAXSTRTB cast_int(luaM_limitN(MAX_INT, TString*)) + + +/* +** equality for long strings +*/ +int luaS_eqlngstr (TString *a, TString *b) { + size_t len = a->u.lnglen; + lua_assert(a->tt == LUA_VLNGSTR && b->tt == LUA_VLNGSTR); + return (a == b) || /* same instance or... */ + ((len == b->u.lnglen) && /* equal length and ... */ + (memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */ +} + + +unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { + unsigned int h = seed ^ cast_uint(l); + for (; l > 0; l--) + h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1])); + return h; +} + + +unsigned int luaS_hashlongstr (TString *ts) { + lua_assert(ts->tt == LUA_VLNGSTR); + if (ts->extra == 0) { /* no hash? */ + size_t len = ts->u.lnglen; + ts->hash = luaS_hash(getstr(ts), len, ts->hash); + ts->extra = 1; /* now it has its hash */ + } + return ts->hash; +} + + +static void tablerehash (TString **vect, int osize, int nsize) { + int i; + for (i = osize; i < nsize; i++) /* clear new elements */ + vect[i] = NULL; + for (i = 0; i < osize; i++) { /* rehash old part of the array */ + TString *p = vect[i]; + vect[i] = NULL; + while (p) { /* for each string in the list */ + TString *hnext = p->u.hnext; /* save next */ + unsigned int h = lmod(p->hash, nsize); /* new position */ + p->u.hnext = vect[h]; /* chain it into array */ + vect[h] = p; + p = hnext; + } + } +} + + +/* +** Resize the string table. If allocation fails, keep the current size. +** (This can degrade performance, but any non-zero size should work +** correctly.) +*/ +void luaS_resize (lua_State *L, int nsize) { + stringtable *tb = &G(L)->strt; + int osize = tb->size; + TString **newvect; + if (nsize < osize) /* shrinking table? */ + tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */ + newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*); + if (l_unlikely(newvect == NULL)) { /* reallocation failed? */ + if (nsize < osize) /* was it shrinking table? */ + tablerehash(tb->hash, nsize, osize); /* restore to original size */ + /* leave table as it was */ + } + else { /* allocation succeeded */ + tb->hash = newvect; + tb->size = nsize; + if (nsize > osize) + tablerehash(newvect, osize, nsize); /* rehash for new size */ + } +} + + +/* +** Clear API string cache. (Entries cannot be empty, so fill them with +** a non-collectable string.) +*/ +void luaS_clearcache (global_State *g) { + int i, j; + for (i = 0; i < STRCACHE_N; i++) + for (j = 0; j < STRCACHE_M; j++) { + if (iswhite(g->strcache[i][j])) /* will entry be collected? */ + g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */ + } +} + + +/* +** Initialize the string table and the string cache +*/ +void luaS_init (lua_State *L) { + global_State *g = G(L); + int i, j; + stringtable *tb = &G(L)->strt; + tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*); + tablerehash(tb->hash, 0, MINSTRTABSIZE); /* clear array */ + tb->size = MINSTRTABSIZE; + /* pre-create memory-error message */ + g->memerrmsg = luaS_newliteral(L, MEMERRMSG); + luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */ + for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */ + for (j = 0; j < STRCACHE_M; j++) + g->strcache[i][j] = g->memerrmsg; +} + + + +/* +** creates a new string object +*/ +static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) { + TString *ts; + GCObject *o; + size_t totalsize; /* total size of TString object */ + totalsize = sizelstring(l); + o = luaC_newobj(L, tag, totalsize); + ts = gco2ts(o); + ts->hash = h; + ts->extra = 0; + getstr(ts)[l] = '\0'; /* ending 0 */ + return ts; +} + + +TString *luaS_createlngstrobj (lua_State *L, size_t l) { + TString *ts = createstrobj(L, l, LUA_VLNGSTR, G(L)->seed); + ts->u.lnglen = l; + return ts; +} + + +void luaS_remove (lua_State *L, TString *ts) { + stringtable *tb = &G(L)->strt; + TString **p = &tb->hash[lmod(ts->hash, tb->size)]; + while (*p != ts) /* find previous element */ + p = &(*p)->u.hnext; + *p = (*p)->u.hnext; /* remove element from its list */ + tb->nuse--; +} + + +static void growstrtab (lua_State *L, stringtable *tb) { + if (l_unlikely(tb->nuse == MAX_INT)) { /* too many strings? */ + luaC_fullgc(L, 1); /* try to free some... */ + if (tb->nuse == MAX_INT) /* still too many? */ + luaM_error(L); /* cannot even create a message... */ + } + if (tb->size <= MAXSTRTB / 2) /* can grow string table? */ + luaS_resize(L, tb->size * 2); +} + + +/* +** Checks whether short string exists and reuses it or creates a new one. +*/ +static TString *internshrstr (lua_State *L, const char *str, size_t l) { + TString *ts; + global_State *g = G(L); + stringtable *tb = &g->strt; + unsigned int h = luaS_hash(str, l, g->seed); + TString **list = &tb->hash[lmod(h, tb->size)]; + lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */ + for (ts = *list; ts != NULL; ts = ts->u.hnext) { + if (l == ts->shrlen && (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) { + /* found! */ + if (isdead(g, ts)) /* dead (but not collected yet)? */ + changewhite(ts); /* resurrect it */ + return ts; + } + } + /* else must create a new string */ + if (tb->nuse >= tb->size) { /* need to grow string table? */ + growstrtab(L, tb); + list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */ + } + ts = createstrobj(L, l, LUA_VSHRSTR, h); + memcpy(getstr(ts), str, l * sizeof(char)); + ts->shrlen = cast_byte(l); + ts->u.hnext = *list; + *list = ts; + tb->nuse++; + return ts; +} + + +/* +** new string (with explicit length) +*/ +TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { + if (l <= LUAI_MAXSHORTLEN) /* short string? */ + return internshrstr(L, str, l); + else { + TString *ts; + if (l_unlikely(l >= (MAX_SIZE - sizeof(TString))/sizeof(char))) + luaM_toobig(L); + ts = luaS_createlngstrobj(L, l); + memcpy(getstr(ts), str, l * sizeof(char)); + return ts; + } +} + + +/* +** Create or reuse a zero-terminated string, first checking in the +** cache (using the string address as a key). The cache can contain +** only zero-terminated strings, so it is safe to use 'strcmp' to +** check hits. +*/ +TString *luaS_new (lua_State *L, const char *str) { + unsigned int i = point2uint(str) % STRCACHE_N; /* hash */ + int j; + TString **p = G(L)->strcache[i]; + for (j = 0; j < STRCACHE_M; j++) { + if (strcmp(str, getstr(p[j])) == 0) /* hit? */ + return p[j]; /* that is it */ + } + /* normal route */ + for (j = STRCACHE_M - 1; j > 0; j--) + p[j] = p[j - 1]; /* move out last element */ + /* new element is first in the list */ + p[0] = luaS_newlstr(L, str, strlen(str)); + return p[0]; +} + + +Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue) { + Udata *u; + int i; + GCObject *o; + if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue))) + luaM_toobig(L); + o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s)); + u = gco2u(o); + u->len = s; + u->nuvalue = nuvalue; + u->metatable = NULL; + for (i = 0; i < nuvalue; i++) + setnilvalue(&u->uv[i].uv); + return u; +} + diff --git a/src/libs/3rdparty/lua/src/lstring.h b/src/libs/3rdparty/lua/src/lstring.h new file mode 100644 index 00000000000..450c2390d1b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lstring.h @@ -0,0 +1,57 @@ +/* +** $Id: lstring.h $ +** String table (keep all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + +#ifndef lstring_h +#define lstring_h + +#include "lgc.h" +#include "lobject.h" +#include "lstate.h" + + +/* +** Memory-allocation error message must be preallocated (it cannot +** be created after memory is exhausted) +*/ +#define MEMERRMSG "not enough memory" + + +/* +** Size of a TString: Size of the header plus space for the string +** itself (including final '\0'). +*/ +#define sizelstring(l) (offsetof(TString, contents) + ((l) + 1) * sizeof(char)) + +#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ + (sizeof(s)/sizeof(char))-1)) + + +/* +** test whether a string is a reserved word +*/ +#define isreserved(s) ((s)->tt == LUA_VSHRSTR && (s)->extra > 0) + + +/* +** equality for short strings, which are always internalized +*/ +#define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b)) + + +LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); +LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts); +LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); +LUAI_FUNC void luaS_resize (lua_State *L, int newsize); +LUAI_FUNC void luaS_clearcache (global_State *g); +LUAI_FUNC void luaS_init (lua_State *L); +LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); +LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue); +LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); +LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); +LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lstrlib.c b/src/libs/3rdparty/lua/src/lstrlib.c new file mode 100644 index 00000000000..03167161df1 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lstrlib.c @@ -0,0 +1,1874 @@ +/* +** $Id: lstrlib.c $ +** Standard library for string operations and pattern-matching +** See Copyright Notice in lua.h +*/ + +#define lstrlib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** maximum number of captures that a pattern can do during +** pattern-matching. This limit is arbitrary, but must fit in +** an unsigned char. +*/ +#if !defined(LUA_MAXCAPTURES) +#define LUA_MAXCAPTURES 32 +#endif + + +/* macro to 'unsign' a character */ +#define uchar(c) ((unsigned char)(c)) + + +/* +** Some sizes are better limited to fit in 'int', but must also fit in +** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) +*/ +#define MAX_SIZET ((size_t)(~(size_t)0)) + +#define MAXSIZE \ + (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) + + + + +static int str_len (lua_State *L) { + size_t l; + luaL_checklstring(L, 1, &l); + lua_pushinteger(L, (lua_Integer)l); + return 1; +} + + +/* +** translate a relative initial string position +** (negative means back from end): clip result to [1, inf). +** The length of any string in Lua must fit in a lua_Integer, +** so there are no overflows in the casts. +** The inverted comparison avoids a possible overflow +** computing '-pos'. +*/ +static size_t posrelatI (lua_Integer pos, size_t len) { + if (pos > 0) + return (size_t)pos; + else if (pos == 0) + return 1; + else if (pos < -(lua_Integer)len) /* inverted comparison */ + return 1; /* clip to 1 */ + else return len + (size_t)pos + 1; +} + + +/* +** Gets an optional ending string position from argument 'arg', +** with default value 'def'. +** Negative means back from end: clip result to [0, len] +*/ +static size_t getendpos (lua_State *L, int arg, lua_Integer def, + size_t len) { + lua_Integer pos = luaL_optinteger(L, arg, def); + if (pos > (lua_Integer)len) + return len; + else if (pos >= 0) + return (size_t)pos; + else if (pos < -(lua_Integer)len) + return 0; + else return len + (size_t)pos + 1; +} + + +static int str_sub (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + size_t start = posrelatI(luaL_checkinteger(L, 2), l); + size_t end = getendpos(L, 3, -1, l); + if (start <= end) + lua_pushlstring(L, s + start - 1, (end - start) + 1); + else lua_pushliteral(L, ""); + return 1; +} + + +static int str_reverse (lua_State *L) { + size_t l, i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i = 0; i < l; i++) + p[i] = s[l - i - 1]; + luaL_pushresultsize(&b, l); + return 1; +} + + +static int str_lower (lua_State *L) { + size_t l; + size_t i; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + char *p = luaL_buffinitsize(L, &b, l); + for (i=0; i MAXSIZE / n)) + return luaL_error(L, "resulting string too large"); + else { + size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; + luaL_Buffer b; + char *p = luaL_buffinitsize(L, &b, totallen); + while (n-- > 1) { /* first n-1 copies (followed by separator) */ + memcpy(p, s, l * sizeof(char)); p += l; + if (lsep > 0) { /* empty 'memcpy' is not that cheap */ + memcpy(p, sep, lsep * sizeof(char)); + p += lsep; + } + } + memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ + luaL_pushresultsize(&b, totallen); + } + return 1; +} + + +static int str_byte (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + lua_Integer pi = luaL_optinteger(L, 2, 1); + size_t posi = posrelatI(pi, l); + size_t pose = getendpos(L, 3, pi, l); + int n, i; + if (posi > pose) return 0; /* empty interval; return no values */ + if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */ + return luaL_error(L, "string slice too long"); + n = (int)(pose - posi) + 1; + luaL_checkstack(L, n, "string slice too long"); + for (i=0; iinit) { + state->init = 1; + luaL_buffinit(L, &state->B); + } + luaL_addlstring(&state->B, (const char *)b, size); + return 0; +} + + +static int str_dump (lua_State *L) { + struct str_Writer state; + int strip = lua_toboolean(L, 2); + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, 1); /* ensure function is on the top of the stack */ + state.init = 0; + if (l_unlikely(lua_dump(L, writer, &state, strip) != 0)) + return luaL_error(L, "unable to dump given function"); + luaL_pushresult(&state.B); + return 1; +} + + + +/* +** {====================================================== +** METAMETHODS +** ======================================================= +*/ + +#if defined(LUA_NOCVTS2N) /* { */ + +/* no coercion from strings to numbers */ + +static const luaL_Reg stringmetamethods[] = { + {"__index", NULL}, /* placeholder */ + {NULL, NULL} +}; + +#else /* }{ */ + +static int tonum (lua_State *L, int arg) { + if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */ + lua_pushvalue(L, arg); + return 1; + } + else { /* check whether it is a numerical string */ + size_t len; + const char *s = lua_tolstring(L, arg, &len); + return (s != NULL && lua_stringtonumber(L, s) == len + 1); + } +} + + +static void trymt (lua_State *L, const char *mtname) { + lua_settop(L, 2); /* back to the original arguments */ + if (l_unlikely(lua_type(L, 2) == LUA_TSTRING || + !luaL_getmetafield(L, 2, mtname))) + luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2, + luaL_typename(L, -2), luaL_typename(L, -1)); + lua_insert(L, -3); /* put metamethod before arguments */ + lua_call(L, 2, 1); /* call metamethod */ +} + + +static int arith (lua_State *L, int op, const char *mtname) { + if (tonum(L, 1) && tonum(L, 2)) + lua_arith(L, op); /* result will be on the top */ + else + trymt(L, mtname); + return 1; +} + + +static int arith_add (lua_State *L) { + return arith(L, LUA_OPADD, "__add"); +} + +static int arith_sub (lua_State *L) { + return arith(L, LUA_OPSUB, "__sub"); +} + +static int arith_mul (lua_State *L) { + return arith(L, LUA_OPMUL, "__mul"); +} + +static int arith_mod (lua_State *L) { + return arith(L, LUA_OPMOD, "__mod"); +} + +static int arith_pow (lua_State *L) { + return arith(L, LUA_OPPOW, "__pow"); +} + +static int arith_div (lua_State *L) { + return arith(L, LUA_OPDIV, "__div"); +} + +static int arith_idiv (lua_State *L) { + return arith(L, LUA_OPIDIV, "__idiv"); +} + +static int arith_unm (lua_State *L) { + return arith(L, LUA_OPUNM, "__unm"); +} + + +static const luaL_Reg stringmetamethods[] = { + {"__add", arith_add}, + {"__sub", arith_sub}, + {"__mul", arith_mul}, + {"__mod", arith_mod}, + {"__pow", arith_pow}, + {"__div", arith_div}, + {"__idiv", arith_idiv}, + {"__unm", arith_unm}, + {"__index", NULL}, /* placeholder */ + {NULL, NULL} +}; + +#endif /* } */ + +/* }====================================================== */ + +/* +** {====================================================== +** PATTERN MATCHING +** ======================================================= +*/ + + +#define CAP_UNFINISHED (-1) +#define CAP_POSITION (-2) + + +typedef struct MatchState { + const char *src_init; /* init of source string */ + const char *src_end; /* end ('\0') of source string */ + const char *p_end; /* end ('\0') of pattern */ + lua_State *L; + int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ + unsigned char level; /* total number of captures (finished or unfinished) */ + struct { + const char *init; + ptrdiff_t len; + } capture[LUA_MAXCAPTURES]; +} MatchState; + + +/* recursive function */ +static const char *match (MatchState *ms, const char *s, const char *p); + + +/* maximum recursion depth for 'match' */ +#if !defined(MAXCCALLS) +#define MAXCCALLS 200 +#endif + + +#define L_ESC '%' +#define SPECIALS "^$*+?.([%-" + + +static int check_capture (MatchState *ms, int l) { + l -= '1'; + if (l_unlikely(l < 0 || l >= ms->level || + ms->capture[l].len == CAP_UNFINISHED)) + return luaL_error(ms->L, "invalid capture index %%%d", l + 1); + return l; +} + + +static int capture_to_close (MatchState *ms) { + int level = ms->level; + for (level--; level>=0; level--) + if (ms->capture[level].len == CAP_UNFINISHED) return level; + return luaL_error(ms->L, "invalid pattern capture"); +} + + +static const char *classend (MatchState *ms, const char *p) { + switch (*p++) { + case L_ESC: { + if (l_unlikely(p == ms->p_end)) + luaL_error(ms->L, "malformed pattern (ends with '%%')"); + return p+1; + } + case '[': { + if (*p == '^') p++; + do { /* look for a ']' */ + if (l_unlikely(p == ms->p_end)) + luaL_error(ms->L, "malformed pattern (missing ']')"); + if (*(p++) == L_ESC && p < ms->p_end) + p++; /* skip escapes (e.g. '%]') */ + } while (*p != ']'); + return p+1; + } + default: { + return p; + } + } +} + + +static int match_class (int c, int cl) { + int res; + switch (tolower(cl)) { + case 'a' : res = isalpha(c); break; + case 'c' : res = iscntrl(c); break; + case 'd' : res = isdigit(c); break; + case 'g' : res = isgraph(c); break; + case 'l' : res = islower(c); break; + case 'p' : res = ispunct(c); break; + case 's' : res = isspace(c); break; + case 'u' : res = isupper(c); break; + case 'w' : res = isalnum(c); break; + case 'x' : res = isxdigit(c); break; + case 'z' : res = (c == 0); break; /* deprecated option */ + default: return (cl == c); + } + return (islower(cl) ? res : !res); +} + + +static int matchbracketclass (int c, const char *p, const char *ec) { + int sig = 1; + if (*(p+1) == '^') { + sig = 0; + p++; /* skip the '^' */ + } + while (++p < ec) { + if (*p == L_ESC) { + p++; + if (match_class(c, uchar(*p))) + return sig; + } + else if ((*(p+1) == '-') && (p+2 < ec)) { + p+=2; + if (uchar(*(p-2)) <= c && c <= uchar(*p)) + return sig; + } + else if (uchar(*p) == c) return sig; + } + return !sig; +} + + +static int singlematch (MatchState *ms, const char *s, const char *p, + const char *ep) { + if (s >= ms->src_end) + return 0; + else { + int c = uchar(*s); + switch (*p) { + case '.': return 1; /* matches any char */ + case L_ESC: return match_class(c, uchar(*(p+1))); + case '[': return matchbracketclass(c, p, ep-1); + default: return (uchar(*p) == c); + } + } +} + + +static const char *matchbalance (MatchState *ms, const char *s, + const char *p) { + if (l_unlikely(p >= ms->p_end - 1)) + luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); + if (*s != *p) return NULL; + else { + int b = *p; + int e = *(p+1); + int cont = 1; + while (++s < ms->src_end) { + if (*s == e) { + if (--cont == 0) return s+1; + } + else if (*s == b) cont++; + } + } + return NULL; /* string ends out of balance */ +} + + +static const char *max_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + ptrdiff_t i = 0; /* counts maximum expand for item */ + while (singlematch(ms, s + i, p, ep)) + i++; + /* keeps trying to match with the maximum repetitions */ + while (i>=0) { + const char *res = match(ms, (s+i), ep+1); + if (res) return res; + i--; /* else didn't match; reduce 1 repetition to try again */ + } + return NULL; +} + + +static const char *min_expand (MatchState *ms, const char *s, + const char *p, const char *ep) { + for (;;) { + const char *res = match(ms, s, ep+1); + if (res != NULL) + return res; + else if (singlematch(ms, s, p, ep)) + s++; /* try with one more repetition */ + else return NULL; + } +} + + +static const char *start_capture (MatchState *ms, const char *s, + const char *p, int what) { + const char *res; + int level = ms->level; + if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); + ms->capture[level].init = s; + ms->capture[level].len = what; + ms->level = level+1; + if ((res=match(ms, s, p)) == NULL) /* match failed? */ + ms->level--; /* undo capture */ + return res; +} + + +static const char *end_capture (MatchState *ms, const char *s, + const char *p) { + int l = capture_to_close(ms); + const char *res; + ms->capture[l].len = s - ms->capture[l].init; /* close capture */ + if ((res = match(ms, s, p)) == NULL) /* match failed? */ + ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ + return res; +} + + +static const char *match_capture (MatchState *ms, const char *s, int l) { + size_t len; + l = check_capture(ms, l); + len = ms->capture[l].len; + if ((size_t)(ms->src_end-s) >= len && + memcmp(ms->capture[l].init, s, len) == 0) + return s+len; + else return NULL; +} + + +static const char *match (MatchState *ms, const char *s, const char *p) { + if (l_unlikely(ms->matchdepth-- == 0)) + luaL_error(ms->L, "pattern too complex"); + init: /* using goto to optimize tail recursion */ + if (p != ms->p_end) { /* end of pattern? */ + switch (*p) { + case '(': { /* start capture */ + if (*(p + 1) == ')') /* position capture? */ + s = start_capture(ms, s, p + 2, CAP_POSITION); + else + s = start_capture(ms, s, p + 1, CAP_UNFINISHED); + break; + } + case ')': { /* end capture */ + s = end_capture(ms, s, p + 1); + break; + } + case '$': { + if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ + goto dflt; /* no; go to default */ + s = (s == ms->src_end) ? s : NULL; /* check end of string */ + break; + } + case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ + switch (*(p + 1)) { + case 'b': { /* balanced string? */ + s = matchbalance(ms, s, p + 2); + if (s != NULL) { + p += 4; goto init; /* return match(ms, s, p + 4); */ + } /* else fail (s == NULL) */ + break; + } + case 'f': { /* frontier? */ + const char *ep; char previous; + p += 2; + if (l_unlikely(*p != '[')) + luaL_error(ms->L, "missing '[' after '%%f' in pattern"); + ep = classend(ms, p); /* points to what is next */ + previous = (s == ms->src_init) ? '\0' : *(s - 1); + if (!matchbracketclass(uchar(previous), p, ep - 1) && + matchbracketclass(uchar(*s), p, ep - 1)) { + p = ep; goto init; /* return match(ms, s, ep); */ + } + s = NULL; /* match failed */ + break; + } + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': { /* capture results (%0-%9)? */ + s = match_capture(ms, s, uchar(*(p + 1))); + if (s != NULL) { + p += 2; goto init; /* return match(ms, s, p + 2) */ + } + break; + } + default: goto dflt; + } + break; + } + default: dflt: { /* pattern class plus optional suffix */ + const char *ep = classend(ms, p); /* points to optional suffix */ + /* does not match at least once? */ + if (!singlematch(ms, s, p, ep)) { + if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ + p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ + } + else /* '+' or no suffix */ + s = NULL; /* fail */ + } + else { /* matched once */ + switch (*ep) { /* handle optional suffix */ + case '?': { /* optional */ + const char *res; + if ((res = match(ms, s + 1, ep + 1)) != NULL) + s = res; + else { + p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ + } + break; + } + case '+': /* 1 or more repetitions */ + s++; /* 1 match already done */ + /* FALLTHROUGH */ + case '*': /* 0 or more repetitions */ + s = max_expand(ms, s, p, ep); + break; + case '-': /* 0 or more repetitions (minimum) */ + s = min_expand(ms, s, p, ep); + break; + default: /* no suffix */ + s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ + } + } + break; + } + } + } + ms->matchdepth++; + return s; +} + + + +static const char *lmemfind (const char *s1, size_t l1, + const char *s2, size_t l2) { + if (l2 == 0) return s1; /* empty strings are everywhere */ + else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ + else { + const char *init; /* to search for a '*s2' inside 's1' */ + l2--; /* 1st char will be checked by 'memchr' */ + l1 = l1-l2; /* 's2' cannot be found after that */ + while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { + init++; /* 1st char is already checked */ + if (memcmp(init, s2+1, l2) == 0) + return init-1; + else { /* correct 'l1' and 's1' to try again */ + l1 -= init-s1; + s1 = init; + } + } + return NULL; /* not found */ + } +} + + +/* +** get information about the i-th capture. If there are no captures +** and 'i==0', return information about the whole match, which +** is the range 's'..'e'. If the capture is a string, return +** its length and put its address in '*cap'. If it is an integer +** (a position), push it on the stack and return CAP_POSITION. +*/ +static size_t get_onecapture (MatchState *ms, int i, const char *s, + const char *e, const char **cap) { + if (i >= ms->level) { + if (l_unlikely(i != 0)) + luaL_error(ms->L, "invalid capture index %%%d", i + 1); + *cap = s; + return e - s; + } + else { + ptrdiff_t capl = ms->capture[i].len; + *cap = ms->capture[i].init; + if (l_unlikely(capl == CAP_UNFINISHED)) + luaL_error(ms->L, "unfinished capture"); + else if (capl == CAP_POSITION) + lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); + return capl; + } +} + + +/* +** Push the i-th capture on the stack. +*/ +static void push_onecapture (MatchState *ms, int i, const char *s, + const char *e) { + const char *cap; + ptrdiff_t l = get_onecapture(ms, i, s, e, &cap); + if (l != CAP_POSITION) + lua_pushlstring(ms->L, cap, l); + /* else position was already pushed */ +} + + +static int push_captures (MatchState *ms, const char *s, const char *e) { + int i; + int nlevels = (ms->level == 0 && s) ? 1 : ms->level; + luaL_checkstack(ms->L, nlevels, "too many captures"); + for (i = 0; i < nlevels; i++) + push_onecapture(ms, i, s, e); + return nlevels; /* number of strings pushed */ +} + + +/* check whether pattern has no special characters */ +static int nospecials (const char *p, size_t l) { + size_t upto = 0; + do { + if (strpbrk(p + upto, SPECIALS)) + return 0; /* pattern has a special character */ + upto += strlen(p + upto) + 1; /* may have more after \0 */ + } while (upto <= l); + return 1; /* no special chars found */ +} + + +static void prepstate (MatchState *ms, lua_State *L, + const char *s, size_t ls, const char *p, size_t lp) { + ms->L = L; + ms->matchdepth = MAXCCALLS; + ms->src_init = s; + ms->src_end = s + ls; + ms->p_end = p + lp; +} + + +static void reprepstate (MatchState *ms) { + ms->level = 0; + lua_assert(ms->matchdepth == MAXCCALLS); +} + + +static int str_find_aux (lua_State *L, int find) { + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; + if (init > ls) { /* start after string's end? */ + luaL_pushfail(L); /* cannot find anything */ + return 1; + } + /* explicit request or no special characters? */ + if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { + /* do a plain search */ + const char *s2 = lmemfind(s + init, ls - init, p, lp); + if (s2) { + lua_pushinteger(L, (s2 - s) + 1); + lua_pushinteger(L, (s2 - s) + lp); + return 2; + } + } + else { + MatchState ms; + const char *s1 = s + init; + int anchor = (*p == '^'); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + prepstate(&ms, L, s, ls, p, lp); + do { + const char *res; + reprepstate(&ms); + if ((res=match(&ms, s1, p)) != NULL) { + if (find) { + lua_pushinteger(L, (s1 - s) + 1); /* start */ + lua_pushinteger(L, res - s); /* end */ + return push_captures(&ms, NULL, 0) + 2; + } + else + return push_captures(&ms, s1, res); + } + } while (s1++ < ms.src_end && !anchor); + } + luaL_pushfail(L); /* not found */ + return 1; +} + + +static int str_find (lua_State *L) { + return str_find_aux(L, 1); +} + + +static int str_match (lua_State *L) { + return str_find_aux(L, 0); +} + + +/* state for 'gmatch' */ +typedef struct GMatchState { + const char *src; /* current position */ + const char *p; /* pattern */ + const char *lastmatch; /* end of last match */ + MatchState ms; /* match state */ +} GMatchState; + + +static int gmatch_aux (lua_State *L) { + GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); + const char *src; + gm->ms.L = L; + for (src = gm->src; src <= gm->ms.src_end; src++) { + const char *e; + reprepstate(&gm->ms); + if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) { + gm->src = gm->lastmatch = e; + return push_captures(&gm->ms, src, e); + } + } + return 0; /* not found */ +} + + +static int gmatch (lua_State *L) { + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; + GMatchState *gm; + lua_settop(L, 2); /* keep strings on closure to avoid being collected */ + gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0); + if (init > ls) /* start after string's end? */ + init = ls + 1; /* avoid overflows in 's + init' */ + prepstate(&gm->ms, L, s, ls, p, lp); + gm->src = s + init; gm->p = p; gm->lastmatch = NULL; + lua_pushcclosure(L, gmatch_aux, 3); + return 1; +} + + +static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e) { + size_t l; + lua_State *L = ms->L; + const char *news = lua_tolstring(L, 3, &l); + const char *p; + while ((p = (char *)memchr(news, L_ESC, l)) != NULL) { + luaL_addlstring(b, news, p - news); + p++; /* skip ESC */ + if (*p == L_ESC) /* '%%' */ + luaL_addchar(b, *p); + else if (*p == '0') /* '%0' */ + luaL_addlstring(b, s, e - s); + else if (isdigit(uchar(*p))) { /* '%n' */ + const char *cap; + ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap); + if (resl == CAP_POSITION) + luaL_addvalue(b); /* add position to accumulated result */ + else + luaL_addlstring(b, cap, resl); + } + else + luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); + l -= p + 1 - news; + news = p + 1; + } + luaL_addlstring(b, news, l); +} + + +/* +** Add the replacement value to the string buffer 'b'. +** Return true if the original string was changed. (Function calls and +** table indexing resulting in nil or false do not change the subject.) +*/ +static int add_value (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e, int tr) { + lua_State *L = ms->L; + switch (tr) { + case LUA_TFUNCTION: { /* call the function */ + int n; + lua_pushvalue(L, 3); /* push the function */ + n = push_captures(ms, s, e); /* all captures as arguments */ + lua_call(L, n, 1); /* call it */ + break; + } + case LUA_TTABLE: { /* index the table */ + push_onecapture(ms, 0, s, e); /* first capture is the index */ + lua_gettable(L, 3); + break; + } + default: { /* LUA_TNUMBER or LUA_TSTRING */ + add_s(ms, b, s, e); /* add value to the buffer */ + return 1; /* something changed */ + } + } + if (!lua_toboolean(L, -1)) { /* nil or false? */ + lua_pop(L, 1); /* remove value */ + luaL_addlstring(b, s, e - s); /* keep original text */ + return 0; /* no changes */ + } + else if (l_unlikely(!lua_isstring(L, -1))) + return luaL_error(L, "invalid replacement value (a %s)", + luaL_typename(L, -1)); + else { + luaL_addvalue(b); /* add result to accumulator */ + return 1; /* something changed */ + } +} + + +static int str_gsub (lua_State *L) { + size_t srcl, lp; + const char *src = luaL_checklstring(L, 1, &srcl); /* subject */ + const char *p = luaL_checklstring(L, 2, &lp); /* pattern */ + const char *lastmatch = NULL; /* end of last match */ + int tr = lua_type(L, 3); /* replacement type */ + lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */ + int anchor = (*p == '^'); + lua_Integer n = 0; /* replacement count */ + int changed = 0; /* change flag */ + MatchState ms; + luaL_Buffer b; + luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || + tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, + "string/function/table"); + luaL_buffinit(L, &b); + if (anchor) { + p++; lp--; /* skip anchor character */ + } + prepstate(&ms, L, src, srcl, p, lp); + while (n < max_s) { + const char *e; + reprepstate(&ms); /* (re)prepare state for new match */ + if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */ + n++; + changed = add_value(&ms, &b, src, e, tr) | changed; + src = lastmatch = e; + } + else if (src < ms.src_end) /* otherwise, skip one character */ + luaL_addchar(&b, *src++); + else break; /* end of subject */ + if (anchor) break; + } + if (!changed) /* no changes? */ + lua_pushvalue(L, 1); /* return original string */ + else { /* something changed */ + luaL_addlstring(&b, src, ms.src_end-src); + luaL_pushresult(&b); /* create and return new string */ + } + lua_pushinteger(L, n); /* number of substitutions */ + return 2; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** STRING FORMAT +** ======================================================= +*/ + +#if !defined(lua_number2strx) /* { */ + +/* +** Hexadecimal floating-point formatter +*/ + +#define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) + + +/* +** Number of bits that goes into the first digit. It can be any value +** between 1 and 4; the following definition tries to align the number +** to nibble boundaries by making what is left after that first digit a +** multiple of 4. +*/ +#define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1) + + +/* +** Add integer part of 'x' to buffer and return new 'x' +*/ +static lua_Number adddigit (char *buff, int n, lua_Number x) { + lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ + int d = (int)dd; + buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ + return x - dd; /* return what is left */ +} + + +static int num2straux (char *buff, int sz, lua_Number x) { + /* if 'inf' or 'NaN', format it like '%g' */ + if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL) + return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x); + else if (x == 0) { /* can be -0... */ + /* create "0" or "-0" followed by exponent */ + return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x); + } + else { + int e; + lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ + int n = 0; /* character count */ + if (m < 0) { /* is number negative? */ + buff[n++] = '-'; /* add sign */ + m = -m; /* make it positive */ + } + buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ + m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ + e -= L_NBFD; /* this digit goes before the radix point */ + if (m > 0) { /* more digits? */ + buff[n++] = lua_getlocaledecpoint(); /* add radix point */ + do { /* add as many digits as needed */ + m = adddigit(buff, n++, m * 16); + } while (m > 0); + } + n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ + lua_assert(n < sz); + return n; + } +} + + +static int lua_number2strx (lua_State *L, char *buff, int sz, + const char *fmt, lua_Number x) { + int n = num2straux(buff, sz, x); + if (fmt[SIZELENMOD] == 'A') { + int i; + for (i = 0; i < n; i++) + buff[i] = toupper(uchar(buff[i])); + } + else if (l_unlikely(fmt[SIZELENMOD] != 'a')) + return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); + return n; +} + +#endif /* } */ + + +/* +** Maximum size for items formatted with '%f'. This size is produced +** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', +** and '\0') + number of decimal digits to represent maxfloat (which +** is maximum exponent + 1). (99+3+1, adding some extra, 110) +*/ +#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP)) + + +/* +** All formats except '%f' do not need that large limit. The other +** float formats use exponents, so that they fit in the 99 limit for +** significant digits; 's' for large strings and 'q' add items directly +** to the buffer; all integer formats also fit in the 99 limit. The +** worst case are floats: they may need 99 significant digits, plus +** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120. +*/ +#define MAX_ITEM 120 + + +/* valid flags in a format specification */ +#if !defined(L_FMTFLAGSF) + +/* valid flags for a, A, e, E, f, F, g, and G conversions */ +#define L_FMTFLAGSF "-+#0 " + +/* valid flags for o, x, and X conversions */ +#define L_FMTFLAGSX "-#0" + +/* valid flags for d and i conversions */ +#define L_FMTFLAGSI "-+0 " + +/* valid flags for u conversions */ +#define L_FMTFLAGSU "-0" + +/* valid flags for c, p, and s conversions */ +#define L_FMTFLAGSC "-" + +#endif + + +/* +** Maximum size of each format specification (such as "%-099.99d"): +** Initial '%', flags (up to 5), width (2), period, precision (2), +** length modifier (8), conversion specifier, and final '\0', plus some +** extra. +*/ +#define MAX_FORMAT 32 + + +static void addquoted (luaL_Buffer *b, const char *s, size_t len) { + luaL_addchar(b, '"'); + while (len--) { + if (*s == '"' || *s == '\\' || *s == '\n') { + luaL_addchar(b, '\\'); + luaL_addchar(b, *s); + } + else if (iscntrl(uchar(*s))) { + char buff[10]; + if (!isdigit(uchar(*(s+1)))) + l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); + else + l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); + luaL_addstring(b, buff); + } + else + luaL_addchar(b, *s); + s++; + } + luaL_addchar(b, '"'); +} + + +/* +** Serialize a floating-point number in such a way that it can be +** scanned back by Lua. Use hexadecimal format for "common" numbers +** (to preserve precision); inf, -inf, and NaN are handled separately. +** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.) +*/ +static int quotefloat (lua_State *L, char *buff, lua_Number n) { + const char *s; /* for the fixed representations */ + if (n == (lua_Number)HUGE_VAL) /* inf? */ + s = "1e9999"; + else if (n == -(lua_Number)HUGE_VAL) /* -inf? */ + s = "-1e9999"; + else if (n != n) /* NaN? */ + s = "(0/0)"; + else { /* format number as hexadecimal */ + int nb = lua_number2strx(L, buff, MAX_ITEM, + "%" LUA_NUMBER_FRMLEN "a", n); + /* ensures that 'buff' string uses a dot as the radix character */ + if (memchr(buff, '.', nb) == NULL) { /* no dot? */ + char point = lua_getlocaledecpoint(); /* try locale point */ + char *ppoint = (char *)memchr(buff, point, nb); + if (ppoint) *ppoint = '.'; /* change it to a dot */ + } + return nb; + } + /* for the fixed representations */ + return l_sprintf(buff, MAX_ITEM, "%s", s); +} + + +static void addliteral (lua_State *L, luaL_Buffer *b, int arg) { + switch (lua_type(L, arg)) { + case LUA_TSTRING: { + size_t len; + const char *s = lua_tolstring(L, arg, &len); + addquoted(b, s, len); + break; + } + case LUA_TNUMBER: { + char *buff = luaL_prepbuffsize(b, MAX_ITEM); + int nb; + if (!lua_isinteger(L, arg)) /* float? */ + nb = quotefloat(L, buff, lua_tonumber(L, arg)); + else { /* integers */ + lua_Integer n = lua_tointeger(L, arg); + const char *format = (n == LUA_MININTEGER) /* corner case? */ + ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */ + : LUA_INTEGER_FMT; /* else use default format */ + nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n); + } + luaL_addsize(b, nb); + break; + } + case LUA_TNIL: case LUA_TBOOLEAN: { + luaL_tolstring(L, arg, NULL); + luaL_addvalue(b); + break; + } + default: { + luaL_argerror(L, arg, "value has no literal form"); + } + } +} + + +static const char *get2digits (const char *s) { + if (isdigit(uchar(*s))) { + s++; + if (isdigit(uchar(*s))) s++; /* (2 digits at most) */ + } + return s; +} + + +/* +** Check whether a conversion specification is valid. When called, +** first character in 'form' must be '%' and last character must +** be a valid conversion specifier. 'flags' are the accepted flags; +** 'precision' signals whether to accept a precision. +*/ +static void checkformat (lua_State *L, const char *form, const char *flags, + int precision) { + const char *spec = form + 1; /* skip '%' */ + spec += strspn(spec, flags); /* skip flags */ + if (*spec != '0') { /* a width cannot start with '0' */ + spec = get2digits(spec); /* skip width */ + if (*spec == '.' && precision) { + spec++; + spec = get2digits(spec); /* skip precision */ + } + } + if (!isalpha(uchar(*spec))) /* did not go to the end? */ + luaL_error(L, "invalid conversion specification: '%s'", form); +} + + +/* +** Get a conversion specification and copy it to 'form'. +** Return the address of its last character. +*/ +static const char *getformat (lua_State *L, const char *strfrmt, + char *form) { + /* spans flags, width, and precision ('0' is included as a flag) */ + size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789."); + len++; /* adds following character (should be the specifier) */ + /* still needs space for '%', '\0', plus a length modifier */ + if (len >= MAX_FORMAT - 10) + luaL_error(L, "invalid format (too long)"); + *(form++) = '%'; + memcpy(form, strfrmt, len * sizeof(char)); + *(form + len) = '\0'; + return strfrmt + len - 1; +} + + +/* +** add length modifier into formats +*/ +static void addlenmod (char *form, const char *lenmod) { + size_t l = strlen(form); + size_t lm = strlen(lenmod); + char spec = form[l - 1]; + strcpy(form + l - 1, lenmod); + form[l + lm - 1] = spec; + form[l + lm] = '\0'; +} + + +static int str_format (lua_State *L) { + int top = lua_gettop(L); + int arg = 1; + size_t sfl; + const char *strfrmt = luaL_checklstring(L, arg, &sfl); + const char *strfrmt_end = strfrmt+sfl; + const char *flags; + luaL_Buffer b; + luaL_buffinit(L, &b); + while (strfrmt < strfrmt_end) { + if (*strfrmt != L_ESC) + luaL_addchar(&b, *strfrmt++); + else if (*++strfrmt == L_ESC) + luaL_addchar(&b, *strfrmt++); /* %% */ + else { /* format item */ + char form[MAX_FORMAT]; /* to store the format ('%...') */ + int maxitem = MAX_ITEM; /* maximum length for the result */ + char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */ + int nb = 0; /* number of bytes in result */ + if (++arg > top) + return luaL_argerror(L, arg, "no value"); + strfrmt = getformat(L, strfrmt, form); + switch (*strfrmt++) { + case 'c': { + checkformat(L, form, L_FMTFLAGSC, 0); + nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg)); + break; + } + case 'd': case 'i': + flags = L_FMTFLAGSI; + goto intcase; + case 'u': + flags = L_FMTFLAGSU; + goto intcase; + case 'o': case 'x': case 'X': + flags = L_FMTFLAGSX; + intcase: { + lua_Integer n = luaL_checkinteger(L, arg); + checkformat(L, form, flags, 1); + addlenmod(form, LUA_INTEGER_FRMLEN); + nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n); + break; + } + case 'a': case 'A': + checkformat(L, form, L_FMTFLAGSF, 1); + addlenmod(form, LUA_NUMBER_FRMLEN); + nb = lua_number2strx(L, buff, maxitem, form, + luaL_checknumber(L, arg)); + break; + case 'f': + maxitem = MAX_ITEMF; /* extra space for '%f' */ + buff = luaL_prepbuffsize(&b, maxitem); + /* FALLTHROUGH */ + case 'e': case 'E': case 'g': case 'G': { + lua_Number n = luaL_checknumber(L, arg); + checkformat(L, form, L_FMTFLAGSF, 1); + addlenmod(form, LUA_NUMBER_FRMLEN); + nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n); + break; + } + case 'p': { + const void *p = lua_topointer(L, arg); + checkformat(L, form, L_FMTFLAGSC, 0); + if (p == NULL) { /* avoid calling 'printf' with argument NULL */ + p = "(null)"; /* result */ + form[strlen(form) - 1] = 's'; /* format it as a string */ + } + nb = l_sprintf(buff, maxitem, form, p); + break; + } + case 'q': { + if (form[2] != '\0') /* modifiers? */ + return luaL_error(L, "specifier '%%q' cannot have modifiers"); + addliteral(L, &b, arg); + break; + } + case 's': { + size_t l; + const char *s = luaL_tolstring(L, arg, &l); + if (form[2] == '\0') /* no modifiers? */ + luaL_addvalue(&b); /* keep entire string */ + else { + luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); + checkformat(L, form, L_FMTFLAGSC, 1); + if (strchr(form, '.') == NULL && l >= 100) { + /* no precision and string is too long to be formatted */ + luaL_addvalue(&b); /* keep entire string */ + } + else { /* format the string into 'buff' */ + nb = l_sprintf(buff, maxitem, form, s); + lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ + } + } + break; + } + default: { /* also treat cases 'pnLlh' */ + return luaL_error(L, "invalid conversion '%s' to 'format'", form); + } + } + lua_assert(nb < maxitem); + luaL_addsize(&b, nb); + } + } + luaL_pushresult(&b); + return 1; +} + +/* }====================================================== */ + + +/* +** {====================================================== +** PACK/UNPACK +** ======================================================= +*/ + + +/* value used for padding */ +#if !defined(LUAL_PACKPADBYTE) +#define LUAL_PACKPADBYTE 0x00 +#endif + +/* maximum size for the binary representation of an integer */ +#define MAXINTSIZE 16 + +/* number of bits in a character */ +#define NB CHAR_BIT + +/* mask for one character (NB 1's) */ +#define MC ((1 << NB) - 1) + +/* size of a lua_Integer */ +#define SZINT ((int)sizeof(lua_Integer)) + + +/* dummy union to get native endianness */ +static const union { + int dummy; + char little; /* true iff machine is little endian */ +} nativeendian = {1}; + + +/* +** information to pack/unpack stuff +*/ +typedef struct Header { + lua_State *L; + int islittle; + int maxalign; +} Header; + + +/* +** options for pack/unpack +*/ +typedef enum KOption { + Kint, /* signed integers */ + Kuint, /* unsigned integers */ + Kfloat, /* single-precision floating-point numbers */ + Knumber, /* Lua "native" floating-point numbers */ + Kdouble, /* double-precision floating-point numbers */ + Kchar, /* fixed-length strings */ + Kstring, /* strings with prefixed length */ + Kzstr, /* zero-terminated strings */ + Kpadding, /* padding */ + Kpaddalign, /* padding for alignment */ + Knop /* no-op (configuration or spaces) */ +} KOption; + + +/* +** Read an integer numeral from string 'fmt' or return 'df' if +** there is no numeral +*/ +static int digit (int c) { return '0' <= c && c <= '9'; } + +static int getnum (const char **fmt, int df) { + if (!digit(**fmt)) /* no number? */ + return df; /* return default value */ + else { + int a = 0; + do { + a = a*10 + (*((*fmt)++) - '0'); + } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); + return a; + } +} + + +/* +** Read an integer numeral and raises an error if it is larger +** than the maximum size for integers. +*/ +static int getnumlimit (Header *h, const char **fmt, int df) { + int sz = getnum(fmt, df); + if (l_unlikely(sz > MAXINTSIZE || sz <= 0)) + return luaL_error(h->L, "integral size (%d) out of limits [1,%d]", + sz, MAXINTSIZE); + return sz; +} + + +/* +** Initialize Header +*/ +static void initheader (lua_State *L, Header *h) { + h->L = L; + h->islittle = nativeendian.little; + h->maxalign = 1; +} + + +/* +** Read and classify next option. 'size' is filled with option's size. +*/ +static KOption getoption (Header *h, const char **fmt, int *size) { + /* dummy structure to get native alignment requirements */ + struct cD { char c; union { LUAI_MAXALIGN; } u; }; + int opt = *((*fmt)++); + *size = 0; /* default */ + switch (opt) { + case 'b': *size = sizeof(char); return Kint; + case 'B': *size = sizeof(char); return Kuint; + case 'h': *size = sizeof(short); return Kint; + case 'H': *size = sizeof(short); return Kuint; + case 'l': *size = sizeof(long); return Kint; + case 'L': *size = sizeof(long); return Kuint; + case 'j': *size = sizeof(lua_Integer); return Kint; + case 'J': *size = sizeof(lua_Integer); return Kuint; + case 'T': *size = sizeof(size_t); return Kuint; + case 'f': *size = sizeof(float); return Kfloat; + case 'n': *size = sizeof(lua_Number); return Knumber; + case 'd': *size = sizeof(double); return Kdouble; + case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; + case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; + case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; + case 'c': + *size = getnum(fmt, -1); + if (l_unlikely(*size == -1)) + luaL_error(h->L, "missing size for format option 'c'"); + return Kchar; + case 'z': return Kzstr; + case 'x': *size = 1; return Kpadding; + case 'X': return Kpaddalign; + case ' ': break; + case '<': h->islittle = 1; break; + case '>': h->islittle = 0; break; + case '=': h->islittle = nativeendian.little; break; + case '!': { + const int maxalign = offsetof(struct cD, u); + h->maxalign = getnumlimit(h, fmt, maxalign); + break; + } + default: luaL_error(h->L, "invalid format option '%c'", opt); + } + return Knop; +} + + +/* +** Read, classify, and fill other details about the next option. +** 'psize' is filled with option's size, 'notoalign' with its +** alignment requirements. +** Local variable 'size' gets the size to be aligned. (Kpadal option +** always gets its full alignment, other options are limited by +** the maximum alignment ('maxalign'). Kchar option needs no alignment +** despite its size. +*/ +static KOption getdetails (Header *h, size_t totalsize, + const char **fmt, int *psize, int *ntoalign) { + KOption opt = getoption(h, fmt, psize); + int align = *psize; /* usually, alignment follows size */ + if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ + if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) + luaL_argerror(h->L, 1, "invalid next option for option 'X'"); + } + if (align <= 1 || opt == Kchar) /* need no alignment? */ + *ntoalign = 0; + else { + if (align > h->maxalign) /* enforce maximum alignment */ + align = h->maxalign; + if (l_unlikely((align & (align - 1)) != 0)) /* not a power of 2? */ + luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); + *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); + } + return opt; +} + + +/* +** Pack integer 'n' with 'size' bytes and 'islittle' endianness. +** The final 'if' handles the case when 'size' is larger than +** the size of a Lua integer, correcting the extra sign-extension +** bytes if necessary (by default they would be zeros). +*/ +static void packint (luaL_Buffer *b, lua_Unsigned n, + int islittle, int size, int neg) { + char *buff = luaL_prepbuffsize(b, size); + int i; + buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ + for (i = 1; i < size; i++) { + n >>= NB; + buff[islittle ? i : size - 1 - i] = (char)(n & MC); + } + if (neg && size > SZINT) { /* negative number need sign extension? */ + for (i = SZINT; i < size; i++) /* correct extra bytes */ + buff[islittle ? i : size - 1 - i] = (char)MC; + } + luaL_addsize(b, size); /* add result to buffer */ +} + + +/* +** Copy 'size' bytes from 'src' to 'dest', correcting endianness if +** given 'islittle' is different from native endianness. +*/ +static void copywithendian (char *dest, const char *src, + int size, int islittle) { + if (islittle == nativeendian.little) + memcpy(dest, src, size); + else { + dest += size - 1; + while (size-- != 0) + *(dest--) = *(src++); + } +} + + +static int str_pack (lua_State *L) { + luaL_Buffer b; + Header h; + const char *fmt = luaL_checkstring(L, 1); /* format string */ + int arg = 1; /* current argument to pack */ + size_t totalsize = 0; /* accumulate total size of result */ + initheader(L, &h); + lua_pushnil(L); /* mark to separate arguments from string buffer */ + luaL_buffinit(L, &b); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); + totalsize += ntoalign + size; + while (ntoalign-- > 0) + luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */ + arg++; + switch (opt) { + case Kint: { /* signed integers */ + lua_Integer n = luaL_checkinteger(L, arg); + if (size < SZINT) { /* need overflow check? */ + lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); + luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); + } + packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); + break; + } + case Kuint: { /* unsigned integers */ + lua_Integer n = luaL_checkinteger(L, arg); + if (size < SZINT) /* need overflow check? */ + luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), + arg, "unsigned overflow"); + packint(&b, (lua_Unsigned)n, h.islittle, size, 0); + break; + } + case Kfloat: { /* C float */ + float f = (float)luaL_checknumber(L, arg); /* get argument */ + char *buff = luaL_prepbuffsize(&b, sizeof(f)); + /* move 'f' to final result, correcting endianness if needed */ + copywithendian(buff, (char *)&f, sizeof(f), h.islittle); + luaL_addsize(&b, size); + break; + } + case Knumber: { /* Lua float */ + lua_Number f = luaL_checknumber(L, arg); /* get argument */ + char *buff = luaL_prepbuffsize(&b, sizeof(f)); + /* move 'f' to final result, correcting endianness if needed */ + copywithendian(buff, (char *)&f, sizeof(f), h.islittle); + luaL_addsize(&b, size); + break; + } + case Kdouble: { /* C double */ + double f = (double)luaL_checknumber(L, arg); /* get argument */ + char *buff = luaL_prepbuffsize(&b, sizeof(f)); + /* move 'f' to final result, correcting endianness if needed */ + copywithendian(buff, (char *)&f, sizeof(f), h.islittle); + luaL_addsize(&b, size); + break; + } + case Kchar: { /* fixed-size string */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, len <= (size_t)size, arg, + "string longer than given size"); + luaL_addlstring(&b, s, len); /* add string */ + while (len++ < (size_t)size) /* pad extra space */ + luaL_addchar(&b, LUAL_PACKPADBYTE); + break; + } + case Kstring: { /* strings with length count */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, size >= (int)sizeof(size_t) || + len < ((size_t)1 << (size * NB)), + arg, "string length does not fit in given size"); + packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ + luaL_addlstring(&b, s, len); + totalsize += len; + break; + } + case Kzstr: { /* zero-terminated string */ + size_t len; + const char *s = luaL_checklstring(L, arg, &len); + luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); + luaL_addlstring(&b, s, len); + luaL_addchar(&b, '\0'); /* add zero at the end */ + totalsize += len + 1; + break; + } + case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ + case Kpaddalign: case Knop: + arg--; /* undo increment */ + break; + } + } + luaL_pushresult(&b); + return 1; +} + + +static int str_packsize (lua_State *L) { + Header h; + const char *fmt = luaL_checkstring(L, 1); /* format string */ + size_t totalsize = 0; /* accumulate total size of result */ + initheader(L, &h); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); + luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1, + "variable-length format"); + size += ntoalign; /* total space used by option */ + luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, + "format result too large"); + totalsize += size; + } + lua_pushinteger(L, (lua_Integer)totalsize); + return 1; +} + + +/* +** Unpack an integer with 'size' bytes and 'islittle' endianness. +** If size is smaller than the size of a Lua integer and integer +** is signed, must do sign extension (propagating the sign to the +** higher bits); if size is larger than the size of a Lua integer, +** it must check the unread bytes to see whether they do not cause an +** overflow. +*/ +static lua_Integer unpackint (lua_State *L, const char *str, + int islittle, int size, int issigned) { + lua_Unsigned res = 0; + int i; + int limit = (size <= SZINT) ? size : SZINT; + for (i = limit - 1; i >= 0; i--) { + res <<= NB; + res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; + } + if (size < SZINT) { /* real size smaller than lua_Integer? */ + if (issigned) { /* needs sign extension? */ + lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); + res = ((res ^ mask) - mask); /* do sign extension */ + } + } + else if (size > SZINT) { /* must check unread bytes */ + int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; + for (i = limit; i < size; i++) { + if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask)) + luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); + } + } + return (lua_Integer)res; +} + + +static int str_unpack (lua_State *L) { + Header h; + const char *fmt = luaL_checkstring(L, 1); + size_t ld; + const char *data = luaL_checklstring(L, 2, &ld); + size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1; + int n = 0; /* number of results */ + luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); + initheader(L, &h); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); + luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2, + "data string too short"); + pos += ntoalign; /* skip alignment */ + /* stack space for item + next position */ + luaL_checkstack(L, 2, "too many results"); + n++; + switch (opt) { + case Kint: + case Kuint: { + lua_Integer res = unpackint(L, data + pos, h.islittle, size, + (opt == Kint)); + lua_pushinteger(L, res); + break; + } + case Kfloat: { + float f; + copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); + lua_pushnumber(L, (lua_Number)f); + break; + } + case Knumber: { + lua_Number f; + copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); + lua_pushnumber(L, f); + break; + } + case Kdouble: { + double f; + copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); + lua_pushnumber(L, (lua_Number)f); + break; + } + case Kchar: { + lua_pushlstring(L, data + pos, size); + break; + } + case Kstring: { + size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); + luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short"); + lua_pushlstring(L, data + pos + size, len); + pos += len; /* skip string */ + break; + } + case Kzstr: { + size_t len = strlen(data + pos); + luaL_argcheck(L, pos + len < ld, 2, + "unfinished string for format 'z'"); + lua_pushlstring(L, data + pos, len); + pos += len + 1; /* skip string plus final '\0' */ + break; + } + case Kpaddalign: case Kpadding: case Knop: + n--; /* undo increment */ + break; + } + pos += size; + } + lua_pushinteger(L, pos + 1); /* next position */ + return n + 1; +} + +/* }====================================================== */ + + +static const luaL_Reg strlib[] = { + {"byte", str_byte}, + {"char", str_char}, + {"dump", str_dump}, + {"find", str_find}, + {"format", str_format}, + {"gmatch", gmatch}, + {"gsub", str_gsub}, + {"len", str_len}, + {"lower", str_lower}, + {"match", str_match}, + {"rep", str_rep}, + {"reverse", str_reverse}, + {"sub", str_sub}, + {"upper", str_upper}, + {"pack", str_pack}, + {"packsize", str_packsize}, + {"unpack", str_unpack}, + {NULL, NULL} +}; + + +static void createmetatable (lua_State *L) { + /* table to be metatable for strings */ + luaL_newlibtable(L, stringmetamethods); + luaL_setfuncs(L, stringmetamethods, 0); + lua_pushliteral(L, ""); /* dummy string */ + lua_pushvalue(L, -2); /* copy table */ + lua_setmetatable(L, -2); /* set table as metatable for strings */ + lua_pop(L, 1); /* pop dummy string */ + lua_pushvalue(L, -2); /* get string library */ + lua_setfield(L, -2, "__index"); /* metatable.__index = string */ + lua_pop(L, 1); /* pop metatable */ +} + + +/* +** Open string library +*/ +LUAMOD_API int luaopen_string (lua_State *L) { + luaL_newlib(L, strlib); + createmetatable(L); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/ltable.c b/src/libs/3rdparty/lua/src/ltable.c new file mode 100644 index 00000000000..3c690c5f175 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ltable.c @@ -0,0 +1,980 @@ +/* +** $Id: ltable.c $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + +#define ltable_c +#define LUA_CORE + +#include "lprefix.h" + + +/* +** Implementation of tables (aka arrays, objects, or hash tables). +** Tables keep its elements in two parts: an array part and a hash part. +** Non-negative integer keys are all candidates to be kept in the array +** part. The actual size of the array is the largest 'n' such that +** more than half the slots between 1 and n are in use. +** Hash uses a mix of chained scatter table with Brent's variation. +** A main invariant of these tables is that, if an element is not +** in its main position (i.e. the 'original' position that its hash gives +** to it), then the colliding element is in its own main position. +** Hence even when the load factor reaches 100%, performance remains good. +*/ + +#include +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lvm.h" + + +/* +** MAXABITS is the largest integer such that MAXASIZE fits in an +** unsigned int. +*/ +#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1) + + +/* +** MAXASIZE is the maximum size of the array part. It is the minimum +** between 2^MAXABITS and the maximum size that, measured in bytes, +** fits in a 'size_t'. +*/ +#define MAXASIZE luaM_limitN(1u << MAXABITS, TValue) + +/* +** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a +** signed int. +*/ +#define MAXHBITS (MAXABITS - 1) + + +/* +** MAXHSIZE is the maximum size of the hash part. It is the minimum +** between 2^MAXHBITS and the maximum size such that, measured in bytes, +** it fits in a 'size_t'. +*/ +#define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node) + + +/* +** When the original hash value is good, hashing by a power of 2 +** avoids the cost of '%'. +*/ +#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) + +/* +** for other types, it is better to avoid modulo by power of 2, as +** they can have many 2 factors. +*/ +#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) + + +#define hashstr(t,str) hashpow2(t, (str)->hash) +#define hashboolean(t,p) hashpow2(t, p) + + +#define hashpointer(t,p) hashmod(t, point2uint(p)) + + +#define dummynode (&dummynode_) + +static const Node dummynode_ = { + {{NULL}, LUA_VEMPTY, /* value's value and type */ + LUA_VNIL, 0, {NULL}} /* key type, next, and key value */ +}; + + +static const TValue absentkey = {ABSTKEYCONSTANT}; + + +/* +** Hash for integers. To allow a good hash, use the remainder operator +** ('%'). If integer fits as a non-negative int, compute an int +** remainder, which is faster. Otherwise, use an unsigned-integer +** remainder, which uses all bits and ensures a non-negative result. +*/ +static Node *hashint (const Table *t, lua_Integer i) { + lua_Unsigned ui = l_castS2U(i); + if (ui <= cast_uint(INT_MAX)) + return hashmod(t, cast_int(ui)); + else + return hashmod(t, ui); +} + + +/* +** Hash for floating-point numbers. +** The main computation should be just +** n = frexp(n, &i); return (n * INT_MAX) + i +** but there are some numerical subtleties. +** In a two-complement representation, INT_MAX does not has an exact +** representation as a float, but INT_MIN does; because the absolute +** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the +** absolute value of the product 'frexp * -INT_MIN' is smaller or equal +** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when +** adding 'i'; the use of '~u' (instead of '-u') avoids problems with +** INT_MIN. +*/ +#if !defined(l_hashfloat) +static int l_hashfloat (lua_Number n) { + int i; + lua_Integer ni; + n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); + if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ + lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); + return 0; + } + else { /* normal case */ + unsigned int u = cast_uint(i) + cast_uint(ni); + return cast_int(u <= cast_uint(INT_MAX) ? u : ~u); + } +} +#endif + + +/* +** returns the 'main' position of an element in a table (that is, +** the index of its hash value). +*/ +static Node *mainpositionTV (const Table *t, const TValue *key) { + switch (ttypetag(key)) { + case LUA_VNUMINT: { + lua_Integer i = ivalue(key); + return hashint(t, i); + } + case LUA_VNUMFLT: { + lua_Number n = fltvalue(key); + return hashmod(t, l_hashfloat(n)); + } + case LUA_VSHRSTR: { + TString *ts = tsvalue(key); + return hashstr(t, ts); + } + case LUA_VLNGSTR: { + TString *ts = tsvalue(key); + return hashpow2(t, luaS_hashlongstr(ts)); + } + case LUA_VFALSE: + return hashboolean(t, 0); + case LUA_VTRUE: + return hashboolean(t, 1); + case LUA_VLIGHTUSERDATA: { + void *p = pvalue(key); + return hashpointer(t, p); + } + case LUA_VLCF: { + lua_CFunction f = fvalue(key); + return hashpointer(t, f); + } + default: { + GCObject *o = gcvalue(key); + return hashpointer(t, o); + } + } +} + + +l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) { + TValue key; + getnodekey(cast(lua_State *, NULL), &key, nd); + return mainpositionTV(t, &key); +} + + +/* +** Check whether key 'k1' is equal to the key in node 'n2'. This +** equality is raw, so there are no metamethods. Floats with integer +** values have been normalized, so integers cannot be equal to +** floats. It is assumed that 'eqshrstr' is simply pointer equality, so +** that short strings are handled in the default case. +** A true 'deadok' means to accept dead keys as equal to their original +** values. All dead keys are compared in the default case, by pointer +** identity. (Only collectable objects can produce dead keys.) Note that +** dead long strings are also compared by identity. +** Once a key is dead, its corresponding value may be collected, and +** then another value can be created with the same address. If this +** other value is given to 'next', 'equalkey' will signal a false +** positive. In a regular traversal, this situation should never happen, +** as all keys given to 'next' came from the table itself, and therefore +** could not have been collected. Outside a regular traversal, we +** have garbage in, garbage out. What is relevant is that this false +** positive does not break anything. (In particular, 'next' will return +** some other valid item on the table or nil.) +*/ +static int equalkey (const TValue *k1, const Node *n2, int deadok) { + if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */ + !(deadok && keyisdead(n2) && iscollectable(k1))) + return 0; /* cannot be same key */ + switch (keytt(n2)) { + case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: + return 1; + case LUA_VNUMINT: + return (ivalue(k1) == keyival(n2)); + case LUA_VNUMFLT: + return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2))); + case LUA_VLIGHTUSERDATA: + return pvalue(k1) == pvalueraw(keyval(n2)); + case LUA_VLCF: + return fvalue(k1) == fvalueraw(keyval(n2)); + case ctb(LUA_VLNGSTR): + return luaS_eqlngstr(tsvalue(k1), keystrval(n2)); + default: + return gcvalue(k1) == gcvalueraw(keyval(n2)); + } +} + + +/* +** True if value of 'alimit' is equal to the real size of the array +** part of table 't'. (Otherwise, the array part must be larger than +** 'alimit'.) +*/ +#define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit)) + + +/* +** Returns the real size of the 'array' array +*/ +LUAI_FUNC unsigned int luaH_realasize (const Table *t) { + if (limitequalsasize(t)) + return t->alimit; /* this is the size */ + else { + unsigned int size = t->alimit; + /* compute the smallest power of 2 not smaller than 'n' */ + size |= (size >> 1); + size |= (size >> 2); + size |= (size >> 4); + size |= (size >> 8); +#if (UINT_MAX >> 14) > 3 /* unsigned int has more than 16 bits */ + size |= (size >> 16); +#if (UINT_MAX >> 30) > 3 + size |= (size >> 32); /* unsigned int has more than 32 bits */ +#endif +#endif + size++; + lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size); + return size; + } +} + + +/* +** Check whether real size of the array is a power of 2. +** (If it is not, 'alimit' cannot be changed to any other value +** without changing the real size.) +*/ +static int ispow2realasize (const Table *t) { + return (!isrealasize(t) || ispow2(t->alimit)); +} + + +static unsigned int setlimittosize (Table *t) { + t->alimit = luaH_realasize(t); + setrealasize(t); + return t->alimit; +} + + +#define limitasasize(t) check_exp(isrealasize(t), t->alimit) + + + +/* +** "Generic" get version. (Not that generic: not valid for integers, +** which may be in array part, nor for floats with integral values.) +** See explanation about 'deadok' in function 'equalkey'. +*/ +static const TValue *getgeneric (Table *t, const TValue *key, int deadok) { + Node *n = mainpositionTV(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (equalkey(key, n, deadok)) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) + return &absentkey; /* not found */ + n += nx; + } + } +} + + +/* +** returns the index for 'k' if 'k' is an appropriate key to live in +** the array part of a table, 0 otherwise. +*/ +static unsigned int arrayindex (lua_Integer k) { + if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */ + return cast_uint(k); /* 'key' is an appropriate array index */ + else + return 0; +} + + +/* +** returns the index of a 'key' for table traversals. First goes all +** elements in the array part, then elements in the hash part. The +** beginning of a traversal is signaled by 0. +*/ +static unsigned int findindex (lua_State *L, Table *t, TValue *key, + unsigned int asize) { + unsigned int i; + if (ttisnil(key)) return 0; /* first iteration */ + i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0; + if (i - 1u < asize) /* is 'key' inside array part? */ + return i; /* yes; that's the index */ + else { + const TValue *n = getgeneric(t, key, 1); + if (l_unlikely(isabstkey(n))) + luaG_runerror(L, "invalid key to 'next'"); /* key not found */ + i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */ + /* hash elements are numbered after array ones */ + return (i + 1) + asize; + } +} + + +int luaH_next (lua_State *L, Table *t, StkId key) { + unsigned int asize = luaH_realasize(t); + unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */ + for (; i < asize; i++) { /* try first array part */ + if (!isempty(&t->array[i])) { /* a non-empty entry? */ + setivalue(s2v(key), i + 1); + setobj2s(L, key + 1, &t->array[i]); + return 1; + } + } + for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */ + if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */ + Node *n = gnode(t, i); + getnodekey(L, s2v(key), n); + setobj2s(L, key + 1, gval(n)); + return 1; + } + } + return 0; /* no more elements */ +} + + +static void freehash (lua_State *L, Table *t) { + if (!isdummy(t)) + luaM_freearray(L, t->node, cast_sizet(sizenode(t))); +} + + +/* +** {============================================================= +** Rehash +** ============================================================== +*/ + +/* +** Compute the optimal size for the array part of table 't'. 'nums' is a +** "count array" where 'nums[i]' is the number of integers in the table +** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of +** integer keys in the table and leaves with the number of keys that +** will go to the array part; return the optimal size. (The condition +** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.) +*/ +static unsigned int computesizes (unsigned int nums[], unsigned int *pna) { + int i; + unsigned int twotoi; /* 2^i (candidate for optimal size) */ + unsigned int a = 0; /* number of elements smaller than 2^i */ + unsigned int na = 0; /* number of elements to go to array part */ + unsigned int optimal = 0; /* optimal size for array part */ + /* loop while keys can fill more than half of total size */ + for (i = 0, twotoi = 1; + twotoi > 0 && *pna > twotoi / 2; + i++, twotoi *= 2) { + a += nums[i]; + if (a > twotoi/2) { /* more than half elements present? */ + optimal = twotoi; /* optimal size (till now) */ + na = a; /* all elements up to 'optimal' will go to array part */ + } + } + lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal); + *pna = na; + return optimal; +} + + +static int countint (lua_Integer key, unsigned int *nums) { + unsigned int k = arrayindex(key); + if (k != 0) { /* is 'key' an appropriate array index? */ + nums[luaO_ceillog2(k)]++; /* count as such */ + return 1; + } + else + return 0; +} + + +/* +** Count keys in array part of table 't': Fill 'nums[i]' with +** number of keys that will go into corresponding slice and return +** total number of non-nil keys. +*/ +static unsigned int numusearray (const Table *t, unsigned int *nums) { + int lg; + unsigned int ttlg; /* 2^lg */ + unsigned int ause = 0; /* summation of 'nums' */ + unsigned int i = 1; /* count to traverse all array keys */ + unsigned int asize = limitasasize(t); /* real array size */ + /* traverse each slice */ + for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { + unsigned int lc = 0; /* counter */ + unsigned int lim = ttlg; + if (lim > asize) { + lim = asize; /* adjust upper limit */ + if (i > lim) + break; /* no more elements to count */ + } + /* count elements in range (2^(lg - 1), 2^lg] */ + for (; i <= lim; i++) { + if (!isempty(&t->array[i-1])) + lc++; + } + nums[lg] += lc; + ause += lc; + } + return ause; +} + + +static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) { + int totaluse = 0; /* total number of elements */ + int ause = 0; /* elements added to 'nums' (can go to array part) */ + int i = sizenode(t); + while (i--) { + Node *n = &t->node[i]; + if (!isempty(gval(n))) { + if (keyisinteger(n)) + ause += countint(keyival(n), nums); + totaluse++; + } + } + *pna += ause; + return totaluse; +} + + +/* +** Creates an array for the hash part of a table with the given +** size, or reuses the dummy node if size is zero. +** The computation for size overflow is in two steps: the first +** comparison ensures that the shift in the second one does not +** overflow. +*/ +static void setnodevector (lua_State *L, Table *t, unsigned int size) { + if (size == 0) { /* no elements to hash part? */ + t->node = cast(Node *, dummynode); /* use common 'dummynode' */ + t->lsizenode = 0; + t->lastfree = NULL; /* signal that it is using dummy node */ + } + else { + int i; + int lsize = luaO_ceillog2(size); + if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE) + luaG_runerror(L, "table overflow"); + size = twoto(lsize); + t->node = luaM_newvector(L, size, Node); + for (i = 0; i < cast_int(size); i++) { + Node *n = gnode(t, i); + gnext(n) = 0; + setnilkey(n); + setempty(gval(n)); + } + t->lsizenode = cast_byte(lsize); + t->lastfree = gnode(t, size); /* all positions are free */ + } +} + + +/* +** (Re)insert all elements from the hash part of 'ot' into table 't'. +*/ +static void reinsert (lua_State *L, Table *ot, Table *t) { + int j; + int size = sizenode(ot); + for (j = 0; j < size; j++) { + Node *old = gnode(ot, j); + if (!isempty(gval(old))) { + /* doesn't need barrier/invalidate cache, as entry was + already present in the table */ + TValue k; + getnodekey(L, &k, old); + luaH_set(L, t, &k, gval(old)); + } + } +} + + +/* +** Exchange the hash part of 't1' and 't2'. +*/ +static void exchangehashpart (Table *t1, Table *t2) { + lu_byte lsizenode = t1->lsizenode; + Node *node = t1->node; + Node *lastfree = t1->lastfree; + t1->lsizenode = t2->lsizenode; + t1->node = t2->node; + t1->lastfree = t2->lastfree; + t2->lsizenode = lsizenode; + t2->node = node; + t2->lastfree = lastfree; +} + + +/* +** Resize table 't' for the new given sizes. Both allocations (for +** the hash part and for the array part) can fail, which creates some +** subtleties. If the first allocation, for the hash part, fails, an +** error is raised and that is it. Otherwise, it copies the elements from +** the shrinking part of the array (if it is shrinking) into the new +** hash. Then it reallocates the array part. If that fails, the table +** is in its original state; the function frees the new hash part and then +** raises the allocation error. Otherwise, it sets the new hash part +** into the table, initializes the new part of the array (if any) with +** nils and reinserts the elements of the old hash back into the new +** parts of the table. +*/ +void luaH_resize (lua_State *L, Table *t, unsigned int newasize, + unsigned int nhsize) { + unsigned int i; + Table newt; /* to keep the new hash part */ + unsigned int oldasize = setlimittosize(t); + TValue *newarray; + /* create new hash part with appropriate size into 'newt' */ + setnodevector(L, &newt, nhsize); + if (newasize < oldasize) { /* will array shrink? */ + t->alimit = newasize; /* pretend array has new size... */ + exchangehashpart(t, &newt); /* and new hash */ + /* re-insert into the new hash the elements from vanishing slice */ + for (i = newasize; i < oldasize; i++) { + if (!isempty(&t->array[i])) + luaH_setint(L, t, i + 1, &t->array[i]); + } + t->alimit = oldasize; /* restore current size... */ + exchangehashpart(t, &newt); /* and hash (in case of errors) */ + } + /* allocate new array */ + newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue); + if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */ + freehash(L, &newt); /* release new hash part */ + luaM_error(L); /* raise error (with array unchanged) */ + } + /* allocation ok; initialize new part of the array */ + exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */ + t->array = newarray; /* set new array part */ + t->alimit = newasize; + for (i = oldasize; i < newasize; i++) /* clear new slice of the array */ + setempty(&t->array[i]); + /* re-insert elements from old hash part into new parts */ + reinsert(L, &newt, t); /* 'newt' now has the old hash */ + freehash(L, &newt); /* free old hash part */ +} + + +void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { + int nsize = allocsizenode(t); + luaH_resize(L, t, nasize, nsize); +} + +/* +** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i +*/ +static void rehash (lua_State *L, Table *t, const TValue *ek) { + unsigned int asize; /* optimal size for array part */ + unsigned int na; /* number of keys in the array part */ + unsigned int nums[MAXABITS + 1]; + int i; + int totaluse; + for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */ + setlimittosize(t); + na = numusearray(t, nums); /* count keys in array part */ + totaluse = na; /* all those keys are integer keys */ + totaluse += numusehash(t, nums, &na); /* count keys in hash part */ + /* count extra key */ + if (ttisinteger(ek)) + na += countint(ivalue(ek), nums); + totaluse++; + /* compute new size for array part */ + asize = computesizes(nums, &na); + /* resize the table to new computed sizes */ + luaH_resize(L, t, asize, totaluse - na); +} + + + +/* +** }============================================================= +*/ + + +Table *luaH_new (lua_State *L) { + GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table)); + Table *t = gco2t(o); + t->metatable = NULL; + t->flags = cast_byte(maskflags); /* table has no metamethod fields */ + t->array = NULL; + t->alimit = 0; + setnodevector(L, t, 0); + return t; +} + + +void luaH_free (lua_State *L, Table *t) { + freehash(L, t); + luaM_freearray(L, t->array, luaH_realasize(t)); + luaM_free(L, t); +} + + +static Node *getfreepos (Table *t) { + if (!isdummy(t)) { + while (t->lastfree > t->node) { + t->lastfree--; + if (keyisnil(t->lastfree)) + return t->lastfree; + } + } + return NULL; /* could not find a free place */ +} + + + +/* +** inserts a new key into a hash table; first, check whether key's main +** position is free. If not, check whether colliding node is in its main +** position or not: if it is not, move colliding node to an empty place and +** put new key in its main position; otherwise (colliding node is in its main +** position), new key goes to an empty position. +*/ +void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) { + Node *mp; + TValue aux; + if (l_unlikely(ttisnil(key))) + luaG_runerror(L, "table index is nil"); + else if (ttisfloat(key)) { + lua_Number f = fltvalue(key); + lua_Integer k; + if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */ + setivalue(&aux, k); + key = &aux; /* insert it as an integer */ + } + else if (l_unlikely(luai_numisnan(f))) + luaG_runerror(L, "table index is NaN"); + } + if (ttisnil(value)) + return; /* do not insert nil values */ + mp = mainpositionTV(t, key); + if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */ + Node *othern; + Node *f = getfreepos(t); /* get a free place */ + if (f == NULL) { /* cannot find a free place? */ + rehash(L, t, key); /* grow table */ + /* whatever called 'newkey' takes care of TM cache */ + luaH_set(L, t, key, value); /* insert key into grown table */ + return; + } + lua_assert(!isdummy(t)); + othern = mainpositionfromnode(t, mp); + if (othern != mp) { /* is colliding node out of its main position? */ + /* yes; move colliding node into free position */ + while (othern + gnext(othern) != mp) /* find previous */ + othern += gnext(othern); + gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ + *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ + if (gnext(mp) != 0) { + gnext(f) += cast_int(mp - f); /* correct 'next' */ + gnext(mp) = 0; /* now 'mp' is free */ + } + setempty(gval(mp)); + } + else { /* colliding node is in its own main position */ + /* new node will go into free position */ + if (gnext(mp) != 0) + gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ + else lua_assert(gnext(f) == 0); + gnext(mp) = cast_int(f - mp); + mp = f; + } + } + setnodekey(L, mp, key); + luaC_barrierback(L, obj2gco(t), key); + lua_assert(isempty(gval(mp))); + setobj2t(L, gval(mp), value); +} + + +/* +** Search function for integers. If integer is inside 'alimit', get it +** directly from the array part. Otherwise, if 'alimit' is not equal to +** the real size of the array, key still can be in the array part. In +** this case, try to avoid a call to 'luaH_realasize' when key is just +** one more than the limit (so that it can be incremented without +** changing the real size of the array). +*/ +const TValue *luaH_getint (Table *t, lua_Integer key) { + if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */ + return &t->array[key - 1]; + else if (!limitequalsasize(t) && /* key still may be in the array part? */ + (l_castS2U(key) == t->alimit + 1 || + l_castS2U(key) - 1u < luaH_realasize(t))) { + t->alimit = cast_uint(key); /* probably '#t' is here now */ + return &t->array[key - 1]; + } + else { + Node *n = hashint(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (keyisinteger(n) && keyival(n) == key) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) break; + n += nx; + } + } + return &absentkey; + } +} + + +/* +** search function for short strings +*/ +const TValue *luaH_getshortstr (Table *t, TString *key) { + Node *n = hashstr(t, key); + lua_assert(key->tt == LUA_VSHRSTR); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (keyisshrstr(n) && eqshrstr(keystrval(n), key)) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) + return &absentkey; /* not found */ + n += nx; + } + } +} + + +const TValue *luaH_getstr (Table *t, TString *key) { + if (key->tt == LUA_VSHRSTR) + return luaH_getshortstr(t, key); + else { /* for long strings, use generic case */ + TValue ko; + setsvalue(cast(lua_State *, NULL), &ko, key); + return getgeneric(t, &ko, 0); + } +} + + +/* +** main search function +*/ +const TValue *luaH_get (Table *t, const TValue *key) { + switch (ttypetag(key)) { + case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key)); + case LUA_VNUMINT: return luaH_getint(t, ivalue(key)); + case LUA_VNIL: return &absentkey; + case LUA_VNUMFLT: { + lua_Integer k; + if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */ + return luaH_getint(t, k); /* use specialized version */ + /* else... */ + } /* FALLTHROUGH */ + default: + return getgeneric(t, key, 0); + } +} + + +/* +** Finish a raw "set table" operation, where 'slot' is where the value +** should have been (the result of a previous "get table"). +** Beware: when using this function you probably need to check a GC +** barrier and invalidate the TM cache. +*/ +void luaH_finishset (lua_State *L, Table *t, const TValue *key, + const TValue *slot, TValue *value) { + if (isabstkey(slot)) + luaH_newkey(L, t, key, value); + else + setobj2t(L, cast(TValue *, slot), value); +} + + +/* +** beware: when using this function you probably need to check a GC +** barrier and invalidate the TM cache. +*/ +void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) { + const TValue *slot = luaH_get(t, key); + luaH_finishset(L, t, key, slot, value); +} + + +void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { + const TValue *p = luaH_getint(t, key); + if (isabstkey(p)) { + TValue k; + setivalue(&k, key); + luaH_newkey(L, t, &k, value); + } + else + setobj2t(L, cast(TValue *, p), value); +} + + +/* +** Try to find a boundary in the hash part of table 't'. From the +** caller, we know that 'j' is zero or present and that 'j + 1' is +** present. We want to find a larger key that is absent from the +** table, so that we can do a binary search between the two keys to +** find a boundary. We keep doubling 'j' until we get an absent index. +** If the doubling would overflow, we try LUA_MAXINTEGER. If it is +** absent, we are ready for the binary search. ('j', being max integer, +** is larger or equal to 'i', but it cannot be equal because it is +** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a +** boundary. ('j + 1' cannot be a present integer key because it is +** not a valid integer in Lua.) +*/ +static lua_Unsigned hash_search (Table *t, lua_Unsigned j) { + lua_Unsigned i; + if (j == 0) j++; /* the caller ensures 'j + 1' is present */ + do { + i = j; /* 'i' is a present index */ + if (j <= l_castS2U(LUA_MAXINTEGER) / 2) + j *= 2; + else { + j = LUA_MAXINTEGER; + if (isempty(luaH_getint(t, j))) /* t[j] not present? */ + break; /* 'j' now is an absent index */ + else /* weird case */ + return j; /* well, max integer is a boundary... */ + } + } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */ + /* i < j && t[i] present && t[j] absent */ + while (j - i > 1u) { /* do a binary search between them */ + lua_Unsigned m = (i + j) / 2; + if (isempty(luaH_getint(t, m))) j = m; + else i = m; + } + return i; +} + + +static unsigned int binsearch (const TValue *array, unsigned int i, + unsigned int j) { + while (j - i > 1u) { /* binary search */ + unsigned int m = (i + j) / 2; + if (isempty(&array[m - 1])) j = m; + else i = m; + } + return i; +} + + +/* +** Try to find a boundary in table 't'. (A 'boundary' is an integer index +** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent +** and 'maxinteger' if t[maxinteger] is present.) +** (In the next explanation, we use Lua indices, that is, with base 1. +** The code itself uses base 0 when indexing the array part of the table.) +** The code starts with 'limit = t->alimit', a position in the array +** part that may be a boundary. +** +** (1) If 't[limit]' is empty, there must be a boundary before it. +** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1' +** is present. If so, it is a boundary. Otherwise, do a binary search +** between 0 and limit to find a boundary. In both cases, try to +** use this boundary as the new 'alimit', as a hint for the next call. +** +** (2) If 't[limit]' is not empty and the array has more elements +** after 'limit', try to find a boundary there. Again, try first +** the special case (which should be quite frequent) where 'limit+1' +** is empty, so that 'limit' is a boundary. Otherwise, check the +** last element of the array part. If it is empty, there must be a +** boundary between the old limit (present) and the last element +** (absent), which is found with a binary search. (This boundary always +** can be a new limit.) +** +** (3) The last case is when there are no elements in the array part +** (limit == 0) or its last element (the new limit) is present. +** In this case, must check the hash part. If there is no hash part +** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call +** 'hash_search' to find a boundary in the hash part of the table. +** (In those cases, the boundary is not inside the array part, and +** therefore cannot be used as a new limit.) +*/ +lua_Unsigned luaH_getn (Table *t) { + unsigned int limit = t->alimit; + if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */ + /* there must be a boundary before 'limit' */ + if (limit >= 2 && !isempty(&t->array[limit - 2])) { + /* 'limit - 1' is a boundary; can it be a new limit? */ + if (ispow2realasize(t) && !ispow2(limit - 1)) { + t->alimit = limit - 1; + setnorealasize(t); /* now 'alimit' is not the real size */ + } + return limit - 1; + } + else { /* must search for a boundary in [0, limit] */ + unsigned int boundary = binsearch(t->array, 0, limit); + /* can this boundary represent the real size of the array? */ + if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) { + t->alimit = boundary; /* use it as the new limit */ + setnorealasize(t); + } + return boundary; + } + } + /* 'limit' is zero or present in table */ + if (!limitequalsasize(t)) { /* (2)? */ + /* 'limit' > 0 and array has more elements after 'limit' */ + if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */ + return limit; /* this is the boundary */ + /* else, try last element in the array */ + limit = luaH_realasize(t); + if (isempty(&t->array[limit - 1])) { /* empty? */ + /* there must be a boundary in the array after old limit, + and it must be a valid new limit */ + unsigned int boundary = binsearch(t->array, t->alimit, limit); + t->alimit = boundary; + return boundary; + } + /* else, new limit is present in the table; check the hash part */ + } + /* (3) 'limit' is the last element and either is zero or present in table */ + lua_assert(limit == luaH_realasize(t) && + (limit == 0 || !isempty(&t->array[limit - 1]))); + if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1)))) + return limit; /* 'limit + 1' is absent */ + else /* 'limit + 1' is also present */ + return hash_search(t, limit); +} + + + +#if defined(LUA_DEBUG) + +/* export these functions for the test library */ + +Node *luaH_mainposition (const Table *t, const TValue *key) { + return mainpositionTV(t, key); +} + +#endif diff --git a/src/libs/3rdparty/lua/src/ltable.h b/src/libs/3rdparty/lua/src/ltable.h new file mode 100644 index 00000000000..75dd9e26e01 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ltable.h @@ -0,0 +1,65 @@ +/* +** $Id: ltable.h $ +** Lua tables (hash) +** See Copyright Notice in lua.h +*/ + +#ifndef ltable_h +#define ltable_h + +#include "lobject.h" + + +#define gnode(t,i) (&(t)->node[i]) +#define gval(n) (&(n)->i_val) +#define gnext(n) ((n)->u.next) + + +/* +** Clear all bits of fast-access metamethods, which means that the table +** may have any of these metamethods. (First access that fails after the +** clearing will set the bit again.) +*/ +#define invalidateTMcache(t) ((t)->flags &= ~maskflags) + + +/* true when 't' is using 'dummynode' as its hash part */ +#define isdummy(t) ((t)->lastfree == NULL) + + +/* allocated size for hash nodes */ +#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) + + +/* returns the Node, given the value of a table entry */ +#define nodefromval(v) cast(Node *, (v)) + + +LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); +LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, + TValue *value); +LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); +LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); +LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); +LUAI_FUNC void luaH_newkey (lua_State *L, Table *t, const TValue *key, + TValue *value); +LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key, + TValue *value); +LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key, + const TValue *slot, TValue *value); +LUAI_FUNC Table *luaH_new (lua_State *L); +LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, + unsigned int nhsize); +LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); +LUAI_FUNC void luaH_free (lua_State *L, Table *t); +LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); +LUAI_FUNC lua_Unsigned luaH_getn (Table *t); +LUAI_FUNC unsigned int luaH_realasize (const Table *t); + + +#if defined(LUA_DEBUG) +LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); +#endif + + +#endif diff --git a/src/libs/3rdparty/lua/src/ltablib.c b/src/libs/3rdparty/lua/src/ltablib.c new file mode 100644 index 00000000000..e6bc4d04af4 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ltablib.c @@ -0,0 +1,430 @@ +/* +** $Id: ltablib.c $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + +#define ltablib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** Operations that an object must define to mimic a table +** (some functions only need some of them) +*/ +#define TAB_R 1 /* read */ +#define TAB_W 2 /* write */ +#define TAB_L 4 /* length */ +#define TAB_RW (TAB_R | TAB_W) /* read/write */ + + +#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) + + +static int checkfield (lua_State *L, const char *key, int n) { + lua_pushstring(L, key); + return (lua_rawget(L, -n) != LUA_TNIL); +} + + +/* +** Check that 'arg' either is a table or can behave like one (that is, +** has a metatable with the required metamethods) +*/ +static void checktab (lua_State *L, int arg, int what) { + if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ + int n = 1; /* number of elements to pop */ + if (lua_getmetatable(L, arg) && /* must have metatable */ + (!(what & TAB_R) || checkfield(L, "__index", ++n)) && + (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && + (!(what & TAB_L) || checkfield(L, "__len", ++n))) { + lua_pop(L, n); /* pop metatable and tested metamethods */ + } + else + luaL_checktype(L, arg, LUA_TTABLE); /* force an error */ + } +} + + +static int tinsert (lua_State *L) { + lua_Integer pos; /* where to insert new element */ + lua_Integer e = aux_getn(L, 1, TAB_RW); + e = luaL_intop(+, e, 1); /* first empty element */ + switch (lua_gettop(L)) { + case 2: { /* called with only 2 arguments */ + pos = e; /* insert new element at the end */ + break; + } + case 3: { + lua_Integer i; + pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ + /* check whether 'pos' is in [1, e] */ + luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2, + "position out of bounds"); + for (i = e; i > pos; i--) { /* move up elements */ + lua_geti(L, 1, i - 1); + lua_seti(L, 1, i); /* t[i] = t[i - 1] */ + } + break; + } + default: { + return luaL_error(L, "wrong number of arguments to 'insert'"); + } + } + lua_seti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int tremove (lua_State *L) { + lua_Integer size = aux_getn(L, 1, TAB_RW); + lua_Integer pos = luaL_optinteger(L, 2, size); + if (pos != size) /* validate 'pos' if given */ + /* check whether 'pos' is in [1, size + 1] */ + luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2, + "position out of bounds"); + lua_geti(L, 1, pos); /* result = t[pos] */ + for ( ; pos < size; pos++) { + lua_geti(L, 1, pos + 1); + lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ + } + lua_pushnil(L); + lua_seti(L, 1, pos); /* remove entry t[pos] */ + return 1; +} + + +/* +** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever +** possible, copy in increasing order, which is better for rehashing. +** "possible" means destination after original range, or smaller +** than origin, or copying to another table. +*/ +static int tmove (lua_State *L) { + lua_Integer f = luaL_checkinteger(L, 2); + lua_Integer e = luaL_checkinteger(L, 3); + lua_Integer t = luaL_checkinteger(L, 4); + int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ + checktab(L, 1, TAB_R); + checktab(L, tt, TAB_W); + if (e >= f) { /* otherwise, nothing to move */ + lua_Integer n, i; + luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, + "too many elements to move"); + n = e - f + 1; /* number of elements to move */ + luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, + "destination wrap around"); + if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) { + for (i = 0; i < n; i++) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + else { + for (i = n - 1; i >= 0; i--) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + } + lua_pushvalue(L, tt); /* return destination table */ + return 1; +} + + +static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { + lua_geti(L, 1, i); + if (l_unlikely(!lua_isstring(L, -1))) + luaL_error(L, "invalid value (%s) at index %I in table for 'concat'", + luaL_typename(L, -1), (LUAI_UACINT)i); + luaL_addvalue(b); +} + + +static int tconcat (lua_State *L) { + luaL_Buffer b; + lua_Integer last = aux_getn(L, 1, TAB_R); + size_t lsep; + const char *sep = luaL_optlstring(L, 2, "", &lsep); + lua_Integer i = luaL_optinteger(L, 3, 1); + last = luaL_optinteger(L, 4, last); + luaL_buffinit(L, &b); + for (; i < last; i++) { + addfield(L, &b, i); + luaL_addlstring(&b, sep, lsep); + } + if (i == last) /* add last value (if interval was not empty) */ + addfield(L, &b, i); + luaL_pushresult(&b); + return 1; +} + + +/* +** {====================================================== +** Pack/unpack +** ======================================================= +*/ + +static int tpack (lua_State *L) { + int i; + int n = lua_gettop(L); /* number of elements to pack */ + lua_createtable(L, n, 1); /* create result table */ + lua_insert(L, 1); /* put it at index 1 */ + for (i = n; i >= 1; i--) /* assign elements */ + lua_seti(L, 1, i); + lua_pushinteger(L, n); + lua_setfield(L, 1, "n"); /* t.n = number of elements */ + return 1; /* return table */ +} + + +static int tunpack (lua_State *L) { + lua_Unsigned n; + lua_Integer i = luaL_optinteger(L, 2, 1); + lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); + if (i > e) return 0; /* empty range */ + n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ + if (l_unlikely(n >= (unsigned int)INT_MAX || + !lua_checkstack(L, (int)(++n)))) + return luaL_error(L, "too many results to unpack"); + for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ + lua_geti(L, 1, i); + } + lua_geti(L, 1, e); /* push last element */ + return (int)n; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Quicksort +** (based on 'Algorithms in MODULA-3', Robert Sedgewick; +** Addison-Wesley, 1993.) +** ======================================================= +*/ + + +/* type for array indices */ +typedef unsigned int IdxT; + + +/* +** Produce a "random" 'unsigned int' to randomize pivot choice. This +** macro is used only when 'sort' detects a big imbalance in the result +** of a partition. (If you don't want/need this "randomness", ~0 is a +** good choice.) +*/ +#if !defined(l_randomizePivot) /* { */ + +#include + +/* size of 'e' measured in number of 'unsigned int's */ +#define sof(e) (sizeof(e) / sizeof(unsigned int)) + +/* +** Use 'time' and 'clock' as sources of "randomness". Because we don't +** know the types 'clock_t' and 'time_t', we cannot cast them to +** anything without risking overflows. A safe way to use their values +** is to copy them to an array of a known type and use the array values. +*/ +static unsigned int l_randomizePivot (void) { + clock_t c = clock(); + time_t t = time(NULL); + unsigned int buff[sof(c) + sof(t)]; + unsigned int i, rnd = 0; + memcpy(buff, &c, sof(c) * sizeof(unsigned int)); + memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int)); + for (i = 0; i < sof(buff); i++) + rnd += buff[i]; + return rnd; +} + +#endif /* } */ + + +/* arrays larger than 'RANLIMIT' may use randomized pivots */ +#define RANLIMIT 100u + + +static void set2 (lua_State *L, IdxT i, IdxT j) { + lua_seti(L, 1, i); + lua_seti(L, 1, j); +} + + +/* +** Return true iff value at stack index 'a' is less than the value at +** index 'b' (according to the order of the sort). +*/ +static int sort_comp (lua_State *L, int a, int b) { + if (lua_isnil(L, 2)) /* no function? */ + return lua_compare(L, a, b, LUA_OPLT); /* a < b */ + else { /* function */ + int res; + lua_pushvalue(L, 2); /* push function */ + lua_pushvalue(L, a-1); /* -1 to compensate function */ + lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ + lua_call(L, 2, 1); /* call function */ + res = lua_toboolean(L, -1); /* get result */ + lua_pop(L, 1); /* pop result */ + return res; + } +} + + +/* +** Does the partition: Pivot P is at the top of the stack. +** precondition: a[lo] <= P == a[up-1] <= a[up], +** so it only needs to do the partition from lo + 1 to up - 2. +** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] +** returns 'i'. +*/ +static IdxT partition (lua_State *L, IdxT lo, IdxT up) { + IdxT i = lo; /* will be incremented before first use */ + IdxT j = up - 1; /* will be decremented before first use */ + /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ + for (;;) { + /* next loop: repeat ++i while a[i] < P */ + while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ + /* next loop: repeat --j while P < a[j] */ + while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { + if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[j] */ + } + /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ + if (j < i) { /* no elements out of place? */ + /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ + lua_pop(L, 1); /* pop a[j] */ + /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ + set2(L, up - 1, i); + return i; + } + /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ + set2(L, i, j); + } +} + + +/* +** Choose an element in the middle (2nd-3th quarters) of [lo,up] +** "randomized" by 'rnd' +*/ +static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) { + IdxT r4 = (up - lo) / 4; /* range/4 */ + IdxT p = rnd % (r4 * 2) + (lo + r4); + lua_assert(lo + r4 <= p && p <= up - r4); + return p; +} + + +/* +** Quicksort algorithm (recursive function) +*/ +static void auxsort (lua_State *L, IdxT lo, IdxT up, + unsigned int rnd) { + while (lo < up) { /* loop for tail recursion */ + IdxT p; /* Pivot index */ + IdxT n; /* to be used later */ + /* sort elements 'lo', 'p', and 'up' */ + lua_geti(L, 1, lo); + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ + set2(L, lo, up); /* swap a[lo] - a[up] */ + else + lua_pop(L, 2); /* remove both values */ + if (up - lo == 1) /* only 2 elements? */ + return; /* already sorted */ + if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ + p = (lo + up)/2; /* middle element is a good pivot */ + else /* for larger intervals, it is worth a random pivot */ + p = choosePivot(lo, up, rnd); + lua_geti(L, 1, p); + lua_geti(L, 1, lo); + if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ + set2(L, p, lo); /* swap a[p] - a[lo] */ + else { + lua_pop(L, 1); /* remove a[lo] */ + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ + set2(L, p, up); /* swap a[up] - a[p] */ + else + lua_pop(L, 2); + } + if (up - lo == 2) /* only 3 elements? */ + return; /* already sorted */ + lua_geti(L, 1, p); /* get middle element (Pivot) */ + lua_pushvalue(L, -1); /* push Pivot */ + lua_geti(L, 1, up - 1); /* push a[up - 1] */ + set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ + p = partition(L, lo, up); + /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ + if (p - lo < up - p) { /* lower interval is smaller? */ + auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ + n = p - lo; /* size of smaller interval */ + lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ + } + else { + auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ + n = up - p; /* size of smaller interval */ + up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ + } + if ((up - lo) / 128 > n) /* partition too imbalanced? */ + rnd = l_randomizePivot(); /* try a new randomization */ + } /* tail call auxsort(L, lo, up, rnd) */ +} + + +static int sort (lua_State *L) { + lua_Integer n = aux_getn(L, 1, TAB_RW); + if (n > 1) { /* non-trivial interval? */ + luaL_argcheck(L, n < INT_MAX, 1, "array too big"); + if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ + luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ + lua_settop(L, 2); /* make sure there are two arguments */ + auxsort(L, 1, (IdxT)n, 0); + } + return 0; +} + +/* }====================================================== */ + + +static const luaL_Reg tab_funcs[] = { + {"concat", tconcat}, + {"insert", tinsert}, + {"pack", tpack}, + {"unpack", tunpack}, + {"remove", tremove}, + {"move", tmove}, + {"sort", sort}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_table (lua_State *L) { + luaL_newlib(L, tab_funcs); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/ltm.c b/src/libs/3rdparty/lua/src/ltm.c new file mode 100644 index 00000000000..07a060811d5 --- /dev/null +++ b/src/libs/3rdparty/lua/src/ltm.c @@ -0,0 +1,271 @@ +/* +** $Id: ltm.c $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#define ltm_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + +static const char udatatypename[] = "userdata"; + +LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = { + "no value", + "nil", "boolean", udatatypename, "number", + "string", "table", "function", udatatypename, "thread", + "upvalue", "proto" /* these last cases are used for tests only */ +}; + + +void luaT_init (lua_State *L) { + static const char *const luaT_eventname[] = { /* ORDER TM */ + "__index", "__newindex", + "__gc", "__mode", "__len", "__eq", + "__add", "__sub", "__mul", "__mod", "__pow", + "__div", "__idiv", + "__band", "__bor", "__bxor", "__shl", "__shr", + "__unm", "__bnot", "__lt", "__le", + "__concat", "__call", "__close" + }; + int i; + for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); + luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ + } +} + + +/* +** function to be used with macro "fasttm": optimized for absence of +** tag methods +*/ +const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { + const TValue *tm = luaH_getshortstr(events, ename); + lua_assert(event <= TM_EQ); + if (notm(tm)) { /* no tag method? */ + events->flags |= cast_byte(1u<metatable; + break; + case LUA_TUSERDATA: + mt = uvalue(o)->metatable; + break; + default: + mt = G(L)->mt[ttype(o)]; + } + return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue); +} + + +/* +** Return the name of the type of an object. For tables and userdata +** with metatable, use their '__name' metafield, if present. +*/ +const char *luaT_objtypename (lua_State *L, const TValue *o) { + Table *mt; + if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || + (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { + const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name")); + if (ttisstring(name)) /* is '__name' a string? */ + return getstr(tsvalue(name)); /* use it as type name */ + } + return ttypename(ttype(o)); /* else use standard type name */ +} + + +void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, const TValue *p3) { + StkId func = L->top.p; + setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ + setobj2s(L, func + 1, p1); /* 1st argument */ + setobj2s(L, func + 2, p2); /* 2nd argument */ + setobj2s(L, func + 3, p3); /* 3rd argument */ + L->top.p = func + 4; + /* metamethod may yield only when called from Lua code */ + if (isLuacode(L->ci)) + luaD_call(L, func, 0); + else + luaD_callnoyield(L, func, 0); +} + + +void luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, StkId res) { + ptrdiff_t result = savestack(L, res); + StkId func = L->top.p; + setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ + setobj2s(L, func + 1, p1); /* 1st argument */ + setobj2s(L, func + 2, p2); /* 2nd argument */ + L->top.p += 3; + /* metamethod may yield only when called from Lua code */ + if (isLuacode(L->ci)) + luaD_call(L, func, 1); + else + luaD_callnoyield(L, func, 1); + res = restorestack(L, result); + setobjs2s(L, res, --L->top.p); /* move result to its place */ +} + + +static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event) { + const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ + if (notm(tm)) + tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ + if (notm(tm)) return 0; + luaT_callTMres(L, tm, p1, p2, res); + return 1; +} + + +void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event) { + if (l_unlikely(!callbinTM(L, p1, p2, res, event))) { + switch (event) { + case TM_BAND: case TM_BOR: case TM_BXOR: + case TM_SHL: case TM_SHR: case TM_BNOT: { + if (ttisnumber(p1) && ttisnumber(p2)) + luaG_tointerror(L, p1, p2); + else + luaG_opinterror(L, p1, p2, "perform bitwise operation on"); + } + /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ + default: + luaG_opinterror(L, p1, p2, "perform arithmetic on"); + } + } +} + + +void luaT_tryconcatTM (lua_State *L) { + StkId top = L->top.p; + if (l_unlikely(!callbinTM(L, s2v(top - 2), s2v(top - 1), top - 2, + TM_CONCAT))) + luaG_concaterror(L, s2v(top - 2), s2v(top - 1)); +} + + +void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2, + int flip, StkId res, TMS event) { + if (flip) + luaT_trybinTM(L, p2, p1, res, event); + else + luaT_trybinTM(L, p1, p2, res, event); +} + + +void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, + int flip, StkId res, TMS event) { + TValue aux; + setivalue(&aux, i2); + luaT_trybinassocTM(L, p1, &aux, flip, res, event); +} + + +/* +** Calls an order tag method. +** For lessequal, LUA_COMPAT_LT_LE keeps compatibility with old +** behavior: if there is no '__le', try '__lt', based on l <= r iff +** !(r < l) (assuming a total order). If the metamethod yields during +** this substitution, the continuation has to know about it (to negate +** the result of rtop.p, event)) /* try original event */ + return !l_isfalse(s2v(L->top.p)); +#if defined(LUA_COMPAT_LT_LE) + else if (event == TM_LE) { + /* try '!(p2 < p1)' for '(p1 <= p2)' */ + L->ci->callstatus |= CIST_LEQ; /* mark it is doing 'lt' for 'le' */ + if (callbinTM(L, p2, p1, L->top.p, TM_LT)) { + L->ci->callstatus ^= CIST_LEQ; /* clear mark */ + return l_isfalse(s2v(L->top.p)); + } + /* else error will remove this 'ci'; no need to clear mark */ + } +#endif + luaG_ordererror(L, p1, p2); /* no metamethod found */ + return 0; /* to avoid warnings */ +} + + +int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, + int flip, int isfloat, TMS event) { + TValue aux; const TValue *p2; + if (isfloat) { + setfltvalue(&aux, cast_num(v2)); + } + else + setivalue(&aux, v2); + if (flip) { /* arguments were exchanged? */ + p2 = p1; p1 = &aux; /* correct them */ + } + else + p2 = &aux; + return luaT_callorderTM(L, p1, p2, event); +} + + +void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci, + const Proto *p) { + int i; + int actual = cast_int(L->top.p - ci->func.p) - 1; /* number of arguments */ + int nextra = actual - nfixparams; /* number of extra arguments */ + ci->u.l.nextraargs = nextra; + luaD_checkstack(L, p->maxstacksize + 1); + /* copy function to the top of the stack */ + setobjs2s(L, L->top.p++, ci->func.p); + /* move fixed parameters to the top of the stack */ + for (i = 1; i <= nfixparams; i++) { + setobjs2s(L, L->top.p++, ci->func.p + i); + setnilvalue(s2v(ci->func.p + i)); /* erase original parameter (for GC) */ + } + ci->func.p += actual + 1; + ci->top.p += actual + 1; + lua_assert(L->top.p <= ci->top.p && ci->top.p <= L->stack_last.p); +} + + +void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) { + int i; + int nextra = ci->u.l.nextraargs; + if (wanted < 0) { + wanted = nextra; /* get all extra arguments available */ + checkstackGCp(L, nextra, where); /* ensure stack space */ + L->top.p = where + nextra; /* next instruction will need top */ + } + for (i = 0; i < wanted && i < nextra; i++) + setobjs2s(L, where + i, ci->func.p - nextra + i); + for (; i < wanted; i++) /* complete required results with nil */ + setnilvalue(s2v(where + i)); +} + diff --git a/src/libs/3rdparty/lua/src/ltm.h b/src/libs/3rdparty/lua/src/ltm.h new file mode 100644 index 00000000000..c309e2ae10e --- /dev/null +++ b/src/libs/3rdparty/lua/src/ltm.h @@ -0,0 +1,104 @@ +/* +** $Id: ltm.h $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#ifndef ltm_h +#define ltm_h + + +#include "lobject.h" +#include "lstate.h" + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER TM" and "ORDER OP" +*/ +typedef enum { + TM_INDEX, + TM_NEWINDEX, + TM_GC, + TM_MODE, + TM_LEN, + TM_EQ, /* last tag method with fast access */ + TM_ADD, + TM_SUB, + TM_MUL, + TM_MOD, + TM_POW, + TM_DIV, + TM_IDIV, + TM_BAND, + TM_BOR, + TM_BXOR, + TM_SHL, + TM_SHR, + TM_UNM, + TM_BNOT, + TM_LT, + TM_LE, + TM_CONCAT, + TM_CALL, + TM_CLOSE, + TM_N /* number of elements in the enum */ +} TMS; + + +/* +** Mask with 1 in all fast-access methods. A 1 in any of these bits +** in the flag of a (meta)table means the metatable does not have the +** corresponding metamethod field. (Bit 7 of the flag is used for +** 'isrealasize'.) +*/ +#define maskflags (~(~0u << (TM_EQ + 1))) + + +/* +** Test whether there is no tagmethod. +** (Because tagmethods use raw accesses, the result may be an "empty" nil.) +*/ +#define notm(tm) ttisnil(tm) + + +#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ + ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) + +#define fasttm(l,et,e) gfasttm(G(l), et, e) + +#define ttypename(x) luaT_typenames_[(x) + 1] + +LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];) + + +LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o); + +LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); +LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, + TMS event); +LUAI_FUNC void luaT_init (lua_State *L); + +LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, const TValue *p3); +LUAI_FUNC void luaT_callTMres (lua_State *L, const TValue *f, + const TValue *p1, const TValue *p2, StkId p3); +LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, + StkId res, TMS event); +LUAI_FUNC void luaT_tryconcatTM (lua_State *L); +LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1, + const TValue *p2, int inv, StkId res, TMS event); +LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, + int inv, StkId res, TMS event); +LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1, + const TValue *p2, TMS event); +LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, + int inv, int isfloat, TMS event); + +LUAI_FUNC void luaT_adjustvarargs (lua_State *L, int nfixparams, + CallInfo *ci, const Proto *p); +LUAI_FUNC void luaT_getvarargs (lua_State *L, CallInfo *ci, + StkId where, int wanted); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lua.c b/src/libs/3rdparty/lua/src/lua.c new file mode 100644 index 00000000000..0ff88454530 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lua.c @@ -0,0 +1,679 @@ +/* +** $Id: lua.c $ +** Lua stand-alone interpreter +** See Copyright Notice in lua.h +*/ + +#define lua_c + +#include "lprefix.h" + + +#include +#include +#include + +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#if !defined(LUA_PROGNAME) +#define LUA_PROGNAME "lua" +#endif + +#if !defined(LUA_INIT_VAR) +#define LUA_INIT_VAR "LUA_INIT" +#endif + +#define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX + + +static lua_State *globalL = NULL; + +static const char *progname = LUA_PROGNAME; + + +#if defined(LUA_USE_POSIX) /* { */ + +/* +** Use 'sigaction' when available. +*/ +static void setsignal (int sig, void (*handler)(int)) { + struct sigaction sa; + sa.sa_handler = handler; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); /* do not mask any signal */ + sigaction(sig, &sa, NULL); +} + +#else /* }{ */ + +#define setsignal signal + +#endif /* } */ + + +/* +** Hook set by signal function to stop the interpreter. +*/ +static void lstop (lua_State *L, lua_Debug *ar) { + (void)ar; /* unused arg. */ + lua_sethook(L, NULL, 0, 0); /* reset hook */ + luaL_error(L, "interrupted!"); +} + + +/* +** Function to be called at a C signal. Because a C signal cannot +** just change a Lua state (as there is no proper synchronization), +** this function only sets a hook that, when called, will stop the +** interpreter. +*/ +static void laction (int i) { + int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT; + setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */ + lua_sethook(globalL, lstop, flag, 1); +} + + +static void print_usage (const char *badoption) { + lua_writestringerror("%s: ", progname); + if (badoption[1] == 'e' || badoption[1] == 'l') + lua_writestringerror("'%s' needs argument\n", badoption); + else + lua_writestringerror("unrecognized option '%s'\n", badoption); + lua_writestringerror( + "usage: %s [options] [script [args]]\n" + "Available options are:\n" + " -e stat execute string 'stat'\n" + " -i enter interactive mode after executing 'script'\n" + " -l mod require library 'mod' into global 'mod'\n" + " -l g=mod require library 'mod' into global 'g'\n" + " -v show version information\n" + " -E ignore environment variables\n" + " -W turn warnings on\n" + " -- stop handling options\n" + " - stop handling options and execute stdin\n" + , + progname); +} + + +/* +** Prints an error message, adding the program name in front of it +** (if present) +*/ +static void l_message (const char *pname, const char *msg) { + if (pname) lua_writestringerror("%s: ", pname); + lua_writestringerror("%s\n", msg); +} + + +/* +** Check whether 'status' is not OK and, if so, prints the error +** message on the top of the stack. It assumes that the error object +** is a string, as it was either generated by Lua or by 'msghandler'. +*/ +static int report (lua_State *L, int status) { + if (status != LUA_OK) { + const char *msg = lua_tostring(L, -1); + l_message(progname, msg); + lua_pop(L, 1); /* remove message */ + } + return status; +} + + +/* +** Message handler used to run all chunks +*/ +static int msghandler (lua_State *L) { + const char *msg = lua_tostring(L, 1); + if (msg == NULL) { /* is error object not a string? */ + if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */ + lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */ + return 1; /* that is the message */ + else + msg = lua_pushfstring(L, "(error object is a %s value)", + luaL_typename(L, 1)); + } + luaL_traceback(L, L, msg, 1); /* append a standard traceback */ + return 1; /* return the traceback */ +} + + +/* +** Interface to 'lua_pcall', which sets appropriate message function +** and C-signal handler. Used to run all chunks. +*/ +static int docall (lua_State *L, int narg, int nres) { + int status; + int base = lua_gettop(L) - narg; /* function index */ + lua_pushcfunction(L, msghandler); /* push message handler */ + lua_insert(L, base); /* put it under function and args */ + globalL = L; /* to be available to 'laction' */ + setsignal(SIGINT, laction); /* set C-signal handler */ + status = lua_pcall(L, narg, nres, base); + setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */ + lua_remove(L, base); /* remove message handler from the stack */ + return status; +} + + +static void print_version (void) { + lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); + lua_writeline(); +} + + +/* +** Create the 'arg' table, which stores all arguments from the +** command line ('argv'). It should be aligned so that, at index 0, +** it has 'argv[script]', which is the script name. The arguments +** to the script (everything after 'script') go to positive indices; +** other arguments (before the script name) go to negative indices. +** If there is no script name, assume interpreter's name as base. +** (If there is no interpreter's name either, 'script' is -1, so +** table sizes are zero.) +*/ +static void createargtable (lua_State *L, char **argv, int argc, int script) { + int i, narg; + narg = argc - (script + 1); /* number of positive indices */ + lua_createtable(L, narg, script + 1); + for (i = 0; i < argc; i++) { + lua_pushstring(L, argv[i]); + lua_rawseti(L, -2, i - script); + } + lua_setglobal(L, "arg"); +} + + +static int dochunk (lua_State *L, int status) { + if (status == LUA_OK) status = docall(L, 0, 0); + return report(L, status); +} + + +static int dofile (lua_State *L, const char *name) { + return dochunk(L, luaL_loadfile(L, name)); +} + + +static int dostring (lua_State *L, const char *s, const char *name) { + return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name)); +} + + +/* +** Receives 'globname[=modname]' and runs 'globname = require(modname)'. +*/ +static int dolibrary (lua_State *L, char *globname) { + int status; + char *modname = strchr(globname, '='); + if (modname == NULL) /* no explicit name? */ + modname = globname; /* module name is equal to global name */ + else { + *modname = '\0'; /* global name ends here */ + modname++; /* module name starts after the '=' */ + } + lua_getglobal(L, "require"); + lua_pushstring(L, modname); + status = docall(L, 1, 1); /* call 'require(modname)' */ + if (status == LUA_OK) + lua_setglobal(L, globname); /* globname = require(modname) */ + return report(L, status); +} + + +/* +** Push on the stack the contents of table 'arg' from 1 to #arg +*/ +static int pushargs (lua_State *L) { + int i, n; + if (lua_getglobal(L, "arg") != LUA_TTABLE) + luaL_error(L, "'arg' is not a table"); + n = (int)luaL_len(L, -1); + luaL_checkstack(L, n + 3, "too many arguments to script"); + for (i = 1; i <= n; i++) + lua_rawgeti(L, -i, i); + lua_remove(L, -i); /* remove table from the stack */ + return n; +} + + +static int handle_script (lua_State *L, char **argv) { + int status; + const char *fname = argv[0]; + if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0) + fname = NULL; /* stdin */ + status = luaL_loadfile(L, fname); + if (status == LUA_OK) { + int n = pushargs(L); /* push arguments to script */ + status = docall(L, n, LUA_MULTRET); + } + return report(L, status); +} + + +/* bits of various argument indicators in 'args' */ +#define has_error 1 /* bad option */ +#define has_i 2 /* -i */ +#define has_v 4 /* -v */ +#define has_e 8 /* -e */ +#define has_E 16 /* -E */ + + +/* +** Traverses all arguments from 'argv', returning a mask with those +** needed before running any Lua code or an error code if it finds any +** invalid argument. In case of error, 'first' is the index of the bad +** argument. Otherwise, 'first' is -1 if there is no program name, +** 0 if there is no script name, or the index of the script name. +*/ +static int collectargs (char **argv, int *first) { + int args = 0; + int i; + if (argv[0] != NULL) { /* is there a program name? */ + if (argv[0][0]) /* not empty? */ + progname = argv[0]; /* save it */ + } + else { /* no program name */ + *first = -1; + return 0; + } + for (i = 1; argv[i] != NULL; i++) { /* handle arguments */ + *first = i; + if (argv[i][0] != '-') /* not an option? */ + return args; /* stop handling options */ + switch (argv[i][1]) { /* else check option */ + case '-': /* '--' */ + if (argv[i][2] != '\0') /* extra characters after '--'? */ + return has_error; /* invalid option */ + *first = i + 1; + return args; + case '\0': /* '-' */ + return args; /* script "name" is '-' */ + case 'E': + if (argv[i][2] != '\0') /* extra characters? */ + return has_error; /* invalid option */ + args |= has_E; + break; + case 'W': + if (argv[i][2] != '\0') /* extra characters? */ + return has_error; /* invalid option */ + break; + case 'i': + args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */ + case 'v': + if (argv[i][2] != '\0') /* extra characters? */ + return has_error; /* invalid option */ + args |= has_v; + break; + case 'e': + args |= has_e; /* FALLTHROUGH */ + case 'l': /* both options need an argument */ + if (argv[i][2] == '\0') { /* no concatenated argument? */ + i++; /* try next 'argv' */ + if (argv[i] == NULL || argv[i][0] == '-') + return has_error; /* no next argument or it is another option */ + } + break; + default: /* invalid option */ + return has_error; + } + } + *first = 0; /* no script name */ + return args; +} + + +/* +** Processes options 'e' and 'l', which involve running Lua code, and +** 'W', which also affects the state. +** Returns 0 if some code raises an error. +*/ +static int runargs (lua_State *L, char **argv, int n) { + int i; + for (i = 1; i < n; i++) { + int option = argv[i][1]; + lua_assert(argv[i][0] == '-'); /* already checked */ + switch (option) { + case 'e': case 'l': { + int status; + char *extra = argv[i] + 2; /* both options need an argument */ + if (*extra == '\0') extra = argv[++i]; + lua_assert(extra != NULL); + status = (option == 'e') + ? dostring(L, extra, "=(command line)") + : dolibrary(L, extra); + if (status != LUA_OK) return 0; + break; + } + case 'W': + lua_warning(L, "@on", 0); /* warnings on */ + break; + } + } + return 1; +} + + +static int handle_luainit (lua_State *L) { + const char *name = "=" LUA_INITVARVERSION; + const char *init = getenv(name + 1); + if (init == NULL) { + name = "=" LUA_INIT_VAR; + init = getenv(name + 1); /* try alternative name */ + } + if (init == NULL) return LUA_OK; + else if (init[0] == '@') + return dofile(L, init+1); + else + return dostring(L, init, name); +} + + +/* +** {================================================================== +** Read-Eval-Print Loop (REPL) +** =================================================================== +*/ + +#if !defined(LUA_PROMPT) +#define LUA_PROMPT "> " +#define LUA_PROMPT2 ">> " +#endif + +#if !defined(LUA_MAXINPUT) +#define LUA_MAXINPUT 512 +#endif + + +/* +** lua_stdin_is_tty detects whether the standard input is a 'tty' (that +** is, whether we're running lua interactively). +*/ +#if !defined(lua_stdin_is_tty) /* { */ + +#if defined(LUA_USE_POSIX) /* { */ + +#include +#define lua_stdin_is_tty() isatty(0) + +#elif defined(LUA_USE_WINDOWS) /* }{ */ + +#include +#include + +#define lua_stdin_is_tty() _isatty(_fileno(stdin)) + +#else /* }{ */ + +/* ISO C definition */ +#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ + +#endif /* } */ + +#endif /* } */ + + +/* +** lua_readline defines how to show a prompt and then read a line from +** the standard input. +** lua_saveline defines how to "save" a read line in a "history". +** lua_freeline defines how to free a line read by lua_readline. +*/ +#if !defined(lua_readline) /* { */ + +#if defined(LUA_USE_READLINE) /* { */ + +#include +#include +#define lua_initreadline(L) ((void)L, rl_readline_name="lua") +#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) +#define lua_saveline(L,line) ((void)L, add_history(line)) +#define lua_freeline(L,b) ((void)L, free(b)) + +#else /* }{ */ + +#define lua_initreadline(L) ((void)L) +#define lua_readline(L,b,p) \ + ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ + fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ +#define lua_saveline(L,line) { (void)L; (void)line; } +#define lua_freeline(L,b) { (void)L; (void)b; } + +#endif /* } */ + +#endif /* } */ + + +/* +** Return the string to be used as a prompt by the interpreter. Leave +** the string (or nil, if using the default value) on the stack, to keep +** it anchored. +*/ +static const char *get_prompt (lua_State *L, int firstline) { + if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL) + return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */ + else { /* apply 'tostring' over the value */ + const char *p = luaL_tolstring(L, -1, NULL); + lua_remove(L, -2); /* remove original value */ + return p; + } +} + +/* mark in error messages for incomplete statements */ +#define EOFMARK "" +#define marklen (sizeof(EOFMARK)/sizeof(char) - 1) + + +/* +** Check whether 'status' signals a syntax error and the error +** message at the top of the stack ends with the above mark for +** incomplete statements. +*/ +static int incomplete (lua_State *L, int status) { + if (status == LUA_ERRSYNTAX) { + size_t lmsg; + const char *msg = lua_tolstring(L, -1, &lmsg); + if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { + lua_pop(L, 1); + return 1; + } + } + return 0; /* else... */ +} + + +/* +** Prompt the user, read a line, and push it into the Lua stack. +*/ +static int pushline (lua_State *L, int firstline) { + char buffer[LUA_MAXINPUT]; + char *b = buffer; + size_t l; + const char *prmt = get_prompt(L, firstline); + int readstatus = lua_readline(L, b, prmt); + if (readstatus == 0) + return 0; /* no input (prompt will be popped by caller) */ + lua_pop(L, 1); /* remove prompt */ + l = strlen(b); + if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ + b[--l] = '\0'; /* remove it */ + if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */ + lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */ + else + lua_pushlstring(L, b, l); + lua_freeline(L, b); + return 1; +} + + +/* +** Try to compile line on the stack as 'return ;'; on return, stack +** has either compiled chunk or original line (if compilation failed). +*/ +static int addreturn (lua_State *L) { + const char *line = lua_tostring(L, -1); /* original line */ + const char *retline = lua_pushfstring(L, "return %s;", line); + int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin"); + if (status == LUA_OK) { + lua_remove(L, -2); /* remove modified line */ + if (line[0] != '\0') /* non empty? */ + lua_saveline(L, line); /* keep history */ + } + else + lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */ + return status; +} + + +/* +** Read multiple lines until a complete Lua statement +*/ +static int multiline (lua_State *L) { + for (;;) { /* repeat until gets a complete statement */ + size_t len; + const char *line = lua_tolstring(L, 1, &len); /* get what it has */ + int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */ + if (!incomplete(L, status) || !pushline(L, 0)) { + lua_saveline(L, line); /* keep history */ + return status; /* cannot or should not try to add continuation line */ + } + lua_pushliteral(L, "\n"); /* add newline... */ + lua_insert(L, -2); /* ...between the two lines */ + lua_concat(L, 3); /* join them */ + } +} + + +/* +** Read a line and try to load (compile) it first as an expression (by +** adding "return " in front of it) and second as a statement. Return +** the final status of load/call with the resulting function (if any) +** in the top of the stack. +*/ +static int loadline (lua_State *L) { + int status; + lua_settop(L, 0); + if (!pushline(L, 1)) + return -1; /* no input */ + if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */ + status = multiline(L); /* try as command, maybe with continuation lines */ + lua_remove(L, 1); /* remove line from the stack */ + lua_assert(lua_gettop(L) == 1); + return status; +} + + +/* +** Prints (calling the Lua 'print' function) any values on the stack +*/ +static void l_print (lua_State *L) { + int n = lua_gettop(L); + if (n > 0) { /* any result to be printed? */ + luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); + lua_getglobal(L, "print"); + lua_insert(L, 1); + if (lua_pcall(L, n, 0, 0) != LUA_OK) + l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)", + lua_tostring(L, -1))); + } +} + + +/* +** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and +** print any results. +*/ +static void doREPL (lua_State *L) { + int status; + const char *oldprogname = progname; + progname = NULL; /* no 'progname' on errors in interactive mode */ + lua_initreadline(L); + while ((status = loadline(L)) != -1) { + if (status == LUA_OK) + status = docall(L, 0, LUA_MULTRET); + if (status == LUA_OK) l_print(L); + else report(L, status); + } + lua_settop(L, 0); /* clear stack */ + lua_writeline(); + progname = oldprogname; +} + +/* }================================================================== */ + + +/* +** Main body of stand-alone interpreter (to be called in protected mode). +** Reads the options and handles them all. +*/ +static int pmain (lua_State *L) { + int argc = (int)lua_tointeger(L, 1); + char **argv = (char **)lua_touserdata(L, 2); + int script; + int args = collectargs(argv, &script); + int optlim = (script > 0) ? script : argc; /* first argv not an option */ + luaL_checkversion(L); /* check that interpreter has correct version */ + if (args == has_error) { /* bad arg? */ + print_usage(argv[script]); /* 'script' has index of bad arg. */ + return 0; + } + if (args & has_v) /* option '-v'? */ + print_version(); + if (args & has_E) { /* option '-E'? */ + lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */ + lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); + } + luaL_openlibs(L); /* open standard libraries */ + createargtable(L, argv, argc, script); /* create table 'arg' */ + lua_gc(L, LUA_GCRESTART); /* start GC... */ + lua_gc(L, LUA_GCGEN, 0, 0); /* ...in generational mode */ + if (!(args & has_E)) { /* no option '-E'? */ + if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */ + return 0; /* error running LUA_INIT */ + } + if (!runargs(L, argv, optlim)) /* execute arguments -e and -l */ + return 0; /* something failed */ + if (script > 0) { /* execute main script (if there is one) */ + if (handle_script(L, argv + script) != LUA_OK) + return 0; /* interrupt in case of error */ + } + if (args & has_i) /* -i option? */ + doREPL(L); /* do read-eval-print loop */ + else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */ + if (lua_stdin_is_tty()) { /* running in interactive mode? */ + print_version(); + doREPL(L); /* do read-eval-print loop */ + } + else dofile(L, NULL); /* executes stdin as a file */ + } + lua_pushboolean(L, 1); /* signal no errors */ + return 1; +} + + +int main (int argc, char **argv) { + int status, result; + lua_State *L = luaL_newstate(); /* create state */ + if (L == NULL) { + l_message(argv[0], "cannot create state: not enough memory"); + return EXIT_FAILURE; + } + lua_gc(L, LUA_GCSTOP); /* stop GC while building state */ + lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */ + lua_pushinteger(L, argc); /* 1st argument */ + lua_pushlightuserdata(L, argv); /* 2nd argument */ + status = lua_pcall(L, 2, 1, 0); /* do the call */ + result = lua_toboolean(L, -1); /* get result */ + report(L, status); + lua_close(L); + return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE; +} + diff --git a/src/libs/3rdparty/lua/src/lua.h b/src/libs/3rdparty/lua/src/lua.h new file mode 100644 index 00000000000..fd16cf8050b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lua.h @@ -0,0 +1,523 @@ +/* +** $Id: lua.h $ +** Lua - A Scripting Language +** Lua.org, PUC-Rio, Brazil (http://www.lua.org) +** See Copyright Notice at the end of this file +*/ + + +#ifndef lua_h +#define lua_h + +#include +#include + + +#include "luaconf.h" + + +#define LUA_VERSION_MAJOR "5" +#define LUA_VERSION_MINOR "4" +#define LUA_VERSION_RELEASE "6" + +#define LUA_VERSION_NUM 504 +#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 6) + +#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE +#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2023 Lua.org, PUC-Rio" +#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" + + +/* mark for precompiled code ('Lua') */ +#define LUA_SIGNATURE "\x1bLua" + +/* option for multiple returns in 'lua_pcall' and 'lua_call' */ +#define LUA_MULTRET (-1) + + +/* +** Pseudo-indices +** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty +** space after that to help overflow detection) +*/ +#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) +#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) + + +/* thread status */ +#define LUA_OK 0 +#define LUA_YIELD 1 +#define LUA_ERRRUN 2 +#define LUA_ERRSYNTAX 3 +#define LUA_ERRMEM 4 +#define LUA_ERRERR 5 + + +typedef struct lua_State lua_State; + + +/* +** basic types +*/ +#define LUA_TNONE (-1) + +#define LUA_TNIL 0 +#define LUA_TBOOLEAN 1 +#define LUA_TLIGHTUSERDATA 2 +#define LUA_TNUMBER 3 +#define LUA_TSTRING 4 +#define LUA_TTABLE 5 +#define LUA_TFUNCTION 6 +#define LUA_TUSERDATA 7 +#define LUA_TTHREAD 8 + +#define LUA_NUMTYPES 9 + + + +/* minimum Lua stack available to a C function */ +#define LUA_MINSTACK 20 + + +/* predefined values in the registry */ +#define LUA_RIDX_MAINTHREAD 1 +#define LUA_RIDX_GLOBALS 2 +#define LUA_RIDX_LAST LUA_RIDX_GLOBALS + + +/* type of numbers in Lua */ +typedef LUA_NUMBER lua_Number; + + +/* type for integer functions */ +typedef LUA_INTEGER lua_Integer; + +/* unsigned integer type */ +typedef LUA_UNSIGNED lua_Unsigned; + +/* type for continuation-function contexts */ +typedef LUA_KCONTEXT lua_KContext; + + +/* +** Type for C functions registered with Lua +*/ +typedef int (*lua_CFunction) (lua_State *L); + +/* +** Type for continuation functions +*/ +typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); + + +/* +** Type for functions that read/write blocks when loading/dumping Lua chunks +*/ +typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); + +typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); + + +/* +** Type for memory-allocation functions +*/ +typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); + + +/* +** Type for warning functions +*/ +typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); + + +/* +** Type used by the debug API to collect debug information +*/ +typedef struct lua_Debug lua_Debug; + + +/* +** Functions to be called by the debugger in specific events +*/ +typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); + + +/* +** generic extra include file +*/ +#if defined(LUA_USER_H) +#include LUA_USER_H +#endif + + +/* +** RCS ident string +*/ +extern const char lua_ident[]; + + +/* +** state manipulation +*/ +LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); +LUA_API void (lua_close) (lua_State *L); +LUA_API lua_State *(lua_newthread) (lua_State *L); +LUA_API int (lua_closethread) (lua_State *L, lua_State *from); +LUA_API int (lua_resetthread) (lua_State *L); /* Deprecated! */ + +LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); + + +LUA_API lua_Number (lua_version) (lua_State *L); + + +/* +** basic stack manipulation +*/ +LUA_API int (lua_absindex) (lua_State *L, int idx); +LUA_API int (lua_gettop) (lua_State *L); +LUA_API void (lua_settop) (lua_State *L, int idx); +LUA_API void (lua_pushvalue) (lua_State *L, int idx); +LUA_API void (lua_rotate) (lua_State *L, int idx, int n); +LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); +LUA_API int (lua_checkstack) (lua_State *L, int n); + +LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); + + +/* +** access functions (stack -> C) +*/ + +LUA_API int (lua_isnumber) (lua_State *L, int idx); +LUA_API int (lua_isstring) (lua_State *L, int idx); +LUA_API int (lua_iscfunction) (lua_State *L, int idx); +LUA_API int (lua_isinteger) (lua_State *L, int idx); +LUA_API int (lua_isuserdata) (lua_State *L, int idx); +LUA_API int (lua_type) (lua_State *L, int idx); +LUA_API const char *(lua_typename) (lua_State *L, int tp); + +LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum); +LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum); +LUA_API int (lua_toboolean) (lua_State *L, int idx); +LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); +LUA_API lua_Unsigned (lua_rawlen) (lua_State *L, int idx); +LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); +LUA_API void *(lua_touserdata) (lua_State *L, int idx); +LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); +LUA_API const void *(lua_topointer) (lua_State *L, int idx); + + +/* +** Comparison and arithmetic functions +*/ + +#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ +#define LUA_OPSUB 1 +#define LUA_OPMUL 2 +#define LUA_OPMOD 3 +#define LUA_OPPOW 4 +#define LUA_OPDIV 5 +#define LUA_OPIDIV 6 +#define LUA_OPBAND 7 +#define LUA_OPBOR 8 +#define LUA_OPBXOR 9 +#define LUA_OPSHL 10 +#define LUA_OPSHR 11 +#define LUA_OPUNM 12 +#define LUA_OPBNOT 13 + +LUA_API void (lua_arith) (lua_State *L, int op); + +#define LUA_OPEQ 0 +#define LUA_OPLT 1 +#define LUA_OPLE 2 + +LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); + + +/* +** push functions (C -> stack) +*/ +LUA_API void (lua_pushnil) (lua_State *L); +LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); +LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); +LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); +LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); +LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, + va_list argp); +LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); +LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); +LUA_API void (lua_pushboolean) (lua_State *L, int b); +LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); +LUA_API int (lua_pushthread) (lua_State *L); + + +/* +** get functions (Lua -> stack) +*/ +LUA_API int (lua_getglobal) (lua_State *L, const char *name); +LUA_API int (lua_gettable) (lua_State *L, int idx); +LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); +LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); +LUA_API int (lua_rawget) (lua_State *L, int idx); +LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n); +LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p); + +LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); +LUA_API void *(lua_newuserdatauv) (lua_State *L, size_t sz, int nuvalue); +LUA_API int (lua_getmetatable) (lua_State *L, int objindex); +LUA_API int (lua_getiuservalue) (lua_State *L, int idx, int n); + + +/* +** set functions (stack -> Lua) +*/ +LUA_API void (lua_setglobal) (lua_State *L, const char *name); +LUA_API void (lua_settable) (lua_State *L, int idx); +LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); +LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); +LUA_API void (lua_rawset) (lua_State *L, int idx); +LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n); +LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p); +LUA_API int (lua_setmetatable) (lua_State *L, int objindex); +LUA_API int (lua_setiuservalue) (lua_State *L, int idx, int n); + + +/* +** 'load' and 'call' functions (load and run Lua code) +*/ +LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, + lua_KContext ctx, lua_KFunction k); +#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) + +LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, + lua_KContext ctx, lua_KFunction k); +#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) + +LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, + const char *chunkname, const char *mode); + +LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); + + +/* +** coroutine functions +*/ +LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, + lua_KFunction k); +LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg, + int *nres); +LUA_API int (lua_status) (lua_State *L); +LUA_API int (lua_isyieldable) (lua_State *L); + +#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) + + +/* +** Warning-related functions +*/ +LUA_API void (lua_setwarnf) (lua_State *L, lua_WarnFunction f, void *ud); +LUA_API void (lua_warning) (lua_State *L, const char *msg, int tocont); + + +/* +** garbage-collection function and options +*/ + +#define LUA_GCSTOP 0 +#define LUA_GCRESTART 1 +#define LUA_GCCOLLECT 2 +#define LUA_GCCOUNT 3 +#define LUA_GCCOUNTB 4 +#define LUA_GCSTEP 5 +#define LUA_GCSETPAUSE 6 +#define LUA_GCSETSTEPMUL 7 +#define LUA_GCISRUNNING 9 +#define LUA_GCGEN 10 +#define LUA_GCINC 11 + +LUA_API int (lua_gc) (lua_State *L, int what, ...); + + +/* +** miscellaneous functions +*/ + +LUA_API int (lua_error) (lua_State *L); + +LUA_API int (lua_next) (lua_State *L, int idx); + +LUA_API void (lua_concat) (lua_State *L, int n); +LUA_API void (lua_len) (lua_State *L, int idx); + +LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s); + +LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); +LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); + +LUA_API void (lua_toclose) (lua_State *L, int idx); +LUA_API void (lua_closeslot) (lua_State *L, int idx); + + +/* +** {============================================================== +** some useful macros +** =============================================================== +*/ + +#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) + +#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) +#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) + +#define lua_pop(L,n) lua_settop(L, -(n)-1) + +#define lua_newtable(L) lua_createtable(L, 0, 0) + +#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) + +#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) + +#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) +#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) +#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) +#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) +#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) +#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) +#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) + +#define lua_pushliteral(L, s) lua_pushstring(L, "" s) + +#define lua_pushglobaltable(L) \ + ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) + +#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) + + +#define lua_insert(L,idx) lua_rotate(L, (idx), 1) + +#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) + +#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) + +/* }============================================================== */ + + +/* +** {============================================================== +** compatibility macros +** =============================================================== +*/ +#if defined(LUA_COMPAT_APIINTCASTS) + +#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) +#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) +#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) + +#endif + +#define lua_newuserdata(L,s) lua_newuserdatauv(L,s,1) +#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1) +#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1) + +#define LUA_NUMTAGS LUA_NUMTYPES + +/* }============================================================== */ + +/* +** {====================================================================== +** Debug API +** ======================================================================= +*/ + + +/* +** Event codes +*/ +#define LUA_HOOKCALL 0 +#define LUA_HOOKRET 1 +#define LUA_HOOKLINE 2 +#define LUA_HOOKCOUNT 3 +#define LUA_HOOKTAILCALL 4 + + +/* +** Event masks +*/ +#define LUA_MASKCALL (1 << LUA_HOOKCALL) +#define LUA_MASKRET (1 << LUA_HOOKRET) +#define LUA_MASKLINE (1 << LUA_HOOKLINE) +#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) + + +LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar); +LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar); +LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n); +LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n); +LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n); + +LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); +LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1, + int fidx2, int n2); + +LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count); +LUA_API lua_Hook (lua_gethook) (lua_State *L); +LUA_API int (lua_gethookmask) (lua_State *L); +LUA_API int (lua_gethookcount) (lua_State *L); + +LUA_API int (lua_setcstacklimit) (lua_State *L, unsigned int limit); + +struct lua_Debug { + int event; + const char *name; /* (n) */ + const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ + const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ + const char *source; /* (S) */ + size_t srclen; /* (S) */ + int currentline; /* (l) */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + unsigned char nups; /* (u) number of upvalues */ + unsigned char nparams;/* (u) number of parameters */ + char isvararg; /* (u) */ + char istailcall; /* (t) */ + unsigned short ftransfer; /* (r) index of first value transferred */ + unsigned short ntransfer; /* (r) number of transferred values */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + struct CallInfo *i_ci; /* active function */ +}; + +/* }====================================================================== */ + + +/****************************************************************************** +* Copyright (C) 1994-2023 Lua.org, PUC-Rio. +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +******************************************************************************/ + + +#endif diff --git a/src/libs/3rdparty/lua/src/lua.hpp b/src/libs/3rdparty/lua/src/lua.hpp new file mode 100644 index 00000000000..ec417f59469 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lua.hpp @@ -0,0 +1,9 @@ +// lua.hpp +// Lua header files for C++ +// <> not supplied automatically because Lua also compiles as C++ + +extern "C" { +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +} diff --git a/src/libs/3rdparty/lua/src/luac.c b/src/libs/3rdparty/lua/src/luac.c new file mode 100644 index 00000000000..5f4a141bddd --- /dev/null +++ b/src/libs/3rdparty/lua/src/luac.c @@ -0,0 +1,723 @@ +/* +** $Id: luac.c $ +** Lua compiler (saves bytecodes to files; also lists bytecodes) +** See Copyright Notice in lua.h +*/ + +#define luac_c +#define LUA_CORE + +#include "lprefix.h" + +#include +#include +#include +#include +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "ldebug.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lopnames.h" +#include "lstate.h" +#include "lundump.h" + +static void PrintFunction(const Proto* f, int full); +#define luaU_print PrintFunction + +#define PROGNAME "luac" /* default program name */ +#define OUTPUT PROGNAME ".out" /* default output file */ + +static int listing=0; /* list bytecodes? */ +static int dumping=1; /* dump bytecodes? */ +static int stripping=0; /* strip debug information? */ +static char Output[]={ OUTPUT }; /* default output file name */ +static const char* output=Output; /* actual output file name */ +static const char* progname=PROGNAME; /* actual program name */ +static TString **tmname; + +static void fatal(const char* message) +{ + fprintf(stderr,"%s: %s\n",progname,message); + exit(EXIT_FAILURE); +} + +static void cannot(const char* what) +{ + fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno)); + exit(EXIT_FAILURE); +} + +static void usage(const char* message) +{ + if (*message=='-') + fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message); + else + fprintf(stderr,"%s: %s\n",progname,message); + fprintf(stderr, + "usage: %s [options] [filenames]\n" + "Available options are:\n" + " -l list (use -l -l for full listing)\n" + " -o name output to file 'name' (default is \"%s\")\n" + " -p parse only\n" + " -s strip debug information\n" + " -v show version information\n" + " -- stop handling options\n" + " - stop handling options and process stdin\n" + ,progname,Output); + exit(EXIT_FAILURE); +} + +#define IS(s) (strcmp(argv[i],s)==0) + +static int doargs(int argc, char* argv[]) +{ + int i; + int version=0; + if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; + for (i=1; itop.p+(i))) + +static const Proto* combine(lua_State* L, int n) +{ + if (n==1) + return toproto(L,-1); + else + { + Proto* f; + int i=n; + if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1)); + f=toproto(L,-1); + for (i=0; ip[i]=toproto(L,i-n-1); + if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0; + } + return f; + } +} + +static int writer(lua_State* L, const void* p, size_t size, void* u) +{ + UNUSED(L); + return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0); +} + +static int pmain(lua_State* L) +{ + int argc=(int)lua_tointeger(L,1); + char** argv=(char**)lua_touserdata(L,2); + const Proto* f; + int i; + tmname=G(L)->tmname; + if (!lua_checkstack(L,argc)) fatal("too many input files"); + for (i=0; i1); + if (dumping) + { + FILE* D= (output==NULL) ? stdout : fopen(output,"wb"); + if (D==NULL) cannot("open"); + lua_lock(L); + luaU_dump(L,f,writer,D,stripping); + lua_unlock(L); + if (ferror(D)) cannot("write"); + if (fclose(D)) cannot("close"); + } + return 0; +} + +int main(int argc, char* argv[]) +{ + lua_State* L; + int i=doargs(argc,argv); + argc-=i; argv+=i; + if (argc<=0) usage("no input files given"); + L=luaL_newstate(); + if (L==NULL) fatal("cannot create state: not enough memory"); + lua_pushcfunction(L,&pmain); + lua_pushinteger(L,argc); + lua_pushlightuserdata(L,argv); + if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1)); + lua_close(L); + return EXIT_SUCCESS; +} + +/* +** print bytecodes +*/ + +#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-") +#define VOID(p) ((const void*)(p)) +#define eventname(i) (getstr(tmname[i])) + +static void PrintString(const TString* ts) +{ + const char* s=getstr(ts); + size_t i,n=tsslen(ts); + printf("\""); + for (i=0; ik[i]; + switch (ttypetag(o)) + { + case LUA_VNIL: + printf("N"); + break; + case LUA_VFALSE: + case LUA_VTRUE: + printf("B"); + break; + case LUA_VNUMFLT: + printf("F"); + break; + case LUA_VNUMINT: + printf("I"); + break; + case LUA_VSHRSTR: + case LUA_VLNGSTR: + printf("S"); + break; + default: /* cannot happen */ + printf("?%d",ttypetag(o)); + break; + } + printf("\t"); +} + +static void PrintConstant(const Proto* f, int i) +{ + const TValue* o=&f->k[i]; + switch (ttypetag(o)) + { + case LUA_VNIL: + printf("nil"); + break; + case LUA_VFALSE: + printf("false"); + break; + case LUA_VTRUE: + printf("true"); + break; + case LUA_VNUMFLT: + { + char buff[100]; + sprintf(buff,LUA_NUMBER_FMT,fltvalue(o)); + printf("%s",buff); + if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0"); + break; + } + case LUA_VNUMINT: + printf(LUA_INTEGER_FMT,ivalue(o)); + break; + case LUA_VSHRSTR: + case LUA_VLNGSTR: + PrintString(tsvalue(o)); + break; + default: /* cannot happen */ + printf("?%d",ttypetag(o)); + break; + } +} + +#define COMMENT "\t; " +#define EXTRAARG GETARG_Ax(code[pc+1]) +#define EXTRAARGC (EXTRAARG*(MAXARG_C+1)) +#define ISK (isk ? "k" : "") + +static void PrintCode(const Proto* f) +{ + const Instruction* code=f->code; + int pc,n=f->sizecode; + for (pc=0; pc0) printf("[%d]\t",line); else printf("[-]\t"); + printf("%-9s\t",opnames[o]); + switch (o) + { + case OP_MOVE: + printf("%d %d",a,b); + break; + case OP_LOADI: + printf("%d %d",a,sbx); + break; + case OP_LOADF: + printf("%d %d",a,sbx); + break; + case OP_LOADK: + printf("%d %d",a,bx); + printf(COMMENT); PrintConstant(f,bx); + break; + case OP_LOADKX: + printf("%d",a); + printf(COMMENT); PrintConstant(f,EXTRAARG); + break; + case OP_LOADFALSE: + printf("%d",a); + break; + case OP_LFALSESKIP: + printf("%d",a); + break; + case OP_LOADTRUE: + printf("%d",a); + break; + case OP_LOADNIL: + printf("%d %d",a,b); + printf(COMMENT "%d out",b+1); + break; + case OP_GETUPVAL: + printf("%d %d",a,b); + printf(COMMENT "%s",UPVALNAME(b)); + break; + case OP_SETUPVAL: + printf("%d %d",a,b); + printf(COMMENT "%s",UPVALNAME(b)); + break; + case OP_GETTABUP: + printf("%d %d %d",a,b,c); + printf(COMMENT "%s",UPVALNAME(b)); + printf(" "); PrintConstant(f,c); + break; + case OP_GETTABLE: + printf("%d %d %d",a,b,c); + break; + case OP_GETI: + printf("%d %d %d",a,b,c); + break; + case OP_GETFIELD: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_SETTABUP: + printf("%d %d %d%s",a,b,c,ISK); + printf(COMMENT "%s",UPVALNAME(a)); + printf(" "); PrintConstant(f,b); + if (isk) { printf(" "); PrintConstant(f,c); } + break; + case OP_SETTABLE: + printf("%d %d %d%s",a,b,c,ISK); + if (isk) { printf(COMMENT); PrintConstant(f,c); } + break; + case OP_SETI: + printf("%d %d %d%s",a,b,c,ISK); + if (isk) { printf(COMMENT); PrintConstant(f,c); } + break; + case OP_SETFIELD: + printf("%d %d %d%s",a,b,c,ISK); + printf(COMMENT); PrintConstant(f,b); + if (isk) { printf(" "); PrintConstant(f,c); } + break; + case OP_NEWTABLE: + printf("%d %d %d",a,b,c); + printf(COMMENT "%d",c+EXTRAARGC); + break; + case OP_SELF: + printf("%d %d %d%s",a,b,c,ISK); + if (isk) { printf(COMMENT); PrintConstant(f,c); } + break; + case OP_ADDI: + printf("%d %d %d",a,b,sc); + break; + case OP_ADDK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_SUBK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_MULK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_MODK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_POWK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_DIVK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_IDIVK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_BANDK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_BORK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_BXORK: + printf("%d %d %d",a,b,c); + printf(COMMENT); PrintConstant(f,c); + break; + case OP_SHRI: + printf("%d %d %d",a,b,sc); + break; + case OP_SHLI: + printf("%d %d %d",a,b,sc); + break; + case OP_ADD: + printf("%d %d %d",a,b,c); + break; + case OP_SUB: + printf("%d %d %d",a,b,c); + break; + case OP_MUL: + printf("%d %d %d",a,b,c); + break; + case OP_MOD: + printf("%d %d %d",a,b,c); + break; + case OP_POW: + printf("%d %d %d",a,b,c); + break; + case OP_DIV: + printf("%d %d %d",a,b,c); + break; + case OP_IDIV: + printf("%d %d %d",a,b,c); + break; + case OP_BAND: + printf("%d %d %d",a,b,c); + break; + case OP_BOR: + printf("%d %d %d",a,b,c); + break; + case OP_BXOR: + printf("%d %d %d",a,b,c); + break; + case OP_SHL: + printf("%d %d %d",a,b,c); + break; + case OP_SHR: + printf("%d %d %d",a,b,c); + break; + case OP_MMBIN: + printf("%d %d %d",a,b,c); + printf(COMMENT "%s",eventname(c)); + break; + case OP_MMBINI: + printf("%d %d %d %d",a,sb,c,isk); + printf(COMMENT "%s",eventname(c)); + if (isk) printf(" flip"); + break; + case OP_MMBINK: + printf("%d %d %d %d",a,b,c,isk); + printf(COMMENT "%s ",eventname(c)); PrintConstant(f,b); + if (isk) printf(" flip"); + break; + case OP_UNM: + printf("%d %d",a,b); + break; + case OP_BNOT: + printf("%d %d",a,b); + break; + case OP_NOT: + printf("%d %d",a,b); + break; + case OP_LEN: + printf("%d %d",a,b); + break; + case OP_CONCAT: + printf("%d %d",a,b); + break; + case OP_CLOSE: + printf("%d",a); + break; + case OP_TBC: + printf("%d",a); + break; + case OP_JMP: + printf("%d",GETARG_sJ(i)); + printf(COMMENT "to %d",GETARG_sJ(i)+pc+2); + break; + case OP_EQ: + printf("%d %d %d",a,b,isk); + break; + case OP_LT: + printf("%d %d %d",a,b,isk); + break; + case OP_LE: + printf("%d %d %d",a,b,isk); + break; + case OP_EQK: + printf("%d %d %d",a,b,isk); + printf(COMMENT); PrintConstant(f,b); + break; + case OP_EQI: + printf("%d %d %d",a,sb,isk); + break; + case OP_LTI: + printf("%d %d %d",a,sb,isk); + break; + case OP_LEI: + printf("%d %d %d",a,sb,isk); + break; + case OP_GTI: + printf("%d %d %d",a,sb,isk); + break; + case OP_GEI: + printf("%d %d %d",a,sb,isk); + break; + case OP_TEST: + printf("%d %d",a,isk); + break; + case OP_TESTSET: + printf("%d %d %d",a,b,isk); + break; + case OP_CALL: + printf("%d %d %d",a,b,c); + printf(COMMENT); + if (b==0) printf("all in "); else printf("%d in ",b-1); + if (c==0) printf("all out"); else printf("%d out",c-1); + break; + case OP_TAILCALL: + printf("%d %d %d%s",a,b,c,ISK); + printf(COMMENT "%d in",b-1); + break; + case OP_RETURN: + printf("%d %d %d%s",a,b,c,ISK); + printf(COMMENT); + if (b==0) printf("all out"); else printf("%d out",b-1); + break; + case OP_RETURN0: + break; + case OP_RETURN1: + printf("%d",a); + break; + case OP_FORLOOP: + printf("%d %d",a,bx); + printf(COMMENT "to %d",pc-bx+2); + break; + case OP_FORPREP: + printf("%d %d",a,bx); + printf(COMMENT "exit to %d",pc+bx+3); + break; + case OP_TFORPREP: + printf("%d %d",a,bx); + printf(COMMENT "to %d",pc+bx+2); + break; + case OP_TFORCALL: + printf("%d %d",a,c); + break; + case OP_TFORLOOP: + printf("%d %d",a,bx); + printf(COMMENT "to %d",pc-bx+2); + break; + case OP_SETLIST: + printf("%d %d %d",a,b,c); + if (isk) printf(COMMENT "%d",c+EXTRAARGC); + break; + case OP_CLOSURE: + printf("%d %d",a,bx); + printf(COMMENT "%p",VOID(f->p[bx])); + break; + case OP_VARARG: + printf("%d %d",a,c); + printf(COMMENT); + if (c==0) printf("all out"); else printf("%d out",c-1); + break; + case OP_VARARGPREP: + printf("%d",a); + break; + case OP_EXTRAARG: + printf("%d",ax); + break; +#if 0 + default: + printf("%d %d %d",a,b,c); + printf(COMMENT "not handled"); + break; +#endif + } + printf("\n"); + } +} + + +#define SS(x) ((x==1)?"":"s") +#define S(x) (int)(x),SS(x) + +static void PrintHeader(const Proto* f) +{ + const char* s=f->source ? getstr(f->source) : "=?"; + if (*s=='@' || *s=='=') + s++; + else if (*s==LUA_SIGNATURE[0]) + s="(bstring)"; + else + s="(string)"; + printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n", + (f->linedefined==0)?"main":"function",s, + f->linedefined,f->lastlinedefined, + S(f->sizecode),VOID(f)); + printf("%d%s param%s, %d slot%s, %d upvalue%s, ", + (int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams), + S(f->maxstacksize),S(f->sizeupvalues)); + printf("%d local%s, %d constant%s, %d function%s\n", + S(f->sizelocvars),S(f->sizek),S(f->sizep)); +} + +static void PrintDebug(const Proto* f) +{ + int i,n; + n=f->sizek; + printf("constants (%d) for %p:\n",n,VOID(f)); + for (i=0; isizelocvars; + printf("locals (%d) for %p:\n",n,VOID(f)); + for (i=0; ilocvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1); + } + n=f->sizeupvalues; + printf("upvalues (%d) for %p:\n",n,VOID(f)); + for (i=0; iupvalues[i].instack,f->upvalues[i].idx); + } +} + +static void PrintFunction(const Proto* f, int full) +{ + int i,n=f->sizep; + PrintHeader(f); + PrintCode(f); + if (full) PrintDebug(f); + for (i=0; ip[i],full); +} diff --git a/src/libs/3rdparty/lua/src/luaconf.h b/src/libs/3rdparty/lua/src/luaconf.h new file mode 100644 index 00000000000..137103edec4 --- /dev/null +++ b/src/libs/3rdparty/lua/src/luaconf.h @@ -0,0 +1,793 @@ +/* +** $Id: luaconf.h $ +** Configuration file for Lua +** See Copyright Notice in lua.h +*/ + + +#ifndef luaconf_h +#define luaconf_h + +#include +#include + + +/* +** =================================================================== +** General Configuration File for Lua +** +** Some definitions here can be changed externally, through the compiler +** (e.g., with '-D' options): They are commented out or protected +** by '#if !defined' guards. However, several other definitions +** should be changed directly here, either because they affect the +** Lua ABI (by making the changes here, you ensure that all software +** connected to Lua, such as C libraries, will be compiled with the same +** configuration); or because they are seldom changed. +** +** Search for "@@" to find all configurable definitions. +** =================================================================== +*/ + + +/* +** {==================================================================== +** System Configuration: macros to adapt (if needed) Lua to some +** particular platform, for instance restricting it to C89. +** ===================================================================== +*/ + +/* +@@ LUA_USE_C89 controls the use of non-ISO-C89 features. +** Define it if you want Lua to avoid the use of a few C99 features +** or Windows-specific features on Windows. +*/ +/* #define LUA_USE_C89 */ + + +/* +** By default, Lua on Windows use (some) specific Windows features +*/ +#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) +#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ +#endif + + +#if defined(LUA_USE_WINDOWS) +#define LUA_DL_DLL /* enable support for DLL */ +#define LUA_USE_C89 /* broadly, Windows is C89 */ +#endif + + +#if defined(LUA_USE_LINUX) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ +#endif + + +#if defined(LUA_USE_MACOSX) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ +#endif + + +#if defined(LUA_USE_IOS) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN +#endif + + +/* +@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits. +*/ +#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3) + +/* }================================================================== */ + + + +/* +** {================================================================== +** Configuration for Number types. These options should not be +** set externally, because any other code connected to Lua must +** use the same configuration. +** =================================================================== +*/ + +/* +@@ LUA_INT_TYPE defines the type for Lua integers. +@@ LUA_FLOAT_TYPE defines the type for Lua floats. +** Lua should work fine with any mix of these options supported +** by your C compiler. The usual configurations are 64-bit integers +** and 'double' (the default), 32-bit integers and 'float' (for +** restricted platforms), and 'long'/'double' (for C compilers not +** compliant with C99, which may not have support for 'long long'). +*/ + +/* predefined options for LUA_INT_TYPE */ +#define LUA_INT_INT 1 +#define LUA_INT_LONG 2 +#define LUA_INT_LONGLONG 3 + +/* predefined options for LUA_FLOAT_TYPE */ +#define LUA_FLOAT_FLOAT 1 +#define LUA_FLOAT_DOUBLE 2 +#define LUA_FLOAT_LONGDOUBLE 3 + + +/* Default configuration ('long long' and 'double', for 64-bit Lua) */ +#define LUA_INT_DEFAULT LUA_INT_LONGLONG +#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE + + +/* +@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. +*/ +#define LUA_32BITS 0 + + +/* +@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for +** C89 ('long' and 'double'); Windows always has '__int64', so it does +** not need to use this case. +*/ +#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) +#define LUA_C89_NUMBERS 1 +#else +#define LUA_C89_NUMBERS 0 +#endif + + +#if LUA_32BITS /* { */ +/* +** 32-bit integers and 'float' +*/ +#if LUAI_IS32INT /* use 'int' if big enough */ +#define LUA_INT_TYPE LUA_INT_INT +#else /* otherwise use 'long' */ +#define LUA_INT_TYPE LUA_INT_LONG +#endif +#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT + +#elif LUA_C89_NUMBERS /* }{ */ +/* +** largest types available for C89 ('long' and 'double') +*/ +#define LUA_INT_TYPE LUA_INT_LONG +#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE + +#else /* }{ */ +/* use defaults */ + +#define LUA_INT_TYPE LUA_INT_DEFAULT +#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT + +#endif /* } */ + + +/* }================================================================== */ + + + +/* +** {================================================================== +** Configuration for Paths. +** =================================================================== +*/ + +/* +** LUA_PATH_SEP is the character that separates templates in a path. +** LUA_PATH_MARK is the string that marks the substitution points in a +** template. +** LUA_EXEC_DIR in a Windows path is replaced by the executable's +** directory. +*/ +#define LUA_PATH_SEP ";" +#define LUA_PATH_MARK "?" +#define LUA_EXEC_DIR "!" + + +/* +@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for +** Lua libraries. +@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for +** C libraries. +** CHANGE them if your machine has a non-conventional directory +** hierarchy or if you want to install your libraries in +** non-conventional directories. +*/ + +#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +#if defined(_WIN32) /* { */ +/* +** In Windows, any exclamation mark ('!') in the path is replaced by the +** path of the directory of the executable file of the current process. +*/ +#define LUA_LDIR "!\\lua\\" +#define LUA_CDIR "!\\" +#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" + +#if !defined(LUA_PATH_DEFAULT) +#define LUA_PATH_DEFAULT \ + LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ + LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ + ".\\?.lua;" ".\\?\\init.lua" +#endif + +#if !defined(LUA_CPATH_DEFAULT) +#define LUA_CPATH_DEFAULT \ + LUA_CDIR"?.dll;" \ + LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ + LUA_CDIR"loadall.dll;" ".\\?.dll" +#endif + +#else /* }{ */ + +#define LUA_ROOT "/usr/local/" +#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" +#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" + +#if !defined(LUA_PATH_DEFAULT) +#define LUA_PATH_DEFAULT \ + LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ + "./?.lua;" "./?/init.lua" +#endif + +#if !defined(LUA_CPATH_DEFAULT) +#define LUA_CPATH_DEFAULT \ + LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" +#endif + +#endif /* } */ + + +/* +@@ LUA_DIRSEP is the directory separator (for submodules). +** CHANGE it if your machine does not use "/" as the directory separator +** and is not Windows. (On Windows Lua automatically uses "\".) +*/ +#if !defined(LUA_DIRSEP) + +#if defined(_WIN32) +#define LUA_DIRSEP "\\" +#else +#define LUA_DIRSEP "/" +#endif + +#endif + +/* }================================================================== */ + + +/* +** {================================================================== +** Marks for exported symbols in the C code +** =================================================================== +*/ + +/* +@@ LUA_API is a mark for all core API functions. +@@ LUALIB_API is a mark for all auxiliary library functions. +@@ LUAMOD_API is a mark for all standard library opening functions. +** CHANGE them if you need to define those functions in some special way. +** For instance, if you want to create one Windows DLL with the core and +** the libraries, you may want to use the following definition (define +** LUA_BUILD_AS_DLL to get it). +*/ +#if defined(LUA_BUILD_AS_DLL) /* { */ + +#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ +#define LUA_API __declspec(dllexport) +#else /* }{ */ +#define LUA_API __declspec(dllimport) +#endif /* } */ + +#else /* }{ */ + +#define LUA_API extern + +#endif /* } */ + + +/* +** More often than not the libs go together with the core. +*/ +#define LUALIB_API LUA_API +#define LUAMOD_API LUA_API + + +/* +@@ LUAI_FUNC is a mark for all extern functions that are not to be +** exported to outside modules. +@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, +** none of which to be exported to outside modules (LUAI_DDEF for +** definitions and LUAI_DDEC for declarations). +** CHANGE them if you need to mark them in some special way. Elf/gcc +** (versions 3.2 and later) mark them as "hidden" to optimize access +** when Lua is compiled as a shared library. Not all elf targets support +** this attribute. Unfortunately, gcc does not offer a way to check +** whether the target offers that support, and those without support +** give a warning about it. To avoid these warnings, change to the +** default definition. +*/ +#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ + defined(__ELF__) /* { */ +#define LUAI_FUNC __attribute__((visibility("internal"))) extern +#else /* }{ */ +#define LUAI_FUNC extern +#endif /* } */ + +#define LUAI_DDEC(dec) LUAI_FUNC dec +#define LUAI_DDEF /* empty */ + +/* }================================================================== */ + + +/* +** {================================================================== +** Compatibility with previous versions +** =================================================================== +*/ + +/* +@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3. +** You can define it to get all options, or change specific options +** to fit your specific needs. +*/ +#if defined(LUA_COMPAT_5_3) /* { */ + +/* +@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated +** functions in the mathematical library. +** (These functions were already officially removed in 5.3; +** nevertheless they are still available here.) +*/ +#define LUA_COMPAT_MATHLIB + +/* +@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for +** manipulating other integer types (lua_pushunsigned, lua_tounsigned, +** luaL_checkint, luaL_checklong, etc.) +** (These macros were also officially removed in 5.3, but they are still +** available here.) +*/ +#define LUA_COMPAT_APIINTCASTS + + +/* +@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod +** using '__lt'. +*/ +#define LUA_COMPAT_LT_LE + + +/* +@@ The following macros supply trivial compatibility for some +** changes in the API. The macros themselves document how to +** change your code to avoid using them. +** (Once more, these macros were officially removed in 5.3, but they are +** still available here.) +*/ +#define lua_strlen(L,i) lua_rawlen(L, (i)) + +#define lua_objlen(L,i) lua_rawlen(L, (i)) + +#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) + +#endif /* } */ + +/* }================================================================== */ + + + +/* +** {================================================================== +** Configuration for Numbers (low-level part). +** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* +** satisfy your needs. +** =================================================================== +*/ + +/* +@@ LUAI_UACNUMBER is the result of a 'default argument promotion' +@@ over a floating number. +@@ l_floatatt(x) corrects float attribute 'x' to the proper float type +** by prefixing it with one of FLT/DBL/LDBL. +@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. +@@ LUA_NUMBER_FMT is the format for writing floats. +@@ lua_number2str converts a float to a string. +@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. +@@ l_floor takes the floor of a float. +@@ lua_str2number converts a decimal numeral to a number. +*/ + + +/* The following definitions are good for most cases here */ + +#define l_floor(x) (l_mathop(floor)(x)) + +#define lua_number2str(s,sz,n) \ + l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) + +/* +@@ lua_numbertointeger converts a float number with an integral value +** to an integer, or returns 0 if float is not within the range of +** a lua_Integer. (The range comparisons are tricky because of +** rounding. The tests here assume a two-complement representation, +** where MININTEGER always has an exact representation as a float; +** MAXINTEGER may not have one, and therefore its conversion to float +** may have an ill-defined value.) +*/ +#define lua_numbertointeger(n,p) \ + ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ + (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ + (*(p) = (LUA_INTEGER)(n), 1)) + + +/* now the variable definitions */ + +#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ + +#define LUA_NUMBER float + +#define l_floatatt(n) (FLT_##n) + +#define LUAI_UACNUMBER double + +#define LUA_NUMBER_FRMLEN "" +#define LUA_NUMBER_FMT "%.7g" + +#define l_mathop(op) op##f + +#define lua_str2number(s,p) strtof((s), (p)) + + +#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ + +#define LUA_NUMBER long double + +#define l_floatatt(n) (LDBL_##n) + +#define LUAI_UACNUMBER long double + +#define LUA_NUMBER_FRMLEN "L" +#define LUA_NUMBER_FMT "%.19Lg" + +#define l_mathop(op) op##l + +#define lua_str2number(s,p) strtold((s), (p)) + +#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ + +#define LUA_NUMBER double + +#define l_floatatt(n) (DBL_##n) + +#define LUAI_UACNUMBER double + +#define LUA_NUMBER_FRMLEN "" +#define LUA_NUMBER_FMT "%.14g" + +#define l_mathop(op) op + +#define lua_str2number(s,p) strtod((s), (p)) + +#else /* }{ */ + +#error "numeric float type not defined" + +#endif /* } */ + + + +/* +@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. +@@ LUAI_UACINT is the result of a 'default argument promotion' +@@ over a LUA_INTEGER. +@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. +@@ LUA_INTEGER_FMT is the format for writing integers. +@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. +@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. +@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED. +@@ lua_integer2str converts an integer to a string. +*/ + + +/* The following definitions are good for most cases here */ + +#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" + +#define LUAI_UACINT LUA_INTEGER + +#define lua_integer2str(s,sz,n) \ + l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) + +/* +** use LUAI_UACINT here to avoid problems with promotions (which +** can turn a comparison between unsigneds into a signed comparison) +*/ +#define LUA_UNSIGNED unsigned LUAI_UACINT + + +/* now the variable definitions */ + +#if LUA_INT_TYPE == LUA_INT_INT /* { int */ + +#define LUA_INTEGER int +#define LUA_INTEGER_FRMLEN "" + +#define LUA_MAXINTEGER INT_MAX +#define LUA_MININTEGER INT_MIN + +#define LUA_MAXUNSIGNED UINT_MAX + +#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ + +#define LUA_INTEGER long +#define LUA_INTEGER_FRMLEN "l" + +#define LUA_MAXINTEGER LONG_MAX +#define LUA_MININTEGER LONG_MIN + +#define LUA_MAXUNSIGNED ULONG_MAX + +#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ + +/* use presence of macro LLONG_MAX as proxy for C99 compliance */ +#if defined(LLONG_MAX) /* { */ +/* use ISO C99 stuff */ + +#define LUA_INTEGER long long +#define LUA_INTEGER_FRMLEN "ll" + +#define LUA_MAXINTEGER LLONG_MAX +#define LUA_MININTEGER LLONG_MIN + +#define LUA_MAXUNSIGNED ULLONG_MAX + +#elif defined(LUA_USE_WINDOWS) /* }{ */ +/* in Windows, can use specific Windows types */ + +#define LUA_INTEGER __int64 +#define LUA_INTEGER_FRMLEN "I64" + +#define LUA_MAXINTEGER _I64_MAX +#define LUA_MININTEGER _I64_MIN + +#define LUA_MAXUNSIGNED _UI64_MAX + +#else /* }{ */ + +#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ + or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" + +#endif /* } */ + +#else /* }{ */ + +#error "numeric integer type not defined" + +#endif /* } */ + +/* }================================================================== */ + + +/* +** {================================================================== +** Dependencies with C99 and other C details +** =================================================================== +*/ + +/* +@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. +** (All uses in Lua have only one format item.) +*/ +#if !defined(LUA_USE_C89) +#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) +#else +#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) +#endif + + +/* +@@ lua_strx2number converts a hexadecimal numeral to a number. +** In C99, 'strtod' does that conversion. Otherwise, you can +** leave 'lua_strx2number' undefined and Lua will provide its own +** implementation. +*/ +#if !defined(LUA_USE_C89) +#define lua_strx2number(s,p) lua_str2number(s,p) +#endif + + +/* +@@ lua_pointer2str converts a pointer to a readable string in a +** non-specified way. +*/ +#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) + + +/* +@@ lua_number2strx converts a float to a hexadecimal numeral. +** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. +** Otherwise, you can leave 'lua_number2strx' undefined and Lua will +** provide its own implementation. +*/ +#if !defined(LUA_USE_C89) +#define lua_number2strx(L,b,sz,f,n) \ + ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) +#endif + + +/* +** 'strtof' and 'opf' variants for math functions are not valid in +** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the +** availability of these variants. ('math.h' is already included in +** all files that use these macros.) +*/ +#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) +#undef l_mathop /* variants not available */ +#undef lua_str2number +#define l_mathop(op) (lua_Number)op /* no variant */ +#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) +#endif + + +/* +@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation +** functions. It must be a numerical type; Lua will use 'intptr_t' if +** available, otherwise it will use 'ptrdiff_t' (the nearest thing to +** 'intptr_t' in C89) +*/ +#define LUA_KCONTEXT ptrdiff_t + +#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 199901L +#include +#if defined(INTPTR_MAX) /* even in C99 this type is optional */ +#undef LUA_KCONTEXT +#define LUA_KCONTEXT intptr_t +#endif +#endif + + +/* +@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). +** Change that if you do not want to use C locales. (Code using this +** macro must include the header 'locale.h'.) +*/ +#if !defined(lua_getlocaledecpoint) +#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) +#endif + + +/* +** macros to improve jump prediction, used mostly for error handling +** and debug facilities. (Some macros in the Lua API use these macros. +** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your +** code.) +*/ +#if !defined(luai_likely) + +#if defined(__GNUC__) && !defined(LUA_NOBUILTIN) +#define luai_likely(x) (__builtin_expect(((x) != 0), 1)) +#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0)) +#else +#define luai_likely(x) (x) +#define luai_unlikely(x) (x) +#endif + +#endif + + +#if defined(LUA_CORE) || defined(LUA_LIB) +/* shorter names for Lua's own use */ +#define l_likely(x) luai_likely(x) +#define l_unlikely(x) luai_unlikely(x) +#endif + + + +/* }================================================================== */ + + +/* +** {================================================================== +** Language Variations +** ===================================================================== +*/ + +/* +@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some +** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from +** numbers to strings. Define LUA_NOCVTS2N to turn off automatic +** coercion from strings to numbers. +*/ +/* #define LUA_NOCVTN2S */ +/* #define LUA_NOCVTS2N */ + + +/* +@@ LUA_USE_APICHECK turns on several consistency checks on the C API. +** Define it as a help when debugging C code. +*/ +#if defined(LUA_USE_APICHECK) +#include +#define luai_apicheck(l,e) assert(e) +#endif + +/* }================================================================== */ + + +/* +** {================================================================== +** Macros that affect the API and must be stable (that is, must be the +** same when you compile Lua and when you compile code that links to +** Lua). +** ===================================================================== +*/ + +/* +@@ LUAI_MAXSTACK limits the size of the Lua stack. +** CHANGE it if you need a different limit. This limit is arbitrary; +** its only purpose is to stop Lua from consuming unlimited stack +** space (and to reserve some numbers for pseudo-indices). +** (It must fit into max(size_t)/32 and max(int)/2.) +*/ +#if LUAI_IS32INT +#define LUAI_MAXSTACK 1000000 +#else +#define LUAI_MAXSTACK 15000 +#endif + + +/* +@@ LUA_EXTRASPACE defines the size of a raw memory area associated with +** a Lua state with very fast access. +** CHANGE it if you need a different size. +*/ +#define LUA_EXTRASPACE (sizeof(void *)) + + +/* +@@ LUA_IDSIZE gives the maximum size for the description of the source +** of a function in debug information. +** CHANGE it if you want a different size. +*/ +#define LUA_IDSIZE 60 + + +/* +@@ LUAL_BUFFERSIZE is the initial buffer size used by the lauxlib +** buffer system. +*/ +#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number))) + + +/* +@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure +** maximum alignment for the other items in that union. +*/ +#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l + +/* }================================================================== */ + + + + + +/* =================================================================== */ + +/* +** Local configuration. You can use this space to add your redefinitions +** without modifying the main part of the file. +*/ + + + + + +#endif + diff --git a/src/libs/3rdparty/lua/src/lualib.h b/src/libs/3rdparty/lua/src/lualib.h new file mode 100644 index 00000000000..2625529076a --- /dev/null +++ b/src/libs/3rdparty/lua/src/lualib.h @@ -0,0 +1,52 @@ +/* +** $Id: lualib.h $ +** Lua standard libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lualib_h +#define lualib_h + +#include "lua.h" + + +/* version suffix for environment variable names */ +#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR + + +LUAMOD_API int (luaopen_base) (lua_State *L); + +#define LUA_COLIBNAME "coroutine" +LUAMOD_API int (luaopen_coroutine) (lua_State *L); + +#define LUA_TABLIBNAME "table" +LUAMOD_API int (luaopen_table) (lua_State *L); + +#define LUA_IOLIBNAME "io" +LUAMOD_API int (luaopen_io) (lua_State *L); + +#define LUA_OSLIBNAME "os" +LUAMOD_API int (luaopen_os) (lua_State *L); + +#define LUA_STRLIBNAME "string" +LUAMOD_API int (luaopen_string) (lua_State *L); + +#define LUA_UTF8LIBNAME "utf8" +LUAMOD_API int (luaopen_utf8) (lua_State *L); + +#define LUA_MATHLIBNAME "math" +LUAMOD_API int (luaopen_math) (lua_State *L); + +#define LUA_DBLIBNAME "debug" +LUAMOD_API int (luaopen_debug) (lua_State *L); + +#define LUA_LOADLIBNAME "package" +LUAMOD_API int (luaopen_package) (lua_State *L); + + +/* open all previous libraries */ +LUALIB_API void (luaL_openlibs) (lua_State *L); + + +#endif diff --git a/src/libs/3rdparty/lua/src/lundump.c b/src/libs/3rdparty/lua/src/lundump.c new file mode 100644 index 00000000000..02aed64fb62 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lundump.c @@ -0,0 +1,335 @@ +/* +** $Id: lundump.c $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#define lundump_c +#define LUA_CORE + +#include "lprefix.h" + + +#include +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstring.h" +#include "lundump.h" +#include "lzio.h" + + +#if !defined(luai_verifycode) +#define luai_verifycode(L,f) /* empty */ +#endif + + +typedef struct { + lua_State *L; + ZIO *Z; + const char *name; +} LoadState; + + +static l_noret error (LoadState *S, const char *why) { + luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why); + luaD_throw(S->L, LUA_ERRSYNTAX); +} + + +/* +** All high-level loads go through loadVector; you can change it to +** adapt to the endianness of the input +*/ +#define loadVector(S,b,n) loadBlock(S,b,(n)*sizeof((b)[0])) + +static void loadBlock (LoadState *S, void *b, size_t size) { + if (luaZ_read(S->Z, b, size) != 0) + error(S, "truncated chunk"); +} + + +#define loadVar(S,x) loadVector(S,&x,1) + + +static lu_byte loadByte (LoadState *S) { + int b = zgetc(S->Z); + if (b == EOZ) + error(S, "truncated chunk"); + return cast_byte(b); +} + + +static size_t loadUnsigned (LoadState *S, size_t limit) { + size_t x = 0; + int b; + limit >>= 7; + do { + b = loadByte(S); + if (x >= limit) + error(S, "integer overflow"); + x = (x << 7) | (b & 0x7f); + } while ((b & 0x80) == 0); + return x; +} + + +static size_t loadSize (LoadState *S) { + return loadUnsigned(S, ~(size_t)0); +} + + +static int loadInt (LoadState *S) { + return cast_int(loadUnsigned(S, INT_MAX)); +} + + +static lua_Number loadNumber (LoadState *S) { + lua_Number x; + loadVar(S, x); + return x; +} + + +static lua_Integer loadInteger (LoadState *S) { + lua_Integer x; + loadVar(S, x); + return x; +} + + +/* +** Load a nullable string into prototype 'p'. +*/ +static TString *loadStringN (LoadState *S, Proto *p) { + lua_State *L = S->L; + TString *ts; + size_t size = loadSize(S); + if (size == 0) /* no string? */ + return NULL; + else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */ + char buff[LUAI_MAXSHORTLEN]; + loadVector(S, buff, size); /* load string into buffer */ + ts = luaS_newlstr(L, buff, size); /* create string */ + } + else { /* long string */ + ts = luaS_createlngstrobj(L, size); /* create string */ + setsvalue2s(L, L->top.p, ts); /* anchor it ('loadVector' can GC) */ + luaD_inctop(L); + loadVector(S, getstr(ts), size); /* load directly in final place */ + L->top.p--; /* pop string */ + } + luaC_objbarrier(L, p, ts); + return ts; +} + + +/* +** Load a non-nullable string into prototype 'p'. +*/ +static TString *loadString (LoadState *S, Proto *p) { + TString *st = loadStringN(S, p); + if (st == NULL) + error(S, "bad format for constant string"); + return st; +} + + +static void loadCode (LoadState *S, Proto *f) { + int n = loadInt(S); + f->code = luaM_newvectorchecked(S->L, n, Instruction); + f->sizecode = n; + loadVector(S, f->code, n); +} + + +static void loadFunction(LoadState *S, Proto *f, TString *psource); + + +static void loadConstants (LoadState *S, Proto *f) { + int i; + int n = loadInt(S); + f->k = luaM_newvectorchecked(S->L, n, TValue); + f->sizek = n; + for (i = 0; i < n; i++) + setnilvalue(&f->k[i]); + for (i = 0; i < n; i++) { + TValue *o = &f->k[i]; + int t = loadByte(S); + switch (t) { + case LUA_VNIL: + setnilvalue(o); + break; + case LUA_VFALSE: + setbfvalue(o); + break; + case LUA_VTRUE: + setbtvalue(o); + break; + case LUA_VNUMFLT: + setfltvalue(o, loadNumber(S)); + break; + case LUA_VNUMINT: + setivalue(o, loadInteger(S)); + break; + case LUA_VSHRSTR: + case LUA_VLNGSTR: + setsvalue2n(S->L, o, loadString(S, f)); + break; + default: lua_assert(0); + } + } +} + + +static void loadProtos (LoadState *S, Proto *f) { + int i; + int n = loadInt(S); + f->p = luaM_newvectorchecked(S->L, n, Proto *); + f->sizep = n; + for (i = 0; i < n; i++) + f->p[i] = NULL; + for (i = 0; i < n; i++) { + f->p[i] = luaF_newproto(S->L); + luaC_objbarrier(S->L, f, f->p[i]); + loadFunction(S, f->p[i], f->source); + } +} + + +/* +** Load the upvalues for a function. The names must be filled first, +** because the filling of the other fields can raise read errors and +** the creation of the error message can call an emergency collection; +** in that case all prototypes must be consistent for the GC. +*/ +static void loadUpvalues (LoadState *S, Proto *f) { + int i, n; + n = loadInt(S); + f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc); + f->sizeupvalues = n; + for (i = 0; i < n; i++) /* make array valid for GC */ + f->upvalues[i].name = NULL; + for (i = 0; i < n; i++) { /* following calls can raise errors */ + f->upvalues[i].instack = loadByte(S); + f->upvalues[i].idx = loadByte(S); + f->upvalues[i].kind = loadByte(S); + } +} + + +static void loadDebug (LoadState *S, Proto *f) { + int i, n; + n = loadInt(S); + f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte); + f->sizelineinfo = n; + loadVector(S, f->lineinfo, n); + n = loadInt(S); + f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo); + f->sizeabslineinfo = n; + for (i = 0; i < n; i++) { + f->abslineinfo[i].pc = loadInt(S); + f->abslineinfo[i].line = loadInt(S); + } + n = loadInt(S); + f->locvars = luaM_newvectorchecked(S->L, n, LocVar); + f->sizelocvars = n; + for (i = 0; i < n; i++) + f->locvars[i].varname = NULL; + for (i = 0; i < n; i++) { + f->locvars[i].varname = loadStringN(S, f); + f->locvars[i].startpc = loadInt(S); + f->locvars[i].endpc = loadInt(S); + } + n = loadInt(S); + if (n != 0) /* does it have debug information? */ + n = f->sizeupvalues; /* must be this many */ + for (i = 0; i < n; i++) + f->upvalues[i].name = loadStringN(S, f); +} + + +static void loadFunction (LoadState *S, Proto *f, TString *psource) { + f->source = loadStringN(S, f); + if (f->source == NULL) /* no source in dump? */ + f->source = psource; /* reuse parent's source */ + f->linedefined = loadInt(S); + f->lastlinedefined = loadInt(S); + f->numparams = loadByte(S); + f->is_vararg = loadByte(S); + f->maxstacksize = loadByte(S); + loadCode(S, f); + loadConstants(S, f); + loadUpvalues(S, f); + loadProtos(S, f); + loadDebug(S, f); +} + + +static void checkliteral (LoadState *S, const char *s, const char *msg) { + char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */ + size_t len = strlen(s); + loadVector(S, buff, len); + if (memcmp(s, buff, len) != 0) + error(S, msg); +} + + +static void fchecksize (LoadState *S, size_t size, const char *tname) { + if (loadByte(S) != size) + error(S, luaO_pushfstring(S->L, "%s size mismatch", tname)); +} + + +#define checksize(S,t) fchecksize(S,sizeof(t),#t) + +static void checkHeader (LoadState *S) { + /* skip 1st char (already read and checked) */ + checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk"); + if (loadByte(S) != LUAC_VERSION) + error(S, "version mismatch"); + if (loadByte(S) != LUAC_FORMAT) + error(S, "format mismatch"); + checkliteral(S, LUAC_DATA, "corrupted chunk"); + checksize(S, Instruction); + checksize(S, lua_Integer); + checksize(S, lua_Number); + if (loadInteger(S) != LUAC_INT) + error(S, "integer format mismatch"); + if (loadNumber(S) != LUAC_NUM) + error(S, "float format mismatch"); +} + + +/* +** Load precompiled chunk. +*/ +LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) { + LoadState S; + LClosure *cl; + if (*name == '@' || *name == '=') + S.name = name + 1; + else if (*name == LUA_SIGNATURE[0]) + S.name = "binary string"; + else + S.name = name; + S.L = L; + S.Z = Z; + checkHeader(&S); + cl = luaF_newLclosure(L, loadByte(&S)); + setclLvalue2s(L, L->top.p, cl); + luaD_inctop(L); + cl->p = luaF_newproto(L); + luaC_objbarrier(L, cl, cl->p); + loadFunction(&S, cl->p, NULL); + lua_assert(cl->nupvalues == cl->p->sizeupvalues); + luai_verifycode(L, cl->p); + return cl; +} + diff --git a/src/libs/3rdparty/lua/src/lundump.h b/src/libs/3rdparty/lua/src/lundump.h new file mode 100644 index 00000000000..f3748a99807 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lundump.h @@ -0,0 +1,36 @@ +/* +** $Id: lundump.h $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#ifndef lundump_h +#define lundump_h + +#include "llimits.h" +#include "lobject.h" +#include "lzio.h" + + +/* data to catch conversion errors */ +#define LUAC_DATA "\x19\x93\r\n\x1a\n" + +#define LUAC_INT 0x5678 +#define LUAC_NUM cast_num(370.5) + +/* +** Encode major-minor version in one byte, one nibble for each +*/ +#define MYINT(s) (s[0]-'0') /* assume one-digit numerals */ +#define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)) + +#define LUAC_FORMAT 0 /* this is the official format */ + +/* load one chunk; from lundump.c */ +LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); + +/* dump one chunk; from ldump.c */ +LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, + void* data, int strip); + +#endif diff --git a/src/libs/3rdparty/lua/src/lutf8lib.c b/src/libs/3rdparty/lua/src/lutf8lib.c new file mode 100644 index 00000000000..3a5b9bc38a5 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lutf8lib.c @@ -0,0 +1,291 @@ +/* +** $Id: lutf8lib.c $ +** Standard library for UTF-8 manipulation +** See Copyright Notice in lua.h +*/ + +#define lutf8lib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#define MAXUNICODE 0x10FFFFu + +#define MAXUTF 0x7FFFFFFFu + + +#define MSGInvalid "invalid UTF-8 code" + +/* +** Integer type for decoded UTF-8 values; MAXUTF needs 31 bits. +*/ +#if (UINT_MAX >> 30) >= 1 +typedef unsigned int utfint; +#else +typedef unsigned long utfint; +#endif + + +#define iscont(c) (((c) & 0xC0) == 0x80) +#define iscontp(p) iscont(*(p)) + + +/* from strlib */ +/* translate a relative string position: negative means back from end */ +static lua_Integer u_posrelat (lua_Integer pos, size_t len) { + if (pos >= 0) return pos; + else if (0u - (size_t)pos > len) return 0; + else return (lua_Integer)len + pos + 1; +} + + +/* +** Decode one UTF-8 sequence, returning NULL if byte sequence is +** invalid. The array 'limits' stores the minimum value for each +** sequence length, to check for overlong representations. Its first +** entry forces an error for non-ascii bytes with no continuation +** bytes (count == 0). +*/ +static const char *utf8_decode (const char *s, utfint *val, int strict) { + static const utfint limits[] = + {~(utfint)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u}; + unsigned int c = (unsigned char)s[0]; + utfint res = 0; /* final result */ + if (c < 0x80) /* ascii? */ + res = c; + else { + int count = 0; /* to count number of continuation bytes */ + for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */ + unsigned int cc = (unsigned char)s[++count]; /* read next byte */ + if (!iscont(cc)) /* not a continuation byte? */ + return NULL; /* invalid byte sequence */ + res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ + } + res |= ((utfint)(c & 0x7F) << (count * 5)); /* add first byte */ + if (count > 5 || res > MAXUTF || res < limits[count]) + return NULL; /* invalid byte sequence */ + s += count; /* skip continuation bytes read */ + } + if (strict) { + /* check for invalid code points; too large or surrogates */ + if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu)) + return NULL; + } + if (val) *val = res; + return s + 1; /* +1 to include first byte */ +} + + +/* +** utf8len(s [, i [, j [, lax]]]) --> number of characters that +** start in the range [i,j], or nil + current position if 's' is not +** well formed in that interval +*/ +static int utflen (lua_State *L) { + lua_Integer n = 0; /* counter for the number of characters */ + size_t len; /* string length in bytes */ + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); + lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len); + int lax = lua_toboolean(L, 4); + luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2, + "initial position out of bounds"); + luaL_argcheck(L, --posj < (lua_Integer)len, 3, + "final position out of bounds"); + while (posi <= posj) { + const char *s1 = utf8_decode(s + posi, NULL, !lax); + if (s1 == NULL) { /* conversion error? */ + luaL_pushfail(L); /* return fail ... */ + lua_pushinteger(L, posi + 1); /* ... and current position */ + return 2; + } + posi = s1 - s; + n++; + } + lua_pushinteger(L, n); + return 1; +} + + +/* +** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all +** characters that start in the range [i,j] +*/ +static int codepoint (lua_State *L) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); + lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len); + int lax = lua_toboolean(L, 4); + int n; + const char *se; + luaL_argcheck(L, posi >= 1, 2, "out of bounds"); + luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds"); + if (posi > pose) return 0; /* empty interval; return no values */ + if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */ + return luaL_error(L, "string slice too long"); + n = (int)(pose - posi) + 1; /* upper bound for number of returns */ + luaL_checkstack(L, n, "string slice too long"); + n = 0; /* count the number of returns */ + se = s + pose; /* string end */ + for (s += posi - 1; s < se;) { + utfint code; + s = utf8_decode(s, &code, !lax); + if (s == NULL) + return luaL_error(L, MSGInvalid); + lua_pushinteger(L, code); + n++; + } + return n; +} + + +static void pushutfchar (lua_State *L, int arg) { + lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg); + luaL_argcheck(L, code <= MAXUTF, arg, "value out of range"); + lua_pushfstring(L, "%U", (long)code); +} + + +/* +** utfchar(n1, n2, ...) -> char(n1)..char(n2)... +*/ +static int utfchar (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + if (n == 1) /* optimize common case of single char */ + pushutfchar(L, 1); + else { + int i; + luaL_Buffer b; + luaL_buffinit(L, &b); + for (i = 1; i <= n; i++) { + pushutfchar(L, i); + luaL_addvalue(&b); + } + luaL_pushresult(&b); + } + return 1; +} + + +/* +** offset(s, n, [i]) -> index where n-th character counting from +** position 'i' starts; 0 means character at 'i'. +*/ +static int byteoffset (lua_State *L) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Integer n = luaL_checkinteger(L, 2); + lua_Integer posi = (n >= 0) ? 1 : len + 1; + posi = u_posrelat(luaL_optinteger(L, 3, posi), len); + luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3, + "position out of bounds"); + if (n == 0) { + /* find beginning of current byte sequence */ + while (posi > 0 && iscontp(s + posi)) posi--; + } + else { + if (iscontp(s + posi)) + return luaL_error(L, "initial position is a continuation byte"); + if (n < 0) { + while (n < 0 && posi > 0) { /* move back */ + do { /* find beginning of previous character */ + posi--; + } while (posi > 0 && iscontp(s + posi)); + n++; + } + } + else { + n--; /* do not move for 1st character */ + while (n > 0 && posi < (lua_Integer)len) { + do { /* find beginning of next character */ + posi++; + } while (iscontp(s + posi)); /* (cannot pass final '\0') */ + n--; + } + } + } + if (n == 0) /* did it find given character? */ + lua_pushinteger(L, posi + 1); + else /* no such character */ + luaL_pushfail(L); + return 1; +} + + +static int iter_aux (lua_State *L, int strict) { + size_t len; + const char *s = luaL_checklstring(L, 1, &len); + lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2); + if (n < len) { + while (iscontp(s + n)) n++; /* go to next character */ + } + if (n >= len) /* (also handles original 'n' being negative) */ + return 0; /* no more codepoints */ + else { + utfint code; + const char *next = utf8_decode(s + n, &code, strict); + if (next == NULL || iscontp(next)) + return luaL_error(L, MSGInvalid); + lua_pushinteger(L, n + 1); + lua_pushinteger(L, code); + return 2; + } +} + + +static int iter_auxstrict (lua_State *L) { + return iter_aux(L, 1); +} + +static int iter_auxlax (lua_State *L) { + return iter_aux(L, 0); +} + + +static int iter_codes (lua_State *L) { + int lax = lua_toboolean(L, 2); + const char *s = luaL_checkstring(L, 1); + luaL_argcheck(L, !iscontp(s), 1, MSGInvalid); + lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict); + lua_pushvalue(L, 1); + lua_pushinteger(L, 0); + return 3; +} + + +/* pattern to match a single UTF-8 character */ +#define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*" + + +static const luaL_Reg funcs[] = { + {"offset", byteoffset}, + {"codepoint", codepoint}, + {"char", utfchar}, + {"len", utflen}, + {"codes", iter_codes}, + /* placeholders */ + {"charpattern", NULL}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_utf8 (lua_State *L) { + luaL_newlib(L, funcs); + lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1); + lua_setfield(L, -2, "charpattern"); + return 1; +} + diff --git a/src/libs/3rdparty/lua/src/lvm.c b/src/libs/3rdparty/lua/src/lvm.c new file mode 100644 index 00000000000..8493a770c56 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lvm.c @@ -0,0 +1,1901 @@ +/* +** $Id: lvm.c $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#define lvm_c +#define LUA_CORE + +#include "lprefix.h" + +#include +#include +#include +#include +#include +#include + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" +#include "lvm.h" + + +/* +** By default, use jump tables in the main interpreter loop on gcc +** and compatible compilers. +*/ +#if !defined(LUA_USE_JUMPTABLE) +#if defined(__GNUC__) +#define LUA_USE_JUMPTABLE 1 +#else +#define LUA_USE_JUMPTABLE 0 +#endif +#endif + + + +/* limit for table tag-method chains (to avoid infinite loops) */ +#define MAXTAGLOOP 2000 + + +/* +** 'l_intfitsf' checks whether a given integer is in the range that +** can be converted to a float without rounding. Used in comparisons. +*/ + +/* number of bits in the mantissa of a float */ +#define NBM (l_floatatt(MANT_DIG)) + +/* +** Check whether some integers may not fit in a float, testing whether +** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.) +** (The shifts are done in parts, to avoid shifting by more than the size +** of an integer. In a worst case, NBM == 113 for long double and +** sizeof(long) == 32.) +*/ +#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \ + >> (NBM - (3 * (NBM / 4)))) > 0 + +/* limit for integers that fit in a float */ +#define MAXINTFITSF ((lua_Unsigned)1 << NBM) + +/* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */ +#define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF)) + +#else /* all integers fit in a float precisely */ + +#define l_intfitsf(i) 1 + +#endif + + +/* +** Try to convert a value from string to a number value. +** If the value is not a string or is a string not representing +** a valid numeral (or if coercions from strings to numbers +** are disabled via macro 'cvt2num'), do not modify 'result' +** and return 0. +*/ +static int l_strton (const TValue *obj, TValue *result) { + lua_assert(obj != result); + if (!cvt2num(obj)) /* is object not a string? */ + return 0; + else + return (luaO_str2num(svalue(obj), result) == vslen(obj) + 1); +} + + +/* +** Try to convert a value to a float. The float case is already handled +** by the macro 'tonumber'. +*/ +int luaV_tonumber_ (const TValue *obj, lua_Number *n) { + TValue v; + if (ttisinteger(obj)) { + *n = cast_num(ivalue(obj)); + return 1; + } + else if (l_strton(obj, &v)) { /* string coercible to number? */ + *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */ + return 1; + } + else + return 0; /* conversion failed */ +} + + +/* +** try to convert a float to an integer, rounding according to 'mode'. +*/ +int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) { + lua_Number f = l_floor(n); + if (n != f) { /* not an integral value? */ + if (mode == F2Ieq) return 0; /* fails if mode demands integral value */ + else if (mode == F2Iceil) /* needs ceil? */ + f += 1; /* convert floor to ceil (remember: n != f) */ + } + return lua_numbertointeger(f, p); +} + + +/* +** try to convert a value to an integer, rounding according to 'mode', +** without string coercion. +** ("Fast track" handled by macro 'tointegerns'.) +*/ +int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) { + if (ttisfloat(obj)) + return luaV_flttointeger(fltvalue(obj), p, mode); + else if (ttisinteger(obj)) { + *p = ivalue(obj); + return 1; + } + else + return 0; +} + + +/* +** try to convert a value to an integer. +*/ +int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) { + TValue v; + if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */ + obj = &v; /* change it to point to its corresponding number */ + return luaV_tointegerns(obj, p, mode); +} + + +/* +** Try to convert a 'for' limit to an integer, preserving the semantics +** of the loop. Return true if the loop must not run; otherwise, '*p' +** gets the integer limit. +** (The following explanation assumes a positive step; it is valid for +** negative steps mutatis mutandis.) +** If the limit is an integer or can be converted to an integer, +** rounding down, that is the limit. +** Otherwise, check whether the limit can be converted to a float. If +** the float is too large, clip it to LUA_MAXINTEGER. If the float +** is too negative, the loop should not run, because any initial +** integer value is greater than such limit; so, the function returns +** true to signal that. (For this latter case, no integer limit would be +** correct; even a limit of LUA_MININTEGER would run the loop once for +** an initial value equal to LUA_MININTEGER.) +*/ +static int forlimit (lua_State *L, lua_Integer init, const TValue *lim, + lua_Integer *p, lua_Integer step) { + if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) { + /* not coercible to in integer */ + lua_Number flim; /* try to convert to float */ + if (!tonumber(lim, &flim)) /* cannot convert to float? */ + luaG_forerror(L, lim, "limit"); + /* else 'flim' is a float out of integer bounds */ + if (luai_numlt(0, flim)) { /* if it is positive, it is too large */ + if (step < 0) return 1; /* initial value must be less than it */ + *p = LUA_MAXINTEGER; /* truncate */ + } + else { /* it is less than min integer */ + if (step > 0) return 1; /* initial value must be greater than it */ + *p = LUA_MININTEGER; /* truncate */ + } + } + return (step > 0 ? init > *p : init < *p); /* not to run? */ +} + + +/* +** Prepare a numerical for loop (opcode OP_FORPREP). +** Return true to skip the loop. Otherwise, +** after preparation, stack will be as follows: +** ra : internal index (safe copy of the control variable) +** ra + 1 : loop counter (integer loops) or limit (float loops) +** ra + 2 : step +** ra + 3 : control variable +*/ +static int forprep (lua_State *L, StkId ra) { + TValue *pinit = s2v(ra); + TValue *plimit = s2v(ra + 1); + TValue *pstep = s2v(ra + 2); + if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */ + lua_Integer init = ivalue(pinit); + lua_Integer step = ivalue(pstep); + lua_Integer limit; + if (step == 0) + luaG_runerror(L, "'for' step is zero"); + setivalue(s2v(ra + 3), init); /* control variable */ + if (forlimit(L, init, plimit, &limit, step)) + return 1; /* skip the loop */ + else { /* prepare loop counter */ + lua_Unsigned count; + if (step > 0) { /* ascending loop? */ + count = l_castS2U(limit) - l_castS2U(init); + if (step != 1) /* avoid division in the too common case */ + count /= l_castS2U(step); + } + else { /* step < 0; descending loop */ + count = l_castS2U(init) - l_castS2U(limit); + /* 'step+1' avoids negating 'mininteger' */ + count /= l_castS2U(-(step + 1)) + 1u; + } + /* store the counter in place of the limit (which won't be + needed anymore) */ + setivalue(plimit, l_castU2S(count)); + } + } + else { /* try making all values floats */ + lua_Number init; lua_Number limit; lua_Number step; + if (l_unlikely(!tonumber(plimit, &limit))) + luaG_forerror(L, plimit, "limit"); + if (l_unlikely(!tonumber(pstep, &step))) + luaG_forerror(L, pstep, "step"); + if (l_unlikely(!tonumber(pinit, &init))) + luaG_forerror(L, pinit, "initial value"); + if (step == 0) + luaG_runerror(L, "'for' step is zero"); + if (luai_numlt(0, step) ? luai_numlt(limit, init) + : luai_numlt(init, limit)) + return 1; /* skip the loop */ + else { + /* make sure internal values are all floats */ + setfltvalue(plimit, limit); + setfltvalue(pstep, step); + setfltvalue(s2v(ra), init); /* internal index */ + setfltvalue(s2v(ra + 3), init); /* control variable */ + } + } + return 0; +} + + +/* +** Execute a step of a float numerical for loop, returning +** true iff the loop must continue. (The integer case is +** written online with opcode OP_FORLOOP, for performance.) +*/ +static int floatforloop (StkId ra) { + lua_Number step = fltvalue(s2v(ra + 2)); + lua_Number limit = fltvalue(s2v(ra + 1)); + lua_Number idx = fltvalue(s2v(ra)); /* internal index */ + idx = luai_numadd(L, idx, step); /* increment index */ + if (luai_numlt(0, step) ? luai_numle(idx, limit) + : luai_numle(limit, idx)) { + chgfltvalue(s2v(ra), idx); /* update internal index */ + setfltvalue(s2v(ra + 3), idx); /* and control variable */ + return 1; /* jump back */ + } + else + return 0; /* finish the loop */ +} + + +/* +** Finish the table access 'val = t[key]'. +** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to +** t[k] entry (which must be empty). +*/ +void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, + const TValue *slot) { + int loop; /* counter to avoid infinite loops */ + const TValue *tm; /* metamethod */ + for (loop = 0; loop < MAXTAGLOOP; loop++) { + if (slot == NULL) { /* 't' is not a table? */ + lua_assert(!ttistable(t)); + tm = luaT_gettmbyobj(L, t, TM_INDEX); + if (l_unlikely(notm(tm))) + luaG_typeerror(L, t, "index"); /* no metamethod */ + /* else will try the metamethod */ + } + else { /* 't' is a table */ + lua_assert(isempty(slot)); + tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */ + if (tm == NULL) { /* no metamethod? */ + setnilvalue(s2v(val)); /* result is nil */ + return; + } + /* else will try the metamethod */ + } + if (ttisfunction(tm)) { /* is metamethod a function? */ + luaT_callTMres(L, tm, t, key, val); /* call it */ + return; + } + t = tm; /* else try to access 'tm[key]' */ + if (luaV_fastget(L, t, key, slot, luaH_get)) { /* fast track? */ + setobj2s(L, val, slot); /* done */ + return; + } + /* else repeat (tail call 'luaV_finishget') */ + } + luaG_runerror(L, "'__index' chain too long; possible loop"); +} + + +/* +** Finish a table assignment 't[key] = val'. +** If 'slot' is NULL, 't' is not a table. Otherwise, 'slot' points +** to the entry 't[key]', or to a value with an absent key if there +** is no such entry. (The value at 'slot' must be empty, otherwise +** 'luaV_fastget' would have done the job.) +*/ +void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + TValue *val, const TValue *slot) { + int loop; /* counter to avoid infinite loops */ + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; /* '__newindex' metamethod */ + if (slot != NULL) { /* is 't' a table? */ + Table *h = hvalue(t); /* save 't' table */ + lua_assert(isempty(slot)); /* slot must be empty */ + tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */ + if (tm == NULL) { /* no metamethod? */ + luaH_finishset(L, h, key, slot, val); /* set new value */ + invalidateTMcache(h); + luaC_barrierback(L, obj2gco(h), val); + return; + } + /* else will try the metamethod */ + } + else { /* not a table; check metamethod */ + tm = luaT_gettmbyobj(L, t, TM_NEWINDEX); + if (l_unlikely(notm(tm))) + luaG_typeerror(L, t, "index"); + } + /* try the metamethod */ + if (ttisfunction(tm)) { + luaT_callTM(L, tm, t, key, val); + return; + } + t = tm; /* else repeat assignment over 'tm' */ + if (luaV_fastget(L, t, key, slot, luaH_get)) { + luaV_finishfastset(L, t, slot, val); + return; /* done */ + } + /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */ + } + luaG_runerror(L, "'__newindex' chain too long; possible loop"); +} + + +/* +** Compare two strings 'ls' x 'rs', returning an integer less-equal- +** -greater than zero if 'ls' is less-equal-greater than 'rs'. +** The code is a little tricky because it allows '\0' in the strings +** and it uses 'strcoll' (to respect locales) for each segments +** of the strings. +*/ +static int l_strcmp (const TString *ls, const TString *rs) { + const char *l = getstr(ls); + size_t ll = tsslen(ls); + const char *r = getstr(rs); + size_t lr = tsslen(rs); + for (;;) { /* for each segment */ + int temp = strcoll(l, r); + if (temp != 0) /* not equal? */ + return temp; /* done */ + else { /* strings are equal up to a '\0' */ + size_t len = strlen(l); /* index of first '\0' in both strings */ + if (len == lr) /* 'rs' is finished? */ + return (len == ll) ? 0 : 1; /* check 'ls' */ + else if (len == ll) /* 'ls' is finished? */ + return -1; /* 'ls' is less than 'rs' ('rs' is not finished) */ + /* both strings longer than 'len'; go on comparing after the '\0' */ + len++; + l += len; ll -= len; r += len; lr -= len; + } + } +} + + +/* +** Check whether integer 'i' is less than float 'f'. If 'i' has an +** exact representation as a float ('l_intfitsf'), compare numbers as +** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'. +** If 'ceil(f)' is out of integer range, either 'f' is greater than +** all integers or less than all integers. +** (The test with 'l_intfitsf' is only for performance; the else +** case is correct for all values, but it is slow due to the conversion +** from float to int.) +** When 'f' is NaN, comparisons must result in false. +*/ +l_sinline int LTintfloat (lua_Integer i, lua_Number f) { + if (l_intfitsf(i)) + return luai_numlt(cast_num(i), f); /* compare them as floats */ + else { /* i < f <=> i < ceil(f) */ + lua_Integer fi; + if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ + return i < fi; /* compare them as integers */ + else /* 'f' is either greater or less than all integers */ + return f > 0; /* greater? */ + } +} + + +/* +** Check whether integer 'i' is less than or equal to float 'f'. +** See comments on previous function. +*/ +l_sinline int LEintfloat (lua_Integer i, lua_Number f) { + if (l_intfitsf(i)) + return luai_numle(cast_num(i), f); /* compare them as floats */ + else { /* i <= f <=> i <= floor(f) */ + lua_Integer fi; + if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ + return i <= fi; /* compare them as integers */ + else /* 'f' is either greater or less than all integers */ + return f > 0; /* greater? */ + } +} + + +/* +** Check whether float 'f' is less than integer 'i'. +** See comments on previous function. +*/ +l_sinline int LTfloatint (lua_Number f, lua_Integer i) { + if (l_intfitsf(i)) + return luai_numlt(f, cast_num(i)); /* compare them as floats */ + else { /* f < i <=> floor(f) < i */ + lua_Integer fi; + if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ + return fi < i; /* compare them as integers */ + else /* 'f' is either greater or less than all integers */ + return f < 0; /* less? */ + } +} + + +/* +** Check whether float 'f' is less than or equal to integer 'i'. +** See comments on previous function. +*/ +l_sinline int LEfloatint (lua_Number f, lua_Integer i) { + if (l_intfitsf(i)) + return luai_numle(f, cast_num(i)); /* compare them as floats */ + else { /* f <= i <=> ceil(f) <= i */ + lua_Integer fi; + if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ + return fi <= i; /* compare them as integers */ + else /* 'f' is either greater or less than all integers */ + return f < 0; /* less? */ + } +} + + +/* +** Return 'l < r', for numbers. +*/ +l_sinline int LTnum (const TValue *l, const TValue *r) { + lua_assert(ttisnumber(l) && ttisnumber(r)); + if (ttisinteger(l)) { + lua_Integer li = ivalue(l); + if (ttisinteger(r)) + return li < ivalue(r); /* both are integers */ + else /* 'l' is int and 'r' is float */ + return LTintfloat(li, fltvalue(r)); /* l < r ? */ + } + else { + lua_Number lf = fltvalue(l); /* 'l' must be float */ + if (ttisfloat(r)) + return luai_numlt(lf, fltvalue(r)); /* both are float */ + else /* 'l' is float and 'r' is int */ + return LTfloatint(lf, ivalue(r)); + } +} + + +/* +** Return 'l <= r', for numbers. +*/ +l_sinline int LEnum (const TValue *l, const TValue *r) { + lua_assert(ttisnumber(l) && ttisnumber(r)); + if (ttisinteger(l)) { + lua_Integer li = ivalue(l); + if (ttisinteger(r)) + return li <= ivalue(r); /* both are integers */ + else /* 'l' is int and 'r' is float */ + return LEintfloat(li, fltvalue(r)); /* l <= r ? */ + } + else { + lua_Number lf = fltvalue(l); /* 'l' must be float */ + if (ttisfloat(r)) + return luai_numle(lf, fltvalue(r)); /* both are float */ + else /* 'l' is float and 'r' is int */ + return LEfloatint(lf, ivalue(r)); + } +} + + +/* +** return 'l < r' for non-numbers. +*/ +static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) { + lua_assert(!ttisnumber(l) || !ttisnumber(r)); + if (ttisstring(l) && ttisstring(r)) /* both are strings? */ + return l_strcmp(tsvalue(l), tsvalue(r)) < 0; + else + return luaT_callorderTM(L, l, r, TM_LT); +} + + +/* +** Main operation less than; return 'l < r'. +*/ +int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { + if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ + return LTnum(l, r); + else return lessthanothers(L, l, r); +} + + +/* +** return 'l <= r' for non-numbers. +*/ +static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) { + lua_assert(!ttisnumber(l) || !ttisnumber(r)); + if (ttisstring(l) && ttisstring(r)) /* both are strings? */ + return l_strcmp(tsvalue(l), tsvalue(r)) <= 0; + else + return luaT_callorderTM(L, l, r, TM_LE); +} + + +/* +** Main operation less than or equal to; return 'l <= r'. +*/ +int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { + if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ + return LEnum(l, r); + else return lessequalothers(L, l, r); +} + + +/* +** Main operation for equality of Lua values; return 't1 == t2'. +** L == NULL means raw equality (no metamethods) +*/ +int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { + const TValue *tm; + if (ttypetag(t1) != ttypetag(t2)) { /* not the same variant? */ + if (ttype(t1) != ttype(t2) || ttype(t1) != LUA_TNUMBER) + return 0; /* only numbers can be equal with different variants */ + else { /* two numbers with different variants */ + /* One of them is an integer. If the other does not have an + integer value, they cannot be equal; otherwise, compare their + integer values. */ + lua_Integer i1, i2; + return (luaV_tointegerns(t1, &i1, F2Ieq) && + luaV_tointegerns(t2, &i2, F2Ieq) && + i1 == i2); + } + } + /* values have same type and same variant */ + switch (ttypetag(t1)) { + case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1; + case LUA_VNUMINT: return (ivalue(t1) == ivalue(t2)); + case LUA_VNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2)); + case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); + case LUA_VLCF: return fvalue(t1) == fvalue(t2); + case LUA_VSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2)); + case LUA_VLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2)); + case LUA_VUSERDATA: { + if (uvalue(t1) == uvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = fasttm(L, uvalue(t1)->metatable, TM_EQ); + if (tm == NULL) + tm = fasttm(L, uvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + case LUA_VTABLE: { + if (hvalue(t1) == hvalue(t2)) return 1; + else if (L == NULL) return 0; + tm = fasttm(L, hvalue(t1)->metatable, TM_EQ); + if (tm == NULL) + tm = fasttm(L, hvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + default: + return gcvalue(t1) == gcvalue(t2); + } + if (tm == NULL) /* no TM? */ + return 0; /* objects are different */ + else { + luaT_callTMres(L, tm, t1, t2, L->top.p); /* call TM */ + return !l_isfalse(s2v(L->top.p)); + } +} + + +/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */ +#define tostring(L,o) \ + (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1))) + +#define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0) + +/* copy strings in stack from top - n up to top - 1 to buffer */ +static void copy2buff (StkId top, int n, char *buff) { + size_t tl = 0; /* size already copied */ + do { + size_t l = vslen(s2v(top - n)); /* length of string being copied */ + memcpy(buff + tl, svalue(s2v(top - n)), l * sizeof(char)); + tl += l; + } while (--n > 0); +} + + +/* +** Main operation for concatenation: concat 'total' values in the stack, +** from 'L->top.p - total' up to 'L->top.p - 1'. +*/ +void luaV_concat (lua_State *L, int total) { + if (total == 1) + return; /* "all" values already concatenated */ + do { + StkId top = L->top.p; + int n = 2; /* number of elements handled in this pass (at least 2) */ + if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) || + !tostring(L, s2v(top - 1))) + luaT_tryconcatTM(L); /* may invalidate 'top' */ + else if (isemptystr(s2v(top - 1))) /* second operand is empty? */ + cast_void(tostring(L, s2v(top - 2))); /* result is first operand */ + else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */ + setobjs2s(L, top - 2, top - 1); /* result is second op. */ + } + else { + /* at least two non-empty string values; get as many as possible */ + size_t tl = vslen(s2v(top - 1)); + TString *ts; + /* collect total length and number of strings */ + for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) { + size_t l = vslen(s2v(top - n - 1)); + if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl)) { + L->top.p = top - total; /* pop strings to avoid wasting stack */ + luaG_runerror(L, "string length overflow"); + } + tl += l; + } + if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ + char buff[LUAI_MAXSHORTLEN]; + copy2buff(top, n, buff); /* copy strings to buffer */ + ts = luaS_newlstr(L, buff, tl); + } + else { /* long string; copy strings directly to final result */ + ts = luaS_createlngstrobj(L, tl); + copy2buff(top, n, getstr(ts)); + } + setsvalue2s(L, top - n, ts); /* create result */ + } + total -= n - 1; /* got 'n' strings to create one new */ + L->top.p -= n - 1; /* popped 'n' strings and pushed one */ + } while (total > 1); /* repeat until only 1 result left */ +} + + +/* +** Main operation 'ra = #rb'. +*/ +void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { + const TValue *tm; + switch (ttypetag(rb)) { + case LUA_VTABLE: { + Table *h = hvalue(rb); + tm = fasttm(L, h->metatable, TM_LEN); + if (tm) break; /* metamethod? break switch to call it */ + setivalue(s2v(ra), luaH_getn(h)); /* else primitive len */ + return; + } + case LUA_VSHRSTR: { + setivalue(s2v(ra), tsvalue(rb)->shrlen); + return; + } + case LUA_VLNGSTR: { + setivalue(s2v(ra), tsvalue(rb)->u.lnglen); + return; + } + default: { /* try metamethod */ + tm = luaT_gettmbyobj(L, rb, TM_LEN); + if (l_unlikely(notm(tm))) /* no metamethod? */ + luaG_typeerror(L, rb, "get length of"); + break; + } + } + luaT_callTMres(L, tm, rb, rb, ra); +} + + +/* +** Integer division; return 'm // n', that is, floor(m/n). +** C division truncates its result (rounds towards zero). +** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer, +** otherwise 'floor(q) == trunc(q) - 1'. +*/ +lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) { + if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ + if (n == 0) + luaG_runerror(L, "attempt to divide by zero"); + return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */ + } + else { + lua_Integer q = m / n; /* perform C division */ + if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */ + q -= 1; /* correct result for different rounding */ + return q; + } +} + + +/* +** Integer modulus; return 'm % n'. (Assume that C '%' with +** negative operands follows C99 behavior. See previous comment +** about luaV_idiv.) +*/ +lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { + if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ + if (n == 0) + luaG_runerror(L, "attempt to perform 'n%%0'"); + return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */ + } + else { + lua_Integer r = m % n; + if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */ + r += n; /* correct result for different rounding */ + return r; + } +} + + +/* +** Float modulus +*/ +lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) { + lua_Number r; + luai_nummod(L, m, n, r); + return r; +} + + +/* number of bits in an integer */ +#define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT) + + +/* +** Shift left operation. (Shift right just negates 'y'.) +*/ +lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) { + if (y < 0) { /* shift right? */ + if (y <= -NBITS) return 0; + else return intop(>>, x, -y); + } + else { /* shift left */ + if (y >= NBITS) return 0; + else return intop(<<, x, y); + } +} + + +/* +** create a new Lua closure, push it in the stack, and initialize +** its upvalues. +*/ +static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, + StkId ra) { + int nup = p->sizeupvalues; + Upvaldesc *uv = p->upvalues; + int i; + LClosure *ncl = luaF_newLclosure(L, nup); + ncl->p = p; + setclLvalue2s(L, ra, ncl); /* anchor new closure in stack */ + for (i = 0; i < nup; i++) { /* fill in its upvalues */ + if (uv[i].instack) /* upvalue refers to local variable? */ + ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx); + else /* get upvalue from enclosing function */ + ncl->upvals[i] = encup[uv[i].idx]; + luaC_objbarrier(L, ncl, ncl->upvals[i]); + } +} + + +/* +** finish execution of an opcode interrupted by a yield +*/ +void luaV_finishOp (lua_State *L) { + CallInfo *ci = L->ci; + StkId base = ci->func.p + 1; + Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ + OpCode op = GET_OPCODE(inst); + switch (op) { /* finish its execution */ + case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { + setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p); + break; + } + case OP_UNM: case OP_BNOT: case OP_LEN: + case OP_GETTABUP: case OP_GETTABLE: case OP_GETI: + case OP_GETFIELD: case OP_SELF: { + setobjs2s(L, base + GETARG_A(inst), --L->top.p); + break; + } + case OP_LT: case OP_LE: + case OP_LTI: case OP_LEI: + case OP_GTI: case OP_GEI: + case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */ + int res = !l_isfalse(s2v(L->top.p - 1)); + L->top.p--; +#if defined(LUA_COMPAT_LT_LE) + if (ci->callstatus & CIST_LEQ) { /* "<=" using "<" instead? */ + ci->callstatus ^= CIST_LEQ; /* clear mark */ + res = !res; /* negate result */ + } +#endif + lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); + if (res != GETARG_k(inst)) /* condition failed? */ + ci->u.l.savedpc++; /* skip jump instruction */ + break; + } + case OP_CONCAT: { + StkId top = L->top.p - 1; /* top when 'luaT_tryconcatTM' was called */ + int a = GETARG_A(inst); /* first element to concatenate */ + int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */ + setobjs2s(L, top - 2, top); /* put TM result in proper position */ + L->top.p = top - 1; /* top is one after last element (at top-2) */ + luaV_concat(L, total); /* concat them (may yield again) */ + break; + } + case OP_CLOSE: { /* yielded closing variables */ + ci->u.l.savedpc--; /* repeat instruction to close other vars. */ + break; + } + case OP_RETURN: { /* yielded closing variables */ + StkId ra = base + GETARG_A(inst); + /* adjust top to signal correct number of returns, in case the + return is "up to top" ('isIT') */ + L->top.p = ra + ci->u2.nres; + /* repeat instruction to close other vars. and complete the return */ + ci->u.l.savedpc--; + break; + } + default: { + /* only these other opcodes can yield */ + lua_assert(op == OP_TFORCALL || op == OP_CALL || + op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE || + op == OP_SETI || op == OP_SETFIELD); + break; + } + } +} + + + + +/* +** {================================================================== +** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute' +** =================================================================== +*/ + +#define l_addi(L,a,b) intop(+, a, b) +#define l_subi(L,a,b) intop(-, a, b) +#define l_muli(L,a,b) intop(*, a, b) +#define l_band(a,b) intop(&, a, b) +#define l_bor(a,b) intop(|, a, b) +#define l_bxor(a,b) intop(^, a, b) + +#define l_lti(a,b) (a < b) +#define l_lei(a,b) (a <= b) +#define l_gti(a,b) (a > b) +#define l_gei(a,b) (a >= b) + + +/* +** Arithmetic operations with immediate operands. 'iop' is the integer +** operation, 'fop' is the float operation. +*/ +#define op_arithI(L,iop,fop) { \ + StkId ra = RA(i); \ + TValue *v1 = vRB(i); \ + int imm = GETARG_sC(i); \ + if (ttisinteger(v1)) { \ + lua_Integer iv1 = ivalue(v1); \ + pc++; setivalue(s2v(ra), iop(L, iv1, imm)); \ + } \ + else if (ttisfloat(v1)) { \ + lua_Number nb = fltvalue(v1); \ + lua_Number fimm = cast_num(imm); \ + pc++; setfltvalue(s2v(ra), fop(L, nb, fimm)); \ + }} + + +/* +** Auxiliary function for arithmetic operations over floats and others +** with two register operands. +*/ +#define op_arithf_aux(L,v1,v2,fop) { \ + lua_Number n1; lua_Number n2; \ + if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \ + pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \ + }} + + +/* +** Arithmetic operations over floats and others with register operands. +*/ +#define op_arithf(L,fop) { \ + StkId ra = RA(i); \ + TValue *v1 = vRB(i); \ + TValue *v2 = vRC(i); \ + op_arithf_aux(L, v1, v2, fop); } + + +/* +** Arithmetic operations with K operands for floats. +*/ +#define op_arithfK(L,fop) { \ + StkId ra = RA(i); \ + TValue *v1 = vRB(i); \ + TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ + op_arithf_aux(L, v1, v2, fop); } + + +/* +** Arithmetic operations over integers and floats. +*/ +#define op_arith_aux(L,v1,v2,iop,fop) { \ + StkId ra = RA(i); \ + if (ttisinteger(v1) && ttisinteger(v2)) { \ + lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \ + pc++; setivalue(s2v(ra), iop(L, i1, i2)); \ + } \ + else op_arithf_aux(L, v1, v2, fop); } + + +/* +** Arithmetic operations with register operands. +*/ +#define op_arith(L,iop,fop) { \ + TValue *v1 = vRB(i); \ + TValue *v2 = vRC(i); \ + op_arith_aux(L, v1, v2, iop, fop); } + + +/* +** Arithmetic operations with K operands. +*/ +#define op_arithK(L,iop,fop) { \ + TValue *v1 = vRB(i); \ + TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ + op_arith_aux(L, v1, v2, iop, fop); } + + +/* +** Bitwise operations with constant operand. +*/ +#define op_bitwiseK(L,op) { \ + StkId ra = RA(i); \ + TValue *v1 = vRB(i); \ + TValue *v2 = KC(i); \ + lua_Integer i1; \ + lua_Integer i2 = ivalue(v2); \ + if (tointegerns(v1, &i1)) { \ + pc++; setivalue(s2v(ra), op(i1, i2)); \ + }} + + +/* +** Bitwise operations with register operands. +*/ +#define op_bitwise(L,op) { \ + StkId ra = RA(i); \ + TValue *v1 = vRB(i); \ + TValue *v2 = vRC(i); \ + lua_Integer i1; lua_Integer i2; \ + if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \ + pc++; setivalue(s2v(ra), op(i1, i2)); \ + }} + + +/* +** Order operations with register operands. 'opn' actually works +** for all numbers, but the fast track improves performance for +** integers. +*/ +#define op_order(L,opi,opn,other) { \ + StkId ra = RA(i); \ + int cond; \ + TValue *rb = vRB(i); \ + if (ttisinteger(s2v(ra)) && ttisinteger(rb)) { \ + lua_Integer ia = ivalue(s2v(ra)); \ + lua_Integer ib = ivalue(rb); \ + cond = opi(ia, ib); \ + } \ + else if (ttisnumber(s2v(ra)) && ttisnumber(rb)) \ + cond = opn(s2v(ra), rb); \ + else \ + Protect(cond = other(L, s2v(ra), rb)); \ + docondjump(); } + + +/* +** Order operations with immediate operand. (Immediate operand is +** always small enough to have an exact representation as a float.) +*/ +#define op_orderI(L,opi,opf,inv,tm) { \ + StkId ra = RA(i); \ + int cond; \ + int im = GETARG_sB(i); \ + if (ttisinteger(s2v(ra))) \ + cond = opi(ivalue(s2v(ra)), im); \ + else if (ttisfloat(s2v(ra))) { \ + lua_Number fa = fltvalue(s2v(ra)); \ + lua_Number fim = cast_num(im); \ + cond = opf(fa, fim); \ + } \ + else { \ + int isf = GETARG_C(i); \ + Protect(cond = luaT_callorderiTM(L, s2v(ra), im, inv, isf, tm)); \ + } \ + docondjump(); } + +/* }================================================================== */ + + +/* +** {================================================================== +** Function 'luaV_execute': main interpreter loop +** =================================================================== +*/ + +/* +** some macros for common tasks in 'luaV_execute' +*/ + + +#define RA(i) (base+GETARG_A(i)) +#define RB(i) (base+GETARG_B(i)) +#define vRB(i) s2v(RB(i)) +#define KB(i) (k+GETARG_B(i)) +#define RC(i) (base+GETARG_C(i)) +#define vRC(i) s2v(RC(i)) +#define KC(i) (k+GETARG_C(i)) +#define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i))) + + + +#define updatetrap(ci) (trap = ci->u.l.trap) + +#define updatebase(ci) (base = ci->func.p + 1) + + +#define updatestack(ci) \ + { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } } + + +/* +** Execute a jump instruction. The 'updatetrap' allows signals to stop +** tight loops. (Without it, the local copy of 'trap' could never change.) +*/ +#define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); } + + +/* for test instructions, execute the jump instruction that follows it */ +#define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); } + +/* +** do a conditional jump: skip next instruction if 'cond' is not what +** was expected (parameter 'k'), else do next instruction, which must +** be a jump. +*/ +#define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci); + + +/* +** Correct global 'pc'. +*/ +#define savepc(L) (ci->u.l.savedpc = pc) + + +/* +** Whenever code can raise errors, the global 'pc' and the global +** 'top' must be correct to report occasional errors. +*/ +#define savestate(L,ci) (savepc(L), L->top.p = ci->top.p) + + +/* +** Protect code that, in general, can raise errors, reallocate the +** stack, and change the hooks. +*/ +#define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci)) + +/* special version that does not change the top */ +#define ProtectNT(exp) (savepc(L), (exp), updatetrap(ci)) + +/* +** Protect code that can only raise errors. (That is, it cannot change +** the stack or hooks.) +*/ +#define halfProtect(exp) (savestate(L,ci), (exp)) + +/* 'c' is the limit of live values in the stack */ +#define checkGC(L,c) \ + { luaC_condGC(L, (savepc(L), L->top.p = (c)), \ + updatetrap(ci)); \ + luai_threadyield(L); } + + +/* fetch an instruction and prepare its execution */ +#define vmfetch() { \ + if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \ + trap = luaG_traceexec(L, pc); /* handle hooks */ \ + updatebase(ci); /* correct stack */ \ + } \ + i = *(pc++); \ +} + +#define vmdispatch(o) switch(o) +#define vmcase(l) case l: +#define vmbreak break + + +void luaV_execute (lua_State *L, CallInfo *ci) { + LClosure *cl; + TValue *k; + StkId base; + const Instruction *pc; + int trap; +#if LUA_USE_JUMPTABLE +#include "ljumptab.h" +#endif + startfunc: + trap = L->hookmask; + returning: /* trap already set */ + cl = clLvalue(s2v(ci->func.p)); + k = cl->p->k; + pc = ci->u.l.savedpc; + if (l_unlikely(trap)) { + if (pc == cl->p->code) { /* first instruction (not resuming)? */ + if (cl->p->is_vararg) + trap = 0; /* hooks will start after VARARGPREP instruction */ + else /* check 'call' hook */ + luaD_hookcall(L, ci); + } + ci->u.l.trap = 1; /* assume trap is on, for now */ + } + base = ci->func.p + 1; + /* main loop of interpreter */ + for (;;) { + Instruction i; /* instruction being executed */ + vmfetch(); + #if 0 + /* low-level line tracing for debugging Lua */ + printf("line: %d\n", luaG_getfuncline(cl->p, pcRel(pc, cl->p))); + #endif + lua_assert(base == ci->func.p + 1); + lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p); + /* invalidate top for instructions not expecting it */ + lua_assert(isIT(i) || (cast_void(L->top.p = base), 1)); + vmdispatch (GET_OPCODE(i)) { + vmcase(OP_MOVE) { + StkId ra = RA(i); + setobjs2s(L, ra, RB(i)); + vmbreak; + } + vmcase(OP_LOADI) { + StkId ra = RA(i); + lua_Integer b = GETARG_sBx(i); + setivalue(s2v(ra), b); + vmbreak; + } + vmcase(OP_LOADF) { + StkId ra = RA(i); + int b = GETARG_sBx(i); + setfltvalue(s2v(ra), cast_num(b)); + vmbreak; + } + vmcase(OP_LOADK) { + StkId ra = RA(i); + TValue *rb = k + GETARG_Bx(i); + setobj2s(L, ra, rb); + vmbreak; + } + vmcase(OP_LOADKX) { + StkId ra = RA(i); + TValue *rb; + rb = k + GETARG_Ax(*pc); pc++; + setobj2s(L, ra, rb); + vmbreak; + } + vmcase(OP_LOADFALSE) { + StkId ra = RA(i); + setbfvalue(s2v(ra)); + vmbreak; + } + vmcase(OP_LFALSESKIP) { + StkId ra = RA(i); + setbfvalue(s2v(ra)); + pc++; /* skip next instruction */ + vmbreak; + } + vmcase(OP_LOADTRUE) { + StkId ra = RA(i); + setbtvalue(s2v(ra)); + vmbreak; + } + vmcase(OP_LOADNIL) { + StkId ra = RA(i); + int b = GETARG_B(i); + do { + setnilvalue(s2v(ra++)); + } while (b--); + vmbreak; + } + vmcase(OP_GETUPVAL) { + StkId ra = RA(i); + int b = GETARG_B(i); + setobj2s(L, ra, cl->upvals[b]->v.p); + vmbreak; + } + vmcase(OP_SETUPVAL) { + StkId ra = RA(i); + UpVal *uv = cl->upvals[GETARG_B(i)]; + setobj(L, uv->v.p, s2v(ra)); + luaC_barrier(L, uv, s2v(ra)); + vmbreak; + } + vmcase(OP_GETTABUP) { + StkId ra = RA(i); + const TValue *slot; + TValue *upval = cl->upvals[GETARG_B(i)]->v.p; + TValue *rc = KC(i); + TString *key = tsvalue(rc); /* key must be a string */ + if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { + setobj2s(L, ra, slot); + } + else + Protect(luaV_finishget(L, upval, rc, ra, slot)); + vmbreak; + } + vmcase(OP_GETTABLE) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = vRB(i); + TValue *rc = vRC(i); + lua_Unsigned n; + if (ttisinteger(rc) /* fast track for integers? */ + ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot)) + : luaV_fastget(L, rb, rc, slot, luaH_get)) { + setobj2s(L, ra, slot); + } + else + Protect(luaV_finishget(L, rb, rc, ra, slot)); + vmbreak; + } + vmcase(OP_GETI) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = vRB(i); + int c = GETARG_C(i); + if (luaV_fastgeti(L, rb, c, slot)) { + setobj2s(L, ra, slot); + } + else { + TValue key; + setivalue(&key, c); + Protect(luaV_finishget(L, rb, &key, ra, slot)); + } + vmbreak; + } + vmcase(OP_GETFIELD) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = vRB(i); + TValue *rc = KC(i); + TString *key = tsvalue(rc); /* key must be a string */ + if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) { + setobj2s(L, ra, slot); + } + else + Protect(luaV_finishget(L, rb, rc, ra, slot)); + vmbreak; + } + vmcase(OP_SETTABUP) { + const TValue *slot; + TValue *upval = cl->upvals[GETARG_A(i)]->v.p; + TValue *rb = KB(i); + TValue *rc = RKC(i); + TString *key = tsvalue(rb); /* key must be a string */ + if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { + luaV_finishfastset(L, upval, slot, rc); + } + else + Protect(luaV_finishset(L, upval, rb, rc, slot)); + vmbreak; + } + vmcase(OP_SETTABLE) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = vRB(i); /* key (table is in 'ra') */ + TValue *rc = RKC(i); /* value */ + lua_Unsigned n; + if (ttisinteger(rb) /* fast track for integers? */ + ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot)) + : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) { + luaV_finishfastset(L, s2v(ra), slot, rc); + } + else + Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); + vmbreak; + } + vmcase(OP_SETI) { + StkId ra = RA(i); + const TValue *slot; + int c = GETARG_B(i); + TValue *rc = RKC(i); + if (luaV_fastgeti(L, s2v(ra), c, slot)) { + luaV_finishfastset(L, s2v(ra), slot, rc); + } + else { + TValue key; + setivalue(&key, c); + Protect(luaV_finishset(L, s2v(ra), &key, rc, slot)); + } + vmbreak; + } + vmcase(OP_SETFIELD) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = KB(i); + TValue *rc = RKC(i); + TString *key = tsvalue(rb); /* key must be a string */ + if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) { + luaV_finishfastset(L, s2v(ra), slot, rc); + } + else + Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); + vmbreak; + } + vmcase(OP_NEWTABLE) { + StkId ra = RA(i); + int b = GETARG_B(i); /* log2(hash size) + 1 */ + int c = GETARG_C(i); /* array size */ + Table *t; + if (b > 0) + b = 1 << (b - 1); /* size is 2^(b - 1) */ + lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0)); + if (TESTARG_k(i)) /* non-zero extra argument? */ + c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */ + pc++; /* skip extra argument */ + L->top.p = ra + 1; /* correct top in case of emergency GC */ + t = luaH_new(L); /* memory allocation */ + sethvalue2s(L, ra, t); + if (b != 0 || c != 0) + luaH_resize(L, t, c, b); /* idem */ + checkGC(L, ra + 1); + vmbreak; + } + vmcase(OP_SELF) { + StkId ra = RA(i); + const TValue *slot; + TValue *rb = vRB(i); + TValue *rc = RKC(i); + TString *key = tsvalue(rc); /* key must be a string */ + setobj2s(L, ra + 1, rb); + if (luaV_fastget(L, rb, key, slot, luaH_getstr)) { + setobj2s(L, ra, slot); + } + else + Protect(luaV_finishget(L, rb, rc, ra, slot)); + vmbreak; + } + vmcase(OP_ADDI) { + op_arithI(L, l_addi, luai_numadd); + vmbreak; + } + vmcase(OP_ADDK) { + op_arithK(L, l_addi, luai_numadd); + vmbreak; + } + vmcase(OP_SUBK) { + op_arithK(L, l_subi, luai_numsub); + vmbreak; + } + vmcase(OP_MULK) { + op_arithK(L, l_muli, luai_nummul); + vmbreak; + } + vmcase(OP_MODK) { + savestate(L, ci); /* in case of division by 0 */ + op_arithK(L, luaV_mod, luaV_modf); + vmbreak; + } + vmcase(OP_POWK) { + op_arithfK(L, luai_numpow); + vmbreak; + } + vmcase(OP_DIVK) { + op_arithfK(L, luai_numdiv); + vmbreak; + } + vmcase(OP_IDIVK) { + savestate(L, ci); /* in case of division by 0 */ + op_arithK(L, luaV_idiv, luai_numidiv); + vmbreak; + } + vmcase(OP_BANDK) { + op_bitwiseK(L, l_band); + vmbreak; + } + vmcase(OP_BORK) { + op_bitwiseK(L, l_bor); + vmbreak; + } + vmcase(OP_BXORK) { + op_bitwiseK(L, l_bxor); + vmbreak; + } + vmcase(OP_SHRI) { + StkId ra = RA(i); + TValue *rb = vRB(i); + int ic = GETARG_sC(i); + lua_Integer ib; + if (tointegerns(rb, &ib)) { + pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic)); + } + vmbreak; + } + vmcase(OP_SHLI) { + StkId ra = RA(i); + TValue *rb = vRB(i); + int ic = GETARG_sC(i); + lua_Integer ib; + if (tointegerns(rb, &ib)) { + pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib)); + } + vmbreak; + } + vmcase(OP_ADD) { + op_arith(L, l_addi, luai_numadd); + vmbreak; + } + vmcase(OP_SUB) { + op_arith(L, l_subi, luai_numsub); + vmbreak; + } + vmcase(OP_MUL) { + op_arith(L, l_muli, luai_nummul); + vmbreak; + } + vmcase(OP_MOD) { + savestate(L, ci); /* in case of division by 0 */ + op_arith(L, luaV_mod, luaV_modf); + vmbreak; + } + vmcase(OP_POW) { + op_arithf(L, luai_numpow); + vmbreak; + } + vmcase(OP_DIV) { /* float division (always with floats) */ + op_arithf(L, luai_numdiv); + vmbreak; + } + vmcase(OP_IDIV) { /* floor division */ + savestate(L, ci); /* in case of division by 0 */ + op_arith(L, luaV_idiv, luai_numidiv); + vmbreak; + } + vmcase(OP_BAND) { + op_bitwise(L, l_band); + vmbreak; + } + vmcase(OP_BOR) { + op_bitwise(L, l_bor); + vmbreak; + } + vmcase(OP_BXOR) { + op_bitwise(L, l_bxor); + vmbreak; + } + vmcase(OP_SHR) { + op_bitwise(L, luaV_shiftr); + vmbreak; + } + vmcase(OP_SHL) { + op_bitwise(L, luaV_shiftl); + vmbreak; + } + vmcase(OP_MMBIN) { + StkId ra = RA(i); + Instruction pi = *(pc - 2); /* original arith. expression */ + TValue *rb = vRB(i); + TMS tm = (TMS)GETARG_C(i); + StkId result = RA(pi); + lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR); + Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm)); + vmbreak; + } + vmcase(OP_MMBINI) { + StkId ra = RA(i); + Instruction pi = *(pc - 2); /* original arith. expression */ + int imm = GETARG_sB(i); + TMS tm = (TMS)GETARG_C(i); + int flip = GETARG_k(i); + StkId result = RA(pi); + Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm)); + vmbreak; + } + vmcase(OP_MMBINK) { + StkId ra = RA(i); + Instruction pi = *(pc - 2); /* original arith. expression */ + TValue *imm = KB(i); + TMS tm = (TMS)GETARG_C(i); + int flip = GETARG_k(i); + StkId result = RA(pi); + Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm)); + vmbreak; + } + vmcase(OP_UNM) { + StkId ra = RA(i); + TValue *rb = vRB(i); + lua_Number nb; + if (ttisinteger(rb)) { + lua_Integer ib = ivalue(rb); + setivalue(s2v(ra), intop(-, 0, ib)); + } + else if (tonumberns(rb, nb)) { + setfltvalue(s2v(ra), luai_numunm(L, nb)); + } + else + Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM)); + vmbreak; + } + vmcase(OP_BNOT) { + StkId ra = RA(i); + TValue *rb = vRB(i); + lua_Integer ib; + if (tointegerns(rb, &ib)) { + setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib)); + } + else + Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT)); + vmbreak; + } + vmcase(OP_NOT) { + StkId ra = RA(i); + TValue *rb = vRB(i); + if (l_isfalse(rb)) + setbtvalue(s2v(ra)); + else + setbfvalue(s2v(ra)); + vmbreak; + } + vmcase(OP_LEN) { + StkId ra = RA(i); + Protect(luaV_objlen(L, ra, vRB(i))); + vmbreak; + } + vmcase(OP_CONCAT) { + StkId ra = RA(i); + int n = GETARG_B(i); /* number of elements to concatenate */ + L->top.p = ra + n; /* mark the end of concat operands */ + ProtectNT(luaV_concat(L, n)); + checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */ + vmbreak; + } + vmcase(OP_CLOSE) { + StkId ra = RA(i); + Protect(luaF_close(L, ra, LUA_OK, 1)); + vmbreak; + } + vmcase(OP_TBC) { + StkId ra = RA(i); + /* create new to-be-closed upvalue */ + halfProtect(luaF_newtbcupval(L, ra)); + vmbreak; + } + vmcase(OP_JMP) { + dojump(ci, i, 0); + vmbreak; + } + vmcase(OP_EQ) { + StkId ra = RA(i); + int cond; + TValue *rb = vRB(i); + Protect(cond = luaV_equalobj(L, s2v(ra), rb)); + docondjump(); + vmbreak; + } + vmcase(OP_LT) { + op_order(L, l_lti, LTnum, lessthanothers); + vmbreak; + } + vmcase(OP_LE) { + op_order(L, l_lei, LEnum, lessequalothers); + vmbreak; + } + vmcase(OP_EQK) { + StkId ra = RA(i); + TValue *rb = KB(i); + /* basic types do not use '__eq'; we can use raw equality */ + int cond = luaV_rawequalobj(s2v(ra), rb); + docondjump(); + vmbreak; + } + vmcase(OP_EQI) { + StkId ra = RA(i); + int cond; + int im = GETARG_sB(i); + if (ttisinteger(s2v(ra))) + cond = (ivalue(s2v(ra)) == im); + else if (ttisfloat(s2v(ra))) + cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im)); + else + cond = 0; /* other types cannot be equal to a number */ + docondjump(); + vmbreak; + } + vmcase(OP_LTI) { + op_orderI(L, l_lti, luai_numlt, 0, TM_LT); + vmbreak; + } + vmcase(OP_LEI) { + op_orderI(L, l_lei, luai_numle, 0, TM_LE); + vmbreak; + } + vmcase(OP_GTI) { + op_orderI(L, l_gti, luai_numgt, 1, TM_LT); + vmbreak; + } + vmcase(OP_GEI) { + op_orderI(L, l_gei, luai_numge, 1, TM_LE); + vmbreak; + } + vmcase(OP_TEST) { + StkId ra = RA(i); + int cond = !l_isfalse(s2v(ra)); + docondjump(); + vmbreak; + } + vmcase(OP_TESTSET) { + StkId ra = RA(i); + TValue *rb = vRB(i); + if (l_isfalse(rb) == GETARG_k(i)) + pc++; + else { + setobj2s(L, ra, rb); + donextjump(ci); + } + vmbreak; + } + vmcase(OP_CALL) { + StkId ra = RA(i); + CallInfo *newci; + int b = GETARG_B(i); + int nresults = GETARG_C(i) - 1; + if (b != 0) /* fixed number of arguments? */ + L->top.p = ra + b; /* top signals number of arguments */ + /* else previous instruction set top */ + savepc(L); /* in case of errors */ + if ((newci = luaD_precall(L, ra, nresults)) == NULL) + updatetrap(ci); /* C call; nothing else to be done */ + else { /* Lua call: run function in this same C frame */ + ci = newci; + goto startfunc; + } + vmbreak; + } + vmcase(OP_TAILCALL) { + StkId ra = RA(i); + int b = GETARG_B(i); /* number of arguments + 1 (function) */ + int n; /* number of results when calling a C function */ + int nparams1 = GETARG_C(i); + /* delta is virtual 'func' - real 'func' (vararg functions) */ + int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0; + if (b != 0) + L->top.p = ra + b; + else /* previous instruction set top */ + b = cast_int(L->top.p - ra); + savepc(ci); /* several calls here can raise errors */ + if (TESTARG_k(i)) { + luaF_closeupval(L, base); /* close upvalues from current call */ + lua_assert(L->tbclist.p < base); /* no pending tbc variables */ + lua_assert(base == ci->func.p + 1); + } + if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0) /* Lua function? */ + goto startfunc; /* execute the callee */ + else { /* C function? */ + ci->func.p -= delta; /* restore 'func' (if vararg) */ + luaD_poscall(L, ci, n); /* finish caller */ + updatetrap(ci); /* 'luaD_poscall' can change hooks */ + goto ret; /* caller returns after the tail call */ + } + } + vmcase(OP_RETURN) { + StkId ra = RA(i); + int n = GETARG_B(i) - 1; /* number of results */ + int nparams1 = GETARG_C(i); + if (n < 0) /* not fixed? */ + n = cast_int(L->top.p - ra); /* get what is available */ + savepc(ci); + if (TESTARG_k(i)) { /* may there be open upvalues? */ + ci->u2.nres = n; /* save number of returns */ + if (L->top.p < ci->top.p) + L->top.p = ci->top.p; + luaF_close(L, base, CLOSEKTOP, 1); + updatetrap(ci); + updatestack(ci); + } + if (nparams1) /* vararg function? */ + ci->func.p -= ci->u.l.nextraargs + nparams1; + L->top.p = ra + n; /* set call for 'luaD_poscall' */ + luaD_poscall(L, ci, n); + updatetrap(ci); /* 'luaD_poscall' can change hooks */ + goto ret; + } + vmcase(OP_RETURN0) { + if (l_unlikely(L->hookmask)) { + StkId ra = RA(i); + L->top.p = ra; + savepc(ci); + luaD_poscall(L, ci, 0); /* no hurry... */ + trap = 1; + } + else { /* do the 'poscall' here */ + int nres; + L->ci = ci->previous; /* back to caller */ + L->top.p = base - 1; + for (nres = ci->nresults; l_unlikely(nres > 0); nres--) + setnilvalue(s2v(L->top.p++)); /* all results are nil */ + } + goto ret; + } + vmcase(OP_RETURN1) { + if (l_unlikely(L->hookmask)) { + StkId ra = RA(i); + L->top.p = ra + 1; + savepc(ci); + luaD_poscall(L, ci, 1); /* no hurry... */ + trap = 1; + } + else { /* do the 'poscall' here */ + int nres = ci->nresults; + L->ci = ci->previous; /* back to caller */ + if (nres == 0) + L->top.p = base - 1; /* asked for no results */ + else { + StkId ra = RA(i); + setobjs2s(L, base - 1, ra); /* at least this result */ + L->top.p = base; + for (; l_unlikely(nres > 1); nres--) + setnilvalue(s2v(L->top.p++)); /* complete missing results */ + } + } + ret: /* return from a Lua function */ + if (ci->callstatus & CIST_FRESH) + return; /* end this frame */ + else { + ci = ci->previous; + goto returning; /* continue running caller in this frame */ + } + } + vmcase(OP_FORLOOP) { + StkId ra = RA(i); + if (ttisinteger(s2v(ra + 2))) { /* integer loop? */ + lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1))); + if (count > 0) { /* still more iterations? */ + lua_Integer step = ivalue(s2v(ra + 2)); + lua_Integer idx = ivalue(s2v(ra)); /* internal index */ + chgivalue(s2v(ra + 1), count - 1); /* update counter */ + idx = intop(+, idx, step); /* add step to index */ + chgivalue(s2v(ra), idx); /* update internal index */ + setivalue(s2v(ra + 3), idx); /* and control variable */ + pc -= GETARG_Bx(i); /* jump back */ + } + } + else if (floatforloop(ra)) /* float loop */ + pc -= GETARG_Bx(i); /* jump back */ + updatetrap(ci); /* allows a signal to break the loop */ + vmbreak; + } + vmcase(OP_FORPREP) { + StkId ra = RA(i); + savestate(L, ci); /* in case of errors */ + if (forprep(L, ra)) + pc += GETARG_Bx(i) + 1; /* skip the loop */ + vmbreak; + } + vmcase(OP_TFORPREP) { + StkId ra = RA(i); + /* create to-be-closed upvalue (if needed) */ + halfProtect(luaF_newtbcupval(L, ra + 3)); + pc += GETARG_Bx(i); + i = *(pc++); /* go to next instruction */ + lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i)); + goto l_tforcall; + } + vmcase(OP_TFORCALL) { + l_tforcall: { + StkId ra = RA(i); + /* 'ra' has the iterator function, 'ra + 1' has the state, + 'ra + 2' has the control variable, and 'ra + 3' has the + to-be-closed variable. The call will use the stack after + these values (starting at 'ra + 4') + */ + /* push function, state, and control variable */ + memcpy(ra + 4, ra, 3 * sizeof(*ra)); + L->top.p = ra + 4 + 3; + ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */ + updatestack(ci); /* stack may have changed */ + i = *(pc++); /* go to next instruction */ + lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i)); + goto l_tforloop; + }} + vmcase(OP_TFORLOOP) { + l_tforloop: { + StkId ra = RA(i); + if (!ttisnil(s2v(ra + 4))) { /* continue loop? */ + setobjs2s(L, ra + 2, ra + 4); /* save control variable */ + pc -= GETARG_Bx(i); /* jump back */ + } + vmbreak; + }} + vmcase(OP_SETLIST) { + StkId ra = RA(i); + int n = GETARG_B(i); + unsigned int last = GETARG_C(i); + Table *h = hvalue(s2v(ra)); + if (n == 0) + n = cast_int(L->top.p - ra) - 1; /* get up to the top */ + else + L->top.p = ci->top.p; /* correct top in case of emergency GC */ + last += n; + if (TESTARG_k(i)) { + last += GETARG_Ax(*pc) * (MAXARG_C + 1); + pc++; + } + if (last > luaH_realasize(h)) /* needs more space? */ + luaH_resizearray(L, h, last); /* preallocate it at once */ + for (; n > 0; n--) { + TValue *val = s2v(ra + n); + setobj2t(L, &h->array[last - 1], val); + last--; + luaC_barrierback(L, obj2gco(h), val); + } + vmbreak; + } + vmcase(OP_CLOSURE) { + StkId ra = RA(i); + Proto *p = cl->p->p[GETARG_Bx(i)]; + halfProtect(pushclosure(L, p, cl->upvals, base, ra)); + checkGC(L, ra + 1); + vmbreak; + } + vmcase(OP_VARARG) { + StkId ra = RA(i); + int n = GETARG_C(i) - 1; /* required results */ + Protect(luaT_getvarargs(L, ci, ra, n)); + vmbreak; + } + vmcase(OP_VARARGPREP) { + ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p)); + if (l_unlikely(trap)) { /* previous "Protect" updated trap */ + luaD_hookcall(L, ci); + L->oldpc = 1; /* next opcode will be seen as a "new" line */ + } + updatebase(ci); /* function has new base after adjustment */ + vmbreak; + } + vmcase(OP_EXTRAARG) { + lua_assert(0); + vmbreak; + } + } + } +} + +/* }================================================================== */ diff --git a/src/libs/3rdparty/lua/src/lvm.h b/src/libs/3rdparty/lua/src/lvm.h new file mode 100644 index 00000000000..dba1ad27702 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lvm.h @@ -0,0 +1,141 @@ +/* +** $Id: lvm.h $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lvm_h +#define lvm_h + + +#include "ldo.h" +#include "lobject.h" +#include "ltm.h" + + +#if !defined(LUA_NOCVTN2S) +#define cvt2str(o) ttisnumber(o) +#else +#define cvt2str(o) 0 /* no conversion from numbers to strings */ +#endif + + +#if !defined(LUA_NOCVTS2N) +#define cvt2num(o) ttisstring(o) +#else +#define cvt2num(o) 0 /* no conversion from strings to numbers */ +#endif + + +/* +** You can define LUA_FLOORN2I if you want to convert floats to integers +** by flooring them (instead of raising an error if they are not +** integral values) +*/ +#if !defined(LUA_FLOORN2I) +#define LUA_FLOORN2I F2Ieq +#endif + + +/* +** Rounding modes for float->integer coercion + */ +typedef enum { + F2Ieq, /* no rounding; accepts only integral values */ + F2Ifloor, /* takes the floor of the number */ + F2Iceil /* takes the ceil of the number */ +} F2Imod; + + +/* convert an object to a float (including string coercion) */ +#define tonumber(o,n) \ + (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) + + +/* convert an object to a float (without string coercion) */ +#define tonumberns(o,n) \ + (ttisfloat(o) ? ((n) = fltvalue(o), 1) : \ + (ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0)) + + +/* convert an object to an integer (including string coercion) */ +#define tointeger(o,i) \ + (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ + : luaV_tointeger(o,i,LUA_FLOORN2I)) + + +/* convert an object to an integer (without string coercion) */ +#define tointegerns(o,i) \ + (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ + : luaV_tointegerns(o,i,LUA_FLOORN2I)) + + +#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) + +#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) + + +/* +** fast track for 'gettable': if 't' is a table and 't[k]' is present, +** return 1 with 'slot' pointing to 't[k]' (position of final result). +** Otherwise, return 0 (meaning it will have to check metamethod) +** with 'slot' pointing to an empty 't[k]' (if 't' is a table) or NULL +** (otherwise). 'f' is the raw get function to use. +*/ +#define luaV_fastget(L,t,k,slot,f) \ + (!ttistable(t) \ + ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ + : (slot = f(hvalue(t), k), /* else, do raw access */ \ + !isempty(slot))) /* result not empty? */ + + +/* +** Special case of 'luaV_fastget' for integers, inlining the fast case +** of 'luaH_getint'. +*/ +#define luaV_fastgeti(L,t,k,slot) \ + (!ttistable(t) \ + ? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \ + : (slot = (l_castS2U(k) - 1u < hvalue(t)->alimit) \ + ? &hvalue(t)->array[k - 1] : luaH_getint(hvalue(t), k), \ + !isempty(slot))) /* result not empty? */ + + +/* +** Finish a fast set operation (when fast get succeeds). In that case, +** 'slot' points to the place to put the value. +*/ +#define luaV_finishfastset(L,t,slot,v) \ + { setobj2t(L, cast(TValue *,slot), v); \ + luaC_barrierback(L, gcvalue(t), v); } + + +/* +** Shift right is the same as shift left with a negative 'y' +*/ +#define luaV_shiftr(x,y) luaV_shiftl(x,intop(-, 0, y)) + + + +LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); +LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); +LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode); +LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p, + F2Imod mode); +LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode); +LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *slot); +LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + TValue *val, const TValue *slot); +LUAI_FUNC void luaV_finishOp (lua_State *L); +LUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci); +LUAI_FUNC void luaV_concat (lua_State *L, int total); +LUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y); +LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); +LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); + +#endif diff --git a/src/libs/3rdparty/lua/src/lzio.c b/src/libs/3rdparty/lua/src/lzio.c new file mode 100644 index 00000000000..cd0a02d5f9b --- /dev/null +++ b/src/libs/3rdparty/lua/src/lzio.c @@ -0,0 +1,68 @@ +/* +** $Id: lzio.c $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + +#define lzio_c +#define LUA_CORE + +#include "lprefix.h" + + +#include + +#include "lua.h" + +#include "llimits.h" +#include "lmem.h" +#include "lstate.h" +#include "lzio.h" + + +int luaZ_fill (ZIO *z) { + size_t size; + lua_State *L = z->L; + const char *buff; + lua_unlock(L); + buff = z->reader(L, z->data, &size); + lua_lock(L); + if (buff == NULL || size == 0) + return EOZ; + z->n = size - 1; /* discount char being returned */ + z->p = buff; + return cast_uchar(*(z->p++)); +} + + +void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { + z->L = L; + z->reader = reader; + z->data = data; + z->n = 0; + z->p = NULL; +} + + +/* --------------------------------------------------------------- read --- */ +size_t luaZ_read (ZIO *z, void *b, size_t n) { + while (n) { + size_t m; + if (z->n == 0) { /* no bytes in buffer? */ + if (luaZ_fill(z) == EOZ) /* try to read more */ + return n; /* no more input; return number of missing bytes */ + else { + z->n++; /* luaZ_fill consumed first byte; put it back */ + z->p--; + } + } + m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ + memcpy(b, z->p, m); + z->n -= m; + z->p += m; + b = (char *)b + m; + n -= m; + } + return 0; +} + diff --git a/src/libs/3rdparty/lua/src/lzio.h b/src/libs/3rdparty/lua/src/lzio.h new file mode 100644 index 00000000000..38f397fd284 --- /dev/null +++ b/src/libs/3rdparty/lua/src/lzio.h @@ -0,0 +1,66 @@ +/* +** $Id: lzio.h $ +** Buffered streams +** See Copyright Notice in lua.h +*/ + + +#ifndef lzio_h +#define lzio_h + +#include "lua.h" + +#include "lmem.h" + + +#define EOZ (-1) /* end of stream */ + +typedef struct Zio ZIO; + +#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) + + +typedef struct Mbuffer { + char *buffer; + size_t n; + size_t buffsize; +} Mbuffer; + +#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) + +#define luaZ_buffer(buff) ((buff)->buffer) +#define luaZ_sizebuffer(buff) ((buff)->buffsize) +#define luaZ_bufflen(buff) ((buff)->n) + +#define luaZ_buffremove(buff,i) ((buff)->n -= (i)) +#define luaZ_resetbuffer(buff) ((buff)->n = 0) + + +#define luaZ_resizebuffer(L, buff, size) \ + ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ + (buff)->buffsize, size), \ + (buff)->buffsize = size) + +#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) + + +LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, + void *data); +LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ + + + +/* --------- Private Part ------------------ */ + +struct Zio { + size_t n; /* bytes still unread */ + const char *p; /* current position in buffer */ + lua_Reader reader; /* reader function */ + void *data; /* additional data */ + lua_State *L; /* Lua state (for reader) */ +}; + + +LUAI_FUNC int luaZ_fill (ZIO *z); + +#endif diff --git a/src/libs/3rdparty/sol2/CMakeLists.txt b/src/libs/3rdparty/sol2/CMakeLists.txt new file mode 100644 index 00000000000..1afdb1bdbb8 --- /dev/null +++ b/src/libs/3rdparty/sol2/CMakeLists.txt @@ -0,0 +1,12 @@ +add_library(sol2 INTERFACE) + +target_include_directories(sol2 INTERFACE + $ + $ +) + +install(TARGETS sol2 EXPORT QtCreator) + +qtc_add_public_header(include/sol/sol.hpp) +qtc_add_public_header(include/sol/config.hpp) +qtc_add_public_header(include/sol/forward.hpp) diff --git a/src/libs/3rdparty/sol2/LICENSE.txt b/src/libs/3rdparty/sol2/LICENSE.txt new file mode 100644 index 00000000000..58134405482 --- /dev/null +++ b/src/libs/3rdparty/sol2/LICENSE.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/libs/3rdparty/sol2/include/sol/config.hpp b/src/libs/3rdparty/sol2/include/sol/config.hpp new file mode 100644 index 00000000000..36ef3fe47e6 --- /dev/null +++ b/src/libs/3rdparty/sol2/include/sol/config.hpp @@ -0,0 +1,57 @@ +// The MIT License (MIT) + +// Copyright (c) 2013-2020 Rapptz, ThePhD and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This file was generated with a script. +// Generated 2024-01-13 14:25:56.570832 UTC +// This header was generated with sol v3.3.1 (revision 9c882a28) +// https://github.com/ThePhD/sol2 + +#ifndef SOL_SINGLE_SOL_CONFIG_HPP +#define SOL_SINGLE_SOL_CONFIG_HPP + +// beginning of sol/config.hpp + +/* Base, empty configuration file! + + To override, place a file in your include paths of the form: + +. (your include path here) +| sol (directory, or equivalent) + | config.hpp (your config.hpp file) + + So that when sol2 includes the file + +#include + + it gives you the configuration values you desire. Configuration values can be +seen in the safety.rst of the doc/src, or at +https://sol2.readthedocs.io/en/latest/safety.html ! You can also pass them through +the build system, or the command line options of your compiler. + +*/ + +#define SOL_SAFE_FUNCTIONS 1 +#define SOL_SAFE_USERTYPE 1 +#define SOL_NO_NIL 1 + +// end of sol/config.hpp + +#endif // SOL_SINGLE_SOL_CONFIG_HPP diff --git a/src/libs/3rdparty/sol2/include/sol/forward.hpp b/src/libs/3rdparty/sol2/include/sol/forward.hpp new file mode 100644 index 00000000000..83fba4d2548 --- /dev/null +++ b/src/libs/3rdparty/sol2/include/sol/forward.hpp @@ -0,0 +1,1340 @@ +// The MIT License (MIT) + +// Copyright (c) 2013-2020 Rapptz, ThePhD and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This file was generated with a script. +// Generated 2024-01-13 14:25:56.569197 UTC +// This header was generated with sol v3.3.1 (revision 9c882a28) +// https://github.com/ThePhD/sol2 + +#ifndef SOL_SINGLE_INCLUDE_SOL_FORWARD_HPP +#define SOL_SINGLE_INCLUDE_SOL_FORWARD_HPP + +// beginning of sol/forward.hpp + +#ifndef SOL_FORWARD_HPP +#define SOL_FORWARD_HPP + +// beginning of sol/version.hpp + +#include "config.hpp" + +#define SOL_VERSION_MAJOR 3 +#define SOL_VERSION_MINOR 2 +#define SOL_VERSION_PATCH 3 +#define SOL_VERSION_STRING "3.2.3" +#define SOL_VERSION ((SOL_VERSION_MAJOR * 100000) + (SOL_VERSION_MINOR * 100) + (SOL_VERSION_PATCH)) + +#define SOL_TOKEN_TO_STRING_POST_EXPANSION_I_(_TOKEN) #_TOKEN +#define SOL_TOKEN_TO_STRING_I_(_TOKEN) SOL_TOKEN_TO_STRING_POST_EXPANSION_I_(_TOKEN) + +#define SOL_CONCAT_TOKENS_POST_EXPANSION_I_(_LEFT, _RIGHT) _LEFT##_RIGHT +#define SOL_CONCAT_TOKENS_I_(_LEFT, _RIGHT) SOL_CONCAT_TOKENS_POST_EXPANSION_I_(_LEFT, _RIGHT) + +#define SOL_RAW_IS_ON(OP_SYMBOL) ((3 OP_SYMBOL 3) != 0) +#define SOL_RAW_IS_OFF(OP_SYMBOL) ((3 OP_SYMBOL 3) == 0) +#define SOL_RAW_IS_DEFAULT_ON(OP_SYMBOL) ((3 OP_SYMBOL 3) > 3) +#define SOL_RAW_IS_DEFAULT_OFF(OP_SYMBOL) ((3 OP_SYMBOL 3 OP_SYMBOL 3) < 0) + +#define SOL_IS_ON(OP_SYMBOL) SOL_RAW_IS_ON(OP_SYMBOL ## _I_) +#define SOL_IS_OFF(OP_SYMBOL) SOL_RAW_IS_OFF(OP_SYMBOL ## _I_) +#define SOL_IS_DEFAULT_ON(OP_SYMBOL) SOL_RAW_IS_DEFAULT_ON(OP_SYMBOL ## _I_) +#define SOL_IS_DEFAULT_OFF(OP_SYMBOL) SOL_RAW_IS_DEFAULT_OFF(OP_SYMBOL ## _I_) + +#define SOL_ON | +#define SOL_OFF ^ +#define SOL_DEFAULT_ON + +#define SOL_DEFAULT_OFF - + +#if defined(SOL_BUILD_CXX_MODE) + #if (SOL_BUILD_CXX_MODE != 0) + #define SOL_BUILD_CXX_MODE_I_ SOL_ON + #else + #define SOL_BUILD_CXX_MODE_I_ SOL_OFF + #endif +#elif defined(__cplusplus) + #define SOL_BUILD_CXX_MODE_I_ SOL_DEFAULT_ON +#else + #define SOL_BUILD_CXX_MODE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_BUILD_C_MODE) + #if (SOL_BUILD_C_MODE != 0) + #define SOL_BUILD_C_MODE_I_ SOL_ON + #else + #define SOL_BUILD_C_MODE_I_ SOL_OFF + #endif +#elif defined(__STDC__) + #define SOL_BUILD_C_MODE_I_ SOL_DEFAULT_ON +#else + #define SOL_BUILD_C_MODE_I_ SOL_DEFAULT_OFF +#endif + +#if SOL_IS_ON(SOL_BUILD_C_MODE) + #include + #include + #include +#else + #include + #include + #include +#endif + +#if defined(SOL_HAS_BUILTIN) + #define SOL_HAS_BUILTIN_I_(...) SOL_HAS_BUILTIN(__VA_ARGS__) +#elif defined(__has_builtin) + #define SOL_HAS_BUILTIN_I_(...) __has_builtin(__VA_ARGS__) +#else + #define SOL_HAS_BUILTIN_I_(...) 0 +#endif + +#if defined(SOL_COMPILER_VCXX) + #if defined(SOL_COMPILER_VCXX != 0) + #define SOL_COMPILER_VCXX_I_ SOL_ON + #else + #define SOL_COMPILER_VCXX_I_ SOL_OFF + #endif +#elif defined(_MSC_VER) + #define SOL_COMPILER_VCXX_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_VCXX_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_GCC) + #if defined(SOL_COMPILER_GCC != 0) + #define SOL_COMPILER_GCC_I_ SOL_ON + #else + #define SOL_COMPILER_GCC_I_ SOL_OFF + #endif +#elif defined(__GNUC__) + #define SOL_COMPILER_GCC_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_GCC_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_CLANG) + #if defined(SOL_COMPILER_CLANG != 0) + #define SOL_COMPILER_CLANG_I_ SOL_ON + #else + #define SOL_COMPILER_CLANG_I_ SOL_OFF + #endif +#elif defined(__clang__) + #define SOL_COMPILER_CLANG_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_CLANG_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_EDG) + #if defined(SOL_COMPILER_EDG != 0) + #define SOL_COMPILER_EDG_I_ SOL_ON + #else + #define SOL_COMPILER_EDG_I_ SOL_OFF + #endif +#else + #define SOL_COMPILER_EDG_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_MINGW) + #if (SOL_COMPILER_MINGW != 0) + #define SOL_COMPILER_MINGW_I_ SOL_ON + #else + #define SOL_COMPILER_MINGW_I_ SOL_OFF + #endif +#elif defined(__MINGW32__) + #define SOL_COMPILER_MINGW_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_MINGW_I_ SOL_DEFAULT_OFF +#endif + +#if SIZE_MAX <= 0xFFFFULL + #define SOL_PLATFORM_X16_I_ SOL_ON + #define SOL_PLATFORM_X86_I_ SOL_OFF + #define SOL_PLATFORM_X64_I_ SOL_OFF +#elif SIZE_MAX <= 0xFFFFFFFFULL + #define SOL_PLATFORM_X16_I_ SOL_OFF + #define SOL_PLATFORM_X86_I_ SOL_ON + #define SOL_PLATFORM_X64_I_ SOL_OFF +#else + #define SOL_PLATFORM_X16_I_ SOL_OFF + #define SOL_PLATFORM_X86_I_ SOL_OFF + #define SOL_PLATFORM_X64_I_ SOL_ON +#endif + +#define SOL_PLATFORM_ARM32_I_ SOL_OFF +#define SOL_PLATFORM_ARM64_I_ SOL_OFF + +#if defined(SOL_PLATFORM_WINDOWS) + #if (SOL_PLATFORM_WINDOWS != 0) + #define SOL_PLATFORM_WINDOWS_I_ SOL_ON + #else + #define SOL_PLATFORM_WINDOWS_I_ SOL_OFF + #endif +#elif defined(_WIN32) + #define SOL_PLATFORM_WINDOWS_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_WINDOWS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_CYGWIN) + #if (SOL_PLATFORM_CYGWIN != 0) + #define SOL_PLATFORM_CYGWIN_I_ SOL_ON + #else + #define SOL_PLATFORM_CYGWIN_I_ SOL_ON + #endif +#elif defined(__CYGWIN__) + #define SOL_PLATFORM_CYGWIN_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_CYGWIN_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_APPLE) + #if (SOL_PLATFORM_APPLE != 0) + #define SOL_PLATFORM_APPLE_I_ SOL_ON + #else + #define SOL_PLATFORM_APPLE_I_ SOL_OFF + #endif +#elif defined(__APPLE__) + #define SOL_PLATFORM_APPLE_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_APPLE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_UNIX) + #if (SOL_PLATFORM_UNIX != 0) + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_ON + #else + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_OFF + #endif +#elif defined(__unix__) + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_DEFAUKT_ON +#else + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_LINUX) + #if (SOL_PLATFORM_LINUX != 0) + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_ON + #else + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_OFF + #endif +#elif defined(__LINUX__) + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_DEFAUKT_ON +#else + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_DEFAULT_OFF +#endif + +#define SOL_PLATFORM_APPLE_IPHONE_I_ SOL_OFF +#define SOL_PLATFORM_BSDLIKE_I_ SOL_OFF + +#if defined(SOL_IN_DEBUG_DETECTED) + #if SOL_IN_DEBUG_DETECTED != 0 + #define SOL_DEBUG_BUILD_I_ SOL_ON + #else + #define SOL_DEBUG_BUILD_I_ SOL_OFF + #endif +#elif !defined(NDEBUG) + #if SOL_IS_ON(SOL_COMPILER_VCXX) && defined(_DEBUG) + #define SOL_DEBUG_BUILD_I_ SOL_ON + #elif (SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC)) && !defined(__OPTIMIZE__) + #define SOL_DEBUG_BUILD_I_ SOL_ON + #else + #define SOL_DEBUG_BUILD_I_ SOL_OFF + #endif +#else + #define SOL_DEBUG_BUILD_I_ SOL_DEFAULT_OFF +#endif // We are in a debug mode of some sort + +#if defined(SOL_NO_EXCEPTIONS) + #if (SOL_NO_EXCEPTIONS != 0) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) + #if !defined(_CPPUNWIND) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC) + #if !defined(__EXCEPTIONS) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#else + #define SOL_EXCEPTIONS_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_NO_RTTI) + #if (SOL_NO_RTTI != 0) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) + #if !defined(_CPPRTTI) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC) + #if !defined(__GXX_RTTI) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#else + #define SOL_RTTI_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_NO_THREAD_LOCAL) + #if SOL_NO_THREAD_LOCAL != 0 + #define SOL_USE_THREAD_LOCAL_I_ SOL_OFF + #else + #define SOL_USE_THREAD_LOCAL_I_ SOL_ON + #endif +#else + #define SOL_USE_THREAD_LOCAL_I_ SOL_DEFAULT_ON +#endif // thread_local keyword is bjorked on some platforms + +#if defined(SOL_ALL_SAFETIES_ON) + #if SOL_ALL_SAFETIES_ON != 0 + #define SOL_ALL_SAFETIES_ON_I_ SOL_ON + #else + #define SOL_ALL_SAFETIES_ON_I_ SOL_OFF + #endif +#else + #define SOL_ALL_SAFETIES_ON_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_SAFE_GETTER) + #if SOL_SAFE_GETTER != 0 + #define SOL_SAFE_GETTER_I_ SOL_ON + #else + #define SOL_SAFE_GETTER_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_GETTER_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_GETTER_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_GETTER_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_USERTYPE) + #if SOL_SAFE_USERTYPE != 0 + #define SOL_SAFE_USERTYPE_I_ SOL_ON + #else + #define SOL_SAFE_USERTYPE_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_USERTYPE_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_USERTYPE_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_USERTYPE_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_REFERENCES) + #if SOL_SAFE_REFERENCES != 0 + #define SOL_SAFE_REFERENCES_I_ SOL_ON + #else + #define SOL_SAFE_REFERENCES_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_REFERENCES_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_REFERENCES_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_REFERENCES_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_FUNCTIONS) + #if SOL_SAFE_FUNCTIONS != 0 + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_OFF + #endif +#elif defined (SOL_SAFE_FUNCTION_OBJECTS) + #if SOL_SAFE_FUNCTION_OBJECTS != 0 + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_FUNCTION_CALLS) + #if SOL_SAFE_FUNCTION_CALLS != 0 + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_PROXIES) + #if SOL_SAFE_PROXIES != 0 + #define SOL_SAFE_PROXIES_I_ SOL_ON + #else + #define SOL_SAFE_PROXIES_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_PROXIES_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_PROXIES_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_PROXIES_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_NUMERICS) + #if SOL_SAFE_NUMERICS != 0 + #define SOL_SAFE_NUMERICS_I_ SOL_ON + #else + #define SOL_SAFE_NUMERICS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_NUMERICS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_NUMERICS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_NUMERICS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_ALL_INTEGER_VALUES_FIT) + #if (SOL_ALL_INTEGER_VALUES_FIT != 0) + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_ON + #else + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_OFF + #endif +#elif !SOL_IS_DEFAULT_OFF(SOL_SAFE_NUMERICS) && SOL_IS_OFF(SOL_SAFE_NUMERICS) + // if numerics is intentionally turned off, flip this on + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_DEFAULT_ON +#else + // default to off + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_SAFE_STACK_CHECK) + #if SOL_SAFE_STACK_CHECK != 0 + #define SOL_SAFE_STACK_CHECK_I_ SOL_ON + #else + #define SOL_SAFE_STACK_CHECK_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_STACK_CHECK_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_STACK_CHECK_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_STACK_CHECK_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_NO_CHECK_NUMBER_PRECISION) + #if SOL_NO_CHECK_NUMBER_PRECISION != 0 + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_OFF + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #endif +#elif defined(SOL_NO_CHECKING_NUMBER_PRECISION) + #if SOL_NO_CHECKING_NUMBER_PRECISION != 0 + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_OFF + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #elif SOL_IS_ON(SOL_SAFE_NUMERICS) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_DEFAULT_ON + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_STRINGS_ARE_NUMBERS) + #if (SOL_STRINGS_ARE_NUMBERS != 0) + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_ON + #else + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_OFF + #endif +#else + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ENABLE_INTEROP) + #if SOL_ENABLE_INTEROP != 0 + #define SOL_USE_INTEROP_I_ SOL_ON + #else + #define SOL_USE_INTEROP_I_ SOL_OFF + #endif +#elif defined(SOL_USE_INTEROP) + #if SOL_USE_INTEROP != 0 + #define SOL_USE_INTEROP_I_ SOL_ON + #else + #define SOL_USE_INTEROP_I_ SOL_OFF + #endif +#else + #define SOL_USE_INTEROP_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_NO_NIL) + #if (SOL_NO_NIL != 0) + #define SOL_NIL_I_ SOL_OFF + #else + #define SOL_NIL_I_ SOL_ON + #endif +#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) || defined(__OBJC__) || defined(nil) + #define SOL_NIL_I_ SOL_DEFAULT_OFF +#else + #define SOL_NIL_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_USERTYPE_TYPE_BINDING_INFO) + #if (SOL_USERTYPE_TYPE_BINDING_INFO != 0) + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_ON + #else + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_OFF + #endif +#else + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_DEFAULT_ON +#endif // We should generate a my_type.__type table with lots of class information for usertypes + +#if defined(SOL_AUTOMAGICAL_TYPES_BY_DEFAULT) + #if (SOL_AUTOMAGICAL_TYPES_BY_DEFAULT != 0) + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_ON + #else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_OFF + #endif +#elif defined(SOL_DEFAULT_AUTOMAGICAL_USERTYPES) + #if (SOL_DEFAULT_AUTOMAGICAL_USERTYPES != 0) + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_ON + #else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_OFF + #endif +#else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_DEFAULT_ON +#endif // make is_automagical on/off by default + +#if defined(SOL_STD_VARIANT) + #if (SOL_STD_VARIANT != 0) + #define SOL_STD_VARIANT_I_ SOL_ON + #else + #define SOL_STD_VARIANT_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_COMPILER_CLANG) && SOL_IS_ON(SOL_PLATFORM_APPLE) + #if defined(__has_include) + #if __has_include() + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_ON + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_OFF + #endif + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_OFF + #endif + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_ON + #endif +#endif // make is_automagical on/off by default + +#if defined(SOL_NOEXCEPT_FUNCTION_TYPE) + #if (SOL_NOEXCEPT_FUNCTION_TYPE != 0) + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_ON + #else + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_OFF + #endif +#else + #if defined(__cpp_noexcept_function_type) + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_ON + #elif SOL_IS_ON(SOL_COMPILER_VCXX) && (defined(_MSVC_LANG) && (_MSVC_LANG < 201403L)) + // There is a bug in the VC++ compiler?? + // on /std:c++latest under x86 conditions (VS 15.5.2), + // compiler errors are tossed for noexcept markings being on function types + // that are identical in every other way to their non-noexcept marked types function types... + // VS 2019: There is absolutely a bug. + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_OFF + #else + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_DEFAULT_ON + #endif +#endif // noexcept is part of a function's type + +#if defined(SOL_STACK_STRING_OPTIMIZATION_SIZE) && SOL_STACK_STRING_OPTIMIZATION_SIZE > 0 + #define SOL_OPTIMIZATION_STRING_CONVERSION_STACK_SIZE_I_ SOL_STACK_STRING_OPTIMIZATION_SIZE +#else + #define SOL_OPTIMIZATION_STRING_CONVERSION_STACK_SIZE_I_ 1024 +#endif + +#if defined(SOL_ID_SIZE) && SOL_ID_SIZE > 0 + #define SOL_ID_SIZE_I_ SOL_ID_SIZE +#else + #define SOL_ID_SIZE_I_ 512 +#endif + +#if defined(LUA_IDSIZE) && LUA_IDSIZE > 0 + #define SOL_FILE_ID_SIZE_I_ LUA_IDSIZE +#elif defined(SOL_ID_SIZE) && SOL_ID_SIZE > 0 + #define SOL_FILE_ID_SIZE_I_ SOL_FILE_ID_SIZE +#else + #define SOL_FILE_ID_SIZE_I_ 2048 +#endif + +#if defined(SOL_PRINT_ERRORS) + #if (SOL_PRINT_ERRORS != 0) + #define SOL_PRINT_ERRORS_I_ SOL_ON + #else + #define SOL_PRINT_ERRORS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_PRINT_ERRORS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_PRINT_ERRORS_I_ SOL_DEFAULT_ON + #else + #define SOL_PRINT_ERRORS_I_ SOL_OFF + #endif +#endif + +#if defined(SOL_DEFAULT_PASS_ON_ERROR) + #if (SOL_DEFAULT_PASS_ON_ERROR != 0) + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_ON + #else + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_OFF + #endif +#else + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USING_CXX_LUA) + #if (SOL_USING_CXX_LUA != 0) + #define SOL_USING_CXX_LUA_I_ SOL_ON + #else + #define SOL_USING_CXX_LUA_I_ SOL_OFF + #endif +#elif defined(SOL_USE_CXX_LUA) + // alternative spelling + #if (SOL_USE_CXX_LUA != 0) + #define SOL_USING_CXX_LUA_I_ SOL_ON + #else + #define SOL_USING_CXX_LUA_I_ SOL_OFF + #endif +#else + #define SOL_USING_CXX_LUA_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USING_CXX_LUAJIT) + #if (SOL_USING_CXX_LUAJIT != 0) + #define SOL_USING_CXX_LUAJIT_I_ SOL_ON + #else + #define SOL_USING_CXX_LUAJIT_I_ SOL_OFF + #endif +#elif defined(SOL_USE_CXX_LUAJIT) + #if (SOL_USE_CXX_LUAJIT != 0) + #define SOL_USING_CXX_LUAJIT_I_ SOL_ON + #else + #define SOL_USING_CXX_LUAJIT_I_ SOL_OFF + #endif +#else + #define SOL_USING_CXX_LUAJIT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_NO_LUA_HPP) + #if (SOL_NO_LUA_HPP != 0) + #define SOL_USE_LUA_HPP_I_ SOL_OFF + #else + #define SOL_USE_LUA_HPP_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_USING_CXX_LUA) + #define SOL_USE_LUA_HPP_I_ SOL_OFF +#elif defined(__has_include) + #if __has_include() + #define SOL_USE_LUA_HPP_I_ SOL_ON + #else + #define SOL_USE_LUA_HPP_I_ SOL_OFF + #endif +#else + #define SOL_USE_LUA_HPP_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_CONTAINERS_START) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINERS_START +#elif defined(SOL_CONTAINERS_START_INDEX) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINERS_START_INDEX +#elif defined(SOL_CONTAINER_START_INDEX) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINER_START_INDEX +#else + #define SOL_CONTAINER_START_INDEX_I_ 1 +#endif + +#if defined (SOL_NO_MEMORY_ALIGNMENT) + #if (SOL_NO_MEMORY_ALIGNMENT != 0) + #define SOL_ALIGN_MEMORY_I_ SOL_OFF + #else + #define SOL_ALIGN_MEMORY_I_ SOL_ON + #endif +#else + #define SOL_ALIGN_MEMORY_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_USE_BOOST) + #if (SOL_USE_BOOST != 0) + #define SOL_USE_BOOST_I_ SOL_ON + #else + #define SOL_USE_BOOST_I_ SOL_OFF + #endif +#else + #define SOL_USE_BOOST_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USE_UNSAFE_BASE_LOOKUP) + #if (SOL_USE_UNSAFE_BASE_LOOKUP != 0) + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_ON + #else + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_OFF + #endif +#else + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_INSIDE_UNREAL) + #if (SOL_INSIDE_UNREAL != 0) + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_ON + #else + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_OFF + #endif +#else + #if defined(UE_BUILD_DEBUG) || defined(UE_BUILD_DEVELOPMENT) || defined(UE_BUILD_TEST) || defined(UE_BUILD_SHIPPING) || defined(UE_SERVER) + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_DEFAULT_ON + #else + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_NO_COMPAT) + #if (SOL_NO_COMPAT != 0) + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_OFF + #else + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_ON + #endif +#else + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_GET_FUNCTION_POINTER_UNSAFE) + #if (SOL_GET_FUNCTION_POINTER_UNSAFE != 0) + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_ON + #else + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_OFF + #endif +#else + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_CONTAINER_CHECK_IS_EXHAUSTIVE) + #if (SOL_CONTAINER_CHECK_IS_EXHAUSTIVE != 0) + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_ON + #else + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_OFF + #endif +#else + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_FUNCTION_CALL_VALUE_SEMANTICS) + #if (SOL_FUNCTION_CALL_VALUE_SEMANTICS != 0) + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_ON + #else + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_OFF + #endif +#else + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_MINGW_CCTYPE_IS_POISONED) + #if (SOL_MINGW_CCTYPE_IS_POISONED != 0) + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_ON + #else + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_COMPILER_MINGW) && defined(__GNUC__) && (__GNUC__ < 6) + // MinGW is off its rocker in some places... + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_DEFAULT_ON +#else + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_CHAR8_T) + #if (SOL_CHAR8_T != 0) + #define SOL_CHAR8_T_I_ SOL_ON + #else + #define SOL_CHAR8_T_I_ SOL_OFF + #endif +#else + #if defined(__cpp_char8_t) + #define SOL_CHAR8_T_I_ SOL_DEFAULT_ON + #else + #define SOL_CHAR8_T_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if SOL_IS_ON(SOL_USE_BOOST) + #include + + #if BOOST_VERSION >= 107500 // Since Boost 1.75.0 boost::none is constexpr + #define SOL_BOOST_NONE_CONSTEXPR_I_ constexpr + #else + #define SOL_BOOST_NONE_CONSTEXPR_I_ const + #endif // BOOST_VERSION +#else + // assume boost isn't using a garbage version + #define SOL_BOOST_NONE_CONSTEXPR_I_ constexpr +#endif + +#if defined(SOL2_CI) + #if (SOL2_CI != 0) + #define SOL2_CI_I_ SOL_ON + #else + #define SOL2_CI_I_ SOL_OFF + #endif +#else + #define SOL2_CI_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ASSERT) + #define SOL_USER_ASSERT_I_ SOL_ON +#else + #define SOL_USER_ASSERT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ASSERT_MSG) + #define SOL_USER_ASSERT_MSG_I_ SOL_ON +#else + #define SOL_USER_ASSERT_MSG_I_ SOL_DEFAULT_OFF +#endif + +// beginning of sol/prologue.hpp + +#if defined(SOL_PROLOGUE_I_) + #error "[sol2] Library Prologue was already included in translation unit and not properly ended with an epilogue." +#endif + +#define SOL_PROLOGUE_I_ 1 + +#if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #define _FWD(...) static_cast( __VA_ARGS__ ) + + #if SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define _MOVE(...) static_cast<__typeof( __VA_ARGS__ )&&>( __VA_ARGS__ ) + #else + #include + + #define _MOVE(...) static_cast<::std::remove_reference_t<( __VA_ARGS__ )>&&>( __VA_OPT__(,) ) + #endif +#endif + +// end of sol/prologue.hpp + +// beginning of sol/epilogue.hpp + +#if !defined(SOL_PROLOGUE_I_) + #error "[sol2] Library Prologue is missing from this translation unit." +#else + #undef SOL_PROLOGUE_I_ +#endif + +#if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #undef _FWD + #undef _MOVE +#endif + +// end of sol/epilogue.hpp + +// beginning of sol/detail/build_version.hpp + +#if defined(SOL_DLL) + #if (SOL_DLL != 0) + #define SOL_DLL_I_ SOL_ON + #else + #define SOL_DLL_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) && (defined(DLL_) || defined(_DLL)) + #define SOL_DLL_I_ SOL_DEFAULT_ON +#else + #define SOL_DLL_I_ SOL_DEFAULT_OFF +#endif // DLL definition + +#if defined(SOL_HEADER_ONLY) + #if (SOL_HEADER_ONLY != 0) + #define SOL_HEADER_ONLY_I_ SOL_ON + #else + #define SOL_HEADER_ONLY_I_ SOL_OFF + #endif +#else + #define SOL_HEADER_ONLY_I_ SOL_DEFAULT_OFF +#endif // Header only library + +#if defined(SOL_BUILD) + #if (SOL_BUILD != 0) + #define SOL_BUILD_I_ SOL_ON + #else + #define SOL_BUILD_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_BUILD_I_ SOL_DEFAULT_OFF +#else + #define SOL_BUILD_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_UNITY_BUILD) + #if (SOL_UNITY_BUILD != 0) + #define SOL_UNITY_BUILD_I_ SOL_ON + #else + #define SOL_UNITY_BUILD_I_ SOL_OFF + #endif +#else + #define SOL_UNITY_BUILD_I_ SOL_DEFAULT_OFF +#endif // Header only library + +#if defined(SOL_C_FUNCTION_LINKAGE) + #define SOL_C_FUNCTION_LINKAGE_I_ SOL_C_FUNCTION_LINKAGE +#else + #if SOL_IS_ON(SOL_BUILD_CXX_MODE) + // C++ + #define SOL_C_FUNCTION_LINKAGE_I_ extern "C" + #else + // normal + #define SOL_C_FUNCTION_LINKAGE_I_ + #endif // C++ or not +#endif // Linkage specification for C functions + +#if defined(SOL_API_LINKAGE) + #define SOL_API_LINKAGE_I_ SOL_API_LINKAGE +#else + #if SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) || SOL_IS_ON(SOL_PLATFORM_WINDOWS) || SOL_IS_ON(SOL_PLATFORM_CYGWIN) + // MSVC Compiler; or, Windows, or Cygwin platforms + #if SOL_IS_ON(SOL_BUILD) + // Building the library + #if SOL_IS_ON(SOL_COMPILER_GCC) + // Using GCC + #define SOL_API_LINKAGE_I_ __attribute__((dllexport)) + #else + // Using Clang, MSVC, etc... + #define SOL_API_LINKAGE_I_ __declspec(dllexport) + #endif + #else + #if SOL_IS_ON(SOL_COMPILER_GCC) + #define SOL_API_LINKAGE_I_ __attribute__((dllimport)) + #else + #define SOL_API_LINKAGE_I_ __declspec(dllimport) + #endif + #endif + #else + // extern if building normally on non-MSVC + #define SOL_API_LINKAGE_I_ extern + #endif + #elif SOL_IS_ON(SOL_UNITY_BUILD) + // Built-in library, like how stb typical works + #if SOL_IS_ON(SOL_HEADER_ONLY) + // Header only, so functions are defined "inline" + #define SOL_API_LINKAGE_I_ inline + #else + // Not header only, so seperately compiled files + #define SOL_API_LINKAGE_I_ extern + #endif + #else + // Normal static library + #if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #define SOL_API_LINKAGE_I_ + #else + #define SOL_API_LINKAGE_I_ extern + #endif + #endif // DLL or not +#endif // Build definitions + +#if defined(SOL_PUBLIC_FUNC_DECL) + #define SOL_PUBLIC_FUNC_DECL_I_ SOL_PUBLIC_FUNC_DECL +#else + #define SOL_PUBLIC_FUNC_DECL_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_INTERNAL_FUNC_DECL_) + #define SOL_INTERNAL_FUNC_DECL_I_ SOL_INTERNAL_FUNC_DECL_ +#else + #define SOL_INTERNAL_FUNC_DECL_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_PUBLIC_FUNC_DEF) + #define SOL_PUBLIC_FUNC_DEF_I_ SOL_PUBLIC_FUNC_DEF +#else + #define SOL_PUBLIC_FUNC_DEF_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_INTERNAL_FUNC_DEF) + #define SOL_INTERNAL_FUNC_DEF_I_ SOL_INTERNAL_FUNC_DEF +#else + #define SOL_INTERNAL_FUNC_DEF_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_FUNC_DECL) + #define SOL_FUNC_DECL_I_ SOL_FUNC_DECL +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_FUNC_DECL_I_ +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_FUNC_DECL_I_ extern __declspec(dllexport) + #else + #define SOL_FUNC_DECL_I_ extern __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_FUNC_DECL_I_ extern __attribute__((visibility("default"))) + #else + #define SOL_FUNC_DECL_I_ extern + #endif +#endif + +#if defined(SOL_FUNC_DEFN) + #define SOL_FUNC_DEFN_I_ SOL_FUNC_DEFN +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_FUNC_DEFN_I_ inline +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_FUNC_DEFN_I_ __declspec(dllexport) + #else + #define SOL_FUNC_DEFN_I_ __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_FUNC_DEFN_I_ __attribute__((visibility("default"))) + #else + #define SOL_FUNC_DEFN_I_ + #endif +#endif + +#if defined(SOL_HIDDEN_FUNC_DECL) + #define SOL_HIDDEN_FUNC_DECL_I_ SOL_HIDDEN_FUNC_DECL +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_HIDDEN_FUNC_DECL_I_ +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_HIDDEN_FUNC_DECL_I_ extern __declspec(dllexport) + #else + #define SOL_HIDDEN_FUNC_DECL_I_ extern __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_HIDDEN_FUNC_DECL_I_ extern __attribute__((visibility("default"))) + #else + #define SOL_HIDDEN_FUNC_DECL_I_ extern + #endif +#endif + +#if defined(SOL_HIDDEN_FUNC_DEFN) + #define SOL_HIDDEN_FUNC_DEFN_I_ SOL_HIDDEN_FUNC_DEFN +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_HIDDEN_FUNC_DEFN_I_ inline +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_HIDDEN_FUNC_DEFN_I_ + #else + #define SOL_HIDDEN_FUNC_DEFN_I_ + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_HIDDEN_FUNC_DEFN_I_ __attribute__((visibility("hidden"))) + #else + #define SOL_HIDDEN_FUNC_DEFN_I_ + #endif +#endif + +// end of sol/detail/build_version.hpp + +// end of sol/version.hpp + +#include +#include +#include + +#if SOL_IS_ON(SOL_USING_CXX_LUA) || SOL_IS_ON(SOL_USING_CXX_LUAJIT) +struct lua_State; +#else +extern "C" { +struct lua_State; +} +#endif // C++ Mangling for Lua vs. Not + +namespace sol { + + enum class type; + + class stateless_reference; + template + class basic_reference; + using reference = basic_reference; + using main_reference = basic_reference; + class stateless_stack_reference; + class stack_reference; + + template + class basic_bytecode; + + struct lua_value; + + struct proxy_base_tag; + template + struct proxy_base; + template + struct table_proxy; + + template + class basic_table_core; + template + using table_core = basic_table_core; + template + using main_table_core = basic_table_core; + template + using stack_table_core = basic_table_core; + template + using basic_table = basic_table_core; + using table = table_core; + using global_table = table_core; + using main_table = main_table_core; + using main_global_table = main_table_core; + using stack_table = stack_table_core; + using stack_global_table = stack_table_core; + + template + struct basic_lua_table; + using lua_table = basic_lua_table; + using stack_lua_table = basic_lua_table; + + template + class basic_usertype; + template + using usertype = basic_usertype; + template + using stack_usertype = basic_usertype; + + template + class basic_metatable; + using metatable = basic_metatable; + using stack_metatable = basic_metatable; + + template + struct basic_environment; + using environment = basic_environment; + using main_environment = basic_environment; + using stack_environment = basic_environment; + + template + class basic_function; + template + class basic_protected_function; + using unsafe_function = basic_function; + using safe_function = basic_protected_function; + using main_unsafe_function = basic_function; + using main_safe_function = basic_protected_function; + using stack_unsafe_function = basic_function; + using stack_safe_function = basic_protected_function; + using stack_aligned_unsafe_function = basic_function; + using stack_aligned_safe_function = basic_protected_function; + using protected_function = safe_function; + using main_protected_function = main_safe_function; + using stack_protected_function = stack_safe_function; + using stack_aligned_protected_function = stack_aligned_safe_function; +#if SOL_IS_ON(SOL_SAFE_FUNCTION_OBJECTS) + using function = protected_function; + using main_function = main_protected_function; + using stack_function = stack_protected_function; + using stack_aligned_function = stack_aligned_safe_function; +#else + using function = unsafe_function; + using main_function = main_unsafe_function; + using stack_function = stack_unsafe_function; + using stack_aligned_function = stack_aligned_unsafe_function; +#endif + using stack_aligned_stack_handler_function = basic_protected_function; + + struct unsafe_function_result; + struct protected_function_result; + using safe_function_result = protected_function_result; +#if SOL_IS_ON(SOL_SAFE_FUNCTION_OBJECTS) + using function_result = safe_function_result; +#else + using function_result = unsafe_function_result; +#endif + + template + class basic_object_base; + template + class basic_object; + template + class basic_userdata; + template + class basic_lightuserdata; + template + class basic_coroutine; + template + class basic_packaged_coroutine; + template + class basic_thread; + + using object = basic_object; + using userdata = basic_userdata; + using lightuserdata = basic_lightuserdata; + using thread = basic_thread; + using coroutine = basic_coroutine; + using packaged_coroutine = basic_packaged_coroutine; + using main_object = basic_object; + using main_userdata = basic_userdata; + using main_lightuserdata = basic_lightuserdata; + using main_coroutine = basic_coroutine; + using stack_object = basic_object; + using stack_userdata = basic_userdata; + using stack_lightuserdata = basic_lightuserdata; + using stack_thread = basic_thread; + using stack_coroutine = basic_coroutine; + + struct stack_proxy_base; + struct stack_proxy; + struct variadic_args; + struct variadic_results; + struct stack_count; + struct this_state; + struct this_main_state; + struct this_environment; + + class state_view; + class state; + + template + struct as_table_t; + template + struct as_container_t; + template + struct nested; + template + struct light; + template + struct user; + template + struct as_args_t; + template + struct protect_t; + template + struct policy_wrapper; + + template + struct usertype_traits; + template + struct unique_usertype_traits; + + template + struct types { + typedef std::make_index_sequence indices; + static constexpr std::size_t size() { + return sizeof...(Args); + } + }; + + template + struct derive : std::false_type { + typedef types<> type; + }; + + template + struct base : std::false_type { + typedef types<> type; + }; + + template + struct weak_derive { + static bool value; + }; + + template + bool weak_derive::value = false; + + namespace stack { + struct record; + } + +#if SOL_IS_OFF(SOL_USE_BOOST) + template + class optional; + + template + class optional; +#endif + + using check_handler_type = int(lua_State*, int, type, type, const char*); + +} // namespace sol + +#define SOL_BASE_CLASSES(T, ...) \ + namespace sol { \ + template <> \ + struct base : std::true_type { \ + typedef ::sol::types<__VA_ARGS__> type; \ + }; \ + } \ + static_assert(true, "") +#define SOL_DERIVED_CLASSES(T, ...) \ + namespace sol { \ + template <> \ + struct derive : std::true_type { \ + typedef ::sol::types<__VA_ARGS__> type; \ + }; \ + } \ + static_assert(true, "") + +#endif // SOL_FORWARD_HPP +// end of sol/forward.hpp + +#endif // SOL_SINGLE_INCLUDE_SOL_FORWARD_HPP diff --git a/src/libs/3rdparty/sol2/include/sol/sol.hpp b/src/libs/3rdparty/sol2/include/sol/sol.hpp new file mode 100644 index 00000000000..063ea72165e --- /dev/null +++ b/src/libs/3rdparty/sol2/include/sol/sol.hpp @@ -0,0 +1,29202 @@ +// The MIT License (MIT) + +// Copyright (c) 2013-2020 Rapptz, ThePhD and contributors + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This file was generated with a script. +// Generated 2024-01-13 14:25:56.532275 UTC +// This header was generated with sol v3.3.1 (revision 9c882a28) +// https://github.com/ThePhD/sol2 + +#ifndef SOL_SINGLE_INCLUDE_SOL_HPP +#define SOL_SINGLE_INCLUDE_SOL_HPP + +// beginning of sol/sol.hpp + +#ifndef SOL_HPP +#define SOL_HPP + +// beginning of sol/version.hpp + +#include "config.hpp" + +#define SOL_VERSION_MAJOR 3 +#define SOL_VERSION_MINOR 2 +#define SOL_VERSION_PATCH 3 +#define SOL_VERSION_STRING "3.2.3" +#define SOL_VERSION ((SOL_VERSION_MAJOR * 100000) + (SOL_VERSION_MINOR * 100) + (SOL_VERSION_PATCH)) + +#define SOL_TOKEN_TO_STRING_POST_EXPANSION_I_(_TOKEN) #_TOKEN +#define SOL_TOKEN_TO_STRING_I_(_TOKEN) SOL_TOKEN_TO_STRING_POST_EXPANSION_I_(_TOKEN) + +#define SOL_CONCAT_TOKENS_POST_EXPANSION_I_(_LEFT, _RIGHT) _LEFT##_RIGHT +#define SOL_CONCAT_TOKENS_I_(_LEFT, _RIGHT) SOL_CONCAT_TOKENS_POST_EXPANSION_I_(_LEFT, _RIGHT) + +#define SOL_RAW_IS_ON(OP_SYMBOL) ((3 OP_SYMBOL 3) != 0) +#define SOL_RAW_IS_OFF(OP_SYMBOL) ((3 OP_SYMBOL 3) == 0) +#define SOL_RAW_IS_DEFAULT_ON(OP_SYMBOL) ((3 OP_SYMBOL 3) > 3) +#define SOL_RAW_IS_DEFAULT_OFF(OP_SYMBOL) ((3 OP_SYMBOL 3 OP_SYMBOL 3) < 0) + +#define SOL_IS_ON(OP_SYMBOL) SOL_RAW_IS_ON(OP_SYMBOL ## _I_) +#define SOL_IS_OFF(OP_SYMBOL) SOL_RAW_IS_OFF(OP_SYMBOL ## _I_) +#define SOL_IS_DEFAULT_ON(OP_SYMBOL) SOL_RAW_IS_DEFAULT_ON(OP_SYMBOL ## _I_) +#define SOL_IS_DEFAULT_OFF(OP_SYMBOL) SOL_RAW_IS_DEFAULT_OFF(OP_SYMBOL ## _I_) + +#define SOL_ON | +#define SOL_OFF ^ +#define SOL_DEFAULT_ON + +#define SOL_DEFAULT_OFF - + +#if defined(SOL_BUILD_CXX_MODE) + #if (SOL_BUILD_CXX_MODE != 0) + #define SOL_BUILD_CXX_MODE_I_ SOL_ON + #else + #define SOL_BUILD_CXX_MODE_I_ SOL_OFF + #endif +#elif defined(__cplusplus) + #define SOL_BUILD_CXX_MODE_I_ SOL_DEFAULT_ON +#else + #define SOL_BUILD_CXX_MODE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_BUILD_C_MODE) + #if (SOL_BUILD_C_MODE != 0) + #define SOL_BUILD_C_MODE_I_ SOL_ON + #else + #define SOL_BUILD_C_MODE_I_ SOL_OFF + #endif +#elif defined(__STDC__) + #define SOL_BUILD_C_MODE_I_ SOL_DEFAULT_ON +#else + #define SOL_BUILD_C_MODE_I_ SOL_DEFAULT_OFF +#endif + +#if SOL_IS_ON(SOL_BUILD_C_MODE) + #include + #include + #include +#else + #include + #include + #include +#endif + +#if defined(SOL_HAS_BUILTIN) + #define SOL_HAS_BUILTIN_I_(...) SOL_HAS_BUILTIN(__VA_ARGS__) +#elif defined(__has_builtin) + #define SOL_HAS_BUILTIN_I_(...) __has_builtin(__VA_ARGS__) +#else + #define SOL_HAS_BUILTIN_I_(...) 0 +#endif + +#if defined(SOL_COMPILER_VCXX) + #if defined(SOL_COMPILER_VCXX != 0) + #define SOL_COMPILER_VCXX_I_ SOL_ON + #else + #define SOL_COMPILER_VCXX_I_ SOL_OFF + #endif +#elif defined(_MSC_VER) + #define SOL_COMPILER_VCXX_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_VCXX_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_GCC) + #if defined(SOL_COMPILER_GCC != 0) + #define SOL_COMPILER_GCC_I_ SOL_ON + #else + #define SOL_COMPILER_GCC_I_ SOL_OFF + #endif +#elif defined(__GNUC__) + #define SOL_COMPILER_GCC_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_GCC_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_CLANG) + #if defined(SOL_COMPILER_CLANG != 0) + #define SOL_COMPILER_CLANG_I_ SOL_ON + #else + #define SOL_COMPILER_CLANG_I_ SOL_OFF + #endif +#elif defined(__clang__) + #define SOL_COMPILER_CLANG_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_CLANG_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_EDG) + #if defined(SOL_COMPILER_EDG != 0) + #define SOL_COMPILER_EDG_I_ SOL_ON + #else + #define SOL_COMPILER_EDG_I_ SOL_OFF + #endif +#else + #define SOL_COMPILER_EDG_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_COMPILER_MINGW) + #if (SOL_COMPILER_MINGW != 0) + #define SOL_COMPILER_MINGW_I_ SOL_ON + #else + #define SOL_COMPILER_MINGW_I_ SOL_OFF + #endif +#elif defined(__MINGW32__) + #define SOL_COMPILER_MINGW_I_ SOL_DEFAULT_ON +#else + #define SOL_COMPILER_MINGW_I_ SOL_DEFAULT_OFF +#endif + +#if SIZE_MAX <= 0xFFFFULL + #define SOL_PLATFORM_X16_I_ SOL_ON + #define SOL_PLATFORM_X86_I_ SOL_OFF + #define SOL_PLATFORM_X64_I_ SOL_OFF +#elif SIZE_MAX <= 0xFFFFFFFFULL + #define SOL_PLATFORM_X16_I_ SOL_OFF + #define SOL_PLATFORM_X86_I_ SOL_ON + #define SOL_PLATFORM_X64_I_ SOL_OFF +#else + #define SOL_PLATFORM_X16_I_ SOL_OFF + #define SOL_PLATFORM_X86_I_ SOL_OFF + #define SOL_PLATFORM_X64_I_ SOL_ON +#endif + +#define SOL_PLATFORM_ARM32_I_ SOL_OFF +#define SOL_PLATFORM_ARM64_I_ SOL_OFF + +#if defined(SOL_PLATFORM_WINDOWS) + #if (SOL_PLATFORM_WINDOWS != 0) + #define SOL_PLATFORM_WINDOWS_I_ SOL_ON + #else + #define SOL_PLATFORM_WINDOWS_I_ SOL_OFF + #endif +#elif defined(_WIN32) + #define SOL_PLATFORM_WINDOWS_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_WINDOWS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_CYGWIN) + #if (SOL_PLATFORM_CYGWIN != 0) + #define SOL_PLATFORM_CYGWIN_I_ SOL_ON + #else + #define SOL_PLATFORM_CYGWIN_I_ SOL_ON + #endif +#elif defined(__CYGWIN__) + #define SOL_PLATFORM_CYGWIN_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_CYGWIN_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_APPLE) + #if (SOL_PLATFORM_APPLE != 0) + #define SOL_PLATFORM_APPLE_I_ SOL_ON + #else + #define SOL_PLATFORM_APPLE_I_ SOL_OFF + #endif +#elif defined(__APPLE__) + #define SOL_PLATFORM_APPLE_I_ SOL_DEFAULT_ON +#else + #define SOL_PLATFORM_APPLE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_UNIX) + #if (SOL_PLATFORM_UNIX != 0) + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_ON + #else + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_OFF + #endif +#elif defined(__unix__) + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_DEFAUKT_ON +#else + #define SOL_PLATFORM_UNIXLIKE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_PLATFORM_LINUX) + #if (SOL_PLATFORM_LINUX != 0) + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_ON + #else + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_OFF + #endif +#elif defined(__LINUX__) + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_DEFAUKT_ON +#else + #define SOL_PLATFORM_LINUXLIKE_I_ SOL_DEFAULT_OFF +#endif + +#define SOL_PLATFORM_APPLE_IPHONE_I_ SOL_OFF +#define SOL_PLATFORM_BSDLIKE_I_ SOL_OFF + +#if defined(SOL_IN_DEBUG_DETECTED) + #if SOL_IN_DEBUG_DETECTED != 0 + #define SOL_DEBUG_BUILD_I_ SOL_ON + #else + #define SOL_DEBUG_BUILD_I_ SOL_OFF + #endif +#elif !defined(NDEBUG) + #if SOL_IS_ON(SOL_COMPILER_VCXX) && defined(_DEBUG) + #define SOL_DEBUG_BUILD_I_ SOL_ON + #elif (SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC)) && !defined(__OPTIMIZE__) + #define SOL_DEBUG_BUILD_I_ SOL_ON + #else + #define SOL_DEBUG_BUILD_I_ SOL_OFF + #endif +#else + #define SOL_DEBUG_BUILD_I_ SOL_DEFAULT_OFF +#endif // We are in a debug mode of some sort + +#if defined(SOL_NO_EXCEPTIONS) + #if (SOL_NO_EXCEPTIONS != 0) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) + #if !defined(_CPPUNWIND) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC) + #if !defined(__EXCEPTIONS) + #define SOL_EXCEPTIONS_I_ SOL_OFF + #else + #define SOL_EXCEPTIONS_I_ SOL_ON + #endif +#else + #define SOL_EXCEPTIONS_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_NO_RTTI) + #if (SOL_NO_RTTI != 0) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) + #if !defined(_CPPRTTI) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_COMPILER_CLANG) || SOL_IS_ON(SOL_COMPILER_GCC) + #if !defined(__GXX_RTTI) + #define SOL_RTTI_I_ SOL_OFF + #else + #define SOL_RTTI_I_ SOL_ON + #endif +#else + #define SOL_RTTI_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_NO_THREAD_LOCAL) + #if SOL_NO_THREAD_LOCAL != 0 + #define SOL_USE_THREAD_LOCAL_I_ SOL_OFF + #else + #define SOL_USE_THREAD_LOCAL_I_ SOL_ON + #endif +#else + #define SOL_USE_THREAD_LOCAL_I_ SOL_DEFAULT_ON +#endif // thread_local keyword is bjorked on some platforms + +#if defined(SOL_ALL_SAFETIES_ON) + #if SOL_ALL_SAFETIES_ON != 0 + #define SOL_ALL_SAFETIES_ON_I_ SOL_ON + #else + #define SOL_ALL_SAFETIES_ON_I_ SOL_OFF + #endif +#else + #define SOL_ALL_SAFETIES_ON_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_SAFE_GETTER) + #if SOL_SAFE_GETTER != 0 + #define SOL_SAFE_GETTER_I_ SOL_ON + #else + #define SOL_SAFE_GETTER_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_GETTER_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_GETTER_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_GETTER_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_USERTYPE) + #if SOL_SAFE_USERTYPE != 0 + #define SOL_SAFE_USERTYPE_I_ SOL_ON + #else + #define SOL_SAFE_USERTYPE_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_USERTYPE_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_USERTYPE_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_USERTYPE_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_REFERENCES) + #if SOL_SAFE_REFERENCES != 0 + #define SOL_SAFE_REFERENCES_I_ SOL_ON + #else + #define SOL_SAFE_REFERENCES_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_REFERENCES_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_REFERENCES_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_REFERENCES_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_FUNCTIONS) + #if SOL_SAFE_FUNCTIONS != 0 + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_OFF + #endif +#elif defined (SOL_SAFE_FUNCTION_OBJECTS) + #if SOL_SAFE_FUNCTION_OBJECTS != 0 + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_FUNCTION_OBJECTS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_FUNCTION_CALLS) + #if SOL_SAFE_FUNCTION_CALLS != 0 + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_ON + #else + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_FUNCTION_CALLS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_PROXIES) + #if SOL_SAFE_PROXIES != 0 + #define SOL_SAFE_PROXIES_I_ SOL_ON + #else + #define SOL_SAFE_PROXIES_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_PROXIES_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_PROXIES_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_PROXIES_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_SAFE_NUMERICS) + #if SOL_SAFE_NUMERICS != 0 + #define SOL_SAFE_NUMERICS_I_ SOL_ON + #else + #define SOL_SAFE_NUMERICS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_NUMERICS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_NUMERICS_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_NUMERICS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_ALL_INTEGER_VALUES_FIT) + #if (SOL_ALL_INTEGER_VALUES_FIT != 0) + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_ON + #else + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_OFF + #endif +#elif !SOL_IS_DEFAULT_OFF(SOL_SAFE_NUMERICS) && SOL_IS_OFF(SOL_SAFE_NUMERICS) + // if numerics is intentionally turned off, flip this on + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_DEFAULT_ON +#else + // default to off + #define SOL_ALL_INTEGER_VALUES_FIT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_SAFE_STACK_CHECK) + #if SOL_SAFE_STACK_CHECK != 0 + #define SOL_SAFE_STACK_CHECK_I_ SOL_ON + #else + #define SOL_SAFE_STACK_CHECK_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_SAFE_STACK_CHECK_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_SAFE_STACK_CHECK_I_ SOL_DEFAULT_ON + #else + #define SOL_SAFE_STACK_CHECK_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_NO_CHECK_NUMBER_PRECISION) + #if SOL_NO_CHECK_NUMBER_PRECISION != 0 + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_OFF + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #endif +#elif defined(SOL_NO_CHECKING_NUMBER_PRECISION) + #if SOL_NO_CHECKING_NUMBER_PRECISION != 0 + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_OFF + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #elif SOL_IS_ON(SOL_SAFE_NUMERICS) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_DEFAULT_ON + #else + #define SOL_NUMBER_PRECISION_CHECKS_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_STRINGS_ARE_NUMBERS) + #if (SOL_STRINGS_ARE_NUMBERS != 0) + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_ON + #else + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_OFF + #endif +#else + #define SOL_STRINGS_ARE_NUMBERS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ENABLE_INTEROP) + #if SOL_ENABLE_INTEROP != 0 + #define SOL_USE_INTEROP_I_ SOL_ON + #else + #define SOL_USE_INTEROP_I_ SOL_OFF + #endif +#elif defined(SOL_USE_INTEROP) + #if SOL_USE_INTEROP != 0 + #define SOL_USE_INTEROP_I_ SOL_ON + #else + #define SOL_USE_INTEROP_I_ SOL_OFF + #endif +#else + #define SOL_USE_INTEROP_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_NO_NIL) + #if (SOL_NO_NIL != 0) + #define SOL_NIL_I_ SOL_OFF + #else + #define SOL_NIL_I_ SOL_ON + #endif +#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) || defined(__OBJC__) || defined(nil) + #define SOL_NIL_I_ SOL_DEFAULT_OFF +#else + #define SOL_NIL_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_USERTYPE_TYPE_BINDING_INFO) + #if (SOL_USERTYPE_TYPE_BINDING_INFO != 0) + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_ON + #else + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_OFF + #endif +#else + #define SOL_USERTYPE_TYPE_BINDING_INFO_I_ SOL_DEFAULT_ON +#endif // We should generate a my_type.__type table with lots of class information for usertypes + +#if defined(SOL_AUTOMAGICAL_TYPES_BY_DEFAULT) + #if (SOL_AUTOMAGICAL_TYPES_BY_DEFAULT != 0) + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_ON + #else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_OFF + #endif +#elif defined(SOL_DEFAULT_AUTOMAGICAL_USERTYPES) + #if (SOL_DEFAULT_AUTOMAGICAL_USERTYPES != 0) + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_ON + #else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_OFF + #endif +#else + #define SOL_DEFAULT_AUTOMAGICAL_USERTYPES_I_ SOL_DEFAULT_ON +#endif // make is_automagical on/off by default + +#if defined(SOL_STD_VARIANT) + #if (SOL_STD_VARIANT != 0) + #define SOL_STD_VARIANT_I_ SOL_ON + #else + #define SOL_STD_VARIANT_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_COMPILER_CLANG) && SOL_IS_ON(SOL_PLATFORM_APPLE) + #if defined(__has_include) + #if __has_include() + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_ON + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_OFF + #endif + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_OFF + #endif + #else + #define SOL_STD_VARIANT_I_ SOL_DEFAULT_ON + #endif +#endif // make is_automagical on/off by default + +#if defined(SOL_NOEXCEPT_FUNCTION_TYPE) + #if (SOL_NOEXCEPT_FUNCTION_TYPE != 0) + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_ON + #else + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_OFF + #endif +#else + #if defined(__cpp_noexcept_function_type) + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_ON + #elif SOL_IS_ON(SOL_COMPILER_VCXX) && (defined(_MSVC_LANG) && (_MSVC_LANG < 201403L)) + // There is a bug in the VC++ compiler?? + // on /std:c++latest under x86 conditions (VS 15.5.2), + // compiler errors are tossed for noexcept markings being on function types + // that are identical in every other way to their non-noexcept marked types function types... + // VS 2019: There is absolutely a bug. + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_OFF + #else + #define SOL_USE_NOEXCEPT_FUNCTION_TYPE_I_ SOL_DEFAULT_ON + #endif +#endif // noexcept is part of a function's type + +#if defined(SOL_STACK_STRING_OPTIMIZATION_SIZE) && SOL_STACK_STRING_OPTIMIZATION_SIZE > 0 + #define SOL_OPTIMIZATION_STRING_CONVERSION_STACK_SIZE_I_ SOL_STACK_STRING_OPTIMIZATION_SIZE +#else + #define SOL_OPTIMIZATION_STRING_CONVERSION_STACK_SIZE_I_ 1024 +#endif + +#if defined(SOL_ID_SIZE) && SOL_ID_SIZE > 0 + #define SOL_ID_SIZE_I_ SOL_ID_SIZE +#else + #define SOL_ID_SIZE_I_ 512 +#endif + +#if defined(LUA_IDSIZE) && LUA_IDSIZE > 0 + #define SOL_FILE_ID_SIZE_I_ LUA_IDSIZE +#elif defined(SOL_ID_SIZE) && SOL_ID_SIZE > 0 + #define SOL_FILE_ID_SIZE_I_ SOL_FILE_ID_SIZE +#else + #define SOL_FILE_ID_SIZE_I_ 2048 +#endif + +#if defined(SOL_PRINT_ERRORS) + #if (SOL_PRINT_ERRORS != 0) + #define SOL_PRINT_ERRORS_I_ SOL_ON + #else + #define SOL_PRINT_ERRORS_I_ SOL_OFF + #endif +#else + #if SOL_IS_ON(SOL_ALL_SAFETIES_ON) + #define SOL_PRINT_ERRORS_I_ SOL_ON + #elif SOL_IS_ON(SOL_DEBUG_BUILD) + #define SOL_PRINT_ERRORS_I_ SOL_DEFAULT_ON + #else + #define SOL_PRINT_ERRORS_I_ SOL_OFF + #endif +#endif + +#if defined(SOL_DEFAULT_PASS_ON_ERROR) + #if (SOL_DEFAULT_PASS_ON_ERROR != 0) + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_ON + #else + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_OFF + #endif +#else + #define SOL_DEFAULT_PASS_ON_ERROR_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USING_CXX_LUA) + #if (SOL_USING_CXX_LUA != 0) + #define SOL_USING_CXX_LUA_I_ SOL_ON + #else + #define SOL_USING_CXX_LUA_I_ SOL_OFF + #endif +#elif defined(SOL_USE_CXX_LUA) + // alternative spelling + #if (SOL_USE_CXX_LUA != 0) + #define SOL_USING_CXX_LUA_I_ SOL_ON + #else + #define SOL_USING_CXX_LUA_I_ SOL_OFF + #endif +#else + #define SOL_USING_CXX_LUA_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USING_CXX_LUAJIT) + #if (SOL_USING_CXX_LUAJIT != 0) + #define SOL_USING_CXX_LUAJIT_I_ SOL_ON + #else + #define SOL_USING_CXX_LUAJIT_I_ SOL_OFF + #endif +#elif defined(SOL_USE_CXX_LUAJIT) + #if (SOL_USE_CXX_LUAJIT != 0) + #define SOL_USING_CXX_LUAJIT_I_ SOL_ON + #else + #define SOL_USING_CXX_LUAJIT_I_ SOL_OFF + #endif +#else + #define SOL_USING_CXX_LUAJIT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_NO_LUA_HPP) + #if (SOL_NO_LUA_HPP != 0) + #define SOL_USE_LUA_HPP_I_ SOL_OFF + #else + #define SOL_USE_LUA_HPP_I_ SOL_ON + #endif +#elif SOL_IS_ON(SOL_USING_CXX_LUA) + #define SOL_USE_LUA_HPP_I_ SOL_OFF +#elif defined(__has_include) + #if __has_include() + #define SOL_USE_LUA_HPP_I_ SOL_ON + #else + #define SOL_USE_LUA_HPP_I_ SOL_OFF + #endif +#else + #define SOL_USE_LUA_HPP_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_CONTAINERS_START) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINERS_START +#elif defined(SOL_CONTAINERS_START_INDEX) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINERS_START_INDEX +#elif defined(SOL_CONTAINER_START_INDEX) + #define SOL_CONTAINER_START_INDEX_I_ SOL_CONTAINER_START_INDEX +#else + #define SOL_CONTAINER_START_INDEX_I_ 1 +#endif + +#if defined (SOL_NO_MEMORY_ALIGNMENT) + #if (SOL_NO_MEMORY_ALIGNMENT != 0) + #define SOL_ALIGN_MEMORY_I_ SOL_OFF + #else + #define SOL_ALIGN_MEMORY_I_ SOL_ON + #endif +#else + #define SOL_ALIGN_MEMORY_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_USE_BOOST) + #if (SOL_USE_BOOST != 0) + #define SOL_USE_BOOST_I_ SOL_ON + #else + #define SOL_USE_BOOST_I_ SOL_OFF + #endif +#else + #define SOL_USE_BOOST_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_USE_UNSAFE_BASE_LOOKUP) + #if (SOL_USE_UNSAFE_BASE_LOOKUP != 0) + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_ON + #else + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_OFF + #endif +#else + #define SOL_USE_UNSAFE_BASE_LOOKUP_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_INSIDE_UNREAL) + #if (SOL_INSIDE_UNREAL != 0) + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_ON + #else + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_OFF + #endif +#else + #if defined(UE_BUILD_DEBUG) || defined(UE_BUILD_DEVELOPMENT) || defined(UE_BUILD_TEST) || defined(UE_BUILD_SHIPPING) || defined(UE_SERVER) + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_DEFAULT_ON + #else + #define SOL_INSIDE_UNREAL_ENGINE_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if defined(SOL_NO_COMPAT) + #if (SOL_NO_COMPAT != 0) + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_OFF + #else + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_ON + #endif +#else + #define SOL_USE_COMPATIBILITY_LAYER_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_GET_FUNCTION_POINTER_UNSAFE) + #if (SOL_GET_FUNCTION_POINTER_UNSAFE != 0) + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_ON + #else + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_OFF + #endif +#else + #define SOL_GET_FUNCTION_POINTER_UNSAFE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_CONTAINER_CHECK_IS_EXHAUSTIVE) + #if (SOL_CONTAINER_CHECK_IS_EXHAUSTIVE != 0) + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_ON + #else + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_OFF + #endif +#else + #define SOL_CONTAINER_CHECK_IS_EXHAUSTIVE_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_FUNCTION_CALL_VALUE_SEMANTICS) + #if (SOL_FUNCTION_CALL_VALUE_SEMANTICS != 0) + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_ON + #else + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_OFF + #endif +#else + #define SOL_FUNCTION_CALL_VALUE_SEMANTICS_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_MINGW_CCTYPE_IS_POISONED) + #if (SOL_MINGW_CCTYPE_IS_POISONED != 0) + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_ON + #else + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_COMPILER_MINGW) && defined(__GNUC__) && (__GNUC__ < 6) + // MinGW is off its rocker in some places... + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_DEFAULT_ON +#else + #define SOL_MINGW_CCTYPE_IS_POISONED_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_CHAR8_T) + #if (SOL_CHAR8_T != 0) + #define SOL_CHAR8_T_I_ SOL_ON + #else + #define SOL_CHAR8_T_I_ SOL_OFF + #endif +#else + #if defined(__cpp_char8_t) + #define SOL_CHAR8_T_I_ SOL_DEFAULT_ON + #else + #define SOL_CHAR8_T_I_ SOL_DEFAULT_OFF + #endif +#endif + +#if SOL_IS_ON(SOL_USE_BOOST) + #include + + #if BOOST_VERSION >= 107500 // Since Boost 1.75.0 boost::none is constexpr + #define SOL_BOOST_NONE_CONSTEXPR_I_ constexpr + #else + #define SOL_BOOST_NONE_CONSTEXPR_I_ const + #endif // BOOST_VERSION +#else + // assume boost isn't using a garbage version + #define SOL_BOOST_NONE_CONSTEXPR_I_ constexpr +#endif + +#if defined(SOL2_CI) + #if (SOL2_CI != 0) + #define SOL2_CI_I_ SOL_ON + #else + #define SOL2_CI_I_ SOL_OFF + #endif +#else + #define SOL2_CI_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ASSERT) + #define SOL_USER_ASSERT_I_ SOL_ON +#else + #define SOL_USER_ASSERT_I_ SOL_DEFAULT_OFF +#endif + +#if defined(SOL_ASSERT_MSG) + #define SOL_USER_ASSERT_MSG_I_ SOL_ON +#else + #define SOL_USER_ASSERT_MSG_I_ SOL_DEFAULT_OFF +#endif + +// beginning of sol/prologue.hpp + +#if defined(SOL_PROLOGUE_I_) + #error "[sol2] Library Prologue was already included in translation unit and not properly ended with an epilogue." +#endif + +#define SOL_PROLOGUE_I_ 1 + +#if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #define _FWD(...) static_cast( __VA_ARGS__ ) + + #if SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define _MOVE(...) static_cast<__typeof( __VA_ARGS__ )&&>( __VA_ARGS__ ) + #else + #include + + #define _MOVE(...) static_cast<::std::remove_reference_t<( __VA_ARGS__ )>&&>( __VA_OPT__(,) ) + #endif +#endif + +// end of sol/prologue.hpp + +// beginning of sol/epilogue.hpp + +#if !defined(SOL_PROLOGUE_I_) + #error "[sol2] Library Prologue is missing from this translation unit." +#else + #undef SOL_PROLOGUE_I_ +#endif + +#if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #undef _FWD + #undef _MOVE +#endif + +// end of sol/epilogue.hpp + +// beginning of sol/detail/build_version.hpp + +#if defined(SOL_DLL) + #if (SOL_DLL != 0) + #define SOL_DLL_I_ SOL_ON + #else + #define SOL_DLL_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_COMPILER_VCXX) && (defined(DLL_) || defined(_DLL)) + #define SOL_DLL_I_ SOL_DEFAULT_ON +#else + #define SOL_DLL_I_ SOL_DEFAULT_OFF +#endif // DLL definition + +#if defined(SOL_HEADER_ONLY) + #if (SOL_HEADER_ONLY != 0) + #define SOL_HEADER_ONLY_I_ SOL_ON + #else + #define SOL_HEADER_ONLY_I_ SOL_OFF + #endif +#else + #define SOL_HEADER_ONLY_I_ SOL_DEFAULT_OFF +#endif // Header only library + +#if defined(SOL_BUILD) + #if (SOL_BUILD != 0) + #define SOL_BUILD_I_ SOL_ON + #else + #define SOL_BUILD_I_ SOL_OFF + #endif +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_BUILD_I_ SOL_DEFAULT_OFF +#else + #define SOL_BUILD_I_ SOL_DEFAULT_ON +#endif + +#if defined(SOL_UNITY_BUILD) + #if (SOL_UNITY_BUILD != 0) + #define SOL_UNITY_BUILD_I_ SOL_ON + #else + #define SOL_UNITY_BUILD_I_ SOL_OFF + #endif +#else + #define SOL_UNITY_BUILD_I_ SOL_DEFAULT_OFF +#endif // Header only library + +#if defined(SOL_C_FUNCTION_LINKAGE) + #define SOL_C_FUNCTION_LINKAGE_I_ SOL_C_FUNCTION_LINKAGE +#else + #if SOL_IS_ON(SOL_BUILD_CXX_MODE) + // C++ + #define SOL_C_FUNCTION_LINKAGE_I_ extern "C" + #else + // normal + #define SOL_C_FUNCTION_LINKAGE_I_ + #endif // C++ or not +#endif // Linkage specification for C functions + +#if defined(SOL_API_LINKAGE) + #define SOL_API_LINKAGE_I_ SOL_API_LINKAGE +#else + #if SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) || SOL_IS_ON(SOL_PLATFORM_WINDOWS) || SOL_IS_ON(SOL_PLATFORM_CYGWIN) + // MSVC Compiler; or, Windows, or Cygwin platforms + #if SOL_IS_ON(SOL_BUILD) + // Building the library + #if SOL_IS_ON(SOL_COMPILER_GCC) + // Using GCC + #define SOL_API_LINKAGE_I_ __attribute__((dllexport)) + #else + // Using Clang, MSVC, etc... + #define SOL_API_LINKAGE_I_ __declspec(dllexport) + #endif + #else + #if SOL_IS_ON(SOL_COMPILER_GCC) + #define SOL_API_LINKAGE_I_ __attribute__((dllimport)) + #else + #define SOL_API_LINKAGE_I_ __declspec(dllimport) + #endif + #endif + #else + // extern if building normally on non-MSVC + #define SOL_API_LINKAGE_I_ extern + #endif + #elif SOL_IS_ON(SOL_UNITY_BUILD) + // Built-in library, like how stb typical works + #if SOL_IS_ON(SOL_HEADER_ONLY) + // Header only, so functions are defined "inline" + #define SOL_API_LINKAGE_I_ inline + #else + // Not header only, so seperately compiled files + #define SOL_API_LINKAGE_I_ extern + #endif + #else + // Normal static library + #if SOL_IS_ON(SOL_BUILD_CXX_MODE) + #define SOL_API_LINKAGE_I_ + #else + #define SOL_API_LINKAGE_I_ extern + #endif + #endif // DLL or not +#endif // Build definitions + +#if defined(SOL_PUBLIC_FUNC_DECL) + #define SOL_PUBLIC_FUNC_DECL_I_ SOL_PUBLIC_FUNC_DECL +#else + #define SOL_PUBLIC_FUNC_DECL_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_INTERNAL_FUNC_DECL_) + #define SOL_INTERNAL_FUNC_DECL_I_ SOL_INTERNAL_FUNC_DECL_ +#else + #define SOL_INTERNAL_FUNC_DECL_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_PUBLIC_FUNC_DEF) + #define SOL_PUBLIC_FUNC_DEF_I_ SOL_PUBLIC_FUNC_DEF +#else + #define SOL_PUBLIC_FUNC_DEF_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_INTERNAL_FUNC_DEF) + #define SOL_INTERNAL_FUNC_DEF_I_ SOL_INTERNAL_FUNC_DEF +#else + #define SOL_INTERNAL_FUNC_DEF_I_ SOL_API_LINKAGE_I_ +#endif + +#if defined(SOL_FUNC_DECL) + #define SOL_FUNC_DECL_I_ SOL_FUNC_DECL +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_FUNC_DECL_I_ +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_FUNC_DECL_I_ extern __declspec(dllexport) + #else + #define SOL_FUNC_DECL_I_ extern __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_FUNC_DECL_I_ extern __attribute__((visibility("default"))) + #else + #define SOL_FUNC_DECL_I_ extern + #endif +#endif + +#if defined(SOL_FUNC_DEFN) + #define SOL_FUNC_DEFN_I_ SOL_FUNC_DEFN +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_FUNC_DEFN_I_ inline +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_FUNC_DEFN_I_ __declspec(dllexport) + #else + #define SOL_FUNC_DEFN_I_ __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_FUNC_DEFN_I_ __attribute__((visibility("default"))) + #else + #define SOL_FUNC_DEFN_I_ + #endif +#endif + +#if defined(SOL_HIDDEN_FUNC_DECL) + #define SOL_HIDDEN_FUNC_DECL_I_ SOL_HIDDEN_FUNC_DECL +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_HIDDEN_FUNC_DECL_I_ +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_HIDDEN_FUNC_DECL_I_ extern __declspec(dllexport) + #else + #define SOL_HIDDEN_FUNC_DECL_I_ extern __declspec(dllimport) + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_HIDDEN_FUNC_DECL_I_ extern __attribute__((visibility("default"))) + #else + #define SOL_HIDDEN_FUNC_DECL_I_ extern + #endif +#endif + +#if defined(SOL_HIDDEN_FUNC_DEFN) + #define SOL_HIDDEN_FUNC_DEFN_I_ SOL_HIDDEN_FUNC_DEFN +#elif SOL_IS_ON(SOL_HEADER_ONLY) + #define SOL_HIDDEN_FUNC_DEFN_I_ inline +#elif SOL_IS_ON(SOL_DLL) + #if SOL_IS_ON(SOL_COMPILER_VCXX) + #if SOL_IS_ON(SOL_BUILD) + #define SOL_HIDDEN_FUNC_DEFN_I_ + #else + #define SOL_HIDDEN_FUNC_DEFN_I_ + #endif + #elif SOL_IS_ON(SOL_COMPILER_GCC) || SOL_IS_ON(SOL_COMPILER_CLANG) + #define SOL_HIDDEN_FUNC_DEFN_I_ __attribute__((visibility("hidden"))) + #else + #define SOL_HIDDEN_FUNC_DEFN_I_ + #endif +#endif + +// end of sol/detail/build_version.hpp + +// end of sol/version.hpp + +#if SOL_IS_ON(SOL_INSIDE_UNREAL_ENGINE) +#ifdef check +#pragma push_macro("check") +#undef check +#endif +#endif // Unreal Engine 4 Bullshit + +#if SOL_IS_ON(SOL_COMPILER_GCC) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wshadow" +#pragma GCC diagnostic ignored "-Wconversion" +#if __GNUC__ > 6 +#pragma GCC diagnostic ignored "-Wnoexcept-type" +#endif +#elif SOL_IS_ON(SOL_COMPILER_CLANG) +#elif SOL_IS_ON(SOL_COMPILER_VCXX) +#pragma warning(push) +#pragma warning(disable : 4505) // unreferenced local function has been removed GEE THANKS +#endif // clang++ vs. g++ vs. VC++ + +// beginning of sol/forward.hpp + +#ifndef SOL_FORWARD_HPP +#define SOL_FORWARD_HPP + +#include +#include +#include + +#if SOL_IS_ON(SOL_USING_CXX_LUA) || SOL_IS_ON(SOL_USING_CXX_LUAJIT) +struct lua_State; +#else +extern "C" { +struct lua_State; +} +#endif // C++ Mangling for Lua vs. Not + +namespace sol { + + enum class type; + + class stateless_reference; + template + class basic_reference; + using reference = basic_reference; + using main_reference = basic_reference; + class stateless_stack_reference; + class stack_reference; + + template + class basic_bytecode; + + struct lua_value; + + struct proxy_base_tag; + template + struct proxy_base; + template + struct table_proxy; + + template + class basic_table_core; + template + using table_core = basic_table_core; + template + using main_table_core = basic_table_core; + template + using stack_table_core = basic_table_core; + template + using basic_table = basic_table_core; + using table = table_core; + using global_table = table_core; + using main_table = main_table_core; + using main_global_table = main_table_core; + using stack_table = stack_table_core; + using stack_global_table = stack_table_core; + + template + struct basic_lua_table; + using lua_table = basic_lua_table; + using stack_lua_table = basic_lua_table; + + template + class basic_usertype; + template + using usertype = basic_usertype; + template + using stack_usertype = basic_usertype; + + template + class basic_metatable; + using metatable = basic_metatable; + using stack_metatable = basic_metatable; + + template + struct basic_environment; + using environment = basic_environment; + using main_environment = basic_environment; + using stack_environment = basic_environment; + + template + class basic_function; + template + class basic_protected_function; + using unsafe_function = basic_function; + using safe_function = basic_protected_function; + using main_unsafe_function = basic_function; + using main_safe_function = basic_protected_function; + using stack_unsafe_function = basic_function; + using stack_safe_function = basic_protected_function; + using stack_aligned_unsafe_function = basic_function; + using stack_aligned_safe_function = basic_protected_function; + using protected_function = safe_function; + using main_protected_function = main_safe_function; + using stack_protected_function = stack_safe_function; + using stack_aligned_protected_function = stack_aligned_safe_function; +#if SOL_IS_ON(SOL_SAFE_FUNCTION_OBJECTS) + using function = protected_function; + using main_function = main_protected_function; + using stack_function = stack_protected_function; + using stack_aligned_function = stack_aligned_safe_function; +#else + using function = unsafe_function; + using main_function = main_unsafe_function; + using stack_function = stack_unsafe_function; + using stack_aligned_function = stack_aligned_unsafe_function; +#endif + using stack_aligned_stack_handler_function = basic_protected_function; + + struct unsafe_function_result; + struct protected_function_result; + using safe_function_result = protected_function_result; +#if SOL_IS_ON(SOL_SAFE_FUNCTION_OBJECTS) + using function_result = safe_function_result; +#else + using function_result = unsafe_function_result; +#endif + + template + class basic_object_base; + template + class basic_object; + template + class basic_userdata; + template + class basic_lightuserdata; + template + class basic_coroutine; + template + class basic_packaged_coroutine; + template + class basic_thread; + + using object = basic_object; + using userdata = basic_userdata; + using lightuserdata = basic_lightuserdata; + using thread = basic_thread; + using coroutine = basic_coroutine; + using packaged_coroutine = basic_packaged_coroutine; + using main_object = basic_object; + using main_userdata = basic_userdata; + using main_lightuserdata = basic_lightuserdata; + using main_coroutine = basic_coroutine; + using stack_object = basic_object; + using stack_userdata = basic_userdata; + using stack_lightuserdata = basic_lightuserdata; + using stack_thread = basic_thread; + using stack_coroutine = basic_coroutine; + + struct stack_proxy_base; + struct stack_proxy; + struct variadic_args; + struct variadic_results; + struct stack_count; + struct this_state; + struct this_main_state; + struct this_environment; + + class state_view; + class state; + + template + struct as_table_t; + template + struct as_container_t; + template + struct nested; + template + struct light; + template + struct user; + template + struct as_args_t; + template + struct protect_t; + template + struct policy_wrapper; + + template + struct usertype_traits; + template + struct unique_usertype_traits; + + template + struct types { + typedef std::make_index_sequence indices; + static constexpr std::size_t size() { + return sizeof...(Args); + } + }; + + template + struct derive : std::false_type { + typedef types<> type; + }; + + template + struct base : std::false_type { + typedef types<> type; + }; + + template + struct weak_derive { + static bool value; + }; + + template + bool weak_derive::value = false; + + namespace stack { + struct record; + } + +#if SOL_IS_OFF(SOL_USE_BOOST) + template + class optional; + + template + class optional; +#endif + + using check_handler_type = int(lua_State*, int, type, type, const char*); + +} // namespace sol + +#define SOL_BASE_CLASSES(T, ...) \ + namespace sol { \ + template <> \ + struct base : std::true_type { \ + typedef ::sol::types<__VA_ARGS__> type; \ + }; \ + } \ + static_assert(true, "") +#define SOL_DERIVED_CLASSES(T, ...) \ + namespace sol { \ + template <> \ + struct derive : std::true_type { \ + typedef ::sol::types<__VA_ARGS__> type; \ + }; \ + } \ + static_assert(true, "") + +#endif // SOL_FORWARD_HPP +// end of sol/forward.hpp + +// beginning of sol/forward_detail.hpp + +#ifndef SOL_FORWARD_DETAIL_HPP +#define SOL_FORWARD_DETAIL_HPP + +// beginning of sol/traits.hpp + +// beginning of sol/tuple.hpp + +// beginning of sol/base_traits.hpp + +#include + +namespace sol { + namespace detail { + struct unchecked_t { }; + const unchecked_t unchecked = unchecked_t {}; + } // namespace detail + + namespace meta { + using sfinae_yes_t = std::true_type; + using sfinae_no_t = std::false_type; + + template + using void_t = void; + + template + using unqualified = std::remove_cv>; + + template + using unqualified_t = typename unqualified::type; + + namespace meta_detail { + template + struct unqualified_non_alias : unqualified { }; + + template