diff --git a/.github/workflows/build_cmake.yml b/.github/workflows/build_cmake.yml index 794b38c6c1c..9541c4c7017 100644 --- a/.github/workflows/build_cmake.yml +++ b/.github/workflows/build_cmake.yml @@ -7,9 +7,9 @@ on: - 'doc/**' env: - QT_VERSION: 6.6.2 + QT_VERSION: 6.7.1 MACOS_DEPLOYMENT_TARGET: 11.0 - CLANG_VERSION: 17.0.1 + CLANG_VERSION: 18.1.7 ELFUTILS_VERSION: 0.175 CMAKE_VERSION: 3.21.1 NINJA_VERSION: 1.10.2 @@ -49,13 +49,12 @@ jobs: } - { name: "macOS Latest Clang", artifact: "macos-universal", - # TODO: move back to macos-latest when macos-latest is 13 or higher - os: macos-13, + os: macos-latest, cc: "clang", cxx: "clang++" } steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Checkout submodules id: git shell: cmake -P {0} @@ -63,10 +62,10 @@ jobs: execute_process(COMMAND git submodule set-url -- perfparser https://code.qt.io/qt-creator/perfparser.git) execute_process(COMMAND git submodule update --init --recursive) file(MAKE_DIRECTORY release) - if (${{github.ref}} MATCHES "tags/v([0-9.]+)") + if (${{github.ref}} MATCHES "tags/v(([0-9.]+).*)") file(APPEND "$ENV{GITHUB_OUTPUT}" "tag=${CMAKE_MATCH_1}\n") - if (EXISTS "dist/changelog/changes-${CMAKE_MATCH_1}.md") - file(READ "dist/changelog/changes-${CMAKE_MATCH_1}.md" changelog_md) + if (EXISTS "dist/changelog/changes-${CMAKE_MATCH_2}.md") + file(READ "dist/changelog/changes-${CMAKE_MATCH_2}.md" changelog_md) endif() file(WRITE "release/changelog.md" "These packages are not officially supported, for official packages please check out https://download.qt.io/official_releases/qtcreator\n\n") file(APPEND "release/changelog.md" "${changelog_md}") @@ -200,7 +199,7 @@ jobs: endif() elseif ("${{ runner.os }}" STREQUAL "Linux") set(url_os "linux_x64") - set(qt_package_arch_suffix "gcc_64") + set(qt_package_arch_suffix "linux_gcc_64") set(qt_dir_prefix "${qt_version}/gcc_64") set(qt_package_suffix "-Linux-RHEL_8_8-GCC-Linux-RHEL_8_8-X86_64") elseif ("${{ runner.os }}" STREQUAL "macOS") @@ -267,10 +266,10 @@ jobs: ) endforeach() - # uic depends on libicu56.so + # uic, qmake depend on libicu*.so libraries if ("${{ runner.os }}" STREQUAL "Linux") downloadAndExtract( - "${qt_base_url}/qt.qt6.${qt_version_dotless}.${qt_package_arch_suffix}/${qt_package_version}icu-linux-Rhel7.2-x64.7z" + "${qt_base_url}/qt.qt6.${qt_version_dotless}.${qt_package_arch_suffix}/${qt_package_version}icu-linux-Rhel8.6-x86_64.7z" icu.7z ) endif() @@ -695,41 +694,41 @@ jobs: endif() - name: Upload - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z name: qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z - name: Upload Devel - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}_dev.7z name: qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}_dev.7z - name: Upload wininterrupt if: runner.os == 'Windows' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/wininterrupt-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z name: wininterrupt-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z - name: Upload qtcreatorcdbext if: runner.os == 'Windows' && matrix.config.is_msvc - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/qtcreatorcdbext-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z name: qtcreatorcdbext-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.7z - name: Upload Debian package if: runner.os == 'Linux' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/build/qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.deb name: qtcreator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.deb - name: Upload disk image if: runner.os == 'macOS' && contains(github.ref, 'tags/v') - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: build/qt-creator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.dmg name: qt-creator-${{ matrix.config.artifact }}-${{ steps.git.outputs.tag }}.dmg @@ -739,14 +738,14 @@ jobs: run: cmake -E tar cf ../${{ steps.ccache.outputs.archive_name }}.tar . - name: Upload ccache archive - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: path: ./${{ steps.ccache.outputs.archive_name }}.tar name: ${{ steps.ccache.outputs.archive_name }} - name: Upload Release Changelog - if: contains(github.ref, 'tags/v') - uses: actions/upload-artifact@v3 + if: runner.os == 'macOS' && contains(github.ref, 'tags/v') + uses: actions/upload-artifact@v4 with: path: ./release/changelog.md name: changelog.md @@ -758,7 +757,7 @@ jobs: steps: - name: Download artifacts - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: path: release-with-dirs @@ -770,7 +769,7 @@ jobs: - name: Create Release id: create_release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: diff --git a/.luarc.json b/.luarc.json new file mode 100644 index 00000000000..0d86a5b80cb --- /dev/null +++ b/.luarc.json @@ -0,0 +1,9 @@ +{ + "workspace.library": [ + "src/plugins/lua/meta" + ], + "hint.paramName": "Literal", + "hint.enable": true, + "hint.await": true, + "hint.arrayIndex": "Disable" +} diff --git a/README.md b/README.md index 9f4b6f1457d..274c5094868 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 @@ -96,7 +96,7 @@ include the version number and compiler ABI. The path to the online installer content is not enough. Note that `/path/to/Qt` doesn't imply the full path depth like: -`$USER/Qt/6.2.4/gcc_64/lib/cmake/Qt6`, but only `$USER/Qt/6.2.4/gcc_64`. +`$USER/Qt/6.4.3/gcc_64/lib/cmake/Qt6`, but only `$USER/Qt/6.4.3/gcc_64`. See [instructions](#getting-llvmclang-for-the-clang-code-model) on how to get LLVM. @@ -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 @@ -118,7 +145,7 @@ include the version number and compiler ABI. The path to the online installer content is not enough. Note that `\path\to\Qt` doesn't imply the full path depth like: -`c:\Qt\6.2.4\msvc2019_64\lib\cmake\Qt6`, but only `c:/Qt/6.2.4/msvc2019_64`. +`c:\Qt\6.4.3\msvc2019_64\lib\cmake\Qt6`, but only `c:/Qt/6.4.3/msvc2019_64`. The usage of slashes `/` is intentional, since CMake has issues with backslashes `\` in `CMAKE_PREFX_PATH`, they are interpreted as escape codes. @@ -198,7 +225,7 @@ CLion...etc) locally: "cacheVariables": { "CMAKE_CXX_COMPILER": "cl.exe", "CMAKE_C_COMPILER": "cl.exe", - "CMAKE_PREFIX_PATH": "c:/Qt/6.2.4/msvc2019_64" + "CMAKE_PREFIX_PATH": "c:/Qt/6.4.3/msvc2019_64" } } ] @@ -286,7 +313,7 @@ http://llvm.org/docs/GettingStarted.html#git-mirror: 1. Clone LLVM/Clang and checkout a suitable branch - git clone -b release_130-based --recursive https://code.qt.io/clang/llvm-project.git + git clone -b release_17.0.6-based --recursive https://code.qt.io/clang/llvm-project.git 2. Build and install LLVM/Clang @@ -314,16 +341,6 @@ http://llvm.org/docs/GettingStarted.html#git-mirror: ..\llvm-project\llvm cmake --build . --target install -### Clang-Format - -The ClangFormat plugin depends on the additional patch - - https://code.qt.io/cgit/clang/llvm-project.git/commit/?h=release_130-based&id=42879d1f355fde391ef46b96a659afeb4ad7814a - -While the plugin builds without it, it might not be fully functional. - -Note that the plugin is disabled by default. - # Licenses and Attributions Qt Creator is available under commercial licenses from The Qt Company, diff --git a/cmake/QtCreatorAPI.cmake b/cmake/QtCreatorAPI.cmake index 954f24ecefd..5d39157b020 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/cmake/QtCreatorAPIInternal.cmake b/cmake/QtCreatorAPIInternal.cmake index bf9ee0132ac..06d53a992c8 100644 --- a/cmake/QtCreatorAPIInternal.cmake +++ b/cmake/QtCreatorAPIInternal.cmake @@ -23,6 +23,7 @@ list(APPEND DEFAULT_DEFINES QT_NO_JAVA_STYLE_ITERATORS QT_NO_CAST_TO_ASCII QT_RESTRICTED_CAST_FROM_ASCII QT_NO_FOREACH QT_DISABLE_DEPRECATED_BEFORE=0x050900 + QT_WARN_DEPRECATED_BEFORE=0x060400 QT_USE_QSTRINGBUILDER ) diff --git a/cmake/QtCreatorDocumentation.cmake b/cmake/QtCreatorDocumentation.cmake index 9587a77e0b1..bf679d2188f 100644 --- a/cmake/QtCreatorDocumentation.cmake +++ b/cmake/QtCreatorDocumentation.cmake @@ -5,6 +5,18 @@ add_feature_info("Build documentation" WITH_DOCS "") option(WITH_ONLINE_DOCS "Build online documentation" OFF) add_feature_info("Build online documentation" WITH_ONLINE_DOCS "") +option(BUILD_DOCS_BY_DEFAULT "Build documentation by default" OFF) +add_feature_info("Build documentation by default" BUILD_DOCS_BY_DEFAULT "") + + +if (BUILD_DOCS_BY_DEFAULT) +set(EXCLUDE_DOCS_FROM_ALL "") +set(INCLUDE_DOCS_INTO_ALL "ALL") +else() +set(EXCLUDE_DOCS_FROM_ALL "EXCLUDE_FROM_ALL") +set(INCLUDE_DOCS_INTO_ALL "") +endif() + # Get information on directories from qmake # as this is not yet exported by cmake. # Used for QT_INSTALL_DOCS @@ -46,13 +58,13 @@ endfunction() function(_setup_doc_targets) # Set up important targets: if (NOT TARGET html_docs) - add_custom_target(html_docs COMMENT "Build HTML documentation") + add_custom_target(html_docs ${INCLUDE_DOCS_INTO_ALL} COMMENT "Build HTML documentation") endif() if (NOT TARGET qch_docs) - add_custom_target(qch_docs COMMENT "Build QCH documentation") + add_custom_target(qch_docs ${INCLUDE_DOCS_INTO_ALL} COMMENT "Build QCH documentation") endif() if (NOT TARGET docs) - add_custom_target(docs COMMENT "Build documentation") + add_custom_target(docs ${INCLUDE_DOCS_INTO_ALL} COMMENT "Build documentation") add_dependencies(docs html_docs qch_docs) endif() endfunction() @@ -114,6 +126,7 @@ function(_setup_qdoc_targets _qdocconf_file _retval) set(_html_target "html_docs_${_target}") add_custom_target("${_html_target}" + ${INCLUDE_DOCS_INTO_ALL} ${_full_qdoc_command} -outputdir "${_html_outputdir}" "${_qdocconf_file}" ${_qdoc_index_args} ${_qdoc_include_args} COMMENT "Build HTML documentation from ${_qdocconf_file}" @@ -126,7 +139,7 @@ function(_setup_qdoc_targets _qdocconf_file _retval) # Install HTML files as a special component install(DIRECTORY "${_html_outputdir}" DESTINATION "${_arg_INSTALL_DIR}" - COMPONENT html_docs EXCLUDE_FROM_ALL) + COMPONENT html_docs ${EXCLUDE_DOCS_FROM_ALL}) set("${_retval}" "${_html_outputdir}" PARENT_SCOPE) endfunction() @@ -154,6 +167,7 @@ function(_setup_qhelpgenerator_targets _qdocconf_file _html_outputdir) set(_qch_target "qch_docs_${_target}") set(_html_target "html_docs_${_target}") add_custom_target("${_qch_target}" + ${INCLUDE_DOCS_INTO_ALL} Qt::qhelpgenerator "${_html_outputdir}/${_target}.qhp" -o "${_qch_outputdir}/${_target}.qch" COMMENT "Build QCH documentation from ${_qdocconf_file}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" @@ -163,7 +177,7 @@ function(_setup_qhelpgenerator_targets _qdocconf_file _html_outputdir) add_dependencies(qch_docs "${_qch_target}") install(FILES "${_qch_outputdir}/${_target}.qch" DESTINATION "${_arg_INSTALL_DIR}" - COMPONENT qch_docs EXCLUDE_FROM_ALL) + COMPONENT qch_docs ${EXCLUDE_DOCS_FROM_ALL}) endfunction() # Helper functions: @@ -283,6 +297,7 @@ function(add_qtc_doc_attribution target attribution_file output_file qdocconf_fi file(MAKE_DIRECTORY ${output_dir}) # add target add_custom_target(${target} + ${INCLUDE_DOCS_INTO_ALL} Qt6::qtattributionsscanner -o "${output_file}" --basedir "${PROJECT_SOURCE_DIR}" ${attribution_file} COMMENT "Create attributions ${output_file} from ${attribution_file}" DEPENDS "${attribution_file}" diff --git a/cmake/QtCreatorIDEBranding.cmake b/cmake/QtCreatorIDEBranding.cmake index 8cab51c3c29..ebe11aa4efc 100644 --- a/cmake/QtCreatorIDEBranding.cmake +++ b/cmake/QtCreatorIDEBranding.cmake @@ -1,6 +1,6 @@ -set(IDE_VERSION "13.0.2") # The IDE version. -set(IDE_VERSION_COMPAT "13.0.0") # The IDE Compatibility version. -set(IDE_VERSION_DISPLAY "13.0.2") # The IDE display version. +set(IDE_VERSION "13.0.84") # The IDE version. +set(IDE_VERSION_COMPAT "13.0.84") # The IDE Compatibility version. +set(IDE_VERSION_DISPLAY "14.0.0-rc1") # 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/coin/instructions/build.yaml b/coin/instructions/build.yaml index 6ec0fcf1711..b98cfbafbcc 100644 --- a/coin/instructions/build.yaml +++ b/coin/instructions/build.yaml @@ -20,29 +20,29 @@ instructions: maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download elfutils package, check logs." - type: ExecuteCommand - command: "/usr/bin/7z x -y {{.AgentWorkingDir}}/build/qt_temp/elfutils-release_0.175qt-linux-x86_64.7z -o{{.AgentWorkingDir}}/build/qt_temp/elfutils" + command: "7z x -y {{.AgentWorkingDir}}/build/qt_temp/elfutils-release_0.175qt-linux-x86_64.7z -o{{.AgentWorkingDir}}/build/qt_temp/elfutils" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract elfutils package, check logs." - type: ExecuteCommand - command: "curl --fail -L --retry 5 --retry-delay 5 -o {{.AgentWorkingDir}}/build/qt_temp/libclang.7z {{.Env.LLVM_BASE_URL}}-linux-Rhel8.4-gcc10.3-x86_64.7z" + command: "curl --fail -L --retry 5 --retry-delay 5 -o {{.AgentWorkingDir}}/build/qt_temp/libclang.7z {{.Env.LLVM_BASE_URL}}-linux-Rhel8.6-gcc10.3-x86_64.7z" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download LLVM package, check logs." - type: ExecuteCommand - command: "/usr/bin/7z x -y {{.AgentWorkingDir}}/build/qt_temp/libclang.7z -o{{.AgentWorkingDir}}/build/qt_temp/" + command: "7z x -y {{.AgentWorkingDir}}/build/qt_temp/libclang.7z -o{{.AgentWorkingDir}}/build/qt_temp/" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract LLVM package, check logs." - type: ExecuteCommand - command: "python3 -u {{.AgentWorkingDir}}/qt-creator/qt-creator/scripts/build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}/qt-creator/qt-creator --build {{.AgentWorkingDir}}/qt-creator/qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --elfutils-path {{.AgentWorkingDir}}/build/qt_temp/elfutils --llvm-path {{.AgentWorkingDir}}/build/qt_temp/libclang {{.Env.QTC_TEST_OPTION}} --no-zip --add-config=-DCMAKE_C_COMPILER_LAUNCHER=sccache --add-config=-DCMAKE_CXX_COMPILER_LAUNCHER=sccache" + command: "python3 -u {{.AgentWorkingDir}}/qt-creator/qt-creator/scripts/build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}/qt-creator/qt-creator --build {{.AgentWorkingDir}}/qt-creator/qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --elfutils-path {{.AgentWorkingDir}}/build/qt_temp/elfutils --llvm-path {{.AgentWorkingDir}}/build/qt_temp/libclang {{.Env.QTC_TEST_OPTION}} --no-zip {{.Env.QTC_SCCACHE_C_OPTION}} {{.Env.QTC_SCCACHE_CXX_OPTION}} {{.Env.QTC_SCCACHE_ENABLE_OPTION}}" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to run build.py, check logs." - type: ChangeDirectory directory: "{{.AgentWorkingDir}}/build/tqtc-qtsdk/packaging_tools" - type: ExecuteCommand - command: "python3 -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}/build/sdktool/qt --src {{.AgentWorkingDir}}/qt-creator/qt-creator/src/tools/sdktool --build {{.AgentWorkingDir}}/build/sdktool/build --install {{.AgentWorkingDir}}/build/sdktool/install --make-command make" + command: "python3 -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}/build/sdktool/qt --src {{.AgentWorkingDir}}/qt-creator/qt-creator/src/tools/sdktool --build {{.AgentWorkingDir}}/build/sdktool/build --install {{.AgentWorkingDir}}/build/sdktool/install --make-command ninja" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to build sdktool, check logs." @@ -64,12 +64,12 @@ instructions: maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download LLVM package, check logs." - type: ExecuteCommand - command: "/usr/local/bin/7z x -y {{.AgentWorkingDir}}/build/qt_temp/libclang.7z -o{{.AgentWorkingDir}}/build/qt_temp/" + command: "7z x -y {{.AgentWorkingDir}}/build/qt_temp/libclang.7z -o{{.AgentWorkingDir}}/build/qt_temp/" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract LLVM package, check logs." - type: ExecuteCommand - command: "python3 -u {{.AgentWorkingDir}}/qt-creator/qt-creator/scripts/build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}/qt-creator/qt-creator --build {{.AgentWorkingDir}}/qt-creator/qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --llvm-path {{.AgentWorkingDir}}/build/qt_temp/libclang --keychain-unlock-script /Users/qt/unlock-keychain.sh {{.Env.QTC_TEST_OPTION}} --no-zip --add-config=-DCMAKE_C_COMPILER_LAUNCHER=sccache --add-config=-DCMAKE_CXX_COMPILER_LAUNCHER=sccache" + command: "python3 -u {{.AgentWorkingDir}}/qt-creator/qt-creator/scripts/build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}/qt-creator/qt-creator --build {{.AgentWorkingDir}}/qt-creator/qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --llvm-path {{.AgentWorkingDir}}/build/qt_temp/libclang --keychain-unlock-script /Users/qt/unlock-keychain.sh {{.Env.QTC_TEST_OPTION}} --no-zip {{.Env.QTC_SCCACHE_C_OPTION}} {{.Env.QTC_SCCACHE_CXX_OPTION}} {{.Env.QTC_SCCACHE_ENABLE_OPTION}}" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to run build.py, check logs." @@ -79,7 +79,7 @@ instructions: variableName: MACOSX_DEPLOYMENT_TARGET variableValue: "{{.Env.SDKTOOL_MACOSX_DEPLOYMENT_TARGET}}" - type: ExecuteCommand - command: "python3 -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}/build/sdktool/qt --src {{.AgentWorkingDir}}/qt-creator/qt-creator/src/tools/sdktool --build {{.AgentWorkingDir}}/build/sdktool/build --install {{.AgentWorkingDir}}/build/sdktool/install --make-command make" + command: "python3 -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}/build/sdktool/qt --src {{.AgentWorkingDir}}/qt-creator/qt-creator/src/tools/sdktool --build {{.AgentWorkingDir}}/build/sdktool/build --install {{.AgentWorkingDir}}/build/sdktool/install --make-command ninja --universal" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to build sdktool, check logs." @@ -96,7 +96,7 @@ instructions: maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download elfutils package, check logs." - type: ExecuteCommand - command: "C:\\Utils\\sevenzip\\7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\elfutils-release_0.175qt-windows-x86_64.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\elfutils" + command: "7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\elfutils-release_0.175qt-windows-x86_64.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\elfutils" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract elfutils package, check logs." @@ -106,7 +106,7 @@ instructions: maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download python package, check logs." - type: ExecuteCommand - command: "C:\\Utils\\sevenzip\\7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\Python38-win-x64.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\python" + command: "7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\Python38-win-x64.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\python" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract python package, check logs." @@ -116,19 +116,19 @@ instructions: maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to download LLVM package, check logs." - type: ExecuteCommand - command: "C:\\Utils\\sevenzip\\7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\libclang.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\" + command: "7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\libclang.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\" maxTimeInSeconds: 3600 maxTimeBetweenOutput: 360 userMessageOnFailure: "Failed to extract LLVM package, check logs." - type: ExecuteCommand - command: "python -u {{.AgentWorkingDir}}\\qt-creator\\qt-creator\\scripts\\build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}\\qt-creator\\qt-creator --build {{.AgentWorkingDir}}\\qt-creator\\qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --python-path {{.AgentWorkingDir}}\\build\\qt_temp\\python --elfutils-path {{.AgentWorkingDir}}\\buid\\qt_temp\\elfutils --llvm-path {{.AgentWorkingDir}}\\build\\qt_temp\\libclang {{.Env.QTC_TEST_OPTION}} --no-zip --add-config=-DCMAKE_C_COMPILER_LAUNCHER=sccache --add-config=-DCMAKE_CXX_COMPILER_LAUNCHER=sccache --add-config=-DWITH_SCCACHE_SUPPORT=ON" + command: "python -u {{.AgentWorkingDir}}\\qt-creator\\qt-creator\\scripts\\build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}\\qt-creator\\qt-creator --build {{.AgentWorkingDir}}\\qt-creator\\qt-creator_build --qt-path {{.AgentWorkingDir}}/build/qt_install_dir --python-path {{.AgentWorkingDir}}\\build\\qt_temp\\python --elfutils-path {{.AgentWorkingDir}}\\buid\\qt_temp\\elfutils --llvm-path {{.AgentWorkingDir}}\\build\\qt_temp\\libclang {{.Env.QTC_TEST_OPTION}} --no-zip {{.Env.QTC_SCCACHE_C_OPTION}} {{.Env.QTC_SCCACHE_CXX_OPTION}} {{.Env.QTC_SCCACHE_ENABLE_OPTION}}" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to run build.py, check logs." - type: ChangeDirectory directory: "{{.AgentWorkingDir}}\\build\\tqtc-qtsdk\\packaging_tools" - type: ExecuteCommand - command: "python -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}\\build\\sdktool\\qt --src {{.AgentWorkingDir}}\\qt-creator\\qt-creator\\src\\tools\\sdktool --build {{.AgentWorkingDir}}\\build\\sdktool\\build --install {{.AgentWorkingDir}}\\build\\sdktool\\install --make-command nmake" + command: "python -m pipenv run python -u bld_sdktool.py --qt-url {{.Env.QTC_SDKTOOL_QT_BASE_URL}}{{.Env.QTC_SDKTOOL_QT_EXT}} --qt-build {{.AgentWorkingDir}}\\build\\sdktool\\qt --src {{.AgentWorkingDir}}\\qt-creator\\qt-creator\\src\\tools\\sdktool --build {{.AgentWorkingDir}}\\build\\sdktool\\build --install {{.AgentWorkingDir}}\\build\\sdktool\\install --make-command ninja" maxTimeInSeconds: 36000 maxTimeBetweenOutput: 3600 userMessageOnFailure: "Failed to build sdktool, check logs." @@ -142,38 +142,6 @@ instructions: property: target.arch equals_value: X86_64 - - type: Group - instructions: - - type: MakeDirectory - directory: "{{.AgentWorkingDir}}/build/qt_temp" - maxTimeInSeconds: 3600 - maxTimeBetweenOutput: 360 - userMessageOnFailure: "Failed to create folder qt_temp, check logs." - - type: ExecuteCommand - command: "curl --fail -L --retry 5 --retry-delay 5 -o {{.AgentWorkingDir}}\\build\\qt_temp\\Python38-win-x86.7z https://master.qt.io/development_releases/prebuilt/python/Python38-win-x86.7z" - maxTimeInSeconds: 3600 - maxTimeBetweenOutput: 360 - userMessageOnFailure: "Failed to download python package, check logs." - - type: ExecuteCommand - command: "C:\\Utils\\sevenzip\\7z.exe x -y {{.AgentWorkingDir}}\\build\\qt_temp\\Python38-win-x86.7z -o{{.AgentWorkingDir}}\\build\\qt_temp\\python" - maxTimeInSeconds: 3600 - maxTimeBetweenOutput: 360 - userMessageOnFailure: "Failed to extract python package, check logs." - - type: ExecuteCommand - command: "python -u {{.AgentWorkingDir}}\\qt-creator\\qt-creator\\scripts\\build.py --build-type {{.Env.QTC_BUILD_TYPE}} --src {{.AgentWorkingDir}}\\qt-creator\\qt-creator --build {{.AgentWorkingDir}}\\qt-creator\\qt-creator_build --python-path {{.AgentWorkingDir}}\\buid\\qt_temp\\python --no-qtcreator --no-zip" - maxTimeInSeconds: 36000 - maxTimeBetweenOutput: 3600 - userMessageOnFailure: "Failed to run build.py, check logs." - enable_if: - condition: and - conditions: - - condition: property - property: target.compiler - in_values: [MSVC2013, MSVC2015, MSVC2017, MSVC2019] - - condition: property - property: target.arch - equals_value: X86 - - type: UploadArtifact archiveDirectory: "{{.AgentWorkingDir}}/qt-creator/qt-creator_build/build" transferType: UploadModuleBuildArtifact diff --git a/coin/instructions/common_environment.yaml b/coin/instructions/common_environment.yaml index e2d11901180..22d53d03e2a 100644 --- a/coin/instructions/common_environment.yaml +++ b/coin/instructions/common_environment.yaml @@ -7,10 +7,10 @@ instructions: variableValue: "RelWithDebInfo" - type: EnvironmentVariable variableName: LLVM_BASE_URL - variableValue: https://ci-files02-hki.ci.qt.io/packages/jenkins/qtcreator_libclang/libclang-release_17.0.1-based + variableValue: https://ci-files02-hki.ci.qt.io/packages/jenkins/qtcreator_libclang/libclang-release_18.1.7-based - type: EnvironmentVariable variableName: QTC_QT_BASE_URL - variableValue: "https://ci-files02-hki.ci.qt.io/packages/jenkins/archive/qt/6.6/6.6.2-released/Qt" + variableValue: "https://ci-files02-hki.ci.qt.io/packages/jenkins/archive/qt/6.7/6.7.1-released/Qt" - type: EnvironmentVariable variableName: QTC_QT_MODULES variableValue: "qt5compat qtbase qtdeclarative qtimageformats qtquick3d qtquicktimeline qtserialport qtshadertools qtsvg qttools qttranslations qtwebengine" @@ -19,10 +19,10 @@ instructions: variableValue: 11.0 - type: EnvironmentVariable variableName: SDKTOOL_MACOSX_DEPLOYMENT_TARGET - variableValue: 10.14 + variableValue: 11.0 - type: EnvironmentVariable variableName: QTC_SDKTOOL_QT_BASE_URL - variableValue: "https://ci-files02-hki.ci.qt.io/packages/jenkins/archive/qt/5.15/5.15.2-final-released/latest/src/submodules/qtbase-everywhere-src-5.15.2" + variableValue: "https://ci-files02-hki.ci.qt.io/packages/jenkins/archive/qt/6.6/6.6.0-released/Qt/src/submodules/qtbase-everywhere-src-6.6.0" - type: Group instructions: - type: EnvironmentVariable @@ -59,6 +59,21 @@ instructions: condition: property property: target.os equals_value: MacOS + - type: Group + instructions: + - type: EnvironmentVariable + variableName: QTC_SCCACHE_C_OPTION + variableValue: --add-config=-DCMAKE_C_COMPILER_LAUNCHER=sccache + - type: EnvironmentVariable + variableName: QTC_SCCACHE_CXX_OPTION + variableValue: --add-config=-DCMAKE_CXX_COMPILER_LAUNCHER=sccache + - type: EnvironmentVariable + variableName: QTC_SCCACHE_ENABLE_OPTION + variableValue: --add-config=-DWITH_SCCACHE_SUPPORT=ON + enable_if: + condition: property + property: features + contains_value: Sccache - type: Group instructions: diff --git a/coin/instructions/provision.yaml b/coin/instructions/provision.yaml index 7b84c6e3baa..a5dad3955c6 100644 --- a/coin/instructions/provision.yaml +++ b/coin/instructions/provision.yaml @@ -20,7 +20,7 @@ instructions: maxTimeInSeconds: 600 maxTimeBetweenOutput: 600 project: qtsdk/tqtc-qtsdk - ref: master + ref: production directory: "build/tqtc-qtsdk" userMessageOnFailure: "Failed to install tqtc-qtsdk, check logs" - type: Group diff --git a/coin/module_config.yaml b/coin/module_config.yaml index 96428853f26..ecef22e379c 100644 --- a/coin/module_config.yaml +++ b/coin/module_config.yaml @@ -16,6 +16,9 @@ accept_configuration: - condition: property property: target.compiler equals_value: MSVC2019 + - condition: property + property: target.arch + not_equals_value: X86 - condition: and conditions: - condition: property diff --git a/coin/product_dependencies.yaml b/coin/product_dependencies.yaml index a658f8103be..9a7e164d2b3 100644 --- a/coin/product_dependencies.yaml +++ b/coin/product_dependencies.yaml @@ -1,4 +1,4 @@ dependencies: ../../qt/qt5.git: - ref: "6.6" + ref: "6.7" diff --git a/dist/changelog/changes-13.0.2.md b/dist/changelog/changes-13.0.2.md new file mode 100644 index 00000000000..629efc3d1b0 --- /dev/null +++ b/dist/changelog/changes-13.0.2.md @@ -0,0 +1,94 @@ +Qt Creator 13.0.2 +================= + +Qt Creator version 13.0.2 contains bug fixes. + +The most important changes are listed in this document. For a complete list of +changes, see the Git log for the Qt Creator sources that you can check out from +the public Git repository. For example: + + git clone git://code.qt.io/qt-creator/qt-creator.git + git log --cherry-pick --pretty=oneline v13.0.1..v13.0.2 + +General +------- + +* Fixed that the `-client` option could start a new Qt Creator instance instead + of using a running one (which affects for example version control operations) + ([QTCREATORBUG-30624](https://bugreports.qt.io/browse/QTCREATORBUG-30624)) + +Editing +------- + +* Fixed that closing files with the tool button didn't add an entry to the + navigation history + +### Widget Designer + +* Fixed that `Use Qt module name in #include-directive` used Qt 4 module names + ([QTCREATORBUG-30751](https://bugreports.qt.io/browse/QTCREATORBUG-30751)) + +### Copilot + +* Adapted to changes in the Copilot neovim plugin + +Projects +-------- + +### CMake + +* Fixed the environment macro expansion for Presets + +### Meson + +* Fixed a crash when selecting kits + ([QTCREATORBUG-30698](https://bugreports.qt.io/browse/QTCREATORBUG-30698)) + +Terminal +-------- + +* Fixed the handling of environment variables with an equal sign `=` in the + value + ([QTCREATORBUG-30844](https://bugreports.qt.io/browse/QTCREATORBUG-30844)) + +Version Control Systems +----------------------- + +### Git + +* Fixed a crash in `Instant Blame` when reloading externally modified files + ([QTCREATORBUG-30824](https://bugreports.qt.io/browse/QTCREATORBUG-30824)) + +Platforms +--------- + +### Windows + +* Fixed missing paths with `Add build library search path to PATH` for CMake + projects + ([QTCREATORBUG-30556](https://bugreports.qt.io/browse/QTCREATORBUG-30556), + [QTCREATORBUG-30827](https://bugreports.qt.io/browse/QTCREATORBUG-30827), + [QTCREATORBUG-30932](https://bugreports.qt.io/browse/QTCREATORBUG-30932)) + +### Android + +* Fixed a crash when re-connecting devices + ([QTCREATORBUG-30645](https://bugreports.qt.io/browse/QTCREATORBUG-30645), + [QTCREATORBUG-30770](https://bugreports.qt.io/browse/QTCREATORBUG-30770)) + +### Remote Linux + +* Fixed passing more than one argument to `rsync` + ([QTCREATORBUG-30795](https://bugreports.qt.io/browse/QTCREATORBUG-30795)) + +Credits for these changes go to: +-------------------------------- +Alessandro Portale +Christian Kandeler +Christian Stenger +Cristian Adam +David Schulz +Eike Ziller +Leena Miettinen +Marcus Tillmanns +Robert Löhning diff --git a/dist/changelog/changes-14.0.0.md b/dist/changelog/changes-14.0.0.md new file mode 100644 index 00000000000..3625940c757 --- /dev/null +++ b/dist/changelog/changes-14.0.0.md @@ -0,0 +1,379 @@ +Qt Creator 14 +============= + +Qt Creator version 14 contains bug fixes and new features. + +The most important changes are listed in this document. For a complete list of +changes, see the Git log for the Qt Creator sources that you can check out from +the public Git repository or view online at + + + +General +------- + +* Started work on supporting Lua based plugins (registering language servers, + actions, preferences, and wizards) + ([Documentation](https://doc-snapshots.qt.io/qtcreator-extending/lua-extensions.html)) +* Added a mode for managing extensions +* Added `Clear` and `Save Contents` to context menus of all output views +* Locator + * Added the option to show results relative to project root + ([QTCREATORBUG-29462](https://bugreports.qt.io/browse/QTCREATORBUG-29462)) + +Editing +------- + +* Changed the default behavior when files change on disk to + `Reload All Unchanged Editors` +* Made the search options session-specific + ([QTCREATORBUG-793](https://bugreports.qt.io/browse/QTCREATORBUG-793)) +* Added menus with the navigation history to the back and forward buttons + ([QTCREATORBUG-347](https://bugreports.qt.io/browse/QTCREATORBUG-347)) +* Added a highlight for the current view in case of multiple views + ([QTCREATORBUG-23654](https://bugreports.qt.io/browse/QTCREATORBUG-23654)) +* Added `Window > Reopen Last Closed Document` +* Added the option to open files in a text editor that were detected as binary + ([QTCREATORBUG-31116](https://bugreports.qt.io/browse/QTCREATORBUG-31116)) +* Fixed that changing a document's MIME type by renaming did not re-open it in + the new editor type when needed + ([QTCREATORBUG-30317](https://bugreports.qt.io/browse/QTCREATORBUG-30317)) +* Fixed that after hiding the editor in `Debug` mode, `Edit` mode always opened + when opening documents, even if an external editor window was available + ([QTCREATORBUG-30408](https://bugreports.qt.io/browse/QTCREATORBUG-30408)) +* Fixed that it wasn't possible to open a file in the text editor if it was + classified as a binary file format by the MIME database + ([QTCREATORBUG-31116](https://bugreports.qt.io/browse/QTCREATORBUG-31116)) +* Fixed the unindenting with backspace when multiple cursors are active + ([QTCREATORBUG-31158](https://bugreports.qt.io/browse/QTCREATORBUG-31158)) + +### C++ + +* Made C++ code model settings configurable per project +* Added a setting for the naming of include guards + ([QTCREATORBUG-25117](https://bugreports.qt.io/browse/QTCREATORBUG-25117)) +* Fixed indentation after function calls with subscript operator + ([QTCREATORBUG-29225](https://bugreports.qt.io/browse/QTCREATORBUG-29225)) +* Refactoring + * Added `Convert Function Call to Qt Meta-Method Invocation` + ([QTCREATORBUG-15972](https://bugreports.qt.io/browse/QTCREATORBUG-15972)) + * Added `Move Class to a Dedicated Set of Source Files` + ([QTCREATORBUG-12190](https://bugreports.qt.io/browse/QTCREATORBUG-12190)) + * Added `Re-order Member Function Definitions According to Declaration Order` + ([QTCREATORBUG-6199](https://bugreports.qt.io/browse/QTCREATORBUG-6199)) + * Added `Add Curly Braces` for do, while, and for loops + * Fixed issues with macros + ([QTCREATORBUG-10279](https://bugreports.qt.io/browse/QTCREATORBUG-10279)) + + [Documentation](https://doc.qt.io/qtcreator/creator-reference-cpp-quick-fixes.html) + +* Clangd + * Updated the prebuilt binaries to LLVM 18.1.7 + * Increased the minimum version to LLVM 17 + * Added the `Per-project index location` and `Per-session index location` + options in `Preferences` > `C++` > `Clangd` for setting the index location + for a project or session + ([QTCREATORBUG-27346](https://bugreports.qt.io/browse/QTCREATORBUG-27346)) + * Added the `Update dependent sources` option to make re-parsing source files + while editing header files optional + ([QTCREATORBUG-29943](https://bugreports.qt.io/browse/QTCREATORBUG-29943)) + * Fixed the handling of system headers + ([QTCREATORBUG-30474](https://bugreports.qt.io/browse/QTCREATORBUG-30474)) +* Built-in + * Added the `Enable indexing` option in `Preferences` > `C++` > `Code Model` + to turn off the built-in indexer + ([QTCREATORBUG-29147](https://bugreports.qt.io/browse/QTCREATORBUG-29147)) + * Added the `Statement Macros` field in `Preferences` > `C++` > `Code Style` + for macros that the indenter interprets as complete statements that don't + require a semicolon at the end + ([QTCREATORBUG-13640](https://bugreports.qt.io/browse/QTCREATORBUG-13640), + [QTCREATORBUG-15069](https://bugreports.qt.io/browse/QTCREATORBUG-15069), + [QTCREATORBUG-18789](https://bugreports.qt.io/browse/QTCREATORBUG-18789)) + ([Clang Format Documentation](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#statementmacros)) + * Added indentation support for `try-catch` statements + ([QTCREATORBUG-29452](https://bugreports.qt.io/browse/QTCREATORBUG-29452)) + +### QML + +* Improved support for enums + ([QTCREATORBUG-19226](https://bugreports.qt.io/browse/QTCREATORBUG-19226)) +* Added `Qt Design Studio` to `Open With` for `.ui.qml` files + ([Documentation](https://doc.qt.io/qtcreator/creator-quick-ui-forms.html)) +* Fixed that the color preview did not work on named colors + ([QTCREATORBUG-30594](https://bugreports.qt.io/browse/QTCREATORBUG-30594)) +* Language Server + * Switched on by default for Qt 6.8 and later + * Added an option for generating `qmlls.ini` files for CMake projects in + `Preferences` > `Qt Quick`> `QML/JS Editing` + ([QTCREATORBUG-30394](https://bugreports.qt.io/browse/QTCREATORBUG-30394)) + ([Qt Documentation](https://doc.qt.io/qt-6/cmake-variable-qt-qml-generate-qmlls-ini.html)) + * Fixed that tool tips from the built-in model were shown instead of tool tips + from the server + + [Documentation](https://doc.qt.io/qtcreator/creator-how-to-use-qml-language-server.html) + +### Python + +* Added options for updating Python Language Server + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-language-servers.html)) + +### Language Server Protocol + +* Added support for `SymbolTag` + ([Protocol Documentation](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag)) +* Added support for type hierarchy + ([QTCREATORBUG-28116](https://bugreports.qt.io/browse/QTCREATORBUG-28116)) + +### Compiler Explorer + +* Added a wizard template for code that uses Qt to `File`> `New File`> + `Compiler Explorer` + [Documentation](https://doc.qt.io/qtcreator/creator-how-to-create-compiler-explorer-sessions.html) + +### Markdown + +* Fixed the navigation history + +### Models + +* Added more visual attributes for relations +* Added support for linked files in model element properties +* Added support for custom images in model element properties + +([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-how-to-create-models.html)) + +### SCXML + +* Added visualization of conditions on transitions by using square brackets: `[]` + ([QTCREATORBUG-21946](https://bugreports.qt.io/browse/QTCREATORBUG-21946)) + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-scxml.html)) + +Projects +-------- + +* Added the `Hide Inactive Kits`/`Show All Kits` button to hide inactive kits + from the list in the `Projects` mode +* Added support for user comments in the environment editor + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-how-to-edit-environment-settings.html)) +* Added the setting `Time to wait before force-stopping applications` + ([QTCREATORBUG-31025](https://bugreports.qt.io/browse/QTCREATORBUG-31025)) +* Fixed the parsing of file links when color was used for the output + ([QTCREATORBUG-30774](https://bugreports.qt.io/browse/QTCREATORBUG-30774)) +* Fixed that the column information was not used when opening files from links + in issues +* Fixed changing the case of file names on case-insensitive file systems + ([QTCREATORBUG-30846](https://bugreports.qt.io/browse/QTCREATORBUG-30846)) +* Fixed that Qt Creator variables were not expanded for the `Copy File` + deploy step + ([QTCREATORBUG-30821](https://bugreports.qt.io/browse/QTCREATORBUG-30821)) +* Fixed duplicate entries in the variable chooser for the build directory + ([QTCREATORBUG-31183](https://bugreports.qt.io/browse/QTCREATORBUG-31183)) + +### CMake + +* Made CMake settings configurable per project +* Implemented `Open Online Documentation` for CMake documentation +* Added `Clear CMake Configuration` to the context menu in the `Projects` view + ([QTCREATORBUG-24658](https://bugreports.qt.io/browse/QTCREATORBUG-24658)) +* Added support for the `CROSSCOMPILING_EMULATOR` target property + ([QTCREATORBUG-29880](https://bugreports.qt.io/browse/QTCREATORBUG-29880)) + ([CMake Documentation](https://cmake.org/cmake/help/latest/prop_tgt/CROSSCOMPILING_EMULATOR.html#crosscompiling-emulator)) +* Fixed that the package manager auto-setup files were not removed with + `Clear CMake Configuration` + ([QTCREATORBUG-30771](https://bugreports.qt.io/browse/QTCREATORBUG-30771)) +* Fixed that files generated by the Qt QML CMake API were not filtered as + generated files + ([QTCREATORBUG-29631](https://bugreports.qt.io/browse/QTCREATORBUG-29631)) +* Fixed a crash when triggering `Follow Symbol` in a CMake file that does not + belong to a project + ([QTCREATORBUG-31077](https://bugreports.qt.io/browse/QTCREATORBUG-31077)) +* Fixed that multiple build configurations of the same type used the same + build directory + ([QTCREATORBUG-26066](https://bugreports.qt.io/browse/QTCREATORBUG-26066)) +* Fixed an issue with adding new files when file globs are used in the CMake + files + ([QTCREATORBUG-30445](https://bugreports.qt.io/browse/QTCREATORBUG-30445)) +* Fixed the default CMake generator for kits if Ninja is not installed + ([QTCREATORBUG-31129](https://bugreports.qt.io/browse/QTCREATORBUG-31129)) +* Fixed that duplicate `CMAKE_CXX_COMPILER` entries could be used + ([QTCREATORBUG-27005](https://bugreports.qt.io/browse/QTCREATORBUG-27005)) +* Presets + * Made CMake settings configurable + ([QTCREATORBUG-25972](https://bugreports.qt.io/browse/QTCREATORBUG-25972), + [QTCREATORBUG-29559](https://bugreports.qt.io/browse/QTCREATORBUG-29559), + [QTCREATORBUG-30385](https://bugreports.qt.io/browse/QTCREATORBUG-30385)) + * Made it possible to register debuggers + ([QTCREATORBUG-30836](https://bugreports.qt.io/browse/QTCREATORBUG-30836)) + * Added support for custom build types + ([QTCREATORBUG-30014](https://bugreports.qt.io/browse/QTCREATORBUG-30014)) + + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-build-settings-cmake-presets.html)) + +### Workspace + +* Added `File > Open Workspace` for opening a directory as a project. A project + file `.qtcreator/project.json` in the directory is used to set a name and + file exclusion filters. + +Debugging +--------- + +### C++ + +* Improved performance +* GDB + * Added a setting for `debuginfod` + ([QTCREATORBUG-28868](https://bugreports.qt.io/browse/QTCREATORBUG-28868)) +* CDB + * Fixed the display type of `HRESULT` + ([QTCREATORBUG-30574](https://bugreports.qt.io/browse/QTCREATORBUG-30574)) + +Analyzer +-------- + +### Clang + +* Added the option to `Suppress Diagnostics Inline` + ([QTCREATORBUG-24847](https://bugreports.qt.io/browse/QTCREATORBUG-24847)) + ([Clazy Documentation](https://github.com/KDE/clazy?tab=readme-ov-file#reducing-warning-noise)) + ([clang-tidy Documentation](https://clang.llvm.org/extra/clang-tidy/#suppressing-undesired-diagnostics)) + +### Axivion + +* Added the `Add` and `Remove` buttons to `Preferences` > `Axivion` for + registering multiple servers + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-preferences-axivion.html)) + +### Cppcheck + +* Fixed that Cppcheck was not working until selecting `Apply` in the settings + ([QTCREATORBUG-28951](https://bugreports.qt.io/browse/QTCREATORBUG-28951), + [QTCREATORBUG-30615](https://bugreports.qt.io/browse/QTCREATORBUG-30615)) + +Terminal +-------- + +* Fixed resizing on Windows + ([QTCREATORBUG-30558](https://bugreports.qt.io/browse/QTCREATORBUG-30558)) + +Version Control Systems +----------------------- + +### Git + +* Fixed that email and author mapping was not used for logs and showing changes + +Test Integration +---------------- + +* Made the test timeout optional in `Preferences` > `Testing` > `General` + ([QTCREATORBUG-30668](https://bugreports.qt.io/browse/QTCREATORBUG-30668)) + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-preferences-testing.html)) +* Added the project specific `Limit Files to Path Patterns` option in `Projects` > + `Project Settings` > `Testing` for restricting the search for tests + ([Documentation](https://doc-snapshots.qt.io/qtcreator-14.0/creator-how-to-limit-files-to-path-patterns.html)) + +### Qt Test + +* Fixed the order of test execution + ([QTCREATORBUG-30670](https://bugreports.qt.io/browse/QTCREATORBUG-30670)) + +Platforms +--------- + +### Linux + +* Adapted the default theme to the system theme +* Fixed issues with light themes on dark system themes + ([QTCREATORBUG-18281](https://bugreports.qt.io/browse/QTCREATORBUG-18281), + [QTCREATORBUG-20889](https://bugreports.qt.io/browse/QTCREATORBUG-20889), + [QTCREATORBUG-26817](https://bugreports.qt.io/browse/QTCREATORBUG-26817), + [QTCREATORBUG-28589](https://bugreports.qt.io/browse/QTCREATORBUG-28589), + [QTCREATORBUG-30138](https://bugreports.qt.io/browse/QTCREATORBUG-30138)) +* Fixed that recent projects on unavailable remote devices regularly + froze Qt Creator + ([QTCREATORBUG-30681](https://bugreports.qt.io/browse/QTCREATORBUG-30681)) + +### Android + +* Added support for creating `android-desktop` devices in `Preferences` > + `Devices` > `Add` > `Android Device` > `Device definition` +* Added support for `namespace` in `build.gradle` + ([QTBUG-106907](https://bugreports.qt.io/browse/QTBUG-106907)) +* Fixed that errors when creating AVDs were not visible to the user + ([QTCREATORBUG-30852](https://bugreports.qt.io/browse/QTCREATORBUG-30852)) + +### iOS + +* Removed Simulator management from the preferences. Use the + `Devices and Simulators` window in Xcode instead. +* Fixed that starting the debugger could be slow for iOS < 17 + ([QTCREATORBUG-31044](https://bugreports.qt.io/browse/QTCREATORBUG-31044)) + +### Remote Linux + +* Added the `Use SSH port forwarding for debugging` option in `Preferences` > + `Devices` for a `Remote Linux Device` +* Improved the performance of the generic deployment method +* Fixed that the file size check that is performed before parsing C++ files + could freeze Qt Creator until finished for remote projects + +### Qt Application Manager + +* Added support for the `perf` profiler + +### Bare Metal + +* Fixed issues with Qbs and the IAR toolchain + ([QTCREATORBUG-24040](https://bugreports.qt.io/browse/QTCREATORBUG-24040)) + +Credits for these changes go to: +-------------------------------- +Ahmad Samir +Aleksei German +Alessandro Portale +Alexander Drozdov +Ali Kianian +Andre Hartmann +André Pönitz +Artem Sokolovskii +Assam Boudjelthia +BogDan Vatra +Brook Cronin +Burak Hancerli +Christian Kandeler +Christian Stenger +Cristian Adam +David Schulz +Dominik Holland +Eike Ziller +Esa Törmänen +Henning Gruendl +Jaroslaw Kobus +Jiajie Chen +Jochen Becher +Johanna Vanhatapio +Jussi Witick +Knud Dollereder +Leena Miettinen +Mahmoud Badri +Marco Bubke +Marcus Tillmanns +Mathias Hasselmann +Mats Honkamaa +Michael Weghorn +Miikka Heikkinen +Orgad Shaneh +Pranta Dastider +Ralf Habacker +Robert Löhning +Sami Shalayel +Semih Yavuz +Sergey Silin +Shrief Gabr +Teea Poldsam +Thiago Macieira +Thomas Hartmann +Tim Jenßen +Vikas Pachdha +Xavier Besson diff --git a/dist/changelog/template.md b/dist/changelog/template.md new file mode 100644 index 00000000000..66e94906aea --- /dev/null +++ b/dist/changelog/template.md @@ -0,0 +1,135 @@ +Qt Creator 13 +============= + +Qt Creator version 13 contains bug fixes and new features. + +The most important changes are listed in this document. For a complete list of +changes, see the Git log for the Qt Creator sources that you can check out from +the public Git repository. For example: + + git clone git://code.qt.io/qt-creator/qt-creator.git + git log --cherry-pick --pretty=oneline origin/12.0..v13.0.0 + +New plugins +----------- + +General +------- + +Help +---- + +Editing +------- + +### C++ + +### QML + +### Python + +### Language Server Protocol + +### Widget Designer + +### Copilot + +### Compiler Explorer + +### TODO + +### Markdown + +### Images + +### Models + +### SCXML + +### Binary Files + +Projects +-------- + +### CMake + +### qmake + +### Qbs + +### Python + +### Workspace + +### vcpkg + +### Qt Safe Renderer + +Debugging +--------- + +### C++ + +### QML + +### Debug Adapter Protocol + +Analyzer +-------- + +### Clang + +### Axivion + +### CTF Visualizer + +### Cppcheck + +Terminal +-------- + +Version Control Systems +----------------------- + +### Git + +### CVS + +Test Integration +---------------- + +### Qt Test + +### Catch2 + +### CTest + +Platforms +--------- + +### Windows + +### Linux + +### macOS + +### Android + +### iOS + +### Remote Linux + +### Docker + +### Boot to Qt + +### MCU + +### Qt Application Manager + +### QNX + +### Bare Metal + +Credits for these changes go to: +-------------------------------- diff --git a/dist/copyright_template.txt b/dist/copyright_template.txt index 974656016df..efdc4bcbe8d 100644 --- a/dist/copyright_template.txt +++ b/dist/copyright_template.txt @@ -1,3 +1,3 @@ -// Copyright (C) 2023 The Qt Company Ltd. +// Copyright (C) %{CurrentDate:yyyy} The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index f78240e4fb0..1100fc0733a 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -25,11 +25,19 @@ function(_find_all_includes _ret_includes _ret_framework_paths) # framework path if (APPLE) - # version-less target Qt::Core is an interface library that links to QtX::Core - get_target_property(_qt_core Qt::Core INTERFACE_LINK_LIBRARIES) - get_target_property(_qt_target ${_qt_core} LOCATION) # /QtCore.framework/QtCore - get_filename_component(_qt_loc "${_qt_target}" DIRECTORY) - set("${_ret_framework_paths}" "${_qt_loc}/.." PARENT_SCOPE) + get_target_property(_qt_type Qt::Core TYPE) + if ("${_qt_type}" STREQUAL "INTERFACE_LIBRARY") + # version-less target Qt::Core is an interface library that links to QtX::Core + get_target_property(_qt_core Qt::Core INTERFACE_LINK_LIBRARIES) + else() + set(_qt_core "Qt::Core") + endif() + get_target_property(_qt_target ${_qt_core} LOCATION) + # eg /QtCore.framework/QtCore + # or /QtCore.framework/Versions/A/QtCore + # cut off /QtCore.framework/* + string(REGEX REPLACE "/QtCore.framework/.*" "" _qt_loc "${_qt_target}") + set("${_ret_framework_paths}" "${_qt_loc}" PARENT_SCOPE) endif() endfunction() @@ -67,8 +75,14 @@ if(WITH_ONLINE_DOCS) _add_doc(${IDE_DOC_FILE_ONLINE} "qtcreatordev/qtcreator-dev-online.qdocconf") endif() +if (BUILD_DOCS_BY_DEFAULT) +set(EXCLUDE_DOCS_FROM_ALL "") +else() +set(EXCLUDE_DOCS_FROM_ALL "EXCLUDE_FROM_ALL") +endif() + install(DIRECTORY config DESTINATION ${IDE_HEADER_INSTALL_PATH}/doc COMPONENT Devel - EXCLUDE_FROM_ALL + ${EXCLUDE_DOCS_FROM_ALL} ) diff --git a/doc/config/macros.qdocconf b/doc/config/macros.qdocconf index 46e4e0b20c2..751bc80ab71 100644 --- a/doc/config/macros.qdocconf +++ b/doc/config/macros.qdocconf @@ -16,6 +16,7 @@ macro.macos = "macOS" macro.note = "\\b{Note:}" macro.oslash.HTML = "ø" macro.ouml.HTML = "ö" +macro.B2Q = "Boot to Qt" macro.Q3DS = "Qt 3D Studio" macro.QA = "Qt Assistant" macro.QAC = "Qt Academy" @@ -26,7 +27,7 @@ macro.QBSK = "Qt Bridge for Sketch" macro.QBF = "Qt Bridge for Figma" macro.QC = "$IDE_DISPLAY_NAME" macro.QCE = "$IDE_DISPLAY_NAME Enterprise" -macro.QD = "Qt Designer" +macro.QD = "Qt Widgets Designer" macro.QDS = "Qt Design Studio" macro.QQEM = "Qt Quick Effect Maker" macro.QDV = "Qt Design Viewer" diff --git a/doc/qtcreator/config/qtcreator-project.qdocconf b/doc/qtcreator/config/qtcreator-project.qdocconf index fd5afe4e314..5e36e0cfc05 100644 --- a/doc/qtcreator/config/qtcreator-project.qdocconf +++ b/doc/qtcreator/config/qtcreator-project.qdocconf @@ -1,5 +1,5 @@ project = qtcreator -description = "$IDE_DISPLAY_NAME Manual" +description = "$IDE_DISPLAY_NAME Documentation" url = http://doc.qt.io/$IDE_ID #Words to ignore for auto-linking @@ -57,14 +57,14 @@ qhp.projects = QtCreator qhp.QtCreator.file = qtcreator.qhp qhp.QtCreator.namespace = org.qt-project.qtcreator.$QTC_VERSION_TAG qhp.QtCreator.virtualFolder = doc -qhp.QtCreator.indexTitle = $IDE_DISPLAY_NAME Manual $QTC_VERSION +qhp.QtCreator.indexTitle = $IDE_DISPLAY_NAME Documentation $QTC_VERSION qhp.QtCreator.filterAttributes = $IDE_ID $QTC_VERSION qhp.QtCreator.customFilters.QtCreator.name = $IDE_DISPLAY_NAME $QTC_VERSION qhp.QtCreator.customFilters.QtCreator.filterAttributes = $IDE_ID $QTC_VERSION qhp.QtCreator.indexRoot = qhp.QtCreator.subprojects = manual -qhp.QtCreator.subprojects.manual.title = $IDE_DISPLAY_NAME Manual +qhp.QtCreator.subprojects.manual.title = $IDE_DISPLAY_NAME Documentation qhp.QtCreator.subprojects.manual.indexTitle = All Topics qhp.QtCreator.subprojects.manual.type = manual @@ -73,10 +73,10 @@ qhp.QtCreator.subprojects.manual.type = manual macro.see = "\\sa" macro.function = "\\fn" -navigation.landingpage = "$IDE_DISPLAY_NAME Manual" +navigation.landingpage = "$IDE_DISPLAY_NAME Documentation" # Auto-generate navigation linking based on "All Topics": navigation.toctitles = "All Topics" navigation.toctitles.inclusive = false -buildversion = "$IDE_DISPLAY_NAME Manual $QTC_VERSION" +buildversion = "$IDE_DISPLAY_NAME $QTC_VERSION" diff --git a/doc/qtcreator/config/style/qt5-sidebar.html b/doc/qtcreator/config/style/qt5-sidebar.html index cf020e31ca0..340da73317c 100644 --- a/doc/qtcreator/config/style/qt5-sidebar.html +++ b/doc/qtcreator/config/style/qt5-sidebar.html @@ -1,24 +1,26 @@ + @@ -77,12 +79,12 @@
  • Technical Support
  • Version Control Systems
  • Analyzers
  • -
  • Build Configurations
  • Build Systems
  • +
  • Debuggers
  • +
  • Devices
  • Editors
  • Platforms
  • Preferences
  • -
  • Run Configurations
  • UI Design
  • Views
  • See All
  • diff --git a/doc/qtcreator/examples/textfinder/CMakeLists.txt b/doc/qtcreator/examples/textfinder/CMakeLists.txt index a00ccd856b4..d0e3130d2f7 100644 --- a/doc/qtcreator/examples/textfinder/CMakeLists.txt +++ b/doc/qtcreator/examples/textfinder/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(TextFinder VERSION 0.1 LANGUAGES CXX) diff --git a/doc/qtcreator/images/front-advanced.png b/doc/qtcreator/images/front-advanced.png deleted file mode 100644 index 99422ed74f0..00000000000 Binary files a/doc/qtcreator/images/front-advanced.png and /dev/null differ diff --git a/doc/qtcreator/images/front-coding.png b/doc/qtcreator/images/front-coding.png deleted file mode 100644 index b39a8c33db0..00000000000 Binary files a/doc/qtcreator/images/front-coding.png and /dev/null differ diff --git a/doc/qtcreator/images/front-gs.png b/doc/qtcreator/images/front-gs.png deleted file mode 100644 index b529411a7df..00000000000 Binary files a/doc/qtcreator/images/front-gs.png and /dev/null differ diff --git a/doc/qtcreator/images/front-help.png b/doc/qtcreator/images/front-help.png deleted file mode 100644 index f9640f48634..00000000000 Binary files a/doc/qtcreator/images/front-help.png and /dev/null differ diff --git a/doc/qtcreator/images/front-preview.png b/doc/qtcreator/images/front-preview.png deleted file mode 100644 index 9cb894c183e..00000000000 Binary files a/doc/qtcreator/images/front-preview.png and /dev/null differ diff --git a/doc/qtcreator/images/front-ui.png b/doc/qtcreator/images/front-ui.png deleted file mode 100644 index ee966bffc11..00000000000 Binary files a/doc/qtcreator/images/front-ui.png and /dev/null differ diff --git a/doc/qtcreator/images/icons/api-reference.png b/doc/qtcreator/images/icons/api-reference.png new file mode 100644 index 00000000000..543d7d1fa3e Binary files /dev/null and b/doc/qtcreator/images/icons/api-reference.png differ diff --git a/doc/qtcreator/images/icons/app-development.png b/doc/qtcreator/images/icons/app-development.png new file mode 100644 index 00000000000..b3333b87c18 Binary files /dev/null and b/doc/qtcreator/images/icons/app-development.png differ diff --git a/doc/qtcreator/images/icons/build-32x32.png b/doc/qtcreator/images/icons/build-32x32.png new file mode 100644 index 00000000000..d6e045b7765 Binary files /dev/null and b/doc/qtcreator/images/icons/build-32x32.png differ diff --git a/doc/qtcreator/images/icons/demo-32x32.png b/doc/qtcreator/images/icons/demo-32x32.png new file mode 100644 index 00000000000..5c42b6f6c3a Binary files /dev/null and b/doc/qtcreator/images/icons/demo-32x32.png differ diff --git a/doc/qtcreator/images/icons/getting-started.png b/doc/qtcreator/images/icons/getting-started.png new file mode 100644 index 00000000000..36b37d47404 Binary files /dev/null and b/doc/qtcreator/images/icons/getting-started.png differ diff --git a/doc/qtcreator/images/icons/ide.png b/doc/qtcreator/images/icons/ide.png new file mode 100644 index 00000000000..dbdb0ef7e0e Binary files /dev/null and b/doc/qtcreator/images/icons/ide.png differ diff --git a/doc/qtcreator/images/icons/installation.png b/doc/qtcreator/images/icons/installation.png new file mode 100644 index 00000000000..6dc6a8e697b Binary files /dev/null and b/doc/qtcreator/images/icons/installation.png differ diff --git a/doc/qtcreator/images/icons/platform-and-toolchain.png b/doc/qtcreator/images/icons/platform-and-toolchain.png new file mode 100644 index 00000000000..7f8a6be7f22 Binary files /dev/null and b/doc/qtcreator/images/icons/platform-and-toolchain.png differ diff --git a/doc/qtcreator/images/icons/settings-32x32.png b/doc/qtcreator/images/icons/settings-32x32.png new file mode 100644 index 00000000000..5c7202a30a6 Binary files /dev/null and b/doc/qtcreator/images/icons/settings-32x32.png differ diff --git a/doc/qtcreator/images/icons/tutorials.png b/doc/qtcreator/images/icons/tutorials.png new file mode 100644 index 00000000000..7044a2625a1 Binary files /dev/null and b/doc/qtcreator/images/icons/tutorials.png differ diff --git a/doc/qtcreator/images/numbers/01.png b/doc/qtcreator/images/numbers/01.png index 4c8b10b26c5..1190a99cc6d 100644 Binary files a/doc/qtcreator/images/numbers/01.png and b/doc/qtcreator/images/numbers/01.png differ diff --git a/doc/qtcreator/images/numbers/02.png b/doc/qtcreator/images/numbers/02.png index df24ef459e6..9ae3bae02cd 100644 Binary files a/doc/qtcreator/images/numbers/02.png and b/doc/qtcreator/images/numbers/02.png differ diff --git a/doc/qtcreator/images/numbers/03.png b/doc/qtcreator/images/numbers/03.png index 525bd926990..9d29cb93fff 100644 Binary files a/doc/qtcreator/images/numbers/03.png and b/doc/qtcreator/images/numbers/03.png differ diff --git a/doc/qtcreator/images/numbers/04.png b/doc/qtcreator/images/numbers/04.png index 6c6b489d5c9..206e9294629 100644 Binary files a/doc/qtcreator/images/numbers/04.png and b/doc/qtcreator/images/numbers/04.png differ diff --git a/doc/qtcreator/images/numbers/05.png b/doc/qtcreator/images/numbers/05.png index 6d831b204de..6baa13123d7 100644 Binary files a/doc/qtcreator/images/numbers/05.png and b/doc/qtcreator/images/numbers/05.png differ diff --git a/doc/qtcreator/images/numbers/06.png b/doc/qtcreator/images/numbers/06.png index b7adb30f960..4f398dc2633 100644 Binary files a/doc/qtcreator/images/numbers/06.png and b/doc/qtcreator/images/numbers/06.png differ diff --git a/doc/qtcreator/images/numbers/07.png b/doc/qtcreator/images/numbers/07.png index a160038f0eb..c71842702f9 100644 Binary files a/doc/qtcreator/images/numbers/07.png and b/doc/qtcreator/images/numbers/07.png differ diff --git a/doc/qtcreator/images/numbers/08.png b/doc/qtcreator/images/numbers/08.png index 6ccf88b7eb8..f0d894c106d 100644 Binary files a/doc/qtcreator/images/numbers/08.png and b/doc/qtcreator/images/numbers/08.png differ diff --git a/doc/qtcreator/images/numbers/09.png b/doc/qtcreator/images/numbers/09.png index 0ed195b154a..0bf3bc7fb16 100644 Binary files a/doc/qtcreator/images/numbers/09.png and b/doc/qtcreator/images/numbers/09.png differ diff --git a/doc/qtcreator/images/numbers/10.png b/doc/qtcreator/images/numbers/10.png index 8c468d99989..bec47399a82 100644 Binary files a/doc/qtcreator/images/numbers/10.png and b/doc/qtcreator/images/numbers/10.png differ diff --git a/doc/qtcreator/images/qtcreator-breakdown.png b/doc/qtcreator/images/qtcreator-breakdown.png deleted file mode 100644 index a226f9f2542..00000000000 Binary files a/doc/qtcreator/images/qtcreator-breakdown.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-build-environment.webp b/doc/qtcreator/images/qtcreator-build-environment.webp index 48bf4753d24..9cc53e85148 100644 Binary files a/doc/qtcreator/images/qtcreator-build-environment.webp and b/doc/qtcreator/images/qtcreator-build-environment.webp differ diff --git a/doc/qtcreator/images/qtcreator-clang-tidy-view.webp b/doc/qtcreator/images/qtcreator-clang-tidy-view.webp index 1a914a683a8..46be17b10ea 100644 Binary files a/doc/qtcreator/images/qtcreator-clang-tidy-view.webp and b/doc/qtcreator/images/qtcreator-clang-tidy-view.webp differ diff --git a/doc/qtcreator/images/qtcreator-clang-tools-filter-diagnostics.webp b/doc/qtcreator/images/qtcreator-clang-tools-filter-diagnostics.webp new file mode 100644 index 00000000000..bfb3b7001fa Binary files /dev/null and b/doc/qtcreator/images/qtcreator-clang-tools-filter-diagnostics.webp differ diff --git a/doc/qtcreator/images/qtcreator-code-style-built-in-indenter.webp b/doc/qtcreator/images/qtcreator-code-style-built-in-indenter.webp index f8eaa1dac52..eb85b20033f 100644 Binary files a/doc/qtcreator/images/qtcreator-code-style-built-in-indenter.webp and b/doc/qtcreator/images/qtcreator-code-style-built-in-indenter.webp differ diff --git a/doc/qtcreator/images/qtcreator-context-sensitive-help.png b/doc/qtcreator/images/qtcreator-context-sensitive-help.png deleted file mode 100644 index b6c7679164b..00000000000 Binary files a/doc/qtcreator/images/qtcreator-context-sensitive-help.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-context-sensitive-help.webp b/doc/qtcreator/images/qtcreator-context-sensitive-help.webp new file mode 100644 index 00000000000..81822ab856f Binary files /dev/null and b/doc/qtcreator/images/qtcreator-context-sensitive-help.webp differ diff --git a/doc/qtcreator/images/qtcreator-custom-wizard.webp b/doc/qtcreator/images/qtcreator-custom-wizard.webp index 6e0f5ddc71d..6a9d75073a0 100644 Binary files a/doc/qtcreator/images/qtcreator-custom-wizard.webp and b/doc/qtcreator/images/qtcreator-custom-wizard.webp differ diff --git a/doc/qtcreator/images/qtcreator-devices-qnx.webp b/doc/qtcreator/images/qtcreator-devices-qnx.webp new file mode 100644 index 00000000000..a431e883b27 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-devices-qnx.webp differ diff --git a/doc/qtcreator/images/qtcreator-edit-cmake-configuration-self-built-qt.webp b/doc/qtcreator/images/qtcreator-edit-cmake-configuration-self-built-qt.webp new file mode 100644 index 00000000000..820461039e9 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-edit-cmake-configuration-self-built-qt.webp differ diff --git a/doc/qtcreator/images/qtcreator-edit-environment.webp b/doc/qtcreator/images/qtcreator-edit-environment.webp index f68eb52540e..55e04cc70c1 100644 Binary files a/doc/qtcreator/images/qtcreator-edit-environment.webp and b/doc/qtcreator/images/qtcreator-edit-environment.webp differ diff --git a/doc/qtcreator/images/qtcreator-extension-mode.webp b/doc/qtcreator/images/qtcreator-extension-mode.webp new file mode 100644 index 00000000000..8a880f3c444 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-extension-mode.webp differ 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 00000000000..f36ac701442 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-heob-in-terminal.webp differ diff --git a/doc/qtcreator/images/qtcreator-heob.png b/doc/qtcreator/images/qtcreator-heob.png deleted file mode 100644 index c3b75ec8479..00000000000 Binary files a/doc/qtcreator/images/qtcreator-heob.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-ios-preferences.png b/doc/qtcreator/images/qtcreator-ios-preferences.png deleted file mode 100644 index 935a528d6cb..00000000000 Binary files a/doc/qtcreator/images/qtcreator-ios-preferences.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-kit-selector-devices.webp b/doc/qtcreator/images/qtcreator-kit-selector-devices.webp index 7cb2b74e82d..b3a7afa7a55 100644 Binary files a/doc/qtcreator/images/qtcreator-kit-selector-devices.webp and b/doc/qtcreator/images/qtcreator-kit-selector-devices.webp differ diff --git a/doc/qtcreator/images/qtcreator-locator-customize.webp b/doc/qtcreator/images/qtcreator-locator-customize.webp index 5a6d4e90d34..34b96a8d6fb 100644 Binary files a/doc/qtcreator/images/qtcreator-locator-customize.webp and b/doc/qtcreator/images/qtcreator-locator-customize.webp differ diff --git a/doc/qtcreator/images/qtcreator-mode-selector.png b/doc/qtcreator/images/qtcreator-mode-selector.png deleted file mode 100644 index e82047cf859..00000000000 Binary files a/doc/qtcreator/images/qtcreator-mode-selector.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-mode-selector.webp b/doc/qtcreator/images/qtcreator-mode-selector.webp new file mode 100644 index 00000000000..54075491e3a Binary files /dev/null and b/doc/qtcreator/images/qtcreator-mode-selector.webp differ diff --git a/doc/qtcreator/images/qtcreator-model-editor-component-diagram.webp b/doc/qtcreator/images/qtcreator-model-editor-component-diagram.webp index e28a94e0a2a..ecd5a013df1 100644 Binary files a/doc/qtcreator/images/qtcreator-model-editor-component-diagram.webp and b/doc/qtcreator/images/qtcreator-model-editor-component-diagram.webp differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor-classes.png b/doc/qtcreator/images/qtcreator-modeleditor-classes.png deleted file mode 100644 index c5747416db2..00000000000 Binary files a/doc/qtcreator/images/qtcreator-modeleditor-classes.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor-classes.webp b/doc/qtcreator/images/qtcreator-modeleditor-classes.webp new file mode 100644 index 00000000000..fcdec4f6452 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-modeleditor-classes.webp differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor-packages.png b/doc/qtcreator/images/qtcreator-modeleditor-packages.png deleted file mode 100644 index 3884886e19f..00000000000 Binary files a/doc/qtcreator/images/qtcreator-modeleditor-packages.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor-packages.webp b/doc/qtcreator/images/qtcreator-modeleditor-packages.webp new file mode 100644 index 00000000000..c9e676207ed Binary files /dev/null and b/doc/qtcreator/images/qtcreator-modeleditor-packages.webp differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor.png b/doc/qtcreator/images/qtcreator-modeleditor.png deleted file mode 100644 index 9f46b26ac62..00000000000 Binary files a/doc/qtcreator/images/qtcreator-modeleditor.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-modeleditor.webp b/doc/qtcreator/images/qtcreator-modeleditor.webp new file mode 100644 index 00000000000..aeaccae16b6 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-modeleditor.webp differ diff --git a/doc/qtcreator/images/qtcreator-move-class-to-separate-files.webp b/doc/qtcreator/images/qtcreator-move-class-to-separate-files.webp new file mode 100644 index 00000000000..5a9540c25e9 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-move-class-to-separate-files.webp differ diff --git a/doc/qtcreator/images/qtcreator-new-project-compiler-explorer.webp b/doc/qtcreator/images/qtcreator-new-project-compiler-explorer.webp new file mode 100644 index 00000000000..3744f4100fa Binary files /dev/null and b/doc/qtcreator/images/qtcreator-new-project-compiler-explorer.webp differ diff --git a/doc/qtcreator/images/qtcreator-options-android-main.png b/doc/qtcreator/images/qtcreator-options-android-main.png deleted file mode 100644 index 5ecea57d998..00000000000 Binary files a/doc/qtcreator/images/qtcreator-options-android-main.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-options-android-sdk-tools.png b/doc/qtcreator/images/qtcreator-options-android-sdk-tools.png deleted file mode 100644 index f3057ce0bca..00000000000 Binary files a/doc/qtcreator/images/qtcreator-options-android-sdk-tools.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-output-panes-taskbar.webp b/doc/qtcreator/images/qtcreator-output-panes-taskbar.webp index 7801e26ff8f..a53aebdb02b 100644 Binary files a/doc/qtcreator/images/qtcreator-output-panes-taskbar.webp and b/doc/qtcreator/images/qtcreator-output-panes-taskbar.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-android.webp b/doc/qtcreator/images/qtcreator-preferences-android.webp new file mode 100644 index 00000000000..3c6e909df2e Binary files /dev/null and b/doc/qtcreator/images/qtcreator-preferences-android.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-axivion.webp b/doc/qtcreator/images/qtcreator-preferences-axivion.webp index a6b69dd1ff5..6d3ebc35ec4 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-axivion.webp and b/doc/qtcreator/images/qtcreator-preferences-axivion.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-build-run-general.webp b/doc/qtcreator/images/qtcreator-preferences-build-run-general.webp index 4826e22fc62..6a0bf6f4811 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-build-run-general.webp and b/doc/qtcreator/images/qtcreator-preferences-build-run-general.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-clangd.webp b/doc/qtcreator/images/qtcreator-preferences-clangd.webp index 6d363c02f93..26a205ae505 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-clangd.webp and b/doc/qtcreator/images/qtcreator-preferences-clangd.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-code-model.webp b/doc/qtcreator/images/qtcreator-preferences-code-model.webp index 9cd9458fe57..2fa62d4fb6d 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-code-model.webp and b/doc/qtcreator/images/qtcreator-preferences-code-model.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-debugger-gdb.webp b/doc/qtcreator/images/qtcreator-preferences-debugger-gdb.webp index 9ac81bce223..c3c4798c553 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-debugger-gdb.webp and b/doc/qtcreator/images/qtcreator-preferences-debugger-gdb.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-devices-remote-linux.webp b/doc/qtcreator/images/qtcreator-preferences-devices-remote-linux.webp index 4b97b88b7a2..565d63ad6df 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-devices-remote-linux.webp and b/doc/qtcreator/images/qtcreator-preferences-devices-remote-linux.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-extensions.webp b/doc/qtcreator/images/qtcreator-preferences-extensions.webp new file mode 100644 index 00000000000..ba94c46dca4 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-preferences-extensions.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-qnx.webp b/doc/qtcreator/images/qtcreator-preferences-qnx.webp new file mode 100644 index 00000000000..435ce04034e Binary files /dev/null and b/doc/qtcreator/images/qtcreator-preferences-qnx.webp differ diff --git a/doc/qtcreator/images/qtcreator-preferences-testing-general.webp b/doc/qtcreator/images/qtcreator-preferences-testing-general.webp index 8fb41b64f7d..f82694ccc91 100644 Binary files a/doc/qtcreator/images/qtcreator-preferences-testing-general.webp and b/doc/qtcreator/images/qtcreator-preferences-testing-general.webp differ diff --git a/doc/qtcreator/images/qtcreator-project-qt-quick.webp b/doc/qtcreator/images/qtcreator-project-qt-quick.webp index ac329a5c430..f4587391bbe 100644 Binary files a/doc/qtcreator/images/qtcreator-project-qt-quick.webp and b/doc/qtcreator/images/qtcreator-project-qt-quick.webp differ diff --git a/doc/qtcreator/images/qtcreator-project-settings-cmake.webp b/doc/qtcreator/images/qtcreator-project-settings-cmake.webp new file mode 100644 index 00000000000..f37c521a866 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-project-settings-cmake.webp differ diff --git a/doc/qtcreator/images/qtcreator-projects-cpp-code-model.webp b/doc/qtcreator/images/qtcreator-projects-cpp-code-model.webp new file mode 100644 index 00000000000..259d8092f30 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-projects-cpp-code-model.webp differ diff --git a/doc/qtcreator/images/qtcreator-projects-environment.webp b/doc/qtcreator/images/qtcreator-projects-environment.webp index eeaed5eaa00..6b33d698522 100644 Binary files a/doc/qtcreator/images/qtcreator-projects-environment.webp and b/doc/qtcreator/images/qtcreator-projects-environment.webp differ diff --git a/doc/qtcreator/images/qtcreator-projects-kits.webp b/doc/qtcreator/images/qtcreator-projects-kits.webp index 827037b0223..38c542c9d14 100644 Binary files a/doc/qtcreator/images/qtcreator-projects-kits.webp and b/doc/qtcreator/images/qtcreator-projects-kits.webp differ diff --git a/doc/qtcreator/images/qtcreator-projects-settings-clangd.webp b/doc/qtcreator/images/qtcreator-projects-settings-clangd.webp index d49b9403e01..2590e9c4e9d 100644 Binary files a/doc/qtcreator/images/qtcreator-projects-settings-clangd.webp and b/doc/qtcreator/images/qtcreator-projects-settings-clangd.webp differ diff --git a/doc/qtcreator/images/qtcreator-projects-settings-testing.webp b/doc/qtcreator/images/qtcreator-projects-settings-testing.webp index 6f8fe53a22f..7af2455f68f 100644 Binary files a/doc/qtcreator/images/qtcreator-projects-settings-testing.webp and b/doc/qtcreator/images/qtcreator-projects-settings-testing.webp differ diff --git a/doc/qtcreator/images/qtcreator-python-update-language-server.webp b/doc/qtcreator/images/qtcreator-python-update-language-server.webp new file mode 100644 index 00000000000..99b9ad2b92e Binary files /dev/null and b/doc/qtcreator/images/qtcreator-python-update-language-server.webp differ diff --git a/doc/qtcreator/images/qtcreator-qml-js-editing.webp b/doc/qtcreator/images/qtcreator-qml-js-editing.webp index c0b56264dd1..f9475414f54 100644 Binary files a/doc/qtcreator/images/qtcreator-qml-js-editing.webp and b/doc/qtcreator/images/qtcreator-qml-js-editing.webp differ diff --git a/doc/qtcreator/images/qtcreator-qml-profiler-toolbar.webp b/doc/qtcreator/images/qtcreator-qml-profiler-toolbar.webp new file mode 100644 index 00000000000..b0b7ba4d7cc Binary files /dev/null and b/doc/qtcreator/images/qtcreator-qml-profiler-toolbar.webp differ diff --git a/doc/qtcreator/images/qtcreator-run-environment.webp b/doc/qtcreator/images/qtcreator-run-environment.webp index 3a0313f994d..7bdd69ebab8 100644 Binary files a/doc/qtcreator/images/qtcreator-run-environment.webp and b/doc/qtcreator/images/qtcreator-run-environment.webp differ diff --git a/doc/qtcreator/images/qtcreator-valgrind-memcheck.png b/doc/qtcreator/images/qtcreator-valgrind-memcheck.png deleted file mode 100644 index 8131846ef53..00000000000 Binary files a/doc/qtcreator/images/qtcreator-valgrind-memcheck.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-valgrind-memcheck.webp b/doc/qtcreator/images/qtcreator-valgrind-memcheck.webp new file mode 100644 index 00000000000..c60fdbb72d4 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-valgrind-memcheck.webp differ diff --git a/doc/qtcreator/images/qtcreator-welcome.webp b/doc/qtcreator/images/qtcreator-welcome.webp new file mode 100644 index 00000000000..a9fe3a047d3 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-welcome.webp differ diff --git a/doc/qtcreator/images/qtcreator-without-menubar.webp b/doc/qtcreator/images/qtcreator-without-menubar.webp index 0201ea89321..1bad87a9d09 100644 Binary files a/doc/qtcreator/images/qtcreator-without-menubar.webp and b/doc/qtcreator/images/qtcreator-without-menubar.webp differ diff --git a/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc b/doc/qtcreator/src/analyze/cpu-usage-analyzer.qdoc index 1341ee95a1c..d267eaf8f60 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{Support Levels for Target Hardware}{supported embedded platforms} @@ -443,15 +456,16 @@ \uicontrol {Performance Analyzer Options}. This format is self-contained, and therefore loading it does not require you to specify the recording environment. You can transfer such trace files to a different computer - without any tool chain or debug symbols and analyze them there. + without any toolchain or debug symbols and analyze them there. \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{\B2Q: Documentation}{\B2Q} 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 +485,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 +503,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 +519,5 @@ The \l {Application Output} view shows some information even if the Performance Analyzer displays error messages. - \sa {Profiling Function Execution} + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code}, {Kits} */ diff --git a/doc/qtcreator/src/analyze/creator-analyze.qdoc b/doc/qtcreator/src/analyze/creator-analyze.qdoc index f57d97b8c02..982d4219923 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,70 +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{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 - 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 + \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 toolchain 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 {Activate kits for a project}, {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..53735a9c31a 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} */ /*! @@ -153,12 +140,18 @@ To connect to an Axivion dashboard server: - \list 1 - \li Select \uicontrol Edit to create a connection to the Axivion + \list + \li Select \uicontrol Add to add a new connection to an Axivion dashboard server. + \li Select \uicontrol Edit to modify an existing connection to + an Axivion dashboard server. \image qtcreator-edit-dashboard-configuration.webp {Edit Dashboard Configuration dialog} - \li In \uicontrol {Dashboard URL}, enter the URL of the server. - \li In \uicontrol Username, enter the username to access the server. + \list + \li In \uicontrol {Dashboard URL}, enter the URL of the server. + \li In \uicontrol Username, enter the username to access the server. + \endlist + \li Select \uicontrol Remove to remove the current selected connection + to an Axivion dashboard server. \endlist The first time you access the server, you must enter the password that @@ -186,6 +179,8 @@ \li Go to \uicontrol Projects > \uicontrol {Project Settings} > \uicontrol Axivion. \image qtcreator-preferences-axivion-project.webp {Axivion settings in Project Settings} + \li From \uicontrol {Dashboard} select one of the configured Axivion + dashboard configurations. \li Select \uicontrol {Fetch Projects} to list projects from Axivion. \li Select a project, and then select \uicontrol {Link Project} to link to it. diff --git a/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc b/doc/qtcreator/src/analyze/creator-clang-static-analyzer.qdoc index c85fd7356de..061feff3c56 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. @@ -93,6 +77,37 @@ Select the \inlineimage icons/settings.png button to customize diagnostics for the current project. + \section2 Filter dianostics + + To filter diagnostics: + + \list 1 + \li Select \inlineimage icons/filtericon.png to open the + \uicontrol {Filter Diagnostics} dialog. + \image qtcreator-clang-tools-filter-diagnostics.webp {Filter Diagnostics dialog} + \li Select the diagnostics to view. + \li Select \uicontrol OK. + \endlist + + To view all diagnostics, select \uicontrol {Select All}. To view diagnostics + that have fixits, select \uicontrol {Select All with Fixits}. + + To hide all diagnostics, select \uicontrol {Clear Selection}. + + To view diagnostics of a particular kind, right-click an entry in + \uicontrol Diagnostics and select \uicontrol {Filter for This Diagnostic Kind} + in the context menu. To hide diagnostics of that kind, select + \uicontrol {Filter out This Diagnostic Kind}. + + \section2 Suppress diagnostics + + To suppress diagnostics, select \uicontrol {Suppress This Diagnostic} or + \uicontrol {Suppress This Diagnostic Inline} in the context menu. + + To view the suppression list for a project and to remove + diagnostics from it, select \uicontrol Projects > + \uicontrol {Project Settings} > \uicontrol {Clang Tools}. + \section1 Disable checks To disable checks of a particular type either globally or for a @@ -107,7 +122,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} */ /*! @@ -271,13 +287,6 @@ \endlist - \section2 Suppressing Diagnostics - - To suppress diagnostics, select \uicontrol {Suppress This Diagnostic} in the - context menu. To view the suppression list for a project and to remove - diagnostics from it, select \uicontrol Projects > - \uicontrol {Project Settings} > \uicontrol {Clang Tools}. - \section2 Selecting Clazy Check Levels The Clazy checks are divided into levels from 0 to 3. The checks at level 0 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..8f02ee0607e 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 @@ -110,7 +113,7 @@ LTTng is a tracing toolkit for Linux that you can apply on embedded Linux systems to find out how to optimize the startup time of an application. - Since Qt 5.13, Qt has a set of kernel trace points and a tracing + Qt has a set of kernel trace points and a tracing subsystem for custom user space trace points. \section2 Configuring the Kernel @@ -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..33d9568c07b 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 @@ // ********************************************************************** /*! - \previouspage creator-clang-tools.html - \page creator-heob.html - \nextpage creator-cpu-usage-analyzer.html + \page creator-how-to-use-heob.html + \previouspage creator-how-tos.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-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..dfc43effb49 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 {Analyze}{How To: Analyze}, {Profile function execution}, + {Run Valgrind tools on external applications}, + {Specify Valgrind settings for a project}, {Analyzers}, {Valgrind Callgrind}, + {Valgrind Memcheck}, {Analyzing Code} +*/ - 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{Kits}{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/android/androiddev.qdoc b/doc/qtcreator/src/android/androiddev.qdoc index 61fbfb5cf75..e2b064d5b50 100644 --- a/doc/qtcreator/src/android/androiddev.qdoc +++ b/doc/qtcreator/src/android/androiddev.qdoc @@ -3,31 +3,30 @@ /*! \page creator-developing-android.html - \previouspage creator-connecting-mobile.html - \nextpage creator-developing-baremetal.html + \previouspage creator-reference.html - \title Connecting Android Devices + \ingroup creator-reference-devices - You can connect Android devices to the development PC using USB cables to - build, run, debug, and analyze applications from \QC. + \title Developing for Android - \note \QC only detects a device and connects to it after you - \l{Debugging on Android Devices}{enable USB debugging on it}. + \brief Set up the toolchain for building applications for Android devices. - To develop for Android, you must install a tool chain for building - applications for Android devices on the development PC. \QC can automatically - download and install the tool chain and create a suitable build and run - \l{glossary-buildandrun-kit}{kit} that has the tool chain and the Qt - version for Android for the device's architecture. + Install a Qt version targeting Android and the Android SDK and NDK to develop + Qt applications for Android devices. To check the Android version supported + by each Qt version, see the \l {Qt for Android} documentation for the Qt + version. - To enable helpful code editing features for Java, such as code completion, + To get helpful code editing features for Java, such as code completion, highlighting, function tooltips, and navigating in code, add a \l{Add a Java language server}{Java language server}. \QC integrates the Android Debug Bridge (\c adb) command-line tool for deploying applications to Android devices, running them, and reading their logs. The \c adb tool includes a client and server that run on - the development host and a daemon that runs on the emulator or device. + the computer and a daemon that runs on the Android emulator or device. + + \note \QC only detects a device and connects to it after you + \l{Debug on Android Devices}{enable USB debugging on it}. The following video shows the whole process from installing Qt for Android to debugging an application on an Android device: @@ -36,18 +35,30 @@ \section1 Requirements - To use \QC to develop Qt applications for Android, you need - \l {Qt for Android} and a tool chain that \QC can automatically - download, install, and configure for you. For more information - about the requirements for developing with a particular Qt version, - see the documentation for that Qt version. The links in this manual - lead to the latest released Qt reference documentation. + To use \QC to develop Qt applications for Android, you need: - \section1 Specifying Android Device Settings + \list + \li \l {Qt for Android} + \li \l {Android Development Prerequisites}{Android tools} that \QC can + automatically download, install, and configure for you. + \endlist + + \sa {Android}{How To: Develop for Android} +*/ + +/*! + \page creator-how-to-set-android-preferences.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-android + + \title Set up Android development environment \QC offers to automatically install all the necessary packages and tools and - to set up your development environment by creating debuggers, tool chains, - and kits. You can use \QC to: + to set up your \l{Qt for Android} development environment by creating + debuggers, toolchains, and kits. + + Use \QC to: \list \li Download and extract the Android SDK Command-line Tools. @@ -58,12 +69,12 @@ To set up the development environment for Android: \list 1 - \li Select \preferences > \uicontrol Devices > \uicontrol Android. - \image qtcreator-options-android-main.png {Android preferences} - \li In the \uicontrol {JDK location} field, set the path to the JDK. + \li Go to \preferences > \uicontrol Devices > \uicontrol Android. + \image qtcreator-preferences-android.webp {Android preferences} + \li In \uicontrol {JDK location}, set the path to the JDK. \QC checks the JDK installation and reports errors. - By default, \QC tries to find a supported \l{AdoptOpenJDK} or + By default, \QC tries to find a supported \l{Adoptium OpenJDK} or \l{OpenJDK} installation. If it cannot find one, you must set the path manually. If you have not installed a supported JDK, select \inlineimage icons/online.png @@ -71,46 +82,42 @@ \note Use a 64-bit JDK because the 32-bit one might cause issues with \c cmdline-tools, and some packages might not appear in the list. - \li In the \uicontrol {Android SDK location} field, set the path to the + \li In \uicontrol {Android SDK location}, set the path to the folder to install the \l{Android SDK Command-line Tools}. \li Select \uicontrol {Set Up SDK} to automatically download and extract the Android SDK Command-line Tools to the selected path. - The SDK Manager checks that you have the necessary tools. If you need - more packages or updates, the SDK Manager offers to add or remove + SDK Manager checks that you have the necessary tools. If you need + more packages or updates, SDK Manager offers to add or remove the appropriate packages. Before taking action, it prompts you to accept the changes. In addition, it prompts you to accept Google licenses, as necessary. - \li The \uicontrol {Android NDK list} lists the installed NDK versions. - The SDK Manager installed the locked items. You can modify them only + \li \uicontrol {Android NDK list} lists the installed NDK versions. + SDK Manager installed the locked items. You can modify them only from the \uicontrol {Android SDK Manager} dialog. For more - information, see \l{Managing Android NDK Packages}. - \li Select the \uicontrol {Automatically create kits for Android tool chains} - check box to allow \QC to create the kits for you. \QC displays a + information, see \l{Manage Android NDK Packages}. + \li Select \uicontrol {Automatically create kits for Android tool chains} + to automatically create the necessary kits. \QC displays a warning if it cannot find a suitable Qt version. - \li Optionally, in the \uicontrol {Android OpenSSL Settings} group, set + \li Optionally, in \uicontrol {Android OpenSSL Settings} group, set the path to the prebuilt OpenSSL libraries. - For Qt applications that require OpenSSL support, you can - quickly add the \l {Android OpenSSL support} to your project. - For more information, see \l{Adding External Libraries}. + For Qt applications that require OpenSSL support, add + \l {Android OpenSSL support} to your project, as instructed in + \l{Adding External Libraries}. \li Select \uicontrol {Download OpenSSL} to download the OpenSSL repository to the selected path. If the automatic download fails, the download web page opens for manual download. \endlist - \section2 Manual Setup + \section1 Manual setup - \note Use the latest Android SDK Command-Line Tools. \QC does not support - Android SDK Tools version 25.2.5 or earlier because it cannot fully - integrate them. - - However, if the automatic setup does not meet your needs, you can download + If the automatic setup does not meet your needs, download and install Android SDK Command-line Tools, and then install or update the necessary NDKs, tools, and packages. For more information, see \l{Getting Started with Qt for Android}. - \section2 Viewing Android Tool Chain Settings + \section1 View Android toolchain settings A JSON configuration file defines the Android SDK Command-Line Tools download URL, the essential packages list, and the appropriate NDK for each Qt version. @@ -124,45 +131,72 @@ C:\Users\Username\AppData\Local\QtProject\qtcreator\android\sdk_definitions.json \endcode - For example, the SDK configuration file sets the NDK version 19.2.5345600 - for use with Qt 5.12.0 to 5.12.5 and Qt 5.13.0 to 5.13.1: + For example, the SDK configuration file sets the NDK version 22.1.7171670 + for use with Qt 6.3, Qt 6.2, and Qt 5.15.9 to 5.15.20: \badcode "specific_qt_versions": [ - { - "versions": ["5.12.[0-5]", "5.13.[0-1]"], - "sdk_essential_packages": ["build-tools;28.0.2", "ndk;19.2.5345600"], - "ndk_path": "ndk/19.2.5345600" - } + { "versions": ["6.3", "6.2", "5.15.[9-20]"], + "sdk_essential_packages": ["build-tools;31.0.0", "ndk;22.1.7171670"] + }, ] \endcode You can view the latest version of the configuration file that is up-to-date with the Android SDK and NDK changes, \l{sdk_definitions.json}, in Git. - \section2 Managing Android NDK Packages + \note For Qt 6.5 or later, \QC reads the NDK version that was used for + building Qt from \c modules/Core.json and uses it instead of the version + in \c sdk_definitions.json. - To view the installed \l{Android NDK} versions, select \preferences > + \sa {Android}{How To: Develop for Android}, {Developing for Android}, {Kits} +*/ + +/*! + \page creator-how-to-manage-android-ndk.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-android + + \title Manage Android NDK packages + + To view the \l{Android NDK} versions that \QC installed, go to \preferences > \uicontrol Devices > \uicontrol Android. - \image qtcreator-options-android-sdk-tools.png {Android NDK and SDK checks} + \image qtcreator-preferences-android.webp {Android preferences} - The SDK Manager installed the locked items. You can modify them only + SDK Manager installed the locked items. You can modify them only in the \uicontrol {Android SDK Manager} dialog. - For more information, see \l{Managing Android SDK Packages}. + For more information, see \l{Manage Android SDK packages}. - To manually download NDKs, select \inlineimage icons/online.png - . + \section1 Download Android NDKs + + To manually download NDKs, select \inlineimage icons/online.png. + + \section1 Set default NDK To use the selected NDK version for all Qt versions by default, select \uicontrol {Make Default}. - To add custom NDK paths manually to the global list of NDKs, select - \uicontrol Add. This creates custom tool chains and debuggers associated - to that NDK. However, you have to manually create a kit that uses the - custom NDK. For more information, see \l{Add kits}. + \section1 Add NDK paths - \section2 Managing Android SDK Packages + To add custom NDK paths manually to the global list of NDKs, select + \uicontrol Add. This creates custom toolchains and debuggers associated + to that NDK. + + You have to manually create a kit that uses the custom NDK. + + \sa {Add kits}, {Android}{How To: Develop for Android}, + {Developing for Android} +*/ + +/*! + \page creator-how-to-manage-android-sdk.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-android + + \title Manage Android SDK packages Since Android SDK Tools version 25.3.0, Android has only a command-line tool, \l {sdkmanager}, for SDK package management. To make SDK management @@ -175,83 +209,152 @@ \image qtcreator-android-sdk-manager.webp {Android SDK Manager} - You can show packages for the release channel you select in - \uicontrol {Show Packages} > \uicontrol Channel. Common channel IDs include - \uicontrol Stable, \uicontrol Beta, \uicontrol Dev, and \uicontrol Canary. + \section1 Show SDK packages + + To show packages for a release channel in \uicontrol Package, select the + channel in \uicontrol {Show Packages} > \uicontrol Channel. Common channel + IDs include \uicontrol Stable, \uicontrol Beta, \uicontrol Dev, and + \uicontrol Canary. + To show and update also obsolete packages, select - \uicontrol {Include obsolete}. To filter packages, select - \uicontrol Available, \uicontrol Installed, or \uicontrol All. + \uicontrol {Include obsolete}. - To update the installed Android SDK packages, select - \uicontrol {Update Installed}. Select the packages to update, and then - select \uicontrol Apply. + To filter packages, select \uicontrol Available, \uicontrol Installed, or + \uicontrol All. - To specify advanced \c sdkmanager settings, select - \uicontrol {Advanced Options} and enter arguments in the - \uicontrol {SDK Manager arguments} field. \uicontrol {Available arguments} - lists the arguments with descriptions. + \section1 Update SDK packages + To update the installed Android SDK packages: + + \list 1 + \li Select \uicontrol {Update Installed}. + \li Select the packages to update. + \li Select \uicontrol Apply. + \endlist + + \section1 Set sdkmanager options + + To set advanced \c sdkmanager options: + + \list 1 + \li Select \uicontrol {Advanced Options}. + \li In \uicontrol {SDK Manager arguments}, enter sdkmanager options from + \uicontrol {Available arguments}. \image qtcreator-android-sdk-manager-arguments.png {Android SDK Manager Arguments dialog} + \endlist - \section1 Managing Android Virtual Devices (AVD) + \sa {Android}{How To: Develop for Android}, {Developing for Android} +*/ - To view the available AVDs, select \preferences > \uicontrol Devices. - You can add more AVDs. +/*! + \page creator-how-to-manage-avd.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-android + + \title Manage AVDs + + To view and add Android Virtual Devices (AVD), go to \preferences > + \uicontrol Devices. \image qtcreator-android-avd-manager.webp {Android device in Devices} - You can see the status of the selected device in \uicontrol {Current state}. + Select an AVD in \uicontrol Device to see its status in + \uicontrol {Current state}. + To update the status information, select \uicontrol Refresh. - To start an AVD, select \uicontrol {Start AVD}. Usually, you don't need to - start AVDs separately because \QC starts them when you - select them in the \l{Build for many platforms}{kit selector} to - \l{Deploying to Android}{deploy applications} to them. + \section1 Start AVDs + + To start an AVD, select \uicontrol {Start AVD}. Usually, \QC starts an AVD + when you select it in the \l{Build for many platforms}{kit selector} to + \l{Android Deploy Configuration}{deploy applications} to it. + + \section1 Set prefrences for starting AVDs + + To set preferences for starting an AVD, select \uicontrol {AVD Arguments}. + + \image qtcreator-android-avd-arguments.png {Startup options for AVDs} + + Set the preferences in \uicontrol {Emulator command-line startup options}. + For available options, see \l{Start the emulator from the command line}. + + To start the emulator manually from the terminal, enter: + + \badcode + cd /emulator + ./emulator -avd + \endcode + + \section1 Remove AVDs To remove an AVD from the list and the kit selector, select \uicontrol {Erase AVD}. - To specify options for starting an AVD, select \uicontrol {AVD Arguments}. + \sa {Android}{How To: Develop for Android}, {Developing for Android} +*/ - \image qtcreator-android-avd-arguments.png {Startup options for AVDs} +/*! + \page creator-how-to-create-avd.html + \previouspage creator-how-tos.html - Specify the options in \uicontrol {Emulator command-line startup options}. - For available options, see \l{Start the emulator from the command line}. + \ingroup creator-how-to-android - \note The Android Emulator has a bug that prevents it from starting on some - systems. If an AVD does not start, you can try starting it manually by - running the following commands: + \title Create an Android Virtual Device (AVD) - \badcode - cd /emulator - ./emulator -avd - \endcode + You can create AVDs for: - \section2 Creating a New AVD + \list + \li Automotive + \li Desktop + \li Phone + \li Tablet + \li TV + \li Wear + \endlist - To create new virtual devices: + To create a new AVD: \list 1 - \li Select \preferences > \uicontrol Devices > - \uicontrol Add > \uicontrol {Android Device} to open the - \uicontrol {Create New AVD} dialog. + \li Go to \preferences > \uicontrol Devices. + \li Select \uicontrol Add > \uicontrol {Android Device} > + \uicontrol {Start Wizard}. \image qtcreator-android-create-avd.png {Create New AVD dialog} - \li Set the name, definition, architecture, target API level, and - SD card size of the device. + \li In \uicontrol Name, give the AVD a name. + \li In \uicontrol {Device definition}, select the AVD type, and then + select one of the predefined AVDs or \uicontrol Custom for a custom + AVD. + \li In \uicontrol {Architecture (ABI)}, select an Android system image + that you installed on the computer. + \li In \uicontrol {Target API level}, select the \l{What is API Level?} + {API level} to use for building the application. + \li In \uicontrol {SD card size}, set the size of the SD card for the + AVD. + \li Select \uicontrol {Override existing AVD name} to overwrite an + existing AVD with a new AVD using the same name (\c avdmanager \c -f + option). \li Select \uicontrol OK to create the AVD. \endlist For more advanced options for creating a new AVD, use the command-line tool \l{avdmanager} or the Android Studio's native AVD Manager UI. - \section1 Debugging on Android Devices + \sa {Android}{How To: Develop for Android}, {Android Deploy Configuration}, + {Developing for Android} +*/ + +/*! + \page creator-how-to-debug-android.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-android + + \title Debug on Android devices You enable debugging in different ways on different Android devices. - Look for \uicontrol {USB Debugging} under \uicontrol {Developer Options}. On - some devices, \uicontrol {Developer Options} is hidden and becomes visible - only when you tap the \uicontrol {Build number} field in \uicontrol Settings - > \uicontrol About several times. For more information, see - \l {Configure on-device developer options}. + Look for \uicontrol {USB Debugging} under \uicontrol {Developer Options}. + Tap \uicontrol {Build number} in \uicontrol Settings > \uicontrol About + several times to show \uicontrol {Developer Options}. Select a \l{glossary-build-config}{debug build configuration} to build the application for debugging. @@ -263,4 +366,7 @@ \badcode Ignoring second debugger -accepting and dropping. \endcode + + \sa {Android}{How To: Develop for Android}, {Developing for Android}, + {Configure on-device developer options} */ diff --git a/doc/qtcreator/src/android/creator-projects-settings-run-android.qdoc b/doc/qtcreator/src/android/creator-projects-settings-run-android.qdoc index 8904f697850..2d264f0e57d 100644 --- a/doc/qtcreator/src/android/creator-projects-settings-run-android.qdoc +++ b/doc/qtcreator/src/android/creator-projects-settings-run-android.qdoc @@ -11,13 +11,13 @@ \brief Settings for running applications on Android devices. - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. To run and debug an application on an Android device, you must create connections from the development host to the device, as instructed in - \l {Connecting Android Devices}. + \l {Developing for Android}. \section1 am Start Options @@ -66,5 +66,5 @@ \endcode \sa {Activate kits for a project}, {Configure projects for running}, - {Connecting Android Devices} + {Android}{How To: Develop for Android}, {Kits} */ diff --git a/doc/qtcreator/src/android/deploying-android.qdoc b/doc/qtcreator/src/android/deploying-android.qdoc index 2b3441290f3..75f497cc6d7 100644 --- a/doc/qtcreator/src/android/deploying-android.qdoc +++ b/doc/qtcreator/src/android/deploying-android.qdoc @@ -2,11 +2,15 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-deployment.html \page creator-deploying-android.html - \nextpage creator-deployment-b2qt.html + \previouspage creator-reference.html - \title Deploying to Android + \ingroup creator-reference-deploy-configurations + + \title Android Deploy Configuration + + \brief Create Application Packages (APK) or Android App Bundles (AAB) to + install and run on devices or to upload to the Google Play store. Android applications are packaged as ZIP files called Application Packages (APK) or Android App Bundles (AAB). You can install and run APK files on a @@ -26,7 +30,7 @@ All Qt versions do not support AABs. Qt 6.3.0 and later support multi-abi builds for applications that you build with CMake. For - more information, see \l{Qt for Android - Building User Projects}. + more information, see \l{Deploying an Application on Android}. \endlist \note Since \QC 4.12, Ministro is not supported. @@ -204,7 +208,8 @@ To add OpenSSL libraries, select \uicontrol {Include prebuilt OpenSSL libraries} in the \uicontrol {Additional Libraries} group. This will add the OpenSSL - include project defined in \l{Specifying Android Device Settings}{device settings} + include project defined in \l{Set up Android development environment} + {device settings} in \uicontrol {Android OpenSSL} group. This can be used for qmake and CMake projects. @@ -492,5 +497,8 @@ \c {android.permission.ACCESS_BACKGROUND_LOCATION} for \l{Qt Positioning}. To add a permission, select it from the list, and then click \uicontrol Add. + + \sa {Build and Run}{How To: Build and Run}, + {Android}{How To: Develop for Android}, {Android Run Settings}, {Kits} */ diff --git a/doc/qtcreator/src/appman/creator-appman-how-to-run.qdoc b/doc/qtcreator/src/appman/creator-appman-how-to-run.qdoc index a6319a7f2ad..e43e3320656 100644 --- a/doc/qtcreator/src/appman/creator-appman-how-to-run.qdoc +++ b/doc/qtcreator/src/appman/creator-appman-how-to-run.qdoc @@ -11,7 +11,7 @@ If you have set up \l{Qt Application Manager}, you can deploy, run, and debug applications on the desktop, remote generic SSH Linux targets, or - \l{Boot2Qt}{Boot2Qt devices}. The applications can be either + \B2Q devices. The applications can be either \e {built-in applications} or \e {third-party applications}. The former are part of the System UI or the base installation, while the latter are dynamically installed, updated, and uninstalled. @@ -118,7 +118,7 @@ \li The path to the controller that installs the application package into the target system. - When you run applications on a Boot2Qt device, you can see the device + When you run applications on a \B2Q device, you can see the device ID here. \row \li \uicontrol {Application ID} @@ -141,14 +141,20 @@ \li Always communicates with the default instance. \endtable - \section1 Profile Qt Quick applications + \section1 Analyze the applications - You can use the \l{Profiling QML Applications}{QML Profiler} to find causes - for typical performance problems in your Qt Quick applications, such as + Use the \l{Profiling QML Applications}{QML Profiler} to find causes + for typical performance problems in Qt Quick applications, such as slowness and unresponsive, stuttering user interfaces. You cannot profile an in-process runtime as an individual process. - \sa {Activate kits for a project}, {Connecting Boot2Qt Devices}, - {Connecting Remote Linux Devices}, {Enable and disable plugins}, - {Run on many platforms}, {Debugging}, {Profiling QML Applications} + Use the \l{Performance Analyzer} to analyze the CPU and memory usage of an + application. + + \sa {Activate kits for a project}, {Enable and disable plugins}, + {\B2Q}{How To: Develop for \B2Q}, + {Remote Linux}{How To: Develop for remote Linux}, + {Run on many platforms}, {Debugging}, {Debuggers}, {Debugger}, + {Developing for \B2Q Devices}, {Developing for Remote Linux Devices}, + {Profiling QML Applications}, {Kits} */ diff --git a/doc/qtcreator/src/baremetal/creator-baremetal-dev.qdoc b/doc/qtcreator/src/baremetal/creator-baremetal-dev.qdoc index 96fabb36244..67b73cf9822 100644 --- a/doc/qtcreator/src/baremetal/creator-baremetal-dev.qdoc +++ b/doc/qtcreator/src/baremetal/creator-baremetal-dev.qdoc @@ -1,24 +1,33 @@ -// 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-developing-android.html \page creator-developing-baremetal.html - \nextpage creator-developing-b2qt.html + \previouspage creator-reference.html - \title Connecting Bare Metal Devices + \ingroup creator-reference-devices - You can configure build and run kits to use Bare Metal tool chains installed - on the development host to build applications for Bare Metal devices. You - can connect the devices to the development host to run and debug - applications on them from \QC using GDB or a hardware debugger. This enables - you to debug on small devices that are not supported by the generic remote - Linux device plugin. + \title Developing for Bare Metal Devices + + \brief Create kits to use Bare Metal toolchains installed on the computer + to build applications for and run and debug them on connected Bare Metal + devices. + + Run and debug applications on small devices that are not supported + by the remote Linux device plugin by using GDB or a hardware debugger. + + \note Enable the Bare Metal plugin to use it. + + Install Bare Metal toolchains on the computer to build applications for + Bare Metal devices. Connect the devices to the computer to run and debug + applications on them. \note If you use qmake to build the project and the device does not have - Qt libraries, you need a fake Qt installation. + Qt libraries, you need a Qt installation that meets the requirements in + \l{Self-built Qt versions}. In addition, the \c mkspecs directory needs + to be complete enough to parse .pro files. - The following tool chains are supported for building applications: + The following toolchains are supported for building applications: \list \li GCC: Microchip Technology (AVR, AVR32, PIC16, PIC32), @@ -42,227 +51,286 @@ the device preferences. You can specify the commands to execute when connecting using a particular debug server provider. + \section1 Debug Server Providers + The following debug server providers are supported when using GDB: \list - \li \l EBlink - \li \l J-Link - \li \l OpenOCD - \li \l ST-Link + \li \l {Set up EBlink}{EBlink} + \li \l {Set up J-Link}{J-Link} + \li \l {Set up OpenOCD}{OpenOCD} + \li \l {Set up ST-Link}{ST-Link} \endlist ST-Link and J-Link debug server providers can be used together with - the \l {uVision IDE}. - - \note Enable the Bare Metal plugin to use it. - - \section1 Specifying Settings for Debug Server Providers + the \l {Set up the uVision IDE}{uVision IDE}. To create connections to bare metal devices using a debug server provider, - select \preferences > \uicontrol Devices > \uicontrol {Bare Metal} > + go to \preferences > \uicontrol Devices > \uicontrol {Bare Metal} and select \uicontrol Add. The available settings depend on the debug server provider. - \section2 EBlink + \sa {Add kits}, {Enable and disable plugins}, + {Bare Metal}{How To: Develop for Bare Metal} +*/ + +/*! + \page creator-how-to-eblink.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + + \title Set up EBlink \l{https://github.com/EmBitz/EBlink}{EBlink} is an ARM Cortex-M debug tool that supports squirrel scripting, live variables, and hot-plugging. \image qtcreator-baremetal-eblink.webp {Bare metal device preferences for EBlink} - To specify settings for \EBlink: + To set preferences for \EBlink: \list 1 - \include creator-baremetal-settings.qdocinc baremetal-common + \include creator-baremetal-settings.qdocinc {baremetal-common} {EBlink} - \li In the \uicontrol {Script file} field, enter the path + \li In \uicontrol {Script file}, enter the path to a device script file. - \li In the \uicontrol {Verbosity level} field, enter the level of + \li In \uicontrol {Verbosity level}, enter the level of verbose logging. - \li Select the \uicontrol {Connect under reset} check box to use - the ST-Link interface. Deselect the check box for hot-plugging. + \li Select \uicontrol {Connect under reset} to use + the ST-Link interface. Clear it for hot-plugging. - \li In the \uicontrol Type field, select the interface type. + \li In \uicontrol Type, select the interface type. - \li In the \uicontrol Speed field, enter the interface speed between + \li In \uicontrol Speed, enter the interface speed between 120 and 8000 kilohertz (kHz). - \li Select the \uicontrol {Disable cache} check box to disable the + \li Select \uicontrol {Disable cache} to disable the \EBlink flash cache. - \li Select the \uicontrol {Auto shutdown} check box to automatically + \li Select \uicontrol {Auto shutdown} to automatically shut down the \EBlink server after disconnecting. \include creator-baremetal-settings.qdocinc baremetal-init-reset \endlist - \section2 J-Link + \sa {Bare Metal}{How To: Develop for Bare Metal}, + {Developing for Bare Metal Devices} +*/ + +/*! + \page creator-how-to-jlink.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + + \title Set up J-Link \l{https://www.segger.com/products/debug-probes/j-link/}{J-Link} is a line of debug probes by Segger. - \image qtcreator-baremetal-jlink.webp "Bare metal device preferences for J-Link" + \image qtcreator-baremetal-jlink.webp {Bare metal device preferences for J-Link} - To specify settings for J-Link debug probes: + To set preferences for J-Link debug probes: \list 1 - \include creator-baremetal-settings.qdocinc baremetal-common + \include creator-baremetal-settings.qdocinc {baremetal-common} {J-Link} - \li In the \uicontrol {Host interface} field, select the connection + \li In \uicontrol {Host interface}, select the connection type, IP or USB, or use the default connection. - \li In the \uicontrol {Target interface} field, select the target - interface type. + \li In \uicontrol {Target interface}, select the target interface type. - \li In the \uicontrol Speed field, enter the interface speed in kHz. + \li In \uicontrol Speed, enter the interface speed in kHz. - \li In the \uicontrol Device field, select the device to connect to. + \li In \uicontrol Device, select the device to connect to. - \li In the \uicontrol {Additional arguments} field, enter - arguments for the commands. + \li In \uicontrol {Additional arguments}, enter arguments for the + commands. \include creator-baremetal-settings.qdocinc baremetal-init-reset \endlist - \section2 OpenOCD + \sa {Bare Metal}{How To: Develop for Bare Metal}, + {Developing for Bare Metal Devices} +*/ + +/*! + \page creator-how-to-openocd.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + + \title Set up OpenOCD \l{http://openocd.org}{OpenOCD} (Open On-Chip Debugger) is an on-chip debug solution for targets based on the ARM7 and ARM9 family with Embedded-ICE (JTAG) facility. It enables source level debugging with the GDB compiled for the ARM architecture. - \image qtcreator-baremetal-openocd.webp "Bare metal device preferences for OpenOCD" + \image qtcreator-baremetal-openocd.webp {Bare metal device preferences for OpenOCD} - To specify settings for \OpenOCD: + To set preferences for \OpenOCD: \list 1 - \include creator-baremetal-settings.qdocinc baremetal-common + \include creator-baremetal-settings.qdocinc {baremetal-common} {OpenOCD} - \li In the \uicontrol {Root scripts directory} field, enter the + \li In \uicontrol {Root scripts directory}, enter the path to the directory that has configuration scripts. - \li In the \uicontrol {Configuration file} field, enter the path + \li In \uicontrol {Configuration file}, enter the path to the device configuration file. - \li In the \uicontrol {Additional arguments} field, enter + \li In \uicontrol {Additional arguments}, enter arguments for the commands. \include creator-baremetal-settings.qdocinc baremetal-init-reset \endlist - \section2 St-Link + \sa {Bare Metal}{How To: Develop for Bare Metal}, + {Developing for Bare Metal Devices} +*/ + +/*! + \page creator-how-to-stlink.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + + \title Set up St-Link \l{https://www.st.com/en/development-tools/stm32-programmers.html#products} {ST-LINK Utility} is used for programming STM32 microcontrollers. - \image qtcreator-baremetal-stlink.webp "Bare metal device preferences for St-Link" + \image qtcreator-baremetal-stlink.webp {Bare metal device preferences for St-Link} - To specify settings for St-Link: + To set preferences for St-Link: \list 1 - \include creator-baremetal-settings.qdocinc baremetal-common + \include creator-baremetal-settings.qdocinc {baremetal-common} {St-Link} - \li In the \uicontrol {Verbosity level} field, enter the level of + \li In \uicontrol {Verbosity level}, enter the level of verbose logging. - \li Select the \uicontrol {Extended mode} check box to continue + \li Select \uicontrol {Extended mode} to continue listening for connection requests after the connection is closed. - \li Select the \uicontrol {Reset on connection} check box to + \li Select \uicontrol {Reset on connection} to reset the board when the connection is created. - \li In the \uicontrol Version field, select the transport + \li In \uicontrol Version, select the transport layer type supported by the device. \include creator-baremetal-settings.qdocinc baremetal-init-reset \endlist - \section2 uVision IDE + \sa {Bare Metal}{How To: Develop for Bare Metal}, + {Developing for Bare Metal Devices} +*/ + +/*! + \page creator-how-to-uvision.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + + \title Set up the uVision IDE \l{http://www.keil.com/support/man/docs/uv4/uv4_overview.htm}{uVision} is - an IDE for developing applications for embedded devices. Applications can - be debugged by using uVision Simulator or directly on hardware by using + an IDE for developing applications for embedded devices. To debug + applications, use uVision Simulator, or debug directly on hardware by using St-Link and J-Link. - You can view the current state of peripheral registers in the - \uicontrol {Peripheral Registers} view in Debug mode. The view - is hidden by default. + The \uicontrol {Peripheral Registers} view in Debug mode shows the current + state of peripheral registers. The view is hidden by default. - \section3 uVision Simulator + \section1 uVision Simulator - \image qtcreator-baremetal-uvision-simulator.png "Bare metal device preferences for uVision Simulator" + \image qtcreator-baremetal-uvision-simulator.png {Bare metal device preferences for uVision Simulator} - To specify settings for uVision Simulator: + To set preferences for uVision Simulator: \list 1 - \include creator-baremetal-settings.qdocinc uvision-common + \include creator-baremetal-settings.qdocinc {uvision-common} {uVision Simulator} - \li Select the \uicontrol {Limit speed to real-time} check box to limit + \li Select \uicontrol {Limit speed to real-time} to limit the connection speed. \li Select \uicontrol Apply to add the debug server provider. \endlist - \section3 uVision St-Link or JLink Debugger + \section1 uVision St-Link or JLink Debugger - \image qtcreator-baremetal-uvision-st-link.png "Bare metal device preferences for uVision St-Link" + \image qtcreator-baremetal-uvision-st-link.png {Bare metal device preferences for uVision St-Link} - To specify settings for uVision St-Link or JLink Debugger: + To set preferences for uVision St-Link or JLink Debugger: \list 1 - \include creator-baremetal-settings.qdocinc uvision-common + \include creator-baremetal-settings.qdocinc {uvision-common} {uVision St-Link or uVision JLink} - \li In the \uicontrol {Adapter options} field specify the adapter + \li In \uicontrol {Adapter options} specify the adapter interface type and speed in MHz. \li Select \uicontrol Apply to add the debug server provider. \endlist - \section1 Adding Bare Metal Devices + \sa {Bare Metal}{How To: Develop for Bare Metal}, + {Developing for Bare Metal Devices} +*/ - \image qtcreator-baremetal-devices.png "Bare Metal device preferences" +/*! + \page creator-how-to-add-bare-metal-devices.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-bare-metal + \ingroup creator-how-to-manage-kits + + \title Add Bare Metal devices + + Run and debug applications on small devices that are not supported + by the remote Linux device plugin by using GDB or a hardware debugger. To add a bare metal device: \list 1 - \li Select \preferences > \uicontrol Devices - > \uicontrol Add > \uicontrol {Bare Metal Device} > + \li Go to \preferences > \uicontrol Devices. + \image qtcreator-baremetal-devices.png {Bare Metal device preferences} + \li Select \uicontrol Add > \uicontrol {Bare Metal Device} > \uicontrol {Start Wizard}. - \li In the \uicontrol {Debug server provider} field, select a debug + \li In \uicontrol {Debug server provider}, select a debug server provider. \li Select \uicontrol Apply to add the device. \endlist - \section1 Building for and Running on Bare Metal Devices + \section1 Add the device to a kit To add a kit for building applications and running them on bare metal - devices, select \preferences > \uicontrol Kits - > \uicontrol Add. For more information, see \l{Add kits}. + devices, go to \preferences > \uicontrol Kits and select \uicontrol Add. - \image qtcreator-baremetal-kit.png "Kit preferences for Bare Metal" + \image qtcreator-baremetal-kit.png {Kit preferences for Bare Metal} - You can build applications for and run them on bare metal devices - in the same way as for and on the desktop. For more information, see - \l{Build for many platforms} and \l{Run on many platforms}. + Build applications for and run them on bare metal devices + in same way as for and on the desktop. - \sa {Enable and disable plugins} + \sa {Add kits}, {Build for many platforms}, + {Bare Metal}{How To: Develop for Bare Metal}, {Run on many platforms}, + {Developing for Bare Metal Devices} */ diff --git a/doc/qtcreator/src/baremetal/creator-baremetal-settings.qdocinc b/doc/qtcreator/src/baremetal/creator-baremetal-settings.qdocinc index ea35fe9855b..a6688da00b7 100644 --- a/doc/qtcreator/src/baremetal/creator-baremetal-settings.qdocinc +++ b/doc/qtcreator/src/baremetal/creator-baremetal-settings.qdocinc @@ -1,16 +1,19 @@ -// 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 //! [baremetal-common] - \li In the \uicontrol Name field, enter a name for the connection. - \li In the \uicontrol {Startup mode} field, select the mode to start + \li Go to \preferences > \uicontrol Devices > \uicontrol {Bare Metal}. + \li Select \uicontrol Add. + \li Select \uicontrol {\1}. + \li In \uicontrol Name, enter a name for the connection. + \li In \uicontrol {Startup mode}, select the mode to start the debug server provider in. - \li In the \uicontrol {Peripheral description file} field, specify a path to + \li In \uicontrol {Peripheral description file}, specify a path to a file that describes the peripherals on the device. - \li In the \uicontrol Host field, select the host name and port number + \li In \uicontrol Host, select the host name and port number to connect to the debug server provider. - \li In the \uicontrol {Executable file} field, enter the path to the + \li In \uicontrol {Executable file}, enter the path to the debug server provider executable. //! [baremetal-common] @@ -18,10 +21,10 @@ //! [baremetal-init-reset] - \li In the \uicontrol {Init commands} field, enter the commands - to execute when initializing the connection. - \li In the \uicontrol {Reset commands} field, enter the commands - to execute when resetting the connection. + \li In \uicontrol {Init commands}, enter the commands + to execute when initializing the connection. + \li In \uicontrol {Reset commands}, enter the commands + to execute when resetting the connection. \li Select \uicontrol Apply to add the debug server provider. //! [baremetal-init-reset] @@ -29,14 +32,16 @@ //! [uvision-common] - \li In the \uicontrol Name field, enter a name for the connection. - \li In the \uicontrol Host field, select the host name and port + \li Go to \preferences > \uicontrol Devices > \uicontrol {Bare Metal}. + \li Select \uicontrol Add. + \li Select \uicontrol {\1}. + \li In \uicontrol Name, enter a name for the connection. + \li In \uicontrol Host, select the host name and port number to connect to the debug server provider. - \li In the \uicontrol {Tools file path} field, enter the path to + \li In \uicontrol {Tools file path}, enter the path to the Keil toolset configuration file. - \li In the \uicontrol {Target device} field, select the device to - debug. - \li In the \uicontrol {Target driver} field, select the driver for + \li In \uicontrol {Target device}, select the device to debug. + \li In \uicontrol {Target driver}, select the driver for connecting to the target device. //! [uvision-common] diff --git a/doc/qtcreator/src/cmake/creator-how-to-debug-cmake-files.qdoc b/doc/qtcreator/src/cmake/creator-how-to-debug-cmake-files.qdoc index ac3ffb12a90..538bd7cd9a0 100644 --- a/doc/qtcreator/src/cmake/creator-how-to-debug-cmake-files.qdoc +++ b/doc/qtcreator/src/cmake/creator-how-to-debug-cmake-files.qdoc @@ -20,7 +20,7 @@ \list 1 \li In the \uicontrol Edit mode, set breakpoints in a CMake file. - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Start CMake Debugging}. \image qtcreator-debugger-cmake.webp {DAP CMake Preset view in the Debug mode} \endlist @@ -28,6 +28,5 @@ When the application stops at a breakpoint, you can examine data in the \uicontrol Debug mode views. - \sa {Debugging},{Examining Data},{Debug Mode Views},{Setting Breakpoints}, - {CMake} + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, {CMake} */ 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/cmake/creator-projects-cmake-building.qdoc b/doc/qtcreator/src/cmake/creator-projects-cmake-building.qdoc index aac591854cd..c3b9692c5ae 100644 --- a/doc/qtcreator/src/cmake/creator-projects-cmake-building.qdoc +++ b/doc/qtcreator/src/cmake/creator-projects-cmake-building.qdoc @@ -11,15 +11,15 @@ \brief Settings for building applications with CMake. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. Configuring medium-sized to large CMake projects in \QC can be a challenge due to the number of variables that you need to pass to CMake to configure the project correctly. To make this easier, - \QC creates an initial configuration for you based on the kit - settings and displays it in \uicontrol {Initial Configuration} in + \QC creates an initial configuration for you based on the \l{Kits} + {kit preferences} and displays it in \uicontrol {Initial Configuration} in the \uicontrol {Build Settings} of the project. Or, you can use CMake presets to configure CMake. diff --git a/doc/qtcreator/src/cmake/creator-projects-cmake-presets.qdoc b/doc/qtcreator/src/cmake/creator-projects-cmake-presets.qdoc index 050b0b1f8c7..4e0160ba9eb 100644 --- a/doc/qtcreator/src/cmake/creator-projects-cmake-presets.qdoc +++ b/doc/qtcreator/src/cmake/creator-projects-cmake-presets.qdoc @@ -15,13 +15,14 @@ \c CMakeUserPresets.json has options for your local builds. Create the presets files in the format described in - \l{https://cmake.org/cmake/help/latest/manual/cmake-presets.7.html} + \l{https://cmake.org/cmake/help/v3.24/manual/cmake-presets.7.html} {cmake-presets(7)} and store them in the project's root directory. You can then see them in the \l {Projects} view. - \QC supports presets up to version 3 (introduced in CMake 3.21), but does not - enforce version checking. It reads and uses all the fields from version 3 if - present. It does not support test presets. + \QC supports \e configure and \e build presets up to version 5 + (introduced in CMake 3.24), but does not enforce version checking. + It reads and uses all the fields from version 5 if present. + It does not support \e test presets. You can import the presets the first time you \l {Open projects} {open a project}, when no \c CMakeLists.txt.user file exists or you have @@ -44,7 +45,7 @@ \c NOT_COMMON_VALUE is displayed in \uicontrol {Initial Parameters} and \c AN_ENVIRONMENT_FLAG in the environment configuration field. - \badcode + \code { "version": 1, "configurePresets": [ @@ -57,12 +58,26 @@ }, "environment": { "AN_ENVIRONMENT_FLAG": "1" + } + }, + "vendor": { + "qt.io/QtCreator/1.0": { + "AskBeforePresetsReload": false, + "AskReConfigureInitialParams": false, + "AutorunCMake": false, + "PackageManagerAutoSetup": false, + "ShowAdvancedOptionsByDefault": true, + "ShowSourceSubFolders": false, + "UseJunctionsForSourceAndBuildDirectories": true + } } - } ] } \endcode + For more information about the CMake project settings in the \c vendor + section, see \l {Override CMake settings for a project}. + \section1 MinGW Example The following example configures a Qt project with: @@ -74,9 +89,10 @@ \li generator – MinGW Makefiles \li path to a CMake executable \li path to the Qt installation via \c CMAKE_PREFIX_PATH + \li GNU gdb 11.2.0 for MinGW 11.2.0 64-bit debugger \endlist - \badcode + \code { "version": 1, "configurePresets": [ @@ -92,8 +108,17 @@ }, "environment": { "PATH": "C:/Qt/Tools/mingw1120_64/bin;$penv{PATH}" - } - } + }, + "vendor": { + "qt.io/QtCreator/1.0": { + "debugger": { + "DisplayName": "GNU gdb 11.2.0 for MinGW 11.2.0 64-bit", + "Abis": ["x86-windows-msys-pe-64bit"], + "Binary": "C:/Qt/Tools/mingw1120_64/bin/gdb.exe", + "EngineType": 1, + "Version": "11.2.0" + } + } ] } \endcode @@ -107,7 +132,7 @@ generator, add \c Debug and \c Release build steps, and specify the path to \c ninja.exe as a value of the \c CMAKE_MAKE_PROGRAM variable: - \badcode + \code { "version": 2, "configurePresets": [ @@ -156,7 +181,7 @@ For example: - \badcode + \code "generator": "Ninja Multi-Config", "toolset": { "value": "v142,host=x64", @@ -172,7 +197,7 @@ in the \c PATH, you might also have to specify the compiler to use in \c cacheVariables or \c environmentVariables: - \badcode + \code "generator": "Ninja Multi-Config", "toolset": { "value": "v142,host=x64", @@ -188,13 +213,57 @@ } \endcode + \section1 Cross-Compilation Example + + The following example configures a Qt project for cross-compilation on \macos + for Windows and running with the \c wine emulator on \macos: + + \list + \li generator – Ninja + \li build directory – \c /build-release + \li LLVM/MinGW toolchain + \li configuration type – \c CMAKE_BUILD_TYPE as \c Release + \li LLDB 18.1.6 debugger + \li \c wine emulator + \endlist + + \code + { + "version": 4, + "configurePresets": [ + { + "name": "llvm-mingw", + "displayName": "LLVM-MinGW 18.1.6", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build-release", + "toolchainFile": "llvm-mingw.cmake", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_CROSSCOMPILING_EMULATOR": "/opt/homebrew/bin/wine" + }, + "vendor": { + "qt.io/QtCreator/1.0": { + "debugger": { + "DisplayName": "LLDB 18.1.6 (CMake Preset)", + "Abis": ["x86-darwin-generic-mach_o-64bit", "arm-darwin-generic-mach_o-64bit"], + "Binary": "/Users/jdoe/llvm-mingw/bin/lldb", + "EngineType": 256, + "Version": "18.1.6" + } + } + } + } + ] + } + \endcode + \section1 Using Conditions The following configure presets are used if they match \c condition. That is, if the \c hostSystemName equals \c Linux, the \c linux presets are used and if it equals \c Windows, the \c windows presets are used. - \badcode + \code { "version": 3, "configurePresets": [ diff --git a/doc/qtcreator/src/cmake/creator-projects-cmake.qdoc b/doc/qtcreator/src/cmake/creator-projects-cmake.qdoc index 6c4b7d8ef09..524163a2894 100644 --- a/doc/qtcreator/src/cmake/creator-projects-cmake.qdoc +++ b/doc/qtcreator/src/cmake/creator-projects-cmake.qdoc @@ -49,7 +49,7 @@ \sa {Configure projects for building}, {Configure projects for running}, {Build with CMake}{How To: Build with CMake}, {CMake Build Configuration}, - {Debug CMake project files}, {Deploying to Remote Linux}, {Open projects}, + {Debug CMake project files}, {Remote Linux Deploy Configuration}, {Open projects}, {Use compilation databases} */ @@ -65,8 +65,7 @@ a tree and lists all files that are part of the project. \QC automatically runs CMake to refresh project information in the view when you edit a \c CMakeLists.txt configuration file - in a project. Project information is also automatically refreshed when - you build the project. + in a project. Also, refreshes project information when you build the project. \image qtcreator-projects-view-edit.png {CMake project in Projects view} @@ -121,11 +120,14 @@ tooltips \li Selecting any of the above elements and pressing \key F1 to show its documentation - \li Switching to the Help mode + \li Switching to the \uicontrol Help mode \endlist - \sa {Build with CMake}{How To: Build with CMake}, {CMake}, - {Read Documentation}{How To: Read Documentation} + To view the documentation online, open it in the \uicontrol Help mode and + select \inlineimage icons/online.png (\uicontrol {Open Online Documentation}). + + \sa {Build with CMake}{How To: Build with CMake}, + {Read Documentation}{How To: Read Documentation}, {CMake} */ /*! @@ -133,12 +135,13 @@ \previouspage creator-how-tos.html \ingroup creator-how-to-build-with-cmake + \ingroup creator-how-to-manage-kits \title Add CMake tools \QC automatically detects the CMake executable that you specify in the \c PATH. You can add paths to other CMake executables and use them in - different build and run \l{glossary-buildandrun-kit}{kits}. + different build and run \l{Kits}{kits}. To see the CMake installations that \QC automatically detects: @@ -183,8 +186,8 @@ \image qtcreator-kits-cmake.png {Kits preferences} - \sa {Build with CMake}{How To: Build with CMake}, {CMake}, {Add kits}, - {kits-tab}{Kits} + \sa {Build with CMake}{How To: Build with CMake}, + {Manage Kits}{How To: Manage Kits}, {CMake}, {Kits} */ /*! diff --git a/doc/qtcreator/src/cmake/creator-projects-settings-cmake.qdoc b/doc/qtcreator/src/cmake/creator-projects-settings-cmake.qdoc new file mode 100644 index 00000000000..24f65674e30 --- /dev/null +++ b/doc/qtcreator/src/cmake/creator-projects-settings-cmake.qdoc @@ -0,0 +1,75 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-configure-cmake-for-project.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-projects-configure + \ingroup creator-how-to-build-with-cmake + + \title Override CMake settings for a project + + To override CMake settings for the current project: + + \list 1 + \li Go to \uicontrol Projects > \uicontrol {Project Settings} > + \uicontrol CMake. + \image qtcreator-project-settings-cmake.webp {CMake settings for a project} + \li Clear \uicontrol {Use global settings}. + \li Configure CMake for the project. + \endlist + + Your choices override the values you set in \preferences > \uicontrol CMake > + \uicontrol General. + + \table + \header + \li Setting + \li Value + \li Read More + \row + \li Autorun CMake + \li Runs CMake to refresh project information when you edit + a \c CMakeLists.txt configuration file in a project. Also, + refreshes project information when you build the project. + \li \l{View CMake project contents} + \row + \li Package manager auto setup + \li Sets up the \l {Conan Package Manager}{Conan} or + \l {vcpkg Package Manager}{vcpkg} package manager for use with CMake. + \li \l{Using CMake with Package Managers} + \row + \li Ask before re-configuring with initial parameters + \li Asks before acting when you select + \uicontrol {Re-configure with Initial Variables}. + \li \l{Re-configuring with Initial Variables} + \row + \li Ask before reloading CMake presets + \li Asks before acting when you select \uicontrol Build > + \uicontrol {Reload CMake Presets}. + \li \l{CMake Presets} + \row + \li Show subfolders inside source group folders + \li Hides subfolder names and arranges the files according to their + source group in the \uicontrol Projects view. + \li \l{Hide subfolder names in Projects view} + \row + \li Show advanced options by default + \li Shows all CMake variables by default in + \uicontrol {Initial Configuration} and + \uicontrol {Current Configuration}. + \li \l{Viewing Advanced Variables} + \row + \li Use junctions for CMake configuration and build operations + \li On Windows, uses junction points for CMake configure, build, and + install operations. + \li \l{Using Junction Points on Windows} + \endtable + + You can set these preferences as \l{Configure Presets}{CMake presets} or in + a \l{Share project settings}{CMakeLists.txt.shared} file. + + \sa {Build with CMake}{How To: Build with CMake}, {CMake}, + {Configuring Projects} +*/ diff --git a/doc/qtcreator/src/conan/creator-projects-conan-building.qdoc b/doc/qtcreator/src/conan/creator-projects-conan-building.qdoc index 55f71c40d05..81ecd115756 100644 --- a/doc/qtcreator/src/conan/creator-projects-conan-building.qdoc +++ b/doc/qtcreator/src/conan/creator-projects-conan-building.qdoc @@ -11,7 +11,7 @@ \brief Settings for building applications with the Conan package manager. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. @@ -30,5 +30,5 @@ Select \uicontrol {Build missing} to build packages from source if binary packages are not found. - \sa {Conan Package Manager} + \sa {Activate kits for a project}, {Conan Package Manager} */ diff --git a/doc/qtcreator/src/conan/creator-projects-conan.qdoc b/doc/qtcreator/src/conan/creator-projects-conan.qdoc index 0e7229ba7c3..67cdd9141ae 100644 --- a/doc/qtcreator/src/conan/creator-projects-conan.qdoc +++ b/doc/qtcreator/src/conan/creator-projects-conan.qdoc @@ -44,9 +44,16 @@ Then, you must edit the build settings of the project to specify the location of the file and the contents of the Conan install command. - Alternatively, you can automatically set up the Conan package manager for - use with CMake. + \section1 Automatic Package Manager Setup + + To automatically set up the Conan package manager for use with CMake, + go to \uicontrol Projects > \uicontrol {Project Settings} > \uicontrol CMake, + and select \uicontrol {Package manager auto setup}. + + To turn off the automatic package manager setup, set + \c PackageManagerAutoSetup to \c false in \l{Configure Presets} + {CMake presets} or a \l{Share project settings}{CMakeLists.txt.shared} file. \sa {Conan Build Configuration}, {Enable and disable plugins}, - {Using CMake with Package Managers} + {Override CMake settings for a project}, {Using CMake with Package Managers} */ diff --git a/doc/qtcreator/src/debugger/creator-debug-views.qdoc b/doc/qtcreator/src/debugger/creator-debug-views.qdoc index 149ac127a8c..8880b64218b 100644 --- a/doc/qtcreator/src/debugger/creator-debug-views.qdoc +++ b/doc/qtcreator/src/debugger/creator-debug-views.qdoc @@ -6,12 +6,17 @@ \if defined(qtdesignstudio) \previouspage creator-debugging-qml.html \else - \previouspage creator-debug-mode.html + \previouspage creator-reference.html \endif - \nextpage creator-breakpoints-view.html + + \ingroup creator-reference-debugger-views + \ingroup studio-debugger-views \title Viewing Call Stack Trace + \brief View the nested function calls leading to the current position as a + call stack trace. + When the application being debugged is interrupted, \QC displays the nested function calls leading to the current position as a call stack trace. This stack trace is built up from call stack frames, each representing a @@ -40,19 +45,27 @@ from the stopped executable and prepends the frames to the C++ frames, should it find any. You can click a frame in the QML stack to open the QML file in the editor. + + \if defined(qtcreator) + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} + \endif */ /*! \page creator-breakpoints-view.html - \previouspage creator-stack-view.html \if defined(qtdesignstudio) - \nextpage creator-locals-view.html + \previouspage creator-debugging-qml.html \else - \nextpage creator-threads-view.html + \previouspage creator-reference.html \endif + \ingroup creator-reference-debugger-views + \ingroup studio-debugger-views + \title Setting Breakpoints + \brief Set breakpoints to interrupt the application. + You can associate breakpoints with: \list @@ -128,7 +141,27 @@ \image qtcreator-debug-breakpoints.webp {Breakpoints view} - \section1 Adding Breakpoints + \if defined(qtdesignstudio) + For more information, see: + + \generatelist studio-how-to-debug + \else + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} + \endif +*/ + +/*! + \page creator-how-to-add-breakpoints.html + \if defined(qtdesignstudio) + \previouspage creator-breakpoints-view.html + \else + \previouspage creator-how-tos.html + \endif + + \ingroup creator-how-to-debug + \ingroup studio-how-to-debug + + \title Add breakpoints To add breakpoints: @@ -139,7 +172,7 @@ \list \li In the code editor, click the left margin or press \key F9 - (\key F8 on \macos) on a particular line you want the + (\key F8 on \macos) on a particular line where you want the application to stop. \li In the \uicontrol {Breakpoint Preset} view or the @@ -152,13 +185,13 @@ \endlist \endlist - \li In the \uicontrol {Breakpoint type} field, select the location in the + \li In \uicontrol {Breakpoint type}, select the location in the application code where you want the application to stop. \image qtcreator-add-breakpoint.webp {Add Breakpoints} dialog \endlist - Deselect the \uicontrol Enabled check box to make the breakpoint temporarily + Clear \uicontrol Enabled to make the breakpoint temporarily inoperative as if you had deleted it, but keep the information about the breakpoint, so that you can enable it again later. @@ -216,59 +249,37 @@ \endtable \if defined(qtcreator) - \section1 Specifying Breakpoint Settings + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} + \endif +*/ - You can specify settings for breakpoints in \preferences > - \uicontrol Debugger. For more information, see \l{Debugger Preferences}. - - \image qtcreator-debugger-general-options.png {General tab in Debugger preferences} - - To use a full absolute path in breakpoints, select the - \uicontrol {Set breakpoints using a full absolute path} check box. - - GDB and CDB enable setting breakpoints on source lines for which no code - was generated. In such situations, the breakpoint is shifted to the next - source code line for which the code was actually generated. To reflect - such temporary changes by moving the breakpoint markers in the source code - editor, select \uicontrol GDB > \uicontrol {Adjust breakpoint locations} - or \uicontrol CDB > \uicontrol {Correct breakpoint location}. - - When using GDB as backend, you can extend the ordinary GDB - breakpoint class by using Python. Select \uicontrol GDB > - \uicontrol {Use pseudo message tracepoints}. - - When using CDB as backend, you can specify that the debugger should break on - specific events, such as C++ exceptions, thread creation or exit, loading or - unloading \l{Viewing Modules}{application modules}, or particular output. - Select the appropriate check boxes in the \uicontrol CDB > - \uicontrol {Break on} group. To disable first-chance break on access - violation exceptions, select the \uicontrol {Ignore first chance access - violations} check box. The second occurrence of an access violation will - break into the debugger. - - You can automatically add breakpoints on some functions to catch error - and warning messages. For more information, see \l{Specifying CDB Settings} - and \l{Specifying GDB Settings}. - - For more information on breakpoints, see - \l{http://sourceware.org/gdb/onlinedocs/gdb/Breakpoints.html#Breakpoints} - {Breakpoints, Watchpoints, and Catchpoints} in GDB documentation. +/*! + \page creator-how-to-manage-breakpoints.html + \if defined(qtdesignstudio) + \previouspage creator-breakpoints-view.html + \else + \previouspage creator-how-tos.html \endif - \section1 Moving Breakpoints + \ingroup creator-how-to-debug + \ingroup studio-how-to-debug + + \title Manage breakpoints + + \section1 Move breakpoints To move a breakpoint: \list - \li Drag and drop a breakpoint marker to another line + \li Drag a breakpoint marker to another line in the text editor. \li In the \uicontrol {Breakpoint Preset} view or the \uicontrol Breakpoints view, select \uicontrol {Edit Selected Breakpoints}, and set the - line number in the \uicontrol {Line number} field. + line number in \uicontrol {Line number}. \endlist - \section1 Deleting Breakpoints + \section1 Delete breakpoints To delete breakpoints: @@ -288,9 +299,9 @@ \endlist - \section1 Enabling and Disabling Breakpoints + \section1 Turn breakpoints on and off - To temporarily disable a breakpoint without deleting it and losing associated + To temporarily turn off a breakpoint without deleting it and losing associated data like conditions and commands: \list @@ -316,7 +327,23 @@ Other than data breakpoints retain their enabled or disabled state when the debugged application is restarted. - \section1 Setting Data Breakpoints + \if defined(qtcreator) + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} + \endif +*/ + +/*! + \page creator-how-to-set-data-breakpoints.html + \if defined(qtdesignstudio) + \previouspage creator-breakpoints-view.html + \else + \previouspage creator-how-tos.html + \endif + + \ingroup creator-how-to-debug + \ingroup studio-how-to-debug + + \title Set data breakpoints A \e {data breakpoint} stops the application when data is read or written at the specified address. @@ -328,11 +355,10 @@ \li In the \uicontrol {Breakpoint Preset} or \uicontrol Breakpoints view, select \uicontrol {Add Breakpoint} in the context menu. - \li In the \uicontrol {Breakpoint type} field, select + \li In \uicontrol {Breakpoint type}, select \uicontrol {Break on data access at fixed address}. - \li In the \uicontrol Address field, specify the address of the memory - block. + \li In \uicontrol Address, specify the address of the memory block. \li Select \uicontrol OK. @@ -349,21 +375,25 @@ it manually. \if defined(qtcreator) - \sa {Debug CMake project files} + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} \endif */ /*! \page creator-locals-view.html \if defined(qtdesignstudio) - \previouspage creator-breakpoints-view.html + \previouspage creator-debugging-qml.html \else - \previouspage creator-source-files-view.html + \previouspage creator-reference.html \endif - \nextpage creator-expressions-view.html + + \ingroup creator-reference-debugger-views + \ingroup studio-debugger-views \title Local Variables and Function Parameters + \brief Inspect local variables and function parameters. + The \uicontrol {Locals} view consists of the \uicontrol Locals pane and the \uicontrol {Return Value} pane (hidden when empty). @@ -388,18 +418,18 @@ //! [0] \list \li Add and remove expression evaluators - \li Change \l{Changing Value Display format}{value display format} + \li \l{Change value display format} \li Expand and collapse view contents \li Copy view contents or expression values to the clipboard \li Open view contents in an editor \li Open memory editor \li Set data breakpoints - \li Use \l{Using Debugging Helpers}{debugging helpers} + \li Use \l{Debugging Helpers}{debugging helpers} \li Show and hide tooltips in the view when debugging \li Dereference pointers automatically \li Sort members of classes and structs alphabetically \li Use dynamic object type for display - \li Set \l{Debugger Preferences}{debugger preferences} + \li Set debugger preferences \endlist //! [0] \endif @@ -410,19 +440,27 @@ objects will be displayed. Select \uicontrol {Use dynamic object type for display} in the context menu. Keep in mind that choosing the dynamic type might be slower. + + \if defined(qtcreator) + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} + \endif */ /*! \page creator-expressions-view.html - \previouspage creator-locals-view.html \if defined(qtdesignstudio) - \nextpage creator-qml-debugging-example.html + \previouspage creator-debugging-qml.html \else - \nextpage creator-registers-view.html + \previouspage creator-reference.html \endif + \ingroup creator-reference-debugger-views + \ingroup studio-debugger-views + \title Evaluating Expressions + \brief Compute values of arithmetic expressions or function calls. + To compute values of arithmetic expressions or function calls, use expression evaluators in the \uicontrol Expressions view. @@ -515,5 +553,7 @@ appears uninitialized, its value is reported as \uicontrol {not in scope}. Not all uninitialized objects, however, can be recognized as such. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} \endif */ diff --git a/doc/qtcreator/src/debugger/creator-only/creator-debugger-example.qdoc b/doc/qtcreator/src/debugger/creator-only/creator-debugger-example.qdoc index ccc9e82fd1b..964bbaf5e1b 100644 --- a/doc/qtcreator/src/debugger/creator-only/creator-debugger-example.qdoc +++ b/doc/qtcreator/src/debugger/creator-only/creator-debugger-example.qdoc @@ -95,5 +95,5 @@ (\uicontrol {Step Into}), and \inlineimage icons/debugger_stepout_small.png (\uicontrol {Step Out}). - \sa {Creating a Qt Widget Based Application}, {Debugging} + \sa {Creating a Qt Widget Based Application}, {Debugging}, {Debuggers}, {Debugger} */ diff --git a/doc/qtcreator/src/debugger/creator-only/creator-debugger-settings.qdoc b/doc/qtcreator/src/debugger/creator-only/creator-debugger-settings.qdoc index 4583460cb42..b3fef5c0e32 100644 --- a/doc/qtcreator/src/debugger/creator-only/creator-debugger-settings.qdoc +++ b/doc/qtcreator/src/debugger/creator-only/creator-debugger-settings.qdoc @@ -3,20 +3,22 @@ /*! \page creator-debugger-preferences.html - \previouspage creator-remote-debugging.html - \nextpage creator-debugging-helpers.html + \previouspage creator-reference.html - \title Debugger Preferences + \ingroup creator-reference-preferences-debugger - To specify settings for managing debugger processes, select \preferences > - \uicontrol Debugger. In the \uicontrol General tab,you can specify settings + \title General + + \brief Customize debug views and map source paths. + + To specify settings for managing debugger processes, go to \preferences > + \uicontrol Debugger. In the \uicontrol General tab, you can specify settings that are common to all debuggers. \image qtcreator-debugger-general-options.png "Debugger General preferences" - You can customize the appearance and behavior of the debug views, - \l{Specifying Breakpoint Settings}{specify settings for breakpoints}, - and map source paths to target paths. + You can customize the appearance and behavior of the debug views and + setting breakpoints, as well as map source paths to target paths. You can view debug output in the \l {Debugger Log} view. However, in some Linux distributions, such as Arch Linux, debug @@ -26,7 +28,39 @@ application, which effectively prevents storing debug output in system logs. - \section1 Mapping Source Paths + \section1 Breakpoints + + To use a full absolute path in breakpoints, select the + \uicontrol {Set breakpoints using a full absolute path} check box. + + GDB and CDB enable setting breakpoints on source lines for which no code + was generated. In such situations, the breakpoint is shifted to the next + source code line for which the code was actually generated. To reflect + such temporary changes by moving the breakpoint markers in the source code + editor, select \uicontrol GDB > \uicontrol {Adjust breakpoint locations} + or \uicontrol CDB > \uicontrol {Correct breakpoint location}. + + When using GDB as backend, you can extend the ordinary GDB + breakpoint class by using Python. Select \uicontrol GDB > + \uicontrol {Use pseudo message tracepoints}. + + When using CDB as backend, you can specify that the debugger should break on + specific events, such as C++ exceptions, thread creation or exit, loading or + unloading \l{Viewing Modules}{application modules}, or particular output. + Select the appropriate check boxes in the \uicontrol CDB > + \uicontrol {Break on} group. To disable first-chance break on access + violation exceptions, select the \uicontrol {Ignore first chance access + violations} check box. The second occurrence of an access violation will + break into the debugger. + + You can automatically add breakpoints on some functions to catch error + and warning messages. For more information, see \l{CDB} and \l{GDB}. + + For more information on breakpoints, see + \l{http://sourceware.org/gdb/onlinedocs/gdb/Breakpoints.html#Breakpoints} + {Breakpoints, Watchpoints, and Catchpoints} in GDB documentation. + + \section1 Source Paths Mapping To enable the debugger to step into the code and display the source code when using a copy of the source tree at a location different from the one @@ -48,52 +82,79 @@ of the source tree on the local machine. \endlist - \section1 Specifying GDB Settings + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ - To specify settings for managing the GDB process, select \preferences > +/*! + \page creator-preferences-debugger-gdb.html + \previouspage creator-reference.html + + \ingroup creator-reference-preferences-debugger + + \title GDB + + \brief Manage the GDB process. + + To specify settings for managing the GDB process, go to \preferences > \uicontrol Debugger > \uicontrol GDB. \image qtcreator-preferences-debugger-gdb.webp {GDB preferences} - To specify a timeout for terminating non-responsive GDB processes, set the - number of seconds to wait in the \uicontrol {GDB timeout} field. The default - value of 20 seconds should be sufficient for most applications, but if - loading big libraries or listing source files takes much longer than - that on slow machines, you should increase the value. + The following table summarizes the preferences. - To compress several steps into one step for less noisy debugging when - stepping into code, select the \uicontrol {Skip known frames when stepping} - check box. For example, the atomic reference counting code is skipped, and - a single \e {Step Into} for a signal emission ends up directly in the slot - connected to it. + \table + \header + \li Setting + \li Value + \row + \li \uicontrol {GDB timeout} + \li The timeout for terminating non-responsive GDB processes in seconds + The default value of 40 seconds should be sufficient for most + applications, but if loading big libraries or listing source files + takes much longer than that on slow machines, increase the value. + \row + \li \uicontrol {Skip known frames when stepping} + \li Compresses several steps into one step for less noisy debugging when + stepping into code. For example, the atomic reference counting code + is skipped, and a single \e {Step Into} for a signal emission ends up + directly in the slot connected to it. + \row + \li \uicontrol {Show a message box when receiving a signal} + \li Shows a message box as soon as your application receives a signal, + such as SIGSEGV, during debugging. + \row + \li \uicontrol {Adjust breakpoint locations} + \li GDB allows setting breakpoints on source lines for which no code was + generated. In such situations, the breakpoint is shifted to the next + source code line for which the code was actually generated. To reflect + such temporary changes by moving the breakpoint markers in the source + code editor, select this checkbox. + \row + \li \uicontrol {Use dynamic object type for display} + \li Whether the dynamic or the static type of objects will be + displayed. Choosing the dynamic type might make debugging slower. + \row + \li \uicontrol {Load .gdbinit file on startup} + \li Reads the user's default .gdbinit file on debugger startup. + \row + \li \uicontrol {Load system GDB pretty printers} + \li Uses the default GDB pretty printers installed on the computer + or linked to the libraries your application uses. + \row + \li \uicontrol {Use Intel style disassembly} + \li Switches from the default AT&T style disassembly to the Intel style. + \row + \li \uicontrol {Use automatic symbol cache} + \li Automatically saves a copy of the GDB symbol index in a cache on disk + and retrieves it from there when loading the same binary in the + future. + \row + \li \uicontrol {Use debug info daemon} + \li Tries to automatically retrieve debug information for system + packages. + \endtable - To display a message box as soon as your application receives a signal, such - as SIGSEGV, during debugging, select the \uicontrol {Show a message box when - receiving a signal} check box. - - GDB allows setting breakpoints on source lines for which no code was - generated. In such situations, the breakpoint is shifted to the next - source code line for which the code was actually generated. To reflect - such temporary changes by moving the breakpoint markers in the source - code editor, select the \uicontrol {Adjust breakpoint locations} check box. - - To specify whether the dynamic or the static type of objects will be - displayed, select the \uicontrol {Use dynamic object type for display} - check box. Keep in mind that choosing the dynamic type might be slower. - - To allow reading the user's default .gdbinit file on debugger startup, - select the \uicontrol {Load .gdbinit file on startup} check box. - - To use the default GDB pretty printers installed in your system - or linked to the libraries your application uses, select the - \uicontrol {Load system GDB pretty printers} check box. - - By default, GDB shows AT&T style disassembly. To switch to the Intel style, - select the \uicontrol {Use Intel style disassembly} check box. - - To have GDB automatically save a copy of its symbol index in a cache - on disk and retrieve it from there when loading the same binary in the - future, select the \uicontrol {Use automatic symbol cache} check box. + \section1 Executing Additional Commands To execute GDB commands after GDB has been started, but before the debugged application is started or attached, and before the debugging helpers are @@ -111,85 +172,134 @@ To execute arbitrary Python scripts, use \c {python execfile('/path/to/script.py')}. - \section2 Extended GDB Settings + \section1 Extended GDB Settings The settings in the \uicontrol Extended group give access to advanced or experimental functions of GDB. Enabling them may negatively impact your debugging experience, so use them with care. - To use asynchronous mode to control the inferior, select the - respective check box. + \table + \header + \li Setting + \li Value + \row + \li \uicontrol {Use asynchronous mode to control the inferior} + \li Execute commands in the background (asynchronous) mode. + GDB immediately opens a command prompt where you can issue + other commands while your program runs. + \row + \li \uicontrol {Use common locations for debug information} + \li Adds common paths to locations of debug information, such as + \c {/usr/src/debug}, when starting GDB. + \row + \li \uicontrol {Stop when qWarning() is called} + \li Adds a breakpoint on each \c qWarning() function. + \row + \li \uicontrol {Stop when qFatal() is called} + \li Adds a breakpoint on each \c qFatal() function. + \row + \li \uicontrol {Stop when abort() is called} + \li Adds a breakpoint on each \c abort() function. + \row + \li \uicontrol {Enable reverse debugging} + \li Enables stepping backwards. This feature is very slow and unstable + on the GDB side. It exhibits unpredictable behavior when steapping + backwards over system calls and is very likely to destroy your + debugging session. + \row + \li\uicontrol {Debug all child processes} + \li Keeps debugging all children after a fork. + \endtable - To add common paths to locations of debug information, such as - \c {/usr/src/debug}, when starting GDB, select the - \uicontrol {Use common locations for debug information} check box. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ - To stop when \c qWarning, \c qFatal, or \c abort is called, select the - respective check box. +/*! + \page creator-preferences-debugger-cdb.html + \previouspage creator-reference.html - To enable stepping backwards, select the \uicontrol {Enable reverse - debugging} check box. This feature is very slow and unstable on the - GDB side. It exhibits unpredictable behavior when going backwards over - system calls and is very likely to destroy your debugging session. + \ingroup creator-reference-preferences-debugger - To keep debugging all children after a fork, select the - \uicontrol {Debug all child processes} check box. + \title CDB - \section1 Specifying CDB Settings + \brief Manage the CDB process. - To specify settings for managing the CDB process, select \preferences > + To specify settings for managing the CDB process, go to \preferences > \uicontrol Debugger > \uicontrol CDB. \image qtcreator-cdb-options.png "CDB preferences" - You can specify additional arguments for starting CDB in the - \uicontrol {Additional arguments} field. + The following table summarizes the preferences. - If a console application does not start up properly in the configured - console and the subsequent attach fails, you can diagnose the issue by - using CDB's native console. Select the \uicontrol {Use CDB console} - check box to override the console set in the Windows system - environment variables. Note that the native console does not - prompt on application exit. + \table + \header + \li Setting + \li Value + \row + \li \uicontrol {Additional arguments} + \li Additional arguments for starting CDB. + \row + \li \uicontrol {Use CDB console} + \li If a console application does not start up properly in the configured + console and the subsequent attach fails, diagnose the issue by + using CDB's native console. Select this checkbox to override the + console set in the Windows system environment variables. Note that + the native console does not prompt on application exit. + \row + \li \uicontrol {Ignore first chance access violations} + \li Disables first-chance break on access violation exceptions. + The second occurrence of an access violation will break into the + debugger. + \row + \li \uicontrol {Stop when CrtDbgReport() is called} + \li Automatically adds a breakpoint on the \c CrtDbgReport() function to + catch runtime error messages caused by \c assert(), for example. + \row + \li \uicontrol {Correct breakpoint location} + \li CDB enables setting breakpoints in comments or on source lines for + which no code was generated. In such situations, the breakpoint is + shifted to the next source code line for which the code was actually + generated. To reflect such temporary changes by moving the breakpoint + markers in the source code editor, select this checkbox. For more + information, see \l{Setting Breakpoints}. + \row + \li \uicontrol {Use Python dumper} + \li Uses the abstraction layer of Python Dumper classes to create a + description of data items in the \uicontrol Locals and + \uicontrol Expressions views. + For more information, see \l{Debugging Helper Implementation}. + \row + \li \uicontrol {Break on} + \li Whether the debugger should break on C++ exceptions, on thread + creation or exit, on loading or unloading the specified + \l{Viewing Modules}{application modules}, or on the specified output. + \row + \li \uicontrol {Add Exceptions to Issues View} + \li Shows information about first-chance and second-chance exceptions + in \l Issues. + \endtable - To automatically add a breakpoint on the \c CrtCbgReport() function, - select the \uicontrol {Stop when CrtCbgReport() is called} check box. - This catches runtime error messages caused by \c assert(), for example. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ - In the \uicontrol {Break on} group, specify whether the debugger should - break on C++ exceptions, on thread creation or exit, on loading or - unloading the specified \l{Viewing Modules}{application modules}, or on - the specified output. +/*! + \page creator-preferences-debugger-cdb-paths.html + \previouspage creator-reference.html - To disable first-chance break on access violation exceptions, select the - \uicontrol {Ignore first chance access violations} check box. - The second occurrence of an access violation will break into the debugger. + \ingroup creator-reference-preferences-debugger - CDB enables setting breakpoints in comments or on source lines for which - no code was generated. In such situations, the breakpoint is shifted to - the next source code line for which the code was actually generated. To - reflect such temporary changes by moving the breakpoint markers in the - source code editor, select the \uicontrol {Correct breakpoint location} - check box. For more information, see \l{Setting Breakpoints}. + \title CDB Paths - To use the abstraction layer of Python Dumper classes to create a description - of data items in the \uicontrol Locals and \uicontrol Expressions - views, select the \uicontrol {Use Python dumper} check box. - For more information, see \l{Debugging Helper Implementation}. - - To display information about first-chance and second-chance exceptions - in \l Issues, select the check boxes - in the \uicontrol {Add Exceptions to Issues View} group. - - \section1 Setting CDB Paths on Windows + \brief Add the Microsoft Symbol Server to the symbol search path of the + debugger. To obtain debugging information for the operating system libraries for debugging Windows applications, add the Microsoft Symbol Server to the symbol search path of the debugger: \list 1 - \li Select \preferences > \uicontrol Debugger > \uicontrol {CDB Paths}. + \li Go to \preferences > \uicontrol Debugger > \uicontrol {CDB Paths}. \image qtcreator-debugger-cdb-paths.png \li In the \uicontrol {Symbol Paths} group, select \uicontrol Insert. \li Select the directory where you want to store the cached information. @@ -204,4 +314,6 @@ To use the Source Server infrastructure for fetching missing source files directly from version control or the web, enter the following string in the \uicontrol {Source Paths} field: \c srv*. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ diff --git a/doc/qtcreator/src/debugger/creator-only/creator-debugger-setup.qdoc b/doc/qtcreator/src/debugger/creator-only/creator-debugger-setup.qdoc index 66386d72c0a..a6bc84a87b0 100644 --- a/doc/qtcreator/src/debugger/creator-only/creator-debugger-setup.qdoc +++ b/doc/qtcreator/src/debugger/creator-only/creator-debugger-setup.qdoc @@ -9,61 +9,22 @@ /*! - \previouspage creator-debugging.html \page creator-debugger-engines.html - \nextpage creator-debugger-operating-modes.html + \previouspage creator-reference.html - \title Setting Up Debugger + \ingroup creator-reference-debugger - The main debugger preferences are associated with the - \l{kits-tab}{kit} you build and run your project with. To - specify the debugger and compiler to use for each kit, select - \preferences > \uicontrol Kits. + \title Supported Debuggers - \image qtcreator-kits.png {Kits preferences} + \brief Summary of supported debugger versions. - You need to set up the debugger only if the automatic setup fails because - the native debugger is missing (for example, you must install the CDB - debugger on Windows yourself) or because \QC does not support the installed - version. For example, when your system does not have GDB - installed or the installed version is outdated, and you want to use a locally - installed replacement instead. - - To change the debugger in an automatically detected kit, select - \preferences > \uicontrol Kits > - \uicontrol Clone to create a copy of the kit, and change the - parameters in the cloned kit. Make sure to enable the cloned kit - for your project. - - If the debugger you want to use is not automatically detected, select - \preferences > \uicontrol Kits > - \uicontrol Debuggers > \uicontrol Add to add it. - - \image qtcreator-preferences-kits-debuggers.webp {Debuggers tab in Kits preferences} - - To use the debugging tools for Windows, you must install them. - Optionally, you can set up the Microsoft Symbol Server if you need - symbol information from Microsoft modules that is not found locally. - For more information, see \l{Setting CDB Paths on Windows}. - - To use the Free Software Foundation (FSF) version of GDB on \macos, you - must sign it and modify your kit preferences. - - This section describes the options you have for debugging C++ and Python code - and installing the supported native debuggers. It also - applies to code in other compiled languages such as C, FORTRAN, and Ada. - - For more information about launching the debugger in different modes, see - \l{Debugger Operating Modes}. - - \section1 Supported Native Debugger Versions - - \QC supports native debuggers for debugging compiled code. + You can use \QC to debug compiled code. On most supported platforms, you can use the GNU Symbolic Debugger (GDB). - On Microsoft Windows, when using the Microsoft tool chain, you need the + On Microsoft Windows, when using the Microsoft toolchain, you need the Microsoft Console Debugger (CDB). On \macos and Linux, you can use the LLDB - debugger. On all supported platforms, you can use PDB to debug Python source - code. + debugger. + + On all supported platforms, you can use PDB to debug Python source code. \note You need a debugger version built with Python scripting support. @@ -73,7 +34,7 @@ \header \li Platform \li Compiler - \li Native Debugger + \li Debugger \row \li Linux \li GCC, ICC @@ -85,7 +46,7 @@ \row \li \macos \li GCC, Clang - \li LLDB, FSF GDB (experimental) + \li LLDB \row \li Windows/\MinGW \li GCC @@ -96,7 +57,12 @@ \li Debugging Tools for Windows/CDB \endtable - \section2 Supported GDB Versions + \QC automatically selects a suitable debugger for + each \l{Kits}{kit} from the ones found on the computer. The automatic + setup fails if the debugger is not installed on the computer or + if \QC does not support the installed version. + + \section1 GDB Versions Use GDB 7.5, or later, with the Python scripting extension and Python version 3.5, or later. @@ -104,49 +70,6 @@ For remote debugging using GDB and GDB server, the minimum supported version of GDB server on the target \l{glossary-device}{device} is 7.0. - \section2 Supported CDB Versions - - \QC supports all versions of CDB targeting platforms that Qt supports. - - \section2 Supported LLDB Versions - - The LLDB native debugger has similar functionality to the GDB debugger. LLDB - is the default debugger in Xcode on \macos for C++ on the desktop. - LLDB is typically used with the Clang compiler (even though you can use it - with GCC, too). - - On \macos you can use the LLDB version delivered with Xcode or build from source. - The minimum supported version is LLDB 320.4. You need a LLDB version built - with Python support. - - On Linux, the minimum supported version is LLDB 3.8. - - \section2 GDB Run Modes - - The GDB native debugger used internally by the debugger plugin runs in - different modes to cope with the variety of supported platforms and - environments: - - \list - - \li Plain mode debugs locally started processes that do not need console input. - - \li Terminal mode debugs locally started processes that need a console. - - \li Attach mode debugs local processes started outside \QC. - - \li Core mode debugs core files generated from crashes. - - \li Remote mode interacts with the GDB server running on Linux. - - \endlist - - \section1 Installing Native Debuggers - - The following sections describe installing native debuggers. - - \section2 GDB - On Windows, use the Python-enabled GDB version that is bundled with the Qt package or comes with recent versions of \MinGW. On most Linux distributions, the GDB builds shipped with the system @@ -157,7 +80,9 @@ Builds of GDB shipped with Xcode on \macos are no longer supported. - \section2 Debugging Tools for Windows + \section1 Debugging Tools for Windows + + \QC supports all versions of CDB targeting platforms that Qt supports. To use the CDB debugger, install the \e {Debugging Tools for Windows} when you install \QC either by using \QOI (in \uicontrol Qt @@ -180,12 +105,12 @@ the required files in \c{"%ProgramFiles%\Debugging Tools for Windows"}. - \section2 Debugging Tools for \macos + \section1 Debugging Tools for \macos The Qt binary distribution has both debug and release variants of the libraries. However, you have to explicitly tell the runtime linker that you want to use the debug libraries even if - your application is compiled as debug, as release is the default + your application is compiled as \e debug because \e release is the default library. If you use a qmake based project in \QC, you can set a flag in @@ -196,88 +121,32 @@ For more detailed information about debugging on \macos, see: \l{http://developer.apple.com/library/mac/#technotes/tn2124/_index.html#//apple_ref/doc/uid/DTS10003391} {Mac OS X Debugging Magic}. + \section1 LLDB Versions - \section2 LLDB + The LLDB debugger has similar functionality to the GDB debugger. LLDB + is the default debugger in Xcode on \macos for C++ on the desktop. + LLDB is typically used with the Clang compiler (even though you can use it + with GCC, too). + + On \macos you can use the LLDB version delivered with Xcode or build from source. + The minimum supported version is LLDB 320.4. You need a LLDB version built + with Python support. We recommend using the LLDB version that is delivered with the latest Xcode. - \section2 PDB + On Linux, the minimum supported version is LLDB 3.8. + + \section1 PDB Versions \l{https://docs.python.org/3/library/pdb.html}{PDB} is a source code debugger for Python applications. You can use it to debug projects that have a \l {Creating a Qt for Python Application with Qt Widgets}{.pyproject} configuration file. - You must install Python and set the interpreter to use in \uicontrol Projects - > \uicontrol Run: + Install Python and set the interpreter to use in \uicontrol Projects + > \uicontrol Run. \image qtcreator-run-settings-python.webp {Run settings for a Python project} - Start debugging the \c main.py file. If you encounter problems, check the - active build target in the kit selector. - - \QC does not support mixed-mode debugging, but you can attach GDB to the - Python interpreter to debug the C++ implementation of the corresponding - Python code. For more information, see - \l{https://doc.qt.io/qtforpython-6/tutorials/debugging/qtcreator/qtcreator.html} - {Debugging PySide with Qt Creator (Linux)}. - - \section1 Setting up FSF GDB for \macos - - To use FSF GDB on \macos, you must sign it and add it to the \QC - \l{glossary-buildandrun-kit}{kits}. - - \list 1 - - \li To create a key for signing FSF GDB, select - \uicontrol {Keychain Access} > \uicontrol {Certificate Assistant} > - \uicontrol {Create a Certificate}: - - \list 1 - - \li In the \uicontrol Name field, input \uicontrol fsfgdb to - replace the existing content. - - \li In the \uicontrol {Certificate Type} field, select - \uicontrol {Code Signing}. - - \li Select the \uicontrol {Let me override defaults} check box. - - \li Select \uicontrol Continue, and follow the instructions of the - wizard (use the default settings), until the - \uicontrol {Specify a Location For The Certificate} dialog - opens. - - \li In the \uicontrol Keychain field, select \uicontrol System. - - \li Select \uicontrol {Keychain Access} > \uicontrol System, and - locate the certificate. - - \li Double click the certificate to view certificate information. - - \li In the \uicontrol Trust section, select - \uicontrol {Always Trust} in the - \uicontrol {When using this certificate} field, and then close - the dialog. - - \endlist - - \li To sign the binary, enter the following command in the terminal: - - \code - codesign -f -s "fsfgdb" $INSTALL_LOCATION/fsfgdb - \endcode - - \li In \QC, select \uicontrol {\QC} > \uicontrol Preferences > - \uicontrol Kits > \uicontrol Add to - create a kit that uses FSF GDB. - - \li In the \uicontrol Debugger field, specify the path to FSF GDB - (\c $HOME/gdb72/bin/fsfgdb, but with an explicit value for - \c $HOME). - - \li To use the debugger, enable the kit in the \uicontrol {Build Settings} - of the project. - - \endlist + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, {Kits} */ diff --git a/doc/qtcreator/src/debugger/creator-only/creator-debugger.qdoc b/doc/qtcreator/src/debugger/creator-only/creator-debugger.qdoc index d3441ab0630..6880c27b5a2 100644 --- a/doc/qtcreator/src/debugger/creator-only/creator-debugger.qdoc +++ b/doc/qtcreator/src/debugger/creator-only/creator-debugger.qdoc @@ -14,8 +14,7 @@ \title Debugging - The \QC debugger plugin acts as an interface between the \QC - core and external native debuggers that you can use to: + You can use debuggers to: \list \li Debug executable binary files - GNU Symbolic Debugger (GDB), @@ -26,94 +25,201 @@ \li Debug Python source code - PDB. \endlist - The following sections describe how to set up, launch, and interact with the - debugger: + \section1 Setting Up the Debugger + + \QC automatically selects a suitable debugger for + each \l{Kits}{kit} from the ones found on your system. You can select + another kit. To specify the debugger and compiler to use for each kit, go to + \preferences > \uicontrol Kits. + + \image qtcreator-kits.png {Kits preferences} + + You need to set up the debugger only if the automatic setup fails because + the debugger is missing (for example, you must install the CDB + debugger on Windows yourself) or because \QC does not support the installed + version. For example, when your system does not have GDB + installed or the installed version is outdated, and you want to use a locally + installed replacement instead. + + To change the debugger in an automatically detected kit, go to + \preferences > \uicontrol Kits > + \uicontrol Clone to create a copy of the kit, and change the + parameters in the cloned kit. Make sure to enable the cloned kit + for your project. + + If the debugger you want to use is not automatically detected, go to + \preferences > \uicontrol Kits > + \uicontrol Debuggers > \uicontrol Add to add it. + + \image qtcreator-preferences-kits-debuggers.webp {Debuggers tab in Kits preferences} + + To use the debugging tools for Windows, you must install them. + Optionally, you can set up the Microsoft Symbol Server if you need + symbol information from Microsoft modules that is not found locally. + + For more information, see \l{Supported Debuggers} and \l{CDB Paths}. + + \section1 Launching the Debugger + + The debuggers run in various operating modes + depending on where and how you start and run the debugged process. Some of + the modes are only available for a particular operating system or platform: + + \list + \li \e{Start internal} to debug applications developed inside \QC, such as + a Qt Widgets-based application. This is the default start mode for + most projects, including all projects using a desktop Qt version and + plain C++ projects. + \li \e{Start external} to start and debug processes without a proper \QC + project setup, either locally or on a remote machine. + \li \e{Attach} to debug processes already started and running outside + \QC, either locally or on a remote machine. + \li \e{Core} to debug crashed processes on Unix. + \li \e{Post-mortem} to debug crashed processes on Windows. + \endlist + + In general, \key F5 and the \uicontrol {Start Debugging of Startup Project} + button start the operating mode that fits the context. So, for a C++ + application that uses the \MinGW toolchain targeting desktop Windows, the GDB + engine starts in \e {start internal} mode. For a QML application that uses C++ + plugins, a \e mixed QML/C++ engine starts, with the C++ parts being + handled by GDB and GDB server remote debugging. + + Change the run configuration parameters (such as + \uicontrol {Run in Terminal}) in the run settings of the project, or select + options from the \uicontrol Debug > \uicontrol {Start Debugging} menu to + select other modes of operation. + + \section2 GDB Run Modes + + The GDB debugger runs in different modes to cope with the variety of + supported platforms and environments: + + \list + \li \e{Plain mode} debugs locally started processes that do not need + console input. + \li \e{Terminal mode} debugs locally started processes that need a + console. + \li \e{Attach mode} debugs local processes started outside \QC. + \li \e{Core mode} debugs core files generated from crashes. + \li \e{Remote mode} interacts with the GDB server running on Linux. + \endlist + + \section1 Stopping Applications + + You can interrupt a running application before it terminates + or to find out why the application does not work correctly. + Set breakpoints to stop the application for examining and changing + variables, setting new breakpoints or removing old ones, and then + continue running the application. + + Once the application starts running under the control of the debugger, it + behaves and performs as usual. + + To interrupt a running C++ application, go to \uicontrol Debug > + \uicontrol Interrupt. The debugger automatically interrupts + the application when it hits a \l {Setting Breakpoints}{breakpoint}. + + Once the application stops, \QC: \list - \li \l{Setting Up Debugger} + \li Retrieves data representing the \l{Viewing Call Stack Trace} + {call stack} at the application's current position. - The debugger plugin automatically selects a suitable - native debugger for each \l{glossary-buildandrun-kit}{kit} from the - ones found on your system. You can edit the kits to override this - choice. + \li Retrieves the contents of \l{Local Variables and Function Parameters} + {local variables}. - \li \l{Launching the Debugger} + \li Examines \l{Evaluating Expressions}{expressions}. - To start an application from an open project under the control - of a debugger, select the \inlineimage icons/qtcreator-debug-button.png - (\uicontrol {Start Debugging of Startup Project}) button or press - \key F5. Other, less common start options are available in the - \uicontrol Debug > \uicontrol {Start Debugging} menu. + \li Updates the \l{Viewing and Editing Register State}{Registers}, + \l{Viewing Modules}{Modules}, and \l{Viewing Disassembled Code} + {Disassembler} views if you are debugging C++ based applications. - \li \l{Debug Mode Views} - - Use the views in the \uicontrol Debug mode to inspect the - state of your application while debugging. - - \li \l{Stopping Applications} - - You can interrupt a running application before it terminates - or to find out why the application does not work correctly. - Set breakpoints to stop the application for examining and changing - variables, setting new breakpoints or removing old ones, and then - continue running the application. - - \li \l{Examining Data} - - You can examine variable values and data structures in detail. - - \li \l{Remote Debugging} - - You can debug an application that runs on a remote target with the - necessary helper processes also running. - - \li \l{Debugger Preferences} - - Specify preferences for managing debugger processes. You can specify - preferences that are common to all debuggers, or the native debugger - that you use, GDB or CDB. - - \li \l{Using Debugging Helpers} - - \QC is able to show complex data types in a customized, - user-extensible manner. For this purpose, it takes advantage of - two technologies, collectively referred to as \e {debugging - helpers}. - - \li \l{Debugging Qt Quick Projects} - - When debugging a Qt Quick application, you can inspect the state of - the application while debugging JavaScript functions. You can set - breakpoints, view call stack trace, and examine locals and - expressions. While the application is running, you can inspect QML - objects and user interfaces, as well as execute JavaScript - expressions. - - \li \l{Debugging a C++ Application} - - Illustrates how to debug C++ applications in \QC. - - \li \l{Debugging a Qt Quick Application} - - Illustrates how to debug Qt Quick applications in \QC. - - \li \l{Troubleshooting Debugger} - - If you encounter problems while debugging, check for possible - solutions to them. \endlist - \sa {Debug CMake project files} + You can examine and change variables, set or remove breakpoints, and then + continue running the application. + + \section1 Examining Data + + When the application stops, you can examine certain data in the debugger. The + availability of data depends on the compiler settings when compiling the + application and the exact location where the application stops. + + Unexpected events are called \e exceptions and the debugger can stop + the application when they occur. Going to the location in the code where + the exception occurred helps you investigate the problem and find ways to + fix it. + + If you have a variable that shows text, but the application does not display + it correctly, for example, your data might be incorrect or the code that sets + the display text might do something wrong. You can step through the code and + examine changes to the variable to find out where the error occurs. + + The following video shows how to examine variable values: + + \youtube EhJ1eV_6RH8 + + \section1 Remote Debugging + + \QC makes remote debugging easy. In general, the remote debugging setup + consist of a probe running on the remote computer and a counterpart running + on the host. The probe is either integrated into the running + process (for example, for QML debugging) or runs a separate process + (for example, when using GDB server on embedded Linux). The host + side typically consists of \QC itself, often with the help of an external + process, such as GDB or CDB. + + While this setup might look daunting, it is mostly invisible to the user of + \QC. To start debugging on a remote target with the necessary helper + processes running, activate the corresponding \l{Activate kits for a project} + {kit} in \uicontrol Projects > \uicontrol {Build & Run}, and then select a + function to start remote debugging in the \uicontrol Debug > + \uicontrol {Start Debugging} menu. + + Special use cases, such as attaching to a running process on the target, + might still require manual setup. You can debug an application that runs on + a remote target with the necessary helper processes also running. + + For more information, see \l{Debug remotely with GDB} and + \l{Debug remotely with CDB}. + + \section1 Using Debugging Helpers + + To show complex structures, such as \c QObjects or associative containers, + in a clear and concise manner, \QC uses Python scripts that are called + \l{Debugging Helpers}{debugging helpers}. + + \QC ships with debugging helpers for more than 200 of the most popular Qt + classes, standard C++ containers, and smart pointers, covering the usual + needs of a C++ application developer out-of-the-box. + + You can customize and add debugging helpers. + + \section1 QML and Qt Quick + + When debugging a Qt Quick application, you can inspect the state of + the application while debugging JavaScript functions. You can set + breakpoints, view call stack trace, and examine locals and + expressions. While the application is running, you can inspect QML + objects and user interfaces, as well as execute JavaScript + expressions. + + For more information, see \l{Debugging Qt Quick Projects} and + \l{Debugging a Qt Quick Application}. + + \sa {Debugging a C++ Application}, {Debug}{How To: Debug}, {Debuggers}, + {Debugger}, {Kits} */ - /*! - \previouspage creator-debugger-engines.html - \page creator-debugger-operating-modes.html - \nextpage creator-debug-mode.html + \page creator-how-to-start-debugging.html + \previouspage creator-how-tos.html - \title Launching the Debugger + \ingroup creator-how-to-debug + + \title Start debugging You can start an application from an open project under the control of a debugger in the following ways: @@ -128,75 +234,46 @@ \endlist \QC checks whether the compiled application is up-to-date, and rebuilds and - deploys it if you set the \uicontrol {Build before deploying} field to - build the whole project or the application to run and select the - \uicontrol {Always deploy before running} check box in \preferences > + deploys it if you set \uicontrol {Build before deploying} to + build the whole project or the application to run and select + \uicontrol {Always deploy before running} in \preferences > \uicontrol {Build & Run} > \uicontrol General. To debug the application - without deploying it, select \uicontrol Debug > \uicontrol {Start Debugging} + without deploying it, go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Start Debugging Without Deployment}. The debugger then takes over and starts the application with suitable parameters. + You can specify breakpoints before or after launching the debugger. + For more information, see \l{Setting Breakpoints}. + + \section1 Execute GDB or CDB commands + When using GDB or CDB as debug backend, you can specify additional commands to execute before and after the backend and debugged application are started or attached in \preferences > \uicontrol Debugger > - \uicontrol GDB and \uicontrol CDB. For more information, see - \l{Debugger Preferences}. + \l GDB and \l CDB. To let the debugger read the user's default .gdbinit file when it starts, - select the \uicontrol {Load .gdbinit file on startup} check box in - GDB settings. For more information, see \l{Specifying GDB Settings}. + select \uicontrol {Load .gdbinit file on startup} in GDB settings. \note Starting a C++ application under the control of the debugger can take a long time. Typically, in the range of several seconds to minutes if you use complex features. + \section1 Debug Python projects + For \l {Creating a Qt for Python Application with Qt Widgets}{Python} projects, start debugging the \c main.py file. If you encounter problems, check the active build target in the \l{Build for many platforms}{kit selector}. - \section1 Debugger Operating Modes + \QC does not support mixed-mode debugging, but you can attach GDB to the + Python interpreter to debug the C++ implementation of the corresponding + Python code. For more information, see + \l{https://doc.qt.io/qtforpython-6/tutorials/debugging/qtcreator/qtcreator.html} + {Debugging PySide with Qt Creator (Linux)}. - The debugger plugin can run the native debuggers in various operating modes - depending on where and how you start and run the debugged process. Some of - the modes are only available for a particular operating system or platform. - - In general, \key F5 and the \uicontrol {Start Debugging of Startup Project} - button start the operating mode that fits the context. So, for a C++ - application that uses the \MinGW toolchain targeting desktop Windows, the GDB - engine starts in \e {start internal} mode. For a QML application that uses C++ - plugins, a \e mixed QML/C++ engine starts, with the C++ parts being - handled by GDB and GDB server remote debugging. - - Change the run configuration parameters (such as - \uicontrol {Run in Terminal}) in the run settings of the project, or select - options from the \uicontrol Debug > \uicontrol {Start Debugging} menu to - select other modes of operation. - - The debugger can run in the following modes: - - \list - - \li \e{Start internal} to debug applications developed inside \QC, such as - a Qt Widgets-based application. - - \li \e{Start external} to start and debug processes without a proper \QC - project setup, either locally or on a remote machine. - - \li \e{Attach} to debug processes already started and running outside - \QC, either locally or on a remote machine. - - \li \e{Core} to debug crashed processes on Unix. - - \li \e{Post-mortem} to debug crashed processes on Windows. - - \endlist - - \section2 Start Internal - - Start internal mode is the default start mode for most projects, including - all projects using a desktop Qt version and plain C++ projects. + \section1 Debug console applications If you need a console window to operate your application, for example because it accepts console input from the user, go to \uicontrol Projects > @@ -205,46 +282,49 @@ If a console application does not start up properly in the configured console and the subsequent attach fails, you can diagnose the issue by - using CDB's native console. Select \preferences > + using CDB's native console. Go to \preferences > \uicontrol Debugger > \uicontrol CDB > \uicontrol {Use CDB console} to override the console set in the Windows system environment variables. Note that the native console does not prompt on application exit. - To launch the debugger in start internal mode, click the - \uicontrol {Start Debugging} button for the active project. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ - You can specify breakpoints before or after launching the debugger. - For more information, see \l{Setting Breakpoints}. +/*! + \page creator-how-to-debug-external-apps.html + \previouspage creator-how-tos.html - \section2 Start External + \ingroup creator-how-to-debug - You can debug any executable on your local or on a remote - machine without using a project. You specify a build and run kit that + \title Start and debug an external application + + To debug any executable on your local or on a remote + machine without using a project, specify a build and run \l{Kits}{kit} that identifies the device to debug the application on. - While this mode does not strictly require a project to be open in \QC, - opening it makes setting breakpoints and stepping through the code easier. + While the \e{start external} debugger mode does not strictly require a + project to be open in \QC, opening it makes setting breakpoints and + stepping through the code easier. To start and debug an external application: \list 1 - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Start and Debug External Application}. \image qtcreator-debugger-start-external.png - \li In the \uicontrol Kit field, select the build and run kit to + \li In \uicontrol Kit, select the build and run kit to use for building the project. - \li In the \uicontrol {Local executable} field, specify the path to the + \li In \uicontrol {Local executable}, specify the path to the application executable on the local machine. - \li In the \uicontrol {Command line arguments} field, specify command + \li In \uicontrol {Command line arguments}, specify command line arguments to be passed to the executable. - \li In the \uicontrol {Working directory} field, specify the working + \li In \uicontrol {Working directory}, specify the working directory. It defaults to the directory of the build result. - \li Select the \uicontrol{Run in terminal} check box for console - applications. - \li Select the \uicontrol {Break at "main"} check box to stop the - debugger at the main function. - \li Select the \uicontrol {Use target extended-remote to connect} - check box to create the connection in the + \li Select \uicontrol{Run in terminal} for console applications. + \li Select \uicontrol {Break at "main"} to stop the debugger at + the main function. + \li Select \uicontrol {Use target extended-remote to connect} + to create the connection in the \c {target extended-remote mode}. In this mode, when the debugged application exits or you detach from it, the debugger remains connected to the target. You can rerun the application, attach @@ -252,29 +332,34 @@ target. For example, GDB does not exit unless it was invoked using the \c {--once} option, but you can make it exit by using the \c {monitor exit} command. - \li In the \uicontrol {Override SysRoot} field, specify the path to + \li In \uicontrol {Override SysRoot}, specify the path to the \c sysroot to use instead of the default \c sysroot. - \li In the \uicontrol {Debug information} field, specify the location + \li In \uicontrol {Debug information}, specify the location for storing debug information. You cannot use an empty path. - \li In the \uicontrol Recent field, you can select a recent + \li In \uicontrol Recent, you can select a recent configuration to use. \endlist - \section2 Attach + \sa {Activate kits for a project}, {Debug}{How To: Debug}, {Debugging}, + {Debuggers}, {Debugger} +*/ - You can attach the debugger to applications that are already running or - instruct the debugger to attach to an application when it starts. +/*! + \page creator-how-to-attach-debugger-to-running-apps.html + \previouspage creator-how-tos.html - \section3 Attaching to Running Applications + \ingroup creator-how-to-debug + + \title Attach the debugger to running applications To attach the debugger to an application already running on your local or on a remote machine: \list 1 - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Attach to Running Application}. \image qtcreator-debugger-attach-to-running.png - \li In the \uicontrol Filter field, enter a string to filter processes + \li In \uicontrol Filter, enter a string to filter processes by their process ID or name. \li Select a process in the list, and then select \uicontrol {Attach to Process} to start debugging. @@ -290,28 +375,47 @@ You can specify breakpoints before or after attaching the debugger to the application. For more information, see \l{Setting Breakpoints}. - \section3 Attaching to Processes when They Start + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ + +/*! + \page creator-how-to-attach-debugger-to-starting-processes.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Attach the debugger to starting processes To instruct the debugger to watch an application process and to attach to it when it starts: \list 1 - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Attach to Unstarted Application}. \image qtcreator-debugger-attach-to-process-not-yet-started.png - \li In the \uicontrol Kit field, select the build and run kit to + \li In \uicontrol Kit, select the build and run kit to use for building the project. - \li In the \uicontrol Executable field, specify the path to the + \li In \uicontrol Executable, specify the path to the application executable. - \li Select the \uicontrol {Reopen dialog when application finishes} - check box to return to this dialog when the application is closed. - \li Select the \uicontrol {Continue on attach} check box to instruct + \li Select \uicontrol {Reopen dialog when application finishes} + to return to this dialog when the application is closed. + \li Select \uicontrol {Continue on attach} to instruct the debugger to keep the application running after attaching to it. \li Select \uicontrol {Start Watching} to wait for the application process to start. \endlist - \section2 Core + \sa {Activate kits for a project}, {Debug}{How To: Debug}, {Debugging}, + {Debuggers}, {Debugger} +*/ + +/*! + \page creator-how-to-load-core-files-to-debugger.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Load core files to the debugger Use the core mode to inspect \e {core} files (crash dumps) that are generated from crashed processes on Linux and Unix systems if the system is @@ -327,38 +431,46 @@ To launch the debugger in the core mode: \list 1 - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Load Core File}. \image qtcreator-debugger-load-core-file.png - \li In the \uicontrol Kit field, select a build and run kit that was + \li In \uicontrol Kit, select a build and run kit that was used for building the binary for which the core file was created. If the core file stems from a binary not built by \QC or a process not initiated by \QC, select a kit that matches the setup used as - closely as possible, in respect to the specified device, tool chain, + closely as possible, in respect to the specified device, toolchain, debugger, and sysroot. - \li In the \uicontrol {Core file} field, specify the core file to - inspect. - \li In the \uicontrol {Executable of symbol file} field, specify + \li In \uicontrol {Core file}, specify the core file to inspect. + \li In \uicontrol {Executable of symbol file}, specify a file that has debug information corresponding to the core file. Typically, this is the executable file or a \c {.debug} file if the debug information is stored separately from the executable. - \li In the \uicontrol {Override start script} field, specify a + \li In \uicontrol {Override start script}, specify a script file to run instead of the default start script. - \li In the \uicontrol {Override SysRoot} field, specify the path to + \li In \uicontrol {Override SysRoot}, specify the path to the \c sysroot to use instead of the default \c sysroot. \endlist Even though using a properly configured project that has the sources of the crashed application is not strictly necessary, it is helpful. - \section2 Post-Mortem + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, {Kits} +*/ - The post-mortem mode is available only on Windows, if you installed the - debugging tools for Windows. +/*! + \page creator-how-to-debug-post-mortem.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Debug crashed processes on Windows + + The \e{post-mortem} debugger operating mode is available only on Windows, + if you installed the debugging tools for Windows. The \QC installation program asks you whether you want to register \QC as a - post-mortem debugger. To change the setting, select + post-mortem debugger. To change the setting, go to \preferences > \uicontrol Debugger > \uicontrol General > \uicontrol {Use \QC for post-mortem debugging}. @@ -366,7 +478,16 @@ crashes on Windows. Click the \uicontrol {Debug in \QC} button in the error message from the Windows operating system. - \section1 Starting the Debugger from the Command Line + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} +*/ + +/*! + \page creator-how-to-start-debugger-from-cli.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Start debugging from the command line You can use the \QC debugger interface from the command line. To attach it to a running process, specify the process ID as a parameter for the @@ -386,35 +507,17 @@ \endlist - For more information, see \l{Command-Line Options}. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, + {Command-Line Options} */ /*! - \page creator-remote-debugging.html - \previouspage creator-debugger-examining-data.html - \nextpage creator-debugger-preferences.html + \page creator-how-to-debug-remotely-gdb.html + \previouspage creator-how-tos.html - \title Remote Debugging + \ingroup creator-how-to-debug - \QC makes remote debugging easy. - In general, the remote debugging setup consist of a probe running on the - remote machine and a counterpart running on the host side. The probe is - either integrated into the running process (e.g. for QML debugging) or runs - a separate process (e.g. when using GDB server on embedded Linux). The host - side typically consists of \QC itself, often with the help of an external - process, such as GDB or CDB. - - While this setup might look daunting, it is mostly invisible to the user of - \QC. To start debugging on a remote target with the necessary helper - processes running, select the corresponding - \l{glossary-buildandrun-kit}{kit} in \uicontrol Projects > - \uicontrol {Build & Run}, and then select a function to start remote - debugging in the \uicontrol Debug > \uicontrol {Start Debugging} menu. - - Special use cases, such as attaching to a running process on the target, - might still require manual setup. - - \section1 Using GDB + \title Debug remotely with GDB When debugging on a target supported by GDB server, a local GDB process talks to a GDB server running on the remote machine that controls the @@ -437,25 +540,24 @@ \list 1 - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Attach to Running Debug Server}. \image qtcreator-debugger-attach-to-running-debug-server.png - \li In the \uicontrol Kit field, select the build and run kit to + \li In \uicontrol Kit, select the build and run kit to use for building the project. - \li In the \uicontrol {Server port} field, enter the name of the remote + \li In \uicontrol {Server port}, enter the name of the remote machine and the port number to use. - \li In the \uicontrol {Local executable} field, specify the path to the + \li In \uicontrol {Local executable}, specify the path to the application executable on the local machine. - \li In the \uicontrol {Command line arguments} field, specify command + \li In \uicontrol {Command line arguments}, specify command line arguments to be passed to the executable. - \li In the \uicontrol {Working directory} field, specify the working + \li In \uicontrol {Working directory}, specify the working directory. It defaults to the directory of the build result. - \li Select the \uicontrol{Run in terminal} check box for console - applications. - \li Select the \uicontrol {Break at "main"} check box to stop the + \li Select \uicontrol{Run in terminal} for console applications. + \li Select \uicontrol {Break at "main"} to stop the debugger at the main function. - \li Select the \uicontrol {Use target extended-remote to connect} - check box to create the connection in the + \li Select \uicontrol {Use target extended-remote to connect} + to create the connection in the \c {target extended-remote mode}. In this mode, when the debugged application exits or you detach from it, the debugger remains connected to the target. You can rerun the application, attach @@ -463,34 +565,57 @@ target. For example, GDB does not exit unless it was invoked using the \c {--once} option, but you can make it exit by using the \c {monitor exit} command. - \li In the \uicontrol {Override SysRoot} field, specify the path to + \li In \uicontrol {Override SysRoot}, specify the path to the \c sysroot to use instead of the default \c sysroot. - \li In the \uicontrol {Init commands} field, enter the commands + \li In \uicontrol {Init commands}, enter the commands to execute immediately after the connection to a target has been established. - \li In the \uicontrol {Reset commands} field, enter the commands + \li In \uicontrol {Reset commands}, enter the commands to execute when resetting the connection to a target. - \li In the \uicontrol {Debug information} field, specify the location + \li In \uicontrol {Debug information}, specify the location for storing debug information. You cannot use an empty path. - \li In the \uicontrol {Override server channel} field, specify a + \li In \uicontrol {Override server channel}, specify a communication channel to use, such as a serial line or custom port. - \li In the \uicontrol Recent field, you can select a recent - configuration to use. + \li In \uicontrol Recent, select a recent configuration to use. \li Select \uicontrol OK to start debugging. \endlist - By default, a non-responsive GDB process is terminated after 20 seconds. - To increase the timeout in the \uicontrol {GDB timeout} field, select - \preferences > \uicontrol Debugger > - \uicontrol GDB. For more information about settings that you can specify - to manage the GDB process, see \l{Specifying GDB Settings}. + By default, a non-responsive GDB process is terminated after 40 seconds. + To increase the timeout in \uicontrol {GDB timeout}, go to \preferences > + \uicontrol Debugger > \uicontrol GDB. For more information about connecting with \c {target extended-remote} mode in GDB, see \l{https://sourceware.org/gdb/onlinedocs/gdb/Connecting.html} {Debugging with GDB: Connecting to a Remote Target}. - \section1 Using CDB + \section1 Use SSH port forwarding + + To enable debugging on remote targets that cannot expose GDB server ports, + map the remote ports to local ports using SSH tunneling. \QC automatically + detects the local and remote ports. + + To turn on SSH port forwarding: + + \list 1 + \li Go to \preferences > \uicontrol Devices. + \image qtcreator-preferences-devices-remote-linux.webp {Remote Linux device preferences} + \li In \uicontrol Device, select \uicontrol {Remote Linux Device}. + \li Select \uicontrol {Use SSH port forwarding for debugging}. + \li Select \uicontrol OK. + \endlist + + \sa {Debug}{How To: Debug}, {Remote Linux}{How To: Develop for remote Linux}, + {GDB}, {Debugging}, {Debuggers}, {Debugger}, {Kits} +*/ + +/*! + \page creator-how-to-debug-remotely-cdb.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Debug remotely with CDB In remote mode, the local CDB process talks to a CDB process that runs on the remote machine. The process is started with special command-line options @@ -555,23 +680,23 @@ \endlist - To specify settings for managing the CDB process, select \preferences > - \uicontrol Debugger > \uicontrol CDB. For more information, see - \l{Specifying CDB Settings}. + To specify settings for managing the CDB process, go to \preferences > + \uicontrol Debugger > \uicontrol CDB. + + \sa {Debug}{How To: Debug}, {CDB}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-debug-mode.html - \if defined(qtdesignstudio) - \previouspage studio-debugging.html - \else - \previouspage creator-debugger-operating-modes.html - \endif - \nextpage creator-stack-view.html + \previouspage creator-reference.html + + \ingroup creator-reference-debugger-views \title Debug Mode Views + \brief Inspect the state of your application while debugging. + In the \uicontrol Debug mode, you can inspect the state of your application while debugging. @@ -659,7 +784,7 @@ The log view acts as a console, so you can send the contents of the line under the text cursor in the log directly to the - native debugger. + debugger. \li \l{Troubleshooting Debugger} \l {Debugger Log} @@ -685,7 +810,7 @@ During debugging, the mode shows the views that you usually need to debug C++ or QML applications. To show other views or to hide views, - select \uicontrol Views. + go to \uicontrol Views. You can drag the views in \QC to new positions on the screen. \QC saves the size and position of views as a perspective for future sessions. Select @@ -714,70 +839,17 @@ interrupted. \endlist - For more information, see \l{Debugger Preferences}. -*/ - -/*! - \page creator-debugger-stopping.html - \previouspage creator-disassembler-view.html - \nextpage creator-debugger-examining-data.html - - \title Stopping Applications - - Once the application starts running under the control of the debugger, it - behaves and performs as usual. - - To interrupt a running C++ application, select \uicontrol Debug > - \uicontrol Interrupt. The debugger automatically interrupts - the application when it hits a \l {Setting Breakpoints}{breakpoint}. - - Once the application stops, \QC: - - \list - - \li Retrieves data representing the \l{Viewing Call Stack Trace} - {call stack} at the application's current position. - - \li Retrieves the contents of \l{Local Variables and Function Parameters} - {local variables}. - - \li Examines \l{Evaluating Expressions}{expressions}. - - \li Updates the \l{Viewing and Editing Register State}{Registers}, - \l{Viewing Modules}{Modules}, and \l{Viewing Disassembled Code} - {Disassembler} views if you are debugging C++ based applications. - - \endlist - You can \l{Examining Data}{Examine} and change variables, set or remove - breakpoints, and then continue running the application. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, + {Debugger Views} */ /*! \page creator-debugger-examining-data.html - \previouspage creator-debugger-stopping.html - \nextpage creator-remote-debugging.html + \previouspage creator-how-tos.html - \title Examining Data + \ingroup creator-how-to-debug - When the application stops, you can examine certain data in the debugger. The - availability of data depends on the compiler settings when compiling the - application and the exact location where the application stops. - - Unexpected events are called \e exceptions and the debugger can stop - the application when they occur. Going to the location in the code where - the exception occurred helps you investigate the problem and find ways to - fix it. - - If you have a variable that shows text, but the application does not display - it correctly, for example, your data might be incorrect or the code that sets - the display text might do something wrong. You can step through the code and - examine changes to the variable to find out where the error occurs. - - The following video shows how to examine variable values: - - \youtube EhJ1eV_6RH8 - - \section1 Showing Tooltips for Simple Values + \title Show tooltips for simple values To display the value of a simple variable, hover the mouse pointer over its name in the code editor. @@ -791,15 +863,25 @@ select \uicontrol {Close Editor Tooltips} in the context menu in the \uicontrol Locals or \uicontrol Expressions view. - To disable tooltips for performance reasons, select \preferences > + To disable tooltips for performance reasons, go to \preferences > \uicontrol Debugger > \uicontrol General > \uicontrol {Use tooltips in main editor when debugging}. - \section1 Examining Complex Values in Debug Views + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, + {Debugger Views} +*/ - \QC displays the raw information from the native debuggers in a clear and +/*! + \page creator-how-to-examine-complex-values.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Examine complex values in Debug views + + \QC displays the raw information from the debuggers in a clear and concise manner to simplify the debugging process without losing the power - of the native debuggers. + of the debuggers. \image qtcreator-locals.png {Locals view} @@ -826,7 +908,7 @@ To show complex structures, such as \c QObjects or associative containers, in a clear and concise manner, \QC uses Python scripts that are called - \l{Using Debugging Helpers}{debugging helpers}. + \l{Debugging Helpers}{debugging helpers}. In addition to the generic IDE functionality of the \l {Viewing Call Stack Trace}{Stack}, \uicontrol {Locals}, @@ -839,10 +921,21 @@ classes in a useful way. To change the number of array elements that are - requested when expanding entries, select \preferences > \uicontrol {Debugger} + requested when expanding entries, go to \preferences > \uicontrol {Debugging} > \uicontrol {Locals & Expressions} > \uicontrol {Default array size}. - \section1 Stepping Through Code + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, + {Debugger Views} +*/ + +/*! + \page creator-how-to-step-through-code.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Step through code The following table summarizes the functions that you can use to step through the code and examine the changes in variables. @@ -900,17 +993,17 @@ stopped. \endtable - \section2 Compressing Steps in GDB + \section1 Compress steps in GDB When using GDB as the debugging backend, you can compress several steps into one step for less noisy debugging. For more information, see - \l{Specifying GDB Settings}. + \l{GDB}. The extended GDB settings have the option to step backwards in code, but this option should be used with care, as it is slow and unstable on the - GDB side. For more information, see \l{Specifying GDB Settings}. + GDB side. For more information, see \l{GDB}. - \section2 Stepping into Frameworks in \macos + \section1 Step into Frameworks in \macos In \macos, external libraries are usually built into so-called Frameworks, which may have both release and debug versions of the library. When you @@ -919,7 +1012,17 @@ \uicontrol {Use debug versions of Frameworks} option in the project run settings. - \section1 Inspecting Basic Qt Objects + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, + {Debugger Views} +*/ + +/*! + \page creator-how-to-inspect-basic-qt-objects.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-debug + + \title Inspect basic Qt objects The most powerful feature of the debugger is that the \uicontrol {Locals} and \uicontrol {Expressions} views show the data that belongs to @@ -931,16 +1034,16 @@ displays the contents of a QHash or QMap in an orderly manner. Also, the debugger shows access data for QFileInfo and the \e real contents of QVariant. - \section2 Changing Value Display format + \section1 Change value display format In the \uicontrol {Locals} or the \uicontrol {Expressions} view, select \uicontrol {Change Value Display Format} in the context menu to change the value display format. The available options depend on the type of the - current items, and are provided by the debugging helpers. + current items, and are provided by \l{Debugging Helpers}{debugging helpers}. - To force a plain C-like display of structures, select \preferences > - \uicontrol Debugger > \uicontrol {Locals & Expressions}, and then deselect the - \uicontrol {Use Debugging Helpers} check box. This still uses the + To force a plain C-like display of structures, go to \preferences > + \uicontrol Debugger > \uicontrol {Locals & Expressions}, and then clear + \uicontrol {Use Debugging Helpers}. This still uses the Python scripts, but generates more basic output. To force the plain display for a single object or for all objects of a given type, select \uicontrol {Change Value Display Format} > \uicontrol Raw in the context @@ -961,7 +1064,7 @@ instead of a single line item in the view. For QPixmap, you can see the pixmap being created pixel-by-pixel when stepping through the code. - \section2 Changing Variable Values + \section1 Change variable values You can use the \uicontrol {Locals} and \uicontrol {Expressions} view to change the contents of variables of simple data types, for example, \c int, \c float, @@ -975,11 +1078,11 @@ applies the changes only if the new content fits into the old memory and if the debugger supports changing values. - \section2 Signal-Slot Connections + \section1 Signal-slot connections If an instance of a class is derived from QObject, you can find all other objects connected to this object's slots with Qt's signals and slots - mechanism. Select \preferences > \uicontrol {Debugger} > + mechanism. Go to \preferences > \uicontrol {Debugging} > \uicontrol {Locals & Expressions} > \uicontrol {Use Debugging Helpers}. \image qtcreator-debugging-helper-options.webp {Locals & Expressions preferences} @@ -988,7 +1091,7 @@ in the \e slots subitem. The view shows the objects connected to this slot as children of the slot. Similarly, you can show the children of signals. - \section2 Low-level Data + \section1 Low-level data If you cannot debug Qt objects because their data is corrupted, you can switch off the debugging helpers to make low-level structures visible. @@ -998,7 +1101,7 @@ \uicontrol Debugger > \uicontrol {Locals & Expressions}. \omit - \section2 Creating Snapshots + \section1 Create snapshots A snapshot has the complete state of the debugged application at a time, including the full memory contents. @@ -1015,15 +1118,20 @@ \l{https://sourceware.org/gdb/onlinedocs/gdb/Core-File-Generation.html}. \endomit + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-threads-view.html - \previouspage creator-breakpoints-view.html - \nextpage creator-modules-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Viewing Threads + \brief View the threads currently active in a multi-threaded application. + An application can have more than one thread of execution that share one address space, which means that they can examine and change the same variables. However, each thread has its own registers, execution stack, @@ -1042,17 +1150,22 @@ The \l {Viewing Call Stack Trace}{Stack} view adjusts its contents accordingly. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-modules-view.html - \previouspage creator-threads-view.html - \nextpage creator-source-files-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Viewing Modules - The \uicontrol Modules view displays information that the debugger plugin - has about modules included in the application that is being debugged. + \brief View information about the modules included in a debugged application. + + The \uicontrol Modules view displays information about modules included in + the application that is being debugged. A module is: @@ -1088,7 +1201,7 @@ \li Show sections in modules - \li Set \l{Debugger Preferences}{debugger preferences} + \li Set \l{Debugger}{debugger preferences} \endlist @@ -1099,21 +1212,26 @@ When using CDB as debug backend, you can specify that the debugger should break when application modules are loaded or unloaded. To enable breaking - for the specified modules, select \preferences > \uicontrol Debugger > + for the specified modules, go to \preferences > \uicontrol Debugger > \uicontrol CDB. \image qtcreator-cdb-options.png {CDB tab in Debugger preferences} - For more information, see \l{Specifying CDB Settings}. + For more information, see \l{CDB}. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-source-files-view.html - \previouspage creator-modules-view.html - \nextpage creator-locals-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Viewing Source Files + \brief View source files included in a debugged project. + The \uicontrol {Source Files} view lists all the source files included in the project. If you cannot step into an instruction, you can check whether the source file is actually part of the project, or whether it was compiled @@ -1126,7 +1244,7 @@ \list \li Reload data \li Open the selected file - \li Set \l{Debugger Preferences}{debugger preferences} + \li Set \l{Debugger}{debugger preferences} \endlist By default, the \uicontrol {Source Files} view is hidden. To show it, select @@ -1137,20 +1255,26 @@ To enable the debugger to step into the code and display the source code when using a copy of the source tree at a location different from the one at which the libraries were built, you can map source paths to target - paths in \preferences > \uicontrol Debugger > \uicontrol General: + paths in \preferences > \uicontrol Debugger > \uicontrol General. \image qtcreator-debugger-general-options.png {General tab in Debugger preferences} - For more information, see \l{Mapping Source Paths}. + For more information, see \l{Source Paths Mapping}. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-registers-view.html - \previouspage creator-expressions-view.html - \nextpage creator-peripheral-registers-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Viewing and Editing Register State + \brief View the current state of general-purpose and special-purpose CPU + registers. + \e {Machine code} consists of machine language instructions that make the CPU perform tasks, such as load or store, on units of data in the CPU's registers or memory. @@ -1177,7 +1301,7 @@ \li Open \l {Examining Memory}{Memory Editor} at the selected value. \li Open the \l {Viewing Disassembled Code}{Disassembler} view. \li Display a value in hexadecimal, decimal, octal, or binary format. - \li Set \l{Debugger Preferences}{debugger preferences}. + \li Set \l{Debugger}{debugger preferences}. \endlist By default, the \uicontrol Registers view is hidden. To show it, select it in @@ -1203,15 +1327,21 @@ \li Set a data breakpoint on the selection. \li Jump to the selected address in the current data view or a new one. \endlist + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-peripheral-registers-view.html - \previouspage creator-registers-view.html - \nextpage creator-debugger-log-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Peripheral Registers + \brief View the current state of peripheral devices, such as a mouse, + keyboard, display, printer, or USB drive. + The \uicontrol {Peripheral Registers} view displays the current state of peripheral devices, such as a mouse, keyboard, display, printer, or USB drive. Applications write registers to send information to the device and @@ -1231,28 +1361,33 @@ \list \li View register groups. - \li Set \l{Debugger Preferences}{debugger preferences}. + \li Set \l{Debugger}{debugger preferences}. \endlist By default, the \uicontrol {Peripheral Registers} view is hidden. To show it, select it in \uicontrol Views on the debugger toolbar. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-debugger-log-view.html - \previouspage creator-peripheral-registers-view.html - \nextpage creator-disassembler-view.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Debugger Log + \brief Troubleshoot the debugger. + You can view debug output in the \uicontrol {Debugger Log} view to \l {Debugger Does Not Work}{troubleshoot the debugger}. \image qtcreator-debugger-log-view.webp {Debugger Log view} - If debug output is sent to the system log, select \preferences > - \uicontrol Debugger > \uicontrol General > - \uicontrol {Force logging to console} check box. + If debug output is sent to the system log, go to \preferences > + \uicontrol Debugger > \uicontrol General and select + \uicontrol {Force logging to console}. Right-click the view to select the following actions: @@ -1265,16 +1400,16 @@ \li Log time stamps. \li Reload debugging helpers after \l{Adding Custom Debugging Helpers} {adding custom debugging helpers}. - \li Set \l{Debugger Preferences}{debugger preferences}. + \li Set \l{Debugger}{debugger preferences}. \endlist - \section1 Directly Interacting with Native Debuggers + \section1 Directly Interacting with Debuggers You can use the left pane of the \uicontrol {Debugger Log} view to directly - interact with the command line of the native debugger. + interact with the command line of the debugger. Press \key {Ctrl+Enter} to send the contents of the line under the - text cursor to the native debugger. Or, enter the command in the + text cursor to the debugger. Or, enter the command in the \uicontrol Command field. The right side pane of the \uicontrol {Debugger Log} view shows the command output. @@ -1282,15 +1417,20 @@ handle the task. For example, instead of using the GDB \c print command from the command line, you can evaluate an expression in the \l {Evaluating Expressions}{Expressions} view. + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! \page creator-disassembler-view.html - \previouspage creator-debugger-log-view.html - \nextpage creator-debugger-stopping.html + \previouspage creator-debug-mode.html + + \ingroup creator-reference-debugger-views \title Viewing Disassembled Code + \brief View disassembled code for the current function. + A \e disassembler translates machine language into assembly language for human-readability. @@ -1301,13 +1441,13 @@ \image qtcreator-debugger-disassembler-view.webp {Disassembler view} By default, GDB shows AT&T style disassembly. To switch to the Intel style, - select \preferences > \uicontrol Debugger > + go to \preferences > \uicontrol Debugger > \uicontrol GDB > \uicontrol {Use Intel style disassembly}. To open the \uicontrol Disassembler view: \list - \li Select \uicontrol Debug > \uicontrol {Operate by Instruction} while + \li Go to \uicontrol Debug > \uicontrol {Operate by Instruction} while the debugger is running. \li Select the \inlineimage icons/debugger_singleinstructionmode.png (\uicontrol {Operate by Instruction}) tool button on the debugger @@ -1323,27 +1463,22 @@ \uicontrol {Open Disassembler} and set the disassembler address: \image qcreator-debugger-select-start-address.webp {Select Start Address dialog} + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! - \previouspage creator-debugger-preferences.html \page creator-debugging-helpers.html - \nextpage creator-debugging-qml.html + \previouspage creator-debug-mode.html - \title Using Debugging Helpers + \ingroup creator-reference-debugger - To show complex structures, such as \c QObjects or associative containers, - in a clear and concise manner, \QC uses Python scripts that are called - \e {debugging helpers}. + \title Debugging Helpers - \QC ships with debugging helpers for more than 200 of the most popular Qt - classes, standard C++ containers, and smart pointers, covering the usual - needs of a C++ application developer out-of-the-box. - - \section1 Extending Debugging Helpers + \brief Load, customize, and add debugging helpers. \QC uses Python scripts to translate raw memory contents and type information - data from native debugger backends (GDB, LLDB, and CDB are currently supported) + data from debugger backends (GDB, LLDB, and CDB are currently supported) into the form presented to the user in the \l {Local Variables and Function Parameters}{Locals} and \l {Evaluating Expressions}{Expressions} views. @@ -1357,17 +1492,17 @@ least one of the three supported backends is available. To use the default GDB pretty printers installed in your system or linked - to the libraries your application uses, select \preferences > + to the libraries your application uses, go to \preferences > \uicontrol Debugger > \uicontrol GDB > \uicontrol {Load system GDB pretty - printers}. For more information, see \l{Specifying GDB Settings}. + printers}. For more information, see \l{GDB}. \image qtcreator-preferences-debugger-gdb.webp {GDB preferences} - \section2 Customizing Built-In Debugging Helpers + \section1 Customizing Built-In Debugging Helpers You can have commands executed after built-in debugging helpers have been loaded and fully initialized. To load additional debugging helpers or - modify existing ones, select \preferences > \uicontrol Debugger > + modify existing ones, go to \preferences > \uicontrol Debugger > \uicontrol {Locals & Expressions}, and enter the commands in the \uicontrol {Debugging Helper Customization} field. @@ -1389,17 +1524,17 @@ \endcode To display a message box as soon as your application receives a signal - during debugging, select \preferences > \uicontrol Debugger > \uicontrol GDB > + during debugging, go to \preferences > \uicontrol Debugger > \uicontrol GDB > \uicontrol {Show a message box when receiving a signal}. - \section2 Adding Custom Debugging Helpers + \section1 Adding Custom Debugging Helpers To add debugging helpers for your own types, no compilation is required, just adding a few lines of Python. The scripts can address multiple versions of Qt, or of your own library, at the same time. To add debugging helpers for custom types, add debugging helper - implementations to the startup file of the native debuggers (for example, + implementations to the startup file of the debuggers (for example, \c{~/.gdbinit} or \c{~/.lldbinit}) or specify them directly in the \uicontrol {Additional Startup Commands} in \preferences > \uicontrol Debugger > \uicontrol GDB. @@ -1444,7 +1579,7 @@ \uicontrol {Reload Debugging Helpers} from the context menu of the \l {Debugger Log} view. - \section2 Debugging Helper Overview + \section1 Debugging Helper Overview The implementation of a debugging helper typically consists of a single Python function, which needs to be named \c{qdump__NS__Foo}, where @@ -1532,7 +1667,7 @@ d.putArrayData(base, size, typeobj) \endcode - \section2 Debugging Helper Implementation + \section1 Debugging Helper Implementation A debugging helper creates a description of the displayed data item in a format that is similar to GDB/MI and JSON. @@ -1586,7 +1721,7 @@ members specified in \c qtcreator\share\qtcreator\debugger\dumper.py. - \section3 Dumper Class + \section2 Dumper Class The \c Dumper class has generic bookkeeping, low-level, and convenience functions: @@ -1612,7 +1747,7 @@ \endcode \li \c{putCallItem(self, name, rettype, value, func, *args)} - Uses the - native debugger backend to place the function call \c func returning + debugger backend to place the function call \c func returning \c rettype on the value specified by \a {value} and to output the resulting item. @@ -1752,14 +1887,14 @@ \endlist - \section3 Dumper.Type Class + \section2 Dumper.Type Class The \c{Dumper.Type} class describes the type of a piece of data, typically a C++ class or struct, a pointer to a struct, or a primitive type, such as an integral or floating point type. Type objects, that is, instances of the \c{Dumper.Type} class, can be - created by native debugger backends, usually by evaluating Debug Information + created by debugger backends, usually by evaluating Debug Information built into or shipped alongside the debugged binary, or created on-the-fly by the debugging helper. @@ -1807,7 +1942,7 @@ \endlist - \section3 Dumper.Field Class + \section2 Dumper.Field Class The \c{Dumper.Field} class describes a base class or a data member of a type object: @@ -1830,7 +1965,7 @@ \endlist - \section3 Dumper.Value Class + \section2 Dumper.Value Class The \c{Dumper.Value} class describes a piece of data, such as instances of C++ classes or primitive data types. It can also be used to describe @@ -1892,7 +2027,7 @@ \endlist - \section3 Children and SubItem Class + \section2 Children and SubItem Class The attempt to create child items might lead to errors if data is uninitialized or corrupted. To gracefully recover in such situations, use @@ -1931,16 +2066,21 @@ d.putSubItem("key", key) d.putSubItem("value", value) \endcode + + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ /*! - \previouspage creator-qml-debugging-example.html \page creator-troubleshooting-debugging.html - \nextpage creator-analyze-mode.html + \previouspage creator-reference.html + + \ingroup creator-reference-debugger \title Troubleshooting Debugger + \brief Solve problems that you might encounter while debugging. + This section lists some typical problems that you might encounter while debugging and solutions to them. @@ -1984,9 +2124,9 @@ \l {Run on many platforms}{build and run kit selector} picked a runnable target and you can run the application. - \li Make sure the debugger is \l{Setting Up Debugger}{set up properly}. + \li Make sure the debugger is \l{Supported Debuggers}{set up properly}. - \li In the \uicontrol Debug mode, select \uicontrol View > + \li In the \uicontrol Debug mode, go to \uicontrol View > \uicontrol Views > \uicontrol {Debugger Log} to open the \l {Debugger Log} view. Browse the contents of the pane on the right hand side to find out what went wrong. Always attach the @@ -2026,7 +2166,7 @@ When using GDB as backend, you can automatically save a copy of its symbol index in a cache on disk and retrieve it from there - when loading the same binary in the future. Select \preferences > + when loading the same binary in the future. Go to \preferences > \uicontrol Debugger > \uicontrol GDB > \uicontrol {Use automatic symbol cache}. \image qtcreator-preferences-debugger-gdb.webp {GDB preferences} @@ -2082,4 +2222,5 @@ calls \c{prctl(0x59616d61, getppid(), 0, 0, 0);}, such as the one in \c{$QTCREATORDIR/lib/libptracepreload.so} to the LD_PRELOAD environment. + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger} */ diff --git a/doc/qtcreator/src/debugger/qtquick-debugging.qdoc b/doc/qtcreator/src/debugger/qtquick-debugging.qdoc index a4150ab4137..e44a2f93fc9 100644 --- a/doc/qtcreator/src/debugger/qtquick-debugging.qdoc +++ b/doc/qtcreator/src/debugger/qtquick-debugging.qdoc @@ -13,15 +13,17 @@ \previouspage studio-debugging.html \nextpage creator-stack-view.html \else - \previouspage creator-debugging-helpers.html - \nextpage creator-debugging-example.html + \previouspage creator-reference.html \endif + \ingroup creator-reference-debugger + \ingroup studio-debugger + \title Debugging Qt Quick Projects - \if defined(qtcreator) - \note You need Qt 5.0 or later to debug Qt Quick projects. - \endif + \brief Debug JavaScript functions, execute JavaScript expressions to get + information about the state of the UI, and inspect QML properties and + JavaScript variables, as well as change their values temporarily at runtime. For an example of how to debug Qt Quick Projects, see \l{Debugging a Qt Quick Application}. @@ -56,8 +58,9 @@ \list 1 \li To create a build configuration that supports QML debugging, - select \uicontrol {Projects} > \uicontrol {Build} > - \uicontrol {QML debugging and profiling} > \uicontrol Enable. + go to \uicontrol {Projects} > \uicontrol {Build}. + + \li In \uicontrol {QML debugging and profiling}, select \uicontrol Enable. \image qtcreator-build-settings-cmake-configure.webp {Build settings for a CMake project} @@ -79,7 +82,7 @@ rebuild the project. \li To debug applications on \l{glossary-device}{devices}, check that - Qt 5.0, or later, libraries are installed on the device and + Qt libraries are installed on the device and \l{Run on many platforms}{select the corresponding kit for the device} before you start debugging. @@ -179,7 +182,7 @@ \note Setting breakpoints is only possible if the application is started with block mode. - \li Select \uicontrol Debug > \uicontrol {Start Debugging} > + \li Go to \uicontrol Debug > \uicontrol {Start Debugging} > \uicontrol {Attach to QML Port}. Choose the kit configured for the device where the application to @@ -225,7 +228,7 @@ \li Select the item in the code editor. - \li Select \uicontrol Debug > \uicontrol Select to activate selection + \li Go to \uicontrol Debug > \uicontrol Select to activate selection mode and then click an item in the running application. \endlist @@ -243,12 +246,6 @@ application to jump to their definitions in the code. The properties of the selected item are displayed in the \uicontrol {Locals} view. - \if defined(qtcreator) - The \uicontrol Select tool will be enabled either if your application is - using Qt 5.7 or later, or if your application is using an earlier version - of Qt and is based on the \c QQuickView class. - \endif - You can also view the item hierarchy in the running application: Double-click an item in the running application to cycle through the item @@ -282,4 +279,8 @@ When you change property values in the \uicontrol {QML Debugger Console} or in the \uicontrol Locals or \uicontrol Expression view, they are immediately updated in the running application, but not in the source code. + + \if defined(qtcreator) + \sa {Debug}{How To: Debug}, {Debugging}, {Debuggers}, {Debugger}, {Kits} + \endif */ diff --git a/doc/qtcreator/src/docker/creator-docker.qdoc b/doc/qtcreator/src/docker/creator-docker.qdoc index c63ab4b3b59..4f1167b359a 100644 --- a/doc/qtcreator/src/docker/creator-docker.qdoc +++ b/doc/qtcreator/src/docker/creator-docker.qdoc @@ -3,12 +3,13 @@ /*! \page creator-adding-docker-devices.html - \previouspage creator-developing-b2qt.html - \nextpage creator-developing-ios.html + \previouspage creator-how-tos.html - \title Adding Docker Devices + \ingroup creator-how-to-docker - Create Docker devices from \l{ https://docs.docker.com/get-started/overview/} + \title Add Docker devices + + Create Docker devices from \l{https://docs.docker.com/get-started/overview/} {Docker images} and use them to build, run, and debug applications. A Docker container operates like a virtual machine but uses less system resources at the cost of being less flexible. @@ -16,7 +17,7 @@ While Linux, \macos, and Windows hosts are supported in principle, Linux is the recommended platform. - To build, run, and debug applications on Docker devices, you must install and + To build, run, and debug applications on Docker devices, install and configure \c docker-cli on the development host. \QC automatically detects \l{kits-tab}{build and run kit} items, such \l{Add debuggers} {debuggers} and \l{Add Qt versions}{Qt versions}, in the Docker container @@ -24,29 +25,70 @@ You are advised to use CMake to build applications in the Docker container. + \note Enable the Docker plugin to use it. + To pull images from Docker hub or other registries, use the \l{https://docs.docker.com/engine/reference/commandline/pull/}{docker pull} command. - \section1 Adding Docker Images as Devices + \section1 Add Docker images as devices To add a Docker image as a device: \list 1 - \li Select \preferences > \uicontrol Devices - > \uicontrol Docker and enter the path to the Docker CLI in - the \uicontrol Command field. - \image qtcreator-preferences-devices-docker.webp "Docker tab in Devices preferences" - \li Select \uicontrol Devices > \uicontrol Add > - \uicontrol {Docker Device} > \uicontrol {Start Wizard} - to search for images in your local Docker installation. - \li Select the Docker image to use, and then select \uicontrol OK. + \li Go to \preferences > \uicontrol Devices > \uicontrol Docker. + \li In \uicontrol Command, enter the path to the Docker CLI. + \image qtcreator-preferences-devices-docker.webp {Docker tab in Devices preferences} + \li Go to \uicontrol Devices. + \li Select \uicontrol Add > \uicontrol {Docker Device} > + \uicontrol {Start Wizard} to search for images in your + local Docker installation. + \li Select a Docker image, and then select \uicontrol OK. \li In \uicontrol Devices, check and change Docker device preferences. - \image qtcreator-preferences-devices-docker-device.png "Docker device preferences" + \image qtcreator-preferences-devices-docker-device.png {Docker device preferences} \li Select \uicontrol Apply to save your changes. \endlist - The following table summarizes the options you can set. + \section2 Select Docker images + + The \uicontrol {Docker Image Selection} dialog displays a list of Docker + images in your local Docker installation. You can sort the images according + to the repository name or tag or the image ID or size. + + \image qtcreator-docker-image-selection.webp {Docker Image Selection dialog} + + Select \uicontrol {Show unnamed images} to show images that are not tagged. + + Double-click an image to select it. + + \section1 Edit Docker device kits + + Go to \preferences > \uicontrol Kits to check + that the automatically generated kits point to the appropriate kit items. + + \sa {Enable and disable plugins}, {Docker}{How To: Develop for Docker}, + {Manage Kits}{How To: Manage Kits} +*/ + +/*! + \page creator-preferences-docker.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-docker + + \title Set preferences for Docker devices + + \note Enable the Docker plugin to use it. + + To set preferences for Docker devices: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \li In \uicontrol Device, select a Docker device. + \image qtcreator-preferences-devices-docker-device.png {Docker device preferences} + \endlist + + The following table summarizes the preferences you can set. \table \header @@ -59,7 +101,7 @@ on Windows. \row \li \uicontrol {Do not modify entry point} - \li Stops \QC from modifying the \l {Modifying Entry Points}{entry point} + \li Stops \QC from modifying the \l {Modify entry points}{entry point} of the image. Make sure that the entry point starts a shell. \row \li \uicontrol {Enable flags needed for LLDB} @@ -69,33 +111,18 @@ \endcode \row \li \uicontrol {Clangd executable} - \li The path to a remote Clangd executable to use for a remote code - model. + \li The path to a remote Clangd executable for a remote code model. \row \li \uicontrol {Paths to mount} - \li Host directories to \l{Specifying Paths to Mount}{mount} into the + \li Host directories to \l{Specify paths to mount}{mount} into the container, such as the project directory. \row \li \uicontrol {Search locations} - \li Where to \l{Auto-detecting Kit Items}{automatically detect} kit + \li Where to \l{Auto-detect kit items}{automatically detect} kit items. \endtable - The following sections describe the Docker device preferences in more detail. - - \section2 Selecting Docker Images - - The \uicontrol {Docker Image Selection} dialog displays a list of Docker - images in your local Docker installation. You can sort the images according - to the repository name or tag or the image ID or size. - - \image qtcreator-docker-image-selection.webp "Docker Image Selection dialog" - - Select \uicontrol {Show unnamed images} to show images that are not tagged. - - Double-click an image to select it. - - \section2 Modifying Entry Points + \section1 Modify entry points The entry point of a Docker container is specified in the container settings and started as the main process when starting the container. The entry point @@ -107,9 +134,9 @@ \uicontrol {Do not modify entry point}. However, if the entry point you specify is not a shell, \QC cannot start the container. - \section2 Specifying Paths to Mount + \section1 Specify paths to mount - You can either copy your project files into the Docker container or specify + Copy your project files into the Docker container or specify paths to them in \uicontrol {Paths to mount}. Shared mounts are restricted to locations in the host system that can end up in the same absolute location in the Docker container. On Windows, network mounts cannot be used as shared @@ -120,7 +147,7 @@ \uicontrol {Delete Line} to delete the selected path or \uicontrol Clear to delete all paths. - \section2 Auto-detecting Kit Items + \section1 Auto-detect kit items Select \uicontrol {Auto-detect Kit Items} to find kit items and create kits for the Docker device. You can search for kit items in the device's PATH or @@ -143,20 +170,32 @@ \uicontrol {List Auto-Detected Kit Items}. To remove them, select \uicontrol {Remove Auto-Detected Kit Items}. - \section1 Editing Docker Device Kits + \sa {Enable and disable plugins}, {Docker}{How To: Develop for Docker}, + {Manage Kits}{How To: Manage Kits} +*/ - Select \preferences > \uicontrol Kits to check - that the automatically generated kits point to the appropriate kit items. +/*! + \page creator-how-to-build-run-docker.html + \previouspage creator-how-tos.html - To specify build settings: + \ingroup creator-how-to-docker + + \title Build for and run on Docker devices + + \note Enable the Docker plugin to use it. + + To specify build settings for Docker images: \list 1 \li Open a project for an application you want to develop for the device. - \li Select \uicontrol Projects > \uicontrol {Build & Run} to enable - the kit that you specified above. + \li Go to \uicontrol Projects > \uicontrol {Build & Run}, and + activate the kit for Docker devices. \endlist Select \uicontrol Run to specify run settings. Usually, you can use the default settings. + + \sa {Enable and disable plugins}, {Docker}{How To: Develop for Docker}, + {Manage Kits}{How To: Manage Kits} */ diff --git a/doc/qtcreator/src/editors/creator-code-syntax.qdoc b/doc/qtcreator/src/editors/creator-code-syntax.qdoc index 5a383f9df8d..f59ba0fd941 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 @@ -68,7 +68,7 @@ To specify the position where the annotations are displayed, go to \preferences > \uicontrol {Text Editor} > - \uicontrol Display > \uicontrol {Line annotations}, and then select + \uicontrol Display > \uicontrol {Line Annotations}, and then select whether to display the annotations directly next to the code, aligned to the right of the code, or in the right margin. Showing annotations between lines can be useful if there is usually not enough space to @@ -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/editors/creator-only/creator-clang-codemodel.qdoc b/doc/qtcreator/src/editors/creator-only/creator-clang-codemodel.qdoc index bdf06e24eb4..ae81bdc3abd 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-clang-codemodel.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-clang-codemodel.qdoc @@ -124,8 +124,34 @@ The document outline in the \l{Outline} view is backed by clangd's document symbol support, which makes the results more reliable than before. - \sa {Code Model}, {Clangd}, {Specify clangd settings}, - {Specify Clang tools settings}, {Use compilation databases} + \sa {Configure C++ code model}, {Specify clangd settings}, + {Specify Clang tools settings}, {Use compilation databases}, + {Code Model}, {Clangd} +*/ + +/*! + \page creator-how-to-cpp-code-model.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-configure-editors + \ingroup creator-how-to-projects-configure + + \title Configure C++ code model + + The code model offers services such as code completion, syntactic and + semantic highlighting, and diagnostics. + + To configure the C++ code model for a project: + + \list 1 + \li Go to \uicontrol Projects > \uicontrol {Project Settings} > + \uicontrol {C++ Code Model}. + \image qtcreator-projects-cpp-code-model.webp {C++ Code Model settings} + \li Clear \uicontrol {Use global settings}. + \li Set \uicontrol {C++ Code Model} settings for the project. + \endlist + + \sa {Code Model} */ /*! @@ -136,42 +162,49 @@ \title Code Model - \brief Sets global preferences for the code model. + \brief Sets global preferences for the C++ code model. - The Clang code model offers services such as code completion, syntactic and + The code model offers services such as code completion, syntactic and semantic highlighting, and diagnostics. - To configure the Clang code model globally: + To configure the C++ code model globally, go to \preferences > + \uicontrol C++ > \uicontrol {Code Model}. - \list 1 + \image qtcreator-preferences-code-model.webp {C++ Code Model preferences} - \li Select \preferences > \uicontrol C++ > - \uicontrol {Code Model}. - - \image qtcreator-preferences-code-model.webp {C++ Code Model preferences} - - \li To instruct the code model to interpret ambiguous header files as C - language files if you develop mainly using C, select the - \uicontrol {Interpret ambiguous headers as C headers} check box. - - \li To process precompiled headers, deselect the - \uicontrol {Ignore precompiled headers} check box. - - \li To use the built-in preprocessor to show the - pre-processed source file in the editor, select - \uicontrol {Use built-in preprocessor to show pre-processed files}. + The following table summarizes the preferences. + \table + \header + \li Setting + \li Value + \row + \li \uicontrol {Interpret ambiguous headers as C headers} + \li Instructs the code model to interpret ambiguous header files as C + language files. Select this checkbox if you develop mainly using C. + \row + \li \uicontrol {Ignore precompiled headers} + \li Clear this checkbox to process precompiled headers. + \row + \li \uicontrol {Use built-in preprocessor to show pre-processed files} + \li Uses the built-in preprocessor to show the + pre-processed source file in the editor. + \row + \li \uicontrol {Enable indexing} + \li Turns on the built-in indexer. Clearing this checkbox severely limits + the capabilities of the code model. + \row + \li \uicontrol {Do not index files greater than} \li To avoid out-of-memory crashes caused by indexing huge source files that are typically auto-generated by scripts or code, the size of - files to index is limited to 5MB by default. To adjust the limit, - edit the value for the \uicontrol {Do not index files greater than} - check box. To index all files, deselect the check box. + files to index is limited to 5MB by default. - \li To ignore files that match wildcard patterns, select the - \uicontrol {Ignore files} check box and enter each wildcard pattern - on a separate line in the field. - - \endlist + To index all files, clear the checkbox. + \row + \li \uicontrol {Ignore files} + \li To ignore files that match wildcard patterns, enter each wildcard + pattern on a separate line in the field. + \endtable \section1 Inspect preprocessed C++ code @@ -186,7 +219,8 @@ this action also expands all \c {"#include "} statements to their actual contents. - \sa {Specify clangd settings}, {Clang Code Model}, {Clangd} + \sa {Configure C++ code model}, {Specify clangd settings}, + {Clang Code Model}, {Clangd} */ /*! @@ -213,9 +247,14 @@ version 14, or later. \li In the \uicontrol {Background indexing} field, select \uicontrol Off to use a faster, but less accurate built-in indexer than the one used - by default. You can set the indexing priority depending on whether + by default. Set the indexing priority depending on whether the accuracy of results or speed is more important to you during global symbol searches. + \li In \uicontrol {Per-project index location}, select the folder to + store the index files for each project. The \c {compile-commands.json} + file is also stored in this folder. + \li In \uicontrol {Per-session index location}, select the folder to + store the index files for each session. \li In \uicontrol {Header/source switch mode}, select the C/C++ backend for switching between header and source files. While the clangd implementation has more capabilities than the built-in @@ -224,6 +263,13 @@ \li By default, clangd attempts to use all unused cores. You can set a fixed number of cores to use in \uicontrol {Worker thread count}. Background indexing also uses this many worker threads. + \li Select \uicontrol {Insert header files on completion} to insert + header files when completing symbols. + \li Select \uicontrol {Update dependent sources} to re-parse all source + files that include a header file when editing the header file. This + can cause a heavy CPU load if the header file is included in many + source files. Clear this option to only re-parse the source files + when saving the header file. \li Set the number of \uicontrol {Completion results} if you regularly miss important results during code completion. Set it to 0 to remove the limit on the number of completion results. Setting this to 0 or a diff --git a/doc/qtcreator/src/editors/creator-only/creator-coding-edit-mode.qdoc b/doc/qtcreator/src/editors/creator-only/creator-coding-edit-mode.qdoc index dbf8b219ed0..9bbfe729d93 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-coding-edit-mode.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-coding-edit-mode.qdoc @@ -111,7 +111,7 @@ \row \li \inlineimage icons/live-preview.png \li Preview changes to QML code live in your application. - \li \l {Previewing on Desktop} + \li \l {Preview a QML file on desktop} \row \li \inlineimage icons/debugger_singleinstructionmode.png \li Run Clang-Tidy or Clazy to analyze the currently open file. @@ -417,18 +417,18 @@ \image qtcreator-options-texteditor-behavior-file-encodings.png {File encoding preferences} - Qt 5 and Qt 6 require UTF-8 encoded source files, and therefore the default + Qt requires UTF-8 encoded source files, and therefore the default encoding is set to \uicontrol UTF-8. - Detecting the correct encoding is tricky, so \QC will not try to do so. - Instead, it displays the following error message when you try to edit a file - that is not UTF-8 encoded: \uicontrol {Error: Could not decode "filename" with + + If you try to edit a file that is not UTF-8 encoded, you see the following + error message: \uicontrol {Error: Could not decode "filename" with "UTF-8"-encoding. Editing not possible.} To resolve the issue, use a file conversion tool to convert the file - encoding to UTF-8 when developing Qt 5 applications. Otherwise, conversion - of string constants to QString might not work as expected. + encoding to UTF-8. Otherwise, conversion of string constants to + QString might not work as expected. - If you develop only Qt 4 applications or other than Qt applications, you + If you do not develop Qt applications, you can set other encoding options as the default encoding. Select the \uicontrol System option to use the file encoding used by your system. diff --git a/doc/qtcreator/src/editors/creator-only/creator-cpp-quick-fixes.qdoc b/doc/qtcreator/src/editors/creator-only/creator-cpp-quick-fixes.qdoc index b3bab5c7feb..ad5577b7a9b 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-cpp-quick-fixes.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-cpp-quick-fixes.qdoc @@ -103,23 +103,192 @@ \li Create function declarations and definitions \endlist - The following table summarizes the quick fixes for C++ code. The - fix is available when the cursor is in the position described in the - Activation column. + The following tables summarize the quick fixes available for C++ code, + according to the cursor position. + + \section1 Block of Code Selected + + \table + \header + \li Quick Fix + \li Description + \row + \li Assign to Local Variable + \li Adds a local variable which stores the return value of a + function call or a new expression. For example, rewrites + + \code + QString s; + s.toLatin1(); + \endcode + + as + + \code + QString s; + QByteArray latin1 = s.toLatin1(); + \endcode + + and + + \code + new Foo; + \endcode + + as + + \code + Foo * localFoo = new Foo; + \endcode + + By default, \QC uses the \c auto variable type when creating the + variable. To label the variable with its actual type, select + \preferences > \uicontrol C++ > \uicontrol {Quick Fixes} and + clear \uicontrol {Use type "auto" when creating new variables}. + + Also available for a function call. + \row + \li Extract Function + \li Moves the selected code to a new function and replaces the block + of code with a call to the new function. Enter a name for the + function in the \uicontrol {Extract Function Refactoring} + dialog. + \row + \li Extract Constant as Function Parameter + \li Replaces the selected literal and all its occurrences with the + function parameter \c{newParameter}, which has the original + literal as the default value. + \endtable + + \section1 Class + + The following quick fixes are available when the cursor is on the definition + of a class. + + \table + \header + \li Quick Fix + \li Description + \row + \li Create Implementations for Member Functions + \li Creates implementations for all member functions in one go. + In the \uicontrol {Member Function Implementations} dialog, + specify whether the member functions are generated + inline or outside the class. + \row + \li Generate Constructor + \li Creates a constructor for a class. + \row + \li Generate Missing Q_PROPERTY Members + \li Adds missing members to a \c Q_PROPERTY: + \list + \li \c read function + \li \c write function, if there is a WRITE + \li \c {onChanged} signal, if there is a NOTIFY + \li data member with the name \c {m_} + \endlist + \row + \li Insert Virtual Functions of Base Classes + \li Inserts declarations and the corresponding definitions inside or + outside the class or in an implementation file (if it exists). + For more information, see \l{Insert virtual functions}. + \row + \li Move All Function Definitions + \li Moves all function definitions to the implementation file or + outside the class. For example, rewrites + \code + class Foo + { + void bar() + { + // do stuff here + } + void baz() + { + // do stuff here + } + }; + \endcode + + as + + \code + class Foo + { + void bar(); + void baz(); + }; + + void Foo::bar() { + // do stuff here + } + + void Foo::baz() { + // do stuff here + } + \endcode + \row + \li Move Class to a Dedicated Set of Source Files + \li Moves a class to separate header and source files. For more + information, see \l{Move classes to separate files}. + \row + \li Re-order Member Function Definitions According to Declaration Order + \li Re-orders method definitions in a .cpp file to follow the order of + method declarations in the corresponding .h file. + \endtable + + \section1 Class Member + + The following quick fixes are available when the cursor is on a member + variable in a class definition. + + \table + \header + \li Quick Fix + \li Description + \row + \li Generate Constant Q_PROPERTY and Missing Members + \li Generates a constant Q_PROPERTY and adds missing members + to it. + \row + \li Generate Getter + \li Creates a getter member function for a member variable. + \row + \li Generate Getter and Setter + \li Creates getter and setter member functions for a member + variable. + \row + \li Create Getter and Setter Member Functions + \li Creates either both getter and setter member functions for + member variables or only a getter or setter. + \row + \li Generate Q_PROPERTY and Missing Members + \li Generates a Q_PROPERTY and adds missing members to it. + \row + \li Generate Q_PROPERTY and Missing Members with Reset Function + \li Generates a Q_PROPERTY and adds missing members to it, with an + additional \c reset function. + \row + \li Generate Setter + \li Creates a setter member function for a member variable. + \endtable + + \section1 Control Statement \table \header \li Quick Fix \li Description - \li Activation \row \li Add Curly Braces - \li Adds curly braces to an if statement that does not have a - compound statement. For example, rewrites + \li Adds curly braces to an if clause or to a do, while, or for + loop. For example, rewrites an if clause \code if (a) b; + else + c; \endcode as @@ -127,9 +296,60 @@ \code if (a) { b; + } else { + c; } \endcode - \li \c if + + Rewrites a do loop + + \code + do + ++i; + while (i < 10); + \endcode + + as + + \code + do { + ++i; + } while (i < 10); + \endcode + + Rewrites a while loop + + \code + while (i > 0) + --i; + \endcode + + as + + \code + while (i > 0) { + --i; + } + \endcode + + Rewrites a for loop + + \code + for (int i = 0; i < 10; ++i) + func(i); + \endcode + + as + + \code + for (int i = 0; i < 10; ++i) { + func(i); + } + \endcode + \row + \li Complete Switch Statement + \li Adds all possible cases to a switch statement of the type + \c enum. \row \li Move Declaration out of Condition \li Moves a declaration out of an if or while condition to simplify @@ -145,219 +365,33 @@ Type name = foo; if (name) {} \endcode - \li Name of the introduced variable \row - \li Rewrite Condition Using || - \li Rewrites the expression according to De Morgan's laws. For - example, rewrites: + \li Optimize for-Loop + \li Rewrites post-increment operators as pre-increment operators and + post-decrement operators as pre-decrement operators. It also + moves other than string or numeric literals and id expressions + from the condition of a for loop to its initializer. For + example, rewrites + \code - !a && !b + for (int i = 0; i < 3 * 2; i++) \endcode as \code - !(a || b) + for (int i = 0, total = 3 * 2; i < total; ++i) \endcode - \li \c && + \endtable + + \section1 Function Declaration or Definition + + \table + \header + \li Quick Fix + \li Description \row - \li Rewrite Using \e operator - \li Rewrites an expression negating it and using the inverse - operator. For example, rewrites: - - \list - - \li \code - a op b - \endcode - - as - - \code - !(a invop b) - \endcode - - \li \code - (a op b) - \endcode - - as - - \code - !(a invop b) - \endcode - - \li \code - !(a op b) - \endcode - - as - - \code - (a invob b) - \endcode - - \endlist - - \li \c {<=}, \c {<}, \c {>}, \c {>=}, \c {==} or \c {!=} - \row - \li Split Declaration - \li Splits a simple declaration into several declarations. For - example, rewrites: - \code - int *a, b; - \endcode - - as - - \code - int *a; - int b; - \endcode - \li Type name or variable name - \row - \li Split if Statement - \li Splits an if statement into several statements. For example, - rewrites: - - \code - if (something && something_else) { - } - \endcode - - as - - \code - if (something) { - if (something_else) { - } - } - \endcode - - and - - \code - if (something || something_else) - x; - \endcode - - with - - \code - if (something) - x; - else if (something_else) - x; - \endcode - - \li \c && or \c || - \row - \li Swap Operands - \li Rewrites an expression in the inverse order using the inverse - operator. For example, rewrites: - \code - a op b - \endcode - - as - \code - b flipop a - \endcode - \li \c {<=}, \c {<}, \c {>}, \c {>=}, \c {==}, \c {!=}, \c {&&} - or \c {||} - \row - \li Convert to Decimal - \li Converts an integer literal to decimal representation - \li Numeric literal - \row - \li Convert to Hexadecimal - \li Converts an integer literal to hexadecimal representation - \li Numeric literal - \row - \li Convert to Octal - \li Converts an integer literal to octal representation - \li Numeric literal - \row - \li Convert to Objective-C String Literal - \li Converts a string literal to an Objective-C string literal if - the file type is Objective-C(++). For example, rewrites the - following strings - - \code - "abcd" - QLatin1String("abcd") - QLatin1Literal("abcd") - \endcode - - as - - \code - @"abcd" - \endcode - \li String literal - \row - \li Enclose in QLatin1Char() - \li Sets the encoding for a character to Latin-1, unless the - character is already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, - tr, trUtf8, QLatin1Literal, or QLatin1String. For example, - rewrites - - \code - 'a' - \endcode - - as - - \code - QLatin1Char('a') - \endcode - \li String literal - \row - \li Enclose in QLatin1String() - \li Sets the encoding for a string to Latin-1, unless the string is - already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, tr, trUtf8, - QLatin1Literal, or QLatin1String. For example, rewrites - \code - "abcd" - \endcode - - as - - \code - QLatin1String("abcd") - \endcode - - \li String literal - \row - \li Enclose in QByteArrayLiteral() - \li Converts a string to a byte array. For example, rewrites - \code - "abcd" - \endcode - - as - - \code - QByteArrayLiteral("abcd") - \endcode - - \li String literal - \row - \li Mark as Translatable - \li Marks a string translatable. For example, rewrites \c "abcd" - with one of the following options, depending on which of them is - available: - - \code - tr("abcd") - QCoreApplication::translate("CONTEXT", "abcd") - QT_TRANSLATE_NOOP("GLOBAL", "abcd") - \endcode - - \li String literal - - \row - \li Add Definition in ... + \li Add Definition ... \li Inserts a definition stub for a function declaration either in the header file (inside or outside the class) or in the implementation file. For free functions, inserts the definition @@ -410,47 +444,381 @@ } \endcode - - \li Function name \row \li Add \c Function Declaration \li Inserts the member function declaration that matches the member function definition into the class declaration. The function can be \c {public}, \c {protected}, \c {private}, \c {public slot}, \c {protected slot}, or \c {private slot}. - \li Function name + \row + \li Apply Changes + \li Keeps function declarations and definitions synchronized by + checking for the matching declaration or definition when you + edit a function signature and by applying the changes to the + matching code. + + When this fix is available, a light bulb icon appears: + \inlineimage icons/refactormarker.png + \row + \li Convert Function Call to Qt Meta-Method Invocation + \li Converts an invokable function call into a meta method + invocation. This applies to signals and slots in general, + as well as functions explicitly marked with \c Q_INVOKABLE. + For example, for the following class: + \code + class Foo : public QObject + { + Q_OBJECT + public: + explicit Foo(QObject *parent = nullptr); + + Q_SLOT void pubBar(int i); + + private: + Q_INVOKABLE void bar(int i, const QString &c); + }; + \endcode + + rewrites + + \code + Foo::Foo(QObject *parent) + : QObject{parent} + { + this->bar(42, QString("answer")); + } + \endcode + + as + + \code + Foo::Foo(QObject *parent) + : QObject{parent} + { + QMetaObject::invokeMethod(this, "bar", Q_ARG(int, 42), Q_ARG(QString, QString("answer"))); + } + \endcode + + The quick fix also works on invokable methods outside the class that are + visible from the location where they are called from. For example, it + rewrites + + \code + Foo f; + f.pubBar(123); + \endcode + + as + + \code + Foo f; + QMetaObject::invokeMethod(&f, "pubBar", Q_ARG(int, 123)); + \endcode + \row + \li Move Definition Here + \li Moves an existing function definition to its declaration. + \row + \li Move Function Definition + \li Moves a function definition to the implementation file, outside + the class or back to its declaration. For example, rewrites + \code + class Foo + { + void bar() + { + // do stuff here + } + }; + \endcode + + as + \code + class Foo + { + void bar(); + }; + + void Foo::bar() { + // do stuff here + } + \endcode + \row + \li Move Function Documentation to Declaration/Definition + \li Moves the documentation comment for a function between its + declaration and definition. + \endtable + + \section1 Identifier + + \table + \header + \li Quick Fix + \li Description + \row + \li Add #include for undeclared or forward declared identifier + \li Adds an \c {#include} directive to the current file to make the + definition of a symbol available. \row \li Add Class Member \li Adds a member declaration for the class member being initialized if it is not yet declared. If \QC cannot automatically detect the data type of the member, you must add it. - \li Identifier \row - \li Create Implementations for Member Functions - \li Creates implementations for all member functions in one go. - In the \uicontrol {Member Function Implementations} dialog, - specify whether the member functions are generated - inline or outside the class. - \li Function name + \li Add Forward Declaration + \li Adds a forward declaration for an undeclared identifier + operation. \row - \li Switch with Next/Previous Parameter - \li Moves a parameter down or up one position in a parameter list. - \li Parameter in the declaration or definition of a function + \li Convert to Camel Case + \li Converts a symbol name to camel case, where elements of the name + are joined without delimiter characters and the initial + character of each element is capitalized. For example, rewrites + \c an_example_symbol as \c anExampleSymbol and + \c AN_EXAMPLE_SYMBOL as \c AnExampleSymbol + \endtable + + \section1 Numeric Literal + + \table + \header + \li Quick Fix + \li Description \row - \li Extract Function - \li Moves the selected code to a new function and replaces the block - of code with a call to the new function. Enter a name for the - function in the \uicontrol {Extract Function Refactoring} - dialog. - \li Block of code selected + \li Convert to Decimal + \li Converts an integer literal to decimal representation \row - \li Extract Constant as Function Parameter - \li Replaces the selected literal and all its occurrences with the - function parameter \c{newParameter}. The parameter - \c{newParameter} will have the original literal as the default - value. - \li Block of code selected + \li Convert to Hexadecimal + \li Converts an integer literal to hexadecimal representation + \row + \li Convert to Octal + \li Converts an integer literal to octal representation + \endtable + + \section1 Operator + + \table + \header + \li Quick Fix + \li Description + \li Operator + + \row + \li Rewrite Condition Using || + \li Rewrites the expression according to De Morgan's laws. For + example, rewrites + \code + !a && !b + \endcode + + as + + \code + !(a || b) + \endcode + \li \c && + \row + \li Rewrite Using \e operator + \li Rewrites an expression negating it and using the inverse + operator. For example, rewrites + + \list + + \li \code + a op b + \endcode + + as + + \code + !(a invop b) + \endcode + + \li \code + (a op b) + \endcode + + as + + \code + !(a invop b) + \endcode + + \li \code + !(a op b) + \endcode + + as + + \code + (a invob b) + \endcode + + \endlist + + \li \c {<=}, \c {<}, \c {>}, \c {>=}, \c {==} or \c {!=} + \row + \li Split if Statement + \li Splits an if statement into several statements. For example, + rewrites + + \code + if (something && something_else) { + } + \endcode + + as + + \code + if (something) { + if (something_else) { + } + } + \endcode + + and + + \code + if (something || something_else) + x; + \endcode + + with + + \code + if (something) + x; + else if (something_else) + x; + \endcode + + \li \c && or \c || + \row + \li Swap Operands + \li Rewrites an expression in the inverse order using the inverse + operator. For example, rewrites + \code + a op b + \endcode + + as + \code + b flipop a + \endcode + \li \c {<=}, \c {<}, \c {>}, \c {>=}, \c {==}, \c {!=}, \c {&&} + or \c {||} + \endtable + + \section1 String Literal + + \table + \header + \li Quick Fix + \li Description + \row + \li Convert to Objective-C String Literal + \li Converts a string literal to an Objective-C string literal if + the file type is Objective-C(++). For example, rewrites the + following strings + + \code + "abcd" + QLatin1String("abcd") + QLatin1Literal("abcd") + \endcode + + as + + \code + @"abcd" + \endcode + \row + \li Enclose in QByteArrayLiteral() + \li Converts a string to a byte array. For example, rewrites + \code + "abcd" + \endcode + + as + + \code + QByteArrayLiteral("abcd") + \endcode + \row + \li Enclose in QLatin1Char() + \li Sets the encoding for a character to Latin-1, unless the + character is already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, + tr, trUtf8, QLatin1Literal, or QLatin1String. For example, + rewrites + + \code + 'a' + \endcode + + as + + \code + QLatin1Char('a') + \endcode + \row + \li Enclose in QLatin1String() + \li Sets the encoding for a string to Latin-1, unless the string is + already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, tr, trUtf8, + QLatin1Literal, or QLatin1String. For example, rewrites + \code + "abcd" + \endcode + + as + + \code + QLatin1String("abcd") + \endcode + \row + \li Escape String Literal as UTF-8 + \li Escapes non-ASCII characters in a string literal to hexadecimal + escape sequences. String Literals are handled as UTF-8. + \row + \li Mark as Translatable + \li Marks a string translatable. For example, rewrites \c "abcd" + with one of the following options, depending on which of them is + available: + + \code + tr("abcd") + QCoreApplication::translate("CONTEXT", "abcd") + QT_TRANSLATE_NOOP("GLOBAL", "abcd") + \endcode + \row + \li Unescape String Literal as UTF-8 + \li Unescapes octal or hexadecimal escape sequences in a string + literal. String Literals are handled as UTF-8. + \endtable + + \section1 \c using directive + + \table + \header + \li Quick Fix + \li Description + \row + \li Remove All Occurrences of \c {using namespace} in Global Scope + and Adjust Type Names Accordingly + \li Remove all occurrences of \c {using namespace} in the global + scope and adjust type names accordingly. + \row + \li Remove \c {using namespace} and Adjust Type Names Accordingly + \li Remove occurrences of \c {using namespace} in the local scope + and adjust type names accordingly. + \endtable + + + \section1 Miscellaneous + + \table + \header + \li Quick Fix + \li Description + \li Activation \row \li Add Local Declaration \li Adds the type of an assignee, if the type of the right-hand @@ -469,277 +837,21 @@ where Type is the return type of \c {foo()} \li Assignee - \row - \li Convert to Camel Case - \li Converts a symbol name to camel case, where elements of the name - are joined without delimiter characters and the initial - character of each element is capitalized. For example, rewrites - \c an_example_symbol as \c anExampleSymbol and - \c AN_EXAMPLE_SYMBOL as \c AnExampleSymbol - \li Identifier + \li Convert connect() to Qt 5 Style + \li Converts a Qt 4 QObject::connect() to Qt 5 style. + \li QObject::connect() (Qt 4 style) \row - \li Complete Switch Statement - \li Adds all possible cases to a switch statement of the type - \c enum - \li \c switch - \row - \li Generate Missing Q_PROPERTY Members - \li Adds missing members to a \c Q_PROPERTY: - \list - \li \c read function - \li \c write function, if there is a WRITE - \li \c {onChanged} signal, if there is a NOTIFY - \li data member with the name \c {m_} - \endlist - \li \c Q_PROPERTY - \row - \li Generate Q_PROPERTY and Missing Members - \li Generates a Q_PROPERTY and adds missing members to it, as - described above. - \li Class member - \row - \li Generate Constant Q_PROPERTY and Missing Members - \li Generates a constant Q_PROPERTY and adds missing members - to it, as described above. - \li Class member - \row - \li Generate Q_PROPERTY and Missing Members with Reset Function - \li Generates a Q_PROPERTY and adds missing members to it, as - described above, but with an additional \c reset function. - \li Class member - \row - \li Apply Changes - \li Keeps function declarations and definitions synchronized by - checking for the matching declaration or definition when you - edit a function signature and by applying the changes to the - matching code. - \li Function signature. When this fix is available, a light bulb - icon appears: \inlineimage icons/refactormarker.png - \row - \li Add #include for undeclared or forward declared identifier - \li Adds an \c {#include} directive to the current file to make the - definition of a symbol available. - \li Undeclared identifier - \row - \li Add Forward Declaration - \li Adds a forward declaration for an undeclared identifier - operation. - \li Undeclared identifier - \row - \li Reformat Pointers or References - \li Reformats declarations with pointers or references according - to the code style settings for the current project. In case no - project is open, the current global code style settings are - used. - - For example, rewrites: - - \code - char*s; - \endcode - - as - - \code - char *s; - \endcode - - When applied to selections, all suitable declarations in the - selection are rewritten. - - \li Declarations with pointers or references and selections - that have such declarations - \row - \li Create Getter and Setter Member Functions - \li Creates either both getter and setter member functions for - member variables or only a getter or setter. - \li Member variable in class definition - \row - \li Generate Getter and Setter - \li Creates getter and setter member functions for a member - variable. - \li Member variable in class definition - \row - \li Generate Getter - \li Creates a getter member function for a member variable. - \li Member variable in class definition - \row - \li Generate Setter - \li Creates a setter member function for a member variable. - \li Member variable in class definition - \row - \li Generate Constructor - \li Creates a constructor for a class. - \li Class definition - \row - \li Move Function Definition - \li Moves a function definition to the implementation file, outside - the class or back to its declaration. For example, rewrites: - \code - class Foo - { - void bar() - { - // do stuff here - } - }; - \endcode - - as - \code - class Foo - { - void bar(); - }; - - void Foo::bar() { - // do stuff here - } - \endcode - - \li Function signature - \row - \li Move All Function Definitions - \li Moves all function definitions to the implementation file or - outside the class. For example, rewrites: - \code - class Foo - { - void bar() - { - // do stuff here - } - void baz() - { - // do stuff here - } - }; - \endcode - - as - - \code - class Foo - { - void bar(); - void baz(); - }; - - void Foo::bar() { - // do stuff here - } - - void Foo::baz() { - // do stuff here - } - \endcode - - \li Class name - \row - \li Move Definition Here - \li Moves an existing function definition to its declaration. - \li Function declaration - \row - \li Assign to Local Variable - \li Adds a local variable which stores the return value of a - function call or a new expression. For example, rewrites: - - \code - QString s; - s.toLatin1(); - \endcode - - as - - \code - QString s; - QByteArray latin1 = s.toLatin1(); - \endcode - - and - - \code - new Foo; - \endcode - - as - - \code - Foo * localFoo = new Foo; - \endcode - - By default, \QC uses the \c auto variable type when creating the - variable. To label the variable with its actual type, select - \preferences > \uicontrol C++ > - \uicontrol {Quick Fixes}, and then deselect the - \uicontrol {Use type "auto" when creating new variables} check - box. - - \li Function call or class name - \row - \li Insert Virtual Functions of Base Classes - \li Inserts declarations and the corresponding definitions inside or - outside the class or in an implementation file (if it exists). - For more information, see \l{Insert virtual functions}. - \li Class or base class name - \row - \li Optimize for-Loop - \li Rewrites post increment operators as pre increment operators and - post decrement operators as pre decrement operators. It also - moves other than string or numeric literals and id expressions - from the condition of a for loop to its initializer. For - example, rewrites: - - \code - for (int i = 0; i < 3 * 2; i++) - \endcode - - as - - \code - for (int i = 0, total = 3 * 2; i < total; ++i) - \endcode - \li \c for - - \row - \li Escape String Literal as UTF-8 - \li Escapes non-ASCII characters in a string literal to hexadecimal - escape sequences. String Literals are handled as UTF-8. - \li String literal - - \row - \li Unescape String Literal as UTF-8 - \li Unescapes octal or hexadecimal escape sequences in a string - literal. String Literals are handled as UTF-8. - \li String literal - - \row - \li Convert to Stack Variable - \li Converts the selected pointer to a stack variable. For example, - rewrites: - - \code - QByteArray *foo = new QByteArray("foo"); - foo->append("bar"); - \endcode - - as - - \code - QByteArray foo("foo"); - foo.append("bar"); - \endcode - - This operation is limited to work only within function scope. - Also, the coding style for pointers and references is not - respected yet. - \li Pointer Variable - + \li Convert Comment to C/C++ Style + \li Converts C-style comments into C++-style comments, and vice + versa. Tries to preserve \e pretty layout and takes Doxygen and + qdoc formatting into consideration, but you might need to clean + up the results. + \li Code comment \row \li Convert to Pointer \li Converts the selected stack variable to a pointer. For example, - rewrites: + rewrites \code QByteArray foo = "foo"; @@ -758,32 +870,69 @@ respected yet. \li Stack Variable \row - \li Remove \c {using namespace} and Adjust Type Names Accordingly - \li Remove occurrences of \c {using namespace} in the local scope - and adjust type names accordingly. - \li \c using directive - \row - \li Remove All Occurrences of \c {using namespace} in Global Scope - and Adjust Type Names Accordingly - \li Remove all occurrences of \c {using namespace} in the global - scope and adjust type names accordingly. - \li \c using directive + \li Convert to Stack Variable + \li Converts the selected pointer to a stack variable. For example, + rewrites + + \code + QByteArray *foo = new QByteArray("foo"); + foo->append("bar"); + \endcode + + as + + \code + QByteArray foo("foo"); + foo.append("bar"); + \endcode + + This operation is limited to work only within function scope. + Also, the coding style for pointers and references is not + respected yet. + \li Pointer Variable \row - \li Convert connect() to Qt 5 Style - \li Converts a Qt 4 QObject::connect() to Qt 5 style. - \li QObject::connect() (Qt 4 style) + \li Reformat Pointers or References + \li Reformats declarations with pointers or references according + to the code style settings for the current project. In case no + project is open, the current global code style settings are + used. + + For example, rewrites + + \code + char*s; + \endcode + + as + + \code + char *s; + \endcode + + When applied to selections, all suitable declarations in the + selection are rewritten. + + \li Declarations with pointers or references and selections + that have such declarations \row - \li Convert Comment to C/C++ Style - \li Converts C-style comments into C++-style comments, and vice - versa. Tries to preserve \e pretty layout and takes Doxygen and - qdoc formatting into consideration, but you might need to clean - up the results. - \li Code comment + \li Split Declaration + \li Splits a simple declaration into several declarations. For + example, rewrites + \code + int *a, b; + \endcode + + as + + \code + int *a; + int b; + \endcode + \li Type name or variable name \row - \li Move Function Documentation to Declaration/Definition - \li Moves the documentation comment for a function between its - declaration and definition. - \li Documentation comment for a function + \li Switch with Next/Previous Parameter + \li Moves a parameter down or up one position in a parameter list. + \li Parameter in the declaration or definition of a function \endtable \sa {Apply quick fixes}, {Find symbols}, {Rename symbols}, diff --git a/doc/qtcreator/src/editors/creator-only/creator-language-server.qdoc b/doc/qtcreator/src/editors/creator-only/creator-language-server.qdoc index aff9f9f357f..7fc22f4b0e8 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-language-server.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-language-server.qdoc @@ -36,6 +36,7 @@ \l{Outline} view or in the \uicontrol Symbols list on the \l{Edit Mode}{editor toolbar} \li \l{Call Hierarchy}{Viewing the callers and callees of a function} + \li \l{Type Hierarchy}{Viewing the base classes and derived classes of a class} \li \l{Find references to a symbol}{Finding references to symbols} \li \l{Rename symbols}{Renaming the symbol under the cursor} \li Code actions @@ -72,7 +73,7 @@ \image qtcreator-language-server-json.webp {Prompt to install JSON language server} - \l{Add a Java language server} for \l{Connecting Android Devices} + \l{Add a Java language server} for \l{Developing for Android} {Android development}. For other languages, \l{Add generic language servers}{add generic stdIO language servers}. @@ -84,12 +85,24 @@ To enable a language server, select the checkbox next to the language server name and set server preferences. - To turn on \l{Turn on \QMLLS}{\QMLLS}, go to - \preferences > \uicontrol {Qt Quick} > \uicontrol {QML/JS Editing} and - select \uicontrol {Enable \QMLLS}. + To configure \l{Configure \QMLLS}{\QMLLS}, go to + \preferences > \uicontrol {Qt Quick} > \uicontrol {QML/JS Editing}. To remove language servers from the list, select \uicontrol Delete. + \section1 Updating Python Language Server + + \QC offers to update the Python language server when you open a Python + file in the editor. + + \image qtcreator-python-update-language-server.webp {Message about updating Python Language Server} + + To update the language server, select \uicontrol Update. To save your choice, + select \uicontrol {Always Update}. + + To skip updating and hide the message for future updates, select + \uicontrol Never. + \section1 Supported Locator Filters The locator enables you to browse not only files, but any items defined by @@ -223,32 +236,33 @@ \ingroup creator-how-to-lsp - \title Turn on \QMLLS + \title Configure \QMLLS - Since Qt 6.4, \QMLLS offers code completion and - issues warnings for QML. To use it, go to \preferences > - \uicontrol {Qt Quick} > \uicontrol {QML/JS Editing} and select - \uicontrol {Enable \QMLLS}. + Since Qt 6.4, \QMLLS offers code completion and issues warnings for QML. - By default, enabling \QMLLS will only enable warning messages - and code completion, while advanced features such as renaming and finding usages - will be handled by the embedded code model. - To disable the embedded code model and use \QMLLS for everything, - select \uicontrol {Use \QMLLS advanced features}. + To turn off \QMLLS, go to \preferences > \uicontrol {Qt Quick} > + \uicontrol {QML/JS Editing} and clear \uicontrol {Turn on}. - Also, \QC tries to use \QMLLS shipped with - the Qt version in your current kit. To override that behavior and always use + By default, \QMLLS issues warning messages and provides code completion, + while the embedded code model handles advanced features, such as renaming + symbols and finding usages. To disable the embedded code model and use + \QMLLS for everything, select \uicontrol {Use advanced features}. + + Also, \QC tries to use \QMLLS shipped with the Qt version in your current + \l{Kits}{kit}. To override that behavior and always use \QMLLS of the highest registered Qt version, select - \uicontrol {Use \QMLLS from latest Qt version}. + \uicontrol {Use from latest Qt version}. + + To use older \QMLLS versions, select + \uicontrol{Allow versions below Qt 6.8}. \image qtcreator-qml-js-editing.webp {QML/JS Editing preferences} - When using \c qmlls from Qt 6.7 or later, set \l{QT_QML_GENERATE_QMLLS_INI} - to \c{ON} in \uicontrol Projects > \uicontrol {Build Settings} - > \uicontrol {Initial Configuration}. + To automatically configure new CMake projects, select + \uicontrol {Create .qmlls.ini files for new projects}. \sa {Manage Language Servers}{How To: Manage Language Servers}, - {Enabling and Disabling Messages}, {CMake Build Configuration}, + {Enabling and Disabling Messages}, {CMake Build Configuration}, {Kits}, {Language Servers} */ diff --git a/doc/qtcreator/src/editors/creator-only/creator-locator.qdoc b/doc/qtcreator/src/editors/creator-only/creator-locator.qdoc index eab661647fd..d739bd3445f 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-locator.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-locator.qdoc @@ -261,6 +261,16 @@ \endlist + \section1 Hiding Long Paths + + To hide the common part of absolute paths in the locator: + + \list 1 + \li Go to \preferences > \uicontrol Environment > \uicontrol Locator. + \li Select \uicontrol {Show Paths in Relation to Active Project} to + show relative paths. + \endlist + \sa {Navigate with locator}, {Search}{How To: Search}, {Perform calculations}, {Locator} */ diff --git a/doc/qtcreator/src/editors/creator-only/creator-modeling.qdoc b/doc/qtcreator/src/editors/creator-only/creator-modeling.qdoc index 426cc25d67c..0b20f36c335 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-modeling.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-modeling.qdoc @@ -30,15 +30,15 @@ You can create the following types of structural diagrams: \list - \li Package diagrams, which consist of packages and their relationships, + \li Package diagrams, which consist of packages and their relationships and visualize how the system is packaged. \li Class diagrams, which consists of classes, dependencies, inheritance, associations, aggregation, and composition, and show a system in an object-oriented way. \li Component diagrams, which represent a set of components and their - relationships, and show the implementation of a system. + relationships and show the implementation of a system. \li Deployment diagrams, which represent a set of software and hardware - components and their relationships, and visualize the deployment + components and their relationships and visualize the deployment of a system. \endlist @@ -55,19 +55,17 @@ \section1 Editing Models - You can create models that have several different structural or - behavioral diagrams. - You can add elements to the diagrams and specify properties for them. You - can either use standard model elements or add your own elements with custom - icons. + You can create models that have several different structural or behavioral + diagrams. Add elements to the diagrams and specify properties for them. Use + standard model elements or add your own elements with custom icons. - \image qtcreator-modeleditor.png {Class diagram in the model editor} + \image qtcreator-modeleditor.webp {Class diagram in the model editor} \caption A class diagram in the model editor. - You can add model elements to diagrams in the following ways: + Add elements to diagrams in the following ways: \list - \li Drag model elements from the element tool bar (1) to the + \li Drag elements from the element tool bar (1) to the editor (2). \li Select tool bar buttons (3) to add elements to the element tree (4). \li Drag elements from the element tree to the editor to add them and @@ -79,22 +77,26 @@ \section2 Grouping Elements - You can group elements by surrounding them with a boundary. When you move - the boundary, all elements within it are moved together. Similarly, drag - a swimlane to the diagram. When you move the swimlane, all elements right - to the swimlane (for vertical swimlanes) or below it (for horizontal swimlanes) - will be moved together. A vertical swimlane is created when you drop the - swimlane icon on the top border of the diagram and a horizontal swimlane - is created when you drop the icon near the left border. + To group elements, surround them with a \e boundary. When you move + the boundary, all elements within it move together. - Classes or other objects that you lay on packages are moved with the packages. - You can move individual elements and modify their properties (5) by selecting - them. You can also use \e multiselection to group elements temporarily. + Similarly, drag a \e swimlane to the diagram. When you move the swimlane, all + elements right to the swimlane (for vertical swimlanes) or below it (for + horizontal swimlanes) move together. + + To create a vertical swimlane, drop the swimlane icon on the top border of + the diagram. To create a horizontal swimlane, drop the icon near the left + border. + + Classes or other objects that you lay on packages move with the packages. + To move individual elements and modify their properties (5), select them. + + Use \e multiselection to group elements temporarily. \section2 Aligning Elements To align elements in the editor, select several elements and right-click to - open a context menu. Select actions in the \uicontrol {Align Objects} menu + open a context menu. Select actions in \uicontrol {Align Objects} menu to align elements horizontally or vertically or to adjust their width and height. @@ -111,20 +113,42 @@ then select \uicontrol {Add Related Elements} in the context menu. By default, when you select an element in a diagram, it is highlighted also - in the \uicontrol Structure view. To change this behavior so that selecting - an element in the \uicontrol Structure makes it highlighted also in the - diagram, click and hold the \inlineimage icons/linkicon.png - button, and then select \uicontrol {Synchronize Diagram with Structure}. - To keep the selections in the diagram and the \uicontrol Structure view + in \uicontrol Structure view. To change this behavior so that selecting + an element in \uicontrol Structure makes it highlighted also in the + diagram, select \inlineimage icons/linkicon.png and then select + \uicontrol {Synchronize Diagram with Structure}. + To keep the selections in the diagram and \uicontrol Structure view synchronized, select \uicontrol {Keep Synchronized}. + \section2 Linking from Element Names to Files + + To link to a file from the name of an element, select the file in + \uicontrol {Linked file}. + \section2 Zooming into Diagrams - To zoom into diagrams, select the \uicontrol {Zoom In} toolbar button, - press \key Ctrl++, or press \key Ctrl and roll the mouse wheel up. To zoom - out of diagrams, select \uicontrol {Zoom Out}, press \key Ctrl+-, or press - \key Ctrl and roll the mouse wheel down. To reset the diagram size to 100%, - select \uicontrol {Reset Zoom} or press \key Ctrl+0. + To zoom into diagrams: + + \list + \li Select \uicontrol {Zoom In} toolbar button. + \li Press \key Ctrl++. + \li Press \key Ctrl and roll the mouse wheel up. + \endlist + + To zoom out of diagrams: + + \list + \li Select \uicontrol {Zoom Out}. + \li Press \key Ctrl+-. + \li Press \key Ctrl and roll the mouse wheel down. + \endlist + + To reset the diagram size to 100%: + + \list + \li Select \uicontrol {Reset Zoom}. + \li Press \key Ctrl+0. + \endlist \section2 Printing Diagrams @@ -137,15 +161,27 @@ \section2 Exporting Diagrams as Images - To save diagrams as images, select \uicontrol File > + To save diagrams as images, go to \uicontrol File, and then select \uicontrol {Export Diagram}. To save only the selected parts of a diagram, select \uicontrol {Export Selected Elements}. \section1 Adding Custom Elements The model editor has the following built-in element types: package, - component, class, and item. For package, component, and class elements, you - can specify custom icons. The color, size, and form of the icon are + component, class, and item. + + To use custom icons for the built-in elements, select an image file in + \uicontrol {Image} in element properties. + + \image qtcreator-model-editor-component-diagram.webp {Component properties} + \caption The Image field in Component properties. + + \section2 Using Definition Files + + For package, component, and class elements, you can use definition files to + specify custom icons. + + The color, size, and form of the icon are determined by a stereotype. If you attach the stereotype to an element, the element icon is replaced by the custom icon. For example, you can attach the entity and interface stereotypes to classes and the database stereotype to @@ -185,7 +221,7 @@ and templates for existing types (such as a composition relation that can be drawn between classes). - You can add your own definition file and save it with the file extension + Add your own definition file and save it with the file extension \e .def to add custom colors and icons for stereotypes, elements, or tool bars. Either store this file in the same directory as the \e standard.def file or select the root element of a model and apply your @@ -203,47 +239,52 @@ \title Create UML-style models - You can use wizards to create UML-style models and \e {scratch models}. + Use wizards to create UML-style models and \e {scratch models}. To create models and edit them in the model editor: \list 1 - \li Select \uicontrol File > \uicontrol {New File} > \uicontrol Modeling - > \uicontrol Model > \uicontrol Choose. + \li Go to \uicontrol File > \uicontrol {New File} > \uicontrol Modeling + > \uicontrol Model, and then select \uicontrol Choose. The model file opens in the model editor. \li Drag model elements to the editor and select them to specify properties for them: - \image qtcreator-modeleditor-packages.png {Package diagram in the model editor} + \image qtcreator-modeleditor-packages.webp {Package diagram in the model editor} \caption A package diagram in the model editor. \list 1 - \li In the \uicontrol Stereotypes field, enter the stereotype to - apply to the model element or select a predefined stereotype + \li In \uicontrol Stereotypes, enter the stereotype to + apply to the element or select a predefined stereotype from the list. - \li In the \uicontrol Name field, give a name to the model element. + \li In \uicontrol Name, give a name to the element. - \li Select the \uicontrol {Auto sized} check box to reset the - element to its default size after you have changed the element + \li In \uicontrol {Linked file}, select a file to create a link to + it from the element name. + + \li In \uicontrol Image, select an image to use as a custom icon for + the element. + + \li Select \uicontrol {Auto sized} to reset the + element to its default size after you changed the element size by dragging its borders. - \li In the \uicontrol Color field, select the color of the model - element. + \li In \uicontrol Color, select the color of the element. - \li In the \uicontrol Role field, select a \e role to make the model + \li In \uicontrol Role, select a \e role to make the model element color lighter, darker, or softer. You can also remove color and draw the element outline or flatten the element by removing gradients. - \li Select the \uicontrol Emphasized check box to draw the model + \li Select \uicontrol Emphasized to draw the model element with a thicker line. - \li In the \uicontrol {Stereotype display} field, select: + \li In \uicontrol {Stereotype display}, select: \list @@ -283,12 +324,12 @@ \list 1 - \li In the \uicontrol Stereotypes field, select the + \li In \uicontrol Stereotypes, select the \e stereotype to apply to the relation. - \li In the \uicontrol Name field, give a name to the relation. + \li In \uicontrol Name, give a name to the relation. - \li In the \uicontrol Direction field, you can change the direction + \li In \uicontrol Direction, change the direction of the connection or make it bidirectional. \endlist @@ -321,11 +362,12 @@ Therefore, you can assign a \l{Keyboard Shortcuts}{keyboard shortcut} to the wizard and use it to create and open models with empty diagrams. - To create a scratch model, select \uicontrol File > \uicontrol {New File} > - \uicontrol Modeling > \uicontrol {Scratch Model} > \uicontrol Choose. + To create a scratch model, go to \uicontrol File > \uicontrol {New File} > + \uicontrol Modeling > \uicontrol {Scratch Model}, and then select + \uicontrol Choose. - \sa {Create class diagrams}, {Create component diagrams}, - {Create package diagrams}, {Model Editor} + \sa {Create Models and Diagrams}{How To: Create Models and Diagrams}, + {Model Editor} */ /*! @@ -336,27 +378,27 @@ \title Create package diagrams - You can create UML-style models that contain \e {package diagrams}. + Create UML-style models that contain \e {package diagrams}. They show packages and their relationships to visualize how the system is packaged. - You can add nested package elements to a package diagram. The depth of the + Add nested package elements to a package diagram. The depth of the elements in the diagram corresponds to the depth of the structured model. Elements stacked on other elements of the same type are automatically drawn in a darker shade of the selected color. - \image qtcreator-modeleditor-packages.png {Package diagram in the model editor} + \image qtcreator-modeleditor-packages.webp {Package diagram in the model editor} \caption A package diagram in the model editor. - Right-click a package to open a context menu, where you can select + Right-click a package to open a context menu, and select \uicontrol {Create Diagram} to create a new package diagram within the - model. You can drag items from the element tree to the diagram. + model. Drag items from the element tree to the diagram. To update the include dependencies of the package, select \uicontrol {Update Include Dependencies}. - \sa {Create class diagrams},{Create component diagrams}, - {Create UML-style models}, {Model Editor} + \sa {Create Models and Diagrams}{How To: Create Models and Diagrams}, + {Model Editor} */ /*! @@ -367,11 +409,11 @@ \title Create class diagrams - You can create UML-style models that contain \e {class diagrams}. They show + Create UML-style models that contain \e {class diagrams}. They show classes, dependencies, inheritance, associations, aggregation, and composition to visualize a system in an object-oriented way. - \image qtcreator-modeleditor-classes.png {Class diagram in the model editor} + \image qtcreator-modeleditor-classes.webp {Class diagram in the model editor} \caption A class diagram in the model editor. To create class diagrams: @@ -387,10 +429,10 @@ \list - \li In the \uicontrol Template field, specify the template to + \li In \uicontrol Template, specify the template to use. - \li In the \uicontrol {Template display} field, select the + \li In \uicontrol {Template display}, select the display format for the template: \list @@ -409,15 +451,15 @@ \endlist - \li In the \uicontrol Members field, specify members for the + \li In \uicontrol Members, specify members for the class, as described in \l {Specify members}. \li Select \uicontrol {Clean Up} to format the contents of - the \uicontrol Members field depending on their visibility + \uicontrol Members depending on their visibility (private, protected, public) and following the rules set for whitespace, line breaks, and so on. - \li Select the \uicontrol {Show members} check box to show + \li Select \uicontrol {Show members} to show the members in the diagram. \endlist @@ -431,17 +473,36 @@ \section1 Add relations Elements in class diagrams can have the following types of relations: - inheritance, association, and dependency. The end points of association - relations can have the following properties: role, cardinality, navigable, - and relationship. + + \list + \li Aggregation + \li Association + \li Composition + \li Dependency + \li Inheritance + \endlist + + The end points of association relations can have the following properties: + + \list + \li Cardinality + \li Navigable + \li Role + \li Relationship + \endlist + + \section2 Create self-relations To create self-relations, start creating a new association and press \key Shift to create a new \e {sampling point} while dragging the association. Create another sampling point and drag the association to the same class. - To add more points, press \key Shift and click a relation. To delete a - point, press \key Ctrl and click a point. + \section2 Add and delete points + + To add more points, press \key Shift and click a relation. + + To delete a point, press \key Ctrl and click a point. \section2 Specify members @@ -490,8 +551,8 @@ \endlist - \sa {Create component diagrams}, {Create package diagrams}, - {Create UML-style models}, {Model Editor} + \sa {Create Models and Diagrams}{How To: Create Models and Diagrams}, + {Model Editor} */ /*! @@ -502,14 +563,19 @@ \title Create component diagrams - You can create UML-style models that contain \e {component diagrams}. - They epresent a set of components and their relationships, and show the + Create UML-style models that contain \e {component diagrams}. + They represent a set of components and their relationships, and show the implementation of a system. - You can add source code components, such as libraries, databases, programs, - and architectural layers to a component diagram. To add components to - component diagrams, drag source code from \uicontrol Projects to - the editor, and select \uicontrol {Add Component}. + Add source code components, such as libraries, databases, programs, + and architectural layers to a component diagram. + + To add components to component diagrams: + + \list 1 + \li Drag source code from \uicontrol Projects to the editor. + \li Select \uicontrol {Add Component}. + \endlist \image qtcreator-model-editor-component-diagram.webp {Component diagram in the model editor} \caption A component diagram in the model editor. @@ -518,6 +584,6 @@ the component in the editor or select \uicontrol {Show Definition} in the context menu. - \sa {Create class diagrams}, {Create package diagrams}, - {Create UML-style models}, {Model Editor} + \sa {Create Models and Diagrams}{How To: Create Models and Diagrams}, + {Model Editor} */ diff --git a/doc/qtcreator/src/editors/creator-only/creator-preferences-cpp-code-style.qdoc b/doc/qtcreator/src/editors/creator-only/creator-preferences-cpp-code-style.qdoc index 56e413b7e93..024b731d3ca 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-preferences-cpp-code-style.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-preferences-cpp-code-style.qdoc @@ -54,6 +54,8 @@ \list \li Interpret the \key Tab and \key Backspace key presses. + \li Add macros that the indenter interprets as complete statements that + don't require a semicolon at the end. \li Indent the contents of classes, functions, blocks, and namespaces. \li Indent braces in classes, namespaces, enums, functions, and blocks. \li Control switch statements and their contents. diff --git a/doc/qtcreator/src/editors/creator-only/creator-scxml.qdoc b/doc/qtcreator/src/editors/creator-only/creator-scxml.qdoc index 80ffbe8ab2b..1600c557a95 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-scxml.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-scxml.qdoc @@ -233,6 +233,9 @@ The editor center-aligns transition labels, but you can drag them to other positions. + Conditions on transitions appear below the transition lines within square + brackets ([]). + To add edge points to transitions, select a transition line. You can add only two edge points for each line. The editor automatically removes unnecessary edge points. To remove the selected edge point, select diff --git a/doc/qtcreator/src/editors/creator-quick-fixes.qdoc b/doc/qtcreator/src/editors/creator-quick-fixes.qdoc index 7e02f60c650..6ef8f778737 100644 --- a/doc/qtcreator/src/editors/creator-quick-fixes.qdoc +++ b/doc/qtcreator/src/editors/creator-quick-fixes.qdoc @@ -38,7 +38,7 @@ By default, the refactored files are saved automatically. To turn off this feature, go to \preferences > \uicontrol Environment > - \uicontrol System and select \uicontrol {Auto-save files after refactoring}. + \uicontrol System and clear \uicontrol {Auto-save files after refactoring}. \if defined(qtcreator) \section1 Create functions @@ -94,6 +94,17 @@ {C++ Quick Fixes} \endif + \section1 Move classes to separate files + + Apply the \uicontrol {Move Class to a Dedicated Set of Source Files} quick + fix to move a class to a separate set of header and implementation files. + + \image qtcreator-move-class-to-separate-files.webp {Give names to header and implementation files} + + Specify paths and file names for the header and implementation file. + + To omit the implementation file, select \uicontrol {Header file only}. + \sa {Rename symbols}, {QML Quick Fixes} */ diff --git a/doc/qtcreator/src/external-resources/external-resources.qdoc b/doc/qtcreator/src/external-resources/external-resources.qdoc index 0fa7ca60dff..bc9ee595a80 100644 --- a/doc/qtcreator/src/external-resources/external-resources.qdoc +++ b/doc/qtcreator/src/external-resources/external-resources.qdoc @@ -1,17 +1,29 @@ // Copyright (C) 2022 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only +/*! + \externalpage https://doc.qt.io/index.html + \title Qt Documentation +*/ /*! \externalpage https://www.perforce.com/manuals/cmdref/Content/CmdRef/P4CONFIG.html \title Perforce: P4CONFIG */ +/*! + \externalpage https://doc.qt.io/qt-6/qtdesigner-manual.html + \title Qt Widgets Designer Manual +*/ +/*! + \externalpage https://doc.qt.io/qt-6/designer-using-custom-widgets.html + \title Using Custom Widgets with Qt Widgets Designer +*/ /*! \externalpage https://doc.qt.io/Boot2Qt/index.html - \title Boot2Qt: Documentation + \title \B2Q: Documentation */ /*! \externalpage https://doc.qt.io/Boot2Qt/b2qt-requirements-x11.html#setting-up-usb-access-to-embedded-devices - \title Boot2Qt: Setting Up USB Access to Embedded Devices + \title \B2Q: Setting Up USB Access to Embedded Devices */ /*! \externalpage https://doc.qt.io/qt/qtqml-index.html @@ -54,8 +66,8 @@ \title Getting Started on Windows */ /*! - \externalpage https://adoptopenjdk.net/ - \title AdoptOpenJDK + \externalpage https://adoptium.net/ + \title Adoptium OpenJDK */ /*! \externalpage http://openjdk.java.net @@ -205,3 +217,19 @@ \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 +*/ +/*! + \externalpage https://www.openssh.com/ + \title OpenSSH +*/ diff --git a/doc/qtcreator/src/howto/creator-external-tools.qdoc b/doc/qtcreator/src/howto/creator-external-tools.qdoc index 13927f3d677..fa58a1e80a2 100644 --- a/doc/qtcreator/src/howto/creator-external-tools.qdoc +++ b/doc/qtcreator/src/howto/creator-external-tools.qdoc @@ -77,7 +77,7 @@ {build environment} or \l {Specify the run environment} {run environment} of the active project. Select the build or run environment if the system environment does not have the necessary - PATH settings to find the tool chain, for example. + PATH settings to find the toolchain, for example. \else \li In the \uicontrol {Base environment} field, use the default settings. \endif @@ -209,6 +209,10 @@ \uicontrol External > \uicontrol {Qt Quick} > \uicontrol {QML Runtime}. \sa {Use external tools} + + \if defined(qtcreator) + \sa {Design UIs}{How To: Design UIs}, {UI Design} + \endif */ /*! diff --git a/doc/qtcreator/src/howto/creator-help.qdoc b/doc/qtcreator/src/howto/creator-help.qdoc index 434ee6fe9b2..fa770177839 100644 --- a/doc/qtcreator/src/howto/creator-help.qdoc +++ b/doc/qtcreator/src/howto/creator-help.qdoc @@ -23,26 +23,26 @@ \li To view context sensitive help on a Qt class or function as a tooltip, move the mouse cursor over the class or function. If help - is not available, the tooltip displays type information for the + is not available, the tooltip shows type information for the symbol. - \li To display tooltips for function signatures regardless of the + \li To show tooltips for function signatures regardless of the cursor position in the function call, press \key {Ctrl+Shift+D}. - \li To display the full help on a Qt class or function, press \key F1 or + \li To show the full help on a Qt class or function, press \key F1 or select \uicontrol {Context Help} in the context menu. - The documentation is displayed in a + The documentation is shown in a view next to the code editor, or, if there is not enough vertical space, in the fullscreen \uicontrol Help mode. - \li To select and configure how the documentation is displayed in the - \uicontrol Help mode, select \preferences > \uicontrol Help. + \li To change how the documentation is shown in the + \uicontrol Help mode, go to \preferences > \uicontrol Help. \endlist - The following image displays the context sensitive help in the \uicontrol Edit + The following image shows the context sensitive help in the \uicontrol Edit mode. - \image qtcreator-context-sensitive-help.png {Context-sensitive help in Edit mode} + \image qtcreator-context-sensitive-help.webp {Context-sensitive help in Edit mode} \section1 Change the font @@ -52,43 +52,43 @@ \image qtcreator-preferences-help-general.webp {General tab in Help preferences} - You can set the default zoom level in the \uicontrol Zoom field. When - viewing help pages, you can use the mouse scroll wheel to zoom them. To - disable this feature, deselect the \uicontrol {Enable scroll wheel zooming} - check box. + Set the default zoom level in \uicontrol Zoom. When viewing help pages, use + the mouse scroll wheel to zoom them. To turn off this feature, clear + \uicontrol {Enable scroll wheel zooming}. - To disable antialiasing, deselect the \uicontrol Antialiasing check box. + To turn off antialiasing, clear \uicontrol Antialias. \section1 Return to the editor To switch to the editor context when you close the last help page, select - the \uicontrol {Return to editor on closing the last page} check box. + \uicontrol {Return to editor on closing the last page}. \section1 Select help viewer backend - The help viewer backend determines the style sheet that is used to display + The help viewer backend determines the style sheet that is used to show the help files. The default help viewer backend that is based on litehtml is recommended for viewing Qt documentation. You can choose another help - viewer backend in the \uicontrol {Viewer backend} field. To take the new + viewer backend in the \uicontrol {Viewer backend}. To take the new backend to use, reload the help page. \section1 View function tooltips - To hide function tooltips by default, select \preferences > - \uicontrol {Text Editor} > \uicontrol Behavior > - \uicontrol {Show help tooltips using the mouse} > - \uicontrol {On Shift+Mouseover}. You can still view the tooltips by pressing - and holding down the \key Shift key. + To hide function tooltips by default: + + \list 1 + \li Go to \preferences > \uicontrol {Text Editor} > \uicontrol Behavior. + \image qtcreator-preferences-texteditor-behavior.webp {Text Editor Behavior preferences} + \li In \uicontrol {Show help tooltips using the mouse}, select + \uicontrol {On Shift+Mouseover}. + \endlist + + You can still view the tooltips by pressing and holding down the \key Shift + key. To use a keyboard shortcut for viewing help tooltips, select \uicontrol {Show help tooltips using keyboard shortcut (Alt)}. - \sa {Find information in Qt documentation}, {Filter documentation}, - {Search from documentation} - - \sa {Add external documentation}, {Detach the help window}, - {Filter documentation}, {Find information in Qt documentation}, - {Select the help start page} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -103,15 +103,18 @@ \title Find information in Qt documentation - \QC, \QSDK and other Qt deliverables have documentation - as .qch files. All the documentation is accessible in the \uicontrol Help mode. + \QC installer, \QOI, and other Qt deliverables install documentation as .qch + files. View the documentation in the \uicontrol Help mode. To view the + currently open document online, select \inlineimage icons/online.png + (\uicontrol {Open Online Documentation}). By default, \QC registers only the latest available version of the documentation for each installed Qt module. To register all installed - documentation, select \preferences > \uicontrol Kits > - \uicontrol {Qt Versions} > \uicontrol {Register documentation}. + documentation, go to \preferences > \uicontrol Kits > + \uicontrol {Qt Versions} and select an option in + \uicontrol {Register documentation}. - \image qtcreator-qt-versions.png {Register documentation field in Qt Versions tab in Kit Preferences} + \image qtcreator-qt-versions.png {Register documentation in Qt Versions preferences} \section1 Help mode sidebar views @@ -137,7 +140,7 @@ \endlist - \sa {Add bookmarks to help pages}, {Search from documentation} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -152,8 +155,8 @@ \title Add bookmarks to help pages - You can add bookmarks to useful help pages to easily find them later - in the \uicontrol Bookmarks view. You can either use the page title as the + Add bookmarks to useful help pages to easily find them later + in the \uicontrol Bookmarks view. Either use the page title as the bookmark or change it to any text. You can organize the bookmarks in folders in the view. @@ -163,21 +166,21 @@ \list 1 - \li Click the \inlineimage icons/bookmark.png - (\uicontrol {Add Bookmark}) button on the toolbar. + \li Select \inlineimage icons/bookmark.png (\uicontrol {Add Bookmark}) + on the toolbar. - \li In the \uicontrol {Add Bookmark} dialog, click \uicontrol OK to save the + \li In the \uicontrol {Add Bookmark} dialog, select \uicontrol OK to save the page title as a bookmark in the selected folder. \endlist \section1 Import and export bookmarks - To import and export bookmarks, select \preferences > - \uicontrol Help > \uicontrol General > \uicontrol {Import Bookmarks} or + To import and export bookmarks, go to \preferences > \uicontrol Help > + \uicontrol General and select \uicontrol {Import Bookmarks} or \uicontrol {Export Bookmarks}. - \sa {Find information in Qt documentation} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -192,10 +195,10 @@ \title Search from documentation - In the \uicontrol Help mode \uicontrol Search pane, you can use full-text + In the \uicontrol Help mode \uicontrol Search pane, use full-text search for finding a particular word in all the installed documents. Enter the term you are - looking for, and select the \uicontrol Search button. All documents that + looking for, and select \uicontrol Search. All documents that have the specified term are listed. The list is sorted by document version (if you have installed several Qt versions, for example) and the number of search hits that the documents have. Select a document in @@ -225,16 +228,15 @@ time when you open the \uicontrol Search pane. If you add or remove documents, \QC recreates the index. - If you cannot find words that you know are there, indexing might not have - been completed for some reason. To regenerate the index, click - \inlineimage icons/reload_gray.png + If you cannot find words that you know are there, the index might not be + complete. To recreate it, select \inlineimage icons/reload_gray.png (\uicontrol {Regenerate Index}). Punctuation is not included in indexed terms. To find terms that have punctuation, such as domain names, use the asterisk as a wild card. For example, to find \c {Pastebin.Com}, enter the search term \c {Pastebin*}. - \sa {Find information in Qt documentation} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -249,7 +251,7 @@ \title Add external documentation - You can display external documentation in the \uicontrol Help mode. + You can view external documentation in the \uicontrol Help mode. To add documentation or replace the documentation that ships with \QC and Qt: \list 1 @@ -259,14 +261,14 @@ For information on how to prepare your documentation and create a .qch file, see \l{The Qt Help Framework}. - \li To add the .qch file to \QC, select \preferences > + \li To add the .qch file to \QC, go to \preferences > \uicontrol Help > \uicontrol Documentation > \uicontrol Add. \image qtcreator-preferences-help-documentation.webp {Documentation tab in Help Preferences} \endlist - \sa {Get help} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -281,26 +283,24 @@ \title Detach the help window - By default, context-sensitive help is opened in a window next to the + By default, context-sensitive help opens in a window next to the code editor when you press \key F1. If there is not enough vertical space, the help opens in the full-screen help mode. - \image qtcreator-context-sensitive-help.png {Context-sensitive help in Edit mode} + \image qtcreator-context-sensitive-help.webp {Context-sensitive help in Edit mode} - To specify that the help always opens in full-screen mode or - is detached to an external window, select \preferences > \uicontrol Help > - \uicontrol General. + To specify that the help always opens in full-screen mode or in an external + window, go to \preferences > \uicontrol Help > \uicontrol General. \image qtcreator-preferences-help-general.webp {General tab in Help preferences} - Set preferences for displaying context-sensitive help - in the \uicontrol {On context help} field. To detach the help window, select + Set preferences for viewing context-sensitive help + in \uicontrol {On context help}. To detach the help window, select \uicontrol {Always Show in External Window}. - To change this setting in a help view, select the \inlineimage icons/linkicon.png - toolbar button. + To change this setting in a help view, select \inlineimage icons/linkicon.png. - \sa {Get help} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -315,27 +315,27 @@ \title Select the help start page - You can select the page to display when you open the \uicontrol Help mode in the - \preferences > \uicontrol Help > \uicontrol General > - \uicontrol {On help start} field. + To set the page to show when you open the \uicontrol Help mode, go to + \preferences > \uicontrol Help > \uicontrol General and select + \uicontrol {On help start}. \image qtcreator-preferences-help-general.webp {General tab in Help preferences} \list - \li To display the page and help views that were open when you exited the mode, + \li To show the page and help views that were open when you exited the mode, select the \uicontrol {Show My Tabs from Last Session} option. However, Web pages are not opened because loading them would slow down opening the \uicontrol Help mode. - \li To display a particular page, select \uicontrol {Show My Home Page}, and specify - the page in the \uicontrol {Home Page} field. + \li To show a particular page, select \uicontrol {Show My Home Page}, and specify + the page in \uicontrol {Home Page}. - \li To display a blank page, select the \uicontrol {Show a Blank Page} option. You can - also select the \uicontrol {Use Blank Page} button to set a blank page as your + \li To show a blank page, select the \uicontrol {Show a Blank Page} option. + Select \uicontrol {Use Blank Page} to set a blank page as your home page. \endlist - \sa {Get help} + \sa {Read Documentation}{How To: Read Documentation} */ /*! @@ -350,40 +350,40 @@ \title Filter documentation - You can filter the documents displayed in the \uicontrol Help mode to find + Filter the documents in the \uicontrol Help mode to find relevant information faster. Select a filter from a list of filters. The contents of the \uicontrol Index and \uicontrol Contents view in the sidebar change accordingly. - \image qtcreator-help-filters.png {Filters field on the Help mode toolbar} + \image qtcreator-help-filters.png {Filters on the Help mode toolbar} \section1 Add filters - You can define your own filters to display documentation for a set of + Define your own filters to show documentation for a set of Qt modules and versions. To add filters: \list 1 - \li Select \preferences > \uicontrol Help > \uicontrol Filters. + \li Go to \preferences > \uicontrol Help > \uicontrol Filters. \image qtcreator-help-filter-attributes.png {Filters tab in Help preferences} \li Select \inlineimage icons/plus.png to add a new filter in the \uicontrol {Add Filter} dialog. - \li In the \uicontrol {Filter name} field, enter a name for the filter, + \li In \uicontrol {Filter name}, enter a name for the filter, and then select \uicontrol {OK} to return to the \uicontrol Filters tab. - \li In the \uicontrol Components field, select the Qt modules to include + \li In \uicontrol Components, select the Qt modules to include in the filter. - \li In the \uicontrol Versions field, select the Qt versions to include + \li In \uicontrol Versions, select the Qt versions to include in the filter. - \li Click \uicontrol OK. + \li Select \uicontrol OK. \li In the \uicontrol Help mode, select the filter in the list of filters to see the filtered documentation in the sidebar. @@ -392,15 +392,14 @@ \section1 Change filters - To modify the selected filter, add and remove Qt modules and versions, and + To modify the selected filter, add and remove Qt modules and versions and then select \uicontrol Apply. To rename the selected filter, select \uicontrol Rename. \section1 Remove filters - To remove the selected filter select \inlineimage icons/minus.png - . + To remove the selected filter, select \inlineimage icons/minus.png. - \sa {Get help} + \sa {Read Documentation}{How To: Read Documentation} */ diff --git a/doc/qtcreator/src/howto/creator-how-to-view-images.qdoc b/doc/qtcreator/src/howto/creator-how-to-view-images.qdoc index c5cf673347a..17d660c4d69 100644 --- a/doc/qtcreator/src/howto/creator-how-to-view-images.qdoc +++ b/doc/qtcreator/src/howto/creator-how-to-view-images.qdoc @@ -43,6 +43,10 @@ Select \uicontrol {Set as Default} to use the current settings for the background and outline modes and fitting images to screen as default values for the image viewer. + + \if defined(qtcreator) + \sa {Design UIs}{How To: Design UIs}, {UI Design} + \endif */ /*! @@ -67,4 +71,8 @@ You can then use QIcon::addPixmap() to add the pixmaps to icons in different modes and states. + + \if defined(qtcreator) + \sa {Design UIs}{How To: Design UIs}, {UI Design} + \endif */ diff --git a/doc/qtcreator/src/howto/creator-only/creator-autotest.qdoc b/doc/qtcreator/src/howto/creator-only/creator-autotest.qdoc index f05c16181a6..0c3ff91b303 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-autotest.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-autotest.qdoc @@ -359,10 +359,6 @@ found by the code based test frameworks and are registered as test with the build system. - If a test takes more than a minute to execute, the default timeout might - stop the test execution. To increase the timeout, go to \preferences > - \uicontrol {Testing} > \uicontrol General. - \section1 Select tests to run The \uicontrol Tests view shows all the tests found for the currently active @@ -501,7 +497,7 @@ the current project. \row \li \uicontrol {Timeout} - \li The maximum time in seconds to execute a test case. + \li Set a maximum time in seconds to execute a test case. \row \li \uicontrol {Reset Cached Choices} \li Sometimes, \QC cannot deduce which executable or run configuration to @@ -519,7 +515,7 @@ By default, \QC groups tests that are in the same directory. \endtable - To select the testing framework for the current project, go to + To override some preferences for the current project, go to \uicontrol Projects > \uicontrol {Project Settings} > \uicontrol {Testing}. \section1 Qt Tests @@ -719,7 +715,7 @@ \li Disable statistical analysis and bootstrapping. \endtable - \section2 Specifying Settings for Running CTest-Based Tests + \section1 CTest-Based Tests To specify settings for running CTest-based tests, go to \preferences > \uicontrol {Testing} > \uicontrol {CTest}. @@ -751,7 +747,7 @@ \li Re-run tests, as determined by \uicontrol {Repetition mode}. Set the maximum number of times for repeating a test in \uicontrol {Count}. \row - \li \uicontrol {Run in parallel} + \li \uicontrol {Run in Parallel} \li Run the tests in parallel using the specified number of \uicontrol {Jobs}. In \uicontrol {Test load}, limit the parallel execution. CTest will not start a new test if it would cause the @@ -853,8 +849,7 @@ \section1 Blacklisting Tests - Since Qt 5.4, you can add a BLACKLIST file for tests. It is mainly used - internally by the Qt CI system. + A BLACKLIST file for tests is mainly used internally by the Qt CI system. \table \header diff --git a/doc/qtcreator/src/howto/creator-only/creator-cli.qdoc b/doc/qtcreator/src/howto/creator-only/creator-cli.qdoc index fbc885df055..a0e9129c6b9 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-cli.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-cli.qdoc @@ -93,7 +93,7 @@ \row \li -installsettingspath \li Override the default path from where user-independent settings are read - (for example written by the installer). + (for example, those written by the installer). \row \li -temporarycleansettings, -tcs @@ -104,6 +104,10 @@ \li -language \li Set the UI language. + Use a lowercase, two-letter + \l {https://www.iso.org/iso-639-language-codes.html} + {ISO 639 language code}, such as \e de, \e en, or \e fr. + \row \li -test [,testfunction[:testdata]] ... \li For \QC plugin developers: run the plugin's tests using a diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-to-find-settings-files.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-to-find-settings-files.qdoc index 8bfb773a402..81bc78e3077 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-how-to-find-settings-files.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-how-to-find-settings-files.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 /*! @@ -7,9 +7,9 @@ \ingroup creator-how-to-use - \title Find settings files + \title Reset \QC settings - \QC creates the following files and directories: + To reset all \QC settings, remove the settings files that it creates: \list \li QtCreator.db @@ -29,4 +29,32 @@ \li On Windows, look in \c {%appdata%\QtProject} and \c {%localappdata%\QtProject}. \endlist + + To check whether the settings are causing a problem before resetting them, + start \QC from the command line with options. + + \section1 Override the default settings path + + To override the default path where user settings are stored, enter: + + \badcode + qtcreator -settingspath + \endcode + + To override the default path from where user-independent settings are read + (for example, those written by the installer), enter: + + \badcode + qtcreator -installsettingspath + \endcode + + \section1 Start \QC with temporary clean settings + + To use clean settings that are deleted when you quit \QC, enter: + + \badcode + qtcreator -tcs + \endcode + + \sa {Run Qt Creator from the command line} */ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-to-install-extensions.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-to-install-extensions.qdoc new file mode 100644 index 00000000000..13ebc406b25 --- /dev/null +++ b/doc/qtcreator/src/howto/creator-only/creator-how-to-install-extensions.qdoc @@ -0,0 +1,39 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-load-extensions.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-use + + \title Load extensions + + In the experimental \uicontrol Extensions mode, you can load and unload + extensions from the computer or the web. + + To load extensions when you start \QC: + + \list 1 + \li Go to \uicontrol Extensions. + \image qtcreator-extension-mode.webp {Extensions mode} + \li Select an extension. + \li Select \uicontrol {Load on start}. + \endlist + + \section1 Load extensions from the web + + By default, the \uicontrol Extensions mode lists extensions installed on the + computer. You can also list extensions from external repositories in the web. + + To load extensions from the web: + + \list 1 + \li Go to \preferences > \uicontrol Environment > \uicontrol Extensions. + \image qtcreator-preferences-extensions.webp {Extensions in Preferences} + \li Select \uicontrol {Use external repository}. + \li Select \uicontrol OK. + \endlist + + \sa {Enable and disable plugins}, {Install plugins} +*/ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-to-install.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-to-install.qdoc index d19c3e9d8fb..f64c870cfe0 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-how-to-install.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-how-to-install.qdoc @@ -3,14 +3,13 @@ /*! \page creator-how-to-install.html - \previouspage creator-how-tos.html + \previouspage index.html + \nextpage creator-getting-started.html - \ingroup creator-how-to-use - - \title Install \QC + \title Installation You can install either a \e commercial or \e {open source} version of \QC in - many ways: + the following ways: \list \li As a part of a Qt installation with \l{Get and Install Qt}{\QOI}. @@ -41,13 +40,13 @@ instructions to install \QC. To develop with Qt, you also need a Qt version. You can register Qt versions - in the stand-alone \QC to use them in \l{kits-tab}{kits}. + in the stand-alone \QC to use them in \l{Kits}{kits}. - \section2 Use package managers + \section2 Using Package Managers The \QC packages that package managers offer are not officially supported. For links to official releases, see - \l {Download installation packages}. + \l {Downloading Installation Packages}. On Windows you can use \c chocolatey, and on \macos you can use \c brew. These package managers install the latest \QC releases available online. @@ -68,7 +67,7 @@ \note Linux distributions might have old \QC versions, so you might want to download and install the latest version. - \section2 Download installation packages + \section2 Downloading Installation Packages You can download \QC installation packages from: @@ -81,7 +80,7 @@ \li \l{https://github.com/qt-creator/qt-creator/releases}{GitHub} \endlist - \section2 Build from sources + \section2 Building from Sources To test the very latest \QC version, maybe with your own changes, you can build it from sources. For more information, see @@ -89,5 +88,5 @@ {Compiling \QC} and \l{https://wiki.qt.io/Building_Qt_Creator_from_Git} {Building Qt Creator from Git}. - \sa {Register installed Qt versions} + \sa {Manage Kits}{How To: Manage Kits}, {Register installed Qt versions} */ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc index 307c436d224..d31fe7a97bd 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc @@ -66,8 +66,7 @@ \section1 Debug - Use native debuggers to inspect the state of your application while - debugging. + Use debuggers to inspect the state of your application while it is running. \generatelist creator-how-to-debug @@ -86,15 +85,69 @@ embedded or mobile platform on the computer, and use \QOI to install Qt libraries that are built for the platform. Then add a kit with the toolchain and the Qt version for the device's architecture. - When possible, \QOI creates suitable kits for you. + When possible, \QOI creates suitable kits for you. Connect the devices + to the computer to run, debug, and analyze applications on them. + + \section2 Android + + Install \l {Qt for Android} and Android tools, and connect Android devices to + the computer. + + \generatelist creator-how-to-android + + \section2 Bare Metal + + Run and debug applications on small Linux devices that are not supported + by the remote Linux device plugin by using GDB or a hardware debugger. + + \generatelist creator-how-to-bare-metal + + \section2 \B2Q + + Run, debug, and analyze applications on \l{\B2Q: Documentation}{\B2Q} + devices. + + \generatelist creator-how-to-b2qt + + \section2 Docker + + Create \e {Docker devices} from \e {Docker images} and use them to build, + run, and debug applications. + + \generatelist creator-how-to-docker + + \section2 iOS + + Install \l {Qt for iOS} and Xcode, and connect iOS devices to the computer. + + \generatelist creator-how-to-ios \section2 MCUs - Install \l {Qt for MCUs} and connect devices to the computer to run and - debug applications on them. + Install \l {Qt for MCUs}, and connect microcontrollers to the computer. \generatelist creator-how-to-mcu + \section2 QNX Neutrino + + Install \l {Qt for QNX}, and connect QNX Neutrino devices to the computer. + + \generatelist creator-how-to-qnx + + \section2 Remote Linux + + Add kits for toolchains for building applications for generic Linux + devices, and connect the devices to the computer. + + \generatelist creator-how-to-remote-linux + + \section2 WebAssembly + + Install \l{Qt for WebAssembly} to build applications for the web and run them + in a web browser. + + \generatelist creator-how-to-webassembly + \section1 Edit Code The code editor offers useful features for editing C++ and QML code, such @@ -130,7 +183,7 @@ \QC groups build and run specific settings as kits to make cross-platform development easier. Each kit consists of a set of values that define one - environment, such as a device, tool chain, Qt version, and debugger command + environment, such as a device, toolchain, Qt version, and debugger command to use. \generatelist creator-how-to-manage-kits 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/howto/creator-only/qtcreator-faq.qdoc b/doc/qtcreator/src/howto/creator-only/qtcreator-faq.qdoc index beadc0eb86a..a67a8fb7657 100644 --- a/doc/qtcreator/src/howto/creator-only/qtcreator-faq.qdoc +++ b/doc/qtcreator/src/howto/creator-only/qtcreator-faq.qdoc @@ -18,14 +18,6 @@ \section1 General Questions - - \b {How do I reset all \QC settings?} - - Remove the settings files created by \QC. - - For more information about where the files are located on each supported - platform, see \l {Find settings files}. - \b {\QC comes with \MinGW, should I use this version with Qt?} Use the version that was built against the Qt version. @@ -41,15 +33,6 @@ This is especially relevant for the \macos where \c {/usr/local/bin} might not be in the path when \QC is started. - \b {How do I change the interface language for \QC?} - - \QC has been localized into several languages. If the system - language is one of the supported languages, it is automatically selected. - To change the language, select \preferences > - \uicontrol Environment and select a language in the \uicontrol Language - field. Select \uicontrol {Restart Now} to restart \QC and have the change - take effect. - \b {Has a reported issue been addressed?} You can look up any issue in the @@ -70,8 +53,8 @@ This also enables code completion of QML code and removes error messages. The following example illustrates how to specify the import path for qmake - projects so that it works when switching between build and run kits for - different target platforms: + projects so that it works when switching between build and run \l{Kits}{kits} + for different target platforms: \code TEMPNAME = $${QMAKE_QMAKE} @@ -138,14 +121,10 @@ \b {The Qt API Reference Documentation is missing and context help does not find topics. What can I do?} - \QC comes fully integrated with Qt documentation and examples using - the Qt Help plugin. The integrated Qt Reference Documentation is available - for Qt 4.4 and later. \QC and other Qt deliverables have - documentation as .qch files. All the documentation is accessible in the - \uicontrol Help mode. + Install a Qt version and Qt documentation with \QOI. - To view the documentation that is available and to add documentation, - select \preferences > \uicontrol Help > + To view the installed documentation (.qch files) and to add documentation, + go to \preferences > \uicontrol Help > \uicontrol Documentation. For more information, see \l{Add external documentation}. @@ -164,12 +143,12 @@ You must use Python version 2.6 or 2.7. - For more information on setting up debugger, see \l{Setting Up Debugger}. + For more information, see \l{Supported Debuggers}. \b {How do I generate a core file in \QC?} To trigger the GDB command that generates a core file while debugging, - select \uicontrol View > \uicontrol Views > \l {Debugger Log}. + go to \uicontrol View > \uicontrol Views > \l {Debugger Log}. In the \uicontrol Command field, type \c gcore and press \key Enter. The core file is created in the current working directory. You can specify another location for the file, including a relative or absolute path, as an diff --git a/doc/qtcreator/src/howto/creator-only/qtcreator-how-to-change-ui-language.qdoc b/doc/qtcreator/src/howto/creator-only/qtcreator-how-to-change-ui-language.qdoc new file mode 100644 index 00000000000..913b1b6fa99 --- /dev/null +++ b/doc/qtcreator/src/howto/creator-only/qtcreator-how-to-change-ui-language.qdoc @@ -0,0 +1,38 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-change-ui-language.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-ui + + \title Change the UI language + + \QC has been localized into several languages. If the system + language is one of the supported languages, it is automatically selected. + + To change the language: + + \list 1 + \li Go to \preferences > \uicontrol Environment. + \li In \uicontrol Language, select a language. + \li Select \uicontrol OK. + \li Select \uicontrol {Restart Now} to restart \QC and have the change + take effect. + \endlist + + \section1 Set the language from the command line + + To set the UI language when you start \QC from the command line, enter: + + \badcode + qtcreator -language + \endcode + + Use a lowercase, two-letter + \l {https://www.iso.org/iso-639-language-codes.html} + {ISO 639 language code}, such as \e de, \e en, or \e fr. + + \sa {Run Qt Creator from the command line} +*/ diff --git a/doc/qtcreator/src/incredibuild/creator-projects-incredibuild-building.qdoc b/doc/qtcreator/src/incredibuild/creator-projects-incredibuild-building.qdoc index f872adc77e6..f3828018149 100644 --- a/doc/qtcreator/src/incredibuild/creator-projects-incredibuild-building.qdoc +++ b/doc/qtcreator/src/incredibuild/creator-projects-incredibuild-building.qdoc @@ -10,7 +10,7 @@ \brief Build and clean steps for Incredibuild. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. diff --git a/doc/qtcreator/src/ios/creator-ios-dev.qdoc b/doc/qtcreator/src/ios/creator-ios-dev.qdoc index d1e15e58b55..b6c8d53cde9 100644 --- a/doc/qtcreator/src/ios/creator-ios-dev.qdoc +++ b/doc/qtcreator/src/ios/creator-ios-dev.qdoc @@ -2,23 +2,22 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-adding-docker-devices.html \page creator-developing-ios.html - \nextpage creator-developing-mcu.html + \previouspage creator-reference.html - \title Connecting iOS Devices + \ingroup creator-reference-devices - You can connect iOS devices to your local machine with a USB cable to - run applications built for them from \QC. + \title Developing for iOS - To be able to use \QC on \macos, you must install Xcode, and therefore, - you already have the tool chain for building applications for iOS. \QC - automatically detects the tool chain and creates the necessary - \l{glossary-buildandrun-kit}{kits} to build applications for and run them on + \brief Connect iOS devices to your local machine with a USB cable to + run applications on them. + + After you install Xcode, \QC automatically detects the toolchain and creates + the necessary \l{Kits}{kits} to build applications for and run them on configured iOS devices. - You only need Qt libraries that are built for iOS. You can install them as - part of Qt 5.2, or later. + You only need Qt libraries that are built for iOS. You can install Qt for iOS + with \QOI. \section1 iOS 17 Devices @@ -29,95 +28,6 @@ physical devices with iOS 17 or later because of limitations of the Apple tool for accessing these devices. - \section1 Configuring Devices - - The connections between \QC and an iOS device are protected by using a - certificate that you receive from Apple when you - \l{https://developer.apple.com/programs/enroll/} - {enroll in the Apple Developer Program}. The certificate is copied to - the device when you configure the device. - - The first time you connect the device to your local machine, you are asked to enable - developer mode on the device. The next time you connect the device, \QC - detects it automatically. To disable automatic connections to a device that - you do not use for development, select \uicontrol Preferences > - \uicontrol iOS, and deselect the \uicontrol {Ask about devices not in - developer mode} check box. - - \note The process of configuring devices and the UI varies slightly - depending on the Xcode version that you use. We recommend that you use the - latest available Xcode version. - - To configure connections between \QC and an iOS device: - - \list 1 - - \li Make sure that you have Xcode and Qt for iOS installed. - - \li Connect the device to your local machine with a USB cable. - - \li Start Xcode to configure the device. - - For example, in Xcode version 15, select \uicontrol Window > - \uicontrol Devices and Simulators > \uicontrol Devices > - \uicontrol + to add the connected device. - - \li To specify build settings: - - \list 1 - - \li Open a project for an application you want to develop for the - device. - - \li Select \uicontrol Projects > \uicontrol {Build & Run} to select - the kit for building applications for and running them on iOS. - - \image qtcreator-ios-add-kit.png "Build & Run Settings" - - \li In \uicontrol {iOS Settings}, select the development team to use - for signing and provisioning applications. You must configure - development teams and provisioning profiles in Xcode using an - Apple developer account. - - \image qtcreator-build-settings-ios.png "iOS build settings" - - \li Select the \uicontrol {Automatically manage signing} check box - to automatically select the provisioning profile and signing - certificate on your local machine that matches the entitlements - and the bundle identifier of the iOS device. - - \endlist - - \li Select \uicontrol Run to specify run settings. - - Usually, you can use the default settings. - - When you run the project, \QC uses Xcode to deploy the application to the - device. - - Your signing certificate is used to sign application packages for deployment - to the device. - - \endlist - - \note If you cannot deploy applications because a provisioning profile is - missing, check that provisioning profiles are listed in Xcode by selecting - \uicontrol Xcode > \uicontrol Preferences > \uicontrol Accounts. For more - information about how to acquire and install a provisioning profile, see - Apple documentation. - - \section1 Viewing Device Connection Status - - When you connect an iOS device to your local machine with USB, \QC - automatically detects the device if you have configured it by using Xcode. - To view information about the connected device, select \uicontrol Preferences > - \uicontrol Devices. - - \image qtcreator-ios-device-configurations.png "Devices dialog" - - If the current device state is \uicontrol Connected, (the traffic light icon is - orange), you need to configure the device using Xcode. - \section1 Specifying Supported iOS Versions You can build applications for the latest iOS version and deploy them to @@ -138,9 +48,116 @@ actual build system code reflects the minimum iOS version that is actually required. - For more information, see \l{Expressing Supported iOS Versions}. + \sa {iOS}{How To: Develop for iOS}, {Expressing Supported iOS Versions} +*/ - \section1 Testing on Simulator +/*! + \page creator-how-to-connect-ios-devices.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-ios + + \title Connect iOS devices + + The connections between \QC and an iOS device are protected by using a + certificate that you receive from Apple when you + \l{https://developer.apple.com/programs/enroll/} + {enroll in the Apple Developer Program}. The certificate is copied to + the device when you configure the device. + + The first time you connect the device to your local machine, you are asked to enable + developer mode on the device. The next time you connect the device, \QC + detects it automatically. To disable automatic connections to a device that + you do not use for development, go to preferences > \uicontrol iOS + and clear \uicontrol {Ask about devices not in developer mode}. + + \note The process of configuring devices and the UI varies slightly + depending on the Xcode version that you use. We recommend that you use the + latest available Xcode version. + + \section1 Create a connection to an iOS device + + To configure connections between \QC and an iOS device: + + \list 1 + + \li Check that you installed Xcode and \l{Qt for iOS}. + + \li Connect the device to your local machine with a USB cable. + + \li Start Xcode to configure the device. + + For example, in Xcode version 15, go to \uicontrol Window > + \uicontrol Devices and Simulators > \uicontrol Devices, and select + \uicontrol + to add the connected device. + + \li To specify build settings: + + \list 1 + + \li Open a project for an application you want to develop for the + device. + + \li Go to \uicontrol Projects > \uicontrol {Build & Run} to select + the kit for building applications for and running them on iOS. + + \image qtcreator-ios-add-kit.png "Build & Run Settings" + + \li In \uicontrol {iOS Settings}, select the development team to use + for signing and provisioning applications. You must configure + development teams and provisioning profiles in Xcode using an + Apple developer account. + + \image qtcreator-build-settings-ios.png "iOS build settings" + + \li Select \uicontrol {Automatically manage signing} + to automatically select the provisioning profile and signing + certificate on your local machine that matches the entitlements + and the bundle identifier of the iOS device. + + \endlist + + \li Select \uicontrol Run to specify run settings. + + Usually, you can use the default settings. + + When you run the project, \QC uses Xcode to deploy the application to the + device. + + Your signing certificate is used to sign application packages for deployment + to the device. + + \endlist + + \note If you cannot deploy applications because a provisioning profile is + missing, check that provisioning profiles are listed in Xcode by going to + \uicontrol Xcode > \uicontrol Preferences > \uicontrol Accounts. For more + information about how to acquire and install a provisioning profile, see + Apple documentation. + + \section1 View device connection status + + When you connect an iOS device to your local machine with USB, \QC + automatically detects the device if you have configured it by using Xcode. + To view information about the connected device, go to \uicontrol Preferences > + \uicontrol Devices. + + \image qtcreator-ios-device-configurations.png {Devices dialog} + + If the current device state is \uicontrol Connected, (the traffic light icon is + orange), you need to configure the device using Xcode. + + \sa {Activate kits for a project}, {iOS}{How To: Develop for iOS}, + {Developing for iOS} +*/ + +/*! + \page creator-how-to-test-on-ios-simulator.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-ios + + \title Test on iOS Simulator If you do not have an iOS device or you do not want to create an account, you can test applications on @@ -149,48 +166,19 @@ simulates a predefined set of hardware devices and software versions. You can change the simulated hardware and software version in the run - settings for the project. Select \uicontrol Projects > \uicontrol Run, and then select + settings for the project. Go to \uicontrol Projects > \uicontrol Run, and then select the device to simulate in the \uicontrol {Device type} field. \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. + The simulator starts automatically when you run the application. + To start the simulator manually, either start the Simulator application + directly with Spotlight, or go to \uicontrol Xcode > \uicontrol {Open Developer Tool} + in Xcode. - 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. + 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}. + \sa {iOS}{How To: Develop for iOS}, {Developing for iOS} */ diff --git a/doc/qtcreator/src/linux-mobile/b2qtdev.qdoc b/doc/qtcreator/src/linux-mobile/b2qtdev.qdoc index b8c2c6f9a47..04dceb49160 100644 --- a/doc/qtcreator/src/linux-mobile/b2qtdev.qdoc +++ b/doc/qtcreator/src/linux-mobile/b2qtdev.qdoc @@ -1,143 +1,79 @@ -// 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 /*! \page creator-developing-b2qt.html - \previouspage creator-developing-baremetal.html - \nextpage creator-adding-docker-devices.html + \previouspage creator-reference.html - \title Connecting Boot2Qt Devices + \ingroup creator-reference-devices - You can connect \l{Boot2Qt} devices to the development PC to run, debug, - and analyze applications built for them from \QC. For this, you need the - appropriate \l{http://qt.io/licensing/}{Qt license}. + \title Developing for \B2Q Devices - If you have a tool chain for building applications for Boot2Qt devices - installed on the development PC, you can add it to \QC. You can then - select a \l{glossary-buildandrun-kit}{kit} with the \uicontrol Boot2Qt - device type to build applications for and run them on the devices. + \brief Connect \B2Q devices to the computer to run, + debug, and analyze applications built for them from \QC. - To be able to run and debug applications on Boot2Qt devices, - you must add devices and select them in the \QC - \l{kits-tab}{kit}. + The \l{\B2Q: Documentation}{\B2Q} stack runs on a variety of hardware. + \l{http://qt.io/licensing/}{Qt license} holders can customize the contents of + the stack and take it into production hardware. - \section1 Enabling the Boot2Qt Plugin + \note Enable the \B2Q plugin to use it. - To enable the Boot2Qt plugin: - - \list 1 - \li Select \uicontrol Help > \uicontrol {About Plugins} > - \uicontrol {Device Support} > \uicontrol Boot2Qt to - enable the plugin. - \li Select \uicontrol {Restart Now} to restart \QC and load the plugin. - \endlist - - \section1 Adding Boot2Qt Devices - - If \QC does not automatically detect a device you connected with USB, select - \preferences > \uicontrol Devices > - \uicontrol Devices > \uicontrol Add > \uicontrol {Boot2Qt Device} to create - either a network connection or a USB connection to it. + If you have a toolchain for building applications for \B2Q devices + installed on the computer, add it to a \l{Kits}{kit} with the + \uicontrol \B2Q device type to build applications for and run them on + the devices. \image qtcreator-boot2qt-device-configurations.webp {Devices tab in Preferences} - To add a device without using a wizard, select \uicontrol {Boot2Qt Device} in - the pull-down menu of the \uicontrol Add button. + \include linuxdev.qdoc openssh - \note On Ubuntu Linux, the development user account must have access to the - plugged-in devices. To grant them access to the device via USB, create a new - \c udev rule, as described in - \l{Boot2Qt: Setting Up USB Access to Embedded Devices}. + \sa {\B2Q}{How To: Develop for \B2Q}, + {Manage Kits}{How To: Manage Kits}, {Run in Qt Application Manager}, + {\B2Q Deploy Configuration}, {\B2Q Run Settings}, + {\B2Q: Documentation} +*/ - You can edit the settings later in \preferences > - \uicontrol Devices > \uicontrol Devices. +/*! + \page creator-how-to-connect-b2qt.html + \previouspage creator-how-tos.html - To reboot the selected device, select \uicontrol {Reboot Device}. + \ingroup creator-how-to-b2qt - To restore the default application to the device, select - \uicontrol {Restore Default App}. + \title Connect \B2Q devices - \section2 Protecting Connections + Create connections between \l{\B2Q: Documentation}{\B2Q} devices and + \QC to run, debug, and analyze applications on them. - You can protect the connections between \QC and a device by using an - \l{https://www.openssh.com/}{OpenSSH} connection. OpenSSH is a - connectivity tool for remote login using the SSH protocol. The OpenSSH - suite is not delivered with \QC, so you must download it and install it - on the development PC. Then, you must configure the paths to the tools in - \QC. For more information, see \l {Configuring SSH Connections}. + \note Enable the \B2Q plugin to use it. - You need either a password or an SSH public and private key pair for - authentication. If you do not have an SSH key, you can use the \c ssh-keygen - tool to create it in \QC. For more information, see \l {Generating SSH Keys}. - - \QC does not store passwords. If you use password authentication, you may - need to enter the password upon every connection to the device, or if - caching is enabled, at every \QC restart. If you frequently run into the - timeout, consider using key-based authentication. On \macos and Linux, you - can also select \preferences > \uicontrol Devices > \uicontrol SSH - and increase the time (in minutes) to use the same SSH connection in the - \uicontrol {Connection sharing timeout} field. Windows does not support - shared connections. - - \image qtcreator-ssh-options.png {SSH preferences} - - \section1 Flashing Boot2Qt Devices - - To flash the Boot2Qt image to an SD card with Flashing Wizard, select - \uicontrol Tools > \uicontrol {Flash Boot to Qt Device} and follow the - instructions of the wizard. - - \image qtcreator-boot2qt-flashing-wizard.png {Boot2Qt Flashing Wizard} - - \section1 Configuring Connections - - To configure connections between \QC and a Boot2Qt device and to - specify build and run settings for the device: + To configure connections between \QC and a \B2Q device: \list 1 \li Check that you can reach the IP address of the device, or use USB to connect it. - \li Select \preferences > \uicontrol Kits > \uicontrol {Qt Versions} > - \uicontrol Add to add the Qt version for Boot2Qt. - \li Select \preferences > \uicontrol Kits > - \uicontrol Compilers > \uicontrol Add to add the compiler for - building the applications. - \li Select \uicontrol Tools > \uicontrol {Flash Boot to Qt Device} - to flash the Boot2Qt image to an SD card with Flashing Wizard. - \li To deploy applications and run them remotely on devices, specify - parameters for connecting to the devices over the network (\QC - automatically detects devices connected with USB): - \list 1 - \li Select \preferences > \uicontrol Devices > - \uicontrol Devices > \uicontrol Add > \uicontrol Boot2Qt. - \image qtcreator-devices-boot2qt.png {Boot2Qt Network Device Setup wizard} - \li In the \uicontrol {Device name} field, enter a name for - the connection. - \li In the \uicontrol {Device address} field, enter the host - name or IP address of the device. This value will be - available in the \c %{Device:HostAddress} variable. - \li Click \uicontrol {Finish} to test the connection and - add the device. + \li Go to \preferences > \uicontrol Kits > \uicontrol {Qt Versions}. + \li Select \uicontrol Add to add the Qt version for \B2Q. + \li Go to \preferences > \uicontrol Kits > \uicontrol Compilers. + \li Select \uicontrol Add to add the compiler for building the + applications. + \li Go to \uicontrol Tools > \uicontrol {Flash \B2Q} + to flash the \B2Q image to an SD card with \B2Q Flashing Wizard. + \image qtcreator-boot2qt-flashing-wizard.png {\B2Q Flashing Wizard} + \li Follow the instructions of the wizard to flash the image to the SD + card. + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \li Select \uicontrol Add to add a \B2Q device. - You can edit the connection parameters in the - \uicontrol Devices tab. The wizard does not show - parameters that have sensible default values. One of - these is the SSH port number, which is available in - the variable \c %{Device:SshPort}. - - To add a device without using the wizard, select - \uicontrol {Boot2Qt Device} in the pull-down menu of the - \uicontrol Add button. - \endlist - \li Select \preferences > \uicontrol Kits > - \uicontrol Add to add a kit for building applications for the - device. Select the Qt version, compiler, and device that you - added above, and choose \uicontrol Boot2Qt as the device type. + \QC automatically detects devices connected with USB. + \li Go to \preferences > \uicontrol Kits. + \li Select \uicontrol Add to add a kit for building for the device. + \li Select the Qt version, compiler, and device that you added above. + \li In \uicontrol {Run device type}, select \uicontrol {Boot2Qt Device}. \li To specify build settings: \list 1 \li Open a project for an application you want to develop for the device. - \li Select \uicontrol Projects > \uicontrol {Build & Run} to enable + \li Go to \uicontrol Projects > \uicontrol {Build & Run} to activate the kit that you specified above. \endlist \li Select \uicontrol Run to specify run settings. Usually, you can use @@ -145,9 +81,66 @@ When you run the project, \QC deploys the application as specified by the deploy steps. By default, \QC copies the - application files to the device. For more information, see - \l{Boot2Qt Run Settings}. + application files to the device. \endlist - \sa {Boot2Qt: Setting Up USB Access to Embedded Devices} + \sa {Configure SSH connections}, {Generate SSH keys}, + {Enable and disable plugins}, {\B2Q}{How To: Develop for \B2Q}, + {Manage Kits}{How To: Manage Kits}, {\B2Q Deploy Configuration}, + {\B2Q Run Settings}, {Developing for \B2Q Devices} +*/ + +/*! + \page creator-how-to-add-b2qt.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-b2qt + + \title Add \B2Q devices + + \note Enable the \B2Q plugin to use it. + + If \QC does not automatically detect a \B2Q device you connect with USB, + check that you followed the instructions in the \l{\B2Q: Documentation} + {Quick Start Guide} for the device. + + If that does not help, but you can reach the IP address of the device, + create a network connection to it: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \image qtcreator-boot2qt-device-configurations.webp {Devices tab in Preferences} + \li Select \uicontrol Add > \uicontrol {Boot2Qt Device} to create + a network connection to the device. + \image qtcreator-devices-boot2qt.png {Boot to Qt Network Device Setup wizard} + \li In \uicontrol {Device name}, enter a name for the connection. + \li In \uicontrol {Device address}, enter the host + name or IP address of the device. This value becomes the value of the + \c %{Device:HostAddress} variable. + \li Select \uicontrol {Finish} to test the connection and add the device. + \endlist + + The wizard does not show parameters that have sensible default values, such + as the SSH port number. It is available in the variable \c %{Device:SshPort}. + + To add a device without using a wizard, select \uicontrol {Boot2Qt Device} in + the pull-down menu of the \uicontrol Add button. + + \note On Ubuntu Linux, the development user account must have access to the + plugged-in devices. To grant them access to the device via USB, create a new + \c udev rule, as described in + \l{\B2Q: Setting Up USB Access to Embedded Devices}. + + \section1 Reboot devices + + To reboot the selected device, select \uicontrol {Reboot Device}. + + \section1 Restore default applications + + To restore the default application to the device, select + \uicontrol {Restore Default App}. + + \sa {Enable and disable plugins}, {\B2Q}{How To: Develop for \B2Q}, + {Developing for \B2Q Devices}, + {\B2Q: Setting Up USB Access to Embedded Devices} */ diff --git a/doc/qtcreator/src/linux-mobile/creator-deployment-b2qt.qdoc b/doc/qtcreator/src/linux-mobile/creator-deployment-b2qt.qdoc index 73301bb173b..298865d794c 100644 --- a/doc/qtcreator/src/linux-mobile/creator-deployment-b2qt.qdoc +++ b/doc/qtcreator/src/linux-mobile/creator-deployment-b2qt.qdoc @@ -1,25 +1,32 @@ -// 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 /*! \page creator-deployment-b2qt.html - \previouspage creator-deploying-android.html - \nextpage creator-deployment-qnx.html + \previouspage creator-reference.html - \title Deploying to Boot2Qt + \ingroup creator-reference-deploy-configurations - You can specify settings for deploying applications to \l{Boot2Qt} devices - in the project configuration file and in \uicontrol Projects > - \uicontrol {Run Settings} > \uicontrol Deployment. + \title \B2Q Deploy Configuration - \image qtcreator-boot2qt-deployment-steps.png "Boot2Qt deployment steps" + \brief Copy application files to \B2Q devices. + + Specify settings for deploying applications to \l{\B2Q: Documentation} + {\B2Q} devices in the project configuration file and in \uicontrol Projects + > \uicontrol {Run Settings} > \uicontrol Deployment. + + \image qtcreator-boot2qt-deployment-steps.png {Boot to Qt deployment steps} The deployment process is described in more detail in - \l{Deploying to Remote Linux}. + \l{Remote Linux Deploy Configuration}. \section1 Launching Applications on Boot - In addition, to have your application launch on boot, select + To have your application launch on boot, select \uicontrol {Add Deploy Step} > \uicontrol {Change default application} > \uicontrol {Set this application to start by default}. + + \sa {Build and Run}{How To: Build and Run}, + {\B2Q}{How To: Develop for \B2Q}, {\B2Q Run Settings}, + {Developing for \B2Q Devices} */ diff --git a/doc/qtcreator/src/linux-mobile/creator-deployment-embedded-linux.qdoc b/doc/qtcreator/src/linux-mobile/creator-deployment-embedded-linux.qdoc index 38c6823fa30..87c54e26faa 100644 --- a/doc/qtcreator/src/linux-mobile/creator-deployment-embedded-linux.qdoc +++ b/doc/qtcreator/src/linux-mobile/creator-deployment-embedded-linux.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 // ********************************************************************** @@ -9,14 +9,18 @@ /*! \page creator-deployment-embedded-linux.html - \previouspage creator-deployment-qnx.html - \nextpage creator-connecting-mobile.html + \previouspage creator-reference.html - \title Deploying to Remote Linux + \ingroup creator-reference-deploy-configurations - You can specify settings for deploying applications to generic remote - Linux devices in the project configuration file and in the - \uicontrol Projects mode, in \uicontrol {Run Settings}. + \title Remote Linux Deploy Configuration + + \brief Copy application files to generic remote Linux devices or create a + tarball. + + Specify settings for deploying applications to generic remote + Linux devices in the project configuration file and in \uicontrol Projects > + \uicontrol {Run Settings} > \uicontrol Deployment. \image qtcreator-embedded-linux-deployment-details.png "Deploy to remote Linux devices" @@ -107,4 +111,7 @@ The \uicontrol {Deploy tarball via SFTP upload} step specifies that \QC uploads the tarball to the device and extracts it. + + \sa {Build and Run}{How To: Build and Run}, + {Remote Linux}{How To: Develop for remote Linux}, {Remote Linux Run Settings} */ diff --git a/doc/qtcreator/src/linux-mobile/creator-embedded-platforms.qdoc b/doc/qtcreator/src/linux-mobile/creator-embedded-platforms.qdoc deleted file mode 100644 index a6ca31f33fe..00000000000 --- a/doc/qtcreator/src/linux-mobile/creator-embedded-platforms.qdoc +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (C) 2022 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! - \page creator-embedded-platforms.html - \previouspage creator-reference.html - - \ingroup creator-reference-platforms - - \title Embedded Platforms - - \brief Embedded platforms that you can develop applications for. - - You can develop applications for the following embedded platforms: - - \list - \li \l {Bare Metal} - \li \l {Boot2Qt} - \li \l {Remote Linux} - \li \l {Microcontroller Units (MCU)} - \li \l QNX - \endlist - - You must install the tool chain for building applications for the targeted - embedded platform on the development PC and use \QMT to - install Qt libraries that are built for the platform. You can then add a - \l{glossary-buildandrun-kit}{kit} with the tool chain and the Qt version - for the device's architecture. When possible, \QMT creates - suitable kits for you. - - You can connect embedded devices to the development PC to run, debug, and - analyze applications built for them from \QC. - - \section1 Bare Metal - - You can run and debug applications on small devices that are not supported - by the remote Linux device plugin by using GDB or a hardware - debugger. - - For more information about developing applications for Bare Metal devices, - see \l{Connecting Bare Metal Devices}. - - \section1 Boot2Qt - - The Boot2Qt stack runs on a variety of hardware. License holders can use - tools to customize the contents of the stack and to take it into - production hardware. - - The following topics have more information about developing applications - for Boot2Qt devices: - - \list - \li \l{Boot2Qt: Documentation} - \li \l{Connecting Boot2Qt Devices} - \li \l{Boot2Qt Run Settings} - \li \l{Deploying to Boot2Qt} - \li \l{Run in Qt Application Manager} - \endlist - - \section1 Remote Linux - - You must have a tool chain for building applications for embedded Linux - devices installed on the development PC. - - The following topics have more information about developing applications - for remote Linux devices: - - \list - \li \l{Adding Docker Devices} - \li \l{Connecting Remote Linux Devices} - \li \l{Deploying to Remote Linux} - \li \l{Remote Linux Run Settings} - \li \l{Run on remote Linux devices} - \li \l{Run in Qt Application Manager} - \endlist - - \section1 Microcontroller Units (MCU) - - You need the GNU Arm Embedded GCC compiler, libraries, and other GNU tools - necessary for bare metal software development on devices based on the Arm - Cortex-M processors. - - The following topics have more information about developing applications - for MCUs: - - \list - \li \l{Connecting MCUs} - \li \l{MCUs}{How To: Develop for MCUs} - \li \l{https://doc.qt.io/QtForMCUs/index.html}{\QMCU} - \endlist - - \section1 QNX - - The QNX Neutrino RTOS has more command-line tools - and services, as described in \l {Qt for QNX}. - - \note In Qt 6, \QC support for QNX is considered experimental. - - The following topics have more information about developing applications - for QNX devices: - - \list - \li \l{Connecting QNX Devices} - \li \l{Deploying to QNX Neutrino} - \li \l{QNX Run Settings} - \li \l{Run on QNX devices} - \li \l{Qt for QNX} - \endlist - - \sa {Develop for Devices}{How To: Develop for Devices}, {Supported Platforms} -*/ diff --git a/doc/qtcreator/src/linux-mobile/creator-projects-how-to-run-generic-linux.qdoc b/doc/qtcreator/src/linux-mobile/creator-projects-how-to-run-generic-linux.qdoc index b78dcd5ca20..aeb17305cf8 100644 --- a/doc/qtcreator/src/linux-mobile/creator-projects-how-to-run-generic-linux.qdoc +++ b/doc/qtcreator/src/linux-mobile/creator-projects-how-to-run-generic-linux.qdoc @@ -5,7 +5,7 @@ \page creator-how-to-run-on-remote-linux.html \previouspage creator-how-tos.html - \ingroup creator-how-to-run + \ingroup creator-how-to-remote-linux \title Run on remote Linux devices @@ -19,7 +19,7 @@ \endlist - \QC uses the compiler from the kit (tool chain) to build the application. + \QC uses the compiler from the kit (toolchain) to build the application. \QC copies the application files to the connected device and runs the application. The application views are @@ -34,6 +34,7 @@ Debugging works transparently if GDB server is installed on the device and it is compatible with the GDB on the host. - \sa {Connecting Remote Linux Devices}, {Run on many platforms}, {Compilers}, - {Embedded Platforms}, {kit-preferences}{Kits} + \sa {Remote Linux}{How To: Develop for remote Linux}, + {Debug remotely with GDB}, {Run on many platforms}, {Compilers}, + {Embedded Platforms}, {Kits} */ diff --git a/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-b2qt.qdoc b/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-b2qt.qdoc index 1391cfcfd48..01eb71f171f 100644 --- a/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-b2qt.qdoc +++ b/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-b2qt.qdoc @@ -1,30 +1,30 @@ -// 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 /*! - \page creator-run-settings-boot2qt.html + \page creator-run-settings-\B2Q.html \previouspage creator-reference.html \ingroup creator-reference-run-configurations - \title Boot2Qt Run Settings + \title \B2Q Run Settings - \brief Settings for running applications on Boot2Qt devices. + \brief Settings for running applications on \B2Q devices. - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. - To run and debug an application on a \l Boot2Qt device (commercial only), you - must create connections from the development host to the device and add the - device configurations to kits. Select \uicontrol {Manage Kits} to add devices - to kits. For more information, see - \l{http://doc.qt.io/Boot2Qt/b2qt-installation-guides.html} - {Boot2Qt: Installation Guide}. + To run and debug an application on a \l{\B2Q: Documentation}{\B2Q} device + (commercial only), create connections from the development host to the device + and add the device configurations to kits. + + Select \uicontrol {Manage Kits} to add devices to kits. The run settings display the path to the executable file on the development host and on the device. - \sa {Activate kits for a project}, {Configure projects for running}, {kits-tab}{Kits}, - {Deploying to Boot2Qt} + \sa {\B2Q}{How To: Develop for \B2Q}, {Manage Kits}{How To: Manage Kits}, + {Configure projects for running}, {Kits}, + {\B2Q Deploy Configuration} */ diff --git a/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-linux.qdoc b/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-linux.qdoc index 4e2a08e1326..37954b8e89a 100644 --- a/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-linux.qdoc +++ b/doc/qtcreator/src/linux-mobile/creator-projects-settings-run-linux.qdoc @@ -11,7 +11,7 @@ \brief Settings for running applications on Linux-based devices. - Specify run settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify run settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. @@ -19,7 +19,7 @@ connections from the development host to the device and add the device configurations to kits. Select \uicontrol {Manage Kits} to add devices to kits. For more information, see - \l {Connecting Remote Linux Devices}. + \l {Remote Linux}{How To: Develop for remote Linux}. When you run the application, \QC copies the files to the connected device. @@ -37,6 +37,6 @@ Select the \uicontrol {Forward to local display} check box to show a remotely running X11 client on a local display. - \sa {Activate kits for a project}, {Configure projects for running}, {kits-tab}{Kits}, - {Connecting Remote Linux Devices} + \sa {Activate kits for a project}, {Configure projects for running}, {Kits}, + {Remote Linux}{How To: Develop for remote Linux} */ diff --git a/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdoc b/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdoc new file mode 100644 index 00000000000..9af4de44ed7 --- /dev/null +++ b/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdoc @@ -0,0 +1,82 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-configure-ssh.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-remote-linux + + \title Configure SSH connections + + To protect the connections between \QC and a device, install the \l{OpenSSH} + suite, which includes the \c ssh, \c sftp, and \c ssh-keygen tools on the + computer. + + SSH connections are established via an OpenSSH client running in master + mode, if possible. By default, multiple sessions are shared over a single SSH + onnection. Establishing a connection once and then re-using it for subsequent + run and deploy procedures reduces connection setup overhead particularly + with embedded devices. Because connection sharing is not supported on + Windows, a new SSH connection is created for each deploy or run procedure. + + To set the paths to the directories where the tools are installed: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol SSH. + \image qtcreator-ssh-options.png "SSH preferences" + \li Clear \uicontrol {Enable connection sharing} to + create a new SSH connection for each deploy and run procedure. This + option is grayed on Windows, where connection sharing is not + supported. + \li In \uicontrol {Connection sharing timeout}, specify the + timeout for reusing the SSH connection in minutes. + \li In \uicontrol {Path to ssh executable}, enter the path + to the directory where the OpenSSH executable is installed. + \li In \uicontrol {Path to sftp executable}, enter the path + to the directory where the SFTP executable is installed. + \li In \uicontrol {Path to ssh-askpass executable}, enter the + path to the directory where the ssh-askpass executable is installed. + Usually, you can use the default path that points to the + implementation of the tool delivered with \QC, qtc-askpass. + \li In \uicontrol {Path to ssh-keygen executable}, enter the + path to the directory where the ssh-keygen executable is installed. + \endlist + + \sa {Remote Linux}{How To: Develop for remote Linux}, + {Developing for Remote Linux Devices} +*/ + +/*! + \page creator-how-to-generate-ssh-keys.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-remote-linux + + \title Generate SSH keys + + To protect the connections between \QC and a device, use \l{OpenSSH}. + + If you do not have an SSH public and private key pair, you can generate it + in \QC. The connection wizard can create the key pair for you, or you can + create it separately. + + You can specify key length and the key algorithm, RSA or ECDSA. + If you only use the keys to protect connections to the emulator or + device, you can use the default values. + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices + \li Select \uicontrol {Create New}. + \image qtcreator-ssh-key-configuration.png {SSH Key Configuration dialog} + \li In \uicontrol {Private key file}, select the location to save + the private key. + \uicontrol {Public key file} displays the location to save the + corresponding public key. + \li Select \uicontrol {Generate And Save Key Pair} to generate and save the + keys at the specified locations. + \endlist + + \sa {Remote Linux}{How To: Develop for remote Linux}, + {Developing for remote Linux devices} +*/ diff --git a/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdocinc b/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdocinc deleted file mode 100644 index f3582f23736..00000000000 --- a/doc/qtcreator/src/linux-mobile/linuxdev-keys.qdocinc +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2019 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! - -//! [configuring ssh] - \section2 Configuring SSH Connections - - SSH connections are established via an OpenSSH client running in master - mode, if possible. Connection sharing is enabled by default to allow - sharing multiple sessions over a single SSH connection. This way, a - connection is only established once and then re-used by subsequent run - and deploy procedures, saving connection setup overhead particularly - with embedded devices. Because connection sharing is not supported on - Windows, a new SSH connection is created for each deploy or run procedure. - - To create SSH connections, you must install the \l{https://www.openssh.com/} - {OpenSSH} suite, which includes the ssh, sftp, and ssh-keygen tools on the - development PC. - - To tell \QC where it can find the tools, specify the paths to the - directories where the tools are installed in \preferences > - \uicontrol Devices > \uicontrol SSH: - - \image qtcreator-ssh-options.png "SSH preferences" - - \list - \li Deselect the \uicontrol {Enable connection sharing} check box to - create a new SSH connection for each deploy and run procedure. This - option is grayed on Windows, where connection sharing is not - supported. - \li In the \uicontrol {Connection sharing timeout} field, specify the - timeout for reusing the SSH connection in minutes. - \li In the \uicontrol {Path to ssh executable} field, enter the path - to the directory where the OpenSSH executable is installed. - \li In the \uicontrol {Path to sftp executable} field, enter the path - to the directory where the SFTP executable is installed. - \li In the \uicontrol {Path to ssh-askpass executable} field, enter the - path to the directory where the ssh-askpass executable is installed. - Usually, you can use the default path that points to the - implementation of the tool delivered with \QC, qtc-askpass. - \li In the \uicontrol {Path to ssh-keygen executable} field, enter the - path to the directory where the ssh-keygen executable is installed. - \endlist - -//! [configuring ssh] - - -//! [generating ssh keys] - - \section2 Generating SSH Keys - - If you do not have an SSH public and private key pair, you can generate it - in \QC. The connection wizard can create the key pair for you, or you can - create it separately. - - You can specify key length and the key algorithm, RSA or ECDSA. - If you only use the keys to protect connections to the emulator or - device, you can use the default values. - - \list 1 - - \li Select \preferences > \uicontrol Devices - > \uicontrol Devices > \uicontrol {Create New}. - - \image qtcreator-ssh-key-configuration.png "SSH Key Configuration dialog" - - \li In the \uicontrol {Private key file} field, select the location to save - the private key. - - The \uicontrol {Public key file} field displays the location to save the - corresponding public key. - - \li Select \uicontrol {Generate And Save Key Pair} to generate and save the - keys at the specified locations. - - \endlist - -//! [generating ssh keys] -*/ diff --git a/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdoc b/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdoc new file mode 100644 index 00000000000..db73410dcaf --- /dev/null +++ b/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdoc @@ -0,0 +1,26 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-manage-device-processes.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-remote-linux + + \title Manage device processes + + To view and end processes running on embedded platforms: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \li Select an embedded device. + \image qtcreator-preferences-devices-remote-linux.webp {Remote Linux Device in Devices} + \li Select \uicontrol {Show Running Processes}. + \li Filter the processes by name or ID. + \li To update the process list, select \uicontrol {Update List}. + \li To end a process, select it in the list, and then select + \uicontrol {Kill Process}. + \endlist + + \sa {Develop for Devices}{How To: Develop for Devices}, {Devices} +*/ diff --git a/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdocinc b/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdocinc deleted file mode 100644 index 1c9c2d0a4ab..00000000000 --- a/doc/qtcreator/src/linux-mobile/linuxdev-processes.qdocinc +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! -//! [managing device processes] - - \section2 Managing Device Processes - - You can view processes running on devices and kill them. Select - \preferences > \uicontrol Devices > - \uicontrol Devices > \uicontrol {Show Running Processes}. - - You can filter the processes by name or ID in the - \uicontrol {List of Processes} dialog. - - To update the process list, select \uicontrol {Update List}. - - To kill a process, select it in the list, and then select \uicontrol {Kill - Process}. - -//! [managing device processes] -*/ diff --git a/doc/qtcreator/src/linux-mobile/linuxdev.qdoc b/doc/qtcreator/src/linux-mobile/linuxdev.qdoc index 401fdbd8c1e..6691ca4b2c4 100644 --- a/doc/qtcreator/src/linux-mobile/linuxdev.qdoc +++ b/doc/qtcreator/src/linux-mobile/linuxdev.qdoc @@ -1,122 +1,99 @@ -// 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 /*! \page creator-developing-generic-linux.html - \previouspage creator-developing-qnx.html - \nextpage creator-setup-webassembly.html + \previouspage creator-reference.html - \title Connecting Remote Linux Devices + \ingroup creator-reference-devices - You can connect generic Linux devices to the development PC to run, + \title Developing for Remote Linux Devices + + \brief Connect generic Linux devices to the computer to run, debug, and analyze applications built for them from \QC. - If you have a tool chain for building applications for embedded Linux - devices installed on the development PC, you can add - it to \QC. You can then select a \l{glossary-buildandrun-kit}{kit} + If you have a toolchain for building applications for embedded Linux + devices installed on the computer, add it to a \l{Kits}{kit} with the device type \uicontrol {Remote Linux Device} to build applications for and run them on the devices. - To be able to run and debug applications on remote Linux devices, - you must add devices and select them in the \QC \l{glossary-buildandrun-kit} - {kit}. + Use a wizard to connect remote Linux devices to the computer. You can edit + the settings later in \preferences > \uicontrol Devices > \uicontrol Devices. - You use a wizard to create the connections. You can edit the settings later - in \preferences > \uicontrol Devices > - \uicontrol Devices. + \image qtcreator-preferences-devices-remote-linux.webp {Remote Linux Device in Devices} - \image qtcreator-preferences-devices-remote-linux.webp "Remote Linux Device in the Devices tab" + //! [openssh] + \section1 Protecting Device Connections - You can protect the connections between \QC and a device by using an - \l{https://www.openssh.com/}{OpenSSH} connection. OpenSSH is a - connectivity tool for remote login using the SSH protocol. The OpenSSH - suite is not delivered with \QC, so you must download it and install it - on the development PC. Then, you must configure the paths to the tools in - \QC. For more information, see \l {Configuring SSH Connections}. + To protect the connections between \QC and a device, use \l{OpenSSH} for + remote login over the SSH protocol. The OpenSSH suite is not delivered with + \QC, so download it and install it on the computer. Then, configure the paths + to the tools in \QC. You need either a password or an SSH public and private key pair for - authentication. If you do not have an SSH key, you can use the ssh-keygen - tool to create it in \QC. For more information, see \l {Generating SSH Keys}. + authentication. If you do not have an SSH key, use the \c ssh-keygen + tool to create it in \QC. \note \QC does not store passwords, so if you use password authentication, you may need to enter the password on every connection to the device, or, if caching is enabled, at every \QC restart. - To configure connections between \QC and a remote Linux device and to - specify build and run settings for the device: + If you frequently run into the timeout, consider using key-based + authentication. Create an SSH key in \QC with the \c ssh-keygen tool. + + On \macos and Linux, go to \preferences > \uicontrol Devices > \uicontrol SSH + and increase the time (in minutes) for sharing an SSH connection in the + \uicontrol {Connection sharing timeout} field. Windows does not support + shared connections. + + \image qtcreator-ssh-options.png {SSH preferences} + //! [openssh] + + \sa {Add Docker devices}, {Remote Linux}{How To: Develop for remote Linux}, + {Run in Qt Application Manager}, {Remote Linux Deploy Configuration}, + {Remote Linux Run Settings} +*/ + +/*! + \page creator-how-to-connect-remote-linux.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-remote-linux + + \title Connect remote Linux devices + + Create connections between generic Linux devices and \QC to run, debug, and + analyze applications on them. + + To configure connections between \QC and a remote Linux device: \list 1 \li Make sure that your device can be reached via an IP address. - \li Select \preferences > \uicontrol Kits > - \uicontrol {Qt Versions} > \uicontrol Add to add the Qt version - for embedded Linux. + \li Go to \preferences > \uicontrol Kits > \uicontrol {Qt Versions}. - \li Select \preferences > \uicontrol Kits > - \uicontrol Compilers > \uicontrol Add to add the compiler for - building the applications. + \li Select \uicontrol Add to add the Qt version for embedded Linux. - \li To deploy applications and run them remotely on devices, specify - parameters for accessing the devices: + \li Go to \preferences > \uicontrol Kits > \uicontrol Compilers. - \list a + \li Select \uicontrol Add to add the compiler for building the + applications. - \li Select \preferences > - \uicontrol Devices > \uicontrol Devices > \uicontrol Add > - \uicontrol {Remote Linux Device} - > \uicontrol {Start Wizard}. + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. - \image qtcreator-preferences-devices-remote-linux-connection.webp "Connection Data wizard" + \li Select \uicontrol Add to add a remote Linux device. - \li In \uicontrol {The name to identify this configuration}, - enter a name for the connection. + \li Go to \preferences > \uicontrol Kits. - \li In \uicontrol {The device's host name or IP address}, - enter the host name or IP address of the device. - This value will be available in the variable \c %{Device:HostAddress}. + \li Select \uicontrol Add to add a kit for building for the device. - \li In \uicontrol {The device's SSH port number}, enter the port - number to use for SSH connections. This value will be - available in the variable \c %{Device:SshPort}. - \li In \uicontrol {The username to log into the device}, - enter the username to log into the device and run the - application as. - This value will be available in the variable \c %{Device:UserName}. + \li Select the Qt version, compiler, and device that you added above. - \li Select \uicontrol {Next} to open the - \uicontrol {Key Deployment} dialog. + \li In \uicontrol {Run device type}, select + \uicontrol {Remote Linux Device}. - \image qtcreator-preferences-devices-remote-linux-key-deployment.webp "Key Deployment dialog" - - \li In \uicontrol {Private key file}, select a private key file - to use for authentication. This value will be available in - the variable \c %{Device:PrivateKeyFile}. - - \li If you do not have a public-private key pair, select - \uicontrol {Create New Key Pair}. For more information, - see \l{Generating SSH Keys}. - - \li Select \uicontrol {Deploy Public Key} to copy the public - key to the device. - - \li Select \uicontrol {Next} to create the connection. - - \endlist - - All of these parameters can be edited later, as well as additional ones that the - wizard does not show because there are sensible default values. - - To add a device without using the wizard, select - \uicontrol {Add Remote Linux Device} in the pull-down - menu of the \uicontrol Add button. - - \li Select \preferences > \uicontrol Kits > - \uicontrol Add to add a kit for building for the device. Select the - Qt version, compiler, and device that you added above, and select - \uicontrol {Remote Linux Device} in \uicontrol {Run device type}. - - To build on the remote device, select \uicontrol {Remote Linux Device} + \li To build on the remote device, select \uicontrol {Remote Linux Device} also in \uicontrol {Build device}. \li To specify build settings: @@ -134,13 +111,33 @@ \li Select \uicontrol Run to specify run settings. Usually, you can use the default settings. - When you run the project, \QC deploys the application as specified by the - deploy steps. By default, \QC copies the application files to the device. - For more information, see \l{Deploying to Remote Linux}. + When you run the project, \QC deploys the application as specified by + the deploy steps. \endlist - \include linux-mobile/linuxdev-keys.qdocinc configuring ssh - \include linux-mobile/linuxdev-keys.qdocinc generating ssh keys - \include linux-mobile/linuxdev-processes.qdocinc managing device processes + \sa {Remote Linux}{How To: Develop for remote Linux}, + {Manage Kits}{How To: Manage Kits}, {Developing for Remote Linux Devices}, + {Remote Linux Deploy Configuration}, {Remote Linux Run Settings} +*/ + +/*! + \page creator-how-to-add-remote-linux.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-remote-linux + + \title Add remote Linux devices + + Create connections between generic Linux devices and \QC to run, debug, and + analyze applications on them. + + \image qtcreator-preferences-devices-remote-linux.webp {Remote Linux Device in Devices} + \caption Remote Linux Device preferences + + \include qtcreator-add-linux-device.qdocinc {add linux device} {Remote Linux Device} + + \sa {Remote Linux}{How To: Develop for remote Linux}, + {Debug remotely with GDB}, {Developing for Remote Linux Devices}, + {Remote Linux Deploy Configuration} */ diff --git a/doc/qtcreator/src/linux-mobile/qtcreator-add-linux-device.qdocinc b/doc/qtcreator/src/linux-mobile/qtcreator-add-linux-device.qdocinc new file mode 100644 index 00000000000..28fb4648331 --- /dev/null +++ b/doc/qtcreator/src/linux-mobile/qtcreator-add-linux-device.qdocinc @@ -0,0 +1,47 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +//! [add linux device] + + \section1 Use a wizard to add a device + + To use a wizard to add \uicontrol {\1}: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \li Select \uicontrol Add > \uicontrol {\1} > \uicontrol {Start Wizard}. + \image qtcreator-preferences-devices-remote-linux-connection.webp {Connection Data wizard} + \li In \uicontrol {The name to identify this configuration}, + enter a name for the connection. + \li In \uicontrol {The device's host name or IP address}, + enter the host name or IP address of the device. + This becomes the value of the \c %{Device:HostAddress} variable. + \li In \uicontrol {The device's SSH port number}, enter the port + number for SSH connections. This becomes the value of the + \c %{Device:SshPort} variable. + \li In \uicontrol {The username to log into the device}, enter the + username to log into the device and run the application. This + becomes the value of the \c %{Device:UserName} variable. + \li Select \uicontrol {Next} to open the \uicontrol {Key Deployment} + dialog. + \image qtcreator-preferences-devices-remote-linux-key-deployment.webp {Key Deployment dialog} + \li In \uicontrol {Private key file}, select a private key file + for authentication. This becomes the value of the + \c %{Device:PrivateKeyFile} variable. + \li If you don't have a public-private key pair, select + \uicontrol {Create New Key Pair}. For more information, + see \l{Generate SSH keys}. + \li Select \uicontrol {Deploy Public Key} to copy the public + key to the device. + \li Select \uicontrol {Next} to create the connection. + \endlist + + To change device preferences, go to \preferences > \uicontrol Devices > + \uicontrol Devices and select a device in \uicontrol Device. + + \section1 Manually add a device + + To add a device without using the wizard, select \uicontrol {\1} in the + pull-down menu of the \uicontrol Add button. + +//! [add linux device] diff --git a/doc/qtcreator/src/mcu/creator-mcu-dev.qdoc b/doc/qtcreator/src/mcu/creator-mcu-dev.qdoc index 5d5dc8b956c..f49e375f617 100644 --- a/doc/qtcreator/src/mcu/creator-mcu-dev.qdoc +++ b/doc/qtcreator/src/mcu/creator-mcu-dev.qdoc @@ -91,7 +91,8 @@ \li 1.0 \endtable - \sa {Enable and disable plugins}, {MCUs}{How To: Develop for MCUs} + \sa {Enable and disable plugins}, {MCUs}{How To: Develop for MCUs}, + {Developing for MCUs}, {\QMCU} */ /*! @@ -157,7 +158,7 @@ \QC automatically adds a default MCU device when you select \uicontrol Apply in the \uicontrol MCU tab after configuring the - MCU tool chain. + MCU toolchain. \image qtcreator-mcu-device.png {MCU devices} @@ -180,6 +181,7 @@ \previouspage creator-how-tos.html \ingroup creator-how-to-mcu + \ingroup creator-how-to-manage-kits \title Manage MCU Kits @@ -208,7 +210,7 @@ software required for MCU development with the current kit. \sa {Enable and disable plugins}, {MCUs}{How To: Develop for MCUs}, - {Developing for MCUs} + {Manage Kits}{How To: Manage Kits}, {Developing for MCUs} */ /*! diff --git a/doc/qtcreator/src/meson/creator-projects-meson-building.qdoc b/doc/qtcreator/src/meson/creator-projects-meson-building.qdoc index d0ada5efced..5132adf9dc0 100644 --- a/doc/qtcreator/src/meson/creator-projects-meson-building.qdoc +++ b/doc/qtcreator/src/meson/creator-projects-meson-building.qdoc @@ -10,7 +10,7 @@ \brief Settings for building applications with Meson. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. diff --git a/doc/qtcreator/src/meson/creator-projects-meson.qdoc b/doc/qtcreator/src/meson/creator-projects-meson.qdoc index a6418fcc663..4c71fc7e5e8 100644 --- a/doc/qtcreator/src/meson/creator-projects-meson.qdoc +++ b/doc/qtcreator/src/meson/creator-projects-meson.qdoc @@ -21,7 +21,7 @@ \QC automatically detects the Meson and Ninja executables specified in the \c PATH. You can add paths to other Meson or Ninja executables and use them - in different build and run \l{glossary-buildandrun-kit}{kits}. + in different build and run \l{Kits}{kits}. \note Enable the Meson plugin to use it. @@ -54,7 +54,7 @@ \image qtcreator-kits-meson.png "Setting Meson executable in Kit preferences" - For more information, see \l {kits-tab}{Kits}. + For more information, see \l {Kits}. \section1 Editing Meson Build Descriptions diff --git a/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc b/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc index 1a1c04edfe1..388801786f3 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc @@ -20,12 +20,12 @@ However, if you install the stand-alone \QC package, build \QC from sources, or install several Qt versions, you may need to tell \QC where to find the Qt versions and compilers by adding the paths to them and by creating - \l{glossary-buildandrun-kit}{kits} that use them. + \l{Kits}{kits} that use them. - To make \QC behave more like your favorite code editor or IDE, you can - change the settings for keyboard shortcuts, color schemes, generic - highlighting, code snippets, and version control systems. In addition, - you can enable and disable \QC features by managing plugins. + To make \QC behave more like your favorite code editor or IDE, + change the preferences for keyboard shortcuts, color schemes, generic + highlighting, code snippets, and version control systems. Manage plugins + to turn on and off \QC features. The following sections summarize the options that you have and point you to detailed information to help you specify any required settings and to make @@ -33,8 +33,8 @@ \section1 Checking Build and Run Settings - \QC is an integrated development environment (IDE) that you can use to - develop Qt applications. While you can use \QOI to install \QC, + \QC is an integrated development environment (IDE) for creating + applications. While you can use \QOI to install \QC, the stand-alone \QC installer never installs Qt or any Qt tools, such as qmake. To use \QC for Qt development, you also need to install a Qt version and a compiler. If you update the compiler version later, you @@ -45,9 +45,7 @@ available in \QC. If it does not, you must add the kits yourself to tell \QC where everything is. - To add kits, select \preferences > \uicontrol Kits > \uicontrol Add. - - For more information, see \l{Add kits}. + To add kits, go to \preferences > \uicontrol Kits and select \uicontrol Add. Each kit consists of a set of values that define one environment, such as a \l{glossary-device}{device}, compiler, and Qt version. If \preferences > @@ -57,48 +55,41 @@ If \uicontrol Auto-detected still does not show the Qt version, select \uicontrol {Add} to add it manually. - For more information, see \l{Add Qt versions}. - Also check that \preferences > \uicontrol Kits > \uicontrol {Compilers} shows your compiler. - For more information, see \l{Add compilers}. + Connect devices to the computer via USB to run, debug, and analyze + applications on them. You can connect Linux-based devices also + over a WLAN. Configure a connection between \QC and the computer, and + select the device in a kit. - You can connect devices to the development PC to run, debug, and - analyze applications on them from \QC. You can connect the device to the - development PC via USB. Additionally, you can connect Linux-based devices - over a WLAN. You must also configure a connection between \QC and the - development PC and specify the device in a kit. + To add devices, go to \preferences > \uicontrol Devices > + \uicontrol Devices and select \uicontrol Add. - To add devices, select \preferences > \uicontrol Devices > - \uicontrol Devices > \uicontrol Add. - - For more information, see \l{Connecting Devices}. + For more information, see \l{Manage Kits}{How To: Manage Kits} and + \l{Develop for Devices}{How To: Develop for Devices}. \section1 Changing Keyboard Shortcuts You can use \QC with your favorite keyboard shortcuts. - To view and edit all keyboard shortcuts defined in \QC, select - \preferences > - \uicontrol Environment > - \uicontrol Keyboard. For more information, see \l{Keyboard Shortcuts}. + To view and edit all keyboard shortcuts defined in \QC, go to \preferences > + \uicontrol Environment > \uicontrol Keyboard. For more information, see + \l{Keyboard Shortcuts}. \section1 Changing Color Schemes - Themes enable you to customize the appearance of the \QC UI: widgets, - colors, and icons. + Themes set the appearance of the \QC UI: widgets, colors, and icons. - To switch themes, select \preferences > \uicontrol Environment > - \uicontrol Interface, and then select a theme in the \uicontrol Theme field. + To switch themes, go to \preferences > \uicontrol Environment > + \uicontrol Interface and select a theme in \uicontrol Theme. - You can use the \QC text and code editors with your favorite color scheme - that defines how to highlight code elements and which background color to - use. You can select one of the predefined color schemes or create custom - ones. The color schemes apply to highlighting C++ files, QML files, and - generic files. + Use the \QC text and code editors with your favorite color scheme that sets + highlighting of code elements and the background color. Select one of the + predefined color schemes or create custom ones. The color schemes apply to + highlighting C++ files, QML files, and generic files. - To change the color scheme, select \preferences > + To change the color scheme, go to \preferences > \uicontrol {Text Editor} > \uicontrol {Font & Colors}. For more information, see \l{Change editor colors}. @@ -108,7 +99,7 @@ highlighting engine for Kate syntax definitions. \QC comes with most of the commonly used syntax files, and you can download additional files. - To download and use highlight definition files, select \preferences > + To download and use highlight definition files, go to \preferences > \uicontrol {Text Editor} > \uicontrol {Generic Highlighter}. For more information, see \l{Download highlight definitions}. @@ -117,10 +108,10 @@ As you write code, \QC suggests properties, IDs, and code snippets to complete the code. It lists context-sensitive suggestions for - the statement currently under your cursor. You can add, modify, and remove + the statement currently under your cursor. Add, modify, and remove snippets in the snippet editor. - To open the snippet editor, select \preferences > + To open the snippet editor, go to \preferences > \uicontrol {Text Editor} > \uicontrol Snippets. For more information, see \l{Snippets}. @@ -131,8 +122,7 @@ to configure the version control in any special way to make it work with \QC. - However, some configuration options are available and you can set them in - \preferences > + However, you can set some configuration options in \preferences > \uicontrol {Version Control} > \uicontrol General. For more information about the supported functions, see @@ -144,13 +134,15 @@ You can \l{Enable and disable plugins}{enable} disabled plugins if you need them and disable plugins you don't need. - You can \l{Install plugins}{download and install} more plugins from + \l{Install plugins}{Download and install} more plugins from \l{https://marketplace.qt.io/}{Qt Marketplace} or some other source, such as \l{https://github.com/}{GitHub}. - To enable and disable plugins, select \uicontrol Help > + To enable and disable plugins, go to \uicontrol Help > \uicontrol {About Plugins}. - To install plugins, select \uicontrol Help > \uicontrol {About Plugins} > - \uicontrol {Install Plugins}. + To install plugins, go to \uicontrol Help > \uicontrol {About Plugins} and + select \uicontrol {Install Plugins}. + + \sa {Installation}, {Reset \QC settings}, {Preferences} */ diff --git a/doc/qtcreator/src/overview/creator-only/creator-deployment-overview.qdoc b/doc/qtcreator/src/overview/creator-only/creator-deployment-overview.qdoc deleted file mode 100644 index 000017249ac..00000000000 --- a/doc/qtcreator/src/overview/creator-only/creator-deployment-overview.qdoc +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2020 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-running-targets.html - \page creator-deployment.html - \nextpage creator-deploying-android.html - - \title Deploying to Devices - - Deploy configurations in the \uicontrol Projects mode - \uicontrol {Run Settings} handle the packaging of the application as an - executable and copying it to a location you want to run the executable at. - The files can be copied to a location in the file system of the development - PC or a \l{glossary-device}{device}. - - \list - - \li \l{Deploying to Android} - - When you deploy the application to an Android device, \QC copies - the application files to the device. In addition, you can determine - the Qt libraries to use. - - \li \l {Deploying to Boot2Qt} - - When you deploy the application to a Boot2Qt device, \QC copies - the application files to the connected device. You can then test - and debug the application on the device with \QC. - - \li \l{Deploying to QNX Neutrino} - - When you deploy the application to a QNX Neutrino device, \QC copies - the application files to the connected device. You can then test and - debug the application on the device with \QC. - - \li \l{Deploying to Remote Linux} - - When you deploy the application to a generic Linux-based device, \QC - copies the application files to the connected device. You can then - test and debug the application on the device with \QC. - \endlist -*/ diff --git a/doc/qtcreator/src/overview/creator-only/creator-desktop-platforms.qdoc b/doc/qtcreator/src/overview/creator-only/creator-desktop-platforms.qdoc index 67605429f86..6a2602b34d0 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-desktop-platforms.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-desktop-platforms.qdoc @@ -45,8 +45,7 @@ \li libxft-dev \li libxi-dev \li libxrandr-dev - \li libgl-dev and libglu-dev if you use Qt OpenGL (deprecated - in Qt 5) or Qt GUI OpenGL functions + \li libgl-dev and libglu-dev if you use Qt GUI OpenGL functions \endlist \section1 macOS diff --git a/doc/qtcreator/src/overview/creator-only/creator-getting-started.qdoc b/doc/qtcreator/src/overview/creator-only/creator-getting-started.qdoc index e735c95adf0..f41033c3e0d 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-getting-started.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-getting-started.qdoc @@ -1,14 +1,8 @@ -// 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 -// ********************************************************************** -// 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 index.html + \previouspage creator-how-to-install.html \page creator-getting-started.html \nextpage creator-overview.html @@ -18,19 +12,17 @@ \l{https://www.qt.io/academy/course-catalog#getting-started-with-qt-creator} {Getting Started with Qt Creator} course in Qt Academy. - For more information about installing \QC, see \l{Install \QC}. - - \table + \table borderless \row - \li \inlineimage front-gs.png - \li \inlineimage front-ui.png - \li \inlineimage front-advanced.png + \li \inlineimage icons/app-development.png + \li \inlineimage icons/ide.png + \li \inlineimage icons/getting-started.png \row - \li \b {\l{Developing with \QC}} + \li \b {\l{Overview}} If you have not used an integrated development environment (IDE) before, or want to know what kind of IDE \QC is, go to - \l{Developing with \QC}. + \l{Overview}. \li \b {\l{User Interface}} If you have not used \QC before, and want to become familiar @@ -43,14 +35,14 @@ control systems. For an overview of the options you have, go to \l{Configuring Qt Creator}. \row - \li \inlineimage front-preview.png - \li \inlineimage front-help.png - \li + \li \inlineimage icons/platform-and-toolchain.png + \li \inlineimage icons/tutorials.png + \li \inlineimage icons/api-reference.png \row \li \b {\l{Building and Running an Example}} To check that \l{https://www.qt.io/download-qt-installer} - {\QOI} created \l{glossary-buildandrun-kit} + {\QOI} created \l{Kits} {build and run kits}, open an example application and run it. If you have not done so before, go to \l{Building and Running an Example}. @@ -59,7 +51,11 @@ Now you are ready to start developing your own applications. Pick a tutorial to follow in \l{Tutorials}. To start developing for mobile devices, select \l{Creating a Mobile Application}. - \li + \li \b{\l {Qt Documentation}} + + For more examples, as well as the details about using Qt tools + and APIs to develop Qt applications, go to \l {Qt Documentation}. \endtable + \sa {Installation} */ diff --git a/doc/qtcreator/src/overview/creator-only/creator-glossary.qdoc b/doc/qtcreator/src/overview/creator-only/creator-glossary.qdoc index ac5e1cae6b4..2cbac901aaf 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-glossary.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-glossary.qdoc @@ -77,7 +77,7 @@ \li \QC groups build and run specific settings as kits to make cross-platform development easier. Each kit consists of a set of values that define one environment, such as a \e {device}, - tool chain, Qt version, and debugger command to use. Configure kits at + toolchain, Qt version, and debugger command to use. Configure kits at \preferences > \uicontrol Kits. \row diff --git a/doc/qtcreator/src/overview/creator-only/creator-issues.qdoc b/doc/qtcreator/src/overview/creator-only/creator-issues.qdoc index de7c8b45d3d..8d310983323 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-issues.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-issues.qdoc @@ -41,7 +41,7 @@ settings are stored locally. \li The Okteta KDE custom widget plugin might be installed as part of - some Linux distributions. It can cause Qt Designer to crash. For + some Linux distributions. It can cause \QD to crash. For more information, see: \list diff --git a/doc/qtcreator/src/overview/creator-only/creator-keyboard-shortcuts.qdoc b/doc/qtcreator/src/overview/creator-only/creator-keyboard-shortcuts.qdoc index c7a29a2c456..d15fc43003c 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-keyboard-shortcuts.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-keyboard-shortcuts.qdoc @@ -28,15 +28,15 @@ If several functions are available for the same shortcut in the current context, \QC will not execute any function due to the conflict. - A keyboard shortcut might also conflict with a shortcut that a window - manager uses for its own purposes. In that case, \QC shortcuts do not work. + A keyboard shortcut might also conflict with a shortcut that your window + manager uses for its own purposes. If the window manager consumes the key event, + the \QC shortcut will not be activated. Typically, you can configure the shortcuts in the window manager, but if that is not allowed, you can change the \QC shortcuts. - For example, Unity on - Ubuntu 11.10 uses \key F10 in its window manager, and therefore the default - \QC keyboard shortcut \key F10 (Step Over) does not work on that system. - + For example, Unity on Ubuntu 11.10 by default uses \key F10 in its window manager, + and therefore the default \QC keyboard shortcut \key F10 (Step Over) will not work on + that system. To override the platform default value that determines whether keyboard shortcuts are shown in the labels of context menu items, @@ -141,8 +141,11 @@ \li Switch to \uicontrol Projects mode \li Ctrl+5 \row - \li Switch to \uicontrol Help mode + \li Switch to \uicontrol Extensions mode \li Ctrl+6 + \row + \li Switch to \uicontrol Help mode + \li Ctrl+7 \row \li Toggle \uicontrol{Issues} \li Alt+1 (Cmd+1 on \macos) @@ -570,7 +573,7 @@ \li Open project \li Ctrl+Shift+O \row - \li Select the \l{glossary-buildandrun-kit}{kit} to build and run your project with + \li Select the \l{Kits}{kit} to build and run your project with \li Ctrl+T \row \li Run diff --git a/doc/qtcreator/src/overview/creator-only/creator-mobile-platforms.qdoc b/doc/qtcreator/src/overview/creator-only/creator-mobile-platforms.qdoc deleted file mode 100644 index fef448c3f15..00000000000 --- a/doc/qtcreator/src/overview/creator-only/creator-mobile-platforms.qdoc +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (C) 2022 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! - \page creator-mobile-platforms.html - \previouspage creator-reference.html - - \ingroup creator-reference-platforms - - \title Mobile Platforms - - \brief Mobile platforms that you can develop applications for. - - You can develop applications for the following mobile platforms: - - \list - \li \l Android - \li \l iOS - \endlist - - You must install the tool chain for building applications for the targeted - mobile platform on the development PC and use \QMT to - install Qt libraries that are built for the platform. You can then add a - \l{glossary-buildandrun-kit}{kit} with the tool chain and the Qt version - for the device's architecture. When possible, \QMT creates - suitable kits for you. - - You can connect mobile devices to the development PC and select the - appropriate kit to build, run, debug, and analyze applications from \QC. - - Before starting application development, analyze and define the requirements, - scope, and functionality of the application to ensure efficient functionality - and a smooth user experience on mobile devices. - - \section1 Android - - Starting from Qt 5.14.0, the Qt for Android package has all the - architectures (ABIs) installed as one. You can let \QC automatically - create kits for installed Qt version and tool chains. - - The following topics have more information about developing applications - for Android devices: - - \list - \li \l{Connecting Android Devices} - \li \l{Deploying to Android} - \li \l{Run on many platforms} - \li \l{Creating a Mobile Application} - \li \l{Debugging on Android Devices} - \li \l{Qt for Android} - \endlist - - \section1 iOS - - \note Deployment, running, and debugging on iOS 17 devices are not supported. - - To be able to use \QC on \macos, you must install Xcode, and therefore - you should already have the tool chain for building applications for - iOS. \QC automatically detects the tool chain and creates the necessary - kits to build applications for and run them on configured iOS devices. - - The following topics have more information about developing applications - for iOS devices: - - \list - \li \l{Connecting iOS Devices} - \li \l{Run on many platforms} - \li \l{Creating a Mobile Application} - \li \l{Qt for iOS} - \endlist - - \sa {Optimizing Applications for Mobile Devices}, {Supported Platforms} -*/ diff --git a/doc/qtcreator/src/overview/creator-only/creator-mobile-targets.qdoc b/doc/qtcreator/src/overview/creator-only/creator-mobile-targets.qdoc deleted file mode 100644 index 395a5ba4589..00000000000 --- a/doc/qtcreator/src/overview/creator-only/creator-mobile-targets.qdoc +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (C) 2022 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. -// ********************************************************************** - -/*! - \page creator-connecting-mobile.html - \previouspage creator-deployment-embedded-linux.html - \nextpage creator-developing-android.html - - \title Connecting Devices - - You can connect \l{glossary-device}{devices} to the development PC to run, debug, - and analyze applications built for them from \QC. When you install Qt for a - target platform, such as Android or QNX, - the build and run settings for the development targets might be set up - automatically in \QC. - - You can connect the device to the development PC using a USB connection. - Additionally, you can connect Linux-based devices by using a WLAN - connection. - - The experimental WebAssembly plugin enables you to build your applications - in WebAssembly format, to deploy them, and to run them in a web browser. - - \list - - \li \l{Connecting Android Devices} - - Qt applications for Android are compiled as \c {shared objects} that - are loaded by a Java launcher that is part of Qt. - This is totally transparent to users. As Qt is composed of libraries - referencing each other, Qt 5 applications are only supported on - Android version 4.1 (API level 16), or later, and Qt 6 applications - on Android version 6.0 (API level 23), or later. You must install a - Qt version targeting Android and the Android SDK and NDK to develop - for Android devices. - - \li \l{Connecting Bare Metal Devices} - - You can connect bare metal devices to the development PC and use \QC - to debug applications on them with GDB or a hardware debugger. - - \li \l{Connecting Boot2Qt Devices} - - You can connect \l{Boot2Qt} devices to the development PC to run, - debug, and analyze applications built for them from \QC. - - \li \l {Adding Docker Devices} - - Create Docker devices from Docker images and use them to build, run, - and debug applications from \QC. - - \li \l{Connecting iOS Devices} - - You use the tools delivered with Xcode to connect devices to \QC. - \QC detects the tools and configured devices automatically and uses - the tools to build, deploy, and run applications. - - \li \l{Developing for MCUs} - - You can connect MCU boards to a development host to deploy, run, and - debug applications on them from \QC. - - \li \l{Connecting QNX Devices} - - You can connect QNX devices to the development PC to deploy, run and - debug applications on them from within \QC. This is currently only - supported for QNX Neutrino devices, and requires the QNX SDK to be - installed on the development PC. - - \li \l{Connecting Remote Linux Devices} - - If you have a tool chain for building applications for embedded - Linux devices installed on the development - PC, you can add it and the device to \QC. - - \endlist - - \sa {Building Applications for the Web}, {Run in Qt Application Manager} -*/ diff --git a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc index b164224e848..9ab035a23e1 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-overview.qdoc @@ -8,11 +8,11 @@ // ********************************************************************** /*! - \previouspage index.html + \previouspage creator-getting-started.html \page creator-overview.html - \nextpage creator-getting-started.html + \nextpage creator-quick-tour.html - \title Developing with \QC + \title Overview \QC is a cross-platform, complete integrated development environment (IDE) that you can use to create applications for desktop, embedded, @@ -94,6 +94,11 @@ Load C++ plugins for QML to simulate data. \endlist + Use the QML live preview to preview a QML file or an entire Qt Quick + application on the desktop, as well as on Android and embedded Linux + devices. The changes you make to the UI are instantly visible to you + in the preview. + If you need a traditional user interface that has a clear structure and enforces a platform look and feel, use \l{Qt Widgets} and the integrated \l{\QD}. @@ -176,7 +181,7 @@ Run and deploy Qt applications that you build for different target platforms or with different compilers, debuggers, or Qt versions. - \l{glossary-buildandrun-kit}{Kits} define the tools, \l{glossary-device} + \l{Kits} define the tools, \l{glossary-device} {device} type and other settings to use when building and running your project. @@ -186,35 +191,66 @@ build the project. Build applications for, deploy them to, and run them on the desktop - environment or a device. With kits, as well as build, run, and deployment + environment or a device. With kits, as well as build, deploy, and run configurations, you can quickly switch between different setups and target platforms. For more information, see \l{Build and Run}{How To: Build and Run}, \l{Build Systems}, \l{Build Configurations}, and \l{Run Configurations}. - \section2 On Devices + \section2 Embedded Platforms - When you install tool chains for device types as part of a Qt distribution, - the build and run configurations for the devices might be set up - automatically. However, you might need to install and configure some - additional software on the devices to be able to connect to them - from the computer. + You can develop applications for the following embedded platforms: - Deployment configurations handle the packaging and copying of the necessary + \list + \li \l {Bare Metal} + \li \l {\B2Q} + \li \l {MCUs} + \li \l {QNX Neutrino} + \li \l {Remote Linux} + \endlist + + Install the toolchain for building applications for the targeted + embedded platform on the computer, and then use \QOI to install Qt + libraries that are built for the platform. Add a kit with the toolchain and + the Qt version for the device's architecture. When possible, \QOI creates + suitable kits for you. + + You can connect embedded devices to the computer and select the appropriate + kit to run, debug, and analyze applications built for them from \QC. + + \e {Deploy configurations} handle the packaging and copying of the necessary files to a location you want to run the executable at, such as the file system of a device. - For more information, see \l{Connecting Devices} and \l{Deploying to Devices}. + For more information, see \l{Develop for Devices}{How To: Develop for Devices} + and \l{Devices}. - \section2 Previewing QML + \section2 Mobile Platforms - Use the QML live preview to preview a QML file or an entire Qt Quick - application on the desktop, as well as on Android and embedded Linux - devices. The changes you make to the UI are instantly visible to you - in the preview. + You can develop applications for the following mobile platforms: - For more information, see \l{Validating with Target Hardware}. + \list + \li \l Android + \li \l iOS + \endlist + + Install the toolchain for building applications for the targeted mobile + platform on the computer, and then use \QOI to install Qt libraries that are + built for the platform. Add a kit with the toolchain and the Qt version for + the device's architecture. When possible, \QOI creates suitable kits for you. + + You can connect mobile devices to the computer and select the + appropriate kit to build, run, debug, and analyze applications from \QC. + + Before starting application development, analyze and define the requirements, + scope, and functionality of the application to ensure efficient functionality + and a smooth user experience on mobile devices. + + For more information, see + \l{Develop for Devices}{How To: Develop for Devices}, + \l{Optimizing Applications for Mobile Devices}, \l {Supported Platforms}, and + \l{Deploy Configurations}. \section1 Debugging Applications @@ -230,10 +266,10 @@ to find the next one. \endlist - \QC integrates several external native debuggers for inspecting the state of - your application while debugging. The debugger plugin automatically selects - a suitable native debugger for each kit from the ones it finds on the - computer. Edit the kits to override this choice. + \QC integrates several debuggers for inspecting the state of your + application. It automatically selects a suitable debugger for each + kit from the ones it finds on the computer. Edit the kits to override + this choice. If you install \QC with \QOI, the GNU Symbolic Debugger is installed automatically and you should be ready to start debugging after you create @@ -242,20 +278,20 @@ Connect devices to your computer to debug processes running on the devices. - For more information, see \l{Debugging}. + For more information, see \l{Debugging} and \l{Debug}{How To: Debug}. - \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 QML Profiler and 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 @@ -287,10 +323,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/overview/creator-only/creator-reference.qdoc b/doc/qtcreator/src/overview/creator-only/creator-reference.qdoc index 86450b31b13..03e81452f75 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-reference.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-reference.qdoc @@ -28,7 +28,7 @@ \annotatedlist creator-reference-build-systems - \section1 Build Configurations + \section2 Build Configurations Build configurations have everything you need to compile the sources into binaries. Build configurations use the tools and settings defined in their @@ -36,6 +36,20 @@ \annotatedlist creator-reference-build-configurations + \section1 Debuggers + + Set up and use debuggers to debug executable binary files, as well as + QML, Java, and Python source code. + + \annotatedlist creator-reference-debugger + + \section2 Debugger Views + + Inspect the state of your application while debugging in the + \uicontrol Debug mode. + + \annotatedlist creator-reference-debugger-views + \section1 Devices Connect devices to the computer to run, debug, and analyze applications @@ -45,6 +59,26 @@ \annotatedlist creator-reference-devices + \section2 Deploy Configurations + + Deploy configurations handle the packaging of the application as an + executable and copying it to a location you want to run the executable at. + The files can be copied to a location in the file system of the computer + or a device. + + \annotatedlist creator-reference-deploy-configurations + + \section2 Run Configurations + + Run configurations start the application in the location where the + deploy configuration copied it. By default, when you select + \uicontrol Run, \QC builds the project, deploys it to the device + defined in the kit, and runs it there. If you did not make changes + to the project since you last built and deployed it, \QC simply runs + it again. + + \annotatedlist creator-reference-run-configurations + \section1 Editors When you open files, \QC chooses a suitable editor according to the file @@ -78,6 +112,10 @@ \annotatedlist creator-reference-preferences-cpp + \section2 Debugger + + \annotatedlist creator-reference-preferences-debugger + \section2 Kits Preferences for build and run kits. @@ -90,17 +128,6 @@ \annotatedlist creator-reference-preferences-text-editor - \section1 Run Configurations - - Run configurations start the application in the location where the - \e {deploy configuration} copied it. By default, when you select - \uicontrol Run, \QC builds the project, deploys it to the device - defined in the kit, and runs it there. If you did not make changes - to the project since you last built and deployed it, \QC simply runs - it again. - - \annotatedlist creator-reference-run-configurations - \section1 UI Design You can use a visual editor, \QD, for designing widget-based UIs diff --git a/doc/qtcreator/src/overview/creator-only/creator-supported-platforms.qdoc b/doc/qtcreator/src/overview/creator-only/creator-supported-platforms.qdoc index 9481519eb77..43c60144c41 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-supported-platforms.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-supported-platforms.qdoc @@ -38,12 +38,7 @@ \li \image ok.png \li \image ok.png \row - \li \l Boot2Qt - \li \image ok.png - \li \image ok.png - \li \image ok.png - \row - \li \l{Remote Linux} + \li \l {\B2Q} \li \image ok.png \li \image ok.png \li \image ok.png @@ -53,7 +48,7 @@ \li \image ok.png \li \row - \li \l{Microcontroller Units (MCU)}{MCUs} + \li \l{MCUs} \li \image ok.png \li \li \image ok.png @@ -63,7 +58,12 @@ \li \image ok.png \li \inlineimage ok.png \row - \li \l{Building Applications for the Web}{WebAssembly} + \li \l{Remote Linux} + \li \image ok.png + \li \image ok.png + \li \image ok.png + \row + \li \l{Build applications for the web}{WebAssembly} \li \image ok.png \li \image ok.png \li \image ok.png @@ -74,5 +74,6 @@ \QC automatically runs scheduled checks for updates based on the settings specified in \preferences > \uicontrol Environment > \uicontrol Update. - \sa {Desktop Platforms}, {Embedded Platforms}, {Mobile Platforms} + \sa {Develop for Devices}{How To: Develop for Devices}, {Desktop Platforms}, + {Devices} */ 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..814189ee7b6 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 @@ -11,7 +11,7 @@ \brief Settings for building applications with qmake. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. @@ -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-how-to-add-wizards.qdoc b/doc/qtcreator/src/projects/creator-only/creator-how-to-add-wizards.qdoc index fa7663f02d7..e6cb582b9bc 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-how-to-add-wizards.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-how-to-add-wizards.qdoc @@ -44,5 +44,5 @@ to specify the position of the wizard. For example, \c B.MyClass. \endlist -\sa {Custom Wizards}, {Find settings files} + \sa {Run Qt Creator from the command line}, {Custom Wizards} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-how-to-create-compiler-explorer-setup.qdoc b/doc/qtcreator/src/projects/creator-only/creator-how-to-create-compiler-explorer-setup.qdoc index b35df2e6707..a8bc0f11d4b 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-how-to-create-compiler-explorer-setup.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-how-to-create-compiler-explorer-setup.qdoc @@ -9,19 +9,27 @@ \title Create compiler explorer sessions - To create a compiler explorer session for a C++ or Python project: + \note Enable the Compiler Explorer plugin to use it. + + To create a compiler explorer session for a Qt and C++, C++, or Python + project: \list 1 \li Go to \uicontrol File > \uicontrol {New File}. - \li Select \uicontrol {Compiler Explorer} > \uicontrol C++ or - \uicontrol Python > \uicontrol Choose. + \li Select \uicontrol {Compiler Explorer}, and then select one of the + following: + \list + \li \uicontrol {Compiler Explorer C++ Source} + \li \uicontrol {Compiler Explorer Python Source} + \li \uicontrol {Compiler Explorer Qt & C++ Source} + \endlist + \image qtcreator-new-project-compiler-explorer.webp {New File dialog} + \li Select \uicontrol Choose. \li Follow the instructions of the wizard to create an example compiler explorer session as a JSON-based \c .qtce file and to open it. \endlist - \note Enable the Compiler Explorer plugin to use it. - \sa {Create files}, {Enable and disable plugins}, {Explore compiler code} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-how-to-edit-qbs-profiles.qdoc b/doc/qtcreator/src/projects/creator-only/creator-how-to-edit-qbs-profiles.qdoc index 60f0d3bb0b1..a5037be5b91 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-how-to-edit-qbs-profiles.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-how-to-edit-qbs-profiles.qdoc @@ -39,5 +39,5 @@ To remove the selected property, select \uicontrol Remove. - \sa {Activate kits for a project}, {Add kits}, {kits-tab}{Kits} + \sa {Activate kits for a project}, {Add kits}, {Kits} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-build-run-tutorial.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-build-run-tutorial.qdoc index c6ce34ca69f..eb8e2a14ee1 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-build-run-tutorial.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-build-run-tutorial.qdoc @@ -23,12 +23,12 @@ To run an example application on an Android or iOS device, you must set up the development environment for Android or iOS. For more information, see - \l{Connecting Android Devices} and \l{Connecting iOS Devices}. + \l{Developing for Android} and \l{Developing for iOS}. - To run an example application on a Boot2Qt device, you must set up - Boot2Qt on the development host and create connections + To run an example application on a \B2Q device, you must set up + \B2Q on the development host and create connections between the host and devices. For more information, see - \l{Boot2Qt: Documentation}. + \l{\B2Q: Documentation}. If you have \l{Qt Design Studio Manual}{\QDS} installed, you can open \QDS examples from \QC in \QDS. @@ -47,11 +47,11 @@ \li Select an example in the list of examples. You can also use tags (3) to filter examples. For instance, enter - the \uicontrol Boot2Qt tag (commercial only) in the search field - (4) to list examples that you can run on Boot2Qt devices. + the \uicontrol \B2Q tag (commercial only) in the search field + (4) to list examples that you can run on \B2Q devices. \li In \uicontrol {Configure Project}, select - \l{glossary-buildandrun-kit}{kits} for building the example for the + \l{Kits}{kits} for building the example for the target platforms. \image qtcreator-configure-project.webp {Configure Project view} @@ -86,6 +86,6 @@ \endlist \sa {Manage Kits}{How To: Manage Kits}, {Open projects}, - {Connecting Android Devices}, {Connecting iOS Devices}, - {Compile Output}, {Boot2Qt: Documentation}, {Qt Design Studio Manual} + {Developing for Android}, {Developing for iOS}, + {Compile Output}, {\B2Q: Documentation}, {Qt Design Studio Manual} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-building-running.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-building-running.qdoc deleted file mode 100644 index bd4743a437b..00000000000 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-building-running.qdoc +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2019 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-scxml.html - \page creator-building-running.html - \nextpage creator-live-preview.html - - \title Running on Devices - - \QC supports running and deploying Qt applications that you build - for different target platforms or with different compilers, debuggers, or - Qt versions. \l{glossary-buildandrun-kit}{Kits} define the tools, - \l{glossary-device}{device} type and other settings to use when building and - running your project. - - \list - - \li \l {Validating with Target Hardware} - - You can use the QML live preview to preview a QML file or an - entire Qt Quick application on the desktop, as well as on - Android and embedded Linux devices. The changes you make to - the UI are instantly visible to you in the preview. - - \li \l{Deploying to Devices} - - \e {Deploy configurations} handle the packaging and copying of - the necessary files to a location you want to run the executable - at. The files can be copied to a location in the file system of - the development PC or a device. - - \li \l{Connecting Devices} - - When you install tool chains for device types as part of a Qt distribution, - the build and run settings for the devices might be set up - automatically. However, you might need to install and configure some - additional software on the devices to be able to connect to them - from the development PC. - - \endlist - - \sa {Build and Run}{How To: Build and Run} -*/ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-building.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-building.qdoc index d42df965a7e..a0189b216ab 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-building.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-building.qdoc @@ -16,7 +16,7 @@ \title Build for many platforms You can build applications for many target platforms, or using different - compilers, debuggers or Qt versions. \l{glossary-buildandrun-kit}{Kits} + compilers, debuggers or Qt versions. \l{Kits} define the tools, \l{glossary-device}{device} type, and other settings to use. By default, when you run the application, you @@ -34,9 +34,8 @@ \list 1 \li Select the \uicontrol {Build and Run Kit Selector} icon or go to - \uicontrol Build > \uicontrol {Open Build and Run Kit Selector} to select the - build and run \l{glossary-buildandrun-kit}{kit} or an - \l{Managing Android Virtual Devices (AVD)}{Android device}. + \uicontrol Build > \uicontrol {Open Build and Run Kit Selector} to + select the build and run kit or an \l{Manage AVDs}{Android device}. \image qtcreator-kit-selector.webp {Kit selector} @@ -105,7 +104,7 @@ \uicontrol Projects view. \sa {Configure projects for building}, {Build and Run}{How To: Build and Run}, - {Adding Docker Devices}, {Specifying Build Settings} + {Add Docker devices}, {Specifying Build Settings} */ /*! diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-compilers.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-compilers.qdoc index d92e8c90a47..e068ec86d4f 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-compilers.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-compilers.qdoc @@ -18,7 +18,7 @@ You can develop Qt applications on several 32-bit and 64-bit platforms. Usually, you can build Qt applications on each platform with GCC, a vendor-supplied compiler, or a third party compiler. In \QC, a - \l{glossary-buildandrun-kit}{kit} specifies the compiler and other + \l{Kits}{kit} specifies the compiler and other necessary tools for building an application for and running it on a particular platform. @@ -103,8 +103,8 @@ \li Other than the listed compilers and remote compilers. \endtable - The emscripten compiler is tool chain for compiling to - \l{Building Applications for the Web}{WebAssembly}. + The emscripten compiler is toolchain for compiling to + \l{Build applications for the web}{WebAssembly}. \section2 Bare-metal compilers @@ -145,10 +145,10 @@ \endcode If these commands show paths, they have been added to the global PATH - variable during the installation of a tool chain based on Cygwin or \MinGW, + variable during the installation of a toolchain based on Cygwin or \MinGW, even though this is against Windows conventions. - To keep working with the third-party tool chain, create a new shell link + To keep working with the third-party toolchain, create a new shell link that adds the required paths (as Visual Studio and Qt do). The shell link must point to cmd.exe: @@ -157,19 +157,19 @@ where the /K parameter carries out the command specified in the bat file. Create the myenv.bat file at \e path_to, which should be in a convenient - location. In the file, specify the paths to the tool chains. For example, + location. In the file, specify the paths to the toolchains. For example, \c {set PATH=C:\path1;C:\path2;%PATH%} - where \e path1 and \e path2 are paths to the tool chains. + where \e path1 and \e path2 are paths to the toolchains. Finally, remove the paths from the global PATH, reboot the computer, and run the \c where commands again to verify that the global PATH is now clean. - You can use the shell link to run the tools in the third-party tool chains. + You can use the shell link to run the tools in the third-party toolchains. \sa {Compilers}, {Add Nim compilers}, {Add custom compilers}, - {Connecting Bare Metal Devices}, {Supported Platforms} + {Developing for Bare Metal Devices}, {Supported Platforms} */ /*! 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..92858ff6078 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-creating.qdoc @@ -63,10 +63,10 @@ To test applications on \l{glossary-device}{devices}, you can install toolchains for mobile and embedded development as part of Qt distributions. - The installers create \l{glossary-buildandrun-kit}{kits} and specify build + The installers create \l{Kits}{kits} and specify build and run settings for the installed device types. However, you might need to install and configure some additional software on the devices to be able to - \l{Connecting Devices}{connect} to them from the development PC. + \l{Develop for Devices}{connect} to them from the computer. \sa {Manage Projects}{How To: Manage Projects}, {Custom Wizards} */ @@ -81,7 +81,7 @@ To create a new project, select \uicontrol File > \uicontrol{New Project} and select the type of your project. The contents of the wizard dialogs depend - on the project type and the \l{glossary-buildandrun-kit}{kits} that you + on the project type and the \l{Kits}{kits} that you select in the \uicontrol {Kit Selection} dialog. Follow the instructions of the wizard. @@ -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/projects/creator-only/creator-projects-custom-wizards-json.qdocinc b/doc/qtcreator/src/projects/creator-only/creator-projects-custom-wizards-json.qdocinc index c2d2fe9e2dd..f2d8d254249 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-custom-wizards-json.qdocinc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-custom-wizards-json.qdocinc @@ -238,7 +238,7 @@ { "key": "CN", "value": "%{JS: Cpp.className(value('Class'))}" }, { "key": "Base", "value": "%{JS: value('BaseCB') === '' ? value('BaseEdit') : value('BaseCB')}" }, { "key": "isQObject", "value": "%{JS: (value('Base') === 'QObject' || value('Base') === 'QWidget' || value('Base') === 'QMainWindow' || value('Base') === 'QQuickItem' ) ? 'true' : 'false'}" }, - { "key": "GUARD", "value": "%{JS: Cpp.classToHeaderGuard(value('Class'), Util.suffix(value('HdrFileName'))}" }, + { "key": "GUARD", "value": "%{JS: Cpp.headerGuard(value('HdrFileName'))}" }, { "key": "SharedDataInit", "value": "%{JS: value('IncludeQSharedData') ? 'data(new %{CN}Data)' : '' }" } ], \endcode diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-debuggers.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-debuggers.qdoc index 8762a9e97b1..8720339ca6a 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-debuggers.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-debuggers.qdoc @@ -15,13 +15,12 @@ \title Add debuggers - The \QC debugger plugin acts as an interface between the \QC core and - external native debuggers such as the GNU Symbolic Debugger (GDB), + You can use debuggers, such as the GNU Symbolic Debugger (GDB), the Microsoft Console Debugger (CDB), a QML/JavaScript debugger, and the debugger of the low level virtual machine (LLVM) project, LLDB. - The debugger plugin automatically selects a suitable native debugger for - each \l{glossary-buildandrun-kit}{kit} from the ones found on your system. + \QC automatically selects a suitable debugger for + each \l{Kits}{kit} from the ones found on your system. To override this choice, select \preferences > \uicontrol Kits. To add debuggers: @@ -75,5 +74,6 @@ The debugger disappears from the list when you select \uicontrol Apply. Until then, you can cancel the deletion by clicking \uicontrol Restore. - \sa {Debugging}, {Setting Up Debugger}, {Troubleshooting Debugger} + \sa {Debugging}, {Debuggers}, {Debugger}, {Supported Debuggers}, + {Troubleshooting Debugger} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-generic.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-generic.qdoc index e4e682d2a6f..2a57fcfaac6 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-generic.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-generic.qdoc @@ -125,7 +125,7 @@ you first need to deploy your executable and possibly other files. \QC does that for you automatically if you enter the necessary information. This works the same way as explained for CMake in - \l {Deploying to Remote Linux}, + \l {Remote Linux Deploy Configuration}, except that you also need to include your application binary in the list. \section1 Create a run configuration diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-kits.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-kits.qdoc index 4654c4326fd..1237c748443 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-kits.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-kits.qdoc @@ -25,16 +25,16 @@ You can add kits for the desktop and for the following types of devices: \list - \li \l{Connecting Android Devices}{Android} - \li \l{Connecting Bare Metal Devices}{Bare Metal} - \li \l{Boot2Qt: Documentation}{Boot2Q} (commercial only) - \li \l{Adding Docker Devices}{Docker} (experimental) - \li \l{Connecting iOS Devices}{iOS} + \li \l{Developing for Android}{Android} + \li \l{Developing for Bare Metal Devices}{Bare Metal} + \li \l{\B2Q: Documentation}{\B2Q} (commercial only) + \li \l{Add Docker devices}{Docker} (experimental) + \li \l{Developing for iOS}{iOS} \li iOS Simulator - \li \l{Connecting MCUs}{MCU} (commercial only) - \li \l{Connecting QNX Devices}{QNX} - \li \l{Connecting Remote Linux Devices}{Remote Linux} - \li \l{Building Applications for the Web}{WebAssembly Runtime} + \li \l{Developing for MCUs}{MCU} (commercial only) + \li \l{Add a QNX Neutrino device}{QNX} + \li \l{Developing for Remote Linux Devices}{Remote Linux} + \li \l{Build applications for the web}{WebAssembly Runtime} \endlist To add kits: @@ -45,7 +45,7 @@ \li Select \uicontrol Add to start from an empty kit or \uicontrol Clone to clone the selected kit and edit its preferences. \image qtcreator-kits.png - \li Set \l{kits-tab}{kit preferences} according to the build system and + \li Set \l{Kits}{kit preferences} according to the build system and device type. \li Select \uicontrol OK to create the kit. @@ -58,8 +58,7 @@ choose the kit to use. To set the selected kit as the default kit, select \uicontrol {Make Default}. - \sa {Activate kits for a project}, {Add debuggers}, {Add Qt versions}, - {Open projects}, {Compilers}, {kits-tab}{Kits} + \sa {Manage Kits}{How To: Manage Kits}, {Compilers}, {Kits} */ /*! @@ -72,7 +71,7 @@ \title Kits \brief Set kit preferences. A kit consists of a set of values that define - one environment, such as a \e {device}, tool chain, Qt version, and debugger + one environment, such as a \e {device}, toolchain, Qt version, and debugger command to use. Typically, only a subset of the kit preferences is relevant for a particular @@ -134,7 +133,7 @@ cross-compiling, leave this field empty. \row \li \uicontrol {Emulator skin} - \li Skin to use for the \l {Emulator}{Boot2Qt Emulator Device}. + \li Skin to use for the \l {Emulator}{\B2Q Emulator Device}. \row \li \uicontrol {Compiler} \li C or C++ compiler that you use to build the project. You can add @@ -214,7 +213,6 @@ \uicontrol Manage to add installed Ninja tools to the list. \endtable - \sa {Activate kits for a project}, {Open projects}, {Add CMake Tools}, - {Add compilers}, {Add debuggers}, {Add kits}, {Add Qt versions}, + \sa {Manage Kits}{How To: Manage Kits}, {Add CMake Tools}, {Edit Qbs profiles} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-libraries.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-libraries.qdoc index c4f8d905a33..fc66a62e8a7 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-libraries.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-libraries.qdoc @@ -91,7 +91,7 @@ For more information about the project file settings, see \l{Declaring Other Libraries}{qmake Manual: Declaring Other Libraries}. - \sa {Adding an Internal Library to a qmake Project}{Tutorial: Adding an Internal Library to a qmake Project}, + \sa {Using an Internal Library in a qmake Project}{Tutorial: Using an Internal Library in a qmake Project}, {Add subprojects to projects}, {Add libraries to CMake projects}, {Use project wizards}, {Creating Projects} */ @@ -103,7 +103,7 @@ \ingroup creator-tutorials - \title Adding an Internal Library to a qmake Project + \title Using an Internal Library in a qmake Project \brief How to create your own library and link your application against it when using qmake as the build system. diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-nimble.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-nimble.qdoc index c85da814661..a01c06b6559 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-nimble.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-nimble.qdoc @@ -20,7 +20,7 @@ \note Enable the Nim plugin to use Nimble and Nim. In addition, you have to download and install Nim and set up a - \l {glossary-buildandrun-kit}{kit} that contains the Nim compiler. + \l {Kits}{kit} that contains the Nim compiler. You can use wizards to create Nim and Nimble projects. diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-opening.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-opening.qdoc index 66b69a573fe..b71064f96e0 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-opening.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-opening.qdoc @@ -13,6 +13,8 @@ \previouspage creator-how-tos.html \ingroup creator-how-to-projects-configure + \ingroup creator-how-to-manage-kits + \ingroup creator-how-to-projects \title Open projects @@ -48,6 +50,15 @@ \endlist \endlist + \section1 Open directories as projects + + To open a directory as a project, go to \uicontrol File > + \uicontrol {Open Workspace}. + + \QC generates the \e .qtcreator/project.json project file in the directory + for setting a project name and file exclusion filters. You can open either + the JSON file or the workspace to open the project the next time. + \section1 Re-configure projects \QC stores information that it needs to build projects in a .user file. If @@ -64,7 +75,7 @@ \list 1 \li In \uicontrol {Configure Project}, select - \l{glossary-buildandrun-kit}{kits} for building + \l{Kits}{kits} for building and running your project. \image qtcreator-configure-project.webp {Configure Project view} \li Select \uicontrol {Configure Project}. @@ -112,5 +123,5 @@ later. Select the \inlineimage icons/pin.png (\uicontrol Pin) button to pin the progress bar back to the toggle button. - \sa {Activate kits for a project}, {Add kits}, {kits-tab}{Kits}, + \sa {Manage Kits}{How To: Manage Kits}, {Kits}, */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-qt-versions.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-qt-versions.qdoc index 0b06e1d84c1..48958f8846e 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-qt-versions.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-qt-versions.qdoc @@ -108,28 +108,45 @@ To verify the installation of a particular Qt version, \QC calls \c {qmake -query} and checks that the directories referenced in the - output exist. When \QC complains about the installation of a self-built Qt - version, try running \c {make install} in the build directory to actually - install Qt into the configured location. If you installed Qt using the Qt - Installer, run \QMT to check for updates or to reinstall - the Qt version. + output exist. If you installed Qt using \QOI, run + \QMT to check for updates or to reinstall the Qt version. - \section1 Minimum requirements - If your build of Qt is incomplete but you still want to use qmake as build - system, you need to ensure the following minimum requirements to use that - setup with \QC. + \section2 Self-built Qt versions - \list 1 + To build projects with a self-built Qt version, add it as described in + \l{Set up new Qt versions}. + + Your Qt has to meet the following minimum requirements: + + \list \li qmake is an executable that understands the \c -query command-line argument. \li The \c bin and \c include directories have to exist. \QC fetches these directories by running \c{qmake -query}. - \li The \c mkspecs directory should be complete enough to parse .pro - files. \endlist - If your Qt version has no \c libQtCore.so, \QC cannot detect the ABI. + Add a kit for the Qt version and configure it for CMake. - \sa {kits-tab}{Kits} + \QC issues warnings if: + + \list + \li \c libQtCore.so is missing, so \QC cannot detect the ABI. + \li \c toolchain.cmake is missing. For example, you built Qt with the + \c -static option for an x86 platform. + \endlist + + Try the following: + + \list + \li Run \c {make install} in the build directory to install Qt into the + configured location. + \li Set the value of the \c CMAKE_PREFIX_PATH variable in \preferences > + \uicontrol Kits > \uicontrol Kits > \uicontrol {CMake Configuration} + to the location where you installed Qt. + \endlist + + \image qtcreator-edit-cmake-configuration-self-built-qt.webp {Setting the path to a self-built Qt} + + \sa {Manage Kits}{How To: Manage Kits}, {kits-tab}{Kits} */ 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..0c33472862d 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 @@ -11,7 +11,7 @@ \brief Settings for building applications with Qbs. - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. @@ -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 @@ -59,7 +59,7 @@ \endlist \li In the \uicontrol ABIs field, select the ABIs for - the \l{Connecting Android Devices}{Android} device + the \l{Developing for Android}{Android} device architectures to build the project for. \li In the \uicontrol {Parallel jobs} field, specify the number of diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build.qdoc index 31bc8204d4a..644b30ac3b1 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-build.qdoc @@ -16,7 +16,7 @@ \title Configure projects for building - Specify build settings for the selected \l{glossary-buildandrun-kit}{kit} in + Specify build settings for the selected \l{Kits}{kit} in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Build > \uicontrol {Build Settings}. @@ -56,8 +56,8 @@ \section1 Build on remote devices - You can build applications on \l{Connecting Remote Linux Devices} - {remote Linux} or \l{Adding Docker Devices}{Docker} devices if you + You can build applications on \l{Developing for Remote Linux Devices} + {remote Linux} or \l{Add Docker devices}{Docker} devices if you have kits that specify the devices and toolchains to use. When the build device of the kit is a remote device, such as a remote Linux or Docker device, the \uicontrol Browse button next to the diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-environment.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-environment.qdoc index ce809fc536d..db6aefeb64c 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-environment.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-environment.qdoc @@ -141,6 +141,10 @@ Use the following syntax to enter environment variable names and values: \c {=}. + To temporarily disable a variable, add a hash character (#) to the beginning + of the line. + \note Using this approach for a different statement (append, prepend, unset) + may result in unexpected changes of the environment. To remove a variable value from the environment, enter the variable name. For example, \c TEST sets the value of the \c TEST variable empty when @@ -160,8 +164,8 @@ following lines. However, you can remove a value after you have referred to it on an earlier line. - To temporarily disable a variable, add a hash character (#) to the beginning - of the line. + To add a comment or disable any of the above actions, prefix it with two hash + characters (##). \sa {Specify the environment for projects}, {Configure projects for building}, {Configure projects for running}, {Use Qt Creator variables} diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-overview.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-overview.qdoc index 4ba2e5b393e..2a032dabf75 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-overview.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-overview.qdoc @@ -16,7 +16,7 @@ When you install Qt for a development or target platform, such as Linux, \macos, Windows, Android or QNX, \l{https://www.qt.io/download-qt-installer} - {\QOI} creates \l{glossary-buildandrun-kit}{kits} for the development targets. + {\QOI} creates \l{Kits}{kits} for the development targets. Select the kits to use for a project in the \uicontrol {Configure Projects} view when you open the project for the first time. At least one kit must be @@ -65,7 +65,7 @@ \section1 Specifying Run Settings The run settings to specify depend on the type of the project and on the - \l{kits-tab}{Run device} that you select for the kit. + \l{Kits}{Run device} that you select for the kit. \QC automatically creates deploy and run configurations for your project. @@ -84,7 +84,9 @@ \li \l{Link projects to Axivion dashboards}{Axivion} \li \l{Specify clangd settings}{Clangd} \li \l{Specify Clang tools settings}{Clang Tools} + \li \l{Override CMake settings for a project}{CMake} \li \l{Set Copilot preferences}{Copilot} + \li \l{Configure C++ code model}{C++ Code Model} \li \l{Specify code style}{C++ Code Style} \li \l{Set C++ file naming preferences}{C++ File Naming} \li \l{Specify dependencies}{Dependencies} @@ -94,7 +96,7 @@ \li \l{Link projects with GitLab}{GitLab} \li \l{Configure language server workspace}{Language Server} \li \l{Specify settings for quick fixes}{Quick Fixes} - \li \l{Testing} + \li \l{Apply filters before scanning for tests}{Testing} \li \l{Exclude files from to-do lists}{To-Do} (experimental) \endlist @@ -111,6 +113,7 @@ \previouspage creator-how-tos.html \ingroup creator-how-to-projects-configure + \ingroup creator-how-to-manage-kits \title Activate kits for a project @@ -125,6 +128,9 @@ is not suitable for the project type. To view the warning and error messages, move the mouse pointer over the kit name. + To hide inactive kits from the list, select \uicontrol {Hide Inactive Kits}. + To show them again, select \uicontrol {Show All Kits}. + \section1 Manage kits To modify kit configuration or to \l{Add kits}{add kits} to the list or to @@ -132,7 +138,7 @@ Each kit consists of a set of values that define one environment, such as a \l{glossary-device}{device}, \l{Add compilers}{compiler}, - \l{Add debuggers}{debugger}, and \l{Add Qt versions}{Qt version}, as well + \l{Add debuggers}{Debugging}, and \l{Add Qt versions}{Qt version}, as well as steps for building, deploying, and running applications. To copy the build, deploy, and run steps from another kit, select @@ -174,5 +180,5 @@ might still see them listed for existing projects. You can copy the build, deploy, and run steps from them to other kits. - \sa {Add kits}, {Configuring Projects}, {kits-tab}{Kits} + \sa {Manage Kits}{How To: Manage Kits}, {Configuring Projects}, {Kits} */ 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..9c1463f2d9b 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 @@ -9,12 +9,12 @@ \title Specify Valgrind settings for a project - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that 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/projects/creator-only/creator-projects-settings-run-debug.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-debug.qdoc index 770478d5b66..486b8b8c4c5 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-debug.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-debug.qdoc @@ -10,7 +10,7 @@ \title Enable debugging - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. @@ -30,7 +30,7 @@ \list \li \l{Adding Custom Debugging Helpers}{Custom debugging helpers} - \li \l{Specifying GDB Settings}{GDB commands} to execute after GDB + \li \l{GDB}{GDB commands} to execute after GDB has started, but before the debugged program is started or attached, and before the debugging helpers are initialized \endlist @@ -42,5 +42,5 @@ {enable QML debugging} either globally or in the \uicontrol {Build Settings} of the project. - \sa {Configuring Projects}, {Debugging} + \sa {Configuring Projects}, {Debugging}, {Debuggers}, {Debugger} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-desktop.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-desktop.qdoc index 72085701e16..35188f5ce94 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-desktop.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run-desktop.qdoc @@ -11,7 +11,7 @@ \brief Settings for running applications on desktop device types. - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run.qdoc index 7f8ba6894b8..f989924d560 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-run.qdoc @@ -16,7 +16,7 @@ \title Configure projects for running - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. @@ -27,7 +27,7 @@ \list \li \l {Android Run Settings}{Android} - \li \l {Boot2Qt Run Settings}{Boot2Qt} + \li \l {\B2Q Run Settings}{\B2Q} \li \l {Desktop Device Run Settings}{Desktop} \li \l {Python Run Settings}{Python} \li \l {QNX Run Settings}{QNX} diff --git a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-sharing.qdoc b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-sharing.qdoc index 3e48923ad36..09898e8f56e 100644 --- a/doc/qtcreator/src/projects/creator-only/creator-projects-settings-sharing.qdoc +++ b/doc/qtcreator/src/projects/creator-only/creator-projects-settings-sharing.qdoc @@ -20,7 +20,8 @@ has the same XML structure as a \e {.user} file, but only has the settings to share. - \note Use \l{CMake Presets} to share CMake project settings. + To share CMake project settings, use \l{CMake Presets} or a + \c {CMakeLists.txt.shared} file. \section1 Create a shared settings file @@ -72,5 +73,38 @@ a permanent sticky setting that was created just because you wanted to try something out. + \section1 Share CMake project settings + + The following is an example of a \c {CMakeLists.txt.shared} file: + + \badcode + + + + + ProjectExplorer.Project.PluginSettings + + + false + false + false + false + true + false + false + true + + + + + Version + 22 + + + \endcode + + For more information about the settings, see + \l {Override CMake settings for a project}. + \sa {Configuring Projects}, {CMake Presets} */ diff --git a/doc/qtcreator/src/projects/creator-only/creator-testing-how-to-limit-files-to-path-patterns.qdoc b/doc/qtcreator/src/projects/creator-only/creator-testing-how-to-limit-files-to-path-patterns.qdoc new file mode 100644 index 00000000000..32d58d028dd --- /dev/null +++ b/doc/qtcreator/src/projects/creator-only/creator-testing-how-to-limit-files-to-path-patterns.qdoc @@ -0,0 +1,32 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-limit-files-to-path-patterns.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-test + \ingroup creator-how-to-projects-configure + + \title Apply filters before scanning for tests + + To override testing preferences for the current project: + + \list 1 + \li Go to \uicontrol Projects > \uicontrol {Project Settings} > + \uicontrol {Testing}. + \image qtcreator-projects-settings-testing.webp {Testing settings in Projects mode} + \li Clear \uicontrol {Use global settings} to select the tests to handle + for the project. + \li To automatically run all or selected tests after successfully + building the current project, select \uicontrol All or + \uicontrol Selected in \uicontrol {Automatically run tests after build}. + \li To apply path filters before scanning for tests, select + \uicontrol {Limit Files to Path Patterns}. + \li Select \uicontrol Add to add the filters as wildcard expressions. + \endlist + + To remove the selected filter, select \uicontrol Remove. + + \sa {Test}{How To: Test}, {Test Results}, {Testing} +*/ diff --git a/doc/qtcreator/src/projects/creator-projects-running.qdoc b/doc/qtcreator/src/projects/creator-projects-running.qdoc index 0b39d0d7077..f83a9c00ba7 100644 --- a/doc/qtcreator/src/projects/creator-projects-running.qdoc +++ b/doc/qtcreator/src/projects/creator-projects-running.qdoc @@ -28,7 +28,7 @@ \li Select the \uicontrol {Build and Run Kit Selector} icon or go to \uicontrol Build > \uicontrol {Open Build and Run Kit Selector} to select the - build and run \l{glossary-buildandrun-kit}{kit}. + build and run \l{Kits}{kit}. \image qtcreator-kit-selector.webp {Kit selector} @@ -40,7 +40,7 @@ If you have connected \l{Mobile Platforms}{mobile devices} or \l{Embedded Platforms}{embedded devices} to the computer - or added virtual devices, such as \l{Managing Android Virtual Devices (AVD)} + or added virtual devices, such as \l{Manage AVDs} {Android Virtual Devices (AVD)}, you can select them in the kit selector. Select \uicontrol Manage to manage device settings. For example, you can add diff --git a/doc/qtcreator/src/python/creator-python-development.qdoc b/doc/qtcreator/src/python/creator-python-development.qdoc index d5cd5fe31c9..10f054dcdab 100644 --- a/doc/qtcreator/src/python/creator-python-development.qdoc +++ b/doc/qtcreator/src/python/creator-python-development.qdoc @@ -25,8 +25,8 @@ \li \l{Configure Python language servers} \li \l{Run Python applications} \li \l{Python Run Settings} - \li \l{PDB} - \li \l{Launching the Debugger} + \li \l{PDB versions} + \li \l{Supported Debuggers} \endlist For more information about developing with Qt for Python, including @@ -74,7 +74,7 @@ \section1 Select the Python version - The \l{kits-tab}{kits} you select for the project in \uicontrol Projects > + The \l{Kits}{kits} you select for the project in \uicontrol Projects > \uicontrol {Build & Run} set the Python version to use. The \l {Edit Mode}{Edit mode} toolbar shows the current Python version. diff --git a/doc/qtcreator/src/python/creator-python-run-settings.qdoc b/doc/qtcreator/src/python/creator-python-run-settings.qdoc index 6c6c3b4fe2b..07cf625450d 100644 --- a/doc/qtcreator/src/python/creator-python-run-settings.qdoc +++ b/doc/qtcreator/src/python/creator-python-run-settings.qdoc @@ -31,7 +31,7 @@ \brief Settings for running Qt for Python applications. - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. 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 765ff75c2a2..13b1f216380 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 @@ -69,7 +71,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..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. @@ -59,7 +61,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 diff --git a/doc/qtcreator/src/qnx/creator-deployment-qnx.qdoc b/doc/qtcreator/src/qnx/creator-deployment-qnx.qdoc index 06fcb20abd5..eb68e9e0f82 100644 --- a/doc/qtcreator/src/qnx/creator-deployment-qnx.qdoc +++ b/doc/qtcreator/src/qnx/creator-deployment-qnx.qdoc @@ -9,22 +9,30 @@ // ********************************************************************** /*! - \previouspage creator-deployment-b2qt.html \page creator-deployment-qnx.html - \nextpage creator-deployment-embedded-linux.html - \title Deploying to QNX Neutrino + \previouspage creator-reference.html - You can specify settings for deploying applications to QNX Neutrino + \ingroup creator-reference-deploy-configurations + + \title QNX Neutrino Deploy Configuration + + \brief Copy application files to QNX Neutrino devices. + + Specify settings for deploying applications to QNX Neutrino devices in the project configuration file and in \uicontrol Projects > \uicontrol {Run Settings} > \uicontrol Deployment. \image qtcreator-qnx-deployment.png "Deploy to device" The deployment process is described in more detail in - \l{Deploying to Remote Linux}. + \l{Remote Linux Deploy Configuration}. \section1 Finding Configured Devices The \uicontrol {Check for a configured device} deployment step looks for a device that is ready for deployment. + + \sa {Build and Run}{How To: Build and Run}, {QNX Neutrino}{How To: Develop for QNX}, + {QNX Run Settings}, {Remote Linux Deploy Configuration}, + {Remote Linux Run Settings} */ diff --git a/doc/qtcreator/src/qnx/creator-developing-qnx.qdoc b/doc/qtcreator/src/qnx/creator-developing-qnx.qdoc index d7ec1e64177..f6990187c3d 100644 --- a/doc/qtcreator/src/qnx/creator-developing-qnx.qdoc +++ b/doc/qtcreator/src/qnx/creator-developing-qnx.qdoc @@ -1,32 +1,51 @@ // Copyright (C) 2018 Blackberry -// 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 /*! - \previouspage creator-developing-mcu.html \page creator-developing-qnx.html - \nextpage creator-developing-generic-linux.html + \previouspage creator-how-tos.html - \title Connecting QNX Devices + \ingroup creator-how-to-qnx - You can connect QNX devices to the development PC to deploy, run and debug - applications on them from within \QC. The QNX Neutrino RTOS has additional + \title Add a QNX Neutrino device + + Create a connection between \QC and a QNX Neutrino device to run, debug, and + analyze applications on the device. The QNX Neutrino RTOS has additional command-line tools and services, as described in \l {Qt for QNX}. - \note In Qt 6, \QC support for QNX is considered experimental. + \image qtcreator-devices-qnx.webp {QNX device preferences} + \caption QNX device preferences - \section1 Adding a QNX Neutrino Device in \QC + \include qtcreator-add-linux-device.qdocinc {add linux device} {QNX Device} - Adding a QNX Neutrino device is very similar to - \l{Connecting Remote Linux Devices}, except that - you need to select \uicontrol {QNX Device} in the - \uicontrol {Device Configuration} wizard. - - \section1 Add kits for QNX Devices - - To view QNX device settings, select \preferences > - \uicontrol Devices > \uicontrol QNX. Select the \uicontrol {Generate kits} - check box to allow \QC to generate kits for QNX development. - - \sa {Add kits} + \sa {QNX Neutrino}{How To: Develop for QNX}, + {Remote Linux}{How To: Develop for remote Linux}, + {Manage Kits}{How To: Manage Kits} +*/ + +/*! + \page creator-how-to-create-qnx-kits.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-qnx + + \title Create kits for QNX Neutrino devices + + To generate a build and run \l {Kits}{kit} for QNX Neutrino devices: + + \list 1 + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices. + \li Select \uicontrol Add > \uicontrol {QNX Device} > + \uicontrol {Start Wizard} to add a QNX Neutrino device. + \li Select \uicontrol Apply to fetch the information needed for + creating kits. + \li Go to \preferences > \uicontrol Devices > \uicontrol QNX. + \li Select \uicontrol {Create Kit} to create a kit for a particular + platform. + \image qtcreator-preferences-qnx.webp {QNX Preferences} + \li Activate the kit for your project. + \endlist + + \sa {QNX Neutrino}{How To: Develop for QNX}, {Activate kits for a project} */ diff --git a/doc/qtcreator/src/qnx/creator-projects-how-to-run-qnx.qdoc b/doc/qtcreator/src/qnx/creator-projects-how-to-run-qnx.qdoc index 364ee316bcc..13fc502533e 100644 --- a/doc/qtcreator/src/qnx/creator-projects-how-to-run-qnx.qdoc +++ b/doc/qtcreator/src/qnx/creator-projects-how-to-run-qnx.qdoc @@ -5,20 +5,22 @@ \page creator-how-to-run-on-qnx.html \previouspage creator-how-tos.html - \ingroup creator-how-to-run + \ingroup creator-how-to-qnx \title Run on QNX devices To build an application and run it on a device: \list 1 - \li Connect the device to the computer or to the Wi-Fi network. - \li Configure the device and specify a connection to it. + \li Connect the device to the computer or to a network. + \li Go to \preferences > \uicontrol Devices > \uicontrol Devices, + and add a QNX device. + \image qtcreator-devices-qnx.webp {QNX device preferences} \li Make sure that your kit has your QNX device set. \li Select \inlineimage icons/run_small.png (\uicontrol Run). \endlist - \QC uses the compiler specified in the QNX tool chain to build the + \QC uses the compiler specified in the QNX toolchain to build the application. \note Debugging is currently only fully supported on Linux and \macos. @@ -32,7 +34,7 @@ \section2 Debug output cannot be shown - For the command-line output to show up in the \uicontrol{Application Output}, + For the command-line output to show up in \l {Application Output}, \QC has to create an SSH connection to the device. This is only possible if QNX Momentics is not running, and the SSH key configured for the device is a 4096-bit key. @@ -48,6 +50,6 @@ \c printf, \c ps, \c read, \c sed, \c sleep, \c uname, \c slog2info, and \c cat. - \sa {Connecting QNX Devices}, {Run on many platforms}, {Compilers}, - {Embedded Platforms}, {kit-preferences}{Kits} + \sa {QNX Neutrino}{How To: Develop for QNX}, {Run on many platforms}, + {Compilers}, {kit-preferences}{Kits} */ diff --git a/doc/qtcreator/src/qnx/creator-projects-settings-run-qnx.qdoc b/doc/qtcreator/src/qnx/creator-projects-settings-run-qnx.qdoc index c3fd8861c07..edd78c0a193 100644 --- a/doc/qtcreator/src/qnx/creator-projects-settings-run-qnx.qdoc +++ b/doc/qtcreator/src/qnx/creator-projects-settings-run-qnx.qdoc @@ -11,17 +11,18 @@ \brief Settings for running applications on Linux-based devices. - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. - To run and debug an application on a QNX device, you must - create connections from the development PC to the device. Select - \uicontrol {Manage device configurations} to create a connection. + To run and debug an application on a QNX device, select + \uicontrol {Manage device configurations} to create a + connection between \QC and the device. Settings for QNX Neutrino devices are very similar to those for remote linux devices. - \sa {Remote Linux Run Settings}, {Activate kits for a project}, - {Configure projects for running}, {kits-tab}{Kits}, {Connecting QNX Devices} + \sa {QNX Neutrino}{How To: Develop for QNX}, {Manage Kits}{How To: Manage Kits}, + {Remote Linux Run Settings}, {Configure projects for running}, + {kits-tab}{Kits} */ diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index 4c6f0c4cb57..5235ec0217b 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -13,81 +13,17 @@ {Qt documentation} portal or in the \l {Get help}{Help} mode. \list - \li \l{Developing with \QC} - \list - \li \l{Getting Started} - \list - \li \l{User Interface} - \li \l{Configuring Qt Creator} - \endlist - \li \l{Creating Projects} - \li \l{Configuring Projects} - \li \l{Validating with Target Hardware} + \li \l{Installation} + \li \l{Getting Started} \list - \li \l{Previewing on Desktop} - \li \l{Previewing on Devices} - \li \l{Previewing in Browsers} + \li \l{Overview} + \li \l{User Interface} + \li \l{Configuring Qt Creator} \endlist - \li \l{Deploying to Devices} - \list - \li \l{Deploying to Android} - \li \l{Deploying to Boot2Qt} - \li \l{Deploying to QNX Neutrino} - \li \l{Deploying to Remote Linux} - \endlist - \li \l{Connecting Devices} - \list - \li \l{Connecting Android Devices} - \li \l{Connecting Bare Metal Devices} - \li \l{Connecting Boot2Qt Devices} - \li \l{Adding Docker Devices} - \li \l{Connecting iOS Devices} - \li \l{Connecting QNX Devices} - \li \l{Connecting Remote Linux Devices} - \li \l{Building Applications for the Web} - \endlist - \li \l{Debugging} - \list - \li \l{Setting Up Debugger} - \li \l{Launching the Debugger} - \li \l{Debug Mode Views} - \list - \li \l{Viewing Call Stack Trace} - \li \l{Setting Breakpoints} - \li \l{Viewing Threads} - \li \l{Viewing Modules} - \li \l{Viewing Source Files} - \li \l{Local Variables and Function Parameters} - \li \l{Evaluating Expressions} - \li \l{Viewing and Editing Register State} - \li \l{Debugger Log} - \li \l{Viewing Disassembled Code} - \endlist - \li \l{Stopping Applications} - \li \l{Examining Data} - \li \l{Remote Debugging} - \li \l{Debugger Preferences} - \li \l{Using Debugging Helpers} - \li \l{Debugging Qt Quick Projects} - \li \l{Troubleshooting Debugger} - \endlist - \li \l{Analyzing Code} - \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} - \li \l{Visualizing Chrome Trace Events} - \endlist - \li \l{Using Squish} - \endlist + \li \l{Creating Projects} + \li \l{Configuring Projects} + \li \l{Debugging} + \li \l{Analyzing Code} \li \l{Tutorials} \generatelist creator-tutorials \li \l{How To} @@ -110,8 +46,24 @@ \generatelist creator-how-to-design \li Develop for Devices \list + \li Android + \generatelist creator-how-to-android + \li Bare Metal + \generatelist creator-how-to-bare-metal + \li \B2Q + \generatelist creator-how-to-b2qt + \li Docker + \generatelist creator-how-to-docker + \li iOS + \generatelist creator-how-to-ios \li MCUs \generatelist creator-how-to-mcu + \li QNX Neutrino + \generatelist creator-how-to-qnx + \li Remote Linux + \generatelist creator-how-to-remote-linux + \li WebAssembly + \generatelist creator-how-to-webassembly \endlist \li Edit Code \generatelist creator-how-to-edit @@ -147,6 +99,8 @@ \li \l{Reference} \generatelist creator-reference \list + \li Analyzers + \generatelist creator-reference-analyzer \li Build Systems \generatelist creator-reference-build-systems \list @@ -156,9 +110,17 @@ \li Devices \generatelist creator-reference-devices \list + \li Deploy Configurations + \generatelist creator-reference-deploy-configurations \li Run Configurations \generatelist creator-reference-run-configurations \endlist + \li Debugger + \generatelist creator-reference-debugger + \list + \li Debugger Views + \generatelist creator-reference-debugger-views + \endlist \li Editors \generatelist creator-reference-editors \li Platforms diff --git a/doc/qtcreator/src/qtcreator.qdoc b/doc/qtcreator/src/qtcreator.qdoc index cc3352dd108..47623561e52 100644 --- a/doc/qtcreator/src/qtcreator.qdoc +++ b/doc/qtcreator/src/qtcreator.qdoc @@ -1,77 +1,95 @@ -// 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 -// ********************************************************************** -// 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. -// ********************************************************************** - /*! \page index.html - \nextpage creator-overview.html + \nextpage creator-how-to-install.html - \title Qt Creator Manual + \keyword {Qt Creator Manual} + \title Qt Creator Documentation - \QC is a cross-platform, complete integrated development environment - (IDE) that you can use to create applications for - \l{Desktop Platforms}{desktop}, \l {Embedded Platforms}{embedded}, and - \l{Mobile Platforms}{mobile device} platforms, such as \l Android and - \l iOS. It is available for \l Linux, \l \macos and \l Windows - operating systems. For more information, see \l{Supported Platforms}. + \raw HTML + + \endraw - In addition, you can use the experimental - \l{Building Applications for the Web}{WebAssembly plugin} - to build applications in web format and run them in web - browsers. - - \table + \div {class="main-navigation"} + \table borderless 100% \row - \li {4,1} \b {\l{All Topics}} + \li \inlineimage icons/installation.png + \li \inlineimage icons/getting-started.png + \li \inlineimage icons/tutorials.png \row - \li \inlineimage front-gs.png - \li \inlineimage front-coding.png - \li \inlineimage front-help.png - \li \inlineimage front-advanced.png - \row - \li \b {\l{Developing with \QC}} - \list - \li \l{Getting Started} - \li \l{Creating Projects} - \li \l{Configuring Projects} - \li \l{Validating with Target Hardware} - \li \l{Connecting Devices} - \li \l{Deploying to Devices} - \li \l{Debugging} - \li \l{Analyzing Code} - \li \l{Using Squish} - \endlist - \li \b {\l{Tutorials}} - \generatelist creator-tutorials - \li \b {\l{How To}} - \list - \li \l{Analyze} - \li \l{Build and Run} - \li \l{Debug} - \li \l{Design UIs} - \li \l{Edit Code} - \li \l{Manage Projects} - \li \l{Read Documentation} - \li \l{Test} - \li \l{Use \QC} - \li \l{Use the UI} - \endlist - \li \b {\l{Reference}} - \list - \li \l {Acknowledgements} - \li \l {Build Systems} - \li \l {Command-Line Options} - \li \l {Custom Wizards} - \li \l {Keyboard Shortcuts} - \li \l {Preferences} - \li \l {Supported Platforms} - \li \l {Version Control Systems} - \li \l {Views} - \endlist + \li \b {INSTALLATION} + + Install either a \e commercial or \e {open source} version of \QC + with \QOI or as a stand-alone tool on Linux, \macos, or Windows. + + \l {Installation} + \li \b {GETTING STARTED} + + Learn about the \QC features and UI, as well as how you can make + \QC behave more like your favorite code editor or IDE. + + \l{Getting Started} + \li \b {TUTORIALS} + + Follow the tutorials to create basic Qt applications for the + desktop and mobile devices by using Qt Widgets and Qt Quick. + + \l{Tutorials} \endtable + \enddiv + + \section1 About + + Use the \QC cross-platform, complete integrated development environment + (IDE) to create applications for \l{Desktop Platforms}{desktop}, + \l {Embedded Platforms}{embedded}, and \l{Mobile Platforms}{mobile device} + platforms, such as \l Android and \l iOS. Also, you can build applications + in web format and run them in web browsers with + \l{Build applications for the web}{Qt for WebAssembly}. + + \b {HOW TO} + + \raw HTML + + \endraw + + \div {class="link-list"} + \table 100% + \row + \li \inlineimage icons/demo-32x32.png + \li \inlineimage icons/build-32x32.png + \li \inlineimage icons/settings-32x32.png + \row + \li Work with Code + \list + \li \l{Edit Code} + \li \l{Debug} + \li \l{Analyze} + \li \l{Test} + \endlist + \li Build and Run Applications + \list + \li \l{Manage Projects} + \li \l{Manage Kits} + \li \l{Build and Run} + \li \l{Develop for Devices} + \endlist + \li Use Tools and Extensions + \list + \li \l{Use \QC} + \li \l{Use the UI} + \li \l{Design UIs} + \li \l{Create Models and Diagrams} + \li \l{Read Documentation} + \endlist + \endtable + \enddiv */ diff --git a/doc/qtcreator/src/qtquick/creator-only/creator-mobile-app-tutorial.qdoc b/doc/qtcreator/src/qtquick/creator-only/creator-mobile-app-tutorial.qdoc index f06917784bc..b6f01f38a59 100644 --- a/doc/qtcreator/src/qtquick/creator-only/creator-mobile-app-tutorial.qdoc +++ b/doc/qtcreator/src/qtquick/creator-only/creator-mobile-app-tutorial.qdoc @@ -32,12 +32,12 @@ To develop for Android devices, you must install \l{Qt for Android} and set up the development environment, as instructed in - \l{Connecting Android Devices}. + \l{Developing for Android}. To develop for iOS devices, you must install Xcode and use it to configure a device. For this, you need an Apple developer account and iOS Developer Program certificate that you receive from Apple. For more information, see - \l{Connecting iOS Devices}. + \l{Developing for iOS}. \include qtquick-tutorial-create-empty-project.qdocinc qtquick empty application diff --git a/doc/qtcreator/src/qtquick/creator-only/creator-projects-settings-run-qtquick.qdoc b/doc/qtcreator/src/qtquick/creator-only/creator-projects-settings-run-qtquick.qdoc index 3f2ee989012..1d7be468c7b 100644 --- a/doc/qtcreator/src/qtquick/creator-only/creator-projects-settings-run-qtquick.qdoc +++ b/doc/qtcreator/src/qtquick/creator-only/creator-projects-settings-run-qtquick.qdoc @@ -11,11 +11,11 @@ \brief Settings for running Qt Quick UI Prototype projects (.qmlproject). - Specify settings for running applications on the \l {kits-tab}{Run device} that + Specify settings for running applications on the \l {Kits}{Run device} that you select for a kit in \uicontrol Projects > \uicontrol {Build & Run} > \uicontrol Run > \uicontrol {Run Settings}. - \note Select the \uicontrol Desktop device type for the \l{kits-tab}{Run device} + \note Select the \uicontrol Desktop device type for the \l{Kits}{Run device} in the kit. \image qtquick-ui-prototype-run-settings.webp {Run Settings for a Qt Quick UI Prototype project} @@ -42,5 +42,5 @@ \endtable \sa {Create Qt Quick UI Prototypes}, {Activate kits for a project}, - {Configure projects for running}, {kits-tab}{Kits} + {Configure projects for running}, {Kits} */ diff --git a/doc/qtcreator/src/qtquick/creator-only/qt-design-viewer.qdoc b/doc/qtcreator/src/qtquick/creator-only/qt-design-viewer.qdoc index 8ff40ec941f..58e3e900ba9 100644 --- a/doc/qtcreator/src/qtquick/creator-only/qt-design-viewer.qdoc +++ b/doc/qtcreator/src/qtquick/creator-only/qt-design-viewer.qdoc @@ -1,27 +1,25 @@ -// Copyright (C) 2019 The Qt Company Ltd. +// Copyright (C) 2024 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! \page qt-design-viewer.html - \previouspage creator-live-preview-devices.html - \nextpage creator-building-targets.html + \previouspage creator-how-tos.html - \title Previewing in Browsers + \ingroup creator-how-to-design + + \title Preview UI prototypes in browsers \image qt-design-viewer.png - \QDV is a QML viewer that runs in your web browser. This means that you can - run applications in most widely-used web browsers, such as Apple Safari, - Google Chrome, Microsoft Edge, and Mozilla Firefox, on the desktop and on - mobile devices. + Run Qt Quick UI Prototype projects in web browsers, such as Apple Safari, + Google Chrome, Microsoft Edge, and Mozilla Firefox, with \QDV. The startup and compilation time depend on your browser and configuration. - However, the actual performance of the application once started is - indistinguishable from the same application running on the desktop. + Once started, the application performs the same as when running on the + desktop. - You can run Qt Quick UI Prototype projects, which - have a .qmlproject file that defines the main QML file and the import paths. - Compress the project folder into a ZIP file that you upload to \QDV. + The .qmlproject configuration file defines the main QML file and the import + paths. Compress the project folder into a ZIP file that you upload to \QDV. The loaded applications remain locally in your browser. No data is uploaded into the cloud. @@ -30,11 +28,12 @@ \list 1 \li In the browser, open \l{ https://designviewer.qt.io/}{\QDV}. - \li Drag and drop your application package to \QDV, or click the load + \li Drag your application package to \QDV, or select the load icon to browse for your file. \endlist Your application is compiled and run on \QDV. - \sa {Create Qt Quick UI Prototypes} + \sa {Create Qt Quick UI Prototypes}, {Design UIs}{How To: Design UIs}, + {UI Design} */ diff --git a/doc/qtcreator/src/qtquick/creator-only/qtquick-creating.qdoc b/doc/qtcreator/src/qtquick/creator-only/qtquick-creating.qdoc index 0ff290f0d0d..f7181c59cf1 100644 --- a/doc/qtcreator/src/qtquick/creator-only/qtquick-creating.qdoc +++ b/doc/qtcreator/src/qtquick/creator-only/qtquick-creating.qdoc @@ -76,12 +76,12 @@ \li Select \uicontrol Next to open the \uicontrol {Kit Selection} dialog. - \li Select \l{glossary-buildandrun-kit}{kits} for the platforms that + \li Select \l{Kits}{kits} for the platforms that you want to build the application for. \note Kits are listed if they have been specified in \preferences > \uicontrol Kits. - For more information, see \l {Add kits} and \l {kits-tab}{Kits}. + For more information, see \l {Add kits} and \l {Kits}. \li Select \uicontrol Next to open the \uicontrol {Project Management} dialog. @@ -149,8 +149,7 @@ imports that are used in the QML files. You can add imports later to combine Qt Quick basic types with - Qt Quick Controls, Qt Quick Dialogs, and Qt Quick Layouts (available - since Qt 5.1). + Qt Quick Controls, Qt Quick Dialogs, and Qt Quick Layouts. \li Select the \uicontrol {Use Qt Virtual Keyboard} check box to add support for \l{Qt Virtual Keyboard} to the application. @@ -162,12 +161,11 @@ \li Select \uicontrol Next to open the \uicontrol {Kit Selection} dialog. - \li Select \l{glossary-buildandrun-kit}{kits} for the platforms that + \li Select \l{Kits}{kits} for the platforms that you want to build the application for. \note Kits are listed if they have been specified in \preferences > \uicontrol Kits. - For more information, see \l {Add kits} and \l {kits-tab}{Kits}. \li Select \uicontrol Next to open the \uicontrol {Project Management} dialog. @@ -198,5 +196,6 @@ To use JavaScript and image files in the application, copy them to the project folder. - \sa {Create Qt Quick Applications}, {Creating Projects} + \sa {Create Qt Quick Applications}, {Manage Kits}{How To: Manage Kits}, + {Creating Projects} */ diff --git a/doc/qtcreator/src/qtquick/creator-only/qtquick-live-preview-desktop.qdoc b/doc/qtcreator/src/qtquick/creator-only/qtquick-live-preview-desktop.qdoc new file mode 100644 index 00000000000..75a64831c0e --- /dev/null +++ b/doc/qtcreator/src/qtquick/creator-only/qtquick-live-preview-desktop.qdoc @@ -0,0 +1,22 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-live-preview-desktop.html + \previouspage creator-how-tos.html + + \ingroup creator-how-to-design + + \title Preview a QML file on desktop + + To preview the currently active QML file on the desktop: + + \list + \li Select \inlineimage icons/live-preview.png (\uicontrol {Live Preview}) + on the \l{Edit Mode}{editor} toolbar. + \image qtcreator-live-preview.webp {Application running on top of the editor view} + \li Go to \uicontrol Build > \uicontrol {QML Preview}. + \endlist + + \sa {Design UIs}{How To: Design UIs}, {UI Design} +*/ diff --git a/doc/qtcreator/src/qtquick/creator-only/qtquick-states-scxml.qdocinc b/doc/qtcreator/src/qtquick/creator-only/qtquick-states-scxml.qdocinc deleted file mode 100644 index 1f0fd5a8e01..00000000000 --- a/doc/qtcreator/src/qtquick/creator-only/qtquick-states-scxml.qdocinc +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2020 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! -//! [scxml state machines] - - \section1 Using SCXML State Machines - - To use QML together with an SCXML state machine, add states and - bind them to the state machine in \l {Connection View} > - \uicontrol Backends, as described in \l {Managing C++ Backend Objects}. - - In the \uicontrol States view, you can select \uicontrol Actions > - \uicontrol {Set when Condition} to edit the \c when condition of states - to map QML states to the states of the SCXML state machine. For an example, - see \l {Qt SCXML Traffic Light QML Example (Dynamic)}. - - \image qmldesigner-states-when-condition.png - - If you add animation to the states, you can - \l{Validating with Target Hardware}{preview} - or \l{Run on many platforms}{run} - the application to test the animation. - -//! [scxml state machines] -*/ diff --git a/doc/qtcreator/src/qtquick/creator-only/qtquick-tutorial-create-empty-project.qdocinc b/doc/qtcreator/src/qtquick/creator-only/qtquick-tutorial-create-empty-project.qdocinc index be0c55516a9..22d887c161c 100644 --- a/doc/qtcreator/src/qtquick/creator-only/qtquick-tutorial-create-empty-project.qdocinc +++ b/doc/qtcreator/src/qtquick/creator-only/qtquick-tutorial-create-empty-project.qdocinc @@ -37,14 +37,14 @@ \li Select \uicontrol Next to open the \uicontrol {Kit Selection} dialog. - \li Select Qt 6.4 or later \l{glossary-buildandrun-kit}{kits} for the + \li Select Qt 6.4 or later \l{Kits}{kits} for the platforms that you want to build the application for. To build applications for mobile devices, select kits also for Android and iOS. \note The list shows kits that you specify in \preferences > \uicontrol Kits. - For more information, see \l {Add kits} and \l {kits-tab}{Kits}. + For more information, see \l {Add kits} and \l {Kits}. \li Select \uicontrol Next to open the \uicontrol {Project Management} dialog. diff --git a/doc/qtcreator/src/qtquick/qtquick-live-preview-devices.qdoc b/doc/qtcreator/src/qtquick/qtquick-live-preview-devices.qdoc index 8dcc8c26413..87142f4a511 100644 --- a/doc/qtcreator/src/qtquick/qtquick-live-preview-devices.qdoc +++ b/doc/qtcreator/src/qtquick/qtquick-live-preview-devices.qdoc @@ -1,20 +1,30 @@ -// 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-live-preview-desktop.html \page creator-live-preview-devices.html + \if defined (qtdesignstudio) + \previouspage studio-live-preview-desktop.html \nextpage qt-design-viewer.html \title Previewing on Devices - To preview UIs on Android devices, enable USB debugging on them - and connect them to your system with a USB cable. + \else + \previouspage creator-how-tos.html - To preview UIs on Boot2Qt devices, connect the devices to your - system with a USB cable, or a wired or wireless connection, depending on - the device, and configure connections to them. The necessary kits have been - predefined and you only need to enable them for your current project. + \ingroup creator-how-to-design + + \title Preview Qt Quick UIs on devices + \endif + + To preview a UI on an Android device, turn on USB debugging on the device + and connect it to the computer with a USB cable. + + To preview a UI on a \B2Q device, connect the device to the computer + with a USB cable, or a wired or wireless connection, depending on + the device, and configure a connection to it. The necessary kits have been + predefined, but you need to select the one appropriate for your current + project. \e {Deploy configurations} handle the packaging and copying of the necessary files to a location in a device where you want to run the @@ -27,8 +37,8 @@ \list 1 \if defined(qtcreator) - \li In \uicontrol Projects > \uicontrol {Build & Run}, enable the kit - predefined for the device type (1). + \li Go to \uicontrol Projects > \uicontrol {Build & Run}. + \li Activate the kit predefined for the device type (1). \li Select the kit for the device in the kit selector (2). \image qtcreator-kit-selector-devices.webp {Kit selector} \else @@ -42,36 +52,36 @@ press \key {Alt+P}. \endlist - \section2 Previewing on Android Devices + \section2 On Android \if defined(qtcreator) - The USB debugging feature on Android devices enables creating connections - to the devices from \QDS and running the preview utility on them. + Use the USB debugging feature on an Android device to create a connection + to the device from \QC and run the preview utility on it. Debugging is turned on in different ways on different Android devices. Look for \uicontrol {USB Debugging} under \uicontrol {Developer Options}. - On some devices, \uicontrol {Developer Options} is hidden and becomes visible - when you tap the \uicontrol {Build number} field in \uicontrol Settings > - \uicontrol About several times. + Tap \uicontrol {Build number} in \uicontrol Settings > \uicontrol About + several times to show \uicontrol {Developer Options}. After you turn on debugging, connect the Android device to the system with a USB cable. - The first time you preview a UI on devices, the preview utility - is copied to them. This might take some time. Thereafter, previewing will - get faster because only the UI files need to be copied to the - device. + The first time you preview a UI on a device, the preview utility + is copied to it, which might take some time. Thereafter, previewing + gets faster because only the UI files need to be copied to the device. \else - Preview your \QDS projects with \QUV. It is an application - that runs on your Android device. + Preview \QDS projects with \QUV on an Android device. Learn more about \l{Viewing Applications on Android}. \endif + \section2 On \B2Q - \section2 Previewing on Boot2Qt Devices + Preview a UI on a supported \B2Q device that you configure as + instructed in the \B2Q documentation. - You can preview UIs on supported Boot2Qt devices that you configure as - instructed in the Boot2Qt documentation. + \sa {\B2Q: Documentation}, {Support Levels for Target Hardware} - \sa {Boot2Qt: Documentation}, {Support Levels for Target Hardware} + \if defined(qtcreator) + \sa {Design UIs}{How To: Design UIs}, {UI Design} + \endif */ diff --git a/doc/qtcreator/src/qtquick/qtquick-live-preview.qdoc b/doc/qtcreator/src/qtquick/qtquick-live-preview.qdoc deleted file mode 100644 index 2d2ac0b36b6..00000000000 --- a/doc/qtcreator/src/qtquick/qtquick-live-preview.qdoc +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2024 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only - -/*! - \page creator-live-preview.html - \if defined(qtdesignstudio) - \previouspage quick-states.html - \else - \previouspage creator-building-running.html - \endif - \nextpage creator-live-preview-desktop.html - - \title Validating with Target Hardware - - Preview a UI file or the entire UI on the desktop, as well as on embedded - Linux devices to instantly view the changes you make to the UI. On Android - devices, the preview shows the snapshot of your project from the moment - you start the preview on the device, not your changes. - - \if defined(qtcreator) - \image qtcreator-live-preview.webp {Application running on top of the editor} - \else - \image studio-live-preview.webp - \endif - - Or, use \QDV to run - \if defined(qtcreator) - \l{Create Qt Quick UI Prototypes}{Qt Quick UI projects} - \else - applications - \endif - in most widely-used web browsers on the desktop and in mobile devices and - share your designs with reviewers who don't have \QC. - - \list - \li \l{Previewing on Desktop} - - Preview individual QML files or the whole UI. - \li \l{Previewing on Devices} - - \if defined(qtcreator) - Preview Qt Quick applications on devices that you - connect to the development PC. For more information, see - \l {Connecting Devices}. - \else - When you install \QDS, everything you need for previewing on - devices is set up automatically. You only need to connect your - devices to your system. - \endif - - \if defined(qtdesignstudio) - \li \l{Sharing Applications Online} - - Share applications online and view them in a web browser. - - \li \l{Viewing Applications on Android} - - Preview your \QDS projects with \QUV. It is an application - that runs on your Android device. - \else - \li \l{Previewing in Browsers} - - Open \l{https://designviewer.qt.io/}{\QDV} - in a browser and load applications to it. - \endif - \endlist -*/ diff --git a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc b/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc index 9c74f946f38..eb74c5b547d 100644 --- a/doc/qtcreator/src/qtquick/qtquick-profiler.qdoc +++ b/doc/qtcreator/src/qtquick/qtquick-profiler.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 // ********************************************************************** @@ -7,31 +7,175 @@ // Run the fixnavi.pl script to adjust the links to the index order. // ********************************************************************** +/*! + \page creator-how-to-profile-qml.html + \if defined(qtdesignstudio) + \previouspage creator-qml-performance-monitor.html + \nextpage studio-advanced.html + \else + \previouspage creator-how-tos.html + \endif + + \ingroup creator-how-to-analyze + + \title Profile QML applications + + With QML Profiler, you can find causes for typical performance problems + in your applications, such as slowness and unresponsive, stuttering user + interfaces. + + \if defined(qtdesignstudio) + \note In this section, you are using advanced menu items. These are not + visible by default. To toggle the visibility of advanced menu items, see + \l{Customizing the Menu Bar}. + \endif + + + To collect data about a QML application: + + \list 1 + \li Set up QML debugging for the project. For more information, see + \l{Setting Up QML Debugging}. + \if defined(qtcreator) + \li In the \uicontrol Projects mode, select a \l{Kits} + {kit} with Qt version 4.7.4 or later. + \endif + \note To profile applications on \l{glossary-device}{devices}, you + must install Qt libraries on them. + \li Go to \uicontrol Analyze > \uicontrol {QML Profiler} to profile the + current application. + \image qtcreator-qml-profiler-toolbar.webp {QML Profiler} + \li Select \inlineimage icons/qtcreator-analyze-start-button.png + (\uicontrol Start) to start the application from QML Profiler. + \endlist + + QML Profiler immediately begins to collect data, as indicated by + the time running in the \uicontrol Elapsed field. + + \note If data collection does not start automatically, select + \inlineimage icons/recordfill.png (\uicontrol {Enable Profiling}). + + Data is collected until you select \inlineimage icons/recordfill.png again. + Data collection takes time, so expect a delay before seeing data. + + Do not use application commands to exit the application because data is + sent to QML Profiler when you select \inlineimage icons/recordfill.png. + The application stops in seconds. If you exit the application, the data is + not sent. + + Select \uicontrol {Disable Profiling} to disable the automatic start of the + data collection when an application is launched. Data collection starts when + you select the button again. + + To save all the collected data, select \uicontrol Analyze > + \uicontrol {QML Profiler Options} > \uicontrol {Save QML Trace}. To view the saved + data, select \uicontrol {Load QML Trace}. You can also deliver the saved data to + others for examination or load data saved by them. + + \section1 Flush data while profiling + + Set data flushing preferences either globally for all projects or separately + for each project. + + To set global preferences, go to \preferences > + \uicontrol Analyzer > \uicontrol {QML Profiler}. + + To specify custom QML Profiler settings for a particular project: + + \list 1 + \li Go to \uicontrol Projects > \uicontrol Run. + \li In \uicontrol {QML Profiler Settings}, select \uicontrol Custom. + \image qml-profiler-settings.png {QML Profiler Settings} + \endlist + + You can set the following preferences: + + \table + \header + \li Setting + \li Value + \row + \li \uicontrol {Flush data while profiling} + \li Flush the data periodically instead of flushing all data when + profiling stops. This saves memory on the target device and shortens + the wait between the profiling being stopped and the data + being displayed. + \row + \li \uicontrol {Flush interval} + \li Set the flush interval in + milliseconds. The shorter the interval, the more often the + data is flushed. The longer the interval, the more data has + to be buffered in the target application, potentially wasting + memory. However, the flushing itself takes time, which can + distort the profiling results. + \row + \li \uicontrol {Process data only when process ends} + \li Aggregate data from many QML engines into one trace. Otherwise, + the profiling stops when one of the engines stops. + \endtable + + To restore the global settings for the project, select + \uicontrol {Restore Global}. + + \section1 Attach to a running Qt Quick application + + You can profile a Qt Quick application that you do not run from \QC. + However, you must enable QML debugging and profiling for the application + in the project build settings. For more information, see + \l{Setting Up QML Debugging}. + + To attach to a waiting application: + + \list 1 + \li Go to \uicontrol Analyze > + \uicontrol {QML Profiler (Attach to Waiting Application)}. + \image qml-profiler-start-dialog.png {Start QML Profiler dialog} + \li In \uicontrol Kit, select the kit used to build the application. + \li In \uicontrol Port, specify the port to listen to. + \li Select \uicontrol OK. + \endlist + + \sa {Profiling QML applications} + + \if defined(qtcreator) + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code} + \endif +*/ + /*! \page creator-qml-performance-monitor.html \if defined(qtdesignstudio) \previouspage creator-qml-debugging-example.html - \nextpage studio-advanced.html + \nextpage creator-how-to-profile-qml.html \else - \previouspage creator-analyze-mode.html - \nextpage creator-coco.html + \previouspage creator-reference.html \endif + \ingroup creator-reference-analyzer + \title Profiling QML Applications - You can use the QML Profiler to find causes for typical performance problems + \brief Improve the performance of QML applications. + + \if defined(qtdesignstudio) + \note In this section, you are using advanced menu items. These are not + visible by default. To toggle the visibility of advanced menu items, see + \l{Customizing the Menu}. + \endif + + With QML Profiler, you can 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 frames. All JavaScript must return before the GUI thread can proceed, and frames are delayed or dropped if the GUI thread is not ready. - Another typical cause for similar performance problems is creating, - painting, or updating invisible items, which takes time in the GUI thread. + Another typical cause for similar performance problems is creating or + updating invisible items, which takes time in the GUI thread. \if defined(qtcreator) Triggering long-running C++ functions, such as paint methods and signal handlers, also takes time in the GUI thread, but is more difficult to see in - the QML Profiler because it does not profile C++ code. + QML Profiler because it does not profile C++ code. \endif To find excessive use of JavaScript, check the frame rate in animations and @@ -49,124 +193,15 @@ \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 - 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 - \if defined(qtdesignstudio) - \note In this section, you are using advanced menu items. These are not - visible by default. To toggle the visibility of advanced menu items, see - \l{Customizing the Menu Bar}. - \endif - - \section1 Using QML Profiler - - To monitor the performance of an application in the QML Profiler: - - \list 1 - - \li To be able to profile an application, you must set up QML debugging - for the project. For more information, see - \l{Setting Up QML Debugging}. - - \if defined(qtcreator) - \li In the \uicontrol Projects mode, select a \l{glossary-buildandrun-kit} - {kit} with Qt version 4.7.4 or later. - \endif - - \note To profile applications on \l{glossary-device}{devices}, you - must install Qt libraries on them. - - \li Select \uicontrol Analyze > \uicontrol {QML Profiler} to profile the - current application. - - \li Select the - \inlineimage icons/qtcreator-analyze-start-button.png - (\uicontrol Start) button to start the application from the - QML Profiler. - - \note If data collection does not start automatically, select the - \inlineimage icons/recordfill.png - (\uicontrol {Enable Profiling}) button. - - \endlist - - When you start analyzing an application, the application is launched, and - the QML Profiler immediately begins to collect data. This is indicated by - the time running in the \uicontrol Elapsed field. - - Data is collected until you select the \uicontrol {Enable Profiling} button. Data - collection - takes time, and therefore, there might be a delay - before the data is displayed. - - Do not use application commands to exit the application because data is - sent to the QML Profiler when you select the \uicontrol {Enable Profiling} button. - The application continues to run for some seconds, after which it is stopped - automatically. If you exit the application, the data is not sent. - - Select the \uicontrol {Disable Profiling} button to disable the automatic - start of the data collection when an - application is launched. Data collection starts when you select the button - again. - - To save all the collected data, select \uicontrol Analyze > - \uicontrol {QML Profiler Options} > \uicontrol {Save QML Trace}. To view the saved - data, select \uicontrol {Load QML Trace}. You can also deliver the saved data to - others for examination or load data saved by them. - - \section1 Specifying Flushing Settings - - You can specify flushing settings for the QML Profiler either globally for - all projects or separately for each project. To specify global settings, - select \preferences > \uicontrol Analyzer. - - To specify custom QML Profiler settings for a particular project, select - \uicontrol Projects > \uicontrol Run and then select \uicontrol Custom in - \uicontrol {QML Profiler Settings}. To restore the global settings for the - project, select \uicontrol {Restore Global}. - - \image qml-profiler-settings.png "QML Profiler Settings" - - Select the \uicontrol {Flush data while profiling} check box to flush the - data periodically instead of flushing all data when profiling stops. This - saves memory on the target device and shortens the wait between the - profiling being stopped and the data being displayed. - - In the \uicontrol {Flush interval} field, set the flush interval in - milliseconds. The shorter the interval, the more often the data is flushed. - The longer the interval, the more data has to be buffered in the target - application, potentially wasting memory. However, the flushing itself takes - time, which can distort the profiling results. - - If you have multiple QML engines and you want to aggregate the data produced - by all of them into one trace, select the \uicontrol {Process data only when - process ends} check box. Otherwise, the profiling stops when one of the - engines stops. - - \section1 Attaching to Running Qt Quick Applications - - You can profile Qt Quick applications that are not launched by \QC. - However, you must enable QML debugging and profiling for the application - in the project build settings. For more information, see - \l{Setting Up QML Debugging}. - - To attach to waiting applications: - - \list 1 - \li Select \uicontrol Analyze > - \uicontrol {QML Profiler (Attach to Waiting Application)}. - \image qml-profiler-start-dialog.png "Start QML Profiler dialog" - \li In \uicontrol Kit, select the kit used to build the application. - \li In \uicontrol Port, specify the port to listen to. - \li Select \uicontrol OK. - \endlist - \section1 Analyzing Collected Data The \uicontrol Timeline view displays graphical representations of QML and @@ -177,16 +212,16 @@ Each row in the timeline (6) describes a type of QML events that were recorded. Move the cursor on an event on a row to see how long it takes and where in the source it is being called. 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 (10) summarizes the period for which data was collected. Drag the zoom range (8) 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 (9). To reset + Select \uicontrol {Show Zoom Slider} (2) to open a slider that sets the zoom + level. You can also drag the zoom handles (9). To reset the default zoom level, right-click the timeline to open the context menu, and select \uicontrol {Reset Zoom}. @@ -194,16 +229,16 @@ \section2 Selecting Event Ranges - You can select an event range (7) to view the frame rate of events and to - compare it with the frame rate of similar events. Select the - \uicontrol {Select Range} button (3) to activate the selection tool. Then click in + Select an event range (7) to view the frame rate of events and to + compare it with the frame rate of similar events. 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. The length of the range indicates the frame rate of the event. - You can 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 between the + To measure delays between two subsequent events, place an event range between + the end of the first event and the beginning of the second event. The + \uicontrol Duration field displays the delay between the events in milliseconds. To zoom into an event range, double-click it. @@ -222,37 +257,28 @@ they include location in source code, duration and some relevant parts of the source code itself. - You can click on an event to move the cursor in the code editor to the part + Select an event to move the cursor in the code editor to the part of the code the event is associated with. The following types of events are displayed in the timeline view on one or - several rows. The availability of event types depends on the version of Qt - the application was compiled with and the version of Qt Quick it is using. + several rows. \table \header \li Event Category \li Description - \li Minimum Qt Version - \li Qt Quick Version - \row \li \uicontrol {Pixmap Cache} \li Displays the general amount of pixmap data cached, in pixels. In addition, displays a separate event for each picture being loaded, with specifics about its file name and size. - \li Qt 5.1 - \li Qt Quick 2 \row \li \uicontrol {Scene Graph} \li Displays the time when scene graph frames are rendered and some additional timing information for the various stages executed to do so. - \li Qt 5.1 - \li Qt Quick 2 - \row \li \uicontrol {Memory Usage} \li Displays block allocations of the JavaScript memory manager. @@ -265,98 +291,64 @@ The second row displays the actual usage of the allocated memory. This is the amount of JavaScript heap the application has actually requested. - \li Qt 5.4 - \li Qt Quick 2 - \row \li \uicontrol {Input Events} \li Displays mouse and keyboard events. - \li Qt 4.7.4 - \li Qt Quick 1 or Qt Quick 2 - \row \li \uicontrol Painting - \li Displays the time spent painting the scene for each frame. - \li Qt 4.7.4 - \li Qt Quick 1 - + \li Not used. \row \li \uicontrol Animations \li Displays the amount of animations that are active and the frame rate that they are running at. - Information about render thread animations is displayed for - applications that are built with Qt 5.3 or later. Render thread - animations are shown in a separate row then. - \li Qt 5.0 (Qt 5.3) - \li Qt Quick 2 - + Render thread animations are shown on a separate row. \row \li \uicontrol Compiling \li Displays the time spent compiling the QML files. - \li Qt 4.7.4 - \li Qt Quick 1 or Qt Quick 2 - \row \li \uicontrol Creating - \li Displays the time spent creating the elements in the scene. In Qt - Quick 2, creation of elements takes place in two stages. The first + \li Displays the time spent creating the elements in the scene. + The creation of elements takes place in two stages. The first stage is for the creation of the data structures, including child elements. The second stage represents the completion callbacks. Not all elements trigger completion callbacks, though. The stages are shown as separate events in the timeline. - For Qt Quick 2 applications compiled with versions of Qt before - 5.2.1 only the creation of top-level elements is shown, as single - events. - \li Qt 4.7.4 (Qt 5.2.1) - \li Qt Quick 1 or Qt Quick 2 - \row \li \uicontrol Binding \li Displays the time when a binding is evaluated and how long the evaluation takes. - \li Qt 4.7.4 - \li Qt Quick 1 or Qt Quick 2 - \row \li \uicontrol {Handling Signal} \li Displays the time when a signal is handled and how long the handling takes. - \li Qt 4.7.4 - \li Qt Quick 1 or Qt Quick 2 - \row \li \uicontrol JavaScript \li Displays the time spent executing the actual JavaScript behind bindings and signal handlers. It lists all the JavaScript functions you may be using to evaluate bindings or handle signals. - \li Qt 5.3 - \li Qt Quick 2 - \row \li \uicontrol Quick3D \li Displays the time spent rendering Qt Quick 3D frames, timing information for frame preparation and synchronization, particle system update times and particle update count, as well as texture and mesh memory allocations and memory consumption. - \li Qt 6.3 - \li Qt Quick 3D + This event type is available since Qt 6.3. \endtable \section2 Analyzing Scene Graph Events - In order to understand the scene graph category, it's important to - understand how the Qt Quick scene graph works. See - \l {Qt Quick Scene Graph} and \l {Qt Quick Scene Graph Default Renderer} - for a detailed description. The following events are reported in the + To understand the scene graph category, read more about how + Qt Quick scene graph works in \l {Qt Quick Scene Graph} and + \l {Qt Quick Scene Graph Default Renderer}. The following events are reported in the \uicontrol {Scene Graph} category. Not all events are generated by all render loops. In the Windows and Basic render loops everything runs in the same thread and the distinction between GUI thread and render thread is meaningless. - If you set the environment variable QSG_RENDER_TIMING, you get a textual + Set the environment variable QSG_RENDER_TIMING, to get a textual output of similar, but slightly different timings from the application - being profiled. For easier orientation, the differences are listed below. + being profiled. The differences are listed below. \table \header @@ -365,7 +357,6 @@ \li Render Loop Types \li Label in output of QSG_RENDER_TIMING \li Description - \li Caveats \row \li \uicontrol {Polish} \li GUI @@ -373,8 +364,6 @@ \li polish \li Final touch-up of items before they are rendered using QQuickItem::updatePolish(). - \li Versions of Qt prior to Qt 5.4 record no polish times for the basic - render loop and incorrect ones for the windows render loop. \row \li \uicontrol {GUI Thread Wait} \li GUI @@ -385,14 +374,12 @@ the same mutex at \uicontrol {GUI Thread Sync}. If this starts long before \uicontrol {Render Thread Sync}, there is \e free time in the GUI thread you could be using for running additional QML or JavaScript. - \li None \row \li \uicontrol {GUI Thread Sync} \li GUI \li Threaded \li blockedForSync \li The time the GUI thread is blocked, waiting for the render thread. - \li None \row \li \uicontrol {Animations} \li GUI @@ -403,7 +390,6 @@ animation events will be shown when using the basic render loop. Watch the \uicontrol {Animations} category to see animation timing in this case. - \li None \row \li \uicontrol {Render Thread Sync} \li Render @@ -411,7 +397,6 @@ \li Frame rendered ... sync \li Synchronizing the QML state into the scene graph using QQuickItem::updatePaintNode(). - \li None \row \li \uicontrol {Render} \li Render @@ -421,20 +406,12 @@ uploading all the necessary data to the GPU. This is the \e gross render time. Do not confuse it with the \e net \uicontrol{Render Render} time below. - \li With versions of Qt prior to Qt 5.5, the gross render time and the - below breakup of render times may be misaligned by some - microseconds due to different, unsynchronized timers being used to - measure them. For example \uicontrol {Render Preprocess} might seem to - start before \uicontrol {Render Thread Sync} is finished. \row \li \uicontrol {Swap} \li Render \li Threaded, Basic, Windows \li Frame rendered ... swap \li Swapping frames after rendering. - \li The output of swap times triggered by setting QSG_RENDER_TIMING is - incorrect for the basic render loop and versions of Qt prior to - Qt 5.4. The QML profiler shows the correct swap times. \row \li \uicontrol {Render Preprocess} \li Render @@ -442,8 +419,6 @@ \li time in renderer ... preprocess \li Calling QSGNode::preprocess() on all nodes that need to be preprocessed. This is part of the gross \uicontrol {Render} step. - \li May not be properly aligned with \uicontrol {Render} with versions of Qt - prior to Qt 5.5. \row \li \uicontrol {Render Update} \li Render @@ -455,8 +430,6 @@ with state from the GUI thread. In \uicontrol {Render Update}, all the nodes are combined to create the final scene. This is part of the gross \uicontrol {Render} step. - \li May not be properly aligned with \uicontrol {Render} with versions of Qt - prior to Qt 5.5. \row \li \uicontrol {Render Bind} \li Render @@ -464,8 +437,6 @@ \li time in renderer ... binding \li Binding the correct framebuffer for OpenGL rendering. This is part of the gross \uicontrol {Render} step. - \li May not be properly aligned with \uicontrol {Render} with versions of Qt - prior to Qt 5.5. \row \li \uicontrol {Render Render} \li Render @@ -473,38 +444,30 @@ \li time in renderer ... rendering \li The actual process of sending all the data to the GPU via OpenGL. This is part of the gross \uicontrol {Render} step. - \li May not be properly aligned with \uicontrol {Render} with versions of Qt - prior to Qt 5.5. \row \li \uicontrol {Material Compile} \li Render \li Threaded, Basic, Windows \li shader compiled \li Compiling GLSL shader programs. - \li None \row \li \uicontrol {Glyph Render} \li Render \li Threaded, Basic, Windows \li glyphs ... rendering \li Rendering of font glyphs into textures. - \li Versions of Qt prior to Qt 5.4 report incorrect times for these - events. \row \li \uicontrol {Glyph Upload} \li Render \li Threaded, Basic, Windows \li glyphs ... upload \li Uploading of glyph textures to the GPU. - \li Versions of Qt prior to Qt 5.4 report incorrect times for these - events. \row \li \uicontrol {Texture Bind} \li Render \li Threaded, Basic, Windows \li plain texture ... bind \li Binding a texture in the OpenGL context using glBindTextures. - \li None \row \li \uicontrol {Texture Convert} \li Render @@ -512,35 +475,30 @@ \li plain texture ... convert \li Converting the format and downscaling an image to make it suitable for usage as a texture. - \li None \row \li \uicontrol {Texture Swizzle} \li Render \li Threaded, Basic, Windows \li plain texture ... swizzle \li Swizzling the texture data on the CPU if necessary. - \li None \row \li \uicontrol {Texture Upload} \li Render \li Threaded, Basic, Windows \li plain texture ... upload / atlastexture uploaded \li Uploading the texture data to the GPU. - \li None \row \li \uicontrol {Texture Mipmap} \li Render \li Threaded, Basic, Windows \li plain texture ... mipmap \li Mipmapping a texture on the GPU. - \li None \row \li \uicontrol {Texture Delete} \li Render \li Threaded, Basic, Windows \li plain texture deleted \li Deleting a texture from the GPU that became unnecessary. - \li None \endtable \section2 Analyzing Qt Quick 3D Events @@ -550,7 +508,7 @@ Synchronize happens in scene graph synchronizing phase, while prepare and render happen in scene graph rendering phase. - Setting the environment variable \c QSG_RENDERER_DEBUG=render will also give + Set the environment variable \c QSG_RENDERER_DEBUG=render to get additional textual output of render call counts of different rendering passes. These call counts are summed up in the Render Frame event. @@ -616,24 +574,24 @@ The \uicontrol Statistics view displays the number of times each binding, create, compile, JavaScript, or signal event is triggered and the average time it - takes. This allows you to examine which events you need to optimize. A high + takes. Examine the statistics to learn which events to optimize. A high number of occurrences might indicate that an event is triggered unnecessarily. To view the median, longest, and shortest time for the occurrences, select \uicontrol {Extended Event Statistics} in the context menu. - Click on an event to move to it in the source code + Select an event to move to it in the source code in the code editor. \image qml-profiler-statistics.png "Statistics view" - The \uicontrol Callers and \uicontrol Callees panes show dependencies between events. + \uicontrol Callers and \uicontrol Callees show dependencies between events. They allow you to examine the internal functions of the application. - The \uicontrol Callers pane summarizes the QML events that trigger a binding. + \uicontrol Callers summarizes the QML events that trigger a binding. This tells you what caused a change in a binding. - The \uicontrol Callees pane summarizes the QML events that a binding triggers. + \uicontrol Callees summarizes the QML events that a binding triggers. This tells you which QML events are affected if you change a binding. - Click on an event to move to it in the source code in the code editor. + Select an event to move to it in the source code in the code editor. When you select an event in the \uicontrol Timeline view, information about it is displayed in the \uicontrol Statistics and \uicontrol {Flame Graph} @@ -642,9 +600,6 @@ To copy the contents of one view or row to the clipboard, select \uicontrol {Copy Table} or \uicontrol {Copy Row} in the context menu. - JavaScript events are shown in the \uicontrol Statistics view only for applications - that use Qt Quick 2 and are compiled with Qt 5.3 or later. - \section2 Visualizing Statistics as Flame Graphs The \uicontrol {Flame Graph} view shows a more concise statistical overview @@ -671,4 +626,9 @@ suitable for analyzing per frame execution times. However, it is very easy to see the total impact of the various QML and JavaScript events there. + \sa {Profile QML applications} + + \if defined(qtcreator) + \sa {Analyze}{How To: Analyze}, {Analyzers}, {Analyzing Code} + \endif */ diff --git a/doc/qtcreator/src/qtquick/qtquick-ui-forms.qdoc b/doc/qtcreator/src/qtquick/qtquick-ui-forms.qdoc index 1cfa1505441..7ff6d416d02 100644 --- a/doc/qtcreator/src/qtquick/qtquick-ui-forms.qdoc +++ b/doc/qtcreator/src/qtquick/qtquick-ui-forms.qdoc @@ -23,14 +23,18 @@ \brief Limitations of \QDS UI files (.ui.qml). \if defined(qtdesignstudio) - You can use \QDS wizards to create UI files that have the filename - extension \e .ui.qml. The UI files can be edited in the \l {2D} view. - If you use the \l {Code} view to add code that is not supported - by the \uicontrol {2D} view, \QDS displays error messages. + \QDS wizards create UI files that have the filename extension \e .ui.qml. + Edit the UI files in the \l {2D} view. + + If you use the \l {Code} view to add code that the \uicontrol {2D} view does + not support, \QDS displays error messages. \else If you switch between \QC and \QDS or cooperate with designers on a project, you might encounter UI files (.ui.qml). They are intended to be edited in \QDS only. + + To open UI files with \QDS, select \uicontrol {Open With} > + \uicontrol {\QDS} in the context menu for the file. \endif diff --git a/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc index a53506eba84..fe498aca9f7 100644 --- a/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc +++ b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc @@ -27,7 +27,7 @@ \li Purpose \li Read More \row - \li {1,7} \inlineimage qtcreator-mode-selector.png + \li {1,8} \inlineimage qtcreator-mode-selector.webp {Mode selector} \row \li \uicontrol Welcome \li \key Ctrl+1 @@ -57,8 +57,13 @@ This mode is available when a project is open. \li \l{Configuring Projects} \row - \li \uicontrol Help + \li \uicontrol Extensions \li \key Ctrl+6 + \li Load \QC extensions from the computer or the web. + \li \l{Load extensions} + \row + \li \uicontrol Help + \li \key Ctrl+7 \li Read documentation. \li \l{Get help} \endtable diff --git a/doc/qtcreator/src/user-interface/creator-only/creator-reference-to-do-entries-view.qdoc b/doc/qtcreator/src/user-interface/creator-only/creator-reference-to-do-entries-view.qdoc index 5d78d8345cf..61613519c3d 100644 --- a/doc/qtcreator/src/user-interface/creator-only/creator-reference-to-do-entries-view.qdoc +++ b/doc/qtcreator/src/user-interface/creator-only/creator-reference-to-do-entries-view.qdoc @@ -63,7 +63,7 @@ \li To determine whether the keywords in the whole project, in the current file, or in a subproject are displayed by default, select - the appropriate option in the \uicontrol {Scanning scope} group. + the appropriate option in the \uicontrol {Scanning Scope} group. \endlist diff --git a/doc/qtcreator/src/user-interface/creator-reference-output-views.qdoc b/doc/qtcreator/src/user-interface/creator-reference-output-views.qdoc index 0381320085f..5116000256c 100644 --- a/doc/qtcreator/src/user-interface/creator-reference-output-views.qdoc +++ b/doc/qtcreator/src/user-interface/creator-reference-output-views.qdoc @@ -294,6 +294,6 @@ \sa {View output} \if defined(qtcreator) - \sa {Add custom output parsers} + \sa {Add custom output parsers}, {Kits} \endif */ diff --git a/doc/qtcreator/src/user-interface/creator-ui.qdoc b/doc/qtcreator/src/user-interface/creator-ui.qdoc index 9794667f5b3..90ef03431ac 100644 --- a/doc/qtcreator/src/user-interface/creator-ui.qdoc +++ b/doc/qtcreator/src/user-interface/creator-ui.qdoc @@ -16,7 +16,7 @@ \if defined(qtcreator) When you start \QC, it opens to the \uicontrol Welcome mode. - \image qtcreator-breakdown.png {Welcome mode} + \image qtcreator-welcome.webp {Welcome mode} \table \header @@ -33,7 +33,7 @@ \row \li \inlineimage numbers/02.png \li Kit selector - \li Select the appropriate \l{glossary-buildandrun-kit}{kit} for building + \li Select the appropriate \l{Kits}{kit} for building the project and running it on particular hardware. \li \l{Activate kits for a project} \row diff --git a/doc/qtcreator/src/webassembly/creator-webassembly.qdoc b/doc/qtcreator/src/webassembly/creator-webassembly.qdoc index 4a459e8cdd6..ab757d7add0 100644 --- a/doc/qtcreator/src/webassembly/creator-webassembly.qdoc +++ b/doc/qtcreator/src/webassembly/creator-webassembly.qdoc @@ -1,116 +1,71 @@ -// 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 /*! - \previouspage creator-developing-generic-linux.html \page creator-setup-webassembly.html - \nextpage creator-build-process-customizing.html + \previouspage creator-how-tos.html - \title Building Applications for the Web + \ingroup creator-how-to-webassembly + + \title Build applications for the Web WebAssembly is a binary format that allows sand-boxed executable code in - web pages. This format is nearly as fast as native machine code, and is - now supported by all major web browsers. + web pages. This format is nearly as fast as native machine code. It is + supported by all major web browsers. - \l {Qt for WebAssembly} enables building Qt applications so that they can be - integrated into web pages. It doesn't require any client-side installations - and reduces the use of server-side resources. - - The experimental WebAssembly plugin enables you to build your applications - in WebAssembly format and deploy and run them in the local web browser. - You can change the web browser in the project's \l{Specifying Run Settings} - {run settings}. + Use \l {Qt for WebAssembly} to build your applications in WebAssembly format + and deploy and run them on the local web browser. Change the web browser in + the project's \l{Run applications in a web browser}{run settings}. \note Enable the WebAssembly plugin to use it. - To build applications for the web and run them in a web browser, you need to - install Qt for WebAssembly and the tool chain for compiling to WebAssembly. + To build applications for the web and run them in a web browser, install + Qt for WebAssembly with \QOI. It automatically adds a build and run kit + to \QC. - \section1 Requirements + \section1 Set up WebAssembly development environment - You need the following software to build Qt applications for the web and run - them in a browser: - - \list - \li Qt for WebAssembly 5.15, or later - \li On Windows: \l{http://wiki.qt.io/MinGW}{\MinGW} 7.3.0, or later - \li \l{https://emscripten.org/docs/introducing_emscripten/index.html} - {emscripten} tool chain for compiling to WebAssembly - \endlist - - \section1 Setting Up the Development Environment - - You need to install and configure Qt for WebAssembly and the tool chain for - compiling to WebAssembly. \QOI automatically adds a build and - run kit to \QC. - - \section2 Setting Up Qt for WebAssembly - - To set up Qt for WebAssembly: - - \list 1 - \li Use \QMT to install Qt for WebAssembly and, on - Windows, \MinGW (found in \uicontrol {Developer and Designer Tools}). - \li Check out a known-good Emscripten version supported by the Qt for - WebAssembly version that you installed, and install and activate - \c emscripten, as instructed in - \l {https://doc.qt.io/qt-5/wasm.html#install-emscripten} - {Install Emscripten}. - \endlist - - \section2 Specifying WebAssembly Settings - - To configure \QC for building Qt apps for the web: + To set up the development environment for WebAssembly: \list 1 - \li Select \preferences > \uicontrol Devices > \uicontrol WebAssembly. - \li In the \uicontrol {Emscripten SDK path} field, enter the root - directory where \c emsdk is installed. + \li Go to \preferences > \uicontrol Devices > \uicontrol WebAssembly. + \li In \uicontrol {Emscripten SDK path}, enter the root directory where + you installed \c emsdk. \li \QC configures the \uicontrol {Emscripten SDK environment} for you - if the \c emsdk is supported by the Qt for WebAssembly version that - you will use for developing the application. - \image qtcreator-webassembly-options.png "Qt for WebAssembly device preferences" - \li Select \preferences > \uicontrol Kits. - \image qtcreator-kit-webassembly.png "Qt for WebAssembly kit" - \li In the \uicontrol Compiler group, \uicontrol {Emscripten Compiler} - should have been automatically detected for both C++ and C. If not, - check that emscripten is set up correctly. + if your Qt for WebAssembly version supports the \c emsdk. + \image qtcreator-webassembly-options.png {Qt for WebAssembly device preferences} + \li Go to \preferences > \uicontrol Kits. + \image qtcreator-kit-webassembly.png {Qt for WebAssembly kit} + \li If \uicontrol {Emscripten Compiler} was not automatically set + for both C++ and C, check that emscripten is set up correctly. \endlist - \section2 Adding WebAssembly Kits + \sa {Run applications in a web browser} +*/ - The Qt for Web Assembly installation automatically adds build and run kits - to \QC. To add kits: +/*! + \page creator-how-to-run-webassembly.html + \previouspage creator-how-tos.html - \list 1 - \li Select \preferences > \uicontrol Kits > \uicontrol Add. - \li In the \uicontrol Name field, specify a name for the kit. - \li In the \uicontrol {Run device type} field, select - \uicontrol {WebAssembly Runtime}. - The value of the \uicontrol Device field is automatically - set to \uicontrol {Web Browser}. - \li In the \uicontrol Compiler field, select - \uicontrol {Emscripten Compiler} for both C and C++. - \li Select \uicontrol Apply to add the kit. - \endlist + \ingroup creator-how-to-webassembly - \section1 Running Applications in a Web Browser + \title Run applications in a web browser - To run a project: + To build Qt applications in \l{Qt for WebAssembly}{WebAssembly} format and + run them in a web browser: \list 1 \li Open a project for an application you want to run in a web browser. - \li Select \uicontrol Projects > \uicontrol {Build & Run}, and then + \li Go to \uicontrol Projects > \uicontrol {Build & Run}, and then select the WebAssembly kit as the build and run kit for the project. \li Select \uicontrol Run to specify run settings. - \li In the \uicontrol {Web browser} field, select the browser to run - the application in. - \image qtcreator-settings-run-webassembly.png "Selecting the browser to run in" + \li In \uicontrol {Web browser}, select a browser. + \image qtcreator-settings-run-webassembly.png {Selecting the browser to run in} \endlist - You can now build Qt applications in WebAssembly format and run them in + Build Qt applications in WebAssembly format and run them in a web browser as described in \l {Build for many platforms} and \l{Run on many platforms}. - \sa {Enable and disable plugins} + \sa {Build applications for the Web}, {Enable and disable plugins} */ diff --git a/doc/qtcreator/src/widgets/creator-faq-qtdesigner.qdocinc b/doc/qtcreator/src/widgets/creator-faq-qtdesigner.qdocinc index 93ed060e4ad..eb93c69a8c7 100644 --- a/doc/qtcreator/src/widgets/creator-faq-qtdesigner.qdocinc +++ b/doc/qtcreator/src/widgets/creator-faq-qtdesigner.qdocinc @@ -4,7 +4,7 @@ /*! //! [qt designer faq] - \section1 Qt Designer Integration Questions + \section1 \QD Integration Questions \b {Why are custom widgets not loaded in the \uicontrol Design mode even though it works in standalone \QD?} @@ -13,7 +13,7 @@ that match its build key. The locations are different for standalone and integrated \QD. - For more information, see \l{Adding Qt Designer Plugins}. + For more information, see \l{Adding \QD Plugins}. //! [qt designer faq] */ diff --git a/doc/qtcreator/src/widgets/qtdesigner-app-tutorial.qdoc b/doc/qtcreator/src/widgets/qtdesigner-app-tutorial.qdoc index f3717ee0491..4596d46da2e 100644 --- a/doc/qtcreator/src/widgets/qtdesigner-app-tutorial.qdoc +++ b/doc/qtcreator/src/widgets/qtdesigner-app-tutorial.qdoc @@ -76,7 +76,7 @@ \image qtcreator-new-project-qt-versions-qt-gui.png {Kit Selection dialog} - \li Select build and run \l{glossary-buildandrun-kit}{kits} for your + \li Select build and run \l{Kits}{kits} for your project. \li Select \uicontrol Next or \uicontrol Continue to open the @@ -197,7 +197,7 @@ \endlist For more information about designing forms with \QD, see the - \l{Qt Designer Manual}. + \l{\QD Manual}. \section2 Completing the Header File diff --git a/doc/qtcreator/src/widgets/qtdesigner-overview.qdoc b/doc/qtcreator/src/widgets/qtdesigner-overview.qdoc index b2357514fac..29d2c7d34b1 100644 --- a/doc/qtcreator/src/widgets/qtdesigner-overview.qdoc +++ b/doc/qtcreator/src/widgets/qtdesigner-overview.qdoc @@ -29,7 +29,7 @@ Furthermore, features such as widget promotion and custom plugins allow you to use your own widgets with \QD. - For more information about \QD, see the \l{Qt Designer Manual}. + For more information about \QD, see the \l{\QD Manual}. Generally, the integrated \QD has the same functions as the standalone \QD. The following sections describe the differences. @@ -62,7 +62,7 @@ \uicontrol {Follow Symbol Under Cursor} in the context menu or press \key F2 when the cursor is over a string literal. - \section1 Specifying Settings for Qt Designer + \section1 Specifying Settings for \QD You can drag and drop the views in \QD to new positions on the screen. @@ -102,7 +102,7 @@ \list 1 \li \preferences > \uicontrol Designer. - \image qtdesigner-embedded-design.png "Qt Designer Embedded Design preferences" + \image qtdesigner-embedded-design.png "Qt Widgets Designer Embedded Design preferences" \li In \uicontrol {Embedded Design}, select \inlineimage icons/plus.png to open the \uicontrol {Add Profile} dialog. \image qtdesigner-add-profile.png "Add Profile dialog" @@ -119,5 +119,5 @@ To import device profiles from .qdp files, select \uicontrol Open. To save them as .qdp files, select \uicontrol Save. - \sa {Creating a Qt Widget Based Application}, {Adding Qt Designer Plugins} + \sa {Creating a Qt Widget Based Application}, {Adding \QD Plugins} */ diff --git a/doc/qtcreator/src/widgets/qtdesigner-plugins.qdoc b/doc/qtcreator/src/widgets/qtdesigner-plugins.qdoc index 00f61ab051e..3ce3dc02f7c 100644 --- a/doc/qtcreator/src/widgets/qtdesigner-plugins.qdoc +++ b/doc/qtcreator/src/widgets/qtdesigner-plugins.qdoc @@ -26,7 +26,7 @@ and to change the default plugin path, see \l{How to Create Qt Plugins}. For more information about how to create plugins for \QD, see - \l{Using Custom Widgets with Qt Designer}. + \l{Using Custom Widgets with \QD}. \section1 Locating \QD Plugins @@ -42,7 +42,7 @@ To check which plugins were loaded successfully and which failed, choose \uicontrol Tools > \uicontrol {Form Editor} > - \uicontrol {About Qt Designer Plugins}. + \uicontrol {About \QD Plugins}. The standalone \QD is part of the Qt library used for building projects, located in \c {\\bin} in the Qt installation diff --git a/doc/qtcreatordev/examples/exampleplugin/CMakeLists.txt b/doc/qtcreatordev/examples/exampleplugin/CMakeLists.txt index 65fba000893..d2c47e4dd8c 100644 --- a/doc/qtcreatordev/examples/exampleplugin/CMakeLists.txt +++ b/doc/qtcreatordev/examples/exampleplugin/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.16) #! [1] # Remove when sharing with others. diff --git a/doc/qtcreatordev/examples/exampleplugin/Example.json.in b/doc/qtcreatordev/examples/exampleplugin/Example.json.in index c5faf0a2559..b6867bb5167 100644 --- a/doc/qtcreatordev/examples/exampleplugin/Example.json.in +++ b/doc/qtcreatordev/examples/exampleplugin/Example.json.in @@ -8,7 +8,7 @@ "Vendor" : "MyCompany", "Copyright" : "(C) MyCompany", "License" : "Put short license information here", - "Description" : "Put a short description of your plugin here", + "Description" : "Put a short description of your plugin here.", "Url" : "https://www.mycompany.com", //! [2] //! [3] diff --git a/doc/qtcreatordev/src/coding-style.qdoc b/doc/qtcreatordev/src/coding-style.qdoc index 49e99a8e8bc..33a2189aaf6 100644 --- a/doc/qtcreatordev/src/coding-style.qdoc +++ b/doc/qtcreatordev/src/coding-style.qdoc @@ -637,8 +637,8 @@ \li Use Utils::FilePath for any QString that semantically is a file or directory, see also \l{Passing File Names}. \li Prefer using Utils::FilePath over any use of QDir and QFileInfo. - \li Prefer using Utils::QtcProcess over QProcess. - \li If Utils::FilePath or Utils::QtcProcess functionality is not sufficient + \li Prefer using Utils::Process over QProcess. + \li If Utils::FilePath or Utils::Process functionality is not sufficient for your purpose, prefer enhancing them over falling back to QString or QProcess. \li Avoid platform #ifdefs unless they are absolutely needed for locally diff --git a/doc/qtcreatordev/src/lua-extensions.qdoc b/doc/qtcreatordev/src/lua-extensions.qdoc new file mode 100644 index 00000000000..581db2e3922 --- /dev/null +++ b/doc/qtcreatordev/src/lua-extensions.qdoc @@ -0,0 +1,275 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +/*! + \page lua-extensions.html + \title Extending \QC with Lua + + \QC can be extended with Lua scripts. The included Lua engine is based on Lua 5.4.6. + + \section1 Writing Lua Extensions + + To create a new Lua extension, choose \uicontrol {File} > \uicontrol {New Project} > + \uicontrol {Library} > \uicontrol {\QC Lua Plugin}. + + To test your new extension, start your project. Your \uicontrol {Application Output} + should show \e {Hello from Lua!}. + + \section1 Lua Extension Specification + + A Lua extension consists of a Lua script with the same name as the folder it is in. + This is necessary for the extension to be loaded. + + This script defines the specification of the extension, such as its display name, vendor, copyright. + + \code + --- MyExtension.lua + return { + Name = "MyExtension", + Version = "1.0.0", + CompatVersion = "1.0.0", + Vendor = "My Company", + Category = "Tests", + Description = "Describe what your extension does in a sentence.", + LongDescription = [[ + Tell users more about your extension. + ]], + Dependencies = { + { Name = "Core", Version = "13.0.82", Required = true }, + { Name = "Lua", Version = "13.0.82", Required = true } + }, + setup = function() print("Hello from Lua!") end, + printToOutputPane = true, + } --[[@as QtcPlugin]] + \endcode + + \section1 The Setup Function + + The setup function is called when the extension is loaded. This is where you can set up the + functionality of your extension. Since the specification file is parsed with very limited + permissions, you need to require a module where you implement the actual functionality. + + \code + --- MyExtension.lua + return { + Name = "MyExtension", + Version = "1.0.0", + ..., + --- This is the setup function that is called when the extension is loaded. + --- It requires the 'init' module and calls the setup function from the returned table. + setup = function() require 'init'.setup() end, + } + \endcode + + \code + --- init.lua + function setup() + print("Hello from Lua!") + end + + -- Returns a table with a single field 'setup' that points to the setup function. + return { + setup = setup + } + \endcode + + + \section1 Asynchronous Operations + + Some of the built-in operations work asynchronously. To handle this, use the Async module. + + \code + local a = require 'async' + local u = require 'Utils' + + a.sync(function() + print("Lets wait for 5 seconds ...") + a.wait(u.waitms(5000)) + print("... done!") + end) + \endcode + + \section1 Interactive Help + + When you open a .lua file in the editor the first time, you are asked to download the Lua + Language Server. This is extremely useful as it gives you context sensitive help and + auto-completion. + + \section1 \QC API + + The \QC API is available to Lua extensions via a number of modules that you can import + using the \c {require} function. C++ extensions may provide additional modules. One example of that + is the LanguageServer Extension that provides a module for creating Language Server clients. + + You can find the API documentation files for the Lua modules in your \QC installation. + On \macos you can find them in \c{Qt Creator.app/Contents/Resources/lua/meta}. + + \annotatedlist lua-modules + + \section1 Extending the Lua API with C++ + + To add functionality to the Lua Interface, you need to register a new module with the Lua Engine. + + \code + #include + + class MyCppExtension final : public ExtensionSystem::IPlugin + { + Q_OBJECT + Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "MyCppExtension.json") + + public: + MyCppExtension() {} + + private: + void initialize() final { + // The registered function will be called when the Lua module 'MyCppExtension' is required. + // The returned table will be returned from the require call in Lua. + ::Lua::LuaEngine::registerProvider("MyCppExtension", [](sol::state_view lua) -> sol::object { + sol::table result = lua.create_table(); + result["myFunction"] = [](int a, int b) { return a + b; }; + return result; + }); + } + }; + \endcode + + You can then access \c{MyCppExtension.myFunction} from your Lua scripts like this: + + \code + local MyCppExtension = require 'MyCppExtension' + --- MyCppExtension is now a table with a single field 'myFunction', as it is returned from the + --- C++ function registered via 'LuaEngine::registerProvider(...)'. + print(MyCppExtension.myFunction(1, 2)) + \endcode + + For more information on how to register C++ functionality, see + \l {https://sol2.readthedocs.io/en/latest/index.html} {sol2}. + + \section1 Examples + + \section2 Language Server + + The \QC LuaLanguageClient Plugin provides support for registering your own Language Server + clients. You can find an example of how to use this in the \QC Extension "Lua Language Server" + and "Rust Language Server". +*/ + +/*! + \page lua-extension-meta-core + \ingroup lua-modules + \title Core.lua + \brief Access and interact with the core functionality of \QC. + + \quotefile ../../../src/plugins/lua/meta/core.lua +*/ + +/*! + \page lua-extension-meta-action + \ingroup lua-modules + \title action.lua + \brief Create user interface actions in \QC. + + \quotefile ../../../src/plugins/lua/meta/action.lua +*/ + +/*! + \page lua-extension-meta-async + \ingroup lua-modules + \title async.lua + \brief Handle asynchronouse operations with the async/await Lua API. + + \quotefile ../../../src/plugins/lua/meta/async.lua +*/ + +/*! + \page lua-extension-meta-fetch + \ingroup lua-modules + \title fetch.lua + \brief Fetch data from the internet. + + \quotefile ../../../src/plugins/lua/meta/fetch.lua +*/ + +/*! + \page lua-extension-meta-gui + \ingroup lua-modules + \title gui.lua + \brief Create user interfaces. + + \quotefile ../../../src/plugins/lua/meta/gui.lua +*/ + +/*! + \page lua-extension-meta-lsp + \ingroup lua-modules + \title lsp.lua + \brief Register Language Server clients. + + \quotefile ../../../src/plugins/lua/meta/lsp.lua +*/ + +/*! + \page lua-extension-meta-messagemanager + \ingroup lua-modules + \title messagemanager.lua + \brief Display messages to the user. + + \quotefile ../../../src/plugins/lua/meta/messagemanager.lua +*/ + +/*! + \page lua-extension-meta-process + \ingroup lua-modules + \title process.lua + \brief Run external processes. + + \quotefile ../../../src/plugins/lua/meta/process.lua +*/ + +/*! + \page lua-extension-meta-qt + \ingroup lua-modules + \title qt.lua + \brief Access Qt functionality. + + \quotefile ../../../src/plugins/lua/meta/qt.lua +*/ + +/*! + \page lua-extension-meta-qtc + \ingroup lua-modules + \title qtc.lua + \brief Access and extend \QC. + + \quotefile ../../../src/plugins/lua/meta/qtc.lua +*/ + +/*! + \page lua-extension-meta-settings + \ingroup lua-modules + \title settings.lua + \brief Read and write settings. + + \quotefile ../../../src/plugins/lua/meta/settings.lua +*/ + +/*! + \page lua-extension-meta-simpletypes + \ingroup lua-modules + \title simpletypes.lua + \brief Access simple types. + + \quotefile ../../../src/plugins/lua/meta/simpletypes.lua +*/ + +/*! + \page lua-extension-meta-utils + \ingroup lua-modules + \title utils.lua + \brief Common utility functions and classes. + + \quotefile ../../../src/plugins/lua/meta/utils.lua +*/ + + diff --git a/doc/qtcreatordev/src/plugin-metadata.qdoc b/doc/qtcreatordev/src/plugin-metadata.qdoc index b233ef60bc6..20d4073fd14 100644 --- a/doc/qtcreatordev/src/plugin-metadata.qdoc +++ b/doc/qtcreatordev/src/plugin-metadata.qdoc @@ -323,6 +323,27 @@ } \endcode + \section2 Other Meta Data + + \table + \header + \li Key + \li Value Type + \li Meaning + \row + \li Mimetypes + \li String or array of strings + \li Possibly multiple lines of + \l{https://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec/}{XML MIME-info} + used for registering additional or adapting built-in MIME types. + \row + \li JsonWizardPaths + \li Array of strings + \li A list of paths relative to the plugin location or paths to the + \l{The Qt Resource System}{Qt resource system} that are searched for + \l{http://doc.qt.io/qtcreator/creator-project-wizards.html}{template-based wizards}. + \endtable + \section2 A Note on Plugin Versions Plugin versions are in the form \c{x.y.z_n} where, \c x, \c y, \c z and \c n are diff --git a/doc/qtcreatordev/src/qtcreator-dev.qdoc b/doc/qtcreatordev/src/qtcreator-dev.qdoc index 368298b31f0..998f040ebf7 100644 --- a/doc/qtcreatordev/src/qtcreator-dev.qdoc +++ b/doc/qtcreatordev/src/qtcreator-dev.qdoc @@ -138,7 +138,7 @@ Most software projects and development processes require various external tools. Several external tools, such as popular version control systems and - build tool chains are integrated into \QC. However, it is impossible for a + build toolchains are integrated into \QC. However, it is impossible for a single tool to cover all the use cases, and therefore you can integrate additional tools to \QC. @@ -214,7 +214,16 @@ \li \l{Options Pages} \li \l{Editors} \endomit - \endlist + \endlist + + \section1 Lua Extensions + + If you have more specific needs that are not covered by the above methods but don't need + a full-blown plugin, you can extend \QC with Lua Extensions. + + \list + \li \l{Extending \QC with Lua} + \endlist \section1 All Topics diff --git a/doc/qtcreatordev/src/qtcreator-module.qdoc b/doc/qtcreatordev/src/qtcreator-module.qdoc index 83d0b3fe157..652f715133a 100644 --- a/doc/qtcreatordev/src/qtcreator-module.qdoc +++ b/doc/qtcreatordev/src/qtcreator-module.qdoc @@ -92,7 +92,7 @@ handling. \row - \li \l{Debugger} + \li \l{Debugging} \li Debugging functionality. \row diff --git a/doc/qtcreatordev/src/qtcreator-ui-text.qdoc b/doc/qtcreatordev/src/qtcreator-ui-text.qdoc index f42c80671af..e76ad238e23 100644 --- a/doc/qtcreatordev/src/qtcreator-ui-text.qdoc +++ b/doc/qtcreatordev/src/qtcreator-ui-text.qdoc @@ -158,11 +158,11 @@ \section3 Writing Tooltips in Design Mode - In Qt Designer, use plain text for tooltips. For extra formatting, write + In \QD, use plain text for tooltips. For extra formatting, write short, canonical HTML in the source tab of the rich text editor: \c {Note: text.} - Qt Designer has a feature that simplifies the rich text (on by default), + \QD has a feature that simplifies the rich text (on by default), but still, you should verify by looking at the \uicontrol Source tab. \section2 Writing Messages @@ -273,8 +273,36 @@ \section2 Marking UI Text for Translation - Make sure the text strings presented to the user are easy to translate. - The user interface text strings are enclosed in \c tr() calls and + \section3 Translation Context + + Avoid creating many different translation contexts. By default, \c tr() + uses the context of the class, which means that translations break when + code is refactored and UI text is moved to a different class. + + Create a single translation context for each plugin instead. Create a header + \c myplugintr.h + + \code + #pragma once + + #include + + namespace MyPlugin { + + struct Tr + { + Q_DECLARE_TR_FUNCTIONS(QtC::MyPlugin) + }; + + } // namespace MyPlugin + \endcode + + and use that struct as the translation context for UI text by calling + \c {Tr::tr()}. Use disambiguation strings in cases that need it. + + \section3 Translator Comments + + The user interface text strings are enclosed in \c {Tr::tr()} calls and extracted from the source code during the translation process. Therefore, the translator might not know the source code context of the messages. @@ -286,26 +314,24 @@ return tr("Add"); \endcode - If the class is not Q_OBJECT, use \c {QCoreApplication::translate("class - context", "message")} or consider using Q_DECLARE_TR_FUNCTIONS. Do not use - \c {QObject::tr()}, which is confusing because the messages appear grouped - by class context in Qt Linguist and messages tied to QObject do not have a - class context. + \section3 File Paths - Use \c{QDir::toNativeSeparators()} for file and directory names that you - pass to \c{tr().arg()}. + Use \c{FilePath::toUserOutput()} from the \c Utils library for file and directory + names that you pass to \c{Tr::tr().arg()}. - Do not use markup that spans the whole string because that can be confusing + \section3 Markup + + Avoid including markup within the translated text itself because that can be confusing for translators. For example, instead of: \code - tr("UI Text") + Tr::tr("UI Text") \endcode use \code - QLatin1String("") + tr("UI Text") + QLatin1String("/span>") + "" + Tr::tr("UI Text") + "" \endcode \section2 Features of Languages or Writing Systems diff --git a/doc/qtcreator/src/qtquick/qtquick-live-preview-desktop.qdoc b/doc/qtdesignstudio/src/how-to/qtdesignstudio-live-preview-desktop.qdoc similarity index 75% rename from doc/qtcreator/src/qtquick/qtquick-live-preview-desktop.qdoc rename to doc/qtdesignstudio/src/how-to/qtdesignstudio-live-preview-desktop.qdoc index 7c43a918e73..b047265f09e 100644 --- a/doc/qtcreator/src/qtquick/qtquick-live-preview-desktop.qdoc +++ b/doc/qtdesignstudio/src/how-to/qtdesignstudio-live-preview-desktop.qdoc @@ -2,8 +2,8 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \previouspage creator-live-preview.html - \page creator-live-preview-desktop.html + \page studio-live-preview-desktop.html + \previouspage studio-live-preview.html \nextpage creator-live-preview-devices.html \title Previewing on Desktop @@ -11,16 +11,9 @@ To preview the currently active QML file on the desktop: \list - \if defined(qtcreator) - \li Select \inlineimage icons/live-preview.png (\uicontrol {Live Preview}) - on the \l{Edit Mode}{editor} toolbar. - \image qtcreator-live-preview.webp {Application running on top of the editor view} - \li Select \uicontrol Build > \uicontrol {QML Preview}. - \endlist - \else \li Select the \uicontrol {Live Preview} button on the top toolbar. \li Press \key {Alt+P}. - \image studio-live-preview.webp + \image studio-live-preview.webp \endlist To preview any QML file in the project: diff --git a/doc/qtdesignstudio/src/overviews/qtquick-live-preview.qdoc b/doc/qtdesignstudio/src/overviews/qtquick-live-preview.qdoc new file mode 100644 index 00000000000..d286c41c7a1 --- /dev/null +++ b/doc/qtdesignstudio/src/overviews/qtquick-live-preview.qdoc @@ -0,0 +1,38 @@ +// Copyright (C) 2024 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page studio-live-preview.html + \previouspage quick-states.html + \nextpage studio-live-preview-desktop.html + + \title Validating with Target Hardware + + Preview a UI file or the entire UI on the desktop, as well as on embedded + Linux devices to instantly view the changes you make to the UI. On Android + devices, the preview shows the snapshot of your project from the moment + you start the preview on the device, not your changes. + + \image studio-live-preview.webp + + Or, use \QDV to run applications in most widely-used web browsers on the + desktop and in mobile devices and share your designs with reviewers who + don't have \QC. + + \list + \li \l{Previewing on Desktop} + + Preview individual QML files or the whole UI. + \li \l{Previewing on Devices} + + Connect your devices to your computer. + + \li \l{Sharing Applications Online} + + Share applications online and view them in a web browser. + + \li \l{Viewing Applications on Android} + + Preview \QDS projects with \QUV on an Android device. + \endlist +*/ diff --git a/doc/qtdesignstudio/src/qtdesignstudio-debugging.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-debugging.qdoc index 9d1fa446aec..09cd1d0f584 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-debugging.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-debugging.qdoc @@ -22,8 +22,10 @@ \uicontrol Debug mode. \li \l{Profiling QML Applications} - You can use the QML Profiler to find causes for typical performance + You can use QML Profiler to find causes for typical performance problems in your UIs, such as slowness, freezing, and stuttering. - The QML Profiler is installed and configured as part of \QDS. + QML Profiler is installed and configured as part of \QDS. \endlist + + \sa {Profile QML applications} */ diff --git a/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc index 1f0aa086290..d19ede682f7 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc @@ -41,7 +41,7 @@ you can inspect the state of your UI while debugging. The memory and CPU power available on devices are limited and - you should use them carefully. The QML Profiler enables you to - profile Qt Quick UIs. + you should use them carefully. With QML Profiler, you can find + problems in QML code. \endlist */ diff --git a/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc index f116ab37d97..2584279e540 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc @@ -218,6 +218,9 @@ \endlist \li \l{Debugging a Qt Quick Application} \li \l{Profiling QML Applications} + \list + \li \l{Profile QML applications} + \endlist \endlist \endlist \li \l{Advanced Designer Topics} diff --git a/doc/qtdesignstudio/src/views/qtquick-states.qdoc b/doc/qtdesignstudio/src/views/qtquick-states.qdoc index 9f91c52f46f..ab31c93f464 100644 --- a/doc/qtdesignstudio/src/views/qtquick-states.qdoc +++ b/doc/qtdesignstudio/src/views/qtquick-states.qdoc @@ -4,7 +4,7 @@ /*! \page quick-states.html \previouspage quick-json-data-properties.html - \nextpage creator-live-preview.html + \nextpage studio-live-preview.html \title Working with States diff --git a/qbs/imports/QtcDocumentation.qbs b/qbs/imports/QtcDocumentation.qbs index 3017114c8c4..c5ddf497206 100644 --- a/qbs/imports/QtcDocumentation.qbs +++ b/qbs/imports/QtcDocumentation.qbs @@ -12,6 +12,7 @@ Product { property string versionTag: qtc.qtcreator_version.replace(/\.|-/g, "") Qt.core.qdocEnvironment: [ + "GENERATED_ATTRIBUTIONS_DIR=" + product.buildDirectory, "IDE_DISPLAY_NAME=" + qtc.ide_display_name, "IDE_CASED_ID=" + qtc.ide_cased_id, "IDE_ID=" + qtc.ide_id, diff --git a/qbs/imports/QtcPlugin.qbs b/qbs/imports/QtcPlugin.qbs index d06f99385e4..f4ee221695f 100644 --- a/qbs/imports/QtcPlugin.qbs +++ b/qbs/imports/QtcPlugin.qbs @@ -46,6 +46,6 @@ QtcProduct { Export { Depends { name: "cpp" } Depends { name: "ExtensionSystem" } - cpp.includePaths: ".." + cpp.includePaths: exportingProduct.sourceDirectory + "/.." } } diff --git a/qbs/modules/libclang/functions.js b/qbs/modules/libclang/functions.js index 0d3c5afb87a..a3c0198bda1 100644 --- a/qbs/modules/libclang/functions.js +++ b/qbs/modules/libclang/functions.js @@ -178,6 +178,7 @@ function toolingParameters(llvmConfig) "-Wno-unknown-warning", "-Wno-unused-command-line-argument", "-fPIC", + "-fno-rtti", "-pedantic", "-Wstring-conversion", "-gsplit-dwarf" diff --git a/qbs/modules/qtc/qtc.qbs b/qbs/modules/qtc/qtc.qbs index 83ef2f88dfc..04016cbb25e 100644 --- a/qbs/modules/qtc/qtc.qbs +++ b/qbs/modules/qtc/qtc.qbs @@ -4,16 +4,16 @@ import qbs.FileInfo import qbs.Utilities Module { - property string qtcreator_display_version: '13.0.2' + property string qtcreator_display_version: '14.0.0-rc1' property string ide_version_major: '13' property string ide_version_minor: '0' - property string ide_version_release: '2' + property string ide_version_release: '84' property string qtcreator_version: ide_version_major + '.' + ide_version_minor + '.' + ide_version_release property string ide_compat_version_major: '13' property string ide_compat_version_minor: '0' - property string ide_compat_version_release: '0' + property string ide_compat_version_release: '84' property string qtcreator_compat_version: ide_compat_version_major + '.' + ide_compat_version_minor + '.' + ide_compat_version_release diff --git a/qt_attributions.json b/qt_attributions.json index 525338f20b8..4d5980f646d 100644 --- a/qt_attributions.json +++ b/qt_attributions.json @@ -181,7 +181,7 @@ "Homepage": "https://invent.kde.org/frameworks/syntax-highlighting/-/tree/master/data/syntax", "License": "GNU General Public License v2.0 OR BSD 2-Clause \"Simplified\" License", "LicenseFile": "doc/qtcreator/src/overview/license-BSD-2-clause.txt", - "Copyright": "Copyright 2008 Darrin Yeager. http://www.dyeager.org/ Dual-Licensed under both GPL and BSD licenses. Extended 2009 Claes Holmerson. http://github.com/claes/kate-markdown/ Extended 2019 Nibaldo González S. (changes under MIT license)." + "Copyright": "Copyright 2008 Darrin Yeager. http://www.dyeager.org/ Dual-Licensed under both GPL and BSD licenses. Extended 2009 Claes Holmerson. http://github.com/claes/kate-markdown/ Extended 2019 Nibaldo Gonzlez S. (changes under MIT license)." }, { "Id": "ksyntaxhighlighting-modelines", @@ -259,7 +259,7 @@ "Homepage": "https://invent.kde.org/frameworks/syntax-highlighting/-/tree/master/data/syntax", "License": "GNU Lesser General Public License v2.0 or later", "LicenseFile": "doc/qtcreator/src/overview/license-LGPLv2.0.txt", - "Copyright": "Copyright (C) 2004 by Sebastian Vuorinen (sebastian dot vuorinen at helsinki dot fi). Copyright (C) 2004 by Stefan Lang (langstefan@gmx.at). Copyright (C) 2008 by Robin Pedersen (robinpeder@gmail.com). Copyright (C) 2011 by Miquel Sabaté (mikisabate@gmail.com)." + "Copyright": "Copyright (C) 2004 by Sebastian Vuorinen (sebastian dot vuorinen at helsinki dot fi). Copyright (C) 2004 by Stefan Lang (langstefan@gmx.at). Copyright (C) 2008 by Robin Pedersen (robinpeder@gmail.com). Copyright (C) 2011 by Miquel Sabat (mikisabate@gmail.com)." }, { "Id": "ksyntaxhighlighting-toml", @@ -311,7 +311,7 @@ "Homepage": "https://invent.kde.org/frameworks/syntax-highlighting/-/tree/master/data/syntax", "License": "GNU Lesser General Public License v2.1", "LicenseFile": "doc/qtcreator/src/overview/license-LGPLv2.1.txt", - "Copyright": "Copyright (C) 2004, Jan Villat . Changes by: 2018 Nibaldo González , 2007 Sebastian Pipping ." + "Copyright": "Copyright (C) 2004, Jan Villat . Changes by: 2018 Nibaldo Gonzlez , 2007 Sebastian Pipping ." }, { "Id": "ksyntaxhighlighting-yaml", @@ -324,7 +324,7 @@ "Homepage": "https://invent.kde.org/frameworks/syntax-highlighting/-/tree/master/data/syntax", "License": "GNU Lesser General Public License v2.1", "LicenseFile": "doc/qtcreator/src/overview/license-LGPLv2.1.txt", - "Copyright": "Copyright (C) Dr Orlovsky MA (dr.orlovsky@gmail.com), Nibaldo González (nibgonz@gmail.com)" + "Copyright": "Copyright (C) Dr Orlovsky MA (dr.orlovsky@gmail.com), Nibaldo Gonzlez (nibgonz@gmail.com)" }, { "Id": "std-span-martinmoene", @@ -436,6 +436,7 @@ "Path": "src/libs/3rdparty/winpty", "Description": "winpty is a Windows software package providing an interface similar to a Unix pty-master for communicating with Windows console programs.", "Homepage": "https://github.com/rprichard/winpty", + "Version": "7e59fe2d09", "License": "MIT License", "LicenseFile": "src/libs/3rdparty/winpty/LICENSE", "Copyright": "Copyright (c) 2011-2016 Ryan Prichard" @@ -449,10 +450,25 @@ "Path": "src/libs/3rdparty/libptyqt", "Description": "Pty-Qt is small library for access to console applications by pseudo-terminal interface on Mac, Linux and Windows.", "Homepage": "https://github.com/kafeg/ptyqt", + "Version" : "045ca5f09f", "License": "MIT License", "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 src/winconpty/ have been ported from microsofts terminal source code and integrated into ptyqt's conptyprocess.cpp.", + "Homepage": "https://github.com/microsoft/terminal", + "Version" : "a38388615e", + "License": "MIT License", + "LicenseFile": "src/libs/3rdparty/libptyqt/LICENSE-CONPTY", + "Copyright": "Copyright (c) Microsoft Corporation" + }, { "Id": "libvterm", "Name": "libvterm", @@ -462,6 +478,7 @@ "Path": "src/libs/3rdparty/libvterm", "Description": "An abstract C99 library which implements a VT220 or xterm-like terminal emulator.", "Homepage": "https://www.leonerd.org.uk/code/libvterm", + "Version" : "0.3.3", "License": "MIT License", "LicenseFile": "src/libs/3rdparty/libvterm/LICENSE", "Copyright": "Copyright (c) 2008 Paul Evans" @@ -475,6 +492,7 @@ "Path": "src/plugins/terminal/shellintegrations", "Description": "Scripts for integrating with various shells.", "Homepage": "https://github.com/microsoft/vscode/tree/main/src/vs/workbench/contrib/terminal/browser/media", + "Version" : "463d9933a4", "License": "MIT License", "LicenseFile": "src/plugins/terminal/shellintegrations/LICENSE.vscode", "Copyright": "Copyright (c) 2015 - present Microsoft Corporation" @@ -488,6 +506,7 @@ "Path": "src/plugins/terminal/shellintegrations", "Description": "A library of Lua scripts for use with Clink.", "Homepage": "https://github.com/chrisant996/clink-gizmos", + "Version" : "680716f3d9", "License": "MIT License", "LicenseFile": "src/plugins/terminal/shellintegrations/LICENSE.clink", "Copyright": "Copyright (c) 2022 Chris Antos" @@ -544,6 +563,74 @@ "LicenseFile": "src/libs/3rdparty/qtkeychain/COPYING", "Copyright": "Copyright (C) 2011-2015 Frank Osterfeld, Copyright (C) 2016 Mathias Hasselmann" }, + { + "Id": "pyprof2calltree", + "Name": "pyprof2calltree", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for converting profile data of debugger dumper execution to kcachegrind-compatible input in visualize.py", + "Path": "share/qtcreator/debugger", + "Description": "Creates python profiling output which is readable by kcachegrind", + "Homepage": "https://github.com/pwaller/pyprof2calltree", + "License": "MIT License", + "LicenseId": "MIT", + "LicenseFile": "share/qtcreator/debugger/LICENSE.MIT", + "Copyright": "Copyright(C) 2006-2008, David Allouche, Jp Calderone, Itamar Shtull-Trauring, Copyright(C) 2006-2017, Johan Dahlin, Copyright(C) 2008, Olivier Grisel , Copyright(C) 2008, David Glick, Copyright(C) 2013, Steven Maude, Copyright(C) 2013-2018, Peter Waller , Copyright(C) 2013, Lukas Graf , Copyright(C) 2013, Jamie Wong , Copyright(C) 2013, Yury V. Zaytsev , Copyright(C) 2014, Michael Droettboom , Copyright(C) 2015, Zev Benjamin , Copyright(C) 2018, Jon Dufresne " + }, + { + "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)" + }, + { + "Id": "ms-jpq-lua-async-await", + "Name": "ms-jpq/lua-async-await", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for async/await support in Lua modules.", + "Path": "src/plugins/lua/bindings", + "Description": "lua-async-await implements the async/await pattern in Lua.", + "Homepage": "https://github.com/ms-jpq/lua-async-await", + "License": "MIT License", + "LicenseFile": "src/plugins/lua/bindings/ASYNC-LICENSE.txt", + "Copyright": "Copyright (c) 2008 Paul Evans" + }, + { + "Id": "kikito/inspect.lua", + "Name": "kikito/inspect.lua", + "QDocModule": "qtcreator", + "QtParts": ["tools"], + "QtUsage": "Used for pretty printing from Lua scripts.", + "Path": "share/qtcreator/lua-plugins/luatests", + "Description": "inspect.lua is a library for pretty printing complex objects in Lua.", + "Homepage": "https://github.com/kikito/inspect.lua", + "License": "MIT License", + "LicenseFile": "share/qtcreator/lua-plugins/luatests/INSPECT-LICENSE.txt", + "Copyright": "Copyright (c) 2022 Enrique Garca Cota" + }, { "Id": "zlib", "Name": "ZLib", @@ -559,3 +646,4 @@ "Copyright": "Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler" } ] + diff --git a/scripts/build.py b/scripts/build.py index 66d5d25d43a..094cc9d6c4b 100755 --- a/scripts/build.py +++ b/scripts/build.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# Copyright (C) 2020 The Qt Company Ltd. +# Copyright (C) 2024 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 # import the print function which is used in python 3.x @@ -295,12 +295,15 @@ def package_qtcreator(args, paths): '*'], paths.debug_install) if common.is_windows_platform(): - common.check_print_call(['7z', 'a', '-mmt' + args.zip_threads, + # use -mf=off to avoid usage of the ARM executable compression filter, + # which cannot be extracted by the p7zip version on the machine doing + # the repository builds + common.check_print_call(['7z', 'a', '-mmt' + args.zip_threads, '-mf=off', os.path.join(paths.result, 'wininterrupt' + args.zip_infix + '.7z'), '*'], paths.wininterrupt_install) if not args.no_cdb: - common.check_print_call(['7z', 'a', '-mmt' + args.zip_threads, + common.check_print_call(['7z', 'a', '-mmt' + args.zip_threads, '-mf=off', os.path.join(paths.result, 'qtcreatorcdbext' + args.zip_infix + '.7z'), '*'], paths.qtcreatorcdbext_install) diff --git a/share/metainfo/org.qt-project.qtcreator.appdata.xml.cmakein b/share/metainfo/org.qt-project.qtcreator.appdata.xml.cmakein index 4d8aabf31cf..3de14afcf39 100644 --- a/share/metainfo/org.qt-project.qtcreator.appdata.xml.cmakein +++ b/share/metainfo/org.qt-project.qtcreator.appdata.xml.cmakein @@ -3,7 +3,10 @@ org.qt-project.qtcreator Qt Creator - Provides a cross-platform, complete integrated development environment (IDE) for application developers to create applications for multiple platforms and devices + + Qt Project + + Cross-platform integrated development environment (IDE) CC0-1.0 GPL-3.0 @@ -23,16 +26,27 @@ newcomers to Qt.

    + org.qt-project.qtcreator.desktop https://www.qt.io/product/development-tools Qt + + Application development life-cycle + https://doc.qt.io/qtcreator/images/qt-app-dev-flow.webp + + Overview https://doc.qt.io/qtcreator/images/qtcreator-breakdown.png - https://doc.qt.io/qtcreator/images/qtcreator-gs-build-example-open.png + Examples + https://doc.qt.io/qtcreator/images/qtcreator-examples-open.webp + + + Code editor + https://doc.qt.io/qtcreator/images/qtcreator-spliteditorview.png @@ -40,6 +54,7 @@

    Qt Creator v${IDE_VERSION_DISPLAY}

    + https://github.com/qt-creator/qt-creator/releases/tag/v${IDE_VERSION_DISPLAY}
    diff --git a/share/qtcreator/CMakeLists.txt b/share/qtcreator/CMakeLists.txt index f8be01a7a7b..6a18147f9fd 100644 --- a/share/qtcreator/CMakeLists.txt +++ b/share/qtcreator/CMakeLists.txt @@ -3,6 +3,8 @@ set(resource_directories cplusplus glsl indexer_preincludes + jsonschemas + lua-plugins modeleditor qmldesigner qmlicons @@ -18,6 +20,7 @@ set(resource_files debugger/.pylintrc debugger/boosttypes.py debugger/cdbbridge.py + debugger/cdbext.pyi debugger/creatortypes.py debugger/dumper.py debugger/gdbbridge.py diff --git a/share/qtcreator/cplusplus/examples/CMakeLists.txt b/share/qtcreator/cplusplus/examples/CMakeLists.txt index 7d14eba5b98..5eafcab4e0b 100644 --- a/share/qtcreator/cplusplus/examples/CMakeLists.txt +++ b/share/qtcreator/cplusplus/examples/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(examples LANGUAGES CXX) 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 99% rename from share/qtcreator/debugger/python2/gdbbridge.py rename to share/qtcreator/debugger-with-python2/gdbbridge.py index d61160eed3b..9699e518fe3 100644 --- a/share/qtcreator/debugger/python2/gdbbridge.py +++ b/share/qtcreator/debugger-with-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/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 99% rename from share/qtcreator/debugger/python2/stdtypes.py rename to share/qtcreator/debugger-with-python2/stdtypes.py index c14812dee1d..8bc86671c69 100644 --- a/share/qtcreator/debugger/python2/stdtypes.py +++ b/share/qtcreator/debugger-with-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/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 diff --git a/share/qtcreator/debugger/LICENSE.MIT b/share/qtcreator/debugger/LICENSE.MIT new file mode 100644 index 00000000000..6dee3d0a7f9 --- /dev/null +++ b/share/qtcreator/debugger/LICENSE.MIT @@ -0,0 +1,20 @@ +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/share/qtcreator/debugger/cdbbridge.py b/share/qtcreator/debugger/cdbbridge.py index b5fc683cbae..afb757ff421 100644 --- a/share/qtcreator/debugger/cdbbridge.py +++ b/share/qtcreator/debugger/cdbbridge.py @@ -7,6 +7,7 @@ import sys import cdbext import re import threading +import time from utils import TypeCode sys.path.insert(1, os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) @@ -75,12 +76,21 @@ class Dumper(DumperBase): self.outputLock = threading.Lock() self.isCdb = True - def enumValue(self, nativeValue): + #FIXME + def register_known_qt_types(self): + DumperBase.register_known_qt_types(self) + typeid = self.typeid_for_string('@QVariantMap') + del self.type_code_cache[typeid] + del self.type_target_cache[typeid] + del self.type_size_cache[typeid] + del self.type_alignment_cache[typeid] + + def enumValue(self, nativeValue: cdbext.Value) -> str: val = nativeValue.nativeDebuggerValue() # remove '0n' decimal prefix of the native cdb value output return val.replace('(0n', '(') - def fromNativeValue(self, nativeValue): + def fromNativeValue(self, nativeValue: cdbext.Value) -> DumperBase.Value: self.check(isinstance(nativeValue, cdbext.Value)) val = self.Value(self) val.name = nativeValue.name() @@ -114,15 +124,16 @@ class Dumper(DumperBase): pass if nativeValue.type().code() == TypeCode.Enum: val.ldisplay = self.enumValue(nativeValue) - elif not nativeValue.type().resolved and nativeValue.type().code() == TypeCode.Struct and not nativeValue.hasChildren(): + elif not nativeValue.type().resolved() and nativeValue.type().code() == TypeCode.Struct and not nativeValue.hasChildren(): val.ldisplay = self.enumValue(nativeValue) val.isBaseClass = val.name == nativeValue.type().name() + val.typeid = self.from_native_type(nativeValue.type()) val.nativeValue = nativeValue val.laddress = nativeValue.address() val.lbitsize = nativeValue.bitsize() return val - def nativeTypeId(self, nativeType): + def nativeTypeId(self, nativeType: cdbext.Type) -> str: self.check(isinstance(nativeType, cdbext.Type)) name = nativeType.name() if name is None or len(name) == 0: @@ -137,14 +148,10 @@ class Dumper(DumperBase): for f in nativeType.fields()]) return typeId - def nativeValueType(self, nativeValue): - return self.fromNativeType(nativeValue.type()) - - def fromNativeType(self, nativeType): + def from_native_type(self, nativeType: cdbext.Type) -> str: self.check(isinstance(nativeType, cdbext.Type)) - typeId = self.nativeTypeId(nativeType) - if self.typeData.get(typeId, None) is not None: - return self.Type(self, typeId) + typeid = self.typeid_for_string(self.nativeTypeId(nativeType)) + self.type_nativetype_cache[typeid] = nativeType if nativeType.name().startswith('void'): nativeType = FakeVoidType(nativeType.name(), self) @@ -154,83 +161,76 @@ class Dumper(DumperBase): if nativeType.name().startswith(''): code = TypeCode.Function elif nativeType.targetName() != nativeType.name(): - return self.createPointerType(nativeType.targetName()) + return self.create_pointer_typeid(self.typeid_for_string(nativeType.targetName())) if code == TypeCode.Array: # cdb reports virtual function tables as arrays those ar handled separetly by # the DumperBase. Declare those types as structs prevents a lookup to a # none existing type if not nativeType.name().startswith('__fptr()') and not nativeType.name().startswith(' int: #DumperBase.warn("NATIVE ALIGN FOR %s" % nativeType.name) def handleItem(nativeFieldType, align): - a = self.fromNativeType(nativeFieldType).alignment() + a = self.type_alignment(self.from_native_type(nativeFieldType)) return a if a > align else align align = 1 for f in nativeType.fields(): align = handleItem(f.type(), align) return align - def nativeTypeEnumDisplay(self, nativeType, intval, form): + def nativeTypeEnumDisplay(self, nativeType: cdbext.Type, intval: int, form) -> str: value = self.nativeParseAndEvaluate('(%s)%d' % (nativeType.name(), intval)) if value is None: return '' return self.enumValue(value) - def enumExpression(self, enumType, enumValue): + def enumExpression(self, enumType: str, enumValue: str) -> str: ns = self.qtNamespace() return ns + "Qt::" + enumType + "(" \ + ns + "Qt::" + enumType + "::" + enumValue + ")" @@ -238,25 +238,25 @@ class Dumper(DumperBase): def pokeValue(self, typeName, *args): return None - def parseAndEvaluate(self, exp): + def parseAndEvaluate(self, exp: str) -> DumperBase.Value: return self.fromNativeValue(self.nativeParseAndEvaluate(exp)) - def nativeParseAndEvaluate(self, exp): + def nativeParseAndEvaluate(self, exp: str) -> cdbext.Value: return cdbext.parseAndEvaluate(exp) - def isWindowsTarget(self): + def isWindowsTarget(self) -> bool: return True - def isQnxTarget(self): + def isQnxTarget(self) -> bool: return False - def isArmArchitecture(self): + def isArmArchitecture(self) -> bool: return False - def isMsvcTarget(self): + def isMsvcTarget(self) -> bool: return True - def qtCoreModuleName(self): + def qtCoreModuleName(self) -> str: modules = cdbext.listOfModules() # first check for an exact module name match for coreName in ['Qt6Core', 'Qt6Cored', 'Qt5Cored', 'Qt5Core', 'QtCored4', 'QtCore4']: @@ -272,7 +272,7 @@ class Dumper(DumperBase): return coreName return None - def qtDeclarativeModuleName(self): + def qtDeclarativeModuleName(self) -> str: modules = cdbext.listOfModules() for declarativeModuleName in ['Qt6Qmld', 'Qt6Qml', 'Qt5Qmld', 'Qt5Qml']: if declarativeModuleName in modules: @@ -285,7 +285,7 @@ class Dumper(DumperBase): return declarativeModuleName return None - def qtHookDataSymbolName(self): + def qtHookDataSymbolName(self) -> str: hookSymbolName = 'qtHookData' coreModuleName = self.qtCoreModuleName() if coreModuleName is not None: @@ -299,7 +299,7 @@ class Dumper(DumperBase): self.qtHookDataSymbolName = lambda: hookSymbolName return hookSymbolName - def qtDeclarativeHookDataSymbolName(self): + def qtDeclarativeHookDataSymbolName(self) -> str: hookSymbolName = 'qtDeclarativeHookData' declarativeModuleName = self.qtDeclarativeModuleName() if declarativeModuleName is not None: @@ -314,27 +314,7 @@ class Dumper(DumperBase): self.qtDeclarativeHookDataSymbolName = lambda: hookSymbolName return hookSymbolName - def qtNamespace(self): - namespace = '' - qstrdupSymbolName = '*qstrdup' - coreModuleName = self.qtCoreModuleName() - if coreModuleName is not None: - qstrdupSymbolName = '%s!%s' % (coreModuleName, qstrdupSymbolName) - resolved = cdbext.resolveSymbol(qstrdupSymbolName) - if resolved: - name = resolved[0].split('!')[1] - namespaceIndex = name.find('::') - if namespaceIndex > 0: - namespace = name[:namespaceIndex + 2] - self.qtNamespace = lambda: namespace - self.qtCustomEventFunc = self.parseAndEvaluate( - '%s!%sQObject::customEvent' % - (self.qtCoreModuleName(), namespace)).address() - self.qtNamespace = lambda: namespace - return namespace - - def qtVersion(self): - qtVersion = None + def extractQtVersion(self) -> int: try: qtVersion = self.parseAndEvaluate( '((void**)&%s)[2]' % self.qtHookDataSymbolName()).integer() @@ -346,13 +326,10 @@ class Dumper(DumperBase): (major, minor, patch) = version.decode('latin1').split('.') qtVersion = 0x10000 * int(major) + 0x100 * int(minor) + int(patch) except: - pass - if qtVersion is None: - qtVersion = self.fallbackQtVersion - self.qtVersion = lambda: qtVersion + return None return qtVersion - def putVtableItem(self, address): + def putVtableItem(self, address: int): funcName = cdbext.getNameByAddress(address) if funcName is None: self.putItem(self.createPointerValue(address, 'void')) @@ -361,7 +338,7 @@ class Dumper(DumperBase): self.putType('void*') self.putAddress(address) - def putVTableChildren(self, item, itemCount): + def putVTableChildren(self, item: DumperBase.Value, itemCount: int) -> int: p = item.address() for i in range(itemCount): deref = self.extractPointer(p) @@ -373,12 +350,12 @@ class Dumper(DumperBase): p += self.ptrSize() return itemCount - def ptrSize(self): + def ptrSize(self) -> int: size = cdbext.pointerSize() self.ptrSize = lambda: size return size - def stripQintTypedefs(self, typeName): + def stripQintTypedefs(self, typeName: str) -> str: if typeName.startswith('qint'): prefix = '' size = typeName[4:] @@ -398,21 +375,7 @@ class Dumper(DumperBase): else: return typeName - def lookupType(self, typeNameIn, module=0): - if len(typeNameIn) == 0: - return None - typeName = self.stripQintTypedefs(typeNameIn) - if self.typeData.get(typeName, None) is None: - nativeType = self.lookupNativeType(typeName, module) - if nativeType is None: - return None - _type = self.fromNativeType(nativeType) - if _type.typeId != typeName: - self.registerTypeAlias(_type.typeId, typeName) - return _type - return self.Type(self, typeName) - - def lookupNativeType(self, name, module=0): + def lookupNativeType(self, name: str, module=0) -> cdbext.Type: if name.startswith('void'): return FakeVoidType(name, self) return cdbext.lookupType(name, module) @@ -420,13 +383,13 @@ class Dumper(DumperBase): def reportResult(self, result, args): cdbext.reportResult('result={%s}' % result) - def readRawMemory(self, address, size): + def readRawMemory(self, address: int, size: int) -> int: mem = cdbext.readRawMemory(address, size) if len(mem) != size: raise Exception("Invalid memory request: %d bytes from 0x%x" % (size, address)) return mem - def findStaticMetaObject(self, type): + def findStaticMetaObject(self, type: DumperBase.Type) -> int: ptr = 0 if type.moduleName is not None: # Try to find the static meta object in the same module as the type definition. This is @@ -439,10 +402,8 @@ class Dumper(DumperBase): ptr = cdbext.getAddressByName(type.name + '::staticMetaObject') return ptr - def warn(self, msg): - self.put('{name="%s",value="",type="",numchild="0"},' % msg) - def fetchVariables(self, args): + start_time = time.perf_counter() self.resetStats() (ok, res) = self.tryFetchInterpreterVariables(args) if ok: @@ -458,13 +419,17 @@ class Dumper(DumperBase): self.anonNumber = 0 variables = [] - for val in cdbext.listOfLocals(self.partialVariable): - dumperVal = self.fromNativeValue(val) - dumperVal.lIsInScope = dumperVal.name not in self.uninitialized - variables.append(dumperVal) + try: + for val in cdbext.listOfLocals(self.partialVariable): + dumperVal = self.fromNativeValue(val) + dumperVal.lIsInScope = dumperVal.name not in self.uninitialized + variables.append(dumperVal) - self.handleLocals(variables) - self.handleWatches(args) + self.handleLocals(variables) + self.handleWatches(args) + except Exception: + t,v,tb = sys.exc_info() + self.showException("FETCH VARIABLES", t, v, tb) self.put('],partial="%d"' % (len(self.partialVariable) > 0)) self.put(',timings=%s' % self.timings) @@ -476,22 +441,18 @@ class Dumper(DumperBase): self.put(',qtnamespace="%s"' % self.qtNamespaceToReport) self.qtNamespaceToReport = None + runtime = time.perf_counter() - start_time + self.put(',runtime="%s"' % runtime) self.reportResult(''.join(self.output), args) self.output = [] def report(self, stuff): sys.stdout.write(stuff + "\n") - def findValueByExpression(self, exp): - return cdbext.parseAndEvaluate(exp) - - def nativeDynamicTypeName(self, address, baseType): - return None # Does not work with cdb - - def nativeValueDereferenceReference(self, value): + def nativeValueDereferenceReference(self, value: DumperBase.Value) -> DumperBase.Value: return self.nativeValueDereferencePointer(value) - def nativeValueDereferencePointer(self, value): + def nativeValueDereferencePointer(self, value: DumperBase.Value) -> DumperBase.Value: def nativeVtCastValue(nativeValue): # If we have a pointer to a derived instance of the pointer type cdb adds a # synthetic '__vtcast_' member as the first child @@ -518,7 +479,7 @@ class Dumper(DumperBase): else: val = self.Value(self) val.laddress = value.pointer() - val._type = DumperBase.Type(self, value.type.targetName) + val.typeid = self.type_target(value.typeid) val.nativeValue = value.nativeValue return val @@ -526,7 +487,7 @@ class Dumper(DumperBase): def callHelper(self, rettype, value, function, args): raise Exception("cdb does not support calling functions") - def nameForCoreId(self, id): + def nameForCoreId(self, id: int) -> DumperBase.Value: for dll in ['Utilsd', 'Utils']: idName = cdbext.call('%s!Utils::nameForId(%d)' % (dll, id)) if idName is not None: @@ -536,427 +497,18 @@ class Dumper(DumperBase): def putCallItem(self, name, rettype, value, func, *args): return - def symbolAddress(self, symbolName): + def symbolAddress(self, symbolName: str) -> int: res = self.nativeParseAndEvaluate(symbolName) return None if res is None else res.address() - def putItemX(self, value): - #DumperBase.warn('PUT ITEM: %s' % value.stringify()) + def wantQObjectNames(self): + return self.showQObjectNames and self.qtCoreModuleName() is not None - typeobj = value.type # unqualified() - typeName = typeobj.name - - self.addToCache(typeobj) # Fill type cache - - if not value.lIsInScope: - self.putSpecialValue('optimizedout') - #self.putType(typeobj) - #self.putSpecialValue('outofscope') - self.putNumChild(0) - return - - if not isinstance(value, self.Value): - raise RuntimeError('WRONG TYPE IN putItem: %s' % type(self.Value)) - - # Try on possibly typedefed type first. - if self.tryPutPrettyItem(typeName, value): - if typeobj.code == TypeCode.Pointer: - self.putOriginalAddress(value.address()) - else: - self.putAddress(value.address()) - return - - if typeobj.code == TypeCode.Pointer: - self.putFormattedPointer(value) - return - - self.putAddress(value.address()) - if value.lbitsize is not None: - self.putField('size', value.lbitsize // 8) - - if typeobj.code == TypeCode.Function: - #DumperBase.warn('FUNCTION VALUE: %s' % value) - self.putType(typeobj) - self.putSymbolValue(value.pointer()) - self.putNumChild(0) - return - - if typeobj.code == TypeCode.Enum: - #DumperBase.warn('ENUM VALUE: %s' % value.stringify()) - self.putType(typeobj.name) - self.putValue(value.display()) - self.putNumChild(0) - return - - if typeobj.code == TypeCode.Array: - #DumperBase.warn('ARRAY VALUE: %s' % value) - self.putCStyleArray(value) - return - - if typeobj.code == TypeCode.Integral: - #DumperBase.warn('INTEGER: %s %s' % (value.name, value)) - val = value.value() - self.putNumChild(0) - self.putValue(val) - self.putType(typeName) - return - - if typeobj.code == TypeCode.Float: - #DumperBase.warn('FLOAT VALUE: %s' % value) - self.putValue(value.value()) - self.putNumChild(0) - self.putType(typeobj.name) - return - - if typeobj.code in (TypeCode.Reference, TypeCode.RValueReference): - #DumperBase.warn('REFERENCE VALUE: %s' % value) - val = value.dereference() - if val.laddress != 0: - self.putItem(val) - else: - self.putSpecialValue('nullreference') - self.putBetterType(typeName) - return - - if typeobj.code == TypeCode.Complex: - self.putType(typeobj) - self.putValue(value.display()) - self.putNumChild(0) - return - - self.putType(typeName) - - if value.summary is not None and self.useFancy: - self.putValue(self.hexencode(value.summary), 'utf8:1:0') - self.putNumChild(0) - return - - self.putExpandable() - self.putEmptyValue() - #DumperBase.warn('STRUCT GUTS: %s ADDRESS: 0x%x ' % (value.name, value.address())) - if self.showQObjectNames: - #with self.timer(self.currentIName): - self.putQObjectNameValue(value) - if self.isExpanded(): - self.putField('sortable', 1) - with Children(self): - baseIndex = 0 - for item in self.listValueChildren(value): - if item.name.startswith('__vfptr'): - with SubItem(self, '[vptr]'): - # int (**)(void) - self.putType(' ') - self.putSortGroup(20) - self.putValue(item.name) - n = 100 - if self.isExpanded(): - with Children(self): - n = self.putVTableChildren(item, n) - self.putNumChild(n) - continue - - if item.isBaseClass: - baseIndex += 1 - # We cannot use nativeField.name as part of the iname as - # it might contain spaces and other strange characters. - with UnnamedSubItem(self, "@%d" % baseIndex): - self.putField('iname', self.currentIName) - self.putField('name', '[%s]' % item.name) - self.putSortGroup(1000 - baseIndex) - self.putAddress(item.address()) - self.putItem(item) - continue - - - with SubItem(self, item.name): - self.putItem(item) - if self.showQObjectNames: - self.tryPutQObjectGuts(value) - - - def putFormattedPointerX(self, value: DumperBase.Value): - self.putOriginalAddress(value.address()) - pointer = value.pointer() - self.putAddress(pointer) - if pointer == 0: - self.putType(value.type) - self.putValue('0x0') - return - - typeName = value.type.name - - try: - self.readRawMemory(pointer, 1) - except: - # Failure to dereference a pointer should at least - # show the value of a pointer. - #DumperBase.warn('BAD POINTER: %s' % value) - self.putValue('0x%x' % pointer) - self.putType(typeName) - return - - if self.currentIName.endswith('.this'): - self.putDerefedPointer(value) - return - - displayFormat = self.currentItemFormat(value.type.name) - - if value.type.targetName == 'void': - #DumperBase.warn('VOID POINTER: %s' % displayFormat) - self.putType(typeName) - self.putSymbolValue(pointer) - return - - if displayFormat == DisplayFormat.Raw: - # Explicitly requested bald pointer. - #DumperBase.warn('RAW') - self.putType(typeName) - self.putValue('0x%x' % pointer) - self.putExpandable() - if self.currentIName in self.expandedINames: - with Children(self): - with SubItem(self, '*'): - self.putItem(value.dereference()) - return - - limit = self.displayStringLimit - if displayFormat in (DisplayFormat.SeparateLatin1String, DisplayFormat.SeparateUtf8String): - limit = 1000000 - if self.tryPutSimpleFormattedPointer(pointer, typeName, - value.type.targetName, displayFormat, limit): - self.putExpandable() - return - - if DisplayFormat.Array10 <= displayFormat and displayFormat <= DisplayFormat.Array10000: - n = (10, 100, 1000, 10000)[displayFormat - DisplayFormat.Array10] - self.putType(typeName) - self.putItemCount(n) - self.putArrayData(value.pointer(), n, value.type.targetName) - return - - #DumperBase.warn('AUTODEREF: %s' % self.autoDerefPointers) - #DumperBase.warn('INAME: %s' % self.currentIName) - if self.autoDerefPointers: - # Generic pointer type with AutomaticFormat, but never dereference char types: - if value.type.targetName not in ( - 'char', - 'signed char', - 'int8_t', - 'qint8', - 'unsigned char', - 'uint8_t', - 'quint8', - 'wchar_t', - 'CHAR', - 'WCHAR', - 'char8_t', - 'char16_t', - 'char32_t' - ): - self.putDerefedPointer(value) - return - - #DumperBase.warn('GENERIC PLAIN POINTER: %s' % value.type) - #DumperBase.warn('ADDR PLAIN POINTER: 0x%x' % value.laddress) - self.putType(typeName) - self.putSymbolValue(pointer) - self.putExpandable() - if self.currentIName in self.expandedINames: - with Children(self): - with SubItem(self, '*'): - self.putItem(value.dereference()) - - - def putCStyleArray(self, value): - arrayType = value.type - innerType = arrayType.ltarget - address = value.address() - if address: - self.putValue('@0x%x' % address, priority=-1) - else: - self.putEmptyValue() - self.putType(arrayType) - - displayFormat = self.currentItemFormat() - arrayByteSize = arrayType.size() - n = self.arrayItemCountFromTypeName(value.type.name, 100) - - p = value.address() - if displayFormat != DisplayFormat.Raw and p: - if innerType.name in ( - 'char', - 'int8_t', - 'qint8', - 'wchar_t', - 'unsigned char', - 'uint8_t', - 'quint8', - 'signed char', - 'CHAR', - 'WCHAR', - 'char8_t', - 'char16_t', - 'char32_t' - ): - self.putCharArrayHelper(p, n, innerType, self.currentItemFormat(), - makeExpandable=False) - else: - self.tryPutSimpleFormattedPointer(p, arrayType, innerType, - displayFormat, arrayByteSize) - self.putNumChild(n) - - if self.isExpanded(): - if n > 100: - addrStep = innerType.size() - with Children(self, n, innerType, addrBase=address, addrStep=addrStep): - for i in self.childRange(): - self.putSubItem(i, self.createValue(address + i * addrStep, innerType)) - else: - with Children(self): - n = 0 - for item in self.listValueChildren(value): - with SubItem(self, n): - n += 1 - self.putItem(item) - - - def putArrayData(self, base, n, innerType, childNumChild=None): - self.checkIntType(base) - self.checkIntType(n) - addrBase = base - innerType = self.createType(innerType) - innerSize = innerType.size() - self.putNumChild(n) - #DumperBase.warn('ADDRESS: 0x%x INNERSIZE: %s INNERTYPE: %s' % (addrBase, innerSize, innerType)) - enc = innerType.simpleEncoding() - maxNumChild = self.maxArrayCount() - if enc: - self.put('childtype="%s",' % innerType.name) - self.put('addrbase="0x%x",' % addrBase) - self.put('addrstep="0x%x",' % innerSize) - self.put('arrayencoding="%s",' % enc) - self.put('endian="%s",' % self.packCode) - if n > maxNumChild: - self.put('childrenelided="%s",' % n) - n = maxNumChild - self.put('arraydata="') - self.put(self.readMemory(addrBase, n * innerSize)) - self.put('",') - else: - with Children(self, n, innerType, childNumChild, maxNumChild, - addrBase=addrBase, addrStep=innerSize): - for i in self.childRange(): - self.putSubItem(i, self.createValue(addrBase + i * innerSize, innerType)) - - def tryPutSimpleFormattedPointer(self, ptr, typeName, innerType, displayFormat, limit): - if isinstance(innerType, self.Type): - innerType = innerType.name - if displayFormat == DisplayFormat.Automatic: - if innerType in ('char', 'signed char', 'unsigned char', 'uint8_t', 'CHAR'): - # Use UTF-8 as default for char *. - self.putType(typeName) - (length, shown, data) = self.readToFirstZero(ptr, 1, limit) - self.putValue(data, 'utf8', length=length) - if self.isExpanded(): - self.putArrayData(ptr, shown, innerType) - return True - - if innerType in ('wchar_t', 'WCHAR'): - self.putType(typeName) - charSize = self.lookupType('wchar_t').size() - (length, data) = self.encodeCArray(ptr, charSize, limit) - if charSize == 2: - self.putValue(data, 'utf16', length=length) - else: - self.putValue(data, 'ucs4', length=length) - return True - - if displayFormat == DisplayFormat.Latin1String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 1, limit) - self.putValue(data, 'latin1', length=length) - return True - - if displayFormat == DisplayFormat.SeparateLatin1String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 1, limit) - self.putValue(data, 'latin1', length=length) - self.putDisplay('latin1:separate', data) - return True - - if displayFormat == DisplayFormat.Utf8String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 1, limit) - self.putValue(data, 'utf8', length=length) - return True - - if displayFormat == DisplayFormat.SeparateUtf8String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 1, limit) - self.putValue(data, 'utf8', length=length) - self.putDisplay('utf8:separate', data) - return True - - if displayFormat == DisplayFormat.Local8BitString: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 1, limit) - self.putValue(data, 'local8bit', length=length) - return True - - if displayFormat == DisplayFormat.Utf16String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 2, limit) - self.putValue(data, 'utf16', length=length) - return True - - if displayFormat == DisplayFormat.Ucs4String: - self.putType(typeName) - (length, data) = self.encodeCArray(ptr, 4, limit) - self.putValue(data, 'ucs4', length=length) - return True - - return False - - def putDerefedPointer(self, value): - derefValue = value.dereference() - savedCurrentChildType = self.currentChildType - self.currentChildType = value.type.targetName - self.putType(value.type.targetName) - derefValue.name = '*' - derefValue.autoDerefCount = value.autoDerefCount + 1 - - if derefValue.type.code == TypeCode.Pointer: - self.putField('autoderefcount', '{}'.format(derefValue.autoDerefCount)) - - self.putItem(derefValue) - self.currentChildType = savedCurrentChildType - - def extractPointer(self, value): - code = 'I' if self.ptrSize() == 4 else 'Q' - return self.extractSomething(value, code, 8 * self.ptrSize()) - - def createValue(self, datish, typish): - if self.isInt(datish): # Used as address. - return self.createValueFromAddressAndType(datish, typish) - if isinstance(datish, bytes): - val = self.Value(self) - if isinstance(typish, self.Type): - val._type = typish - else: - val._type = self.Type(self, typish) - #DumperBase.warn('CREATING %s WITH DATA %s' % (val.type.name, self.hexencode(datish))) - val.ldata = datish - val.check() - return val - raise RuntimeError('EXPECTING ADDRESS OR BYTES, GOT %s' % type(datish)) - - def createValueFromAddressAndType(self, address, typish): - val = self.Value(self) - if isinstance(typish, self.Type): - val._type = typish - else: - val._type = self.Type(self, typish) - val.laddress = address - if self.useDynamicType: - val._type = val.type.dynamicType(address) - return val + def fetchInternalFunctions(self): + coreModuleName = self.qtCoreModuleName() + ns = self.qtNamespace() + if coreModuleName is not None: + self.qtCustomEventFunc = self.parseAndEvaluate( + '%s!%sQObject::customEvent' % + (self.qtCoreModuleName(), ns)).address() + self.fetchInternalFunctions = lambda: None diff --git a/share/qtcreator/debugger/cdbext.pyi b/share/qtcreator/debugger/cdbext.pyi new file mode 100644 index 00000000000..27a3538cfe9 --- /dev/null +++ b/share/qtcreator/debugger/cdbext.pyi @@ -0,0 +1,51 @@ +class Type: ... + +class Field: + def name(self) -> str : ... + def isBaseClass(self) -> bool : ... + def type(self) -> Type : ... + def parentType(self) -> Type : ... + def bitsize(self) -> int : ... + def bitpos(self) -> int : ... + +class Type: + def name(self) -> str: ... + def bitsize(self) -> int : ... + def code(self) -> int : ... + def unqualified(self) -> bool : ... + def target(self) -> Type : ... + def targetName(self) -> str : ... + def stripTypedef(self) -> Type : ... + def fields(self) -> Field : ... + def module(self) -> str : ... + def moduleId(self) -> int : ... + def arrayElements(self) -> int : ... + def templateArguments(self) -> list[int | str] : ... + def resolved(self) -> bool : ... + +class Value: ... +class Value: + def name(self) -> str : ... + def type(self) -> Type : ... + def bitsize(self) -> int : ... + def asBytes(self) -> bytes : ... + def address(self) -> int : ... + def hasChildren(self) -> bool : ... + def expand(self) -> bool : ... + def nativeDebuggerValue(self) -> str : ... + def childFromName(self) -> Value : ... + def childFromField(self) -> Value : ... + def childFromIndex(self) -> Value : ... + +def parseAndEvaluate() -> Value : ... +def resolveSymbol() -> list[str] : ... +def getNameByAddress() -> str : ... +def getAddressByName() -> int : ... +def lookupType() -> Type | None : ... +def listOfLocals() -> list[Value] : ... +def listOfModules() -> list[str] : ... +def pointerSize() -> int : ... +def readRawMemory() -> bytes : ... +def createValue() -> Value | None : ... +def call() -> Value | None : ... +def reportResult() -> None : ... diff --git a/share/qtcreator/debugger/creatortypes.py b/share/qtcreator/debugger/creatortypes.py index ba5b53450b0..9c2933ba06b 100644 --- a/share/qtcreator/debugger/creatortypes.py +++ b/share/qtcreator/debugger/creatortypes.py @@ -53,7 +53,7 @@ def readTemplateName(d, value): def readLiteral(d, value): if not value.integer(): return "" - type = typeTarget(value.type.unqualified()) + type = typeTarget(value.type) if type and (type.name == "CPlusPlus::TemplateNameId"): return readTemplateName(d, value) elif type and (type.name == "CPlusPlus::QualifiedNameId"): diff --git a/share/qtcreator/debugger/dumper.py b/share/qtcreator/debugger/dumper.py index 059bf7b23e7..29fa29e0eb0 100644 --- a/share/qtcreator/debugger/dumper.py +++ b/share/qtcreator/debugger/dumper.py @@ -3,7 +3,7 @@ import os import codecs -import collections +import functools import glob import struct import sys @@ -31,11 +31,7 @@ except: def hexencode_(s): return ''.join(["%x" % c for c in s]) -if sys.version_info[0] >= 3: - toInteger = int -else: - toInteger = long - +toInteger = int class ReportItem(): """ @@ -55,19 +51,6 @@ class ReportItem(): % (self.value, self.encoding, self.priority, self.length) -class Timer(): - def __init__(self, d, desc): - self.d = d - self.desc = desc + '-' + d.currentIName - - def __enter__(self): - self.starttime = time.time() - - def __exit__(self, exType, exValue, exTraceBack): - elapsed = int(1000 * (time.time() - self.starttime)) - self.d.timings.append([self.desc, elapsed]) - - class Children(): def __init__(self, d, numChild=1, childType=None, childNumChild=None, maxNumChild=None, addrBase=None, addrStep=None): @@ -147,20 +130,28 @@ class UnnamedSubItem(SubItem): class DumperBase(): @staticmethod def warn(message): - print('bridgemessage={msg="%s"},' % message.replace('"', '$').encode('latin1')) + print('bridgemessage={msg="%s"}' % message.replace('"', "'").replace('\\', '\\\\')) - @staticmethod - def showException(msg, exType, exValue, exTraceback): - DumperBase.warn('**** CAUGHT EXCEPTION: %s ****' % msg) + #@staticmethod + def showException(self, msg, exType, exValue, exTraceback): + self.warn('**** CAUGHT EXCEPTION: %s ****' % msg) try: import traceback - for line in traceback.format_exception(exType, exValue, exTraceback): - DumperBase.warn('%s' % line) + for frame_desc in traceback.format_exception(exType, exValue, exTraceback): + for line in frame_desc.split('\n'): + self.warn(line) except: pass - def timer(self, desc): - return Timer(self, desc) + def dump_location(self): + import traceback + from io import StringIO + io = StringIO() + traceback.print_stack(file=io) + data = io.getvalue() + self.warn('LOCATION:') + for line in data.split('\n')[:-3]: + self.warn(line) def __init__(self): self.isCdb = False @@ -181,11 +172,10 @@ class DumperBase(): self.qtCustomEventFunc = 0 self.qtCustomEventPltFunc = 0 self.qtPropertyFunc = 0 - self.fallbackQtVersion = 0x60200 self.passExceptions = False self.isTesting = False + self.qtLoaded = False - self.typeData = {} self.isBigEndian = False self.packCode = '<' @@ -197,6 +187,13 @@ class DumperBase(): self.dumpermodules = [] + # These are sticky for the session + self.qtversion = None + self.qtversionAtLeast6 = None + self.qtnamespace = None + + self.init_type_cache() + try: # Fails in the piping case self.dumpermodules = [ @@ -217,9 +214,10 @@ class DumperBase(): self.currentPrintsAddress = True self.currentChildType = None self.currentChildNumChild = None - self.registerKnownTypes() + self.register_known_simple_types() def setVariableFetchingOptions(self, args): + self.last_args = args self.resultVarName = args.get('resultvarname', '') self.expandedINames = args.get('expanded', {}) self.stringCutOff = int(args.get('stringcutoff', 10000)) @@ -238,15 +236,80 @@ class DumperBase(): self.useTimeStamps = int(args.get('timestamps', '0')) self.partialVariable = args.get('partialvar', '') self.uninitialized = args.get('uninitialized', []) - self.uninitialized = list(map(lambda x: self.hexdecode(x), self.uninitialized)) - self.partialUpdate = int(args.get('partial', '0')) - #DumperBase.warn('NAMESPACE: "%s"' % self.qtNamespace()) - #DumperBase.warn('EXPANDED INAMES: %s' % self.expandedINames) - #DumperBase.warn('WATCHERS: %s' % self.watchers) - def setFallbackQtVersion(self, args): - version = int(args.get('version', self.fallbackQtVersion)) - self.fallbackQtVersion = version + self.uninitialized = list(map(lambda x: self.hexdecode(x), self.uninitialized)) + + if self.qtversion is None: + self.qtversion = args.get('qtversion', None) + if self.qtversion == 0: + self.qtversion = None + if self.qtnamespace is None: + self.qtnamespace = args.get('qtnamespace', None) + + #self.warn('NAMESPACE: "%s"' % self.qtNamespace()) + #self.warn('EXPANDED INAMES: %s' % self.expandedINames) + #self.warn('WATCHERS: %s' % self.watchers) + + # Call this with 'py theDumper.profile1() from Creator + def profile(self): + '''Internal profiling''' + import cProfile + import visualize + profiler = cProfile.Profile() + profiler.enable() + self.profiled_command() + profiler.disable() + visualize.profile_visualize(profiler.getstats()) + + def profiled_command(self): + args = self.last_args + args['partialvar'] = '' + self.fetchVariables(args) + + def extractQtVersion(self): + # can be overridden in bridges + pass + + def qtVersion(self): + if self.qtversion: + return self.qtversion + + #self.warn("ACCESSING UNKNOWN QT VERSION") + self.qtversion = self.extractQtVersion() + if self.qtversion: + return self.qtversion + + #self.warn("EXTRACTING QT VERSION FAILED. GUESSING NOW.") + if self.qtversionAtLeast6 is None or self.qtversionAtLeast6 is True: + return 0x060602 + return 0x050f00 + + def qtVersionAtLeast(self, version): + # A hack to cover most of the changes from Qt 5 to 6 + if version == 0x60000 and self.qtversionAtLeast6 is not None: + return self.qtversionAtLeast6 + if version == 0x50000: # FIXME: This drops unknown 4.x for now + return True + return self.qtVersion() >= version + + def qtVersionPing(self, typeid, size_for_qt5=-1): + # To be called from places where the type size is sufficient + # to distinguish Qt 5.x and 6.x + if size_for_qt5 == -1: + size_for_qt5 = self.ptrSize() + test_size = self.type_size(typeid) + self.setQtVersionAtLeast6(test_size > size_for_qt5) + + def setQtVersionAtLeast6(self, is6): + if self.qtversionAtLeast6 is None: + #self.warn("SETTING Qt VERSION AT LEAST 6 TO %s" % is6) + self.qtversionAtLeast6 = is6 + self.register_known_qt_types() + #else: + # self.warn("QT VERSION ALREADY KNOWN") + + def qtNamespace(self): + return '' if self.qtnamespace is None else self.qtnamespace def resetPerStepCaches(self): self.perStepCache = {} @@ -279,7 +342,6 @@ class DumperBase(): self.generalCache = {} self.counts = {} - self.structPatternCache = {} self.timings = [] self.expandableINames = set({}) @@ -331,7 +393,7 @@ class DumperBase(): self.currentType = ReportItem() def exitSubItem(self, item, exType, exValue, exTraceBack): - #DumperBase.warn('CURRENT VALUE: %s: %s %s' % + #self.warn('CURRENT VALUE: %s: %s %s' % # (self.currentIName, self.currentValue, self.currentType)) if exType is not None: if self.passExceptions: @@ -341,9 +403,9 @@ class DumperBase(): if not self.isCli: try: if self.currentType.value: - typeName = self.currentType.value - if len(typeName) > 0 and typeName != self.currentChildType: - self.putField('type', typeName) + typename = self.currentType.value + if len(typename) > 0 and typename != self.currentChildType: + self.putField('type', typename) if self.currentValue.value is None: self.put('value="",encoding="notaccessible",numchild="0",') else: @@ -361,8 +423,8 @@ class DumperBase(): self.indent -= 1 try: if self.currentType.value: - typeName = self.currentType.value - self.put('<%s> = {' % typeName) + typename = self.currentType.value + self.put('<%s> = {' % typename) if self.currentValue.value is None: self.put('') @@ -388,14 +450,14 @@ class DumperBase(): self.currentType = item.savedType return True - def stripForFormat(self, typeName): - if not isinstance(typeName, str): - raise RuntimeError('Expected string in stripForFormat(), got %s' % type(typeName)) - if typeName in self.cachedFormats: - return self.cachedFormats[typeName] + def stripForFormat(self, typename): + if not isinstance(typename, str): + raise RuntimeError('Expected string in stripForFormat(), got %s' % type(typename)) + if typename in self.cachedFormats: + return self.cachedFormats[typename] stripped = '' inArray = 0 - for c in typeName: + for c in typename: if c == '<': break if c == ' ': @@ -407,59 +469,200 @@ class DumperBase(): if inArray and ord(c) >= 48 and ord(c) <= 57: continue stripped += c - self.cachedFormats[typeName] = stripped + self.cachedFormats[typename] = stripped return stripped - def templateArgument(self, typeobj, position): - return typeobj.templateArgument(position) + def templateArgument(self, typeobj, index): + return self.type_template_argument(typeobj.typeid, index) def intType(self): - result = self.lookupType('int') - self.intType = lambda: result - return result + return self.type_for_int def charType(self): - result = self.lookupType('char') - self.charType = lambda: result - return result + return self.type_for_char def ptrSize(self): result = self.lookupType('void*').size() self.ptrSize = lambda: result return result - def lookupType(self, typeName): - nativeType = self.lookupNativeType(typeName) - return None if nativeType is None else self.fromNativeType(nativeType) + def lookupType(self, typename): + if not isinstance(typename, str): + raise RuntimeError('ARG ERROR FOR lookupType, got %s' % type(typename)) - def registerKnownTypes(self): - tdata = self.TypeData(self, 'unsigned short') - tdata.lbitsize = 16 - tdata.lalignment = 2 - tdata.code = TypeCode.Integral + typeid = self.typeid_for_string(typename) + native_type = self.type_nativetype_cache.get(typeid) + if native_type is None: + native_type = self.lookupNativeType(typename) + if native_type is None: + #sCANNOT DETERMINE SIZE FOR TYelf.dump_location() + self.dump_location() + self.warn("TYPEIDS: %s" % self.typeid_cache) + self.warn("COULD NOT FIND TYPE '%s'" % typename) + return None - tdata = self.TypeData(self, 'QChar') - tdata.lbitsize = 16 - tdata.lalignment = 2 - tdata.code = TypeCode.Struct - tdata.lfields = [self.Field(dumper=self, name='ucs', - type='unsigned short', bitsize=16, bitpos=0)] - tdata.templateArguments = lambda: [] + self.type_nativetype_cache[typeid] = native_type + typeid = self.from_native_type(native_type) + if typeid == 0: + return None + return self.Type(self, typeid) + + def register_type(self, name, code, size, enc=None): + typeid = self.typeid_for_string(name) + self.type_code_cache[typeid] = code + self.type_size_cache[typeid] = size + self.type_alignment_cache[typeid] = size + if enc is not None: + self.type_encoding_cache[typeid] = enc + return typeid + + def register_int(self, name, size, enc=None): + typeid = self.typeid_for_string(name) + self.type_code_cache[typeid] = TypeCode.Integral + self.type_size_cache[typeid] = size + self.type_alignment_cache[typeid] = size + if enc is not None: + self.type_encoding_cache[typeid] = enc + return typeid + + def register_enum(self, name, size): + typeid = self.typeid_for_string(name) + self.type_code_cache[typeid] = TypeCode.Enum + self.type_size_cache[typeid] = size + self.type_alignment_cache[typeid] = size + return typeid + + def register_typedef(self, name, target_typeid): + typeid = self.typeid_for_string(name) + self.type_code_cache[typeid] = TypeCode.Typedef + self.type_target_cache[typeid] = target_typeid + self.type_size_cache[typeid] = self.type_size_cache[target_typeid] + self.type_alignment_cache[typeid] = self.type_alignment_cache[target_typeid] + return typeid + + def register_struct(self, name, p5=0, p6=0, s=0, qobject_based=False): + # p5 = n -> n * ptrsize for Qt 5 + # p6 = n -> n * ptrsize for Qt 6 + if self.qtversionAtLeast6 is None: + self.warn("TOO EARLY TO GUESS QT VERSION") + size = 8 * p6 + s + elif self.qtversionAtLeast6 is True: + size = 8 * p6 + s + else: + size = 8 * p5 + s + typeid = self.typeid_for_string(name) + self.type_code_cache[typeid] = TypeCode.Struct + self.type_size_cache[typeid] = size + self.type_qobject_based_cache[typeid] = qobject_based + self.type_alignment_cache[typeid] = 8 + return typeid + + def register_known_simple_types(self): + typeid = 0 + self.typeid_cache[''] = typeid + self.type_code_cache[typeid] = TypeCode.Void + self.type_name_cache[typeid] = '' + self.type_size_cache[typeid] = 1 + + typeid_char = self.register_int('char', 1, 'uint:1') + self.type_for_char = self.Type(self, typeid_char) + self.register_int('signed char', 1, 'int:1') + self.register_int('unsigned char', 1, 'uint:1') + self.register_int('bool', 1, 'uint:1') + self.register_int('char8_t', 1, 'uint:1') + self.register_int('int8_t', 1, 'int:1') + self.register_int('uint8_t', 1, 'uint:1') + self.register_int('qint8', 1, 'int:1') + self.register_int('quint8', 1, 'uint:1') + + self.register_int('short', 2, 'int:2') + self.register_int('short int', 2, 'int:2') + self.register_int('signed short', 2, 'int:2') + self.register_int('signed short int', 2, 'int:2') + typeid_unsigned_short = \ + self.register_int('unsigned short', 2, 'uint:2') + self.register_int('unsigned short int', 2, 'uint:2') + self.register_int('char16_t', 2, 'uint:2') + self.register_int('int16_t', 2, 'int:2') + self.register_int('uint16_t', 2, 'uint:2') + self.register_int('qint16', 2, 'int:2') + self.register_int('quint16', 2, 'uint:2') + + typeid_int = self.register_type('int', 4, 'int:4') + self.type_for_int = self.Type(self, typeid_int) + self.register_int('int', 4, 'int:4') + self.register_int('signed int', 4, 'int:4') + self.register_int('unsigned int', 4, 'uint:4') + self.register_int('char32_t', 4, 'int:4') + self.register_int('int32_t', 4, 'int:4') + self.register_int('uint32_t', 4, 'uint:4') + self.register_int('qint32', 4, 'int:4') + self.register_int('quint32', 4, 'uint:4') + + self.register_int('long long', 8, 'int:8') + self.register_int('signed long long', 8, 'int:8') + self.register_int('unsigned long long', 8, 'uint:8') + self.register_int('int64_t', 8, 'int:8') + self.register_int('uint64_t', 8, 'uint:8') + self.register_int('qint64', 8, 'int:8') + self.register_int('quint64', 8, 'uint:8') + + self.register_type('float', TypeCode.Float, 4, 'float:4') + typeid_double = self.register_type('double', TypeCode.Float, 8, 'float:8') + self.register_typedef('qreal', typeid_double) + + typeid_qchar = self.register_type('@QChar', TypeCode.Struct, 2, 'uint:2') + #self.type_fields_cache[typeid_qchar] = [ + # self.Field(name='ucs', typeid=typeid_unsigned_short, bitsize=16, bitpos=0)] + + self.register_enum('@Qt::ItemDataRole', 4) + + def register_known_qt_types(self): + #self.warn("REGISTERING KNOWN QT TYPES NOW") + self.register_struct('@QObject', p5=2, p6=2, qobject_based=True) + self.register_struct('@QObjectPrivate', p5=10, p6=10) # FIXME: Not exact + + self.register_struct('@QByteArray', p5=1, p6=3) + self.register_struct('@QString', p5=1, p6=3) + self.register_struct('@QStandardItemData', p5=3, p6=5) + self.register_struct('@QVariant', p5=2, p6=4) + self.register_struct('@QXmlAttributes::Attribute', p5=4, p6=12) + + self.register_struct('@QList<@QObject*>', p5=1, p6=3) + self.register_struct('@QList<@QStandardItemData>', p5=1, p6=3) + self.register_struct('@QList<@QRect>', p5=1, p6=3) + + typeid_var_list = self.register_struct('@QList<@QVariant>', p5=1, p6=3) + self.register_typedef('@QVariantList', typeid_var_list) + + typeid_var_map = self.register_struct('@QMap<@QString, @QVariant>', p5=1, p6=1) + self.register_typedef('@QVariantMap', typeid_var_map) + + typeid_var_hash = self.register_struct('@QHash<@QString, @QVariant>', p5=1, p6=1) + self.register_typedef('@QVariantHash', typeid_var_hash) + + self.register_struct('@QPoint', s=8) + self.register_struct('@QPointF', s=16) + self.register_struct('@QLine', s=16) + self.register_struct('@QLineF', s=32) + + # FIXME: Comment out for production, see [MARK_A] + name1 = 'std::__cxx11::basic_string,std::allocator>' + self.register_struct(name1, p6=4) def nativeDynamicType(self, address, baseType): return baseType # Override in backends. - def listTemplateParameters(self, typename): - return self.listTemplateParametersManually(typename) - - def listTemplateParametersManually(self, typename): + def fill_template_parameters_manually(self, typeid): + typename = self.type_name(typeid) # Undo id mangling for template typedefs. Relevant for QPair. if typename.endswith('}'): typename = typename[typename.find('{') + 1 : -1] - targs = [] if not typename.endswith('>'): - return targs + return + + targs = [] def push(inner): # Handle local struct definitions like QList @@ -471,14 +674,14 @@ class DumperBase(): inner = inner[6:].strip() if inner.endswith(' const'): inner = inner[:-6].strip() - #DumperBase.warn("FOUND: %s" % inner) + #self.warn("FOUND: %s" % inner) targs.append(inner) - #DumperBase.warn("SPLITTING %s" % typename) + #self.warn("SPLITTING %s" % typename) level = 0 inner = '' for c in typename[::-1]: # Reversed... - #DumperBase.warn("C: %s" % c) + #self.warn("C: %s" % c) if c == '>': if level > 0: inner += c @@ -492,7 +695,7 @@ class DumperBase(): inner = '' break elif c == ',': - #DumperBase.warn('c: %s level: %s' % (c, level)) + #self.warn('c: %s level: %s' % (c, level)) if level == 1: push(inner) inner = '' @@ -501,35 +704,38 @@ class DumperBase(): else: inner += c - #DumperBase.warn("TARGS: %s %s" % (typename, targs)) - res = [] + #self.warn("TARGS: %s %s" % (typename, targs)) + idx = 0 for item in targs[::-1]: if len(item) == 0: continue - c = ord(item[0]) - if c in (45, 46) or (c >= 48 and c < 58): # '-', '.' or digit. - if item.find('.') > -1: - res.append(float(item)) - else: - if item.endswith('l'): - item = item[:-1] - if item.endswith('u'): - item = item[:-1] - val = toInteger(item) - if val > 0x80000000: - val -= 0x100000000 - res.append(val) + if item == "false": # Triggered in StdTuple dumper + self.type_template_arguments_cache[(typeid, idx)] = False + elif item == "true": + self.type_template_arguments_cache[(typeid, idx)] = True else: - res.append(self.Type(self, item)) - #DumperBase.warn("RES: %s %s" % (typename, [(None if t is None else t.name) for t in res])) - return res + c = ord(item[0]) + if c in (45, 46) or (c >= 48 and c < 58): # '-', '.' or digit. + if '.' in item: + self.type_template_arguments_cache[(typeid, idx)] = float(item) + else: + if item.endswith('l'): + item = item[:-1] + if item.endswith('u'): + item = item[:-1] + val = int(item) + if val > 0x80000000: + val -= 0x100000000 + self.type_template_arguments_cache[(typeid, idx)] = val + else: + targ = self.Type(self, self.create_typeid_from_name(item)) + self.type_template_arguments_cache[(typeid, idx)] = targ + idx += 1 + #self.warn('MANUAL: %s %s' % (type_name, targs)) # Hex decoding operating on str, return str. @staticmethod def hexdecode(s, encoding='utf8'): - if sys.version_info[0] == 2: - # For python2 we need an extra str() call to return str instead of unicode - return str(s.decode('hex').decode(encoding)) return bytes.fromhex(s).decode(encoding) # Hex encoding operating on str or bytes, return str. @@ -537,10 +743,6 @@ class DumperBase(): def hexencode(s): if s is None: s = '' - if sys.version_info[0] == 2: - if isinstance(s, buffer): - return bytes(s).encode('hex') - return s.encode('hex') if isinstance(s, str): s = s.encode('utf8') return hexencode_(s) @@ -558,9 +760,9 @@ class DumperBase(): return limit def vectorData(self, value): - if self.qtVersion() >= 0x060000: + if self.qtVersionAtLeast(0x060000): data, length, alloc = self.qArrayData(value) - elif self.qtVersion() >= 0x050000: + elif self.qtVersionAtLeast(0x050000): vector_data_ptr = self.extractPointer(value) if self.ptrSize() == 4: (ref, length, alloc, offset) = self.split('IIIp', vector_data_ptr) @@ -576,7 +778,7 @@ class DumperBase(): return data, length def qArrayData(self, value): - if self.qtVersion() >= 0x60000: + if self.qtVersionAtLeast(0x60000): dd, data, length = self.split('ppp', value) if dd: _, _, alloc = self.split('iip', dd) @@ -587,7 +789,7 @@ class DumperBase(): def qArrayDataHelper(self, array_data_ptr): # array_data_ptr is what is e.g. stored in a QByteArray's d_ptr. - if self.qtVersion() >= 0x050000: + if self.qtVersionAtLeast(0x050000): # QTypedArray: # - QtPrivate::RefCount ref # - int length @@ -600,7 +802,7 @@ class DumperBase(): data = data & 0xffffffff else: data = data & 0xffffffffffffffff - elif self.qtVersion() >= 0x040000: + elif self.qtVersionAtLeast(0x040000): # Data: # - QBasicAtomicInt ref; # - int alloc, length; @@ -619,7 +821,7 @@ class DumperBase(): (dummy, dummy, dummy, length) = self.split('IIIp', array_data_ptr) length = self.extractInt(array_data_ptr + 3 * self.ptrSize()) & 0x3ffffff alloc = length # pretend. - data = self.extractPointer(array_data_ptr + self.ptrSize()) + data = self.extract_pointer_at_address(array_data_ptr + self.ptrSize()) return data, length, alloc def encodeStringHelper(self, value, limit): @@ -666,14 +868,14 @@ class DumperBase(): displayFormat=DisplayFormat.Automatic, makeExpandable=True): charSize = charType.size() - self.putCharArrayValue(data, size, charSize, displayFormat=displayFormat) + self.putCharArrayValue(data, size, charSize, displayFormat) if makeExpandable: self.putNumChild(size) if self.isExpanded(): with Children(self): for i in range(size): - self.putSubItem(size, self.createValue(data + i * charSize, charType)) + self.putSubItem(size, self.createValueFromAddress(data + i * charSize, charType)) def readMemory(self, addr, size): return self.hexencode(bytes(self.readRawMemory(addr, size))) @@ -699,39 +901,6 @@ class DumperBase(): def stringData(self, value): # -> (data, size, alloc) return self.qArrayData(value) - def extractTemplateArgument(self, typename, position): - level = 0 - skipSpace = False - inner = '' - for c in typename[typename.find('<') + 1: -1]: - if c == '<': - inner += c - level += 1 - elif c == '>': - level -= 1 - inner += c - elif c == ',': - if level == 0: - if position == 0: - return inner.strip() - position -= 1 - inner = '' - else: - inner += c - skipSpace = True - else: - if skipSpace and c == ' ': - pass - else: - inner += c - skipSpace = False - # Handle local struct definitions like QList - inner = inner.strip() - p = inner.find(')::') - if p > -1: - inner = inner[p + 3:] - return inner - def putStringValue(self, value): length, data = self.encodeStringHelper(value, self.displayStringLimit) self.putValue(data, 'utf16', length=length) @@ -750,10 +919,9 @@ class DumperBase(): self.putType('int') def putEnumItem(self, name, ival, typish): - buf = bytearray(struct.pack('i', ival)) val = self.Value(self) - val.ldata = bytes(buf) - val._type = self.createType(typish) + val.ldata = ival + val.typeid = self.create_typeid(typish) with SubItem(self, name): self.putItem(val) @@ -826,15 +994,19 @@ class DumperBase(): def putSymbolValue(self, address): self.putValue(self.prettySymbolByAddress(address)) - def putVTableChildren(self, item, itemCount): - p = item.pointer() + def putVTableChildren(self, value, itemCount): + p = self.value_as_address(value) + entry_typeid = self.create_pointer_typeid(self.create_typeid('void')) for i in range(itemCount): - deref = self.extractPointer(p) + deref = self.extract_pointer_at_address(p) if deref == 0: itemCount = i break with SubItem(self, i): - self.putItem(self.createPointerValue(deref, 'void')) + val = self.Value(self) + val.ldata = deref + val.typeid = entry_typeid + self.putItem(val) p += self.ptrSize() return itemCount @@ -842,7 +1014,9 @@ class DumperBase(): baseIndex = 0 for item in value.members(True): if item.name is not None: - if item.name.startswith('_vptr.') or item.name.startswith('__vfptr'): + if (item.name.startswith('_vptr.') + or item.name.startswith('_vptr$') + or item.name.startswith('__vfptr')): with SubItem(self, '[vptr]'): # int (**)(void) self.putType(' ') @@ -892,15 +1066,21 @@ class DumperBase(): def check(self, exp): if not exp: + self.warn('Check failed: %s' % exp) + self.dump_location() raise RuntimeError('Check failed: %s' % exp) + def check_typeid(self, typeid): + if not isinstance(typeid, int): + raise RuntimeError('WRONG TYPE FOR TYPEID: %s %s' % (str(typeid), type(typeid))) + def checkRef(self, ref): # Assume there aren't a million references to any object. self.check(ref >= -1) self.check(ref < 1000000) def checkIntType(self, thing): - if not self.isInt(thing): + if not isinstance(thing, int): raise RuntimeError('Expected an integral value, got %s' % type(thing)) def readToFirstZero(self, base, typesize, maximum): @@ -919,7 +1099,7 @@ class DumperBase(): maximum = int(maximum / 2) self.warn('REDUCING READING MAXIMUM TO %s' % maximum) - #DumperBase.warn('BASE: 0x%x TSIZE: %s MAX: %s' % (base, typesize, maximum)) + #self.warn('BASE: 0x%x TSIZE: %s MAX: %s' % (base, typesize, maximum)) for i in range(0, maximum, typesize): t = struct.unpack_from(code, blob, i)[0] if t == 0: @@ -1039,11 +1219,14 @@ class DumperBase(): def putType(self, typish, priority=0): # Higher priority values override lower ones. if priority >= self.currentType.priority: - types = (str) if sys.version_info[0] >= 3 else (str, unicode) - if isinstance(typish, types): + if isinstance(typish, str): self.currentType.value = typish - else: + elif isinstance(typish, int): + self.currentType.value = self.type_name(typish) + elif isinstance(typish, self.Type): self.currentType.value = typish.name + else: + self.currentType.value = str(type(typish)) self.currentType.priority = priority def putValue(self, value, encoding=None, priority=0, length=None): @@ -1095,23 +1278,24 @@ class DumperBase(): self.putItem(value) def isExpanded(self): - #DumperBase.warn('IS EXPANDED: %s in %s: %s' % (self.currentIName, + #self.warn('IS EXPANDED: %s in %s: %s' % (self.currentIName, # self.expandedINames, self.currentIName in self.expandedINames)) return self.currentIName in self.expandedINames - def mangleName(self, typeName): + def mangleName(self, typename): return '_ZN%sE' % ''.join(map(lambda x: '%d%s' % (len(x), x), - typeName.split('::'))) + typename.split('::'))) - def arrayItemCountFromTypeName(self, typeName, fallbackMax=1): - itemCount = typeName[typeName.find('[') + 1:typeName.find(']')] + def arrayItemCountFromTypeName(self, typename, fallbackMax=1): + itemCount = typename[typename.find('[') + 1:typename.find(']')] return int(itemCount) if itemCount else fallbackMax def putCStyleArray(self, value): - arrayType = value.type.unqualified() - innerType = arrayType.ltarget - if innerType is None: - innerType = value.type.target().unqualified() + arrayType = value.type + innerType = arrayType.target() + #self.warn("ARRAY TYPE: %s" % arrayType) + #self.warn("INNER TYPE: %s" % innerType) + address = value.address() if address: self.putValue('@0x%x' % address, priority=-1) @@ -1121,14 +1305,17 @@ class DumperBase(): displayFormat = self.currentItemFormat() arrayByteSize = arrayType.size() + n = self.arrayItemCountFromTypeName(value.type.name, 100) if arrayByteSize == 0: # This should not happen. But it does, see QTCREATORBUG-14755. # GDB/GCC produce sizeof == 0 for QProcess arr[3] # And in the Nim string dumper. - itemCount = self.arrayItemCountFromTypeName(value.type.name, 100) - arrayByteSize = int(itemCount) * innerType.size() + arrayByteSize = n * innerType.size() + elif not self.isCdb: + # Do not check the inner type size for cdb since this requires a potentially expensive + # type lookup + n = arrayByteSize // innerType.size() - n = arrayByteSize // innerType.size() p = value.address() if displayFormat != DisplayFormat.Raw and p: if innerType.name in ( @@ -1161,19 +1348,19 @@ class DumperBase(): def cleanAddress(self, addr): if addr is None: return '' - return '0x%x' % toInteger(hex(addr), 16) + return '0x%x' % int(hex(addr), 16) - def stripNamespaceFromType(self, typeName): + def stripNamespaceFromType(self, typename): ns = self.qtNamespace() - if len(ns) > 0 and typeName.startswith(ns): - typeName = typeName[len(ns):] - # DumperBase.warn( 'stripping %s' % typeName ) + if len(ns) > 0 and typename.startswith(ns): + typename = typename[len(ns):] + # self.warn( 'stripping %s' % typename ) lvl = 0 pos = None stripChunks = [] - sz = len(typeName) + sz = len(typename) for index in range(0, sz): - s = typeName[index] + s = typename[index] if s == '<': lvl += 1 if lvl == 1: @@ -1188,22 +1375,22 @@ class DumperBase(): if lvl != 0: raise RuntimeError("unbalanced at end of type name") for (f, l) in reversed(stripChunks): - typeName = typeName[:f] + typeName[l:] - return typeName + typename = typename[:f] + typename[l:] + return typename - def tryPutPrettyItem(self, typeName, value): + def tryPutPrettyItem(self, typename, value): value.check() if self.useFancy and self.currentItemFormat() != DisplayFormat.Raw: - self.putType(typeName) + self.putType(typename) - nsStrippedType = self.stripNamespaceFromType(typeName)\ + nsStrippedType = self.stripNamespaceFromType(typename)\ .replace('::', '__') # Strip leading 'struct' for C structs if nsStrippedType.startswith('struct '): nsStrippedType = nsStrippedType[7:] - #DumperBase.warn('STRIPPED: %s' % nsStrippedType) + #self.warn('STRIPPED: %s' % nsStrippedType) # The following block is only needed for D. if nsStrippedType.startswith('_A'): # DMD v2.058 encodes string[] as _Array_uns long long. @@ -1216,7 +1403,7 @@ class DumperBase(): return True dumper = self.qqDumpers.get(nsStrippedType) - #DumperBase.warn('DUMPER: %s' % dumper) + #self.warn('DUMPER: %s' % dumper) if dumper is not None: dumper(self, value) return True @@ -1242,15 +1429,16 @@ class DumperBase(): self.putField('editvalue', value) # This is shared by pointer and array formatting. - def tryPutSimpleFormattedPointer(self, ptr, typeName, innerType, displayFormat, limit): + def tryPutSimpleFormattedPointer(self, ptr, typename, innerType, displayFormat, limit): if displayFormat == DisplayFormat.Automatic: - targetType = innerType - if innerType.code == TypeCode.Typedef: - targetType = innerType.ltarget + if self.isCdb or innerType.code is not TypeCode.Typedef: + targetType = innerType + else: + targetType = innerType.target() if targetType.name in ('char', 'signed char', 'unsigned char', 'uint8_t', 'CHAR'): # Use UTF-8 as default for char *. - self.putType(typeName) + self.putType(typename) (length, shown, data) = self.readToFirstZero(ptr, 1, limit) self.putValue(data, 'utf8', length=length) if self.isExpanded(): @@ -1258,7 +1446,7 @@ class DumperBase(): return True if targetType.name in ('wchar_t', 'WCHAR'): - self.putType(typeName) + self.putType(typename) charSize = self.lookupType('wchar_t').size() (length, data) = self.encodeCArray(ptr, charSize, limit) if charSize == 2: @@ -1268,58 +1456,54 @@ class DumperBase(): return True if displayFormat == DisplayFormat.Latin1String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 1, limit) self.putValue(data, 'latin1', length=length) return True if displayFormat == DisplayFormat.SeparateLatin1String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 1, limit) self.putValue(data, 'latin1', length=length) self.putDisplay('latin1:separate', data) return True if displayFormat == DisplayFormat.Utf8String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 1, limit) self.putValue(data, 'utf8', length=length) return True if displayFormat == DisplayFormat.SeparateUtf8String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 1, limit) self.putValue(data, 'utf8', length=length) self.putDisplay('utf8:separate', data) return True if displayFormat == DisplayFormat.Local8BitString: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 1, limit) self.putValue(data, 'local8bit', length=length) return True if displayFormat == DisplayFormat.Utf16String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 2, limit) self.putValue(data, 'utf16', length=length) return True if displayFormat == DisplayFormat.Ucs4String: - self.putType(typeName) + self.putType(typename) (length, data) = self.encodeCArray(ptr, 4, limit) self.putValue(data, 'ucs4', length=length) return True return False - def putFormattedPointer(self, value): - #with self.timer('formattedPointer'): - self.putFormattedPointerX(value) - def putDerefedPointer(self, value): - derefValue = value.dereference() - innerType = value.type.target() # .unqualified() + derefValue = self.value_dereference(value) + innerType = value.type.target() self.putType(innerType) savedCurrentChildType = self.currentChildType self.currentChildType = innerType.name @@ -1332,47 +1516,47 @@ class DumperBase(): self.putItem(derefValue) self.currentChildType = savedCurrentChildType - def putFormattedPointerX(self, value): + def putFormattedPointer(self, value): self.putOriginalAddress(value.address()) - #DumperBase.warn("PUT FORMATTED: %s" % value) - pointer = value.pointer() + #self.warn("PUT FORMATTED: %s" % value) + pointer = self.value_as_address(value) self.putAddress(pointer) - #DumperBase.warn('POINTER: 0x%x' % pointer) + #self.warn('POINTER: 0x%x' % pointer) if pointer == 0: - #DumperBase.warn('NULL POINTER') - self.putType(value.type) + #self.warn('NULL POINTER') + self.putType(value.typeid) self.putValue('0x0') return - typeName = value.type.name + typename = self.type_name(value.typeid) try: self.readRawMemory(pointer, 1) except: # Failure to dereference a pointer should at least # show the value of a pointer. - #DumperBase.warn('BAD POINTER: %s' % value) + #self.warn('BAD POINTER: %s' % value) self.putValue('0x%x' % pointer) - self.putType(typeName) + self.putType(typename) return if self.currentIName.endswith('.this'): self.putDerefedPointer(value) return - displayFormat = self.currentItemFormat(value.type.name) - innerType = value.type.target() # .unqualified() + displayFormat = self.currentItemFormat(typename) + innerType = value.type.target() if innerType.name == 'void': - #DumperBase.warn('VOID POINTER: %s' % displayFormat) - self.putType(typeName) + #self.warn('VOID POINTER: %s' % displayFormat) + self.putType(typename) self.putSymbolValue(pointer) return if displayFormat == DisplayFormat.Raw: # Explicitly requested bald pointer. - #DumperBase.warn('RAW') - self.putType(typeName) + #self.warn('RAW') + self.putType(typename) self.putValue('0x%x' % pointer) self.putExpandable() if self.currentIName in self.expandedINames: @@ -1384,27 +1568,27 @@ class DumperBase(): limit = self.displayStringLimit if displayFormat in (DisplayFormat.SeparateLatin1String, DisplayFormat.SeparateUtf8String): limit = 1000000 - if self.tryPutSimpleFormattedPointer(pointer, typeName, + if self.tryPutSimpleFormattedPointer(pointer, typename, innerType, displayFormat, limit): self.putExpandable() return if DisplayFormat.Array10 <= displayFormat and displayFormat <= DisplayFormat.Array10000: n = (10, 100, 1000, 10000)[displayFormat - DisplayFormat.Array10] - self.putType(typeName) + self.putType(typename) self.putItemCount(n) - self.putArrayData(value.pointer(), n, innerType) + self.putArrayData(self.value_as_address(value), n, innerType) return if innerType.code == TypeCode.Function: # A function pointer. self.putSymbolValue(pointer) - self.putType(typeName) + self.putType(typename) return - #DumperBase.warn('AUTODEREF: %s' % self.autoDerefPointers) - #DumperBase.warn('INAME: %s' % self.currentIName) - #DumperBase.warn('INNER: %s' % innerType.name) + #self.warn('AUTODEREF: %s' % self.autoDerefPointers) + #self.warn('INAME: %s' % self.currentIName) + #self.warn('INNER: %s' % innerType.name) if self.autoDerefPointers: # Generic pointer type with AutomaticFormat, but never dereference char types: if innerType.name not in ( @@ -1425,9 +1609,9 @@ class DumperBase(): self.putDerefedPointer(value) return - #DumperBase.warn('GENERIC PLAIN POINTER: %s' % value.type) - #DumperBase.warn('ADDR PLAIN POINTER: 0x%x' % value.laddress) - self.putType(typeName) + #self.warn('GENERIC PLAIN POINTER: %s' % value.type) + #self.warn('ADDR PLAIN POINTER: 0x%x' % value.laddress) + self.putType(typename) self.putSymbolValue(pointer) self.putExpandable() if self.currentIName in self.expandedINames: @@ -1439,7 +1623,22 @@ class DumperBase(): if address is not None: self.put('origaddr="0x%x",' % address) + def wantQObjectNames(self): + return self.showQObjectNames and self.qtLoaded + + def fetchInternalFunctions(self): + # Overrridden + pass + def putQObjectNameValue(self, value): + is_qobject_based = self.type_qobject_based_cache.get(value.typeid, None) + if is_qobject_based == False: + #self.warn("SKIP TEST OBJNAME: %s" % self.type_name(value.typeid)) + return + + #self.warn("TEST OBJNAME: %s" % self.type_name(value.typeid)) + self.fetchInternalFunctions() + try: # dd = value['d_ptr']['d'] is just behind the vtable. (vtable, dd) = self.split('pp', value) @@ -1448,7 +1647,7 @@ class DumperBase(): intSize = 4 ptrSize = self.ptrSize() - if self.qtVersion() >= 0x060000: + if self.qtVersionAtLeast(0x060000): # Size of QObjectData: 9 pointer + 2 int # - vtable # - QObject *q_ptr; @@ -1458,7 +1657,7 @@ class DumperBase(): # - int postedEvents; # - QDynamicMetaObjectData *metaObject; # - QBindingStorage bindingStorage; - extra = self.extractPointer(dd + 9 * ptrSize + 2 * intSize) + extra = self.extract_pointer_at_address(dd + 9 * ptrSize + 2 * intSize) if extra == 0: return False @@ -1469,7 +1668,7 @@ class DumperBase(): # - QList > eventFilters; # - QString objectName objectNameAddress = extra + 12 * ptrSize - elif self.qtVersion() >= 0x050000: + elif self.qtVersionAtLeast(0x050000): # Size of QObjectData: 5 pointer + 2 int # - vtable # - QObject *q_ptr; @@ -1478,7 +1677,7 @@ class DumperBase(): # - uint isWidget : 1; etc... # - int postedEvents; # - QDynamicMetaObjectData *metaObject; - extra = self.extractPointer(dd + 5 * ptrSize + 2 * intSize) + extra = self.extract_pointer_at_address(dd + 5 * ptrSize + 2 * intSize) if extra == 0: return False @@ -1582,7 +1781,7 @@ class DumperBase(): try: customEventOffset = 8 if self.isMsvcTarget() else 9 - customEventFunc = self.extractPointer(vtablePtr + customEventOffset * self.ptrSize()) + customEventFunc = self.extract_pointer_at_address(vtablePtr + customEventOffset * self.ptrSize()) except: self.bump('nostruct-3') return False @@ -1594,7 +1793,7 @@ class DumperBase(): customEventFunc = getJumpAddress_x86(self, customEventFunc) if customEventFunc in (self.qtCustomEventFunc, self.qtCustomEventPltFunc): return True - customEventFunc = self.extractPointer(customEventFunc) + customEventFunc = self.extract_pointer_at_address(customEventFunc) if customEventFunc in (self.qtCustomEventFunc, self.qtCustomEventPltFunc): return True # If the object is defined in another module there may be another level of indirection @@ -1603,18 +1802,18 @@ class DumperBase(): return customEventFunc in (self.qtCustomEventFunc, self.qtCustomEventPltFunc) # def extractQObjectProperty(objectPtr): -# vtablePtr = self.extractPointer(objectPtr) -# metaObjectFunc = self.extractPointer(vtablePtr) +# vtablePtr = self.extract_pointer_at_address(objectPtr) +# metaObjectFunc = self.extract_pointer_at_address(vtablePtr) # cmd = '((void*(*)(void*))0x%x)((void*)0x%x)' % (metaObjectFunc, objectPtr) # try: -# #DumperBase.warn('MO CMD: %s' % cmd) +# #self.warn('MO CMD: %s' % cmd) # res = self.parseAndEvaluate(cmd) -# #DumperBase.warn('MO RES: %s' % res) +# #self.warn('MO RES: %s' % res) # self.bump('successfulMetaObjectCall') -# return res.pointer() +# return self.value_as_address(res) # except: # self.bump('failedMetaObjectCall') -# #DumperBase.warn('COULD NOT EXECUTE: %s' % cmd) +# #self.warn('COULD NOT EXECUTE: %s' % cmd) # return 0 def extractMetaObjectPtr(self, objectPtr, typeobj): @@ -1631,29 +1830,29 @@ class DumperBase(): # contents 'vanishes' as the reported size of the string # gets zeroed out(?). # Try vtable, metaObject() is the first entry. - vtablePtr = self.extractPointer(objectPtr) - metaObjectFunc = self.extractPointer(vtablePtr) + vtablePtr = self.extract_pointer_at_address(objectPtr) + metaObjectFunc = self.extract_pointer_at_address(vtablePtr) cmd = '((void*(*)(void*))0x%x)((void*)0x%x)' % (metaObjectFunc, objectPtr) try: - #DumperBase.warn('MO CMD: %s' % cmd) + #self.warn('MO CMD: %s' % cmd) res = self.parseAndEvaluate(cmd) - #DumperBase.warn('MO RES: %s' % res) + #self.warn('MO RES: %s' % res) self.bump('successfulMetaObjectCall') - return res.pointer() + return self.value_as_address(res) except: self.bump('failedMetaObjectCall') - #DumperBase.warn('COULD NOT EXECUTE: %s' % cmd) + #self.warn('COULD NOT EXECUTE: %s' % cmd) return 0 def extractStaticMetaObjectFromTypeHelper(someTypeObj): if someTypeObj.isSimpleType(): return 0 - typeName = someTypeObj.name - isQObjectProper = typeName == self.qtNamespace() + 'QObject' + typename = someTypeObj.name + isQObjectProper = typename == self.qtNamespace() + 'QObject' # No templates for now. - if typeName.find('<') >= 0: + if typename.find('<') >= 0: return 0 result = self.findStaticMetaObject(someTypeObj) @@ -1662,7 +1861,7 @@ class DumperBase(): # a Q_OBJECT SMO has a non-null superdata (unless it's QObject itself), # a Q_GADGET SMO has a null superdata (hopefully) if result and not isQObjectProper: - if self.qtVersion() >= 0x60000 and self.isWindowsTarget(): + if self.qtVersionAtLeast(0x60000) and self.isWindowsTarget(): (direct, indirect) = self.split('pp', result) # since Qt 6 there is an additional indirect super data getter on windows if direct == 0 and indirect == 0: @@ -1706,16 +1905,16 @@ class DumperBase(): ptrSize = self.ptrSize() - typeName = typeobj.name - result = self.knownStaticMetaObjects.get(typeName, None) + typename = typeobj.name + result = self.knownStaticMetaObjects.get(typename, None) if result is not None: # Is 0 or the static metaobject. self.bump('typecached') - #DumperBase.warn('CACHED RESULT: %s %s 0x%x' % (self.currentIName, typeName, result)) + #self.warn('CACHED RESULT: %s %s 0x%x' % (self.currentIName, typename, result)) return result if not self.couldBeQObjectPointer(objectPtr): self.bump('cannotBeQObject') - #DumperBase.warn('DOES NOT LOOK LIKE A QOBJECT: %s' % self.currentIName) + #self.warn('DOES NOT LOOK LIKE A QOBJECT: %s' % self.currentIName) return 0 metaObjectPtr = 0 @@ -1731,38 +1930,29 @@ class DumperBase(): #if metaObjectPtr: # self.bump('foundMetaObject') - # self.knownStaticMetaObjects[typeName] = metaObjectPtr + # self.8; return metaObjectPtr - def split(self, pattern, value): - if isinstance(value, self.Value): - return value.split(pattern) - if self.isInt(value): - val = self.Value(self) - val.laddress = value - return val.split(pattern) - raise RuntimeError('CANNOT EXTRACT STRUCT FROM %s' % type(value)) - def extractCString(self, addr): result = bytearray() while True: - d = self.extractByte(addr) - if d == 0: + d = bytes(self.readRawMemory(addr, 1)) + if d[0] == 0: break - result.append(d) + result += d addr += 1 return result def listData(self, value, check=True): - if self.qtVersion() >= 0x60000: + if self.qtVersionAtLeast(0x60000): dd, data, size = self.split('ppi', value) return data, size base = self.extractPointer(value) (ref, alloc, begin, end) = self.split('IIII', base) array = base + 16 - if self.qtVersion() < 0x50000: + if not self.qtVersionAtLeast(0x50000): array += self.ptrSize() size = end - begin @@ -1775,21 +1965,21 @@ class DumperBase(): data = array + begin * stepSize return data, size - def putTypedPointer(self, name, addr, typeName): + def putTypedPointer(self, name, addr, typename): """ Prints a typed pointer, expandable if the type can be resolved, and without children otherwise """ with SubItem(self, name): self.putAddress(addr) self.putValue('@0x%x' % addr) - typeObj = self.lookupType(typeName) + typeObj = self.lookupType(typename) if typeObj: self.putType(typeObj) self.putExpandable() if self.isExpanded(): with Children(self): - self.putFields(self.createValue(addr, typeObj)) + self.putFields(self.createValueFromAddress(addr, typeObj)) else: - self.putType(typeName) + self.putType(typename) # This is called is when a QObject derived class is expanded def tryPutQObjectGuts(self, value): @@ -1801,26 +1991,26 @@ class DumperBase(): def metaString(self, metaObjectPtr, index, revision): ptrSize = self.ptrSize() stringdataOffset = ptrSize - if self.isWindowsTarget() and self.qtVersion() >= 0x060000: + if self.isWindowsTarget() and self.qtVersionAtLeast(0x060000): stringdataOffset += ptrSize # indirect super data member - stringdata = self.extractPointer(toInteger(metaObjectPtr) + stringdataOffset) + stringdata = self.extract_pointer_at_address(int(metaObjectPtr) + stringdataOffset) - def unpackString(base, size): + def unpack_string(base, size): try: s = struct.unpack_from('%ds' % size, self.readRawMemory(base, size))[0] - return s if sys.version_info[0] == 2 else s.decode('utf8') + return s.decode('utf8') except: return '' if revision >= 9: # Qt 6. pos, size = self.split('II', stringdata + 8 * index) - return unpackString(stringdata + pos, size) + return unpack_string(stringdata + pos, size) if revision >= 7: # Qt 5. byteArrayDataSize = 24 if ptrSize == 8 else 16 - literal = stringdata + toInteger(index) * byteArrayDataSize + literal = stringdata + int(index) * byteArrayDataSize base, size, _ = self.qArrayDataHelper(literal) - return unpackString(base, size) + return unpack_string(base, size) ldata = stringdata + index return self.extractCString(ldata).decode('utf8') @@ -1830,25 +2020,25 @@ class DumperBase(): self.putField('sortgroup', sortorder) def putQMetaStuff(self, value, origType): - if self.qtVersion() >= 0x060000: + if self.qtVersionAtLeast(0x060000): metaObjectPtr, handle = value.split('pp') else: metaObjectPtr, handle = value.split('pI') if metaObjectPtr != 0: - if self.qtVersion() >= 0x060000: + if self.qtVersionAtLeast(0x060000): if handle == 0: self.putEmptyValue() return revision = 9 name, alias, flags, keyCount, data = self.split('IIIII', handle) index = name - elif self.qtVersion() >= 0x050000: + elif self.qtVersionAtLeast(0x050000): revision = 7 - dataPtr = self.extractPointer(metaObjectPtr + 2 * self.ptrSize()) + dataPtr = self.extract_pointer_at_address(metaObjectPtr + 2 * self.ptrSize()) index = self.extractInt(dataPtr + 4 * handle) else: revision = 6 - dataPtr = self.extractPointer(metaObjectPtr + 2 * self.ptrSize()) + dataPtr = self.extract_pointer_at_address(metaObjectPtr + 2 * self.ptrSize()) index = self.extractInt(dataPtr + 4 * handle) #self.putValue("index: %s rev: %s" % (index, revision)) name = self.metaString(metaObjectPtr, index, revision) @@ -1873,29 +2063,29 @@ class DumperBase(): def putQObjectGutsHelper(self, qobject, qobjectPtr, handle, metaObjectPtr, origType): ptrSize = self.ptrSize() - def putt(name, value, typeName=' '): + def putt(name, value, typename=' '): with SubItem(self, name): self.putValue(value) - self.putType(typeName) + self.putType(typename) def extractSuperDataPtr(someMetaObjectPtr): #return someMetaObjectPtr['d']['superdata'] - return self.extractPointer(someMetaObjectPtr) + return self.extract_pointer_at_address(someMetaObjectPtr) def extractDataPtr(someMetaObjectPtr): # dataPtr = metaObjectPtr['d']['data'] - if self.qtVersion() >= 0x60000 and self.isWindowsTarget(): + if self.qtVersionAtLeast(0x60000) and self.isWindowsTarget(): offset = 3 else: offset = 2 - return self.extractPointer(someMetaObjectPtr + offset * ptrSize) + return self.extract_pointer_at_address(someMetaObjectPtr + offset * ptrSize) isQMetaObject = origType == 'QMetaObject' isQObject = origType == 'QObject' - #DumperBase.warn('OBJECT GUTS: %s 0x%x ' % (self.currentIName, metaObjectPtr)) + #self.warn('OBJECT GUTS: %s 0x%x ' % (self.currentIName, metaObjectPtr)) dataPtr = extractDataPtr(metaObjectPtr) - #DumperBase.warn('DATA PTRS: %s 0x%x ' % (self.currentIName, dataPtr)) + #self.warn('DATA PTRS: %s 0x%x ' % (self.currentIName, dataPtr)) (revision, classname, classinfo, classinfo2, methodCount, methods, @@ -1913,14 +2103,14 @@ class DumperBase(): ns = self.qtNamespace() extraData = 0 if qobjectPtr: - dd = self.extractPointer(qobjectPtr + ptrSize) - if self.qtVersion() >= 0x60000: + dd = self.extract_pointer_at_address(qobjectPtr + ptrSize) + if self.qtVersionAtLeast(0x60000): (dvtablePtr, qptr, parent, children, bindingStorageData, bindingStatus, flags, postedEvents, dynMetaObjectPtr, # Up to here QObjectData. extraData, threadDataPtr, connectionListsPtr, sendersPtr, currentSenderPtr) \ = self.split('pp{@QObject*}{@QList<@QObject *>}ppIIp' + 'ppppp', dd) - elif self.qtVersion() >= 0x50000: + elif self.qtVersionAtLeast(0x50000): (dvtablePtr, qptr, parent, children, flags, postedEvents, dynMetaObjectPtr, # Up to here QObjectData. extraData, threadDataPtr, connectionListsPtr, @@ -1942,7 +2132,7 @@ class DumperBase(): if not self.isCli: self.putSortGroup(8) - dvtablePtr, qptr, parentPtr, children = self.split('ppp{QList}', dd) + dvtablePtr, qptr, parentPtr, children = self.split('ppp{@QList<@QObject *>}', dd) self.putItem(children) if isQMetaObject: @@ -2003,8 +2193,9 @@ class DumperBase(): if False: with SubItem(self, '[connections]'): if connectionListsPtr: - typeName = '@QObjectConnectionListVector' - self.putItem(self.createValue(connectionListsPtr, typeName)) + typename = '@QObjectConnectionListVector' + self.putItem(self.createValueFromAddress(connectionListsPtr, +typename)) else: self.putItemCount(0) @@ -2045,7 +2236,7 @@ class DumperBase(): with Children(self): # Static properties. for i in range(propertyCount): - if self.qtVersion() >= 0x60000: + if self.qtVersionAtLeast(0x60000): t = self.split('IIIII', dataPtr + properties * 4 + 20 * i) else: t = self.split('III', dataPtr + properties * 4 + 12 * i) @@ -2053,19 +2244,19 @@ class DumperBase(): if qobject and self.qtPropertyFunc: # LLDB doesn't like calling it on a derived class, possibly # due to type information living in a different shared object. - #base = self.createValue(qobjectPtr, '@QObject') - #DumperBase.warn("CALL FUNC: 0x%x" % self.qtPropertyFunc) + #base = self.createValueFromAddress(qobjectPtr, '@QObject') + #self.warn("CALL FUNC: 0x%x" % self.qtPropertyFunc) cmd = '((QVariant(*)(void*,char*))0x%x)((void*)0x%x,"%s")' \ % (self.qtPropertyFunc, qobjectPtr, name) try: - #DumperBase.warn('PROP CMD: %s' % cmd) + #self.warn('PROP CMD: %s' % cmd) res = self.parseAndEvaluate(cmd) - #DumperBase.warn('PROP RES: %s' % res) + #self.warn('PROP RES: %s' % res) except: self.bump('failedMetaObjectCall') putt(name, ' ') continue - #DumperBase.warn('COULD NOT EXECUTE: %s' % cmd) + #self.warn('COULD NOT EXECUTE: %s' % cmd) #self.putCallItem(name, '@QVariant', base, 'property', '"' + name + '"') if res is None: self.bump('failedMetaObjectCall2') @@ -2077,37 +2268,42 @@ class DumperBase(): # Dynamic properties. if extraData: - def list6Generator(addr, innerType): + def list6Generator(addr, inner_typeid): + data, size = self.listData(addr) + inner_size = self.type_size(inner_typeid) + for i in range(size): + yield self.createValueFromAddress(data, inner_typeid) + data += inner_size + + def list5Generator(addr, inner_typeid): data, size = self.listData(addr) for i in range(size): - yield self.createValue(data + i * innerType.size(), innerType) + yield self.createValueFromAddress(data, inner_typeid) + data += ptrSize - def list5Generator(addr, innerType): - data, size = self.listData(addr) - for i in range(size): - yield self.createValue(data + i * ptrSize, innerType) - - def vectorGenerator(addr, innerType): + def vectorGenerator(addr, inner_typeid): data, size = self.vectorData(addr) + inner_size = self.type_size(inner_typeid) for i in range(size): - yield self.createValue(data + i * innerType.size(), innerType) + yield self.createValueFromAddress(data, inner_typeid) + data += inner_size - byteArrayType = self.createType('@QByteArray') - variantType = self.createType('@QVariant') - if self.qtVersion() >= 0x60000: - values = vectorGenerator(extraData + 3 * ptrSize, variantType) - elif self.qtVersion() >= 0x50600: - values = vectorGenerator(extraData + 2 * ptrSize, variantType) - elif self.qtVersion() >= 0x50000: - values = list5Generator(extraData + 2 * ptrSize, variantType) + variant_typeid = self.cheap_typeid_from_name('@QVariant') + if self.qtVersionAtLeast(0x60000): + values = vectorGenerator(extraData + 3 * ptrSize, variant_typeid) + elif self.qtVersionAtLeast(0x50600): + values = vectorGenerator(extraData + 2 * ptrSize, variant_typeid) + elif self.qtVersionAtLeast(0x50000): + values = list5Generator(extraData + 2 * ptrSize, variant_typeid) else: - values = list5Generator(extraData + 2 * ptrSize, - variantType.pointer()) + variantptr_typeid = self.cheap_typeid_from_name('@QVariant') + values = list5Generator(extraData + 2 * ptrSize, variantptr_typeid) - if self.qtVersion() >= 0x60000: - names = list6Generator(extraData, byteArrayType) + bytearray_typeid = self.cheap_typeid_from_name('@QByteArray') + if self.qtVersionAtLeast(0x60000): + names = list6Generator(extraData, bytearray_typeid) else: - names = list5Generator(extraData + ptrSize, byteArrayType) + names = list5Generator(extraData + ptrSize, bytearray_typeid) for (k, v) in zip(names, values): with SubItem(self, propertyCount + dynamicPropertyCount): @@ -2169,7 +2365,7 @@ class DumperBase(): if isQObject: with SubItem(self, '[d]'): - self.putItem(self.createValue(dd, '@QObjectPrivate')) + self.putItem(self.createValueFromAddress(dd, '@QObjectPrivate')) self.putSortGroup(15) if isQMetaObject: @@ -2199,10 +2395,10 @@ class DumperBase(): with SubItem(self, '[connections]'): ptrSize = self.ptrSize() self.putNoType() - privateType = self.createType('@QObjectPrivate') + privateType = self.create_typeid_from_name('@QObjectPrivate') d_ptr = dd.cast(privateType.pointer()).dereference() connections = d_ptr['connectionLists'] - if self.connections.integer() == 0: + if self.value_as_integer(connections) == 0: self.putItemCount(0) else: connections = connections.dereference() @@ -2215,72 +2411,74 @@ class DumperBase(): innerType = connections.type[0] # Should check: innerType == ns::QObjectPrivate::ConnectionList data, size = self.vectorData(connections) - connectionType = self.createType('@QObjectPrivate::Connection') + connection_typeid = self.create_typeid_from_name('@QObjectPrivate::Connection') + connection_ptr_typeid = self.create_pointer_typeid(connection_typeid) for i in range(size): - first = self.extractPointer(data + i * 2 * ptrSize) + first = self.extract_pointer_at_address(data + i * 2 * ptrSize) while first: - self.putSubItem('%s' % pp, - self.createPointerValue(first, connectionType)) - first = self.extractPointer(first + 3 * ptrSize) + val = self.Value(self) + val.ldata = first + val.typeid = connection_typeid + self.putSubItem('%s' % pp, val) + first = self.extract_pointer_at_address(first + 3 * ptrSize) # We need to enforce some upper limit. pp += 1 if pp > 1000: break - def currentItemFormat(self, typeName=None): + def currentItemFormat(self, typename=None): displayFormat = self.formats.get(self.currentIName, DisplayFormat.Automatic) if displayFormat == DisplayFormat.Automatic: - if typeName is None: - typeName = self.currentType.value - needle = None if typeName is None else self.stripForFormat(typeName) + if typename is None: + typename = self.currentType.value + needle = None if typename is None else self.stripForFormat(typename) displayFormat = self.typeformats.get(needle, DisplayFormat.Automatic) return displayFormat def putSubItem(self, component, value): # -> ReportItem if not isinstance(value, self.Value): raise RuntimeError('WRONG VALUE TYPE IN putSubItem: %s' % type(value)) - if not isinstance(value.type, self.Type): - raise RuntimeError('WRONG TYPE TYPE IN putSubItem: %s' % type(value.type)) res = None with SubItem(self, component): self.putItem(value) res = self.currentValue return res # The 'short' display. - def putArrayData(self, base, n, innerType, childNumChild=None): + def putArrayData(self, base, n, inner_typish, childNumChild=None): self.checkIntType(base) self.checkIntType(n) - addrBase = base - innerSize = innerType.size() + inner_typeid = self.typeid_for_typish(inner_typish) + inner_size = self.type_size(inner_typeid) self.putNumChild(n) - #DumperBase.warn('ADDRESS: 0x%x INNERSIZE: %s INNERTYPE: %s' % (addrBase, innerSize, innerType)) - enc = innerType.simpleEncoding() + #self.warn('ADDRESS: 0x%x INNERSIZE: %s INNERTYPE: %s' % (base, inner_size, inner_typeid)) + enc = self.type_encoding_cache.get(inner_typeid, None) maxNumChild = self.maxArrayCount() if enc: - self.put('childtype="%s",' % innerType.name) - self.put('addrbase="0x%x",' % addrBase) - self.put('addrstep="0x%x",' % innerSize) + self.put('childtype="%s",' % self.type_name(inner_typeid)) + self.put('addrbase="0x%x",' % base) + self.put('addrstep="0x%x",' % inner_size) self.put('arrayencoding="%s",' % enc) self.put('endian="%s",' % self.packCode) if n > maxNumChild: self.put('childrenelided="%s",' % n) n = maxNumChild self.put('arraydata="') - self.put(self.readMemory(addrBase, n * innerSize)) + self.put(self.readMemory(base, n * inner_size)) self.put('",') else: + innerType = self.Type(self, inner_typeid) with Children(self, n, innerType, childNumChild, maxNumChild, - addrBase=addrBase, addrStep=innerSize): + addrBase=base, addrStep=inner_size): for i in self.childRange(): - self.putSubItem(i, self.createValue(addrBase + i * innerSize, innerType)) + self.putSubItem(i, self.createValueFromAddress(base + i * inner_size, innerType)) - def putArrayItem(self, name, addr, n, typeName): + def putArrayItem(self, name, addr, n, typename): self.checkIntType(addr) self.checkIntType(n) with SubItem(self, name): self.putEmptyValue() - self.putType('%s [%d]' % (typeName, n)) - self.putArrayData(addr, n, self.lookupType(typeName)) + self.putType('%s [%d]' % (typename, n)) + self.putArrayData(addr, n, self.lookupType(typename)) self.putAddress(addr) def putPlotDataHelper(self, base, n, innerType, maxNumChild=1000 * 1000): @@ -2303,13 +2501,15 @@ class DumperBase(): """ Special handling for char** argv. """ + ptr_size = self.ptrSize() n = 0 - p = value - # p is 0 for "optimized out" cases. Or contains rubbish. + argv = self.value_as_address(value) + # argv is 0 for "optimized out" cases. Or contains rubbish. try: - if value.integer(): - while p.dereference().integer() and n <= 100: - p += 1 + if argv: + p = argv + while self.extract_pointer_at_address(p) and n <= 100: + p += ptr_size n += 1 except: pass @@ -2325,44 +2525,54 @@ class DumperBase(): self.putSubItem(i, p.dereference()) p += 1 + def extract_pointer_at_address(self, address): + blob = self.value_data_from_address(address, self.ptrSize()) + return int.from_bytes(blob, byteorder='little') + + def value_extract_integer(self, value, size, signed): + if isinstance(value.lvalue, int): + return value.lvalue + if isinstance(value.ldata, int): + return value.ldata + #with self.dumper.timer('extractInt'): + value.check() + blob = self.value_data(value, size) + return int.from_bytes(blob, byteorder='little', signed=signed) + + def value_extract_something(self, valuish, size, signed=False): + if isinstance(valuish, int): + blob = self.value_data_from_address(valuish, size) + elif isinstance(valuish, self.Value): + blob = self.value_data(valuish, size) + else: + raise RuntimeError('CANT EXTRACT FROM %s' % type(valuish)) + res = int.from_bytes(blob, byteorder='little', signed=signed) + #self.warn("EXTRACTED %s SIZE %s FROM %s" % (res, size, blob)) + return res + def extractPointer(self, value): - try: - if value.type.code == TypeCode.Array: - return value.address() - except: - pass - code = 'I' if self.ptrSize() == 4 else 'Q' - return self.extractSomething(value, code, 8 * self.ptrSize()) + return self.value_extract_something(value, self.ptrSize()) def extractInt64(self, value): - return self.extractSomething(value, 'q', 64) + return self.value_extract_something(value, 8, True) def extractUInt64(self, value): - return self.extractSomething(value, 'Q', 64) + return self.value_extract_something(value, 8) def extractInt(self, value): - return self.extractSomething(value, 'i', 32) + return self.value_extract_something(value, 4, True) def extractUInt(self, value): - return self.extractSomething(value, 'I', 32) + return self.value_extract_something(value, 4) def extractShort(self, value): - return self.extractSomething(value, 'h', 16) + return self.value_extract_something(value, 2, True) def extractUShort(self, value): - return self.extractSomething(value, 'H', 16) + return self.value_extract_something(value, 2) def extractByte(self, value): - return self.extractSomething(value, 'b', 8) - - def extractSomething(self, value, pattern, bitsize): - if self.isInt(value): - val = self.Value(self) - val.laddress = value - return val.extractSomething(pattern, bitsize) - if isinstance(value, self.Value): - return value.extractSomething(pattern, bitsize) - raise RuntimeError('CANT EXTRACT FROM %s' % type(value)) + return self.value_extract_something(value, 1) # Parses a..b and a.(s).b def parseRange(self, exp): @@ -2405,9 +2615,9 @@ class DumperBase(): try: # Allow integral expressions. - ss = self.parseAndEvaluate(s[1:len(s) - 1]).integer() if s else 1 - aa = self.parseAndEvaluate(a).integer() - bb = self.parseAndEvaluate(b).integer() + ss = self.value_as_integer(self.parseAndEvaluate(s[1:len(s) - 1])) if s else 1 + aa = self.value_as_integer(self.parseAndEvaluate(a)) + bb = self.value_as_integer(self.parseAndEvaluate(b)) if aa < bb and ss > 0: return True, aa, ss, bb + 1, template except: @@ -2419,14 +2629,14 @@ class DumperBase(): self.putField('numchild', numchild) def handleLocals(self, variables): - #DumperBase.warn('VARIABLES: %s' % variables) - #with self.timer('locals'): + #self.warn('VARIABLES: %s' % variables) shadowed = {} for value in variables: if value.name == 'argv': if value.type.code == TypeCode.Pointer: - if value.type.ltarget.code == TypeCode.Pointer: - if value.type.ltarget.ltarget.name == 'char': + target = value.type.target() + if target.code == TypeCode.Pointer: + if target.target().name == 'char': self.putSpecialArgv(value) continue @@ -2455,7 +2665,7 @@ class DumperBase(): def handleWatch(self, origexp, exp, iname): exp = str(exp).strip() escapedExp = self.hexencode(exp) - #DumperBase.warn('HANDLING WATCH %s -> %s, INAME: "%s"' % (origexp, exp, iname)) + #self.warn('HANDLING WATCH %s -> %s, INAME: "%s"' % (origexp, exp, iname)) # Grouped items separated by semicolon. if exp.find(';') >= 0: @@ -2475,7 +2685,7 @@ class DumperBase(): # Special array index: e.g a[1..199] or a[1.(3).199] for stride 3. isRange, begin, step, end, template = self.parseRange(exp) if isRange: - #DumperBase.warn('RANGE: %s %s %s in %s' % (begin, step, end, template)) + #self.warn('RANGE: %s %s %s in %s' % (begin, step, end, template)) r = range(begin, end, step) n = len(r) with TopLevelItem(self, iname): @@ -2511,10 +2721,7 @@ class DumperBase(): try: if funcname.startswith('qdump__'): typename = funcname[7:] - if sys.version_info > (3,): - spec = inspect.getfullargspec(function) - else: - spec = inspect.getargspec(function) + spec = inspect.getfullargspec(function) if len(spec.args) == 2: self.qqDumpers[typename] = function elif len(spec.args) == 3 and len(spec.defaults) == 1: @@ -2561,11 +2768,8 @@ class DumperBase(): def reloadDumpers(self, args): for mod in self.dumpermodules: m = sys.modules[mod] - if sys.version_info[0] >= 3: - import importlib - importlib.reload(m) - else: - reload(m) + import importlib + importlib.reload(m) self.setupDumpers(args) def loadDumpers(self, args): @@ -2714,7 +2918,7 @@ class DumperBase(): self.doContinue() def doInsertInterpreterBreakpoint(self, args, wasPending): - #DumperBase.warn('DO INSERT INTERPRETER BREAKPOINT, WAS PENDING: %s' % wasPending) + #self.warn('DO INSERT INTERPRETER BREAKPOINT, WAS PENDING: %s' % wasPending) # Will fail if the service is not yet up and running. response = self.sendInterpreterRequest('setbreakpoint', args) bp = None if response is None else response.get('breakpoint', None) @@ -2749,14 +2953,6 @@ class DumperBase(): def extractInterpreterStack(self): return self.sendInterpreterRequest('backtrace', {'limit': 10}) - def isInt(self, thing): - if isinstance(thing, int): - return True - if sys.version_info[0] == 2: - if isinstance(thing, long): - return True - return False - def putItems(self, count, generator, maxNumChild=10000): self.putItemCount(count) if self.isExpanded(): @@ -2765,131 +2961,124 @@ class DumperBase(): self.putSubItem(i, val) def putItem(self, value): - #with self.timer('putItem'): - self.putItemX(value) - - def putItemX(self, value): - #DumperBase.warn('PUT ITEM: %s' % value.stringify()) - - typeobj = value.type # unqualified() - typeName = typeobj.name - - self.addToCache(typeobj) # Fill type cache + #self.warn('PUT ITEM: %s' % value.stringify()) + #self.dump_location() + #self.addToCache(typeobj) # Fill type cache if not value.lIsInScope: self.putSpecialValue('optimizedout') - #self.putType(typeobj) - #self.putSpecialValue('outofscope') self.putNumChild(0) return if not isinstance(value, self.Value): raise RuntimeError('WRONG TYPE IN putItem: %s' % type(self.Value)) + typeid = value.typeid + typecode = self.type_code(typeid) + typename = self.type_name(typeid) + # Try on possibly typedefed type first. - if self.tryPutPrettyItem(typeName, value): - if typeobj.code == TypeCode.Pointer: + if self.tryPutPrettyItem(typename, value): + if typecode == TypeCode.Pointer: self.putOriginalAddress(value.address()) else: self.putAddress(value.address()) return - if typeobj.code == TypeCode.Typedef: - #DumperBase.warn('TYPEDEF VALUE: %s' % value.stringify()) + if typecode == TypeCode.Typedef: + #self.warn('TYPEDEF VALUE: %s' % value.stringify()) self.putItem(value.detypedef()) - self.putBetterType(typeName) + self.putBetterType(typename) return - if typeobj.code == TypeCode.Pointer: + if typecode == TypeCode.Pointer: self.putFormattedPointer(value) if value.summary and self.useFancy: self.putValue(self.hexencode(value.summary), 'utf8:1:0') return self.putAddress(value.address()) - if value.lbitsize is not None: - self.putField('size', value.lbitsize // 8) - if typeobj.code == TypeCode.Function: - #DumperBase.warn('FUNCTION VALUE: %s' % value) - self.putType(typeobj) - self.putSymbolValue(value.pointer()) + if typecode == TypeCode.Function: + #self.warn('FUNCTION VALUE: %s' % value) + self.putType(typeid) + self.putSymbolValue(self.value_as_address(value)) self.putNumChild(0) return - if typeobj.code == TypeCode.Enum: - #DumperBase.warn('ENUM VALUE: %s' % value.stringify()) - self.putType(typeobj.name) + if typecode == TypeCode.Enum: + #self.warn('ENUM VALUE: %s' % value.stringify()) + self.putType(typename) self.putValue(value.display()) self.putNumChild(0) return - if typeobj.code == TypeCode.Array: - #DumperBase.warn('ARRAY VALUE: %s' % value) + if typecode == TypeCode.Array: + #self.warn('ARRAY VALUE: %s' % value) self.putCStyleArray(value) return - if typeobj.code == TypeCode.Bitfield: - #DumperBase.warn('BITFIELD VALUE: %s %d %s' % (value.name, value.lvalue, typeName)) + if typecode == TypeCode.Bitfield: + #self.warn('BITFIELD VALUE: %s %d %s' % (value.name, value.lvalue, typename)) self.putNumChild(0) - dd = typeobj.ltarget.tdata.enumDisplay - self.putValue(str(value.lvalue) if dd is None else dd( - value.lvalue, value.laddress, '%d')) - self.putType(typeName) + #dd = typeobj.target().enumDisplay + #self.putValue(str(value.lvalue) if dd is None else dd( + # value.lvalue, value.laddress, '%d')) + self.putValue(self.value_as_integer(value)) + self.putType(typename) return - if typeobj.code == TypeCode.Integral: - #DumperBase.warn('INTEGER: %s %s' % (value.name, value)) - val = value.value() + if typecode == TypeCode.Integral: + #self.warn('INTEGER: %s %s' % (value.name, value)) self.putNumChild(0) - self.putValue(val) - self.putType(typeName) + self.putValue(self.value_as_integer(value)) + self.putType(typename) return - if typeobj.code == TypeCode.Float: - #DumperBase.warn('FLOAT VALUE: %s' % value) + if typecode == TypeCode.Float: + #self.warn('FLOAT VALUE: %s' % value) self.putValue(value.value()) self.putNumChild(0) - self.putType(typeobj.name) + self.putType(typename) return - if typeobj.code in (TypeCode.Reference, TypeCode.RValueReference): - #DumperBase.warn('REFERENCE VALUE: %s' % value) + if typecode in (TypeCode.Reference, TypeCode.RValueReference): + #self.warn('REFERENCE VALUE: %s' % value) val = value.dereference() if val.laddress != 0: self.putItem(val) else: self.putSpecialValue('nullreference') - self.putBetterType(typeName) + self.putBetterType(typename) return - if typeobj.code == TypeCode.Complex: - self.putType(typeobj) + if typecode == TypeCode.Complex: + self.putType(typeid) self.putValue(value.display()) self.putNumChild(0) return - if typeobj.code == TypeCode.FortranString: + if typecode == TypeCode.FortranString: self.putValue(self.hexencode(value.data()), 'latin1') self.putNumChild(0) - self.putType(typeobj) + self.putType(typeid) - if typeName.endswith('[]'): + if typename.endswith('[]'): # D arrays, gdc compiled. n = value['length'] base = value['ptr'] - self.putType(typeName) + self.putType(typename) self.putItemCount(n) if self.isExpanded(): - self.putArrayData(base.pointer(), n, base.type.target()) + self.putArrayData(self.value_as_address(base), n, base.type.target()) return - #DumperBase.warn('SOME VALUE: %s' % value) - #DumperBase.warn('GENERIC STRUCT: %s' % typeobj) - #DumperBase.warn('INAME: %s ' % self.currentIName) - #DumperBase.warn('INAMES: %s ' % self.expandedINames) - #DumperBase.warn('EXPANDED: %s ' % (self.currentIName in self.expandedINames)) - self.putType(typeName) + #self.warn('SOME VALUE: %s' % value) + #self.warn('GENERIC STRUCT: %s' % typeid) + #self.warn('INAME: %s ' % self.currentIName) + #self.warn('INAMES: %s ' % self.expandedINames) + #self.warn('EXPANDED: %s ' % (self.currentIName in self.expandedINames)) + self.putType(typename) if value.summary is not None and self.useFancy: self.putValue(self.hexencode(value.summary), 'utf8:1:0') @@ -2898,8 +3087,8 @@ class DumperBase(): self.putExpandable() self.putEmptyValue() - #DumperBase.warn('STRUCT GUTS: %s ADDRESS: 0x%x ' % (value.name, value.address())) - if self.showQObjectNames: + #self.warn('STRUCT GUTS: %s ADDRESS: 0x%x ' % (value.name, value.address())) + if self.wantQObjectNames(): #with self.timer(self.currentIName): self.putQObjectNameValue(value) if self.isExpanded(): @@ -2907,12 +3096,12 @@ class DumperBase(): self.putField('sortable', 1) with Children(self, 1, childType=None): self.putFields(value) - if self.showQObjectNames: + if self.wantQObjectNames(): self.tryPutQObjectGuts(value) def symbolAddress(self, symbolName): - res = self.parseAndEvaluate('(size_t)&' + symbolName) - return None if res is None else res.pointer() + res = self.parseAndEvaluate('(void *)&' + symbolName) + return None if res is None else self.value_as_address(res) def qtHookDataSymbolName(self): return 'qtHookData' @@ -2922,7 +3111,7 @@ class DumperBase(): if addr: # Only available with Qt 5.3+ (hookVersion, x, x, x, x, x, tiVersion) = self.split('ppppppp', addr) - #DumperBase.warn('HOOK: %s TI: %s' % (hookVersion, tiVersion)) + #self.warn('HOOK: %s TI: %s' % (hookVersion, tiVersion)) if hookVersion >= 3: self.qtTypeInfoVersion = lambda: tiVersion return tiVersion @@ -2954,16 +3143,15 @@ class DumperBase(): #self._stack = inspect.stack() self.dumper = dumper self.name = None - self._type = None + self.typeid = None + self.code = None + self.size = None self.ldata = None # Target address in case of references and pointers. self.laddress = None # Own address. self.lvalue = None self.lIsInScope = True self.ldisplay = None self.summary = None # Always hexencoded UTF-8. - self.lbitpos = None - self.lbitsize = None - self.targetValue = None # For references. self.isBaseClass = None self.nativeValue = None self.autoDerefCount = 0 @@ -2972,49 +3160,47 @@ class DumperBase(): val = self.dumper.Value(self.dumper) val.dumper = self.dumper val.name = self.name - val._type = self._type + val.typeid = self.typeid + val.code = self.code = None + val.size = self.size val.ldata = self.ldata val.laddress = self.laddress + val.lvalue = self.lvalue val.lIsInScope = self.lIsInScope val.ldisplay = self.ldisplay val.summary = self.summary - val.lbitpos = self.lbitpos - val.lbitsize = self.lbitsize - val.targetValue = self.targetValue val.nativeValue = self.nativeValue return val @property def type(self): - if self._type is None and self.nativeValue is not None: - self._type = self.dumper.nativeValueType(self.nativeValue) - return self._type + return self.dumper.Type(self.dumper, self.typeid) def check(self): - if self.laddress is not None and not self.dumper.isInt(self.laddress): - raise RuntimeError('INCONSISTENT ADDRESS: %s' % type(self.laddress)) - if self.type is not None and not isinstance(self.type, self.dumper.Type): - raise RuntimeError('INCONSISTENT TYPE: %s' % type(self.type)) + #if self.typeid is not None and not isinstance(self.typeid, int): + # raise RuntimeError('INCONSISTENT TYPE: %s' % type(self.typeid)) + #if self.laddress is not None and not isinstance(self.laddress, int): + # raise RuntimeError('INCONSISTENT ADDRESS: %s' % type(self.laddress)) + pass def __str__(self): #raise RuntimeError('Not implemented') return self.stringify() def __int__(self): - return self.integer() + return self.dumper.value_as_integer(self) def stringify(self): addr = 'None' if self.laddress is None else ('0x%x' % self.laddress) - return "Value(name='%s',type=%s,bsize=%s,bpos=%s,data=%s,address=%s)" \ - % (self.name, self.type.name, self.lbitsize, self.lbitpos, - self.dumper.hexencode(self.ldata), addr) + if isinstance(self.ldata, int): + data = str(self.ldata) + else: + data = self.dumper.hexencode(self.ldata) + return "Value(name='%s',typeid=%s, type=%s,data=%s,address=%s)" \ + % (self.name, self.typeid, self.type.name, data, addr) def displayEnum(self, form='%d', bitsize=None): - intval = self.integer(bitsize) - dd = self.type.tdata.enumDisplay - if dd is None: - return str(intval) - return dd(intval, self.laddress, form) + return self.dumper.value_display_enum(self, form, bitsize) def display(self): if self.ldisplay is not None: @@ -3023,451 +3209,70 @@ class DumperBase(): if simple is not None: return str(simple) #if self.ldata is not None: - # if sys.version_info[0] == 2 and isinstance(self.ldata, buffer): - # return bytes(self.ldata).encode('hex') # return self.ldata.encode('hex') if self.laddress is not None: return 'value of type %s at address 0x%x' % (self.type.name, self.laddress) return '' def pointer(self): - if self.type.code == TypeCode.Typedef: - return self.detypedef().pointer() - return self.extractInteger(self.dumper.ptrSize() * 8, True) + return self.dumper.value_as_address(self) - def integer(self, bitsize=None): - if self.type.code == TypeCode.Typedef: - return self.detypedef().integer() - elif isinstance(self.lvalue, int): - return self.lvalue - # Could be something like 'short unsigned int' - unsigned = self.type.name == 'unsigned' \ - or self.type.name.startswith('unsigned ') \ - or self.type.name.find(' unsigned ') != -1 - if bitsize is None: - bitsize = self.type.lbitsize - return self.extractInteger(bitsize, unsigned) + def as_address(self): + return self.dumper.value_as_address(self) + + def integer(self): + return self.dumper.value_as_integer(self) def floatingPoint(self): - if self.nativeValue is not None and not self.dumper.isCdb: - return str(self.nativeValue) - if self.type.code == TypeCode.Typedef: - return self.detypedef().floatingPoint() - if self.type.size() == 8: - return self.extractSomething('d', 64) - if self.type.size() == 4: - return self.extractSomething('f', 32) - # Fall back in case we don't have a nativeValue at hand. - # FIXME: This assumes Intel's 80bit extended floats. Which might - # be wrong. - l, h = self.split('QQ') - if True: # 80 bit floats - sign = (h >> 15) & 1 - exp = (h & 0x7fff) - fraction = l - bit63 = (l >> 63) & 1 - #DumperBase.warn("SIGN: %s EXP: %s H: 0x%x L: 0x%x" % (sign, exp, h, l)) - if exp == 0: - if bit63 == 0: - if l == 0: - res = '-0' if sign else '0' - else: - res = (-1)**sign * l * 2**(-16382) # subnormal - else: - res = 'pseudodenormal' - elif exp == 0x7fff: - res = 'special' - else: - res = (-1)**sign * l * 2**(exp - 16383 - 63) - else: # 128 bits - sign = h >> 63 - exp = (h >> 48) & 0x7fff - fraction = h & (2**48 - 1) - #DumperBase.warn("SIGN: %s EXP: %s FRAC: %s H: 0x%x L: 0x%x" % (sign, exp, fraction, h, l)) - if exp == 0: - if fraction == 0: - res = -0.0 if sign else 0.0 - else: - res = (-1)**sign * fraction / 2**48 * 2**(-62) # subnormal - elif exp == 0x7fff: - res = ('-inf' if sign else 'inf') if fraction == 0 else 'nan' - else: - res = (-1)**sign * (1 + fraction / 2**48) * 2**(exp - 63) - return res + return self.dumper.value_as_floating_point(self) def value(self): - if self.type is not None: - if self.type.code == TypeCode.Enum: - return self.displayEnum() - if self.type.code == TypeCode.Typedef: - return self.detypedef().value() - if self.type.code == TypeCode.Integral: - return self.integer() - if self.type.code == TypeCode.Bitfield: - return self.integer() - if self.type.code == TypeCode.Float: - return self.floatingPoint() - if self.type.code == TypeCode.Pointer: - return self.pointer() - return None + return self.dumper.value_display(self) def extractPointer(self): - return self.split('p')[0] + return self.dumper.value_extract_something(self, self.dumper.ptrSize()) def hasMember(self, name): - return self.findMemberByName(name) is not None + return self.dumper.value_member_by_name(self, name) is not None - def findMemberByName(self, name): - self.check() - if self.type.code == TypeCode.Typedef: - return self.findMemberByName(self.detypedef()) - if self.type.code in ( - TypeCode.Pointer, - TypeCode.Reference, - TypeCode.RValueReference): - res = self.dereference().findMemberByName(name) - if res is not None: - return res - if self.type.code == TypeCode.Struct: - #DumperBase.warn('SEARCHING FOR MEMBER: %s IN %s' % (name, self.type.name)) - members = self.members(True) - #DumperBase.warn('MEMBERS: %s' % members) - for member in members: - #DumperBase.warn('CHECKING FIELD %s' % member.name) - if member.type.code == TypeCode.Typedef: - member = member.detypedef() - if member.name == name: - return member - for member in members: - if member.type.code == TypeCode.Typedef: - member = member.detypedef() - if member.name == name: # Could be base class. - return member - if member.type.code == TypeCode.Struct: - res = member.findMemberByName(name) - if res is not None: - return res - return None + def __getitem__(self, indexish): + return self.dumper.value_member_by_indexish(self, indexish) - def __getitem__(self, index): - #DumperBase.warn('GET ITEM %s %s' % (self, index)) - self.check() - if self.type.code == TypeCode.Typedef: - #DumperBase.warn('GET ITEM STRIP TYPEDEFS TO %s' % self.type.ltarget) - return self.cast(self.type.ltarget).__getitem__(index) - if isinstance(index, str): - if self.type.code == TypeCode.Pointer: - #DumperBase.warn('GET ITEM %s DEREFERENCE TO %s' % (self, self.dereference())) - return self.dereference().__getitem__(index) - res = self.findMemberByName(index) - if res is None: - raise RuntimeError('No member named %s in type %s' - % (index, self.type.name)) - return res - elif isinstance(index, self.dumper.Field): - field = index - elif self.dumper.isInt(index): - if self.type.code == TypeCode.Array: - addr = self.laddress + int(index) * self.type.ltarget.size() - return self.dumper.createValue(addr, self.type.ltarget) - if self.type.code == TypeCode.Pointer: - addr = self.pointer() + int(index) * self.type.ltarget.size() - return self.dumper.createValue(addr, self.type.ltarget) - return self.members(False)[index] - else: - raise RuntimeError('BAD INDEX TYPE %s' % type(index)) - field.check() - - #DumperBase.warn('EXTRACT FIELD: %s, BASE 0x%x' % (field, self.address())) - if self.type.code == TypeCode.Pointer: - #DumperBase.warn('IS TYPEDEFED POINTER!') - res = self.dereference() - #DumperBase.warn('WAS POINTER: %s' % res) - - return field.extract(self) - - def extractField(self, field): - if not isinstance(field, self.dumper.Field): - raise RuntimeError('BAD INDEX TYPE %s' % type(field)) - - if field.extractor is not None: - val = field.extractor(self) - if val is not None: - #DumperBase.warn('EXTRACTOR SUCCEEDED: %s ' % val) - return val - - if self.type.code == TypeCode.Typedef: - return self.cast(self.type.ltarget).extractField(field) - if self.type.code in (TypeCode.Reference, TypeCode.RValueReference): - return self.dereference().extractField(field) - #DumperBase.warn('FIELD: %s ' % (field,)) - val = self.dumper.Value(self.dumper) - val.name = field.name - val.isBaseClass = field.isBase - val._type = field.fieldType() - - if field.isArtificial: - if self.laddress is not None: - val.laddress = self.laddress - if self.ldata is not None: - val.ldata = self.ldata - return val - - fieldBitsize = field.bitsize - fieldSize = (fieldBitsize + 7) // 8 - fieldBitpos = field.bitpos - fieldOffset = fieldBitpos // 8 - fieldType = field.fieldType() - - if fieldType.code == TypeCode.Bitfield: - fieldBitpos -= fieldOffset * 8 - ldata = self.data() - data = 0 - for i in range(fieldSize): - data = data << 8 - if self.dumper.isBigEndian: - lbyte = ldata[i] - else: - lbyte = ldata[fieldOffset + fieldSize - 1 - i] - if isinstance(lbyte, (str, bytes)): - data += ord(lbyte) - else: - data += lbyte - data = data >> fieldBitpos - data = data & ((1 << fieldBitsize) - 1) - val.lvalue = data - val.laddress = None - return val - - if self.laddress is not None: - val.laddress = self.laddress + fieldOffset - elif self.ldata is not None: - val.ldata = self.ldata[fieldOffset:fieldOffset + fieldSize] - else: - self.dumper.check(False) - - if fieldType.code in (TypeCode.Reference, TypeCode.RValueReference): - if val.laddress is not None: - val = self.dumper.createReferenceValue(val.laddress, fieldType.ltarget) - val.name = field.name - - #DumperBase.warn('GOT VAL %s FOR FIELD %s' % (val, field)) - val.lbitsize = fieldBitsize - val.check() - return val - - # This is the generic version for synthetic values. - # The native backends replace it in their fromNativeValue() - # implementations. - def members(self, includeBases): - #DumperBase.warn("LISTING MEMBERS OF %s" % self) - if self.type.code == TypeCode.Typedef: - return self.detypedef().members(includeBases) - - tdata = self.type.tdata - #if isinstance(tdata.lfields, list): - # return tdata.lfields - - fields = [] - if tdata.lfields is not None: - if isinstance(tdata.lfields, list): - fields = tdata.lfields - else: - fields = list(tdata.lfields(self)) - - #DumperBase.warn("FIELDS: %s" % fields) - res = [] - for field in fields: - if isinstance(field, self.dumper.Value): - #DumperBase.warn("USING VALUE DIRECTLY %s" % field.name) - res.append(field) - continue - if field.isBase and not includeBases: - #DumperBase.warn("DROPPING BASE %s" % field.name) - continue - res.append(self.extractField(field)) - #DumperBase.warn("GOT MEMBERS: %s" % res) - return res + def members(self, include_bases): + return self.dumper.value_members(self, include_bases) def __add__(self, other): - self.check() - if self.dumper.isInt(other): - stripped = self.type.stripTypedefs() - if stripped.code == TypeCode.Pointer: - address = self.pointer() + stripped.dereference().size() * other - val = self.dumper.Value(self.dumper) - val.laddress = None - val.ldata = bytes(struct.pack(self.dumper.packCode + 'Q', address)) - val._type = self._type - return val - raise RuntimeError('BAD DATA TO ADD TO: %s %s' % (self.type, other)) + return self.dumper.value_plus_something(self, other) def __sub__(self, other): - self.check() - if self.type.name == other.type.name: - stripped = self.type.stripTypedefs() - if stripped.code == TypeCode.Pointer: - return (self.pointer() - other.pointer()) // stripped.dereference().size() - raise RuntimeError('BAD DATA TO SUB TO: %s %s' % (self.type, other)) + return self.dumper.value_minus_something(self, other) def dereference(self): - self.check() - if self.type.code == TypeCode.Typedef: - return self.detypedef().dereference() - val = self.dumper.Value(self.dumper) - if self.type.code in (TypeCode.Reference, TypeCode.RValueReference): - val.summary = self.summary - if self.nativeValue is None: - val.laddress = self.pointer() - if val.laddress is None and self.laddress is not None: - val.laddress = self.laddress - val._type = self.type.dereference() - if self.dumper.useDynamicType: - val._type = self.dumper.nativeDynamicType(val.laddress, val.type) - else: - val = self.dumper.nativeValueDereferenceReference(self) - elif self.type.code == TypeCode.Pointer: - try: - val = self.dumper.nativeValueDereferencePointer(self) - except: - val.laddress = self.pointer() - val._type = self.type.dereference() - if self.dumper.useDynamicType: - val._type = self.dumper.nativeDynamicType(val.laddress, val.type) - else: - raise RuntimeError("WRONG: %s" % self.type.code) - #DumperBase.warn("DEREFERENCING FROM: %s" % self) - #DumperBase.warn("DEREFERENCING TO: %s" % val) - #dynTypeName = val.type.dynamicTypeName(val.laddress) - #if dynTypeName is not None: - # val._type = self.dumper.createType(dynTypeName) - return val + return self.dumper.value_dereference(self) def detypedef(self): - self.check() - if self.type.code != TypeCode.Typedef: - raise RuntimeError("WRONG") - val = self.copy() - val._type = self.type.ltarget - #DumperBase.warn("DETYPEDEF FROM: %s" % self) - #DumperBase.warn("DETYPEDEF TO: %s" % val) - return val - - def extend(self, size): - if self.type.size() < size: - val = self.dumper.Value(self.dumper) - val.laddress = None - val.ldata = self.zeroExtend(self.ldata) - return val - if self.type.size() == size: - return self - raise RuntimeError('NOT IMPLEMENTED') - - def zeroExtend(self, data, size): - ext = '\0' * (size - len(data)) - if sys.version_info[0] == 3: - pad = bytes(ext, encoding='latin1') - else: - pad = bytes(ext) - return pad + data if self.dumper.isBigEndian else data + pad + return self.dumper.value_detypedef(self) def cast(self, typish): - self.check() - val = self.dumper.Value(self.dumper) - val.laddress = self.laddress - val.lbitsize = self.lbitsize - val.ldata = self.ldata - val._type = self.dumper.createType(typish) - return val + return self.dumper.value_cast(self, typish) def address(self): self.check() return self.laddress - def data(self, size=None): - self.check() - if self.ldata is not None: - if len(self.ldata) > 0: - if size is None: - return self.ldata - if size == len(self.ldata): - return self.ldata - if size < len(self.ldata): - return self.ldata[:size] - #raise RuntimeError('ZERO-EXTENDING DATA TO %s BYTES: %s' % (size, self)) - return self.zeroExtend(self.ldata, size) - if self.laddress is not None: - if size is None: - size = self.type.size() - res = self.dumper.readRawMemory(self.laddress, size) - if len(res) > 0: - return res - raise RuntimeError('CANNOT CONVERT ADDRESS TO BYTES: %s' % self) - raise RuntimeError('CANNOT CONVERT TO BYTES: %s' % self) - - def extractInteger(self, bitsize, unsigned): - #with self.dumper.timer('extractInt'): - self.check() - if bitsize > 32: - size = 8 - code = 'Q' if unsigned else 'q' - elif bitsize > 16: - size = 4 - code = 'I' if unsigned else 'i' - elif bitsize > 8: - size = 2 - code = 'H' if unsigned else 'h' - else: - size = 1 - code = 'B' if unsigned else 'b' - rawBytes = self.data(size) - res = struct.unpack_from(self.dumper.packCode + code, rawBytes, 0)[0] - #DumperBase.warn('Extract: Code: %s Bytes: %s Bitsize: %s Size: %s' - # % (self.dumper.packCode + code, self.dumper.hexencode(rawBytes), bitsize, size)) - return res - - def extractSomething(self, code, bitsize): - #with self.dumper.timer('extractSomething'): - self.check() - size = (bitsize + 7) >> 3 - rawBytes = self.data(size) - res = struct.unpack_from(self.dumper.packCode + code, rawBytes, 0)[0] - return res + def data(self): + return self.dumper.value_data(self, self.dumper.type_size(self.typeid)) def to(self, pattern): return self.split(pattern)[0] def split(self, pattern): - #with self.dumper.timer('split'): - #DumperBase.warn('EXTRACT STRUCT FROM: %s' % self.type) - (pp, size, fields) = self.dumper.describeStruct(pattern) - #DumperBase.warn('SIZE: %s ' % size) - result = struct.unpack_from(self.dumper.packCode + pp, self.data(size)) - - def structFixer(field, thing): - #DumperBase.warn('STRUCT MEMBER: %s' % type(thing)) - if field.isStruct: - #if field.type != field.fieldType(): - # raise RuntimeError('DO NOT SIMPLIFY') - #DumperBase.warn('FIELD POS: %s' % field.type.stringify()) - #DumperBase.warn('FIELD TYE: %s' % field.fieldType().stringify()) - res = self.dumper.createValue(thing, field.fieldType()) - #DumperBase.warn('RES TYPE: %s' % res.type) - if self.laddress is not None: - res.laddress = self.laddress + field.offset() - return res - return thing - if len(fields) != len(result): - raise RuntimeError('STRUCT ERROR: %s %s' % (fields, result)) - return tuple(map(structFixer, fields, result)) + return self.dumper.value_split(self, pattern) def checkPointer(self, p, align=1): - ptr = p if self.isInt(p) else p.pointer() + ptr = p if isinstance(p, int) else p.pointer() self.readRawMemory(ptr, 1) - def type(self, typeId): - return self.typeData.get(typeId) - def splitArrayType(self, type_name): # "foo[2][3][4]" -> ("foo", "[3][4]", 2) pos1 = len(type_name) @@ -3481,249 +3286,165 @@ class DumperBase(): item_count = type_name[pos1 + 1:pos2] return (type_name[0:pos1].strip(), type_name[pos2 + 1:].strip(), int(item_count)) - def registerTypeAlias(self, existingTypeId, aliasId): - #DumperBase.warn('REGISTER ALIAS %s FOR %s' % (aliasId, existingTypeId)) - self.typeData[aliasId] = self.typeData[existingTypeId] + def registerTypeAlias(self, existing_type_id, alias_id): + #self.warn('REGISTER ALIAS %s FOR %s' % (aliasId, existingTypeId)) + self.type_alias[alias_id] = existing_type_id - class TypeData(): - def __init__(self, dumper, type_id): - self.dumper = dumper - self.lfields = None # None or Value -> list of member Values - self.lalignment = None # Function returning alignment of this struct - self.lbitsize = None - self.ltarget = None # Inner type for arrays - self.templateArguments = None - self.code = None - self.name = type_id - self.typeId = type_id - self.enumDisplay = None - self.moduleName = None - #DumperBase.warn('REGISTER TYPE: %s' % type_id) - dumper.typeData[type_id] = self + def init_type_cache(self): + self.type_name_cache = {} + self.type_fields_cache = {} + self.type_alignment_cache = {} + self.type_bitsize_cache = {} + self.type_size_cache = {} + self.type_target_cache = {} + self.type_template_arguments_cache = {} + self.type_code_cache = {} + self.type_enum_display_cache = {} + self.type_module_name_cache = {} + self.type_nativetype_cache = {} + self.type_modulename_cache = {} + self.type_encoding_cache = {} + self.type_qobject_based_cache = {} + self.typeid_cache = {} # internal typename -> id + self.typeid_current = 100 + self.typeid_from_typekey = {} # typename -> id - def copy(self): - tdata = self.dumper.TypeData(self.dumper, self.typeId) - tdata.dumper = self.dumper - tdata.lfields = self.lfields - tdata.lalignment = self.lalignment - tdata.lbitsize = self.lbitsize - tdata.ltarget = self.ltarget - tdata.templateArguments = self.templateArguments - tdata.code = self.code - tdata.name = self.name - tdata.typeId = self.typeId - tdata.enumDisplay = self.enumDisplay - tdata.moduleName = self.moduleName - return tdata + def dump_type_cache(self): + self.warn('NAME: %s' % self.type_name_cache) + self.warn('CODE: %s' % self.type_code_cache) + #self.warn('FIELDS: %s' % self.type_fields_cache) + self.warn('SIZE: %s' % self.type_size_cache) + self.warn('TARGS: %s' % self.type_template_arguments_cache) + self.warn('BITSIZE: %s' % self.type_bitsize_cache) + self.warn('TARGET: %s' % self.type_target_cache) + #self.warn('NATIVETYPE: %s' % self.type_nativetype_cache) - @property - def bitsize(self): - if callable(self.lbitsize): - self.lbitsize = self.lbitsize() - return self.lbitsize + def dump_typeid(self, typeid): + self.warn(' NAME: %s' % self.type_name_cache.get(typeid, None)) + self.warn(' CODE: %s' % self.type_code_cache.get(typeid, None)) + #self.warn(' FIELDS: %s' % self.type_fields_cache.get(typeid, None)) + self.warn(' SIZE: %s' % self.type_size_cache.get(typeid, None)) + self.warn(' TARGS: %s' % self.type_template_arguments_cache.get(typeid, None)) + self.warn(' BITSIZE: %s' % self.type_bitsize_cache.get(typeid, None)) + self.warn(' TARGET: %s' % self.type_target_cache.get(typeid, None)) + #self.warn(' NATIVETYPE: %s' % self.type_nativetype_cache.get(typeid, None)) + + def typeid_for_typish(self, typish): + if isinstance(typish, int): + return typish + if isinstance(typish, str): + return self.typeid_for_string(typish) + if isinstance(typish, self.Type): + return typish.typeid + self.warn('NO TYPE FOR TYPISH: %s' % str(typish)) + return 0 + + def sanitize_type_name(self, typeid_str): + if not ' ' in typeid_str: + # FIXME: This uses self.qtNamespace() too early. + #typeid_arr.append(self.qtNamespace()) + return typeid_str.replace('@', '') + typeid_arr = [] + last_char_was_space = False + for c in typeid_str: + if c == '@' in typeid_str: + # FIXME: This uses self.qtNamespace() too early. + #typeid_arr.append(self.qtNamespace()) + pass + elif c == ' ': + last_char_was_space = True + elif c in '&*<>,': + last_char_was_space = False + typeid_arr.append(c) + else: + if last_char_was_space: + typeid_arr.append(' ') + last_char_was_space = False + typeid_arr.append(c) + #self.warn("SANITIZE: '%s' TO '%s'" % (typeid_str, ''.join(typeid_arr))) + return ''.join(typeid_arr) + + def typeid_for_string(self, typeid_str, type_name=None): + #typeid = self.typeid_cache.get(typeid_str, None) + #if typeid is not None: + # return typeid + sane_typeid_str = self.sanitize_type_name(typeid_str) + typeid = self.typeid_cache.get(sane_typeid_str, None) + if typeid is not None: + return typeid + + self.typeid_current += 1 + if type_name is None: + type_name = sane_typeid_str + typeid = self.typeid_current + self.typeid_cache[typeid_str] = typeid + self.typeid_cache[sane_typeid_str] = typeid + self.type_name_cache[typeid] = type_name + #if typeid == 103: + #self.warn("CREATED TYPE: %d %s" % (typeid, sane_typeid_str)) + #if typeid == 135: self.dump_location() + return typeid class Type(): - def __init__(self, dumper, typeId): - self.typeId = typeId.replace('@', dumper.qtNamespace()) + __slots__ = ['dumper', 'typeid'] + def __init__(self, dumper, typeid): self.dumper = dumper - self.initialized = False + self.typeid = typeid def __str__(self): - #return self.typeId - return self.stringify() - - @property - def tdata(self): - if not self.initialized: - self.initialized = True - self.data = self.dumper.typeData.get(self.typeId, None) - if self.data is None: - #DumperBase.warn('USING : %s' % self.typeId) - self.dumper.lookupType(self.typeId) - self.data = self.dumper.typeData.get(self.typeId) - return self.data - - def setTdata(self, tdata): - self.initialized = True - self.data = tdata + return self.dumper.type_stringify(self.typeid) @property def name(self): - return self.typeId if self.tdata is None else self.tdata.name + return self.dumper.type_name(self.typeid) @property def code(self): - return self.tdata.code + return self.dumper.type_code(self.typeid) - @property - def lbitsize(self): - return self.tdata.bitsize + def bitsize(self): + return self.dumper.type_bitsize(self.typeid) - @property - def lbitpos(self): - return self.tdata.lbitpos + def size(self): + return self.dumper.type_size(self.typeid) - @property - def ltarget(self): - if isinstance(self.tdata.ltarget, str): - self.tdata.ltarget = self.dumper.createType(self.tdata.ltarget) - return self.tdata.ltarget - - @property - def targetName(self): - if self.tdata.ltarget is None: - return '' - return self.tdata.ltarget if isinstance(self.tdata.ltarget, str) else self.tdata.ltarget.name + def target(self): + return self.dumper.Type(self.dumper, self.dumper.type_target(self.typeid)) @property def moduleName(self): - if callable(self.tdata.moduleName): - self.tdata.moduleName = self.tdata.moduleName() - return self.tdata.moduleName - - def stringify(self): - return 'Type(name="%s",bsize=%s,code=%s)' \ - % (self.tdata.name, self.lbitsize, self.tdata.code) + return self.dumper.type_modulename_cache.get(self.typeid, None) def __getitem__(self, index): - if self.dumper.isInt(index): - return self.templateArgument(index) + if isinstance(index, int): + return self.dumper.type_template_argument(self.typeid, index) raise RuntimeError('CANNOT INDEX TYPE') - def dynamicTypeName(self, address): - if self.tdata.code != TypeCode.Struct: - return None - try: - vtbl = self.dumper.extractPointer(address) - except: - return None - #DumperBase.warn('VTBL: 0x%x' % vtbl) - if not self.dumper.couldBePointer(vtbl): - return None - return self.dumper.nativeDynamicTypeName(address, self) - - def dynamicType(self, address): - # FIXME: That buys some performance at the cost of a fail - # of Gdb13393 dumper test. - #return self - #with self.dumper.timer('dynamicType %s 0x%s' % (self.name, address)): - dynTypeName = self.dynamicTypeName(address) - if dynTypeName is not None: - return self.dumper.createType(dynTypeName) - return self - def check(self): - if self.tdata.name is None: - raise RuntimeError('TYPE WITHOUT NAME: %s' % self.typeId) + #if self.tdata.name is None: + # raise RuntimeError('TYPE WITHOUT NAME: %s' % self.typeid) + pass def dereference(self): - if self.code == TypeCode.Typedef: - return self.ltarget.dereference() - self.check() - return self.ltarget - - def unqualified(self): - return self + return self.dumper.Type(self.dumper, self.dumper.type_dereference(self.typeid)) def templateArguments(self): - if self.tdata is None: - return self.dumper.listTemplateParameters(self.typeId) - return self.tdata.templateArguments() + return self.dumper.type_template_arguments(self.typeid) - def templateArgument(self, position): - #DumperBase.warn('TDATA: %s' % self.tdata) - #DumperBase.warn('ID: %s' % self.typeId) - if self.tdata is None or self.tdata.templateArguments is None: - # Native lookups didn't help. Happens for 'wrong' placement of 'const' - # etc. with LLDB. But not all is lost: - ta = self.dumper.listTemplateParameters(self.typeId) - #DumperBase.warn('MANUAL: %s' % ta) - res = ta[position] - #DumperBase.warn('RES: %s' % res.typeId) - return res - #DumperBase.warn('TA: %s %s' % (position, self.typeId)) - #DumperBase.warn('ARGS: %s' % self.tdata.templateArguments()) - return self.tdata.templateArguments()[position] - - def simpleEncoding(self): - res = { - 'bool': 'int:1', - 'char': 'int:1', - 'int8_t': 'int:1', - 'qint8': 'int:1', - 'signed char': 'int:1', - 'char8_t': 'uint:1', - 'unsigned char': 'uint:1', - 'uint8_t': 'uint:1', - 'quint8': 'uint:1', - 'short': 'int:2', - 'int16_t': 'int:2', - 'qint16': 'int:2', - 'unsigned short': 'uint:2', - 'char16_t': 'uint:2', - 'uint16_t': 'uint:2', - 'quint16': 'uint:2', - 'int': 'int:4', - 'int32_t': 'int:4', - 'qint32': 'int:4', - 'unsigned int': 'uint:4', - 'char32_t': 'uint:4', - 'uint32_t': 'uint:4', - 'quint32': 'uint:4', - 'long long': 'int:8', - 'int64_t': 'int:8', - 'qint64': 'int:8', - 'unsigned long long': 'uint:8', - 'uint64_t': 'uint:8', - 'quint64': 'uint:8', - 'float': 'float:4', - 'double': 'float:8', - 'QChar': 'uint:2' - }.get(self.name, None) - return res + def templateArgument(self, index): + return self.dumper.type_template_argument(self.typeid, index) def isSimpleType(self): return self.code in (TypeCode.Integral, TypeCode.Float, TypeCode.Enum) def alignment(self): - if self.tdata.code == TypeCode.Typedef: - return self.ltarget.alignment() - if self.tdata.code in (TypeCode.Integral, TypeCode.Float, TypeCode.Enum): - if self.tdata.name in ('double', 'long long', 'unsigned long long'): - # Crude approximation. - return 8 if self.dumper.isWindowsTarget() else self.dumper.ptrSize() - return self.size() - if self.tdata.code in (TypeCode.Pointer, TypeCode.Reference, TypeCode.RValueReference): - return self.dumper.ptrSize() - if self.tdata.lalignment is not None: - #if isinstance(self.tdata.lalignment, function): # Does not work that way. - if hasattr(self.tdata.lalignment, '__call__'): - return self.tdata.lalignment() - return self.tdata.lalignment - return 1 + return self.dumper.type_alignment(self.typeid) def pointer(self): - return self.dumper.createPointerType(self) - - def target(self): - return self.ltarget + return self.dumper.Type(self.dumper, self.dumper.create_pointer_typeid(self.typeid)) def stripTypedefs(self): - if isinstance(self, self.dumper.Type) and self.code != TypeCode.Typedef: - #DumperBase.warn('NO TYPEDEF: %s' % self) - return self - return self.ltarget - - def size(self): - bs = self.lbitsize - if bs % 8 != 0: - DumperBase.warn('ODD SIZE: %s' % self) - return (7 + bs) >> 3 - - def bitsize(self): - if self.lbitsize is not None: - return self.lbitsize - raise RuntimeError('DONT KNOW SIZE: %s' % self) + return self.dumper.Type(self.dumper, self.dumper.type_target(self.typeid)) def isMovableType(self): if self.code in (TypeCode.Pointer, TypeCode.Integral, TypeCode.Float): @@ -3743,269 +3464,202 @@ class DumperBase(): ): return True if strippedName == 'QStringList': - return self.dumper.qtVersion() >= 0x050000 + return self.dumper.qtVersionAtLeast(0x050000) if strippedName == 'QList': - return self.dumper.qtVersion() >= 0x050600 + return self.dumper.qtVersionAtLeast(0x050600) return False - class Field(collections.namedtuple('Field', - ['dumper', 'name', 'type', 'bitsize', 'bitpos', - 'extractor', 'isBase', 'isStruct', 'isArtificial'])): + class Field: + __slots__ = ['name', 'typeid', 'bitsize', 'bitpos', 'is_struct', 'is_artificial', 'is_base_class'] - def __new__(cls, dumper, name=None, type=None, bitsize=None, bitpos=None, - extractor=None, isBase=False, isStruct=False, isArtificial=False): - return super(DumperBase.Field, cls).__new__( - cls, dumper, name, type, bitsize, bitpos, - extractor, isBase, isStruct, isArtificial) + def __init__(self, name=None, typeid=None, bitsize=None, bitpos=None, + extractor=None, is_struct=False, is_artificial=False, is_base_class=False): + self.name = name + self.typeid = typeid + self.bitsize = bitsize + self.bitpos = bitpos + self.is_struct = is_struct + self.is_base_class = is_base_class - __slots__ = () - - def __str__(self): - return self.stringify() - - def stringify(self): - #return 'Field(name="%s")' % self.name - typename = None if self.type is None else self.type.stringify() - return 'Field(name="%s",type=%s,bitpos=%s,bitsize=%s)' \ - % (self.name, typename, self.bitpos, self.bitsize) - - def check(self): - pass - - def size(self): - return self.bitsize() // 8 - - def offset(self): - return self.bitpos // 8 - - def fieldType(self): - if self.type is not None: - return self.type - raise RuntimeError('CANT GET FIELD TYPE FOR %s' % self) - return None def ptrCode(self): return 'I' if self.ptrSize() == 4 else 'Q' - def toPointerData(self, address): - if not self.isInt(address): - raise RuntimeError('wrong') - return bytes(struct.pack(self.packCode + self.ptrCode(), address)) - def fromPointerData(self, bytes_value): return struct.unpack(self.packCode + self.ptrCode(), bytes_value) - def createPointerValue(self, targetAddress, targetTypish): - if not isinstance(targetTypish, self.Type) and not isinstance(targetTypish, str): - raise RuntimeError('Expected type in createPointerValue(), got %s' - % type(targetTypish)) - if not self.isInt(targetAddress): + def createPointerValue(self, target_address, target_typish): + if not isinstance(target_address, int): raise RuntimeError('Expected integral address value in createPointerValue(), got %s' - % type(targetTypish)) + % type(target_typish)) val = self.Value(self) - val.ldata = self.toPointerData(targetAddress) - targetType = self.createType(targetTypish) - if self.useDynamicType: - targetType = targetType.dynamicType(targetAddress) - val._type = self.createPointerType(targetType) + val.ldata = target_address + val.typeid = self.create_pointer_typeid(self.create_typeid(target_typish)) return val + #target_typeid = self.create_typeid(target_typish) + #if self.useDynamicType: + # target_typeid = self.dynamic_typeid_at_address(target_typeid, target_address) + #val.typeid = self.create_pointer_typeid(target_typeid) + #return val - def createReferenceValue(self, targetAddress, targetType): - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createReferenceValue(), got %s' - % type(targetType)) - if not self.isInt(targetAddress): - raise RuntimeError('Expected integral address value in createReferenceValue(), got %s' - % type(targetType)) - val = self.Value(self) - val.ldata = self.toPointerData(targetAddress) - if self.useDynamicType: - targetType = targetType.dynamicType(targetAddress) - val._type = self.createReferenceType(targetType) - return val + def createPointerType(self, target_typish): + typeid = self.create_pointer_typeid(self.typeid_for_typish(target_typish)) + return self.Type(self, typeid) - def createPointerType(self, targetType): - if not isinstance(targetType, (str, self.Type)): - raise RuntimeError('Expected type or str in createPointerType(), got %s' - % type(targetType)) - typeId = (targetType if isinstance(targetType, str) else targetType.typeId) + ' *' - tdata = self.TypeData(self, typeId) - tdata.name = (targetType if isinstance(targetType, str) else targetType.name) + '*' - tdata.lbitsize = 8 * self.ptrSize() - tdata.code = TypeCode.Pointer - tdata.ltarget = targetType - return self.Type(self, typeId) + def create_pointer_typeid(self, target_typeid): + name = self.type_name(target_typeid) + ' *' + typeid = self.typeid_for_string(name) + self.type_size_cache[typeid] = self.ptrSize() + self.type_alignment_cache[typeid] = self.ptrSize() + self.type_code_cache[typeid] = TypeCode.Pointer + self.type_target_cache[typeid] = target_typeid + return typeid - def createReferenceType(self, targetType): - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createReferenceType(), got %s' - % type(targetType)) - typeId = targetType.typeId + ' &' - tdata = self.TypeData(self, typeId) - tdata.name = targetType.name + ' &' - tdata.code = TypeCode.Reference - tdata.ltarget = targetType - tdata.lbitsize = 8 * self.ptrSize() # Needed for Gdb13393 test. - #tdata.lbitsize = None - return self.Type(self, typeId) + def create_reference_typeid(self, target_typeid): + type_name = self.type_name_cache[target_typeid] + ' &' + typeid = self.typeid_for_string(type_name) + self.type_code_cache[typeid] = TypeCode.Reference + self.type_target_cache[typeid] = target_typeid + #self.type_size_cache[typeid] = self.ptrSize() # Needed for Gdb13393 test. + return typeid - def createRValueReferenceType(self, targetType): - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createRValueReferenceType(), got %s' - % type(targetType)) - typeId = targetType.typeId + ' &&' - tdata = self.TypeData(self, typeId) - tdata.name = targetType.name + ' &&' - tdata.code = TypeCode.RValueReference - tdata.ltarget = targetType - tdata.lbitsize = None - return self.Type(self, typeId) + def create_rvalue_reference_typeid(self, target_typeid): + type_name = self.type_name_cache[target_typeid] + ' &&' + typeid = self.typeid_for_string(type_name) + self.type_code_cache[typeid] = TypeCode.RValueReference + self.type_target_cache[typeid] = target_typeid + return typeid - def createArrayType(self, targetType, count): - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createArrayType(), got %s' - % type(targetType)) - targetTypeId = targetType.typeId - - if targetTypeId.endswith(']'): - (prefix, suffix, inner_count) = self.splitArrayType(targetTypeId) - type_id = '%s[%d][%d]%s' % (prefix, count, inner_count, suffix) - type_name = type_id + def create_array_typeid(self, target_typeid, count): + target_type_name = self.type_name(target_typeid) + if target_type_name.endswith(']'): + (prefix, suffix, inner_count) = self.splitArrayType(target_type_name) + type_name = '%s[%d][%d]%s' % (prefix, count, inner_count, suffix) else: - type_id = '%s[%d]' % (targetTypeId, count) - type_name = '%s[%d]' % (targetType.name, count) + type_name = '%s[%d]' % (target_type_name, count) + typeid = self.typeid_for_string(type_name) + self.type_code_cache[typeid] = TypeCode.Array + self.type_target_cache[typeid] = target_typeid + self.type_size_cache[typeid] = self.type_size(target_typeid) * count + self.type_alignment_cache[typeid] = self.type_alignment_cache.get(target_typeid, None) + return typeid - tdata = self.TypeData(self, type_id) - tdata.name = type_name - tdata.code = TypeCode.Array - tdata.ltarget = targetType - tdata.lbitsize = targetType.lbitsize * count - return self.Type(self, type_id) + def create_bitfield_typeid(self, target_typeid, bitsize): + target_typename = self.type_name(target_typeid) + typeid = self.typeid_for_string('%s:%d' % (target_typename, bitsize)) + self.type_name_cache[typeid] = '%s : %d' % (target_typename, bitsize) + self.type_code_cache[typeid] = TypeCode.Bitfield + self.type_target_cache[typeid] = target_typeid + self.type_bitsize_cache[typeid] = bitsize + return typeid - def createBitfieldType(self, targetType, bitsize): - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createBitfieldType(), got %s' - % type(targetType)) - typeId = '%s:%d' % (targetType.typeId, bitsize) - tdata = self.TypeData(self, typeId) - tdata.name = '%s : %d' % (targetType.typeId, bitsize) - tdata.code = TypeCode.Bitfield - tdata.ltarget = targetType - tdata.lbitsize = bitsize - return self.Type(self, typeId) - - def createTypedefedType(self, targetType, typeName, typeId=None): - if typeId is None: - typeId = typeName - if not isinstance(targetType, self.Type): - raise RuntimeError('Expected type in createTypedefType(), got %s' - % type(targetType)) + def create_typedefed_typeid(self, target_typeid, type_name, type_key): + typeid = self.typeid_for_string(type_key, type_name) # Happens for C-style struct in GDB: typedef { int x; } struct S1; - if targetType.typeId == typeId: - return targetType - tdata = self.TypeData(self, typeId) - tdata.name = typeName - tdata.code = TypeCode.Typedef - tdata.ltarget = targetType - tdata.lbitsize = targetType.lbitsize - #tdata.lfields = targetType.lfields - tdata.lbitsize = targetType.lbitsize - return self.Type(self, typeId) - - def knownArrayTypeSize(self): - return 3 * self.ptrSize() if self.qtVersion() >= 0x060000 else self.ptrSize() - - def knownTypeSize(self, typish): - if typish[0] == 'Q': - if typish.startswith('QList<') or typish.startswith('QVector<'): - return self.knownArrayTypeSize() - if typish == 'QObject': - return 2 * self.ptrSize() - if typish == 'QStandardItemData': - return 4 * self.ptrSize() if self.qtVersion() >= 0x060000 else 2 * self.ptrSize() - if typish == 'Qt::ItemDataRole': - return 4 - if typish == 'QChar': - return 2 - if typish in ('quint32', 'qint32'): - return 4 - return None + if target_typeid == typeid: + return target_typeid + self.type_code_cache[typeid] = TypeCode.Typedef + self.type_target_cache[typeid] = target_typeid + size = self.type_size_cache.get(target_typeid, None) + if size is not None: + self.type_size_cache[typeid] = size + return typeid def createType(self, typish, size=None): + return self.Type(self, self.create_typeid(typish, size)) + + def create_typeid(self, typish, size=None): + if isinstance(typish, int): + return typish if isinstance(typish, self.Type): - #typish.check() - if hasattr(typish, 'lbitsize') and typish.lbitsize is not None and typish.lbitsize > 0: - return typish - # Size 0 is sometimes reported by GDB but doesn't help at all. - # Force using the fallback: - typish = typish.name - + return typish.typeid if isinstance(typish, str): - ns = self.qtNamespace() - typish = typish.replace('@', ns) - if typish.startswith(ns): - if size is None: - size = self.knownTypeSize(typish[len(ns):]) - else: - if size is None: - size = self.knownTypeSize(typish) - if size is not None: - typish = ns + typish - - tdata = self.typeData.get(typish, None) - if tdata is not None: - if tdata.lbitsize is not None: - if callable(tdata.lbitsize) or tdata.lbitsize > 0: - return self.Type(self, typish) - - knownType = self.lookupType(typish) - #DumperBase.warn('KNOWN: %s' % knownType) - if knownType is not None: - #DumperBase.warn('USE FROM NATIVE') - return knownType - - #DumperBase.warn('FAKING: %s SIZE: %s' % (typish, size)) - tdata = self.TypeData(self, typish) - tdata.templateArguments = lambda: self.listTemplateParameters(typish) - if size is not None: - tdata.lbitsize = 8 * size - if typish.endswith('*'): - tdata.code = TypeCode.Pointer - tdata.lbitsize = 8 * self.ptrSize() - tdata.ltarget = typish[:-1].strip() - - typeobj = self.Type(self, tdata.typeId) - #DumperBase.warn('CREATE TYPE: %s' % typeobj.stringify()) - typeobj.check() - return typeobj + return self.create_typeid_from_name(typish) raise RuntimeError('NEED TYPE, NOT %s' % type(typish)) - def createValueFromAddressAndType(self, address, typish): + def cheap_typeid_from_name(self, typename_): + ns = self.qtNamespace() + typename = typename_.replace('@', ns) + return self.cheap_typeid_from_name_nons(typename) + + def cheap_typeid_from_name_nons(self, typename): + if typename in self.typeid_cache: + return self.typeid_for_string(typename) + + if typename.startswith('QList<') or typename.startswith('QVector<'): + typeid = self.typeid_for_string(typename) + if typeid: + size = 3 * self.ptrSize() if self.qtVersionAtLeast(0x060000) else self.ptrSize() + self.type_code_cache[typeid] = TypeCode.Struct + self.type_size_cache[typeid] = size + return typeid + + if typename.endswith('*'): + inner_typeid = self.cheap_typeid_from_name_nons(typename[0:-1]) + if inner_typeid != 0: + return self.create_pointer_typeid(inner_typeid) + + return 0 + + def create_typeid_from_name(self, typename_, size=None): + ns = self.qtNamespace() + typename = typename_.replace('@', ns) + + if typename in self.typeid_cache: + return self.typeid_for_string(typename) + + # This triggers for boost::variant due to the mis-encoding + # of the second template parameter. [MARK_A] + knownType = self.lookupType(typename) + #self.warn('KNOWN: %s FOR %s' % (knownType, typename)) + if knownType is not None: + #self.warn('USE FROM NATIVE') + #self.dump_location() + return knownType.typeid + + #self.warn('FAKING: %s SIZE: %s' % (typename, size)) + typeid = self.typeid_for_string(typename) + if size is not None: + self.type_size_cache[typeid] = size + self.type_code_cache[typeid] = TypeCode.Struct + if typename.endswith('*'): + self.type_code_cache[typeid] = TypeCode.Pointer + self.type_size_cache[typeid] = self.ptrSize() + self.type_target_cache[typeid] = self.typeid_for_string(typename[:-1].strip()) + + #self.dump_location() + #self.warn('CREATED TYPE: %s' % typeid) + return typeid + + def createValueFromAddress(self, address, typish): val = self.Value(self) - val._type = self.createType(typish) - #DumperBase.warn('CREATING %s AT 0x%x' % (val.type.name, datish)) + val.typeid = self.create_typeid(typish) + #self.warn('CREATING %s AT 0x%x' % (val.type.name, address)) val.laddress = address if self.useDynamicType: - val._type = val.type.dynamicType(address) + val.typeid = self.dynamic_typeid_at_address(val.typeid, address) + return val + + def createValueFromData(self, data, typish): + val = self.Value(self) + val.typeid = self.create_typeid(typish) + #self.warn('CREATING %s WITH DATA %s' % (val.type.name, self.hexencode(data))) + val.ldata = data + val.check() return val def createValue(self, datish, typish): - if self.isInt(datish): # Used as address. - return self.createValueFromAddressAndType(datish, typish) + if isinstance(datish, int): # Used as address. + return self.createValueFromAddress(datish, typish) if isinstance(datish, bytes): - val = self.Value(self) - val._type = self.createType(typish) - #DumperBase.warn('CREATING %s WITH DATA %s' % (val.type.name, self.hexencode(datish))) - val.ldata = datish - val.check() - return val + return self.createValueFromData(datish, typish) raise RuntimeError('EXPECTING ADDRESS OR BYTES, GOT %s' % type(datish)) def createProxyValue(self, proxy_data, type_name): - tdata = self.TypeData(self, type_name) - tdata.code = TypeCode.Struct + typeid = self.typeid_for_string(type_name) + self.type_code_cache[typeid] = TypeCode.Struct val = self.Value(self) - val._type = self.Type(self, type_name) + val.typeid = typeid val.ldata = proxy_data return val @@ -4013,109 +3667,669 @@ class DumperBase(): def __init__(self, dumper): self.dumper = dumper self.pattern = '' - self.currentBitsize = 0 + self.current_size = 0 self.fields = [] self.autoPadNext = False self.maxAlign = 1 - def addField(self, fieldSize, fieldCode=None, fieldIsStruct=False, - fieldName=None, fieldType=None, fieldAlign=1): + def add_field(self, field_size, field_code=None, field_is_struct=False, + field_name=None, field_typeid=0, field_align=1): - if fieldType is not None: - fieldType = self.dumper.createType(fieldType) - if fieldSize is None and fieldType is not None: - fieldSize = fieldType.size() - if fieldCode is None: - fieldCode = '%ss' % fieldSize + if field_code is None: + field_code = '%ss' % field_size + + #self.dumper.warn("FIELD SIZE: %s %s %s " % (field_name, field_size, str(field_align))) if self.autoPadNext: - self.currentBitsize = 8 * ((self.currentBitsize + 7) >> 3) # Fill up byte. - padding = (fieldAlign - (self.currentBitsize >> 3)) % fieldAlign - #DumperBase.warn('AUTO PADDING AT %s BITS BY %s BYTES' % (self.currentBitsize, padding)) - field = self.dumper.Field(self.dumper, bitpos=self.currentBitsize, + padding = (field_align - self.current_size) % field_align + #self.warn('AUTO PADDING AT %s BITS BY %s BYTES' % (self.current_size, padding)) + field = self.dumper.Field(self.dumper, bitpos=self.current_size * 8, bitsize=padding * 8) self.pattern += '%ds' % padding - self.currentBitsize += padding * 8 + self.current_size += padding self.fields.append(field) self.autoPadNext = False - if fieldAlign > self.maxAlign: - self.maxAlign = fieldAlign - #DumperBase.warn("MAX ALIGN: %s" % self.maxAlign) + if field_align > self.maxAlign: + self.maxAlign = field_align - field = self.dumper.Field(dumper=self.dumper, name=fieldName, type=fieldType, - isStruct=fieldIsStruct, bitpos=self.currentBitsize, - bitsize=fieldSize * 8) + #self.warn("MAX ALIGN: %s" % self.maxAlign) - self.pattern += fieldCode - self.currentBitsize += fieldSize * 8 + field = self.dumper.Field(name=field_name, typeid=field_typeid, + is_struct=field_is_struct, bitpos=self.current_size *8, + bitsize=field_size * 8) + + self.pattern += field_code + self.current_size += field_size self.fields.append(field) + def describe_struct_member(self, typename): + typename = typename.replace('@', self.qtNamespace()) + + typeid = self.cheap_typeid_from_name_nons(typename) + if typeid: + size = self.type_size(typeid) + if size is not None: + return size, typeid + + typeobj = self.lookupType(typename) + self.warn("LOOKUP FIELD TYPE: %s TYPEOBJ: %s" % (typename, typeobj)) + if typeobj is not None: + typeid = typeobj.typeid + size = self.type_size(typeid) + if size is not None: + return size, typeid + + self.warn("UNKNOWN EMBEDDED TYPE: %s" % typename) + return 0, 0 + + @functools.lru_cache(maxsize = None) def describeStruct(self, pattern): - if pattern in self.structPatternCache: - return self.structPatternCache[pattern] ptrSize = self.ptrSize() builder = self.StructBuilder(self) n = None - typeName = '' + typename = '' readingTypeName = False + #self.warn("PATTERN: %s" % pattern) for c in pattern: + #self.warn("PAT CODE: %s %s" % (c, str(n))) if readingTypeName: if c == '}': readingTypeName = False - fieldType = self.createType(typeName) - fieldAlign = fieldType.alignment() - builder.addField(n, fieldIsStruct=True, - fieldType=fieldType, fieldAlign=fieldAlign) - typeName = None + n, field_typeid = self.describe_struct_member(typename) + + field_align = self.type_alignment(field_typeid) + builder.add_field(n, + field_is_struct=True, + field_typeid=field_typeid, + field_align=field_align) + typename = None n = None else: - typeName += c + typename += c elif c == 't': # size_t - builder.addField(ptrSize, self.ptrCode(), fieldAlign=ptrSize) + builder.add_field(ptrSize, self.ptrCode(), field_align=ptrSize) elif c == 'p': # Pointer as int - builder.addField(ptrSize, self.ptrCode(), fieldAlign=ptrSize) + builder.add_field(ptrSize, self.ptrCode(), field_align=ptrSize) elif c == 'P': # Pointer as Value - builder.addField(ptrSize, '%ss' % ptrSize, fieldAlign=ptrSize) + builder.add_field(ptrSize, '%ss' % ptrSize, field_align=ptrSize) elif c in ('d'): - builder.addField(8, c, fieldAlign=ptrSize) # fieldType = 'double' ? + builder.add_field(8, c, field_align=ptrSize) # field_type = 'double' ? elif c in ('q', 'Q'): - builder.addField(8, c, fieldAlign=ptrSize) + builder.add_field(8, c, field_align=ptrSize) elif c in ('i', 'I', 'f'): - builder.addField(4, c, fieldAlign=4) + builder.add_field(4, c, field_align=4) elif c in ('h', 'H'): - builder.addField(2, c, fieldAlign=2) + builder.add_field(2, c, field_align=2) elif c in ('b', 'B', 'c'): - builder.addField(1, c, fieldAlign=1) + builder.add_field(1, c, field_align=1) elif c >= '0' and c <= '9': if n is None: n = '' n += c elif c == 's': - builder.addField(int(n), fieldAlign=1) + builder.add_field(int(n), field_align=1) n = None elif c == '{': readingTypeName = True - typeName = '' + typename = '' elif c == '@': if n is None: # Automatic padding depending on next item builder.autoPadNext = True else: # Explicit padding. - builder.currentBitsize = 8 * ((builder.currentBitsize + 7) >> 3) - padding = (int(n) - (builder.currentBitsize >> 3)) % int(n) + padding = (int(n) - builder.current_size) % int(n) field = self.Field(self) builder.pattern += '%ds' % padding - builder.currentBitsize += padding * 8 + builder.current_size += padding builder.fields.append(field) n = None else: raise RuntimeError('UNKNOWN STRUCT CODE: %s' % c) pp = builder.pattern - size = (builder.currentBitsize + 7) >> 3 + size = builder.current_size fields = builder.fields tailPad = (builder.maxAlign - size) % builder.maxAlign size += tailPad - self.structPatternCache[pattern] = (pp, size, fields) + #self.warn("FIELDS: %s" % ((pp, size, fields),)) return (pp, size, fields) + + def type_stringify(self, typeid): + return 'Type(id="%s",name="%s",bsize=%s,code=%s)'% ( + str(typeid), + self.type_name_cache.get(typeid, '?'), + self.type_bitsize_cache.get(typeid, '?'), + self.type_code_cache.get(typeid, '?')) + + def type_name(self, typeid): + name = self.type_name_cache.get(typeid, None) + if name is None: + self.dump_type_cache() + self.check_typeid(typeid) + raise RuntimeError('UNNAMED TYPE: %d' % typeid) + return name + + def type_code(self, typeid): + # This does not seem to be needed for GDB and LLDB + if not typeid in self.type_code_cache: + typename = self.type_name_cache.get(typeid, None) + if typename is None: + raise RuntimeError('NAME/ID ERROR FOR %s' % typeid) + #self.warn("EMERGENCY LOOKUP: %s " % typename) + typeobj = self.lookupType(typename) + if typeobj is None: + #self.warn("EMERGENCY LOOKUP FAILED: %s " % typeid) + #self.dump_type_cache() + return TypeCode.Struct + #self.warn("EMERGENCY LOOKUP SUCCEEDED: %s " % typeid) + typeid = typeobj.typeid + return self.type_code_cache[typeid] + + def type_bitpos(self, typeid): + return self.type_bitpos_cache[typeid] + + def type_target(self, typeid): + return self.type_target_cache.get(typeid, None) + targetid = self.type_target_cache.get(typeid, None) + if not targetid in self.type_code_cache: + typename = self.type_name_cache.get(targetid, None) + if typename is None: + raise RuntimeError('NAME/ID ERROR FOR TARGET %s' % targetid) + typeobj = self.lookupType(typename) + if typeobj is None: + #self.warn("EMERGENCY LOOKUP FAILED FOR %s %s " % (typename, typeid)) + #self.dump_type_cache() + return 0 # Void type id + return targetid + + def type_template_arguments(self, typeid): + targs = [] + #self.dump_type_cache() + #self.warn('TRY TEMPLATE ARGS FOR %s' % typeid) + for index in range(0, 100): + targ = self.type_template_argument(typeid, index) + #self.warn('INDEX %s %s' % (index, targ)) + if targ is None: + break + targs.append(targ) + #self.warn('TARGS %s' % targs) + return targs + + def nativeTemplateParameter(self, typeid, index, nativeType): + return None + + def type_template_argument(self, typeid, index): + targ = self.type_template_arguments_cache.get((typeid, index), None) + if targ is not None: + return targ + + native_type = self.type_nativetype_cache.get(typeid, None) + if native_type is not None: + targ = self.nativeTemplateParameter(typeid, index, native_type) + if targ is not None: + self.type_template_arguments_cache[(typeid, index)] = targ + return targ + + # FIXME: The block below is apparently not needed anymore in the GDB + # and LLDB cases, so removing also doesn't bring performance. But it + # is at least potentially one source of type lookups. + #typename = self.type_name(typeid) + #self.dump_type_cache() + #self.warn('TEMPLATE ARGS FOR %s %s' % (typeid, typename)) + #typeobj = self.lookupType(typename) + #if typeobj is not None: + # #self.warn(' FOUNT NATIVE %s %s, %s' % (typeid, typeobj, native_type)) + # native_type = self.type_nativetype_cache.get(typeobj.typeid, None) + # #targ = self.type_template_argument(typeobj.typeid, index) + # targ = self.nativeTemplateParameter(typeobj.typeid, index, native_type) + # if targ is not None: + # self.type_template_arguments_cache[(typeid, index)] = targ + # return targ + + # Native lookups didn't help. Happens for 'wrong' placement of 'const' + # etc. with LLDB or template parameter packs with gcc in boost::variant + # 13.2.0. But not all is lost: + self.fill_template_parameters_manually(typeid) + targ = self.type_template_arguments_cache.get((typeid, index), None) + return targ + + def type_alignment(self, typeid): + alignment = self.type_alignment_cache.get(typeid, None) + if alignment is not None: + return alignment + + code = self.type_code_cache.get(typeid, None) + if code in (TypeCode.Typedef, TypeCode.Array): + alignment = self.type_alignment(self.type_target_cache[typeid]) + elif code in (TypeCode.Integral, TypeCode.Float, TypeCode.Enum): + name = self.type_name(typeid) + if name in ('double', 'long long', 'unsigned long long'): + # Crude approximation. + alignment = 8 if self.isWindowsTarget() else self.ptrSize() + else: + alignment = self.type_size(typeid) + elif code in (TypeCode.Pointer, TypeCode.Reference, TypeCode.RValueReference): + alignment = self.ptrSize() + elif self.isCdb: + alignment = self.nativeStructAlignment(self.type_nativetype(typeid)) + else: + size = self.type_size(typeid) + if size is None: + self.dump_type_cache() + self.warn("NO ALIGNMENT FOUND FOR SIZE OF TYPE %s" % str(typeid)) + return 1 + if size >= self.ptrSize(): + alignment = self.ptrSize() + else: + alignment = size + #self.warn("GUESSING ALIGNMENT %s FOR TYPEID %s" % (alignment, typeid)) + self.type_alignment_cache[typeid] = alignment + return alignment + + + def type_nativetype(self, typeid): + native_type = self.type_nativetype_cache.get(typeid, None) + if native_type is not None: + return native_type + + typename = self.type_name(typeid) + native_type = self.lookupNativeType(typename) + # Also cache unsuccessful attempts + self.type_nativetype_cache[typeid] = native_type + + return native_type + + + def type_size(self, typeid): + self.check_typeid(typeid) + size = self.type_size_cache.get(typeid, None) + if size is not None: + return size + + nativeType = self.type_nativetype(typeid) + if self.isCdb: + size = nativeType.bitsize() // 8 + else: + if not self.type_size_cache.get(typeid): + self.from_native_type(nativeType) + size = self.type_size_cache.get(typeid, None) + + if size is not None: + self.type_size_cache[typeid] = size + else: + self.dump_type_cache() + self.warn("CANNOT DETERMINE SIZE FOR TYPE %s" % str(typeid)) + + return size + + def type_bitsize(self, typeid): + bitsize = self.type_bitsize_cache.get(typeid, None) + if bitsize is None: + bitsize = 8 * self.type_size(typeid) + self.type_bitsize_cache[typeid] = bitsize + return bitsize + + def dynamic_typeid_at_address(self, base_typeid, address): + #with self.dumper.timer('dynamic_typeid_at_address %s 0x%s' % (self.name, address)): + type_code = self.type_code_cache.get(base_typeid, None) + if type_code != TypeCode.Struct: + #self.dump_type_cache() + #self.warn('SHORT CUT FOR BASE ID: %d TC: %s' % (base_typeid, type_code)) + return base_typeid + + # This turned out to be expensive. + #try: + # vtbl = self.extract_pointer_at_address(address) + #except: + # return base_typeid + ##self.warn('VTBL: 0x%x' % vtbl) + #if not self.couldBePointer(vtbl): + # return base_typeid + #self.warn("DYN TYPE FOR %s %s" % (base_typeid, self.type_name(base_typeid))) + + return self.nativeDynamicType(address, base_typeid) + + # This is the generic version for synthetic values. + # The native backends replace it in their fromNativeValue() + # implementations. + def value_members(self, value, include_bases): + #self.warn("LISTING MEMBERS OF %s" % value) + #self.warn("LISTING MEMBERS OF TYPE %s %s" % (value.typeid, self.type_name(value.typeid))) + typeid = value.typeid + + members = self.type_fields_cache.get(typeid, None) + if members is not None: + return members + + members = [] + native_type = self.type_nativetype_cache.get(typeid, None) + if native_type is None: + native_type = self.lookupNativeType(self.type_name(typeid)) + if not native_type is None: + members = self.nativeListMembers(value, native_type, include_bases) + #self.warn("FIELDS 2: %s" % ', '.join(str(f) for f in members)) + else: + self.warn("NO NATIVE TYPE FIELDS FOR: %s" % typeid) + + #self.warn("GOT MEMBERS: %s" % ', '.join(str(f.name) for f in members)) + return members + + def value_member_by_field(self, value, field): + #self.warn("EXTRACTING MEMBER '%s' OF %s AT OFFSET %s" % (field.name, field.typeid, field.bitpos)) + val = self.Value(self) + val.typeid = field.typeid + val.name = field.name + val.isBaseClass = field.is_base_class + #self.warn('CREATING %s WITH DATA %s' % (val.type.name, self.hexencode(data))) + field_offset = field.bitpos // 8 + if value.laddress is not None: + val.laddress = value.laddress + field_offset + field_size = (field.bitsize + 7) // 8 + blob = self.value_data(value, field_offset + field_size) + val.ldata = blob[field_offset:field_offset + field_size] + #self.dump_location() + return val + + def value_member_by_name(self, value, name): + #field = self.type_fields_cache.get((value.typeid, name), None) + #if field is not None: + # return self.value_member_by_field(value, field) + + #self.dump_location() + #self.warn("WANT MEMBER '%s' OF '%s'" % (name, value)) + #value.check() + value_typecode = self.type_code(value.typeid) + if value_typecode == TypeCode.Typedef: + return self.value_member_by_name(self.value_detypedef(value), name) + if value_typecode in (TypeCode.Pointer, TypeCode.Reference, TypeCode.RValueReference): + res = self.value_member_by_name(self.value_dereference(value), name) + if res is not None: + return res + if value_typecode == TypeCode.Struct: + #self.warn('SEARCHING FOR MEMBER: %s IN %s' % (name, value.type.name)) + members = self.value_members(value, True) + #self.warn('MEMBERS: %s' % ', '.join(str(m.name) for m in members)) + base = None + for member in members: + #self.warn('CHECKING FIELD %s' % member.name) + if member.type.code == TypeCode.Typedef: + member = member.detypedef() + if member.name == name: + #self.warn('FOUND MEMBER 1: %s IN %s' % (name, value.type.name)) + return member + if member.isBaseClass: + base = member + if self.isCdb: + if base is not None: + # self.warn("CHECKING BASE CLASS '%s' for '%s'" % (base.type.name, name)) + res = self.value_member_by_name(base, name) + if res is not None: + # self.warn('FOUND MEMBER 2: %s IN %s' % (name, value.type.name)) + return res + else: + for member in members: + if member.type.code == TypeCode.Typedef: + member = member.detypedef() + if member.name == name: # Could be base class. + return member + if member.type.code == TypeCode.Struct: + res = self.value_member_by_name(member, name) + if res is not None: + #self.warn('FOUND MEMBER 2: %s IN %s' % (name, value.type.name)) + return res + + #self.warn('DID NOT FIND MEMBER: %s IN %s' % (name, value.type.name)) + #self.dump_location() + return None + + def value_member_by_indexish(self, value, indexish): + #self.warn('GET ITEM %s %s' % (self, indexish)) + #value.check() + value_typecode = self.type_code(value.typeid) + if isinstance(indexish, str): + if value_typecode == TypeCode.Pointer: + #self.warn('GET ITEM %s DEREFERENCE TO %s' % (value, value.dereference())) + return value.dereference().__getitem__(indexish) + res = self.value_member_by_name(value, indexish) + if res is None: + raise RuntimeError('No member named %s in type %s' + % (indexish, value.type.name)) + return res + if isinstance(indexish, int): + if value_typecode == TypeCode.Array: + addr = value.laddress + int(indexish) * value.type.target().size() + return self.createValueFromAddress(addr, value.type.target()) + if value_typecode == TypeCode.Pointer: + addr = value.pointer() + int(indexish) * value.type.target().size() + return self.createValueFromAddress(addr, value.type.target()) + return self.value_members(value, False)[indexish] + raise RuntimeError('BAD INDEX TYPE %s' % type(indexish)) + + def value_extract_bits(self, value, bitpos, bitsize): + value_size = self.type_size(value.typeid) + ldata = bytes(self.value_data(value, value_size)) + bdata = ''.join([format(x, '0>8b')[::-1] for x in ldata]) + fdata = bdata[bitpos : bitpos + bitsize] + fdata = fdata[::-1] + return int(fdata, 2) + + def value_display_enum(self, value, form='%d', bitsize=None): + size = value.type.size() + intval = self.value_extract_integer(value, size, False) + dd = self.type_enum_display_cache.get(value.typeid, None) + if dd is None: + return str(intval) + return dd(intval, value.laddress, form) + + def value_as_address(self, value): + return self.value_extract_integer(value, self.ptrSize(), False) + + def value_as_integer(self, value): + if isinstance(value.ldata, int): + return value.ldata + type_name = self.type_name(value.typeid) + signed = type_name != 'unsigned' \ + and not type_name.startswith('unsigned ') \ + and type_name.find(' unsigned ') == -1 + size = value.type.size() + return self.value_extract_integer(value, size, signed) + + def value_as_floating_point(self, value): + if value.nativeValue is not None and not self.isCdb: + return str(value.nativeValue) + if self.type_code(value.typeid) == TypeCode.Typedef: + return self.value_as_floating_point(self.value_detypedef(value)) + if value.type.size() == 8: + blob = self.value_data(value, 8) + return struct.unpack_from(self.packCode + 'd', blob, 0)[0] + if value.type.size() == 4: + blob = self.value_data(value, 4) + return struct.unpack_from(self.packCode + 'f', blob, 0)[0] + # Fall back in case we don't have a nativeValue at hand. + # FIXME: This assumes Intel's 80bit extended floats. Which might + # be wrong. + l, h = value.split('QQ') + if True: # 80 bit floats + sign = (h >> 15) & 1 + exp = (h & 0x7fff) + fraction = l + bit63 = (l >> 63) & 1 + #self.warn("SIGN: %s EXP: %s H: 0x%x L: 0x%x" % (sign, exp, h, l)) + if exp == 0: + if bit63 == 0: + if l == 0: + res = '-0' if sign else '0' + else: + res = (-1)**sign * l * 2**(-16382) # subnormal + else: + res = 'pseudodenormal' + elif exp == 0x7fff: + res = 'special' + else: + res = (-1)**sign * l * 2**(exp - 16383 - 63) + else: # 128 bits + sign = h >> 63 + exp = (h >> 48) & 0x7fff + fraction = h & (2**48 - 1) + #self.warn("SIGN: %s EXP: %s FRAC: %s H: 0x%x L: 0x%x" % (sign, exp, fraction, h, l)) + if exp == 0: + if fraction == 0: + res = -0.0 if sign else 0.0 + else: + res = (-1)**sign * fraction / 2**48 * 2**(-62) # subnormal + elif exp == 0x7fff: + res = ('-inf' if sign else 'inf') if fraction == 0 else 'nan' + else: + res = (-1)**sign * (1 + fraction / 2**48) * 2**(exp - 63) + return res + + def value_data(self, value, size): + if value.ldata is not None: + return value.ldata[:size] + if value.laddress is not None: + return self.value_data_from_address(value.laddress, size) + raise RuntimeError('CANNOT CONVERT TO BYTES: %s' % value) + + def value_data_from_address(self, address, size): + if not isinstance(address, int): + raise RuntimeError('ADDRESS WRONG TYPE: %s' % type(address)) + if not isinstance(size, int): + raise RuntimeError('SIZE WRONG TYPE: %s' % type(size)) + if size <= 0: + raise RuntimeError('SIZE WRONG VALUE: %s' % size) + res = self.readRawMemory(address, size) + if len(res) > 0: + return res + raise RuntimeError('CANNOT READ %d BYTES FROM ADDRESS: %s' % (size, address)) + + def value_display(self, value): + type_code = self.type_code(value.typeid) + if type_code == TypeCode.Enum: + return self.value_display_enum(value) + if type_code == TypeCode.Typedef: + return self.value_display(self.value_detypedef(value)) + if type_code == TypeCode.Integral: + return self.value_as_integer(value) + if type_code == TypeCode.Bitfield: + return self.value_as_integer(value) + if type_code == TypeCode.Float: + return self.value_as_floating_point(value) + if type_code == TypeCode.Pointer: + return self.value_as_address(value) + return None + + def value_detypedef(self, value): + #value.check() + #if value.type.code != TypeCode.Typedef: + # raise RuntimeError("WRONG") + val = value.copy() + val.typeid = self.type_target(value.typeid) + #self.warn("DETYPEDEF FROM: %s" % self) + #self.warn("DETYPEDEF TO: %s" % val) + return val + + def split(self, pattern, value_or_address): + if isinstance(value_or_address, self.Value): + return self.value_split(value_or_address, pattern) + if isinstance(value_or_address, int): + val = self.Value(self) + val.laddress = value_or_address + return self.value_split(val, pattern) + raise RuntimeError('CANNOT EXTRACT STRUCT FROM %s' % type(value_or_address)) + + def value_split(self, value, pattern): + #self.warn('EXTRACT STRUCT FROM: %s' % self.type) + (pp, size, fields) = self.describeStruct(pattern) + #self.warn('SIZE: %s ' % size) + + blob = self.value_data(value, size) + address = value.laddress + + parts = struct.unpack_from(self.packCode + pp, blob) + + def fix_struct(field, part): + #self.warn('STRUCT MEMBER: %s' % type(part)) + if field.is_struct: + res = self.Value(self) + res.typeid = field.typeid + res.ldata = part + if address is not None: + res.laddress = address + field.bitpos // 8 + return res + return part + + if len(fields) != len(parts): + raise RuntimeError('STRUCT ERROR: %s %s' % (fields, parts)) + return tuple(map(fix_struct, fields, parts)) + + def type_dereference(self, typeid): + if self.type_code(typeid) == TypeCode.Typedef: + return self.type_dereference(self.type_target(typeid)) + return self.type_target(typeid) + + def type_strip_typedefs(self, typeid): + if self.type_code(typeid) == TypeCode.Typedef: + return self.type_strip_typedefs(self.type_target(typeid)) + return typeid + + def value_dereference(self, value): + value.check() + #if value.type.code == TypeCode.Typedef: + # return self.value_dereference(self.value_detypedef(value)) + val = self.Value(self) + if value.type.code in (TypeCode.Reference, TypeCode.RValueReference): + val.summary = value.summary + if value.nativeValue is None: + val.laddress = value.pointer() + if val.laddress is None and value.laddress is not None: + val.laddress = value.laddress + val.typeid = self.type_dereference(value.typeid) + if self.useDynamicType: + val.typeid = self.nativeDynamicType(val.laddress, val.typeid) + else: + val = self.nativeValueDereferenceReference(value) + elif value.type.code == TypeCode.Pointer: + try: + val = self.nativeValueDereferencePointer(value) + except: + val.laddress = value.pointer() + val.typeid = self.type_dereference(value.typeid) + if self.useDynamicType: + val.typeid = self.nativeDynamicType(val.laddress, val.typeid) + else: + raise RuntimeError("WRONG: %s" % value.type.code) + + return val + + def value_cast(self, value, typish): + value.check() + val = self.Value(self) + val.laddress = value.laddress + val.ldata = value.ldata + val.typeid = self.create_typeid(typish) + return val + + def value_plus_something(self, value, other): + value.check() + if isinstance(other, int): + stripped = self.type_strip_typedefs(value.typeid) + if self.type_code(stripped) == TypeCode.Pointer: + item_size = self.type_size(self.type_dereference(stripped)) + address = self.value_as_address(value) + item_size * other + val = self.Value(self) + val.laddress = None + val.ldata = address + val.typeid = value.typeid + return val + raise RuntimeError('BAD DATA TO ADD TO: %s %s' % (value.type, other)) + + def value_minus_something(self, value, other): + value.check() + if other.type.name == value.type.name: + stripped = self.type_strip_typedefs(value.typeid) + if self.type_code(stripped.code) == TypeCode.Pointer: + item_size = self.type_size(self.type_dereference(stripped)) + return (value.pointer() - other.pointer()) // item_size + raise RuntimeError('BAD DATA TO SUB TO: %s %s' % (value.type, other)) + diff --git a/share/qtcreator/debugger/gdbbridge.py b/share/qtcreator/debugger/gdbbridge.py index d61160eed3b..ee25520bced 100644 --- a/share/qtcreator/debugger/gdbbridge.py +++ b/share/qtcreator/debugger/gdbbridge.py @@ -10,11 +10,10 @@ import gdb import os import os.path import re -import sys import struct import tempfile -from dumper import DumperBase, Children, toInteger, TopLevelItem +from dumper import DumperBase, Children, TopLevelItem from utils import TypeCode from gdbtracepoint import * @@ -119,7 +118,6 @@ ScanStackCommand() class PlainDumper(): def __init__(self, printer): self.printer = printer - self.typeCache = {} def __call__(self, d, value): if value.nativeValue is None: @@ -137,8 +135,6 @@ class PlainDumper(): if isinstance(val, str): # encode and avoid extra quotes ('"') at beginning and end d.putValue(d.hexencode(val), 'utf8:1:0') - elif sys.version_info[0] <= 2 and isinstance(val, unicode): - d.putValue(val) elif val is not None: # Assuming LazyString d.putCharArrayValue(val.address, val.length, val.type.target().sizeof) @@ -166,7 +162,7 @@ def importPlainDumpers(args): gdb.execute('disable pretty-printer .* .*') except: # Might occur in non-ASCII directories - DumperBase.warn('COULD NOT DISABLE PRETTY PRINTERS') + theDumper.warn('COULD NOT DISABLE PRETTY PRINTERS') else: theDumper.usePlainDumpers = True theDumper.importPlainDumpers() @@ -192,15 +188,17 @@ class Dumper(DumperBase): # These values will be kept between calls to 'fetchVariables'. self.isGdb = True - self.typeCache = {} self.interpreterBreakpointResolvers = [] + def warn(self, message): + print('bridgemessage={msg="%s"},' % message.replace('"', '$').encode('latin1')) + def prepare(self, args): self.output = [] self.setVariableFetchingOptions(args) def fromFrameValue(self, nativeValue): - #DumperBase.warn('FROM FRAME VALUE: %s' % nativeValue.address) + #self.warn('FROM FRAME VALUE: %s' % nativeValue.address) val = nativeValue if self.useDynamicType: try: @@ -209,71 +207,43 @@ class Dumper(DumperBase): pass return self.fromNativeValue(val) - def nativeValueType(self, nativeValue): - return self.fromNativeType(nativeValue.type) - def fromNativeValue(self, nativeValue): - #DumperBase.warn('FROM NATIVE VALUE: %s' % nativeValue) + #self.warn('FROM NATIVE VALUE: %s' % nativeValue) self.check(isinstance(nativeValue, gdb.Value)) nativeType = nativeValue.type code = nativeType.code - if code == gdb.TYPE_CODE_REF: - targetType = self.fromNativeType(nativeType.target().unqualified()) - val = self.createReferenceValue(toInteger(nativeValue.address), targetType) - val.nativeValue = nativeValue - #DumperBase.warn('CREATED REF: %s' % val) - return val - if code == gdb.TYPE_CODE_PTR: - try: - nativeTargetValue = nativeValue.dereference() - except: - nativeTargetValue = None - targetType = self.fromNativeType(nativeType.target().unqualified()) - val = self.createPointerValue(toInteger(nativeValue), targetType) - # The nativeValue is needed in case of multiple inheritance, see - # QTCREATORBUG-17823. Using it triggers nativeValueDereferencePointer() - # later which - # is surprisingly expensive. - val.nativeValue = nativeValue - #DumperBase.warn('CREATED PTR 1: %s' % val) - if nativeValue.address is not None: - val.laddress = toInteger(nativeValue.address) - #DumperBase.warn('CREATED PTR 2: %s' % val) - return val - if code == gdb.TYPE_CODE_TYPEDEF: - targetType = nativeType.strip_typedefs().unqualified() - #DumperBase.warn('TARGET TYPE: %s' % targetType) - if targetType.code == gdb.TYPE_CODE_ARRAY: - val = self.Value(self) - else: - try: - # Cast may fail for arrays, for typedefs to __uint128_t with - # gdb.error: That operation is not available on integers - # of more than 8 bytes. - # See test for Bug5799, QTCREATORBUG-18450. - val = self.fromNativeValue(nativeValue.cast(targetType)) - except: - val = self.Value(self) - #DumperBase.warn('CREATED TYPEDEF: %s' % val) - else: - val = self.Value(self) + val = self.Value(self) val.nativeValue = nativeValue - if nativeValue.address is not None: - val.laddress = toInteger(nativeValue.address) - else: - size = nativeType.sizeof - chars = self.lookupNativeType('unsigned char') - y = nativeValue.cast(chars.array(0, int(nativeType.sizeof - 1))) - buf = bytearray(struct.pack('x' * size)) - for i in range(size): - try: - buf[i] = int(y[i]) - except: - pass - val.ldata = bytes(buf) - val._type = self.fromNativeType(nativeType) + if code == gdb.TYPE_CODE_REF: + target_typeid = self.from_native_type(nativeType.target().unqualified()) + val.ldata = int(nativeValue.address) + if self.useDynamicType: # needed for Gdb13393 + target_typeid = self.dynamic_typeid_at_address(target_typeid, val.ldata) + val.typeid = self.create_reference_typeid(target_typeid) + #self.warn('CREATED REF: %s' % val) + return val + + if code == gdb.TYPE_CODE_PTR: + target_typeid = self.from_native_type(nativeType.target().unqualified()) + val.ldata = int(nativeValue) + val.typeid = self.create_pointer_typeid(target_typeid) + #self.warn('CREATED PTR 1: %s' % val) + if nativeValue.address is not None: + val.laddress = int(nativeValue.address) + #self.warn('CREATED PTR 2: %s' % val) + return val + + if nativeValue.address is not None: + val.laddress = int(nativeValue.address) + elif code == gdb.TYPE_CODE_STRUCT: + try: + val.ldata = nativeValue.bytes # GDB 15 only + except: + val.ldata = self.nativeDataFromValueFallback(nativeValue, nativeValue.type.sizeof) + + val.typeid = self.from_native_type(nativeType) val.lIsInScope = not nativeValue.is_optimized_out code = nativeType.code if code == gdb.TYPE_CODE_ENUM: @@ -283,76 +253,103 @@ class Dumper(DumperBase): val.ldisplay += ' (%s)' % intval elif code == gdb.TYPE_CODE_COMPLEX: val.ldisplay = str(nativeValue) - elif code in [gdb.TYPE_CODE_BOOL, gdb.TYPE_CODE_INT]: + elif code == gdb.TYPE_CODE_BOOL: + # FIXME: why? + # Using ldata breaks StdVariant test, not setting lvalue breaks the Bitfield[s2] test. + val.lvalue = int(nativeValue) + val.ldata = None + elif code == gdb.TYPE_CODE_INT: try: # extract int presentation from native value and remember it - val.lvalue = int(nativeValue) + val.ldata = int(nativeValue) except: # GDB only support converting integers of max. 64 bits to Python int as of now pass + elif code == gdb.TYPE_CODE_TYPEDEF: + targetType = nativeType.strip_typedefs().unqualified() + if targetType.code in [gdb.TYPE_CODE_BOOL, gdb.TYPE_CODE_INT]: + typeid = val.typeid + val = self.fromNativeValue(nativeValue.cast(targetType)) + val.typeid = typeid #elif code == gdb.TYPE_CODE_ARRAY: # val.type.ltarget = nativeValue[0].type.unqualified() return val + def nativeDataFromValueFallback(self, nativeValue, size): + chars = self.lookupNativeType('unsigned char') + try: + y = nativeValue.cast(chars.array(0, int(size - 1))) + buf = bytearray(struct.pack('x' * size)) + for i in range(size): + try: + buf[i] = int(y[i]) + except: + pass + return bytes(buf) + except: + self.warn('VALUE EXTRACTION FAILED: VALUE: %s SIZE: %s' % (nativeValue, size)) + return None + def ptrSize(self): result = gdb.lookup_type('void').pointer().sizeof self.ptrSize = lambda: result return result - def fromNativeType(self, nativeType): + def from_native_type(self, nativeType): self.check(isinstance(nativeType, gdb.Type)) - code = nativeType.code - #DumperBase.warn('FROM NATIVE TYPE: %s' % nativeType) + + #self.warn('FROM NATIVE TYPE: %s' % nativeType) nativeType = nativeType.unqualified() + typeid_str = self.native_type_key(nativeType) + known_typeid = self.typeid_from_typekey.get(typeid_str, None) + if known_typeid is not None: + return known_typeid + + code = nativeType.code + if code == gdb.TYPE_CODE_PTR: - #DumperBase.warn('PTR') - targetType = self.fromNativeType(nativeType.target().unqualified()) - return self.createPointerType(targetType) + #self.warn('PTR') + target_typeid = self.from_native_type(nativeType.target().unqualified()) + typeid = self.create_pointer_typeid(target_typeid) - if code == gdb.TYPE_CODE_REF: - #DumperBase.warn('REF') - targetType = self.fromNativeType(nativeType.target().unqualified()) - return self.createReferenceType(targetType) + elif code == gdb.TYPE_CODE_REF: + #self.warn('REF') + target_typeid = self.from_native_type(nativeType.target().unqualified()) + typeid = self.create_reference_typeid(target_typeid) - if hasattr(gdb, "TYPE_CODE_RVALUE_REF"): - if code == gdb.TYPE_CODE_RVALUE_REF: - #DumperBase.warn('RVALUEREF') - targetType = self.fromNativeType(nativeType.target()) - return self.createRValueReferenceType(targetType) + elif code == gdb.TYPE_CODE_RVALUE_REF and hasattr(gdb, "TYPE_CODE_RVALUE_REF"): + #self.warn('RVALUEREF') + target_typeid = self.from_native_type(nativeType.target()) + typeid = self.create_rvalue_reference_typeid(target_typeid) - if code == gdb.TYPE_CODE_ARRAY: - #DumperBase.warn('ARRAY') + elif code == gdb.TYPE_CODE_ARRAY: + #self.warn('ARRAY') nativeTargetType = nativeType.target().unqualified() - targetType = self.fromNativeType(nativeTargetType) + target_typeid = self.from_native_type(nativeTargetType) if nativeType.sizeof == 0: # QTCREATORBUG-23998, note that nativeType.name == None here, # whereas str(nativeType) returns sth like 'QObject [5]' count = self.arrayItemCountFromTypeName(str(nativeType), 1) else: count = nativeType.sizeof // nativeTargetType.sizeof - return self.createArrayType(targetType, count) + typeid = self.create_array_typeid(target_typeid, count) - if code == gdb.TYPE_CODE_TYPEDEF: - #DumperBase.warn('TYPEDEF') + elif code == gdb.TYPE_CODE_TYPEDEF: + #self.warn('TYPEDEF') nativeTargetType = nativeType.unqualified() while nativeTargetType.code == gdb.TYPE_CODE_TYPEDEF: nativeTargetType = nativeTargetType.strip_typedefs().unqualified() - targetType = self.fromNativeType(nativeTargetType) - return self.createTypedefedType(targetType, str(nativeType), - self.nativeTypeId(nativeType)) + target_typeid = self.from_native_type(nativeTargetType) + typeid = self.create_typedefed_typeid(target_typeid, str(nativeType), typeid_str) - if code == gdb.TYPE_CODE_ERROR: + elif code == gdb.TYPE_CODE_ERROR: self.warn('Type error: %s' % nativeType) - return self.Type(self, '') + typeid = 0 # the invalid id - typeId = self.nativeTypeId(nativeType) - res = self.typeData.get(typeId, None) - if res is None: - tdata = self.TypeData(self, typeId) - tdata.name = str(nativeType) - tdata.lbitsize = nativeType.sizeof * 8 - tdata.code = { + else: + typeid = self.typeid_for_string(typeid_str) + type_code = { #gdb.TYPE_CODE_TYPEDEF : TypeCode.Typedef, # Handled above. gdb.TYPE_CODE_METHOD: TypeCode.Function, gdb.TYPE_CODE_VOID: TypeCode.Void, @@ -372,38 +369,82 @@ class Dumper(DumperBase): gdb.TYPE_CODE_COMPLEX: TypeCode.Complex, gdb.TYPE_CODE_STRING: TypeCode.FortranString, }[code] - if tdata.code == TypeCode.Enum: - tdata.enumDisplay = lambda intval, addr, form: \ - self.nativeTypeEnumDisplay(nativeType, intval, form) - if tdata.code == TypeCode.Struct: - tdata.lalignment = lambda: \ - self.nativeStructAlignment(nativeType) - tdata.lfields = lambda value: \ - self.listMembers(value, nativeType) - tdata.templateArguments = lambda: \ - self.listTemplateParameters(nativeType) - # warn('CREATE TYPE: %s' % typeId) - #else: - # warn('REUSE TYPE: %s' % typeId) - return self.Type(self, typeId) + self.type_name_cache[typeid] = str(nativeType) + self.type_size_cache[typeid] = nativeType.sizeof + self.type_code_cache[typeid] = type_code + self.type_nativetype_cache[typeid] = nativeType - def listTemplateParameters(self, nativeType): - targs = [] - pos = 0 - while True: - try: - targ = nativeType.template_argument(pos) - except: - break - if isinstance(targ, gdb.Type): - targs.append(self.fromNativeType(targ.unqualified())) - elif isinstance(targ, gdb.Value): - targs.append(self.fromNativeValue(targ).value()) - else: - raise RuntimeError('UNKNOWN TEMPLATE PARAMETER') - pos += 1 - targs2 = self.listTemplateParametersManually(str(nativeType)) - return targs if len(targs) >= len(targs2) else targs2 + if type_code == TypeCode.Enum: + self.type_enum_display_cache[typeid] = lambda intval, addr, form: \ + self.nativeTypeEnumDisplay(nativeType, intval, form) + + self.type_nativetype_cache[typeid] = nativeType + + if code == gdb.TYPE_CODE_STRUCT: + self.type_qobject_based_cache[typeid] = self.is_qobject_based(nativeType) + #res = self.is_qobject_based(nativeType) + #if res == False: + # self.warn("RECOGNIZED AS NON-QOBJECT: %s" % nativeType) + #elif res == True: + # self.warn("RECOGNIZED AS QOBJECT: %s" % nativeType) + #else: + # self.warn("UNRECOGNIZED: %s" % nativeType) + elif code != gdb.TYPE_CODE_TYPEDEF: + self.type_qobject_based_cache[typeid] = False + +# FIXME: Field offset caching (or later extraction?) broken +# if code == gdb.TYPE_CODE_STRUCT: +# field_type_name = self.type_name_cache.get(typeid, '') +# #self.warn("CACHING FIELDS OF %s '%s'" % (typeid, field_type_name)) +# try: +# fields = nativeType.fields() +# #self.warn("FOUND FIELDS %s" % fields) +# except: +# #self.warn("NO FIELDS IN %s '%s'" % (typeid, field_type_name)) +# fields = [] +# for nativeField in fields: +# field_name = nativeField.name +# if field_name.startswith('std::allocator'): +# continue +# field_bitpos = nativeField.bitpos +# field_typeid = self.typeid_for_string(str(nativeType)) +# field_size = nativeField.type.sizeof +# #self.warn("CACHING '%s' OF %s AT BITPOS %s SIZE %s" % +# # (field_name, typeid, field_bitpos, field_size)) +# self.type_fields_cache[(typeid, field_name)] = self.Field( +# name=field_name, +# typeid=field_typeid, +# bitpos=field_bitpos, +# bitsize=field_size * 8 +# ) +# pass + + + #self.warn("FROM NATIVE TYPE: %s %s %s" % (typeid, id(nativeType), nativeType)) + self.typeid_from_typekey[str(nativeType)] = typeid + + return typeid + + def is_qobject_based(self, nativeType): + if str(nativeType) == self.qtNamespace() + 'QObject': + return True + fields = nativeType.fields() + if len(fields) == 0: + return None # No info, can't drill deeper + if not fields[0].is_base_class: + return False + return self.is_qobject_based(fields[0].type) + + def nativeTemplateParameter(self, typeid, index, nativeType): + try: + targ = nativeType.template_argument(index) + except: + return None + if isinstance(targ, gdb.Type): + return self.Type(self, self.from_native_type(targ.unqualified())) + if isinstance(targ, gdb.Value): + return self.fromNativeValue(targ).value() + raise RuntimeError('UNKNOWN TEMPLATE PARAMETER') def nativeTypeEnumDisplay(self, nativeType, intval, form): try: @@ -432,7 +473,7 @@ class Dumper(DumperBase): pass return form % intval - def nativeTypeId(self, nativeType): + def native_type_key(self, nativeType): if nativeType and (nativeType.code == gdb.TYPE_CODE_TYPEDEF): return '%s{%s}' % (nativeType, nativeType.strip_typedefs()) name = str(nativeType) @@ -444,133 +485,106 @@ class Dumper(DumperBase): c = 's' else: return name - typeId = c + ''.join(['{%s:%s}' % (f.name, self.nativeTypeId(f.type)) - for f in nativeType.fields()]) - return typeId + id_str = c + ''.join(['{%s:%s}' % + (f.name, self.typeid_for_string(self.native_type_key(f.type))) + for f in nativeType.fields()]) + #self.warn("NATIVE TYPE KEY: %s" % id_str) + return id_str - def nativeStructAlignment(self, nativeType): - #DumperBase.warn('NATIVE ALIGN FOR %s' % nativeType.name) - def handleItem(nativeFieldType, align): - a = self.fromNativeType(nativeFieldType).alignment() - return a if a > align else align - align = 1 - for f in nativeType.fields(): - align = handleItem(f.type, align) - return align - - #except: - # # Happens in the BoostList dumper for a 'const bool' - # # item named 'constant_time_size'. There isn't anything we can do - # # in this case. - # pass - - #yield value.extractField(field) - - def memberFromNativeFieldAndValue(self, nativeField, nativeValue, fieldName, value): - nativeMember = self.nativeMemberFromField(nativeValue, nativeField) - if nativeMember is None: - val = self.Value(self) - val.name = fieldName - val._type = self.fromNativeType(nativeField.type) - val.lIsInScope = False - return val - val = self.fromNativeValue(nativeMember) - nativeFieldType = nativeField.type.unqualified() - if nativeField.bitsize: - val.lvalue = int(nativeMember) - val.laddress = None - fieldType = self.fromNativeType(nativeFieldType) - val._type = self.createBitfieldType(fieldType, nativeField.bitsize) - val.isBaseClass = nativeField.is_base_class - val.name = fieldName - return val - - def nativeMemberFromField(self, nativeValue, nativeField): - if nativeField.is_base_class: - return nativeValue.cast(nativeField.type) - try: - return nativeValue[nativeField] - except: - pass - try: - return nativeValue[nativeField.name] - except: - pass - return None - - def listMembers(self, value, nativeType): + def nativeListMembers(self, value, nativeType, include_base): nativeValue = value.nativeValue + value_size = self.type_size(value.typeid) + ldata = bytes(self.value_data(value, value_size)) + laddress = value.laddress anonNumber = 0 - #DumperBase.warn('LISTING FIELDS FOR %s' % nativeType) + fields = [] + #self.warn('LISTING FIELDS FOR %s' % nativeType) for nativeField in nativeType.fields(): - fieldName = nativeField.name + if not include_base and nativeField.is_base_class: + continue + + field_name = nativeField.name # Something without a name. # Anonymous union? We need a dummy name to distinguish # multiple anonymous unions in the struct. # Since GDB commit b5b08fb4 anonymous structs get also reported # with a 'None' name. - if fieldName is None or len(fieldName) == 0: - # Something without a name. - # Anonymous union? We need a dummy name to distinguish - # multiple anonymous unions in the struct. + if field_name is None or len(field_name) == 0: anonNumber += 1 - fieldName = '#%s' % anonNumber - #DumperBase.warn('FIELD: %s' % fieldName) + field_name = '#%s' % anonNumber + #self.warn('FIELD: %s' % field_name) + + nativeFieldType = nativeField.type.unqualified() + field_typeid = self.from_native_type(nativeFieldType) + #self.warn(' TYPE: %s' % nativeFieldType) + #self.warn(' TYPE KEY: %s' % self.native_type_key(nativeFieldType)) + + if nativeValue is not None: + try: + native_member = nativeValue[nativeField] + except: + self.warn(' COULD NOT ACCESS FIELD: %s' % nativeFieldType) + continue + + val = self.fromNativeValue(native_member) + if nativeField.bitsize: + val.lvalue = None + val.ldata = int(native_member) + val.laddress = None + val.typeid = self.create_bitfield_typeid(field_typeid, nativeField.bitsize) + val.isBaseClass = nativeField.is_base_class + val.name = field_name + fields.append(val) + continue + # hasattr(nativeField, 'bitpos') == False indicates a static field, - # but if we have access to a nativeValue .fromNativeField will + # but if we have access to a nativeValue, so fromNativeField will # also succeed. We essentially skip only static members from # artificial values, like array members constructed from address. - if hasattr(nativeField, 'bitpos') or nativeValue is not None: - yield self.fromNativeField(nativeField, nativeValue, fieldName) + if not hasattr(nativeField, 'bitpos'): + continue - def fromNativeField(self, nativeField, nativeValue, fieldName): - nativeFieldType = nativeField.type.unqualified() - #DumperBase.warn(' TYPE: %s' % nativeFieldType) - #DumperBase.warn(' TYPEID: %s' % self.nativeTypeId(nativeFieldType)) - - if hasattr(nativeField, 'bitpos'): bitpos = nativeField.bitpos - else: - bitpos = 0 - if hasattr(nativeField, 'bitsize') and nativeField.bitsize != 0: - bitsize = nativeField.bitsize - else: - bitsize = 8 * nativeFieldType.sizeof + if hasattr(nativeField, 'bitsize') and nativeField.bitsize != 0: + bitsize = nativeField.bitsize + else: + bitsize = 8 * nativeFieldType.sizeof - fieldType = self.fromNativeType(nativeFieldType) - if bitsize != nativeFieldType.sizeof * 8: - fieldType = self.createBitfieldType(fieldType, bitsize) - else: - fieldType = fieldType + field_typeid = self.from_native_type(nativeFieldType) + is_bitfield = bitsize != nativeFieldType.sizeof * 8 - if nativeValue is None: - extractor = None - else: - extractor = lambda value, \ - capturedNativeField = nativeField, \ - capturedNativeValue = nativeValue, \ - capturedFieldName = fieldName: \ - self.memberFromNativeFieldAndValue(capturedNativeField, - capturedNativeValue, - capturedFieldName, - value) + val = self.Value(self) + val.name = field_name + val.isBaseClass = nativeField.is_base_class + + if is_bitfield: + val.typeid = self.create_bitfield_typeid(field_typeid, bitsize) + val.ldata = self.value_extract_bits(value, bitpos, bitsize) + else: + val.typeid = field_typeid + field_offset = bitpos // 8 + if laddress is not None: + val.laddress = laddress + field_offset + field_size = (bitsize + 7) // 8 + val.ldata = ldata[field_offset:field_offset + field_size] + + #self.warn('GOT VAL %s FOR FIELD %s' % (val, nativeField)) + fields.append(val) + + return fields - #DumperBase.warn("FOUND NATIVE FIELD: %s bitpos: %s" % (fieldName, bitpos)) - return self.Field(dumper=self, name=fieldName, isBase=nativeField.is_base_class, - bitsize=bitsize, bitpos=bitpos, type=fieldType, - extractor=extractor) def listLocals(self, partialVar): frame = gdb.selected_frame() try: block = frame.block() - #DumperBase.warn('BLOCK: %s ' % block) + #self.warn('BLOCK: %s ' % block) except RuntimeError as error: - #DumperBase.warn('BLOCK IN FRAME NOT ACCESSIBLE: %s' % error) + #self.warn('BLOCK IN FRAME NOT ACCESSIBLE: %s' % error) return [] except: self.warn('BLOCK NOT ACCESSIBLE FOR UNKNOWN REASONS') @@ -594,14 +608,12 @@ class Dumper(DumperBase): if partialVar is not None and partialVar != name: continue - # 'NotImplementedError: Symbol type not yet supported in - # Python scripts.' - #DumperBase.warn('SYMBOL %s (%s, %s)): ' % (symbol, name, symbol.name)) + #self.warn('SYMBOL %s (%s, %s)): ' % (symbol, name, symbol.name)) if self.passExceptions and not self.isTesting: nativeValue = frame.read_var(name, block) value = self.fromFrameValue(nativeValue) value.name = name - #DumperBase.warn('READ 0: %s' % value.stringify()) + #self.warn('READ 0: %s' % value.stringify()) items.append(value) continue @@ -610,14 +622,14 @@ class Dumper(DumperBase): nativeValue = frame.read_var(name, block) value = self.fromFrameValue(nativeValue) value.name = name - #DumperBase.warn('READ 1: %s' % value.stringify()) + #self.warn('READ 1: %s' % value.stringify()) items.append(value) continue except: pass try: - #DumperBase.warn('READ 2: %s' % item.value) + #self.warn('READ 2: %s' % item.value) value = self.fromFrameValue(frame.read_var(name)) value.name = name items.append(value) @@ -631,8 +643,8 @@ class Dumper(DumperBase): pass try: - #DumperBase.warn('READ 3: %s %s' % (name, item.value)) - #DumperBase.warn('ITEM 3: %s' % item.value) + #self.warn('READ 3: %s %s' % (name, item.value)) + #self.warn('ITEM 3: %s' % item.value) value = self.fromFrameValue(gdb.parse_and_eval(name)) value.name = name items.append(value) @@ -661,16 +673,17 @@ class Dumper(DumperBase): return self.ptrSize() == 8 def fetchVariables(self, args): + start_time = time.perf_counter() self.resetStats() self.prepare(args) self.isBigEndian = gdb.execute('show endian', to_string=True).find('big endian') > 0 self.packCode = '>' if self.isBigEndian else '<' - (ok, res) = self.tryFetchInterpreterVariables(args) - if ok: - safePrint(res) - return + #(ok, res) = self.tryFetchInterpreterVariables(args) + #if ok: + # safePrint(res) + # return self.put('data=[') @@ -679,7 +692,7 @@ class Dumper(DumperBase): partialName = partialVar.split('.')[1].split('@')[0] if isPartial else None variables = self.listLocals(partialName) - #DumperBase.warn('VARIABLES: %s' % variables) + #self.warn('VARIABLES: %s' % variables) # Take care of the return value of the last function call. if len(self.resultVarName) > 0: @@ -711,9 +724,12 @@ class Dumper(DumperBase): self.put(',qtnamespace="%s"' % self.qtNamespaceToReport) self.qtNamespaceToReport = None + run_time = time.perf_counter() - start_time + #self.warn("PTIME: %s" % run_time) self.put(',partial="%d"' % isPartial) + self.put(',runtime="%s"' % run_time) self.put(',counts=%s' % self.counts) - self.put(',timings=%s' % self.timings) + #self.put(',timings=%s' % self.timings) self.reportResult(''.join(self.output), args) def parseAndEvaluate(self, exp): @@ -721,7 +737,7 @@ class Dumper(DumperBase): return None if val is None else self.fromNativeValue(val) def nativeParseAndEvaluate(self, exp): - #DumperBase.warn('EVALUATE "%s"' % exp) + #self.warn('EVALUATE "%s"' % exp) try: val = gdb.parse_and_eval(exp) return val @@ -744,20 +760,20 @@ class Dumper(DumperBase): else: arg += a - #DumperBase.warn('CALL: %s -> %s(%s)' % (value, function, arg)) - typeName = value.type.name - if typeName.find(':') >= 0: - typeName = "'" + typeName + "'" + #self.warn('CALL: %s -> %s(%s)' % (value, function, arg)) + type_name = value.type.name + if type_name.find(':') >= 0: + type_name = "'" + type_name + "'" # 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912 - #exp = '((class %s*)%s)->%s(%s)' % (typeName, value.laddress, function, arg) + #exp = '((class %s*)%s)->%s(%s)' % (type_name, value.laddress, function, arg) addr = value.address() if addr is None: addr = self.pokeValue(value) - #DumperBase.warn('PTR: %s -> %s(%s)' % (value, function, addr)) - exp = '((%s*)0x%x)->%s(%s)' % (typeName, addr, function, arg) - #DumperBase.warn('CALL: %s' % exp) + #self.warn('PTR: %s -> %s(%s)' % (value, function, addr)) + exp = '((%s*)0x%x)->%s(%s)' % (type_name, addr, function, arg) + #self.warn('CALL: %s' % exp) result = gdb.parse_and_eval(exp) - #DumperBase.warn(' -> %s' % result) + #self.warn(' -> %s' % result) res = self.fromNativeValue(result) if value.address() is None: self.releaseValue(addr) @@ -765,14 +781,14 @@ class Dumper(DumperBase): def makeExpression(self, value): typename = '::' + value.type.name - #DumperBase.warn(' TYPE: %s' % typename) + #self.warn(' TYPE: %s' % typename) exp = '(*(%s*)(0x%x))' % (typename, value.address()) - #DumperBase.warn(' EXP: %s' % exp) + #self.warn(' EXP: %s' % exp) return exp 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() @@ -785,14 +801,14 @@ class Dumper(DumperBase): size = value.type.size() data = value.data() h = self.hexencode(data) - #DumperBase.warn('DATA: %s' % h) + #self.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) + #self.warn('EXP: %s' % exp) res = gdb.parse_and_eval(exp) - #DumperBase.warn('RES: %s' % res) - return toInteger(res) + #self.warn('RES: %s' % res) + return int(res) def releaseValue(self, address): gdb.parse_and_eval('free(0x%x)' % address) @@ -819,7 +835,7 @@ class Dumper(DumperBase): return self.cachedInferior def readRawMemory(self, address, size): - #DumperBase.warn('READ: %s FROM 0x%x' % (size, address)) + #self.warn('READ: %s FROM 0x%x' % (size, address)) if address == 0 or size == 0: return bytes() res = self.selectedInferior().read_memory(address, size) @@ -832,7 +848,7 @@ class Dumper(DumperBase): return 0 try: # Older GDB ~7.4 don't have gdb.Symbol.value() - return toInteger(symbol.value().address) + return int(symbol.value().address) except: pass @@ -870,12 +886,10 @@ class Dumper(DumperBase): pass return None - def qtVersion(self): + def extractQtVersion(self): try: # Only available with Qt 5.3+ - qtversion = int(str(gdb.parse_and_eval('((void**)&qtHookData)[2]')), 16) - self.qtVersion = lambda: qtversion - return qtversion + return int(str(gdb.parse_and_eval('((void**)&qtHookData)[2]')), 16) except: pass @@ -887,7 +901,8 @@ class Dumper(DumperBase): return qtversion except: # Use fallback until we have a better answer. - return self.fallbackQtVersion + return None + def createSpecialBreakpoints(self, args): self.specialBreakpoints = [] @@ -1014,13 +1029,9 @@ class Dumper(DumperBase): for obj in gdb.objfiles(): self.importPlainDumpersForObj(obj) - def qtNamespace(self): - # This function is replaced by handleQtCoreLoaded() - return '' - def findSymbol(self, symbolName): try: - return toInteger(gdb.parse_and_eval("(size_t)&'%s'" % symbolName)) + return int(gdb.parse_and_eval("(size_t)&'%s'" % symbolName)) except: return 0 @@ -1050,47 +1061,38 @@ class Dumper(DumperBase): pass def handleQtCoreLoaded(self, objfile): - fd, tmppath = tempfile.mkstemp() - os.close(fd) - try: - cmd = 'maint print msymbols -objfile "%s" -- %s' % (objfile.filename, tmppath) - symbols = gdb.execute(cmd, to_string=True) - except: - try: - # command syntax depends on gdb version - below is gdb < 8 - cmd = 'maint print msymbols %s "%s"' % (tmppath, objfile.filename) - symbols = gdb.execute(cmd, to_string=True) - except: - pass - ns = '' - with open(tmppath) as f: - for line in f: - if line.find('msgHandlerGrabbed ') >= 0: - # [11] b 0x7ffff683c000 _ZN4MynsL17msgHandlerGrabbedE - # section .tbss Myns::msgHandlerGrabbed qlogging.cpp - ns = re.split(r'_ZN?(\d*)(\w*)L17msgHandlerGrabbedE? ', line)[2] - if len(ns): - ns += '::' - break - if line.find('currentThreadData ') >= 0: - # [ 0] b 0x7ffff67d3000 _ZN2UUL17currentThreadDataE - # section .tbss UU::currentThreadData qthread_unix.cpp\\n - ns = re.split(r'_ZN?(\d*)(\w*)L17currentThreadDataE? ', line)[2] - if len(ns): - ns += '::' - break - os.remove(tmppath) + self.qtLoaded = True + # FIXME: Namespace auto-detection. Is it worth the price? + # fd, tmppath = tempfile.mkstemp() + # os.close(fd) + # cmd = 'maint print msymbols -objfile "%s" -- %s' % (objfile.filename, tmppath) + # symbols = gdb.execute(cmd, to_string=True) + # ns = '' + # with open(tmppath) as f: + # ns1re = re.compile(r'_ZN?(\d*)(\w*)L17msgHandlerGrabbedE? ') + # ns2re = re.compile(r'_ZN?(\d*)(\w*)L17currentThreadDataE? ') + # for line in f: + # if 'msgHandlerGrabbed ' in line: + # # [11] b 0x7ffff683c000 _ZN4MynsL17msgHandlerGrabbedE + # # section .tbss Myns::msgHandlerGrabbed qlogging.cpp + # ns = ns1re.split(line)[2] + # if len(ns): + # ns += '::' + # break + # if 'currentThreadData ' in line: + # # [ 0] b 0x7ffff67d3000 _ZN2UUL17currentThreadDataE + # # section .tbss UU::currentThreadData qthread_unix.cpp\\n + # ns = ns2re.split(line)[2] + # if len(ns): + # ns += '::' + # break + # os.remove(tmppath) + def fetchInternalFunctions(self): + ns = self.qtNamespace() lenns = len(ns) strns = ('%d%s' % (lenns - 2, ns[:lenns - 2])) if lenns else '' - if lenns: - # This might be wrong, but we can't do better: We found - # a libQt5Core and could not extract a namespace. - # The best guess is that there isn't any. - self.qtNamespaceToReport = ns - self.qtNamespace = lambda: ns - sym = '_ZN%s7QObject11customEventEPNS_6QEventE' % strns else: sym = '_ZN7QObject11customEventEP6QEvent' @@ -1103,22 +1105,24 @@ class Dumper(DumperBase): if not self.isWindowsTarget(): # prevent calling the property function on windows self.qtPropertyFunc = self.findSymbol(sym) + self.fetchInternalFunctions = lambda: None + def assignValue(self, args): - typeName = self.hexdecode(args['type']) + type_name = self.hexdecode(args['type']) expr = self.hexdecode(args['expr']) value = self.hexdecode(args['value']) simpleType = int(args['simpleType']) ns = self.qtNamespace() - if typeName.startswith(ns): - typeName = typeName[len(ns):] - typeName = typeName.replace('::', '__') - pos = typeName.find('<') + if type_name.startswith(ns): + type_name = type_name[len(ns):] + type_name = type_name.replace('::', '__') + pos = type_name.find('<') if pos != -1: - typeName = typeName[0:pos] - if typeName in self.qqEditable and not simpleType: - #self.qqEditable[typeName](self, expr, value) + type_name = type_name[0:pos] + if type_name in self.qqEditable and not simpleType: + #self.qqEditable[type_name](self, expr, value) expr = self.parseAndEvaluate(expr) - self.qqEditable[typeName](self, expr, value) + self.qqEditable[type_name](self, expr, value) else: cmd = 'set variable (%s)=%s' % (expr, value) gdb.execute(cmd) @@ -1152,63 +1156,28 @@ class Dumper(DumperBase): nativeValue = value.nativeValue return self.fromNativeValue(nativeValue.cast(nativeValue.type.target())) - def nativeDynamicTypeName(self, address, baseType): + def nativeDynamicType(self, address, base_typeid): # Needed for Gdb13393 test. - nativeType = self.lookupNativeType(baseType.name) + nativeType = self.type_nativetype_cache.get(base_typeid, None) if nativeType is None: - return None + return base_typeid nativeTypePointer = nativeType.pointer() nativeValue = gdb.Value(address).cast(nativeTypePointer).dereference() - val = nativeValue.cast(nativeValue.dynamic_type) - return str(val.type) - #try: - # vtbl = gdb.execute('info symbol {%s*}0x%x' % (baseType.name, address), to_string = True) - #except: - # return None - #pos1 = vtbl.find('vtable ') - #if pos1 == -1: - # return None - #pos1 += 11 - #pos2 = vtbl.find(' +', pos1) - #if pos2 == -1: - # return None - #return vtbl[pos1 : pos2] - - def nativeDynamicType(self, address, baseType): - # Needed for Gdb13393 test. - nativeType = self.lookupNativeType(baseType.name) - if nativeType is None: - return baseType - nativeTypePointer = nativeType.pointer() - nativeValue = gdb.Value(address).cast(nativeTypePointer).dereference() - return self.fromNativeType(nativeValue.dynamic_type) + return self.from_native_type(nativeValue.dynamic_type) def enumExpression(self, enumType, enumValue): return self.qtNamespace() + 'Qt::' + enumValue - def lookupNativeType(self, typeName): - nativeType = self.lookupNativeTypeHelper(typeName) - if nativeType is not None: - self.check(isinstance(nativeType, gdb.Type)) - return nativeType - - def lookupNativeTypeHelper(self, typeName): - typeobj = self.typeCache.get(typeName) - #DumperBase.warn('LOOKUP 1: %s -> %s' % (typeName, typeobj)) - if typeobj is not None: - return typeobj - - if typeName == 'void': - typeobj = gdb.lookup_type(typeName) - self.typeCache[typeName] = typeobj - self.typesToReport[typeName] = typeobj + def lookupNativeType(self, type_name): + if type_name == 'void': + typeobj = gdb.lookup_type(type_name) + self.typesToReport[type_name] = typeobj return typeobj #try: - # typeobj = gdb.parse_and_eval('{%s}&main' % typeName).typeobj + # typeobj = gdb.parse_and_eval('{%s}&main' % type_name).typeobj # if not typeobj is None: - # self.typeCache[typeName] = typeobj - # self.typesToReport[typeName] = typeobj + # self.typesToReport[type_name] = typeobj # return typeobj #except: # pass @@ -1217,22 +1186,21 @@ class Dumper(DumperBase): # gcc produces '{anonymous}', gdb '(anonymous namespace)' # '' has been seen too. The only thing gdb # understands when reading things back is '(anonymous namespace)' - if typeName.find('{anonymous}') != -1: - ts = typeName + if type_name.find('{anonymous}') != -1: + ts = type_name ts = ts.replace('{anonymous}', '(anonymous namespace)') typeobj = self.lookupNativeType(ts) if typeobj is not None: - self.typeCache[typeName] = typeobj - self.typesToReport[typeName] = typeobj + self.typesToReport[type_name] = typeobj return typeobj - #DumperBase.warn(" RESULT FOR 7.2: '%s': %s" % (typeName, typeobj)) + #self.warn(" RESULT FOR 7.2: '%s': %s" % (type_name, typeobj)) # This part should only trigger for # gdb 7.1 for types with namespace separators. # And anonymous namespaces. - ts = typeName + ts = type_name while True: if ts.startswith('class '): ts = ts[6:] @@ -1259,36 +1227,32 @@ class Dumper(DumperBase): typeobj = self.lookupNativeType(ts[0:-1]) if typeobj is not None: typeobj = typeobj.pointer() - self.typeCache[typeName] = typeobj - self.typesToReport[typeName] = typeobj + self.typesToReport[type_name] = typeobj return typeobj try: - #DumperBase.warn("LOOKING UP 1 '%s'" % ts) + #self.warn("LOOKING UP 1 '%s'" % ts) typeobj = gdb.lookup_type(ts) except RuntimeError as error: - #DumperBase.warn("LOOKING UP 2 '%s' ERROR %s" % (ts, error)) + #self.warn("LOOKING UP '%s' FAILED" % ts) + pass + #self.warn("LOOKING UP 2 '%s' ERROR %s" % (ts, error)) # See http://sourceware.org/bugzilla/show_bug.cgi?id=11912 exp = "(class '%s'*)0" % ts try: typeobj = self.parse_and_eval(exp).type.target() - #DumperBase.warn("LOOKING UP 3 '%s'" % typeobj) + #self.warn("LOOKING UP 3 '%s'" % typeobj) except: # Can throw 'RuntimeError: No type named class Foo.' pass - except: - #DumperBase.warn("LOOKING UP '%s' FAILED" % ts) - pass if typeobj is not None: - #DumperBase.warn('CACHING: %s' % typeobj) - self.typeCache[typeName] = typeobj - self.typesToReport[typeName] = typeobj + #self.warn('CACHING: %s' % typeobj) + self.typesToReport[type_name] = typeobj # This could still be None as gdb.lookup_type('char[3]') generates # 'RuntimeError: No type named char[3]' - #self.typeCache[typeName] = typeobj - #self.typesToReport[typeName] = typeobj + #self.typesToReport[type_name] = typeobj return typeobj def doContinue(self): @@ -1332,7 +1296,7 @@ class Dumper(DumperBase): if typeobj.code == gdb.TYPE_CODE_PTR: dereftype = typeobj.target().unqualified() if dereftype.name == needle: - addr = toInteger(value) + addr = int(value) res = None for pat in pats: try: @@ -1442,14 +1406,6 @@ class Dumper(DumperBase): def reportResult(self, result, args): print('result={token="%s",%s}' % (args.get("token", 0), result)) - def profile1(self, args): - '''Internal profiling''' - import cProfile - tempDir = tempfile.gettempdir() + '/bbprof' - cProfile.run('theDumper.fetchVariables(%s)' % args, tempDir) - import pstats - pstats.Stats(tempDir).sort_stats('time').print_stats() - def profile2(self, args): import timeit print(timeit.repeat('theDumper.fetchVariables(%s)' % args, diff --git a/share/qtcreator/debugger/libcpp_stdtypes.py b/share/qtcreator/debugger/libcpp_stdtypes.py index 44b3a235ffd..2db83521013 100644 --- a/share/qtcreator/debugger/libcpp_stdtypes.py +++ b/share/qtcreator/debugger/libcpp_stdtypes.py @@ -5,6 +5,7 @@ from stdtypes import qdump__std__array, qdump__std__complex, qdump__std__once_fl from utils import DisplayFormat from dumper import Children, DumperBase +import struct def qform__std____1__array(): return [DisplayFormat.ArrayPlot] @@ -163,231 +164,114 @@ def qdump__std____1__stack(d, value): d.putBetterType(value.type) -def GetChildMemberWithName(value, name): - members = value.members(True) - for member in members: - if member.name == name: - return member - return None - - -def GetIndexOfChildWithName(value, name): - members = value.members(True) - - for i, member in enumerate(members): - if member.name == name: - return i - return None - - -class StringLayout: - CSD = 0 - DSC = 1 - - -def std_1_string_dumper_v2(d, value): - charType = value['__l']['__data_'].dereference().type - - R = GetChildMemberWithName(value, "__r_") - if not R: - raise Exception("Could not find __r_") - - # __r_ is a compressed_pair of the actual data and the allocator. The data we - # want is in the first base class. - R_Base_SP = R[0] - - if not R_Base_SP: - raise Exception("Could not find R_Base_SP") - - Rep_Sp = GetChildMemberWithName(R_Base_SP, "__value_") - - if not Rep_Sp: - raise Exception("Could not find __value_") - - # Our layout seems a little different - Rep_Sp = Rep_Sp[0] - - if not Rep_Sp: - raise Exception("Could not find Rep_Sp") - - L = GetChildMemberWithName(Rep_Sp, "__l") - - if not L: - raise Exception("Could not find __l") - - layout = StringLayout.CSD - if GetIndexOfChildWithName(L, "__data_") == 0: - layout = StringLayout.DSC - - short_mode = False - using_bitmasks = True - size = 0 - size_mode_value = 0 - - Short_Sp = GetChildMemberWithName(Rep_Sp, "__s") - if not Short_Sp: - raise Exception("Could not find __s") - - Is_Long = GetChildMemberWithName(Short_Sp, "__is_long_") - Size_Sp = GetChildMemberWithName(Short_Sp, "__size_") - if not Size_Sp: - raise Exception("Could not find __size_") - - if Is_Long: - using_bitmasks = False - short_mode = Is_Long.integer() == 0 - size = Size_Sp.integer() - else: - size_mode_value = Size_Sp.integer() - mode_mask = 1 - if layout == StringLayout.DSC: - mode_mask = 0x80 - short_mode = (size_mode_value & mode_mask) == 0 - - if short_mode: - Location_Sp = GetChildMemberWithName(Short_Sp, "__data_") - - if using_bitmasks: - size = ((size_mode_value >> 1) % 256) - if layout == StringLayout.DSC: - size = size_mode_value - - # The string is most likely not initialized yet - if size > 100 or not Location_Sp: - raise Exception("Probably not initialized yet") - - d.putCharArrayHelper(d.extractPointer(Location_Sp), size, - charType, d.currentItemFormat()) - return - - Location_Sp = GetChildMemberWithName(L, "__data_") - Size_Vo = GetChildMemberWithName(L, "__size_") - Capacity_Vo = GetChildMemberWithName(L, "__cap_") - - if not Location_Sp or not Size_Vo or not Capacity_Vo: - raise Exception("Could not find Location_Sp, Size_Vo or Capacity_Vo") - - size = Size_Vo.integer() - capacity = Capacity_Vo.integer() - if not using_bitmasks and layout == StringLayout.CSD: - capacity *= 2 - if capacity < size: - raise Exception("Capacity is less than size") - - d.putCharArrayHelper(d.extractPointer(Location_Sp), size, - charType, d.currentItemFormat()) - - -def std_1_string_dumper_v1(d, value): - charType = value['__l']['__data_'].dereference().type - D = None - - if d.isLldb: - D = value[0][0][0][0] - elif d.isGdb: - D = value["__r_"].members(True)[0][0][0] - else: - raise Exception("Unknown debugger (neither gdb nor lldb)") - - layoutDecider = D[0][0] - if not layoutDecider: - raise Exception("Could not find layoutDecider") - - size = 0 - size_mode_value = 0 - short_mode = False - libcxx_version = 14 - - layoutModeIsDSC = layoutDecider.name == '__data_' - if (layoutModeIsDSC): - size_mode = D[1][1][0] - if not size_mode: - raise Exception("Could not find size_mode") - if not size_mode.name == '__size_': - size_mode = D[1][1][1] - if not size_mode: - raise Exception("Could not find size_mode") - - size_mode_value = size_mode.integer() - short_mode = ((size_mode_value & 0x80) == 0) - else: - size_mode = D[1][0][0] - if not size_mode: - raise Exception("Could not find size_mode") - - if size_mode.name == '__is_long_': - libcxx_version = 15 - short_mode = (size_mode.integer() == 0) - - size_mode = D[1][0][1] - size_mode_value = size_mode.integer() - else: - size_mode_value = size_mode.integer() - short_mode = ((size_mode_value & 1) == 0) - - if short_mode: - s = D[1] - - if not s: - raise Exception("Could not find s") - - if libcxx_version == 14: - location_sp = s[0] if layoutModeIsDSC else s[1] - size = size_mode_value if layoutModeIsDSC else ((size_mode_value >> 1) % 256) - elif libcxx_version == 15: - location_sp = s[0] if layoutModeIsDSC else s[2] - size = size_mode_value - - else: - l = D[0] - if not l: - raise Exception("Could not find l") - - # we can use the layout_decider object as the data pointer - location_sp = layoutDecider if layoutModeIsDSC else l[2] - size_vo = l[1] - if not size_vo or not location_sp: - raise Exception("Could not find size_vo or location_sp") - size = size_vo.integer() - - if short_mode and location_sp: - d.putCharArrayHelper(d.extractPointer(location_sp), size, - charType, d.currentItemFormat()) - else: - d.putCharArrayHelper(location_sp.integer(), - size, charType, d.currentItemFormat()) - - return +# Examples for std::__1::string layouts for libcxx version 16 +# +# std::string b = "asd" +# +# b = { +# static __endian_factor = 2, +# __r_ = { +# , std::__1::allocator >::__rep, 0, false>> = { +# __value_ = {{ +# __l = { +# {__is_long_ = 0, __cap_ = 842641539}, +# __size_ = 140737353746888, +# __data_ = 0x7ffff7fa0a20 ::id> \"\\377\\377\\377\\377\\377\\377\\377\\377\\006\" +# }, +# __s = { +# {__is_long_ = 0 '\\000', __size_ = 3 '\\003'}, +# __padding_ = 0x7fffffffd859 \"asd\", +# __data_ = \"asd\\000\\000\\000\\000\\310\\t\\372\\367\\377\\177\\000\\000 \\n\\372\\367\\377\\177\\000\" +# }, +# __r = { +# __words = {1685283078, 140737353746888, 140737353746976} +# } +# }} +# }, +# , 1, true>> = { +# > = { +# >> = { +# +# }, +# +# }, +# +# }, +# +# }, +# static npos = 18446744073709551615 +# } +# +# +# std::string c = "asdlonasdlongstringasdlongstringasdlongstringasdlongstringgstring" +# +# c = { +# static __endian_factor = 2, +# __r_ = { +# , std::__1::allocator >::__rep, 0, false>> = { +# __value_ = {{ +# __l = { +# {__is_long_ = 1, __cap_ = 40}, # size_type: __cap_ +# __size_ = 65, +# __data_ = 0x5555555592a0 \"asdlonasdlongstringasdlongstringasdlongstringasdlongstringgstring\" +# }, +# __s = { +# {__is_long_ = 1 '\\001', __size_ = 40 '('}, +# __padding_ = 0x7fffffffd831 \"\", __data_ = \"\\000\\000\\000\\000\\000\\000\\000A\\000\\000\\000\\000\\000\\000\\000\\240\\222UUUU\\000\" +# }, +# __r = { +# __words = {81, 65, 93824992252576} +# } +# }} +# }, +# , 1, true>> = { +# > = { +# >> = { +# +# }, +# +# }, +# }, +# +# }, +# static npos = 18446744073709551615 +# }" def qdump__std____1__string(d, value): - try: - std_1_string_dumper_v2(d, value) - except Exception as eV2: - try: - std_1_string_dumper_v1(d, value) - except Exception as eV1: - d.putValue("Could not parse: %s, %s" % (eV1, eV2)) - - -def qdump__std____1__wstring(d, value): - try: - std_1_string_dumper_v2(d, value) - except Exception as eV2: - try: - std_1_string_dumper_v1(d, value) - except Exception as eV1: - d.putValue("Could not parse: %s, %s" % (eV1, eV2)) - - -def qdump__std____1__basic_string(d, value): - innerType = value.type[0].name - if innerType in ("char", "char8_t", "char16_t"): - qdump__std____1__string(d, value) - elif innerType in ("wchar_t", "char32_t"): - qdump__std____1__wstring(d, value) + charType = value.type[0] + blob = bytes(value.data()) + r0, r1, r2 = struct.unpack(d.packCode + 'QQQ', blob) + if d.isLldb and d.isArmMac: + is_long = r2 >> 63 + if is_long: + # [---------------- data ptr ---------------] 63:0 + # [------------------ size ----------------] + # [?---------------- alloc ----------------] + data = r0 + size = r1 + else: + # [------------------- data ----------------] 63:0 + # [------------------- data ----------------] + # [?ssss-------------- data ----------------] + data = value.laddress + size = (r2 >> 56) & 255 else: - d.warn("UNKNOWN INNER TYPE %s" % innerType) + is_long = r0 & 1 + if is_long: + # [------------------ alloc ---------------?] 63:0 + # [------------------- size ----------------] + # [----------------- data ptr --------------] + data = r2 + size = r1 + else: + # [------------------- data ----------sssss?] 63:0 + # [------------------- data ----------------] + # [------------------- data ----------------] + data = value.laddress + charType.size() + size = (r0 & 255) // 2 + d.putCharArrayHelper(data, size, charType) def qdump__std____1__shared_ptr(d, value): diff --git a/share/qtcreator/debugger/lldbbridge.py b/share/qtcreator/debugger/lldbbridge.py index f2387ac913c..3f7ec792a61 100644 --- a/share/qtcreator/debugger/lldbbridge.py +++ b/share/qtcreator/debugger/lldbbridge.py @@ -18,11 +18,7 @@ sys.path.insert(1, os.path.dirname(os.path.abspath(inspect.getfile(inspect.curre # Simplify development of this module by reloading deps if 'dumper' in sys.modules: - if sys.version_info[0] >= 3: - if sys.version_info[1] > 3: - from importlib import reload - else: - def reload(m): print('Unsupported Python version - not reloading %s' % str(m)) + from importlib import reload reload(sys.modules['dumper']) from dumper import DumperBase, SubItem, Children, TopLevelItem @@ -34,16 +30,10 @@ from dumper import DumperBase, SubItem, Children, TopLevelItem ####################################################################### qqWatchpointOffset = 10000 -_c_str_trans = None - -if sys.version_info[0] >= 3: - _c_str_trans = str.maketrans({"\n": "\\n", '"':'\\"', "\\":"\\\\"}) +_c_str_trans = str.maketrans({"\n": "\\n", '"':'\\"', "\\":"\\\\"}) def toCString(s): - if _c_str_trans is not None: - return str(s).translate(_c_str_trans) - else: - return str(s).replace('\\', '\\\\').replace('\n', '\\n').replace('"', '\\"') + return str(s).translate(_c_str_trans) def fileNameAsString(file): return toCString(file) if file.IsValid() else '' @@ -116,33 +106,29 @@ class Dumper(DumperBase): self.isInterrupting_ = False self.interpreterBreakpointResolvers = [] - DumperBase.warn = Dumper.warn_impl self.report('lldbversion=\"%s\"' % lldb.SBDebugger.GetVersionString()) - @staticmethod - def warn_impl(message): - if message[-1:] == '\n': - message += '\n' + def warn(self, msg): + #self.put('{name="%s",value="",type="",numchild="0"},' % toCString(msg)) + if msg[-1:] == '\n': + msg += '\n' print('@\nbridgemessage={msg="%s",channel="%s"}\n@' - % (message.replace('"', '$'), LogChannel.AppError)) - - def fromNativeFrameValue(self, nativeValue): - return self.fromNativeValue(nativeValue) + % (msg.replace('"', '$'), LogChannel.AppError)) def fromNativeValue(self, nativeValue): self.check(isinstance(nativeValue, lldb.SBValue)) nativeType = nativeValue.GetType() - typeName = nativeType.GetName() + type_name = nativeType.GetName() code = nativeType.GetTypeClass() # Display the result of GetSummary() for Core Foundation string # and string-like types. summary = None if self.useFancy: - if (typeName.startswith('CF') - or typeName.startswith('__CF') - or typeName.startswith('NS') - or typeName.startswith('__NSCF')): + if (type_name.startswith('CF') + or type_name.startswith('__CF') + or type_name.startswith('NS') + or type_name.startswith('__NSCF')): if code == lldb.eTypeClassPointer: summary = nativeValue.Dereference().GetSummary() elif code == lldb.eTypeClassReference: @@ -156,26 +142,26 @@ class Dumper(DumperBase): nativeTargetType = nativeType.GetDereferencedType() if not nativeTargetType.IsPointerType(): nativeTargetType = nativeTargetType.GetUnqualifiedType() - targetType = self.fromNativeType(nativeTargetType) - val = self.createReferenceValue(nativeValue.GetValueAsUnsigned(), targetType) + target_typeid = self.from_native_type(nativeTargetType) + target_address = nativeValue.GetValueAsUnsigned() + val = self.Value(self) + val.ldata = target_address.to_bytes(self.ptrSize(), 'little') + if self.useDynamicType: + target_typeid = self.dynamic_typeid_at_address(target_typeid, target_address) + val.typeid = self.create_reference_typeid(target_typeid) val.laddress = nativeValue.AddressOf().GetValueAsUnsigned() - #DumperBase.warn('CREATED REF: %s' % val) + #self.warn('CREATED REF: %s' % val) + elif code == lldb.eTypeClassPointer: nativeTargetType = nativeType.GetPointeeType() if not nativeTargetType.IsPointerType(): nativeTargetType = nativeTargetType.GetUnqualifiedType() - targetType = self.fromNativeType(nativeTargetType) - val = self.createPointerValue(nativeValue.GetValueAsUnsigned(), targetType) - #DumperBase.warn('CREATED PTR 1: %s' % val) + target_typeid = self.from_native_type(nativeTargetType) + val = self.Value(self) + val.ldata = nativeValue.GetValueAsUnsigned() + val.typeid = self.create_pointer_typeid(target_typeid) val.laddress = nativeValue.AddressOf().GetValueAsUnsigned() - #DumperBase.warn('CREATED PTR 2: %s' % val) - elif code == lldb.eTypeClassTypedef: - nativeTargetType = nativeType.GetUnqualifiedType() - if hasattr(nativeTargetType, 'GetCanonicalType'): - nativeTargetType = nativeTargetType.GetCanonicalType() - val = self.fromNativeValue(nativeValue.Cast(nativeTargetType)) - val._type = self.fromNativeType(nativeType) - #DumperBase.warn('CREATED TYPEDEF: %s' % val) + else: val = self.Value(self) address = nativeValue.GetLoadAddress() @@ -193,7 +179,7 @@ class Dumper(DumperBase): except: pass - val._type = self.fromNativeType(nativeType) + val.typeid = self.from_native_type(nativeType) if code == lldb.eTypeClassEnumeration: intval = nativeValue.GetValueAsSigned() @@ -209,43 +195,32 @@ class Dumper(DumperBase): val.ldisplay = str(nativeValue.GetValue()) #elif code == lldb.eTypeClassArray: # if hasattr(nativeType, 'GetArrayElementType'): # New in 3.8(?) / 350.x - # val.type.ltarget = self.fromNativeType(nativeType.GetArrayElementType()) + # val.type.ltarget = self.from_native_type(nativeType.GetArrayElementType()) # else: # fields = nativeType.get_fields_array() # if len(fields): - # val.type.ltarget = self.fromNativeType(fields[0]) + # val.type.ltarget = self.from_native_type(fields[0]) #elif code == lldb.eTypeClassVector: - # val.type.ltarget = self.fromNativeType(nativeType.GetVectorElementType()) + # val.type.ltarget = self.from_native_type(nativeType.GetVectorElementType()) val.summary = summary val.lIsInScope = nativeValue.IsInScope() val.name = nativeValue.GetName() return val - def nativeStructAlignment(self, nativeType): - def handleItem(nativeFieldType, align): - a = self.fromNativeType(nativeFieldType).alignment() - return a if a > align else align - align = 1 - for i in range(nativeType.GetNumberOfDirectBaseClasses()): - base = nativeType.GetDirectBaseClassAtIndex(i) - align = handleItem(base.GetType(), align) - for i in range(nativeType.GetNumberOfFields()): - child = nativeType.GetFieldAtIndex(i) - align = handleItem(child.GetType(), align) - return align + def nativeListMembers(self, value, nativeType, include_base): + #self.warn("ADDR: 0x%x" % self.fakeAddress_) + nativeValue = value.nativeValue + if nativeValue is None: + if value.laddress: + fakeAddress = lldb.SBAddress(value.laddress, self.target) + fakeLAddress = value.laddress + else: + fakeAddress = self.fakeAddress_ + fakeLAddress = self.fakeLAddress_ + nativeValue = self.target.CreateValueFromAddress('x', fakeAddress, nativeType) - def listMembers(self, value, nativeType): - #DumperBase.warn("ADDR: 0x%x" % self.fakeAddress_) - if value.laddress: - fakeAddress = lldb.SBAddress(value.laddress, self.target) - fakeLAddress = value.laddress - else: - fakeAddress = self.fakeAddress_ - fakeLAddress = self.fakeLAddress_ - - fakeValue = self.target.CreateValueFromAddress('x', fakeAddress, nativeType) - fakeValue.SetPreferSyntheticValue(False) + nativeValue.SetPreferSyntheticValue(False) baseNames = {} for i in range(nativeType.GetNumberOfDirectBaseClasses()): @@ -262,86 +237,108 @@ class Dumper(DumperBase): # Normal members and non-empty base classes. anonNumber = 0 - for i in range(fakeValue.GetNumChildren()): - nativeField = fakeValue.GetChildAtIndex(i) + + fields = [] + for i in range(nativeValue.GetNumChildren()): + nativeField = nativeValue.GetChildAtIndex(i) nativeField.SetPreferSyntheticValue(False) fieldName = nativeField.GetName() nativeFieldType = nativeField.GetType() if fieldName in fieldBits: - (fieldBitsize, fieldBitpos, isBitfield) = fieldBits[fieldName] + (bitsize, bitpos, isBitfield) = fieldBits[fieldName] else: - fieldBitsize = nativeFieldType.GetByteSize() * 8 - fieldBitpos = None + bitsize = nativeFieldType.GetByteSize() * 8 + bitpos = None isBitfield = False if isBitfield: # Bit fields - fieldType = self.createBitfieldType( - self.createType(self.typeName(nativeFieldType)), fieldBitsize) - yield self.Field(self, name=fieldName, type=fieldType, - bitsize=fieldBitsize, bitpos=fieldBitpos) + field_typeid = self.create_bitfield_typeid( + self.create_typeid(nativeFieldType.GetName()), bitsize) + val = self.Value(self) + val.name = fieldName + val.isBaseClass = False + val.typeid = field_typeid + val.ldata = self.value_extract_bits(value, bitpos, bitsize) + val.laddress = None + fields.append(val) elif fieldName is None: # Anon members anonNumber += 1 fieldName = '#%s' % anonNumber - fakeMember = fakeValue.GetChildAtIndex(i) + fakeMember = nativeValue.GetChildAtIndex(i) fakeMemberAddress = fakeMember.GetLoadAddress() - offset = fakeMemberAddress - fakeLAddress - yield self.Field(self, name=fieldName, type=self.fromNativeType(nativeFieldType), - bitsize=fieldBitsize, bitpos=8 * offset) + val = self.Value(self) + val.name = fieldName + val.isBaseClass = False + val.typeid = typeid=self.from_native_type(nativeFieldType) + field_offset = fakeMemberAddress - fakeLAddress + if value.laddress is not None: + val.laddress = value.laddress + field_offset + if value.ldata is not None: + field_size = (bitsize + 7) // 8 + val.ldata = value.ldata[field_offset:field_offset + field_size] + fields.append(val) elif fieldName in baseNames: # Simple bases - member = self.fromNativeValue(fakeValue.GetChildAtIndex(i)) + member = self.fromNativeValue(nativeValue.GetChildAtIndex(i)) member.isBaseClass = True - yield member + fields.append(member) else: # Normal named members - member = self.fromNativeValue(fakeValue.GetChildAtIndex(i)) + member = self.fromNativeValue(nativeValue.GetChildAtIndex(i)) member.name = nativeField.GetName() - yield member + fields.append(member) - # Empty bases are not covered above. - for i in range(nativeType.GetNumberOfDirectBaseClasses()): - fieldObj = nativeType.GetDirectBaseClassAtIndex(i) - fieldType = fieldObj.GetType() - if fieldType.GetNumberOfFields() == 0: - if fieldType.GetNumberOfDirectBaseClasses() == 0: - member = self.Value(self) - fieldName = fieldObj.GetName() - member._type = self.fromNativeType(fieldType) - member.name = fieldName - member.fields = [] - if False: - # This would be correct if we came here only for - # truly empty base classes. Alas, we don't, see below. - member.ldata = bytes() - member.lbitsize = fieldType.GetByteSize() * 8 - else: - # This is a hack. LLDB 3.8 reports declared but not defined - # types as having no fields and(!) size == 1. At least - # for the common case of a single base class we can - # fake the contents by using the whole derived object's - # data as base class data. - data = fakeValue.GetData() - size = nativeType.GetByteSize() - member.lbitsize = size * 8 - error = lldb.SBError() - member.laddress = value.laddress - member.ldata = data.ReadRawData(error, 0, size) - member.isBaseClass = True - member.ltype = self.fromNativeType(fieldType) - member.name = fieldName - yield member + + if include_base: + # Empty bases are not covered above. + for i in range(nativeType.GetNumberOfDirectBaseClasses()): + fieldObj = nativeType.GetDirectBaseClassAtIndex(i) + fieldType = fieldObj.GetType() + if fieldType.GetNumberOfFields() == 0: + if fieldType.GetNumberOfDirectBaseClasses() == 0: + member = self.Value(self) + fieldName = fieldObj.GetName() + member.typeid = self.from_native_type(fieldType) + member.name = fieldName + member.fields = [] + if False: + # This would be correct if we came here only for + # truly empty base classes. Alas, we don't, see below. + member.ldata = bytes() + else: + # This is a hack. LLDB 3.8 reports declared but not defined + # types as having no fields and(!) size == 1. At least + # for the common case of a single base class we can + # fake the contents by using the whole derived object's + # data as base class data. + data = nativeValue.GetData() + size = nativeType.GetByteSize() + error = lldb.SBError() + member.laddress = value.laddress + member.ldata = data.ReadRawData(error, 0, size) + member.isBaseClass = True + fields.append(member) + return fields def ptrSize(self): result = self.target.GetAddressByteSize() self.ptrSize = lambda: result return result - def fromNativeType(self, nativeType): + def is_qobject_based(self, nativeType): + if nativeType.GetName() == self.qtNamespace() + 'QObject': + return True + if nativeType.GetNumberOfDirectBaseClasses() > 0: + return self.is_qobject_based(nativeType.GetDirectBaseClassAtIndex(0).GetType()) + if nativeType.GetNumberOfFields() > 0: + return False + return None # No info, can't drill deeper + + def from_native_type(self, nativeType): self.check(isinstance(nativeType, lldb.SBType)) - code = nativeType.GetTypeClass() # eTypeClassInvalid = (0u), # eTypeClassArray = (1u << 0), @@ -367,43 +364,41 @@ class Dumper(DumperBase): # // Define a mask that can be used for any type when finding types # eTypeClassAny = (0xffffffffu) - #DumperBase.warn('CURRENT: %s' % self.typeData.keys()) - #DumperBase.warn('FROM NATIVE TYPE: %s' % nativeType.GetName()) + #self.warn('CURRENT: %s' % self.typeData.keys()) + #self.warn('FROM NATIVE TYPE: %s' % nativeType.GetName()) + + typeid_str = self.native_type_key(nativeType) + known_typeid = self.typeid_from_typekey.get(typeid_str, None) + if known_typeid is not None: + return known_typeid + + code = nativeType.GetTypeClass() + if code == lldb.eTypeClassInvalid: - return None + typeid = 0 - if code == lldb.eTypeClassBuiltin: - nativeType = nativeType.GetUnqualifiedType() + elif code == lldb.eTypeClassPointer: + #self.warn('PTR: %s' % nativeTargetType.name) + target_typeid = self.from_native_type(nativeType.GetPointeeType()) + typeid = self.create_pointer_typeid(target_typeid) - if code == lldb.eTypeClassPointer: - #DumperBase.warn('PTR') - nativeTargetType = nativeType.GetPointeeType() - if not nativeTargetType.IsPointerType(): - nativeTargetType = nativeTargetType.GetUnqualifiedType() - #DumperBase.warn('PTR: %s' % nativeTargetType.name) - return self.createPointerType(self.fromNativeType(nativeTargetType)) - - if code == lldb.eTypeClassReference: + elif code == lldb.eTypeClassReference: #DumperBase.warn('REF') - nativeTargetType = nativeType.GetDereferencedType() - if not nativeTargetType.IsPointerType(): - nativeTargetType = nativeTargetType.GetUnqualifiedType() - #DumperBase.warn('REF: %s' % nativeTargetType.name) - return self.createReferenceType(self.fromNativeType(nativeTargetType)) + target_typeid = self.from_native_type(nativeType.GetDereferencedType()) + typeid = self.create_reference_typeid(target_typeid) - if code == lldb.eTypeClassTypedef: + elif code == lldb.eTypeClassTypedef: #DumperBase.warn('TYPEDEF') nativeTargetType = nativeType.GetUnqualifiedType() if hasattr(nativeTargetType, 'GetCanonicalType'): nativeTargetType = nativeTargetType.GetCanonicalType() - targetType = self.fromNativeType(nativeTargetType) - return self.createTypedefedType(targetType, nativeType.GetName(), - self.nativeTypeId(nativeType)) + target_typeid = self.from_native_type(nativeTargetType) + typeid = self.create_typedefed_typeid(target_typeid, nativeType.GetName(), + typeid_str) - nativeType = nativeType.GetUnqualifiedType() - typeName = self.typeName(nativeType) - - if code in (lldb.eTypeClassArray, lldb.eTypeClassVector): + elif code in (lldb.eTypeClassArray, lldb.eTypeClassVector): + nativeType = nativeType.GetUnqualifiedType() + type_name = nativeType.GetName() #DumperBase.warn('ARRAY: %s' % nativeType.GetName()) if hasattr(nativeType, 'GetArrayElementType'): # New in 3.8(?) / 350.x nativeTargetType = nativeType.GetArrayElementType() @@ -412,141 +407,143 @@ class Dumper(DumperBase): #DumperBase.warn('BAD: %s ' % nativeTargetType.get_fields_array()) nativeTargetType = nativeType.GetVectorElementType() count = nativeType.GetByteSize() // nativeTargetType.GetByteSize() - targetTypeName = nativeTargetType.GetName() - if targetTypeName.startswith('(anon'): - typeName = nativeType.GetName() - pos1 = typeName.rfind('[') - targetTypeName = typeName[0:pos1].strip() - #DumperBase.warn("TARGET TYPENAME: %s" % targetTypeName) - targetType = self.fromNativeType(nativeTargetType) - targetType.setTdata(targetType.tdata.copy()) - targetType.tdata.name = targetTypeName - return self.createArrayType(targetType, count) - if hasattr(nativeType, 'GetVectorElementType'): # New in 3.8(?) / 350.x + target_typename = nativeTargetType.GetName() + if target_typename.startswith('(anon'): + type_name = nativeType.GetName() + pos1 = type_name.rfind('[') + target_typename = type_name[0:pos1].strip() + #DumperBase.warn("TARGET TYPENAME: %s" % target_typename) + target_typeid = self.from_native_type(nativeTargetType) + #target_typeid.setTdata(target_typeid.tdata.copy()) + #target_typeid.tdata.name = target_typename + typeid = self.create_array_typeid(target_typeid, count) + elif hasattr(nativeType, 'GetVectorElementType'): # New in 3.8(?) / 350.x nativeTargetType = nativeType.GetVectorElementType() count = nativeType.GetByteSize() // nativeTargetType.GetByteSize() - targetType = self.fromNativeType(nativeTargetType) - return self.createArrayType(targetType, count) - return self.createType(nativeType.GetName()) + target_typeid = self.from_native_type(nativeTargetType) + typeid = self.create_array_typeid(target_typeid, count) + else: + typeid = self.create_type(nativeType.GetName()) - typeId = self.nativeTypeId(nativeType) - res = self.typeData.get(typeId, None) - if res is None: + else: + nativeType = nativeType.GetUnqualifiedType() + type_name = nativeType.GetName() + + typeid = self.typeid_for_string(typeid_str) + #if not typeid in self.typeid_cache: # # This strips typedefs for pointers. We don't want that. # typeobj.nativeType = nativeType.GetUnqualifiedType() - tdata = self.TypeData(self, typeId) - tdata.name = typeName - tdata.lbitsize = nativeType.GetByteSize() * 8 + self.type_name_cache[typeid] = type_name + self.type_size_cache[typeid] = nativeType.GetByteSize() + type_code = None if code == lldb.eTypeClassBuiltin: - if utils.isFloatingPointTypeName(typeName): - tdata.code = TypeCode.Float - elif utils.isIntegralTypeName(typeName): - tdata.code = TypeCode.Integral - elif typeName in ('__int128', 'unsigned __int128'): - tdata.code = TypeCode.Integral - elif typeName == 'void': - tdata.code = TypeCode.Void - elif typeName == 'wchar_t': - tdata.code = TypeCode.Integral - elif typeName in ("char16_t", "char32_t", "char8_t"): - tdata.code = TypeCode.Integral + if utils.isFloatingPointTypeName(type_name): + type_code = TypeCode.Float + elif utils.isIntegralTypeName(type_name): + type_code = TypeCode.Integral + elif type_name in ('__int128', 'unsigned __int128'): + type_code = TypeCode.Integral + elif type_name == 'void': + type_code = TypeCode.Void + elif type_name == 'wchar_t': + type_code = TypeCode.Integral + elif type_name in ("char16_t", "char32_t", "char8_t"): + type_code = TypeCode.Integral else: - self.warn('UNKNOWN TYPE KEY: %s: %s' % (typeName, code)) + self.warn('UNKNOWN TYPE KEY: %s: %s' % (type_name, code)) elif code == lldb.eTypeClassEnumeration: - tdata.code = TypeCode.Enum - tdata.enumDisplay = lambda intval, addr, form: \ + type_code = TypeCode.Enum + self.type_enum_display_cache[typeid] = lambda intval, addr, form: \ self.nativeTypeEnumDisplay(nativeType, intval, form) elif code in (lldb.eTypeClassComplexInteger, lldb.eTypeClassComplexFloat): - tdata.code = TypeCode.Complex - elif code in (lldb.eTypeClassClass, lldb.eTypeClassStruct, lldb.eTypeClassUnion): - tdata.code = TypeCode.Struct - tdata.lalignment = lambda: \ - self.nativeStructAlignment(nativeType) - tdata.lfields = lambda value: \ - self.listMembers(value, nativeType) - tdata.templateArguments = lambda: \ - self.listTemplateParametersHelper(nativeType) + type_code = TypeCode.Complex + elif code in (lldb.eTypeClassClass, lldb.eTypeClassStruct): + type_code = TypeCode.Struct + self.type_qobject_based_cache[typeid] = self.is_qobject_based(nativeType) + elif code == lldb.eTypeClassUnion: + type_code = TypeCode.Struct + self.type_qobject_based_cache[typeid] = False elif code == lldb.eTypeClassFunction: - tdata.code = TypeCode.Function + type_code = TypeCode.Function elif code == lldb.eTypeClassMemberPointer: - tdata.code = TypeCode.MemberPointer - # warn('CREATE TYPE: %s' % typeId) + type_code = TypeCode.MemberPointer + + if code is not None: + self.type_code_cache[typeid] = type_code + + self.type_nativetype_cache[typeid] = nativeType + self.typeid_from_typekey[typeid_str] = typeid + + # self.warn('REUSE TYPE: %s' % typeid) + return typeid + + def nativeTemplateParameter(self, typeid, index, nativeType): + #n = nativeType.GetNumberOfTemplateArguments() + #if n != len(stringArgs): + # # Something wrong in the debug info. + # # Should work in theory, doesn't work in practice. + # # Items like std::allocator report 0 + # # for nativeType.GetNumberOfTemplateArguments() with LLDB 3.8 + # return stringArgs + + kind = nativeType.GetTemplateArgumentKind(index) + # eTemplateArgumentKindNull = 0, + # eTemplateArgumentKindType, + # eTemplateArgumentKindDeclaration, + # eTemplateArgumentKindIntegral, + # eTemplateArgumentKindTemplate, + # eTemplateArgumentKindTemplateExpansion, + # eTemplateArgumentKindExpression, + # eTemplateArgumentKindPack + if kind == lldb.eTemplateArgumentKindType: + innerType = nativeType.GetTemplateArgumentType(index) \ + .GetUnqualifiedType().GetCanonicalType() + return self.Type(self, self.from_native_type(innerType)) + #elif kind == lldb.eTemplateArgumentKindIntegral: + # innerType = nativeType.GetTemplateArgumentType(i).GetUnqualifiedType().GetCanonicalType() + # #DumperBase.warn('INNER TYP: %s' % innerType) + # basicType = innerType.GetBasicType() + # #DumperBase.warn('IBASIC TYP: %s' % basicType) + # inner = self.extractTemplateArgument(nativeType.GetName(), i) + # exp = '(%s)%s' % (innerType.GetName(), inner) + # #DumperBase.warn('EXP : %s' % exp) + # val = self.nativeParseAndEvaluate('(%s)%s' % (innerType.GetName(), inner)) + # # Clang writes 'int' and '0xfffffff' into the debug info + # # LLDB manages to read a value of 0xfffffff... + # #if basicType == lldb.eBasicTypeInt: + # value = val.GetValueAsUnsigned() + # if value >= 0x8000000: + # value -= 0x100000000 + # #DumperBase.warn('KIND: %s' % kind) + # targs.append(value) #else: - # warn('REUSE TYPE: %s' % typeId) - return self.Type(self, typeId) - - def listTemplateParametersHelper(self, nativeType): - stringArgs = self.listTemplateParameters(nativeType.GetName()) - n = nativeType.GetNumberOfTemplateArguments() - if n != len(stringArgs): - # Something wrong in the debug info. - # Should work in theory, doesn't work in practice. - # Items like std::allocator report 0 - # for nativeType.GetNumberOfTemplateArguments() with LLDB 3.8 - return stringArgs - - targs = [] - for i in range(nativeType.GetNumberOfTemplateArguments()): - kind = nativeType.GetTemplateArgumentKind(i) - # eTemplateArgumentKindNull = 0, - # eTemplateArgumentKindType, - # eTemplateArgumentKindDeclaration, - # eTemplateArgumentKindIntegral, - # eTemplateArgumentKindTemplate, - # eTemplateArgumentKindTemplateExpansion, - # eTemplateArgumentKindExpression, - # eTemplateArgumentKindPack - if kind == lldb.eTemplateArgumentKindType: - innerType = nativeType.GetTemplateArgumentType( - i).GetUnqualifiedType().GetCanonicalType() - targs.append(self.fromNativeType(innerType)) - #elif kind == lldb.eTemplateArgumentKindIntegral: - # innerType = nativeType.GetTemplateArgumentType(i).GetUnqualifiedType().GetCanonicalType() - # #DumperBase.warn('INNER TYP: %s' % innerType) - # basicType = innerType.GetBasicType() - # #DumperBase.warn('IBASIC TYP: %s' % basicType) - # inner = self.extractTemplateArgument(nativeType.GetName(), i) - # exp = '(%s)%s' % (innerType.GetName(), inner) - # #DumperBase.warn('EXP : %s' % exp) - # val = self.nativeParseAndEvaluate('(%s)%s' % (innerType.GetName(), inner)) - # # Clang writes 'int' and '0xfffffff' into the debug info - # # LLDB manages to read a value of 0xfffffff... - # #if basicType == lldb.eBasicTypeInt: - # value = val.GetValueAsUnsigned() - # if value >= 0x8000000: - # value -= 0x100000000 - # #DumperBase.warn('KIND: %s' % kind) - # targs.append(value) - else: - #DumperBase.warn('UNHANDLED TEMPLATE TYPE : %s' % kind) - targs.append(stringArgs[i]) # Best we can do. + # #DumperBase.warn('UNHANDLED TEMPLATE TYPE : %s' % kind) + # targs.append(stringArgs[i]) # Best we can do. #DumperBase.warn('TARGS: %s %s' % (nativeType.GetName(), [str(x) for x in targs])) - return targs + #return targs + return None - def typeName(self, nativeType): - # Don't use GetDisplayTypeName since LLDB removed the inline namespace __1 - # https://reviews.llvm.org/D74478 - return nativeType.GetName() - - def nativeTypeId(self, nativeType): - if nativeType and (nativeType.GetTypeClass() == lldb.eTypeClassTypedef): + def native_type_key(self, nativeType): + code = nativeType.GetTypeClass() + if nativeType and code == lldb.eTypeClassTypedef: nativeTargetType = nativeType.GetUnqualifiedType() if hasattr(nativeTargetType, 'GetCanonicalType'): nativeTargetType = nativeTargetType.GetCanonicalType() return '%s{%s}' % (nativeType.name, nativeTargetType.name) - name = self.typeName(nativeType) + # Don't use GetDisplayTypeName since LLDB removed the inline namespace __1 + # https://reviews.llvm.org/D74478 + name = nativeType.GetName() if name is None or len(name) == 0: c = '0' - elif name == '(anonymous struct)' and nativeType.GetTypeClass() == lldb.eTypeClassStruct: - c = 's' - elif name == '(anonymous struct)' and nativeType.GetTypeClass() == lldb.eTypeClassUnion: - c = 'u' + elif name == '(anonymous struct)': + c = 's' if code == lldb.eTypeClassStruct else 'u' else: return name fields = nativeType.get_fields_array() - typeId = c + ''.join(['{%s:%s}' % (f.name, self.nativeTypeId(f.GetType())) for f in fields]) - #DumperBase.warn('NATIVE TYPE ID FOR %s IS %s' % (name, typeId)) - return typeId + id_str = c + ''.join(['{%s:%s}' % + (f.name, self.typeid_for_string(self.native_type_key(f.GetType()))) + for f in fields]) + return id_str def nativeTypeEnumDisplay(self, nativeType, intval, form): if hasattr(nativeType, 'get_enum_members_array'): @@ -575,12 +572,82 @@ class Dumper(DumperBase): return '(' + ' | '.join(flags) + ') (' + (form % intval) + ')' return form % intval - def nativeDynamicTypeName(self, address, baseType): - return None # FIXME: Seems sufficient, no idea why. - addr = self.target.ResolveLoadAddress(address) - ctx = self.target.ResolveSymbolContextForAddress(addr, 0) - sym = ctx.GetSymbol() - return sym.GetName() + def nativeDynamicType(self, address, base_typeid): + return self.nativeDynamicType_2(address, base_typeid) + + def nativeDynamicType_1(self, address, base_typeid): + # Solutions 1: Breaks StdUniquePtr and QVariant1 test + return base_typeid + + def nativeDynamicType_2(self, address, base_typeid): + # Solution 2: ~10% slower in total than Solution 1 + typename = self.type_name(base_typeid) + #self.warn("LOOKING FOR DYN TYPE: 0x%x %s" % (address, typename)) + #self.warn(" PRETTY: 0x%x %s" % (address, self.prettySymbolByAddress(address))) + + expr = '(void*)%s' % address + value = self.target.EvaluateExpression(expr) + + #self.warn("VALUE: %s" % value) + if value.GetType().GetName() == "void *": + #self.warn("NO DYN TYPE: %s" % value) + return base_typeid + + dvalue = value.Dereference() + #self.warn("DVALUE: %s" % value) + sbtype = dvalue.GetType() + #self.warn("TYPE: %s" % sbtype) + + #self.warn("OUTPUT: %s" % output) + #self.warn("DYNTYPE: %s" % dyn_typename) + return self.from_native_type(sbtype) + + def nativeDynamicType_3(self, address, base_typeid): + # Solution 3: Doesn't improve over 1 + typename = self.type_name(base_typeid) + self.warn("LOOKING FOR DYN TYPE: 0x%x %s" % (address, typename)) + #self.warn(" PRETTY: 0x%x %s" % (address, self.prettySymbolByAddress(address))) + nativeType = self.type_nativetype_cache.get(base_typeid, None) + #self.warn(" NATIVE BASE %s" % nativeType) + if nativeType is None: + return base_typeid + #versionValue = self.target.EvaluateExpression('qtHookData[2]').GetNonSyntheticValue() + addr = lldb.SBAddress(address, self.target) + value = self.target.CreateValueFromAddress('x', addr, nativeType) + self.warn(" VALUE %s" % value) + return base_typeid + + def nativeDynamicType_4(self, address, base_typeid): + #self.warn("RESULT: %s" % result) + #self.warn("ADDRESS: 0x%x" % address) + + #thread = self.currentThread() + #frame = thread.GetFrameAtIndex(0) + #expr = '(void*)%s' % address + #value = self.target.EvaluateExpression(expr) + #sbtype = self.lookupNativeType(typename) + #addr = self.target.ResolveLoadAddress(address) + #addr = lldb.SBAddress(address, self.target) + #value = self.target.CreateValueFromAddress('x', addr, sbtype) + #x = lldb::DynamicValueType() + #lldb.eNoDynamicValues + #lldb.eDynamicCanRunTarget + #lldb.eDynamicDontRunTarget + #dyn_value = value.GetDynamicValue(lldb.eDynamicDontRunTarget) + #typ = dyn_value.GetType() + self.warn("GOT DYN VALUE: %s" % dyn_value) + #self.warn("GOT TYPE: %s FOR OBJECT AT 0x%x" % (typ, address)) + return self.from_native_type(typ) + + #result = lldb.SBCommandReturnObject() + #cmd = 'p (void*)%s' % address + #self.debugger.GetCommandInterpreter().HandleCommand(cmd, result) + #if not result.Succeeded(): + # return self.Type(self, typeid) + #output = result.GetOutput().strip() + #dyn_typename = output[1:output.find('$') - 4] + #sbtype = self.lookupNativeType(dyn_typename) + def stateName(self, s): try: @@ -638,11 +705,11 @@ class Dumper(DumperBase): #DumperBase.warn(' -> %s' % result) return self.fromNativeValue(result) - def pokeValue(self, typeName, *args): + def pokeValue(self, type_name, *args): thread = self.currentThread() frame = thread.GetFrameAtIndex(0) inner = ','.join(args) - value = frame.EvaluateExpression(typeName + '{' + inner + '}') + value = frame.EvaluateExpression(type_name + '{' + inner + '}') #DumperBase.warn(' TYPE: %s' % value.type) #DumperBase.warn(' ADDR: 0x%x' % value.address) #DumperBase.warn(' VALUE: %s' % value) @@ -704,7 +771,9 @@ class Dumper(DumperBase): symbol = funcs[0].GetSymbol() self.qtPropertyFunc = symbol.GetStartAddress().GetLoadAddress(self.target) - def fetchQtVersionAndNamespace(self): + self.fetchInternalFunctions = lambda: None + + def extractQtVersion(self): for func in self.target.FindFunctions('qVersion'): name = func.GetSymbol().GetName() if name == None: @@ -714,8 +783,8 @@ class Dumper(DumperBase): if name.count(':') > 2: continue - qtNamespace = name[:name.find('qVersion')] - self.qtNamespace = lambda: qtNamespace + #qtNamespace = name[:name.find('qVersion')] + #self.qtNamespace = lambda: qtNamespace options = lldb.SBExpressionOptions() res = self.target.EvaluateExpression(name + '()', options) @@ -740,44 +809,17 @@ class Dumper(DumperBase): (major, minor, patch) = version.split('.') qtVersion = 0x10000 * int(major) + 0x100 * int(minor) + int(patch) - self.qtVersion = lambda: qtVersion - - return (qtNamespace, qtVersion) + return qtVersion try: versionValue = self.target.EvaluateExpression('qtHookData[2]').GetNonSyntheticValue() if versionValue.IsValid(): - return ('', versionValue.unsigned) + return versionValue.unsigned except: pass - return ('', self.fallbackQtVersion) + return None - def qtVersionAndNamespace(self): - qtVersionAndNamespace = None - try: - qtVersionAndNamespace = self.fetchQtVersionAndNamespace() - self.report("Detected Qt Version: 0x%0x (namespace='%s')" % - (qtVersionAndNamespace[1], qtVersionAndNamespace[0] or "no namespace")) - except Exception as e: - DumperBase.warn('[lldb] Error detecting Qt version: %s' % e) - - try: - self.fetchInternalFunctions() - self.report('Found function QObject::property: 0x%0x' % self.qtPropertyFunc) - self.report('Found function QObject::customEvent: 0x%0x' % self.qtCustomEventFunc) - except Exception as e: - DumperBase.warn('[lldb] Error fetching internal Qt functions: %s' % e) - - # Cache version information by overriding this function. - self.qtVersionAndNamespace = lambda: qtVersionAndNamespace - return qtVersionAndNamespace - - def qtNamespace(self): - return self.qtVersionAndNamespace()[0] - - def qtVersion(self): - return self.qtVersionAndNamespace()[1] def handleCommand(self, command): result = lldb.SBCommandReturnObject() @@ -830,8 +872,6 @@ class Dumper(DumperBase): #DumperBase.warn('RECURSE PTR') typeobj = self.lookupNativeType(name[:-1].strip()) if typeobj is not None: - #DumperBase.warn('RECURSE RESULT X: %s' % typeobj) - self.fromNativeType(typeobj.GetPointerType()) #DumperBase.warn('RECURSE RESULT: %s' % typeobj.GetPointerType()) return typeobj.GetPointerType() @@ -1289,17 +1329,18 @@ class Dumper(DumperBase): def findSymbol(self, symbolName): return self.target.FindFirstGlobalVariable(symbolName) - def warn(self, msg): - self.put('{name="%s",value="",type="",numchild="0"},' % toCString(msg)) - def fetchVariables(self, args): - (ok, res) = self.tryFetchInterpreterVariables(args) - if ok: - self.reportResult(res, args) - return + start_time = time.perf_counter() + #(ok, res) = self.tryFetchInterpreterVariables(args) + #if ok: + # self.reportResult(res, args) + # return self.setVariableFetchingOptions(args) + self.qtLoaded = True # FIXME: Do that elsewhere + + # Reset certain caches whenever a step over / into / continue # happens. # FIXME: Caches are currently also cleared if currently @@ -1312,6 +1353,8 @@ class Dumper(DumperBase): self.reportResult('error="No frame"', args) return + self.isArmMac = frame.module.triple.startswith('arm64-apple') + self.output = [] isPartial = len(self.partialVariable) > 0 @@ -1358,13 +1401,15 @@ class Dumper(DumperBase): # This can happen for unnamed function parameters with # default values: void foo(int = 0) continue - value = self.fromNativeFrameValue(val) + value = self.fromNativeValue(val) variables.append(value) self.handleLocals(variables) self.handleWatches(args) - self.put('],partial="%d"' % isPartial) + run_time = time.perf_counter() - start_time + + self.put('],partial="%d",runtime="%s"' % (isPartial, run_time)) self.reportResult(self.takeOutput(), args) @@ -1985,14 +2030,14 @@ class Dumper(DumperBase): value = self.hexdecode(args['value']) simpleType = int(args['simpleType']) lhs = self.findValueByExpression(expr) - typeName = lhs.GetType().GetName() - typeName = typeName.replace('::', '__') - pos = typeName.find('<') + type_name = lhs.GetType().GetName() + type_name = type_name.replace('::', '__') + pos = type_name.find('<') if pos != -1: - typeName = typeName[0:pos] - if typeName in self.qqEditable and not simpleType: + type_name = type_name[0:pos] + if type_name in self.qqEditable and not simpleType: expr = self.parseAndEvaluate(expr) - self.qqEditable[typeName](self, expr, value) + self.qqEditable[type_name](self, expr, value) else: self.parseAndEvaluate(expr + '=' + value) self.reportResult(self.describeError(error), args) @@ -2096,10 +2141,10 @@ class Tester(Dumper): if 'QT_CREATOR_LLDB_PROCESS' in os.environ: # Initialize Qt Creator dumper - try: + #try: theDumper = Dumper() - except Exception as error: - print('@\nstate="enginesetupfailed",error="{}"@\n'.format(error)) + #except Exception as error: + # print('@\nstate="enginesetupfailed",error="{}"@\n'.format(error)) # ------------------------------ For use in LLDB ------------------------------ @@ -2305,9 +2350,6 @@ class SummaryProvider(LogMixin): if encoding in text_encodings: try: decodedValue = Dumper.hexdecode(summaryValue, encoding) - # LLDB expects UTF-8 for python 2 - if sys.version_info[0] < 3: - return "\"%s\"" % (decodedValue.encode('utf8')) return '"' + decodedValue + '"' except: return "" % (summaryValue, encoding, sys.exc_info()[1]) diff --git a/share/qtcreator/debugger/qttypes.py b/share/qtcreator/debugger/qttypes.py index 06e7d473254..9f2f1354ce2 100644 --- a/share/qtcreator/debugger/qttypes.py +++ b/share/qtcreator/debugger/qttypes.py @@ -33,7 +33,8 @@ def qedit__QByteArray(d, value, data): def qdump__QByteArray(d, value): - if d.qtVersion() >= 0x60000: + d.qtVersionPing(value.typeid) + if d.qtVersionAtLeast(0x060000): dd, data, length = value.split('ppi') if dd: _, _, alloc = d.split('iii', dd) @@ -76,7 +77,8 @@ def qdump__QByteArray(d, value): def qdump__QBitArray(d, value): - if d.qtVersion() >= 0x60000: + d.qtVersionPing(value.typeid) + if d.qtVersionAtLeast(0x060000): _, data, basize = value.split('ppi') else: data, basize, _ = d.qArrayData(value['d']) @@ -221,24 +223,39 @@ def qdump__Qt__ItemDataRole(d, value): def qdump__QStandardItemData(d, value): - d.createType('@Qt::ItemDataRole') # warm up cache + #d.createType('@Qt::ItemDataRole') # warm up cache role, pad, val = value.split('{@Qt::ItemDataRole}@{@QVariant}') d.putPairContents(role.value(), (role, val), 'role', 'value') def qdump__QStandardItem(d, value): - d.createType('@QStandardItemData') # warm up cache - d.createType('@QStandardItem') - d.createType('@QStandardItem*') + #d.createType('@QStandardItemData') # warm up cache + #d.createType('@QStandardItem') + #d.createType('@QStandardItem*') vtable, dptr = value.split('pp') - if d.qtVersion() >= 0x060000: - model, parent, values, children, rows, cols, item = \ - d.split('pp{@QList<@QStandardItemData>}{@QList<@QStandardItem *>}IIp', dptr) + if d.qtVersionAtLeast(0x060000): + if d.isCdb: + if d.isDebugBuild is None: + try: + value["d_ptr"] + d.isDebugBuild = True + except Exception: + d.isDebugBuild = False + if d.isDebugBuild: + model = value["d_ptr"]["d"]["model"] + values = value["d_ptr"]["d"]["values"] + children = value["d_ptr"]["d"]["children"] + else: + model, parent, values, children, rows, cols, item = \ + d.split('pp{@QList<@QStandardItemData>}{@QList<@QStandardItem *>}IIp', dptr) + else: + model, parent, values, children, rows, cols, item = \ + d.split('pp{@QList<@QStandardItemData>}{@QList<@QStandardItem *>}IIp', dptr) else: # There used to be a virtual destructor that got removed in # 88b6abcebf29b455438 on Apr 18 17:01:22 2017 - if d.qtVersion() < 0x050900 and not d.isMsvcTarget(): + if not d.qtVersionAtLeast(0x050900) and not d.isMsvcTarget(): dptr += d.ptrSize(); model, parent, values, children, rows, cols, item = \ d.split('pp{@QVector<@QStandardItemData>}{@QVector<@QStandardItem *>}IIp', dptr) @@ -247,7 +264,9 @@ def qdump__QStandardItem(d, value): d.putExpandable() if d.isExpanded(): with Children(d): - d.putSubItem('[model]', d.createValue(model, '@QStandardItemModel')) + if isinstance(model, int): # Used as address. + model = d.createValue(model, '@QStandardItemModel') + d.putSubItem('[model]', model) d.putSubItem('[values]', values) d.putSubItem('[children]', children) @@ -266,7 +285,7 @@ def qdump__QDate(d, value): d.enumExpression('DateFormat', 'TextDate')) d.putCallItem('(ISO)', '@QString', value, 'toString', d.enumExpression('DateFormat', 'ISODate')) - if d.qtVersion() < 0x060000: + if not d.qtVersionAtLeast(0x060000): d.putCallItem('(SystemLocale)', '@QString', value, 'toString', d.enumExpression('DateFormat', 'SystemLocaleDate')) d.putCallItem('(Locale)', '@QString', value, 'toString', @@ -286,7 +305,7 @@ def qdump__QTime(d, value): d.enumExpression('DateFormat', 'TextDate')) d.putCallItem('(ISO)', '@QString', value, 'toString', d.enumExpression('DateFormat', 'ISODate')) - if d.canCallLocale() and d.qtVersion() < 0x060000: + if d.canCallLocale() and not d.qtVersionAtLeast(0x060000): d.putCallItem('(SystemLocale)', '@QString', value, 'toString', d.enumExpression('DateFormat', 'SystemLocaleDate')) d.putCallItem('(Locale)', '@QString', value, 'toString', @@ -305,13 +324,12 @@ def qdump__QTimeZone(d, value): def qdump__QDateTime(d, value): - qtVersion = d.qtVersion() isValid = False # This relies on the Qt4/Qt5 internal structure layout: # {sharedref(4), ... base = d.extractPointer(value) is32bit = d.ptrSize() == 4 - if qtVersion >= 0x050200: + if d.qtVersionAtLeast(0x050200): tiVersion = d.qtTypeInfoVersion() #DumperBase.warn('TI VERSION: %s' % tiVersion) if tiVersion is None: @@ -384,9 +402,9 @@ def qdump__QDateTime(d, value): # - [QTime time;] # - - uint mds; # - Spec spec; - dateSize = 8 if qtVersion >= 0x050000 else 4 # Qt5: qint64, Qt4 uint + dateSize = 8 if d.qtVersionAtLeast(0x050000) else 4 # Qt5: qint64, Qt4 uint # 4 byte padding after 4 byte QAtomicInt if we are on 64 bit and QDate is 64 bit - refPlusPadding = 8 if qtVersion >= 0x050000 and d.ptrSize() == 8 else 4 + refPlusPadding = 8 if d.qtVersionAtLeast(0x050000) and d.ptrSize() == 8 else 4 dateBase = base + refPlusPadding timeBase = dateBase + dateSize mds = d.extractInt(timeBase) @@ -410,7 +428,7 @@ def qdump__QDateTime(d, value): d.enumExpression('DateFormat', 'ISODate')) d.putCallItem('toUTC', '@QDateTime', value, 'toTimeSpec', d.enumExpression('TimeSpec', 'UTC')) - if d.qtVersion() < 0x060000: + if not d.qtVersionAtLeast(0x060000): d.putCallItem('(SystemLocale)', '@QString', value, 'toString', d.enumExpression('DateFormat', 'SystemLocaleDate')) d.putCallItem('(Locale)', '@QString', value, 'toString', @@ -549,14 +567,11 @@ def qdump__QDir(d, value): #d.putCallItem('absolutePath', '@QString', value, 'absolutePath') #d.putCallItem('canonicalPath', '@QString', value, 'canonicalPath') with SubItem(d, 'absolutePath'): - typ = d.lookupType(ns + 'QString') - d.putItem(d.createValue(privAddress + absoluteDirEntryOffset, typ)) + d.putItem(d.createValue(privAddress + absoluteDirEntryOffset, '@QString')) with SubItem(d, 'entryInfoList'): - typ = d.lookupType(ns + 'QFileInfo') - qdumpHelper_QList(d, privAddress + fileInfosOffset, typ) + qdumpHelper_QList(d, d.createValue(privAddress + fileInfosOffset, '@QList<@QFileInfo>'), '@QFileInfo') with SubItem(d, 'entryList'): - typ = d.lookupType(ns + 'QStringList') - d.putItem(d.createValue(privAddress + filesOffset, typ)) + d.putItem(d.createValue(privAddress + filesOffset, '@QStringList')) d.putFields(value) @@ -759,7 +774,6 @@ def qdump__QFile(d, value): def qdump__QFileInfo(d, value): privAddress = d.extractPointer(value) #bit32 = d.ptrSize() == 4 - #qt5 = d.qtVersion() >= 0x050000 #try: # d.putStringValue(value['d_ptr']['d'].dereference()['fileNames'][3]) #except: @@ -879,7 +893,7 @@ def qdump__QVariantHash(d, value): def qdumpHelper_QHash(d, value, keyType, valueType): - if d.qtVersion() >= 0x60000: + if d.qtVersionAtLeast(0x060000): qdumpHelper_QHash_6(d, value, keyType, valueType) else: qdumpHelper_QHash_5(d, value, keyType, valueType) @@ -921,7 +935,7 @@ def qdumpHelper_QHash_5(d, value, keyType, valueType): d.putItemCount(size) if d.isExpanded(): - isShort = d.qtVersion() < 0x050000 and keyType.name == 'int' + isShort = not d.qtVersionAtLeast(0x050000) and keyType.name == 'int' with Children(d, size): node = hashDataFirstNode() for i in d.childRange(): @@ -997,7 +1011,7 @@ def qHashIteratorHelper(d, value): if d.isExpanded(): with Children(d): node = d.extractPointer(value) - isShort = d.qtVersion() < 0x050000 and keyType.name == 'int' + isShort = not d.qtVersionAtLeast(0x050000) and keyType.name == 'int' if isShort: typeCode = 'P{%s}@{%s}' % (keyType.name, valueType.name) (pnext, key, padding2, val) = d.split(typeCode, node) @@ -1018,9 +1032,8 @@ def qdump__QHash__iterator(d, value): def qdump__QHostAddress(d, value): dd = d.extractPointer(value) - qtVersion = d.qtVersion() tiVersion = d.qtTypeInfoVersion() - #DumperBase.warn('QT: %x, TI: %s' % (qtVersion, tiVersion)) + #DumperBase.warn('QT: %x, TI: %s' % (d.qtVersion(), tiVersion)) mayNeedParse = True if tiVersion is not None: if tiVersion >= 16: @@ -1035,14 +1048,14 @@ def qdump__QHostAddress(d, value): else: (ipString, scopeId, a4, pad, a6, protocol, isParsed) \ = d.split('{@QString}{@QString}{@quint32}I16sI{bool}', dd) - elif qtVersion >= 0x050600: # 5.6.0 at f3aabb42 + elif d.qtVersionAtLeast(0x050600): # 5.6.0 at f3aabb42 if d.ptrSize() == 8 or d.isWindowsTarget(): (ipString, scopeId, a4, pad, a6, protocol, isParsed) \ = d.split('{@QString}{@QString}{@quint32}I16sI{bool}', dd) else: (ipString, scopeId, a4, a6, protocol, isParsed) \ = d.split('{@QString}{@QString}{@quint32}16sI{bool}', dd) - elif qtVersion >= 0x050000: # 5.2.0 at 62feb088 + elif d.qtVersionAtLeast(0x050000): # 5.2.0 at 62feb088 (ipString, scopeId, a4, a6, protocol, isParsed) \ = d.split('{@QString}{@QString}{@quint32}16sI{bool}', dd) else: # 4.8.7 at b05d05f @@ -1095,18 +1108,20 @@ def qform__QList(): def qdump__QList(d, value): - return qdumpHelper_QList(d, value, d.createType(value.type[0])) + return qdumpHelper_QList(d, value, value.type[0]) def qdump__QVariantList(d, value): - qdumpHelper_QList(d, value, d.createType('@QVariant')) + qdumpHelper_QList(d, value, '@QVariant') -def qdumpHelper_QList(d, value, innerType): +def qdumpHelper_QList(d, value, inner_typish): + innerType = d.createType(inner_typish) data, size = d.listData(value, check=True) d.putItemCount(size) - if d.qtVersion() >= 0x60000: + d.qtVersionPing(value.typeid) + if d.qtVersionAtLeast(0x060000): d.putPlotData(data, size, innerType) return @@ -1147,9 +1162,9 @@ def qform__QImage(): def qdump__QImage(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): vtbl, painters, image_data = value.split('ppp') - elif d.qtVersion() >= 0x050000: + elif d.qtVersionAtLeast(0x050000): vtbl, painters, reserved, image_data = value.split('pppp') else: vtbl, painters, image_data = value.split('ppp') @@ -1163,12 +1178,12 @@ def qdump__QImage(d, value): d.putExpandable() if d.isExpanded(): - if d.qtVersion() < 0x060000: - (ref, width, height, depth, nbytes, pad, devicePixelRatio, colorTable, - bits, iformat) = d.split('iiiii@dppi', image_data) - else: + if d.qtVersionAtLeast(0x060000): (ref, width, height, depth, nbytes, pad, devicePixelRatio, _, _, _, bits, iformat) = d.split('iiiii@dppppi', image_data) + else: + (ref, width, height, depth, nbytes, pad, devicePixelRatio, colorTable, + bits, iformat) = d.split('iiiii@dppi', image_data) with Children(d): d.putIntItem('width', width) d.putIntItem('height', height) @@ -1224,7 +1239,7 @@ def qdump__QLocale(d, value): # index = int(value['d']['d']['m_data']...) #d.check(index >= 0) #d.check(index <= qqLocalesCount) - if d.qtVersion() < 0x50000: + if not d.qtVersionAtLeast(0x50000): d.putStringValue(d.call('const char *', value, 'name')) d.putPlainChildren(value) return @@ -1238,14 +1253,20 @@ def qdump__QLocale(d, value): = d.split('2s{short}2s' + '{@QChar}{@QChar}{short}{@QChar}{@QChar}' + '{@QChar}{@QChar}{@QChar}', data) + + prefix = ns + 'QLocale::' try: - d.putStringValue(d.call('const char *', value, 'name')) + if d.qtVersionAtLeast(0x060700): + res = d.call('const char *', value, 'name', prefix + 'TagSeparator::Underscore') + else: + res = d.call('const char *', value, 'name') + d.putStringValue(res) except: pass + d.putExpandable() if d.isExpanded(): with Children(d): - prefix = ns + 'QLocale::' d.putSubItem('country', d.createValue(countryId, prefix + 'Country')) d.putSubItem('language', d.createValue(languageId, prefix + 'Language')) d.putSubItem('numberOptions', d.createValue(numberOptions, prefix + 'NumberOptions')) @@ -1342,9 +1363,9 @@ def qdump__QMap(d, value): def qdumpHelper_QMap(d, value, keyType, valueType): - if d.qtVersion() >= 0x60000: + if d.qtVersionAtLeast(0x060000): qdumpHelper_Qt6_QMap(d, value, keyType, valueType) - elif d.qtVersion() >= 0x50000: + elif d.qtVersionAtLeast(0x50000): qdumpHelper_Qt5_QMap(d, value, keyType, valueType) else: qdumpHelper_Qt4_QMap(d, value, keyType, valueType) @@ -1364,7 +1385,7 @@ def qdumpHelper_Qt6_QMultiMap(d, value, keyType, valueType): d.putBetterType('@QMultiMap<%s, %s>' % (keyType.name, valueType.name)) def qdump__QMultiMap(d, value): - if d.qtVersion() >= 0x60000: + if d.qtVersionAtLeast(0x060000): qdumpHelper_Qt6_QMultiMap(d, value, value.type[0], value.type[1]) else: qdump__QMap(d, value) @@ -1425,7 +1446,9 @@ if False: d.putSpecialValue('minimumitemcount', 0) -def qdump__QPair(d, value): +# FIXME: Qt 5 +# remvign the _xxxx makes GDB work with Qt 5 but breaks LLDB +def qdump__QPair_xxxx(d, value): typeCode = '{%s}@{%s}' % (value.type[0].name, value.type[1].name) first, pad, second = value.split(typeCode) with Children(d): @@ -1442,9 +1465,9 @@ def qdump__QProcEnvKey(d, value): def qdump__QPixmap(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): vtbl, painters, data = value.split('ppp') - elif d.qtVersion() >= 0x050000: + elif d.qtVersionAtLeast(0x050000): vtbl, painters, reserved, data = s = d.split('pppp', value) else: vtbl, painters, data = value.split('ppp') @@ -1511,15 +1534,15 @@ def qdump__QRegion(d, value): if d_ptr == 0: d.putSpecialValue('empty') else: - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): ref, _, rgn = d.split('i@p', d_ptr) numRects, innerArea, rects, extents, innerRect = \ d.split('ii{@QList<@QRect>}{@QRect}{@QRect}', rgn) - elif d.qtVersion() >= 0x050400: # Padding removed in ee324e4ed + elif d.qtVersionAtLeast(0x050400): # Padding removed in ee324e4ed ref, _, rgn = d.split('i@p', d_ptr) numRects, innerArea, rects, extents, innerRect = \ d.split('ii{@QVector<@QRect>}{@QRect}{@QRect}', rgn) - elif d.qtVersion() >= 0x050000: + elif d.qtVersionAtLeast(0x050000): ref, _, rgn = d.split('i@p', d_ptr) numRects, _, rects, extents, innerRect, innerArea = \ d.split('i@{@QVector<@QRect>}{@QRect}{@QRect}i', rgn) @@ -1557,7 +1580,7 @@ def qdump__QScopedPointer(d, value): def qdump__QSet(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): qdumpHelper_QSet6(d, value) else: qdumpHelper_QSet45(d, value) @@ -1630,7 +1653,7 @@ def qdumpHelper_QSet45(d, value): d.putItemCount(length) if d.isExpanded(): keyType = value.type[0] - isShort = d.qtVersion() < 0x050000 and keyType.name == 'int' + isShort = not d.qtVersionAtLeast(0x050000) and keyType.name == 'int' with Children(d, length, childType=keyType): node = hashDataFirstNode() for i in d.childRange(): @@ -1707,7 +1730,7 @@ def qform__QStack(): def qdump__QStack(d, value): - if d.qtVersion() >= 0x60000: + if d.qtVersionAtLeast(0x060000): qdump__QList(d, value) else: qdump__QVector(d, value) @@ -1727,7 +1750,7 @@ def qdump__QPolygon(d, value): def qdump__QGraphicsPolygonItem(d, value): (vtbl, dptr) = value.split('pp') - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): if d.ptrSize() == 8: offset = 424 # sizeof(QGraphicsPolygonItemPrivate), the base else: @@ -1757,6 +1780,7 @@ def qform__QString(): def qdump__QString(d, value): + d.qtVersionPing(value.typeid) d.putStringValue(value) data, length, _ = d.stringData(value) displayFormat = d.currentItemFormat() @@ -1857,7 +1881,7 @@ def qdump__QStringRef(d, value): def qdump__QStringList(d, value): - qdumpHelper_QList(d, value, d.createType('@QString')) + qdumpHelper_QList(d, value, '@QString') d.putBetterType(value.type) @@ -1917,7 +1941,7 @@ def qdump__QUrl(d, value): d.putValue('') return - if d.qtVersion() < 0x050000: + if not d.qtVersionAtLeast(0x050000): d.call('void', value, 'port') # Warm up internal cache. d.call('void', value, 'path') st = '{@QString}' @@ -2147,7 +2171,8 @@ qdumpHelper_QVariants_F = [ def qdump__QVariant(d, value): - if d.qtVersion() >= 0x060000: + d.qtVersionPing(value.typeid, 2 * d.ptrSize()) + if d.qtVersionAtLeast(0x060000): qdumpHelper__QVariant6(d, value) else: qdumpHelper__QVariant45(d, value) @@ -2201,12 +2226,12 @@ def qdumpHelper__QVariant45(d, value): return None # Extended Core type (Qt 5) - if variantType >= 31 and variantType <= 38 and d.qtVersion() >= 0x050000: + if variantType >= 31 and variantType <= 38 and d.qtVersionAtLeast(0x050000): qdumpHelper_QVariants_D[variantType - 31](d, value) return None # Extended Core type (Qt 4) - if variantType >= 128 and variantType <= 135 and d.qtVersion() < 0x050000: + if variantType >= 128 and variantType <= 135 and not d.qtVersionAtLeast(0x050000): if variantType == 128: d.putBetterType('@QVariant (void *)') d.putValue('0x%x' % value.extractPointer()) @@ -2227,7 +2252,7 @@ def qdumpHelper__QVariant45(d, value): innert = qdumpHelper_QVariants_B[variantType - 7] elif variantType <= 74: innert = qdumpHelper_QVariants_E[variantType - 64] - elif d.qtVersion() < 0x050000: + elif not d.qtVersionAtLeast(0x050000): innert = qdumpHelper_QVariants_F[variantType - 76] else: innert = qdumpHelper_QVariants_F[variantType - 75] @@ -2301,29 +2326,30 @@ def qform__QVector(): def qdump__QVector(d, value): - if d.qtVersion() >= 0x060000: + d.qtVersionPing(value.typeid) + if d.qtVersionAtLeast(0x060000): data, length = d.listData(value) d.putItemCount(length) - d.putPlotData(data, length, d.createType(value.type.ltarget[0])) + d.putPlotData(data, length, value.type.target()[0]) # g++ 9.3 does not add the template parameter list to the debug info. # Fake it for the common case: if value.type.name == d.qtNamespace() + "QVector": - d.putBetterType(value.type.name + '<' + value.type.ltarget[0].name + '>') + d.putBetterType(value.type.name + '<' + value.type.target()[0].name + '>') else: data, length = d.vectorData(value) d.putItemCount(length) - d.putPlotData(data, length, d.createType(value.type[0])) + d.putPlotData(data, length, value.type[0]) if False: def qdump__QObjectConnectionList(d, value): data, length = d.vectorData(value) d.putItemCount(length) - d.putPlotData(data, length, d.createType('@QObjectPrivate::ConnectionList')) + d.putPlotData(data, length, '@QObjectPrivate::ConnectionList') def qdump__QVarLengthArray(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): cap, length, data = value.split('QQp') else: cap, length, data = value.split('iip') @@ -2359,7 +2385,7 @@ def qdump_QWeakPointerHelper(d, value, isWeak, innerType=None): d.putValue('') return - if d.qtVersion() >= 0x050000: + if d.qtVersionAtLeast(0x050000): (weakref, strongref) = d.split('ii', d_ptr) else: (vptr, weakref, strongref) = d.split('pii', d_ptr) @@ -2865,7 +2891,7 @@ def qdump__QJSValue(d, value): if d.ptrSize() == 4: qdump_32__QJSValue(d, value) else: - if d.qtVersion() >= 0x60000: + if d.qtVersionAtLeast(0x060000): qdump_64__QJSValue_6(d, value) else: qdump_64__QJSValue_5(d, value) @@ -2899,7 +2925,7 @@ def qdump_64__QJSValue_6(d, value): if dd == 0: d.putValue('(undefined)') d.putType(value.type.name + ' (undefined)') - if d.qtVersion() < 0x60500: + if not d.qtVersionAtLeast(0x60500): typ = dd >> 47 if typ == 5: d.putValue('(null)') @@ -2913,15 +2939,13 @@ def qdump_64__QJSValue_6(d, value): elif typ > 7: val = d.Value(d) val.ldata = struct.pack('q', dd ^ 0xfffc000000000000) - val._type = d.createType('double') - d.putItem(val) + d.putItem(val.cast('double')) d.putType(value.type.name + ' (double)') elif typ <= 3: # Heap if dd & 1: # String val = d.Value(d) val.ldata = struct.pack('q', dd & ~1) - val._type = d.createType('@QString*') - d.putItem(val) + d.putItem(val.cast('@QString*')) d.putType(value.type.name + ' (QString)') else: # FIXME: Arrays, Objects missing. @@ -2955,16 +2979,13 @@ def qdump_64__QJSValue_6(d, value): val = d.Value(d) val.ldata = struct.pack('q', pointer) if typ == 1: - val._type = d.createType('double*') - d.putItem(val) + d.putItem(val.cast('double*')) d.putType(value.type.name + ' (double)') elif typ == 3: - val._type = d.createType('@QV4::Value*') - d.putItem(val) + d.putItem(val.cast('@QV4::Value*')) d.putType(value.type.name + ' (QV4::Value)') elif typ == 5: - val._type = d.createType('@QString*') - d.putItem(val) + d.putItem(val.cast('@QString*')) d.putType(value.type.name + ' (QString)') else: @@ -3324,7 +3345,7 @@ def qdumpHelper_QJsonObject(d, data, obj): def qdump__QJsonValue(d, value): (data, dd, t) = value.split('QpI') - if d.qtVersion() >= 0x050f00: + if d.qtVersionAtLeast(0x050f00): value = d.createProxyValue((data, dd, t, False), 'QCborValue_proxy') d.putItem(value) return @@ -3359,13 +3380,13 @@ def qdump__QJsonValue(d, value): def qdump__QJsonArray(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): dptr = d.extractPointer(value) if not dptr: d.putItemCount(0) else: qdumpHelper_QCbor_array(d, dptr, False) - elif d.qtVersion() >= 0x050f00: + elif d.qtVersionAtLeast(0x050f00): _, container_ptr = value.split('pp') qdumpHelper_QCbor_array(d, container_ptr, False) else: @@ -3373,13 +3394,13 @@ def qdump__QJsonArray(d, value): def qdump__QJsonObject(d, value): - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): dptr = d.extractPointer(value) if not dptr: d.putItemCount(0) else: qdumpHelper_QCbor_map(d, dptr, False) - elif d.qtVersion() >= 0x050f00: + elif d.qtVersionAtLeast(0x050f00): _, container_ptr = value.split('pp') qdumpHelper_QCbor_map(d, container_ptr, False) else: @@ -3454,15 +3475,15 @@ def qdump__qfloat16(d, value): def qdumpHelper_QCbor_string(d, container_ptr, element_index, is_bytes): # d.split('i@{@QByteArray::size_type}pp', container_ptr) doesn't work with CDB, # so be explicit: - data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersion() >= 0x060000 else 8) - elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersion() >= 0x060000 else d.ptrSize()) + data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else 8) + elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else d.ptrSize()) elements_data_ptr, elements_size = d.vectorData(elements_pos) element_at_n_addr = elements_data_ptr + element_index * 16 # sizeof(QtCbor::Element) == 16 element_value, _, element_flags = d.split('qII', element_at_n_addr) enc = 'latin1' if is_bytes or (element_flags & 8) else 'utf16' bytedata, _, _ = d.qArrayData(data_pos) bytedata += element_value - if d.qtVersion() >= 0x060000: + if d.qtVersionAtLeast(0x060000): bytedata_len = d.extractInt64(bytedata) bytedata_data = bytedata + 8 else: @@ -3491,8 +3512,8 @@ def qdumpHelper_QCbor_array(d, container_ptr, is_cbor): return # d.split('i@{@QByteArray::size_type}pp', container_ptr) doesn't work with CDB, # so be explicit: - data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersion() >= 0x060000 else 8) - elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersion() >= 0x060000 else d.ptrSize()) + data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else 8) + elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else d.ptrSize()) elements_data_ptr, elements_size = d.vectorData(elements_pos) d.putItemCount(elements_size) if d.isExpanded(): @@ -3513,8 +3534,8 @@ def qdumpHelper_QCbor_map(d, container_ptr, is_cbor): return # d.split('i@{@QByteArray::size_type}pp', container_ptr) doesn't work with CDB, # so be explicit: - data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersion() >= 0x060000 else 8) - elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersion() >= 0x060000 else d.ptrSize()) + data_pos = container_ptr + (2 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else 8) + elements_pos = data_pos + (3 * d.ptrSize() if d.qtVersionAtLeast(0x060000) else d.ptrSize()) elements_data_ptr, elements_size = d.vectorData(elements_pos) elements_size = int(elements_size / 2) d.putItemCount(elements_size) @@ -3538,7 +3559,7 @@ def qdump__QCborValue(d, value): d.putPlainChildren(value) def qdump__QCborValue_proxy(d, value): - item_data, container_ptr, item_type, is_cbor = value.data() + item_data, container_ptr, item_type, is_cbor = value.ldata def typename(key, is_cbor): if is_cbor: 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) diff --git a/share/qtcreator/debugger/visualize.py b/share/qtcreator/debugger/visualize.py new file mode 100644 index 00000000000..578d3bb7050 --- /dev/null +++ b/share/qtcreator/debugger/visualize.py @@ -0,0 +1,86 @@ +# Copyright(C) 2006-2008, David Allouche, Jp Calderone, Itamar Shtull-Trauring +# Copyright(C) 2006-2017, Johan Dahlin +# Copyright(C) 2008, Olivier Grisel +# Copyright(C) 2008, David Glick +# Copyright(C) 2013, Steven Maude +# Copyright(C) 2013-2018, Peter Waller +# Copyright(C) 2013, Lukas Graf +# Copyright(C) 2013, Jamie Wong +# Copyright(C) 2013, Yury V. Zaytsev +# Copyright(C) 2014, Michael Droettboom +# Copyright(C) 2015, Zev Benjamin +# Copyright(C) 2018, Jon Dufresne +# +# All rights reserved. +# +# 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 is a stripped down and modified version of pyprof2calltree """ + +def profile_visualize(entries): + import cProfile + import io + import subprocess + import tempfile + from collections import defaultdict + + def add_code_by_position(code): + filename, _, name = cProfile.label(code) + code_by_position[(filename, name)].add(code) + + def munged_function_name(code): + filename, firstlineno, name = cProfile.label(code) + if len(code_by_position[(filename, name)]) == 1: + return name + return "%s:%d" % (name, firstlineno) + + code_by_position = defaultdict(set) + for entry in entries: + add_code_by_position(entry.code) + if entry.calls: + for subentry in entry.calls: + add_code_by_position(subentry.code) + + fd, outfile = tempfile.mkstemp("-qtc-debugger-profile.txt") + with io.open(fd, "w") as out: + scale = 1e9 + + out.write('event: ns : Nanoseconds\n') + out.write('events: ns\n') + + for entry in entries: + code = entry.code + + filename, firstlineno, name = cProfile.label(code) + munged_name = munged_function_name(code) + + out.write('fl=%s\nfn=%s\n' % (filename, munged_name)) + out.write('%d %d\n' % (firstlineno, int(entry.inlinetime * scale))) + + if entry.calls: + for subentry in entry.calls: + filename, firstlineno, name = cProfile.label(subentry.code) + munged_name = munged_function_name(subentry.code) + out.write('cfl=%s\ncfn=%s\n' % (filename, munged_name)) + out.write('calls=%d %d\n' % (subentry.callcount, firstlineno)) + out.write('%d %d\n' % (firstlineno, int(subentry.totaltime * scale))) + out.write('\n') + + subprocess.Popen(["kcachegrind", outfile]) + diff --git a/share/qtcreator/jsonschemas/project.json b/share/qtcreator/jsonschemas/project.json new file mode 100644 index 00000000000..df55dbd693a --- /dev/null +++ b/share/qtcreator/jsonschemas/project.json @@ -0,0 +1,57 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Qt Creator workspace project definition", + "description": "A Qt Creator workspace project definition", + "type": "object", + "properties": { + "project.name": { + "type": "string", + "description": "The name of the project" + }, + "files.exclude": { + "type": "array", + "items": [ + { + "type": "string" + } + ], + "description": "Files to exclude from the project" + }, + "targets": { + "type": "array", + "description": "A list of targets", + "items": [ + { + "type": "object", + "properties": { + "arguments": { + "type": "array", + "items": [ + { + "type": "string" + } + ], + "description": "Arguments to pass to the executable" + }, + "executable": { + "type": "string", + "description": "The executable to run" + }, + "name": { + "type": "string", + "description": "The name of the target" + }, + "workingDirectory": { + "type": "string", + "description": "The working directory to run the executable in" + } + }, + "required": [ + "executable", + "name" + ] + } + ] + } + } +} diff --git a/share/qtcreator/lua-plugins/luals/init.lua b/share/qtcreator/lua-plugins/luals/init.lua new file mode 100644 index 00000000000..e7bc13629cc --- /dev/null +++ b/share/qtcreator/lua-plugins/luals/init.lua @@ -0,0 +1,235 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local LSP = require('LSP') +local mm = require('MessageManager') +local Utils = require('Utils') +local S = require('Settings') +local Gui = require('Gui') +local a = require('async') +local fetch = require('Fetch').fetch +local Install = require('Install') + +Settings = {} + +local function createCommand() + local cmd = { Settings.binary.expandedValue:nativePath() } + if Settings.showNode.value then + table.insert(cmd, '--shownode=true') + end + if Settings.showSource.value then + table.insert(cmd, '--showsource=true') + end + if Settings.developMode.value then + table.insert(cmd, '--develop=true') + end + + return cmd +end +local function filter(tbl, callback) + for i = #tbl, 1, -1 do + if not callback(tbl[i]) then + table.remove(tbl, i) + end + end +end + +local function installOrUpdateServer() + local data = a.wait(fetch({ + url = "https://qtccache.qt.io/LuaLanguageServer/LatestRelease", + convertToTable = true + })) + + if type(data) == "table" and #data > 0 then + local r = data[1] + local lspPkgInfo = Install.packageInfo("lua-language-server") + if not lspPkgInfo or lspPkgInfo.version ~= r.tag_name then + local osTr = { mac = "darwin", windows = "win32", linux = "linux" } + local archTr = { unknown = "", x86 = "ia32", x86_64 = "x64", itanium = "", arm = "", arm64 = "arm64" } + local os = osTr[Utils.HostOsInfo.os] + local arch = archTr[Utils.HostOsInfo.architecture] + + local expectedFileName = "lua-language-server-" .. r.tag_name .. "-" .. os .. "-" .. arch + + filter(r.assets, function(asset) + return string.find(asset.name, expectedFileName, 1, true) == 1 + end) + + if #r.assets == 0 then + print("No assets found for this platform") + return + end + local res, err = a.wait(Install.install( + "Do you want to install the lua-language-server?", { + name = "lua-language-server", + url = r.assets[1].browser_download_url, + version = r.tag_name + })) + + if not res then + mm.writeFlashing("Failed to install lua-language-server: " .. err) + return + end + + lspPkgInfo = Install.packageInfo("lua-language-server") + print("Installed:", lspPkgInfo.name, "version:", lspPkgInfo.version, "at", lspPkgInfo.path) + end + + local binary = "bin/lua-language-server" + if Utils.HostOsInfo.isWindowsHost() then + binary = "bin/lua-language-server.exe" + end + + Settings.binary:setValue(lspPkgInfo.path:resolvePath(binary)) + Settings:apply() + return + end + + if type(data) == "string" then + print("Failed to fetch:", data) + else + print("No lua-language-server release found.") + end +end +IsTryingToInstall = false + +local function setupClient() + Client = LSP.Client.create({ + name = 'Lua Language Server', + cmd = createCommand, + transport = 'stdio', + languageFilter = { + patterns = { '*.lua' }, + mimeTypes = { 'text/x-lua' } + }, + settings = Settings, + startBehavior = "RequiresFile", + onStartFailed = function() + a.sync(function() + if IsTryingToInstall == true then + mm.writeFlashing("RECURSION!"); + return + end + IsTryingToInstall = true + installOrUpdateServer() + IsTryingToInstall = false + end)() + end + }) + + Client.on_instance_start = function() + print("Instance has started") + end + + Client:registerMessage("$/status/report", function(params) + mm.writeFlashing(params.params.text .. ": " .. params.params.tooltip); + end) +end + +local function using(tbl) + local result = _G + for k, v in pairs(tbl) do result[k] = v end + return result +end +local function layoutSettings() + --- "using namespace Gui" + local _ENV = using(Gui) + + local layout = Form { + Settings.binary, br, + Settings.developMode, br, + Settings.showSource, br, + Settings.showNode, br, + Row { + PushButton { + text = "Update Lua Language Server", + onClicked = function() a.sync(installOrUpdateServer)() end, + }, + st + } + } + return layout +end + +local function binaryFromPkg() + local lspPkgInfo = Install.packageInfo("lua-language-server") + if lspPkgInfo then + local binary = "bin/lua-language-server" + if Utils.HostOsInfo.isWindowsHost() then + binary = "bin/lua-language-server.exe" + end + local binaryPath = lspPkgInfo.path:resolvePath(binary) + if binaryPath:isExecutableFile() == true then + return binaryPath + end + end + + return nil +end + +local function findBinary() + local binary = binaryFromPkg() + if binary then + return binary + end + + -- Search for the binary in the PATH + local serverPath = Utils.FilePath.fromUserInput("lua-language-server") + local absolute = a.wait(serverPath:searchInPath()):resolveSymlinks() + if absolute:isExecutableFile() == true then + return absolute + end + return serverPath +end + +local function setupAspect() + ---@class Settings: AspectContainer + Settings = S.AspectContainer.create({ + autoApply = false, + layouter = layoutSettings, + }); + + Settings.binary = S.FilePathAspect.create({ + settingsKey = "LuaCopilot.Binary", + displayName = "Binary", + labelText = "Binary:", + toolTip = "The path to the lua-language-server binary.", + expectedKind = S.Kind.ExistingCommand, + defaultPath = findBinary(), + }) + + Settings.developMode = S.BoolAspect.create({ + settingsKey = "LuaCopilot.DevelopMode", + displayName = "Enable Develop Mode", + labelText = "Enable Develop Mode:", + toolTip = "Turns on the develop mode of the language server.", + defaultValue = false, + labelPlacement = S.LabelPlacement.InExtraLabel, + }) + + Settings.showSource = S.BoolAspect.create({ + settingsKey = "LuaCopilot.ShowSource", + displayName = "Show Source", + labelText = "Show Source:", + toolTip = "Display the internal data of the hovering token.", + defaultValue = false, + labelPlacement = S.LabelPlacement.InExtraLabel, + }) + + Settings.showNode = S.BoolAspect.create({ + settingsKey = "LuaCopilot.ShowNode", + displayName = "Show Node", + labelText = "Show Node:", + toolTip = "Display the internal data of the hovering token.", + defaultValue = false, + labelPlacement = S.LabelPlacement.InExtraLabel, + }) + return Settings +end +local function setup(parameters) + setupAspect() + setupClient() +end + +return { + setup = function() a.sync(setup)() end, +} diff --git a/share/qtcreator/lua-plugins/luals/luals.lua b/share/qtcreator/lua-plugins/luals/luals.lua new file mode 100644 index 00000000000..5a68388dd06 --- /dev/null +++ b/share/qtcreator/lua-plugins/luals/luals.lua @@ -0,0 +1,23 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +return { + Name = "LuaLanguageServer", + Version = "1.0.0", + CompatVersion = "1.0.0", + Vendor = "The Qt Company", + Category = "Language Client", + Description = "The Lua Language Server", + Experimental = false, + DisabledByDefault = false, + LongDescription = [[ +This plugin provides the Lua Language Server. +It will try to install it if it is not found. + ]], + Dependencies = { + { Name = "Lua", Version = "14.0.0" }, + { Name = "LuaLanguageClient", Version = "14.0.0" } + }, + setup = function() + require 'init'.setup() + end, +} --[[@as QtcPlugin]] diff --git a/share/qtcreator/lua-plugins/luatests/INSPECT-LICENSE.txt b/share/qtcreator/lua-plugins/luatests/INSPECT-LICENSE.txt new file mode 100644 index 00000000000..6149bd7823f --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/INSPECT-LICENSE.txt @@ -0,0 +1,22 @@ +MIT LICENSE + +Copyright (c) 2022 Enrique García Cota + +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/share/qtcreator/lua-plugins/luatests/guidemo.lua b/share/qtcreator/lua-plugins/luatests/guidemo.lua new file mode 100644 index 00000000000..2771529f87a --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/guidemo.lua @@ -0,0 +1,23 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +local Utils = require("Utils") +local Gui = require("Gui") + +local function using(tbl) + local result = _G + for k, v in pairs(tbl) do result[k] = v end + return result +end + +local function show() + --- "using namespace Gui" + local _ENV = using(Gui) + + Widget { + size = { 400, 300 }, + Row { "Hello World!" }, + }:show() +end + +return show diff --git a/share/qtcreator/lua-plugins/luatests/inspect.lua b/share/qtcreator/lua-plugins/luatests/inspect.lua new file mode 100644 index 00000000000..9900a0b81b9 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/inspect.lua @@ -0,0 +1,371 @@ +local _tl_compat; if (tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3 then local p, m = pcall(require, 'compat53.module'); if p then _tl_compat = m end end; local math = _tl_compat and _tl_compat.math or math; local string = _tl_compat and _tl_compat.string or string; local table = _tl_compat and _tl_compat.table or table +local inspect = {Options = {}, } + + + + + + + + + + + + + + + + + +inspect._VERSION = 'inspect.lua 3.1.0' +inspect._URL = 'http://github.com/kikito/inspect.lua' +inspect._DESCRIPTION = 'human-readable representations of tables' +inspect._LICENSE = [[ + MIT LICENSE + + Copyright (c) 2022 Enrique García Cota + + 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. +]] +inspect.KEY = setmetatable({}, { __tostring = function() return 'inspect.KEY' end }) +inspect.METATABLE = setmetatable({}, { __tostring = function() return 'inspect.METATABLE' end }) + +local tostring = tostring +local rep = string.rep +local match = string.match +local char = string.char +local gsub = string.gsub +local fmt = string.format + +local _rawget +if rawget then + _rawget = rawget +else + _rawget = function(t, k) return t[k] end +end + +local function rawpairs(t) + return next, t, nil +end + + + +local function smartQuote(str) + if match(str, '"') and not match(str, "'") then + return "'" .. str .. "'" + end + return '"' .. gsub(str, '"', '\\"') .. '"' +end + + +local shortControlCharEscapes = { + ["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", + ["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v", ["\127"] = "\\127", +} +local longControlCharEscapes = { ["\127"] = "\127" } +for i = 0, 31 do + local ch = char(i) + if not shortControlCharEscapes[ch] then + shortControlCharEscapes[ch] = "\\" .. i + longControlCharEscapes[ch] = fmt("\\%03d", i) + end +end + +local function escape(str) + return (gsub(gsub(gsub(str, "\\", "\\\\"), + "(%c)%f[0-9]", longControlCharEscapes), + "%c", shortControlCharEscapes)) +end + +local luaKeywords = { + ['and'] = true, + ['break'] = true, + ['do'] = true, + ['else'] = true, + ['elseif'] = true, + ['end'] = true, + ['false'] = true, + ['for'] = true, + ['function'] = true, + ['goto'] = true, + ['if'] = true, + ['in'] = true, + ['local'] = true, + ['nil'] = true, + ['not'] = true, + ['or'] = true, + ['repeat'] = true, + ['return'] = true, + ['then'] = true, + ['true'] = true, + ['until'] = true, + ['while'] = true, +} + +local function isIdentifier(str) + return type(str) == "string" and + not not str:match("^[_%a][_%a%d]*$") and + not luaKeywords[str] +end + +local flr = math.floor +local function isSequenceKey(k, sequenceLength) + return type(k) == "number" and + flr(k) == k and + 1 <= (k) and + k <= sequenceLength +end + +local defaultTypeOrders = { + ['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4, + ['function'] = 5, ['userdata'] = 6, ['thread'] = 7, +} + +local function sortKeys(a, b) + local ta, tb = type(a), type(b) + + + if ta == tb and (ta == 'string' or ta == 'number') then + return (a) < (b) + end + + local dta = defaultTypeOrders[ta] or 100 + local dtb = defaultTypeOrders[tb] or 100 + + + return dta == dtb and ta < tb or dta < dtb +end + +local function getKeys(t) + + local seqLen = 1 + while _rawget(t, seqLen) ~= nil do + seqLen = seqLen + 1 + end + seqLen = seqLen - 1 + + local keys, keysLen = {}, 0 + for k in rawpairs(t) do + if not isSequenceKey(k, seqLen) then + keysLen = keysLen + 1 + keys[keysLen] = k + end + end + table.sort(keys, sortKeys) + return keys, keysLen, seqLen +end + +local function countCycles(x, cycles) + if type(x) == "table" then + if cycles[x] then + cycles[x] = cycles[x] + 1 + else + cycles[x] = 1 + for k, v in rawpairs(x) do + countCycles(k, cycles) + countCycles(v, cycles) + end + countCycles(getmetatable(x), cycles) + end + end +end + +local function makePath(path, a, b) + local newPath = {} + local len = #path + for i = 1, len do newPath[i] = path[i] end + + newPath[len + 1] = a + newPath[len + 2] = b + + return newPath +end + + +local function processRecursive(process, + item, + path, + visited) + if item == nil then return nil end + if visited[item] then return visited[item] end + + local processed = process(item, path) + if type(processed) == "table" then + local processedCopy = {} + visited[item] = processedCopy + local processedKey + + for k, v in rawpairs(processed) do + processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited) + if processedKey ~= nil then + processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited) + end + end + + local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited) + if type(mt) ~= 'table' then mt = nil end + setmetatable(processedCopy, mt) + processed = processedCopy + end + return processed +end + +local function puts(buf, str) + buf.n = buf.n + 1 + buf[buf.n] = str +end + + + +local Inspector = {} + + + + + + + + + + +local Inspector_mt = { __index = Inspector } + +local function tabify(inspector) + puts(inspector.buf, inspector.newline .. rep(inspector.indent, inspector.level)) +end + +function Inspector:getId(v) + local id = self.ids[v] + local ids = self.ids + if not id then + local tv = type(v) + id = (ids[tv] or 0) + 1 + ids[v], ids[tv] = id, id + end + return tostring(id) +end + +function Inspector:putValue(v) + local buf = self.buf + local tv = type(v) + if tv == 'string' then + puts(buf, smartQuote(escape(v))) + elseif tv == 'number' or tv == 'boolean' or tv == 'nil' or + tv == 'cdata' or tv == 'ctype' then + puts(buf, tostring(v)) + elseif tv == 'table' and not self.ids[v] then + local t = v + + if t == inspect.KEY or t == inspect.METATABLE then + puts(buf, tostring(t)) + elseif self.level >= self.depth then + puts(buf, '{...}') + else + if self.cycles[t] > 1 then puts(buf, fmt('<%d>', self:getId(t))) end + + local keys, keysLen, seqLen = getKeys(t) + + puts(buf, '{') + self.level = self.level + 1 + + for i = 1, seqLen + keysLen do + if i > 1 then puts(buf, ',') end + if i <= seqLen then + puts(buf, ' ') + self:putValue(t[i]) + else + local k = keys[i - seqLen] + tabify(self) + if isIdentifier(k) then + puts(buf, k) + else + puts(buf, "[") + self:putValue(k) + puts(buf, "]") + end + puts(buf, ' = ') + self:putValue(t[k]) + end + end + + local mt = getmetatable(t) + if type(mt) == 'table' then + if seqLen + keysLen > 0 then puts(buf, ',') end + tabify(self) + puts(buf, ' = ') + self:putValue(mt) + end + + self.level = self.level - 1 + + if keysLen > 0 or type(mt) == 'table' then + tabify(self) + elseif seqLen > 0 then + puts(buf, ' ') + end + + puts(buf, '}') + end + + else + puts(buf, fmt('<%s %d>', tv, self:getId(v))) + end +end + + + + +function inspect.inspect(root, options) + options = options or {} + + local depth = options.depth or (math.huge) + local newline = options.newline or '\n' + local indent = options.indent or ' ' + local process = options.process + + if process then + root = processRecursive(process, root, {}, {}) + end + + local cycles = {} + countCycles(root, cycles) + + local inspector = setmetatable({ + buf = { n = 0 }, + ids = {}, + cycles = cycles, + depth = depth, + level = 0, + newline = newline, + indent = indent, + }, Inspector_mt) + + inspector:putValue(root) + + return table.concat(inspector.buf) +end + +setmetatable(inspect, { + __call = function(_, root, options) + return inspect.inspect(root, options) + end, +}) + +return inspect diff --git a/share/qtcreator/lua-plugins/luatests/luatests.lua b/share/qtcreator/lua-plugins/luatests/luatests.lua new file mode 100644 index 00000000000..e85f0d95278 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/luatests.lua @@ -0,0 +1,20 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +return { + Name = "LuaTests", + Version = "1.0.0", + CompatVersion = "1.0.0", + Vendor = "The Qt Company", + Category = "Tests", + DisabledByDefault = true, + Experimental = true, + Description = "This plugin tests the Lua API.", + LongDescription = [[ + It has tests for (almost) all functionality exposed by the API. + ]], + Dependencies = { + { Name = "Lua", Version = "14.0.0" } + }, + setup = function() require 'tests'.setup() end, + printToOutputPane = true, +} --[[@as QtcPlugin]] diff --git a/share/qtcreator/lua-plugins/luatests/qtctest.lua b/share/qtcreator/lua-plugins/luatests/qtctest.lua new file mode 100644 index 00000000000..3914979d554 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/qtctest.lua @@ -0,0 +1,32 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local inspect = require('inspect') + +local function traceback() + local result = "" + local level = 1 + while true do + local info = debug.getinfo(level, "Sl") + if not info then break end + if info.what ~= "C" then + ---Get the last part of the path in info.source + local fileName = info.source:match("^.+/(.+)$") + result = result .. (string.format(" %s:%d\n", fileName, info.currentline)) + end + level = level + 1 + end + return result +end + +local function compare(actual, expected) + if (actual == expected) then + return true + end + + error("Compared values were not the same.\n Actual: " .. + inspect(actual) .. "\n Expected: " .. inspect(expected) .. "\nTrace:\n" .. traceback()) +end + +return { + compare = compare, +} diff --git a/share/qtcreator/lua-plugins/luatests/tests.lua b/share/qtcreator/lua-plugins/luatests/tests.lua new file mode 100644 index 00000000000..213aff47ebf --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/tests.lua @@ -0,0 +1,82 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local Utils = require("Utils") +local Action = require("Action") +local a = require("async") + + +local function script_path() + local str = debug.getinfo(2, "S").source:sub(2) + return str +end + +local function printResults(results) + print("Passed:", results.passed) + print("Failed:", results.failed) + for index, value in ipairs(results.failedTests) do + print("Failed test:", value.name, value.error) + end +end + +local function runTest(testFile, results) + local testScript, err = loadfile(testFile:nativePath()) + if not testScript then + print("Failed to load test:", testFile, err) + return + end + + local ok, testFunctions = pcall(testScript) + if not ok then + print("Failed to run test:", testFile, testFunctions) + return + end + + for k, v in pairs(testFunctions) do + print("* " .. testFile:fileName() .. " : " .. k) + local ok, res_or_error = pcall(v) + + if ok then + results.passed = results.passed + 1 + else + results.failed = results.failed + 1 + table.insert(results.failedTests, { name = testFile:fileName() .. ":" .. k, error = res_or_error }) + end + end +end + +local function runTests() + local results = { + passed = 0, + failed = 0, + failedTests = {} + } + + local testDir = Utils.FilePath.fromUserInput(script_path()):parentDir() + local tests = a.wait(testDir:dirEntries({ nameFilters = { "tst_*.lua" } })) + for _, testFile in ipairs(tests) do + runTest(testFile, results) + end + printResults(results) +end + +local function setup() + Action.create("LuaTests.run", { + text = "Run lua tests", + onTrigger = function() a.sync(runTests)() end, + }) + Action.create("LuaTests.layoutDemo", { + text = "Lua Layout Demo", + onTrigger = function() + local script, err = loadfile(Utils.FilePath.fromUserInput(script_path()):parentDir():resolvePath( + "guidemo.lua"):nativePath()) + if not script then + print("Failed to load demo:", err) + return + end + + script()() + end, + }) +end + +return { setup = setup } diff --git a/share/qtcreator/lua-plugins/luatests/tst_aspectcontainer.lua b/share/qtcreator/lua-plugins/luatests/tst_aspectcontainer.lua new file mode 100644 index 00000000000..f948583e1c1 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/tst_aspectcontainer.lua @@ -0,0 +1,32 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +T = require("qtctest") +local S = require('Settings') + +local function testAutoApply() + local container = S.AspectContainer.create({ autoApply = true }) + + container.test = S.BoolAspect.create({ defaultValue = true }) + T.compare(container.test.value, true) + container.test.volatileValue = false + T.compare(container.test.volatileValue, false) + T.compare(container.test.value, false) +end + +local function testNoAutoApply() + local container = S.AspectContainer.create({ autoApply = false }) + + container.test = S.BoolAspect.create({ defaultValue = true }) + T.compare(container.test.value, true) + container.test.volatileValue = false + T.compare(container.test.volatileValue, false) + T.compare(container.test.value, true) + container:apply() + T.compare(container.test.volatileValue, false) + T.compare(container.test.value, false) +end + +return { + testAutoApply = testAutoApply, + testNoAutoApply = testNoAutoApply, +} diff --git a/share/qtcreator/lua-plugins/luatests/tst_fetch.lua b/share/qtcreator/lua-plugins/luatests/tst_fetch.lua new file mode 100644 index 00000000000..55a8d1773b4 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/tst_fetch.lua @@ -0,0 +1,38 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local T = require("qtctest") +local fetch = require("Fetch").fetch +local inspect = require('inspect') +local a = require("async") +local string = require("string") + +local function testFetch() + local r = a.wait(fetch({ url = "https://dummyjson.com/products", convertToTable = true })) + local y = a.wait(fetch({ url = "https://dummyjson.com/products", convertToTable = true })) + T.compare(type(r), "table") + T.compare(type(y), "table") +end + +local function testGoogle() + local r = a.wait(fetch({ url = "https://www.google.com" })) + T.compare(r.error, 0) + print(r) +end + +local function fetchTwo() + local r = a.wait_all { + fetch({ url = "https://dummyjson.com/products", convertToTable = true }), + fetch({ url = "https://www.google.com" }), + } + + T.compare(type(r), "table") + T.compare(#r, 2) + T.compare(type(r[1]), "table") + T.compare(r[2].error, 0) +end + +return { + testFetch = testFetch, + testGoogle = testGoogle, + testFetchTwo = fetchTwo +} diff --git a/share/qtcreator/lua-plugins/luatests/tst_utils.lua b/share/qtcreator/lua-plugins/luatests/tst_utils.lua new file mode 100644 index 00000000000..940f6ff7e97 --- /dev/null +++ b/share/qtcreator/lua-plugins/luatests/tst_utils.lua @@ -0,0 +1,34 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local T = require("qtctest") +local a = require('async') +local Utils = require('Utils') +local Qt = require('Qt') + +local function testDirEntries() + local u = require("Utils") + local d = u.FilePath.currentWorkingPath() + print("CWD:", d) + local result = a.wait(d:dirEntries({})) + print("RESULT:", result, #result) +end + +local function testSearchInPath() + local u = require("Utils") + local d = u.FilePath.fromUserInput('hostname') + local result = a.wait(d:searchInPath()) + print("Hostname found at:", result) +end + +local function testWaitMs() + local u = require("Utils") + print("Starting to wait ...") + a.wait(u.waitms(1000)) + print("About a second should have elapsed now.") +end + +return { + testDirEntries = testDirEntries, + testSearchInPath = testSearchInPath, + testWaitMs = testWaitMs, +} diff --git a/share/qtcreator/lua-plugins/rustls/init.lua b/share/qtcreator/lua-plugins/rustls/init.lua new file mode 100644 index 00000000000..fcfd4954fef --- /dev/null +++ b/share/qtcreator/lua-plugins/rustls/init.lua @@ -0,0 +1,196 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +local LSP = require('LSP') +local mm = require('MessageManager') +local Utils = require('Utils') +local Process = require('Process') +local S = require('Settings') +local Gui = require('Gui') +local a = require('async') +local fetch = require('Fetch').fetch +local Install = require('Install') + +Settings = {} + +local function createCommand() + local cmd = { Settings.binary.expandedValue:nativePath() } + return cmd +end + +local function filter(tbl, callback) + for i = #tbl, 1, -1 do + if not callback(tbl[i]) then + table.remove(tbl, i) + end + end +end + +local function installOrUpdateServer() + local data = a.wait(fetch({ + url = "https://qtccache.qt.io/RustLanguageServer/LatestReleases", + convertToTable = true, + })) + + if type(data) == "table" and #data > 1 then + local r = data[1] + if r.prerelease then + r = data[2] + end + local lspPkgInfo = Install.packageInfo("rust-analyzer") + if not lspPkgInfo or lspPkgInfo.version ~= r.tag_name then + local osTr = { mac = "apple-darwin", windows = "pc-windows-msvc", linux = "unknown-linux-gnu" } + local archTr = { unknown = "", x86 = "", x86_64 = "x86_64", itanium = "", arm = "", arm64 = "aarch64" } + local extTr = { mac = "gz", windows = "zip", linux = "gz" } + local os = osTr[Utils.HostOsInfo.os] + local arch = archTr[Utils.HostOsInfo.architecture] + local ext = extTr[Utils.HostOsInfo.os] + + local expectedFileName = "rust-analyzer-" .. arch .. "-" .. os .. "." .. ext + + filter(r.assets, function(asset) + return string.find(asset.name, expectedFileName, 1, true) == 1 + end) + + if #r.assets == 0 then + print("No assets found for this platform") + return + end + local res, err = a.wait(Install.install( + "Do you want to install the rust-analyzer?", { + name = "rust-analyzer", + url = r.assets[1].browser_download_url, + version = r.tag_name + })) + + if not res then + mm.writeFlashing("Failed to install rust-analyzer: " .. err) + return + end + + lspPkgInfo = Install.packageInfo("rust-analyzer") + print("Installed:", lspPkgInfo.name, "version:", lspPkgInfo.version, "at", lspPkgInfo.path) + end + + local binary = "rust-analyzer" + if Utils.HostOsInfo.isWindowsHost() then + binary = "rust-analyzer.exe" + end + + Settings.binary:setValue(lspPkgInfo.path:resolvePath(binary)) + Settings:apply() + return + end + + if type(data) == "string" then + print("Failed to fetch:", data) + else + print("No rust-analyzer release found.") + end +end +IsTryingToInstall = false + +local function setupClient() + Client = LSP.Client.create({ + name = 'Rust Language Server', + cmd = createCommand, + transport = 'stdio', + languageFilter = { + patterns = { '*.rs' }, + mimeTypes = { 'text/rust' } + }, + settings = Settings, + startBehavior = "RequiresProject", + onStartFailed = function() + a.sync(function() + if IsTryingToInstall == true then + return + end + IsTryingToInstall = true + installOrUpdateServer() + IsTryingToInstall = false + end)() + end + }) +end + +local function using(tbl) + local result = _G + for k, v in pairs(tbl) do result[k] = v end + return result +end +local function layoutSettings() + --- "using namespace Gui" + local _ENV = using(Gui) + + local layout = Form { + Settings.binary, br, + Row { + PushButton { + text = "Try to install Rust language server", + onClicked = function() a.sync(installOrUpdateServer)() end, + br, + }, + st + } + } + + return layout +end + +local function binaryFromPkg() + local lspPkgInfo = Install.packageInfo("rust-analyzer") + if lspPkgInfo then + local binary = "rust-analyzer" + if Utils.HostOsInfo.isWindowsHost() then + binary = "rust-analyzer.exe" + end + local binaryPath = lspPkgInfo.path:resolvePath(binary) + if binaryPath:isExecutableFile() == true then + return binaryPath + end + end + + return nil +end + +local function findBinary() + local binary = binaryFromPkg() + if binary then + return binary + end + + -- Search for the binary in the PATH + local serverPath = Utils.FilePath.fromUserInput("rust-analyzer") + local absolute = a.wait(serverPath:searchInPath()):resolveSymlinks() + if absolute:isExecutableFile() == true then + return absolute + end + return serverPath +end +local function setupAspect() + ---@class Settings: AspectContainer + Settings = S.AspectContainer.create({ + autoApply = false, + layouter = layoutSettings, + }); + + Settings.binary = S.FilePathAspect.create({ + settingsKey = "Rustls.Binary", + displayName = "Binary", + labelText = "Binary:", + toolTip = "The path to the rust analyzer binary.", + expectedKind = S.Kind.ExistingCommand, + defaultPath = findBinary(), + }) + + return Settings +end + +local function setup(parameters) + setupAspect() + setupClient() +end + +return { + setup = function() a.sync(setup)() end, +} diff --git a/share/qtcreator/lua-plugins/rustls/rustls.lua b/share/qtcreator/lua-plugins/rustls/rustls.lua new file mode 100644 index 00000000000..7e0056de25f --- /dev/null +++ b/share/qtcreator/lua-plugins/rustls/rustls.lua @@ -0,0 +1,23 @@ +-- Copyright (C) 2024 The Qt Company Ltd. +-- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +return { + Name = "RustLanguageServer", + Version = "1.0.0", + CompatVersion = "1.0.0", + Vendor = "The Qt Company", + Category = "Language Client", + Description = "The Rust Language Server", + Experimental = false, + DisabledByDefault = false, + LongDescription = [[ +This plugin provides the Rust Language Server. +It will try to install it if it is not found. + ]], + Dependencies = { + { Name = "Lua", Version = "14.0.0" }, + { Name = "LuaLanguageClient", Version = "14.0.0" } + }, + setup = function() + require 'init'.setup() + end, +} --[[@as QtcPlugin]] diff --git a/share/qtcreator/lua-plugins/tellajoke/tellajoke.lua b/share/qtcreator/lua-plugins/tellajoke/tellajoke.lua new file mode 100644 index 00000000000..58d07e0b178 --- /dev/null +++ b/share/qtcreator/lua-plugins/tellajoke/tellajoke.lua @@ -0,0 +1,56 @@ +--- Copyright (C) 2024 The Qt Company Ltd. +--- SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +local function fetchJoke() + print("Fetching ...") + + local a = require("async") + local fetch = require("Fetch").fetch + local utils = require("Utils") + local mm = require("MessageManager") + + local r = a.wait(fetch({ url = "https://official-joke-api.appspot.com/random_joke", convertToTable = true })) + if (type(r) == "table") then + mm.writeDisrupting(r.setup) + a.wait(utils.waitms(1000)) + mm.writeSilently(".") + a.wait(utils.waitms(1000)) + mm.writeSilently(".") + a.wait(utils.waitms(1000)) + mm.writeSilently(".") + a.wait(utils.waitms(1000)) + mm.writeDisrupting(r.punchline) + else + print("echo Error fetching: " .. r) + end +end + +local function fetchJokeSafe() + local ok, err = pcall(fetchJoke) + if not ok then + print("echo Error fetching: " .. err) + end +end + +local function setup() + local a = require("async") + Action = require("Action") + Action.create("Simple.joke", { + text = "Tell a joke", + onTrigger = function() a.sync(fetchJokeSafe)() end, + defaultKeySequences = { "Meta+Ctrl+Shift+J", "Ctrl+Shift+Alt+J" }, + }) +end + +return { + Name = "Tell A Joke", + Version = "1.0.0", + CompatVersion = "1.0.0", + Vendor = "The Qt Company", + Category = "Fun", + Description = "This plugin adds an action that tells a joke.", + Dependencies = { + { Name = "Lua", Version = "14.0.0" }, + }, + setup = setup, +} --[[@as QtcPlugin]] diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/QtQuick/AdvancedSection.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/QtQuick/AdvancedSection.qml index f88defbff56..1b626623ead 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/QtQuick/AdvancedSection.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/QtQuick/AdvancedSection.qml @@ -33,7 +33,7 @@ Section { PropertyLabel { text: qsTr("Smooth") - tooltip: qsTr("Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. ") + tooltip: qsTr("Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items.") blockedByTemplate: !backendValues.smooth.isAvailable } diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/qmldir b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/qmldir old mode 100755 new mode 100644 diff --git a/share/qtcreator/templates/wizards/autotest/files/tst.txt b/share/qtcreator/templates/wizards/autotest/files/tst.txt index f0eeb813392..18653bdc32c 100644 --- a/share/qtcreator/templates/wizards/autotest/files/tst.txt +++ b/share/qtcreator/templates/wizards/autotest/files/tst.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(%{TestCaseName} LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/codesnippet/CMakeLists.txt b/share/qtcreator/templates/wizards/codesnippet/CMakeLists.txt index 0e923c87945..b411048ef28 100644 --- a/share/qtcreator/templates/wizards/codesnippet/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/codesnippet/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} VERSION 0.1 LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/files/form/wizard.json b/share/qtcreator/templates/wizards/files/form/wizard.json index ec5fd422a36..d0d826b6c6d 100644 --- a/share/qtcreator/templates/wizards/files/form/wizard.json +++ b/share/qtcreator/templates/wizards/files/form/wizard.json @@ -3,8 +3,8 @@ "supportedProjectTypes": [ ], "id": "D.Form", "category": "R.Qt", - "trDescription": "Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic.", - "trDisplayName": "Qt Designer Form", + "trDescription": "Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic.", + "trDisplayName": "Qt Widgets Designer Form", "trDisplayCategory": "Qt", "iconText": "ui", "enabled": "%{JS: value('Plugins').indexOf('Designer') >= 0}", diff --git a/share/qtcreator/templates/wizards/projects/consoleapp/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/consoleapp/CMakeLists.txt index a6f956127dd..d548d199a3c 100644 --- a/share/qtcreator/templates/wizards/projects/consoleapp/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/consoleapp/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/projects/consoleapp/main.cpp b/share/qtcreator/templates/wizards/projects/consoleapp/main.cpp index 3609b36c4e1..356f567b8c3 100644 --- a/share/qtcreator/templates/wizards/projects/consoleapp/main.cpp +++ b/share/qtcreator/templates/wizards/projects/consoleapp/main.cpp @@ -22,5 +22,16 @@ int main(int argc, char *argv[]) } @endif + // Set up code that uses the Qt event loop here. + // Call a.quit() or a.exit() to quit the application. + // A not very useful example would be including + // #include + // near the top of the file and calling + // QTimer::singleShot(5000, &a, &QCoreApplication::quit); + // which quits the application after 5 seconds. + + // If you do not need a running Qt event loop, remove the call + // to a.exec() or use the Non-Qt Plain C++ Application template. + return a.exec(); } diff --git a/share/qtcreator/templates/wizards/projects/cpplibrary/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/cpplibrary/CMakeLists.txt index 4391af9678c..ef67bd5f7ad 100644 --- a/share/qtcreator/templates/wizards/projects/cpplibrary/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/cpplibrary/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/projects/plainc/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/plainc/CMakeLists.txt index 1a0a570e66f..bc89ded9d0b 100644 --- a/share/qtcreator/templates/wizards/projects/plainc/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/plainc/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} LANGUAGES C) diff --git a/share/qtcreator/templates/wizards/projects/plaincpp/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/plaincpp/CMakeLists.txt index df5ef8a5cce..e8ba55ff43d 100644 --- a/share/qtcreator/templates/wizards/projects/plaincpp/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/plaincpp/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/projects/qtforpythonapplication/widget/wizard.json b/share/qtcreator/templates/wizards/projects/qtforpythonapplication/widget/wizard.json index c52c05c12cb..6d3f968c1bf 100644 --- a/share/qtcreator/templates/wizards/projects/qtforpythonapplication/widget/wizard.json +++ b/share/qtcreator/templates/wizards/projects/qtforpythonapplication/widget/wizard.json @@ -3,7 +3,7 @@ "supportedProjectTypes": [ "PythonProject" ], "id": "F.QtForPythonApplicationWindowWidget", "category": "F.ApplicationPySide", - "trDescription": "Creates a Qt for Python application that includes a Qt Designer-based widget (ui file). Requires .ui to Python conversion.", + "trDescription": "Creates a Qt for Python application that includes a Qt Widgets Designer-based widget (ui file). Requires .ui to Python conversion.", "trDisplayName": "Window UI", "trDisplayCategory": "Application (Qt for Python)", "icon": "../icons/icon.png", diff --git a/share/qtcreator/templates/wizards/projects/qtquick2-extension/wizard.json b/share/qtcreator/templates/wizards/projects/qtquick2-extension/wizard.json index 0164a9f3d57..d12edc4576d 100644 --- a/share/qtcreator/templates/wizards/projects/qtquick2-extension/wizard.json +++ b/share/qtcreator/templates/wizards/projects/qtquick2-extension/wizard.json @@ -23,8 +23,8 @@ { "key": "ObjectHdr", "value": "%{JS: Cpp.classToFileName(value('ObjectName'), Util.preferredSuffix('text/x-c++hdr'))}" }, { "key": "ObjectQml", "value": "%{JS: Util.fileName(value('ObjectName') + 'Controls', 'qml')}" }, { "key": "PluginName", "value": "%{JS: value('ProjectName').charAt(0).toUpperCase() + value('ProjectName').slice(1) + 'Plugin' }" }, - { "key": "PLUGINGUARD", "value": "%{JS: Cpp.classToHeaderGuard(value('PluginBaseFileName'), Util.preferredSuffix('text/x-c++hdr'))}" }, - { "key": "OBJECTGUARD", "value": "%{JS: Cpp.classToHeaderGuard(value('ObjectName'), Util.preferredSuffix('text/x-c++hdr'))}" }, + { "key": "PLUGINGUARD", "value": "%{JS: Cpp.headerGuard(value('PluginHdr'))}" }, + { "key": "OBJECTGUARD", "value": "%{JS: Cpp.headerGuard(value('ObjectHdr'))}" }, { "key": "IsQt6", "value": "%{JS: value('QtVersion').IsQt6}" }, { "key": "QtQuickVersion", "value": "%{JS: value('QtVersion').QtQuickVersion}" }, { "key": "QtQuickFeature", "value": "%{JS: (value('QtQuickVersion')=='') ? 'QtSupport.Wizards.FeatureQt.6.2' : 'QtSupport.Wizards.FeatureQtQuick.%{QtQuickVersion}'}" }, diff --git a/share/qtcreator/templates/wizards/projects/qtquickapplication/wizard.json b/share/qtcreator/templates/wizards/projects/qtquickapplication/wizard.json index 2e885c2bb63..a41ee12e516 100644 --- a/share/qtcreator/templates/wizards/projects/qtquickapplication/wizard.json +++ b/share/qtcreator/templates/wizards/projects/qtquickapplication/wizard.json @@ -87,7 +87,7 @@ { "trKey": "Qt 6.4", "value": "6.4" }, { "trKey": "Qt 6.5", "value": "6.5" } ], - "index": 1 + "index": 2 } } ] diff --git a/share/qtcreator/templates/wizards/projects/qtquickapplication_compat/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/qtquickapplication_compat/CMakeLists.txt index b7afb831a77..de5e6850c23 100644 --- a/share/qtcreator/templates/wizards/projects/qtquickapplication_compat/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/qtquickapplication_compat/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} VERSION 0.1 LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/CMakeLists.txt b/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/CMakeLists.txt index 9d854899c36..d2ca81d463b 100644 --- a/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) project(%{ProjectName} VERSION 0.1 LANGUAGES CXX) diff --git a/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/wizard.json b/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/wizard.json index 098cb4f0ec0..48791e4fd87 100644 --- a/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/wizard.json +++ b/share/qtcreator/templates/wizards/projects/qtwidgetsapplication/wizard.json @@ -3,7 +3,7 @@ "supportedProjectTypes": [ "MesonProjectManager.MesonProject","CMakeProjectManager.CMakeProject", "Qt4ProjectManager.Qt4Project", "Qbs.QbsProject" ], "id": "C.QtWidgets", "category": "D.ApplicationQt", - "trDescription": "Creates a widget-based Qt application that contains a Qt Designer-based main window and C++ source and header files to implement the application logic.\n\nPreselects a desktop Qt for building the application if available.", + "trDescription": "Creates a widget-based Qt application that contains a Qt Widgets Designer-based main window and C++ source and header files to implement the application logic.\n\nPreselects a desktop Qt for building the application if available.", "trDisplayName": "Qt Widgets Application", "trDisplayCategory": "Application (Qt)", "icon": "../../global/guiapplication.png", diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/CMakeLists.txt b/share/qtcreator/templates/wizards/qtcreatorplugin/CMakeLists.txt index be6f16a3fb6..283ebad166a 100644 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/CMakeLists.txt +++ b/share/qtcreator/templates/wizards/qtcreatorplugin/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.16) # Remove when sharing with others. @if %{JS: Util.isDirectory('%{QtCreatorBuild}/Qt Creator.app/Contents/Resources')} @@ -16,11 +16,12 @@ project(%{PluginName}) 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) find_package(QtCreator REQUIRED COMPONENTS Core) -find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets) -set(QtX Qt${QT_VERSION_MAJOR}) +find_package(Qt6 COMPONENTS Widgets REQUIRED) # Add a CMake option that enables building your plugin with tests. # You don't want your released plugin binaries to contain tests, @@ -30,7 +31,7 @@ option(WITH_TESTS "Builds with tests" NO) if(WITH_TESTS) # Look for QtTest - find_package(${QtX} REQUIRED COMPONENTS Test) + find_package(Qt6 REQUIRED COMPONENTS Test) # Tell CMake functions like add_qtc_plugin about the QtTest component. set(IMPLICIT_DEPENDS Qt::Test) @@ -43,7 +44,7 @@ add_qtc_plugin(%{PluginName} PLUGIN_DEPENDS QtCreator::Core DEPENDS - ${QtX}::Widgets + Qt::Widgets QtCreator::ExtensionSystem QtCreator::Utils SOURCES @@ -51,8 +52,6 @@ add_qtc_plugin(%{PluginName} .github/workflows/README.md README.md %{SrcFileName} - %{HdrFileName} - %{GlobalHdrFileName} %{ConstantsHdrFileName} %{TrHdrFileName} ) diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/github_workflows_build_cmake.yml b/share/qtcreator/templates/wizards/qtcreatorplugin/github_workflows_build_cmake.yml index d69cbfae59a..d5e53f033b5 100644 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/github_workflows_build_cmake.yml +++ b/share/qtcreator/templates/wizards/qtcreatorplugin/github_workflows_build_cmake.yml @@ -7,13 +7,16 @@ env: QT_VERSION: %{JS: Util.qtVersion()} QT_CREATOR_VERSION: %{JS: Util.qtCreatorVersion()} QT_CREATOR_SNAPSHOT: NO - CMAKE_VERSION: 3.21.1 - NINJA_VERSION: 1.10.1 + MACOS_DEPLOYMENT_TARGET: "11.0" + CMAKE_VERSION: "3.29.6" + NINJA_VERSION: "1.12.1" jobs: build: name: ${{ matrix.config.name }} runs-on: ${{ matrix.config.os }} + outputs: + tag: ${{ steps.git.outputs.tag }} strategy: matrix: config: @@ -29,13 +32,22 @@ jobs: cc: "gcc", cxx: "g++" } - { - name: "macOS Latest Clang", artifact: "macOS-x64", + name: "macOS Latest Clang", artifact: "macOS-universal", os: macos-latest, cc: "clang", cxx: "clang++" } steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Checkout submodules + id: git + shell: cmake -P {0} + run: | + if (${{github.ref}} MATCHES "tags/v(.*)") + file(APPEND "$ENV{GITHUB_OUTPUT}" "tag=${CMAKE_MATCH_1}\\n") + else() + file(APPEND "$ENV{GITHUB_OUTPUT}" "tag=${{github.run_id}}\\n") + endif() - name: Download Ninja and CMake shell: cmake -P {0} @@ -107,17 +119,21 @@ jobs: set(url_os "windows_x86") set(qt_package_arch_suffix "win64_msvc2019_64") set(qt_dir_prefix "${qt_version}/msvc2019_64") - set(qt_package_suffix "-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64") + set(qt_package_suffix "-Windows-Windows_10_22H2-MSVC2019-Windows-Windows_10_22H2-X86_64") elseif ("${{ runner.os }}" STREQUAL "Linux") set(url_os "linux_x64") - set(qt_package_arch_suffix "gcc_64") + if (qt_version VERSION_LESS "6.7.0") + set(qt_package_arch_suffix "gcc_64") + else() + set(qt_package_arch_suffix "linux_gcc_64") + endif() set(qt_dir_prefix "${qt_version}/gcc_64") - set(qt_package_suffix "-Linux-RHEL_8_4-GCC-Linux-RHEL_8_4-X86_64") + set(qt_package_suffix "-Linux-RHEL_8_8-GCC-Linux-RHEL_8_8-X86_64") elseif ("${{ runner.os }}" STREQUAL "macOS") set(url_os "mac_x64") set(qt_package_arch_suffix "clang_64") set(qt_dir_prefix "${qt_version}/macos") - set(qt_package_suffix "-MacOS-MacOS_12-Clang-MacOS-MacOS_12-X86_64-ARM64") + set(qt_package_suffix "-MacOS-MacOS_13-Clang-MacOS-MacOS_13-X86_64-ARM64") endif() set(qt_base_url "https://download.qt.io/online/qtsdkrepository/${url_os}/desktop/qt6_${qt_version_dotless}") @@ -154,10 +170,15 @@ jobs: ) endforeach() - # uic depends on libicu56.so + # uic depends on libicu*.so if ("${{ runner.os }}" STREQUAL "Linux") + if (qt_version VERSION_LESS "6.7.0") + set(uic_suffix "Rhel7.2-x64") + else() + set(uic_suffix "Rhel8.6-x86_64") + endif() downloadAndExtract( - "${qt_base_url}/qt.qt6.${qt_version_dotless}.${qt_package_arch_suffix}/${qt_package_version}icu-linux-Rhel7.2-x64.7z" + "${qt_base_url}/qt.qt6.${qt_version_dotless}.${qt_package_arch_suffix}/${qt_package_version}icu-linux-${uic_suffix}.7z" icu.7z ) endif() @@ -202,7 +223,7 @@ jobs: run: | set(ENV{CC} ${{ matrix.config.cc }}) set(ENV{CXX} ${{ matrix.config.cxx }}) - set(ENV{MACOSX_DEPLOYMENT_TARGET} "10.13") + set(ENV{MACOSX_DEPLOYMENT_TARGET} "${{ env.MACOS_DEPLOYMENT_TARGET }}") if ("${{ runner.os }}" STREQUAL "Windows" AND NOT "x${{ matrix.config.environment_script }}" STREQUAL "x") execute_process( @@ -218,6 +239,9 @@ jobs: endif() set(ENV{NINJA_STATUS} "[%f/%t %o/sec] ") + if ("${{ runner.os }}" STREQUAL "macOS") + set(ENV{CMAKE_OSX_ARCHITECTURES} "x86_64;arm64") + endif() set(build_plugin_py "scripts/build_plugin.py") foreach(dir "share/qtcreator/scripts" "Qt Creator.app/Contents/Resources/scripts" "Contents/Resources/scripts") @@ -246,8 +270,8 @@ jobs: message(FATAL_ERROR "Build failed") endif() - - uses: actions/upload-artifact@v3 - id: upload_artifact + - name: Upload + uses: actions/upload-artifact@v4 with: path: ./${{ env.PLUGIN_NAME }}-${{ env.QT_CREATOR_VERSION }}-${{ matrix.config.artifact }}.7z name: ${{ env.PLUGIN_NAME}}-${{ env.QT_CREATOR_VERSION }}-${{ matrix.config.artifact }}.7z @@ -258,72 +282,23 @@ jobs: needs: build steps: + - name: Download artifacts + uses: actions/download-artifact@v4 + with: + path: release-with-dirs + + - name: Fixup artifacts + run: | + mkdir release + mv release-with-dirs/*/* release/ + - name: Create Release id: create_release - uses: actions/create-release@v1 + uses: softprops/action-gh-release@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - tag_name: ${{ github.ref }} - release_name: Release ${{ github.ref }} + tag_name: v${{ needs.build.outputs.tag }} + files: release/* draft: false prerelease: false - - - name: Store Release url - run: | - echo "${{ steps.create_release.outputs.upload_url }}" > ./upload_url - - - uses: actions/upload-artifact@v3 - with: - path: ./upload_url - name: upload_url - - publish: - if: contains(github.ref, 'tags/v') - - name: ${{ matrix.config.name }} - runs-on: ${{ matrix.config.os }} - strategy: - matrix: - config: - - { - name: "Windows Latest x64", artifact: "Windows-x64.7z", - os: ubuntu-latest - } - - { - name: "Linux Latest x64", artifact: "Linux-x64.7z", - os: ubuntu-latest - } - - { - name: "macOS Latest x64", artifact: "macOS-x64.7z", - os: macos-latest - } - needs: release - - steps: - - name: Download artifact - uses: actions/download-artifact@v3 - with: - name: ${{ env.PLUGIN_NAME }}-${{ env.QT_CREATOR_VERSION }}-${{ matrix.config.artifact }} - path: ./ - - - name: Download URL - uses: actions/download-artifact@v3 - with: - name: upload_url - path: ./ - - id: set_upload_url - run: | - upload_url=`cat ./upload_url` - echo upload_url=$upload_url >> $GITHUB_OUTPUT - - - name: Upload to Release - id: upload_to_release - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.set_upload_url.outputs.upload_url }} - asset_path: ./${{ env.PLUGIN_NAME }}-${{ env.QT_CREATOR_VERSION }}-${{ matrix.config.artifact }} - asset_name: ${{ env.PLUGIN_NAME }}-${{ env.QT_CREATOR_VERSION }}-${{ matrix.config.artifact }} - asset_content_type: application/x-7z-compressed diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.cpp b/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.cpp index c6724f1b0a8..d045fd19bb1 100644 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.cpp +++ b/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.cpp @@ -1,78 +1,89 @@ %{Cpp:LicenseTemplate}\ -#include "%{HdrFileName}" #include "%{ConstantsHdrFileName}" #include "%{TrHdrFileName}" -#include -#include +#include #include #include -#include #include +#include +#include + +#include #include -#include #include #include +#include namespace %{PluginName}::Internal { -%{CN}::%{CN}() +class %{CN} : public ExtensionSystem::IPlugin { - // Create your members -} + Q_OBJECT + Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "%{PluginName}.json") -%{CN}::~%{CN}() -{ - // Unregister objects from the plugin manager's object pool - // Delete members -} +public: + %{CN}() + { + // Create your members + } -void %{CN}::initialize() -{ - // Register objects in the plugin manager's object pool - // Load settings - // Add actions to menus - // Connect to other plugins' signals - // In the initialize function, a plugin can be sure that the plugins it - // depends on have initialized their members. + ~%{CN}() final + { + // Unregister objects from the plugin manager's object pool + // Delete members + } - // If you need access to command line arguments or to report errors, use the - // bool IPlugin::initialize(const QStringList &arguments, QString *errorString) - // overload. + void initialize() final + { + // Register objects in the plugin manager's object pool + // Load settings + // Add actions to menus + // Connect to other plugins' signals + // In the initialize function, a plugin can be sure that the plugins it + // depends on have initialized their members. - auto action = new QAction(Tr::tr("%{PluginName} Action"), this); - Core::Command *cmd = Core::ActionManager::registerAction(action, Constants::ACTION_ID, - Core::Context(Core::Constants::C_GLOBAL)); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Meta+A"))); - connect(action, &QAction::triggered, this, &%{CN}::triggerAction); + // If you need access to command line arguments or to report errors, use the + // bool IPlugin::initialize(const QStringList &arguments, QString *errorString) + // overload. - Core::ActionContainer *menu = Core::ActionManager::createMenu(Constants::MENU_ID); - menu->menu()->setTitle(Tr::tr("%{PluginName}")); - menu->addAction(cmd); - Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu); -} + auto action = new QAction(Tr::tr("%{PluginName} Action"), this); + Core::Command *cmd = Core::ActionManager::registerAction( + action, Constants::ACTION_ID, Core::Context(Core::Constants::C_GLOBAL)); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+Meta+A"))); + connect(action, &QAction::triggered, this, &%{CN}::triggerAction); -void %{CN}::extensionsInitialized() -{ - // Retrieve objects from the plugin manager's object pool - // In the extensionsInitialized function, a plugin can be sure that all - // plugins that depend on it are completely initialized. -} + Core::ActionContainer *menu = Core::ActionManager::createMenu(Constants::MENU_ID); + menu->menu()->setTitle(Tr::tr("%{PluginName}")); + menu->addAction(cmd); + Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu); + } -ExtensionSystem::IPlugin::ShutdownFlag %{CN}::aboutToShutdown() -{ - // Save settings - // Disconnect from signals that are not needed during shutdown - // Hide UI (if you add UI that is not in the main window directly) - return SynchronousShutdown; -} + void extensionsInitialized() final + { + // Retrieve objects from the plugin manager's object pool + // In the extensionsInitialized function, a plugin can be sure that all + // plugins that depend on it are completely initialized. + } -void %{CN}::triggerAction() -{ - QMessageBox::information(Core::ICore::mainWindow(), - Tr::tr("Action Triggered"), - Tr::tr("This is an action from %{PluginName}.")); -} + ShutdownFlag aboutToShutdown() final + { + // Save settings + // Disconnect from signals that are not needed during shutdown + // Hide UI (if you add UI that is not in the main window directly) + return SynchronousShutdown; + } + +private: + void triggerAction() + { + QMessageBox::information(Core::ICore::mainWindow(), + Tr::tr("Action Triggered"), + Tr::tr("This is an action from %{PluginName}.")); + } +}; } // namespace %{PluginName}::Internal + +#include <%{MocFileName}> diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.h b/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.h deleted file mode 100644 index 6e1fad933c0..00000000000 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin.h +++ /dev/null @@ -1,27 +0,0 @@ -%{Cpp:LicenseTemplate}\ -#pragma once - -#include "%{GlobalHdrFileName}" - -#include - -namespace %{PluginName}::Internal { - -class %{CN} : public ExtensionSystem::IPlugin -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "%{PluginName}.json") - -public: - %{CN}(); - ~%{CN}() override; - - void initialize() override; - void extensionsInitialized() override; - ShutdownFlag aboutToShutdown() override; - -private: - void triggerAction(); -}; - -} // namespace %{PluginName}::Internal diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin_global.h b/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin_global.h deleted file mode 100644 index a81c8fcee0d..00000000000 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/myplugin_global.h +++ /dev/null @@ -1,10 +0,0 @@ -%{Cpp:LicenseTemplate}\ -#pragma once - -#include - -#if defined(%{LibraryDefine}) -# define %{LibraryExport} Q_DECL_EXPORT -#else -# define %{LibraryExport} Q_DECL_IMPORT -#endif diff --git a/share/qtcreator/templates/wizards/qtcreatorplugin/wizard.json b/share/qtcreator/templates/wizards/qtcreatorplugin/wizard.json index e1feaa53bbb..0ac4d29ae23 100644 --- a/share/qtcreator/templates/wizards/qtcreatorplugin/wizard.json +++ b/share/qtcreator/templates/wizards/qtcreatorplugin/wizard.json @@ -19,8 +19,7 @@ { "key": "LibraryDefine", "value": "%{JS: Cpp.headerGuard(value('PluginName')) + '_LIBRARY'}" }, { "key": "LibraryExport", "value": "%{JS: Cpp.headerGuard(value('PluginName')) + '_EXPORT'}" }, { "key": "SrcFileName", "value": "%{JS: Util.fileName(value('PluginNameLower'), Util.preferredSuffix('text/x-c++src'))}" }, - { "key": "HdrFileName", "value": "%{JS: Util.fileName(value('PluginNameLower'), Util.preferredSuffix('text/x-c++hdr'))}" }, - { "key": "GlobalHdrFileName", "value": "%{JS: Util.fileName(value('PluginNameLower') + '_global', Util.preferredSuffix('text/x-c++hdr'))}" }, + { "key": "MocFileName", "value": "%{JS: Util.fileName(value('PluginNameLower'), 'moc')}" }, { "key": "ConstantsHdrFileName", "value": "%{JS: Util.fileName(value('PluginNameLower') + 'constants', Util.preferredSuffix('text/x-c++hdr'))}" }, { "key": "TrHdrFileName", "value": "%{JS: Util.fileName(value('PluginNameLower') + 'tr', Util.preferredSuffix('text/x-c++hdr'))}" }, { "key": "CN", "value": "%{JS: Cpp.className(value('PluginName') + 'Plugin')}" }, @@ -170,14 +169,6 @@ "source": "myplugin.cpp", "target": "%{SrcFileName}" }, - { - "source": "myplugin.h", - "target": "%{HdrFileName}" - }, - { - "source": "myplugin_global.h", - "target": "%{GlobalHdrFileName}" - }, { "source": "mypluginconstants.h", "target": "%{ConstantsHdrFileName}" diff --git a/share/qtcreator/themes/dark.creatortheme b/share/qtcreator/themes/dark.creatortheme index c2846fa0940..463204fd513 100644 --- a/share/qtcreator/themes/dark.creatortheme +++ b/share/qtcreator/themes/dark.creatortheme @@ -502,7 +502,6 @@ DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=true DrawToolBarBorders=false -ApplyThemePaletteGlobally=true FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=true diff --git a/share/qtcreator/themes/dark.figmatokens b/share/qtcreator/themes/dark.figmatokens index 194ce7fab25..d65ae21fa3f 100644 --- a/share/qtcreator/themes/dark.figmatokens +++ b/share/qtcreator/themes/dark.figmatokens @@ -36,3 +36,8 @@ Token_Notification_Alert=ffc98014 Token_Notification_Success=ff1f9b5d Token_Notification_Neutral=ff016876 Token_Notification_Danger=ffb22245 + +Token_Gradient01_Start=ff016876 +Token_Gradient01_End=ff1F9B5D +Token_Gradient02_Start=ff3A3A3A +Token_Gradient02_End=ff838383 diff --git a/share/qtcreator/themes/default.creatortheme b/share/qtcreator/themes/default.creatortheme index f2c4c7f7a43..e6cdab1bc30 100644 --- a/share/qtcreator/themes/default.creatortheme +++ b/share/qtcreator/themes/default.creatortheme @@ -1,5 +1,5 @@ [General] -Includes=light.figmatokens +Includes=light.figmatokens, light-palette.inc ThemeName=Classic PreferredStyles= @@ -465,13 +465,12 @@ TerminalAnsi15=e5e5e6 [Flags] ComboBoxDrawTextShadow=true -DerivePaletteFromTheme=false +DerivePaletteFromThemeIfNeeded=true DrawIndicatorBranch=false DrawSearchResultWidgetFrame=true DrawTargetSelectorBottom=true DrawToolBarHighlights=true DrawToolBarBorders=false -ApplyThemePaletteGlobally=false FlatToolBars=false FlatSideBarIcons=false FlatProjectsMode=false diff --git a/share/qtcreator/themes/design-light.creatortheme b/share/qtcreator/themes/design-light.creatortheme index 41a9f07ba84..5271d5fc57a 100644 --- a/share/qtcreator/themes/design-light.creatortheme +++ b/share/qtcreator/themes/design-light.creatortheme @@ -513,7 +513,6 @@ DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=false DrawToolBarBorders=true -ApplyThemePaletteGlobally=true FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=false diff --git a/share/qtcreator/themes/design.creatortheme b/share/qtcreator/themes/design.creatortheme index 11022bd7e5d..874c5116e03 100644 --- a/share/qtcreator/themes/design.creatortheme +++ b/share/qtcreator/themes/design.creatortheme @@ -562,7 +562,6 @@ DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=false DrawToolBarBorders=false -ApplyThemePaletteGlobally=true FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=true diff --git a/share/qtcreator/themes/flat-dark.creatortheme b/share/qtcreator/themes/flat-dark.creatortheme index 9737e9cd53e..bdf46614b05 100644 --- a/share/qtcreator/themes/flat-dark.creatortheme +++ b/share/qtcreator/themes/flat-dark.creatortheme @@ -506,7 +506,6 @@ DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=false DrawToolBarBorders=false -ApplyThemePaletteGlobally=true FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=true diff --git a/share/qtcreator/themes/flat-light.creatortheme b/share/qtcreator/themes/flat-light.creatortheme index 1ff8a7a3ff4..a85d3654d88 100644 --- a/share/qtcreator/themes/flat-light.creatortheme +++ b/share/qtcreator/themes/flat-light.creatortheme @@ -1,25 +1,28 @@ [General] -Includes=light.figmatokens +Includes=light.figmatokens, light-palette.inc ThemeName=Flat Light PreferredStyles= [Palette] -shadowBackground=ffe4e4e4 -text=ff000000 -textDisabled=55000000 +shadowBackground=PaletteDark +text=PaletteWindowText +textDisabled=PaletteTextDisabled toolBarItem=a0010508 toolBarItemDisabled=38000000 fancyBarsNormalTextColor=ff000000 fancyBarsBoldTextColor=a0010508 hoverBackground=1a000000 selectedBackground=a8ffffff -normalBackground=ffffffff -alternateBackground=ff515151 +normalBackground=PaletteWindow +alternateBackground=PaletteAlternateBase stop_error=ffec7373 run_success=ff52c23b splitter=ffbdbebf error=ffdf4f4f warning=ffecbc1c +textColorLink=PaletteLink +textColorLinkVisited=PaletteLinkVisited +backgroundColorDisabled=PaletteWindowDisabled qmlDesignerButtonColor=fff8f8f8 ;DS Theme Palette START @@ -474,13 +477,12 @@ TerminalAnsi15=e5e5e6 [Flags] ComboBoxDrawTextShadow=false -DerivePaletteFromTheme=false +DerivePaletteFromThemeIfNeeded=true DrawIndicatorBranch=true DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=false DrawToolBarBorders=true -ApplyThemePaletteGlobally=false FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=false diff --git a/share/qtcreator/themes/flat.creatortheme b/share/qtcreator/themes/flat.creatortheme index f479077889e..7fd222e168a 100644 --- a/share/qtcreator/themes/flat.creatortheme +++ b/share/qtcreator/themes/flat.creatortheme @@ -1,23 +1,26 @@ [General] -Includes=light.figmatokens +Includes=light.figmatokens, light-palette.inc ThemeName=Flat PreferredStyles= [Palette] shadowBackground=ff404142 -text=ff000000 -textDisabled=55000000 +text=PaletteWindowText +textDisabled=PaletteTextDisabled toolBarItem=bcfbfdff toolBarItemDisabled=56a5a6a7 fancyBarsNormalTextColor=ffffffff fancyBarsBoldTextColor=b6fbfdff hoverBackground=28ffffff selectedBackground=7a000000 -normalBackground=ffffffff -alternateBackground=ff515151 +normalBackground=PaletteWindow +alternateBackground=PaletteAlternateBase error=ffdf4f4f warning=ffecbc1c splitter=ff313131 +textColorLink=PaletteLink +textColorLinkVisited=PaletteLinkVisited +backgroundColorDisabled=PaletteWindowDisabled qmlDesignerButtonColor=ff4c4e50 ;DS Theme Palette START @@ -472,13 +475,12 @@ TerminalAnsi15=e5e5e6 [Flags] ComboBoxDrawTextShadow=false -DerivePaletteFromTheme=false +DerivePaletteFromThemeIfNeeded=true DrawIndicatorBranch=true DrawSearchResultWidgetFrame=false DrawTargetSelectorBottom=false DrawToolBarHighlights=false DrawToolBarBorders=false -ApplyThemePaletteGlobally=false FlatToolBars=true FlatSideBarIcons=true FlatProjectsMode=false diff --git a/share/qtcreator/themes/light-palette.inc b/share/qtcreator/themes/light-palette.inc new file mode 100644 index 00000000000..99fe763a8bd --- /dev/null +++ b/share/qtcreator/themes/light-palette.inc @@ -0,0 +1,41 @@ +[Palette] +PaletteWindow=ffffffff +PaletteWindowDisabled=ffececec +PaletteWindowText=ff000000 +PaletteWindowTextDisabled=PaletteTextDisabled +PaletteBase=PaletteWindow +PaletteBaseDisabled=PaletteWindowDisabled +PaletteAlternateBase=ff515151 +;PaletteAlternateBaseDisabled +PaletteToolTipBase=PaletteDark +;PaletteToolTipBaseDisabled +PaletteToolTipText=PaletteWindowText +;PaletteToolTipTextDisabled +PaletteText=PaletteWindowText +PaletteTextDisabled=55000000 +PaletteButton=PaletteDark +;PaletteButtonDisabled +PaletteButtonText=PaletteWindowText +PaletteButtonTextDisabled=PaletteTextDisabled +PaletteBrightText=ffffffff +;PaletteBrightTextDisabled +PaletteHighlight=ffa5cdff +;PaletteHighlightDisabled +PaletteHighlightedText=ff000000 +;PaletteHighlightedTextDisabled +PaletteLink=ff0000ff +;PaletteLinkDisabled +PaletteLinkVisited=ff800080 +;PaletteLinkVisitedDisabled +;PaletteLight +;PaletteLightDisabled +;PaletteMidlight +;PaletteMidlightDisabled +PaletteDark=ffe4e4e4 +;PaletteDarkDisabled +PaletteMid=ffa9a9a9 +;PaletteMidDisabled +;PaletteShadow +;PaletteShadowDisabled +PalettePlaceholderText=3f000000 +;PalettePlaceholderTextDisabled diff --git a/share/qtcreator/themes/light.figmatokens b/share/qtcreator/themes/light.figmatokens index 138ad74afdf..8bbe56319d3 100644 --- a/share/qtcreator/themes/light.figmatokens +++ b/share/qtcreator/themes/light.figmatokens @@ -35,3 +35,8 @@ Token_Notification_Alert=ffeb991f Token_Notification_Success=ff23b26a Token_Notification_Neutral=ff0e7887 Token_Notification_Danger=ffdc1343 + +Token_Gradient01_Start=ff23B26A +Token_Gradient01_End=ff0E7887 +Token_Gradient02_Start=ff949494 +Token_Gradient02_End=ff474747 diff --git a/share/qtcreator/translations/README.md b/share/qtcreator/translations/README.md index ff9caddf2a6..7261305a4b7 100644 --- a/share/qtcreator/translations/README.md +++ b/share/qtcreator/translations/README.md @@ -80,9 +80,9 @@ How To add translations to Qt Creator *Note:* `.qm` files are generated as part of the regular build. They are not submitted to the repository. -*Note:* QmlDesigner contains code from the Gradient Editor of Qt Designer. If an -official translation of Qt for your language exists, you can re-use the -translation of those messages by merging Qt Creator's and Qt Designer's +*Note:* QmlDesigner contains code from the Gradient Editor of Qt Widgets Designer. +If an official translation of Qt for your language exists, you can re-use the +translation of those messages by merging Qt Creator's and Qt Widgets Designer's translation using `lconvert`: lconvert qtcreator_.ts $QTDIR/translations/designer_.ts > temp.ts @@ -91,6 +91,6 @@ Move the temporary file back to `qtcreator_.ts`, complete the Gradient Editor's translations and update the file, passing the additional option `-noobsolete` to `lupdate` (by temporarily modifying `/cmake/QtCreatorTranslations.cmake`). This will remove the now -redundant messages originating from Qt Designer. +redundant messages originating from Qt Widgets Designer. [1]: https://lists.qt-project.org/listinfo/localization diff --git a/share/qtcreator/translations/qtcreator_cs.ts b/share/qtcreator/translations/qtcreator_cs.ts index 94bbf49d0b3..23d62545e10 100644 --- a/share/qtcreator/translations/qtcreator_cs.ts +++ b/share/qtcreator/translations/qtcreator_cs.ts @@ -764,7 +764,7 @@ Automaticky vkládat středníky a uzavírající závorky, kulaté závorky, složené závorky a uvozovky, když je to vhodné. - &Automatically insert matching characters + &Automatically Insert Matching Characters &Automaticky vložit odpovídající znaky @@ -2008,7 +2008,7 @@ Chcete je nechat přepsat? Když je to vhodné, automaticky vkládat středníky a uzavírající závorky, kulaté závorky, složené závorky a uvozovky. - &Automatically insert matching characters + &Automatically Insert Matching Characters &Automaticky vložit odpovídající znaky @@ -4278,8 +4278,8 @@ Rebuilding the project might help. Zkuste projekt vytvořit znovu. - Qt Designer Form Class - Třída formuláře programu Qt Designer + Qt Widgets Designer Form Class + Třída formuláře programu Qt Widgets Designer Form Template @@ -4326,8 +4326,8 @@ Zkuste projekt vytvořit znovu. Shift+F4 - Qt Designer Form - Formulář programu Qt Designer + Qt Widgets Designer Form + Formulář programu Qt Widgets Designer Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. @@ -4458,8 +4458,8 @@ Zkuste projekt vytvořit znovu. Alt+Shift+R - About Qt Designer Plugins... - O přídavných modulech programu Qt Designer... + About Qt Widgets Designer Plugins... + O přídavných modulech programu Qt Widgets Designer... Views @@ -10752,8 +10752,8 @@ Vybere pro sestavení programu verzi Qt pro stolní počítač, je-li dostupná. Tento průvodce vytvoří projekt konzolové aplikace v Qt4. Aplikace je odvozena z QCoreApplication a nemá žádné uživatelské rozhraní. - Qt Designer is not responding (%1). - Qt Designer neodpovídá (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer neodpovídá (%1). Unable to create server socket: %1 @@ -16025,8 +16025,8 @@ Toho se dosáhne vložením této zkratky v zadávacím poli vyhledávače, nás Editor .qmlproject - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -17504,7 +17504,7 @@ Důvod: %2 Qt Custom Designer Widget - Uživatelsky stanovený prvek pro Qt Designer + Uživatelsky stanovený prvek pro Qt Widgets Designer Creates a Qt Custom Designer Widget or a Custom Widget Collection. @@ -40550,7 +40550,7 @@ Určuje chování odsazení se zřetelem k navazujícím řádkům. Nastavit znovu - Scanning scope + Scanning Scope Oblast prohledávání diff --git a/share/qtcreator/translations/qtcreator_da.ts b/share/qtcreator/translations/qtcreator_da.ts index 43f21468465..53c0246ee3c 100644 --- a/share/qtcreator/translations/qtcreator_da.ts +++ b/share/qtcreator/translations/qtcreator_da.ts @@ -338,12 +338,12 @@ Minimum API-niveauet krævet af kittet er %1. - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -Afinstallation af den installerede pakke løser måske problemstillingen. -Vil du afinstallere den eksisterende pakke? + Uninstalling the installed package may solve the issue. + Afinstallation af den installerede pakke løser måske problemstillingen. + + + Do you want to uninstall the existing package? + Vil du afinstallere den eksisterende pakke? Install failed @@ -13547,8 +13547,8 @@ Det hjælper måske at genbygge projektet. Designer - Qt Designer Form Class - Qt Designer-udformningsklasse + Qt Widgets Designer Form Class + Qt Widgets Designer-udformningsklasse Choose a Class Name @@ -13571,8 +13571,8 @@ Det hjælper måske at genbygge projektet. Skift kilde/udformning - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - Opretter en Qt Designer-udformning sammen med en matchende klasse (C++-header og kildefil) til implementeringsformål. Du kan tilføje udformningen og klassen til et eksisterende Qt widget-projekt. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Opretter en Qt Widgets Designer-udformning sammen med en matchende klasse (C++-header og kildefil) til implementeringsformål. Du kan tilføje udformningen og klassen til et eksisterende Qt widget-projekt. For&m Editor @@ -14990,8 +14990,8 @@ når de ikke kræves, hvilket i de fleste tilfælde vil forbedre ydelsen.Alt+Skift+R - About Qt Designer Plugins... - Om Qt Designer-plugins... + About Qt Widgets Designer Plugins... + Om Qt Widgets Designer-plugins... Preview in @@ -19970,8 +19970,8 @@ Fejl: %5 Python-redigering - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -23386,12 +23386,12 @@ til projektet "%2". Udformningsskabelon - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Opretter en Qt Designer-udformning som du kan tilføje til et Qt widget-projekt. Dette er nyttigt hvis du allerede har en eksisterende klasse til brugerflade travlhedslogik. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Opretter en Qt Widgets Designer-udformning som du kan tilføje til et Qt widget-projekt. Dette er nyttigt hvis du allerede har en eksisterende klasse til brugerflade travlhedslogik. - Qt Designer Form - Qt Designer-udformning + Qt Widgets Designer Form + Qt Widgets Designer-udformning Creates a Java file with boilerplate code. @@ -24002,52 +24002,36 @@ Brug det kun hvis du prototyper. Du kan ikke oprette et fuldt program med dette. Page med typeId'et "%1" har ugyldigt "index". - Path "%1" does not exist when checking Json wizard search paths. - - Stien "%1" findes ikke under tjek af Json-assistentens søgestier. - + Path "%1" does not exist when checking JSON wizard search paths. + Stien "%1" findes ikke under tjek af JSON-assistentens søgestier. - Checking "%1" for %2. - - Tjekker "%1" for %2. - + Checking "%1" for %2. + Tjekker "%1" for %2. - * Failed to parse "%1":%2:%3: %4 - - * Kunne ikke parse "%1":%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + * Kunne ikke parse "%1":%2:%3: %4 - * Did not find a JSON object in "%1". - - * Fandt ikke et JSON-objekt i "%1". - + * Did not find a JSON object in "%1". + * Fandt ikke et JSON-objekt i "%1". - * Configuration found and parsed. - - * Konfiguration fundet og parset. - + * Configuration found and parsed. + * Konfiguration fundet og parset. - * Version %1 not supported. - - * Version %1 understøttes ikke. - + * Version %1 not supported. + * Version %1 understøttes ikke. - * Failed to create: %1 - - * Kunne ikke oprette: %1 - + * Failed to create: %1 + * Kunne ikke oprette: %1 - JsonWizard: "%1" not found - - JsonWizard: "%1" ikke fundet - + JsonWizard: "%1" not found. + JsonWizard: "%1" ikke fundet. key not found. @@ -26282,12 +26266,12 @@ Opdater venligst dit kit eller vælg en mkspec for qmake som matcher dit mål-mi Opretter et Qt brugerdefineret Designer-widget eller en brugerdefineret widget-samling. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - Denne assistent genererer en Qt Designer brugerdefineret widget eller et Qt Designer brugerdefineret widget-samling-projekt. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + Denne assistent genererer en Qt Widgets Designer brugerdefineret widget eller et Qt Widgets Designer brugerdefineret widget-samling-projekt. - Qt Designer is not responding (%1). - Qt Designer svarer ikke (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer svarer ikke (%1). Unable to create server socket: %1 @@ -26358,10 +26342,10 @@ Opdater venligst dit kit eller vælg en mkspec for qmake som matcher dit mål-mi Qt widgets-program - Creates a Qt application for the desktop. Includes a Qt Designer-based main window. + Creates a Qt application for the desktop. Includes a Qt Widgets Designer-based main window. Preselects a desktop Qt for building the application if available. - Opretter et Qt-program til desktop. Inkluderer et Qt Designer-baseret hovedvindue. + Opretter et Qt-program til desktop. Inkluderer et Qt Widgets Designer-baseret hovedvindue. Prævælger en desktop Qt til bygning af programmet, hvis tilgængeligt. @@ -33820,7 +33804,7 @@ Derudover indsætter Skift+Enter et undvigetegn ved markørens placering og flyt Opdel strenge automatisk - &Automatically insert matching characters + &Automatically Insert Matching Characters &Indsæt automatisk matchende tegn @@ -34000,7 +33984,7 @@ Derudover indsætter Skift+Enter et undvigetegn ved markørens placering og flyt Justeret til højre side - Line annotations + Line Annotations Linjeannotationer @@ -35607,7 +35591,7 @@ Vil blive anvendt på blanktegn i kommentarer og strenge. Nulstil - Scanning scope + Scanning Scope Skanningsområde diff --git a/share/qtcreator/translations/qtcreator_de.ts b/share/qtcreator/translations/qtcreator_de.ts index 28c3e2c44ce..e21c369fd18 100644 --- a/share/qtcreator/translations/qtcreator_de.ts +++ b/share/qtcreator/translations/qtcreator_de.ts @@ -110,7 +110,7 @@ Frequently used signals - Häufig benutzte Signale + Häufig verwendete Signale Property changes @@ -140,7 +140,7 @@ Erweitert - Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. + Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. @@ -795,6 +795,10 @@ Bind to AmbientSound.Infinite to loop the current sound forever. New Effect + + Add to Content Library + + AudioEngineSection @@ -1374,6 +1378,36 @@ It should be a relative path. URL der Bildquelle. + + CameraSpeedConfigAction + + Open camera speed configuration dialog + + + + + CameraSpeedConfigurationDialog + + Camera Speed Configuration + + + + The speed camera moves when controlled by keyboard. + + + + Multiplier + + + + The value multiplier for the speed slider. + + + + Reset + Zurücksetzen + + CameraToggleAction @@ -1568,168 +1602,6 @@ It should be a relative path. Anwenden - - CollectionDetailsToolbar - - Add property left - - - - Add property right - - - - Delete selected property - - - - Insert row below - - - - Insert row above - - - - Delete selected row - - - - Save changes - - - - Export model - - - - Add Column - - - - Column name: - - - - The model already contains "%1"! - - - - Type: - Typ: - - - Add - Hinzufügen - - - Cancel - Abbrechen - - - - CollectionDetailsView - - Edit - - - - Delete - - - - Sort Ascending - - - - Sort Descending - - - - Add row above - - - - Add row below - - - - Delete this row - - - - Select a model to continue - - - - Delete Column - - - - Are you sure that you want to delete column "%1"? - - - - Cancel - Abbrechen - - - - CollectionItem - - Delete - - - - Rename - Umbenennen - - - Assign to the selected node - - - - Deleting the model - - - - Are you sure that you want to delete model "%1"? -The model will be deleted permanently. - - - - Are you sure that you want to delete model "%1"? -The model will be removed from the project but the file will not be deleted. - - - - Rename model - - - - Cancel - Abbrechen - - - New name: - Neuer Name: - - - - CollectionView - - Data Models - - - - Import a model - - - - Add a new model - - - ColorAnimationSpecifics @@ -1869,10 +1741,26 @@ The model will be removed from the project but the file will not be deleted.Column spacing + + Sets the space between the items in pixels in the <b>Column Layout</b>. + + Layout direction + + Sets the direction of the item flow in the <b>Column Layout</b>. + + + + Uniform cell size + + + + Toggles all cells to have a uniform size. + + ColumnSpecifics @@ -2025,6 +1913,27 @@ The model will be removed from the project but the file will not be deleted. + + ConfirmClearAllDialog + + Confirm clear list + + + + You are about to clear the list of effect nodes. + +This can not be undone. + + + + Clear + Löschen + + + Cancel + Abbrechen + + ConfirmDeleteFilesDialog @@ -2236,11 +2145,8 @@ The model will be removed from the project but the file will not be deleted.Effects - - - ContentLibraryEffect - Effect is imported to project + User Assets @@ -2283,22 +2189,14 @@ The model will be removed from the project but the file will not be deleted. - ContentLibraryMaterial + ContentLibraryItem - Material is imported to project - - - - Add an instance to project - - - - Click to download material + Item is imported to the project - ContentLibraryMaterialContextMenu + ContentLibraryItemContextMenu Apply to selected (replace) @@ -2315,6 +2213,25 @@ The model will be removed from the project but the file will not be deleted.Remove from project + + Remove from Content Library + + + + + ContentLibraryMaterial + + Material is imported to project + + + + Add an instance to project + + + + Click to download material + + ContentLibraryMaterialsView @@ -2407,6 +2324,10 @@ The model will be removed from the project but the file will not be deleted.Add light probe + + Remove from Content Library + + ContentLibraryTexturesView @@ -2419,6 +2340,25 @@ The model will be removed from the project but the file will not be deleted. + + ContentLibraryUserView + + No match found. + + + + <b>Content Library</b> is not supported in Qt5 projects. + + + + To use <b>Content Library</b>, first add the QtQuick3D module in the <b>Components</b> view. + + + + <b>Content Library</b> is disabled inside a non-visual component. + + + ContextMenu @@ -2516,6 +2456,25 @@ The model will be removed from the project but the file will not be deleted. + + DeleteBundleItemDialog + + Remove bundle %1 + + + + Are you sure you? The action cannot be undone + + + + Remove + + + + Cancel + Abbrechen + + DesignerActionManager @@ -2608,6 +2567,22 @@ The model will be removed from the project but the file will not be deleted.Sets the number by which the dial value changes. + + Start angle + + + + Sets the starting angle of the dial in degrees. + + + + End angle + + + + Sets the ending angle of the dial in degrees. + + Sets how the dial's handle snaps to the steps defined in <b>Step size</b>. @@ -2767,33 +2742,6 @@ defined in <b>Step size</b>. - - EditPropertyDialog - - Edit Column - - - - Name - Name - - - Type - Typ - - - Conversion from %1 to %2 may lead to data loss - - - - Apply - Anwenden - - - Cancel - Abbrechen - - EffectComposer @@ -2813,6 +2761,49 @@ defined in <b>Step size</b>. + + EffectComposer::EffectComposerModel + + Animation + Animation + + + Running + Läuft + + + Set this property to animate the effect. + + + + Time + Zeit + + + This property allows explicit control of current animation time. + + + + Frame + Frame + + + This property allows explicit control of current animation frame. + + + + General + Allgemein + + + Extra Margin + + + + This property specifies how much of extra space is reserved for the effect outside the parent geometry. + + + EffectComposer::EffectComposerView @@ -2828,6 +2819,25 @@ defined in <b>Step size</b>. + + EffectComposer::Uniform + + X + X + + + Y + Y + + + Z + + + + W + + + EffectComposerPreview @@ -2839,8 +2849,8 @@ defined in <b>Step size</b>. - Zoom Fit - + Reset View + Ansicht zurücksetzen Restart Animation @@ -2879,7 +2889,7 @@ defined in <b>Step size</b>. 2. Adjust the effect nodes properties 3. Change the order of the effects, if you like 4. See the preview -5. Save in the library, if you wish to reuse the effect later +5. Save in the assets library, if you wish to reuse the effect later @@ -2894,6 +2904,13 @@ defined in <b>Step size</b>. + + EffectCompositionNodeUniform + + Reset value + + + EffectNode @@ -2908,6 +2925,138 @@ defined in <b>Step size</b>. + + EffectsSection + + Effects <a style="color:%1;">[beta]</a> + + + + Remove Effects + + + + Add Effects + + + + Adds visual effects on the component. + + + + Visible + Sichtbar + + + Toggles the visibility of visual effects on the component. + + + + Layer Blur + + + + Toggles the visibility of the <b>Layer Blur</b> on the component. + + + + Blur + + + + Sets the intensity of the <b>Layer Blur</b> on the component. + + + + Background Blur + + + + Toggles the visibility of blur on the selected background component. + + + + Sets the intensity of blur on the selected background component. +The foreground component should be transparent, and the background component should be opaque. + + + + Background + Hintergrund + + + Sets a component as the background of a transparent component.The <b>Background Blur</b> works only on this component. The component should be solid. + + + + Drop Shadow + + + + Inner Shadow + + + + Toggles the visibility of the component shadow. + + + + Sets the softness of the component shadow. A larger value causes the edges of the shadow to appear more blurry. + + + + Spread + + + + Resizes the base shadow of the component by pixels. + + + + Only supported for Rectangles. + + + + Color + Farbe + + + Sets the color of the shadow. + + + + Offset + Abstand + + + Moves the shadow with respect to the component in X and Y coordinates by pixels. + + + + X-coordinate + + + + Y-coordinate + + + + Show behind + + + + Toggles the visibility of the shadow behind a transparent component. + + + + Add Shadow Effect + + + + Adds <b>Drop Shadow</b> or <b>Inner Shadow</b> effects to a component. + + + EmptyMaterialEditorPane @@ -3025,6 +3174,25 @@ defined in <b>Step size</b>. + + FlagsComboBox + + empty + + + + %1 items selected + + + + Select All + + + + Select None + + + FlickableGeometrySection @@ -3542,18 +3710,50 @@ defined in <b>Step size</b>. Columns & Rows + + Sets the number of columns and rows in the <b>Grid Layout</b>. + + Spacing Abstand + + Sets the space between the items in pixels in the rows and columns in the <b>Grid Layout</b>. + + Flow Anordnung + + Set the direction of dynamic items to flow in rows or columns in the <b>Grid Layout</b>. + + Layout direction + + Sets the direction of the dynamic items left to right or right to left in the <b>Grid Layout</b>. + + + + Uniform cell sizes + + + + Toggles all cells to have a uniform height or width. + + + + Heights + + + + Widths + + GridSpecifics @@ -3918,57 +4118,6 @@ a highlight component. - - ImportDialog - - Import a model - - - - Model path - - - - Select a model file - - - - Open - Öffnen - - - Could not load the file - - - - An error occurred while trying to load the file. - - - - File name - - - - The model name - - - - File name can not be empty - - - - The model name can not be empty - - - - Import - - - - Cancel - Abbrechen - - InsetSection @@ -4670,6 +4819,14 @@ a highlight component. Share + + Share your project online. + + + + Sharing your project online is disabled in the Community Version. + + More Items @@ -4896,6 +5053,10 @@ a highlight component. Create New Material + + Add to Content Library + + MaterialEditorToolBar @@ -5006,13 +5167,6 @@ a highlight component. - - Message - - Close - Schließen - - ModelNodeOperations @@ -5208,37 +5362,6 @@ Error: Das Verschieben der Komponente %1 an diese Stelle bewirkt das Löschen der Komponente %2. Möchten Sie den Vorgang fortsetzen? - - NewCollectionDialog - - Add a new Model - - - - Model - Modell - - - The model name - - - - The model name can not be empty - - - - The model name already exists %1 - - - - Create - - - - Cancel - Abbrechen - - NewEffectDialog @@ -6632,147 +6755,6 @@ Exporting assets: %2 - - QmlDesigner::CollectionSourceModel - - Node is not indexed in the models. - - - - Node should be a JSON model. - - - - A model with the identical name already exists. - - - - Selected node must have a valid source file address - - - - Can't read or write "%1". -%2 - - - - "%1" is corrupted. -%2 - - - - Can't clean "%1". - - - - Can't write to "%1". - - - - No model is available for the JSON model group. - - - - JSON document type should be an object containing models. - - - - Rename Model - - - - Invalid node - - - - Can't rename the node - - - - Invalid node type - - - - The model group doesn't contain the old model name (%1). - - - - The model name "%1" already exists in the model group. - - - - Delete Model - - - - The selected node has an invalid source address - - - - The model group doesn't contain the model name (%1). - - - - - QmlDesigner::CollectionView - - Model Editor - Model-Editor - - - Model Editor view - - - - - QmlDesigner::CollectionWidget - - Model Editor - Title of model editor widget - Model-Editor - - - Cannot Create QtQuick View - QtQuick View konnte nicht erzeugt werden - - - StatesEditorWidget: %1 cannot be created.%2 - - - - File error - - - - Can not open the file to write. - - - - - Can not add a model to the JSON file - - - - The imported model is empty or is not supported. - - - - Can not import to the main model - - - - The data store is not available. - - - - The default model node is not available. - - - - Failed to add a model to the default model group - - - QmlDesigner::ColorTool @@ -6873,12 +6855,35 @@ Exporting assets: %2 Verbindungen + + QmlDesigner::ContentLibraryUserModel + + Materials + + + + Textures + + + + 3D + 3D + + QmlDesigner::ContentLibraryView Content Library + + 3D Item Exists + + + + A 3D item with the same name '%1' already exists in the Content Library, are you sure you want to overwrite it? + + QmlDesigner::ContentLibraryWidget @@ -7027,10 +7032,6 @@ Exporting assets: %2 QmlDesigner::DocumentWarningWidget - - Always ignore these warnings about features not supported by Qt Quick Designer. - Diese Warnungen über in Qt Quick Designer nicht unterstütze Features immer ignorieren. - Cannot open this QML document because of an error in the QML file: Dieses QML-Dokument kann wegen eines Fehlers in der QML-Datei nicht geöffnet werden: @@ -7040,8 +7041,12 @@ Exporting assets: %2 OK - This QML file contains features which are not supported by Qt Quick Designer at: - Diese QML-Datei enthält Features, die von Qt Quick Designer nicht unterstützt werden: + Turn off warnings about unsupported Qt Design Studio features. + + + + This QML file contains features which are not supported by Qt Design Studio at: + Ignore @@ -7264,6 +7269,10 @@ Exporting assets: %2 Reset all shading options for all viewports. + + Add to Content Library + + 3D view is not supported in MCU projects. @@ -7458,6 +7467,33 @@ Exporting assets: %2 QML Resource File (*.qrc) + + Successfully generated QRC resource file + %1 + + + + Generating deployable package. Please wait... + + + + Failed to generate deployable package! + + + + Error + Fehler + + + Failed to generate deployable package! + +Please check the output pane for more information. + + + + Successfully generated deployable package + + Unable to generate resource file: %1 @@ -7486,23 +7522,10 @@ Exporting assets: %2 Success - - Successfully generated deployable package - %1 - - Save Project as Resource - - QML Resource File (*.qmlrc);;Resource File (*.rcc) - - - - Generate a resource file out of project %1 to %2 - - QmlDesigner::GlobalAnnotationDialog @@ -7770,13 +7793,9 @@ Exporting assets: %2 Reset Style Stil zurücksetzen - - If you select this radio button, Qt Quick Designer always uses the QML emulation layer (QML Puppet) located at the following path. - Wenn Sie diesen Radiobutton auswählen, benutzt der Qt Quick Designer immer die QML-Emulationsschicht (QML Puppet) im folgenden Pfad. - Use fallback QML emulation layer - Fallback QML-Emulationsschicht benutzen + Fallback QML-Emulationsschicht verwenden Path: @@ -7790,10 +7809,6 @@ Exporting assets: %2 Top level build path: Oberstes Build-Verzeichnis: - - Warns about QML features that are not properly supported by the Qt Quick Designer. - Zeigt eine Warnung bei QML-Features an, die vom Qt Quick Designer nicht vollständig unterstützt werden. - Also warns in the code editor about QML features that are not properly supported by the Qt Quick Designer. Zeigt auch im Code-Editor eine Warnung bei QML-Features an, die vom Qt Quick Designer nicht vollständig unterstützt werden. @@ -7806,6 +7821,14 @@ Exporting assets: %2 qsTr() qsTr() + + If you select this radio button, Qt Design Studio always uses the QML emulation layer (QML Puppet) located at the following path. + + + + Warns about QML features that are not properly supported by the Qt Design Studio. + + qsTrId() qsTrId() @@ -7840,7 +7863,7 @@ Exporting assets: %2 Warn about using .qml files instead of .ui.qml files - Bei der Benutzung von .qml-Dateien statt .ui.qml-Dateien warnen + Bei der Verwendung von .qml-Dateien statt .ui.qml-Dateien warnen Width: @@ -7856,7 +7879,7 @@ Exporting assets: %2 Use QML emulation layer that is built with the selected Qt - Mit dem gewählten Qt erstellte QML-Emulationsschicht benutzen + Mit dem gewählten Qt erstellte QML-Emulationsschicht verwenden qsTranslate() @@ -7967,6 +7990,10 @@ Exporting assets: %2 Select import options and press "Import" to import the following files: + + Importing: + + Locate 3D Asset "%1" @@ -7987,6 +8014,18 @@ Exporting assets: %2 Cancel Abbrechen + + Accept + + + + Import is ready for preview. + + + + Click "Accept" to finish the import or adjust options and click "Import" to import again. + + Close Schließen @@ -8062,6 +8101,10 @@ Exporting assets: %2 Could not access temporary asset directory: "%1". + + Attempted to reimport non-existing asset: %1 + + Failed to create qmldir file for asset: "%1". @@ -8261,6 +8304,13 @@ Exporting assets: %2 + + QmlDesigner::Model + + Invalid Id + Ungültige ID + + QmlDesigner::NavigatorSearchWidget @@ -8295,10 +8345,6 @@ Locked components cannot be modified or selected. Invalid Id Ungültige ID - - %1 is an invalid id. - %1 ist keine gültige ID. - %1 already exists. %1 existiert bereits. @@ -8393,7 +8439,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 @@ -8497,6 +8543,14 @@ Locked components cannot be modified or selected. The QML file is not currently opened in a QML Editor. Die QML-Datei ist in keinem QML-Editor geöffnet. + + Qml Designer Lite + + + + The Qml Designer Lite plugin is not enabled. + + Give Feedback... @@ -8993,10 +9047,6 @@ Locked components cannot be modified or selected. The Design Mode requires a valid Qt kit. - - Unsupported Qt Quick version. - - No import for Qt Quick found. Es konnte kein Import für Qt Quick gefunden werden. @@ -9039,10 +9089,6 @@ Locked components cannot be modified or selected. Invalid Id Ungültige ID - - %1 is an invalid id. - %1 ist keine gültige ID. - %1 already exists. %1 existiert bereits. @@ -9138,10 +9184,6 @@ Locked components cannot be modified or selected. Invalid Id Ungültige ID - - %1 is an invalid id. - %1 ist keine gültige ID. - %1 already exists. %1 existiert bereits. @@ -9465,10 +9507,6 @@ Locked components cannot be modified or selected. Invalid ID - - %1 is an invalid ID. - - %1 already exists. %1 existiert bereits. @@ -9501,6 +9539,13 @@ Locked components cannot be modified or selected. + + QmlDesigner::View3DTool + + View3D Tool + + + QmlDesignerAddResources @@ -9544,7 +9589,7 @@ Locked components cannot be modified or selected. Edit - Editieren + Bearbeiten Anchors @@ -9690,6 +9735,10 @@ Locked components cannot be modified or selected. Edit Annotations + + Edit in 3D View + + Fill Parent @@ -10360,7 +10409,7 @@ Locked components cannot be modified or selected. Retype password: - Passwort noch einmal eingeben: + Passwort erneut eingeben: Show password @@ -10495,7 +10544,7 @@ Locked components cannot be modified or selected. Pfad des JDK existiert und ist schreibbar. - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) OpenSSL-Einstellungen für Android (optional) @@ -10714,6 +10763,10 @@ Locked components cannot be modified or selected. Verifying the integrity of the downloaded file has failed. Das Prüfen der Integrität der heruntergeladenen Datei ist fehlgeschlagen. + + Verifying package integrity... + + Unarchiving error. Fehler beim Entpacken. @@ -10763,7 +10816,7 @@ in the system's browser for manual download. Diese Bibliotheken können mit Ihrer Anwendung weitergegeben werden, falls diese SSL-Funktionen verwendet. Sie finden eine Checkbox unter "Projekte > Erstellen > Schritte zum Erstellen > Android-APK erstellen > Zusätzliche Bibliotheken". -Falls das automatische Herunterladen scheitert, wird Qt Creator vorschlagen, die URL zum +Falls das automatische Herunterladen fehlschlägt, wird Qt Creator vorschlagen, die URL zum manuellen Herunterladen im Browser des System zu öffnen. @@ -10908,6 +10961,10 @@ Dies kann nicht rückgängig gemacht werden. Android Device Android-Gerät + + Android support is not yet configured. + + The device info returned from AvdDialog is invalid. Die vom AvdDialog zurückgelieferte Geräteinformation ist ungültig. @@ -11110,6 +11167,14 @@ Dies kann nicht rückgängig gemacht werden. Cannot find the androiddeployqt tool. Kann das androiddeployqt-Werkzeug nicht finden. + + Cannot find the package name from AndroidManifest.xml nor build.gradle files at "%1". + + + + Deployment failed with the following errors: + + Install an APK File Eine APK-Datei installieren @@ -11148,11 +11213,11 @@ Dies kann nicht rückgängig gemacht werden. Package deploy: Failed to pull "%1" to "%2". - Paket-Deployment: "pull" von "%1" nach "%2" scheiterte. + Paket-Deployment: "pull" von "%1" nach "%2" ist fehlgeschlagen. Install failed - Installation gescheitert + Installation fehlgeschlagen Android package (*.apk) @@ -11216,10 +11281,6 @@ Das Kit unterstützt "%2", aber das Gerät verwendet "%3".Cannot find the androiddeployqt input JSON file. Die JSON-Datei für androiddeployqt konnte nicht gefunden werden. - - Cannot find the package name from the Android Manifest file "%1". - Der Paketname aus der Android-Manifest-Datei "%1" konnte nicht gefunden werden. - Uninstalling the previous package "%1". Deinstalliere das vorherige Paket "%1". @@ -11237,20 +11298,12 @@ Das Kit unterstützt "%2", aber das Gerät verwendet "%3".Die Installation der Anwendung ist mit einem unbekannten Fehler fehlgeschlagen. - Deployment failed with the following errors: - - - Das Deployment ist mit den folgenden Fehlern gescheitert: - - + Uninstalling the installed package may solve the issue. + Das installierte Paket zu deinstallieren könnte das Problem lösen. - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -Das installierte Paket zu deinstallieren könnte das Problem lösen. -Möchten Sie das vorhandene Paket deinstallieren? + Do you want to uninstall the existing package? + Möchten Sie das vorhandene Paket deinstallieren? The deployment AVD "%1" cannot be started. @@ -11272,14 +11325,6 @@ Möchten Sie das vorhandene Paket deinstallieren? %1 needs additional settings to enable Android support. You can configure those settings in the Options dialog. %1 benötigt zusätzliche Einstellungen, um die Android-Unterstützung zu aktivieren. Sie können diese im Einstellungsdialog konfigurieren. - - Could not run: %1 - Keine Ausführung möglich: %1 - - - No devices found in output of: %1 - In der Ausgabe von %1 konnten keine Geräte festgestellt werden - Configure Android... Android konfigurieren... @@ -11351,8 +11396,8 @@ Der vom Kit mindestens benötigte API-Level ist %1. Unbekannte Android-Version. API-Level: %1 - Error creating Android templates. - Fehler beim Erstellen der Android-Vorlagendateien. + Cannot open "%1". + Cannot parse "%1". @@ -11365,21 +11410,13 @@ Der vom Kit mindestens benötigte API-Level ist %1. Android package installation failed. %1 - Android-Paketinstallation gescheitert. + Android-Paketinstallation fehlgeschlagen. %1 Cannot create AVD. Invalid input. AVD kann nicht erstellt werden. Ungültige Eingabe. - - Could not start process "%1". - Der Prozess "%1" konnte nicht gestartet werden. - - - Cannot create AVD. Command timed out. - AVD kann nicht erstellt werden. Zeitüberschreitung des Kommandos. - Incorrect password. Ungültiges Passwort. @@ -11561,8 +11598,40 @@ Installieren Sie diese manuell, nachdem der aktuelle Vorgang abgeschlossen ist. Die Installation von Android-SDK-Paketen kann fehlschlagen, wenn die entsprechenden Lizenzen nicht akzeptiert werden. - SDK Manager is busy. - SDK-Manager arbeitet. + Finished successfully. + + + + Installing / Uninstalling selected packages... + + + + Closing the preferences dialog will cancel the running and scheduled SDK operations. + + + + Closing the options dialog will cancel the running and scheduled SDK operations. + + + + Uninstalling %1... + + + + Installing %1... + + + + Updating installed packages... + + + + [Packages to be uninstalled:] + + + + [Packages to be installed:] + Android SDK Changes @@ -11575,100 +11644,10 @@ Installieren Sie diese manuell, nachdem der aktuelle Vorgang abgeschlossen ist. %n Android SDK-Pakete sollen aktualisiert werden. - - [Packages to be uninstalled:] - - [Pakete, die deinstalliert werden sollen:] - - - - SDK Manager is busy. Operation cancelled. - SDK-Manager arbeitet. Die Operation wurde abgebrochen. - - - Installing/Uninstalling selected packages... - - Installiere/Deinstalliere ausgewählte Pakete... - - - - Closing the %1 dialog will cancel the running and scheduled SDK operations. - - Wenn Sie den %1-Dialog schließen, werden die laufenden und geplanten SDK-Operationen abgebrochen. - - - - preferences - Einstellungen - - - options - Einstellungen - - - Updating installed packages... - - Aktualisiere installierte Pakete... - - - - Android SDK operations finished. - Android SDK-Operationen beendet. - - - Operation cancelled. - - Operation abgebrochen. - - - - -No pending operations to cancel... - - -Keine ausstehenden Operationen sind abzubrechen... - - - - -Cancelling pending operations... - - -Breche ausstehende Operationen ab... - - - - The operation requires user interaction. Use the "sdkmanager" command-line tool. - Die Operation benötigt Benutzereingaben. Benutzen Sie das Kommandozeilenwerkzeug "sdkmanager". - - - License command failed. - Lizenzkommando fehlgeschlagen. - - - Updating installed packages. - Aktualisiere installierte Pakete. - Failed. Fehlgeschlagen. - - Done - Fertig - - - Installing - Installiere - - - Uninstalling - Deinstalliere - - - Failed - Fehlgeschlagen - SDK Manager Arguments SDK-Manager-Argumente @@ -11739,6 +11718,10 @@ Breche ausstehende Operationen ab... Install the missing emulator tool (%1) to the installed Android SDK. Installieren Sie den fehlenden Emulator (%1) im installierten Android-SDK. + + Failed to start AVD emulator for "%1" device. + + Clean Environment Saubere Umgebung @@ -12131,7 +12114,7 @@ Rufen Sie QtAndroid::hideSplashScreen() auf, um einen Startbildschirm zu verstec Select master image to use. - Wählen Sie das zu benutzende Hauptbild aus. + Wählen Sie das zu verwendende Hauptbild aus. Master image: @@ -12181,7 +12164,7 @@ Rufen Sie QtAndroid::hideSplashScreen() auf, um einen Startbildschirm zu verstec An image is used for the splashscreen. Qt Creator manages splashscreen by using a different method which requires changing the manifest file by overriding your settings. Allow override? - Für den Startbildschirm wird ein Bild benutzt. Qt Creator verwaltet + Für den Startbildschirm wird ein Bild verwendet. Qt Creator verwaltet Startbildschirme auf andere Weise, was eine Änderung der Manifest-Datei und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlauben? @@ -12294,7 +12277,7 @@ und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlaube Using: %1. - Benutze: %1. + Verwende: %1. Cannot debug: Only QML and native applications are supported. @@ -12353,7 +12336,15 @@ und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlaube Number of worker threads used when scanning for tests. - Anzahl der Threads, die zum Suchen nach Tests benutzt werden. + Anzahl der Threads, die zum Suchen nach Tests verwendet werden. + + + Use a timeout while executing test cases. + + + + Timeout used when executing test cases. This will apply for each test case on its own, not the whole project. Overrides test framework or build system defaults. + Omit run configuration warnings @@ -12365,7 +12356,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. @@ -12395,10 +12386,6 @@ und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlaube Automatically scroll results Ergebnisse automatisch scrollen - - Timeout used when executing each test case. - Zeitlimit für jeden Testfall benutzen. - Scan threads: Such-Threads: @@ -12419,10 +12406,6 @@ und das Überschreiben Ihrer Einstellungen erfordert. Das Überschreiben erlaube Timeout: Zeitlimit: - - Timeout used when executing test cases. This will apply for each test case on its own, not the whole project. - Das Zeitlimit wird für jeden einzelnen Testfall und nicht das ganze Projekt gesetzt. - s s @@ -12483,7 +12466,7 @@ Warnung: Dies ist eine experimentelle Funktion und könnte dazu führen, dass di Only for unsuccessful test runs - Nur bei gescheiterten Tests + Nur bei fehlgeschlagenen Tests Automatically run @@ -12493,10 +12476,6 @@ Warnung: Dies ist eine experimentelle Funktion und könnte dazu führen, dass di Runs chosen tests automatically if a build succeeded. Führt ausgewählte Tests automatisch aus, wenn ein Build erfolgreich endete. - - Active frameworks: - Aktive Frameworks: - Automatically run tests after build Tests automatisch nach dem Erstellen ausführen @@ -12513,6 +12492,26 @@ Warnung: Dies ist eine experimentelle Funktion und könnte dazu führen, dass di Selected Ausgewählte + + Apply path filters before scanning for tests. + + + + Wildcard expressions for filtering: + + + + Add + Hinzufügen + + + Remove + + + + Limit Files to Path Patterns + + Scanning for Tests Suche nach Tests @@ -12617,7 +12616,7 @@ Warnung: Dies ist eine experimentelle Funktion und könnte dazu führen, dass di Running tests failed. %1 Executable: %2 - Ausführung von Tests gescheitert. + Ausführung von Tests fehlgeschlagen. %1 Ausführbare Datei: %2 @@ -12659,7 +12658,7 @@ Ausführbare Datei: %2 Expected Fail - Erwartetes Scheitern + Erwartetes Fehlschlagen Unexpected Pass @@ -12873,7 +12872,7 @@ Dies könnte Probleme während der Ausführung verursachen. Unable to display test results when using CDB. - Wenn CDB benutzt wird, können keine Testergebnisse angezeigt werden. + Wenn CDB verwendet wird, können keine Testergebnisse angezeigt werden. Build failed. Canceling test run. @@ -12929,11 +12928,11 @@ Dies könnte Probleme während der Ausführung verursachen. Number of resamples used for statistical bootstrapping. - Anzahl der für statistisches Bootstrapping benutzten Resamples. + Anzahl der für statistisches Bootstrapping verwendeten Resamples. Confidence interval used for statistical bootstrapping. - Für das statistische Bootstrapping benutzte Konfidenzinterval. + Konfidenzinterval, das für statistisches Bootstrapping verwendet wird. Benchmark confidence interval @@ -13027,6 +13026,10 @@ Dies könnte Probleme während der Ausführung verursachen. Repeats a test run (you might be required to increase the timeout to avoid canceling the tests). Testlauf wiederholen (eine Erhöhung des Zeitlimits kann nötig sein, um einen Abbruch zu vermeiden). + + Repeat Tests + + Output on failure Ausgabe bei Fehlschlag @@ -13108,7 +13111,7 @@ Dies könnte Probleme während der Ausführung verursachen. Tests wiederholen - Run in parallel + Run in Parallel Parallel ausführen @@ -13125,7 +13128,7 @@ Dies könnte Probleme während der Ausführung verursachen. A seed of 0 means no randomization. A value of 1 uses the current time, any other value is used as random seed generator. - Ein Startwert von 0 bedeutet keine Randomisierung. Ein Wert von 1 benutzt die aktuelle Zeit, jeder andere Wert wird als Startwert für Zufallszahlen benutzt. + Ein Startwert von 0 bedeutet keine Randomisierung. Ein Wert von 1 verwendet die aktuelle Zeit, jeder andere Wert wird als Startwert für Zufallszahlen verwendet. Randomize @@ -13247,7 +13250,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Uses tick counter when executing benchmarks. - Den Tickzähler bei der Benchmarkausführung benutzen. + Den Tickzähler bei der Benchmarkausführung verwenden. Tick counter @@ -13255,7 +13258,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Uses event counter when executing benchmarks. - Ereigniszähler bei der Benchmarkausführung benutzen. + Ereigniszähler bei der Benchmarkausführung verwenden. Event counter @@ -13263,7 +13266,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Uses Valgrind Callgrind when executing benchmarks (it must be installed). - "Valgrind Callgrind" zur Benchmarkausführung benutzen (dazu muss es installiert sein). + "Valgrind Callgrind" zur Benchmarkausführung verwenden (dazu muss es installiert sein). Find user-defined locations @@ -13271,7 +13274,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Parse messages for the following pattern and use it as location information:<pre>file://filepath:line</pre>where ":line" is optional.<p>Warning: If the patterns are used in code, the location information for debug messages and other messages might improve,at the risk of some incorrect locations and lower performance. - Wertet Nachrichten nach den folgenden Mustern aus und benutzt sie als Positionsinformation:<pre>file://dateipfad:zeile</pre>wobei ":zeile" optional ist.<p>Achtung: Wenn diese Muster im Code benutzt werden, können sich die Positionsinformationen für Debug- und andere Nachrichten verbessern, es besteht aber die Gefahr falscher Positionen und verringerter Leistung. + Wertet Nachrichten nach den folgenden Mustern aus und verwendet sie als Positionsinformation:<pre>file://dateipfad:zeile</pre>wobei ":zeile" optional ist.<p>Achtung: Wenn diese Muster im Code verwendet werden, können sich die Positionsinformationen für Debug- und andere Nachrichten verbessern, es besteht aber die Gefahr falscher Positionen und verringerter Leistung. Callgrind @@ -13279,7 +13282,7 @@ Weitere Informationen über GTest-Filter finden Sie in der Dokumenation von Goog Uses Perf when executing benchmarks (it must be installed). - "Perf" zur Benchmarkausführung benutzen (dazu muss es installiert sein). + "Perf" zur Benchmarkausführung verwenden (dazu muss es installiert sein). Perf @@ -13387,7 +13390,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 @@ -13723,6 +13726,10 @@ Siehe auch die Einstellungen für Google Test. Total rows: Gesamtzeilen: + + No Data + + Axivion Axivion @@ -13735,6 +13742,18 @@ Siehe auch die Einstellungen für Google Test. Search for issues Probleme durchsuchen + + Open Issue in Dashboard + + + + Open Table in Dashboard + + + + Copy Dashboard Link to Clipboard + + Show rule details Regeldetails anzeigen @@ -13771,6 +13790,10 @@ Hinweis: Dies macht Sie anfällig für Man-in-the-middle-Angriffe. Key chain message: "%1". Meldung der Schlüsselverwaltung: "%1". + + Unauthenticated access failed (wrong user), using authenticated access... + + Enter the password for: Dashboard: %1 @@ -13805,6 +13828,10 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? Open External Links Externe Links öffnen + + Search for issues inside the Axivion dashboard or request issue details for Axivion inline annotations to see them here. + + Fetch Projects Projekte abrufen @@ -13853,10 +13880,38 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? User name Benutzername + + Add... + Hinzufügen... + Edit... Bearbeiten... + + Remove + + + + Default dashboard server: + + + + unset + + + + Remove Server Configuration + + + + Remove the server configuration "%1"? + + + + Add Dashboard Configuration + + Edit Dashboard Configuration Dashboard-Konfiguration bearbeiten @@ -14038,7 +14093,7 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? Use GDB target extended-remote - GDB "target extended-remote" benutzen + GDB "target extended-remote" verwenden Extended mode: @@ -14101,13 +14156,13 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? GDB compatible provider engine (used together with the GDB debuggers). GDB-kompatible Provider-Engine -(wird zusammen mit GDB-Debuggern benutzt). +(wird zusammen mit GDB-Debuggern verwendet). UVSC compatible provider engine (used together with the KEIL uVision). UVSC-kompatible Provider-Engine -(wird zusammen mit KEIL uVision benutzt). +(wird zusammen mit KEIL uVision verwendet). Name @@ -14127,7 +14182,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 @@ -14199,7 +14254,7 @@ Wollen Sie "%1" mit der Standardanwendung öffnen? Do not use EBlink flash cache. - EBlink-Flash-Cache nicht benutzen. + EBlink-Flash-Cache nicht verwenden. Disable cache: @@ -14636,15 +14691,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. @@ -15559,7 +15614,7 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev Enter one CMake <a href="variable">variable</a> per line.<br/>To set or change a variable, use -D&lt;variable&gt;:&lt;type&gt;=&lt;value&gt;.<br/>&lt;type&gt; can have one of the following values: FILEPATH, PATH, BOOL, INTERNAL, or STRING.<br/>To unset a variable, use -U&lt;variable&gt;.<br/> - Geben Sie eine CMake-<a href="variable">Variable</a> pro Zeile ein.<br/>Um eine Variable zu setzen oder zu ändern, benutzen Sie -D&lt;Variable&gt;:&lt;Typ&gt;=&lt;Wert&gt;.<br/>&lt;Typ&gt; kann einer der folgenden Werte sein: FILEPATH, PATH, BOOL, INTERNAL oder STRING.<br/>Um eine Variable zurückzusetzen, benutzen Sie -U&lt;Variable&gt;.<br/> + Geben Sie eine CMake-<a href="variable">Variable</a> pro Zeile ein.<br/>Um eine Variable zu setzen oder zu ändern, verwenden Sie -D&lt;Variable&gt;:&lt;Typ&gt;=&lt;Wert&gt;.<br/>&lt;Typ&gt; kann einer der folgenden Werte sein: FILEPATH, PATH, BOOL, INTERNAL oder STRING.<br/>Um eine Variable zurückzusetzen, verwenden Sie -U&lt;Variable&gt;.<br/> Re-configure with Initial Parameters @@ -15967,7 +16022,7 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev Show subfolders inside source group folders - Unterverzeichnisse in Sourcegruppen anzeigen + Unterverzeichnisse in Quelltext-Gruppenverzeichnissen anzeigen Show advanced options by default @@ -15975,11 +16030,11 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev Use junctions for CMake configuration and build operations - Junctions für die CMake-Konfiguration und das Erstellen benutzen + Junctions für die CMake-Konfiguration und das Erstellen verwenden Create and use junctions for the source and build directories to overcome issues with long paths on Windows.<br><br>Junctions are stored under <tt>C:\ProgramData\QtCreator\Links</tt> (overridable via the <tt>QTC_CMAKE_JUNCTIONS_DIR</tt> environment variable).<br><br>With <tt>QTC_CMAKE_JUNCTIONS_HASH_LENGTH</tt>, you can shorten the MD5 hash key length to a value smaller than the default length value of 32.<br><br>Junctions are used for CMake configure, build and install operations. - Erstellt und benutzt Junctions für die Quell- und Build-Verzeichnisse, um Probleme mit langen Pfaden auf Windows zu umgehen.<br><br>Junctions werden unter <tt>C:\ProgramData\QtCreator\Links</tt> gespeichert (überschreibbar mit der Umgebungsvariable <tt>QTC_CMAKE_JUNCTIONS_DIR</tt>).<br><br>Sie können mit der Umgebungsvariable <tt>QTC_CMAKE_JUNCTIONS_HASH_LENGTH</tt> die Länge des MD5-Hashschlüssels auf einen kleineren Wert als die Voreinstellung 32 verkürzen.<br><br>Junctions werden für das Konfigurieren mit CMake, das Erstellen und die Installation benutzt. + Erstellt und verwendet Junctions für die Quell- und Build-Verzeichnisse, um Probleme mit langen Pfaden auf Windows zu umgehen.<br><br>Junctions werden unter <tt>C:\ProgramData\QtCreator\Links</tt> gespeichert (überschreibbar mit der Umgebungsvariable <tt>QTC_CMAKE_JUNCTIONS_DIR</tt>).<br><br>Sie können mit der Umgebungsvariable <tt>QTC_CMAKE_JUNCTIONS_HASH_LENGTH</tt> die Länge des MD5-Hashschlüssels auf einen kleineren Wert als die Voreinstellung 32 verkürzen.<br><br>Junctions werden für das Konfigurieren mit CMake, das Erstellen und die Installation verwendet. General @@ -16119,7 +16174,7 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev <Use Default Generator> - <Benutze Standardgenerator> + <Verwende Standardgenerator> Generator: %1<br>Extra generator: %2 @@ -16147,7 +16202,7 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev Enter one CMake <a href="variable">variable</a> per line.<br/>To set a variable, use -D&lt;variable&gt;:&lt;type&gt;=&lt;value&gt;.<br/>&lt;type&gt; can have one of the following values: FILEPATH, PATH, BOOL, INTERNAL, or STRING. - Geben Sie eine CMake-<a href="variable">Variable</a> pro Zeile ein.<br/>Um eine Variable zu setzen, benutzen Sie -D&lt;Variable&gt;:&lt;Typ&gt;=&lt;Wert&gt;.<br/>&lt;Typ&gt; kann einer der folgenden Werte sein: FILEPATH, PATH, BOOL, INTERNAL oder STRING. + Geben Sie eine CMake-<a href="variable">Variable</a> pro Zeile ein.<br/>Um eine Variable zu setzen, verwenden Sie -D&lt;Variable&gt;:&lt;Typ&gt;=&lt;Wert&gt;.<br/>&lt;Typ&gt; kann einer der folgenden Werte sein: FILEPATH, PATH, BOOL, INTERNAL oder STRING. CMake Configuration @@ -16213,6 +16268,10 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev Locates the definition of a target of any open CMake project. Findet die Definition eines Ziels in allen geöffneten CMake-Projekten. + + You may need to add the project directory to the list of directories that are mounted by the build device. + Sie müssen das Projektverzeichnis möglicherweise zur Liste der vom Gerät eingehängten Pfade hinzufügen. + The source directory %1 is not reachable by the CMake executable %2. Das Quellverzeichnis %1 kann vom CMake-Werkzeug %2 nicht erreicht werden. @@ -16249,6 +16308,10 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev <Generated Files> <Generierte Dateien> + + CMake Preset (%1) %2 Debugger + CMake-Preset (%1) %2 Debugger + Unexpected source directory "%1", expected "%2". This can be correct in some situations, for example when importing a standalone Qt test, but usually this is an error. Import the build anyway? Unerwartetes Quellverzeichnis "%1", erwartet wurde "%2". Dies kann in einigen Situationen korrekt sein, zum Beispiel beim Importieren eines eigenständigen Qt-Tests, aber normalerweise ist es ein Fehler. Soll der Build trotzdem importiert werden? @@ -16370,8 +16433,9 @@ Zum Beispiel bewirkt die Angabe "Revision: 15" dass der Branch auf Rev CMake-Auswertung wurde abgebrochen. - CMake project configuration failed. No CMake configuration for build type "%1" found. - Die CMake-Konfiguration des Projekts ist fehlgeschlagen. Es wurde keine CMake-Konfiguration für den Build-Typ "%1" gefunden. + CMake project configuration failed. No CMake configuration for build type "%1" found. Check General Messages for more information. + General Messages refers to the output view + Die CMake-Konfiguration des Projekts ist fehlgeschlagen. Es wurde keine CMake-Konfiguration für den Build-Typ "%1" gefunden. Überprüfen Sie "Allgemeine Ausgaben" für weitere Informationen. No "%1" CMake configuration found. Available configurations: "%2". @@ -16410,12 +16474,16 @@ Stellen Sie sicher, dass der Wert der CMAKE_BUILD_TYPE-Variable derselbe wie der Ungültige "version" in Datei "%1". - Invalid "configurePresets" section in %1 file - Ungültiger Abschnitt "configurePresets" in Datei %1 + Invalid "configurePresets" section in file "%1". + Ungültiger Abschnitt "configurePresets" in Datei "%1". - Invalid "buildPresets" section in %1 file - Ungültiger Abschnitt "buildPresets" in Datei %1 + Invalid "buildPresets" section in file "%1". + Ungültiger Abschnitt "buildPresets" in Datei "%1". + + + Invalid "vendor" section in file "%1". + Ungültiger Abschnitt "vendor" in Datei "%1". <File System> @@ -16801,6 +16869,10 @@ Stellen Sie sicher, dass der Wert der CMAKE_BUILD_TYPE-Variable derselbe wie der Generate Compilation Database Kompilierungsdatenbank erzeugen + + Generating Clang compilation database canceled. + Erzeugen der Clang-Kompilierungsdatenbank wurde abgebrochen. + Generate Compilation Database for "%1" Kompilierungsdatenbank für "%1" erzeugen @@ -16899,6 +16971,10 @@ Stellen Sie sicher, dass der Wert der CMAKE_BUILD_TYPE-Variable derselbe wie der Enable Anyway Trotzdem aktivieren + + Cannot use clangd: Generating compilation database canceled. + Kann Clangd nicht nutzen: Erstellen der Kompilierungsdatenbank wurde abgebrochen. + Cannot use clangd: Failed to generate compilation database: %1 @@ -16930,6 +17006,10 @@ Stellen Sie sicher, dass der Wert der CMAKE_BUILD_TYPE-Variable derselbe wie der Could not retrieve build directory. Build-Verzeichnis konnte nicht abgefragt werden. + + Could not retrieve project info. + Projekt-Information konnte nicht abgefragt werden. + Could not create "%1": %2 Konnte "%1" nicht erzeugen: %2 @@ -16942,12 +17022,8 @@ Stellen Sie sicher, dass der Wert der CMAKE_BUILD_TYPE-Variable derselbe wie der Aktuelle ClangFormat-Version: %1. - Warning: - Warnung: - - - The current ClangFormat (C++ > Code Style > ClangFormat) settings are not valid. Are you sure you want to apply them? - Die aktuellen Einstellungen für ClangFormat (C++ > Coding-Stil > ClangFormat) sind ungültig. Sind Sie sicher, dass Sie diese anwenden wollen? + Warning: + Warnung: Open Used .clang-format Configuration File @@ -16981,7 +17057,7 @@ Das integrierte Codemodell übernimmt das Einrücken. Use built-in indenter - Integriertes Codemodell für das Einrücken benutzen + Integriertes Codemodell für das Einrücken verwenden Use global settings @@ -16989,11 +17065,11 @@ Das integrierte Codemodell übernimmt das Einrücken. Please note that the current project includes a .clang-format file, which will be used for code indenting and formatting. - Beachten Sie, dass das aktuelle Projekt eine .clang-format-Datei enthält, welche für das Einrücken und die Formatierung von Code benutzt werden wird. + Beachten Sie, dass das aktuelle Projekt eine .clang-format-Datei enthält, welche für das Einrücken und die Formatierung von Code verwendet werden wird. - ClangFormat settings: - Einstellungen für ClangFormat: + ClangFormat Settings + Einstellungen für ClangFormat Indenting only @@ -17009,7 +17085,7 @@ Das integrierte Codemodell übernimmt das Einrücken. When this option is enabled, ClangFormat will use a user-specified configuration from the widget below, instead of the project .clang-format file. You can customize the formatting options for your code by adjusting the settings in the widget. Note that any changes made there will only affect the current configuration, and will not modify the project .clang-format file. - Wenn diese Einstellung aktiviert ist, wird statt der .clang-format-Datei des Projekts die benutzerdefinierte Einstellung unten benutzt. Beachten Sie, dass die unten durchgeführten Einstellungen nur die aktuelle Konfiguration beeinflussen und die .clang-format-Datei des Projekts nicht verändert wird. + Wenn diese Einstellung aktiviert ist, wird statt der .clang-format-Datei des Projekts die benutzerdefinierte Einstellung unten verwendet. Beachten Sie, dass die unten durchgeführten Einstellungen nur die aktuelle Konfiguration beeinflussen und die .clang-format-Datei des Projekts nicht verändert wird. ClangFormat @@ -17116,6 +17192,14 @@ Ausgabe: Suppress This Diagnostic Diese Art von Meldungen nicht anzeigen + + Suppress Selected Diagnostics Inline + Inline-Anzeige der ausgewählten Meldungen unterdrücken + + + Suppress This Diagnostic Inline + Inline-Anzeige dieser Meldung unterdrücken + Disable These Checks Diese Checks deaktivieren @@ -17266,7 +17350,7 @@ Setzen Sie erst eine gültige ausführbare Datei. Clang-Tidy and Clazy use a customized Clang executable from the Clang project to search for diagnostics. - Clang-Tidy und Clazy benutzen eine angepasste Version der Anwendung Clang vom Clang-Projekt, um nach Problemen zu suchen. + Clang-Tidy und Clazy verwenden eine angepasste Version der Anwendung Clang vom Clang-Projekt, um nach Problemen zu suchen. Release @@ -17278,11 +17362,11 @@ Setzen Sie erst eine gültige ausführbare Datei. You are trying to run the tool "%1" on an application in %2 mode. The tool is designed to be used in Debug mode since enabled assertions can reduce the number of false positives. - Sie versuchen das Werkzeug "%1" auf eine Applikation im %2-Modus anzuwenden. Das Werkzeug sollte im Debug-Modus benutzt werden, da eingeschaltete Assertions die Zahl der False-Positives verringern können. + Sie versuchen das Werkzeug "%1" auf eine Applikation im %2-Modus anzuwenden. Das Werkzeug sollte im Debug-Modus verwendet werden, da eingeschaltete Assertions die Zahl der False-Positives verringern können. Do you want to continue and run the tool in %1 mode? - Wollen Sie fortfahren und das Werkzeug im %1-Modus benutzen? + Wollen Sie fortfahren und das Werkzeug im %1-Modus verwenden? Analyze Project with %1... @@ -17338,7 +17422,7 @@ Setzen Sie erst eine gültige ausführbare Datei. Failed to start the analyzer. - Das Analyse-Werkzeug konnte nicht gestartet werden. + Das Analysewerkzeug konnte nicht gestartet werden. All Files @@ -18261,11 +18345,11 @@ Setzen Sie erst eine gültige ausführbare Datei. &Username: - &Nutzername: + &Benutzername: <Username> - <Nutzername> + <Benutzername> &Description: @@ -18293,7 +18377,7 @@ Setzen Sie erst eine gültige ausführbare Datei. Username: - Nutzername: + Benutzername: Default protocol: @@ -18331,7 +18415,7 @@ Setzen Sie erst eine gültige ausführbare Datei. Reset used libraries - Benutzte Bibliotheken zurücksetzen + Verwendete Bibliotheken zurücksetzen No libraries selected @@ -18371,7 +18455,7 @@ Setzen Sie erst eine gültige ausführbare Datei. No source code added yet. Add some using the button below. - Es wurde noch kein Quelltext hinzugefügt. Benutzen Sie die Schaltfläche unten, um einen Code-Editor hinzuzufügen. + Es wurde noch kein Quelltext hinzugefügt. Verwenden Sie die Schaltfläche unten, um einen Code-Editor hinzuzufügen. Add Source @@ -18447,7 +18531,7 @@ Setzen Sie erst eine gültige ausführbare Datei. URL of the Compiler Explorer instance to use. - URL der zu benutzenden Compiler Explorer-Instanz. + URL der zu verwendenden Compiler Explorer-Instanz. @@ -18517,22 +18601,13 @@ Der Code wurde in die Zwischenablage kopiert. Enabling %1 is subject to your agreement and abidance with your applicable %1 terms. It is your responsibility to know and accept the requirements and parameters of using tools like %1. This may include, but is not limited to, ensuring you have the rights to allow %1 access to your code, as well as understanding any implications of your use of %1 and suggestions produced (like copyright, accuracy, etc.). Das Aktivieren von %1 unterliegt Ihrer Zustimmung und der Einhaltung der für Sie geltenden Bestimmungen für die Nutzung von %1. Es liegt in Ihrer Verantwortung, die Bedingungen und Parameter für die Nutzung von Werkzeugen wie %1 zu kennen und zu akzeptieren. Dies umfasst unter anderem, aber beschränkt sich nicht darauf, sicherzustellen, dass Sie das Recht haben, %1 Zugriff zu Ihrem Code zu geben, und dass Sie die Implikationen Ihrer Nutzung von %1 und der davon erstellten Vorschläge kennen (bzgl. Urheberrecht, Copyright, Genauigkeit, usw.). - - The Copilot plugin requires node.js and the Copilot neovim plugin. If you install the neovim plugin as described in %1, the plugin will find the agent.js file automatically. - -Otherwise you need to specify the path to the %2 file from the Copilot neovim plugin. - Markdown text for the copilot instruction label - Das Copilot-Plugin benötigt node.js und das Copilot-Plugin für Neovim. Wenn Sie das Neovim-Plugin wie in der %1 beschrieben installieren, findet das Plugin die Datei agent.js automatisch. - -Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim angeben. - Request Copilot Suggestion Vorschlag von Copilot anfordern 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 @@ -18580,7 +18655,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. @@ -18600,17 +18675,19 @@ Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim a Wählen Sie den Pfad zur ausführbaren node.js-Datei. Siehe auch %1 für eine Installationsanleitung. - Path to agent.js: - Pfad zu agent.js: + Path to %1: + %1 is the filename of the copilot language server + Pfad zu %1: - Agent.js path - Pfad zu agent.js + %1 path + %1 is the filename of the copilot language server + Pfad zu %1 - Select path to agent.js in Copilot Neovim plugin. See %1 for installation instructions. - %1 is the URL to copilot.vim getting started - Wählen Sie den Pfad zur agent.js-Datei vom Copilot-Plugin für Neovim. Siehe auch %1 für eine Installationsanleitung. + Select path to %2 in Copilot Neovim plugin. See %1 for installation instructions. + %1 is the URL to copilot.vim getting started, %2 is the filename of the copilot language server + Wählen Sie den Pfad zu %2 im Copilot-Plugin für Neovim. Siehe auch %1 für eine Installationsanleitung. Auto Request @@ -18704,13 +18781,22 @@ Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim a Reject unauthorized certificates from the proxy server. Turning this off is a security risk. Lehnt nicht-authorisierte Zertifikate vom Proxy-Server ab. Dies abzustellen ist ein Sicherheitsrisiko. + + The Copilot plugin requires node.js and the Copilot neovim plugin. If you install the neovim plugin as described in %1, the plugin will find the %3 file automatically. + +Otherwise you need to specify the path to the %2 file from the Copilot neovim plugin. + Markdown text for the copilot instruction label + Das Copilot-Plugin benötigt node.js und das Copilot-Plugin für Neovim. Wenn Sie das Neovim-Plugin wie in der %1 beschrieben installieren, findet das Plugin die Datei %3 automatisch. + +Ansonsten müssen Sie den Pfad zur Datei %2 aus dem Copilot-Plugin für Neovim angeben. + Note Hinweis 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. @@ -18845,7 +18931,7 @@ Trotzdem fortfahren? Edit - Editieren + Bearbeiten <System Language> @@ -18866,8 +18952,8 @@ Trotzdem fortfahren? Provide cursors for resizing views. If the system cursors for resizing views are not displayed properly, you can use the cursors provided by %1. - Benutzt separate Mauszeiger für das Verändern der Größe von Ansichten. -Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrekt dargestellt werden, können von %1 bereitgestellte Zeiger benutzt werden. + Verwendet separate Mauszeiger für das Verändern der Größe von Ansichten. +Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrekt dargestellt werden, können von %1 bereitgestellte Zeiger verwendet werden. Toolbar style: @@ -18909,10 +18995,6 @@ Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrek Text codec for tools: Zeichenkodierung für Werkzeuge: - - The cursors for resizing views will change after restart. - - The language change will take effect after restart. Die Änderung der Sprache wird nach einem Neustart wirksam. @@ -18961,7 +19043,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: @@ -19125,7 +19207,7 @@ Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrek <p>Qt Creator developers can be reached at the Qt Creator mailing list:</p>%1<p>or the #qt-creator channel on Libera.Chat IRC:</p>%2<p>Our bug tracker is located at %3.</p><p>Please use %4 for bigger chunks of text.</p> - <p>Sie können die Qt Creator-Entwickler auf dem E-Mail-Verteiler</p>%1<p>oder dem IRC Kanal #qt-creator auf Libera.Chat</p>%2<p>erreichen. Unseren Bugtracker finden Sie unter %3.</p><p>Bitte benutzen Sie %4 für längere Texte.</p> + <p>Sie können die Qt Creator-Entwickler auf dem E-Mail-Verteiler</p>%1<p>oder dem IRC Kanal #qt-creator auf Libera.Chat</p>%2<p>erreichen. Unseren Bugtracker finden Sie unter %3.</p><p>Bitte verwenden Sie %4 für längere Texte.</p> Minimize @@ -19523,8 +19605,8 @@ Wenn die Systemzeiger für das Verändern der Größe von Ansichten nicht korrek QMLJS-Editor - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -20064,6 +20146,15 @@ konnte nicht unter Versionsverwaltung (%2) gestellt werden MIME Types MIME-Typen + + output.txt + default file name suggested for saving text from output views + ausgabe.txt + + + Save Contents... + Inhalt speichern... + Elided %n characters due to Application Output settings @@ -20161,14 +20252,6 @@ konnte nicht unter Versionsverwaltung (%2) gestellt werden %2 - - Launching Windows Explorer Failed - Das Starten des Windows-Explorers schlug fehl - - - Could not find explorer.exe in path to launch Windows Explorer. - Windows Explorer konnte nicht gestartet werden, da die Datei explorer.exe nicht im Pfad gefunden werden konnte. - The command for file browser is not set. Das Kommando für den Datei-Browser ist nicht konfiguriert. @@ -20261,7 +20344,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... @@ -20350,7 +20433,7 @@ konnte nicht unter Versionsverwaltung (%2) gestellt werden Use re&gular expressions - Benutze &reguläre Ausdrücke + Verwende &reguläre Ausdrücke Sco&pe: @@ -20434,6 +20517,10 @@ Um es abzurufen, tippen Sie das Kürzel im Locator, gefolgt von einem Leerzeiche min Minuten + + Locator filters show relative paths to the active project when possible. + Locator-Filter zeigen relative Pfade zum aktiven Projekt an, wenn möglich. + Files in Directories Dateien in Verzeichnissen @@ -20588,7 +20675,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: @@ -20654,7 +20741,7 @@ Um es abzurufen, tippen Sie das Kürzel im Locator, gefolgt von einem Leerzeiche Filter Results - Resultate filtern + Ergebnisse filtern %1 %2 @@ -20736,7 +20823,7 @@ Möchten Sie es beenden? Include the filter when not using a prefix for searches. - Diesen Filter einschließen, wenn kein Präfix benutzt wird. + Diesen Filter einschließen, wenn kein Präfix verwendet wird. Prefix: @@ -20838,7 +20925,7 @@ Möchten Sie es beenden? Do not ask again. - Nicht noch einmal nachfragen. + Nicht erneut nachfragen. No themes found in installation. @@ -20900,10 +20987,18 @@ Möchten Sie es beenden? The platform executable suffix. Die plattformspezifische Dateinamenserweiterung für ausführbare Dateien. + + The path to the running %1 itself. + Der Pfad zum laufenden %1 selbst. + The directory where %1 finds its pre-installed resources. Das Verzeichnis, in dem %1 seine vorinstallierten Ressourcen findet. + + The directory where %1 puts custom user data. + Das Verzeichnis, in dem %1 Benutzerdaten speichert. + The current date (QDate formatstring). Das aktuelle Datum (QDate Formatstring). @@ -20970,7 +21065,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: @@ -21140,6 +21235,10 @@ Möchten Sie sie jetzt auschecken? Alt+Right Alt+Right + + Reopen Last Closed Document + Zuletzt geschlossenes Dokument erneut öffnen + Meta+E,2 Meta+E,2 @@ -21462,10 +21561,6 @@ provided they were unmodified before the refactoring. Crash Reporting Absturzberichte - - The change will take effect after restart. - Die Änderung wird nach einem Neustart wirksam. - Case Sensitive (Default) Groß-/Kleinschreibung beachten (Vorgabe) @@ -21599,7 +21694,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 @@ -21756,11 +21851,11 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Use "Cmd", "Opt", "Ctrl", and "Shift" for modifier keys. Use "Escape", "Backspace", "Delete", "Insert", "Home", and so on, for special keys. Combine individual keys with "+", and combine multiple shortcuts to a shortcut sequence with ",". For example, if the user must hold the Ctrl and Shift modifier keys while pressing Escape, and then release and press A, enter "Ctrl+Shift+Escape,A". - Benutzen Sie "Cmd", "Opt", "Ctrl", und "Shift" für Hilfstasten. Benutzen Sie "Escape", "Backspace", "Delete", "Insert", "Home" und so weiter für Sondertasten. Kombinieren Sie einzelne Tasten mit "+" und kombinieren Sie mehrere Tastenkombinationen mit "," zu einer Tastenfolge. Wenn der Benutzer etwa die Strg- und Umschalttasten gedrückt halten muss, während er Escape drückt, um danach alle Tasten zu lösen und A zu drücken, geben Sie "Ctrl+Shift+Escape,A" ein. + Verwenden Sie "Cmd", "Opt", "Ctrl", und "Shift" für Hilfstasten. Verwenden Sie "Escape", "Backspace", "Delete", "Insert", "Home" und so weiter für Sondertasten. Kombinieren Sie einzelne Tasten mit "+" und kombinieren Sie mehrere Tastenkombinationen mit "," zu einer Tastenfolge. Wenn der Benutzer etwa die Strg- und Umschalttasten gedrückt halten muss, während er Escape drückt, um danach alle Tasten zu lösen und A zu drücken, geben Sie "Ctrl+Shift+Escape,A" ein. Use "Ctrl", "Alt", "Meta", and "Shift" for modifier keys. Use "Escape", "Backspace", "Delete", "Insert", "Home", and so on, for special keys. Combine individual keys with "+", and combine multiple shortcuts to a shortcut sequence with ",". For example, if the user must hold the Ctrl and Shift modifier keys while pressing Escape, and then release and press A, enter "Ctrl+Shift+Escape,A". - Benutzen Sie "Ctrl", "Alt", "Meta", und "Shift" für Hilfstasten. Benutzen Sie "Escape", "Backspace", "Delete", "Insert", "Home" und so weiter für Sondertasten. Kombinieren Sie einzelne Tasten mit "+" und kombinieren Sie mehrere Tastenkombinationen mit "," zu einer Tastenfolge. Wenn der Benutzer etwa die Strg- und Umschalttasten gedrückt halten muss, während er Escape drückt, um danach alle Tasten zu lösen und A zu drücken, geben Sie "Ctrl+Shift+Escape,A" ein. + Verwenden Sie "Ctrl", "Alt", "Meta", und "Shift" für Hilfstasten. Verwenden Sie "Escape", "Backspace", "Delete", "Insert", "Home" und so weiter für Sondertasten. Kombinieren Sie einzelne Tasten mit "+" und kombinieren Sie mehrere Tastenkombinationen mit "," zu einer Tastenfolge. Wenn der Benutzer etwa die Strg- und Umschalttasten gedrückt halten muss, während er Escape drückt, um danach alle Tasten zu lösen und A zu drücken, geben Sie "Ctrl+Shift+Escape,A" ein. Enter key sequence as text @@ -21824,7 +21919,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 +21927,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 @@ -21936,8 +22031,14 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Executable: + adjective Ausführbar: + + Executable: + noun + Ausführbare Datei: + Symbolic link: Symbolischer Link: @@ -22262,10 +22363,6 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Evaluating type hierarchy... Werte Typ-Hierarchie aus... - - Type Hierarchy - Klassenhierarchie - Add Definition in %1 Definition in %1 hinzufügen @@ -22427,7 +22524,7 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. #include %1 hinzufügen - Add forward declaration for %1 + Add Forward Declaration for %1 Vorwärtsdeklaration für %1 hinzufügen @@ -22638,14 +22735,6 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Open Type Hierarchy Klassenhierarchie öffnen - - Meta+Shift+T - Meta+Shift+T - - - Ctrl+Shift+T - Ctrl+Shift+T - Open Include Hierarchy Include-Hierarchie öffnen @@ -22828,7 +22917,7 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Convert to Stack Variable - In Stack-Variable umwandeln + In Stackvariable umwandeln Convert to Pointer @@ -22896,6 +22985,14 @@ Doppelklicken Sie einen Eintrag um ihn zu ändern. Deklarationen in Namensraum-Definition + + Macros that can be used as statements without a trailing semicolon. + Makros, die ohne abschließendes Semikolon benutzt werden können. + + + Statement Macros + Anweisungs-Makros + Braces Klammern @@ -23054,7 +23151,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)() = ...; @@ -23115,18 +23212,10 @@ These prefixes are used in addition to current file name on Switch Header/Source Diese Präfixe werden zusätzlich zum Dateinamen beim Wechseln zwischen Header- und Quelldatei verwendet. - - Include guards - Include-Guards - Uses "#pragma once" instead of "#ifndef" include guards. Verwendet "#pragma once" statt Include-Guards mit "#ifndef". - - Use "#pragma once" instead of "#ifndef" guards - "#pragma once" statt Include-Guards mit "#ifndef" verwenden - Headers Header-Dateien @@ -23167,10 +23256,26 @@ These prefixes are used in addition to current file name on Switch Header/Source Diese Präfixe werden zusätzlich zum Dateinamen beim Wechseln zwischen Header- und Quelldatei verwendet. + + Header File Variables + Variablen für Header-Dateien + + + Header file + Header-Datei + + + Use "#pragma once" instead + Stattdessen "#pragma once" benutzen + &Lower case file names &Kleinbuchstaben für Dateinamen verwenden + + Include guard template: + Vorlage für Include-Guards: + License &template: Lizenz&vorlage: @@ -23297,7 +23402,7 @@ Diese Präfixe werden zusätzlich zum Dateinamen beim Wechseln zwischen Header- Use type "auto" when creating new variables - Typ "auto" beim Erstellen von neuen Variablen benutzen + Typ "auto" beim Erstellen von neuen Variablen verwenden Custom Getter Setter Templates @@ -23349,9 +23454,9 @@ Diese Präfixe werden zusätzlich zum Dateinamen beim Wechseln zwischen Header- Normalerweise werden Argumente als konstante Referenz übergeben. Das Argument wird als Wert übergeben, wenn der Typ einer der folgenden ist. Namensräume und Vorlagenargumente werden entfernt. Der wirkliche Typ muss den angegebenen Typ enthalten. Zum Beispiel passt "int" zu "int32_t", aber nicht zu "vector<int>". "vector" passt zu "std::pmr::vector<int>", aber nicht zu "std::optional<vector<int>>" - Value types: + Value Types https://learn.microsoft.com/de-de/cpp/cpp/value-types-modern-cpp - Werttypen: + Werttypen Return non-value types by const reference @@ -23582,11 +23687,11 @@ z.B. name = "m_test_foo_": Use Built-in Only - Nur integriertes Backend benutzen + Nur integriertes Backend verwenden Use Clangd Only - Nur Clangd benutzen + Nur Clangd verwenden Try Both @@ -23604,6 +23709,14 @@ z.B. name = "m_test_foo_": Interpret ambiguous headers as C headers Mehrdeutige Header als C-Header behandeln + + Enable indexing + Indizieren aktivieren + + + Indexing should almost always be kept enabled, as disabling it will severely limit the capabilities of the code model. + Das Indizieren sollte nahezu immer aktiviert bleiben, da das Deaktivieren die Fähigkeiten des Codemodells erheblich einschränkt. + Do not index files greater than Dateien nicht indizieren, wenn sie größer sind als @@ -23630,11 +23743,11 @@ z.B. name = "m_test_foo_": Use built-in preprocessor to show pre-processed files - Den integrierten Präprozessor zum Anzeigen von vorverarbeiteten Dateien benutzen + Den integrierten Präprozessor zum Anzeigen von vorverarbeiteten Dateien verwenden Uncheck this to invoke the actual compiler to show a pre-processed source file in the editor. - Wählen Sie dies ab, um den Compiler zum Anzeigen von vorverarbeiteten Dateien zu benutzen. + Wählen Sie dies ab, um den Compiler zum Anzeigen von vorverarbeiteten Dateien zu verwenden. Code Model @@ -23642,29 +23755,41 @@ 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 verwendet. 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> + + + The location of the per-project clangd index.<p>This is also where the compile_commands.json file will go. + Der Pfad zum Clangd-Index pro Projekt.<p>Dies ist auch der Ort, an dem die compile_commands.json-Datei gespeichert wird. + + + The location of the per-session clangd index.<p>This is also where the compile_commands.json file will go. + Der Pfad zum Clangd-Index pro Sitzung.<p>Dies ist auch der Ort, an dem die compile_commands.json-Datei gespeichert wird. <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> - <p>Bestimmt, welches C/C++-Backend zum Wechseln zwischen Header- und Quelldatei benutzt wird.</p><p>Die Clangd-Implementation hat mehr Fähigkeiten, aber auch einige Fehler, die nicht in der integrierten Variante vorhanden sind.</p><p>Wenn "Beide versuchen" ausgewählt ist, wird Clangd nur benutzt, wenn die integrierte Variant nichts findet.</p> + <p>Bestimmt, welches C/C++-Backend zum Wechseln zwischen Header- und Quelldatei verwendet wird.</p><p>Die Clangd-Implementation hat mehr Fähigkeiten, aber auch einige Fehler, die nicht in der integrierten Variante vorhanden sind.</p><p>Wenn "Beide versuchen" ausgewählt ist, wird Clangd nur verwendet, wenn die integrierte Variant nichts findet.</p> <p>Which model clangd should use to rank possible completions.</p><p>This determines the order of candidates in the combo box when doing code completion.</p><p>The "%1" model used by default results from (pre-trained) machine learning and provides superior results on average.</p><p>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.</p> - <p>Das Modell, das Clangd für die Rangfolge der möglichen Vervollständigungen benutzen soll.</p><p>Dies bestimmt die Reihenfolge der Kandidaten im Drop-Down-Menü der Code-Vervollständigung.</p><p>Das voreingestellte Modell "%1" wurde durch maschinelles Lernen trainiert und bietet im Schnitt die besten Ergebnisse.</p><p>Falls dies für Ihren Code zu sehr von Ihren Erwartungen abweicht, können Sie auf das manuell erstellte Modell "%2" umstellen.<p> + <p>Das Modell, das Clangd für die Rangfolge der möglichen Vervollständigungen verwenden soll.</p><p>Dies bestimmt die Reihenfolge der Kandidaten im Drop-Down-Menü der Code-Vervollständigung.</p><p>Das voreingestellte Modell "%1" wurde durch maschinelles Lernen trainiert und bietet im Schnitt die besten Ergebnisse.</p><p>Falls dies für Ihren Code zu sehr von Ihren Erwartungen abweicht, können Sie auf das manuell erstellte Modell "%2" umstellen.<p> Number of worker threads used by clangd. Background indexing also uses this many worker threads. - Anzahl der Threads, die von Clangd benutzt werden. Die globale Indizierung nutzt auch diese Anzahl Threads. + Anzahl der Threads, die von Clangd verwendet werden. Die globale Indizierung nutzt auch diese Anzahl Threads. Controls whether clangd may insert header files as part of symbol completion. Bestimmt, ob Clangd beim Vervollständigen von Symbolen Header-Dateien einfügen darf. + + <p>Controls whether when editing a header file, clangd should re-parse all source files including that header.</p><p>Note that enabling this option can cause considerable CPU load when editing widely included headers.</p><p>If this option is disabled, the dependent source files are only re-parsed when the header file is saved.</p> + <p>Bestimmt, ob Clangd beim Bearbeiten einer Header-Datei alle Quelldateien, die diesen Header benutzen, neu auswerten soll.</p><p>Beachten Sie, dass das Aktivieren dieser Einstellung erhebliche Prozessorauslastung beim Bearbeiten weitgenutzter Header-Dateien zur Folge haben kann.</p><p>Wenn diese Einstellung deaktiviert ist, werden abhängige Quelldateien erst erneut ausgewertet, wenn die Header-Datei gespeichert wird.</p> + 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. @@ -23674,16 +23799,20 @@ 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 - Clangd benutzen + Clangd verwenden Insert header files on completion Bei Code-Vervollständigung Header-Dateien hinzufügen + + Update dependent sources + Abhängige Quellen aktualisieren + Automatic Automatisch @@ -23694,7 +23823,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 @@ -23708,6 +23837,14 @@ Das integrierte Codemodell übernimmt Syntaxhervorhebung, Code-Vervollständigun Background indexing: Indizierung: + + Per-project index location: + Pfad des Index pro Projekt: + + + Per-session index location: + Pfad des Index pro Sitzung: + Header/source switch mode: Modus für das Wechseln zwischen Header- und Quelldatei: @@ -23725,7 +23862,7 @@ Das integrierte Codemodell übernimmt Syntaxhervorhebung, Code-Vervollständigun Zeitabstand für das Aktualisieren von Dokumenten: - Sessions with a single clangd instance + Sessions with a Single Clangd Instance Sitzungen mit einer einzigen Clangd-Instanz @@ -23973,7 +24110,7 @@ Ziehen Sie Eintrage mit der Maus, um die Reihenfolge der Parameter zu ändern. Quick Fix settings are saved in a file. Existing settings file "%1" found. Should this file be used or a new one be created? - Einstellungen für Quick Fixes werden in einer Datei gespeichert. Es wurde eine existierende Einstellungs-Datei "%1" gefunden. Soll diese Datei benutzt, oder eine neue Datei erstellt werden? + Einstellungen für Quick Fixes werden in einer Datei gespeichert. Es wurde eine existierende Einstellungs-Datei "%1" gefunden. Soll diese Datei verwendet oder eine neue Datei erstellt werden? Switch Back to Global Settings @@ -23981,7 +24118,7 @@ Ziehen Sie Eintrage mit der Maus, um die Reihenfolge der Parameter zu ändern. Use Existing - Existierende benutzen + Existierende verwenden Create New @@ -23989,7 +24126,7 @@ Ziehen Sie Eintrage mit der Maus, um die Reihenfolge der Parameter zu ändern. Custom settings are saved in a file. If you use the global settings, you can delete that file. - Benutzerdefinierte Einstellungen werden in einer Datei gespeichert. Wenn Sie die globalen Einstellungen benutzen, können Sie diese Datei löschen. + Benutzerdefinierte Einstellungen werden in einer Datei gespeichert. Wenn Sie die globalen Einstellungen verwenden, können Sie diese Datei löschen. Delete Custom Settings File @@ -24066,12 +24203,50 @@ 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... Suche überschriebene Methoden... + + Convert Function Call to Qt Meta-Method Invocation + Funktionsaufruf in Qt Meta-Methodenaufruf umwandeln + + + Move Class to a Dedicated Set of Source Files + Klasse in dedizierten Satz Quelldateien verschieben + + + Header file only + Nur Header-Datei + + + Project: + Projekt: + + + Header file: + Header-Datei: + + + Implementation file: + Implementationsdatei: + + + Refusing to overwrite the following files: %1 + + Folgende Dateien existieren und werden nicht überschrieben: %1 + + + + Failed to add to project file "%1": %2 + Hinzufügen zur Projektdatei "%1" fehlgeschlagen: %2 + + + Re-order Member Function Definitions According to Declaration Order + Definitionen der Memberfunktionen entsprechend der Deklarationsreihenfolge anordnen + QtC::Cppcheck @@ -24145,7 +24320,7 @@ Flags: %3 Can find missing includes but makes checking slower. Use only when needed. - Kann fehlende Includes finden, verlangsamt aber die Prüfung. Benutzen Sie dies nur, wenn es nötig ist. + Kann fehlende Includes finden, verlangsamt aber die Prüfung. Verwenden Sie dies nur, wenn es nötig ist. Like C++ standard and language. @@ -24232,7 +24407,7 @@ Flags: %3 Stack Level %1 - Stack-Level %1 + Stacklevel %1 Value @@ -24353,7 +24528,7 @@ Flags: %3 The trace contains threads with stack depth > 512. Do you want to display them anyway? - Die Trace-Daten enthalten Threads mit einer Stack-Tiefe größer als 512. + Die Trace-Daten enthalten Threads mit einer Stacktiefe größer als 512. Möchten Sie die Daten trotzdem anzeigen? @@ -24722,6 +24897,14 @@ Möchten Sie die Daten trotzdem anzeigen? &Condition: &Bedingung: + + Disable All Breakpoints + Alle Haltepunkte deaktivieren + + + Enable All Breakpoints + Alle Haltepunkte aktivieren + Disable Selected Locations Ausgewählte Adressen deaktivieren @@ -24920,7 +25103,7 @@ Möchten Sie die Daten trotzdem anzeigen? Configure Symbol paths that are used to locate debug symbol files. - Symbolpfade konfigurieren, die benutzt werden, um Debug-Symboldateien zu finden. + Symbolpfade konfigurieren, die verwendet werden, um Debug-Symboldateien zu finden. Log Time Stamps @@ -24980,7 +25163,7 @@ Möchten Sie die Daten trotzdem anzeigen? Displays the objectName property of QObject based items. Note that this can negatively impact debugger performance even if no QObjects are present. - Zeigt die objectName-Eigenschaft von QObject basierten Elementen an. Dies kann die Debugger-Geschwindigkeit verschlechtern, selbst wenn keine QObjects benutzt werden. + Zeigt die objectName-Eigenschaft von QObject basierten Elementen an. Dies kann die Debugger-Geschwindigkeit verschlechtern, selbst wenn keine QObjects verwendet werden. Sort Members of Classes and Structs Alphabetically @@ -24992,7 +25175,7 @@ Möchten Sie die Daten trotzdem anzeigen? Use Debugging Helpers - Ausgabe-Hilfsbibliothek benutzen + Ausgabe-Hilfsbibliothek verwenden Use code model @@ -25000,7 +25183,7 @@ Möchten Sie die Daten trotzdem anzeigen? Selecting this causes the C++ Code Model being asked for variable scope information. This might result in slightly faster debugger operation but may fail for optimized code. - Benutzt das Codemodell, um Informationen bezüglich des Gültigkeitsbereiches von Variablen zu erhalten. Dies kann eine etwas schnellere Anzeige der Werte bewirken, aber bei optimiertem Code auch fehlschlagen. + Verwendet das Codemodell, um Informationen bezüglich des Gültigkeitsbereiches von Variablen zu erhalten. Dies kann eine etwas schnellere Anzeige der Werte bewirken, aber bei optimiertem Code auch fehlschlagen. Displays names of QThread based threads. @@ -25060,7 +25243,7 @@ Möchten Sie die Daten trotzdem anzeigen? Use Tooltips in Stack View when Debugging - Tooltips für Stack-Anzeige beim Debuggen + Tooltips für Stackanzeige beim Debuggen Skip Known Frames @@ -25084,7 +25267,7 @@ Möchten Sie die Daten trotzdem anzeigen? Use tooltips in main editor when debugging - Tooltips im Haupt-Editor beim Debuggen benutzen + Tooltips im Haupt-Editor beim Debuggen verwenden Configure Debugger... @@ -25198,7 +25381,7 @@ Sie haben die Wahl zu warten oder das Debuggen abzubrechen. Retrieving data for stack view thread %1... - Daten der Stack-Anzeige für Thread %1 werden empfangen... + Daten der Stackanzeige für Thread %1 werden empfangen... Application started. @@ -25298,7 +25481,7 @@ Sie haben die Wahl zu warten oder das Debuggen abzubrechen. Retrieving data for stack view... - Daten der Stack-Anzeige werden empfangen... + Daten der Stackanzeige werden empfangen... The gdb process failed to start. @@ -25524,12 +25707,12 @@ was generated. In such situations the breakpoint is shifted to the next source code line for which code was actually generated. This option reflects such temporary change by moving the breakpoint markers in the source code editor. - Nicht alle Quellcode-Zeilen bewirken die Erzeugung von ausführbarem Code. Wenn man dort einen Haltepunkt setzt, verhält er sich so, als ob er auf die nächste Zeile gesetzt worden wäre. Das Aktivieren der Einstellung 'Positionen der Haltepunkte korrigieren' bewirkt, dass der Haltepunkt-Marker in so einem Fall auf die Stelle des resultierenden Haltepunkts verschoben wird. + Nicht alle Quelltext-Zeilen bewirken die Erzeugung von ausführbarem Code. Wenn man dort einen Haltepunkt setzt, verhält er sich so, als ob er auf die nächste Zeile gesetzt worden wäre. Das Aktivieren der Einstellung 'Positionen der Haltepunkte korrigieren' bewirkt, dass der Haltepunkt-Marker in so einem Fall auf die Stelle des resultierenden Haltepunkts verschoben wird. 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 @@ -25547,6 +25730,18 @@ markers in the source code editor. Use common locations for debug information Verwende Standardpfade zu Debug-Information + + Use debug info daemon + Debuginfo-Daemon benutzen + + + Use system settings + Systemeinstellungen benutzen + + + Lets GDB attempt to automatically retrieve debug information for system packages. + Lässt GDB versuchen, die Debuginformation für Systempakete automatisch abzurufen. + <html><head/><body><p>Enables stepping backwards.</p><p><b>Note:</b> This feature is very slow and unstable on the GDB side. It exhibits unpredictable behavior when going backwards over system calls and is very likely to destroy your debugging session.</p></body></html> <html><head/><body><p>Rückwärts-Debuggen aktivieren.</p><p><b>Hinweis:</b> Diese Funktionalität ist sehr langsam und instabil innerhalb von GDB. Es kann unvorhergesehenes Verhalten auftreten, wenn man rückwärts über einen Systemaufruf springt, und die Debugger-Sitzung kann leicht zerstört werden.</p></body></html> @@ -25561,7 +25756,7 @@ markers in the source code editor. Uses the default GDB pretty printers installed in your system or linked to the libraries your application uses. - Verwendet die GDB-Pretty-Printers, die im System installiert sind oder gegen die Bibliotheken gelinkt sind, die die Anwendung benutzt. + Verwendet die GDB-Pretty-Printers, die im System installiert sind oder gegen die Bibliotheken gelinkt sind, die die Anwendung verwendet. The options below give access to advanced<br>or experimental functions of GDB.<p>Enabling them may negatively impact<br>your debugging experience. @@ -25765,11 +25960,11 @@ markers in the source code editor. Memory at Frame #%1 (%2) 0x%3 - Speicher bei Stack-Frame #%1 (%2) 0x%3 + Speicher bei Stackframe #%1 (%2) 0x%3 Frame #%1 (%2) - Stack-Frame #%1 (%2) + Stackframe #%1 (%2) Open Disassembler at 0x%1 @@ -25833,15 +26028,15 @@ markers in the source code editor. Sources for this frame are available.<br>Double-click on the file name to open an editor. - Für diesen Stack-Frame ist Quellcode vorhanden<br>Doppelklicken Sie auf den Dateinamen, um einen Editor zu öffnen. + Für diesen Stackframe ist Quelltext vorhanden<br>Doppelklicken Sie auf den Dateinamen, um einen Editor zu öffnen. Binary debug information is not accessible for this frame. This either means the core was not compiled with debug information, or the debug information is not accessible. - Für diesen Stack-Frame ist keine binäre Debuginformation verfügbar. Entweder stammt die Core-Datei von einer ohne Debuginformation erstellten Anwendung oder es kann nicht auf die Debuginformation zugegriffen werden. + Für diesen Stackframe ist keine binäre Debuginformation verfügbar. Entweder stammt die Core-Datei von einer ohne Debuginformation erstellten Anwendung oder es kann nicht auf die Debuginformation zugegriffen werden. Binary debug information is accessible for this frame. However, matching sources have not been found. - Für diesen Stack-Frame ist binäre Debuginformation verfügbar. Es konnte aber kein passender Quellcode gefunden werden. + Für diesen Stackframe ist binäre Debuginformation verfügbar. Es konnte aber kein passender Quelltext gefunden werden. Note that most distributions ship debug information in separate packages. @@ -26076,7 +26271,7 @@ markers in the source code editor. Cannot Display Stack Layout - Das Stack-Layout kann nicht angezeigt werden + Das Stacklayout kann nicht angezeigt werden Could not determine a suitable address range. @@ -26204,7 +26399,7 @@ markers in the source code editor. Open Memory View Showing Stack Layout - Speicheranzeige an Adresse des Stack-Frames öffnen + Speicheranzeige an Adresse des Stackframes öffnen Open Memory Editor at Object's Address (0x%1) @@ -26224,7 +26419,7 @@ markers in the source code editor. Open Memory Editor Showing Stack Layout - Speichereditor an Adresse des Stack-Frames öffnen + Speichereditor an Adresse des Stackframes öffnen Open Memory Editor... @@ -26240,6 +26435,7 @@ markers in the source code editor. %1 of length %2 + <type> of length <number>, e.g. for strings and byte arrays %1 der Länge %2 @@ -26381,8 +26577,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 @@ -26413,6 +26609,10 @@ markers in the source code editor. DAP I/O Error DAP Ein/Ausgabefehler + + "%1" could not be started. Error message: %2 + "%1" konnte nicht gestartet werden. Fehlermeldung: %2 + Python Error Python-Fehler @@ -26471,7 +26671,7 @@ If you have updated %2 via Maintenance Tool, you may need to rerun the Tool and If you build %2 from sources and want to use a CDB executable with another bitness than your %2 build, you will need to build a separate CDB extension with the same bitness as the CDB you want to use. Interner Fehler: Die Erweiterung %1 wurde nicht gefunden. Wenn Sie %2 mit dem Maintenance Tool aktualisiert haben, müssen Sie dieses vielleicht erneut ausführen, "Komponenten hinzufügen oder entfernen" auswählen und die Komponente Qt > Tools > Qt Creator CDB Debugger Support auswählen. -Wenn Sie %2 aus den Quelltexten erstellen und eine ausführbare CDB-Datei mit einer anderen Architektur (32 Bit, 64 Bit) verwenden wollen als %2, müssen Sie eine separate CDB-Erweiterung mit der gleichen Architektur wie diese CDB-Datei erstellen. +Wenn Sie %2 aus dem Quelltext erstellen und eine ausführbare CDB-Datei mit einer anderen Architektur (32 Bit, 64 Bit) verwenden wollen als %2, müssen Sie eine separate CDB-Erweiterung mit der gleichen Architektur wie diese CDB-Datei erstellen. Trace point %1 in thread %2 triggered. @@ -26588,14 +26788,14 @@ Installieren Sie das Paket "Qt Debug Information Files" für diese Qt- You may be asked to share the contents of this log when reporting bugs related to debugger operation. In this case, make sure your submission does not contain data you do not want to or you are not allowed to share. - Hinweis: Dieses Log enhält möglicherweise vertrauliche Informationen über Ihren Computer, Umgebungsvariablen, Speicherinhalte der untersuchten Prozesse oder weiteres. Es wird von %1 nie über das Internet übertragen und nur auf der Festplatte gespeichert, wenn Sie die entsprechende Option aus dem Kontextmenü aufrufen, oder durch Abläufe, die das Debugger-Plugin von %1 nicht beeinflussen kann, bespielsweise Auslagerungsdateien or andere Plugins, die Sie vielleicht benutzen. + Hinweis: Dieses Log enhält möglicherweise vertrauliche Informationen über Ihren Computer, Umgebungsvariablen, Speicherinhalte der untersuchten Prozesse oder weiteres. Es wird von %1 nie über das Internet übertragen und nur auf der Festplatte gespeichert, wenn Sie die entsprechende Option aus dem Kontextmenü aufrufen, oder durch Abläufe, die das Debugger-Plugin von %1 nicht beeinflussen kann, bespielsweise Auslagerungsdateien or andere Plugins, die Sie vielleicht verwenden. Sie werden möglicherweise gebeten, den Inhalt dieses Logs mitzuteilen, wenn Sie über Fehlfunktionen des Debugger berichten. In diesem Fall achten Sie darauf, dass Ihre Einsendung nur Daten enthält, die Sie weitergeben wollen und dürfen. 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 @@ -26935,6 +27135,10 @@ Sie werden möglicherweise gebeten, den Inhalt dieses Logs mitzuteilen, wenn Sie GDB Preset GDB-Voreinstellung + + LLDB Preset + LLDB Voreinstellung + Python Preset Python-Voreinstellung @@ -27011,7 +27215,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 @@ -27019,7 +27223,7 @@ Soll es noch einmal versucht werden? Cannot evaluate %1 in current stack frame. - %1 kann im aktuellen Stack-Frame nicht ausgewertet werden. + %1 kann im aktuellen Stackframe nicht ausgewertet werden. Context: @@ -27031,7 +27235,7 @@ Soll es noch einmal versucht werden? QML Debugger: Connection failed. - QML-Debugger: Verbindung gescheitert. + QML-Debugger: Verbindung fehlgeschlagen. JS Source for %1 @@ -27083,7 +27287,7 @@ Soll es noch einmal versucht werden? <p>Add a mapping for Qt's source folders when using an unpatched version of Qt. - <p>Fügt eine Umsetzung für die Qt-Quellen hinzu, wenn eine nicht gepatchte Version von Qt benutzt wird. + <p>Fügt eine Umsetzung für die Qt-Quellen hinzu, wenn eine nicht gepatchte Version von Qt verwendet wird. <p>The source path contained in the debug information of the executable as reported by the debugger @@ -27099,7 +27303,7 @@ Soll es noch einmal versucht werden? <p>Mappings of source file folders to be used in the debugger can be entered here.</p><p>This is useful when using a copy of the source tree at a location different from the one at which the modules where built, for example, while doing remote debugging.</p><p>If source is specified as a regular expression by starting it with an open parenthesis, the paths in the ELF are matched with the regular expression to automatically determine the source path.</p><p>Example: <b>(/home/.*/Project)/KnownSubDir -> D:\Project</b> will substitute ELF built by any user to your local project directory.</p> - <p>Hier können Zuordnungen für die beim Debuggen benutzten Quelldateien festgelegt werden.</p><p>Das ist nützlich, wenn eine lokale Kopie des Quelldateibaums verwendet wird, der sich von der beim Erstellen der Module verwendeten unterscheidet, zum Beispiel beim Remote-Debuggen.</p><p>Wenn die Zuordnung durch eine öffnende Klammer am Anfang als regulärer Ausdruck angegeben wird, werden die passenden Pfade im ELF verwendet um den Quellpfad automatisch zu bestimmen.</p><p>Beispiel: <b>(/home/.*/Projekt)/BekanntesUnterverzeichnis -> D:\Projekt</b> wird ein von einem beliebigen Benutzer erstelltes ELF in Ihr lokales Projektverzeichnis umleiten.</p> + <p>Hier können Zuordnungen für die beim Debuggen verwendeten Quelldateien festgelegt werden.</p><p>Das ist nützlich, wenn eine lokale Kopie des Quelldateibaums verwendet wird, der sich von der beim Erstellen der Module verwendeten unterscheidet, zum Beispiel beim Remote-Debuggen.</p><p>Wenn die Zuordnung durch eine öffnende Klammer am Anfang als regulärer Ausdruck angegeben wird, werden die passenden Pfade im ELF verwendet um den Quellpfad automatisch zu bestimmen.</p><p>Beispiel: <b>(/home/.*/Projekt)/BekanntesUnterverzeichnis -> D:\Projekt</b> wird ein von einem beliebigen Benutzer erstelltes ELF in Ihr lokales Projektverzeichnis umleiten.</p> &Target path: @@ -27151,7 +27355,7 @@ Soll es noch einmal versucht werden? &Username: - &Nutzername: + &Benutzername: &Password: @@ -27392,7 +27596,7 @@ Einzelschritte in das Modul und das Setzen von Haltepunkten nach Datei und Zeile Base path for external debug information and debug sources. If empty, $SYSROOT/usr/lib/debug will be chosen. - Basispfad für Debuginformationen und Quellen. Als Vorgabe wird $SYSROOT/usr/lib/debug benutzt. + Basispfad für Debuginformationen und Quellen. Als Vorgabe wird $SYSROOT/usr/lib/debug verwendet. &Kit: @@ -27450,14 +27654,17 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve Enable %1 debugger. + %1 is C++, QML, or Python %1-Debugger aktivieren. Disable %1 debugger. + %1 is C++, QML, or Python %1-Debugger deaktivieren. Try to determine need for %1 debugger. + %1 is C++, QML, or Python Versuche, die Notwendigkeit für den %1-Debugger zu ermitteln. @@ -27466,7 +27673,7 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve Use additional startup commands. - Benutze zusätzliche Kommandos beim Start. + Verwende zusätzliche Kommandos beim Start. C++ debugger: @@ -27538,7 +27745,7 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve <html><head/><body><p>The debugger is not configured to use the public Microsoft Symbol Server.<br/>This is recommended for retrieval of the symbols of the operating system libraries.</p><p><span style=" font-style:italic;">Note:</span> It is recommended, that if you use the Microsoft Symbol Server, to also use a local symbol cache.<br/>A fast internet connection is required for this to work smoothly,<br/>and a delay might occur when connecting for the first time and caching the symbols.</p><p>What would you like to set up?</p></body></html> - <html><head/><body><p>Der Debugger ist nicht zur Benutzung des öffentlichen Microsoft Symbol Servers eingerichtet.<br/>Dies wird zur Anzeige der Symbole der Betriebssystem-Bibliotheken empfohlen.</p><p><span style=" font-style:italic;">Hinweis:</span> Bei der Verwendung des Microsoft Symbol Servers wird zusätzlich die Benutzung eines lokalen Zwischenspeichers für Symbole empfohlen.<br/>Allerdings ist dabei eine schnelle Internetverbindung für flüssiges Arbeiten erforderlich<br/>und bei der ersten Verbindung zum Zwischenspeichern der Symbole können Verzögerungen auftreten.</p><p>Was möchten Sie einrichten?</p></body></html> + <html><head/><body><p>Der Debugger ist nicht zur Verwendung des öffentlichen Microsoft Symbol Servers eingerichtet.<br/>Dies wird zur Anzeige der Symbole der Betriebssystem-Bibliotheken empfohlen.</p><p><span style=" font-style:italic;">Hinweis:</span> Bei der Verwendung des Microsoft Symbol Servers wird zusätzlich der Einsatz eines lokalen Zwischenspeichers für Symbole empfohlen.<br/>Allerdings ist dabei eine schnelle Internetverbindung für flüssiges Arbeiten erforderlich<br/>und bei der ersten Verbindung zum Zwischenspeichern der Symbole können Verzögerungen auftreten.</p><p>Was möchten Sie einrichten?</p></body></html> Set up Symbol Paths @@ -27664,11 +27871,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 @@ -27712,7 +27919,7 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve The debugging helpers are used to produce a nice display of objects of certain types like QString or std::map in the &quot;Locals&quot; and &quot;Expressions&quot; views. - Die Ausgabe-Hilfsbibliothek wird benutzt um bestimmte Datentypen wie QString oder std::map in &quot;Lokale Variablen&quot; und &quot;Ausdrücke&quot; ansprechend anzuzeigen. + Die Ausgabe-Hilfsbibliothek wird verwendet um bestimmte Datentypen wie QString oder std::map in &quot;Lokale Variablen&quot; und &quot;Ausdrücke&quot; ansprechend anzuzeigen. Extra Debugging Helper @@ -27726,6 +27933,10 @@ Sie können hier eine andere Verbindung wählen, beispielsweise eine serielle Ve Python commands entered here will be executed after built-in debugging helpers have been loaded and fully initialized. You can load additional debugging helpers or modify existing ones here. Hier angegebene Python-Kommandos werden ausgeführt, nachdem die integrierte Ausgabe-Hilfsbibliothek geladen und vollständig initialisiert wurde. Sie können hier weitere Ausgabehelfer laden oder bereits existierende Ausgabehelfer ändern. + + Behavior + Verhalten + Extra Debugging Helpers Zusätzliche Ausgabe-Hilfsbibliotheken @@ -27996,6 +28207,10 @@ Bitte wählen Sie einen 64-bit-Debugger in den Kit-Einstellungen für dieses Kit Enable or Disable Breakpoint Haltepunkt aktivieren oder deaktivieren + + Launching %1 Debugger + Starte Debugger %1 + Loading finished. Laden beendet. @@ -28034,7 +28249,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. @@ -28051,7 +28266,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". @@ -28181,7 +28396,7 @@ Für dieses Binärformat wären GDB oder LLDB besser als Debugger geeignet. Reverse-execution recording failed. - Aufzeichnung für Rückwärtsausführung gescheitert. + Aufzeichnung für Rückwärtsausführung fehlgeschlagen. Found. @@ -28484,7 +28699,7 @@ Das Setzen von Haltepunkten anhand von Dateinamen und Zeilennummern könnte fehl Use alternating row colors in debug views - Alternierende Farben für Zeilen in Debug-Ansichten benutzen + Alternierende Farben für Zeilen in Debug-Ansichten verwenden Changes the font size in the debugger views when the font size in the main editor changes. @@ -28496,7 +28711,7 @@ Das Setzen von Haltepunkten anhand von Dateinamen und Zeilennummern könnte fehl Not all source code lines generate executable code. Putting a breakpoint on such a line acts as if the breakpoint was set on the next line that generated code. Selecting 'Adjust Breakpoint Locations' shifts the red breakpoint markers in such cases to the location of the true breakpoint. - Nicht aus allen Quellcode-Zeilen wird ausführbarer Code erzeugt. Wenn man dort einen Haltepunkt setzt, verhält er sich so, als ob er auf die nächste Zeile gesetzt worden wäre, aus der Maschinencode erzeugt wurde. Das Aktivieren der Einstellung 'Positionen der Haltepunkte korrigieren' bewirkt, dass der Haltepunkt-Marker in so einem Fall an die Stelle des resultierenden Haltepunkts verschoben wird. + Nicht aus allen Quelltext-Zeilen wird ausführbarer Code erzeugt. Wenn man dort einen Haltepunkt setzt, verhält er sich so, als ob er auf die nächste Zeile gesetzt worden wäre, aus der Maschinencode erzeugt wurde. Das Aktivieren der Einstellung 'Positionen der Haltepunkte korrigieren' bewirkt, dass der Haltepunkt-Marker in so einem Fall an die Stelle des resultierenden Haltepunkts verschoben wird. Stopping and stepping in the debugger will automatically open views associated with the current location. @@ -28532,7 +28747,7 @@ Das Setzen von Haltepunkten anhand von Dateinamen und Zeilennummern könnte fehl Use annotations in main editor when debugging - Annotationen im Haupt-Editor beim Debuggen benutzen + Annotationen im Haupt-Editor beim Debuggen verwenden Shows simple variable values as annotations in the main editor during debugging. @@ -28620,7 +28835,7 @@ Das Setzen von Haltepunkten anhand von Dateinamen und Zeilennummern könnte fehl Maximum stack depth: - Maximale Stack-Tiefe: + Maximale Stacktiefe: <unlimited> @@ -28977,8 +29192,8 @@ Rebuilding the project might help. Versuchen Sie, das Projekt neu zu erstellen. - Qt Designer Form Class - Qt-Designer-Formularklasse + Qt Widgets Designer Form Class + Qt-Widgets-Designer-Formularklasse Class Details @@ -29009,8 +29224,8 @@ Versuchen Sie, das Projekt neu zu erstellen. Shift+F4 - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - Erstellt ein Qt-Designer-Formular mit zugehörigem Klassenrumpf (bestehend aus C++-Header- und -Quelldatei) für Implementierungszwecke. Sie können Formular und Klasse zu einem existierenden Qt-Widget-Projekt hinzufügen. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Erstellt ein Qt-Widgets-Designer-Formular mit zugehörigem Klassenrumpf (bestehend aus C++-Header- und -Quelldatei) für Implementierungszwecke. Sie können Formular und Klasse zu einem existierenden Qt-Widget-Projekt hinzufügen. Choose a Form Template @@ -29161,8 +29376,8 @@ Versuchen Sie, das Projekt neu zu erstellen. Alt+Shift+R - About Qt Designer Plugins... - Über Qt Designer-Plugins... + About Qt Widgets Designer Plugins... + Über Qt Widgets Designer-Plugins... Preview in @@ -29486,10 +29701,6 @@ Versuchen Sie, das Projekt neu zu erstellen. Failed to create container shell (Out of memory). Container-Shell konnte nicht erstellt werden (nicht genügend Speicherplatz). - - Cannot start docker device from non-main thread - Docker-Gerät kann nur vom Haupt-Thread gestartet werden - Device is shut down Das Gerät ist heruntergefahren @@ -29731,7 +29942,7 @@ Versuchen Sie, das Projekt neu zu erstellen. Exchange Cursor and Mark - Textmarke und Markierung austauschen + Einfügemarke und Markierung austauschen Copy @@ -29758,79 +29969,102 @@ Versuchen Sie, das Projekt neu zu erstellen. QtC::ExtensionManager Extensions - - - - Get started - - - - Install the extension from above. Installation starts automatically. You can always uninstall the extension afterwards. - + Erweiterungen More information - - - - Online Documentation - - - - Tutorials - Anleitungen - - - Examples - Beispiele - - - Extension library details - - - - Size - Größe - - - Version - Version - - - Location - + Mehr Informationen Extension details - + Erweiterungsdetails + + + Pack contains %n plugins. + + Paket enthält ein Plugin. + Paket enthält %n Plugins. + - Released - + Load on start + Beim Start laden - Related tags - + Restart Now + Jetzt neu starten + + + Error + Fehler + + + Loaded + Geladen + + + Not loaded + Nicht geladen + + + Tags + Tags Platforms - + Plattformen Dependencies - Abhängigkeiten + Abhängigkeiten Extensions in pack - + Erweiterungen im Paket + + + Downloading... + Lade herunter... + + + Cancel + Abbrechen + + + Download Extension + Erweiterung herunterladen + + + Download Error + Ladefehler + + + Cannot download extension + Erweiterung kann nicht heruntergeladen werden + + + Code: %1. + Code: %1. Manage Extensions - + Erweiterungen verwalten + + + Search + Suche Install... - + Installieren... + + + Use external repository + Externes Repository benutzen + + + Repository: %1 + Repository: %1 @@ -29867,6 +30101,10 @@ Versuchen Sie, das Projekt neu zu erstellen. Dependencies: Abhängigkeiten: + + Loadable without restart: + Kann ohne Neustart geladen werden: + Plugin Details of %1 Beschreibung zu %1 @@ -30031,6 +30269,10 @@ Grund: %3 The option %1 requires an argument. Das Kommandozeilenargument %1 erfordert ein Argument. + + Cannot open file + Datei kann nicht geöffnet werden + "%1" is missing "%1" fehlt @@ -30045,16 +30287,24 @@ 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 Wert "%2" des Schlüssels "%1" ist in ungültigem Format + + No IID found + Keine IID gefunden + + + Expected IID "%1", but found "%2" + IID "%1" erwartet, aber "%2" gefunden + Resolving dependencies failed because state != Read Das Bestimmen der Abhängigkeiten schlug fehl, weil der Status != Gelesen ist @@ -30125,7 +30375,7 @@ Grund: %3 Load on Startup - Beim Start Laden + Beim Start laden Utilities @@ -30179,7 +30429,7 @@ Plugin durch ein Kommandozeilenargument deaktiviert. Load on startup - Beim Start Laden + Beim Start laden Enabling Plugins @@ -30260,7 +30510,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: QtC::FakeVim Use FakeVim - FakeVim benutzen + FakeVim verwenden Read .vimrc from location: @@ -30348,7 +30598,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: Use system encoding for :source - System-Zeichenkodierung für :source benutzen + System-Zeichenkodierung für :source verwenden Scroll offset: @@ -30388,7 +30638,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: Use Vim-style Editing - Vim benutzen + Vim verwenden Mark "%1" not set. @@ -30413,11 +30663,11 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: Type Control-Shift-Y, Control-Shift-Y to quit FakeVim mode. These are the names of the actual keys on my german Apple keyboard https://support.apple.com/de-de/HT201236 - Benutzen sie Control-Umschalt-Y, Control-Umschalt-Y, um den FakeVim-Modus zu verlassen. + Verwenden sie Control-Umschalt-Y, Control-Umschalt-Y, um den FakeVim-Modus zu verlassen. Type Alt-Y, Alt-Y to quit FakeVim mode. - Benutzen Sie Alt-Y, Alt-Y, um den FakeVim-Modus zu verlassen. + Verwenden Sie Alt-Y, Alt-Y, um den FakeVim-Modus zu verlassen. Unknown option: @@ -30675,7 +30925,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: SSL/TLS client identity key to use if requested by the server. - SSL/TLS Client Identity Key, der benutzt werden soll, wenn der Server diesen anfordert. + Der SSL/TLS Client Identity Key, der auf Anforderung des Servers verwendet werden soll. Disable auto-sync @@ -30691,7 +30941,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: User: - Nutzer: + Benutzer: Repository Settings @@ -31103,7 +31353,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: User - Nutzer + Benutzer Miscellaneous @@ -31162,7 +31412,7 @@ zu deaktivieren, deaktiviert auch die folgenden Plugins: Imports existing projects that do not use qmake, CMake, Qbs, Meson, or Autotools. This allows you to use %1 as a code editor. - Importiert bereits existierende Projekte, die weder qmake, CMake, Qbs, Meson oder Autotools verwenden. Dadurch kann %1 als Code-Editor benutzt werden. + Importiert bereits existierende Projekte, die weder qmake, CMake, Qbs, Meson oder Autotools verwenden. Dadurch kann %1 als Code-Editor verwendet werden. Project Name and Location @@ -31341,7 +31591,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. @@ -32360,7 +32610,7 @@ Möchten Sie ihn beenden? &User: - &Nutzer: + &Benutzer: &ssh: @@ -32404,7 +32654,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. @@ -32790,8 +33040,8 @@ Leer lassen, um das Dateisystem zu durchsuchen. Include branches and tags that have not been active for %n days. - Branches und Tags einschließen, die seit einem Tag nicht benutzt wurden. - Branches und Tags einschließen, die seit %n Tagen nicht benutzt wurden. + Branches und Tags einschließen, die seit einem Tag nicht verwendet wurden. + Branches und Tags einschließen, die seit %n Tagen nicht verwendet wurden. @@ -33502,7 +33752,7 @@ Hinweis: Dies macht Sie anfällig für Man-in-the-middle-Angriffe. Using project access token. - Benutze das Zugriffstoken des Projekts. + Verwende das Zugriffstoken des Projekts. Logged in as %1 @@ -34090,7 +34340,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 @@ -34486,8 +34736,8 @@ Möchten Sie sie überschreiben? Geben Sie die entsprechenden Argumente für das Erstellkommando ein. - Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools) - Stellen Sie sicher, dass der Wert für die Anzahl paralleler Jobs im Erstellkommando groß genug ist (wie zum Beispiel -j200 für JOM oder Make) + Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools). + Stellen Sie sicher, dass der Wert für die Anzahl paralleler Jobs im Erstellkommando groß genug ist (wie zum Beispiel -j200 für JOM oder Make). Keep original jobs number: @@ -34507,7 +34757,7 @@ Möchten Sie sie überschreiben? Defines how Automatic Interception Interface should handle the various processes involved in a distributed job. It is not necessary for "Visual Studio" or "Make and Build tools" builds, but can be used to provide configuration options if those builds use additional processes that are not included in those packages. It is required to configure distributable processes in "Dev Tools" builds. - Bestimmt, wie das Automatic Interception Interface die in einem verteilten Job involvierten Prozesse behandelt. Benötigt, um verteilte Prozesse in Kompilierungen mit "Dev Tools" zu konfigurieren. Nicht für Kompilierungen mit "Visual Studio" oder "Make and Build tools" benötigt, kann aber zur Konfiguration zusätzlicher Prozesse benutzt werden, die nicht in diesen Paketen enthalten sind. + Bestimmt, wie das Automatic Interception Interface die in einem verteilten Job involvierten Prozesse behandelt. Benötigt, um verteilte Prozesse in Kompilierungen mit "Dev Tools" zu konfigurieren. Nicht für Kompilierungen mit "Visual Studio" oder "Make and Build tools" benötigt, kann aber zur Konfiguration zusätzlicher Prozesse verwendet werden, die nicht in diesen Paketen enthalten sind. Avoid local task execution: @@ -34519,7 +34769,7 @@ Möchten Sie sie überschreiben? Determines the maximum number of CPU cores that can be used in a build, regardless of the number of available Agents. It takes into account both local and remote cores, even if the Avoid Task Execution on Local Machine option is selected. - Bestimmt unabhängig von der Anzahl verfügbarer Agents die maximale Anzahl CPU-Kerne, die beim Erstellen benutzt werden. Berücksichtigt sowohl lokale als auch entfernte Kerne, auch wenn die Option "Lokales Ausführen von Aufgaben vermeiden" ausgewählt ist. + Bestimmt unabhängig von der Anzahl verfügbarer Agents die maximale Anzahl CPU-Kerne, die beim Erstellen verwendet werden. Berücksichtigt sowohl lokale als auch entfernte Kerne, auch wenn die Option "Lokales Ausführen von Aufgaben vermeiden" ausgewählt ist. Maximum CPUs to utilize in the build: @@ -34551,7 +34801,7 @@ Möchten Sie sie überschreiben? Specifies a custom header line which will be displayed in the beginning of the build output text. This title will also be used for the Build History and Build Monitor displays. - Gibt eine benutzerdefinierte Kopfzeile an, die vor der Ausgabe der Kompilierung angezeigt wird. Dieser Titel wird auch für die Anzeigen "Build History" und "Build Monitor" benutzt. + Gibt eine benutzerdefinierte Kopfzeile an, die vor der Ausgabe der Kompilierung angezeigt wird. Dieser Titel wird auch für die Anzeigen "Build History" und "Build Monitor" verwendet. Save IncrediBuild monitor file: @@ -34559,7 +34809,7 @@ Möchten Sie sie überschreiben? Writes a copy of the build progress file (.ib_mon) to the specified location. If only a folder name is given, a generated GUID will serve as the file name. The full path of the saved Build Monitor will be written to the end of the build output. - Schreibt eine Kopie der Monitor-Datei (.ib_mon) an den angegebenen Ort. Wenn nur ein Verzeichnisname angegeben ist, wird eine generierte GUID als Dateiname benutzt. Der vollständige Pfad der gespeicherten Monitor-Datei wird am Ende der Ausgabe der Kompilierung angezeigt. + Schreibt eine Kopie der Monitor-Datei (.ib_mon) an den angegebenen Ort. Wenn nur ein Verzeichnisname angegeben ist, wird eine generierte GUID als Dateiname verwendet. Der vollständige Pfad der gespeicherten Monitor-Datei wird am Ende der Ausgabe der Kompilierung angezeigt. Suppress STDOUT: @@ -34583,7 +34833,7 @@ Möchten Sie sie überschreiben? Shows, for each file built, the command-line used by IncrediBuild to build the file. - Zeigt für jede Datei die Kommandozeile, die von IncrediBuild zum Erstellen der Datei benutzt wird. + Zeigt für jede Datei die Kommandozeile, die von IncrediBuild zum Erstellen der Datei verwendet wird. Show Agents in output: @@ -34591,7 +34841,7 @@ Möchten Sie sie überschreiben? Shows the Agent used to build each file. - Zeigt für jede Datei den Agent, der zum Erstellen der Datei benutzt wird. + Zeigt für jede Datei den Agent, der zum Erstellen der Datei verwendet wird. Show Time in output: @@ -34606,16 +34856,16 @@ Möchten Sie sie überschreiben? IncrediBuilds Kopfzeile in der Ausgabe verstecken: - Suppresses IncrediBuild's header in the build output - Unterdrückt die Kopfzeile von IncrediBuild in der Ausgabe der Kompilierung + Suppresses IncrediBuild's header in the build output. + Unterdrückt die Kopfzeile von IncrediBuild in der Ausgabe der Kompilierung. Internal IncrediBuild logging level: Stufe der internen IncrediBuild-Protokollierung: - Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support - Überschreibt die Stufe der internen Protokollierung von IncrediBuild für diese Kompilierung. Beeinflusst weder die Ausgabe noch die dem Benutzer zugängliche Protokollierung. Wird hauptsächlich zur Fehlerbehebung mit Hilfe des Supports von IncrediBuild benutzt + Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support. + Überschreibt die Stufe der internen Protokollierung von IncrediBuild für diese Kompilierung. Beeinflusst weder die Ausgabe noch die dem Benutzer zugängliche Protokollierung. Wird hauptsächlich zur Fehlerbehebung mit Hilfe des Supports von IncrediBuild verwendet. Miscellaneous @@ -34634,16 +34884,16 @@ Möchten Sie sie überschreiben? Bei Fehler anhalten: - When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds - Wenn angegeben, wird die Ausführung angehalten sobald ein Fehler auftritt. Dies ist das voreingestellte Verhalten bei Kompilierungen mit "Visual Studio", aber nicht für Kompilierungen mit "Make and Build tools" oder "Dev Tools" + When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds. + Wenn angegeben, wird die Ausführung angehalten sobald ein Fehler auftritt. Dies ist das voreingestellte Verhalten bei Kompilierungen mit "Visual Studio", aber nicht für Kompilierungen mit "Make and Build tools" oder "Dev Tools". Additional Arguments: Zusätzliche Argumente: - Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line - Fügt zusätzliche Argumente für buildconsole manuell hinzu. Der Inhalt dieses Eingabefelds wird an die finale Kommandozeile für buildconsole angefügt + Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line. + Fügt zusätzliche Argumente für buildconsole manuell hinzu. Der Inhalt dieses Eingabefelds wird an die finale Kommandozeile für buildconsole angefügt. Open Build Monitor: @@ -34667,11 +34917,11 @@ Möchten Sie sie überschreiben? Force remote: - "--force-remote" benutzen: + "--force-remote" verwenden: Alternate tasks preference: - "--alternate" benutzen: + "--alternate" verwenden: CMake @@ -34783,7 +35033,7 @@ Möchten Sie sie überschreiben? The provisioning profile "%1" (%2) used to sign the application does not cover the device %3 (%4). Deployment to it will fail. - Das zum Signieren der Anwendung verwendete Provisioning-Profil "%1" (%2) deckt das Gerät %3 (%4) nicht ab. Deployment auf dieses wird scheitern. + Das zum Signieren der Anwendung verwendete Provisioning-Profil "%1" (%2) deckt das Gerät %3 (%4) nicht ab. Deployment auf dieses wird fehlschlagen. Deploy to iOS device @@ -34809,6 +35059,10 @@ Möchten Sie sie überschreiben? CPU Architecture: CPU-Architektur: + + Product type: + Produkttyp: + Device name Gerätename @@ -34838,6 +35092,10 @@ Möchten Sie sie überschreiben? OS version Betriebssystem-Version + + Product type + Produkttyp + An iOS device in user mode has been detected. Es wurde ein iOS-Gerät im Benutzermodus gefunden. @@ -34881,7 +35139,7 @@ Möchten Sie sie überschreiben? To use this device you need to enable developer mode on it. - Um dieses Gerät zu benutzen, müssen Sie darauf den Entwicklungsmodus aktivieren. + Um dieses Gerät zu verwenden, müssen Sie darauf den Entwicklungsmodus aktivieren. %1 is not connected. Select %2? @@ -34903,6 +35161,10 @@ Möchten Sie sie überschreiben? Device type: Gerätetyp: + + Update + Aktualisieren + iOS Simulator iOS-Simulator @@ -34913,11 +35175,11 @@ Möchten Sie sie überschreiben? Application install on simulator failed. Simulator not running. - Die Installation der Anwendung im Simulator ist gescheitert. Der Simulator läuft nicht. + Die Installation der Anwendung im Simulator ist fehlgeschlagen. Der Simulator läuft nicht. Application launch on simulator failed. Invalid bundle path %1 - Der Start der Anwendung im Simulator ist gescheitert. Der Bundle-Pfad %1 ist ungültig + Der Start der Anwendung im Simulator ist fehlgeschlagen. Der Bundle-Pfad %1 ist ungültig Application launch on simulator failed. Simulator not running. %1 @@ -34925,7 +35187,7 @@ Möchten Sie sie überschreiben? Application install on simulator failed. %1 - Die Installation der Anwendung im Simulator ist gescheitert. %1 + Die Installation der Anwendung im Simulator ist fehlgeschlagen. %1 Cannot capture console output from %1. Error redirecting output to %2.* @@ -34937,7 +35199,7 @@ Möchten Sie sie überschreiben? Application launch on simulator failed. %1 - Der Start der Anwendung im Simulator ist gescheitert. %1 + Der Start der Anwendung im Simulator ist fehlgeschlagen. %1 Invalid simulator response. Device Id mismatch. Device Id = %1 Response Id = %2 @@ -34991,22 +35253,14 @@ Möchten Sie sie überschreiben? Run ended with error. Ausführung mit Fehler beendet. - - Create Simulator - Simulator erstellen - - - Simulator name: - Name des Simulators: - - - OS version: - Betriebssystemversion: - iOS Configuration iOS-Konfiguration + + Configure available simulator devices in <a href="%1">Xcode</a>. + Konfigurieren Sie verfügbare Simulator-Geräte in <a href="%1">Xcode</a>. + Devices Geräte @@ -35019,184 +35273,6 @@ Möchten Sie sie überschreiben? Simulator Simulator - - Rename a simulator device. - Ein Simulator-Gerät umbenennen. - - - Rename - Umbenennen - - - Delete simulator devices. - Simulator-Geräte entfernen. - - - Delete - Entfernen - - - Reset contents and settings of simulator devices. - Inhalte und Einstellungen von Simulator-Geräten zurücksetzen. - - - Screenshot directory: - Screenshot-Verzeichnis: - - - Create a new simulator device. - Ein neues Simulator-Gerät erstellen. - - - Create - Erstellen - - - Start simulator devices. - Simulator-Geräte starten. - - - Start - Starten - - - Screenshot - Screenshot - - - You are trying to launch %n simulators simultaneously. This will take significant system resources. Do you really want to continue? - - Sie versuchen einen Simulator zu starten. Dies benötigt erhebliche Systemressourcen. Wollen Sie fortfahren? - Sie versuchen %n Simulatoren gleichzeitig zu starten. Dies benötigt erhebliche Systemressourcen. Wollen Sie fortfahren? - - - - Simulator Start - Simulator starten - - - Cannot start simulator (%1, %2) in current state: %3. - Der Simulator (%1, %2) kann im momentanen Zustand (%3) nicht gestartet werden. - - - simulator start - Simulator starten - - - Creating simulator device... - Simulator-Gerät erstellen... - - - Simulator device (%1) created. -UDID: %2 - Das Simulator-Gerät (%1) wurde erstellt. -UDID: %2 - - - Simulator device (%1) creation failed. -Error: %2 - Das Simulator-Gerät (%1) konnte nicht erstellt werden. -Fehler: %2 - - - Starting %n simulator device(s)... - - Starte Simulator-Gerät... - Starte %n Simulator-Geräte... - - - - Do you really want to reset the contents and settings of the %n selected device(s)? - - Wollen Sie die Inhalte und Einstellungen des ausgewählten Geräts zurücksetzen? - Wollen Sie die Inhalte und Einstellungen der %n ausgewählten Geräte zurücksetzen? - - - - Resetting contents and settings... - Setze Inhalte und Einstellungen zurück... - - - simulator reset - Simulator zurücksetzen - - - Rename %1 - %1 umbenennen - - - Enter new name: - Geben Sie einen neuen Namen ein: - - - Renaming simulator device... - Benenne Simulator-Gerät um... - - - simulator rename - Simulator umbenennen - - - Delete Device - Gerät entfernen - - - Do you really want to delete the %n selected device(s)? - - Wollen Sie das ausgewählte Gerät entfernen? - Wollen Sie die %n ausgewählten Geräte entfernen? - - - - Deleting %n simulator device(s)... - - Entferne Simulator-Gerät... - Entferne %n Simulator-Geräte... - - - - Capturing screenshots from %n device(s)... - - Nehme Screenshot vom Gerät auf... - Nehme Screenshots von %n Geräten auf... - - - - simulator delete - Simulator entfernen - - - simulator screenshot - Simulator Screenshot - - - Simulator Operation Status - Simulator-Betriebszustand - - - %1, %2 -Operation %3 completed successfully. - %1, %2 -Operation %3 erfolgreich abgeschlossen. - - - %1, %2 -Operation %3 failed. -UDID: %4 -Error: %5 - %1, %2 -Operation %3 fehlgeschlagen. -UDID: %4 -Fehler: %5 - - - Unknown - Unbekannt - - - Done. - Fertig. - %1 - Free Provisioning Team : %2 %1 - Free Provisioning-Team : %2 @@ -35225,22 +35301,6 @@ Ablaufdatum: %3 Could not get necessary ports for the profiler connection. Auf die für die Profiler-Verbindung notwendigen Ports konnte nicht zugegriffen werden. - - UDID: %1 - UDID: %1 - - - Simulator Name - Name des Simulators - - - Runtime - Runtime - - - Current State - Status - Deploy on iOS Deployment auf iOS @@ -35283,7 +35343,7 @@ Ablaufdatum: %3 Using default development team and provisioning profile. - Die Vorgaben für Entwicklerteam und Provisioning-Profil werden benutzt. + Die Vorgaben für Entwicklerteam und Provisioning-Profil werden verwendet. Development team: %1 (%2) @@ -35295,7 +35355,7 @@ Ablaufdatum: %3 %1 not configured. Use Xcode and Apple developer account to configure the provisioning profiles and teams. - %1 sind nicht konfiguriert. Benutzen Sie Xcode und Ihr Apple-Entwicklerkonto, um die Provisioning-Profile und Teams zu konfigurieren. + %1 sind nicht konfiguriert. Verwenden Sie Xcode und Ihr Apple-Entwicklerkonto, um die Provisioning-Profile und Teams zu konfigurieren. Development teams @@ -35546,6 +35606,10 @@ Beispiel: *.cpp%1*.h Language server-specific JSON to pass via "initializationOptions" field of "initialize" request. Language Server-abhängiges JSON, das über das "initializationOptions"-Feld der "initialize"-Anfrage übergeben werden soll. + + File pattern: + Suchmuster für Dateinamen: + Executable: Ausführbare Datei: @@ -35566,7 +35630,7 @@ Beispiel: *.cpp%1*.h Additional JSON configuration sent to all running language servers for this project. See the documentation of the specific language server for valid settings. Zusätzliche JSON-Konfiguration, die an alle laufenden Language Server für dieses Projekt gesendet wird. -Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Language Servers. +Für gültige Einstellungen schauen Sie in die Dokumentation des verwendeten Language Servers. &Add @@ -35686,6 +35750,14 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu Inspect Language Clients... Language Clients inspizieren... + + Language Server Diagnostics + Language Server-Meldungen + + + Issues provided by the Language Server in the current document. + Probleme, die der Language Server im aktuellen Dokument gefunden hat. + Always On Immer an @@ -35791,6 +35863,10 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu Clear Löschen + + Deprecated + Veraltet + Incoming Eingehend @@ -35799,6 +35875,14 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu Outgoing Ausgehend + + Bases + Basistypen + + + Derived + Abgeleitet + Call Hierarchy Aufrufhierarchie @@ -35847,6 +35931,140 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu %1 löschen + + QtC::Lua + + Network Access + Netzwerkzugriff + + + Allow Internet Access + Internetzugriff erlauben + + + Allow the extension "%1" to fetch from the following URL: +%2 + Der Erweiterung "%1" erlauben, auf folgende URL zuzugreifen: +%2 + + + Remember choice + Auswahl speichern + + + Allow the extension "%1" to fetch data from the internet? + Der Erweiterung "%1" erlauben, Daten aus dem Internet zu laden? + + + Allow the extension "%1" to fetch datafrom the following URL: + + + Der Erweiterung "%1" erlauben, Daten von der folgenden URL zu laden: + + + + + Always Allow + Immer erlauben + + + Allow Once + Einmal erlauben + + + Deny + Verbieten + + + Fetching is not allowed for the extension "%1". (You can edit permissions in Preferences > Lua.) + Das Laden von Daten ist der Erweiterung "%1" nicht erlaubt. (Sie können die Rechte in Einstellungen > Lua ändern.) + + + Package info is not an object. + Paketinformation ist kein Objekt. + + + Installed package info is not an object. + Installierte Paketinformation ist kein Objekt. + + + Cannot create app data directory. + Das Verzeichnis für Anwendungsdaten konnte nicht angelegt werden. + + + Cannot write to package info: %1 + Paketinformation konnte nicht geschrieben werden: %1 + + + Cannot write to temporary file. + Temporäre Datei konnte nicht geschrieben werden. + + + Unarchiving failed. + Entpacken fehlgeschlagen. + + + Cannot open temporary file. + Temporäre Datei konnte nicht geöffnet werden. + + + Installing package(s) %1 + Installiere Paket(e) %1 + + + Install Package + Installiere Paket + + + The extension "%1" wants to install the following package(s): + + + Die Erweiterung "%1" möchte folgende Pakete installieren: + + + + + Install + Installieren + + + * %1 - %2 (from: [%3](%3)) + Markdown list item: %1 = package name, %2 = version, %3 = URL + * %1 - %2 (von: [%3](%3)) + + + Failed to run script %1: %2 + Das Ausführen des Skripts %1 ist fehlgeschlagen: %2 + + + No hook with the name "%1" found. + Kein Einsprungpunkt mit dem Namen "%1" gefunden. + + + Script did not return a table. + Das Skript hat keine Tabelle zurückgeliefert. + + + Extension info table did not contain a setup function. + Informationstabelle der Erweiterung enthält keine Setup-Funktion. + + + Failed to load plugin %1: %2 + Laden des Plugins %1 ist fehlgeschlagen: %2 + + + Cannot prepare extension setup: %1 + Setup der Erweiterung kann nicht vorbereitet werden: %1 + + + Extension setup function returned false. + Die Setup-Funktion der Erweiterung hat "false" zurückgeliefert. + + + Extension setup function returned error: %1 + Die Setup-Funktion der Erweiterung hat einen Fehler zurückgeliefert: %1 + + QtC::Macros @@ -36043,10 +36261,6 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu Status Status - - Unable to apply changes in Devices > MCU. - - No target selected. @@ -36392,6 +36606,10 @@ Für gültige Einstellungen schauen Sie in die Dokumentation des benutzten Langu No CMake tool was detected. Add a CMake tool in the <a href="cmake">CMake options</a> and select Apply. + + Cannot apply changes in Devices > MCU. + + MCU @@ -36492,15 +36710,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 +36758,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]". @@ -37024,6 +37242,14 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt Add Canvas Diagram Canvasdiagramm hinzufügen + + Toggle View and Filter Settings + Einstellungen für Ansicht und Filter umschalten + + + Ctrl+Shift+L + Ctrl+Shift+L + Synchronize Browser and Diagram Browser und Diagramm synchronisieren @@ -37034,7 +37260,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 +37268,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 @@ -37165,6 +37391,18 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt Add Class %1 Klasse %1 hinzufügen + + Add Package Link to %1 + Paket-Link zu %1 hinzufügen + + + Add Diagram Link to %1 + Diagramm-Link zu %1 hinzufügen + + + Add Document Link to %1 + Dokument-Link zu %1 hinzufügen + Add Package %1 Paket %1 hinzufügen @@ -37193,14 +37431,50 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt Config path: Konfigurationspfad: + + Select File Target + Zieldatei auswählen + + + Linked file: + Verlinkte Datei: + + + Select Image File + Bilddatei auswählen + + + Image: + Bild: + <font color=red>Model file must be reloaded.</font> <font color=red>Modell muss neu geladen werden.</font> + + Selecting Image + Bild auswählen + + + Unable to read image file "%1". + Bilddatei "%1" konnte nicht gelesen werden. + Zoom: %1% Vergrößerung: %1% + + Opening File + Öffne Datei + + + File "%1" does not exist. + Datei "%1" existiert nicht. + + + Add Related Elements... + Zugehörige Elemente hinzufügen... + Update Include Dependencies Include-Abhängigkeiten aktualisieren @@ -37347,7 +37621,7 @@ Dies ist hilfreich, wenn das Build-Verzeichnis beschädigt ist oder das Projekt QtC::PerfProfiler Stack snapshot size (kB): - Größe des Stack-Abbilds (kB): + Größe des Stackabbilds (kB): Call graph mode: @@ -37964,7 +38238,7 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z Edit File - Datei zum Editieren anfordern + Datei zum Bearbeiten anfordern Add @@ -38316,15 +38590,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 +38618,7 @@ Weitere Erklärungen sind möglicherweise in "Ausgabe der Anwendung" z User: - Nutzer: + Benutzer: No executable specified @@ -38601,7 +38875,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 @@ -38683,6 +38957,11 @@ Außer: %2 Compile Output Kompilierung + + compile-output.txt + file name suggested for saving compile output + kompilierungsausgabe.txt + Show Compile &Output Ausgabe der &Kompilierung zeigen @@ -38701,7 +38980,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" @@ -38764,7 +39043,7 @@ konnte dem Projekt "%2" nicht hinzugefügt werden. Hide Source and Header Groups - Source- und Headergruppen ausblenden + Quelltext- und Header-Gruppenverzeichnisse ausblenden Synchronize with Editor @@ -39039,6 +39318,10 @@ Title of a the cloned RunConfiguration window, text of the window Ctrl+Shift+O Ctrl+Shift+O + + Open Workspace... + Workspace öffnen... + Open File Datei öffnen @@ -39361,6 +39644,10 @@ Bitte versuchen Sie es erneut. Load Project Projekt laden + + Open Workspace + Workspace öffnen + Sanitizer Category for sanitizer issues listed under 'Issues' @@ -39387,10 +39674,6 @@ Bitte versuchen Sie es erneut. <h3>Project already open</h3> <h3>Projekt bereits geöffnet</h3> - - Failed opening project "%1": Project is not a file. - Das Projekt "%1" konnte nicht geöffnet werden: Die angegebene Projektdatei ist keine Datei. - Open Project in "%1" Projekt in "%1" öffnen @@ -39451,7 +39734,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 @@ -40019,6 +40302,22 @@ Rename %2 to %3 anyway? The project was not parsed successfully. Das Projekt konnte nicht erfolgreich ausgewertet werden. + + No build device is set for the kit "%1". + Es ist kein Gerät (Erstellung) für das Kit "%1" eingerichtet. + + + You can try mounting the folder in your device settings. + Sie können in den Geräteeinstellungen versuchen, das Verzeichnis einzuhängen. + + + The build device "%1" cannot reach the project directory. + Das Gerät "%1" für das Erstellen kann das Projektverzeichnis nicht erreichen. + + + The build device "%1" cannot reach the build directory. + Das Gerät "%1" für das Erstellen kann das Build-Verzeichnis nicht erreichen. + Default The name of the build configuration created by default for a autotools project. @@ -40249,11 +40548,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 @@ -40307,6 +40606,11 @@ Aktivieren Sie dies, wenn Sie 32bit-x86-Binärdateien erstellen wollen, ohne ein Stop running program. Laufendes Programm anhalten. + + application-output-%1.txt + file name suggested for saving application output, %1 = run configuration display name + anwendungsausgabe-%1.txt + Application Output Ausgabe der Anwendung @@ -40588,7 +40892,7 @@ Aktivieren Sie dies, wenn Sie 32bit-x86-Binärdateien erstellen wollen, ohne ein <html><head/><body><p>The name of the kit suitable for generating directory names. This value is used for the variable <i>%1</i>, which for example determines the name of the shadow build directory.</p></body></html> - <html><head/><body><p>Der Name des Kits, der zum Erzeugen von Verzeichnisnamen geeignet ist. Dieser Wert wird für die Variable <i>%1</i> benutzt, die zum Beispiel den Namen des Shadow-Build-Verzeichnisses bestimmt.</p></body></html> + <html><head/><body><p>Der Name des Kits, der zum Erzeugen von Verzeichnisnamen geeignet ist. Dieser Wert wird für die Variable <i>%1</i> verwendet, die zum Beispiel den Namen des Shadow-Build-Verzeichnisses bestimmt.</p></body></html> File system name: @@ -40872,7 +41176,7 @@ Aktivieren Sie dies, wenn Sie 32bit-x86-Binärdateien erstellen wollen, ohne ein The process cannot access the file because it is being used by another process. Please close all running instances of your application before starting a build. - Der Prozess kann nicht auf die Datei zugreifen, da sie von einem anderen Prozess benutzt wird. + Der Prozess kann nicht auf die Datei zugreifen, da sie von einem anderen Prozess verwendet wird. Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. @@ -40891,10 +41195,6 @@ Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. DebugBreakProcess failed: DebugBreakProcess schlug fehl: - - could not break the process. - konnte den Prozess nicht anhalten. - Cannot kill process with pid %1: %2 Der Prozess mit der PID %1 konnte nicht beendet werden: %2 @@ -40903,14 +41203,6 @@ Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. Cannot interrupt process with pid %1: %2 Der Prozess mit der PID %1 konnte nicht unterbrochen werden: %2 - - %1 does not exist. If you built %2 yourself, check out https://code.qt.io/cgit/qt-creator/binary-artifacts.git/. - %1 existiert nicht. Wenn Sie %2 selbst erstellt haben, checken Sie bitte auch https://code.qt.io/cgit/qt-creator/binary-artifacts.git/ aus. - - - Cannot start %1. Check src\tools\win64interrupt\win64interrupt.c for more information. - %1 konnte nicht gestartet werden. Für weiterführende Informationen siehe auch src\tools\win64interrupt\win64interrupt.c. - Import Build From... Build importieren von... @@ -41052,11 +41344,11 @@ Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. File Generation Failed - Dateierzeugung gescheitert + Dateierzeugung fehlgeschlagen The wizard failed to generate files.<br>The error message was: "%1". - Der Wizard scheiterte beim Erzeugen von Dateien.<br>Die Fehlermeldung war: "%1". + Der Wizard konnte Dateien nicht erzeugen.<br>Die Fehlermeldung war: "%1". Failed to Overwrite Files @@ -41076,7 +41368,7 @@ Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. Failed to Polish Files - "Polish" von Dateien gescheitert + "Polish" von Dateien fehlgeschlagen Failed to Open Files @@ -41285,10 +41577,10 @@ Bitte schließen Sie alle laufenden Instanzen Ihrer Anwendung vor dem Erstellen. Pfad - Creates a widget-based Qt application that contains a Qt Designer-based main window and C++ source and header files to implement the application logic. + Creates a widget-based Qt application that contains a Qt Widgets Designer-based main window and C++ source and header files to implement the application logic. Preselects a desktop Qt for building the application if available. - Erstellt eine Widget-basierte Qt-Anwendung mit einem Qt Designer-basierten Hauptfenster und C++-Quell- und Headerdateien zur Implementierung der Applikationslogik. + Erstellt eine Widget-basierte Qt-Anwendung mit einem Qt Widgets Designer-basierten Hauptfenster und C++-Quell- und Headerdateien zur Implementierung der Applikationslogik. Wählt eine für Desktop-Entwicklung geeignete Qt-Version aus, sofern verfügbar. @@ -41318,7 +41610,7 @@ Wählt eine für Desktop-Entwicklung geeignete Qt-Version aus, sofern verfügbar Use this "compat" version if you want to use other build systems than CMake or Qt versions lower than 6. Erstellt eine Qt Quick-Anwendung, die ein leeres Fenster enthält. -Nutzen Sie diese "Kompatibilitätsversion", falls Sie andere Buildsysteme als CMake oder frühere Qt-Versionen als Qt 6 benutzen wollen. +Nutzen Sie diese "Kompatibilitätsversion", falls Sie andere Buildsysteme als CMake oder frühere Qt-Versionen als Qt 6 verwenden wollen. Qt Quick Application (compat) @@ -41381,11 +41673,11 @@ Wahlweise können Sie ein Projekt erstellen, das in Qt Design Studio geöffnet w Formularvorlage - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Erstellt ein Qt-Designer-Formular, das Sie zu einem Qt Widget-Projekt hinzufügen können. Dies ist nützlich, wenn Sie bereits eine Klasse für die Anwendungslogik haben. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Erstellt ein Qt-Widgets-Designer-Formular, das Sie zu einem Qt Widget-Projekt hinzufügen können. Dies ist nützlich, wenn Sie bereits eine Klasse für die Anwendungslogik haben. - Qt Designer Form + Qt Widgets Designer Form Qt-Designer-Formular @@ -41452,7 +41744,7 @@ Wahlweise können Sie ein Projekt erstellen, das in Qt Design Studio geöffnet w You must tell Qt Creator which test framework is used inside the project. You should not mix multiple test frameworks in a project. - Sie müssen Qt Creator mitteilen, welches Test-Framework im Projekt benutzt wird. + Sie müssen Qt Creator mitteilen, welches Test-Framework im Projekt verwendet wird. Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen. @@ -41824,7 +42116,7 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen. Specify basic information about the classes for which you want to generate skeleton source code files. - Geben Sie Informationen bezüglich der Klassen ein, für die Sie Quelltexte generieren wollen. + Geben Sie Informationen bezüglich der Klassen ein, für die Sie Quelltext generieren wollen. Fully qualified name, including namespaces @@ -41899,8 +42191,8 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen.Leeres Fenster - Creates a Qt for Python application that includes a Qt Designer-based widget (ui file). Requires .ui to Python conversion. - Erstellt eine Qt for Python-Anwendung, die ein Qt Designer-basiertes Widget (ui-Datei) enthält. Erfordert Umwandlung von .ui nach Python. + Creates a Qt for Python application that includes a Qt Widgets Designer-based widget (ui file). Requires .ui to Python conversion. + Erstellt eine Qt for Python-Anwendung, die ein Qt Widgets Designer-basiertes Widget (ui-Datei) enthält. Erfordert Umwandlung von .ui nach Python. Window UI @@ -42048,7 +42340,7 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen. The minimum version of Qt you want to build the application for - Die niedrigste Qt-Version, die Sie zum Bauen der Anwendung benutzen wollen + Die niedrigste Qt-Version, die Sie zum Bauen der Anwendung verwenden wollen This wizard creates a simple unit test project using Boost. @@ -42651,46 +42943,38 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen.Page mit typeId "%1" hat ungültigen "index". - Path "%1" does not exist when checking Json wizard search paths. - - Pfad "%1" existiert nicht in Json-Wizard Suchpfaden. - + Path "%1" does not exist when checking JSON wizard search paths. + Pfad "%1" existiert nicht in JSON-Wizard Suchpfaden. - Checking "%1" for %2. - - Prüfe "%1" für %2. - + Checking "%1" for %2. + Prüfe "%1" für %2. - * Failed to parse "%1":%2:%3: %4 - - * Konnte "%1" nicht auswerten: %2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + * Konnte "%1" nicht auswerten: %2:%3: %4 + + + * Did not find a JSON object in "%1". + * Kein JSON-Objekt in "%1" gefunden. + + + * Configuration found and parsed. + * Konfiguration gefunden und ausgewertet. * Did not find a JSON object in "%1". - * Kein JSON-Objekt in "%1" gefunden. + * Konnte kein JSON-Objekt in "%1" finden. - * Configuration found and parsed. - - * Konfiguration gefunden und ausgewertet. - + * Version %1 not supported. + * Version %1 nicht unterstützt. - * Version %1 not supported. - - * Version %1 nicht unterstützt. - - - - * Failed to create: %1 - - * Erstellen fehlgeschlagen: %1 - + * Failed to create: %1 + * Erstellen fehlgeschlagen: %1 The platform selected for the wizard. @@ -42721,10 +43005,8 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen.Bilddatei "%1" nicht gefunden. - JsonWizard: "%1" not found - - JsonWizard: "%1" nicht gefunden - + JsonWizard: "%1" not found. + JsonWizard: "%1" nicht gefunden. key not found. @@ -42838,6 +43120,11 @@ Sie sollten nicht mehrere Test-Frameworks im selben Projekt mischen.%1 is something like "Active project" %1: Vollständiger Pfad zur Hauptdatei. + + %1: Full path to Project Directory. + %1 is something like "Active project" + %1: Vollständiger Pfad zum Projektverzeichnis. + %1: The name of the active kit. %1 is something like "Active project" @@ -43189,6 +43476,14 @@ Sie werden erhalten. &Configure Project Projekt &konfigurieren + + Show All Kits + Alle Kits anzeigen + + + Hide Inactive Kits + Inaktive Kits verbergen + Enable Kit for Project "%1" Kit für das Projekt "%1" aktivieren @@ -43340,7 +43635,7 @@ Was soll %1 tun? A version control operation failed for the following files. Please check your repository. - Für die folgenden Dateien ist eine Versionskontroll-Operation gescheitert. Bitte prüfen Sie Ihr Repository. + Für die folgenden Dateien ist eine Versionskontroll-Operation fehlgeschlagen. Bitte prüfen Sie Ihr Repository. Failure Updating Project @@ -43382,6 +43677,14 @@ Was soll %1 tun? Use debug version of frameworks (DYLD_IMAGE_SUFFIX=_debug) Debug-Version von Frameworks verwenden (DYLD_IMAGE_SUFFIX=_debug) + + Emulator + Emulator + + + Launcher: + Startprogramm: + X11 Forwarding: X11-Weiterleitung: @@ -43565,8 +43868,8 @@ Was soll %1 tun? Das Build-Verzeichnis enthält das möglicherweise problematische Zeichen "%1". - This warning can be suppressed <a href="dummy">here</a>. - Diese Warnung kann <a href="dummy">hier</a> unterdrückt werden. + This warning can be suppressed <a href="dummy">here</a>. + Diese Warnung kann <a href="dummy">hier</a> unterdrückt werden. The project is currently being parsed. @@ -43742,11 +44045,11 @@ Was soll %1 tun? Either switches MSVC to English or keeps the language and just forces UTF-8 output (may vary depending on the used MSVC compiler). - Stellt MSVC entweder auf Englisch um oder behält die Sprache bei und erzwingt UTF-8-Ausgabe (abhängig vom benutzen MSVC-Compiler). + Stellt MSVC entweder auf Englisch um oder behält die Sprache bei und erzwingt UTF-8-Ausgabe (abhängig vom verwendeten MSVC-Compiler). Additional build environment settings when using this kit. - Zusätzliche Build-Umgebungseinstellungen bei Benutzung dieses Kits. + Zusätzliche Build-Umgebungseinstellungen bei Verwendung dieses Kits. The environment setting value is invalid. @@ -43806,7 +44109,7 @@ Was soll %1 tun? Use parsers from kit: - Parser vom Kit benutzen: + Parser vom Kit verwenden: Cannot Parse @@ -43833,6 +44136,15 @@ Was soll %1 tun? Building "%1" is disabled: %2<br> Das Erstellen von "%1" ist deaktiviert: %2<br> + + s + Suffix for "seconds" + s + + + The amount of seconds to wait between a "soft kill" and a "hard kill" of a running application. + Die Zeit in Sekunden, die zwischen einem "soft kill" und einem "hard kill" einer laufenden Anwendung gewartet werden soll. + Current directory Arbeitsverzeichnis @@ -43929,6 +44241,14 @@ Was soll %1 tun? Use jom instead of nmake jom statt nmake verwenden + + Show all kits in "Build & Run" in "Projects" mode + Alle Kits in "Erstellung und Ausführung" im Modus "Projekte" anzeigen + + + Show also inactive kits in "Build & Run" in "Projects" mode. + Zeige auch inaktive Kits in "Erstellung und Ausführung" im Modus "Projekte". + Environment changes to apply to run configurations, but not build configurations. Änderungen der Umgebung, die auf Ausführungskonfigurationen, aber nicht auf Build-Konfigurationen angewendet werden sollen. @@ -43961,6 +44281,10 @@ Was soll %1 tun? Default for "Run in terminal": Vorgabe für "Im Terminal ausführen": + + Time to wait before force-stopping applications: + Zu wartende Zeit vor dem erzwungenen Beenden von Anwendungen: + Files Dateien @@ -44051,19 +44375,23 @@ Was soll %1 tun? Use Project Default - Projekt-Vorgabe benutzen + Projekt-Vorgabe verwenden Default build directory: Vorgabe-Build-Verzeichnis: + + Template used to construct the default build directory.<br><br>The default value can be set using the environment variable <tt>%1</tt>. + Vorlage für das Standard-Build-Verzeichnis.<br><br>Der Standardwert kann über die Umgebungsvariable <tt>%1</tt> gesetzt werden. + QML debugging: QML-Debuggen: Use qmlcachegen: - qmlcachegen benutzen: + qmlcachegen verwenden: Default Build Properties @@ -44130,7 +44458,7 @@ Was soll %1 tun? If available, use a different margin. For example, the ColumnLimit from the ClangFormat plugin. - Benutzt unterschiedlichen Rand abhängig vom Kontext, falls verfügbar. Zum Beispiel das ColumnLimit vom ClangFormat Plugin. + Verwendet unterschiedlichen Rand abhängig vom Kontext, falls verfügbar. Zum Beispiel das ColumnLimit vom ClangFormat Plugin. Files in All Project Directories @@ -44195,7 +44523,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. @@ -44219,7 +44547,7 @@ fails because Clang does not understand the target architecture. Imports existing projects that do not use qmake, CMake, Qbs, Meson, or Autotools.<p>This creates a project file that allows you to use %1 as a code editor and as a launcher for debugging and analyzing tools. If you want to build the project, you might need to edit the generated project file. - Importiert ein existierendes Projekt, dass nicht qmake, CMake, Qbs, Meson oder Autotools benutzt.<p>Dies erstellt eine Projektdatei, die Ihnen erlaubt, %1 als Code-Editor und zum Starten des Debuggers und von Analysewerkzeugen zu benutzen. Wenn Sie das Projekt bauen wollen, müssen Sie die generierte Datei möglicherweise anpassen. + Importiert ein existierendes Projekt, dass nicht qmake, CMake, Qbs, Meson oder Autotools verwendet.<p>Dies erstellt eine Projektdatei, die Ihnen erlaubt, %1 als Code-Editor und zum Starten des Debuggers und von Analysewerkzeugen zu verwenden. Wenn Sie das Projekt bauen wollen, müssen Sie die generierte Datei möglicherweise anpassen. Unknown build system "%1" @@ -44276,6 +44604,18 @@ fails because Clang does not understand the target architecture. unavailable nicht verfügbar + + You can edit this configuration inside the .qtcreator/project.json file. + Sie können diese Konfiguration über die Datei ".qtcreator/project.json" bearbeiten. + + + Exclude from Project + Vom Projekt ausschließen + + + Rescan Workspace + Workspace erneut durchsuchen + QtC::Python @@ -44361,7 +44701,7 @@ fails because Clang does not understand the target architecture. Use Python Language Server - Python Language Server benutzen + Python Language Server verwenden For a complete list of available options, consult the [Python LSP Server configuration documentation](%1). @@ -44409,7 +44749,7 @@ fails because Clang does not understand the target architecture. You can install PySide from PyPi (Community OSS version) or from your Qt installation location, if you are using the Qt Installer and have a commercial license. - Sie können PySide von PyPI (Community OSS-Version) oder, falls Sie den Qt-Installer benutzen und eine kommerzielle Lizenz besitzen, von Ihrer Qt-Installation installieren. + Sie können PySide von PyPI (Community OSS-Version) oder, falls Sie den Qt-Installer verwenden und eine kommerzielle Lizenz besitzen, von Ihrer Qt-Installation installieren. Select which version to install: @@ -44436,8 +44776,29 @@ fails because Clang does not understand the target architecture. Installieren - Install Python Packages - Python-Pakete installieren + Update Requirements + Requirements aktualisieren + + + Install Requirements + Requirements installieren + + + Update %1 + %1 = package name + %1 aktualisieren + + + Install %1 + %1 installieren + + + Update Packages + Pakete aktualisieren + + + Install Packages + Pakete installieren Running "%1" to install %2. @@ -44540,6 +44901,22 @@ fails because Clang does not understand the target architecture. Install Python language server (PyLS) for %1 (%2). The language server provides Python specific completion and annotation. Python Language Server (PyLS) für %1 (%2) installieren. Der Language Server stellt Code-Vervollständigung und Annotationen für Python zur Verfügung. + + Update Python language server (PyLS) for %1 (%2). + Python Language Server (PyLS) für %1 (%2) aktualisieren. + + + Always Update + Immer aktualisieren + + + Update + Aktualisieren + + + Never + Niemals + Searching Python binaries... Suche ausführbare Python-Dateien... @@ -44558,7 +44935,7 @@ fails because Clang does not understand the target architecture. An item of Python wizard page data expects a "trKey" field containing the UI visible string for that Python version and a "value" field containing an object with a "PySideVersion" field used for import statements in the Python files. - Ein Eintrag in den "items" im Feld "data" einer Python-Assistenzseite erwartet ein Feld "trKey", das den Anzeigenamen für diese Python-Version enthält, und ein Feld "value", das ein Objekt mit einem Feld "PySideVersion" enthält, das für import-Anweisungen in den Python-Dateien benutzt wird. + Ein Eintrag in den "items" im Feld "data" einer Python-Assistenzseite erwartet ein Feld "trKey", das den Anzeigenamen für diese Python-Version enthält, und ein Feld "value", das ein Objekt mit einem Feld "PySideVersion" enthält, das für import-Anweisungen in den Python-Dateien verwendet wird. PySide version: @@ -44574,7 +44951,7 @@ fails because Clang does not understand the target architecture. The interpreter used for Python based projects. - Der für Python-basierte Projekte benutzte Interpreter. + Der für Python-basierte Projekte verwendete Interpreter. No Python setup. @@ -44590,7 +44967,7 @@ fails because Clang does not understand the target architecture. Python "%1" does not contain a usable pip. pip is needed to install Python packages from the Python Package Index, like PySide and the Python language server. To use any of that functionality ensure that pip is installed for that Python. - Python "%1" enthält kein verwendbares pip. pip wird für das Installieren von Python-Paketen wie PySide und dem Python Language Server vom Python Package Index benötigt. Um diese Funktionen benutzen zu können, stellen Sie sicher, dass pip für dieses Python installiert ist. + Python "%1" enthält kein verwendbares pip. pip wird für das Installieren von Python-Paketen wie PySide und dem Python Language Server vom Python Package Index benötigt. Um diese Funktionen verwenden zu können, stellen Sie sicher, dass pip für dieses Python installiert ist. Python "%1" does not contain a usable venv. venv is the recommended way to isolate a development environment for a project from the globally installed Python. @@ -44605,8 +44982,8 @@ fails because Clang does not understand the target architecture. Pfad zum Python-Interpreter - No Python interpreter set for kit "%1" - Kein Python-Interpreter für das Kit "%1" eingerichtet + No Python interpreter set for kit "%1". + Kein Python-Interpreter für das Kit "%1" eingerichtet. @@ -44900,7 +45277,7 @@ fails because Clang does not understand the target architecture. Use %1 settings directory for Qbs %1 == "Qt Creator" or "Qt Design Studio" - Das Verzeichnis für Einstellungen von %1 auch für Qbs benutzen + Das Verzeichnis für Einstellungen von %1 auch für Qbs verwenden Path to qbs executable: @@ -44994,20 +45371,20 @@ Die betroffenen Dateien sind: Command failed on device "%1". - - stdout was: "%1" - - - - stderr was: "%1" - - Commands on device "%1" finished successfully. - Boot2Qt Device + stdout was: "%1". + + + + stderr was: "%1". + + + + Boot to Qt Device @@ -45043,7 +45420,7 @@ Die betroffenen Dateien sind: - Boot2Qt Network Device Setup + Boot to Qt Network Device Setup @@ -45066,6 +45443,10 @@ Die betroffenen Dateien sind: Executable on device: Ausführbare Datei auf Mobilgerät: + + Run on Boot to Qt Device + + Remote path not set Der entfernte Pfad ist nicht gesetzt @@ -45075,11 +45456,7 @@ Die betroffenen Dateien sind: Ausführbare Datei auf Hostrechner: - Run on Boot2Qt Device - - - - The remote executable must be set in order to run on a Boot2Qt device. + The remote executable must be set to run on a Boot to Qt device. @@ -45087,7 +45464,7 @@ Die betroffenen Dateien sind: - Qt Debug Bridge device %1 + Boot to Qt device %1 @@ -45134,10 +45511,6 @@ Die betroffenen Dateien sind: Starting QDB host server. - - Deploy to Boot2Qt target - - Set this application to start by default @@ -45162,6 +45535,10 @@ Die betroffenen Dateien sind: Flash Boot to Qt Device + + Deploy to Boot to Qt target + + Could not check and possibly stop running application. @@ -45183,7 +45560,7 @@ Die betroffenen Dateien sind: - Boot2Qt: %1 + Boot to Qt: %1 @@ -45542,24 +45919,20 @@ Weder der Pfad zur Bibliothek noch der Pfad zu den Headerdateien wird zur .pro-D Qt Custom Designer Widget - Benutzerdefiniertes Widget für Qt Designer + Benutzerdefiniertes Widget für Qt Widgets Designer Creates a Qt Custom Designer Widget or a Custom Widget Collection. - Erstellt ein oder mehrere benutzerdefinierte Widgets für Qt Designer. + Erstellt ein oder mehrere benutzerdefinierte Widgets für Qt Widgets Designer. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - Dieser Assistent erstellt ein Projekt mit einem oder mehreren benutzerdefinierten Widgets für Qt Designer. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + Dieser Assistent erstellt ein Projekt mit einem oder mehreren benutzerdefinierten Widgets für Qt Widgets Designer. Creating multiple widget libraries (%1, %2) in one project (%3) is not supported. Die Erzeugung von mehreren Bibliotheken (%1, %2) in einem Projekt (%3) wird nicht unterstützt. - - Unable to start "%1" - "%1" kann nicht gestartet werden - Could not load kits in a reasonable amount of time. Kits konnten nicht in angemessener Zeit geladen werden. @@ -45569,8 +45942,12 @@ Weder der Pfad zur Bibliothek noch der Pfad zu den Headerdateien wird zur .pro-D Die Anwendung "%1" konnte nicht gefunden werden. - Qt Designer is not responding (%1). - Qt Designer antwortet nicht (%1). + Unable to start "%1". + "%1" kann nicht gestartet werden. + + + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer antwortet nicht (%1). Unable to create server socket: %1 @@ -45976,7 +46353,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 @@ -46025,7 +46402,7 @@ Bitte aktualisieren Sie Ihr Kit (%3) oder wählen Sie eine mkspec für qmake, di Debug connection failed. - Debug-Verbindung gescheitert. + Debug-Verbindung fehlgeschlagen. @@ -46261,9 +46638,9 @@ For qmlRegister... calls, make sure that you define the Module URI as a string l Import-Verzeichnisse: %2 -Für qmake-Projekte benutzen Sie die Variable QML_IMPORT_PATH, um Importpfade hinzuzufügen. +Für qmake-Projekte verwenden Sie die Variable QML_IMPORT_PATH, um Importpfade hinzuzufügen. Für Qbs-Projekte geben Sie eine qmlImportPaths-Eigenschaft in Ihrem Produkt an, um Importpfade hinzuzufügen. -Für qmlproject-Projekte benutzen Sie die importPaths-Eigenschaft, um Importpfade hinzuzufügen. +Für qmlproject-Projekte verwenden Sie die importPaths-Eigenschaft, um Importpfade hinzuzufügen. Für CMake-Projekte stellen Sie sicher, dass die Variable QML_IMPORT_PATH in CMakeCache.txt steht. Für qmlRegister...-Aufrufe stellen Sie sicher, dass Sie den Modul-URI als Zeichenkettenliteral definieren. @@ -46288,9 +46665,9 @@ For CMake projects, make sure QML_IMPORT_PATH variable is in CMakeCache.txt. Importpfade: %3 -Für qmake-Projekte benutzen Sie die Variable QML_IMPORT_PATH, um Importpfade hinzuzufügen. +Für qmake-Projekte verwenden Sie die Variable QML_IMPORT_PATH, um Importpfade hinzuzufügen. Für Qbs-Projekte geben Sie eine qmlImportPaths-Eigenschaft in Ihrem Produkt an, um Importpfade hinzuzufügen. -Für qmlproject-Projekte benutzen Sie die Eigenschaft importPaths, um Importpfade hinzuzufügen. +Für qmlproject-Projekte verwenden Sie die Eigenschaft importPaths, um Importpfade hinzuzufügen. Für CMake-Projekte stellen Sie sicher, dass die Variable QML_IMPORT_PATH in CMakeCache.txt steht. @@ -46388,11 +46765,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 +46777,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. @@ -46602,10 +46979,6 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code Use %1 instead of 'var' or 'variant' to improve performance. Zur Steigerung der Ausführungsgeschwindigkeit sollte %1 statt 'var' oder 'variant' verwendet werden. - - Imperative code is not supported in Qt Design Studio. - Imperativer Code wird von Qt Design Studio nicht unterstützt. - This type (%1) is not supported in Qt Design Studio. Dieser Typ (%1) wird von Qt Design Studio nicht unterstützt. @@ -46686,6 +47059,10 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code A State cannot have a child item (%1). Ein State kann kein Kind-Item haben (%1). + + JavaScript can break the visual tooling in Qt Design Studio. + + Duplicate import (%1). Doppelter Import (%1). @@ -46716,7 +47093,7 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code var "%1" is used before its declaration. - Variable "%1" wird vor Deklaration benutzt. + Variable "%1" wird vor Deklaration verwendet. "%1" already is a var. @@ -46728,7 +47105,7 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code Function "%1" is used before its declaration. - Funktion "%1" wird vor ihrer Deklaration benutzt. + Funktion "%1" wird vor ihrer Deklaration verwendet. Could not resolve the prototype "%1" of "%2". @@ -46756,7 +47133,7 @@ Weitere Informationen finden Sie auf der Dokumentationsseite "Checking Code Array value expected. - Feld erwartet. + Array erwartet. %1 value expected. @@ -46792,7 +47169,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 @@ -47041,7 +47418,7 @@ Sie können eine Annotation "// @uri My.Module.Uri" hinzufügen, um de Use custom command instead of built-in formatter - Benutzerdefiniertes Kommando anstatt des integrierten Formatierers benutzen + Benutzerdefiniertes Kommando anstatt des integrierten Formatierers verwenden Command: @@ -47067,13 +47444,33 @@ Sie können eine Annotation "// @uri My.Module.Uri" hinzufügen, um de Qt Creator Qt Creator + + Turn on + + + + Allow versions below Qt %1 + + + + Use advanced features (renaming, find usages, and so on) (experimental) + + + + Use from latest Qt version + + + + Create .qmlls.ini files for new projects + + QML Language Server QML Language Server Use customized static analyzer - Angepasste statische Analyse benutzen + Angepasste statische Analyse verwenden Enabled @@ -47115,18 +47512,6 @@ Sie können eine Annotation "// @uri My.Module.Uri" hinzufügen, um de Restrict to files contained in the current project Auf Dateien des aktuellen Projekts beschränken - - Enable QML Language Server (EXPERIMENTAL!) - QML Language Server aktivieren (EXPERIMENTELL!) - - - Use QML Language Server advanced features (renaming, find usages and co.) (EXPERIMENTAL!) - Fortgeschrittene Funktionen vom QML Language Server benutzen (umbenennen, Verweise finden und weiteres) (EXPERIMENTELL!) - - - Use QML Language Server from latest Qt version - QML Language Server der neuesten Qt-Version benutzen - Features Zusatzfunktionen @@ -47313,7 +47698,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 @@ -48291,125 +48676,12 @@ Speichern fehlgeschlagen. Remember my choice - - Select Files to Generate - - - - Start CMakeFiles.txt generation - - - - Advanced Options - Erweiterte Optionen - - - File %1 will be created. - - - - - File %1 will be overwritten. - - - - - File %1 contains invalid characters and will be skipped. - - - - - This file already exists and will be overwritten. - - - - This file or folder will be created. - - - - Generate CMake Build Files... - - Export Project - The project is not properly structured for automatically generating CMake files. - -Aborting process. - -The following files or directories are missing: - -%1 - - - - Cannot Generate CMake Files - - - - Export as Latest Project Format... - - - - Creating Project - - - - Creating project failed. -%1 - - - - Creating project succeeded. - - - - Unable to write to directory -%1. - - - - This process creates a copy of the existing project. The new project's folder structure is adjusted for CMake build process and necessary related new files are generated. - -The new project can be opened in Qt Creator using the main CMakeLists.txt file. - - - - Name: - Name: - - - Create in: - Erzeugen in: - - - Name is empty. - Der Name ist leer. - - - Name must not start with "%1". - - - - Name must begin with a capital letter - - - - Name must contain only letters, numbers or characters - _. - - - - Target is not a directory. - - - - Cannot write to target directory. - - - - Project directory already exists. + Enable Automatic CMake Generation @@ -48474,11 +48746,11 @@ Are you sure? - Failed to find valid build system + Cannot find a valid build system. - Failed to create valid build directory + Cannot create a valid build directory. @@ -48502,7 +48774,7 @@ Are you sure? - Failed to find valid Qt for MCUs kit + Cannot find a valid Qt for MCUs kit. @@ -49299,7 +49571,7 @@ wirklich löschen? The Qt library to use for all projects using this kit.<br>A Qt version is required for qmake-based projects and optional when using other build systems. - Die für alle Projekte, die dieses Kit verwenden, zu benutzende Qt-Bibliothek.<br>Für qmake-basierende Projekte ist diese Angabe erforderlich, für andere Build-Systeme optional. + Die zu verwendende Qt-Bibliothek für alle Projekte, die dieses Kit verwenden.<br>Für qmake-basierende Projekte ist diese Angabe erforderlich, für andere Build-Systeme optional. None @@ -49578,10 +49850,8 @@ Zusätzlich wird die Verbindung zum Gerät getestet. Verbinde zu Gerät... - Connected. Now doing extended checks. - - Verbunden. Führe erweiterte Überprüfungen aus. - + Connected. Now doing extended checks. + Verbunden. Führe erweiterte Überprüfungen aus. Basic connectivity test failed, device is considered unusable. @@ -49625,7 +49895,7 @@ Zusätzlich wird die Verbindung zum Gerät getestet. "%1" will be used for deployment, because "%2" and "%3" are not available. - "%1" wird für das Deployment benutzt, da "%2" und "%3" nicht verfügbar sind. + "%1" wird für das Deployment verwendet, da "%2" und "%3" nicht verfügbar sind. Checking if required commands are available... @@ -49769,7 +50039,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: @@ -49808,9 +50078,19 @@ Zusätzlich wird die Verbindung zum Gerät getestet. Direct Direkt + + Use SSH port forwarding for debugging + + + + Enable debugging on remote targes which cannot expose gdbserver ports. +The ssh tunneling is used to map the remote gdbserver port to localhost. +The local and remote ports are determined automatically. + + &Username: - &Nutzername: + &Benutzername: QML runtime executable: @@ -49907,6 +50187,10 @@ Der Steuerprozess konnte nicht gestartet werden. Can't send control signal to the %1 device. The device might have been disconnected. Senden des Steuersignals zum Gerät %1 ist fehlgeschlagen. Das Gerät ist möglicherweise nicht verbunden. + + Device "%1" is disconnected. + + Remote Linux Entferntes Linuxgerät @@ -49928,8 +50212,19 @@ Der Steuerprozess konnte nicht gestartet werden. Das Gerät war bei einem vorherigen Verbindungsversuch nicht erreichbar.<br>Es werden keine weiteren Verbindungsversuche unternommen, bis das Gerät manuell über einen erfolgreichen Verbindungstest in den <a href="dummy">Einstellungen</a> zurückgesetzt wurde. - Failed: %1 - Fehlgeschlagen: %1 + Created directory: "%1". + + + + + Copied %1/%2: "%3" -> "%4". + + %1/%2 = progress in the form 4/15, %3 and %4 = source and target file paths + + + + Failed to deploy files. + Device is considered unconnected. Re-run device test to reset state. @@ -49947,22 +50242,6 @@ Der Steuerprozess konnte nicht gestartet werden. "sftp" binary "%1" does not exist. Ausführbare "sftp"-Datei "%1" existiert nicht. - - Creating directory: %1 - - Erstelle Verzeichnis: %1 - - - - Failed. - Fehlgeschlagen. - - - Copying %1/%2: %3 -> %4 - - Kopiere %1/%2: %3 -> %4 - - Clean Environment Saubere Umgebung @@ -50071,31 +50350,31 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Use sftp if available. Otherwise use default transfer. - Benutze SFTP, sofern verfügbar. Sonst verwende Standardmethode. + Verwende SFTP, sofern verfügbar. Sonst verwende Standardmethode. Use default transfer. This might be slow. - Benutze Standardmethode. Dies könnte langsam sein. + Verwende Standardmethode. Dies könnte langsam sein. - Unknown error occurred while trying to create remote directories - Beim Erstellen von entfernten Verzeichnissen ist ein unbekannter Fehler aufgetreten + Unknown error occurred while trying to create remote directories. + Beim Erstellen von entfernten Verzeichnissen ist ein unbekannter Fehler aufgetreten. Transfer method was downgraded from "%1" to "%2". If this is unexpected, please re-test device "%3". Die Übertragungsmethode wurde von "%1" auf "%2" zurückgestuft. Falls dies unerwartet auftritt, führen Sie bitte die Gerätetests für "%3" erneut aus. - rsync failed to start: %1 - rsync konnte nicht gestartet werden: %1 + %1 failed to start: %2 + - rsync crashed. - rsync ist abgestürzt. + %1 crashed. + %1 ist abgestürzt. - rsync failed with exit code %1. - rsync scheiterte mit dem Rückgabewert %1. + %1 failed with exit code %2. + Deploy files @@ -50107,7 +50386,7 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Use rsync or sftp if available, but prefer rsync. Otherwise use default transfer. - Benutze rsync oder sftp, sofern verfügbar, bevorzuge aber rsync. Sonst verwende Standardmethode. + Verwende rsync oder sftp, sofern verfügbar, bevorzuge aber rsync. Sonst verwende Standardmethode. rsync is only supported for transfers between different devices. @@ -50471,6 +50750,10 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Crop and Trim Zuschneiden und trimmen + + Cropping + + Crop and Trim... Zuschneiden und trimmen... @@ -50636,7 +50919,7 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Last used colors - Zuletzt benutzte Farben + Zuletzt verwendete Farben Create New Color Theme @@ -50720,7 +51003,7 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e SCXML Generation Failed - SCXML-Erzeugung gescheitert + SCXML-Erzeugung fehlgeschlagen Loading document... @@ -50764,7 +51047,7 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Export Failed - Export gescheitert + Export fehlgeschlagen Could not export to image. @@ -50776,7 +51059,7 @@ Wenn Sie noch keinen privaten Schlüssel besitzen, können Sie hier auch einen e Saving Failed - Speichern gescheitert + Speichern fehlgeschlagen Could not save the screenshot. @@ -51413,7 +51696,7 @@ Zeile: %4, Spalte: %5 The Symbolic Name <span style='white-space: nowrap'>"%1"</span> you want to remove is used in Multi Property Names. Select the action to apply to references in these Multi Property Names. - Der symbolische Name <span style='white-space: nowrap'>"%1"</span>, den Sie entfernen wollen, wird in Multi-Property-Namen benutzt. Wählen Sie die Aktion, die Sie auf Referenzen in diesen Multi-Property-Namen anwenden wollen. + Der symbolische Name <span style='white-space: nowrap'>"%1"</span>, den Sie entfernen wollen, wird in Multi-Property-Namen verwendet. Wählen Sie die Aktion, die Sie auf Referenzen in diesen Multi-Property-Namen anwenden wollen. Failed to write "%1" @@ -51477,7 +51760,7 @@ Zeile: %4, Spalte: %5 The properties of the Multi Property Name associated with the selected Symbolic Name. (use \\ for a literal \ in the value) - Die Eigenschaften des Multi-Property-Namens, der mit dem ausgewählten symbolischen Namen assoziiert ist. (Benutzen Sie \\ für ein \-Literal im Wert) + Die Eigenschaften des Multi-Property-Namens, der mit dem ausgewählten symbolischen Namen assoziiert ist. (Verwenden Sie \\ für ein \-Literal im Wert) The Hierarchical Name associated with the selected Symbolic Name. @@ -52142,7 +52425,7 @@ Warten Sie, bis er beendet ist, und versuchen Sie es dann erneut. Invalid Squish settings. Configure Squish installation path inside Preferences... > Squish > General to use this wizard. - Ungültige Squish-Einstellungen. Stellen Sie in Einstellungen... > Squish > Allgemein den Squish-Installationspfad ein, um diesen Assistenten zu benutzen. + Ungültige Squish-Einstellungen. Stellen Sie in Einstellungen... > Squish > Allgemein den Squish-Installationspfad ein, um diesen Assistenten zu verwenden. Available languages: @@ -52496,7 +52779,7 @@ Die Datei "%1" konnte nicht geöffnet werden. The color used for %1. - Die für "%1" benutzte Farbe. + Die für "%1" verwendete Farbe. Failed to open file. @@ -52520,11 +52803,11 @@ Die Datei "%1" konnte nicht geöffnet werden. Use internal terminal - Integriertes Terminal benutzen + Integriertes Terminal verwenden Uses the internal terminal when "Run In Terminal" is enabled and for "Open Terminal here". - Benutzt das integrierte Terminal, wenn "Im Terminal ausführen" aktiviert ist und für "Terminalfenster hier öffnen". + Verwendet das integrierte Terminal, wenn "Im Terminal ausführen" aktiviert ist und für "Terminalfenster hier öffnen". Family: @@ -52532,7 +52815,7 @@ Die Datei "%1" konnte nicht geöffnet werden. The font family used in the terminal. - Der Name der Zeichensatz-Familie, die im Terminal benutzt wird. + Der Name der Zeichensatz-Familie, die im Terminal verwendet wird. Size: @@ -52540,15 +52823,15 @@ Die Datei "%1" konnte nicht geöffnet werden. The font size used in the terminal (in points). - Die Größe des Zeichensatzes, der im Terminal benutzt wird (in Punkten). + Die Größe des Zeichensatzes, der im Terminal verwendet wird (in Punkten). 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: @@ -52659,12 +52942,12 @@ Die Datei "%1" konnte nicht geöffnet werden. "%1" ist nicht ausführbar. - Terminal process exited with code %1 - Der Terminalprozess wurde mit dem Rückgabewert %1 beendet + Terminal process exited with code %1. + Der Terminalprozess wurde mit dem Rückgabewert %1 beendet. - Process exited with code: %1 - Prozess wurde mit dem Rückgabewert %1 beendet + Process exited with code: %1. + Prozess wurde mit dem Rückgabewert %1 beendet. Copy @@ -52688,11 +52971,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 +53453,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. @@ -53247,7 +53530,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 @@ -53648,7 +53931,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 @@ -53692,7 +53975,7 @@ Gibt an, wie sich die Rücktaste bezüglich Einrückung verhält. If available, use a different margin. For example, the ColumnLimit from the ClangFormat plugin. - Benutzt einen anderen Rand, falls verfügbar. Zum Beispiel das ColumnLimit vom ClangFormat Plugin. + Verwendet einen anderen Rand, falls verfügbar. Zum Beispiel das ColumnLimit vom ClangFormat Plugin. Animate navigation within file @@ -53727,7 +54010,7 @@ Gibt an, wie sich die Rücktaste bezüglich Einrückung verhält. Rechtsbündig - Line annotations + Line Annotations Zeilenannotationen @@ -53894,7 +54177,7 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. </pre> </li> -<li>Normale Einrückung: Benutze Tabulatoren oder Leerzeichen entsprechend obiger Konfiguration. +<li>Normale Einrückung: Verwende Tabulatoren oder Leerzeichen entsprechend obiger Konfiguration. <pre> (tab)int i = foo(a, b (tab)(tab)(tab) c, d); @@ -53912,7 +54195,7 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. With Regular Indent - Benutze normale Einrückung + Verwende normale Einrückung The text editor indentation setting is used for non-code files only. See the C++ and Qt Quick coding style settings to configure indentation for code files. @@ -54052,14 +54335,6 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Line: %1, Col: %2 Zeile: %1, Spalte: %2 - - &Undo - &Rückgängig - - - &Redo - &Wiederholen - Delete &Line &Zeile löschen @@ -54240,6 +54515,18 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Open Call Hierarchy Aufrufhierarchie öffnen + + Open Type Hierarchy + Klassenhierarchie öffnen + + + Meta+Shift+T + Meta+Shift+T + + + Ctrl+Shift+T + Ctrl+Shift+T + Move the View a Page Up and Keep the Cursor Position Ansicht eine Bildschirmseite nach oben bewegen, ohne die Einfügemarke zu verändern @@ -54425,8 +54712,24 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Alt+U - &Sort Lines - Zeilen &sortieren + Sort Lines + + + + Go to Previous Word (Camel Case) + + + + Go to Next Word (Camel Case) + + + + Go to Previous Word (Camel Case) with Selection + + + + Go to Next Word (Camel Case) with Selection + Meta+Shift+S @@ -54476,10 +54779,6 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Reset Font Size Schriftgröße zurücksetzen - - Meta+0 - Meta+0 - Ctrl+0 Ctrl+0 @@ -54560,14 +54859,6 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Go to Next Word Zum nächsten Wort springen - - Go to Previous Word Camel Case - Zum vorhergehenden Wort springen (Camel Case) - - - Go to Next Word Camel Case - Zum nächsten Wort springen (Camel Case) - Go to Line Start with Selection Bis Zeilenanfang markieren @@ -54600,14 +54891,6 @@ Bestimmt das Verhalten bezüglich der Einrückung von Fortsetzungszeilen. Go to Next Word with Selection Nächstes Wort markieren - - Go to Previous Word Camel Case with Selection - Vorhergehendes Wort markieren (Camel Case) - - - Go to Next Word Camel Case with Selection - Nächstes Wort markieren (Camel Case) - Activate completion: Code-Vervollständigung aktivieren: @@ -54661,7 +54944,7 @@ Drücken Sie zusätzlich die Umschalttaste, wird ein Escape-Zeichen an der aktue Zeichenketten automatisch teilen - &Automatically insert matching characters + &Automatically Insert Matching Characters &Passende Zeichen automatisch einfügen @@ -54743,10 +55026,10 @@ Drücken Sie zusätzlich die Umschalttaste, wird ein Escape-Zeichen an der aktue Doxygen allows "@" and "\" to start commands. By default, "@" is used if the surrounding comment starts with "/**" or "///", and "\" is used -if the comment starts with "/*!" or "//! +if the comment starts with "/*!" or "//!". Doxygen erlaubt es, Befehle mit "@" und "\" zu beginnen. Die Vorgabe ist, mit "@" zu beginnen, wenn der umgebende Kommentar mit "/**" oder "///" anfängt, -und "\" zu benutzen, wenn der Kommentar mit "/*!" oder "//!". +und "\" zu verwenden, wenn der Kommentar mit "/*!" oder "//!". Generate brief description @@ -54822,7 +55105,7 @@ Wird auf Zeichen angewendet, sofern keine andere Regel zutrifft. Highlighted search results inside the editor. Used to mark read accesses to C++ symbols. Hervorgehobene Suchergebnisse im Editor. -Wird benutzt, um Lesezugriffe eines C++-Symbols zu markieren. +Wird verwendet, um Lesezugriffe eines C++-Symbols zu markieren. Search Result (Alternative 2) @@ -54832,7 +55115,7 @@ Wird benutzt, um Lesezugriffe eines C++-Symbols zu markieren. Highlighted search results inside the editor. Used to mark write accesses to C++ symbols. Hervorgehobene Suchergebnisse im Editor. -Wird benutzt, um Schreibzugriffe eines C++-Symbols zu markieren. +Wird verwendet, um Schreibzugriffe eines C++-Symbols zu markieren. Search Result Containing function @@ -54842,7 +55125,7 @@ Wird benutzt, um Schreibzugriffe eines C++-Symbols zu markieren. Highlighted search results inside the editor. Used to mark containing function of the symbol usage. Hervorgehobene Suchergebnisse im Editor. -Wird benutzt um die Funktion zu markieren, die ein gesuchtes Symbol benutzt. +Wird verwendet um die Funktion zu markieren, die ein gesuchtes Symbol verwendet. Search Scope @@ -54900,7 +55183,7 @@ Wird benutzt um die Funktion zu markieren, die ein gesuchtes Symbol benutzt.Occurrences of the symbol under the cursor. (Only the background will be applied.) Vorkommen des unter der Einfügemarke befindlichen Symbols. -(Nur der Hintergrund wird benutzt.) +(Nur der Hintergrund wird verwendet.) Unused Occurrence @@ -55142,7 +55425,7 @@ Wird benutzt um die Funktion zu markieren, die ein gesuchtes Symbol benutzt.Non user-defined language operators. To style user-defined operators, use Overloaded Operator. Nicht benutzerdefinierte Sprachoperatoren. -Um den Stil von benutzerdefinierten Operatoren festzulegen, benutzen Sie "Überladene Operatoren". +Um den Stil von benutzerdefinierten Operatoren festzulegen, verwenden Sie "Überladene Operatoren". Preprocessor @@ -55684,6 +55967,18 @@ Außer Leerzeichen innerhalb von Kommentaren und Zeichenketten. JSON Editor JSON-Editor + + Type Hierarchy + Klassenhierarchie + + + No type hierarchy available + Keine Klassenhierarchie verfügbar + + + Reloads the type hierarchy for the symbol under the cursor. + + QtC::Todo @@ -55700,7 +55995,7 @@ Außer Leerzeichen innerhalb von Kommentaren und Zeichenketten. Zurücksetzen - Scanning scope + Scanning Scope Suchbereich @@ -56033,11 +56328,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. @@ -56438,6 +56733,10 @@ Die Trace-Daten sind verloren. createTempFile is not implemented for "%1". createTempFile ist für "%1" nicht implementiert. + + watch is not implemented. + + Refusing to remove the standard directory "%1". Das Standardverzeichnis "%1" kann nicht entfernt werden. @@ -56448,7 +56747,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". @@ -56724,7 +57023,7 @@ Die Trace-Daten sind verloren. <p>No valid settings file could be found.</p><p>All settings files found in directory "%1" were unsuitable for the current version of %2, for instance because they were written by an incompatible version of %2, or because a different settings path was used.</p> - <p>Es konnte keine gültige Einstellungsdatei gefunden werden.</p><p>Alle im Verzeichnis "%1" gefundenen Einstellungsdateien sind für die aktuelle Version von %2 ungeeignet, zum Beispiel weil sie von einer inkompatiblen Version von %2 geschrieben wurden oder weil ein anderes Einstellungsverzeichnis benutzt wurde.</p> + <p>Es konnte keine gültige Einstellungsdatei gefunden werden.</p><p>Alle im Verzeichnis "%1" gefundenen Einstellungsdateien sind für die aktuelle Version von %2 ungeeignet, zum Beispiel weil sie von einer inkompatiblen Version von %2 geschrieben wurden oder weil ein anderes Einstellungsverzeichnis verwendet wurde.</p> <p>No valid settings file could be found.</p><p>All settings files found in directory "%1" were either too new or too old to be read.</p> @@ -56790,22 +57089,6 @@ Die Trace-Daten sind verloren. Edit Environment Umgebung bearbeiten - - Enter one environment variable per line. -To set or change a variable, use VARIABLE=VALUE. -To append to a variable, use VARIABLE+=VALUE. -To prepend to a variable, use VARIABLE=+VALUE. -Existing variables can be referenced in a VALUE with ${OTHER}. -To clear a variable, put its name on a line with nothing else on it. -To disable a variable, prefix the line with "#". - Geben Sie eine Umgebungsvariable pro Zeile ein. -Um eine Variable zu setzen oder zu ändern, benutzen Sie VARIABLE=WERT. -Um einen Wert an eine Variable anzufügen, benutzen Sie VARIABLE+=WERT. -Um einen Wert einer Variable voranzustellen, benutzen Sie VARIABLE=+WERT. -Existierende Variablen können in einem WERT mit ${ANDERE} verwendet werden. -Um eine Variable zu leeren, schreiben Sie nichts als ihren Namen in eine Zeile. -Um eine Variable zu deaktivieren, stellen Sie der Zeile "#" voran. - Remove File Datei entfernen @@ -56899,7 +57182,7 @@ Um eine Variable zu deaktivieren, stellen Sie der Zeile "#" voran. Do Not Show Again - Nicht noch einmal anzeigen + Nicht erneut anzeigen Close @@ -56921,6 +57204,14 @@ Um eine Variable zu deaktivieren, stellen Sie der Zeile "#" voran.No destination directory set. Kein Zielverzeichnis gesetzt. + + Failed to open output file. + + + + Failed to write output file. + + Command failed. Das Kommando schlug fehl. @@ -56949,8 +57240,8 @@ in "%2" aus. Deaktivieren - Leave at Default - Vorgabe beibehalten + Default + Vorgabe Show %1 Column @@ -57018,6 +57309,17 @@ in "%2" aus. Minimize Minimieren + + Enter one environment variable per line. +To set or change a variable, use VARIABLE=VALUE. +To disable a variable, prefix this line with "#". +To append to a variable, use VARIABLE+=VALUE. +To prepend to a variable, use VARIABLE=+VALUE. +Existing variables can be referenced in a VALUE with ${OTHER}. +To clear a variable, put its name on a line with nothing else on it. +Lines starting with "##" will be treated as comments. + + &OK &OK @@ -57122,7 +57424,7 @@ in "%2" aus. User: - Nutzer: + Benutzer: Password: @@ -57132,6 +57434,10 @@ in "%2" aus. Could not find any shell. Es konnte keine Shell gefunden werden. + + No Lua interface set + + QtC::Valgrind @@ -57285,7 +57591,7 @@ in "%2" aus. Backtrace frame count: - Stack-Frames: + Stackframes: Suppression files: @@ -57573,7 +57879,7 @@ Mit Cache-Simulation werden weitere Ereigniszähler aktiviert: Use of Uninitialized Memory - Benutzung von nicht initialisiertem Speicher + Verwendung von nicht initialisiertem Speicher Show issues originating outside currently opened projects. @@ -57617,7 +57923,7 @@ Mit Cache-Simulation werden weitere Ereigniszähler aktiviert: Valgrind Analyze Memory uses the Memcheck tool to find memory leaks. - Die Speicheranalyse von Valgrind benutzt das Programm "memcheck", um Speicherlecks zu finden. + Die Speicheranalyse von Valgrind verwendet das Programm "memcheck", um Speicherlecks zu finden. Valgrind Memory Analyzer @@ -57630,7 +57936,7 @@ Mit Cache-Simulation werden weitere Ereigniszähler aktiviert: Valgrind Analyze Memory with GDB uses the Memcheck tool to find memory leaks. When a problem is detected, the application is interrupted and can be debugged. - Die Speicheranalyse mit Valgrind und GDB benutzt das Programm "memcheck", um Speicherlecks zu finden. + Die Speicheranalyse mit Valgrind und GDB verwendet das Programm "memcheck", um Speicherlecks zu finden. Wird ein Problem gefunden, dann wird die Anwendung angehalten und kann untersucht werden. @@ -57842,7 +58148,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. @@ -58643,10 +58949,6 @@ Check settings or ensure Valgrind is installed and available in PATH. Open "%1" "%1" öffnen - - Clear - Löschen - Running: %1 Führe aus: %1 @@ -58807,17 +59109,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. @@ -58933,7 +59235,7 @@ should a repository require SSH-authentication (see documentation on SSH and the The activated version %1 is not supported by %2. Activate version %3 or higher. %1=sdkVersion, %2=QtC-Version, %3=minVersion - Die aktivierte Version %1 wird von %2 nicht unterstützt. Benutzen Sie Version %3 oder höher. + Die aktivierte Version %1 wird von %2 nicht unterstützt. Verwenden Sie Version %3 oder höher. Activated version: %1 @@ -59034,7 +59336,7 @@ should a repository require SSH-authentication (see documentation on SSH and the Would you like to take a quick UI tour? This tour highlights important user interface elements and shows how they are used. To take the tour later, select Help > UI Tour. - Wollen Sie sich kurz die Oberfläche vorführen lassen? Dabei wird gezeigt, wo die wichtigsten Bedienelemente sind und wie man sie benutzt. Sie können die Vorführung auch später über "Hilfe" > "Oberfläche vorführen" starten. + Wollen Sie sich kurz die Oberfläche vorführen lassen? Dabei wird gezeigt, wo die wichtigsten Bedienelemente sind und wie man sie verwendet. Sie können die Vorführung auch später über "Hilfe" > "Oberfläche vorführen" starten. Take UI Tour @@ -59050,7 +59352,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 @@ -59227,6 +59529,34 @@ should a repository require SSH-authentication (see documentation on SSH and the Association Assoziation + + Reset + Zurücksetzen + + + Relations + Beziehungen + + + Diagram Elements + Diagrammelemente + + + Clear + Löschen + + + View + Ansicht + + + Filter + Filter + + + Type: + Typ: + Stereotypes: Stereotypen: @@ -59495,6 +59825,14 @@ should a repository require SSH-authentication (see documentation on SSH and the Shape: Form: + + Warning + Warnung + + + Error + Fehler + Intermediate points: Dazwischen liegende Punkte: @@ -59623,6 +59961,10 @@ should a repository require SSH-authentication (see documentation on SSH and the Center Horizontally Horizontal zentrieren + + Open Linked File + Verlinkte Datei öffnen + Align Bottom Unten ausrichten @@ -59659,10 +60001,6 @@ should a repository require SSH-authentication (see documentation on SSH and the Equal Vertical Space Gleicher vertikaler Zwischenraum - - Add Related Elements - Zugehörige Elemente hinzufügen - Unacceptable null object. Unzulässiges Null-Objekt. @@ -59691,6 +60029,30 @@ should a repository require SSH-authentication (see documentation on SSH and the Unable to handle file version %1. Dateiversion %1 ist nicht nutzbar. + + Relation Attributes + Beziehungsattribute + + + Type + Typ + + + Direction + Richtung + + + Stereotypes + Stereotype + + + Other Element Attributes + Andere Elementattribute + + + Number of matching elements: + Anzahl der übereinstimmenden Elemente: + RadioButtonSpecifics @@ -59959,10 +60321,26 @@ defined in step size. Row spacing + + Sets the space between the items in pixels in the <b>Row Layout</b>. + + Layout direction + + Sets the direction of the item flow in the <b>Row Layout</b>. + + + + Uniform cell size + + + + Toggles all cells to have a uniform size. + + RowSpecifics @@ -60002,15 +60380,19 @@ defined in step size. - Name must start with a capital letter + Name must start with a capital letter. - Name must have at least 3 characters + Name must have at least 3 characters. - Name cannot contain white space + Name cannot contain white space. + + + + Name is already taken. @@ -60172,6 +60554,17 @@ This is used for calculating the total implicit size. + + ShowLookAtAction + + Show Look-at + + + + Toggle the visibility of the edit camera look-at indicator. + + + ShowParticleEmitterAction @@ -60603,6 +60996,10 @@ it reaches the start or end. Current index Aktueller Index + + Sets the index of the child item currently visible in the <b>Stack Layout</b>. + + StackViewSpecifics @@ -61158,7 +61555,7 @@ This is used for calculating the total implicit size. - + Basic @@ -61498,7 +61895,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. @@ -61874,15 +62271,15 @@ top or bottom. - UnimportBundleMaterialDialog + UnimportBundleItemDialog - Bundle material might be in use + Bundle %1 might be in use If the %1 you are removing is in use, it might cause the project to malfunction. -Are you sure you want to remove the %1? +Are you sure you want to remove it? diff --git a/share/qtcreator/translations/qtcreator_es.ts b/share/qtcreator/translations/qtcreator_es.ts index 623ffc7e0ae..d9de9393a9b 100644 --- a/share/qtcreator/translations/qtcreator_es.ts +++ b/share/qtcreator/translations/qtcreator_es.ts @@ -3777,8 +3777,8 @@ Es recomendado usar gdb 6.7 o posterior. Editor de signals/slots - Qt Designer Form Class - Clase del formulario Qt Designer + Qt Widgets Designer Form Class + Clase del formulario Qt Widgets Designer %1 - Error @@ -3825,20 +3825,20 @@ Es recomendado usar gdb 6.7 o posterior. - Qt Designer Form + Qt Widgets Designer Form Diseñador de formularios de Qt - Creates a Qt Designer form file (.ui). - Crea un archivo de formulario de Qt Designer (.ui). + Creates a Qt Widgets Designer form file (.ui). + Crea un archivo de formulario de Qt Widgets Designer (.ui). - Creates a Qt Designer form file (.ui) with a matching class. - Crea un archivo de formulario de Qt Designer (.ui) para una clase. + Creates a Qt Widgets Designer form file (.ui) with a matching class. + Crea un archivo de formulario de Qt Widgets Designer (.ui) para una clase. - Qt Designer Form Class - Clase del formulario de Qt Designer + Qt Widgets Designer Form Class + Clase del formulario de Qt Widgets Designer Object inspector @@ -3953,8 +3953,8 @@ Es recomendado usar gdb 6.7 o posterior. - About Qt Designer plugins.... - Acerca de los plugins de Qt Designer... + About Qt Widgets Designer plugins.... + Acerca de los plugins de Qt Widgets Designer... Preview in @@ -3989,8 +3989,8 @@ Es recomendado usar gdb 6.7 o posterior. Imposible escribir a %1: %2 - Qt Designer Form - Formulario de Qt Designer + Qt Widgets Designer Form + Formulario de Qt Widgets Designer The class definition of '%1' could not be found in %2. @@ -7459,8 +7459,8 @@ al control de versiones (%2)? Este asistente genera un proyecto de aplicación Qt4 para consola. La aplicación es derivada de QCoreApplication y no provee interfaz gráfica de usuario. - Qt Designer is not responding (%1). - Qt Designer no está respondiendo (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer no está respondiendo (%1). Unable to create server socket: %1 diff --git a/share/qtcreator/translations/qtcreator_fr.ts b/share/qtcreator/translations/qtcreator_fr.ts index 8e802d897c6..ff5318759a9 100644 --- a/share/qtcreator/translations/qtcreator_fr.ts +++ b/share/qtcreator/translations/qtcreator_fr.ts @@ -152,8 +152,8 @@ Lissage - Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. - Active/désactive l'utilisation de l'interpolation linéaire pour le lissage. Lorsque décoché, la méthode du plus proche voisin sera utilisée. Cela s'applique principalement aux éléments images. + Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. + Active/désactive l'utilisation de l'interpolation linéaire pour le lissage. Lorsque décoché, la méthode du plus proche voisin sera utilisée. Cela s'applique principalement aux éléments images. Antialiasing @@ -10730,7 +10730,7 @@ dans le navigateur système pour un téléchargement manuel. Liste des NDK Android : - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) Paramètres Android d'OpenSSL (optionnel) @@ -11066,12 +11066,12 @@ Le kit supporte « %2 », mais le périphérique utilise « %3&#x - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -La désinstallation du paquet installé peut résoudre le problème. -Voulez-vous désinstaller le paquet existant ? + Uninstalling the installed package may solve the issue. + La désinstallation du paquet installé peut résoudre le problème. + + + Do you want to uninstall the existing package? + Voulez-vous désinstaller le paquet existant ? Install failed @@ -12712,7 +12712,7 @@ Exécutable : %2 Répétition des tests - Run in parallel + Run in Parallel Exécuter en parallèle @@ -20440,8 +20440,8 @@ To do this, you type this shortcut and a space in the Locator entry field, and t Éditeur QMLJS - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -22228,7 +22228,7 @@ Le modèle de code intégré gèrera le surlignage, la complétion, etc.Seuil de mise à jour du document : - Sessions with a single clangd instance + Sessions with a Single Clangd Instance Sessions avec une seule instance de clangd @@ -22450,7 +22450,7 @@ devraient être gérés par le même processus clangd, ajoutez-les ici.Convertir en Camel Case - Add forward declaration for %1 + Add Forward Declaration for %1 Ajouter la déclaration préalable pour %1 @@ -22982,8 +22982,8 @@ p.ex. nom = « m_test_toto_ » : Modèles de getters et setters personnalisés - Value types: - Types de valeur : + Value Types + Types de valeur Projects only @@ -28811,8 +28811,8 @@ L’accès au module ou la mise en place de points d’arrêt par fichier et par Éditeur d’interface graphique - Qt Designer Form Class - Classe d’interface graphique Qt Designer + Qt Widgets Designer Form Class + Classe d’interface graphique Qt Widgets Designer Form Template @@ -28835,12 +28835,12 @@ L’accès au module ou la mise en place de points d’arrêt par fichier et par Sélectionner un nom de classe - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - Crée un formulaire Qt Designer avec une classe correspondante (en-tête C++ et fichier source) pour implémentation. Vous pouvez ajouter le formulaire et la classe à un projet Qt Widget existant. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Crée un formulaire Qt Widgets Designer avec une classe correspondante (en-tête C++ et fichier source) pour implémentation. Vous pouvez ajouter le formulaire et la classe à un projet Qt Widget existant. Widget Box - this translation must coherent with the translation of Qt Designer + this translation must coherent with the translation of Qt Widgets Designer Boite de widget @@ -28937,8 +28937,8 @@ L’accès au module ou la mise en place de points d’arrêt par fichier et par Maj+F4 - About Qt Designer Plugins... - À propos des greffons de Qt Designer… + About Qt Widgets Designer Plugins... + À propos des greffons de Qt Widgets Designer… Signals && Slots Editor @@ -34341,8 +34341,8 @@ Souhaitez-vous les écraser ? Entrez les arguments appropriés pour votre commande de construction. - Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools) - Assurez vous que le paramètre multi-job de la commande de construction est assez grande (telle que -j200 pour les outils de compilation comme JOM ou Make) + Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools). + Assurez vous que le paramètre multi-job de la commande de construction est assez grande (telle que -j200 pour les outils de compilation comme JOM ou Make). Keep original jobs number: @@ -34461,16 +34461,16 @@ Souhaitez-vous les écraser ? Cacher l'entête IncrediBuild dans la sortie : - Suppresses IncrediBuild's header in the build output - Supprimer l'entête d'IncrediBuild de la sortie de construction + Suppresses IncrediBuild's header in the build output. + Supprimer l'entête d'IncrediBuild de la sortie de construction. Internal IncrediBuild logging level: Niveau de journalisation interne d'IncrediBuild : - Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support - Écrase le niveau interne de journalisation d'IncrediBuild pour cette construction. N'affecte pas la sortie ou un quelconque journal accessible par l'utilisateur. Utilisé principalement pour comprendre les problèmes avec l'aide du support d'IncrediBuild + Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support. + Écrase le niveau interne de journalisation d'IncrediBuild pour cette construction. N'affecte pas la sortie ou un quelconque journal accessible par l'utilisateur. Utilisé principalement pour comprendre les problèmes avec l'aide du support d'IncrediBuild. Miscellaneous @@ -34489,16 +34489,16 @@ Souhaitez-vous les écraser ? Arrêter en cas d'erreur : - When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds - Lorsque spécifié, l'exécution s'arrête dès qu'une erreur est rencontrée. C'est le comportement par défaut dans les constructions « Visual Studio », mais ce n'est pas le cas pour les constructions avec « Make et les outils de compilation » ou les « outils de développeur » + When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds. + Lorsque spécifié, l'exécution s'arrête dès qu'une erreur est rencontrée. C'est le comportement par défaut dans les constructions « Visual Studio », mais ce n'est pas le cas pour les constructions avec « Make et les outils de compilation » ou les « outils de développeur ». Additional Arguments: Arguments supplémentaires : - Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line - Ajouter manuellement des arguments pour buildconsole. La valeur de ce champ est concaténé à la ligne de commande finale de buildconsole + Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line. + Ajouter manuellement des arguments pour buildconsole. La valeur de ce champ est concaténé à la ligne de commande finale de buildconsole. Open Build Monitor: @@ -40386,8 +40386,8 @@ Présélectionne un Qt optimisé pour le bureau pour compiler l'application Définir l'interpréteur Python - Creates a Qt for Python application that includes a Qt Designer-based widget (ui file). Requires .ui to Python conversion. - Génère une application Qt pour Python qui inclût un widget basé sur Qt Designer (fichier ui). Nécessite une conversion de .ui vers Python. + Creates a Qt for Python application that includes a Qt Widgets Designer-based widget (ui file). Requires .ui to Python conversion. + Génère une application Qt pour Python qui inclût un widget basé sur Qt Widgets Designer (fichier ui). Nécessite une conversion de .ui vers Python. Creates a Qt Quick UI project for previewing and prototyping designs. @@ -40910,10 +40910,10 @@ Utilisez cette version « de compatibilité » si vous souhaitez utili Application Qt Quick (compatibilité) - Creates a widget-based Qt application that contains a Qt Designer-based main window and C++ source and header files to implement the application logic. + Creates a widget-based Qt application that contains a Qt Widgets Designer-based main window and C++ source and header files to implement the application logic. Preselects a desktop Qt for building the application if available. - Génère une application basée sur les widgets qui contient une fenêtre principale basée sur Qt Designer et un ensemble de fichiers d'entêtes et de sources C++ pour implémenter la logique de l'application. + Génère une application basée sur les widgets qui contient une fenêtre principale basée sur Qt Widgets Designer et un ensemble de fichiers d'entêtes et de sources C++ pour implémenter la logique de l'application. Sélectionne un Qt optimisé pour bureaux pour compiler l'application, si disponible. @@ -41254,12 +41254,12 @@ Sélectionne un Qt optimisé pour bureaux pour compiler l'application, si d Modèle d’interface graphique - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Crée un formulaire Qt Designer que l’on peut ajouter à un projet Qt Widget. Ceci est utile si vous utilisez déjà une classe pour la logique métier de l’interface. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Crée un formulaire Qt Widgets Designer que l’on peut ajouter à un projet Qt Widget. Ceci est utile si vous utilisez déjà une classe pour la logique métier de l’interface. - Qt Designer Form - Interface graphique Qt Designer + Qt Widgets Designer Form + Interface graphique Qt Widgets Designer Creates a source file that you can add to a C/C++ project. @@ -43130,8 +43130,8 @@ Activez cette option si vous envisagez de créer des binaires x86 32 bits sans u Le répertoire de compilation contient des caractères potentiellement problématiques « %1 ». - This warning can be suppressed <a href="dummy">here</a>. - Cet avertissement peut être supprimé <a href="dummy">ici</a>. + This warning can be suppressed <a href="dummy">here</a>. + Cet avertissement peut être supprimé <a href="dummy">ici</a>. Separate debug info: @@ -43548,39 +43548,28 @@ au projet « %2 ». Le typeId « %1 » du générateur est inconnu. Les typesIds pris en charge sont : « %2 ». - Path "%1" does not exist when checking Json wizard search paths. - - Le chemin « %1 » n’existe pas lors de la vérification des chemins de recherche de l’assistant Json. + Path "%1" does not exist when checking JSON wizard search paths. + Le chemin « %1 » n’existe pas lors de la vérification des chemins de recherche de l’assistant JSON. - Checking "%1" for %2. - - Vérification de « %1 » pour %2. - + Checking "%1" for %2. + Vérification de « %1 » pour %2. - * Failed to parse "%1":%2:%3: %4 - - * Échec de l’analyse de « %1 »:%2:%3 : %4 - + * Failed to parse "%1":%2:%3: %4 + * Échec de l’analyse de « %1 »:%2:%3 : %4 - * Did not find a JSON object in "%1". - - * N’a pas trouvé d’objet JSON dans « %1 ». - + * Did not find a JSON object in "%1". + * N’a pas trouvé d’objet JSON dans « %1 ». - * Configuration found and parsed. - - * La configuration a été trouvée et analysée. - + * Configuration found and parsed. + * La configuration a été trouvée et analysée. - JsonWizard: "%1" not found - - Assistant Json : « %1 » introuvable - + JsonWizard: "%1" not found + Assistant Json : « %1 » introuvable. Page is not an object. @@ -43599,16 +43588,12 @@ au projet « %2 ». La page avec le typeId « %1 » a un « index » invalide. - * Version %1 not supported. - - * La version %1 n’est pas prise en charge. - + * Version %1 not supported. + * La version %1 n’est pas prise en charge. - * Failed to create: %1 - - * Impossible de créer : %1 - + * Failed to create: %1 + * Impossible de créer : %1 key not found. @@ -44461,8 +44446,8 @@ Ces fichiers sont préservés. Chemin de l'interpréteur Python - No Python interpreter set for kit "%1" - Aucun interpréteur Python n'est défini pour le kit « %1 » + No Python interpreter set for kit "%1". + Aucun interpréteur Python n'est défini pour le kit « %1 ». @@ -45047,8 +45032,8 @@ Les fichiers affectés sont : QtC::QmakeProjectManager - Qt Designer is not responding (%1). - Qt Designer ne répond pas (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer ne répond pas (%1). Unable to create server socket: %1 @@ -45419,9 +45404,9 @@ Les fichiers affectés sont : Crée un widget personnalisé ou une collection de widgets personnalisés pour Qt4 Designer. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - lourd ? "contenant un widget ou une collection de widgets, personnalisé pour Qt Designer" ? - Cet assistant génère un projet contenant un widget ou une collection de widgets personnalisés pour Qt Designer. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + lourd ? "contenant un widget ou une collection de widgets, personnalisé pour Qt Widgets Designer" ? + Cet assistant génère un projet contenant un widget ou une collection de widgets personnalisés pour Qt Widgets Designer. Custom Widgets @@ -49563,10 +49548,8 @@ Le processus de contrôle n'a pas pu démarrer. Connexion au périphérique… - Connected. Now doing extended checks. - - Connecté. Exécution des tests étendus. - + Connected. Now doing extended checks. + Connecté. Exécution des tests étendus. Basic connectivity test failed, device is considered unusable. @@ -49893,8 +49876,8 @@ Le processus de contrôle n'a pas pu démarrer. Utiliser le transfert par défaut. Cela peut être lent. - Unknown error occurred while trying to create remote directories - Une erreur inconnue s'est produite lors de la création des répertoires distants + Unknown error occurred while trying to create remote directories. + Une erreur inconnue s'est produite lors de la création des répertoires distants. Transfer method was downgraded from "%1" to "%2". If this is unexpected, please re-test device "%3". @@ -52415,12 +52398,12 @@ Impossible d'ouvrir le fichier « %1 ». « %1 » n'est pas un exécutable. - Terminal process exited with code %1 - Le processus du terminal s'est terminé avec le code %1 + Terminal process exited with code %1. + Le processus du terminal s'est terminé avec le code %1. - Process exited with code: %1 - Le processus s'est terminé avec le code : %1 + Process exited with code: %1. + Le processus s'est terminé avec le code : %1. Copy @@ -52708,10 +52691,10 @@ En outre, Maj+Entrée insère un caractère d’échappement à la position du c Doxygen allows "@" and "\" to start commands. By default, "@" is used if the surrounding comment starts with "/**" or "///", and "\" is used -if the comment starts with "/*!" or "//! +if the comment starts with "/*!" or "//!". Doxygen permet d'utiliser « @ » et « \ » pour démarrer une commande. Par défaut, « @ » est utilisé si le commentaire l'englobant commence avec « /** » ou « /// » et « \ » est utilisé -si le commentaire débute avec « /*! » ou « //! » +si le commentaire débute avec « /*! » ou « //! ». Documentation Comments @@ -52734,7 +52717,7 @@ si le commentaire débute avec « /*! » ou « //! »À la demande - &Automatically insert matching characters + &Automatically Insert Matching Characters Insérer &automatiquement les caractères correspondants @@ -54991,7 +54974,7 @@ francis : en effet, une erreur de ma part --> validé. Entre les lignes - Line annotations + Line Annotations Annotations de ligne @@ -55434,7 +55417,7 @@ Influence l’indentation des lignes de continuation. Scanner le sous-projet actuel - Scanning scope + Scanning Scope Portée de la recherche diff --git a/share/qtcreator/translations/qtcreator_hr.ts b/share/qtcreator/translations/qtcreator_hr.ts index 6d69f112adb..93848c19411 100644 --- a/share/qtcreator/translations/qtcreator_hr.ts +++ b/share/qtcreator/translations/qtcreator_hr.ts @@ -2133,8 +2133,14 @@ Međutim, korištenje opuštenih i proširenih pravila također znači da nije m Executable: + adjective Izvršavajuća: + + Executable: + noun + Izvršna datoteka: + Symbolic link: Simbolička poveznica: @@ -8025,7 +8031,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and Automatski rastavi znakovne nizove - &Automatically insert matching characters + &Automatically Insert Matching Characters &Automatski umetni poklapajuće znakove @@ -8193,7 +8199,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and Označi promjene u &tekstu - Line annotations + Line Annotations Napomene za retke @@ -8443,7 +8449,7 @@ Utječe na uvlačenje neprekinutih redaka. Resetiraj - Scanning scope + Scanning Scope Raspon pretrage @@ -13221,9 +13227,11 @@ The minimum API level required by the kit is %1. - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? + Uninstalling the installed package may solve the issue. + + + + Do you want to uninstall the existing package? @@ -15304,8 +15312,8 @@ Check the test environment. Python uređivač - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -20900,8 +20908,8 @@ Rebuilding the project might help. Alt+Shift+R - About Qt Designer Plugins... - O Qt Designer dodacima … + About Qt Widgets Designer Plugins... + O Qt Widgets Designer dodacima … Preview in @@ -27563,43 +27571,35 @@ to project "%2". - Path "%1" does not exist when checking Json wizard search paths. - + Path "%1" does not exist when checking JSON wizard search paths. - Checking "%1" for %2. - + Checking "%1" for %2. - * Failed to parse "%1":%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 - * Did not find a JSON object in "%1". - + * Did not find a JSON object in "%1". - * Configuration found and parsed. - + * Configuration found and parsed. - * Version %1 not supported. - + * Version %1 not supported. - * Failed to create: %1 - + * Failed to create: %1 - JsonWizard: "%1" not found - + JsonWizard: "%1" not found. diff --git a/share/qtcreator/translations/qtcreator_hu.ts b/share/qtcreator/translations/qtcreator_hu.ts index 9f29949c84d..23c59c4d416 100644 --- a/share/qtcreator/translations/qtcreator_hu.ts +++ b/share/qtcreator/translations/qtcreator_hu.ts @@ -5235,8 +5235,8 @@ A projekt újraépítése talán segít. Qt modulnevek használata az #include irányelvekben - Qt Designer Form Class - Qt Designer forma osztály + Qt Widgets Designer Form Class + Qt Widgets Designer forma osztály Choose a class name @@ -5259,16 +5259,16 @@ A projekt újraépítése talán segít. Qt - Qt Designer Form - Qt Designer forma + Qt Widgets Designer Form + Qt Widgets Designer forma - Creates a Qt Designer form file (.ui). - Qt Designer forma fájl (.ui) létrehozása. + Creates a Qt Widgets Designer form file (.ui). + Qt Widgets Designer forma fájl (.ui) létrehozása. - Creates a Qt Designer form file (.ui) with a matching class. - Qt Designer forma fájl(.ui) létrehozása illeszkedő osztályokkal. + Creates a Qt Widgets Designer form file (.ui) with a matching class. + Qt Widgets Designer forma fájl(.ui) létrehozása illeszkedő osztályokkal. Widget Box @@ -5371,8 +5371,8 @@ A projekt újraépítése talán segít. Ctrl+Alt+R - About Qt Designer plugins.... - Névjegy a Qt Designer beépülő moduljairól... + About Qt Widgets Designer plugins.... + Névjegy a Qt Widgets Designer beépülő moduljairól... Preview in @@ -8651,8 +8651,8 @@ SOURCES *= .../ide/main/bin/dumper/dumper.cpp(new line) CVS feltöltési sablon - Qt Designer file - Qt Designer fájl + Qt Widgets Designer file + Qt Widgets Designer fájl Generic Qt Creator Project file @@ -12834,8 +12834,8 @@ p, li { white-space: pre-wrap; } Ez a varázsló egy Qt4 Designer szokásos Widget-t vagy Qt4 Designer szokásos Widget gyűjtemény projektet generál. - Qt Designer is not responding (%1). - A Qt Designer nem válaszol (%1). + Qt Widgets Designer is not responding (%1). + A Qt Widgets Designer nem válaszol (%1). Unable to create server socket: %1 diff --git a/share/qtcreator/translations/qtcreator_it.ts b/share/qtcreator/translations/qtcreator_it.ts index 549bf8f77b7..211f4099556 100644 --- a/share/qtcreator/translations/qtcreator_it.ts +++ b/share/qtcreator/translations/qtcreator_it.ts @@ -3652,8 +3652,8 @@ L'utilizzo di gdb 6.7 o successivi è fortemente consigliato. Editor di segnali e slot - Qt Designer Form Class - Classe Form di Qt Designer + Qt Widgets Designer Form Class + Classe Form di Qt Widgets Designer Choose a class name @@ -3700,16 +3700,16 @@ L'utilizzo di gdb 6.7 o successivi è fortemente consigliato. Qt - Qt Designer Form - Form di Qt Designer + Qt Widgets Designer Form + Form di Qt Widgets Designer - Creates a Qt Designer form file (.ui). - Crea un file form Qt Designer (.ui). + Creates a Qt Widgets Designer form file (.ui). + Crea un file form Qt Widgets Designer (.ui). - Creates a Qt Designer form file (.ui) with a matching class. - Crea un file form Qt Designer (.ui) e la relativa classe. + Creates a Qt Widgets Designer form file (.ui) with a matching class. + Crea un file form Qt Widgets Designer (.ui) e la relativa classe. Designer widgetbox @@ -3824,8 +3824,8 @@ L'utilizzo di gdb 6.7 o successivi è fortemente consigliato. - About Qt Designer plugins.... - Informazioni sui plugin Qt Designer... + About Qt Widgets Designer plugins.... + Informazioni sui plugin Qt Widgets Designer... Preview in @@ -7309,8 +7309,8 @@ al VCS (%2)? Questa procedura guidata genera un progetto per applicazione console Qt4. L'applicazione deriva da QCoreApplication e non include una GUI. - Qt Designer is not responding (%1). - Qt Designer non risponde (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer non risponde (%1). Unable to create server socket: %1 diff --git a/share/qtcreator/translations/qtcreator_ja.ts b/share/qtcreator/translations/qtcreator_ja.ts index 71665c23d51..22f040580f6 100644 --- a/share/qtcreator/translations/qtcreator_ja.ts +++ b/share/qtcreator/translations/qtcreator_ja.ts @@ -785,7 +785,7 @@ SDK のセットアップ - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) Android OpenSSL の設定 (オプション) @@ -1895,7 +1895,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and 文字列を自動的に分割する - &Automatically insert matching characters + &Automatically Insert Matching Characters マッチング文字を自動的に挿入する(&A) @@ -6322,7 +6322,7 @@ Backspace キーが押された時のインデントの動作を指定します ファイル内のナビゲーションをアニメーション化する - Line annotations + Line Annotations ラインアノテーション @@ -6678,7 +6678,7 @@ Influences the indentation of continuation lines. リセット - Scanning scope + Scanning Scope スキャンする範囲 @@ -10949,12 +10949,12 @@ with a password, which you can enter below. - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -インストールされているパッケージをアンインストールすると、問題が解決する場合があります。 -既存のパッケージをアンインストールしますか? + Uninstalling the installed package may solve the issue. + インストールされているパッケージをアンインストールすると、問題が解決する場合があります。 + + + Do you want to uninstall the existing package? + 既存のパッケージをアンインストールしますか? Package deploy: Running command "%1". @@ -12152,8 +12152,8 @@ in the system's browser for manual download. Python エディタ - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -14319,7 +14319,7 @@ to version control (%2) #include %1 を追加 - Add forward declaration for %1 + Add Forward Declaration for %1 %1 の前方宣言を追加する @@ -18978,8 +18978,8 @@ Rebuilding the project might help. プロジェクトのリビルドをお奨めします。 - Qt Designer Form Class - Qt Designer フォームクラス + Qt Widgets Designer Form Class + Qt Widgets Designer フォームクラス Switch Source/Form @@ -18994,8 +18994,8 @@ Rebuilding the project might help. Shift+F4 - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - 既存の Qt ウィジェットプロジェクトに追加可能な Qt Designer フォームとそれに対応したクラス (C++ ヘッダとソースファイル) を作成します。 + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + 既存の Qt ウィジェットプロジェクトに追加可能な Qt Widgets Designer フォームとそれに対応したクラス (C++ ヘッダとソースファイル) を作成します。 Choose a Form Template @@ -25088,8 +25088,8 @@ Neither the path to the library nor the path to its includes is added to the .pr Qt カスタム Designer ウィジェットかカスタムウィジェットコレクションを作成します。 - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - このウィザードは Qt Designer カスタムウィジェットあるいは Qt Designer カスタムウィジェットコレクションプロジェクトを生成します。 + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + このウィザードは Qt Widgets Designer カスタムウィジェットあるいは Qt Widgets Designer カスタムウィジェットコレクションプロジェクトを生成します。 Creating multiple widget libraries (%1, %2) in one project (%3) is not supported. @@ -25140,8 +25140,8 @@ Neither the path to the library nor the path to its includes is added to the .pr アプリケーション "%1" が見つかりませんでした。 - Qt Designer is not responding (%1). - Qt Designer が無応答です(%1)。 + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer が無応答です(%1)。 Unable to create server socket: %1 @@ -25612,10 +25612,10 @@ Neither the path to the library nor the path to its includes is added to the .pr Qt ウィジェットアプリケーション - Creates a Qt application for the desktop. Includes a Qt Designer-based main window. + Creates a Qt application for the desktop. Includes a Qt Widgets Designer-based main window. Preselects a desktop Qt for building the application if available. - Qt Designer ベースのメインウィンドウを持つデスクトップ用 Qt アプリケーションを作成します。 + Qt Widgets Designer ベースのメインウィンドウを持つデスクトップ用 Qt アプリケーションを作成します。 デスクトップ用 Qt が存在する場合、アプリケーションのビルド用に選択します。 @@ -37181,8 +37181,8 @@ Affected are breakpoints %1 Alt+Shift+R - About Qt Designer Plugins... - Qt Designer プラグインについて... + About Qt Widgets Designer Plugins... + Qt Widgets Designer プラグインについて... Preview in @@ -37506,12 +37506,12 @@ Affected are breakpoints %1 フォームテンプレート - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Qt ウィジェットプロジェクトに追加可能な Qt Designer フォームを作成します。これは既に UI ビジネスロジックを実装したクラスを持っている場合に役立ちます。 + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Qt ウィジェットプロジェクトに追加可能な Qt Widgets Designer フォームを作成します。これは既に UI ビジネスロジックを実装したクラスを持っている場合に役立ちます。 - Qt Designer Form - Qt Designer フォーム + Qt Widgets Designer Form + Qt Widgets Designer フォーム Creates a Java file with boilerplate code. @@ -39137,40 +39137,28 @@ Would you like to overwrite it? typeId が "%1" のページの "index" が無効です。 - Path "%1" does not exist when checking Json wizard search paths. - - Json ウィザードの検索パスを確認しましたが、パス "%1" は存在しません。 - + Path "%1" does not exist when checking JSON wizard search paths. + JSON ウィザードの検索パスを確認しましたが、パス "%1" は存在しません。 - Checking "%1" for %2. - - %2 向けに "%1" を確認しています。 - + Checking "%1" for %2. + %2 向けに "%1" を確認しています。 - * Failed to parse "%1":%2:%3: %4 - - ・"%1" の解析に失敗しました:%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + ・"%1" の解析に失敗しました:%2:%3: %4 - * Did not find a JSON object in "%1". - - ・"%1" に JSON オブジェクトが見つかりませんでした。 - + * Did not find a JSON object in "%1". + ・"%1" に JSON オブジェクトが見つかりませんでした。 - * Configuration found and parsed. - - ・設定が見つかり、解析しました。 - + * Configuration found and parsed. + ・設定が見つかり、解析しました。 - * Version %1 not supported. - - ・バージョン %1 には未対応です。 - + * Version %1 not supported. + ・バージョン %1 には未対応です。 The platform selected for the wizard. @@ -39201,16 +39189,12 @@ Would you like to overwrite it? 画像ファイル "%1" が見つかりません。 - * Failed to create: %1 - - ・作成に失敗しました: %1 - + * Failed to create: %1 + ・作成に失敗しました: %1 - JsonWizard: "%1" not found - - JsonWizard: "%1" が見つかりません - + JsonWizard: "%1" not found. + JsonWizard: "%1" が見つかりません。 key not found. diff --git a/share/qtcreator/translations/qtcreator_pl.ts b/share/qtcreator/translations/qtcreator_pl.ts index a59ebcb424c..00278fb998f 100644 --- a/share/qtcreator/translations/qtcreator_pl.ts +++ b/share/qtcreator/translations/qtcreator_pl.ts @@ -151,7 +151,7 @@ - Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. + Toggles if the smoothing is performed using linear interpolation method. Keeping it unchecked would follow non-smooth method using nearest neighbor. It is mostly applicable on image based items. @@ -9917,7 +9917,7 @@ in the system's browser for manual download. Lista Android NDK: - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) Ustawienia Android OpenSSL (opcjonalne) @@ -10692,12 +10692,12 @@ The kit supports "%2", but the device uses "%3". Błąd instalacji, przyczyna nieznana. - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -Deinstalacja uprzednio zainstalowanego pakietu może rozwiązać problem. -Czy zdeinstalować istniejący pakiet? + Uninstalling the installed package may solve the issue. + Deinstalacja uprzednio zainstalowanego pakietu może rozwiązać problem. + + + Do you want to uninstall the existing package? + Czy zdeinstalować istniejący pakiet? The deployment AVD "%1" cannot be started. @@ -12496,7 +12496,7 @@ See also Google Test settings. Powtarzanie testów - Run in parallel + Run in Parallel Uruchomianie równoległe @@ -15958,8 +15958,8 @@ tylko przez wbudowane narzędzie. Użyj globalnych ustawień - ClangFormat settings: - Ustawienia ClangFormat: + ClangFormat Settings + Ustawienia ClangFormat Indenting only @@ -17866,8 +17866,8 @@ Otherwise you need to specify the path to the %2 file from the Copilot neovim pl Edytor QMLJS - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -21384,7 +21384,7 @@ The built-in code model will handle highlighting, completion and so on. Próg uaktualniania dokumentu: - Sessions with a single clangd instance + Sessions with a Single Clangd Instance Sesje z pojedynczą instancją clangd @@ -21537,7 +21537,7 @@ managed by the same clangd process, add them here. Skonwertuj do pliku binarnego - Add forward declaration for %1 + Add Forward Declaration for %1 @@ -22069,8 +22069,8 @@ e.g. name = "m_test_foo_": Własne szablony pobieraczy i ustawiaczy - Value types: - Typy wartości: + Value Types + Typy wartości Projects only @@ -27865,8 +27865,8 @@ Please select a 64 bit Debugger in the kit settings for this kit. Podaj nazwę klasy - Qt Designer Form Class - Klasa formularza Qt Designer + Qt Widgets Designer Form Class + Klasa formularza Qt Widgets Designer Designer @@ -27901,8 +27901,8 @@ Spróbuj ponownie przebudować projekt. Shift+F4 - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - Tworzy formularz Qt Designera wraz z klasą implementującą (plik nagłówkowy i źródłowy C++). Utworzony formularz i klasę można dodać do istniejącego projektu Qt Widget. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Tworzy formularz Qt Widgets Designera wraz z klasą implementującą (plik nagłówkowy i źródłowy C++). Utworzony formularz i klasę można dodać do istniejącego projektu Qt Widget. Choose a Form Template @@ -28053,8 +28053,8 @@ Przebudowanie projektu może pomóc w ich odnalezieniu. Alt+Shift+R - About Qt Designer Plugins... - Informacje o wtyczkach Qt Designera... + About Qt Widgets Designer Plugins... + Informacje o wtyczkach Qt Widgets Designera... Preview in @@ -33297,7 +33297,7 @@ Czy nadpisać je? - Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools) + Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools). @@ -33425,7 +33425,7 @@ Czy nadpisać je? - Suppresses IncrediBuild's header in the build output + Suppresses IncrediBuild's header in the build output. @@ -33433,7 +33433,7 @@ Czy nadpisać je? - Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support + Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support. @@ -33449,7 +33449,7 @@ Czy nadpisać je? - When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds + When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds. @@ -33457,7 +33457,7 @@ Czy nadpisać je? - Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line + Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line. @@ -40741,10 +40741,10 @@ You can select an option to create a project that you can open in Qt Design Stud Informacje o klasie - Creates a widget-based Qt application that contains a Qt Designer-based main window and C++ source and header files to implement the application logic. + Creates a widget-based Qt application that contains a Qt Widgets Designer-based main window and C++ source and header files to implement the application logic. Preselects a desktop Qt for building the application if available. - Tworzy aplikację Qt bazującą na widżetach, zawierającą główne okno do edycji w Qt Designerze wraz z plikami: źródłowym oraz nagłówkowym C++, przeznaczonymi do zaimplementowania logiki aplikacji. + Tworzy aplikację Qt bazującą na widżetach, zawierającą główne okno do edycji w Qt Widgets Designerze wraz z plikami: źródłowym oraz nagłówkowym C++, przeznaczonymi do zaimplementowania logiki aplikacji. Wstępnie wybiera platformę desktopową Qt do budowania aplikacji, jeśli jest ona dostępna. @@ -41115,12 +41115,12 @@ You should not mix multiple test frameworks in a project. Szablon formularza - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Tworzy formularz Qt Designer, który można dodać do projektu typu Qt Widget. Jest to przydatne w sytuacji, kiedy istnieje już klasa zarządzająca logiką UI. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Tworzy formularz Qt Widgets Designer, który można dodać do projektu typu Qt Widget. Jest to przydatne w sytuacji, kiedy istnieje już klasa zarządzająca logiką UI. - Qt Designer Form - Formularz Qt Designer + Qt Widgets Designer Form + Formularz Qt Widgets Designer Creates a Java file with boilerplate code. @@ -41748,40 +41748,28 @@ To develop a full application, create a Qt Quick Application project instead.Strona z typeid "%1" posiada niepoprawny "index". - Path "%1" does not exist when checking Json wizard search paths. - - Ścieżka "%1" nie istnieje podczas sprawdzania ścieżek poszukiwań kreatora Json. - + Path "%1" does not exist when checking JSON wizard search paths. + Ścieżka "%1" nie istnieje podczas sprawdzania ścieżek poszukiwań kreatora JSON. - Checking "%1" for %2. - - Sprawdzanie "%1" dla "%2". - + Checking "%1" for %2. + Sprawdzanie "%1" dla "%2". - * Failed to parse "%1":%2:%3: %4 - - * Nie można sparsować "%1":%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + * Nie można sparsować "%1":%2:%3: %4 - * Did not find a JSON object in "%1". - - * Nie odnaleziono obiektu JSON w "%1". - + * Did not find a JSON object in "%1". + * Nie odnaleziono obiektu JSON w "%1". - * Configuration found and parsed. - - * Konfiguracja odnaleziona i przeparsowana. - + * Configuration found and parsed. + * Konfiguracja odnaleziona i przeparsowana. - * Version %1 not supported. - - * Wersja %1 nieobsługiwana. - + * Version %1 not supported. + * Wersja %1 nieobsługiwana. The platform selected for the wizard. @@ -41812,10 +41800,8 @@ To develop a full application, create a Qt Quick Application project instead.Brak pliku graficznego "%1". - JsonWizard: "%1" not found - - JsonWizard: Nie znaleziono "%1" - + JsonWizard: "%1" not found. + JsonWizard: Nie znaleziono "%1". key not found. @@ -43972,15 +43958,15 @@ The affected files are: Qt Custom Designer Widget - Własny widżet Qt Designera + Własny widżet Qt Widgets Designera Creates a Qt Custom Designer Widget or a Custom Widget Collection. - Tworzy własny widżet Qt Designera lub kolekcję własnych widżetów. + Tworzy własny widżet Qt Widgets Designera lub kolekcję własnych widżetów. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - Ten kreator generuje projekt własnego widżetu Qt Designera lub projekt kolekcji własnych widżetów Qt4 Designera. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + Ten kreator generuje projekt własnego widżetu Qt Widgets Designera lub projekt kolekcji własnych widżetów Qt4 Widget Designera. Creating multiple widget libraries (%1, %2) in one project (%3) is not supported. @@ -43999,8 +43985,8 @@ The affected files are: Nie można odnaleźć aplikacji "%1". - Qt Designer is not responding (%1). - Qt Designer nie odpowiada (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer nie odpowiada (%1). Unable to create server socket: %1 @@ -48594,7 +48580,7 @@ Błąd uruchamiania procesu kontrolnego. - Unknown error occurred while trying to create remote directories + Unknown error occurred while trying to create remote directories. @@ -51127,11 +51113,11 @@ Nie można otworzyć pliku "%1". - Terminal process exited with code %1 + Terminal process exited with code %1. - Process exited with code: %1 + Process exited with code: %1. @@ -52785,7 +52771,7 @@ Ustala, jak klawisz "Backspace" reaguje na wcięcia. Pomiędzy liniami - Line annotations + Line Annotations Adnotacje linii @@ -53763,7 +53749,7 @@ po naciśnięciu klawisza Enter - &Automatically insert matching characters + &Automatically Insert Matching Characters &Automatyczne wstawianie znaków @@ -53843,7 +53829,7 @@ po naciśnięciu klawisza backspace Doxygen allows "@" and "\" to start commands. By default, "@" is used if the surrounding comment starts with "/**" or "///", and "\" is used -if the comment starts with "/*!" or "//! +if the comment starts with "/*!" or "//!". @@ -54158,7 +54144,7 @@ if the comment starts with "/*!" or "//! Zresetuj - Scanning scope + Scanning Scope Zakres skanowania diff --git a/share/qtcreator/translations/qtcreator_ru.ts b/share/qtcreator/translations/qtcreator_ru.ts index ac9a564f8b3..44f5dfa5823 100644 --- a/share/qtcreator/translations/qtcreator_ru.ts +++ b/share/qtcreator/translations/qtcreator_ru.ts @@ -933,12 +933,12 @@ The files in the Android package source directory are copied to the build direct - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -Удаление установленного пакета может решить проблему. -Желаете его удалить? + Uninstalling the installed package may solve the issue. + Удаление установленного пакета может решить проблему. + + + Do you want to uninstall the existing package? + Желаете его удалить? Pulling files necessary for debugging. @@ -2169,7 +2169,7 @@ To hide a sticky splash screen, invoke QtAndroid::hideSplashScreen(). Настроить SDK - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) Настройки Android OpenSSL (опционально) @@ -11815,7 +11815,7 @@ Flags: %3 Добавить #include %1 - Add forward declaration for %1 + Add Forward Declaration for %1 Добавление предъобъявления %1 @@ -16950,8 +16950,8 @@ Rebuilding the project might help. Пересборка проекта может помочь. - Qt Designer Form Class - Класс формы Qt Designer + Qt Widgets Designer Form Class + Класс формы Qt Widgets Designer Class Details @@ -16982,7 +16982,7 @@ Rebuilding the project might help. Shift+F4 - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. Создание формы дизайнера Qt и соответствующего класса (исходный и заголовочный файлы C++) для реализации. Их можно будет добавить к существующему проекту Qt Widget. @@ -18313,8 +18313,14 @@ will also disable the following plugins: Executable: + adjective Можно запускать: + + Executable: + noun + Программа: + Symbolic link: Символьная ссылка: @@ -18681,8 +18687,8 @@ when they are not required, which will improve performance in most cases.Alt+Shift+R - About Qt Designer Plugins... - О модулях Qt Designer... + About Qt Widgets Designer Plugins... + О модулях Qt Widgets Designer... Preview in @@ -22415,8 +22421,8 @@ Would you like to overwrite them? Максимальное количество ЦП для сборки: - When specified, the execution will stop as soon as an error is encountered. This is the default behavior in 'Visual Studio' builds, but not the default for 'Make and Build tools' or 'Dev Tools' builds - Включение остановки выполнения при возникновении ошибки. Это поведение по умолчанию в сборках «Visual Studio», но не по умолчанию для сборок «Make and Build tools» или «Dev Tools» + When specified, the execution will stop as soon as an error is encountered. This is the default behavior in 'Visual Studio' builds, but not the default for 'Make and Build tools' or 'Dev Tools' builds. + Включение остановки выполнения при возникновении ошибки. Это поведение по умолчанию в сборках «Visual Studio», но не по умолчанию для сборок «Make and Build tools» или «Dev Tools». Stop On Errors @@ -22467,7 +22473,7 @@ Would you like to overwrite them? Помощник запуска: - Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line + Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line. Дополнительные параметры buildconsole. Значение поля будет добавлено к итоговой командной строке buildconsole. @@ -22495,7 +22501,7 @@ Would you like to overwrite them? Исходное число задач - Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support + Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support. Меняет для этой сборки уровень ведения внутреннего журнала Incredibuild. Не влияет на вывод или любые доступные пользователю журналы. В основном используется для устранения проблем через службу поддержки IncrediBuild. @@ -25534,8 +25540,8 @@ If set to false, the target will be moved straight to the current mouse position Редактор QMLJS - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -29867,12 +29873,12 @@ Enable this if you plan to create 32-bit x86 binaries without using a dedicated Шаблон формы - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Создание формы Qt Designer, которую можно добавить в проект Qt Widget. Имеет смысл, если у вас уже есть класс с бизнес-логикой. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Создание формы Qt Widgets Designer, которую можно добавить в проект Qt Widget. Имеет смысл, если у вас уже есть класс с бизнес-логикой. - Qt Designer Form - Форма Qt Designer + Qt Widgets Designer Form + Форма Qt Widgets Designer Creates a Java file with boilerplate code. @@ -30627,7 +30633,7 @@ Use this only if you are prototyping. You cannot create a full application with Информация о классе - Creates a Qt application for the desktop. Includes a Qt Designer-based main window. + Creates a Qt application for the desktop. Includes a Qt Widgets Designer-based main window. Preselects a desktop Qt for building the application if available. Создание приложения Qt для настольных компьютеров. Включает основное окно в виде формы дизайнера Qt. @@ -30707,8 +30713,8 @@ Preselects a desktop Qt for building the application if available. Qt для Python - Приложение Qt Quick - Пустое - Creates a Qt for Python application that includes a Qt Designer-based widget (ui file) - Создание приложения на Qt для Python, включающее виджет Qt Designer (файл ui) + Creates a Qt for Python application that includes a Qt Widgets Designer-based widget (ui file) + Создание приложения на Qt для Python, включающее виджет Qt Widgets Designer (файл ui) Qt for Python - Window (UI file) @@ -30999,40 +31005,28 @@ Preselects a desktop Qt for building the application if available. У страницы с typeId «%1» неверный «index». - Path "%1" does not exist when checking Json wizard search paths. - - При проверке путей мастера Json: путь «%1» не существует. - + Path "%1" does not exist when checking JSON wizard search paths. + При проверке путей мастера JSON: путь «%1» не существует. - Checking "%1" for %2. - - Проверяется «%1» у %2. - + Checking "%1" for %2. + Проверяется «%1» у %2. - * Failed to parse "%1":%2:%3: %4 - - * Не удалось разобрать «%1»:%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + * Не удалось разобрать «%1»:%2:%3: %4 - * Did not find a JSON object in "%1". - - * Объект JSON не был найден в «%1». - + * Did not find a JSON object in "%1". + * Объект JSON не был найден в «%1». - * Configuration found and parsed. - - * Конфигурация обнаружена и разобрана. - + * Configuration found and parsed. + * Конфигурация обнаружена и разобрана. - * Version %1 not supported. - - * Версия %1 не поддерживается. - + * Version %1 not supported. + * Версия %1 не поддерживается. The platform selected for the wizard. @@ -31063,16 +31057,12 @@ Preselects a desktop Qt for building the application if available. Файл изображения «%1» не найден. - * Failed to create: %1 - - * Не удалось создать: %1 - + * Failed to create: %1 + * Не удалось создать: %1 - JsonWizard: "%1" not found - - JsonWizard: «%1» не найден - + JsonWizard: "%1" not found. + JsonWizard: «%1» не найден. key not found. @@ -33673,19 +33663,19 @@ Please update your kit (%3) or choose a mkspec for qmake that matches your targe Qt Custom Designer Widget - Пользовательский виджет Qt Designer + Пользовательский виджет Qt Widgets Designer Creates a Qt Custom Designer Widget or a Custom Widget Collection. - Создание пользовательского виджета Qt Designer или набора пользовательских виджетов. + Создание пользовательского виджета Qt Widgets Designer или набора пользовательских виджетов. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - Этот мастер создаст пользовательский виджет или набор пользовательских виджетов для Qt Designer. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + Этот мастер создаст пользовательский виджет или набор пользовательских виджетов для Qt Widgets Designer. - Qt Designer is not responding (%1). - Qt Designer не отвечает (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer не отвечает (%1). Unable to create server socket: %1 @@ -35227,7 +35217,7 @@ Neither the path to the library nor the path to its includes is added to the .pr Warn about unsupported features of Qt Quick Designer in the code editor - Предупреждать о неподдерживаемых особенностях Qt Designer в редакторе кода + Предупреждать о неподдерживаемых особенностях Qt Quick Designer в редакторе кода Debugging @@ -43141,7 +43131,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and Автоматически разделять строки - &Automatically insert matching characters + &Automatically Insert Matching Characters &Автоматически вставлять парные символы @@ -43325,7 +43315,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and Прижать к правому краю - Line annotations + Line Annotations Построчная аннотация @@ -45147,7 +45137,7 @@ The trace data is lost. Сбросить - Scanning scope + Scanning Scope Область поиска diff --git a/share/qtcreator/translations/qtcreator_sl.ts b/share/qtcreator/translations/qtcreator_sl.ts index e5b3b87b02b..837f8267ded 100644 --- a/share/qtcreator/translations/qtcreator_sl.ts +++ b/share/qtcreator/translations/qtcreator_sl.ts @@ -3532,8 +3532,8 @@ Morda lahko pomaga ponovna gradnja projekta. Urejevalnik XML - Qt Designer Form Class - Razred obrazca Qt Designer + Qt Widgets Designer Form Class + Razred obrazca Qt Widgets Designer Form Template @@ -3560,8 +3560,8 @@ Morda lahko pomaga ponovna gradnja projekta. Nastavitve … - Qt Designer Form - Obrazec Qt Designer + Qt Widgets Designer Form + Obrazec Qt Widgets Designer Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. @@ -3676,8 +3676,8 @@ Morda lahko pomaga ponovna gradnja projekta. Urejevalnik signalov in rež - About Qt Designer plugins.... - O vstavkih za Qt Designer … + About Qt Widgets Designer plugins.... + O vstavkih za Qt Widgets Designer … Preview in @@ -7756,14 +7756,6 @@ Preselects a desktop Qt for building the application if available. problemLabel oznakaTežave - - Error: - Napaka: - - - Warning: - Opozorilo: - Configuration name: Ime nastavitev: @@ -10733,8 +10725,8 @@ Za uporabo v polje Iskalnika vtipkajte to bližnjico in presledek ter nato iskan Urejevalniku QMLJS - Qt Designer - Qt Designerju + Qt Widgets Designer + Qt Widgets Designerju Qt Linguist @@ -11579,15 +11571,15 @@ Razlog: %2 Qt Custom Designer Widget - Gradnik za Qt Designer po meri + Gradnik za Qt Widgets Designer po meri Creates a Qt Custom Designer Widget or a Custom Widget Collection. - Ustvari gradnik za Qt Designer po meri ali pa zbirko gradnikov po meri + Ustvari gradnik za Qt Widgets Designer po meri ali pa zbirko gradnikov po meri This wizard generates a Qt4 Designer Custom Widget or a Qt4 Designer Custom Widget Collection project. - Ta čarovnik ustvari projekt gradnika po meri za Qt Designer ali pa projekt zbirke gradnikov po meri za Qt Designer. + Ta čarovnik ustvari projekt gradnika po meri za Qt Widgets Designer ali pa projekt zbirke gradnikov po meri za Qt Widgets Designer. Custom Widgets @@ -11618,8 +11610,8 @@ Razlog: %2 Programa »%1« ni bilo moč najti. - Qt Designer is not responding (%1). - Qt Designer se ne odziva (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer se ne odziva (%1). Unable to create server socket: %1 @@ -16012,8 +16004,8 @@ Projekte programov QML izvede pregledovalnik QML in jih ni potrebno zgraditi.Predloga pošiljanja za CVS - Qt Designer file - Datoteka za Qt Designer + Qt Widgets Designer file + Datoteka za Qt Widgets Designer Generic Qt Creator Project file diff --git a/share/qtcreator/translations/qtcreator_uk.ts b/share/qtcreator/translations/qtcreator_uk.ts index 432f5ab3a24..d3da748f62e 100644 --- a/share/qtcreator/translations/qtcreator_uk.ts +++ b/share/qtcreator/translations/qtcreator_uk.ts @@ -3153,7 +3153,7 @@ to version control (%2) Автоматично вставляти крапки з комами, закриваючі квадратні, круглі, фігурні дужки та лапки, коли необхідно. - &Automatically insert matching characters + &Automatically Insert Matching Characters &Автоматично вставляти парні символи @@ -6843,8 +6843,8 @@ Rebuilding the project might help. Додавати версію Qt в #ifdef для імен модулів - Qt Designer Form Class - Клас форми Qt Designer + Qt Widgets Designer Form Class + Клас форми Qt Widgets Designer Choose a Class Name @@ -6883,8 +6883,8 @@ Rebuilding the project might help. Створює форму Qt Designer, яку ви можете додати до проекту Qt Widget. Це корисно, якщо ви вже маєте існуючий клас для бізнес-логіки UI. - Creates a Qt Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. - Створює форму Qt Designer разом з відповідним класом (файли заголовку та коду C++) з метою реалізації.. Ви можете додати форму та клас до існуючого проекту Qt Widget. + Creates a Qt Widgets Designer form along with a matching class (C++ header and source file) for implementation purposes. You can add the form and class to an existing Qt Widget Project. + Створює форму Qt Widgets Designer разом з відповідним класом (файли заголовку та коду C++) з метою реалізації.. Ви можете додати форму та клас до існуючого проекту Qt Widget. Location @@ -11142,8 +11142,8 @@ Ids must begin with a lowercase letter. Редактор QMLJS - Qt Designer - Qt Designer + Qt Widgets Designer + Qt Widgets Designer Qt Linguist @@ -15626,19 +15626,19 @@ Preselects a desktop Qt for building the application if available. Qt Custom Designer Widget - Користувацький віджет Qt Designer + Користувацький віджет Qt Widgets Designer Creates a Qt Custom Designer Widget or a Custom Widget Collection. - Створює користувацький віджет Qt Designer або колекцію користувацьких віджетів. + Створює користувацький віджет Qt Widgets Designer або колекцію користувацьких віджетів. - This wizard generates a Qt Designer Custom Widget or a Qt Designer Custom Widget Collection project. - Цей майстер генерує проект користувацького віджета Qt Designer або колекції користувацьких віджетів Qt Designer. + This wizard generates a Qt Widgets Designer Custom Widget or a Qt Widgets Designer Custom Widget Collection project. + Цей майстер генерує проект користувацького віджета Qt Widgets Designer або колекції користувацьких віджетів Qt Widgets Designer. - Qt Designer is not responding (%1). - Qt Designer не відповідає (%1). + Qt Widgets Designer is not responding (%1). + Qt Widgets Designer не відповідає (%1). Unable to create server socket: %1 @@ -15717,10 +15717,10 @@ Preselects a desktop Qt for building the application if available. Програма Qt Widgets - Creates a Qt application for the desktop. Includes a Qt Designer-based main window. + Creates a Qt application for the desktop. Includes a Qt Widgets Designer-based main window. Preselects a desktop Qt for building the application if available. - Створює програму Qt для стаціонарного комп'ютера. Включає головне вікно на основі Qt Designer. + Створює програму Qt для стаціонарного комп'ютера. Включає головне вікно на основі Qt Widgets Designer. Обирає Qt для стільниці для збірки програми, якщо доступно. @@ -21894,7 +21894,7 @@ Influences the indentation of continuation lines. Скинути - Scanning scope + Scanning Scope Область пошуку @@ -37378,8 +37378,8 @@ The statements may not contain '{' nor '}' characters.Alt+Shift+R - About Qt Designer Plugins... - Про додатки Qt Designer.... + About Qt Widgets Designer Plugins... + Про додатки Qt Widgets Designer.... Preview in @@ -37719,12 +37719,12 @@ The statements may not contain '{' nor '}' characters.Шаблон форми - Creates a Qt Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. - Створює форму Qt Designer, яку ви можете додати до проекту Qt Widget. Це корисно, якщо ви вже маєте існуючий клас для бізнес-логіки UI. + Creates a Qt Widgets Designer form that you can add to a Qt Widget Project. This is useful if you already have an existing class for the UI business logic. + Створює форму Qt Widgets Designer, яку ви можете додати до проекту Qt Widget. Це корисно, якщо ви вже маєте існуючий клас для бізнес-логіки UI. - Qt Designer Form - Форма Qt Designer + Qt Widgets Designer Form + Форма Qt Widgets Designer Creates a Java file with boilerplate code. @@ -38747,40 +38747,28 @@ Preselects a desktop Qt for building the application if available. Сторінка з "%1" має неправильний "index". - Path "%1" does not exist when checking Json wizard search paths. - - Перевірка шляхів пошуків майстра Json: шлях "%1" не існує. - + Path "%1" does not exist when checking JSON wizard search paths. + Перевірка шляхів пошуків майстра JSON: шлях "%1" не існує. - Checking "%1" for %2. - - Перевірка "%1" для %2. - + Checking "%1" for %2. + Перевірка "%1" для %2. - * Failed to parse "%1":%2:%3: %4 - - * Збій розбору "%1":%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 + * Збій розбору "%1":%2:%3: %4 - * Did not find a JSON object in "%1". - - * Не знайдено об'єкт JSON в "%1". - + * Did not find a JSON object in "%1". + * Не знайдено об'єкт JSON в "%1". - * Configuration found and parsed. - - * Конфігурацію знайдено та розібрано. - + * Configuration found and parsed. + * Конфігурацію знайдено та розібрано. - * Version %1 not supported. - - * Версія %1 не підтримується. - + * Version %1 not supported. + * Версія %1 не підтримується. The platform selected for the wizard. @@ -38817,16 +38805,12 @@ Preselects a desktop Qt for building the application if available. - * Failed to create: %1 - - * Збій створення: %1 - + * Failed to create: %1 + * Збій створення: %1 - JsonWizard: "%1" not found - - JsonWizard: "%1" не знайдено - + JsonWizard: "%1" not found. + JsonWizard: "%1" не знайдено. key not found. diff --git a/share/qtcreator/translations/qtcreator_zh_CN.ts b/share/qtcreator/translations/qtcreator_zh_CN.ts index 7526f78c968..66a622a4259 100644 --- a/share/qtcreator/translations/qtcreator_zh_CN.ts +++ b/share/qtcreator/translations/qtcreator_zh_CN.ts @@ -787,12 +787,12 @@ The kit supports "%2", but the device uses "%3". - -Uninstalling the installed package may solve the issue. -Do you want to uninstall the existing package? - -卸载已安装的包可能解决这个问题。 -你想卸载已经存在的包吗? + Uninstalling the installed package may solve the issue. + 卸载已安装的包可能解决这个问题。 + + + Do you want to uninstall the existing package? + 你想卸载已经存在的包吗? Install failed @@ -1900,7 +1900,7 @@ in the system's browser for manual download. 安卓 NDK 列表: - Android OpenSSL settings (Optional) + Android OpenSSL Settings (Optional) 安卓 OpenSSL 设置(可选) @@ -2714,7 +2714,7 @@ Executable: %2 重复测试 - Run in parallel + Run in Parallel 并行运行 @@ -11600,7 +11600,7 @@ The built-in code model will handle highlighting, completion and so on. - Sessions with a single clangd instance + Sessions with a Single Clangd Instance @@ -12511,7 +12511,7 @@ Flags: %3 添加#include %1 - Add forward declaration for %1 + Add Forward Declaration for %1 @@ -12767,7 +12767,7 @@ Flags: %3 - Value types: + Value Types: @@ -22584,7 +22584,7 @@ Would you like to overwrite them? - Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools) + Make sure the build command's multi-job parameter value is large enough (such as -j200 for the JOM or Make build tools). @@ -22704,7 +22704,7 @@ Would you like to overwrite them? - Suppresses IncrediBuild's header in the build output + Suppresses IncrediBuild's header in the build output. @@ -22712,7 +22712,7 @@ Would you like to overwrite them? - Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support + Overrides the internal Incredibuild logging level for this build. Does not affect output or any user accessible logging. Used mainly to troubleshoot issues with the help of IncrediBuild support. @@ -22732,7 +22732,7 @@ Would you like to overwrite them? - When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds + When specified, the execution will stop as soon as an error is encountered. This is the default behavior in "Visual Studio" builds, but not the default for "Make and Build tools" or "Dev Tools" builds. @@ -22740,7 +22740,7 @@ Would you like to overwrite them? - Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line + Add additional buildconsole arguments manually. The value of this field will be concatenated to the final buildconsole command line. @@ -28771,33 +28771,27 @@ Enable this if you plan to create 32-bit x86 binaries without using a dedicated - Path "%1" does not exist when checking Json wizard search paths. - + Path "%1" does not exist when checking JSON wizard search paths. - Checking "%1" for %2. - + Checking "%1" for %2. - * Failed to parse "%1":%2:%3: %4 - + * Failed to parse "%1":%2:%3: %4 - * Did not find a JSON object in "%1". - + * Did not find a JSON object in "%1". - * Configuration found and parsed. - + * Configuration found and parsed. - JsonWizard: "%1" not found - + JsonWizard: "%1" not found. @@ -28817,8 +28811,7 @@ Enable this if you plan to create 32-bit x86 binaries without using a dedicated - * Version %1 not supported. - + * Version %1 not supported. @@ -42598,7 +42591,7 @@ Specifies how backspace interacts with indentation. - Line annotations + Line Annotations @@ -42985,7 +42978,7 @@ In addition, Shift+Enter inserts an escape character at the cursor position and - &Automatically insert matching characters + &Automatically Insert Matching Characters @@ -44781,7 +44774,7 @@ Will not be applied to whitespace in comments and strings. 重置 - Scanning scope + Scanning Scope 扫描范围 diff --git a/share/qtcreator/translations/qtcreator_zh_TW.ts b/share/qtcreator/translations/qtcreator_zh_TW.ts index d21d4d9bca2..7b5f5cfba84 100644 --- a/share/qtcreator/translations/qtcreator_zh_TW.ts +++ b/share/qtcreator/translations/qtcreator_zh_TW.ts @@ -1715,7 +1715,7 @@ 在適當的時候自動插入分號、結束的括號、大括號與引號等等。 - &Automatically insert matching characters + &Automatically Insert Matching Characters 自動插入對應的字元(&A) @@ -25376,7 +25376,7 @@ Influences the indentation of continuation lines. 重置 - Scanning scope + Scanning Scope 掃描範圍 diff --git a/share/share.qbs b/share/share.qbs index a2114dad2d2..745a8131a94 100644 --- a/share/share.qbs +++ b/share/share.qbs @@ -16,6 +16,8 @@ Product { "debugger/**/*", "designer/**/*", "glsl/**/*", + "jsonschemas/**/*", + "lua-plugins/**/*", "modeleditor/**/*", "qml/**/*", "qmldesigner/**/*", diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 792b3012f27..f537d8b9c4f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -36,6 +36,10 @@ install(EXPORT QtCreator ) file(WRITE ${CMAKE_BINARY_DIR}/cmake/QtCreatorConfig.cmake " +\# Qt version used for building +\# A compatible Qt version should be used by externally built plugins +set(QTC_QT_VERSION ${QT_VERSION}) + \# force plugins to same path naming conventions as Qt Creator \# otherwise plugins will not be found if(UNIX AND NOT APPLE) diff --git a/src/app/main.cpp b/src/app/main.cpp index 42cb4f6a65e..ba15eef6856 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -91,8 +91,6 @@ const char PLUGINPATH_OPTION[] = "-pluginpath"; const char LANGUAGE_OPTION[] = "-language"; const char USER_LIBRARY_PATH_OPTION[] = "-user-library-path"; // hidden option for qtcreator.sh -using PluginSpecSet = QVector; - // Helpers for displaying messages. Note that there is no console on Windows. // Format as
     HTML
    @@ -179,8 +177,11 @@ static inline int askMsgSendFailed()
     
     static inline QStringList getPluginPaths()
     {
    -    QStringList rc(QDir::cleanPath(QApplication::applicationDirPath()
    -                                   + '/' + RELATIVE_PLUGIN_PATH));
    +    QStringList rc;
    +    rc << (QDir::cleanPath(QApplication::applicationDirPath()
    +                                   + '/' + RELATIVE_PLUGIN_PATH))
    +       << (QDir::cleanPath(QApplication::applicationDirPath()
    +                           + '/' + RELATIVE_DATA_PATH + "/lua-plugins"));
         // Local plugin path: /plugins/
         //    where  is e.g.
         //    "%LOCALAPPDATA%\QtProject\qtcreator" on Windows Vista and later
    @@ -583,11 +584,6 @@ int main(int argc, char **argv)
             QApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);
         }
     
    -    if (Utils::HostOsInfo::isLinuxHost() && !qEnvironmentVariableIsSet("GTK_THEME"))
    -        // Work around QTCREATORBUG-28497:
    -        // Prevent Qt's GTK3 platform theme plugin from enforcing a dark palette
    -        qputenv("GTK_THEME", ":light");
    -
     #if defined(QTC_FORCE_XCB)
         if (Utils::HostOsInfo::isLinuxHost() && !qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) {
             // Enforce XCB on Linux/Gnome, if the user didn't override via QT_QPA_PLATFORM
    @@ -684,10 +680,19 @@ int main(int argc, char **argv)
         setPixmapCacheLimit();
         loadFonts();
     
    -    if (Utils::HostOsInfo::isWindowsHost() && !qFuzzyCompare(qApp->devicePixelRatio(), 1.0)
    -        && !hasStyleOption) {
    -        QApplication::setStyle(QLatin1String("fusion"));
    +    if (Utils::HostOsInfo::isWindowsHost() && !hasStyleOption) {
    +        // The Windows 11 default style (Qt 6.7) has major issues, therefore
    +        // set the previous default style: "windowsvista"
    +        // FIXME: check newer Qt Versions
    +        QApplication::setStyle(QLatin1String("windowsvista"));
    +
    +        // On scaling different than 100% or 200% use the "fusion" style
    +        qreal tmp;
    +        const bool fractionalDpi = !qFuzzyIsNull(std::modf(qApp->devicePixelRatio(), &tmp));
    +        if (fractionalDpi)
    +            QApplication::setStyle(QLatin1String("fusion"));
         }
    +
         const int threadCount = QThreadPool::globalInstance()->maxThreadCount();
         QThreadPool::globalInstance()->setMaxThreadCount(qMax(4, 2 * threadCount));
     
    @@ -768,7 +773,7 @@ int main(int argc, char **argv)
         // Load
         const QStringList pluginPaths = getPluginPaths() + installPluginPaths
                                         + options.customPluginPaths;
    -    PluginManager::setPluginPaths(pluginPaths);
    +    PluginManager::setPluginPaths(Utils::transform(pluginPaths, &Utils::FilePath::fromUserInput));
         QMap foundAppOptions;
         if (pluginArguments.size() > 1) {
             QMap appOptions;
    @@ -798,7 +803,7 @@ int main(int argc, char **argv)
                 settingspath};
         PluginManager::setCreatorProcessData(processData);
     
    -    const PluginSpecSet plugins = PluginManager::plugins();
    +    const PluginSpecs plugins = PluginManager::plugins();
         PluginSpec *coreplugin = nullptr;
         for (PluginSpec *spec : plugins) {
             if (spec->name() == QLatin1String(corePluginNameC)) {
    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/cplusplus/AST.h b/src/libs/3rdparty/cplusplus/AST.h
    index 3f48e192b93..085fff92bdb 100644
    --- a/src/libs/3rdparty/cplusplus/AST.h
    +++ b/src/libs/3rdparty/cplusplus/AST.h
    @@ -99,8 +99,8 @@ public:
                     iter = iter->next;
                 return *this;
             }
    -        bool operator==(const ListIterator &other) { return iter == other.iter; }
    -        bool operator!=(const ListIterator &other) { return iter != other.iter; }
    +        bool operator==(const ListIterator &other) const { return iter == other.iter; }
    +        bool operator!=(const ListIterator &other) const { return iter != other.iter; }
         };
         ListIterator begin() { return {this}; }
         ListIterator end() { return {nullptr}; }
    diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
    index e680ee2660e..3e51352b147 100644
    --- a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
    +++ b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
    @@ -27,7 +27,7 @@
     #include "Literals.h"
     #include "DiagnosticClient.h"
     
    -#include "cppassert.h"
    +#include 
     #include 
     
     #include 
    @@ -88,7 +88,7 @@ int TranslationUnit::sourceLength() const
     
     void TranslationUnit::setSource(const char *source, int size)
     {
    -    CPP_CHECK(source);
    +    QTC_ASSERT(source, return);
         _firstSourceChar = source;
         _lastSourceChar = source + size;
     }
    @@ -191,6 +191,8 @@ void TranslationUnit::tokenize()
         int lineColumnIdx = 0;
     
         Token tk;
    +    int macroOffset = -1;
    +    int macroLength = -1;
         do {
             lex(&tk);
     
    @@ -209,17 +211,12 @@ recognize:
                             lex(&tk);
     
                             // Gather where the expansion happens and its length.
    -                        //int macroOffset = static_cast(strtoul(tk.spell(), 0, 0));
    +                        macroOffset = static_cast(strtoul(tk.spell(), 0, 0));
                             lex(&tk);
                             lex(&tk); // Skip the separating comma
    -                        //int macroLength = static_cast(strtoul(tk.spell(), 0, 0));
    +                        macroLength = static_cast(strtoul(tk.spell(), 0, 0));
                             lex(&tk);
     
    -                        // NOTE: We are currently not using the macro offset and length. They
    -                        // are kept here for now because of future use.
    -                        //Q_UNUSED(macroOffset)
    -                        //Q_UNUSED(macroLength)
    -
                             // Now we need to gather the real line and columns from the upcoming
                             // tokens. But notice this is only relevant for tokens which are expanded
                             // but not generated.
    @@ -307,6 +304,11 @@ recognize:
             tk.f.generated = currentGenerated;
     
             _tokens->push_back(tk);
    +
    +        if (currentExpanded) {
    +            QTC_ASSERT(macroOffset != -1 && macroLength != -1, continue);
    +            _expansionPositions[int(_tokens->size()) - 1] = std::make_pair(macroOffset, macroLength);
    +        }
         } while (tk.kind());
     
         for (; ! braces.empty(); braces.pop()) {
    @@ -462,6 +464,14 @@ int TranslationUnit::getTokenEndPositionInDocument(const Token &token,
         return Utils::Text::positionInText(doc, line, column);
     }
     
    +std::pair TranslationUnit::getExpansionPosition(int tokenIndex) const
    +{
    +    QTC_ASSERT(tokenIndex < int(_tokens->size()) && tokenAt(tokenIndex).generated(), return {});
    +    const auto it = _expansionPositions.find(tokenIndex);
    +    QTC_ASSERT(it != _expansionPositions.end(), return {});
    +    return it->second;
    +}
    +
     void TranslationUnit::getPosition(int utf16charOffset,
                                       int *line,
                                       int *column,
    diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.h b/src/libs/3rdparty/cplusplus/TranslationUnit.h
    index 40f79d0091d..1332549ffde 100644
    --- a/src/libs/3rdparty/cplusplus/TranslationUnit.h
    +++ b/src/libs/3rdparty/cplusplus/TranslationUnit.h
    @@ -133,6 +133,7 @@ public:
                                  const StringLiteral **fileName = nullptr) const;
         int getTokenPositionInDocument(const Token token, const QTextDocument *doc) const;
         int getTokenEndPositionInDocument(const Token &token, const QTextDocument *doc) const;
    +    std::pair getExpansionPosition(int tokenIndex) const;
     
         void pushLineOffset(int offset);
         void pushPreprocessorLine(int utf16charOffset,
    @@ -183,6 +184,11 @@ private:
         std::vector *_comments;
         std::vector _lineOffsets;
         std::vector _ppLines;
    +
    +    // Offset and length. Note that in contrast to token offsets, this is a raw file offset
    +    // with no preprocessor prefix.
    +    std::unordered_map> _expansionPositions;
    +
         typedef std::unordered_map > TokenLineColumn;
         TokenLineColumn _expandedLineColumn;
         MemoryPool *_pool;
    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..c957e0bdd9e 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
    @@ -397,10 +1132,6 @@ qint64 ConPtyProcess::write(const QByteArray &byteArray)
     
     bool ConPtyProcess::isAvailable()
     {
    -#ifdef TOO_OLD_WINSDK
    -    return false; //very importnant! ConPty can be built, but it doesn't work if built with old sdk and Win10 < 1903
    -#endif
    -
         qint32 buildNumber = QSysInfo::kernelVersion().split(".").last().toInt();
         if (buildNumber < CONPTY_MINIMAL_WINDOWS_VERSION)
             return false;
    diff --git a/src/libs/3rdparty/libptyqt/conptyprocess.h b/src/libs/3rdparty/libptyqt/conptyprocess.h
    index aaf56fe76f1..0f30288dab9 100644
    --- a/src/libs/3rdparty/libptyqt/conptyprocess.h
    +++ b/src/libs/3rdparty/libptyqt/conptyprocess.h
    @@ -20,7 +20,6 @@
     
     typedef VOID* HPCON;
     
    -#define TOO_OLD_WINSDK
     #endif
     
     class QWinEventNotifier;
    diff --git a/src/libs/3rdparty/libvterm/vterm.qbs b/src/libs/3rdparty/libvterm/vterm.qbs
    index e35658908da..4c3a08e519e 100644
    --- a/src/libs/3rdparty/libvterm/vterm.qbs
    +++ b/src/libs/3rdparty/libvterm/vterm.qbs
    @@ -30,6 +30,6 @@ QtcLibrary {
     
         Export {
             Depends { name: "cpp" }
    -        cpp.includePaths: "include"
    +        cpp.includePaths: exportingProduct.sourceDirectory + "/include"
         }
     }
    diff --git a/src/libs/3rdparty/lua/CMakeLists.txt b/src/libs/3rdparty/lua/CMakeLists.txt
    new file mode 100644
    index 00000000000..4501f540c89
    --- /dev/null
    +++ b/src/libs/3rdparty/lua/CMakeLists.txt
    @@ -0,0 +1,75 @@
    +
    +add_qtc_library(lua546
    +  PROPERTIES QT_COMPILE_OPTIONS_DISABLE_WARNINGS ON
    +  PUBLIC_INCLUDES src
    +  STATIC
    +  SOURCES
    +    src/lapi.c
    +    src/lapi.h
    +    src/lauxlib.c
    +    src/lauxlib.h
    +    src/lbaselib.c
    +    src/lcode.c
    +    src/lcode.h
    +    src/lcorolib.c
    +    src/lctype.c
    +    src/lctype.h
    +    src/ldblib.c
    +    src/ldebug.c
    +    src/ldebug.h
    +    src/ldo.c
    +    src/ldo.h
    +    src/ldump.c
    +    src/lfunc.c
    +    src/lfunc.h
    +    src/lgc.c
    +    src/lgc.h
    +    src/linit.c
    +    src/liolib.c
    +    src/llex.c
    +    src/llex.h
    +    src/lmathlib.c
    +    src/lmem.c
    +    src/lmem.h
    +    src/loadlib.c
    +    src/lobject.c
    +    src/lobject.h
    +    src/lopcodes.c
    +    src/lopcodes.h
    +    src/loslib.c
    +    src/lparser.c
    +    src/lparser.h
    +    src/lstate.c
    +    src/lstate.h
    +    src/lstring.c
    +    src/lstring.h
    +    src/lstrlib.c
    +    src/ltable.c
    +    src/ltable.h
    +    src/ltablib.c
    +    src/ltm.c
    +    src/ltm.h
    +    src/lua.c
    +    src/lua.h
    +    src/luaconf.h
    +    src/lundump.c
    +    src/lundump.h
    +    src/lutf8lib.c
    +    src/lvm.c
    +    src/lvm.h
    +    src/lzio.c
    +    src/lzio.h
    +)
    +
    +extend_qtc_library(lua546
    +  CONDITION LINUX
    +  PUBLIC_DEFINES LUA_USE_LINUX
    +)
    +extend_qtc_library(lua546
    +  CONDITION WIN32
    +  PUBLIC_DEFINES LUA_USE_WINDOWS
    +)
    +extend_qtc_library(lua546
    +  CONDITION APPLE
    +  PUBLIC_DEFINES LUA_USE_MACOSX
    +)
    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 00000000000..5c77eacc3b8 Binary files /dev/null and b/src/libs/3rdparty/lua/doc/logo.gif differ 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 00000000000..07df5f6ee7a Binary files /dev/null and b/src/libs/3rdparty/lua/doc/osi-certified-72x60.png differ 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/lua.qbs b/src/libs/3rdparty/lua/lua.qbs new file mode 100644 index 00000000000..73d61b039cf --- /dev/null +++ b/src/libs/3rdparty/lua/lua.qbs @@ -0,0 +1,81 @@ +QtcLibrary { + name: "lua546" + type: "staticlibrary" + + cpp.defines: { + var defines = base; + if (qbs.targetOS.contains("windows")) + defines.push("LUA_USE_WINDOWS"); + else if (qbs.targetOS.contains("macos")) + defines.push("LUA_USE_MACOSX"); + else if (qbs.targetOS.contains("linux")) + defines.push("LUA_USE_LINUX"); + return defines; + } + + Group { + name: "Sources" + prefix: "src/" + + files: [ + "lapi.c", + "lapi.h", + "lauxlib.c", + "lauxlib.h", + "lbaselib.c", + "lcode.c", + "lcode.h", + "lcorolib.c", + "lctype.c", + "lctype.h", + "ldblib.c", + "ldebug.c", + "ldebug.h", + "ldo.c", + "ldo.h", + "ldump.c", + "lfunc.c", + "lfunc.h", + "lgc.c", + "lgc.h", + "linit.c", + "liolib.c", + "llex.c", + "llex.h", + "lmathlib.c", + "lmem.c", + "lmem.h", + "loadlib.c", + "lobject.c", + "lobject.h", + "lopcodes.c", + "lopcodes.h", + "loslib.c", + "lparser.c", + "lparser.h", + "lstate.c", + "lstate.h", + "lstring.c", + "lstring.h", + "lstrlib.c", + "ltable.c", + "ltable.h", + "ltablib.c", + "ltm.c", + "ltm.h", + "lua.c", + "lua.h", + "lundump.c", + "lundump.h", + "lutf8lib.c", + "lvm.c", + "lvm.h", + "lzio.c", + "lzio.h", + ] + } + + Export { + cpp.includePaths: project.ide_source_tree + "/src/libs/3rdparty/lua/src" + } +} 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..433df492959 --- /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) &&!defined(LUA_USE_WINDOWS) +#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..85665a50c93 --- /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