From dfab9bbcd4416a1663becde007d8b0ad1ef0c0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Mart=C3=ADnez?= Date: Sat, 1 Dec 2012 01:06:15 -0200 Subject: [PATCH] initial commit --- .gitignore | 2 + CMakeLists.txt | 13 + README.txt | 69 + doc/cmake.html | 6189 ++++++++++++++++++++++++ doc/lua/contents.html | 405 ++ doc/lua/logo.gif | Bin 0 -> 4232 bytes doc/lua/lua.1 | 163 + doc/lua/lua.css | 15 + doc/lua/lua.html | 172 + doc/lua/luac.1 | 136 + doc/lua/luac.html | 145 + doc/lua/manual.html | 6247 +++++++++++++++++++++++++ doc/lua/readme.html | 32 + doc/luairc/LICENSE | 7 + doc/luairc/README | 31 + doc/luairc/TODO | 20 + doc/luairc/index.html | 156 + doc/luairc/luadoc.css | 286 ++ doc/luairc/modules/callbacks.html | 858 ++++ doc/luairc/modules/irc.channel.html | 945 ++++ doc/luairc/modules/irc.constants.html | 117 + doc/luairc/modules/irc.ctcp.html | 117 + doc/luairc/modules/irc.dcc.html | 164 + doc/luairc/modules/irc.debug.html | 196 + doc/luairc/modules/irc.html | 683 +++ doc/luairc/modules/irc.message.html | 117 + doc/luairc/modules/irc.misc.html | 117 + doc/luasocket/LICENSE | 20 + doc/luasocket/NEW | 54 + doc/luasocket/README | 6 + doc/luasocket/dns.html | 132 + doc/luasocket/ftp.html | 289 ++ doc/luasocket/home.html | 256 + doc/luasocket/http.html | 325 ++ doc/luasocket/installation.html | 161 + doc/luasocket/introduction.html | 333 ++ doc/luasocket/ltn12.html | 430 ++ doc/luasocket/luasocket.png | Bin 0 -> 11732 bytes doc/luasocket/mime.html | 476 ++ doc/luasocket/reference.css | 54 + doc/luasocket/reference.html | 239 + doc/luasocket/smtp.html | 417 ++ doc/luasocket/socket.html | 398 ++ doc/luasocket/tcp.html | 532 +++ doc/luasocket/udp.html | 416 ++ doc/luasocket/url.html | 329 ++ etc/luasocket-samples/README | 50 + etc/luasocket-samples/cddb.lua | 46 + etc/luasocket-samples/daytimeclnt.lua | 23 + etc/luasocket-samples/echoclnt.lua | 24 + etc/luasocket-samples/echosrvr.lua | 29 + etc/luasocket-samples/listener.lua | 26 + etc/luasocket-samples/lpr.lua | 51 + etc/luasocket-samples/talker.lua | 21 + etc/luasocket-samples/tinyirc.lua | 90 + etc/luasocket/README | 89 + etc/luasocket/b64.lua | 20 + etc/luasocket/check-links.lua | 112 + etc/luasocket/check-memory.lua | 17 + etc/luasocket/dict.lua | 152 + etc/luasocket/dispatch.lua | 301 ++ etc/luasocket/eol.lua | 14 + etc/luasocket/forward.lua | 65 + etc/luasocket/get.lua | 140 + etc/luasocket/lp.lua | 324 ++ etc/luasocket/qp.lua | 24 + etc/luasocket/tftp.lua | 155 + etc/tests/luairc/luabot.lua | 109 + etc/tests/luairc/test.lua | 228 + etc/tests/luasocket/README | 12 + etc/tests/luasocket/testclnt.lua | 655 +++ etc/tests/luasocket/testsrvr.lua | 15 + etc/tests/luasocket/testsupport.lua | 37 + packmod.sh | 71 + src/CMakeLists.txt | 5 + src/dummy.c | 0 src/init.lua | 118 + src/lua/CMakeLists.txt | 16 + src/lua/lapi.c | 1077 +++++ src/lua/lapi.h | 16 + src/lua/lauxlib.c | 647 +++ src/lua/lauxlib.h | 172 + src/lua/lbaselib.c | 643 +++ src/lua/lcode.c | 825 ++++ src/lua/lcode.h | 77 + src/lua/ldblib.c | 397 ++ src/lua/ldebug.c | 620 +++ src/lua/ldebug.h | 33 + src/lua/ldo.c | 515 ++ src/lua/ldo.h | 57 + src/lua/ldump.c | 164 + src/lua/lfunc.c | 174 + src/lua/lfunc.h | 34 + src/lua/lgc.c | 707 +++ src/lua/lgc.h | 110 + src/lua/linit.c | 38 + src/lua/liolib.c | 532 +++ src/lua/llex.c | 460 ++ src/lua/llex.h | 81 + src/lua/llimits.h | 128 + src/lua/lmathlib.c | 263 ++ src/lua/lmem.c | 86 + src/lua/lmem.h | 49 + src/lua/loadlib.c | 667 +++ src/lua/lobject.c | 214 + src/lua/lobject.h | 381 ++ src/lua/lopcodes.c | 102 + src/lua/lopcodes.h | 268 ++ src/lua/loslib.c | 238 + src/lua/lparser.c | 1336 ++++++ src/lua/lparser.h | 83 + src/lua/lstate.c | 214 + src/lua/lstate.h | 168 + src/lua/lstring.c | 111 + src/lua/lstring.h | 31 + src/lua/lstrlib.c | 863 ++++ src/lua/ltable.c | 588 +++ src/lua/ltable.h | 40 + src/lua/ltablib.c | 278 ++ src/lua/ltm.c | 75 + src/lua/ltm.h | 54 + src/lua/lua.c | 377 ++ src/lua/lua.h | 384 ++ src/lua/luac.c | 196 + src/lua/luaconf.h | 736 +++ src/lua/lualib.h | 53 + src/lua/lundump.c | 223 + src/lua/lundump.h | 36 + src/lua/lvm.c | 762 +++ src/lua/lvm.h | 36 + src/lua/lzio.c | 82 + src/lua/lzio.h | 67 + src/lua/print.c | 224 + src/luairc/irc.lua | 994 ++++ src/luairc/irc/channel.lua | 475 ++ src/luairc/irc/constants.lua | 191 + src/luairc/irc/ctcp.lua | 115 + src/luairc/irc/dcc.lua | 196 + src/luairc/irc/debug.lua | 92 + src/luairc/irc/message.lua | 69 + src/luairc/irc/misc.lua | 303 ++ src/luasocket/CMakeLists.txt | 50 + src/luasocket/auxiliar.c | 149 + src/luasocket/auxiliar.h | 48 + src/luasocket/buffer.c | 263 ++ src/luasocket/buffer.h | 47 + src/luasocket/compat51.c | 97 + src/luasocket/compat51.h | 13 + src/luasocket/compat51.lua | 235 + src/luasocket/except.c | 99 + src/luasocket/except.h | 35 + src/luasocket/ftp.lua | 280 ++ src/luasocket/http.lua | 326 ++ src/luasocket/inet.c | 281 ++ src/luasocket/inet.h | 42 + src/luasocket/io.c | 32 + src/luasocket/io.h | 67 + src/luasocket/ltn12.lua | 291 ++ src/luasocket/luasocket.c | 118 + src/luasocket/luasocket.h | 32 + src/luasocket/makefile | 88 + src/luasocket/mime.c | 711 +++ src/luasocket/mime.h | 31 + src/luasocket/mime.lua | 86 + src/luasocket/mycompat.h | 59 + src/luasocket/options.c | 149 + src/luasocket/options.h | 39 + src/luasocket/select.c | 200 + src/luasocket/select.h | 17 + src/luasocket/smtp.lua | 245 + src/luasocket/socket.h | 76 + src/luasocket/socket.lua | 133 + src/luasocket/tcp.c | 339 ++ src/luasocket/tcp.h | 36 + src/luasocket/timeout.c | 207 + src/luasocket/timeout.h | 30 + src/luasocket/tmp/list | 115 + src/luasocket/tp.lua | 123 + src/luasocket/udp.c | 336 ++ src/luasocket/udp.h | 33 + src/luasocket/unix.c | 348 ++ src/luasocket/unix.h | 30 + src/luasocket/url.lua | 297 ++ src/luasocket/usocket.c | 370 ++ src/luasocket/usocket.h | 40 + src/luasocket/wsocket.c | 401 ++ src/luasocket/wsocket.h | 21 + 187 files changed, 51600 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 README.txt create mode 100644 doc/cmake.html create mode 100644 doc/lua/contents.html create mode 100644 doc/lua/logo.gif create mode 100644 doc/lua/lua.1 create mode 100644 doc/lua/lua.css create mode 100644 doc/lua/lua.html create mode 100644 doc/lua/luac.1 create mode 100644 doc/lua/luac.html create mode 100644 doc/lua/manual.html create mode 100644 doc/lua/readme.html create mode 100644 doc/luairc/LICENSE create mode 100644 doc/luairc/README create mode 100644 doc/luairc/TODO create mode 100644 doc/luairc/index.html create mode 100644 doc/luairc/luadoc.css create mode 100644 doc/luairc/modules/callbacks.html create mode 100644 doc/luairc/modules/irc.channel.html create mode 100644 doc/luairc/modules/irc.constants.html create mode 100644 doc/luairc/modules/irc.ctcp.html create mode 100644 doc/luairc/modules/irc.dcc.html create mode 100644 doc/luairc/modules/irc.debug.html create mode 100644 doc/luairc/modules/irc.html create mode 100644 doc/luairc/modules/irc.message.html create mode 100644 doc/luairc/modules/irc.misc.html create mode 100644 doc/luasocket/LICENSE create mode 100644 doc/luasocket/NEW create mode 100644 doc/luasocket/README create mode 100644 doc/luasocket/dns.html create mode 100644 doc/luasocket/ftp.html create mode 100644 doc/luasocket/home.html create mode 100644 doc/luasocket/http.html create mode 100644 doc/luasocket/installation.html create mode 100644 doc/luasocket/introduction.html create mode 100644 doc/luasocket/ltn12.html create mode 100644 doc/luasocket/luasocket.png create mode 100644 doc/luasocket/mime.html create mode 100644 doc/luasocket/reference.css create mode 100644 doc/luasocket/reference.html create mode 100644 doc/luasocket/smtp.html create mode 100644 doc/luasocket/socket.html create mode 100644 doc/luasocket/tcp.html create mode 100644 doc/luasocket/udp.html create mode 100644 doc/luasocket/url.html create mode 100644 etc/luasocket-samples/README create mode 100644 etc/luasocket-samples/cddb.lua create mode 100644 etc/luasocket-samples/daytimeclnt.lua create mode 100644 etc/luasocket-samples/echoclnt.lua create mode 100644 etc/luasocket-samples/echosrvr.lua create mode 100644 etc/luasocket-samples/listener.lua create mode 100644 etc/luasocket-samples/lpr.lua create mode 100644 etc/luasocket-samples/talker.lua create mode 100644 etc/luasocket-samples/tinyirc.lua create mode 100644 etc/luasocket/README create mode 100644 etc/luasocket/b64.lua create mode 100644 etc/luasocket/check-links.lua create mode 100644 etc/luasocket/check-memory.lua create mode 100644 etc/luasocket/dict.lua create mode 100644 etc/luasocket/dispatch.lua create mode 100644 etc/luasocket/eol.lua create mode 100644 etc/luasocket/forward.lua create mode 100644 etc/luasocket/get.lua create mode 100644 etc/luasocket/lp.lua create mode 100644 etc/luasocket/qp.lua create mode 100644 etc/luasocket/tftp.lua create mode 100755 etc/tests/luairc/luabot.lua create mode 100755 etc/tests/luairc/test.lua create mode 100644 etc/tests/luasocket/README create mode 100644 etc/tests/luasocket/testclnt.lua create mode 100644 etc/tests/luasocket/testsrvr.lua create mode 100644 etc/tests/luasocket/testsupport.lua create mode 100644 packmod.sh create mode 100644 src/CMakeLists.txt create mode 100644 src/dummy.c create mode 100644 src/init.lua create mode 100644 src/lua/CMakeLists.txt create mode 100644 src/lua/lapi.c create mode 100644 src/lua/lapi.h create mode 100644 src/lua/lauxlib.c create mode 100644 src/lua/lauxlib.h create mode 100644 src/lua/lbaselib.c create mode 100644 src/lua/lcode.c create mode 100644 src/lua/lcode.h create mode 100644 src/lua/ldblib.c create mode 100644 src/lua/ldebug.c create mode 100644 src/lua/ldebug.h create mode 100644 src/lua/ldo.c create mode 100644 src/lua/ldo.h create mode 100644 src/lua/ldump.c create mode 100644 src/lua/lfunc.c create mode 100644 src/lua/lfunc.h create mode 100644 src/lua/lgc.c create mode 100644 src/lua/lgc.h create mode 100644 src/lua/linit.c create mode 100644 src/lua/liolib.c create mode 100644 src/lua/llex.c create mode 100644 src/lua/llex.h create mode 100644 src/lua/llimits.h create mode 100644 src/lua/lmathlib.c create mode 100644 src/lua/lmem.c create mode 100644 src/lua/lmem.h create mode 100644 src/lua/loadlib.c create mode 100644 src/lua/lobject.c create mode 100644 src/lua/lobject.h create mode 100644 src/lua/lopcodes.c create mode 100644 src/lua/lopcodes.h create mode 100644 src/lua/loslib.c create mode 100644 src/lua/lparser.c create mode 100644 src/lua/lparser.h create mode 100644 src/lua/lstate.c create mode 100644 src/lua/lstate.h create mode 100644 src/lua/lstring.c create mode 100644 src/lua/lstring.h create mode 100644 src/lua/lstrlib.c create mode 100644 src/lua/ltable.c create mode 100644 src/lua/ltable.h create mode 100644 src/lua/ltablib.c create mode 100644 src/lua/ltm.c create mode 100644 src/lua/ltm.h create mode 100644 src/lua/lua.c create mode 100644 src/lua/lua.h create mode 100644 src/lua/luac.c create mode 100644 src/lua/luaconf.h create mode 100644 src/lua/lualib.h create mode 100644 src/lua/lundump.c create mode 100644 src/lua/lundump.h create mode 100644 src/lua/lvm.c create mode 100644 src/lua/lvm.h create mode 100644 src/lua/lzio.c create mode 100644 src/lua/lzio.h create mode 100644 src/lua/print.c create mode 100644 src/luairc/irc.lua create mode 100644 src/luairc/irc/channel.lua create mode 100644 src/luairc/irc/constants.lua create mode 100644 src/luairc/irc/ctcp.lua create mode 100644 src/luairc/irc/dcc.lua create mode 100644 src/luairc/irc/debug.lua create mode 100644 src/luairc/irc/message.lua create mode 100644 src/luairc/irc/misc.lua create mode 100644 src/luasocket/CMakeLists.txt create mode 100644 src/luasocket/auxiliar.c create mode 100644 src/luasocket/auxiliar.h create mode 100644 src/luasocket/buffer.c create mode 100644 src/luasocket/buffer.h create mode 100644 src/luasocket/compat51.c create mode 100644 src/luasocket/compat51.h create mode 100644 src/luasocket/compat51.lua create mode 100644 src/luasocket/except.c create mode 100644 src/luasocket/except.h create mode 100644 src/luasocket/ftp.lua create mode 100644 src/luasocket/http.lua create mode 100644 src/luasocket/inet.c create mode 100644 src/luasocket/inet.h create mode 100644 src/luasocket/io.c create mode 100644 src/luasocket/io.h create mode 100644 src/luasocket/ltn12.lua create mode 100644 src/luasocket/luasocket.c create mode 100644 src/luasocket/luasocket.h create mode 100644 src/luasocket/makefile create mode 100644 src/luasocket/mime.c create mode 100644 src/luasocket/mime.h create mode 100644 src/luasocket/mime.lua create mode 100644 src/luasocket/mycompat.h create mode 100644 src/luasocket/options.c create mode 100644 src/luasocket/options.h create mode 100644 src/luasocket/select.c create mode 100644 src/luasocket/select.h create mode 100644 src/luasocket/smtp.lua create mode 100644 src/luasocket/socket.h create mode 100644 src/luasocket/socket.lua create mode 100644 src/luasocket/tcp.c create mode 100644 src/luasocket/tcp.h create mode 100644 src/luasocket/timeout.c create mode 100644 src/luasocket/timeout.h create mode 100644 src/luasocket/tmp/list create mode 100644 src/luasocket/tp.lua create mode 100644 src/luasocket/udp.c create mode 100644 src/luasocket/udp.h create mode 100644 src/luasocket/unix.c create mode 100644 src/luasocket/unix.h create mode 100644 src/luasocket/url.lua create mode 100644 src/luasocket/usocket.c create mode 100644 src/luasocket/usocket.h create mode 100644 src/luasocket/wsocket.c create mode 100644 src/luasocket/wsocket.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..54ef9f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +Build +irc-* diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..f1fa558 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,13 @@ + +# :mode=cmake:noTabs=true:tabSize=4: + +cmake_minimum_required(VERSION 2.8) + +project(MINETEST_IRC C) + +set(MINETEST_IRC_VERSION 0.1.0) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/lua) + +add_subdirectory(src) diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..2cb58d9 --- /dev/null +++ b/README.txt @@ -0,0 +1,69 @@ + +IRC Mod for Minetest +(C) 2012 Diego Martínez + +INTRODUCTION +------------ +This mod is just a glue between luasocket, LuaIRC, and Minetest. It + provides a two-way communication between the in-game chat, and an + arbitrary IRC channel. + +Note: This mod is currently a work-in-progress, and is only tested under + Ubuntu 12.04 with Minetest 0.4.3 and 0.4.4-dev. Testers for other + platforms are welcome. + + +INSTALLING +---------- +Unpack the archive and put the `irc' directory in any of the directories + where Minetest looks for mods. For more information, see: + http://wiki.minetest.net/wiki/Installing_mods + + +SETTINGS +-------- +All settings are changed directly in the script. If any of these settings + are either nil or false, the default value is used. + + SERVER (string, default "irc.freenode.net") + This is the IRC server the mod connects to. + + CHANNEL (string, default "#minetest-irc-testing") + The IRC channel to join. + + DTIME (number, default 0.2) + This is the time in seconds between updates in the connection. + In order not to block the game, the mod must periodically "poll" + the connection to both send messages to, and receive messages + from the channel. A high value means slower connection to IRC, + but possibly better response from the game. A low value means + the mod "polls" the connection more often, but can make the + game hang. It allows fractional values. + + +LICENSE +------- +This license applies only to my code (in init.lua). + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2004 Sam Hocevar + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + +The files `http.lua', `ltn12.lua', `mime.lua', `smtp.lua', `socket.lua', + and `url.lua' are part of the luasocket project + (http://luasocket.luaforge.org/). See `LICENSE-luasocket.txt' for + licensing information. + +The `irc.lua' file and the entire content of the `irc' directory are part + of the LuaIRC project (http://luairc.luaforge.org/). See + `LICENSE-LuaIRC.txt' for licensing information. diff --git a/doc/cmake.html b/doc/cmake.html new file mode 100644 index 0000000..4dc7bab --- /dev/null +++ b/doc/cmake.html @@ -0,0 +1,6189 @@ + + +cmake - cmake +

Master Index CMake 2.8.7

+ +

Name

+
  cmake - Cross-Platform Makefile Generator.
+ +

Usage

+
  cmake [options] <path-to-source>
cmake [options] <path-to-existing-build>
+ +

Description

+

The "cmake" executable is the CMake command-line interface. It may be used to configure projects in scripts. Project configuration settings may be specified on the command line with the -D option. The -i option will cause cmake to interactively prompt for such settings.

+ +

CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.

+ +

Options

+ +
    +
  • + -C <initial-cache>: Pre-load a script to populate the cache.
    +

    When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a file from which to load cache entries before the first pass through the project's cmake listfiles. The loaded entries take priority over the project's default values. The given file should be a CMake script containing SET commands that use the CACHE option, not a cache-format file.

    + +
  • +
  • + -D <var>:<type>=<value>: Create a cmake cache entry.
    +

    When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a setting that takes priority over the project's default value. The option may be repeated for as many cache entries as desired.

    + +
  • +
  • + -U <globbing_expr>: Remove matching entries from CMake cache.
    +

    This option may be used to remove one or more variables from the CMakeCache.txt file, globbing expressions using * and ? are supported. The option may be repeated for as many cache entries as desired.

    +

    Use with care, you can make your CMakeCache.txt non-working.

    + +
  • +
  • + -G <generator-name>: Specify a makefile generator.
    +

    CMake may support multiple native build systems on certain platforms. A makefile generator is responsible for generating a particular build system. Possible generator names are specified in the Generators section.

    + +
  • +
  • + -Wno-dev: Suppress developer warnings.
    +

    Suppress warnings that are meant for the author of the CMakeLists.txt files.

    + +
  • +
  • + -Wdev: Enable developer warnings.
    +

    Enable warnings that are meant for the author of the CMakeLists.txt files.

    + +
  • +
  • + -E: CMake command mode.
    +

    For true platform independence, CMake provides a list of commands that can be used on all systems. Run with -E help for the usage information. Commands available are: chdir, compare_files, copy, copy_directory, copy_if_different, echo, echo_append, environment, make_directory, md5sum, remove, remove_directory, rename, tar, time, touch, touch_nocreate. In addition, some platform specific commands are available. On Windows: comspec, delete_regv, write_regv. On UNIX: create_symlink.

    + +
  • +
  • + -i: Run in wizard mode.
    +

    Wizard mode runs cmake interactively without a GUI. The user is prompted to answer questions about the project configuration. The answers are used to set cmake cache values.

    + +
  • +
  • + -L[A][H]: List non-advanced cached variables.
    +

    List cache variables will run CMake and list all the variables from the CMake cache that are not marked as INTERNAL or ADVANCED. This will effectively display current CMake settings, which can be then changed with -D option. Changing some of the variable may result in more variables being created. If A is specified, then it will display also advanced variables. If H is specified, it will also display help for each variable.

    + +
  • +
  • + --build <dir>: Build a CMake-generated project binary tree.
    +

    This abstracts a native build tool's command-line interface with the following options:

    +
      <dir>          = Project binary directory to be built.
    --target <tgt> = Build <tgt> instead of default targets.
    --config <cfg> = For multi-configuration tools, choose <cfg>.
    --clean-first = Build target 'clean' first, then build.
    (To clean only, use --target 'clean'.)
    --use-stderr = Don't merge stdout/stderr.
    -- = Pass remaining options to the native tool.
    +

    Run cmake --build with no options for quick help.

    + +
  • +
  • + -N: View mode only.
    +

    Only load the cache. Do not actually run configure and generate steps.

    + +
  • +
  • + -P <file>: Process script mode.
    +

    Process the given cmake file as a script written in the CMake language. No configure or generate step is performed and the cache is not modified. If variables are defined using -D, this must be done before the -P argument.

    + +
  • +
  • + --find-package: Run in pkg-config like mode.
    +

    Search a package using find_package() and print the resulting flags to stdout. This can be used to use cmake instead of pkg-config to find installed libraries in plain Makefile-based projects or in autoconf-based projects (via share/aclocal/cmake.m4).

    + +
  • +
  • + --graphviz=[file]: Generate graphviz of dependencies.
    +

    Generate a graphviz input file that will contain all the library and executable dependencies in the project.

    + +
  • +
  • + --system-information [file]: Dump information about this system.
    +

    Dump a wide range of information about the current system. If run from the top of a binary tree for a CMake project it will dump additional information such as the cache, log files etc.

    + +
  • +
  • + --debug-trycompile: Do not delete the try_compile build tree. Only useful on one try_compile at a time.
    +

    Do not delete the files and directories created for try_compile calls. This is useful in debugging failed try_compiles. It may however change the results of the try-compiles as old junk from a previous try-compile may cause a different test to either pass or fail incorrectly. This option is best used for one try-compile at a time, and only when debugging.

    + +
  • +
  • + --debug-output: Put cmake in a debug mode.
    +

    Print extra stuff during the cmake run like stack traces with message(send_error ) calls.

    + +
  • +
  • + --trace: Put cmake in trace mode.
    +

    Print a trace of all calls made and from where with message(send_error ) calls.

    + +
  • +
  • + --warn-uninitialized: Warn about uninitialized values.
    +

    Print a warning when an uninitialized variable is used.

    + +
  • +
  • + --warn-unused-vars: Warn about unused variables.
    +

    Find variables that are declared or set, but not used.

    + +
  • +
  • + --no-warn-unused-cli: Don't warn about command line options.
    +

    Don't find variables that are declared on the command line, but not used.

    + +
  • +
  • + --check-system-vars: Find problems with variable usage in system files.
    +

    Normally, unused and uninitialized variables are searched for only in CMAKE_SOURCE_DIR and CMAKE_BINARY_DIR. This flag tells CMake to warn about other files as well.

    + +
  • +
  • + --help-command cmd [file]: Print help for a single command and exit.
    +

    Full documentation specific to the given command is displayed. If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-command-list [file]: List available listfile commands and exit.
    +

    The list contains all commands for which help may be obtained by using the --help-command argument followed by a command name. If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-commands [file]: Print help for all commands and exit.
    +

    Full documentation specific for all current command is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-compatcommands [file]: Print help for compatibility commands.
    +

    Full documentation specific for all compatibility commands is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-module module [file]: Print help for a single module and exit.
    +

    Full documentation specific to the given module is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-module-list [file]: List available modules and exit.
    +

    The list contains all modules for which help may be obtained by using the --help-module argument followed by a module name. If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-modules [file]: Print help for all modules and exit.
    +

    Full documentation for all modules is displayed. If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-custom-modules [file]: Print help for all custom modules and exit.
    +

    Full documentation for all custom modules is displayed. If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-policy cmp [file]: Print help for a single policy and exit.
    +

    Full documentation specific to the given policy is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-policies [file]: Print help for all policies and exit.
    +

    Full documentation for all policies is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-property prop [file]: Print help for a single property and exit.
    +

    Full documentation specific to the given property is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-property-list [file]: List available properties and exit.
    +

    The list contains all properties for which help may be obtained by using the --help-property argument followed by a property name. If a file is specified, the help is written into it.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-properties [file]: Print help for all properties and exit.
    +

    Full documentation for all properties is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-variable var [file]: Print help for a single variable and exit.
    +

    Full documentation specific to the given variable is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-variable-list [file]: List documented variables and exit.
    +

    The list contains all variables for which help may be obtained by using the --help-variable argument followed by a variable name. If a file is specified, the help is written into it.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --help-variables [file]: Print help for all variables and exit.
    +

    Full documentation for all variables is displayed.If a file is specified, the documentation is written into and the output format is determined depending on the filename suffix. Supported are man page, HTML, DocBook and plain text.

    + +
  • +
  • + --copyright [file]: Print the CMake copyright and exit.
    +

    If a file is specified, the copyright is written into it.

    + +
  • +
  • + --help,-help,-usage,-h,-H,/?: Print usage information and exit.
    +

    Usage describes the basic command line interface and its options.

    + +
  • +
  • + --help-full [file]: Print full help and exit.
    +

    Full help displays most of the documentation provided by the UNIX man page. It is provided for use on non-UNIX platforms, but is also convenient if the man page is not installed. If a file is specified, the help is written into it.

    + +
  • +
  • + --help-html [file]: Print full help in HTML format.
    +

    This option is used by CMake authors to help produce web pages. If a file is specified, the help is written into it.

    + +
  • +
  • + --help-man [file]: Print full help as a UNIX man page and exit.
    +

    This option is used by the cmake build to generate the UNIX man page. If a file is specified, the help is written into it.

    + +
  • +
  • + --version,-version,/V [file]: Show program name/version banner and exit.
    +

    If a file is specified, the version is written into it.

    + +
  • +
+

Generators

+ +

The following generators are available on this platform:

+ +
    +
  • + Unix Makefiles: Generates standard UNIX makefiles.
    +

    A hierarchy of UNIX makefiles is generated into the build tree. Any standard UNIX-style make program can build the project through the default make target. A "make install" target is also provided.

    + +
  • +
  • + CodeBlocks - Unix Makefiles: Generates CodeBlocks project files.
    +

    Project files for CodeBlocks will be created in the top directory and in every subdirectory which features a CMakeLists.txt file containing a PROJECT() call. Additionally a hierarchy of makefiles is generated into the build tree. The appropriate make program can build the project through the default make target. A "make install" target is also provided.

    + +
  • +
  • + Eclipse CDT4 - Unix Makefiles: Generates Eclipse CDT 4.0 project files.
    +

    Project files for Eclipse will be created in the top directory. In out of source builds, a linked resource to the top level source directory will be created.Additionally a hierarchy of makefiles is generated into the build tree. The appropriate make program can build the project through the default make target. A "make install" target is also provided.

    + +
  • +
  • + KDevelop3: Generates KDevelop 3 project files.
    +

    Project files for KDevelop 3 will be created in the top directory and in every subdirectory which features a CMakeLists.txt file containing a PROJECT() call. If you change the settings using KDevelop cmake will try its best to keep your changes when regenerating the project files. Additionally a hierarchy of UNIX makefiles is generated into the build tree. Any standard UNIX-style make program can build the project through the default make target. A "make install" target is also provided.

    + +
  • +
  • + KDevelop3 - Unix Makefiles: Generates KDevelop 3 project files.
    +

    Project files for KDevelop 3 will be created in the top directory and in every subdirectory which features a CMakeLists.txt file containing a PROJECT() call. If you change the settings using KDevelop cmake will try its best to keep your changes when regenerating the project files. Additionally a hierarchy of UNIX makefiles is generated into the build tree. Any standard UNIX-style make program can build the project through the default make target. A "make install" target is also provided.

    + +
  • +
+

Commands

+ +
    +
  • + add_custom_command: Add a custom build rule to the generated build system.
    +

    There are two main signatures for add_custom_command The first signature is for adding a custom command to produce an output.

    +
      add_custom_command(OUTPUT output1 [output2 ...]
    COMMAND command1 [ARGS] [args1...]
    [COMMAND command2 [ARGS] [args2...] ...]
    [MAIN_DEPENDENCY depend]
    [DEPENDS [depends...]]
    [IMPLICIT_DEPENDS <lang1> depend1 ...]
    [WORKING_DIRECTORY dir]
    [COMMENT comment] [VERBATIM] [APPEND])
    +

    This defines a command to generate specified OUTPUT file(s). A target created in the same directory (CMakeLists.txt file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time. Do not list the output in more than one independent target that may build in parallel or the two instances of the rule may conflict (instead use add_custom_target to drive the command and make the other targets depend on that one). If an output name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. Note that MAIN_DEPENDENCY is completely optional and is used as a suggestion to visual studio about where to hang the custom command. In makefile terms this creates a new target in the following form:

    +
      OUTPUT: MAIN_DEPENDENCY DEPENDS
    COMMAND
    +

    If more than one command is specified they will be executed in order. The optional ARGS argument is for backward compatibility and will be ignored.

    +

    The second signature adds a custom command to a target such as a library or executable. This is useful for performing an operation before or after building the target. The command becomes part of the target and will only execute when the target itself is built. If the target is already built, the command will not execute.

    +
      add_custom_command(TARGET target
    PRE_BUILD | PRE_LINK | POST_BUILD
    COMMAND command1 [ARGS] [args1...]
    [COMMAND command2 [ARGS] [args2...] ...]
    [WORKING_DIRECTORY dir]
    [COMMENT comment] [VERBATIM])
    +

    This defines a new command that will be associated with building the specified target. When the command will happen is determined by which of the following is specified:

    +
      PRE_BUILD - run before all other dependencies
    PRE_LINK - run after other dependencies
    POST_BUILD - run after the target has been built
    +

    Note that the PRE_BUILD option is only supported on Visual Studio 7 or later. For all other generators PRE_BUILD will be treated as PRE_LINK.

    +

    If WORKING_DIRECTORY is specified the command will be executed in the directory given. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. If COMMENT is set, the value will be displayed as a message before the commands are executed at build time. If APPEND is specified the COMMAND and DEPENDS option values are appended to the custom command for the first output specified. There must have already been a previous call to this command with the same output. The COMMENT, WORKING_DIRECTORY, and MAIN_DEPENDENCY options are currently ignored when APPEND is given, but may be used in the future.

    +

    If VERBATIM is given then all arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_command even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.

    +

    If the output of the custom command is not actually created as a file on disk it should be marked as SYMBOLIC with SET_SOURCE_FILES_PROPERTIES.

    +

    The IMPLICIT_DEPENDS option requests scanning of implicit dependencies of an input file. The language given specifies the programming language whose corresponding dependency scanner should be used. Currently only C and CXX language scanners are supported. Dependencies discovered from the scanning are added to those of the custom command at build time. Note that the IMPLICIT_DEPENDS option is currently supported only for Makefile generators and will be ignored by other generators.

    +

    If COMMAND specifies an executable target (created by ADD_EXECUTABLE) it will automatically be replaced by the location of the executable created at build time. Additionally a target-level dependency will be added so that the executable target will be built before any target using this custom command. However this does NOT add a file-level dependency that would cause the custom command to re-run whenever the executable is recompiled.

    +

    Arguments to COMMAND may use "generator expressions" with the syntax "$<...>". Generator expressions are evaluted during build system generation to produce information specific to each build configuration. Valid expressions are:

    +
      $<CONFIGURATION>          = configuration name
    $<TARGET_FILE:tgt> = main file (.exe, .so.1.2, .a)
    $<TARGET_LINKER_FILE:tgt> = file used to link (.a, .lib, .so)
    $<TARGET_SONAME_FILE:tgt> = file with soname (.so.3)
    +

    where "tgt" is the name of a target. Target file expressions produce a full path, but _DIR and _NAME versions can produce the directory and file name components:

    +
      $<TARGET_FILE_DIR:tgt>/$<TARGET_FILE_NAME:tgt>
    $<TARGET_LINKER_FILE_DIR:tgt>/$<TARGET_LINKER_FILE_NAME:tgt>
    $<TARGET_SONAME_FILE_DIR:tgt>/$<TARGET_SONAME_FILE_NAME:tgt>
    +

    References to target names in generator expressions imply target-level dependencies, but NOT file-level dependencies. List target names with the DEPENDS option to add file dependencies.

    +

    The DEPENDS option specifies files on which the command depends. If any dependency is an OUTPUT of another custom command in the same directory (CMakeLists.txt file) CMake automatically brings the other custom command into the target in which this command is built. If DEPENDS is not specified the command will run whenever the OUTPUT is missing; if the command does not actually create the OUTPUT then the rule will always run. If DEPENDS specifies any target (created by an ADD_* command) a target-level dependency is created to make sure the target is built before any target using this custom command. Additionally, if the target is an executable or library a file-level dependency is created to cause the custom command to re-run whenever the target is recompiled.

    + +
  • +
  • + add_custom_target: Add a target with no output so it will always be built.
    +
      add_custom_target(Name [ALL] [command1 [args1...]]
    [COMMAND command2 [args2...] ...]
    [DEPENDS depend depend depend ... ]
    [WORKING_DIRECTORY dir]
    [COMMENT comment] [VERBATIM]
    [SOURCES src1 [src2...]])
    +

    Adds a target with the given name that executes the given commands. The target has no output file and is ALWAYS CONSIDERED OUT OF DATE even if the commands try to create a file with the name of the target. Use ADD_CUSTOM_COMMAND to generate a file with dependencies. By default nothing depends on the custom target. Use ADD_DEPENDENCIES to add dependencies to or from other targets. If the ALL option is specified it indicates that this target should be added to the default build target so that it will be run every time (the command cannot be called ALL). The command and arguments are optional and if not specified an empty target will be created. If WORKING_DIRECTORY is set, then the command will be run in that directory. If it is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. If COMMENT is set, the value will be displayed as a message before the commands are executed at build time. Dependencies listed with the DEPENDS argument may reference files and outputs of custom commands created with add_custom_command() in the same directory (CMakeLists.txt file).

    +

    If VERBATIM is given then all arguments to the commands will be escaped properly for the build tool so that the invoked command receives each argument unchanged. Note that one level of escapes is still used by the CMake language processor before add_custom_target even sees the arguments. Use of VERBATIM is recommended as it enables correct behavior. When VERBATIM is not given the behavior is platform specific because there is no protection of tool-specific special characters.

    +

    The SOURCES option specifies additional source files to be included in the custom target. Specified source files will be added to IDE project files for convenience in editing even if they have not build rules.

    + +
  • +
  • + add_definitions: Adds -D define flags to the compilation of source files.
    +
      add_definitions(-DFOO -DBAR ...)
    +

    Adds flags to the compiler command line for sources in the current directory and below. This command can be used to add any flags, but it was originally intended to add preprocessor definitions. Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the COMPILE_DEFINITIONS property for the current directory. Definitions with non-trival values may be left in the set of flags instead of being converted for reasons of backwards compatibility. See documentation of the directory, target, and source file COMPILE_DEFINITIONS properties for details on adding preprocessor definitions to specific scopes and configurations.

    + +
  • +
  • + add_dependencies: Add a dependency between top-level targets.
    +
      add_dependencies(target-name depend-target1
    depend-target2 ...)
    +

    Make a top-level target depend on other top-level targets. A top-level target is one created by ADD_EXECUTABLE, ADD_LIBRARY, or ADD_CUSTOM_TARGET. Adding dependencies with this command can be used to make sure one target is built before another target. Dependencies added to an IMPORTED target are followed transitively in its place since the target itself does not build. See the DEPENDS option of ADD_CUSTOM_TARGET and ADD_CUSTOM_COMMAND for adding file-level dependencies in custom rules. See the OBJECT_DEPENDS option in SET_SOURCE_FILES_PROPERTIES to add file-level dependencies to object files.

    + +
  • +
  • + add_executable: Add an executable to the project using the specified source files.
    +
      add_executable(<name> [WIN32] [MACOSX_BUNDLE]
    [EXCLUDE_FROM_ALL]
    source1 source2 ... sourceN)
    +

    Adds an executable target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project. The actual file name of the executable built is constructed based on conventions of the native platform (such as <name>.exe or just <name>).

    +

    By default the executable file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the RUNTIME_OUTPUT_DIRECTORY target property to change this location. See documentation of the OUTPUT_NAME target property to change the <name> part of the final file name.

    +

    If WIN32 is given the property WIN32_EXECUTABLE will be set on the target created. See documentation of that target property for details.

    +

    If MACOSX_BUNDLE is given the corresponding property will be set on the created target. See documentation of the MACOSX_BUNDLE target property for details.

    +

    If EXCLUDE_FROM_ALL is given the corresponding property will be set on the created target. See documentation of the EXCLUDE_FROM_ALL target property for details.

    +

    The add_executable command can also create IMPORTED executable targets using this signature:

    +
      add_executable(<name> IMPORTED)
    +

    An IMPORTED executable target references an executable file located outside the project. No rules are generated to build it. The target name has scope in the directory in which it is created and below. It may be referenced like any target built within the project. IMPORTED executables are useful for convenient reference from commands like add_custom_command. Details about the imported executable are specified by setting properties whose names begin in "IMPORTED_". The most important such property is IMPORTED_LOCATION (and its per-configuration version IMPORTED_LOCATION_<CONFIG>) which specifies the location of the main executable file on disk. See documentation of the IMPORTED_* properties for more information.

    + +
  • +
  • + add_library: Add a library to the project using the specified source files.
    +
      add_library(<name> [STATIC | SHARED | MODULE]
    [EXCLUDE_FROM_ALL]
    source1 source2 ... sourceN)
    +

    Adds a library target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project. The actual file name of the library built is constructed based on conventions of the native platform (such as lib<name>.a or <name>.lib).

    +

    STATIC, SHARED, or MODULE may be given to specify the type of library to be created. STATIC libraries are archives of object files for use when linking other targets. SHARED libraries are linked dynamically and loaded at runtime. MODULE libraries are plugins that are not linked into other targets but may be loaded dynamically at runtime using dlopen-like functionality. If no type is given explicitly the type is STATIC or SHARED based on whether the current value of the variable BUILD_SHARED_LIBS is true.

    +

    By default the library file will be created in the build tree directory corresponding to the source tree directory in which the command was invoked. See documentation of the ARCHIVE_OUTPUT_DIRECTORY, LIBRARY_OUTPUT_DIRECTORY, and RUNTIME_OUTPUT_DIRECTORY target properties to change this location. See documentation of the OUTPUT_NAME target property to change the <name> part of the final file name.

    +

    If EXCLUDE_FROM_ALL is given the corresponding property will be set on the created target. See documentation of the EXCLUDE_FROM_ALL target property for details.

    +

    The add_library command can also create IMPORTED library targets using this signature:

    +
      add_library(<name> <SHARED|STATIC|MODULE|UNKNOWN> IMPORTED)
    +

    An IMPORTED library target references a library file located outside the project. No rules are generated to build it. The target name has scope in the directory in which it is created and below. It may be referenced like any target built within the project. IMPORTED libraries are useful for convenient reference from commands like target_link_libraries. Details about the imported library are specified by setting properties whose names begin in "IMPORTED_". The most important such property is IMPORTED_LOCATION (and its per-configuration version IMPORTED_LOCATION_<CONFIG>) which specifies the location of the main library file on disk. See documentation of the IMPORTED_* properties for more information.

    + +
  • +
  • + add_subdirectory: Add a subdirectory to the build.
    +
      add_subdirectory(source_dir [binary_dir] 
    [EXCLUDE_FROM_ALL])
    +

    Add a subdirectory to the build. The source_dir specifies the directory in which the source CmakeLists.txt and code files are located. If it is a relative path it will be evaluated with respect to the current directory (the typical usage), but it may also be an absolute path. The binary_dir specifies the directory in which to place the output files. If it is a relative path it will be evaluated with respect to the current output directory, but it may also be an absolute path. If binary_dir is not specified, the value of source_dir, before expanding any relative path, will be used (the typical usage). The CMakeLists.txt file in the specified source directory will be processed immediately by CMake before processing in the current input file continues beyond this command.

    +

    If the EXCLUDE_FROM_ALL argument is provided then targets in the subdirectory will not be included in the ALL target of the parent directory by default, and will be excluded from IDE project files. Users must explicitly build targets in the subdirectory. This is meant for use when the subdirectory contains a separate part of the project that is useful but not necessary, such as a set of examples. Typically the subdirectory should contain its own project() command invocation so that a full build system will be generated in the subdirectory (such as a VS IDE solution file). Note that inter-target dependencies supercede this exclusion. If a target built by the parent project depends on a target in the subdirectory, the dependee target will be included in the parent project build system to satisfy the dependency.

    + +
  • +
  • + add_test: Add a test to the project with the specified arguments.
    +
      add_test(testname Exename arg1 arg2 ... )
    +

    If the ENABLE_TESTING command has been run, this command adds a test target to the current directory. If ENABLE_TESTING has not been run, this command does nothing. The tests are run by the testing subsystem by executing Exename with the specified arguments. Exename can be either an executable built by this project or an arbitrary executable on the system (like tclsh). The test will be run with the current working directory set to the CMakeList.txt files corresponding directory in the binary tree.

    +


    +
      add_test(NAME <name> [CONFIGURATIONS [Debug|Release|...]]
    [WORKING_DIRECTORY dir]
    COMMAND <command> [arg1 [arg2 ...]])
    +

    If COMMAND specifies an executable target (created by add_executable) it will automatically be replaced by the location of the executable created at build time. If a CONFIGURATIONS option is given then the test will be executed only when testing under one of the named configurations. If a WORKING_DIRECTORY option is given then the test will be executed in the given directory.

    +

    Arguments after COMMAND may use "generator expressions" with the syntax "$<...>". Generator expressions are evaluted during build system generation to produce information specific to each build configuration. Valid expressions are:

    +
      $<CONFIGURATION>          = configuration name
    $<TARGET_FILE:tgt> = main file (.exe, .so.1.2, .a)
    $<TARGET_LINKER_FILE:tgt> = file used to link (.a, .lib, .so)
    $<TARGET_SONAME_FILE:tgt> = file with soname (.so.3)
    +

    where "tgt" is the name of a target. Target file expressions produce a full path, but _DIR and _NAME versions can produce the directory and file name components:

    +
      $<TARGET_FILE_DIR:tgt>/$<TARGET_FILE_NAME:tgt>
    $<TARGET_LINKER_FILE_DIR:tgt>/$<TARGET_LINKER_FILE_NAME:tgt>
    $<TARGET_SONAME_FILE_DIR:tgt>/$<TARGET_SONAME_FILE_NAME:tgt>
    +

    Example usage:

    +
      add_test(NAME mytest
    COMMAND testDriver --config $<CONFIGURATION>
    --exe $<TARGET_FILE:myexe>)
    +

    This creates a test "mytest" whose command runs a testDriver tool passing the configuration name and the full path to the executable file produced by target "myexe".

    + +
  • +
  • + aux_source_directory: Find all source files in a directory.
    +
      aux_source_directory(<dir> <variable>)
    +

    Collects the names of all the source files in the specified directory and stores the list in the <variable> provided. This command is intended to be used by projects that use explicit template instantiation. Template instantiation files can be stored in a "Templates" subdirectory and collected automatically using this command to avoid manually listing all instantiations.

    +

    It is tempting to use this command to avoid writing the list of source files for a library or executable target. While this seems to work, there is no way for CMake to generate a build system that knows when a new source file has been added. Normally the generated build system knows when it needs to rerun CMake because the CMakeLists.txt file is modified to add a new source. When the source is just added to the directory without modifying this file, one would have to manually rerun CMake to generate a build system incorporating the new file.

    + +
  • +
  • + break: Break from an enclosing foreach or while loop.
    +
      break()
    +

    Breaks from an enclosing foreach loop or while loop

    + +
  • +
  • + build_command: Get the command line to build this project.
    +
      build_command(<variable>
    [CONFIGURATION <config>]
    [PROJECT_NAME <projname>]
    [TARGET <target>])
    +

    Sets the given <variable> to a string containing the command line for building one configuration of a target in a project using the build tool appropriate for the current CMAKE_GENERATOR.

    +

    If CONFIGURATION is omitted, CMake chooses a reasonable default value for multi-configuration generators. CONFIGURATION is ignored for single-configuration generators.

    +

    If PROJECT_NAME is omitted, the resulting command line will build the top level PROJECT in the current build tree.

    +

    If TARGET is omitted, the resulting command line will build everything, effectively using build target 'all' or 'ALL_BUILD'.

    +
      build_command(<cachevariable> <makecommand>)
    +

    This second signature is deprecated, but still available for backwards compatibility. Use the first signature instead.

    +

    Sets the given <cachevariable> to a string containing the command to build this project from the root of the build tree using the build tool given by <makecommand>. <makecommand> should be the full path to msdev, devenv, nmake, make or one of the end user build tools.

    + +
  • +
  • + cmake_minimum_required: Set the minimum required version of cmake for a project.
    +
      cmake_minimum_required(VERSION major[.minor[.patch[.tweak]]]
    [FATAL_ERROR])
    +

    If the current version of CMake is lower than that required it will stop processing the project and report an error. When a version higher than 2.4 is specified the command implicitly invokes

    +
      cmake_policy(VERSION major[.minor[.patch[.tweak]]])
    +

    which sets the cmake policy version level to the version specified. When version 2.4 or lower is given the command implicitly invokes

    +
      cmake_policy(VERSION 2.4)
    +

    which enables compatibility features for CMake 2.4 and lower.

    +

    The FATAL_ERROR option is accepted but ignored by CMake 2.6 and higher. It should be specified so CMake versions 2.4 and lower fail with an error instead of just a warning.

    + +
  • +
  • + cmake_policy: Manage CMake Policy settings.
    +

    As CMake evolves it is sometimes necessary to change existing behavior in order to fix bugs or improve implementations of existing features. The CMake Policy mechanism is designed to help keep existing projects building as new versions of CMake introduce changes in behavior. Each new policy (behavioral change) is given an identifier of the form "CMP<NNNN>" where "<NNNN>" is an integer index. Documentation associated with each policy describes the OLD and NEW behavior and the reason the policy was introduced. Projects may set each policy to select the desired behavior. When CMake needs to know which behavior to use it checks for a setting specified by the project. If no setting is available the OLD behavior is assumed and a warning is produced requesting that the policy be set.

    +

    The cmake_policy command is used to set policies to OLD or NEW behavior. While setting policies individually is supported, we encourage projects to set policies based on CMake versions.

    +
      cmake_policy(VERSION major.minor[.patch[.tweak]])
    +

    Specify that the current CMake list file is written for the given version of CMake. All policies introduced in the specified version or earlier will be set to use NEW behavior. All policies introduced after the specified version will be unset (unless variable CMAKE_POLICY_DEFAULT_CMP<NNNN> sets a default). This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies. The policy version specified must be at least 2.4 or the command will report an error. In order to get compatibility features supporting versions earlier than 2.4 see documentation of policy CMP0001.

    +
      cmake_policy(SET CMP<NNNN> NEW)
    cmake_policy(SET CMP<NNNN> OLD)
    +

    Tell CMake to use the OLD or NEW behavior for a given policy. Projects depending on the old behavior of a given policy may silence a policy warning by setting the policy state to OLD. Alternatively one may fix the project to work with the new behavior and set the policy state to NEW.

    +
      cmake_policy(GET CMP<NNNN> <variable>)
    +

    Check whether a given policy is set to OLD or NEW behavior. The output variable value will be "OLD" or "NEW" if the policy is set, and empty otherwise.

    +

    CMake keeps policy settings on a stack, so changes made by the cmake_policy command affect only the top of the stack. A new entry on the policy stack is managed automatically for each subdirectory to protect its parents and siblings. CMake also manages a new entry for scripts loaded by include() and find_package() commands except when invoked with the NO_POLICY_SCOPE option (see also policy CMP0011). The cmake_policy command provides an interface to manage custom entries on the policy stack:

    +
      cmake_policy(PUSH)
    cmake_policy(POP)
    +

    Each PUSH must have a matching POP to erase any changes. This is useful to make temporary changes to policy settings.

    +

    Functions and macros record policy settings when they are created and use the pre-record policies when they are invoked. If the function or macro implementation sets policies, the changes automatically propagate up through callers until they reach the closest nested policy stack entry.

    + +
  • +
  • + configure_file: Copy a file to another location and modify its contents.
    +
      configure_file(<input> <output>
    [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
    [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
    +

    Copies a file <input> to file <output> and substitutes variable values referenced in the file content. If <input> is a relative path it is evaluated with respect to the current source directory. The <input> must be a file, not a directory. If <output> is a relative path it is evaluated with respect to the current binary directory. If <output> names an existing directory the input file is placed in that directory with its original name.

    +

    This command replaces any variables in the input file referenced as ${VAR} or @VAR@ with their values as determined by CMake. If a variable is not defined, it will be replaced with nothing. If COPYONLY is specified, then no variable expansion will take place. If ESCAPE_QUOTES is specified then any substituted quotes will be C-style escaped. The file will be configured with the current values of CMake variables. If @ONLY is specified, only variables of the form @VAR@ will be replaces and ${VAR} will be ignored. This is useful for configuring scripts that use ${VAR}. Any occurrences of #cmakedefine VAR will be replaced with either #define VAR or /* #undef VAR */ depending on the setting of VAR in CMake. Any occurrences of #cmakedefine01 VAR will be replaced with either #define VAR 1 or #define VAR 0 depending on whether VAR evaluates to TRUE or FALSE in CMake.

    +

    With NEWLINE_STYLE the line ending could be adjusted:

    +
        'UNIX' or 'LF' for \n, 'DOS', 'WIN32' or 'CRLF' for \r\n.
    +

    COPYONLY must not be used with NEWLINE_STYLE.

    + +
  • +
  • + create_test_sourcelist: Create a test driver and source list for building test programs.
    +
      create_test_sourcelist(sourceListName driverName
    test1 test2 test3
    EXTRA_INCLUDE include.h
    FUNCTION function)
    +

    A test driver is a program that links together many small tests into a single executable. This is useful when building static executables with large libraries to shrink the total required size. The list of source files needed to build the test driver will be in sourceListName. DriverName is the name of the test driver program. The rest of the arguments consist of a list of test source files, can be semicolon separated. Each test source file should have a function in it that is the same name as the file with no extension (foo.cxx should have int foo(int, char*[]);) DriverName will be able to call each of the tests by name on the command line. If EXTRA_INCLUDE is specified, then the next argument is included into the generated file. If FUNCTION is specified, then the next argument is taken as a function name that is passed a pointer to ac and av. This can be used to add extra command line processing to each test. The cmake variable CMAKE_TESTDRIVER_BEFORE_TESTMAIN can be set to have code that will be placed directly before calling the test main function. CMAKE_TESTDRIVER_AFTER_TESTMAIN can be set to have code that will be placed directly after the call to the test main function.

    + +
  • +
  • + define_property: Define and document custom properties.
    +
      define_property(<GLOBAL | DIRECTORY | TARGET | SOURCE |
    TEST | VARIABLE | CACHED_VARIABLE>
    PROPERTY <name> [INHERITED]
    BRIEF_DOCS <brief-doc> [docs...]
    FULL_DOCS <full-doc> [docs...])
    +

    Define one property in a scope for use with the set_property and get_property commands. This is primarily useful to associate documentation with property names that may be retrieved with the get_property command. The first argument determines the kind of scope in which the property should be used. It must be one of the following:

    +
      GLOBAL    = associated with the global namespace
    DIRECTORY = associated with one directory
    TARGET = associated with one target
    SOURCE = associated with one source file
    TEST = associated with a test named with add_test
    VARIABLE = documents a CMake language variable
    CACHED_VARIABLE = documents a CMake cache variable
    +

    Note that unlike set_property and get_property no actual scope needs to be given; only the kind of scope is important.

    +

    The required PROPERTY option is immediately followed by the name of the property being defined.

    +

    If the INHERITED option then the get_property command will chain up to the next higher scope when the requested property is not set in the scope given to the command. DIRECTORY scope chains to GLOBAL. TARGET, SOURCE, and TEST chain to DIRECTORY.

    +

    The BRIEF_DOCS and FULL_DOCS options are followed by strings to be associated with the property as its brief and full documentation. Corresponding options to the get_property command will retrieve the documentation.

    + +
  • +
  • + else: Starts the else portion of an if block.
    +
      else(expression)
    +

    See the if command.

    + +
  • +
  • + elseif: Starts the elseif portion of an if block.
    +
      elseif(expression)
    +

    See the if command.

    + +
  • +
  • + enable_language: Enable a language (CXX/C/Fortran/etc)
    +
      enable_language(languageName [OPTIONAL] )
    +

    This command enables support for the named language in CMake. This is the same as the project command but does not create any of the extra variables that are created by the project command. Example languages are CXX, C, Fortran. If OPTIONAL is used, use the CMAKE_<languageName>_COMPILER_WORKS variable to check whether the language has been enabled successfully.

    + +
  • +
  • + enable_testing: Enable testing for current directory and below.
    +
      enable_testing()
    +

    Enables testing for this directory and below. See also the add_test command. Note that ctest expects to find a test file in the build directory root. Therefore, this command should be in the source directory root.

    + +
  • +
  • + endforeach: Ends a list of commands in a FOREACH block.
    +
      endforeach(expression)
    +

    See the FOREACH command.

    + +
  • +
  • + endfunction: Ends a list of commands in a function block.
    +
      endfunction(expression)
    +

    See the function command.

    + +
  • +
  • + endif: Ends a list of commands in an if block.
    +
      endif(expression)
    +

    See the if command.

    + +
  • +
  • + endmacro: Ends a list of commands in a macro block.
    +
      endmacro(expression)
    +

    See the macro command.

    + +
  • +
  • + endwhile: Ends a list of commands in a while block.
    +
      endwhile(expression)
    +

    See the while command.

    + +
  • +
  • + execute_process: Execute one or more child processes.
    +
      execute_process(COMMAND <cmd1> [args1...]]
    [COMMAND <cmd2> [args2...] [...]]
    [WORKING_DIRECTORY <directory>]
    [TIMEOUT <seconds>]
    [RESULT_VARIABLE <variable>]
    [OUTPUT_VARIABLE <variable>]
    [ERROR_VARIABLE <variable>]
    [INPUT_FILE <file>]
    [OUTPUT_FILE <file>]
    [ERROR_FILE <file>]
    [OUTPUT_QUIET]
    [ERROR_QUIET]
    [OUTPUT_STRIP_TRAILING_WHITESPACE]
    [ERROR_STRIP_TRAILING_WHITESPACE])
    +

    Runs the given sequence of one or more commands with the standard output of each process piped to the standard input of the next. A single standard error pipe is used for all processes. If WORKING_DIRECTORY is given the named directory will be set as the current working directory of the child processes. If TIMEOUT is given the child processes will be terminated if they do not finish in the specified number of seconds (fractions are allowed). If RESULT_VARIABLE is given the variable will be set to contain the result of running the processes. This will be an integer return code from the last child or a string describing an error condition. If OUTPUT_VARIABLE or ERROR_VARIABLE are given the variable named will be set with the contents of the standard output and standard error pipes respectively. If the same variable is named for both pipes their output will be merged in the order produced. If INPUT_FILE, OUTPUT_FILE, or ERROR_FILE is given the file named will be attached to the standard input of the first process, standard output of the last process, or standard error of all processes respectively. If OUTPUT_QUIET or ERROR_QUIET is given then the standard output or standard error results will be quietly ignored. If more than one OUTPUT_* or ERROR_* option is given for the same pipe the precedence is not specified. If no OUTPUT_* or ERROR_* options are given the output will be shared with the corresponding pipes of the CMake process itself.

    +

    The execute_process command is a newer more powerful version of exec_program, but the old command has been kept for compatibility.

    + +
  • +
  • + export: Export targets from the build tree for use by outside projects.
    +
      export(TARGETS [target1 [target2 [...]]] [NAMESPACE <namespace>]
    [APPEND] FILE <filename>)
    +

    Create a file <filename> that may be included by outside projects to import targets from the current project's build tree. This is useful during cross-compiling to build utility executables that can run on the host platform in one project and then import them into another project being compiled for the target platform. If the NAMESPACE option is given the <namespace> string will be prepended to all target names written to the file. If the APPEND option is given the generated code will be appended to the file instead of overwriting it. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.

    +

    The file created by this command is specific to the build tree and should never be installed. See the install(EXPORT) command to export targets from an installation tree.

    +

    Do not set properties that affect the location of a target after passing it to this command. These include properties whose names match "(RUNTIME|LIBRARY|ARCHIVE)_OUTPUT_(NAME|DIRECTORY)(_<CONFIG>)?" or "(IMPLIB_)?(PREFIX|SUFFIX)". Failure to follow this rule is not diagnosed and leaves the location of the target undefined.

    +
      export(PACKAGE <name>)
    +

    Store the current build directory in the CMake user package registry for package <name>. The find_package command may consider the directory while searching for package <name>. This helps dependent projects find and use a package from the current project's build tree without help from the user. Note that the entry in the package registry that this command creates works only in conjunction with a package configuration file (<name>Config.cmake) that works with the build tree.

    + +
  • +
  • + file: File manipulation command.
    +
      file(WRITE filename "message to write"... )
    file(APPEND filename "message to write"... )
    file(READ filename variable [LIMIT numBytes] [OFFSET offset] [HEX])
    file(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512> filename variable)
    file(STRINGS filename variable [LIMIT_COUNT num]
    [LIMIT_INPUT numBytes] [LIMIT_OUTPUT numBytes]
    [LENGTH_MINIMUM numBytes] [LENGTH_MAXIMUM numBytes]
    [NEWLINE_CONSUME] [REGEX regex]
    [NO_HEX_CONVERSION])
    file(GLOB variable [RELATIVE path] [globbing expressions]...)
    file(GLOB_RECURSE variable [RELATIVE path]
    [FOLLOW_SYMLINKS] [globbing expressions]...)
    file(RENAME <oldname> <newname>)
    file(REMOVE [file1 ...])
    file(REMOVE_RECURSE [file1 ...])
    file(MAKE_DIRECTORY [directory1 directory2 ...])
    file(RELATIVE_PATH variable directory file)
    file(TO_CMAKE_PATH path result)
    file(TO_NATIVE_PATH path result)
    file(DOWNLOAD url file [INACTIVITY_TIMEOUT timeout]
    [TIMEOUT timeout] [STATUS status] [LOG log] [SHOW_PROGRESS]
    [EXPECTED_MD5 sum])
    file(UPLOAD filename url [INACTIVITY_TIMEOUT timeout]
    [TIMEOUT timeout] [STATUS status] [LOG log] [SHOW_PROGRESS])
    +

    WRITE will write a message into a file called 'filename'. It overwrites the file if it already exists, and creates the file if it does not exist.

    +

    APPEND will write a message into a file same as WRITE, except it will append it to the end of the file

    +

    READ will read the content of a file and store it into the variable. It will start at the given offset and read up to numBytes. If the argument HEX is given, the binary data will be converted to hexadecimal representation and this will be stored in the variable.

    +

    MD5, SHA1, SHA224, SHA256, SHA384, and SHA512 will compute a cryptographic hash of the content of a file.

    +

    STRINGS will parse a list of ASCII strings from a file and store it in a variable. Binary data in the file are ignored. Carriage return (CR) characters are ignored. It works also for Intel Hex and Motorola S-record files, which are automatically converted to binary format when reading them. Disable this using NO_HEX_CONVERSION.

    +

    LIMIT_COUNT sets the maximum number of strings to return. LIMIT_INPUT sets the maximum number of bytes to read from the input file. LIMIT_OUTPUT sets the maximum number of bytes to store in the output variable. LENGTH_MINIMUM sets the minimum length of a string to return. Shorter strings are ignored. LENGTH_MAXIMUM sets the maximum length of a string to return. Longer strings are split into strings no longer than the maximum length. NEWLINE_CONSUME allows newlines to be included in strings instead of terminating them.

    +

    REGEX specifies a regular expression that a string must match to be returned. Typical usage

    +
      file(STRINGS myfile.txt myfile)
    +

    stores a list in the variable "myfile" in which each item is a line from the input file.

    +

    GLOB will generate a list of all files that match the globbing expressions and store it into the variable. Globbing expressions are similar to regular expressions, but much simpler. If RELATIVE flag is specified for an expression, the results will be returned as a relative path to the given path. (We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.)

    +

    Examples of globbing expressions include:

    +
       *.cxx      - match all files with extension cxx
    *.vt? - match all files with extension vta,...,vtz
    f[3-5].txt - match files f3.txt, f4.txt, f5.txt
    +

    GLOB_RECURSE will generate a list similar to the regular GLOB, except it will traverse all the subdirectories of the matched directory and match the files. Subdirectories that are symlinks are only traversed if FOLLOW_SYMLINKS is given or cmake policy CMP0009 is not set to NEW. See cmake --help-policy CMP0009 for more information.

    +

    Examples of recursive globbing include:

    +
       /dir/*.py  - match all python files in /dir and subdirectories
    +

    MAKE_DIRECTORY will create the given directories, also if their parent directories don't exist yet

    +

    RENAME moves a file or directory within a filesystem, replacing the destination atomically.

    +

    REMOVE will remove the given files, also in subdirectories

    +

    REMOVE_RECURSE will remove the given files and directories, also non-empty directories

    +

    RELATIVE_PATH will determine relative path from directory to the given file.

    +

    TO_CMAKE_PATH will convert path into a cmake style path with unix /. The input can be a single path or a system path like "$ENV{PATH}". Note the double quotes around the ENV call TO_CMAKE_PATH only takes one argument.

    +

    TO_NATIVE_PATH works just like TO_CMAKE_PATH, but will convert from a cmake style path into the native path style \ for windows and / for UNIX.

    +

    DOWNLOAD will download the given URL to the given file. If LOG var is specified a log of the download will be put in var. If STATUS var is specified the status of the operation will be put in var. The status is returned in a list of length 2. The first element is the numeric return value for the operation, and the second element is a string value for the error. A 0 numeric error means no error in the operation. If TIMEOUT time is specified, the operation will timeout after time seconds, time should be specified as an integer. The INACTIVITY_TIMEOUT specifies an integer number of seconds of inactivity after which the operation should terminate. If EXPECTED_MD5 sum is specified, the operation will verify that the downloaded file's actual md5 sum matches the expected value. If it does not match, the operation fails with an error. If SHOW_PROGRESS is specified, progress information will be printed as status messages until the operation is complete.

    +

    UPLOAD will upload the given file to the given URL. If LOG var is specified a log of the upload will be put in var. If STATUS var is specified the status of the operation will be put in var. The status is returned in a list of length 2. The first element is the numeric return value for the operation, and the second element is a string value for the error. A 0 numeric error means no error in the operation. If TIMEOUT time is specified, the operation will timeout after time seconds, time should be specified as an integer. The INACTIVITY_TIMEOUT specifies an integer number of seconds of inactivity after which the operation should terminate. If SHOW_PROGRESS is specified, progress information will be printed as status messages until the operation is complete.

    +

    The file() command also provides COPY and INSTALL signatures:

    +
      file(<COPY|INSTALL> files... DESTINATION <dir>
    [FILE_PERMISSIONS permissions...]
    [DIRECTORY_PERMISSIONS permissions...]
    [NO_SOURCE_PERMISSIONS] [USE_SOURCE_PERMISSIONS]
    [FILES_MATCHING]
    [[PATTERN <pattern> | REGEX <regex>]
    [EXCLUDE] [PERMISSIONS permissions...]] [...])
    +

    The COPY signature copies files, directories, and symlinks to a destination folder. Relative input paths are evaluated with respect to the current source directory, and a relative destination is evaluated with respect to the current build directory. Copying preserves input file timestamps, and optimizes out a file if it exists at the destination with the same timestamp. Copying preserves input permissions unless explicit permissions or NO_SOURCE_PERMISSIONS are given (default is USE_SOURCE_PERMISSIONS). See the install(DIRECTORY) command for documentation of permissions, PATTERN, REGEX, and EXCLUDE options.

    +

    The INSTALL signature differs slightly from COPY: it prints status messages, and NO_SOURCE_PERMISSIONS is default. Installation scripts generated by the install() command use this signature (with some undocumented options for internal use).

    + +
  • +
  • + find_file: Find the full path to a file.
    +
       find_file(<VAR> name1 [path1 path2 ...])
    +

    This is the short-hand signature for the command that is sufficient in many cases. It is the same as find_file(<VAR> name1 [PATHS path1 path2 ...])

    +
       find_file(
    <VAR>
    name | NAMES name1 [name2 ...]
    [HINTS path1 [path2 ... ENV var]]
    [PATHS path1 [path2 ... ENV var]]
    [PATH_SUFFIXES suffix1 [suffix2 ...]]
    [DOC "cache documentation string"]
    [NO_DEFAULT_PATH]
    [NO_CMAKE_ENVIRONMENT_PATH]
    [NO_CMAKE_PATH]
    [NO_SYSTEM_ENVIRONMENT_PATH]
    [NO_CMAKE_SYSTEM_PATH]
    [CMAKE_FIND_ROOT_PATH_BOTH |
    ONLY_CMAKE_FIND_ROOT_PATH |
    NO_CMAKE_FIND_ROOT_PATH]
    )
    +

    This command is used to find a full path to named file. A cache entry named by <VAR> is created to store the result of this command. If the full path to a file is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again the next time find_file is invoked with the same variable. The name of the full path to a file that is searched for is specified by the names listed after the NAMES argument. Additional search locations can be specified after the PATHS argument. If ENV var is found in the HINTS or PATHS section the environment variable var will be read and converted from a system environment variable to a cmake style list of paths. For example ENV PATH would be a way to list the system path variable. The argument after DOC will be used for the documentation string in the cache. PATH_SUFFIXES specifies additional subdirectories to check below each search path.

    +

    If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:

    +

    1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. This can be skipped if NO_CMAKE_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_INCLUDE_PATH
    CMAKE_FRAMEWORK_PATH
    +

    2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration. This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_INCLUDE_PATH
    CMAKE_FRAMEWORK_PATH
    +

    3. Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.

    +

    4. Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is an argument.

    +
       PATH
    INCLUDE
    +

    5. Search cmake variables defined in the Platform files for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
    CMAKE_SYSTEM_INCLUDE_PATH
    CMAKE_SYSTEM_FRAMEWORK_PATH
    +

    6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.

    +

    On Darwin or systems supporting OS X Frameworks, the cmake variable CMAKE_FIND_FRAMEWORK can be set to empty or one of the following:

    +
       "FIRST"  - Try to find frameworks before standard
    libraries or headers. This is the default on Darwin.
    "LAST" - Try to find frameworks after standard
    libraries or headers.
    "ONLY" - Only try to find frameworks.
    "NEVER" - Never try to find frameworks.
    +

    On Darwin or systems supporting OS X Application Bundles, the cmake variable CMAKE_FIND_APPBUNDLE can be set to empty or one of the following:

    +
       "FIRST"  - Try to find application bundles before standard
    programs. This is the default on Darwin.
    "LAST" - Try to find application bundles after standard
    programs.
    "ONLY" - Only try to find application bundles.
    "NEVER" - Never try to find application bundles.
    +

    The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively "re-roots" the entire search under given locations. By default it is empty. It is especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_INCLUDE. This behavior can be manually overridden on a per-call basis. By using CMAKE_FIND_ROOT_PATH_BOTH the search order will be as described above. If NO_CMAKE_FIND_ROOT_PATH is used then CMAKE_FIND_ROOT_PATH will not be used. If ONLY_CMAKE_FIND_ROOT_PATH is used then only the re-rooted directories will be searched.

    +

    The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:

    +
       find_file(<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
    find_file(<VAR> NAMES name)
    +

    Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.

    + +
  • +
  • + find_library: Find a library.
    +
       find_library(<VAR> name1 [path1 path2 ...])
    +

    This is the short-hand signature for the command that is sufficient in many cases. It is the same as find_library(<VAR> name1 [PATHS path1 path2 ...])

    +
       find_library(
    <VAR>
    name | NAMES name1 [name2 ...]
    [HINTS path1 [path2 ... ENV var]]
    [PATHS path1 [path2 ... ENV var]]
    [PATH_SUFFIXES suffix1 [suffix2 ...]]
    [DOC "cache documentation string"]
    [NO_DEFAULT_PATH]
    [NO_CMAKE_ENVIRONMENT_PATH]
    [NO_CMAKE_PATH]
    [NO_SYSTEM_ENVIRONMENT_PATH]
    [NO_CMAKE_SYSTEM_PATH]
    [CMAKE_FIND_ROOT_PATH_BOTH |
    ONLY_CMAKE_FIND_ROOT_PATH |
    NO_CMAKE_FIND_ROOT_PATH]
    )
    +

    This command is used to find a library. A cache entry named by <VAR> is created to store the result of this command. If the library is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again the next time find_library is invoked with the same variable. The name of the library that is searched for is specified by the names listed after the NAMES argument. Additional search locations can be specified after the PATHS argument. If ENV var is found in the HINTS or PATHS section the environment variable var will be read and converted from a system environment variable to a cmake style list of paths. For example ENV PATH would be a way to list the system path variable. The argument after DOC will be used for the documentation string in the cache. PATH_SUFFIXES specifies additional subdirectories to check below each search path.

    +

    If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:

    +

    1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. This can be skipped if NO_CMAKE_PATH is passed.

    +
       <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and
    <prefix>/lib for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_LIBRARY_PATH
    CMAKE_FRAMEWORK_PATH
    +

    2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration. This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.

    +
       <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and
    <prefix>/lib for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_LIBRARY_PATH
    CMAKE_FRAMEWORK_PATH
    +

    3. Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.

    +

    4. Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is an argument.

    +
       PATH
    LIB
    +

    5. Search cmake variables defined in the Platform files for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH is passed.

    +
       <prefix>/lib/<arch> if CMAKE_LIBRARY_ARCHITECTURE is set, and
    <prefix>/lib for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
    CMAKE_SYSTEM_LIBRARY_PATH
    CMAKE_SYSTEM_FRAMEWORK_PATH
    +

    6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.

    +

    On Darwin or systems supporting OS X Frameworks, the cmake variable CMAKE_FIND_FRAMEWORK can be set to empty or one of the following:

    +
       "FIRST"  - Try to find frameworks before standard
    libraries or headers. This is the default on Darwin.
    "LAST" - Try to find frameworks after standard
    libraries or headers.
    "ONLY" - Only try to find frameworks.
    "NEVER" - Never try to find frameworks.
    +

    On Darwin or systems supporting OS X Application Bundles, the cmake variable CMAKE_FIND_APPBUNDLE can be set to empty or one of the following:

    +
       "FIRST"  - Try to find application bundles before standard
    programs. This is the default on Darwin.
    "LAST" - Try to find application bundles after standard
    programs.
    "ONLY" - Only try to find application bundles.
    "NEVER" - Never try to find application bundles.
    +

    The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively "re-roots" the entire search under given locations. By default it is empty. It is especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_LIBRARY. This behavior can be manually overridden on a per-call basis. By using CMAKE_FIND_ROOT_PATH_BOTH the search order will be as described above. If NO_CMAKE_FIND_ROOT_PATH is used then CMAKE_FIND_ROOT_PATH will not be used. If ONLY_CMAKE_FIND_ROOT_PATH is used then only the re-rooted directories will be searched.

    +

    The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:

    +
       find_library(<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
    find_library(<VAR> NAMES name)
    +

    Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.

    +

    If the library found is a framework, then VAR will be set to the full path to the framework <fullPath>/A.framework. When a full path to a framework is used as a library, CMake will use a -framework A, and a -F<fullPath> to link the framework to the target.

    + +
  • +
  • + find_package: Load settings for an external project.
    +
      find_package(<package> [version] [EXACT] [QUIET]
    [[REQUIRED|COMPONENTS] [components...]]
    [NO_POLICY_SCOPE])
    +

    Finds and loads settings from an external project. <package>_FOUND will be set to indicate whether the package was found. When the package is found package-specific information is provided through variables documented by the package itself. The QUIET option disables messages if the package cannot be found. The REQUIRED option stops processing with an error message if the package cannot be found. A package-specific list of components may be listed after the REQUIRED option or after the COMPONENTS option if no REQUIRED option is given. The [version] argument requests a version with which the package found should be compatible (format is major[.minor[.patch[.tweak]]]). The EXACT option requests that the version be matched exactly. If no [version] and/or component list is given to a recursive invocation inside a find-module, the corresponding arguments are forwarded automatically from the outer call (including the EXACT flag for [version]). Version support is currently provided only on a package-by-package basis (details below).

    +

    User code should generally look for packages using the above simple signature. The remainder of this command documentation specifies the full command signature and details of the search process. Project maintainers wishing to provide a package to be found by this command are encouraged to read on.

    +

    The command has two modes by which it searches for packages: "Module" mode and "Config" mode. Module mode is available when the command is invoked with the above reduced signature. CMake searches for a file called "Find<package>.cmake" in the CMAKE_MODULE_PATH followed by the CMake installation. If the file is found, it is read and processed by CMake. It is responsible for finding the package, checking the version, and producing any needed messages. Many find-modules provide limited or no support for versioning; check the module documentation. If no module is found the command proceeds to Config mode.

    +

    The complete Config mode command signature is:

    +
      find_package(<package> [version] [EXACT] [QUIET]
    [[REQUIRED|COMPONENTS] [components...]] [NO_MODULE]
    [NO_POLICY_SCOPE]
    [NAMES name1 [name2 ...]]
    [CONFIGS config1 [config2 ...]]
    [HINTS path1 [path2 ... ]]
    [PATHS path1 [path2 ... ]]
    [PATH_SUFFIXES suffix1 [suffix2 ...]]
    [NO_DEFAULT_PATH]
    [NO_CMAKE_ENVIRONMENT_PATH]
    [NO_CMAKE_PATH]
    [NO_SYSTEM_ENVIRONMENT_PATH]
    [NO_CMAKE_PACKAGE_REGISTRY]
    [NO_CMAKE_BUILDS_PATH]
    [NO_CMAKE_SYSTEM_PATH]
    [NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]
    [CMAKE_FIND_ROOT_PATH_BOTH |
    ONLY_CMAKE_FIND_ROOT_PATH |
    NO_CMAKE_FIND_ROOT_PATH])
    +

    The NO_MODULE option may be used to skip Module mode explicitly. It is also implied by use of options not specified in the reduced signature.

    +

    Config mode attempts to locate a configuration file provided by the package to be found. A cache entry called <package>_DIR is created to hold the directory containing the file. By default the command searches for a package with the name <package>. If the NAMES option is given the names following it are used instead of <package>. The command searches for a file called "<name>Config.cmake" or "<lower-case-name>-config.cmake" for each name specified. A replacement set of possible configuration file names may be given using the CONFIGS option. The search procedure is specified below. Once found, the configuration file is read and processed by CMake. Since the file is provided by the package it already knows the location of package contents. The full path to the configuration file is stored in the cmake variable <package>_CONFIG.

    +

    All configuration files which have been considered by CMake while searching for an installation of the package with an appropriate version are stored in the cmake variable <package>_CONSIDERED_CONFIGS, the associated versions in <package>_CONSIDERED_VERSIONS.

    +

    If the package configuration file cannot be found CMake will generate an error describing the problem unless the QUIET argument is specified. If REQUIRED is specified and the package is not found a fatal error is generated and the configure step stops executing. If <package>_DIR has been set to a directory not containing a configuration file CMake will ignore it and search from scratch.

    +

    When the [version] argument is given Config mode will only find a version of the package that claims compatibility with the requested version (format is major[.minor[.patch[.tweak]]]). If the EXACT option is given only a version of the package claiming an exact match of the requested version may be found. CMake does not establish any convention for the meaning of version numbers. Package version numbers are checked by "version" files provided by the packages themselves. For a candidate package configuration file "<config-file>.cmake" the corresponding version file is located next to it and named either "<config-file>-version.cmake" or "<config-file>Version.cmake". If no such version file is available then the configuration file is assumed to not be compatible with any requested version. A basic version file containing generic version matching code can be created using the macro write_basic_config_version_file(), see its documentation for more details. When a version file is found it is loaded to check the requested version number. The version file is loaded in a nested scope in which the following variables have been defined:

    +
      PACKAGE_FIND_NAME          = the <package> name
    PACKAGE_FIND_VERSION = full requested version string
    PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0
    PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0
    PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0
    PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0
    PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4
    +

    The version file checks whether it satisfies the requested version and sets these variables:

    +
      PACKAGE_VERSION            = full provided version string
    PACKAGE_VERSION_EXACT = true if version is exact match
    PACKAGE_VERSION_COMPATIBLE = true if version is compatible
    PACKAGE_VERSION_UNSUITABLE = true if unsuitable as any version
    +

    These variables are checked by the find_package command to determine whether the configuration file provides an acceptable version. They are not available after the find_package call returns. If the version is acceptable the following variables are set:

    +
      <package>_VERSION       = full provided version string
    <package>_VERSION_MAJOR = major version if provided, else 0
    <package>_VERSION_MINOR = minor version if provided, else 0
    <package>_VERSION_PATCH = patch version if provided, else 0
    <package>_VERSION_TWEAK = tweak version if provided, else 0
    <package>_VERSION_COUNT = number of version components, 0 to 4
    +

    and the corresponding package configuration file is loaded. When multiple package configuration files are available whose version files claim compatibility with the version requested it is unspecified which one is chosen. No attempt is made to choose a highest or closest version number.

    +

    Config mode provides an elaborate interface and search procedure. Much of the interface is provided for completeness and for use internally by find-modules loaded by Module mode. Most user code should simply call

    +
      find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])
    +

    in order to find a package. Package maintainers providing CMake package configuration files are encouraged to name and install them such that the procedure outlined below will find them without requiring use of additional options.

    +

    CMake constructs a set of possible installation prefixes for the package. Under each prefix several directories are searched for a configuration file. The tables below show the directories searched. Each entry is meant for installation trees following Windows (W), UNIX (U), or Apple (A) conventions.

    +
      <prefix>/                                               (W)
    <prefix>/(cmake|CMake)/ (W)
    <prefix>/<name>*/ (W)
    <prefix>/<name>*/(cmake|CMake)/ (W)
    <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U)
    <prefix>/(lib/<arch>|lib|share)/<name>*/ (U)
    <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U)
    +

    On systems supporting OS X Frameworks and Application Bundles the following directories are searched for frameworks or bundles containing a configuration file:

    +
      <prefix>/<name>.framework/Resources/                    (A)
    <prefix>/<name>.framework/Resources/CMake/ (A)
    <prefix>/<name>.framework/Versions/*/Resources/ (A)
    <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)
    <prefix>/<name>.app/Contents/Resources/ (A)
    <prefix>/<name>.app/Contents/Resources/CMake/ (A)
    +

    In all cases the <name> is treated as case-insensitive and corresponds to any of the names specified (<package> or names given by NAMES). Paths with lib/<arch> are enabled if CMAKE_LIBRARY_ARCHITECTURE is set. If PATH_SUFFIXES is specified the suffixes are appended to each (W) or (U) directory entry one-by-one.

    +

    This set of directories is intended to work in cooperation with projects that provide configuration files in their installation trees. Directories above marked with (W) are intended for installations on Windows where the prefix may point at the top of an application's installation directory. Those marked with (U) are intended for installations on UNIX platforms where the prefix is shared by multiple packages. This is merely a convention, so all (W) and (U) directories are still searched on all platforms. Directories marked with (A) are intended for installations on Apple platforms. The cmake variables CMAKE_FIND_FRAMEWORK and CMAKE_FIND_APPBUNDLE determine the order of preference as specified below.

    +

    The set of installation prefixes is constructed using the following steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.

    +

    1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. This can be skipped if NO_CMAKE_PATH is passed.

    +
       CMAKE_PREFIX_PATH
    CMAKE_FRAMEWORK_PATH
    CMAKE_APPBUNDLE_PATH
    +

    2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration. This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.

    +
       <package>_DIR
    CMAKE_PREFIX_PATH
    CMAKE_FRAMEWORK_PATH
    CMAKE_APPBUNDLE_PATH
    +

    3. Search paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.

    +

    4. Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed. Path entries ending in "/bin" or "/sbin" are automatically converted to their parent directories.

    +
       PATH
    +

    5. Search project build trees recently configured in a CMake GUI. This can be skipped if NO_CMAKE_BUILDS_PATH is passed. It is intended for the case when a user is building multiple dependent projects one after another.

    +

    6. Search paths stored in the CMake user package registry. This can be skipped if NO_CMAKE_PACKAGE_REGISTRY is passed. On Windows a <package> may appear under registry key

    +
      HKEY_CURRENT_USER\Software\Kitware\CMake\Packages\<package>
    +

    as a REG_SZ value, with arbitrary name, that specifies the directory containing the package configuration file. On UNIX platforms a <package> may appear under the directory

    +
      ~/.cmake/packages/<package>
    +

    as a file, with arbitrary name, whose content specifies the directory containing the package configuration file. See the export(PACKAGE) command to create user package registry entries for project build trees.

    +

    7. Search cmake variables defined in the Platform files for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH is passed.

    +
       CMAKE_SYSTEM_PREFIX_PATH
    CMAKE_SYSTEM_FRAMEWORK_PATH
    CMAKE_SYSTEM_APPBUNDLE_PATH
    +

    8. Search paths stored in the CMake system package registry. This can be skipped if NO_CMAKE_SYSTEM_PACKAGE_REGISTRY is passed. On Windows a <package> may appear under registry key

    +
      HKEY_LOCAL_MACHINE\Software\Kitware\CMake\Packages\<package>
    +

    as a REG_SZ value, with arbitrary name, that specifies the directory containing the package configuration file. There is no system package registry on non-Windows platforms.

    +

    9. Search paths specified by the PATHS option. These are typically hard-coded guesses.

    +

    On Darwin or systems supporting OS X Frameworks, the cmake variable CMAKE_FIND_FRAMEWORK can be set to empty or one of the following:

    +
       "FIRST"  - Try to find frameworks before standard
    libraries or headers. This is the default on Darwin.
    "LAST" - Try to find frameworks after standard
    libraries or headers.
    "ONLY" - Only try to find frameworks.
    "NEVER" - Never try to find frameworks.
    +

    On Darwin or systems supporting OS X Application Bundles, the cmake variable CMAKE_FIND_APPBUNDLE can be set to empty or one of the following:

    +
       "FIRST"  - Try to find application bundles before standard
    programs. This is the default on Darwin.
    "LAST" - Try to find application bundles after standard
    programs.
    "ONLY" - Only try to find application bundles.
    "NEVER" - Never try to find application bundles.
    +

    The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively "re-roots" the entire search under given locations. By default it is empty. It is especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_PACKAGE. This behavior can be manually overridden on a per-call basis. By using CMAKE_FIND_ROOT_PATH_BOTH the search order will be as described above. If NO_CMAKE_FIND_ROOT_PATH is used then CMAKE_FIND_ROOT_PATH will not be used. If ONLY_CMAKE_FIND_ROOT_PATH is used then only the re-rooted directories will be searched.

    +

    The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:

    +
       find_package(<package> PATHS paths... NO_DEFAULT_PATH)
    find_package(<package>)
    +

    Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.

    +

    Every non-REQUIRED find_package() call can be disabled by setting the variable CMAKE_DISABLE_FIND_PACKAGE_<package> to TRUE. See the documentation for the CMAKE_DISABLE_FIND_PACKAGE_<package> variable for more information.

    +

    See the cmake_policy() command documentation for discussion of the NO_POLICY_SCOPE option.

    + +
  • +
  • + find_path: Find the directory containing a file.
    +
       find_path(<VAR> name1 [path1 path2 ...])
    +

    This is the short-hand signature for the command that is sufficient in many cases. It is the same as find_path(<VAR> name1 [PATHS path1 path2 ...])

    +
       find_path(
    <VAR>
    name | NAMES name1 [name2 ...]
    [HINTS path1 [path2 ... ENV var]]
    [PATHS path1 [path2 ... ENV var]]
    [PATH_SUFFIXES suffix1 [suffix2 ...]]
    [DOC "cache documentation string"]
    [NO_DEFAULT_PATH]
    [NO_CMAKE_ENVIRONMENT_PATH]
    [NO_CMAKE_PATH]
    [NO_SYSTEM_ENVIRONMENT_PATH]
    [NO_CMAKE_SYSTEM_PATH]
    [CMAKE_FIND_ROOT_PATH_BOTH |
    ONLY_CMAKE_FIND_ROOT_PATH |
    NO_CMAKE_FIND_ROOT_PATH]
    )
    +

    This command is used to find a directory containing the named file. A cache entry named by <VAR> is created to store the result of this command. If the file in a directory is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again the next time find_path is invoked with the same variable. The name of the file in a directory that is searched for is specified by the names listed after the NAMES argument. Additional search locations can be specified after the PATHS argument. If ENV var is found in the HINTS or PATHS section the environment variable var will be read and converted from a system environment variable to a cmake style list of paths. For example ENV PATH would be a way to list the system path variable. The argument after DOC will be used for the documentation string in the cache. PATH_SUFFIXES specifies additional subdirectories to check below each search path.

    +

    If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:

    +

    1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. This can be skipped if NO_CMAKE_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_INCLUDE_PATH
    CMAKE_FRAMEWORK_PATH
    +

    2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration. This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_INCLUDE_PATH
    CMAKE_FRAMEWORK_PATH
    +

    3. Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.

    +

    4. Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is an argument.

    +
       PATH
    INCLUDE
    +

    5. Search cmake variables defined in the Platform files for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH is passed.

    +
       <prefix>/include for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
    CMAKE_SYSTEM_INCLUDE_PATH
    CMAKE_SYSTEM_FRAMEWORK_PATH
    +

    6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.

    +

    On Darwin or systems supporting OS X Frameworks, the cmake variable CMAKE_FIND_FRAMEWORK can be set to empty or one of the following:

    +
       "FIRST"  - Try to find frameworks before standard
    libraries or headers. This is the default on Darwin.
    "LAST" - Try to find frameworks after standard
    libraries or headers.
    "ONLY" - Only try to find frameworks.
    "NEVER" - Never try to find frameworks.
    +

    On Darwin or systems supporting OS X Application Bundles, the cmake variable CMAKE_FIND_APPBUNDLE can be set to empty or one of the following:

    +
       "FIRST"  - Try to find application bundles before standard
    programs. This is the default on Darwin.
    "LAST" - Try to find application bundles after standard
    programs.
    "ONLY" - Only try to find application bundles.
    "NEVER" - Never try to find application bundles.
    +

    The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively "re-roots" the entire search under given locations. By default it is empty. It is especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_INCLUDE. This behavior can be manually overridden on a per-call basis. By using CMAKE_FIND_ROOT_PATH_BOTH the search order will be as described above. If NO_CMAKE_FIND_ROOT_PATH is used then CMAKE_FIND_ROOT_PATH will not be used. If ONLY_CMAKE_FIND_ROOT_PATH is used then only the re-rooted directories will be searched.

    +

    The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:

    +
       find_path(<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
    find_path(<VAR> NAMES name)
    +

    Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.

    +

    When searching for frameworks, if the file is specified as A/b.h, then the framework search will look for A.framework/Headers/b.h. If that is found the path will be set to the path to the framework. CMake will convert this to the correct -F option to include the file.

    + +
  • +
  • + find_program: Find an executable program.
    +
       find_program(<VAR> name1 [path1 path2 ...])
    +

    This is the short-hand signature for the command that is sufficient in many cases. It is the same as find_program(<VAR> name1 [PATHS path1 path2 ...])

    +
       find_program(
    <VAR>
    name | NAMES name1 [name2 ...]
    [HINTS path1 [path2 ... ENV var]]
    [PATHS path1 [path2 ... ENV var]]
    [PATH_SUFFIXES suffix1 [suffix2 ...]]
    [DOC "cache documentation string"]
    [NO_DEFAULT_PATH]
    [NO_CMAKE_ENVIRONMENT_PATH]
    [NO_CMAKE_PATH]
    [NO_SYSTEM_ENVIRONMENT_PATH]
    [NO_CMAKE_SYSTEM_PATH]
    [CMAKE_FIND_ROOT_PATH_BOTH |
    ONLY_CMAKE_FIND_ROOT_PATH |
    NO_CMAKE_FIND_ROOT_PATH]
    )
    +

    This command is used to find a program. A cache entry named by <VAR> is created to store the result of this command. If the program is found the result is stored in the variable and the search will not be repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again the next time find_program is invoked with the same variable. The name of the program that is searched for is specified by the names listed after the NAMES argument. Additional search locations can be specified after the PATHS argument. If ENV var is found in the HINTS or PATHS section the environment variable var will be read and converted from a system environment variable to a cmake style list of paths. For example ENV PATH would be a way to list the system path variable. The argument after DOC will be used for the documentation string in the cache. PATH_SUFFIXES specifies additional subdirectories to check below each search path.

    +

    If NO_DEFAULT_PATH is specified, then no additional paths are added to the search. If NO_DEFAULT_PATH is not specified, the search process is as follows:

    +

    1. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a -DVAR=value. This can be skipped if NO_CMAKE_PATH is passed.

    +
       <prefix>/[s]bin for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_PROGRAM_PATH
    CMAKE_APPBUNDLE_PATH
    +

    2. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration. This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.

    +
       <prefix>/[s]bin for each <prefix> in CMAKE_PREFIX_PATH
    CMAKE_PROGRAM_PATH
    CMAKE_APPBUNDLE_PATH
    +

    3. Search the paths specified by the HINTS option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the PATHS option.

    +

    4. Search the standard system environment variables. This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is an argument.

    +
       PATH

    +

    5. Search cmake variables defined in the Platform files for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH is passed.

    +
       <prefix>/[s]bin for each <prefix> in CMAKE_SYSTEM_PREFIX_PATH
    CMAKE_SYSTEM_PROGRAM_PATH
    CMAKE_SYSTEM_APPBUNDLE_PATH
    +

    6. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses.

    +

    On Darwin or systems supporting OS X Frameworks, the cmake variable CMAKE_FIND_FRAMEWORK can be set to empty or one of the following:

    +
       "FIRST"  - Try to find frameworks before standard
    libraries or headers. This is the default on Darwin.
    "LAST" - Try to find frameworks after standard
    libraries or headers.
    "ONLY" - Only try to find frameworks.
    "NEVER" - Never try to find frameworks.
    +

    On Darwin or systems supporting OS X Application Bundles, the cmake variable CMAKE_FIND_APPBUNDLE can be set to empty or one of the following:

    +
       "FIRST"  - Try to find application bundles before standard
    programs. This is the default on Darwin.
    "LAST" - Try to find application bundles after standard
    programs.
    "ONLY" - Only try to find application bundles.
    "NEVER" - Never try to find application bundles.
    +

    The CMake variable CMAKE_FIND_ROOT_PATH specifies one or more directories to be prepended to all other search directories. This effectively "re-roots" the entire search under given locations. By default it is empty. It is especially useful when cross-compiling to point to the root directory of the target environment and CMake will search there too. By default at first the directories listed in CMAKE_FIND_ROOT_PATH and then the non-rooted directories will be searched. The default behavior can be adjusted by setting CMAKE_FIND_ROOT_PATH_MODE_PROGRAM. This behavior can be manually overridden on a per-call basis. By using CMAKE_FIND_ROOT_PATH_BOTH the search order will be as described above. If NO_CMAKE_FIND_ROOT_PATH is used then CMAKE_FIND_ROOT_PATH will not be used. If ONLY_CMAKE_FIND_ROOT_PATH is used then only the re-rooted directories will be searched.

    +

    The default search order is designed to be most-specific to least-specific for common use cases. Projects may override the order by simply calling the command multiple times and using the NO_* options:

    +
       find_program(<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH)
    find_program(<VAR> NAMES name)
    +

    Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again.

    + +
  • +
  • + fltk_wrap_ui: Create FLTK user interfaces Wrappers.
    +
      fltk_wrap_ui(resultingLibraryName source1
    source2 ... sourceN )
    +

    Produce .h and .cxx files for all the .fl and .fld files listed. The resulting .h and .cxx files will be added to a variable named resultingLibraryName_FLTK_UI_SRCS which should be added to your library.

    + +
  • +
  • + foreach: Evaluate a group of commands for each value in a list.
    +
      foreach(loop_var arg1 arg2 ...)
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    endforeach(loop_var)
    +

    All commands between foreach and the matching endforeach are recorded without being invoked. Once the endforeach is evaluated, the recorded list of commands is invoked once for each argument listed in the original foreach command. Before each iteration of the loop "${loop_var}" will be set as a variable with the current value in the list.

    +
      foreach(loop_var RANGE total)
    foreach(loop_var RANGE start stop [step])
    +

    Foreach can also iterate over a generated range of numbers. There are three types of this iteration:

    +

    * When specifying single number, the range will have elements 0 to "total".

    +

    * When specifying two numbers, the range will have elements from the first number to the second number.

    +

    * The third optional number is the increment used to iterate from the first number to the second number.

    +
      foreach(loop_var IN [LISTS [list1 [...]]]
    [ITEMS [item1 [...]]])
    +

    Iterates over a precise list of items. The LISTS option names list-valued variables to be traversed, including empty elements (an empty string is a zero-length list). The ITEMS option ends argument parsing and includes all arguments following it in the iteration.

    + +
  • +
  • + function: Start recording a function for later invocation as a command.
    +
      function(<name> [arg1 [arg2 [arg3 ...]]])
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    endfunction(<name>)
    +

    Define a function named <name> that takes arguments named arg1 arg2 arg3 (...). Commands listed after function, but before the matching endfunction, are not invoked until the function is invoked. When it is invoked, the commands recorded in the function are first modified by replacing formal parameters (${arg1}) with the arguments passed, and then invoked as normal commands. In addition to referencing the formal parameters you can reference the variable ARGC which will be set to the number of arguments passed into the function as well as ARGV0 ARGV1 ARGV2 ... which will have the actual values of the arguments passed in. This facilitates creating functions with optional arguments. Additionally ARGV holds the list of all arguments given to the function and ARGN holds the list of argument past the last expected argument.

    +

    See the cmake_policy() command documentation for the behavior of policies inside functions.

    + +
  • +
  • + get_cmake_property: Get a property of the CMake instance.
    +
      get_cmake_property(VAR property)
    +

    Get a property from the CMake instance. The value of the property is stored in the variable VAR. If the property is not found, VAR will be set to "NOTFOUND". Some supported properties include: VARIABLES, CACHE_VARIABLES, COMMANDS, MACROS, and COMPONENTS.

    +

    See also the more general get_property() command.

    + +
  • +
  • + get_directory_property: Get a property of DIRECTORY scope.
    +
      get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>)
    +

    Store a property of directory scope in the named variable. If the property is not defined the empty-string is returned. The DIRECTORY argument specifies another directory from which to retrieve the property value. The specified directory must have already been traversed by CMake.

    +
      get_directory_property(<variable> [DIRECTORY <dir>]
    DEFINITION <var-name>)
    +

    Get a variable definition from a directory. This form is useful to get a variable definition from another directory.

    +

    See also the more general get_property() command.

    + +
  • +
  • + get_filename_component: Get a specific component of a full filename.
    +
      get_filename_component(<VAR> FileName
    PATH|ABSOLUTE|NAME|EXT|NAME_WE|REALPATH
    [CACHE])
    +

    Set <VAR> to be the path (PATH), file name (NAME), file extension (EXT), file name without extension (NAME_WE) of FileName, the full path (ABSOLUTE), or the full path with all symlinks resolved (REALPATH). Note that the path is converted to Unix slashes format and has no trailing slashes. The longest file extension is always considered. If the optional CACHE argument is specified, the result variable is added to the cache.

    +
      get_filename_component(<VAR> FileName
    PROGRAM [PROGRAM_ARGS <ARG_VAR>]
    [CACHE])
    +

    The program in FileName will be found in the system search path or left as a full path. If PROGRAM_ARGS is present with PROGRAM, then any command-line arguments present in the FileName string are split from the program name and stored in <ARG_VAR>. This is used to separate a program name from its arguments in a command line string.

    + +
  • +
  • + get_property: Get a property.
    +
      get_property(<variable>
    <GLOBAL |
    DIRECTORY [dir] |
    TARGET <target> |
    SOURCE <source> |
    TEST <test> |
    CACHE <entry> |
    VARIABLE>
    PROPERTY <name>
    [SET | DEFINED | BRIEF_DOCS | FULL_DOCS])
    +

    Get one property from one object in a scope. The first argument specifies the variable in which to store the result. The second argument determines the scope from which to get the property. It must be one of the following:

    +

    GLOBAL scope is unique and does not accept a name.

    +

    DIRECTORY scope defaults to the current directory but another directory (already processed by CMake) may be named by full or relative path.

    +

    TARGET scope must name one existing target.

    +

    SOURCE scope must name one source file.

    +

    TEST scope must name one existing test.

    +

    CACHE scope must name one cache entry.

    +

    VARIABLE scope is unique and does not accept a name.

    +

    The required PROPERTY option is immediately followed by the name of the property to get. If the property is not set an empty value is returned. If the SET option is given the variable is set to a boolean value indicating whether the property has been set. If the DEFINED option is given the variable is set to a boolean value indicating whether the property has been defined such as with define_property. If BRIEF_DOCS or FULL_DOCS is given then the variable is set to a string containing documentation for the requested property. If documentation is requested for a property that has not been defined NOTFOUND is returned.

    + +
  • +
  • + get_source_file_property: Get a property for a source file.
    +
      get_source_file_property(VAR file property)
    +

    Get a property from a source file. The value of the property is stored in the variable VAR. If the property is not found, VAR will be set to "NOTFOUND". Use set_source_files_properties to set property values. Source file properties usually control how the file is built. One property that is always there is LOCATION

    +

    See also the more general get_property() command.

    + +
  • +
  • + get_target_property: Get a property from a target.
    +
      get_target_property(VAR target property)
    +

    Get a property from a target. The value of the property is stored in the variable VAR. If the property is not found, VAR will be set to "NOTFOUND". Use set_target_properties to set property values. Properties are usually used to control how a target is built, but some query the target instead. This command can get properties for any target so far created. The targets do not need to be in the current CMakeLists.txt file.

    +

    See also the more general get_property() command.

    + +
  • +
  • + get_test_property: Get a property of the test.
    +
      get_test_property(test property VAR)
    +

    Get a property from the Test. The value of the property is stored in the variable VAR. If the property is not found, VAR will be set to "NOTFOUND". For a list of standard properties you can type cmake --help-property-list

    +

    See also the more general get_property() command.

    + +
  • +
  • + if: Conditionally execute a group of commands.
    +
      if(expression)
    # then section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    elseif(expression2)
    # elseif section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    else(expression)
    # else section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    endif(expression)
    +

    Evaluates the given expression. If the result is true, the commands in the THEN section are invoked. Otherwise, the commands in the else section are invoked. The elseif and else sections are optional. You may have multiple elseif clauses. Note that the expression in the else and endif clause is optional. Long expressions can be used and there is a traditional order of precedence. Parenthetical expressions are evaluated first followed by unary operators such as EXISTS, COMMAND, and DEFINED. Then any EQUAL, LESS, GREATER, STRLESS, STRGREATER, STREQUAL, MATCHES will be evaluated. Then NOT operators and finally AND, OR operators will be evaluated. Possible expressions are:

    +
      if(<constant>)
    +

    True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number. False if the constant is 0, OFF, NO, FALSE, N, IGNORE, "", or ends in the suffix '-NOTFOUND'. Named boolean constants are case-insensitive. If the argument is not one of these constants, it is treated as a variable:

    +
      if(<variable>)
    +

    True if the variable is defined to a value that is not a false constant. False otherwise.

    +
      if(NOT <expression>)
    +

    True if the expression is not true.

    +
      if(<expr1> AND <expr2>)
    +

    True if both expressions would be considered true individually.

    +
      if(<expr1> OR <expr2>)
    +

    True if either expression would be considered true individually.

    +
      if(COMMAND command-name)
    +

    True if the given name is a command, macro or function that can be invoked.

    +
      if(POLICY policy-id)
    +

    True if the given name is an existing policy (of the form CMP<NNNN>).

    +
      if(TARGET target-name)
    +

    True if the given name is an existing target, built or imported.

    +
      if(EXISTS file-name)
    if(EXISTS directory-name)
    +

    True if the named file or directory exists. Behavior is well-defined only for full paths.

    +
      if(file1 IS_NEWER_THAN file2)
    +

    True if file1 is newer than file2 or if one of the two files doesn't exist. Behavior is well-defined only for full paths.

    +
      if(IS_DIRECTORY directory-name)
    +

    True if the given name is a directory. Behavior is well-defined only for full paths.

    +
      if(IS_SYMLINK file-name)
    +

    True if the given name is a symbolic link. Behavior is well-defined only for full paths.

    +
      if(IS_ABSOLUTE path)
    +

    True if the given path is an absolute path.

    +
      if(<variable|string> MATCHES regex)
    +

    True if the given string or variable's value matches the given regular expression.

    +
      if(<variable|string> LESS <variable|string>)
    if(<variable|string> GREATER <variable|string>)
    if(<variable|string> EQUAL <variable|string>)
    +

    True if the given string or variable's value is a valid number and the inequality or equality is true.

    +
      if(<variable|string> STRLESS <variable|string>)
    if(<variable|string> STRGREATER <variable|string>)
    if(<variable|string> STREQUAL <variable|string>)
    +

    True if the given string or variable's value is lexicographically less (or greater, or equal) than the string or variable on the right.

    +
      if(<variable|string> VERSION_LESS <variable|string>)
    if(<variable|string> VERSION_EQUAL <variable|string>)
    if(<variable|string> VERSION_GREATER <variable|string>)
    +

    Component-wise integer version number comparison (version format is major[.minor[.patch[.tweak]]]).

    +
      if(DEFINED <variable>)
    +

    True if the given variable is defined. It does not matter if the variable is true or false just if it has been set.

    +
      if((expression) AND (expression OR (expression)))
    +

    The expressions inside the parenthesis are evaluated first and then the remaining expression is evaluated as in the previous examples. Where there are nested parenthesis the innermost are evaluated as part of evaluating the expression that contains them.

    +

    The if command was written very early in CMake's history, predating the ${} variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures. Note that normal variable evaluation with ${} applies before the if command even receives the arguments. Therefore code like

    +
      set(var1 OFF)
    set(var2 "var1")
    if(${var2})
    +

    appears to the if command as

    +
      if(var1)
    +

    and is evaluated according to the if(<variable>) case documented above. The result is OFF which is false. However, if we remove the ${} from the example then the command sees

    +
      if(var2)
    +

    which is true because var2 is defined to "var1" which is not a false constant.

    +

    Automatic evaluation applies in the other cases whenever the above-documented signature accepts <variable|string>:

    +

    1) The left hand argument to MATCHES is first checked to see if it is a defined variable, if so the variable's value is used, otherwise the original value is used.

    +

    2) If the left hand argument to MATCHES is missing it returns false without error

    +

    3) Both left and right hand arguments to LESS GREATER EQUAL are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.

    +

    4) Both left and right hand arguments to STRLESS STREQUAL STRGREATER are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.

    +

    5) Both left and right hand argumemnts to VERSION_LESS VERSION_EQUAL VERSION_GREATER are independently tested to see if they are defined variables, if so their defined values are used otherwise the original value is used.

    +

    6) The right hand argument to NOT is tested to see if it is a boolean constant, if so the value is used, otherwise it is assumed to be a variable and it is dereferenced.

    +

    7) The left and right hand arguments to AND OR are independently tested to see if they are boolean constants, if so they are used as such, otherwise they are assumed to be variables and are dereferenced.

    + +
  • +
  • + include: Read CMake listfile code from the given file.
    +
      include(<file|module> [OPTIONAL] [RESULT_VARIABLE <VAR>]
    [NO_POLICY_SCOPE])
    +

    Reads CMake listfile code from the given file. Commands in the file are processed immediately as if they were written in place of the include command. If OPTIONAL is present, then no error is raised if the file does not exist. If RESULT_VARIABLE is given the variable will be set to the full filename which has been included or NOTFOUND if it failed.

    +

    If a module is specified instead of a file, the file with name <modulename>.cmake is searched first in CMAKE_MODULE_PATH, then in the CMake module directory. There is one exception to this: if the file which calls include() is located itself in the CMake module directory, then first the CMake module directory is searched and CMAKE_MODULE_PATH afterwards. See also policy CMP0017.

    +

    See the cmake_policy() command documentation for discussion of the NO_POLICY_SCOPE option.

    + +
  • +
  • + include_directories: Add include directories to the build.
    +
      include_directories([AFTER|BEFORE] [SYSTEM] dir1 dir2 ...)
    +

    Add the given directories to those searched by the compiler for include files. By default the directories are appended onto the current list of directories. This default behavior can be changed by setting CMAKE_INCLUDE_DIRECTORIES_BEFORE to ON. By using BEFORE or AFTER you can select between appending and prepending, independent from the default. If the SYSTEM option is given the compiler will be told that the directories are meant as system include directories on some platforms.

    + +
  • +
  • + include_external_msproject: Include an external Microsoft project file in a workspace.
    +
      include_external_msproject(projectname location
    dep1 dep2 ...)
    +

    Includes an external Microsoft project in the generated workspace file. Currently does nothing on UNIX. This will create a target named [projectname]. This can be used in the add_dependencies command to make things depend on the external project.

    + +
  • +
  • + include_regular_expression: Set the regular expression used for dependency checking.
    +
      include_regular_expression(regex_match [regex_complain])
    +

    Set the regular expressions used in dependency checking. Only files matching regex_match will be traced as dependencies. Only files matching regex_complain will generate warnings if they cannot be found (standard header paths are not searched). The defaults are:

    +
      regex_match    = "^.*$" (match everything)
    regex_complain = "^$" (match empty string only)
    + +
  • +
  • + install: Specify rules to run at install time.
    +

    This command generates installation rules for a project. Rules specified by calls to this command within a source directory are executed in order during installation. The order across directories is not defined.

    +

    There are multiple signatures for this command. Some of them define installation properties for files and targets. Properties common to multiple signatures are covered here but they are valid only for signatures that specify them.

    +

    DESTINATION arguments specify the directory on disk to which a file will be installed. If a full path (with a leading slash or drive letter) is given it is used directly. If a relative path is given it is interpreted relative to the value of CMAKE_INSTALL_PREFIX.

    +

    PERMISSIONS arguments specify permissions for installed files. Valid permissions are OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_WRITE, GROUP_EXECUTE, WORLD_READ, WORLD_WRITE, WORLD_EXECUTE, SETUID, and SETGID. Permissions that do not make sense on certain platforms are ignored on those platforms.

    +

    The CONFIGURATIONS argument specifies a list of build configurations for which the install rule applies (Debug, Release, etc.).

    +

    The COMPONENT argument specifies an installation component name with which the install rule is associated, such as "runtime" or "development". During component-specific installation only install rules associated with the given component name will be executed. During a full installation all components are installed.

    +

    The RENAME argument specifies a name for an installed file that may be different from the original file. Renaming is allowed only when a single file is installed by the command.

    +

    The OPTIONAL argument specifies that it is not an error if the file to be installed does not exist.

    +

    The TARGETS signature:

    +
      install(TARGETS targets... [EXPORT <export-name>]
    [[ARCHIVE|LIBRARY|RUNTIME|FRAMEWORK|BUNDLE|
    PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
    [DESTINATION <dir>]
    [PERMISSIONS permissions...]
    [CONFIGURATIONS [Debug|Release|...]]
    [COMPONENT <component>]
    [OPTIONAL] [NAMELINK_ONLY|NAMELINK_SKIP]
    ] [...])
    +

    The TARGETS form specifies rules for installing targets from a project. There are five kinds of target files that may be installed: ARCHIVE, LIBRARY, RUNTIME, FRAMEWORK, and BUNDLE. Executables are treated as RUNTIME targets, except that those marked with the MACOSX_BUNDLE property are treated as BUNDLE targets on OS X. Static libraries are always treated as ARCHIVE targets. Module libraries are always treated as LIBRARY targets. For non-DLL platforms shared libraries are treated as LIBRARY targets, except that those marked with the FRAMEWORK property are treated as FRAMEWORK targets on OS X. For DLL platforms the DLL part of a shared library is treated as a RUNTIME target and the corresponding import library is treated as an ARCHIVE target. All Windows-based systems including Cygwin are DLL platforms. The ARCHIVE, LIBRARY, RUNTIME, and FRAMEWORK arguments change the type of target to which the subsequent properties apply. If none is given the installation properties apply to all target types. If only one is given then only targets of that type will be installed (which can be used to install just a DLL or just an import library).

    +

    The PRIVATE_HEADER, PUBLIC_HEADER, and RESOURCE arguments cause subsequent properties to be applied to installing a FRAMEWORK shared library target's associated files on non-Apple platforms. Rules defined by these arguments are ignored on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See documentation of the PRIVATE_HEADER, PUBLIC_HEADER, and RESOURCE target properties for details.

    +

    Either NAMELINK_ONLY or NAMELINK_SKIP may be specified as a LIBRARY option. On some platforms a versioned shared library has a symbolic link such as

    +
      lib<name>.so -> lib<name>.so.1
    +

    where "lib<name>.so.1" is the soname of the library and "lib<name>.so" is a "namelink" allowing linkers to find the library when given "-l<name>". The NAMELINK_ONLY option causes installation of only the namelink when a library target is installed. The NAMELINK_SKIP option causes installation of library files other than the namelink when a library target is installed. When neither option is given both portions are installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned the NAMELINK_SKIP option installs the library and the NAMELINK_ONLY option installs nothing. See the VERSION and SOVERSION target properties for details on creating versioned shared libraries.

    +

    One or more groups of properties may be specified in a single call to the TARGETS form of this command. A target may be installed more than once to different locations. Consider hypothetical targets "myExe", "mySharedLib", and "myStaticLib". The code

    +
        install(TARGETS myExe mySharedLib myStaticLib
    RUNTIME DESTINATION bin
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib/static)
    install(TARGETS mySharedLib DESTINATION /some/full/path)
    +

    will install myExe to <prefix>/bin and myStaticLib to <prefix>/lib/static. On non-DLL platforms mySharedLib will be installed to <prefix>/lib and /some/full/path. On DLL platforms the mySharedLib DLL will be installed to <prefix>/bin and /some/full/path and its import library will be installed to <prefix>/lib/static and /some/full/path. On non-DLL platforms mySharedLib will be installed to <prefix>/lib and /some/full/path.

    +

    The EXPORT option associates the installed target files with an export called <export-name>. It must appear before any RUNTIME, LIBRARY, or ARCHIVE options. To actually install the export file itself, call install(EXPORT). See documentation of the install(EXPORT ...) signature below for details.

    +

    Installing a target with EXCLUDE_FROM_ALL set to true has undefined behavior.

    +

    The FILES signature:

    +
      install(FILES files... DESTINATION <dir>
    [PERMISSIONS permissions...]
    [CONFIGURATIONS [Debug|Release|...]]
    [COMPONENT <component>]
    [RENAME <name>] [OPTIONAL])
    +

    The FILES form specifies rules for installing files for a project. File names given as relative paths are interpreted with respect to the current source directory. Files installed by this form are by default given permissions OWNER_WRITE, OWNER_READ, GROUP_READ, and WORLD_READ if no PERMISSIONS argument is given.

    +

    The PROGRAMS signature:

    +
      install(PROGRAMS files... DESTINATION <dir>
    [PERMISSIONS permissions...]
    [CONFIGURATIONS [Debug|Release|...]]
    [COMPONENT <component>]
    [RENAME <name>] [OPTIONAL])
    +

    The PROGRAMS form is identical to the FILES form except that the default permissions for the installed file also include OWNER_EXECUTE, GROUP_EXECUTE, and WORLD_EXECUTE. This form is intended to install programs that are not targets, such as shell scripts. Use the TARGETS form to install targets built within the project.

    +

    The DIRECTORY signature:

    +
      install(DIRECTORY dirs... DESTINATION <dir>
    [FILE_PERMISSIONS permissions...]
    [DIRECTORY_PERMISSIONS permissions...]
    [USE_SOURCE_PERMISSIONS] [OPTIONAL]
    [CONFIGURATIONS [Debug|Release|...]]
    [COMPONENT <component>] [FILES_MATCHING]
    [[PATTERN <pattern> | REGEX <regex>]
    [EXCLUDE] [PERMISSIONS permissions...]] [...])
    +

    The DIRECTORY form installs contents of one or more directories to a given destination. The directory structure is copied verbatim to the destination. The last component of each directory name is appended to the destination directory but a trailing slash may be used to avoid this because it leaves the last component empty. Directory names given as relative paths are interpreted with respect to the current source directory. If no input directory names are given the destination directory will be created but nothing will be installed into it. The FILE_PERMISSIONS and DIRECTORY_PERMISSIONS options specify permissions given to files and directories in the destination. If USE_SOURCE_PERMISSIONS is specified and FILE_PERMISSIONS is not, file permissions will be copied from the source directory structure. If no permissions are specified files will be given the default permissions specified in the FILES form of the command, and the directories will be given the default permissions specified in the PROGRAMS form of the command.

    +

    Installation of directories may be controlled with fine granularity using the PATTERN or REGEX options. These "match" options specify a globbing pattern or regular expression to match directories or files encountered within input directories. They may be used to apply certain options (see below) to a subset of the files and directories encountered. The full path to each input file or directory (with forward slashes) is matched against the expression. A PATTERN will match only complete file names: the portion of the full path matching the pattern must occur at the end of the file name and be preceded by a slash. A REGEX will match any portion of the full path but it may use '/' and '$' to simulate the PATTERN behavior. By default all files and directories are installed whether or not they are matched. The FILES_MATCHING option may be given before the first match option to disable installation of files (but not directories) not matched by any expression. For example, the code

    +
      install(DIRECTORY src/ DESTINATION include/myproj
    FILES_MATCHING PATTERN "*.h")
    +

    will extract and install header files from a source tree.

    +

    Some options may follow a PATTERN or REGEX expression and are applied only to files or directories matching them. The EXCLUDE option will skip the matched file or directory. The PERMISSIONS option overrides the permissions setting for the matched file or directory. For example the code

    +
      install(DIRECTORY icons scripts/ DESTINATION share/myproj
    PATTERN "CVS" EXCLUDE
    PATTERN "scripts/*"
    PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
    GROUP_EXECUTE GROUP_READ)
    +

    will install the icons directory to share/myproj/icons and the scripts directory to share/myproj. The icons will get default file permissions, the scripts will be given specific permissions, and any CVS directories will be excluded.

    +

    The SCRIPT and CODE signature:

    +
      install([[SCRIPT <file>] [CODE <code>]] [...])
    +

    The SCRIPT form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The CODE form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string. For example, the code

    +
      install(CODE "MESSAGE(\"Sample install message.\")")
    +

    will print a message during installation.

    +

    The EXPORT signature:

    +
      install(EXPORT <export-name> DESTINATION <dir>
    [NAMESPACE <namespace>] [FILE <name>.cmake]
    [PERMISSIONS permissions...]
    [CONFIGURATIONS [Debug|Release|...]]
    [COMPONENT <component>])
    +

    The EXPORT form generates and installs a CMake file containing code to import targets from the installation tree into another project. Target installations are associated with the export <export-name> using the EXPORT option of the install(TARGETS ...) signature documented above. The NAMESPACE option will prepend <namespace> to the target names as they are written to the import file. By default the generated file will be called <export-name>.cmake but the FILE option may be used to specify a different name. The value given to the FILE option must be a file name with the ".cmake" extension. If a CONFIGURATIONS option is given then the file will only be installed when one of the named configurations is installed. Additionally, the generated import file will reference only the matching target configurations. If a COMPONENT option is specified that does not match that given to the targets associated with <export-name> the behavior is undefined. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.

    +

    The EXPORT form is useful to help outside projects use targets built and installed by the current project. For example, the code

    +
      install(TARGETS myexe EXPORT myproj DESTINATION bin)
    install(EXPORT myproj NAMESPACE mp_ DESTINATION lib/myproj)
    +

    will install the executable myexe to <prefix>/bin and code to import it in the file "<prefix>/lib/myproj/myproj.cmake". An outside project may load this file with the include command and reference the myexe executable from the installation tree using the imported target name mp_myexe as if the target were built in its own tree.

    +

    NOTE: This command supercedes the INSTALL_TARGETS command and the target properties PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT. It also replaces the FILES forms of the INSTALL_FILES and INSTALL_PROGRAMS commands. The processing order of these install rules relative to those generated by INSTALL_TARGETS, INSTALL_FILES, and INSTALL_PROGRAMS commands is not defined.

    + +
  • +
  • + link_directories: Specify directories in which the linker will look for libraries.
    +
      link_directories(directory1 directory2 ...)
    +

    Specify the paths in which the linker should search for libraries. The command will apply only to targets created after it is called. For historical reasons, relative paths given to this command are passed to the linker unchanged (unlike many CMake commands which interpret them relative to the current source directory).

    +

    Note that this command is rarely necessary. Library locations returned by find_package() and find_library() are absolute paths. Pass these absolute library file paths directly to the target_link_libraries() command. CMake will ensure the linker finds them.

    + +
  • +
  • + list: List operations.
    +
      list(LENGTH <list> <output variable>)
    list(GET <list> <element index> [<element index> ...]
    <output variable>)
    list(APPEND <list> <element> [<element> ...])
    list(FIND <list> <value> <output variable>)
    list(INSERT <list> <element_index> <element> [<element> ...])
    list(REMOVE_ITEM <list> <value> [<value> ...])
    list(REMOVE_AT <list> <index> [<index> ...])
    list(REMOVE_DUPLICATES <list>)
    list(REVERSE <list>)
    list(SORT <list>)
    +

    LENGTH will return a given list's length.

    +

    GET will return list of elements specified by indices from the list.

    +

    APPEND will append elements to the list.

    +

    FIND will return the index of the element specified in the list or -1 if it wasn't found.

    +

    INSERT will insert elements to the list to the specified location.

    +

    REMOVE_AT and REMOVE_ITEM will remove items from the list. The difference is that REMOVE_ITEM will remove the given items, while REMOVE_AT will remove the items at the given indices.

    +

    REMOVE_DUPLICATES will remove duplicated items in the list.

    +

    REVERSE reverses the contents of the list in-place.

    +

    SORT sorts the list in-place alphabetically.

    +

    The list subcommands APPEND, INSERT, REMOVE_AT, REMOVE_ITEM, REMOVE_DUPLICATES, REVERSE and SORT may create new values for the list within the current CMake variable scope. Similar to the SET command, the LIST command creates new variable values in the current scope, even if the list itself is actually defined in a parent scope. To propagate the results of these operations upwards, use SET with PARENT_SCOPE, SET with CACHE INTERNAL, or some other means of value propagation.

    +

    NOTES: A list in cmake is a ; separated group of strings. To create a list the set command can be used. For example, set(var a b c d e) creates a list with a;b;c;d;e, and set(var "a b c d e") creates a string or a list with one item in it.

    +

    When specifying index values, if <element index> is 0 or greater, it is indexed from the beginning of the list, with 0 representing the first list element. If <element index> is -1 or lesser, it is indexed from the end of the list, with -1 representing the last list element. Be careful when counting with negative indices: they do not start from 0. -0 is equivalent to 0, the first list element.

    + +
  • +
  • + load_cache: Load in the values from another project's CMake cache.
    +
      load_cache(pathToCacheFile READ_WITH_PREFIX
    prefix entry1...)
    +

    Read the cache and store the requested entries in variables with their name prefixed with the given prefix. This only reads the values, and does not create entries in the local project's cache.

    +
      load_cache(pathToCacheFile [EXCLUDE entry1...]
    [INCLUDE_INTERNALS entry1...])
    +

    Load in the values from another cache and store them in the local project's cache as internal entries. This is useful for a project that depends on another project built in a different tree. EXCLUDE option can be used to provide a list of entries to be excluded. INCLUDE_INTERNALS can be used to provide a list of internal entries to be included. Normally, no internal entries are brought in. Use of this form of the command is strongly discouraged, but it is provided for backward compatibility.

    + +
  • +
  • + load_command: Load a command into a running CMake.
    +
      load_command(COMMAND_NAME <loc1> [loc2 ...])
    +

    The given locations are searched for a library whose name is cmCOMMAND_NAME. If found, it is loaded as a module and the command is added to the set of available CMake commands. Usually, TRY_COMPILE is used before this command to compile the module. If the command is successfully loaded a variable named

    +
      CMAKE_LOADED_COMMAND_<COMMAND_NAME>
    +

    will be set to the full path of the module that was loaded. Otherwise the variable will not be set.

    + +
  • +
  • + macro: Start recording a macro for later invocation as a command.
    +
      macro(<name> [arg1 [arg2 [arg3 ...]]])
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    endmacro(<name>)
    +

    Define a macro named <name> that takes arguments named arg1 arg2 arg3 (...). Commands listed after macro, but before the matching endmacro, are not invoked until the macro is invoked. When it is invoked, the commands recorded in the macro are first modified by replacing formal parameters (${arg1}) with the arguments passed, and then invoked as normal commands. In addition to referencing the formal parameters you can reference the values ${ARGC} which will be set to the number of arguments passed into the function as well as ${ARGV0} ${ARGV1} ${ARGV2} ... which will have the actual values of the arguments passed in. This facilitates creating macros with optional arguments. Additionally ${ARGV} holds the list of all arguments given to the macro and ${ARGN} holds the list of argument past the last expected argument. Note that the parameters to a macro and values such as ARGN are not variables in the usual CMake sense. They are string replacements much like the c preprocessor would do with a macro. If you want true CMake variables you should look at the function command.

    +

    See the cmake_policy() command documentation for the behavior of policies inside macros.

    + +
  • +
  • + mark_as_advanced: Mark cmake cached variables as advanced.
    +
      mark_as_advanced([CLEAR|FORCE] VAR VAR2 VAR...)
    +

    Mark the named cached variables as advanced. An advanced variable will not be displayed in any of the cmake GUIs unless the show advanced option is on. If CLEAR is the first argument advanced variables are changed back to unadvanced. If FORCE is the first argument, then the variable is made advanced. If neither FORCE nor CLEAR is specified, new values will be marked as advanced, but if the variable already has an advanced/non-advanced state, it will not be changed.

    +

    It does nothing in script mode.

    + +
  • +
  • + math: Mathematical expressions.
    +
      math(EXPR <output variable> <math expression>)
    +

    EXPR evaluates mathematical expression and return result in the output variable. Example mathematical expression is '5 * ( 10 + 13 )'. Supported operators are + - * / % | & ^ ~ << >> * / %. They have the same meaning as they do in c code.

    + +
  • +
  • + message: Display a message to the user.
    +
      message([STATUS|WARNING|AUTHOR_WARNING|FATAL_ERROR|SEND_ERROR]
    "message to display" ...)
    +

    The optional keyword determines the type of message:

    +
      (none)         = Important information
    STATUS = Incidental information
    WARNING = CMake Warning, continue processing
    AUTHOR_WARNING = CMake Warning (dev), continue processing
    SEND_ERROR = CMake Error, continue but skip generation
    FATAL_ERROR = CMake Error, stop all processing
    +

    The CMake command-line tool displays STATUS messages on stdout and all other message types on stderr. The CMake GUI displays all messages in its log area. The interactive dialogs (ccmake and CMakeSetup) show STATUS messages one at a time on a status line and other messages in interactive pop-up boxes.

    +

    CMake Warning and Error message text displays using a simple markup language. Non-indented text is formatted in line-wrapped paragraphs delimited by newlines. Indented text is considered pre-formatted.

    + +
  • +
  • + option: Provides an option that the user can optionally select.
    +
      option(<option_variable> "help string describing option"
    [initial value])
    +

    Provide an option for the user to select as ON or OFF. If no initial value is provided, OFF is used.

    +

    If you have options that depend on the values of other options, see the module help for CMakeDependentOption.

    + +
  • +
  • + project: Set a name for the entire project.
    +
      project(<projectname> [languageName1 languageName2 ... ] )
    +

    Sets the name of the project. Additionally this sets the variables <projectName>_BINARY_DIR and <projectName>_SOURCE_DIR to the respective values.

    +

    Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled.

    + +
  • +
  • + qt_wrap_cpp: Create Qt Wrappers.
    +
      qt_wrap_cpp(resultingLibraryName DestName
    SourceLists ...)
    +

    Produce moc files for all the .h files listed in the SourceLists. The moc files will be added to the library using the DestName source list.

    + +
  • +
  • + qt_wrap_ui: Create Qt user interfaces Wrappers.
    +
      qt_wrap_ui(resultingLibraryName HeadersDestName
    SourcesDestName SourceLists ...)
    +

    Produce .h and .cxx files for all the .ui files listed in the SourceLists. The .h files will be added to the library using the HeadersDestNamesource list. The .cxx files will be added to the library using the SourcesDestNamesource list.

    + +
  • +
  • + remove_definitions: Removes -D define flags added by add_definitions.
    +
      remove_definitions(-DFOO -DBAR ...)
    +

    Removes flags (added by add_definitions) from the compiler command line for sources in the current directory and below.

    + +
  • +
  • + return: Return from a file, directory or function.
    +
      return()
    +

    Returns from a file, directory or function. When this command is encountered in an included file (via include() or find_package()), it causes processing of the current file to stop and control is returned to the including file. If it is encountered in a file which is not included by another file, e.g. a CMakeLists.txt, control is returned to the parent directory if there is one. If return is called in a function, control is returned to the caller of the function. Note that a macro is not a function and does not handle return like a function does.

    + +
  • +
  • + separate_arguments: Parse space-separated arguments into a semicolon-separated list.
    +
      separate_arguments(<var> <UNIX|WINDOWS>_COMMAND "<args>")
    +

    Parses a unix- or windows-style command-line string "<args>" and stores a semicolon-separated list of the arguments in <var>. The entire command line must be given in one "<args>" argument.

    +

    The UNIX_COMMAND mode separates arguments by unquoted whitespace. It recognizes both single-quote and double-quote pairs. A backslash escapes the next literal character (\" is "); there are no special escapes (\n is just n).

    +

    The WINDOWS_COMMAND mode parses a windows command-line using the same syntax the runtime library uses to construct argv at startup. It separates arguments by whitespace that is not double-quoted. Backslashes are literal unless they precede double-quotes. See the MSDN article "Parsing C Command-Line Arguments" for details.

    +
      separate_arguments(VARIABLE)
    +

    Convert the value of VARIABLE to a semi-colon separated list. All spaces are replaced with ';'. This helps with generating command lines.

    + +
  • +
  • + set: Set a CMAKE variable to a given value.
    +
      set(<variable> <value>
    [[CACHE <type> <docstring> [FORCE]] | PARENT_SCOPE])
    +

    Within CMake sets <variable> to the value <value>. <value> is expanded before <variable> is set to it. If CACHE is present, then the <variable> is put in the cache. <type> and <docstring> are then required. <type> is used by the CMake GUI to choose a widget with which the user sets a value. The value for <type> may be one of

    +
      FILEPATH = File chooser dialog.
    PATH = Directory chooser dialog.
    STRING = Arbitrary string.
    BOOL = Boolean ON/OFF checkbox.
    INTERNAL = No GUI entry (used for persistent variables).
    +

    If <type> is INTERNAL, then the <value> is always written into the cache, replacing any values existing in the cache. If it is not a cache variable, then this always writes into the current makefile. The FORCE option will overwrite the cache value removing any changes by the user.

    +

    If PARENT_SCOPE is present, the variable will be set in the scope above the current scope. Each new directory or function creates a new scope. This command will set the value of a variable into the parent directory or calling function (whichever is applicable to the case at hand).

    +

    If <value> is not specified then the variable is removed instead of set. See also: the unset() command.

    +
      set(<variable> <value1> ... <valueN>)
    +

    In this case <variable> is set to a semicolon separated list of values.

    +

    <variable> can be an environment variable such as:

    +
      set( ENV{PATH} /home/martink )
    +

    in which case the environment variable will be set.

    + +
  • +
  • + set_directory_properties: Set a property of the directory.
    +
      set_directory_properties(PROPERTIES prop1 value1 prop2 value2)
    +

    Set a property for the current directory and subdirectories. If the property is not found, CMake will report an error. The properties include: INCLUDE_DIRECTORIES, LINK_DIRECTORIES, INCLUDE_REGULAR_EXPRESSION, and ADDITIONAL_MAKE_CLEAN_FILES. ADDITIONAL_MAKE_CLEAN_FILES is a list of files that will be cleaned as a part of "make clean" stage.

    + +
  • +
  • + set_property: Set a named property in a given scope.
    +
      set_property(<GLOBAL                            |
    DIRECTORY [dir] |
    TARGET [target1 [target2 ...]] |
    SOURCE [src1 [src2 ...]] |
    TEST [test1 [test2 ...]] |
    CACHE [entry1 [entry2 ...]]>
    [APPEND] [APPEND_STRING]
    PROPERTY <name> [value1 [value2 ...]])
    +

    Set one property on zero or more objects of a scope. The first argument determines the scope in which the property is set. It must be one of the following:

    +

    GLOBAL scope is unique and does not accept a name.

    +

    DIRECTORY scope defaults to the current directory but another directory (already processed by CMake) may be named by full or relative path.

    +

    TARGET scope may name zero or more existing targets.

    +

    SOURCE scope may name zero or more source files. Note that source file properties are visible only to targets added in the same directory (CMakeLists.txt).

    +

    TEST scope may name zero or more existing tests.

    +

    CACHE scope must name zero or more cache existing entries.

    +

    The required PROPERTY option is immediately followed by the name of the property to set. Remaining arguments are used to compose the property value in the form of a semicolon-separated list. If the APPEND option is given the list is appended to any existing property value.If the APPEND_STRING option is given the string is append to any existing property value as string, i.e. it results in a longer string and not a list of strings.

    + +
  • +
  • + set_source_files_properties: Source files can have properties that affect how they are built.
    +
      set_source_files_properties([file1 [file2 [...]]]
    PROPERTIES prop1 value1
    [prop2 value2 [...]])
    +

    Set properties associated with source files using a key/value paired list. See properties documentation for those known to CMake. Unrecognized properties are ignored. Source file properties are visible only to targets added in the same directory (CMakeLists.txt).

    + +
  • +
  • + set_target_properties: Targets can have properties that affect how they are built.
    +
      set_target_properties(target1 target2 ...
    PROPERTIES prop1 value1
    prop2 value2 ...)
    +

    Set properties on a target. The syntax for the command is to list all the files you want to change, and then provide the values you want to set next. You can use any prop value pair you want and extract it later with the GET_TARGET_PROPERTY command.

    +

    Properties that affect the name of a target's output file are as follows. The PREFIX and SUFFIX properties override the default target name prefix (such as "lib") and suffix (such as ".so"). IMPORT_PREFIX and IMPORT_SUFFIX are the equivalent properties for the import library corresponding to a DLL (for SHARED library targets). OUTPUT_NAME sets the real name of a target when it is built and can be used to help create two targets of the same name even though CMake requires unique logical target names. There is also a <CONFIG>_OUTPUT_NAME that can set the output name on a per-configuration basis. <CONFIG>_POSTFIX sets a postfix for the real name of the target when it is built under the configuration named by <CONFIG> (in upper-case, such as "DEBUG_POSTFIX"). The value of this property is initialized when the target is created to the value of the variable CMAKE_<CONFIG>_POSTFIX (except for executable targets because earlier CMake versions which did not use this variable for executables).

    +

    The LINK_FLAGS property can be used to add extra flags to the link step of a target. LINK_FLAGS_<CONFIG> will add to the configuration <CONFIG>, for example, DEBUG, RELEASE, MINSIZEREL, RELWITHDEBINFO. DEFINE_SYMBOL sets the name of the preprocessor symbol defined when compiling sources in a shared library. If not set here then it is set to target_EXPORTS by default (with some substitutions if the target is not a valid C identifier). This is useful for headers to know whether they are being included from inside their library or outside to properly setup dllexport/dllimport decorations. The COMPILE_FLAGS property sets additional compiler flags used to build sources within the target. It may also be used to pass additional preprocessor definitions.

    +

    The LINKER_LANGUAGE property is used to change the tool used to link an executable or shared library. The default is set the language to match the files in the library. CXX and C are common values for this property.

    +

    For shared libraries VERSION and SOVERSION can be used to specify the build version and api version respectively. When building or installing appropriate symlinks are created if the platform supports symlinks and the linker supports so-names. If only one of both is specified the missing is assumed to have the same version number. For executables VERSION can be used to specify the build version. When building or installing appropriate symlinks are created if the platform supports symlinks. For shared libraries and executables on Windows the VERSION attribute is parsed to extract a "major.minor" version number. These numbers are used as the image version of the binary.

    +

    There are a few properties used to specify RPATH rules. INSTALL_RPATH is a semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it). INSTALL_RPATH_USE_LINK_PATH is a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL_RPATH. SKIP_BUILD_RPATH is a boolean specifying whether to skip automatic generation of an rpath allowing the target to run from the build tree. BUILD_WITH_INSTALL_RPATH is a boolean specifying whether to link the target in the build tree with the INSTALL_RPATH. This takes precedence over SKIP_BUILD_RPATH and avoids the need for relinking before installation. INSTALL_NAME_DIR is a string specifying the directory portion of the "install_name" field of shared libraries on Mac OSX to use in the installed targets. When the target is created the values of the variables CMAKE_INSTALL_RPATH, CMAKE_INSTALL_RPATH_USE_LINK_PATH, CMAKE_SKIP_BUILD_RPATH, CMAKE_BUILD_WITH_INSTALL_RPATH, and CMAKE_INSTALL_NAME_DIR are used to initialize these properties.

    +

    PROJECT_LABEL can be used to change the name of the target in an IDE like visual studio. VS_KEYWORD can be set to change the visual studio keyword, for example QT integration works better if this is set to Qt4VSv1.0.

    +

    VS_SCC_PROJECTNAME, VS_SCC_LOCALPATH, VS_SCC_PROVIDER and VS_SCC_AUXPATH can be set to add support for source control bindings in a Visual Studio project file.

    +

    VS_GLOBAL_<variable> can be set to add a Visual Studio project-specific global variable. Qt integration works better if VS_GLOBAL_QtVersion is set to the Qt version FindQt4.cmake found. For example, "4.7.3"

    +

    The PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT properties are the old way to specify CMake scripts to run before and after installing a target. They are used only when the old INSTALL_TARGETS command is used to install the target. Use the INSTALL command instead.

    +

    The EXCLUDE_FROM_DEFAULT_BUILD property is used by the visual studio generators. If it is set to 1 the target will not be part of the default build when you select "Build Solution".

    + +
  • +
  • + set_tests_properties: Set a property of the tests.
    +
      set_tests_properties(test1 [test2...] PROPERTIES prop1 value1 prop2 value2)
    +

    Set a property for the tests. If the property is not found, CMake will report an error. The properties include:

    +

    WILL_FAIL: If set to true, this will invert the pass/fail flag of the test.

    +

    PASS_REGULAR_EXPRESSION: If set, the test output will be checked against the specified regular expressions and at least one of the regular expressions has to match, otherwise the test will fail.

    +
      Example: PASS_REGULAR_EXPRESSION "TestPassed;All ok"
    +

    FAIL_REGULAR_EXPRESSION: If set, if the output will match to one of specified regular expressions, the test will fail.

    +
      Example: PASS_REGULAR_EXPRESSION "[^a-z]Error;ERROR;Failed"
    +

    Both PASS_REGULAR_EXPRESSION and FAIL_REGULAR_EXPRESSION expect a list of regular expressions.

    +

    TIMEOUT: Setting this will limit the test runtime to the number of seconds specified.

    + +
  • +
  • + site_name: Set the given variable to the name of the computer.
    +
      site_name(variable)
    + +
  • +
  • + source_group: Define a grouping for sources in the makefile.
    +
      source_group(name [REGULAR_EXPRESSION regex] [FILES src1 src2 ...])
    +

    Defines a group into which sources will be placed in project files. This is mainly used to setup file tabs in Visual Studio. Any file whose name is listed or matches the regular expression will be placed in this group. If a file matches multiple groups, the LAST group that explicitly lists the file will be favored, if any. If no group explicitly lists the file, the LAST group whose regular expression matches the file will be favored.

    +

    The name of the group may contain backslashes to specify subgroups:

    +
      source_group(outer\\inner ...)
    +

    For backwards compatibility, this command is also supports the format:

    +
      source_group(name regex)
    + +
  • +
  • + string: String operations.
    +
      string(REGEX MATCH <regular_expression>
    <output variable> <input> [<input>...])
    string(REGEX MATCHALL <regular_expression>
    <output variable> <input> [<input>...])
    string(REGEX REPLACE <regular_expression>
    <replace_expression> <output variable>
    <input> [<input>...])
    string(REPLACE <match_string>
    <replace_string> <output variable>
    <input> [<input>...])
    string(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512>
    <output variable> <input>)
    string(COMPARE EQUAL <string1> <string2> <output variable>)
    string(COMPARE NOTEQUAL <string1> <string2> <output variable>)
    string(COMPARE LESS <string1> <string2> <output variable>)
    string(COMPARE GREATER <string1> <string2> <output variable>)
    string(ASCII <number> [<number> ...] <output variable>)
    string(CONFIGURE <string1> <output variable>
    [@ONLY] [ESCAPE_QUOTES])
    string(TOUPPER <string1> <output variable>)
    string(TOLOWER <string1> <output variable>)
    string(LENGTH <string> <output variable>)
    string(SUBSTRING <string> <begin> <length> <output variable>)
    string(STRIP <string> <output variable>)
    string(RANDOM [LENGTH <length>] [ALPHABET <alphabet>]
    [RANDOM_SEED <seed>] <output variable>)
    string(FIND <string> <substring> <output variable> [REVERSE])
    +

    REGEX MATCH will match the regular expression once and store the match in the output variable.

    +

    REGEX MATCHALL will match the regular expression as many times as possible and store the matches in the output variable as a list.

    +

    REGEX REPLACE will match the regular expression as many times as possible and substitute the replacement expression for the match in the output. The replace expression may refer to paren-delimited subexpressions of the match using \1, \2, ..., \9. Note that two backslashes (\\1) are required in CMake code to get a backslash through argument parsing.

    +

    REPLACE will replace all occurrences of match_string in the input with replace_string and store the result in the output.

    +

    MD5, SHA1, SHA224, SHA256, SHA384, and SHA512 will compute a cryptographic hash of the input string.

    +

    COMPARE EQUAL/NOTEQUAL/LESS/GREATER will compare the strings and store true or false in the output variable.

    +

    ASCII will convert all numbers into corresponding ASCII characters.

    +

    CONFIGURE will transform a string like CONFIGURE_FILE transforms a file.

    +

    TOUPPER/TOLOWER will convert string to upper/lower characters.

    +

    LENGTH will return a given string's length.

    +

    SUBSTRING will return a substring of a given string. If length is -1 the remainder of the string starting at begin will be returned.

    +

    STRIP will return a substring of a given string with leading and trailing spaces removed.

    +

    RANDOM will return a random string of given length consisting of characters from the given alphabet. Default length is 5 characters and default alphabet is all numbers and upper and lower case letters. If an integer RANDOM_SEED is given, its value will be used to seed the random number generator.

    +

    FIND will return the position where the given substring was found in the supplied string. If the REVERSE flag was used, the command will search for the position of the last occurrence of the specified substring.

    +

    The following characters have special meaning in regular expressions:

    +
       ^         Matches at beginning of a line
    $ Matches at end of a line
    . Matches any single character
    [ ] Matches any character(s) inside the brackets
    [^ ] Matches any character(s) not inside the brackets
    - Matches any character in range on either side of a dash
    * Matches preceding pattern zero or more times
    + Matches preceding pattern one or more times
    ? Matches preceding pattern zero or once only
    | Matches a pattern on either side of the |
    () Saves a matched subexpression, which can be referenced
    in the REGEX REPLACE operation. Additionally it is saved
    by all regular expression-related commands, including
    e.g. if( MATCHES ), in the variables CMAKE_MATCH_(0..9).
    + +
  • +
  • + target_link_libraries: Link a target to given libraries.
    +
      target_link_libraries(<target> [item1 [item2 [...]]]
    [[debug|optimized|general] <item>] ...)
    +

    Specify libraries or flags to use when linking a given target. The named <target> must have been created in the current directory by a command such as add_executable or add_library. The remaining arguments specify library names or flags.

    +

    If a library name matches that of another target in the project a dependency will automatically be added in the build system to make sure the library being linked is up-to-date before the target links. Item names starting with '-', but not '-l' or '-framework', are treated as linker flags.

    +

    A "debug", "optimized", or "general" keyword indicates that the library immediately following it is to be used only for the corresponding build configuration. The "debug" keyword corresponds to the Debug configuration (or to configurations named in the DEBUG_CONFIGURATIONS global property if it is set). The "optimized" keyword corresponds to all other configurations. The "general" keyword corresponds to all configurations, and is purely optional (assumed if omitted). Higher granularity may be achieved for per-configuration rules by creating and linking to IMPORTED library targets. See the IMPORTED mode of the add_library command for more information.

    +

    Library dependencies are transitive by default. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too. See the LINK_INTERFACE_LIBRARIES target property to override the set of transitive link dependencies for a target.

    +
      target_link_libraries(<target> LINK_INTERFACE_LIBRARIES
    [[debug|optimized|general] <lib>] ...)
    +

    The LINK_INTERFACE_LIBRARIES mode appends the libraries to the LINK_INTERFACE_LIBRARIES and its per-configuration equivalent target properties instead of using them for linking. Libraries specified as "debug" are appended to the the LINK_INTERFACE_LIBRARIES_DEBUG property (or to the properties corresponding to configurations listed in the DEBUG_CONFIGURATIONS global property if it is set). Libraries specified as "optimized" are appended to the the LINK_INTERFACE_LIBRARIES property. Libraries specified as "general" (or without any keyword) are treated as if specified for both "debug" and "optimized".

    +
      target_link_libraries(<target>
    <LINK_PRIVATE|LINK_PUBLIC>
    [[debug|optimized|general] <lib>] ...
    [<LINK_PRIVATE|LINK_PUBLIC>
    [[debug|optimized|general] <lib>] ...])
    +

    The LINK_PUBLIC and LINK_PRIVATE modes can be used to specify both the link dependencies and the link interface in one command. Libraries and targets following LINK_PUBLIC are linked to, and are made part of the LINK_INTERFACE_LIBRARIES. Libraries and targets following LINK_PRIVATE are linked to, but are not made part of the LINK_INTERFACE_LIBRARIES.

    +

    The library dependency graph is normally acyclic (a DAG), but in the case of mutually-dependent STATIC libraries CMake allows the graph to contain cycles (strongly connected components). When another target links to one of the libraries CMake repeats the entire connected component. For example, the code

    +
      add_library(A STATIC a.c)
    add_library(B STATIC b.c)
    target_link_libraries(A B)
    target_link_libraries(B A)
    add_executable(main main.c)
    target_link_libraries(main A)
    +

    links 'main' to 'A B A B'. (While one repetition is usually sufficient, pathological object file and symbol arrangements can require more. One may handle such cases by manually repeating the component in the last target_link_libraries call. However, if two archives are really so interdependent they should probably be combined into a single archive.)

    + +
  • +
  • + try_compile: Try building some code.
    +
      try_compile(RESULT_VAR <bindir> <srcdir>
    <projectName> [targetName] [CMAKE_FLAGS flags...]
    [OUTPUT_VARIABLE <var>])
    +

    Try building a project. In this form, srcdir should contain a complete CMake project with a CMakeLists.txt file and all sources. The bindir and srcdir will not be deleted after this command is run. Specify targetName to build a specific target instead of the 'all' or 'ALL_BUILD' target.

    +
      try_compile(RESULT_VAR <bindir> <srcfile>
    [CMAKE_FLAGS flags...]
    [COMPILE_DEFINITIONS flags...]
    [OUTPUT_VARIABLE <var>]
    [COPY_FILE <fileName>])
    +

    Try building a source file into an executable. In this form the user need only supply a source file that defines a 'main'. CMake will create a CMakeLists.txt file to build the source as an executable. Specify COPY_FILE to get a copy of the linked executable at the given fileName.

    +

    In this version all files in bindir/CMakeFiles/CMakeTmp will be cleaned automatically. For debugging, --debug-trycompile can be passed to cmake to avoid this clean. However, multiple sequential try_compile operations reuse this single output directory. If you use --debug-trycompile, you can only debug one try_compile call at a time. The recommended procedure is to configure with cmake all the way through once, then delete the cache entry associated with the try_compile call of interest, and then re-run cmake again with --debug-trycompile.

    +

    Some extra flags that can be included are, INCLUDE_DIRECTORIES, LINK_DIRECTORIES, and LINK_LIBRARIES. COMPILE_DEFINITIONS are -Ddefinition that will be passed to the compile line. try_compile creates a CMakeList.txt file on the fly that looks like this:

    +
      add_definitions( <expanded COMPILE_DEFINITIONS from calling cmake>)
    include_directories(${INCLUDE_DIRECTORIES})
    link_directories(${LINK_DIRECTORIES})
    add_executable(cmTryCompileExec sources)
    target_link_libraries(cmTryCompileExec ${LINK_LIBRARIES})
    +

    In both versions of the command, if OUTPUT_VARIABLE is specified, then the output from the build process is stored in the given variable. The success or failure of the try_compile, i.e. TRUE or FALSE respectively, is returned in RESULT_VAR. CMAKE_FLAGS can be used to pass -DVAR:TYPE=VALUE flags to the cmake that is run during the build. Set variable CMAKE_TRY_COMPILE_CONFIGURATION to choose a build configuration.

    + +
  • +
  • + try_run: Try compiling and then running some code.
    +
      try_run(RUN_RESULT_VAR COMPILE_RESULT_VAR
    bindir srcfile [CMAKE_FLAGS <Flags>]
    [COMPILE_DEFINITIONS <flags>]
    [COMPILE_OUTPUT_VARIABLE comp]
    [RUN_OUTPUT_VARIABLE run]
    [OUTPUT_VARIABLE var]
    [ARGS <arg1> <arg2>...])
    +

    Try compiling a srcfile. Return TRUE or FALSE for success or failure in COMPILE_RESULT_VAR. Then if the compile succeeded, run the executable and return its exit code in RUN_RESULT_VAR. If the executable was built, but failed to run, then RUN_RESULT_VAR will be set to FAILED_TO_RUN. COMPILE_OUTPUT_VARIABLE specifies the variable where the output from the compile step goes. RUN_OUTPUT_VARIABLE specifies the variable where the output from the running executable goes.

    +

    For compatibility reasons OUTPUT_VARIABLE is still supported, which gives you the output from the compile and run step combined.

    +

    Cross compiling issues

    +

    When cross compiling, the executable compiled in the first step usually cannot be run on the build host. try_run() checks the CMAKE_CROSSCOMPILING variable to detect whether CMake is in crosscompiling mode. If that's the case, it will still try to compile the executable, but it will not try to run the executable. Instead it will create cache variables which must be filled by the user or by presetting them in some CMake script file to the values the executable would have produced if it would have been run on its actual target platform. These variables are RUN_RESULT_VAR (explanation see above) and if RUN_OUTPUT_VARIABLE (or OUTPUT_VARIABLE) was used, an additional cache variable RUN_RESULT_VAR__COMPILE_RESULT_VAR__TRYRUN_OUTPUT.This is intended to hold stdout and stderr from the executable.

    +

    In order to make cross compiling your project easier, use try_run only if really required. If you use try_run, use RUN_OUTPUT_VARIABLE (or OUTPUT_VARIABLE) only if really required. Using them will require that when crosscompiling, the cache variables will have to be set manually to the output of the executable. You can also "guard" the calls to try_run with if(CMAKE_CROSSCOMPILING) and provide an easy-to-preset alternative for this case.

    +

    Set variable CMAKE_TRY_COMPILE_CONFIGURATION to choose a build configuration.

    + +
  • +
  • + unset: Unset a variable, cache variable, or environment variable.
    +
      unset(<variable> [CACHE])
    +

    Removes the specified variable causing it to become undefined. If CACHE is present then the variable is removed from the cache instead of the current scope.

    +

    <variable> can be an environment variable such as:

    +
      unset(ENV{LD_LIBRARY_PATH})
    +

    in which case the variable will be removed from the current environment.

    + +
  • +
  • + variable_watch: Watch the CMake variable for change.
    +
      variable_watch(<variable name> [<command to execute>])
    +

    If the specified variable changes, the message will be printed about the variable being changed. If the command is specified, the command will be executed. The command will receive the following arguments: COMMAND(<variable> <access> <value> <current list file> <stack>)

    + +
  • +
  • + while: Evaluate a group of commands while a condition is true
    +
      while(condition)
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
    ...
    endwhile(condition)
    +

    All commands between while and the matching endwhile are recorded without being invoked. Once the endwhile is evaluated, the recorded list of commands is invoked as long as the condition is true. The condition is evaluated using the same logic as the if command.

    + +
  • +
+

Properties

+
  CMake Properties - Properties supported by CMake, the Cross-Platform Makefile Generator.
+ +

This is the documentation for the properties supported by CMake. Properties can have different scopes. They can either be assigned to a source file, a directory, a target or globally to CMake. By modifying the values of properties the behaviour of the build system can be customized.

+ +

Properties of Global Scope

+ +
    +
  • + ALLOW_DUPLICATE_CUSTOM_TARGETS: Allow duplicate custom targets to be created.
    +

    Normally CMake requires that all targets built in a project have globally unique logical names (see policy CMP0002). This is necessary to generate meaningful project file names in Xcode and VS IDE generators. It also allows the target names to be referenced unambiguously.

    +

    Makefile generators are capable of supporting duplicate custom target names. For projects that care only about Makefile generators and do not wish to support Xcode or VS IDE generators, one may set this property to true to allow duplicate custom targets. The property allows multiple add_custom_target command calls in different directories to specify the same target name. However, setting this property will cause non-Makefile generators to produce an error and refuse to generate the project.

    + +
  • +
  • + DEBUG_CONFIGURATIONS: Specify which configurations are for debugging.
    +

    The value must be a semi-colon separated list of configuration names. Currently this property is used only by the target_link_libraries command (see its documentation for details). Additional uses may be defined in the future.

    +

    This property must be set at the top level of the project and before the first target_link_libraries command invocation. If any entry in the list does not match a valid configuration for the project the behavior is undefined.

    + +
  • +
  • + DISABLED_FEATURES: List of features which are disabled during the CMake run.
    +

    List of features which are disabled during the CMake run. Be default it contains the names of all packages which were not found. This is determined using the <NAME>_FOUND variables. Packages which are searched QUIET are not listed. A project can add its own features to this list.This property is used by the macros in FeatureSummary.cmake.

    + +
  • +
  • + ENABLED_FEATURES: List of features which are enabled during the CMake run.
    +

    List of features which are enabled during the CMake run. Be default it contains the names of all packages which were found. This is determined using the <NAME>_FOUND variables. Packages which are searched QUIET are not listed. A project can add its own features to this list.This property is used by the macros in FeatureSummary.cmake.

    + +
  • +
  • + ENABLED_LANGUAGES: Read-only property that contains the list of currently enabled languages
    +

    Set to list of currently enabled languages.

    + +
  • +
  • + FIND_LIBRARY_USE_LIB64_PATHS: Whether FIND_LIBRARY should automatically search lib64 directories.
    +

    FIND_LIBRARY_USE_LIB64_PATHS is a boolean specifying whether the FIND_LIBRARY command should automatically search the lib64 variant of directories called lib in the search path when building 64-bit binaries.

    + +
  • +
  • + FIND_LIBRARY_USE_OPENBSD_VERSIONING: Whether FIND_LIBRARY should find OpenBSD-style shared libraries.
    +

    This property is a boolean specifying whether the FIND_LIBRARY command should find shared libraries with OpenBSD-style versioned extension: ".so.<major>.<minor>". The property is set to true on OpenBSD and false on other platforms.

    + +
  • +
  • + GLOBAL_DEPENDS_DEBUG_MODE: Enable global target dependency graph debug mode.
    +

    CMake automatically analyzes the global inter-target dependency graph at the beginning of native build system generation. This property causes it to display details of its analysis to stderr.

    + +
  • +
  • + GLOBAL_DEPENDS_NO_CYCLES: Disallow global target dependency graph cycles.
    +

    CMake automatically analyzes the global inter-target dependency graph at the beginning of native build system generation. It reports an error if the dependency graph contains a cycle that does not consist of all STATIC library targets. This property tells CMake to disallow all cycles completely, even among static libraries.

    + +
  • +
  • + IN_TRY_COMPILE: Read-only property that is true during a try-compile configuration.
    +

    True when building a project inside a TRY_COMPILE or TRY_RUN command.

    + +
  • +
  • + PACKAGES_FOUND: List of packages which were found during the CMake run.
    +

    List of packages which were found during the CMake run. Whether a package has been found is determined using the <NAME>_FOUND variables.

    + +
  • +
  • + PACKAGES_NOT_FOUND: List of packages which were not found during the CMake run.
    +

    List of packages which were not found during the CMake run. Whether a package has been found is determined using the <NAME>_FOUND variables.

    + +
  • +
  • + PREDEFINED_TARGETS_FOLDER: Name of FOLDER for targets that are added automatically by CMake.
    +

    If not set, CMake uses "CMakePredefinedTargets" as a default value for this property. Targets such as INSTALL, PACKAGE and RUN_TESTS will be organized into this FOLDER. See also the documentation for the FOLDER target property.

    + +
  • +
  • + REPORT_UNDEFINED_PROPERTIES: If set, report any undefined properties to this file.
    +

    If this property is set to a filename then when CMake runs it will report any properties or variables that were accessed but not defined into the filename specified in this property.

    + +
  • +
  • + RULE_LAUNCH_COMPILE: Specify a launcher for compile rules.
    +

    Makefile generators prefix compiler commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Non-Makefile generators currently ignore this property.

    + +
  • +
  • + RULE_LAUNCH_CUSTOM: Specify a launcher for custom rules.
    +

    Makefile generators prefix custom commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Non-Makefile generators currently ignore this property.

    + +
  • +
  • + RULE_LAUNCH_LINK: Specify a launcher for link rules.
    +

    Makefile generators prefix link and archive commands with the given launcher command line. This is intended to allow launchers to intercept build problems with high granularity. Non-Makefile generators currently ignore this property.

    + +
  • +
  • + RULE_MESSAGES: Specify whether to report a message for each make rule.
    +

    This property specifies whether Makefile generators should add a progress message describing what each build rule does. If the property is not set the default is ON. Set the property to OFF to disable granular messages and report only as each target completes. This is intended to allow scripted builds to avoid the build time cost of detailed reports. If a CMAKE_RULE_MESSAGES cache entry exists its value initializes the value of this property. Non-Makefile generators currently ignore this property.

    + +
  • +
  • + TARGET_ARCHIVES_MAY_BE_SHARED_LIBS: Set if shared libraries may be named like archives.
    +

    On AIX shared libraries may be named "lib<name>.a". This property is set to true on such platforms.

    + +
  • +
  • + TARGET_SUPPORTS_SHARED_LIBS: Does the target platform support shared libraries.
    +

    TARGET_SUPPORTS_SHARED_LIBS is a boolean specifying whether the target platform supports shared libraries. Basically all current general general purpose OS do so, the exception are usually embedded systems with no or special OSs.

    + +
  • +
  • + USE_FOLDERS: Use the FOLDER target property to organize targets into folders.
    +

    If not set, CMake treats this property as OFF by default. CMake generators that are capable of organizing into a hierarchy of folders use the values of the FOLDER target property to name those folders. See also the documentation for the FOLDER target property.

    + +
  • +
  • + __CMAKE_DELETE_CACHE_CHANGE_VARS_: Internal property
    +

    Used to detect compiler changes, Do not set.

    + +
  • +
+

Properties on Directories

+ +
    +
  • + ADDITIONAL_MAKE_CLEAN_FILES: Additional files to clean during the make clean stage.
    +

    A list of files that will be cleaned as a part of the "make clean" stage.

    + +
  • +
  • + CACHE_VARIABLES: List of cache variables available in the current directory.
    +

    This read-only property specifies the list of CMake cache variables currently defined. It is intended for debugging purposes.

    + +
  • +
  • + CLEAN_NO_CUSTOM: Should the output of custom commands be left.
    +

    If this is true then the outputs of custom commands for this directory will not be removed during the "make clean" stage.

    + +
  • +
  • + COMPILE_DEFINITIONS: Preprocessor definitions for compiling a directory's sources.
    +

    The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values). This property may be set on a per-configuration basis using the name COMPILE_DEFINITIONS_<CONFIG> where <CONFIG> is an upper-case name (ex. "COMPILE_DEFINITIONS_DEBUG"). This property will be initialized in each directory by its value in the directory's parent.

    +

    CMake will automatically drop some definitions that are not supported by the native build tool. The VS6 IDE does not support definition values with spaces (but NMake does).

    +

    Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:

    +
      #          - broken almost everywhere
    ; - broken in VS IDE and Borland Makefiles
    , - broken in VS IDE
    % - broken in some cases in NMake
    & | - broken in some cases on MinGW
    ^ < > \" - broken in most Make tools on Windows
    +

    CMake does not reject these values outright because they do work in some cases. Use with caution.

    + +
  • +
  • + COMPILE_DEFINITIONS_<CONFIG>: Per-configuration preprocessor definitions in a directory.
    +

    This is the configuration-specific version of COMPILE_DEFINITIONS. This property will be initialized in each directory by its value in the directory's parent.

    + +
  • +
  • + DEFINITIONS: For CMake 2.4 compatibility only. Use COMPILE_DEFINITIONS instead.
    +

    This read-only property specifies the list of flags given so far to the add_definitions command. It is intended for debugging purposes. Use the COMPILE_DEFINITIONS instead.

    + +
  • +
  • + EXCLUDE_FROM_ALL: Exclude the directory from the all target of its parent.
    +

    A property on a directory that indicates if its targets are excluded from the default build target. If it is not, then with a Makefile for example typing make will cause the targets to be built. The same concept applies to the default build of other generators.

    + +
  • +
  • + IMPLICIT_DEPENDS_INCLUDE_TRANSFORM: Specify #include line transforms for dependencies in a directory.
    +

    This property specifies rules to transform macro-like #include lines during implicit dependency scanning of C and C++ source files. The list of rules must be semicolon-separated with each entry of the form "A_MACRO(%)=value-with-%" (the % must be literal). During dependency scanning occurrences of A_MACRO(...) on #include lines will be replaced by the value given with the macro argument substituted for '%'. For example, the entry

    +
      MYDIR(%)=<mydir/%>
    +

    will convert lines of the form

    +
      #include MYDIR(myheader.h)
    +

    to

    +
      #include <mydir/myheader.h>
    +

    allowing the dependency to be followed.

    +

    This property applies to sources in all targets within a directory. The property value is initialized in each directory by its value in the directory's parent.

    + +
  • +
  • + INCLUDE_DIRECTORIES: List of preprocessor include file search directories.
    +

    This read-only property specifies the list of directories given so far to the include_directories command. It is intended for debugging purposes.

    + +
  • +
  • + INCLUDE_REGULAR_EXPRESSION: Include file scanning regular expression.
    +

    This read-only property specifies the regular expression used during dependency scanning to match include files that should be followed. See the include_regular_expression command.

    + +
  • +
  • + INTERPROCEDURAL_OPTIMIZATION: Enable interprocedural optimization for targets in a directory.
    +

    If set to true, enables interprocedural optimizations if they are known to be supported by the compiler.

    + +
  • +
  • + INTERPROCEDURAL_OPTIMIZATION_<CONFIG>: Per-configuration interprocedural optimization for a directory.
    +

    This is a per-configuration version of INTERPROCEDURAL_OPTIMIZATION. If set, this property overrides the generic property for the named configuration.

    + +
  • +
  • + LINK_DIRECTORIES: List of linker search directories.
    +

    This read-only property specifies the list of directories given so far to the link_directories command. It is intended for debugging purposes.

    + +
  • +
  • + LISTFILE_STACK: The current stack of listfiles being processed.
    +

    This property is mainly useful when trying to debug errors in your CMake scripts. It returns a list of what list files are currently being processed, in order. So if one listfile does an INCLUDE command then that is effectively pushing the included listfile onto the stack.

    + +
  • +
  • + MACROS: List of macro commands available in the current directory.
    +

    This read-only property specifies the list of CMake macros currently defined. It is intended for debugging purposes. See the macro command.

    + +
  • +
  • + PARENT_DIRECTORY: Source directory that added current subdirectory.
    +

    This read-only property specifies the source directory that added the current source directory as a subdirectory of the build. In the top-level directory the value is the empty-string.

    + +
  • +
  • + RULE_LAUNCH_COMPILE: Specify a launcher for compile rules.
    +

    See the global property of the same name for details. This overrides the global property for a directory.

    + +
  • +
  • + RULE_LAUNCH_CUSTOM: Specify a launcher for custom rules.
    +

    See the global property of the same name for details. This overrides the global property for a directory.

    + +
  • +
  • + RULE_LAUNCH_LINK: Specify a launcher for link rules.
    +

    See the global property of the same name for details. This overrides the global property for a directory.

    + +
  • +
  • + TEST_INCLUDE_FILE: A cmake file that will be included when ctest is run.
    +

    If you specify TEST_INCLUDE_FILE, that file will be included and processed when ctest is run on the directory.

    + +
  • +
  • + VARIABLES: List of variables defined in the current directory.
    +

    This read-only property specifies the list of CMake variables currently defined. It is intended for debugging purposes.

    + +
  • +
+

Properties on Targets

+ +
    +
  • + <CONFIG>_OUTPUT_NAME: Old per-configuration target file base name.
    +

    This is a configuration-specific version of OUTPUT_NAME. Use OUTPUT_NAME_<CONFIG> instead.

    + +
  • +
  • + <CONFIG>_POSTFIX: Postfix to append to the target file name for configuration <CONFIG>.
    +

    When building with configuration <CONFIG> the value of this property is appended to the target file name built on disk. For non-executable targets, this property is initialized by the value of the variable CMAKE_<CONFIG>_POSTFIX if it is set when a target is created. This property is ignored on the Mac for Frameworks and App Bundles.

    + +
  • +
  • + ARCHIVE_OUTPUT_DIRECTORY: Output directory in which to build ARCHIVE target files.
    +

    This property specifies the directory into which archive target files should be built. Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms. This property is initialized by the value of the variable CMAKE_ARCHIVE_OUTPUT_DIRECTORY if it is set when a target is created.

    + +
  • +
  • + ARCHIVE_OUTPUT_DIRECTORY_<CONFIG>: Per-configuration output directory for ARCHIVE target files.
    +

    This is a per-configuration version of ARCHIVE_OUTPUT_DIRECTORY, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the variable CMAKE_ARCHIVE_OUTPUT_DIRECTORY_<CONFIG> if it is set when a target is created.

    + +
  • +
  • + ARCHIVE_OUTPUT_NAME: Output name for ARCHIVE target files.
    +

    This property specifies the base name for archive target files. It overrides OUTPUT_NAME and OUTPUT_NAME_<CONFIG> properties. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms.

    + +
  • +
  • + ARCHIVE_OUTPUT_NAME_<CONFIG>: Per-configuration output name for ARCHIVE target files.
    +

    This is the configuration-specific version of ARCHIVE_OUTPUT_NAME.

    + +
  • +
  • + AUTOMOC: Should the target be processed with automoc (for Qt projects).
    +

    AUTOMOC is a boolean specifying whether CMake will handle the Qt moc preprocessor automatically, i.e. without having to use the QT4_WRAP_CPP() macro. Currently Qt4 is supported. When this property is set to TRUE, CMake will scan the source files at build time and invoke moc accordingly. If an #include statement like #include "moc_foo.cpp" is found, the Q_OBJECT class declaration is expected in the header, and moc is run on the header file. If an #include statement like #include "foo.moc" is found, then a Q_OBJECT is expected in the current source file and moc is run on the file itself. Additionally, all header files are parsed for Q_OBJECT macros, and if found, moc is also executed on those files. The resulting moc files, which are not included as shown above in any of the source files are included in a generated <targetname>_automoc.cpp file, which is compiled as part of the target.This property is initialized by the value of the variable CMAKE_AUTOMOC if it is set when a target is created.

    +

    Additional command line options for moc can be set via the AUTOMOC_MOC_OPTIONS property.

    +

    By setting the CMAKE_AUTOMOC_RELAXED_MODE variable to TRUE the rules for searching the files which will be processed by moc can be relaxed. See the documentation for this variable for more details.

    + +
  • +
  • + AUTOMOC_MOC_OPTIONS: Additional options for moc when using automoc (see the AUTOMOC property)
    +

    This property is only used if the AUTOMOC property is set to TRUE for this target. In this case, it holds additional command line options which will be used when moc is executed during the build, i.e. it is equivalent to the optional OPTIONS argument of the qt4_wrap_cpp() macro.

    +

    By default it is empty.

    + +
  • +
  • + BUILD_WITH_INSTALL_RPATH: Should build tree targets have install tree rpaths.
    +

    BUILD_WITH_INSTALL_RPATH is a boolean specifying whether to link the target in the build tree with the INSTALL_RPATH. This takes precedence over SKIP_BUILD_RPATH and avoids the need for relinking before installation. This property is initialized by the value of the variable CMAKE_BUILD_WITH_INSTALL_RPATH if it is set when a target is created.

    + +
  • +
  • + BUNDLE: This target is a CFBundle on the Mac.
    +

    If a module library target has this property set to true it will be built as a CFBundle when built on the mac. It will have the directory structure required for a CFBundle and will be suitable to be used for creating Browser Plugins or other application resources.

    + +
  • +
  • + BUNDLE_EXTENSION: The file extension used to name a BUNDLE target on the Mac.
    +

    The default value is "bundle" - you can also use "plugin" or whatever file extension is required by the host app for your bundle.

    + +
  • +
  • + COMPILE_DEFINITIONS: Preprocessor definitions for compiling a target's sources.
    +

    The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values). This property may be set on a per-configuration basis using the name COMPILE_DEFINITIONS_<CONFIG> where <CONFIG> is an upper-case name (ex. "COMPILE_DEFINITIONS_DEBUG").

    +

    CMake will automatically drop some definitions that are not supported by the native build tool. The VS6 IDE does not support definition values with spaces (but NMake does).

    +

    Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:

    +
      #          - broken almost everywhere
    ; - broken in VS IDE and Borland Makefiles
    , - broken in VS IDE
    % - broken in some cases in NMake
    & | - broken in some cases on MinGW
    ^ < > \" - broken in most Make tools on Windows
    +

    CMake does not reject these values outright because they do work in some cases. Use with caution.

    + +
  • +
  • + COMPILE_DEFINITIONS_<CONFIG>: Per-configuration preprocessor definitions on a target.
    +

    This is the configuration-specific version of COMPILE_DEFINITIONS.

    + +
  • +
  • + COMPILE_FLAGS: Additional flags to use when compiling this target's sources.
    +

    The COMPILE_FLAGS property sets additional compiler flags used to build sources within the target. Use COMPILE_DEFINITIONS to pass additional preprocessor definitions.

    + +
  • +
  • + DEBUG_POSTFIX: See target property <CONFIG>_POSTFIX.
    +

    This property is a special case of the more-general <CONFIG>_POSTFIX property for the DEBUG configuration.

    + +
  • +
  • + DEFINE_SYMBOL: Define a symbol when compiling this target's sources.
    +

    DEFINE_SYMBOL sets the name of the preprocessor symbol defined when compiling sources in a shared library. If not set here then it is set to target_EXPORTS by default (with some substitutions if the target is not a valid C identifier). This is useful for headers to know whether they are being included from inside their library our outside to properly setup dllexport/dllimport decorations.

    + +
  • +
  • + ENABLE_EXPORTS: Specify whether an executable exports symbols for loadable modules.
    +

    Normally an executable does not export any symbols because it is the final program. It is possible for an executable to export symbols to be used by loadable modules. When this property is set to true CMake will allow other targets to "link" to the executable with the TARGET_LINK_LIBRARIES command. On all platforms a target-level dependency on the executable is created for targets that link to it. For DLL platforms an import library will be created for the exported symbols and then used for linking. All Windows-based systems including Cygwin are DLL platforms. For non-DLL platforms that require all symbols to be resolved at link time, such as Mac OS X, the module will "link" to the executable using a flag like "-bundle_loader". For other non-DLL platforms the link rule is simply ignored since the dynamic loader will automatically bind symbols when the module is loaded.

    + +
  • +
  • + EXCLUDE_FROM_ALL: Exclude the target from the all target.
    +

    A property on a target that indicates if the target is excluded from the default build target. If it is not, then with a Makefile for example typing make will cause this target to be built. The same concept applies to the default build of other generators. Installing a target with EXCLUDE_FROM_ALL set to true has undefined behavior.

    + +
  • +
  • + EchoString: A message to be displayed when the target is built.
    +

    A message to display on some generators (such as makefiles) when the target is built.

    + +
  • +
  • + FOLDER: Set the folder name. Use to organize targets in an IDE.
    +

    Targets with no FOLDER property will appear as top level entities in IDEs like Visual Studio. Targets with the same FOLDER property value will appear next to each other in a folder of that name. To nest folders, use FOLDER values such as 'GUI/Dialogs' with '/' characters separating folder levels.

    + +
  • +
  • + FRAMEWORK: This target is a framework on the Mac.
    +

    If a shared library target has this property set to true it will be built as a framework when built on the mac. It will have the directory structure required for a framework and will be suitable to be used with the -framework option

    + +
  • +
  • + Fortran_FORMAT: Set to FIXED or FREE to indicate the Fortran source layout.
    +

    This property tells CMake whether the Fortran source files in a target use fixed-format or free-format. CMake will pass the corresponding format flag to the compiler. Use the source-specific Fortran_FORMAT property to change the format of a specific source file. If the variable CMAKE_Fortran_FORMAT is set when a target is created its value is used to initialize this property.

    + +
  • +
  • + Fortran_MODULE_DIRECTORY: Specify output directory for Fortran modules provided by the target.
    +

    If the target contains Fortran source files that provide modules and the compiler supports a module output directory this specifies the directory in which the modules will be placed. When this property is not set the modules will be placed in the build directory corresponding to the target's source directory. If the variable CMAKE_Fortran_MODULE_DIRECTORY is set when a target is created its value is used to initialize this property.

    + +
  • +
  • + GENERATOR_FILE_NAME: Generator's file for this target.
    +

    An internal property used by some generators to record the name of project or dsp file associated with this target.

    + +
  • +
  • + GNUtoMS: Convert GNU import library (.dll.a) to MS format (.lib).
    +

    When linking a shared library or executable that exports symbols using GNU tools on Windows (MinGW/MSYS) with Visual Studio installed convert the import library (.dll.a) from GNU to MS format (.lib). Both import libraries will be installed by install(TARGETS) and exported by install(EXPORT) and export() to be linked by applications with either GNU- or MS-compatible tools.

    +

    If the variable CMAKE_GNUtoMS is set when a target is created its value is used to initialize this property. The variable must be set prior to the first command that enables a language such as project() or enable_language(). CMake provides the variable as an option to the user automatically when configuring on Windows with GNU tools.

    + +
  • +
  • + HAS_CXX: Link the target using the C++ linker tool (obsolete).
    +

    This is equivalent to setting the LINKER_LANGUAGE property to CXX. See that property's documentation for details.

    + +
  • +
  • + IMPLICIT_DEPENDS_INCLUDE_TRANSFORM: Specify #include line transforms for dependencies in a target.
    +

    This property specifies rules to transform macro-like #include lines during implicit dependency scanning of C and C++ source files. The list of rules must be semicolon-separated with each entry of the form "A_MACRO(%)=value-with-%" (the % must be literal). During dependency scanning occurrences of A_MACRO(...) on #include lines will be replaced by the value given with the macro argument substituted for '%'. For example, the entry

    +
      MYDIR(%)=<mydir/%>
    +

    will convert lines of the form

    +
      #include MYDIR(myheader.h)
    +

    to

    +
      #include <mydir/myheader.h>
    +

    allowing the dependency to be followed.

    +

    This property applies to sources in the target on which it is set.

    + +
  • +
  • + IMPORTED: Read-only indication of whether a target is IMPORTED.
    +

    The boolean value of this property is true for targets created with the IMPORTED option to add_executable or add_library. It is false for targets built within the project.

    + +
  • +
  • + IMPORTED_CONFIGURATIONS: Configurations provided for an IMPORTED target.
    +

    Lists configuration names available for an IMPORTED target. The names correspond to configurations defined in the project from which the target is imported. If the importing project uses a different set of configurations the names may be mapped using the MAP_IMPORTED_CONFIG_<CONFIG> property. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_IMPLIB: Full path to the import library for an IMPORTED target.
    +

    Specifies the location of the ".lib" part of a windows DLL. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_IMPLIB_<CONFIG>: Per-configuration version of IMPORTED_IMPLIB property.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported.

    + +
  • +
  • + IMPORTED_LINK_DEPENDENT_LIBRARIES: Dependent shared libraries of an imported shared library.
    +

    Shared libraries may be linked to other shared libraries as part of their implementation. On some platforms the linker searches for the dependent libraries of shared libraries they are including in the link. This property lists the dependent shared libraries of an imported library. The list should be disjoint from the list of interface libraries in the IMPORTED_LINK_INTERFACE_LIBRARIES property. On platforms requiring dependent shared libraries to be found at link time CMake uses this list to add appropriate files or paths to the link command line. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_LINK_DEPENDENT_LIBRARIES_<CONFIG>: Per-configuration version of IMPORTED_LINK_DEPENDENT_LIBRARIES.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_LANGUAGES: Languages compiled into an IMPORTED static library.
    +

    Lists languages of soure files compiled to produce a STATIC IMPORTED library (such as "C" or "CXX"). CMake accounts for these languages when computing how to link a target to the imported library. For example, when a C executable links to an imported C++ static library CMake chooses the C++ linker to satisfy language runtime dependencies of the static library.

    +

    This property is ignored for targets that are not STATIC libraries. This property is ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_LANGUAGES_<CONFIG>: Per-configuration version of IMPORTED_LINK_INTERFACE_LANGUAGES.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_LIBRARIES: Transitive link interface of an IMPORTED target.
    +

    Lists libraries whose interface is included when an IMPORTED library target is linked to another target. The libraries will be included on the link line for the target. Unlike the LINK_INTERFACE_LIBRARIES property, this property applies to all imported target types, including STATIC libraries. This property is ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_LIBRARIES_<CONFIG>: Per-configuration version of IMPORTED_LINK_INTERFACE_LIBRARIES.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_MULTIPLICITY: Repetition count for cycles of IMPORTED static libraries.
    +

    This is LINK_INTERFACE_MULTIPLICITY for IMPORTED targets.

    + +
  • +
  • + IMPORTED_LINK_INTERFACE_MULTIPLICITY_<CONFIG>: Per-configuration repetition count for cycles of IMPORTED archives.
    +

    This is the configuration-specific version of IMPORTED_LINK_INTERFACE_MULTIPLICITY. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + IMPORTED_LOCATION: Full path to the main file on disk for an IMPORTED target.
    +

    Specifies the location of an IMPORTED target file on disk. For executables this is the location of the executable file. For bundles on OS X this is the location of the executable file inside Contents/MacOS under the application bundle folder. For static libraries and modules this is the location of the library or module. For shared libraries on non-DLL platforms this is the location of the shared library. For frameworks on OS X this is the location of the library file symlink just inside the framework folder. For DLLs this is the location of the ".dll" part of the library. For UNKNOWN libraries this is the location of the file to be linked. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_LOCATION_<CONFIG>: Per-configuration version of IMPORTED_LOCATION property.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported.

    + +
  • +
  • + IMPORTED_NO_SONAME: Specifies that an IMPORTED shared library target has no "soname".
    +

    Set this property to true for an imported shared library file that has no "soname" field. CMake may adjust generated link commands for some platforms to prevent the linker from using the path to the library in place of its missing soname. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_NO_SONAME_<CONFIG>: Per-configuration version of IMPORTED_NO_SONAME property.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported.

    + +
  • +
  • + IMPORTED_SONAME: The "soname" of an IMPORTED target of shared library type.
    +

    Specifies the "soname" embedded in an imported shared library. This is meaningful only on platforms supporting the feature. Ignored for non-imported targets.

    + +
  • +
  • + IMPORTED_SONAME_<CONFIG>: Per-configuration version of IMPORTED_SONAME property.
    +

    This property is used when loading settings for the <CONFIG> configuration of an imported target. Configuration names correspond to those provided by the project from which the target is imported.

    + +
  • +
  • + IMPORT_PREFIX: What comes before the import library name.
    +

    Similar to the target property PREFIX, but used for import libraries (typically corresponding to a DLL) instead of regular libraries. A target property that can be set to override the prefix (such as "lib") on an import library name.

    + +
  • +
  • + IMPORT_SUFFIX: What comes after the import library name.
    +

    Similar to the target property SUFFIX, but used for import libraries (typically corresponding to a DLL) instead of regular libraries. A target property that can be set to override the suffix (such as ".lib") on an import library name.

    + +
  • +
  • + INSTALL_NAME_DIR: Mac OSX directory name for installed targets.
    +

    INSTALL_NAME_DIR is a string specifying the directory portion of the "install_name" field of shared libraries on Mac OSX to use in the installed targets.

    + +
  • +
  • + INSTALL_RPATH: The rpath to use for installed targets.
    +

    A semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it). This property is initialized by the value of the variable CMAKE_INSTALL_RPATH if it is set when a target is created.

    + +
  • +
  • + INSTALL_RPATH_USE_LINK_PATH: Add paths to linker search and installed rpath.
    +

    INSTALL_RPATH_USE_LINK_PATH is a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL_RPATH. This property is initialized by the value of the variable CMAKE_INSTALL_RPATH_USE_LINK_PATH if it is set when a target is created.

    + +
  • +
  • + INTERPROCEDURAL_OPTIMIZATION: Enable interprocedural optimization for a target.
    +

    If set to true, enables interprocedural optimizations if they are known to be supported by the compiler.

    + +
  • +
  • + INTERPROCEDURAL_OPTIMIZATION_<CONFIG>: Per-configuration interprocedural optimization for a target.
    +

    This is a per-configuration version of INTERPROCEDURAL_OPTIMIZATION. If set, this property overrides the generic property for the named configuration.

    + +
  • +
  • + LABELS: Specify a list of text labels associated with a target.
    +

    Target label semantics are currently unspecified.

    + +
  • +
  • + LIBRARY_OUTPUT_DIRECTORY: Output directory in which to build LIBRARY target files.
    +

    This property specifies the directory into which library target files should be built. Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms. This property is initialized by the value of the variable CMAKE_LIBRARY_OUTPUT_DIRECTORY if it is set when a target is created.

    + +
  • +
  • + LIBRARY_OUTPUT_DIRECTORY_<CONFIG>: Per-configuration output directory for LIBRARY target files.
    +

    This is a per-configuration version of LIBRARY_OUTPUT_DIRECTORY, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the variable CMAKE_LIBRARY_OUTPUT_DIRECTORY_<CONFIG> if it is set when a target is created.

    + +
  • +
  • + LIBRARY_OUTPUT_NAME: Output name for LIBRARY target files.
    +

    This property specifies the base name for library target files. It overrides OUTPUT_NAME and OUTPUT_NAME_<CONFIG> properties. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms.

    + +
  • +
  • + LIBRARY_OUTPUT_NAME_<CONFIG>: Per-configuration output name for LIBRARY target files.
    +

    This is the configuration-specific version of LIBRARY_OUTPUT_NAME.

    + +
  • +
  • + LINKER_LANGUAGE: Specifies language whose compiler will invoke the linker.
    +

    For executables, shared libraries, and modules, this sets the language whose compiler is used to link the target (such as "C" or "CXX"). A typical value for an executable is the language of the source file providing the program entry point (main). If not set, the language with the highest linker preference value is the default. See documentation of CMAKE_<LANG>_LINKER_PREFERENCE variables.

    + +
  • +
  • + LINK_DEPENDS: Additional files on which a target binary depends for linking.
    +

    Specifies a semicolon-separated list of full-paths to files on which the link rule for this target depends. The target binary will be linked if any of the named files is newer than it.

    +

    This property is ignored by non-Makefile generators. It is intended to specify dependencies on "linker scripts" for custom Makefile link rules.

    + +
  • +
  • + LINK_FLAGS: Additional flags to use when linking this target.
    +

    The LINK_FLAGS property can be used to add extra flags to the link step of a target. LINK_FLAGS_<CONFIG> will add to the configuration <CONFIG>, for example, DEBUG, RELEASE, MINSIZEREL, RELWITHDEBINFO.

    + +
  • +
  • + LINK_FLAGS_<CONFIG>: Per-configuration linker flags for a target.
    +

    This is the configuration-specific version of LINK_FLAGS.

    + +
  • +
  • + LINK_INTERFACE_LIBRARIES: List public interface libraries for a shared library or executable.
    +

    By default linking to a shared library target transitively links to targets with which the library itself was linked. For an executable with exports (see the ENABLE_EXPORTS property) no default transitive link dependencies are used. This property replaces the default transitive link dependencies with an explicit list. When the target is linked into another target the libraries listed (and recursively their link interface libraries) will be provided to the other target also. If the list is empty then no transitive link dependencies will be incorporated when this target is linked into another target even if the default set is non-empty. This property is initialized by the value of the variable CMAKE_LINK_INTERFACE_LIBRARIES if it is set when a target is created. This property is ignored for STATIC libraries.

    + +
  • +
  • + LINK_INTERFACE_LIBRARIES_<CONFIG>: Per-configuration list of public interface libraries for a target.
    +

    This is the configuration-specific version of LINK_INTERFACE_LIBRARIES. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + LINK_INTERFACE_MULTIPLICITY: Repetition count for STATIC libraries with cyclic dependencies.
    +

    When linking to a STATIC library target with cyclic dependencies the linker may need to scan more than once through the archives in the strongly connected component of the dependency graph. CMake by default constructs the link line so that the linker will scan through the component at least twice. This property specifies the minimum number of scans if it is larger than the default. CMake uses the largest value specified by any target in a component.

    + +
  • +
  • + LINK_INTERFACE_MULTIPLICITY_<CONFIG>: Per-configuration repetition count for cycles of STATIC libraries.
    +

    This is the configuration-specific version of LINK_INTERFACE_MULTIPLICITY. If set, this property completely overrides the generic property for the named configuration.

    + +
  • +
  • + LINK_SEARCH_END_STATIC: End a link line such that static system libraries are used.
    +

    Some linkers support switches such as -Bstatic and -Bdynamic to determine whether to use static or shared libraries for -lXXX options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default CMake adds an option at the end of the library list (if necessary) to set the linker search type back to its starting type. This property switches the final linker search type to -Bstatic regardless of how it started. See also LINK_SEARCH_START_STATIC.

    + +
  • +
  • + LINK_SEARCH_START_STATIC: Assume the linker looks for static libraries by default.
    +

    Some linkers support switches such as -Bstatic and -Bdynamic to determine whether to use static or shared libraries for -lXXX options. CMake uses these options to set the link type for libraries whose full paths are not known or (in some cases) are in implicit link directories for the platform. By default the linker search type is assumed to be -Bdynamic at the beginning of the library list. This property switches the assumption to -Bstatic. It is intended for use when linking an executable statically (e.g. with the GNU -static option). See also LINK_SEARCH_END_STATIC.

    + +
  • +
  • + LOCATION: Read-only location of a target on disk.
    +

    For an imported target, this read-only property returns the value of the LOCATION_<CONFIG> property for an unspecified configuration <CONFIG> provided by the target.

    +

    For a non-imported target, this property is provided for compatibility with CMake 2.4 and below. It was meant to get the location of an executable target's output file for use in add_custom_command. The path may contain a build-system-specific portion that is replaced at build time with the configuration getting built (such as "$(ConfigurationName)" in VS). In CMake 2.6 and above add_custom_command automatically recognizes a target name in its COMMAND and DEPENDS options and computes the target location. In CMake 2.8.4 and above add_custom_command recognizes generator expressions to refer to target locations anywhere in the command. Therefore this property is not needed for creating custom commands.

    +

    Do not set properties that affect the location of a target after reading this property. These include properties whose names match "(RUNTIME|LIBRARY|ARCHIVE)_OUTPUT_(NAME|DIRECTORY)(_<CONFIG>)?" or "(IMPLIB_)?(PREFIX|SUFFIX)". Failure to follow this rule is not diagnosed and leaves the location of the target undefined.

    + +
  • +
  • + LOCATION_<CONFIG>: Read-only property providing a target location on disk.
    +

    A read-only property that indicates where a target's main file is located on disk for the configuration <CONFIG>. The property is defined only for library and executable targets. An imported target may provide a set of configurations different from that of the importing project. By default CMake looks for an exact-match but otherwise uses an arbitrary available configuration. Use the MAP_IMPORTED_CONFIG_<CONFIG> property to map imported configurations explicitly.

    +

    Do not set properties that affect the location of a target after reading this property. These include properties whose names match "(RUNTIME|LIBRARY|ARCHIVE)_OUTPUT_(NAME|DIRECTORY)(_<CONFIG>)?" or "(IMPLIB_)?(PREFIX|SUFFIX)". Failure to follow this rule is not diagnosed and leaves the location of the target undefined.

    + +
  • +
  • + MACOSX_BUNDLE: Build an executable as an application bundle on Mac OS X.
    +

    When this property is set to true the executable when built on Mac OS X will be created as an application bundle. This makes it a GUI executable that can be launched from the Finder. See the MACOSX_BUNDLE_INFO_PLIST target property for information about creation of the Info.plist file for the application bundle.

    + +
  • +
  • + MACOSX_BUNDLE_INFO_PLIST: Specify a custom Info.plist template for a Mac OS X App Bundle.
    +

    An executable target with MACOSX_BUNDLE enabled will be built as an application bundle on Mac OS X. By default its Info.plist file is created by configuring a template called MacOSXBundleInfo.plist.in located in the CMAKE_MODULE_PATH. This property specifies an alternative template file name which may be a full path.

    +

    The following target properties may be set to specify content to be configured into the file:

    +
      MACOSX_BUNDLE_INFO_STRING
    MACOSX_BUNDLE_ICON_FILE
    MACOSX_BUNDLE_GUI_IDENTIFIER
    MACOSX_BUNDLE_LONG_VERSION_STRING
    MACOSX_BUNDLE_BUNDLE_NAME
    MACOSX_BUNDLE_SHORT_VERSION_STRING
    MACOSX_BUNDLE_BUNDLE_VERSION
    MACOSX_BUNDLE_COPYRIGHT
    +

    CMake variables of the same name may be set to affect all targets in a directory that do not have each specific property set. If a custom Info.plist is specified by this property it may of course hard-code all the settings instead of using the target properties.

    + +
  • +
  • + MACOSX_FRAMEWORK_INFO_PLIST: Specify a custom Info.plist template for a Mac OS X Framework.
    +

    An library target with FRAMEWORK enabled will be built as a framework on Mac OS X. By default its Info.plist file is created by configuring a template called MacOSXFrameworkInfo.plist.in located in the CMAKE_MODULE_PATH. This property specifies an alternative template file name which may be a full path.

    +

    The following target properties may be set to specify content to be configured into the file:

    +
      MACOSX_FRAMEWORK_ICON_FILE
    MACOSX_FRAMEWORK_IDENTIFIER
    MACOSX_FRAMEWORK_SHORT_VERSION_STRING
    MACOSX_FRAMEWORK_BUNDLE_VERSION
    +

    CMake variables of the same name may be set to affect all targets in a directory that do not have each specific property set. If a custom Info.plist is specified by this property it may of course hard-code all the settings instead of using the target properties.

    + +
  • +
  • + MAP_IMPORTED_CONFIG_<CONFIG>: Map from project configuration to IMPORTED target's configuration.
    +

    List configurations of an imported target that may be used for the current project's <CONFIG> configuration. Targets imported from another project may not provide the same set of configuration names available in the current project. Setting this property tells CMake what imported configurations are suitable for use when building the <CONFIG> configuration. The first configuration in the list found to be provided by the imported target is selected. If no matching configurations are available the imported target is considered to be not found. This property is ignored for non-imported targets.

    + +
  • +
  • + OSX_ARCHITECTURES: Target specific architectures for OS X.
    +

    The OSX_ARCHITECTURES property sets the target binary architecture for targets on OS X. This property is initialized by the value of the variable CMAKE_OSX_ARCHITECTURES if it is set when a target is created. Use OSX_ARCHITECTURES_<CONFIG> to set the binary architectures on a per-configuration basis. <CONFIG> is an upper-case name (ex: "OSX_ARCHITECTURES_DEBUG").

    + +
  • +
  • + OSX_ARCHITECTURES_<CONFIG>: Per-configuration OS X binary architectures for a target.
    +

    This property is the configuration-specific version of OSX_ARCHITECTURES.

    + +
  • +
  • + OUTPUT_NAME: Output name for target files.
    +

    This sets the base name for output files created for an executable or library target. If not set, the logical target name is used by default.

    + +
  • +
  • + OUTPUT_NAME_<CONFIG>: Per-configuration target file base name.
    +

    This is the configuration-specific version of OUTPUT_NAME.

    + +
  • +
  • + POST_INSTALL_SCRIPT: Deprecated install support.
    +

    The PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT properties are the old way to specify CMake scripts to run before and after installing a target. They are used only when the old INSTALL_TARGETS command is used to install the target. Use the INSTALL command instead.

    + +
  • +
  • + PREFIX: What comes before the library name.
    +

    A target property that can be set to override the prefix (such as "lib") on a library name.

    + +
  • +
  • + PRE_INSTALL_SCRIPT: Deprecated install support.
    +

    The PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT properties are the old way to specify CMake scripts to run before and after installing a target. They are used only when the old INSTALL_TARGETS command is used to install the target. Use the INSTALL command instead.

    + +
  • +
  • + PRIVATE_HEADER: Specify private header files in a FRAMEWORK shared library target.
    +

    Shared library targets marked with the FRAMEWORK property generate frameworks on OS X and normal shared libraries on other platforms. This property may be set to a list of header files to be placed in the PrivateHeaders directory inside the framework folder. On non-Apple platforms these headers may be installed using the PRIVATE_HEADER option to the install(TARGETS) command.

    + +
  • +
  • + PROJECT_LABEL: Change the name of a target in an IDE.
    +

    Can be used to change the name of the target in an IDE like Visual Studio.

    + +
  • +
  • + PUBLIC_HEADER: Specify public header files in a FRAMEWORK shared library target.
    +

    Shared library targets marked with the FRAMEWORK property generate frameworks on OS X and normal shared libraries on other platforms. This property may be set to a list of header files to be placed in the Headers directory inside the framework folder. On non-Apple platforms these headers may be installed using the PUBLIC_HEADER option to the install(TARGETS) command.

    + +
  • +
  • + RESOURCE: Specify resource files in a FRAMEWORK shared library target.
    +

    Shared library targets marked with the FRAMEWORK property generate frameworks on OS X and normal shared libraries on other platforms. This property may be set to a list of files to be placed in the Resources directory inside the framework folder. On non-Apple platforms these files may be installed using the RESOURCE option to the install(TARGETS) command.

    + +
  • +
  • + RULE_LAUNCH_COMPILE: Specify a launcher for compile rules.
    +

    See the global property of the same name for details. This overrides the global and directory property for a target.

    + +
  • +
  • + RULE_LAUNCH_CUSTOM: Specify a launcher for custom rules.
    +

    See the global property of the same name for details. This overrides the global and directory property for a target.

    + +
  • +
  • + RULE_LAUNCH_LINK: Specify a launcher for link rules.
    +

    See the global property of the same name for details. This overrides the global and directory property for a target.

    + +
  • +
  • + RUNTIME_OUTPUT_DIRECTORY: Output directory in which to build RUNTIME target files.
    +

    This property specifies the directory into which runtime target files should be built. Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms. This property is initialized by the value of the variable CMAKE_RUNTIME_OUTPUT_DIRECTORY if it is set when a target is created.

    + +
  • +
  • + RUNTIME_OUTPUT_DIRECTORY_<CONFIG>: Per-configuration output directory for RUNTIME target files.
    +

    This is a per-configuration version of RUNTIME_OUTPUT_DIRECTORY, but multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory. This property is initialized by the value of the variable CMAKE_RUNTIME_OUTPUT_DIRECTORY_<CONFIG> if it is set when a target is created.

    + +
  • +
  • + RUNTIME_OUTPUT_NAME: Output name for RUNTIME target files.
    +

    This property specifies the base name for runtime target files. It overrides OUTPUT_NAME and OUTPUT_NAME_<CONFIG> properties. There are three kinds of target files that may be built: archive, library, and runtime. Executables are always treated as runtime targets. Static libraries are always treated as archive targets. Module libraries are always treated as library targets. For non-DLL platforms shared libraries are treated as library targets. For DLL platforms the DLL part of a shared library is treated as a runtime target and the corresponding import library is treated as an archive target. All Windows-based systems including Cygwin are DLL platforms.

    + +
  • +
  • + RUNTIME_OUTPUT_NAME_<CONFIG>: Per-configuration output name for RUNTIME target files.
    +

    This is the configuration-specific version of RUNTIME_OUTPUT_NAME.

    + +
  • +
  • + SKIP_BUILD_RPATH: Should rpaths be used for the build tree.
    +

    SKIP_BUILD_RPATH is a boolean specifying whether to skip automatic generation of an rpath allowing the target to run from the build tree. This property is initialized by the value of the variable CMAKE_SKIP_BUILD_RPATH if it is set when a target is created.

    + +
  • +
  • + SOURCES: Source names specified for a target.
    +

    Read-only list of sources specified for a target. The names returned are suitable for passing to the set_source_files_properties command.

    + +
  • +
  • + SOVERSION: What version number is this target.
    +

    For shared libraries VERSION and SOVERSION can be used to specify the build version and api version respectively. When building or installing appropriate symlinks are created if the platform supports symlinks and the linker supports so-names. If only one of both is specified the missing is assumed to have the same version number. For shared libraries and executables on Windows the VERSION attribute is parsed to extract a "major.minor" version number. These numbers are used as the image version of the binary.

    + +
  • +
  • + STATIC_LIBRARY_FLAGS: Extra flags to use when linking static libraries.
    +

    Extra flags to use when linking a static library.

    + +
  • +
  • + STATIC_LIBRARY_FLAGS_<CONFIG>: Per-configuration flags for creating a static library.
    +

    This is the configuration-specific version of STATIC_LIBRARY_FLAGS.

    + +
  • +
  • + SUFFIX: What comes after the library name.
    +

    A target property that can be set to override the suffix (such as ".so") on a library name.

    + +
  • +
  • + TYPE: The type of the target.
    +

    This read-only property can be used to test the type of the given target. It will be one of STATIC_LIBRARY, MODULE_LIBRARY, SHARED_LIBRARY, EXECUTABLE or one of the internal target types.

    + +
  • +
  • + VERSION: What version number is this target.
    +

    For shared libraries VERSION and SOVERSION can be used to specify the build version and api version respectively. When building or installing appropriate symlinks are created if the platform supports symlinks and the linker supports so-names. If only one of both is specified the missing is assumed to have the same version number. For executables VERSION can be used to specify the build version. When building or installing appropriate symlinks are created if the platform supports symlinks. For shared libraries and executables on Windows the VERSION attribute is parsed to extract a "major.minor" version number. These numbers are used as the image version of the binary.

    + +
  • +
  • + VS_DOTNET_REFERENCES: Visual Studio managed project .NET references
    +

    Adds one or more semicolon-delimited .NET references to a generated Visual Studio project. For example, "System;System.Windows.Forms".

    + +
  • +
  • + VS_GLOBAL_<variable>: Visual Studio project-specific global variable.
    +

    Tell the Visual Studio generator to set the global variable '<variable>' to a given value in the generated Visual Studio project. Ignored on other generators. Qt integration works better if VS_GLOBAL_QtVersion is set to the version FindQt4.cmake found. For example, "4.7.3"

    + +
  • +
  • + VS_GLOBAL_KEYWORD: Visual Studio project keyword.
    +

    Sets the "keyword" attribute for a generated Visual Studio project. Defaults to "Win32Proj". You may wish to override this value with "ManagedCProj", for example, in a Visual Studio managed C++ unit test project.

    + +
  • +
  • + VS_GLOBAL_PROJECT_TYPES: Visual Studio project type(s).
    +

    Can be set to one or more UUIDs recognized by Visual Studio to indicate the type of project. This value is copied verbatim into the generated project file. Example for a managed C++ unit testing project: "{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}". UUIDs are semicolon-delimited.

    + +
  • +
  • + VS_KEYWORD: Visual Studio project keyword.
    +

    Can be set to change the visual studio keyword, for example QT integration works better if this is set to Qt4VSv1.0.

    + +
  • +
  • + VS_SCC_AUXPATH: Visual Studio Source Code Control Aux Path.
    +

    Can be set to change the visual studio source code control auxpath property.

    + +
  • +
  • + VS_SCC_LOCALPATH: Visual Studio Source Code Control Local Path.
    +

    Can be set to change the visual studio source code control local path property.

    + +
  • +
  • + VS_SCC_PROJECTNAME: Visual Studio Source Code Control Project.
    +

    Can be set to change the visual studio source code control project name property.

    + +
  • +
  • + VS_SCC_PROVIDER: Visual Studio Source Code Control Provider.
    +

    Can be set to change the visual studio source code control provider property.

    + +
  • +
  • + WIN32_EXECUTABLE: Build an executable with a WinMain entry point on windows.
    +

    When this property is set to true the executable when linked on Windows will be created with a WinMain() entry point instead of of just main().This makes it a GUI executable instead of a console application. See the CMAKE_MFC_FLAG variable documentation to configure use of MFC for WinMain executables.

    + +
  • +
  • + XCODE_ATTRIBUTE_<an-attribute>: Set Xcode target attributes directly.
    +

    Tell the Xcode generator to set '<an-attribute>' to a given value in the generated Xcode project. Ignored on other generators.

    + +
  • +
+

Properties on Tests

+ +
    +
  • + ATTACHED_FILES: Attach a list of files to a dashboard submission.
    +

    Set this property to a list of files that will be encoded and submitted to the dashboard as an addition to the test result.

    + +
  • +
  • + ATTACHED_FILES_ON_FAIL: Attach a list of files to a dashboard submission if the test fails.
    +

    Same as ATTACHED_FILES, but these files will only be included if the test does not pass.

    + +
  • +
  • + COST: Set this to a floating point value. Tests in a test set will be run in descending order of cost.
    +

    This property describes the cost of a test. You can explicitly set this value; tests with higher COST values will run first.

    + +
  • +
  • + DEPENDS: Specifies that this test should only be run after the specified list of tests.
    +

    Set this to a list of tests that must finish before this test is run.

    + +
  • +
  • + ENVIRONMENT: Specify environment variables that should be defined for running a test.
    +

    If set to a list of environment variables and values of the form MYVAR=value those environment variables will be defined while running the test. The environment is restored to its previous state after the test is done.

    + +
  • +
  • + FAIL_REGULAR_EXPRESSION: If the output matches this regular expression the test will fail.
    +

    If set, if the output matches one of specified regular expressions, the test will fail.For example: PASS_REGULAR_EXPRESSION "[^a-z]Error;ERROR;Failed"

    + +
  • +
  • + LABELS: Specify a list of text labels associated with a test.
    +

    The list is reported in dashboard submissions.

    + +
  • +
  • + MEASUREMENT: Specify a CDASH measurement and value to be reported for a test.
    +

    If set to a name then that name will be reported to CDASH as a named measurement with a value of 1. You may also specify a value by setting MEASUREMENT to "measurement=value".

    + +
  • +
  • + PASS_REGULAR_EXPRESSION: The output must match this regular expression for the test to pass.
    +

    If set, the test output will be checked against the specified regular expressions and at least one of the regular expressions has to match, otherwise the test will fail.

    + +
  • +
  • + PROCESSORS: How many process slots this test requires
    +

    Denotes the number of processors that this test will require. This is typically used for MPI tests, and should be used in conjunction with the ctest_test PARALLEL_LEVEL option.

    + +
  • +
  • + REQUIRED_FILES: List of files required to run the test.
    +

    If set to a list of files, the test will not be run unless all of the files exist.

    + +
  • +
  • + RESOURCE_LOCK: Specify a list of resources that are locked by this test.
    +

    If multiple tests specify the same resource lock, they are guaranteed not to run concurrently.

    + +
  • +
  • + RUN_SERIAL: Do not run this test in parallel with any other test.
    +

    Use this option in conjunction with the ctest_test PARALLEL_LEVEL option to specify that this test should not be run in parallel with any other tests.

    + +
  • +
  • + TIMEOUT: How many seconds to allow for this test.
    +

    This property if set will limit a test to not take more than the specified number of seconds to run. If it exceeds that the test process will be killed and ctest will move to the next test. This setting takes precedence over CTEST_TESTING_TIMEOUT.

    + +
  • +
  • + WILL_FAIL: If set to true, this will invert the pass/fail flag of the test.
    +

    This property can be used for tests that are expected to fail and return a non zero return code.

    + +
  • +
  • + WORKING_DIRECTORY: The directory from which the test executable will be called.
    +

    If this is not set it is called from the directory the test executable is located in.

    + +
  • +
+

Properties on Source Files

+ +
    +
  • + ABSTRACT: Is this source file an abstract class.
    +

    A property on a source file that indicates if the source file represents a class that is abstract. This only makes sense for languages that have a notion of an abstract class and it is only used by some tools that wrap classes into other languages.

    + +
  • +
  • + COMPILE_DEFINITIONS: Preprocessor definitions for compiling a source file.
    +

    The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values). This property may be set on a per-configuration basis using the name COMPILE_DEFINITIONS_<CONFIG> where <CONFIG> is an upper-case name (ex. "COMPILE_DEFINITIONS_DEBUG").

    +

    CMake will automatically drop some definitions that are not supported by the native build tool. The VS6 IDE does not support definition values with spaces (but NMake does). Xcode does not support per-configuration definitions on source files.

    +

    Disclaimer: Most native build tools have poor support for escaping certain values. CMake has work-arounds for many cases but some values may just not be possible to pass correctly. If a value does not seem to be escaped correctly, do not attempt to work-around the problem by adding escape sequences to the value. Your work-around may break in a future version of CMake that has improved escape support. Instead consider defining the macro in a (configured) header file. Then report the limitation. Known limitations include:

    +
      #          - broken almost everywhere
    ; - broken in VS IDE and Borland Makefiles
    , - broken in VS IDE
    % - broken in some cases in NMake
    & | - broken in some cases on MinGW
    ^ < > \" - broken in most Make tools on Windows
    +

    CMake does not reject these values outright because they do work in some cases. Use with caution.

    + +
  • +
  • + COMPILE_DEFINITIONS_<CONFIG>: Per-configuration preprocessor definitions on a source file.
    +

    This is the configuration-specific version of COMPILE_DEFINITIONS. Note that Xcode does not support per-configuration source file flags so this property will be ignored by the Xcode generator.

    + +
  • +
  • + COMPILE_FLAGS: Additional flags to be added when compiling this source file.
    +

    These flags will be added to the list of compile flags when this source file builds. Use COMPILE_DEFINITIONS to pass additional preprocessor definitions.

    + +
  • +
  • + EXTERNAL_OBJECT: If set to true then this is an object file.
    +

    If this property is set to true then the source file is really an object file and should not be compiled. It will still be linked into the target though.

    + +
  • +
  • + Fortran_FORMAT: Set to FIXED or FREE to indicate the Fortran source layout.
    +

    This property tells CMake whether a given Fortran source file uses fixed-format or free-format. CMake will pass the corresponding format flag to the compiler. Consider using the target-wide Fortran_FORMAT property if all source files in a target share the same format.

    + +
  • +
  • + GENERATED: Is this source file generated as part of the build process.
    +

    If a source file is generated by the build process CMake will handle it differently in terms of dependency checking etc. Otherwise having a non-existent source file could create problems.

    + +
  • +
  • + HEADER_FILE_ONLY: Is this source file only a header file.
    +

    A property on a source file that indicates if the source file is a header file with no associated implementation. This is set automatically based on the file extension and is used by CMake to determine is certain dependency information should be computed.

    + +
  • +
  • + KEEP_EXTENSION: Make the output file have the same extension as the source file.
    +

    If this property is set then the file extension of the output file will be the same as that of the source file. Normally the output file extension is computed based on the language of the source file, for example .cxx will go to a .o extension.

    + +
  • +
  • + LABELS: Specify a list of text labels associated with a source file.
    +

    This property has meaning only when the source file is listed in a target whose LABELS property is also set. No other semantics are currently specified.

    + +
  • +
  • + LANGUAGE: What programming language is the file.
    +

    A property that can be set to indicate what programming language the source file is. If it is not set the language is determined based on the file extension. Typical values are CXX C etc. Setting this property for a file means this file will be compiled. Do not set this for header or files that should not be compiled.

    + +
  • +
  • + LOCATION: The full path to a source file.
    +

    A read only property on a SOURCE FILE that contains the full path to the source file.

    + +
  • +
  • + MACOSX_PACKAGE_LOCATION: Place a source file inside a Mac OS X bundle, CFBundle, or framework.
    +

    Executable targets with the MACOSX_BUNDLE property set are built as Mac OS X application bundles on Apple platforms. Shared library targets with the FRAMEWORK property set are built as Mac OS X frameworks on Apple platforms. Module library targets with the BUNDLE property set are built as Mac OS X CFBundle bundles on Apple platforms. Source files listed in the target with this property set will be copied to a directory inside the bundle or framework content folder specified by the property value. For bundles the content folder is "<name>.app/Contents". For frameworks the content folder is "<name>.framework/Versions/<version>". For cfbundles the content folder is "<name>.bundle/Contents" (unless the extension is changed). See the PUBLIC_HEADER, PRIVATE_HEADER, and RESOURCE target properties for specifying files meant for Headers, PrivateHeaders, or Resources directories.

    + +
  • +
  • + OBJECT_DEPENDS: Additional files on which a compiled object file depends.
    +

    Specifies a semicolon-separated list of full-paths to files on which any object files compiled from this source file depend. An object file will be recompiled if any of the named files is newer than it.

    +

    This property need not be used to specify the dependency of a source file on a generated header file that it includes. Although the property was originally introduced for this purpose, it is no longer necessary. If the generated header file is created by a custom command in the same target as the source file, the automatic dependency scanning process will recognize the dependency. If the generated header file is created by another target, an inter-target dependency should be created with the add_dependencies command (if one does not already exist due to linking relationships).

    + +
  • +
  • + OBJECT_OUTPUTS: Additional outputs for a Makefile rule.
    +

    Additional outputs created by compilation of this source file. If any of these outputs is missing the object will be recompiled. This is supported only on Makefile generators and will be ignored on other generators.

    + +
  • +
  • + SYMBOLIC: Is this just a name for a rule.
    +

    If SYMBOLIC (boolean) is set to true the build system will be informed that the source file is not actually created on disk but instead used as a symbolic name for a build rule.

    + +
  • +
  • + WRAP_EXCLUDE: Exclude this source file from any code wrapping techniques.
    +

    Some packages can wrap source files into alternate languages to provide additional functionality. For example, C++ code can be wrapped into Java or Python etc using SWIG etc. If WRAP_EXCLUDE is set to true (1 etc) that indicates then this source file should not be wrapped.

    + +
  • +
+

Properties on Cache Entries

+ +
    +
  • + ADVANCED: True if entry should be hidden by default in GUIs.
    +

    This is a boolean value indicating whether the entry is considered interesting only for advanced configuration. The mark_as_advanced() command modifies this property.

    + +
  • +
  • + HELPSTRING: Help associated with entry in GUIs.
    +

    This string summarizes the purpose of an entry to help users set it through a CMake GUI.

    + +
  • +
  • + MODIFIED: Internal management property. Do not set or get.
    +

    This is an internal cache entry property managed by CMake to track interactive user modification of entries. Ignore it.

    + +
  • +
  • + STRINGS: Enumerate possible STRING entry values for GUI selection.
    +

    For cache entries with type STRING, this enumerates a set of values. CMake GUIs may use this to provide a selection widget instead of a generic string entry field. This is for convenience only. CMake does not enforce that the value matches one of those listed.

    + +
  • +
  • + TYPE: Widget type for entry in GUIs.
    +

    Cache entry values are always strings, but CMake GUIs present widgets to help users set values. The GUIs use this property as a hint to determine the widget type. Valid TYPE values are:

    +
      BOOL          = Boolean ON/OFF value.
    PATH = Path to a directory.
    FILEPATH = Path to a file.
    STRING = Generic string value.
    INTERNAL = Do not present in GUI at all.
    STATIC = Value managed by CMake, do not change.
    UNINITIALIZED = Type not yet specified.
    +

    Generally the TYPE of a cache entry should be set by the command which creates it (set, option, find_library, etc.).

    + +
  • +
  • + VALUE: Value of a cache entry.
    +

    This property maps to the actual value of a cache entry. Setting this property always sets the value without checking, so use with care.

    + +
  • +
+

Compatibility Commands

+ +
  CMake Compatibility Listfile Commands - Obsolete commands supported by CMake for compatibility.
+ +

This is the documentation for now obsolete listfile commands from previous CMake versions, which are still supported for compatibility reasons. You should instead use the newer, faster and shinier new commands. ;-)

+ +
    +
  • + build_name: Deprecated. Use ${CMAKE_SYSTEM} and ${CMAKE_CXX_COMPILER} instead.
    +
      build_name(variable)
    +

    Sets the specified variable to a string representing the platform and compiler settings. These values are now available through the CMAKE_SYSTEM and CMAKE_CXX_COMPILER variables.

    + +
  • +
  • + exec_program: Deprecated. Use the execute_process() command instead.
    +

    Run an executable program during the processing of the CMakeList.txt file.

    +
      exec_program(Executable [directory in which to run]
    [ARGS <arguments to executable>]
    [OUTPUT_VARIABLE <var>]
    [RETURN_VALUE <var>])
    +

    The executable is run in the optionally specified directory. The executable can include arguments if it is double quoted, but it is better to use the optional ARGS argument to specify arguments to the program. This is because cmake will then be able to escape spaces in the executable path. An optional argument OUTPUT_VARIABLE specifies a variable in which to store the output. To capture the return value of the execution, provide a RETURN_VALUE. If OUTPUT_VARIABLE is specified, then no output will go to the stdout/stderr of the console running cmake.

    + +
  • +
  • + export_library_dependencies: Deprecated. Use INSTALL(EXPORT) or EXPORT command.
    +

    This command generates an old-style library dependencies file. Projects requiring CMake 2.6 or later should not use the command. Use instead the install(EXPORT) command to help export targets from an installation tree and the export() command to export targets from a build tree.

    +

    The old-style library dependencies file does not take into account per-configuration names of libraries or the LINK_INTERFACE_LIBRARIES target property.

    +
      export_library_dependencies(<file> [APPEND])
    +

    Create a file named <file> that can be included into a CMake listfile with the INCLUDE command. The file will contain a number of SET commands that will set all the variables needed for library dependency information. This should be the last command in the top level CMakeLists.txt file of the project. If the APPEND option is specified, the SET commands will be appended to the given file instead of replacing it.

    + +
  • +
  • + install_files: Deprecated. Use the install(FILES ) command instead.
    +

    This command has been superceded by the install command. It is provided for compatibility with older CMake code. The FILES form is directly replaced by the FILES form of the install command. The regexp form can be expressed more clearly using the GLOB form of the file command.

    +
      install_files(<dir> extension file file ...)
    +

    Create rules to install the listed files with the given extension into the given directory. Only files existing in the current source tree or its corresponding location in the binary tree may be listed. If a file specified already has an extension, that extension will be removed first. This is useful for providing lists of source files such as foo.cxx when you want the corresponding foo.h to be installed. A typical extension is '.h'.

    +
      install_files(<dir> regexp)
    +

    Any files in the current source directory that match the regular expression will be installed.

    +
      install_files(<dir> FILES file file ...)
    +

    Any files listed after the FILES keyword will be installed explicitly from the names given. Full paths are allowed in this form.

    +

    The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX.

    + +
  • +
  • + install_programs: Deprecated. Use the install(PROGRAMS ) command instead.
    +

    This command has been superceded by the install command. It is provided for compatibility with older CMake code. The FILES form is directly replaced by the PROGRAMS form of the INSTALL command. The regexp form can be expressed more clearly using the GLOB form of the FILE command.

    +
      install_programs(<dir> file1 file2 [file3 ...])
    install_programs(<dir> FILES file1 [file2 ...])
    +

    Create rules to install the listed programs into the given directory. Use the FILES argument to guarantee that the file list version of the command will be used even when there is only one argument.

    +
      install_programs(<dir> regexp)
    +

    In the second form any program in the current source directory that matches the regular expression will be installed.

    +

    This command is intended to install programs that are not built by cmake, such as shell scripts. See the TARGETS form of the INSTALL command to create installation rules for targets built by cmake.

    +

    The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX.

    + +
  • +
  • + install_targets: Deprecated. Use the install(TARGETS ) command instead.
    +

    This command has been superceded by the install command. It is provided for compatibility with older CMake code.

    +
      install_targets(<dir> [RUNTIME_DIRECTORY dir] target target)
    +

    Create rules to install the listed targets into the given directory. The directory <dir> is relative to the installation prefix, which is stored in the variable CMAKE_INSTALL_PREFIX. If RUNTIME_DIRECTORY is specified, then on systems with special runtime files (Windows DLL), the files will be copied to that directory.

    + +
  • +
  • + link_libraries: Deprecated. Use the target_link_libraries() command instead.
    +

    Link libraries to all targets added later.

    +
      link_libraries(library1 <debug | optimized> library2 ...)
    +

    Specify a list of libraries to be linked into any following targets (typically added with the add_executable or add_library calls). This command is passed down to all subdirectories. The debug and optimized strings may be used to indicate that the next library listed is to be used only for that specific type of build.

    + +
  • +
  • + make_directory: Deprecated. Use the file(MAKE_DIRECTORY ) command instead.
    +
      make_directory(directory)
    +

    Creates the specified directory. Full paths should be given. Any parent directories that do not exist will also be created. Use with care.

    + +
  • +
  • + output_required_files: Deprecated. Approximate C preprocessor dependency scanning.
    +

    This command exists only because ancient CMake versions provided it. CMake handles preprocessor dependency scanning automatically using a more advanced scanner.

    +
      output_required_files(srcfile outputfile)
    +

    Outputs a list of all the source files that are required by the specified srcfile. This list is written into outputfile. This is similar to writing out the dependencies for srcfile except that it jumps from .h files into .cxx, .c and .cpp files if possible.

    + +
  • +
  • + remove: Deprecated. Use the list(REMOVE_ITEM ) command instead.
    +
      remove(VAR VALUE VALUE ...)
    +

    Removes VALUE from the variable VAR. This is typically used to remove entries from a vector (e.g. semicolon separated list). VALUE is expanded.

    + +
  • +
  • + subdir_depends: Deprecated. Does nothing.
    +
      subdir_depends(subdir dep1 dep2 ...)
    +

    Does not do anything. This command used to help projects order parallel builds correctly. This functionality is now automatic.

    + +
  • +
  • + subdirs: Deprecated. Use the add_subdirectory() command instead.
    +

    Add a list of subdirectories to the build.

    +
      subdirs(dir1 dir2 ...[EXCLUDE_FROM_ALL exclude_dir1 exclude_dir2 ...]
    [PREORDER] )
    +

    Add a list of subdirectories to the build. The add_subdirectory command should be used instead of subdirs although subdirs will still work. This will cause any CMakeLists.txt files in the sub directories to be processed by CMake. Any directories after the PREORDER flag are traversed first by makefile builds, the PREORDER flag has no effect on IDE projects. Any directories after the EXCLUDE_FROM_ALL marker will not be included in the top level makefile or project file. This is useful for having CMake create makefiles or projects for a set of examples in a project. You would want CMake to generate makefiles or project files for all the examples at the same time, but you would not want them to show up in the top level project or be built each time make is run from the top.

    + +
  • +
  • + use_mangled_mesa: Copy mesa headers for use in combination with system GL.
    +
      use_mangled_mesa(PATH_TO_MESA OUTPUT_DIRECTORY)
    +

    The path to mesa includes, should contain gl_mangle.h. The mesa headers are copied to the specified output directory. This allows mangled mesa headers to override other GL headers by being added to the include directory path earlier.

    + +
  • +
  • + utility_source: Specify the source tree of a third-party utility.
    +
      utility_source(cache_entry executable_name
    path_to_source [file1 file2 ...])
    +

    When a third-party utility's source is included in the distribution, this command specifies its location and name. The cache entry will not be set unless the path_to_source and all listed files exist. It is assumed that the source tree of the utility will have been built before it is needed.

    +

    When cross compiling CMake will print a warning if a utility_source() command is executed, because in many cases it is used to build an executable which is executed later on. This doesn't work when cross compiling, since the executable can run only on their target platform. So in this case the cache entry has to be adjusted manually so it points to an executable which is runnable on the build host.

    + +
  • +
  • + variable_requires: Deprecated. Use the if() command instead.
    +

    Assert satisfaction of an option's required variables.

    +
      variable_requires(TEST_VARIABLE RESULT_VARIABLE
    REQUIRED_VARIABLE1
    REQUIRED_VARIABLE2 ...)
    +

    The first argument (TEST_VARIABLE) is the name of the variable to be tested, if that variable is false nothing else is done. If TEST_VARIABLE is true, then the next argument (RESULT_VARIABLE) is a variable that is set to true if all the required variables are set. The rest of the arguments are variables that must be true or not set to NOTFOUND to avoid an error. If any are not true, an error is reported.

    + +
  • +
  • + write_file: Deprecated. Use the file(WRITE ) command instead.
    +
      write_file(filename "message to write"... [APPEND])
    +

    The first argument is the file name, the rest of the arguments are messages to write. If the argument APPEND is specified, then the message will be appended.

    +

    NOTE 1: file(WRITE ... and file(APPEND ... do exactly the same as this one but add some more functionality.

    +

    NOTE 2: When using write_file the produced file cannot be used as an input to CMake (CONFIGURE_FILE, source file ...) because it will lead to an infinite loop. Use configure_file if you want to generate input files to CMake.

    + +
  • +
+

Standard CMake Modules

+ +

The following modules are provided with CMake. They can be used with INCLUDE(ModuleName).

+ +
  CMake Modules - Modules coming with CMake, the Cross-Platform Makefile Generator.
+ +

This is the documentation for the modules and scripts coming with CMake. Using these modules you can check the computer system for installed software packages, features of the compiler and the existance of headers to name just a few.

+ +
    +
  • + AddFileDependencies: ADD_FILE_DEPENDENCIES(source_file depend_files...)
    +

    Adds the given files as dependencies to source_file

    + +
  • +
  • + BundleUtilities: Functions to help assemble a standalone bundle application.
    +

    A collection of CMake utility functions useful for dealing with .app bundles on the Mac and bundle-like directories on any OS.

    +

    The following functions are provided by this module:

    +
       fixup_bundle
    copy_and_fixup_bundle
    verify_app
    get_bundle_main_executable
    get_dotapp_dir
    get_bundle_and_executable
    get_bundle_all_executables
    get_item_key
    clear_bundle_keys
    set_bundle_key_values
    get_bundle_keys
    copy_resolved_item_into_bundle
    copy_resolved_framework_into_bundle
    fixup_bundle_item
    verify_bundle_prerequisites
    verify_bundle_symlinks
    +

    Requires CMake 2.6 or greater because it uses function, break and PARENT_SCOPE. Also depends on GetPrerequisites.cmake.

    +
      FIXUP_BUNDLE(<app> <libs> <dirs>)
    +

    Fix up a bundle in-place and make it standalone, such that it can be drag-n-drop copied to another machine and run on that machine as long as all of the system libraries are compatible.

    +

    If you pass plugins to fixup_bundle as the libs parameter, you should install them or copy them into the bundle before calling fixup_bundle. The "libs" parameter is a list of libraries that must be fixed up, but that cannot be determined by otool output analysis. (i.e., plugins)

    +

    Gather all the keys for all the executables and libraries in a bundle, and then, for each key, copy each prerequisite into the bundle. Then fix each one up according to its own list of prerequisites.

    +

    Then clear all the keys and call verify_app on the final bundle to ensure that it is truly standalone.

    +
      COPY_AND_FIXUP_BUNDLE(<src> <dst> <libs> <dirs>)
    +

    Makes a copy of the bundle <src> at location <dst> and then fixes up the new copied bundle in-place at <dst>...

    +
      VERIFY_APP(<app>)
    +

    Verifies that an application <app> appears valid based on running analysis tools on it. Calls "message(FATAL_ERROR" if the application is not verified.

    +
      GET_BUNDLE_MAIN_EXECUTABLE(<bundle> <result_var>)
    +

    The result will be the full path name of the bundle's main executable file or an "error:" prefixed string if it could not be determined.

    +
      GET_DOTAPP_DIR(<exe> <dotapp_dir_var>)
    +

    Returns the nearest parent dir whose name ends with ".app" given the full path to an executable. If there is no such parent dir, then simply return the dir containing the executable.

    +

    The returned directory may or may not exist.

    +
      GET_BUNDLE_AND_EXECUTABLE(<app> <bundle_var> <executable_var> <valid_var>)
    +

    Takes either a ".app" directory name or the name of an executable nested inside a ".app" directory and returns the path to the ".app" directory in <bundle_var> and the path to its main executable in <executable_var>

    +
      GET_BUNDLE_ALL_EXECUTABLES(<bundle> <exes_var>)
    +

    Scans the given bundle recursively for all executable files and accumulates them into a variable.

    +
      GET_ITEM_KEY(<item> <key_var>)
    +

    Given a file (item) name, generate a key that should be unique considering the set of libraries that need copying or fixing up to make a bundle standalone. This is essentially the file name including extension with "." replaced by "_"

    +

    This key is used as a prefix for CMake variables so that we can associate a set of variables with a given item based on its key.

    +
      CLEAR_BUNDLE_KEYS(<keys_var>)
    +

    Loop over the list of keys, clearing all the variables associated with each key. After the loop, clear the list of keys itself.

    +

    Caller of get_bundle_keys should call clear_bundle_keys when done with list of keys.

    +
      SET_BUNDLE_KEY_VALUES(<keys_var> <context> <item> <exepath> <dirs>
    <copyflag>)
    +

    Add a key to the list (if necessary) for the given item. If added, also set all the variables associated with that key.

    +
      GET_BUNDLE_KEYS(<app> <libs> <dirs> <keys_var>)
    +

    Loop over all the executable and library files within the bundle (and given as extra <libs>) and accumulate a list of keys representing them. Set values associated with each key such that we can loop over all of them and copy prerequisite libs into the bundle and then do appropriate install_name_tool fixups.

    +
      COPY_RESOLVED_ITEM_INTO_BUNDLE(<resolved_item> <resolved_embedded_item>)
    +

    Copy a resolved item into the bundle if necessary. Copy is not necessary if the resolved_item is "the same as" the resolved_embedded_item.

    +
      COPY_RESOLVED_FRAMEWORK_INTO_BUNDLE(<resolved_item> <resolved_embedded_item>)
    +

    Copy a resolved framework into the bundle if necessary. Copy is not necessary if the resolved_item is "the same as" the resolved_embedded_item.

    +

    By default, BU_COPY_FULL_FRAMEWORK_CONTENTS is not set. If you want full frameworks embedded in your bundles, set BU_COPY_FULL_FRAMEWORK_CONTENTS to ON before calling fixup_bundle. By default, COPY_RESOLVED_FRAMEWORK_INTO_BUNDLE copies the framework dylib itself plus the framework Resources directory.

    +
      FIXUP_BUNDLE_ITEM(<resolved_embedded_item> <exepath> <dirs>)
    +

    Get the direct/non-system prerequisites of the resolved embedded item. For each prerequisite, change the way it is referenced to the value of the _EMBEDDED_ITEM keyed variable for that prerequisite. (Most likely changing to an "@executable_path" style reference.)

    +

    This function requires that the resolved_embedded_item be "inside" the bundle already. In other words, if you pass plugins to fixup_bundle as the libs parameter, you should install them or copy them into the bundle before calling fixup_bundle. The "libs" parameter is a list of libraries that must be fixed up, but that cannot be determined by otool output analysis. (i.e., plugins)

    +

    Also, change the id of the item being fixed up to its own _EMBEDDED_ITEM value.

    +

    Accumulate changes in a local variable and make *one* call to install_name_tool at the end of the function with all the changes at once.

    +

    If the BU_CHMOD_BUNDLE_ITEMS variable is set then bundle items will be marked writable before install_name_tool tries to change them.

    +
      VERIFY_BUNDLE_PREREQUISITES(<bundle> <result_var> <info_var>)
    +

    Verifies that the sum of all prerequisites of all files inside the bundle are contained within the bundle or are "system" libraries, presumed to exist everywhere.

    +
      VERIFY_BUNDLE_SYMLINKS(<bundle> <result_var> <info_var>)
    +

    Verifies that any symlinks found in the bundle point to other files that are already also in the bundle... Anything that points to an external file causes this function to fail the verification.

    + +
  • +
  • + CMakeBackwardCompatibilityCXX: define a bunch of backwards compatibility variables
    +
      CMAKE_ANSI_CXXFLAGS - flag for ansi c++ 
    CMAKE_HAS_ANSI_STRING_STREAM - has <strstream>
    INCLUDE(TestForANSIStreamHeaders)
    INCLUDE(CheckIncludeFileCXX)
    INCLUDE(TestForSTDNamespace)
    INCLUDE(TestForANSIForScope)
    + +
  • +
  • + CMakeDependentOption: Macro to provide an option dependent on other options.
    +

    This macro presents an option to the user only if a set of other conditions are true. When the option is not presented a default value is used, but any value set by the user is preserved for when the option is presented again. Example invocation:

    +
      CMAKE_DEPENDENT_OPTION(USE_FOO "Use Foo" ON
    "USE_BAR;NOT USE_ZOT" OFF)
    +

    If USE_BAR is true and USE_ZOT is false, this provides an option called USE_FOO that defaults to ON. Otherwise, it sets USE_FOO to OFF. If the status of USE_BAR or USE_ZOT ever changes, any value for the USE_FOO option is saved so that when the option is re-enabled it retains its old value.

    + +
  • +
  • + CMakeDetermineVSServicePack: Includes a public function for assisting users in trying to determine the
    +

    Visual Studio service pack in use.

    +

    Sets the passed in variable to one of the following values or an empty string if unknown.

    +
        vc80
    vc80sp1
    vc90
    vc90sp1
    vc100
    vc100sp1
    +


    +

    Usage: ===========================

    +
        if(MSVC)
    include(CMakeDetermineVSServicePack)
    DetermineVSServicePack( my_service_pack )
    +


    +
           if( my_service_pack )
    message(STATUS "Detected: ${my_service_pack}")
    endif()
    endif()
    +


    +

    ===========================

    + +
  • +
  • + CMakeFindFrameworks: helper module to find OSX frameworks +
  • +
  • + CMakeFindPackageMode:
    +

    This file is executed by cmake when invoked with --find-package. It expects that the following variables are set using -D:

    +
       NAME = name of the package
    COMPILER_ID = the CMake compiler ID for which the result is, i.e. GNU/Intel/Clang/MSVC, etc.
    LANGUAGE = language for which the result will be used, i.e. C/CXX/Fortan/ASM
    MODE = EXIST : only check for existance of the given package
    COMPILE : print the flags needed for compiling an object file which uses the given package
    LINK : print the flags needed for linking when using the given package
    QUIET = if TRUE, don't print anything
    + +
  • +
  • + CMakeForceCompiler:
    +

    This module defines macros intended for use by cross-compiling toolchain files when CMake is not able to automatically detect the compiler identification.

    +

    Macro CMAKE_FORCE_C_COMPILER has the following signature:

    +
       CMAKE_FORCE_C_COMPILER(<compiler> <compiler-id>)
    +

    It sets CMAKE_C_COMPILER to the given compiler and the cmake internal variable CMAKE_C_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

    +

    Macro CMAKE_FORCE_CXX_COMPILER has the following signature:

    +
       CMAKE_FORCE_CXX_COMPILER(<compiler> <compiler-id>)
    +

    It sets CMAKE_CXX_COMPILER to the given compiler and the cmake internal variable CMAKE_CXX_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

    +

    Macro CMAKE_FORCE_Fortran_COMPILER has the following signature:

    +
       CMAKE_FORCE_Fortran_COMPILER(<compiler> <compiler-id>)
    +

    It sets CMAKE_Fortran_COMPILER to the given compiler and the cmake internal variable CMAKE_Fortran_COMPILER_ID to the given compiler-id. It also bypasses the check for working compiler and basic compiler information tests.

    +

    So a simple toolchain file could look like this:

    +
       INCLUDE (CMakeForceCompiler)
    SET(CMAKE_SYSTEM_NAME Generic)
    CMAKE_FORCE_C_COMPILER (chc12 MetrowerksHicross)
    CMAKE_FORCE_CXX_COMPILER (chc12 MetrowerksHicross)
    + +
  • +
  • + CMakeParseArguments:
    +

    CMAKE_PARSE_ARGUMENTS(<prefix> <options> <one_value_keywords> <multi_value_keywords> args...)

    +

    CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions for parsing the arguments given to that macro or function. It processes the arguments and defines a set of variables which hold the values of the respective options.

    +

    The <options> argument contains all options for the respective macro, i.e. keywords which can be used when calling the macro without any value following, like e.g. the OPTIONAL keyword of the install() command.

    +

    The <one_value_keywords> argument contains all keywords for this macro which are followed by one value, like e.g. DESTINATION keyword of the install() command.

    +

    The <multi_value_keywords> argument contains all keywords for this macro which can be followed by more than one value, like e.g. the TARGETS or FILES keywords of the install() command.

    +

    When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the keywords listed in <options>, <one_value_keywords> and <multi_value_keywords> a variable composed of the given <prefix> followed by "_" and the name of the respective keyword. These variables will then hold the respective value from the argument list. For the <options> keywords this will be TRUE or FALSE.

    +

    All remaining arguments are collected in a variable <prefix>_UNPARSED_ARGUMENTS, this can be checked afterwards to see whether your macro was called with unrecognized parameters.

    +

    As an example here a my_install() macro, which takes similar arguments as the real install() command:

    +
       function(MY_INSTALL)
    set(options OPTIONAL FAST)
    set(oneValueArgs DESTINATION RENAME)
    set(multiValueArgs TARGETS CONFIGURATIONS)
    cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
    ...
    +


    +

    Assume my_install() has been called like this:

    +
       my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub)
    +


    +

    After the cmake_parse_arguments() call the macro will have set the following variables:

    +
       MY_INSTALL_OPTIONAL = TRUE
    MY_INSTALL_FAST = FALSE (this option was not used when calling my_install()
    MY_INSTALL_DESTINATION = "bin"
    MY_INSTALL_RENAME = "" (was not used)
    MY_INSTALL_TARGETS = "foo;bar"
    MY_INSTALL_CONFIGURATIONS = "" (was not used)
    MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL"
    +


    +

    You can the continue and process these variables.

    +

    Keywords terminate lists of values, e.g. if directly after a one_value_keyword another recognized keyword follows, this is interpreted as the beginning of the new option. E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION would be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor.

    + +
  • +
  • + CMakePrintSystemInformation: print system information
    +

    This file can be used for diagnostic purposes just include it in a project to see various internal CMake variables.

    + +
  • +
  • + CMakePushCheckState:
    +

    This module defines two macros: CMAKE_PUSH_CHECK_STATE() and CMAKE_POP_CHECK_STATE() These two macros can be used to save and restore the state of the variables CMAKE_REQUIRED_FLAGS, CMAKE_REQUIRED_DEFINITIONS, CMAKE_REQUIRED_LIBRARIES and CMAKE_REQUIRED_INCLUDES used by the various Check-files coming with CMake, like e.g. check_function_exists() etc. The variable contents are pushed on a stack, pushing multiple times is supported. This is useful e.g. when executing such tests in a Find-module, where they have to be set, but after the Find-module has been executed they should have the same value as they had before.

    +

    Usage:

    +
       cmake_push_check_state()
    set(CMAKE_REQUIRED_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} -DSOME_MORE_DEF)
    check_function_exists(...)
    cmake_pop_check_state()
    + +
  • +
  • + CMakeVerifyManifest:
    +

    CMakeVerifyManifest.cmake

    +

    This script is used to verify that embeded manifests and side by side manifests for a project match. To run this script, cd to a directory and run the script with cmake -P. On the command line you can pass in versions that are OK even if not found in the .manifest files. For example, cmake -Dallow_versions=8.0.50608.0 -PCmakeVerifyManifest.cmake could be used to allow an embeded manifest of 8.0.50608.0 to be used in a project even if that version was not found in the .manifest file.

    + +
  • +
  • + CPack: foreach generator, it then
    +


    +

    The CPack module generates binary and source installers in a variety of formats using the cpack program. Inclusion of the CPack module adds two new targets to the resulting makefiles, package and package_source, which build the binary and source installers, respectively. The generated binary installers contain everything installed via CMake's INSTALL command (and the deprecated INSTALL_FILES, INSTALL_PROGRAMS, and INSTALL_TARGETS commands).

    +

    For certain kinds of binary installers (including the graphical installers on Mac OS X and Windows), CPack generates installers that allow users to select individual application components to install. See CPackComponent module for that.

    +

    The CPACK_GENERATOR variable has different meanings in different contexts. In your CMakeLists.txt file, CPACK_GENERATOR is a *list of generators*: when run with no other arguments, CPack will iterate over that list and produce one package for each generator. In a CPACK_PROJECT_CONFIG_FILE, though, CPACK_GENERATOR is a *string naming a single generator*. If you need per-cpack- generator logic to control *other* cpack settings, then you need a CPACK_PROJECT_CONFIG_FILE.

    +

    The CMake source tree itself contains a CPACK_PROJECT_CONFIG_FILE. See the top level file CMakeCPackOptions.cmake.in for an example.

    +

    If set, the CPACK_PROJECT_CONFIG_FILE is included automatically on a per-generator basis. It only need contain overrides.

    +

    Here's how it works:

    +
         CPACK_GENERATOR list variable (unless told to use just a
    specific one via -G on the command line...)
    +


    +
       - sets CPACK_GENERATOR to the one currently being iterated
    - includes the CPACK_PROJECT_CONFIG_FILE
    - produces the package for that generator
    +


    +

    This is the key: For each generator listed in CPACK_GENERATOR in CPackConfig.cmake, cpack will *reset* CPACK_GENERATOR internally to *the one currently being used* and then include the CPACK_PROJECT_CONFIG_FILE.

    +

    Before including this CPack module in your CMakeLists.txt file, there are a variety of variables that can be set to customize the resulting installers. The most commonly-used variables are:

    +
       CPACK_PACKAGE_NAME - The name of the package (or application). If
    not specified, defaults to the project name.
    +


    +
       CPACK_PACKAGE_VENDOR - The name of the package vendor (e.g.,
    "Kitware").
    +


    +
       CPACK_PACKAGE_VERSION_MAJOR - Package major Version
    +


    +
       CPACK_PACKAGE_VERSION_MINOR - Package minor Version
    +


    +
       CPACK_PACKAGE_VERSION_PATCH - Package patch Version
    +


    +
       CPACK_PACKAGE_DESCRIPTION_FILE - A text file used to describe the
    project. Used, for example, the introduction screen of a
    CPack-generated Windows installer to describe the project.
    +


    +
       CPACK_PACKAGE_DESCRIPTION_SUMMARY - Short description of the
    project (only a few words).
    +


    +
       CPACK_PACKAGE_FILE_NAME - The name of the package file to generate,
    not including the extension. For example, cmake-2.6.1-Linux-i686.
    +


    +
       CPACK_PACKAGE_INSTALL_DIRECTORY - Installation directory on the
    target system, e.g., "CMake 2.5".
    +


    +
       CPACK_PROJECT_CONFIG_FILE - File included at cpack time, once per
    generator after setting CPACK_GENERATOR to the actual generator
    being used. Allows per-generator setting of CPACK_* variables at
    cpack time.
    +


    +
       CPACK_RESOURCE_FILE_LICENSE - License file for the project, which
    will typically be displayed to the user (often with an explicit
    "Accept" button, for graphical installers) prior to installation.
    +


    +
       CPACK_RESOURCE_FILE_README - ReadMe file for the project, which
    typically describes in some detail
    +


    +
       CPACK_RESOURCE_FILE_WELCOME - Welcome file for the project, which
    welcomes users to this installer. Typically used in the graphical
    installers on Windows and Mac OS X.
    +


    +
       CPACK_MONOLITHIC_INSTALL - Disables the component-based 
    installation mechanism, so that all components are always installed.
    +


    +
       CPACK_GENERATOR - List of CPack generators to use. If not
    specified, CPack will create a set of options (e.g.,
    CPACK_BINARY_NSIS) allowing the user to enable/disable individual
    generators.
    +


    +
       CPACK_OUTPUT_CONFIG_FILE - The name of the CPack configuration file
    for binary installers that will be generated by the CPack
    module. Defaults to CPackConfig.cmake.
    +


    +
       CPACK_PACKAGE_EXECUTABLES - Lists each of the executables along
    with a text label, to be used to create Start Menu shortcuts on
    Windows. For example, setting this to the list ccmake;CMake will
    create a shortcut named "CMake" that will execute the installed
    executable ccmake.
    +


    +
       CPACK_STRIP_FILES - List of files to be stripped. Starting with
    CMake 2.6.0 CPACK_STRIP_FILES will be a boolean variable which
    enables stripping of all files (a list of files evaluates to TRUE
    in CMake, so this change is compatible).
    +


    +

    The following CPack variables are specific to source packages, and will not affect binary packages:

    +
       CPACK_SOURCE_PACKAGE_FILE_NAME - The name of the source package,
    e.g., cmake-2.6.1
    +


    +
       CPACK_SOURCE_STRIP_FILES - List of files in the source tree that
    will be stripped. Starting with CMake 2.6.0
    CPACK_SOURCE_STRIP_FILES will be a boolean variable which enables
    stripping of all files (a list of files evaluates to TRUE in CMake,
    so this change is compatible).
    +


    +
       CPACK_SOURCE_GENERATOR - List of generators used for the source
    packages. As with CPACK_GENERATOR, if this is not specified then
    CPack will create a set of options (e.g., CPACK_SOURCE_ZIP)
    allowing users to select which packages will be generated.
    +


    +
       CPACK_SOURCE_OUTPUT_CONFIG_FILE - The name of the CPack
    configuration file for source installers that will be generated by
    the CPack module. Defaults to CPackSourceConfig.cmake.
    +


    +
       CPACK_SOURCE_IGNORE_FILES - Pattern of files in the source tree
    that won't be packaged when building a source package. This is a
    list of patterns, e.g., /CVS/;/\\.svn/;\\.swp$;\\.#;/#;.*~;cscope.*
    +


    +

    The following variables are specific to the DragNDrop installers built on Mac OS X:

    +
       CPACK_DMG_VOLUME_NAME - The volume name of the generated disk
    image. Defaults to CPACK_PACKAGE_FILE_NAME.
    +


    +
       CPACK_DMG_FORMAT - The disk image format. Common values are UDRO
    (UDIF read-only), UDZO (UDIF zlib-compressed) or UDBZ (UDIF
    bzip2-compressed). Refer to hdiutil(1) for more information on
    other available formats.
    +


    +
       CPACK_DMG_DS_STORE - Path to a custom .DS_Store file which e.g.
    can be used to specify the Finder window position/geometry and
    layout (such as hidden toolbars, placement of the icons etc.).
    This file has to be generated by the Finder (either manually or
    through OSA-script) using a normal folder from which the .DS_Store
    file can then be extracted.
    +


    +
       CPACK_DMG_BACKGROUND_IMAGE - Path to an image file which is to be
    used as the background for the Finder Window when the disk image
    is opened. By default no background image is set. The background
    image is applied after applying the custom .DS_Store file.
    +


    +
       CPACK_COMMAND_HDIUTIL - Path to the hdiutil(1) command used to
    operate on disk image files on Mac OS X. This variable can be used
    to override the automatically detected command (or specify its
    location if the auto-detection fails to find it.)
    +


    +
       CPACK_COMMAND_SETFILE - Path to the SetFile(1) command used to set
    extended attributes on files and directories on Mac OS X. This
    variable can be used to override the automatically detected
    command (or specify its location if the auto-detection fails to
    find it.)
    +


    +
       CPACK_COMMAND_REZ - Path to the Rez(1) command used to compile
    resources on Mac OS X. This variable can be used to override the
    automatically detected command (or specify its location if the
    auto-detection fails to find it.)
    +


    +

    The following variable is specific to installers build on Mac OS X using PackageMaker:

    +
       CPACK_OSX_PACKAGE_VERSION - The version of Mac OS X that the
    resulting PackageMaker archive should be compatible
    with. Different versions of Mac OS X support different
    features. For example, CPack can only build component-based
    installers for Mac OS X 10.4 or newer, and can only build
    installers that download component son-the-fly for Mac OS X 10.5
    or newer. If left blank, this value will be set to the minimum
    version of Mac OS X that supports the requested features. Set this
    variable to some value (e.g., 10.4) only if you want to guarantee
    that your installer will work on that version of Mac OS X, and
    don't mind missing extra features available in the installer
    shipping with later versions of Mac OS X.
    +


    +

    The following variables are for advanced uses of CPack:

    +
       CPACK_CMAKE_GENERATOR - What CMake generator should be used if the
    project is CMake project. Defaults to the value of CMAKE_GENERATOR;
    few users will want to change this setting.
    +


    +
       CPACK_INSTALL_CMAKE_PROJECTS - List of four values that specify
    what project to install. The four values are: Build directory,
    Project Name, Project Component, Directory. If omitted, CPack will
    build an installer that installers everything.
    +


    +
       CPACK_SYSTEM_NAME - System name, defaults to the value of
    ${CMAKE_SYSTEM_NAME}.
    +


    +
       CPACK_PACKAGE_VERSION - Package full version, used internally. By
    default, this is built from CPACK_PACKAGE_VERSION_MAJOR,
    CPACK_PACKAGE_VERSION_MINOR, and CPACK_PACKAGE_VERSION_PATCH.
    +


    +
       CPACK_TOPLEVEL_TAG - Directory for the installed files.
    +


    +
       CPACK_INSTALL_COMMANDS - Extra commands to install components.
    +


    +
       CPACK_INSTALLED_DIRECTORIES - Extra directories to install.
    +


    + +
  • +
  • + CPackBundle: CPack Bundle generator (Mac OS X) specific options
    +


    +

    Installers built on Mac OS X using the Bundle generator use the aforementioned DragNDrop variables, plus the following Bundle-specific parameters:

    +
       CPACK_BUNDLE_NAME - The name of the generated bundle.  This
    appears in the OSX finder as the bundle name. Required.
    +


    +
       CPACK_BUNDLE_PLIST - Path to an OSX plist file that will be used
    as the Info.plist for the generated bundle. This assumes that
    the caller has generated or specified their own Info.plist file.
    Required.
    +


    +
       CPACK_BUNDLE_ICON - Path to an OSX icns file that will be used as
    the icon for the generated bundle. This is the icon that appears
    in the OSX finder for the bundle, and in the OSX dock when the
    bundle is opened. Required.
    +


    +
       CPACK_BUNDLE_STARTUP_SCRIPT - Path to an executable or script that
    will be run whenever an end-user double-clicks the generated bundle
    in the OSX Finder. Optional.
    + +
  • +
  • + CPackComponent: Build binary and source package installers
    +


    +

    The CPackComponent module is the module which handles the component part of CPack. See CPack module for general information about CPack.

    +

    For certain kinds of binary installers (including the graphical installers on Mac OS X and Windows), CPack generates installers that allow users to select individual application components to install. The contents of each of the components are identified by the COMPONENT argument of CMake's INSTALL command. These components can be annotated with user-friendly names and descriptions, inter-component dependencies, etc., and grouped in various ways to customize the resulting installer. See the cpack_add_* commands, described below, for more information about component-specific installations.

    +

    Component-specific installation allows users to select specific sets of components to install during the install process. Installation components are identified by the COMPONENT argument of CMake's INSTALL commands, and should be further described by the following CPack commands:

    +
       cpack_add_component - Describes a CPack installation component
    named by the COMPONENT argument to a CMake INSTALL command.
    +


    +
         cpack_add_component(compname
    [DISPLAY_NAME name]
    [DESCRIPTION description]
    [HIDDEN | REQUIRED | DISABLED ]
    [GROUP group]
    [DEPENDS comp1 comp2 ... ]
    [INSTALL_TYPES type1 type2 ... ]
    [DOWNLOADED]
    [ARCHIVE_FILE filename])
    +


    +
       The cmake_add_component command describes an installation
    component, which the user can opt to install or remove as part of
    the graphical installation process. compname is the name of the
    component, as provided to the COMPONENT argument of one or more
    CMake INSTALL commands.
    +


    +
       DISPLAY_NAME is the displayed name of the component, used in
    graphical installers to display the component name. This value can
    be any string.
    +


    +
       DESCRIPTION is an extended description of the component, used in
    graphical installers to give the user additional information about
    the component. Descriptions can span multiple lines using "\n" as
    the line separator. Typically, these descriptions should be no
    more than a few lines long.
    +


    +
       HIDDEN indicates that this component will be hidden in the
    graphical installer, so that the user cannot directly change
    whether it is installed or not.
    +


    +
       REQUIRED indicates that this component is required, and therefore
    will always be installed. It will be visible in the graphical
    installer, but it cannot be unselected. (Typically, required
    components are shown greyed out).
    +


    +
       DISABLED indicates that this component should be disabled
    (unselected) by default. The user is free to select this component
    for installation, unless it is also HIDDEN.
    +


    +
       DEPENDS lists the components on which this component depends. If
    this component is selected, then each of the components listed
    must also be selected. The dependency information is encoded
    within the installer itself, so that users cannot install
    inconsitent sets of components.
    +


    +
       GROUP names the component group of which this component is a
    part. If not provided, the component will be a standalone
    component, not part of any component group. Component groups are
    described with the cpack_add_component_group command, detailed
    below.
    +


    +
       INSTALL_TYPES lists the installation types of which this component
    is a part. When one of these installations types is selected, this
    component will automatically be selected. Installation types are
    described with the cpack_add_install_type command, detailed below.
    +


    +
       DOWNLOADED indicates that this component should be downloaded
    on-the-fly by the installer, rather than packaged in with the
    installer itself. For more information, see the cpack_configure_downloads
    command.
    +


    +
       ARCHIVE_FILE provides a name for the archive file created by CPack
    to be used for downloaded components. If not supplied, CPack will
    create a file with some name based on CPACK_PACKAGE_FILE_NAME and
    the name of the component. See cpack_configure_downloads for more
    information.
    +


    +
       cpack_add_component_group - Describes a group of related CPack
    installation components.
    +


    +
         cpack_add_component_group(groupname
    [DISPLAY_NAME name]
    [DESCRIPTION description]
    [PARENT_GROUP parent]
    [EXPANDED]
    [BOLD_TITLE])
    +


    +
       The cpack_add_component_group describes a group of installation
    components, which will be placed together within the listing of
    options. Typically, component groups allow the user to
    select/deselect all of the components within a single group via a
    single group-level option. Use component groups to reduce the
    complexity of installers with many options. groupname is an
    arbitrary name used to identify the group in the GROUP argument of
    the cpack_add_component command, which is used to place a
    component in a group. The name of the group must not conflict with
    the name of any component.
    +


    +
       DISPLAY_NAME is the displayed name of the component group, used in
    graphical installers to display the component group name. This
    value can be any string.
    +


    +
       DESCRIPTION is an extended description of the component group,
    used in graphical installers to give the user additional
    information about the components within that group. Descriptions
    can span multiple lines using "\n" as the line
    separator. Typically, these descriptions should be no more than a
    few lines long.
    +


    +
       PARENT_GROUP, if supplied, names the parent group of this group.
    Parent groups are used to establish a hierarchy of groups,
    providing an arbitrary hierarchy of groups.
    +


    +
       EXPANDED indicates that, by default, the group should show up as
    "expanded", so that the user immediately sees all of the
    components within the group. Otherwise, the group will initially
    show up as a single entry.
    +


    +
       BOLD_TITLE indicates that the group title should appear in bold,
    to call the user's attention to the group.
    +


    +
       cpack_add_install_type - Add a new installation type containing a
    set of predefined component selections to the graphical installer.
    +


    +
         cpack_add_install_type(typename
    [DISPLAY_NAME name])
    +


    +
       The cpack_add_install_type command identifies a set of preselected
    components that represents a common use case for an
    application. For example, a "Developer" install type might include
    an application along with its header and library files, while an
    "End user" install type might just include the application's
    executable. Each component identifies itself with one or more
    install types via the INSTALL_TYPES argument to
    cpack_add_component.
    +


    +
       DISPLAY_NAME is the displayed name of the install type, which will
    typically show up in a drop-down box within a graphical
    installer. This value can be any string.
    +


    +
       cpack_configure_downloads - Configure CPack to download selected
    components on-the-fly as part of the installation process.
    +


    +
         cpack_configure_downloads(site
    [UPLOAD_DIRECTORY dirname]
    [ALL]
    [ADD_REMOVE|NO_ADD_REMOVE])
    +


    +
       The cpack_configure_downloads command configures installation-time
    downloads of selected components. For each downloadable component,
    CPack will create an archive containing the contents of that
    component, which should be uploaded to the given site. When the
    user selects that component for installation, the installer will
    download and extract the component in place. This feature is
    useful for creating small installers that only download the
    requested components, saving bandwidth. Additionally, the
    installers are small enough that they will be installed as part of
    the normal installation process, and the "Change" button in
    Windows Add/Remove Programs control panel will allow one to add or
    remove parts of the application after the original
    installation. On Windows, the downloaded-components functionality
    requires the ZipDLL plug-in for NSIS, available at:
    +


    +
         http://nsis.sourceforge.net/ZipDLL_plug-in
    +


    +
       On Mac OS X, installers that download components on-the-fly can
    only be built and installed on system using Mac OS X 10.5 or
    later.
    +


    +
       The site argument is a URL where the archives for downloadable
    components will reside, e.g., http://www.cmake.org/files/2.6.1/installer/
    All of the archives produced by CPack should be uploaded to that location.
    +


    +
       UPLOAD_DIRECTORY is the local directory where CPack will create the
    various archives for each of the components. The contents of this
    directory should be uploaded to a location accessible by the URL given
    in the site argument. If omitted, CPack will use the directory
    CPackUploads inside the CMake binary directory to store the generated
    archives.
    +


    +
       The ALL flag indicates that all components be downloaded. Otherwise, only
    those components explicitly marked as DOWNLOADED or that have a specified
    ARCHIVE_FILE will be downloaded. Additionally, the ALL option implies
    ADD_REMOVE (unless NO_ADD_REMOVE is specified).
    +


    +
       ADD_REMOVE indicates that CPack should install a copy of the installer
    that can be called from Windows' Add/Remove Programs dialog (via the
    "Modify" button) to change the set of installed components. NO_ADD_REMOVE
    turns off this behavior. This option is ignored on Mac OS X.
    + +
  • +
  • + CPackDeb: The builtin (binary) CPack Deb generator (Unix only)
    +

    CPackDeb may be used to create Deb package using CPack. CPackDeb is a CPack generator thus it uses the CPACK_XXX variables used by CPack : http://www.cmake.org/Wiki/CMake:CPackConfiguration. CPackDeb generator should work on any linux host but it will produce better deb package when Debian specific tools 'dpkg-xxx' are usable on the build system.

    +

    CPackDeb has specific features which are controlled by the specifics CPACK_DEBIAN_XXX variables.You'll find a detailed usage on the wiki:

    +
      http://www.cmake.org/Wiki/CMake:CPackPackageGenerators#DEB_.28UNIX_only.29
    +

    However as a handy reminder here comes the list of specific variables:

    +

    CPACK_DEBIAN_PACKAGE_NAME

    +
         Mandatory : YES
    Default : CPACK_PACKAGE_NAME (lower case)
    The debian package summary
    +

    CPACK_DEBIAN_PACKAGE_VERSION

    +
         Mandatory : YES
    Default : CPACK_PACKAGE_VERSION
    The debian package version
    +

    CPACK_DEBIAN_PACKAGE_ARCHITECTURE

    +
         Mandatory : YES
    Default : Output of dpkg --print-architecture (or i386 if dpkg is not found)
    The debian package architecture
    +

    CPACK_DEBIAN_PACKAGE_DEPENDS

    +
         Mandatory : NO
    Default : -
    May be used to set deb dependencies.
    +

    CPACK_DEBIAN_PACKAGE_MAINTAINER

    +
         Mandatory : YES
    Default : CPACK_PACKAGE_CONTACT
    The debian package maintainer
    +

    CPACK_DEBIAN_PACKAGE_DESCRIPTION

    +
         Mandatory : YES
    Default : CPACK_PACKAGE_DESCRIPTION_SUMMARY
    The debian package description
    +

    CPACK_DEBIAN_PACKAGE_SECTION

    +
         Mandatory : YES
    Default : 'devel'
    The debian package section
    +

    CPACK_DEBIAN_PACKAGE_PRIORITY

    +
         Mandatory : YES
    Default : 'optional'
    The debian package priority
    +

    CPACK_DEBIAN_PACKAGE_HOMEPAGE

    +
         Mandatory : NO
    Default : -
    The URL of the web site for this package
    +

    CPACK_DEBIAN_PACKAGE_SHLIBDEPS

    +
         Mandatory : NO
    Default : OFF
    May be set to ON in order to use dpkg-shlibdeps to generate
    better package dependency list.
    You may need set CMAKE_INSTALL_RPATH toi appropriate value
    if you use this feature, because if you don't dpkg-shlibdeps
    may fail to find your own shared libs.
    See http://www.cmake.org/Wiki/CMake_RPATH_handling.
    +

    CPACK_DEBIAN_PACKAGE_DEBUG

    +
         Mandatory : NO
    Default : -
    May be set when invoking cpack in order to trace debug information
    during CPackDeb run.
    +

    CPACK_DEBIAN_PACKAGE_PREDEPENDS

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    This field is like Depends, except that it also forces dpkg to complete installation of
    the packages named before even starting the installation of the package which declares
    the pre-dependency.
    +

    CPACK_DEBIAN_PACKAGE_ENHANCES

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    This field is similar to Suggests but works in the opposite direction.
    It is used to declare that a package can enhance the functionality of another package.
    +

    CPACK_DEBIAN_PACKAGE_BREAKS

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    When one binary package declares that it breaks another, dpkg will refuse to allow the
    package which declares Breaks be installed unless the broken package is deconfigured first,
    and it will refuse to allow the broken package to be reconfigured.
    +

    CPACK_DEBIAN_PACKAGE_CONFLICTS

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    When one binary package declares a conflict with another using a Conflicts field,
    dpkg will refuse to allow them to be installed on the system at the same time.
    +

    CPACK_DEBIAN_PACKAGE_PROVIDES

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    A virtual package is one which appears in the Provides control field of another package.
    +

    CPACK_DEBIAN_PACKAGE_REPLACES

    +
         Mandatory : NO
    Default : -
    see http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
    Packages can declare in their control file that they should overwrite
    files in certain other packages, or completely replace other packages.
    + +
  • +
  • + CPackNSIS: CPack NSIS generator specific options
    +


    +

    The following variables are specific to the graphical installers built on Windows using the Nullsoft Installation System.

    +
       CPACK_PACKAGE_INSTALL_REGISTRY_KEY - Registry key used when
    installing this project.
    +


    +
       CPACK_NSIS_INSTALL_ROOT - The default installation directory presented
    to the end user by the NSIS installer is under this root dir. The full
    directory presented to the end user is:
    ${CPACK_NSIS_INSTALL_ROOT}/${CPACK_PACKAGE_INSTALL_DIRECTORY}
    +


    +
       CPACK_NSIS_MUI_ICON - The icon file (.ico) for the generated
    install program.
    +


    +
       CPACK_NSIS_MUI_UNIICON - The icon file (.ico) for the generated
    uninstall program.
    +


    +
       CPACK_PACKAGE_ICON - A branding image that will be displayed inside
    the installer.
    +


    +
       CPACK_NSIS_EXTRA_INSTALL_COMMANDS - Extra NSIS commands that will
    be added to the install Section.
    +


    +
       CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS - Extra NSIS commands that will
    be added to the uninstall Section.
    +


    +
       CPACK_NSIS_COMPRESSOR - The arguments that will be passed to the
    NSIS SetCompressor command.
    +


    +
       CPACK_NSIS_MODIFY_PATH - If this is set to "ON", then an extra page
    will appear in the installer that will allow the user to choose
    whether the program directory should be added to the system PATH
    variable.
    +


    +
       CPACK_NSIS_DISPLAY_NAME - The display name string that appears in
    the Windows Add/Remove Program control panel
    +


    +
       CPACK_NSIS_PACKAGE_NAME - The title displayed at the top of the
    installer.
    +


    +
       CPACK_NSIS_INSTALLED_ICON_NAME - A path to the executable that
    contains the installer icon.
    +


    +
       CPACK_NSIS_HELP_LINK - URL to a web site providing assistance in
    installing your application.
    +


    +
       CPACK_NSIS_URL_INFO_ABOUT - URL to a web site providing more
    information about your application.
    +


    +
       CPACK_NSIS_CONTACT - Contact information for questions and comments
    about the installation process.
    +


    +
       CPACK_NSIS_CREATE_ICONS_EXTRA - Additional NSIS commands for
    creating start menu shortcuts.
    +


    +
       CPACK_NSIS_DELETE_ICONS_EXTRA -Additional NSIS commands to
    uninstall start menu shortcuts.
    +


    +
       CPACK_NSIS_EXECUTABLES_DIRECTORY - Creating NSIS start menu links
    assumes that they are in 'bin' unless this variable is set.
    For example, you would set this to 'exec' if your executables are
    in an exec directory.
    +


    +
       CPACK_NSIS_MUI_FINISHPAGE_RUN - Specify an executable to add an option
    to run on the finish page of the NSIS installer.
    + +
  • +
  • + CPackRPM: The builtin (binary) CPack RPM generator (Unix only)
    +

    CPackRPM may be used to create RPM package using CPack. CPackRPM is a CPack generator thus it uses the CPACK_XXX variables used by CPack : http://www.cmake.org/Wiki/CMake:CPackConfiguration

    +

    However CPackRPM has specific features which are controlled by the specifics CPACK_RPM_XXX variables. CPackRPM is a component aware generator so when CPACK_RPM_COMPONENT_INSTALL is ON some more CPACK_RPM_<ComponentName>_XXXX variables may be used in order to have component specific values. Note however that <componentName> refers to the **grouping name**. This may be either a component name or a component GROUP name. Usually those vars correspond to RPM spec file entities, one may find information about spec files here http://www.rpm.org/wiki/Docs. You'll find a detailed usage of CPackRPM on the wiki:

    +
      http://www.cmake.org/Wiki/CMake:CPackPackageGenerators#RPM_.28Unix_Only.29
    +

    However as a handy reminder here comes the list of specific variables:

    +
      CPACK_RPM_PACKAGE_SUMMARY
    Mandatory : YES
    Default : CPACK_PACKAGE_DESCRIPTION_SUMMARY
    The RPM package summary
    CPACK_RPM_PACKAGE_NAME
    Mandatory : YES
    Default : CPACK_PACKAGE_NAME
    The RPM package name
    CPACK_RPM_PACKAGE_VERSION
    Mandatory : YES
    Default : CPACK_PACKAGE_VERSION
    The RPM package version
    CPACK_RPM_PACKAGE_ARCHITECTURE
    Mandatory : NO
    Default : -
    The RPM package architecture. This may be set to "noarch" if you
    know you are building a noarch package.
    CPACK_RPM_PACKAGE_RELEASE
    Mandatory : YES
    Default : 1
    The RPM package release. This is the numbering of the RPM package
    itself, i.e. the version of the packaging and not the version of the
    content (see CPACK_RPM_PACKAGE_VERSION). One may change the default
    value if the previous packaging was buggy and/or you want to put here
    a fancy Linux distro specific numbering.
    CPACK_RPM_PACKAGE_LICENSE
    Mandatory : YES
    Default : "unknown"
    The RPM package license policy.
    CPACK_RPM_PACKAGE_GROUP
    Mandatory : YES
    Default : "unknown"
    The RPM package group.
    CPACK_RPM_PACKAGE_VENDOR
    Mandatory : YES
    Default : CPACK_PACKAGE_VENDOR if set or "unknown"
    The RPM package vendor.
    CPACK_RPM_PACKAGE_URL
    Mandatory : NO
    Default : -
    The projects URL.
    CPACK_RPM_PACKAGE_DESCRIPTION
    Mandatory : YES
    Default : CPACK_PACKAGE_DESCRIPTION_FILE if set or "no package description available"
    CPACK_RPM_COMPRESSION_TYPE
    Mandatory : NO
    Default : -
    May be used to override RPM compression type to be used
    to build the RPM. For example some Linux distribution now default
    to lzma or xz compression whereas older cannot use such RPM.
    Using this one can enforce compression type to be used.
    Possible value are: lzma, xz, bzip2 and gzip.
    CPACK_RPM_PACKAGE_REQUIRES
    Mandatory : NO
    Default : -
    May be used to set RPM dependencies (requires).
    Note that you must enclose the complete requires string between quotes,
    for example:
    set(CPACK_RPM_PACKAGE_REQUIRES "python >= 2.5.0, cmake >= 2.8")
    The required package list of an RPM file could be printed with
    rpm -qp --requires file.rpm
    CPACK_RPM_PACKAGE_SUGGESTS
    Mandatory : NO
    Default : -
    May be used to set weak RPM dependencies (suggests).
    Note that you must enclose the complete requires string between quotes.
    CPACK_RPM_PACKAGE_PROVIDES
    Mandatory : NO
    Default : -
    May be used to set RPM dependencies (provides).
    The provided package list of an RPM file could be printed with
    rpm -qp --provides file.rpm
    CPACK_RPM_PACKAGE_OBSOLETES
    Mandatory : NO
    Default : -
    May be used to set RPM packages that are obsoleted by this one.
    CPACK_RPM_PACKAGE_RELOCATABLE
    Mandatory : NO
    Default : CPACK_PACKAGE_RELOCATABLE
    If this variable is set to TRUE or ON CPackRPM will try
    to build a relocatable RPM package. A relocatable RPM may
    be installed using rpm --prefix or --relocate in order to
    install it at an alternate place see rpm(8).
    Note that currently this may fail if CPACK_SET_DESTDIR is set to ON.
    If CPACK_SET_DESTDIR is set then you will get a warning message
    but if there is file installed with absolute path you'll get
    unexpected behavior.
    CPACK_RPM_SPEC_INSTALL_POST [deprecated]
    Mandatory : NO
    Default : -
    This way of specifying post-install script is deprecated use
    CPACK_RPM_POST_INSTALL_SCRIPT_FILE
    May be used to set an RPM post-install command inside the spec file.
    For example setting it to "/bin/true" may be used to prevent
    rpmbuild to strip binaries.
    CPACK_RPM_SPEC_MORE_DEFINE
    Mandatory : NO
    Default : -
    May be used to add any %define lines to the generated spec file.
    CPACK_RPM_PACKAGE_DEBUG
    Mandatory : NO
    Default : -
    May be set when invoking cpack in order to trace debug information
    during CPack RPM run. For example you may launch CPack like this
    cpack -D CPACK_RPM_PACKAGE_DEBUG=1 -G RPM
    CPACK_RPM_USER_BINARY_SPECFILE
    Mandatory : NO
    Default : -
    May be set by the user in order to specify a USER binary spec file
    to be used by CPackRPM instead of generating the file.
    The specified file will be processed by CONFIGURE_FILE( @ONLY).
    CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE
    Mandatory : NO
    Default : -
    If set CPack will generate a template for USER specified binary
    spec file and stop with an error. For example launch CPack like this
    cpack -D CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE=1 -G RPM
    The user may then use this file in order to hand-craft is own
    binary spec file which may be used with CPACK_RPM_USER_BINARY_SPECFILE.
    CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
    CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
    Mandatory : NO
    Default : -
    May be used to embed a pre (un)installation script in the spec file.
    The refered script file(s) will be read and directly
    put after the %pre or %preun section
    If CPACK_RPM_COMPONENT_INSTALL is set to ON the (un)install script for
    each component can be overriden with
    CPACK_RPM_<COMPONENT>_PRE_INSTALL_SCRIPT_FILE and
    CPACK_RPM_<COMPONENT>_PRE_UNINSTALL_SCRIPT_FILE
    One may verify which scriptlet has been included with
    rpm -qp --scripts package.rpm
    CPACK_RPM_POST_INSTALL_SCRIPT_FILE
    CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
    Mandatory : NO
    Default : -
    May be used to embed a post (un)installation script in the spec file.
    The refered script file(s) will be read and directly
    put after the %post or %postun section
    If CPACK_RPM_COMPONENT_INSTALL is set to ON the (un)install script for
    each component can be overriden with
    CPACK_RPM_<COMPONENT>_POST_INSTALL_SCRIPT_FILE and
    CPACK_RPM_<COMPONENT>_POST_UNINSTALL_SCRIPT_FILE
    One may verify which scriptlet has been included with
    rpm -qp --scripts package.rpm
    CPACK_RPM_USER_FILELIST
    CPACK_RPM_<COMPONENT>_USER_FILELIST
    Mandatory : NO
    Default : -
    May be used to explicitely specify %(<directive>) file line
    in the spec file. Like %config(noreplace) or any other directive
    that be found in the %files section. Since CPackRPM is generating
    the list of files (and directories) the user specified files of
    the CPACK_RPM_<COMPONENT>_USER_FILELIST list will be removed from the generated list.
    CPACK_RPM_CHANGELOG_FILE
    Mandatory : NO
    Default : -
    May be used to embed a changelog in the spec file.
    The refered file will be read and directly put after the %changelog
    section.
    + +
  • +
  • + CTest: Configure a project for testing with CTest/CDash
    +

    Include this module in the top CMakeLists.txt file of a project to enable testing with CTest and dashboard submissions to CDash:

    +
       project(MyProject)
    ...
    include(CTest)
    +

    The module automatically creates a BUILD_TESTING option that selects whether to enable testing support (ON by default). After including the module, use code like

    +
       if(BUILD_TESTING)
    # ... CMake code to create tests ...
    endif()
    +

    to creating tests when testing is enabled.

    +

    To enable submissions to a CDash server, create a CTestConfig.cmake file at the top of the project with content such as

    +
       set(CTEST_PROJECT_NAME "MyProject")
    set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC")
    set(CTEST_DROP_METHOD "http")
    set(CTEST_DROP_SITE "my.cdash.org")
    set(CTEST_DROP_LOCATION "/submit.php?project=MyProject")
    set(CTEST_DROP_SITE_CDASH TRUE)
    +

    (the CDash server can provide the file to a project administrator who configures 'MyProject'). Settings in the config file are shared by both this CTest module and the CTest command-line tool's dashboard script mode (ctest -S).

    +

    While building a project for submission to CDash, CTest scans the build output for errors and warnings and reports them with surrounding context from the build log. This generic approach works for all build tools, but does not give details about the command invocation that produced a given problem. One may get more detailed reports by adding

    +
       set(CTEST_USE_LAUNCHERS 1)
    +

    to the CTestConfig.cmake file. When this option is enabled, the CTest module tells CMake's Makefile generators to invoke every command in the generated build system through a CTest launcher program. (Currently the CTEST_USE_LAUNCHERS option is ignored on non-Makefile generators.) During a manual build each launcher transparently runs the command it wraps. During a CTest-driven build for submission to CDash each launcher reports detailed information when its command fails or warns. (Setting CTEST_USE_LAUNCHERS in CTestConfig.cmake is convenient, but also adds the launcher overhead even for manual builds. One may instead set it in a CTest dashboard script and add it to the CMake cache for the build tree.)

    + +
  • +
  • + CTestScriptMode:
    +

    This file is read by ctest in script mode (-S)

    + +
  • +
  • + CheckCCompilerFlag: Check whether the C compiler supports a given flag.
    +

    CHECK_C_COMPILER_FLAG(<flag> <var>)

    +
      <flag> - the compiler flag
    <var> - variable to store the result
    +

    This internally calls the check_c_source_compiles macro. See help for CheckCSourceCompiles for a listing of variables that can modify the build.

    + +
  • +
  • + CheckCSourceCompiles: Check if given C source compiles and links into an executable
    +

    CHECK_C_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])

    +
      <code>       - source code to try to compile, must define 'main'
    <var> - variable to store whether the source code compiled
    <fail-regex> - fail if test output matches this regex
    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckCSourceRuns: Check if the given C source code compiles and runs.
    +

    CHECK_C_SOURCE_RUNS(<code> <var>)

    +
      <code>   - source code to try to compile
    <var> - variable to store the result
    (1 for success, empty for failure)
    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckCXXCompilerFlag: Check whether the CXX compiler supports a given flag.
    +

    CHECK_CXX_COMPILER_FLAG(<flag> <var>)

    +
      <flag> - the compiler flag
    <var> - variable to store the result
    +

    This internally calls the check_cxx_source_compiles macro. See help for CheckCXXSourceCompiles for a listing of variables that can modify the build.

    + +
  • +
  • + CheckCXXSourceCompiles: Check if given C++ source compiles and links into an executable
    +

    CHECK_CXX_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])

    +
      <code>       - source code to try to compile, must define 'main'
    <var> - variable to store whether the source code compiled
    <fail-regex> - fail if test output matches this regex
    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckCXXSourceRuns: Check if the given C++ source code compiles and runs.
    +

    CHECK_CXX_SOURCE_RUNS(<code> <var>)

    +
      <code>   - source code to try to compile
    <var> - variable to store the result
    (1 for success, empty for failure)
    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckCXXSymbolExists: Check if a symbol exists as a function, variable, or macro in C++
    +

    CHECK_CXX_SYMBOL_EXISTS(<symbol> <files> <variable>)

    +

    Check that the <symbol> is available after including given header <files> and store the result in a <variable>. Specify the list of files in one argument as a semicolon-separated list. CHECK_CXX_SYMBOL_EXISTS() can be used to check in C++ files, as opposed to CHECK_SYMBOL_EXISTS(), which works only for C.

    +

    If the header files define the symbol as a macro it is considered available and assumed to work. If the header files declare the symbol as a function or variable then the symbol must also be available for linking. If the symbol is a type or enum value it will not be recognized (consider using CheckTypeSize or CheckCSourceCompiles).

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckFortranFunctionExists: macro which checks if the Fortran function exists
    +

    CHECK_FORTRAN_FUNCTION_EXISTS(FUNCTION VARIABLE)

    +
      FUNCTION - the name of the Fortran function
    VARIABLE - variable to store the result
    +


    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckFunctionExists: Check if a C function can be linked
    +

    CHECK_FUNCTION_EXISTS(<function> <variable>)

    +

    Check that the <function> is provided by libraries on the system and store the result in a <variable>. This does not verify that any system header file declares the function, only that it can be found at link time (considure using CheckSymbolExists).

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckIncludeFile: macro which checks the include file exists.
    +

    CHECK_INCLUDE_FILE(INCLUDE VARIABLE)

    +
      INCLUDE  - name of include file
    VARIABLE - variable to return result

    +

    an optional third argument is the CFlags to add to the compile line or you can use CMAKE_REQUIRED_FLAGS

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    +


    + +
  • +
  • + CheckIncludeFileCXX: Check if the include file exists.
    +
      CHECK_INCLUDE_FILE_CXX(INCLUDE VARIABLE)
    +


    +
      INCLUDE  - name of include file
    VARIABLE - variable to return result

    +

    An optional third argument is the CFlags to add to the compile line or you can use CMAKE_REQUIRED_FLAGS.

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    +


    + +
  • +
  • + CheckIncludeFiles: Check if the files can be included
    +


    +

    CHECK_INCLUDE_FILES(INCLUDE VARIABLE)

    +
      INCLUDE  - list of files to include
    VARIABLE - variable to return result
    +


    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    + +
  • +
  • + CheckLibraryExists: Check if the function exists.
    +

    CHECK_LIBRARY_EXISTS (LIBRARY FUNCTION LOCATION VARIABLE)

    +
      LIBRARY  - the name of the library you are looking for
    FUNCTION - the name of the function
    LOCATION - location where the library should be found
    VARIABLE - variable to store the result
    +


    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckPrototypeDefinition: Check if the protoype we expect is correct.
    +

    check_prototype_definition(FUNCTION PROTOTYPE RETURN HEADER VARIABLE)

    +
      FUNCTION - The name of the function (used to check if prototype exists)
    PROTOTYPE- The prototype to check.
    RETURN - The return value of the function.
    HEADER - The header files required.
    VARIABLE - The variable to store the result.
    +

    Example:

    +
      check_prototype_definition(getpwent_r
    "struct passwd *getpwent_r(struct passwd *src, char *buf, int buflen)"
    "NULL"
    "unistd.h;pwd.h"
    SOLARIS_GETPWENT_R)
    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckStructHasMember: Check if the given struct or class has the specified member variable
    +

    CHECK_STRUCT_HAS_MEMBER (STRUCT MEMBER HEADER VARIABLE)

    +
      STRUCT - the name of the struct or class you are interested in
    MEMBER - the member which existence you want to check
    HEADER - the header(s) where the prototype should be declared
    VARIABLE - variable to store the result
    +


    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    +


    +

    Example: CHECK_STRUCT_HAS_MEMBER("struct timeval" tv_sec sys/select.h HAVE_TIMEVAL_TV_SEC)

    + +
  • +
  • + CheckSymbolExists: Check if a symbol exists as a function, variable, or macro
    +

    CHECK_SYMBOL_EXISTS(<symbol> <files> <variable>)

    +

    Check that the <symbol> is available after including given header <files> and store the result in a <variable>. Specify the list of files in one argument as a semicolon-separated list.

    +

    If the header files define the symbol as a macro it is considered available and assumed to work. If the header files declare the symbol as a function or variable then the symbol must also be available for linking. If the symbol is a type or enum value it will not be recognized (consider using CheckTypeSize or CheckCSourceCompiles). If the check needs to be done in C++, consider using CHECK_CXX_SYMBOL_EXISTS(), which does the same as CHECK_SYMBOL_EXISTS(), but in C++.

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + CheckTypeSize: Check sizeof a type
    +
      CHECK_TYPE_SIZE(TYPE VARIABLE [BUILTIN_TYPES_ONLY])
    +

    Check if the type exists and determine its size. On return, "HAVE_${VARIABLE}" holds the existence of the type, and "${VARIABLE}" holds one of the following:

    +
       <size> = type has non-zero size <size>
    "0" = type has arch-dependent size (see below)
    "" = type does not exist
    +

    Furthermore, the variable "${VARIABLE}_CODE" holds C preprocessor code to define the macro "${VARIABLE}" to the size of the type, or leave the macro undefined if the type does not exist.

    +

    The variable "${VARIABLE}" may be "0" when CMAKE_OSX_ARCHITECTURES has multiple architectures for building OS X universal binaries. This indicates that the type size varies across architectures. In this case "${VARIABLE}_CODE" contains C preprocessor tests mapping from each architecture macro to the corresponding type size. The list of architecture macros is stored in "${VARIABLE}_KEYS", and the value for each key is stored in "${VARIABLE}-${KEY}".

    +

    If the BUILTIN_TYPES_ONLY option is not given, the macro checks for headers <sys/types.h>, <stdint.h>, and <stddef.h>, and saves results in HAVE_SYS_TYPES_H, HAVE_STDINT_H, and HAVE_STDDEF_H. The type size check automatically includes the available headers, thus supporting checks of types defined in the headers.

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_INCLUDES = list of include directories
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    CMAKE_EXTRA_INCLUDE_FILES = list of extra headers to include
    + +
  • +
  • + CheckVariableExists: Check if the variable exists.
    +
      CHECK_VARIABLE_EXISTS(VAR VARIABLE)

    VAR - the name of the variable
    VARIABLE - variable to store the result
    +


    +

    This macro is only for C variables.

    +

    The following variables may be set before calling this macro to modify the way the check is run:

    +
      CMAKE_REQUIRED_FLAGS = string of compile command line flags
    CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
    CMAKE_REQUIRED_LIBRARIES = list of libraries to link
    + +
  • +
  • + Dart: Configure a project for testing with CTest or old Dart Tcl Client
    +

    This file is the backwards-compatibility version of the CTest module. It supports using the old Dart 1 Tcl client for driving dashboard submissions as well as testing with CTest. This module should be included in the CMakeLists.txt file at the top of a project. Typical usage:

    +
      INCLUDE(Dart)
    IF(BUILD_TESTING)
    # ... testing related CMake code ...
    ENDIF(BUILD_TESTING)
    +

    The BUILD_TESTING option is created by the Dart module to determine whether testing support should be enabled. The default is ON.

    + +
  • +
  • + DeployQt4: Functions to help assemble a standalone Qt4 executable.
    +

    A collection of CMake utility functions useful for deploying Qt4 executables.

    +

    The following functions are provided by this module:

    +
       write_qt4_conf
    resolve_qt4_paths
    fixup_qt4_executable
    install_qt4_plugin_path
    install_qt4_plugin
    install_qt4_executable
    +

    Requires CMake 2.6 or greater because it uses function and PARENT_SCOPE. Also depends on BundleUtilities.cmake.

    +
      WRITE_QT4_CONF(<qt_conf_dir> <qt_conf_contents>)
    +

    Writes a qt.conf file with the <qt_conf_contents> into <qt_conf_dir>.

    +
      RESOLVE_QT4_PATHS(<paths_var> [<executable_path>])
    +

    Loop through <paths_var> list and if any don't exist resolve them relative to the <executable_path> (if supplied) or the CMAKE_INSTALL_PREFIX.

    +
      FIXUP_QT4_EXECUTABLE(<executable> [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf>])
    +

    Copies Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable using BundleUtilities so it is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible.

    +

    <executable> should point to the executable to be fixed-up.

    +

    <qtplugins> should contain a list of the names or paths of any Qt plugins to be installed.

    +

    <libs> will be passed to BundleUtilities and should be a list of any already installed plugins, libraries or executables to also be fixed-up.

    +

    <dirs> will be passed to BundleUtilities and should contain and directories to be searched to find library dependencies.

    +

    <plugins_dir> allows an custom plugins directory to be used.

    +

    <request_qt_conf> will force a qt.conf file to be written even if not needed.

    +
      INSTALL_QT4_PLUGIN_PATH(plugin executable copy installed_plugin_path_var <plugins_dir> <component> <configurations>)
    +

    Install (or copy) a resolved <plugin> to the default plugins directory (or <plugins_dir>) relative to <executable> and store the result in <installed_plugin_path_var>.

    +

    If <copy> is set to TRUE then the plugins will be copied rather than installed. This is to allow this module to be used at CMake time rather than install time.

    +

    If <component> is set then anything installed will use this COMPONENT.

    +
      INSTALL_QT4_PLUGIN(plugin executable copy installed_plugin_path_var <plugins_dir> <component>)
    +

    Install (or copy) an unresolved <plugin> to the default plugins directory (or <plugins_dir>) relative to <executable> and store the result in <installed_plugin_path_var>. See documentation of INSTALL_QT4_PLUGIN_PATH.

    +
      INSTALL_QT4_EXECUTABLE(<executable> [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf> <component>])
    +

    Installs Qt plugins, writes a Qt configuration file (if needed) and fixes up a Qt4 executable using BundleUtilities so it is standalone and can be drag-and-drop copied to another machine as long as all of the system libraries are compatible. The executable will be fixed-up at install time. <component> is the COMPONENT used for bundle fixup and plugin installation. See documentation of FIXUP_QT4_BUNDLE.

    + +
  • +
  • + Documentation: DocumentationVTK.cmake
    +

    This file provides support for the VTK documentation framework. It relies on several tools (Doxygen, Perl, etc).

    + +
  • +
  • + ExternalProject: Create custom targets to build projects in external trees
    +

    The 'ExternalProject_Add' function creates a custom target to drive download, update/patch, configure, build, install and test steps of an external project:

    +
      ExternalProject_Add(<name>    # Name for custom target
    [DEPENDS projects...] # Targets on which the project depends
    [PREFIX dir] # Root dir for entire project
    [LIST_SEPARATOR sep] # Sep to be replaced by ; in cmd lines
    [TMP_DIR dir] # Directory to store temporary files
    [STAMP_DIR dir] # Directory to store step timestamps
    #--Download step--------------
    [DOWNLOAD_DIR dir] # Directory to store downloaded files
    [DOWNLOAD_COMMAND cmd...] # Command to download source tree
    [CVS_REPOSITORY cvsroot] # CVSROOT of CVS repository
    [CVS_MODULE mod] # Module to checkout from CVS repo
    [CVS_TAG tag] # Tag to checkout from CVS repo
    [SVN_REPOSITORY url] # URL of Subversion repo
    [SVN_REVISION rev] # Revision to checkout from Subversion repo
    [SVN_USERNAME john ] # Username for Subversion checkout and update
    [SVN_PASSWORD doe ] # Password for Subversion checkout and update
    [SVN_TRUST_CERT 1 ] # Trust the Subversion server site certificate
    [GIT_REPOSITORY url] # URL of git repo
    [GIT_TAG tag] # Git branch name, commit id or tag
    [URL /.../src.tgz] # Full path or URL of source
    [URL_MD5 md5] # MD5 checksum of file at URL
    [TIMEOUT seconds] # Time allowed for file download operations
    #--Update/Patch step----------
    [UPDATE_COMMAND cmd...] # Source work-tree update command
    [PATCH_COMMAND cmd...] # Command to patch downloaded source
    #--Configure step-------------
    [SOURCE_DIR dir] # Source dir to be used for build
    [CONFIGURE_COMMAND cmd...] # Build tree configuration command
    [CMAKE_COMMAND /.../cmake] # Specify alternative cmake executable
    [CMAKE_GENERATOR gen] # Specify generator for native build
    [CMAKE_ARGS args...] # Arguments to CMake command line
    [CMAKE_CACHE_ARGS args...] # Initial cache arguments, of the form -Dvar:string=on
    #--Build step-----------------
    [BINARY_DIR dir] # Specify build dir location
    [BUILD_COMMAND cmd...] # Command to drive the native build
    [BUILD_IN_SOURCE 1] # Use source dir for build dir
    #--Install step---------------
    [INSTALL_DIR dir] # Installation prefix
    [INSTALL_COMMAND cmd...] # Command to drive install after build
    #--Test step------------------
    [TEST_BEFORE_INSTALL 1] # Add test step executed before install step
    [TEST_AFTER_INSTALL 1] # Add test step executed after install step
    [TEST_COMMAND cmd...] # Command to drive test
    #--Output logging-------------
    [LOG_DOWNLOAD 1] # Wrap download in script to log output
    [LOG_UPDATE 1] # Wrap update in script to log output
    [LOG_CONFIGURE 1] # Wrap configure in script to log output
    [LOG_BUILD 1] # Wrap build in script to log output
    [LOG_TEST 1] # Wrap test in script to log output
    [LOG_INSTALL 1] # Wrap install in script to log output
    #--Custom targets-------------
    [STEP_TARGETS st1 st2 ...] # Generate custom targets for these steps
    )
    +

    The *_DIR options specify directories for the project, with default directories computed as follows. If the PREFIX option is given to ExternalProject_Add() or the EP_PREFIX directory property is set, then an external project is built and installed under the specified prefix:

    +
       TMP_DIR      = <prefix>/tmp
    STAMP_DIR = <prefix>/src/<name>-stamp
    DOWNLOAD_DIR = <prefix>/src
    SOURCE_DIR = <prefix>/src/<name>
    BINARY_DIR = <prefix>/src/<name>-build
    INSTALL_DIR = <prefix>
    +

    Otherwise, if the EP_BASE directory property is set then components of an external project are stored under the specified base:

    +
       TMP_DIR      = <base>/tmp/<name>
    STAMP_DIR = <base>/Stamp/<name>
    DOWNLOAD_DIR = <base>/Download/<name>
    SOURCE_DIR = <base>/Source/<name>
    BINARY_DIR = <base>/Build/<name>
    INSTALL_DIR = <base>/Install/<name>
    +

    If no PREFIX, EP_PREFIX, or EP_BASE is specified then the default is to set PREFIX to "<name>-prefix". Relative paths are interpreted with respect to the build directory corresponding to the source directory in which ExternalProject_Add is invoked.

    +

    If SOURCE_DIR is explicitly set to an existing directory the project will be built from it. Otherwise a download step must be specified using one of the DOWNLOAD_COMMAND, CVS_*, SVN_*, or URL options. The URL option may refer locally to a directory or source tarball, or refer to a remote tarball (e.g. http://.../src.tgz).

    +

    The 'ExternalProject_Add_Step' function adds a custom step to an external project:

    +
      ExternalProject_Add_Step(<name> <step> # Names of project and custom step
    [COMMAND cmd...] # Command line invoked by this step
    [COMMENT "text..."] # Text printed when step executes
    [DEPENDEES steps...] # Steps on which this step depends
    [DEPENDERS steps...] # Steps that depend on this step
    [DEPENDS files...] # Files on which this step depends
    [ALWAYS 1] # No stamp file, step always runs
    [WORKING_DIRECTORY dir] # Working directory for command
    [LOG 1] # Wrap step in script to log output
    )
    +

    The command line, comment, and working directory of every standard and custom step is processed to replace tokens <SOURCE_DIR>, <BINARY_DIR>, <INSTALL_DIR>, and <TMP_DIR> with corresponding property values.

    +

    The 'ExternalProject_Get_Property' function retrieves external project target properties:

    +
      ExternalProject_Get_Property(<name> [prop1 [prop2 [...]]])
    +

    It stores property values in variables of the same name. Property names correspond to the keyword argument names of 'ExternalProject_Add'.

    +

    The 'ExternalProject_Add_StepTargets' function generates custom targets for the steps listed:

    +
      ExternalProject_Add_StepTargets(<name> [step1 [step2 [...]]])
    +


    +

    If STEP_TARGETS is set then ExternalProject_Add_StepTargets is automatically called at the end of matching calls to ExternalProject_Add_Step. Pass STEP_TARGETS explicitly to individual ExternalProject_Add calls, or implicitly to all ExternalProject_Add calls by setting the directory property EP_STEP_TARGETS.

    +

    If STEP_TARGETS is not set, clients may still manually call ExternalProject_Add_StepTargets after calling ExternalProject_Add or ExternalProject_Add_Step.

    +

    This functionality is provided to make it easy to drive the steps independently of each other by specifying targets on build command lines. For example, you may be submitting to a sub-project based dashboard, where you want to drive the configure portion of the build, then submit to the dashboard, followed by the build portion, followed by tests. If you invoke a custom target that depends on a step halfway through the step dependency chain, then all the previous steps will also run to ensure everything is up to date.

    +

    For example, to drive configure, build and test steps independently for each ExternalProject_Add call in your project, write the following line prior to any ExternalProject_Add calls in your CMakeLists file:

    +
       set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
    + +
  • +
  • + FeatureSummary: Macros for generating a summary of enabled/disabled features
    +


    +

    This module provides the macros feature_summary(), set_package_properties() and add_feature_info(). For compatibility it also still provides set_package_info(), set_feature_info(), print_enabled_features() and print_disabled_features().

    +

    These macros can be used to generate a summary of enabled and disabled packages and/or feature for a build tree:

    +
        -- The following OPTIONAL packages have been found:
    LibXml2 (required version >= 2.4) , XML processing library. , <http://xmlsoft.org>
    * Enables HTML-import in MyWordProcessor
    * Enables odt-export in MyWordProcessor
    PNG , A PNG image library. , <http://www.libpng.org/pub/png/>
    * Enables saving screenshots
    -- The following OPTIONAL packages have not been found:
    Lua51 , The Lua scripting language. , <http://www.lua.org>
    * Enables macros in MyWordProcessor
    Foo , Foo provides cool stuff.
    +


    +


    +
        FEATURE_SUMMARY( [FILENAME <file>]
    [APPEND]
    [VAR <variable_name>]
    [INCLUDE_QUIET_PACKAGES]
    [FATAL_ON_MISSING_REQUIRED_PACKAGES]
    [DESCRIPTION "Found packages:"]
    WHAT (ALL | PACKAGES_FOUND | PACKAGES_NOT_FOUND
    | ENABLED_FEATURES | DISABLED_FEATURES]
    )
    +


    +

    The FEATURE_SUMMARY() macro can be used to print information about enabled or disabled packages or features of a project. By default, only the names of the features/packages will be printed and their required version when one was specified. Use SET_PACKAGE_PROPERTIES() to add more useful information, like e.g. a download URL for the respective package or their purpose in the project.

    +

    The WHAT option is the only mandatory option. Here you specify what information will be printed:

    +
        ALL: print everything
    ENABLED_FEATURES: the list of all features which are enabled
    DISABLED_FEATURES: the list of all features which are disabled
    PACKAGES_FOUND: the list of all packages which have been found
    PACKAGES_NOT_FOUND: the list of all packages which have not been found
    OPTIONAL_PACKAGES_FOUND: only those packages which have been found which have the type OPTIONAL
    OPTIONAL_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type OPTIONAL
    RECOMMENDED_PACKAGES_FOUND: only those packages which have been found which have the type RECOMMENDED
    RECOMMENDED_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type RECOMMENDED
    REQUIRED_PACKAGES_FOUND: only those packages which have been found which have the type REQUIRED
    REQUIRED_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type REQUIRED
    RUNTIME_PACKAGES_FOUND: only those packages which have been found which have the type RUNTIME
    RUNTIME_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type RUNTIME
    +


    +

    If a FILENAME is given, the information is printed into this file. If APPEND is used, it is appended to this file, otherwise the file is overwritten if it already existed. If the VAR option is used, the information is "printed" into the specified variable. If FILENAME is not used, the information is printed to the terminal. Using the DESCRIPTION option a description or headline can be set which will be printed above the actual content. If INCLUDE_QUIET_PACKAGES is given, packages which have been searched with find_package(... QUIET) will also be listed. By default they are skipped. If FATAL_ON_MISSING_REQUIRED_PACKAGES is given, CMake will abort if a package which is marked as REQUIRED has not been found.

    +

    Example 1, append everything to a file:

    +
       feature_summary(WHAT ALL
    FILENAME ${CMAKE_BINARY_DIR}/all.log APPEND)
    +


    +

    Example 2, print the enabled features into the variable enabledFeaturesText, including QUIET packages:

    +
       feature_summary(WHAT ENABLED_FEATURES
    INCLUDE_QUIET_PACKAGES
    DESCRIPTION "Enabled Features:"
    VAR enabledFeaturesText)
    message(STATUS "${enabledFeaturesText}")
    +


    +


    +
        SET_PACKAGE_PROPERTIES(<name> PROPERTIES [ URL <url> ]
    [ DESCRIPTION <description> ]
    [ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
    [ PURPOSE <purpose> ]
    )
    +


    +

    Use this macro to set up information about the named package, which can then be displayed via FEATURE_SUMMARY(). This can be done either directly in the Find-module or in the project which uses the module after the FIND_PACKAGE() call. The features for which information can be set are added automatically by the find_package() command.

    +

    URL: this should be the homepage of the package, or something similar. Ideally this is set already directly in the Find-module.

    +

    DESCRIPTION: A short description what that package is, at most one sentence. Ideally this is set already directly in the Find-module.

    +

    TYPE: What type of dependency has the using project on that package. Default is OPTIONAL. In this case it is a package which can be used by the project when available at buildtime, but it also work without. RECOMMENDED is similar to OPTIONAL, i.e. the project will build if the package is not present, but the functionality of the resulting binaries will be severly limited. If a REQUIRED package is not available at buildtime, the project may not even build. This can be combined with the FATAL_ON_MISSING_REQUIRED_PACKAGES argument for feature_summary(). Last, a RUNTIME package is a package which is actually not used at all during the build, but which is required for actually running the resulting binaries. So if such a package is missing, the project can still be built, but it may not work later on. If set_package_properties() is called multiple times for the same package with different TYPEs, the TYPE is only changed to higher TYPEs ( RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED ), lower TYPEs are ignored. The TYPE property is project-specific, so it cannot be set by the Find-module, but must be set in the project.

    +

    PURPOSE: This describes which features this package enables in the project, i.e. it tells the user what functionality he gets in the resulting binaries. If set_package_properties() is called multiple times for a package, all PURPOSE properties are appended to a list of purposes of the package in the project. As the TYPE property, also the PURPOSE property is project-specific, so it cannot be set by the Find-module, but must be set in the project.

    +


    +

    Example for setting the info for a package:

    +
       find_package(LibXml2)
    set_package_properties(LibXml2 PROPERTIES DESCRIPTION "A XML processing library."
    URL "http://xmlsoft.org/")
    +


    +
       set_package_properties(LibXml2 PROPERTIES TYPE RECOMMENDED
    PURPOSE "Enables HTML-import in MyWordProcessor")
    +

    ...

    +
       set_package_properties(LibXml2 PROPERTIES TYPE OPTIONAL
    PURPOSE "Enables odt-export in MyWordProcessor")
    +


    +
       find_package(DBUS)
    set_package_properties(DBUS PROPERTIES TYPE RUNTIME
    PURPOSE "Necessary to disable the screensaver during a presentation" )
    +


    +
        ADD_FEATURE_INFO(<name> <enabled> <description>)
    +

    Use this macro to add information about a feature with the given <name>. <enabled> contains whether this feature is enabled or not, <description> is a text describing the feature. The information can be displayed using feature_summary() for ENABLED_FEATURES and DISABLED_FEATURES respectively.

    +

    Example for setting the info for a feature:

    +
       option(WITH_FOO "Help for foo" ON)
    add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")
    +


    +


    +

    The following macros are provided for compatibility with previous CMake versions:

    +
        SET_PACKAGE_INFO(<name> <description> [<url> [<purpose>] ] )
    +

    Use this macro to set up information about the named package, which can then be displayed via FEATURE_SUMMARY(). This can be done either directly in the Find-module or in the project which uses the module after the FIND_PACKAGE() call. The features for which information can be set are added automatically by the find_package() command.

    +
        PRINT_ENABLED_FEATURES()
    +

    Does the same as FEATURE_SUMMARY(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")

    +
        PRINT_DISABLED_FEATURES()
    +

    Does the same as FEATURE_SUMMARY(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")

    +
        SET_FEATURE_INFO(<name> <description> [<url>] )
    +

    Does the same as SET_PACKAGE_INFO(<name> <description> <url> )

    + +
  • +
  • + FindALSA: Find alsa
    +

    Find the alsa libraries (asound)

    +
      This module defines the following variables:
    ALSA_FOUND - True if ALSA_INCLUDE_DIR & ALSA_LIBRARY are found
    ALSA_LIBRARIES - Set when ALSA_LIBRARY is found
    ALSA_INCLUDE_DIRS - Set when ALSA_INCLUDE_DIR is found
    +


    +
         ALSA_INCLUDE_DIR - where to find asoundlib.h, etc.
    ALSA_LIBRARY - the asound library
    +


    + +
  • +
  • + FindASPELL: Try to find ASPELL
    +

    Once done this will define

    +
      ASPELL_FOUND - system has ASPELL
    ASPELL_EXECUTABLE - the ASPELL executable
    ASPELL_INCLUDE_DIR - the ASPELL include directory
    ASPELL_LIBRARIES - The libraries needed to use ASPELL
    ASPELL_DEFINITIONS - Compiler switches required for using ASPELL
    + +
  • +
  • + FindAVIFile: Locate AVIFILE library and include paths
    +

    AVIFILE (http://avifile.sourceforge.net/)is a set of libraries for i386 machines to use various AVI codecs. Support is limited beyond Linux. Windows provides native AVI support, and so doesn't need this library. This module defines

    +
      AVIFILE_INCLUDE_DIR, where to find avifile.h , etc.
    AVIFILE_LIBRARIES, the libraries to link against
    AVIFILE_DEFINITIONS, definitions to use when compiling
    AVIFILE_FOUND, If false, don't try to use AVIFILE
    + +
  • +
  • + FindArmadillo: Find Armadillo
    +

    Find the Armadillo C++ library

    +

    Using Armadillo:

    +
      find_package(Armadillo REQUIRED)
    include_directories(${ARMADILLO_INCLUDE_DIRS})
    add_executable(foo foo.cc)
    target_link_libraries(foo ${ARMADILLO_LIBRARIES})
    +

    This module sets the following variables:

    +
      ARMADILLO_FOUND - set to true if the library is found
    ARMADILLO_INCLUDE_DIRS - list of required include directories
    ARMADILLO_LIBRARIES - list of libraries to be linked
    ARMADILLO_VERSION_MAJOR - major version number
    ARMADILLO_VERSION_MINOR - minor version number
    ARMADILLO_VERSION_PATCH - patch version number
    ARMADILLO_VERSION_STRING - version number as a string (ex: "1.0.4")
    ARMADILLO_VERSION_NAME - name of the version (ex: "Antipodean Antileech")
    + +
  • +
  • + FindBISON: Find bison executable and provides macros to generate custom build rules
    +

    The module defines the following variables:

    +
      BISON_EXECUTABLE - path to the bison program
    BISON_VERSION - version of bison
    BISON_FOUND - true if the program was found
    +


    +

    The minimum required version of bison can be specified using the standard CMake syntax, e.g. find_package(BISON 2.1.3)

    +

    If bison is found, the module defines the macros:

    +
      BISON_TARGET(<Name> <YaccInput> <CodeOutput> [VERBOSE <file>]
    [COMPILE_FLAGS <string>])
    +

    which will create a custom rule to generate a parser. <YaccInput> is the path to a yacc file. <CodeOutput> is the name of the source file generated by bison. A header file is also be generated, and contains the token list. If COMPILE_FLAGS option is specified, the next parameter is added in the bison command line. if VERBOSE option is specified, <file> is created and contains verbose descriptions of the grammar and parser. The macro defines a set of variables:

    +
      BISON_${Name}_DEFINED - true is the macro ran successfully
    BISON_${Name}_INPUT - The input source file, an alias for <YaccInput>
    BISON_${Name}_OUTPUT_SOURCE - The source file generated by bison
    BISON_${Name}_OUTPUT_HEADER - The header file generated by bison
    BISON_${Name}_OUTPUTS - The sources files generated by bison
    BISON_${Name}_COMPILE_FLAGS - Options used in the bison command line
    +


    +
      ====================================================================
    Example:
    +


    +
       find_package(BISON)
    BISON_TARGET(MyParser parser.y ${CMAKE_CURRENT_BINARY_DIR}/parser.cpp)
    add_executable(Foo main.cpp ${BISON_MyParser_OUTPUTS})
    ====================================================================
    + +
  • +
  • + FindBLAS: Find BLAS library
    +

    This module finds an installed fortran library that implements the BLAS linear-algebra interface (see http://www.netlib.org/blas/). The list of libraries searched for is taken from the autoconf macro file, acx_blas.m4 (distributed at http://ac-archive.sourceforge.net/ac-archive/acx_blas.html).

    +

    This module sets the following variables:

    +
      BLAS_FOUND - set to true if a library implementing the BLAS interface
    is found
    BLAS_LINKER_FLAGS - uncached list of required linker flags (excluding -l
    and -L).
    BLAS_LIBRARIES - uncached list of libraries (using full path name) to
    link against to use BLAS
    BLAS95_LIBRARIES - uncached list of libraries (using full path name)
    to link against to use BLAS95 interface
    BLAS95_FOUND - set to true if a library implementing the BLAS f95 interface
    is found
    BLA_STATIC if set on this determines what kind of linkage we do (static)
    BLA_VENDOR if set checks only the specified vendor, if not set checks
    all the possibilities
    BLA_F95 if set on tries to find the f95 interfaces for BLAS/LAPACK
    +

    ######### ## List of vendors (BLA_VENDOR) valid in this module # Goto,ATLAS PhiPACK,CXML,DXML,SunPerf,SCSL,SGIMATH,IBMESSL,Intel10_32 (intel mkl v10 32 bit),Intel10_64lp (intel mkl v10 64 bit,lp thread model, lp64 model), # Intel( older versions of mkl 32 and 64 bit), ACML,ACML_MP,ACML_GPU,Apple, NAS, Generic C/CXX should be enabled to use Intel mkl

    + +
  • +
  • + FindBZip2: Try to find BZip2
    +

    Once done this will define

    +
      BZIP2_FOUND - system has BZip2
    BZIP2_INCLUDE_DIR - the BZip2 include directory
    BZIP2_LIBRARIES - Link these to use BZip2
    BZIP2_NEED_PREFIX - this is set if the functions are prefixed with BZ2_
    + +
  • +
  • + FindBoost: Try to find Boost include dirs and libraries
    +

    Usage of this module as follows:

    +

    NOTE: Take note of the Boost_ADDITIONAL_VERSIONS variable below. Due to Boost naming conventions and limitations in CMake this find module is NOT future safe with respect to Boost version numbers, and may break.

    +

    == Using Header-Only libraries from within Boost: ==

    +
       find_package( Boost 1.36.0 )
    if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(foo foo.cc)
    endif()
    +


    +


    +

    == Using actual libraries from within Boost: ==

    +
       set(Boost_USE_STATIC_LIBS        ON)
    set(Boost_USE_MULTITHREADED ON)
    set(Boost_USE_STATIC_RUNTIME OFF)
    find_package( Boost 1.36.0 COMPONENTS date_time filesystem system ... )
    +


    +
       if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(foo foo.cc)
    target_link_libraries(foo ${Boost_LIBRARIES})
    endif()
    +


    +


    +

    The components list needs to contain actual names of boost libraries only, such as "date_time" for "libboost_date_time". If you're using parts of Boost that contain header files only (e.g. foreach) you do not need to specify COMPONENTS.

    +

    You should provide a minimum version number that should be used. If you provide this version number and specify the REQUIRED attribute, this module will fail if it can't find the specified or a later version. If you specify a version number this is automatically put into the considered list of version numbers and thus doesn't need to be specified in the Boost_ADDITIONAL_VERSIONS variable (see below).

    +

    NOTE for Visual Studio Users:

    +
         Automatic linking is used on MSVC & Borland compilers by default when
    #including things in Boost. It's important to note that setting
    Boost_USE_STATIC_LIBS to OFF is NOT enough to get you dynamic linking,
    should you need this feature. Automatic linking typically uses static
    libraries with a few exceptions (Boost.Python is one).
    +


    +
         Please see the section below near Boost_LIB_DIAGNOSTIC_DEFINITIONS for
    more details. Adding a TARGET_LINK_LIBRARIES() as shown in the example
    above appears to cause VS to link dynamically if Boost_USE_STATIC_LIBS
    gets set to OFF. It is suggested you avoid automatic linking since it
    will make your application less portable.
    +


    +

    =========== The mess that is Boost_ADDITIONAL_VERSIONS (sorry?) ============

    +

    OK, so the Boost_ADDITIONAL_VERSIONS variable can be used to specify a list of boost version numbers that should be taken into account when searching for Boost. Unfortunately boost puts the version number into the actual filename for the libraries, so this variable will certainly be needed in the future when new Boost versions are released.

    +

    Currently this module searches for the following version numbers: 1.33, 1.33.0, 1.33.1, 1.34, 1.34.0, 1.34.1, 1.35, 1.35.0, 1.35.1, 1.36, 1.36.0, 1.36.1, 1.37, 1.37.0, 1.38, 1.38.0, 1.39, 1.39.0, 1.40, 1.40.0, 1.41, 1.41.0, 1.42, 1.42.0, 1.43, 1.43.0, 1.44, 1.44.0, 1.45, 1.45.0, 1.46, 1.46.0, 1.46.1, 1.47, 1.47.0, 1.48, 1.48.0

    +

    NOTE: If you add a new major 1.x version in Boost_ADDITIONAL_VERSIONS you should add both 1.x and 1.x.0 as shown above. Official Boost include directories omit the 3rd version number from include paths if it is 0 although not all binary Boost releases do so.

    +

    set(Boost_ADDITIONAL_VERSIONS "1.78" "1.78.0" "1.79" "1.79.0")

    +

    ===================================== ============= ========================

    +

    Variables used by this module, they can change the default behaviour and need to be set before calling find_package:

    +
       Boost_USE_MULTITHREADED      Can be set to OFF to use the non-multithreaded
    boost libraries. If not specified, defaults
    to ON.
    +


    +
       Boost_USE_STATIC_LIBS        Can be set to ON to force the use of the static
    boost libraries. Defaults to OFF.
    +


    +
       Boost_NO_SYSTEM_PATHS        Set to TRUE to suppress searching in system
    paths (or other locations outside of BOOST_ROOT
    or BOOST_INCLUDEDIR). Useful when specifying
    BOOST_ROOT. Defaults to OFF.
    [Since CMake 2.8.3]
    +


    +
       Boost_NO_BOOST_CMAKE         Do not do a find_package call in config mode
    before searching for a regular boost install.
    This will avoid finding boost-cmake installs.
    Defaults to OFF.
    [Since CMake 2.8.6]
    +


    +
       Boost_USE_STATIC_RUNTIME     If enabled, searches for boost libraries
    linked against a static C++ standard library
    ('s' ABI tag). This option should be set to
    ON or OFF because the default behavior
    if not specified is platform dependent
    for backwards compatibility.
    [Since CMake 2.8.3]
    +


    +
       Boost_USE_DEBUG_PYTHON       If enabled, searches for boost libraries
    compiled against a special debug build of
    Python ('y' ABI tag). Defaults to OFF.
    [Since CMake 2.8.3]
    +


    +
       Boost_USE_STLPORT            If enabled, searches for boost libraries
    compiled against the STLPort standard
    library ('p' ABI tag). Defaults to OFF.
    [Since CMake 2.8.3]
    +


    +
       Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS
    If enabled, searches for boost libraries
    compiled against the deprecated STLPort
    "native iostreams" feature ('n' ABI tag).
    Defaults to OFF.
    [Since CMake 2.8.3]
    +


    +

    Other Variables used by this module which you may want to set.

    +
       Boost_ADDITIONAL_VERSIONS    A list of version numbers to use for searching
    the boost include directory. Please see
    the documentation above regarding this
    annoying, but necessary variable :(
    +


    +
       Boost_DEBUG                  Set this to TRUE to enable debugging output
    of FindBoost.cmake if you are having problems.
    Please enable this before filing any bug
    reports.
    +


    +
       Boost_DETAILED_FAILURE_MSG   FindBoost doesn't output detailed information
    about why it failed or how to fix the problem
    unless this is set to TRUE or the REQUIRED
    keyword is specified in find_package().
    [Since CMake 2.8.0]
    +


    +
       Boost_COMPILER               Set this to the compiler suffix used by Boost
    (e.g. "-gcc43") if FindBoost has problems finding
    the proper Boost installation
    +


    +
       Boost_THREADAPI                When building boost.thread, sometimes the name of the
    library contains an additional "pthread" or "win32"
    string known as the threadapi. This can happen when
    compiling against pthreads on Windows or win32 threads
    on Cygwin. You may specify this variable and if set
    when FindBoost searches for the Boost threading library
    it will first try to match the threadapi you specify.
    For Example: libboost_thread_win32-mgw45-mt-1_43.a
    might be found if you specified "win32" here before
    falling back on libboost_thread-mgw45-mt-1_43.a.
    [Since CMake 2.8.3]
    +


    +
       Boost_REALPATH               Resolves symbolic links for discovered boost libraries
    to assist with packaging. For example, instead of
    Boost_SYSTEM_LIBRARY_RELEASE being resolved to
    "/usr/lib/libboost_system.so" it would be
    "/usr/lib/libboost_system.so.1.42.0" instead.
    This does not affect linking and should not be
    enabled unless the user needs this information.
    [Since CMake 2.8.3]
    +


    + +
  • +
  • + FindBullet: Try to find the Bullet physics engine
    +


    +
      This module defines the following variables
    +


    +
      BULLET_FOUND - Was bullet found
    BULLET_INCLUDE_DIRS - the Bullet include directories
    BULLET_LIBRARIES - Link to this, by default it includes
    all bullet components (Dynamics,
    Collision, LinearMath, & SoftBody)
    +


    +
      This module accepts the following variables
    +


    +
      BULLET_ROOT - Can be set to bullet install path or Windows build path
    +


    + +
  • +
  • + FindCABLE: Find CABLE
    +

    This module finds if CABLE is installed and determines where the include files and libraries are. This code sets the following variables:

    +
      CABLE             the path to the cable executable
    CABLE_TCL_LIBRARY the path to the Tcl wrapper library
    CABLE_INCLUDE_DIR the path to the include directory
    +


    +

    To build Tcl wrappers, you should add shared library and link it to ${CABLE_TCL_LIBRARY}. You should also add ${CABLE_INCLUDE_DIR} as an include directory.

    + +
  • +
  • + FindCUDA: Tools for building CUDA C files: libraries and build dependencies.
    +

    This script locates the NVIDIA CUDA C tools. It should work on linux, windows, and mac and should be reasonably up to date with CUDA C releases.

    +

    This script makes use of the standard find_package arguments of <VERSION>, REQUIRED and QUIET. CUDA_FOUND will report if an acceptable version of CUDA was found.

    +

    The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if the prefix cannot be determined by the location of nvcc in the system path and REQUIRED is specified to find_package(). To use a different installed version of the toolkit set the environment variable CUDA_BIN_PATH before running cmake (e.g. CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default /usr/local/cuda) or set CUDA_TOOLKIT_ROOT_DIR after configuring. If you change the value of CUDA_TOOLKIT_ROOT_DIR, various components that depend on the path will be relocated.

    +

    It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain platforms, or to use a cuda runtime not installed in the default location. In newer versions of the toolkit the cuda library is included with the graphics driver- be sure that the driver version matches what is needed by the cuda runtime version.

    +

    The following variables affect the behavior of the macros in the script (in alphebetical order). Note that any of these flags can be changed multiple times in the same directory before calling CUDA_ADD_EXECUTABLE, CUDA_ADD_LIBRARY, CUDA_COMPILE, CUDA_COMPILE_PTX or CUDA_WRAP_SRCS.

    +
      CUDA_64_BIT_DEVICE_CODE (Default matches host bit size)
    -- Set to ON to compile for 64 bit device code, OFF for 32 bit device code.
    Note that making this different from the host code when generating object
    or C files from CUDA code just won't work, because size_t gets defined by
    nvcc in the generated source. If you compile to PTX and then load the
    file yourself, you can mix bit sizes between device and host.
    +


    +
      CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default ON)
    -- Set to ON if you want the custom build rule to be attached to the source
    file in Visual Studio. Turn OFF if you add the same cuda file to multiple
    targets.
    +


    +
         This allows the user to build the target from the CUDA file; however, bad
    things can happen if the CUDA source file is added to multiple targets.
    When performing parallel builds it is possible for the custom build
    command to be run more than once and in parallel causing cryptic build
    errors. VS runs the rules for every source file in the target, and a
    source can have only one rule no matter how many projects it is added to.
    When the rule is run from multiple targets race conditions can occur on
    the generated file. Eventually everything will get built, but if the user
    is unaware of this behavior, there may be confusion. It would be nice if
    this script could detect the reuse of source files across multiple targets
    and turn the option off for the user, but no good solution could be found.
    +


    +
      CUDA_BUILD_CUBIN (Default OFF)
    -- Set to ON to enable and extra compilation pass with the -cubin option in
    Device mode. The output is parsed and register, shared memory usage is
    printed during build.
    +


    +
      CUDA_BUILD_EMULATION (Default OFF for device mode)
    -- Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files
    when CUDA_BUILD_EMULATION is TRUE.
    +


    +
      CUDA_GENERATED_OUTPUT_DIR (Default CMAKE_CURRENT_BINARY_DIR)
    -- Set to the path you wish to have the generated files placed. If it is
    blank output files will be placed in CMAKE_CURRENT_BINARY_DIR.
    Intermediate files will always be placed in
    CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
    +


    +
      CUDA_HOST_COMPILATION_CPP (Default ON)
    -- Set to OFF for C compilation of host code.
    +


    +
      CUDA_NVCC_FLAGS
    CUDA_NVCC_FLAGS_<CONFIG>
    -- Additional NVCC command line arguments. NOTE: multiple arguments must be
    semi-colon delimited (e.g. --compiler-options;-Wall)
    +


    +
      CUDA_PROPAGATE_HOST_FLAGS (Default ON)
    -- Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration
    dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the
    host compiler through nvcc's -Xcompiler flag. This helps make the
    generated host code match the rest of the system better. Sometimes
    certain flags give nvcc problems, and this will help you turn the flag
    propagation off. This does not affect the flags supplied directly to nvcc
    via CUDA_NVCC_FLAGS or through the OPTION flags specified through
    CUDA_ADD_LIBRARY, CUDA_ADD_EXECUTABLE, or CUDA_WRAP_SRCS. Flags used for
    shared library compilation are not affected by this flag.
    +


    +
      CUDA_VERBOSE_BUILD (Default OFF)
    -- Set to ON to see all the commands used when building the CUDA file. When
    using a Makefile generator the value defaults to VERBOSE (run make
    VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will
    always print the output.
    +


    +

    The script creates the following macros (in alphebetical order):

    +
      CUDA_ADD_CUFFT_TO_TARGET( cuda_target )
    -- Adds the cufft library to the target (can be any target). Handles whether
    you are in emulation mode or not.
    +


    +
      CUDA_ADD_CUBLAS_TO_TARGET( cuda_target )
    -- Adds the cublas library to the target (can be any target). Handles
    whether you are in emulation mode or not.
    +


    +
      CUDA_ADD_EXECUTABLE( cuda_target file0 file1 ...
    [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
    -- Creates an executable "cuda_target" which is made up of the files
    specified. All of the non CUDA C files are compiled using the standard
    build rules specified by CMAKE and the cuda files are compiled to object
    files using nvcc and the host compiler. In addition CUDA_INCLUDE_DIRS is
    added automatically to include_directories(). Some standard CMake target
    calls can be used on the target after calling this macro
    (e.g. set_target_properties and target_link_libraries), but setting
    properties that adjust compilation flags will not affect code compiled by
    nvcc. Such flags should be modified before calling CUDA_ADD_EXECUTABLE,
    CUDA_ADD_LIBRARY or CUDA_WRAP_SRCS.
    +


    +
      CUDA_ADD_LIBRARY( cuda_target file0 file1 ...
    [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
    -- Same as CUDA_ADD_EXECUTABLE except that a library is created.
    +


    +
      CUDA_BUILD_CLEAN_TARGET()
    -- Creates a convience target that deletes all the dependency files
    generated. You should make clean after running this target to ensure the
    dependency files get regenerated.
    +


    +
      CUDA_COMPILE( generated_files file0 file1 ... [STATIC | SHARED | MODULE]
    [OPTIONS ...] )
    -- Returns a list of generated files from the input source files to be used
    with ADD_LIBRARY or ADD_EXECUTABLE.
    +


    +
      CUDA_COMPILE_PTX( generated_files file0 file1 ... [OPTIONS ...] )
    -- Returns a list of PTX files generated from the input source files.
    +


    +
      CUDA_INCLUDE_DIRECTORIES( path0 path1 ... )
    -- Sets the directories that should be passed to nvcc
    (e.g. nvcc -Ipath0 -Ipath1 ... ). These paths usually contain other .cu
    files.
    +


    +
      CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
    [STATIC | SHARED | MODULE] [OPTIONS ...] )
    -- This is where all the magic happens. CUDA_ADD_EXECUTABLE,
    CUDA_ADD_LIBRARY, CUDA_COMPILE, and CUDA_COMPILE_PTX all call this
    function under the hood.
    +


    +
         Given the list of files (file0 file1 ... fileN) this macro generates
    custom commands that generate either PTX or linkable objects (use "PTX" or
    "OBJ" for the format argument to switch). Files that don't end with .cu
    or have the HEADER_FILE_ONLY property are ignored.
    +


    +
         The arguments passed in after OPTIONS are extra command line options to
    give to nvcc. You can also specify per configuration options by
    specifying the name of the configuration followed by the options. General
    options must preceed configuration specific options. Not all
    configurations need to be specified, only the ones provided will be used.
    +


    +
            OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
    DEBUG -g
    RELEASE --use_fast_math
    RELWITHDEBINFO --use_fast_math;-g
    MINSIZEREL --use_fast_math
    +


    +
         For certain configurations (namely VS generating object files with
    CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will
    be produced for the given cuda file. This is because when you add the
    cuda file to Visual Studio it knows that this file produces an object file
    and will link in the resulting object file automatically.
    +


    +
         This script will also generate a separate cmake script that is used at
    build time to invoke nvcc. This is for several reasons.
    +


    +
           1. nvcc can return negative numbers as return values which confuses
    Visual Studio into thinking that the command succeeded. The script now
    checks the error codes and produces errors when there was a problem.
    +


    +
           2. nvcc has been known to not delete incomplete results when it
    encounters problems. This confuses build systems into thinking the
    target was generated when in fact an unusable file exists. The script
    now deletes the output files if there was an error.
    +


    +
           3. By putting all the options that affect the build into a file and then
    make the build rule dependent on the file, the output files will be
    regenerated when the options change.
    +


    +
         This script also looks at optional arguments STATIC, SHARED, or MODULE to
    determine when to target the object compilation for a shared library.
    BUILD_SHARED_LIBS is ignored in CUDA_WRAP_SRCS, but it is respected in
    CUDA_ADD_LIBRARY. On some systems special flags are added for building
    objects intended for shared libraries. A preprocessor macro,
    <target_name>_EXPORTS is defined when a shared library compilation is
    detected.
    +


    +
         Flags passed into add_definitions with -D or /D are passed along to nvcc.
    +


    +

    The script defines the following variables:

    +
      CUDA_VERSION_MAJOR    -- The major version of cuda as reported by nvcc.
    CUDA_VERSION_MINOR -- The minor version.
    CUDA_VERSION
    CUDA_VERSION_STRING -- CUDA_VERSION_MAJOR.CUDA_VERSION_MINOR
    +


    +
      CUDA_TOOLKIT_ROOT_DIR -- Path to the CUDA Toolkit (defined if not set).
    CUDA_SDK_ROOT_DIR -- Path to the CUDA SDK. Use this to find files in the
    SDK. This script will not directly support finding
    specific libraries or headers, as that isn't
    supported by NVIDIA. If you want to change
    libraries when the path changes see the
    FindCUDA.cmake script for an example of how to clear
    these variables. There are also examples of how to
    use the CUDA_SDK_ROOT_DIR to locate headers or
    libraries, if you so choose (at your own risk).
    CUDA_INCLUDE_DIRS -- Include directory for cuda headers. Added automatically
    for CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY.
    CUDA_LIBRARIES -- Cuda RT library.
    CUDA_CUFFT_LIBRARIES -- Device or emulation library for the Cuda FFT
    implementation (alternative to:
    CUDA_ADD_CUFFT_TO_TARGET macro)
    CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
    implementation (alterative to:
    CUDA_ADD_CUBLAS_TO_TARGET macro).
    +


    +


    +
      James Bigler, NVIDIA Corp (nvidia.com - jbigler)
    Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
    +


    +
      Copyright (c) 2008 - 2009 NVIDIA Corporation.  All rights reserved.
    +


    +
      Copyright (c) 2007-2009
    Scientific Computing and Imaging Institute, University of Utah
    +


    +
      This code is licensed under the MIT License.  See the FindCUDA.cmake script
    for the text of the license.
    + +
  • +
  • + FindCURL: Find curl
    +

    Find the native CURL headers and libraries.

    +
      CURL_INCLUDE_DIRS - where to find curl/curl.h, etc.
    CURL_LIBRARIES - List of libraries when using curl.
    CURL_FOUND - True if curl found.
    + +
  • +
  • + FindCVS:
    +

    The module defines the following variables:

    +
       CVS_EXECUTABLE - path to cvs command line client
    CVS_FOUND - true if the command line client was found
    +

    Example usage:

    +
       find_package(CVS)
    if(CVS_FOUND)
    message("CVS found: ${CVS_EXECUTABLE}")
    endif(CVS_FOUND)
    + +
  • +
  • + FindCoin3D: Find Coin3D (Open Inventor)
    +

    Coin3D is an implementation of the Open Inventor API. It provides data structures and algorithms for 3D visualization http://www.coin3d.org/

    +

    This module defines the following variables

    +
      COIN3D_FOUND         - system has Coin3D - Open Inventor
    COIN3D_INCLUDE_DIRS - where the Inventor include directory can be found
    COIN3D_LIBRARIES - Link to this to use Coin3D
    +


    + +
  • +
  • + FindCups: Try to find the Cups printing system
    +

    Once done this will define

    +
      CUPS_FOUND - system has Cups
    CUPS_INCLUDE_DIR - the Cups include directory
    CUPS_LIBRARIES - Libraries needed to use Cups
    Set CUPS_REQUIRE_IPP_DELETE_ATTRIBUTE to TRUE if you need a version which
    features this function (i.e. at least 1.1.19)
    + +
  • +
  • + FindCurses: Find the curses include file and library
    +


    +
      CURSES_FOUND - system has Curses
    CURSES_INCLUDE_DIR - the Curses include directory
    CURSES_LIBRARIES - The libraries needed to use Curses
    CURSES_HAVE_CURSES_H - true if curses.h is available
    CURSES_HAVE_NCURSES_H - true if ncurses.h is available
    CURSES_HAVE_NCURSES_NCURSES_H - true if ncurses/ncurses.h is available
    CURSES_HAVE_NCURSES_CURSES_H - true if ncurses/curses.h is available
    CURSES_LIBRARY - set for backwards compatibility with 2.4 CMake
    +


    +

    Set CURSES_NEED_NCURSES to TRUE before the FIND_PACKAGE() command if NCurses functionality is required.

    + +
  • +
  • + FindCxxTest: Find CxxTest
    +

    Find the CxxTest suite and declare a helper macro for creating unit tests and integrating them with CTest. For more details on CxxTest see http://cxxtest.tigris.org

    +

    INPUT Variables

    +
       CXXTEST_USE_PYTHON [deprecated since 1.3]
    Only used in the case both Python & Perl
    are detected on the system to control
    which CxxTest code generator is used.
    +


    +
           NOTE: In older versions of this Find Module,
    this variable controlled if the Python test
    generator was used instead of the Perl one,
    regardless of which scripting language the
    user had installed.
    +


    +
       CXXTEST_TESTGEN_ARGS (since CMake 2.8.3)
    Specify a list of options to pass to the CxxTest code
    generator. If not defined, --error-printer is
    passed.
    +


    +

    OUTPUT Variables

    +
       CXXTEST_FOUND
    True if the CxxTest framework was found
    CXXTEST_INCLUDE_DIRS
    Where to find the CxxTest include directory
    CXXTEST_PERL_TESTGEN_EXECUTABLE
    The perl-based test generator
    CXXTEST_PYTHON_TESTGEN_EXECUTABLE
    The python-based test generator
    CXXTEST_TESTGEN_EXECUTABLE (since CMake 2.8.3)
    The test generator that is actually used (chosen using user preferences
    and interpreters found in the system)
    CXXTEST_TESTGEN_INTERPRETER (since CMake 2.8.3)
    The full path to the Perl or Python executable on the system
    +


    +

    MACROS for optional use by CMake users:

    +
        CXXTEST_ADD_TEST(<test_name> <gen_source_file> <input_files_to_testgen...>)
    Creates a CxxTest runner and adds it to the CTest testing suite
    Parameters:
    test_name The name of the test
    gen_source_file The generated source filename to be
    generated by CxxTest
    input_files_to_testgen The list of header files containing the
    CxxTest::TestSuite's to be included in
    this runner

    #==============
    Example Usage:
    +


    +
               find_package(CxxTest)
    if(CXXTEST_FOUND)
    include_directories(${CXXTEST_INCLUDE_DIR})
    enable_testing()
    +


    +
                   CXXTEST_ADD_TEST(unittest_foo foo_test.cc
    ${CMAKE_CURRENT_SOURCE_DIR}/foo_test.h)
    target_link_libraries(unittest_foo foo) # as needed
    endif()
    +


    +
                  This will (if CxxTest is found):
    1. Invoke the testgen executable to autogenerate foo_test.cc in the
    binary tree from "foo_test.h" in the current source directory.
    2. Create an executable and test called unittest_foo.

    #=============
    Example foo_test.h:
    +


    +
              #include <cxxtest/TestSuite.h>

    class MyTestSuite : public CxxTest::TestSuite
    {
    public:
    void testAddition( void )
    {
    TS_ASSERT( 1 + 1 > 1 );
    TS_ASSERT_EQUALS( 1 + 1, 2 );
    }
    };
    +


    + +
  • +
  • + FindCygwin: this module looks for Cygwin
    +


    + +
  • +
  • + FindDCMTK: find DCMTK libraries and applications
    +


    + +
  • +
  • + FindDart: Find DART
    +

    This module looks for the dart testing software and sets DART_ROOT to point to where it found it.

    + +
  • +
  • + FindDevIL:
    +

    This module locates the developer's image library. http://openil.sourceforge.net/

    +

    This module sets: IL_LIBRARIES the name of the IL library. These include the full path to the core DevIL library. This one has to be linked into the application. ILU_LIBRARIES the name of the ILU library. Again, the full path. This library is for filters and effects, not actual loading. It doesn't have to be linked if the functionality it provides is not used. ILUT_LIBRARIES the name of the ILUT library. Full path. This part of the library interfaces with OpenGL. It is not strictly needed in applications. IL_INCLUDE_DIR where to find the il.h, ilu.h and ilut.h files. IL_FOUND this is set to TRUE if all the above variables were set. This will be set to false if ILU or ILUT are not found, even if they are not needed. In most systems, if one library is found all the others are as well. That's the way the DevIL developers release it.

    + +
  • +
  • + FindDoxygen: This module looks for Doxygen and the path to Graphviz's dot
    +

    Doxygen is a documentation generation tool. Please see http://www.doxygen.org

    +

    This module accepts the following optional variables:

    +
       DOXYGEN_SKIP_DOT       = If true this module will skip trying to find Dot
    (an optional component often used by Doxygen)
    +


    +

    This modules defines the following variables:

    +
       DOXYGEN_EXECUTABLE     = The path to the doxygen command.
    DOXYGEN_FOUND = Was Doxygen found or not?
    +


    +
       DOXYGEN_DOT_EXECUTABLE = The path to the dot program used by doxygen.
    DOXYGEN_DOT_FOUND = Was Dot found or not?
    DOXYGEN_DOT_PATH = The path to dot not including the executable
    +


    +


    + +
  • +
  • + FindEXPAT: Find expat
    +

    Find the native EXPAT headers and libraries.

    +
      EXPAT_INCLUDE_DIRS - where to find expat.h, etc.
    EXPAT_LIBRARIES - List of libraries when using expat.
    EXPAT_FOUND - True if expat found.
    + +
  • +
  • + FindFLEX: Find flex executable and provides a macro to generate custom build rules
    +


    +

    The module defines the following variables:

    +
      FLEX_FOUND - true is flex executable is found
    FLEX_EXECUTABLE - the path to the flex executable
    FLEX_VERSION - the version of flex
    FLEX_LIBRARIES - The flex libraries
    FLEX_INCLUDE_DIRS - The path to the flex headers
    +


    +

    The minimum required version of flex can be specified using the standard syntax, e.g. FIND_PACKAGE(FLEX 2.5.13)

    +


    +

    If flex is found on the system, the module provides the macro:

    +
      FLEX_TARGET(Name FlexInput FlexOutput [COMPILE_FLAGS <string>])
    +

    which creates a custom command to generate the <FlexOutput> file from the <FlexInput> file. If COMPILE_FLAGS option is specified, the next parameter is added to the flex command line. Name is an alias used to get details of this custom command. Indeed the macro defines the following variables:

    +
      FLEX_${Name}_DEFINED - true is the macro ran successfully
    FLEX_${Name}_OUTPUTS - the source file generated by the custom rule, an
    alias for FlexOutput
    FLEX_${Name}_INPUT - the flex source file, an alias for ${FlexInput}
    +


    +

    Flex scanners oftenly use tokens defined by Bison: the code generated by Flex depends of the header generated by Bison. This module also defines a macro:

    +
      ADD_FLEX_BISON_DEPENDENCY(FlexTarget BisonTarget)
    +

    which adds the required dependency between a scanner and a parser where <FlexTarget> and <BisonTarget> are the first parameters of respectively FLEX_TARGET and BISON_TARGET macros.

    +
      ====================================================================
    Example:
    +


    +
       find_package(BISON)
    find_package(FLEX)
    +


    +
       BISON_TARGET(MyParser parser.y ${CMAKE_CURRENT_BINARY_DIR}/parser.cpp)
    FLEX_TARGET(MyScanner lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lexer.cpp)
    ADD_FLEX_BISON_DEPENDENCY(MyScanner MyParser)
    +


    +
       include_directories(${CMAKE_CURRENT_BINARY_DIR})
    add_executable(Foo
    Foo.cc
    ${BISON_MyParser_OUTPUTS}
    ${FLEX_MyScanner_OUTPUTS}
    )
    ====================================================================
    + +
  • +
  • + FindFLTK: Find the native FLTK includes and library
    +


    +

    By default FindFLTK.cmake will search for all of the FLTK components and add them to the FLTK_LIBRARIES variable.

    +
       You can limit the components which get placed in FLTK_LIBRARIES by
    defining one or more of the following three options:
    +


    +
         FLTK_SKIP_OPENGL, set to true to disable searching for opengl and
    the FLTK GL library
    FLTK_SKIP_FORMS, set to true to disable searching for fltk_forms
    FLTK_SKIP_IMAGES, set to true to disable searching for fltk_images
    +


    +
         FLTK_SKIP_FLUID, set to true if the fluid binary need not be present
    at build time
    +


    +

    The following variables will be defined:

    +
         FLTK_FOUND, True if all components not skipped were found
    FLTK_INCLUDE_DIR, where to find include files
    FLTK_LIBRARIES, list of fltk libraries you should link against
    FLTK_FLUID_EXECUTABLE, where to find the Fluid tool
    FLTK_WRAP_UI, This enables the FLTK_WRAP_UI command
    +


    +

    The following cache variables are assigned but should not be used. See the FLTK_LIBRARIES variable instead.

    +
         FLTK_BASE_LIBRARY   = the full path to fltk.lib
    FLTK_GL_LIBRARY = the full path to fltk_gl.lib
    FLTK_FORMS_LIBRARY = the full path to fltk_forms.lib
    FLTK_IMAGES_LIBRARY = the full path to fltk_images.lib
    + +
  • +
  • + FindFLTK2: Find the native FLTK2 includes and library
    +

    The following settings are defined

    +
      FLTK2_FLUID_EXECUTABLE, where to find the Fluid tool
    FLTK2_WRAP_UI, This enables the FLTK2_WRAP_UI command
    FLTK2_INCLUDE_DIR, where to find include files
    FLTK2_LIBRARIES, list of fltk2 libraries
    FLTK2_FOUND, Don't use FLTK2 if false.
    +

    The following settings should not be used in general.

    +
      FLTK2_BASE_LIBRARY   = the full path to fltk2.lib
    FLTK2_GL_LIBRARY = the full path to fltk2_gl.lib
    FLTK2_IMAGES_LIBRARY = the full path to fltk2_images.lib
    + +
  • +
  • + FindFreetype: Locate FreeType library
    +

    This module defines

    +
      FREETYPE_LIBRARIES, the library to link against
    FREETYPE_FOUND, if false, do not try to link to FREETYPE
    FREETYPE_INCLUDE_DIRS, where to find headers.
    This is the concatenation of the paths:
    FREETYPE_INCLUDE_DIR_ft2build
    FREETYPE_INCLUDE_DIR_freetype2
    +


    +

    $FREETYPE_DIR is an environment variable that would correspond to the ./configure --prefix=$FREETYPE_DIR used in building FREETYPE.

    + +
  • +
  • + FindGCCXML: Find the GCC-XML front-end executable.
    +


    +

    This module will define the following variables:

    +
      GCCXML - the GCC-XML front-end executable.
    + +
  • +
  • + FindGDAL:
    +

    Locate gdal

    +

    This module accepts the following environment variables:

    +
        GDAL_DIR or GDAL_ROOT - Specify the location of GDAL
    +


    +

    This module defines the following CMake variables:

    +
        GDAL_FOUND - True if libgdal is found
    GDAL_LIBRARY - A variable pointing to the GDAL library
    GDAL_INCLUDE_DIR - Where to find the headers
    + +
  • +
  • + FindGIF:
    +

    This module searches giflib and defines GIF_LIBRARIES - libraries to link to in order to use GIF GIF_FOUND, if false, do not try to link GIF_INCLUDE_DIR, where to find the headers GIF_VERSION, reports either version 4 or 3 (for everything before version 4)

    +

    The minimum required version of giflib can be specified using the standard syntax, e.g. FIND_PACKAGE(GIF 4)

    +

    $GIF_DIR is an environment variable that would correspond to the ./configure --prefix=$GIF_DIR

    + +
  • +
  • + FindGLUT: try to find glut library and include files
    +
      GLUT_INCLUDE_DIR, where to find GL/glut.h, etc.
    GLUT_LIBRARIES, the libraries to link against
    GLUT_FOUND, If false, do not try to use GLUT.
    +

    Also defined, but not for general use are:

    +
      GLUT_glut_LIBRARY = the full path to the glut library.
    GLUT_Xmu_LIBRARY = the full path to the Xmu library.
    GLUT_Xi_LIBRARY = the full path to the Xi Library.
    + +
  • +
  • + FindGTK: try to find GTK (and glib) and GTKGLArea
    +
      GTK_INCLUDE_DIR   - Directories to include to use GTK
    GTK_LIBRARIES - Files to link against to use GTK
    GTK_FOUND - GTK was found
    GTK_GL_FOUND - GTK's GL features were found
    + +
  • +
  • + FindGTK2: FindGTK2.cmake
    +

    This module can find the GTK2 widget libraries and several of its other optional components like gtkmm, glade, and glademm.

    +

    NOTE: If you intend to use version checking, CMake 2.6.2 or later is

    +
           required.
    +


    +

    Specify one or more of the following components as you call this find module. See example below.

    +
       gtk
    gtkmm
    glade
    glademm
    +


    +

    The following variables will be defined for your use

    +
       GTK2_FOUND - Were all of your specified components found?
    GTK2_INCLUDE_DIRS - All include directories
    GTK2_LIBRARIES - All libraries
    +


    +
       GTK2_VERSION - The version of GTK2 found (x.y.z)
    GTK2_MAJOR_VERSION - The major version of GTK2
    GTK2_MINOR_VERSION - The minor version of GTK2
    GTK2_PATCH_VERSION - The patch version of GTK2
    +


    +

    Optional variables you can define prior to calling this module:

    +
       GTK2_DEBUG - Enables verbose debugging of the module
    GTK2_SKIP_MARK_AS_ADVANCED - Disable marking cache variables as advanced
    GTK2_ADDITIONAL_SUFFIXES - Allows defining additional directories to
    search for include files
    +


    +

    ================= Example Usage:

    +
       Call find_package() once, here are some examples to pick from:
    +


    +
       Require GTK 2.6 or later
    find_package(GTK2 2.6 REQUIRED gtk)
    +


    +
       Require GTK 2.10 or later and Glade
    find_package(GTK2 2.10 REQUIRED gtk glade)
    +


    +
       Search for GTK/GTKMM 2.8 or later
    find_package(GTK2 2.8 COMPONENTS gtk gtkmm)
    +


    +
       if(GTK2_FOUND)
    include_directories(${GTK2_INCLUDE_DIRS})
    add_executable(mygui mygui.cc)
    target_link_libraries(mygui ${GTK2_LIBRARIES})
    endif()
    +


    + +
  • +
  • + FindGTest: --------------------
    +

    Locate the Google C++ Testing Framework.

    +

    Defines the following variables:

    +
       GTEST_FOUND - Found the Google Testing framework
    GTEST_INCLUDE_DIRS - Include directories
    +


    +

    Also defines the library variables below as normal variables. These contain debug/optimized keywords when a debugging library is found.

    +
       GTEST_BOTH_LIBRARIES - Both libgtest & libgtest-main
    GTEST_LIBRARIES - libgtest
    GTEST_MAIN_LIBRARIES - libgtest-main
    +


    +

    Accepts the following variables as input:

    +
       GTEST_ROOT - (as a CMake or environment variable)
    The root directory of the gtest install prefix
    +


    +
       GTEST_MSVC_SEARCH - If compiling with MSVC, this variable can be set to
    "MD" or "MT" to enable searching a GTest build tree
    (defaults: "MD")
    +


    +

    Example Usage:

    +
        enable_testing()
    find_package(GTest REQUIRED)
    include_directories(${GTEST_INCLUDE_DIRS})
    +


    +
        add_executable(foo foo.cc)
    target_link_libraries(foo ${GTEST_BOTH_LIBRARIES})
    +


    +
        add_test(AllTestsInFoo foo)
    +


    +


    +

    If you would like each Google test to show up in CTest as a test you may use the following macro. NOTE: It will slow down your tests by running an executable for each test and test fixture. You will also have to rerun CMake after adding or removing tests or test fixtures.

    +

    GTEST_ADD_TESTS(executable extra_args ARGN)

    +
        executable = The path to the test executable
    extra_args = Pass a list of extra arguments to be passed to
    executable enclosed in quotes (or "" for none)
    ARGN = A list of source files to search for tests & test
    fixtures.
    +


    +
      Example:
    set(FooTestArgs --foo 1 --bar 2)
    add_executable(FooTest FooUnitTest.cc)
    GTEST_ADD_TESTS(FooTest "${FooTestArgs}" FooUnitTest.cc)
    + +
  • +
  • + FindGettext: Find GNU gettext tools
    +

    This module looks for the GNU gettext tools. This module defines the following values:

    +
      GETTEXT_MSGMERGE_EXECUTABLE: the full path to the msgmerge tool.
    GETTEXT_MSGFMT_EXECUTABLE: the full path to the msgfmt tool.
    GETTEXT_FOUND: True if gettext has been found.
    +


    +

    Additionally it provides the following macros: GETTEXT_CREATE_TRANSLATIONS ( outputFile [ALL] file1 ... fileN )

    +
        This will create a target "translations" which will convert the
    given input po files into the binary output mo file. If the
    ALL option is used, the translations will also be created when
    building the default target.
    +

    GETTEXT_PROCESS_POT( <potfile> [ALL] [INSTALL_DESTINATION <destdir>] LANGUAGES <lang1> <lang2> ... )

    +
         Process the given pot file to mo files.
    If INSTALL_DESTINATION is given then automatically install rules will be created,
    the language subdirectory will be taken into account (by default use share/locale/).
    If ALL is specified, the pot file is processed when building the all traget.
    It creates a custom target "potfile".
    +

    GETTEXT_PROCESS_PO_FILES( <lang> [ALL] [INSTALL_DESTINATION <dir>] PO_FILES <po1> <po2> ... )

    +
         Process the given po files to mo files for the given language.
    If INSTALL_DESTINATION is given then automatically install rules will be created,
    the language subdirectory will be taken into account (by default use share/locale/).
    If ALL is specified, the po files are processed when building the all traget.
    It creates a custom target "pofiles".
    + +
  • +
  • + FindGit:
    +

    The module defines the following variables:

    +
       GIT_EXECUTABLE - path to git command line client
    GIT_FOUND - true if the command line client was found
    +

    Example usage:

    +
       find_package(Git)
    if(GIT_FOUND)
    message("git found: ${GIT_EXECUTABLE}")
    endif()
    + +
  • +
  • + FindGnuTLS: Try to find the GNU Transport Layer Security library (gnutls)
    +


    +

    Once done this will define

    +
      GNUTLS_FOUND - System has gnutls
    GNUTLS_INCLUDE_DIR - The gnutls include directory
    GNUTLS_LIBRARIES - The libraries needed to use gnutls
    GNUTLS_DEFINITIONS - Compiler switches required for using gnutls
    + +
  • +
  • + FindGnuplot: this module looks for gnuplot
    +


    +

    Once done this will define

    +
      GNUPLOT_FOUND - system has Gnuplot
    GNUPLOT_EXECUTABLE - the Gnuplot executable
    + +
  • +
  • + FindHDF5: Find HDF5, a library for reading and writing self describing array data.
    +


    +

    This module invokes the HDF5 wrapper compiler that should be installed alongside HDF5. Depending upon the HDF5 Configuration, the wrapper compiler is called either h5cc or h5pcc. If this succeeds, the module will then call the compiler with the -show argument to see what flags are used when compiling an HDF5 client application.

    +

    The module will optionally accept the COMPONENTS argument. If no COMPONENTS are specified, then the find module will default to finding only the HDF5 C library. If one or more COMPONENTS are specified, the module will attempt to find the language bindings for the specified components. The only valid components are C, CXX, Fortran, HL, and Fortran_HL. If the COMPONENTS argument is not given, the module will attempt to find only the C bindings.

    +

    On UNIX systems, this module will read the variable HDF5_USE_STATIC_LIBRARIES to determine whether or not to prefer a static link to a dynamic link for HDF5 and all of it's dependencies. To use this feature, make sure that the HDF5_USE_STATIC_LIBRARIES variable is set before the call to find_package.

    +

    To provide the module with a hint about where to find your HDF5 installation, you can set the environment variable HDF5_ROOT. The Find module will then look in this path when searching for HDF5 executables, paths, and libraries.

    +

    In addition to finding the includes and libraries required to compile an HDF5 client application, this module also makes an effort to find tools that come with the HDF5 distribution that may be useful for regression testing.

    +

    This module will define the following variables:

    +
      HDF5_INCLUDE_DIRS - Location of the hdf5 includes
    HDF5_INCLUDE_DIR - Location of the hdf5 includes (deprecated)
    HDF5_DEFINITIONS - Required compiler definitions for HDF5
    HDF5_C_LIBRARIES - Required libraries for the HDF5 C bindings.
    HDF5_CXX_LIBRARIES - Required libraries for the HDF5 C++ bindings
    HDF5_Fortran_LIBRARIES - Required libraries for the HDF5 Fortran bindings
    HDF5_HL_LIBRARIES - Required libraries for the HDF5 high level API
    HDF5_Fortran_HL_LIBRARIES - Required libraries for the high level Fortran
    bindings.
    HDF5_LIBRARIES - Required libraries for all requested bindings
    HDF5_FOUND - true if HDF5 was found on the system
    HDF5_LIBRARY_DIRS - the full set of library directories
    HDF5_IS_PARALLEL - Whether or not HDF5 was found with parallel IO support
    HDF5_C_COMPILER_EXECUTABLE - the path to the HDF5 C wrapper compiler
    HDF5_CXX_COMPILER_EXECUTABLE - the path to the HDF5 C++ wrapper compiler
    HDF5_Fortran_COMPILER_EXECUTABLE - the path to the HDF5 Fortran wrapper compiler
    HDF5_DIFF_EXECUTABLE - the path to the HDF5 dataset comparison tool
    + +
  • +
  • + FindHSPELL: Try to find Hspell
    +

    Once done this will define

    +
      HSPELL_FOUND - system has Hspell
    HSPELL_INCLUDE_DIR - the Hspell include directory
    HSPELL_LIBRARIES - The libraries needed to use Hspell
    HSPELL_DEFINITIONS - Compiler switches required for using Hspell
    +


    +
      HSPELL_VERSION_STRING - The version of Hspell found (x.y)
    HSPELL_MAJOR_VERSION - the major version of Hspell
    HSPELL_MINOR_VERSION - The minor version of Hspell
    + +
  • +
  • + FindHTMLHelp: This module looks for Microsoft HTML Help Compiler
    +

    It defines:

    +
       HTML_HELP_COMPILER     : full path to the Compiler (hhc.exe)
    HTML_HELP_INCLUDE_PATH : include path to the API (htmlhelp.h)
    HTML_HELP_LIBRARY : full path to the library (htmlhelp.lib)
    +


    + +
  • +
  • + FindITK: Find an ITK installation or build tree. +
  • +
  • + FindImageMagick: Find the ImageMagick binary suite.
    +

    This module will search for a set of ImageMagick tools specified as components in the FIND_PACKAGE call. Typical components include, but are not limited to (future versions of ImageMagick might have additional components not listed here):

    +
      animate
    compare
    composite
    conjure
    convert
    display
    identify
    import
    mogrify
    montage
    stream
    +


    +

    If no component is specified in the FIND_PACKAGE call, then it only searches for the ImageMagick executable directory. This code defines the following variables:

    +
      ImageMagick_FOUND                  - TRUE if all components are found.
    ImageMagick_EXECUTABLE_DIR - Full path to executables directory.
    ImageMagick_<component>_FOUND - TRUE if <component> is found.
    ImageMagick_<component>_EXECUTABLE - Full path to <component> executable.
    +


    +

    There are also components for the following ImageMagick APIs:

    +
      Magick++
    MagickWand
    MagickCore
    +


    +

    For these components the following variables are set:

    +
      ImageMagick_FOUND                    - TRUE if all components are found.
    ImageMagick_INCLUDE_DIRS - Full paths to all include dirs.
    ImageMagick_LIBRARIES - Full paths to all libraries.
    ImageMagick_<component>_FOUND - TRUE if <component> is found.
    ImageMagick_<component>_INCLUDE_DIRS - Full path to <component> include dirs.
    ImageMagick_<component>_LIBRARIES - Full path to <component> libraries.
    +


    +

    Example Usages:

    +
      FIND_PACKAGE(ImageMagick)
    FIND_PACKAGE(ImageMagick COMPONENTS convert)
    FIND_PACKAGE(ImageMagick COMPONENTS convert mogrify display)
    FIND_PACKAGE(ImageMagick COMPONENTS Magick++)
    FIND_PACKAGE(ImageMagick COMPONENTS Magick++ convert)
    +


    +

    Note that the standard FIND_PACKAGE features are supported (i.e., QUIET, REQUIRED, etc.).

    + +
  • +
  • + FindJNI: Find JNI java libraries.
    +

    This module finds if Java is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
       
    JNI_INCLUDE_DIRS = the include dirs to use
    JNI_LIBRARIES = the libraries to use
    JNI_FOUND = TRUE if JNI headers and libraries were found.
    JAVA_AWT_LIBRARY = the path to the jawt library
    JAVA_JVM_LIBRARY = the path to the jvm library
    JAVA_INCLUDE_PATH = the include path to jni.h
    JAVA_INCLUDE_PATH2 = the include path to jni_md.h
    JAVA_AWT_INCLUDE_PATH = the include path to jawt.h
    +


    + +
  • +
  • + FindJPEG: Find JPEG
    +

    Find the native JPEG includes and library This module defines

    +
      JPEG_INCLUDE_DIR, where to find jpeglib.h, etc.
    JPEG_LIBRARIES, the libraries needed to use JPEG.
    JPEG_FOUND, If false, do not try to use JPEG.
    +

    also defined, but not for general use are

    +
      JPEG_LIBRARY, where to find the JPEG library.
    + +
  • +
  • + FindJasper: Try to find the Jasper JPEG2000 library
    +

    Once done this will define

    +
      JASPER_FOUND - system has Jasper
    JASPER_INCLUDE_DIR - the Jasper include directory
    JASPER_LIBRARIES - The libraries needed to use Jasper
    + +
  • +
  • + FindJava: Find Java
    +

    This module finds if Java is installed and determines where the include files and libraries are. This code sets the following variables:

    +
      Java_JAVA_EXECUTABLE    = the full path to the Java runtime
    Java_JAVAC_EXECUTABLE = the full path to the Java compiler
    Java_JAVAH_EXECUTABLE = the full path to the Java header generator
    Java_JAVADOC_EXECUTABLE = the full path to the Java documention generator
    Java_JAR_EXECUTABLE = the full path to the Java archiver
    Java_VERSION_STRING = Version of the package found (java version), eg. 1.6.0_12
    Java_VERSION_MAJOR = The major version of the package found.
    Java_VERSION_MINOR = The minor version of the package found.
    Java_VERSION_PATCH = The patch version of the package found.
    Java_VERSION_TWEAK = The tweak version of the package found (after '_')
    Java_VERSION = This is set to: $major.$minor.$patch(.$tweak)
    +


    +

    The minimum required version of Java can be specified using the standard CMake syntax, e.g. FIND_PACKAGE(Java 1.5)

    +

    NOTE: ${Java_VERSION} and ${Java_VERSION_STRING} are not guaranteed to be identical. For example some java version may return: Java_VERSION_STRING = 1.5.0_17 and Java_VERSION = 1.5.0.17

    +

    another example is the Java OEM, with: Java_VERSION_STRING = 1.6.0-oem and Java_VERSION = 1.6.0

    +

    For these components the following variables are set:

    +
      Java_FOUND                    - TRUE if all components are found.
    Java_INCLUDE_DIRS - Full paths to all include dirs.
    Java_LIBRARIES - Full paths to all libraries.
    Java_<component>_FOUND - TRUE if <component> is found.
    +


    +

    Example Usages:

    +
      FIND_PACKAGE(Java)
    FIND_PACKAGE(Java COMPONENTS Runtime)
    FIND_PACKAGE(Java COMPONENTS Development)
    +


    + +
  • +
  • + FindKDE3: Find the KDE3 include and library dirs, KDE preprocessors and define a some macros
    +


    +

    This module defines the following variables:

    +
      KDE3_DEFINITIONS         - compiler definitions required for compiling KDE software
    KDE3_INCLUDE_DIR - the KDE include directory
    KDE3_INCLUDE_DIRS - the KDE and the Qt include directory, for use with INCLUDE_DIRECTORIES()
    KDE3_LIB_DIR - the directory where the KDE libraries are installed, for use with LINK_DIRECTORIES()
    QT_AND_KDECORE_LIBS - this contains both the Qt and the kdecore library
    KDE3_DCOPIDL_EXECUTABLE - the dcopidl executable
    KDE3_DCOPIDL2CPP_EXECUTABLE - the dcopidl2cpp executable
    KDE3_KCFGC_EXECUTABLE - the kconfig_compiler executable
    KDE3_FOUND - set to TRUE if all of the above has been found
    +


    +

    The following user adjustable options are provided:

    +
      KDE3_BUILD_TESTS - enable this to build KDE testcases
    +


    +


    +

    It also adds the following macros (from KDE3Macros.cmake) SRCS_VAR is always the variable which contains the list of source files for your application or library.

    +

    KDE3_AUTOMOC(file1 ... fileN)

    +
        Call this if you want to have automatic moc file handling.
    This means if you include "foo.moc" in the source file foo.cpp
    a moc file for the header foo.h will be created automatically.
    You can set the property SKIP_AUTOMAKE using SET_SOURCE_FILES_PROPERTIES()
    to exclude some files in the list from being processed.
    +


    +

    KDE3_ADD_MOC_FILES(SRCS_VAR file1 ... fileN )

    +
        If you don't use the KDE3_AUTOMOC() macro, for the files
    listed here moc files will be created (named "foo.moc.cpp")
    +


    +

    KDE3_ADD_DCOP_SKELS(SRCS_VAR header1.h ... headerN.h )

    +
        Use this to generate DCOP skeletions from the listed headers.
    +


    +

    KDE3_ADD_DCOP_STUBS(SRCS_VAR header1.h ... headerN.h )

    +
         Use this to generate DCOP stubs from the listed headers.
    +


    +

    KDE3_ADD_UI_FILES(SRCS_VAR file1.ui ... fileN.ui )

    +
        Use this to add the Qt designer ui files to your application/library.
    +


    +

    KDE3_ADD_KCFG_FILES(SRCS_VAR file1.kcfgc ... fileN.kcfgc )

    +
        Use this to add KDE kconfig compiler files to your application/library.
    +


    +

    KDE3_INSTALL_LIBTOOL_FILE(target)

    +
        This will create and install a simple libtool file for the given target.
    +


    +

    KDE3_ADD_EXECUTABLE(name file1 ... fileN )

    +
        Currently identical to ADD_EXECUTABLE(), may provide some advanced features in the future.
    +


    +

    KDE3_ADD_KPART(name [WITH_PREFIX] file1 ... fileN )

    +
        Create a KDE plugin (KPart, kioslave, etc.) from the given source files.
    If WITH_PREFIX is given, the resulting plugin will have the prefix "lib", otherwise it won't.
    It creates and installs an appropriate libtool la-file.
    +


    +

    KDE3_ADD_KDEINIT_EXECUTABLE(name file1 ... fileN )

    +
        Create a KDE application in the form of a module loadable via kdeinit.
    A library named kdeinit_<name> will be created and a small executable which links to it.
    +


    +

    The option KDE3_ENABLE_FINAL to enable all-in-one compilation is no longer supported.

    +


    +

    Author: Alexander Neundorf <neundorf@kde.org>

    + +
  • +
  • + FindKDE4:
    +

    Find KDE4 and provide all necessary variables and macros to compile software for it. It looks for KDE 4 in the following directories in the given order:

    +
      CMAKE_INSTALL_PREFIX
    KDEDIRS
    /opt/kde4
    +


    +

    Please look in FindKDE4Internal.cmake and KDE4Macros.cmake for more information. They are installed with the KDE 4 libraries in $KDEDIRS/share/apps/cmake/modules/.

    +

    Author: Alexander Neundorf <neundorf@kde.org>

    + +
  • +
  • + FindLAPACK: Find LAPACK library
    +

    This module finds an installed fortran library that implements the LAPACK linear-algebra interface (see http://www.netlib.org/lapack/).

    +

    The approach follows that taken for the autoconf macro file, acx_lapack.m4 (distributed at http://ac-archive.sourceforge.net/ac-archive/acx_lapack.html).

    +

    This module sets the following variables:

    +
      LAPACK_FOUND - set to true if a library implementing the LAPACK interface
    is found
    LAPACK_LINKER_FLAGS - uncached list of required linker flags (excluding -l
    and -L).
    LAPACK_LIBRARIES - uncached list of libraries (using full path name) to
    link against to use LAPACK
    LAPACK95_LIBRARIES - uncached list of libraries (using full path name) to
    link against to use LAPACK95
    LAPACK95_FOUND - set to true if a library implementing the LAPACK f95
    interface is found
    BLA_STATIC if set on this determines what kind of linkage we do (static)
    BLA_VENDOR if set checks only the specified vendor, if not set checks
    all the possibilities
    BLA_F95 if set on tries to find the f95 interfaces for BLAS/LAPACK
    +

    ## List of vendors (BLA_VENDOR) valid in this module # Intel(mkl), ACML,Apple, NAS, Generic

    + +
  • +
  • + FindLATEX: Find Latex
    +

    This module finds if Latex is installed and determines where the executables are. This code sets the following variables:

    +
      
    LATEX_COMPILER: path to the LaTeX compiler
    PDFLATEX_COMPILER: path to the PdfLaTeX compiler
    BIBTEX_COMPILER: path to the BibTeX compiler
    MAKEINDEX_COMPILER: path to the MakeIndex compiler
    DVIPS_CONVERTER: path to the DVIPS converter
    PS2PDF_CONVERTER: path to the PS2PDF converter
    LATEX2HTML_CONVERTER: path to the LaTeX2Html converter
    +


    + +
  • +
  • + FindLibArchive: Find libarchive library and headers
    +

    The module defines the following variables:

    +
      LibArchive_FOUND        - true if libarchive was found
    LibArchive_INCLUDE_DIRS - include search path
    LibArchive_LIBRARIES - libraries to link
    LibArchive_VERSION - libarchive 3-component version number
    + +
  • +
  • + FindLibXml2: Try to find the LibXml2 xml processing library
    +

    Once done this will define

    +
      LIBXML2_FOUND - System has LibXml2
    LIBXML2_INCLUDE_DIR - The LibXml2 include directory
    LIBXML2_LIBRARIES - The libraries needed to use LibXml2
    LIBXML2_DEFINITIONS - Compiler switches required for using LibXml2
    LIBXML2_XMLLINT_EXECUTABLE - The XML checking tool xmllint coming with LibXml2
    + +
  • +
  • + FindLibXslt: Try to find the LibXslt library
    +

    Once done this will define

    +
      LIBXSLT_FOUND - system has LibXslt
    LIBXSLT_INCLUDE_DIR - the LibXslt include directory
    LIBXSLT_LIBRARIES - Link these to LibXslt
    LIBXSLT_DEFINITIONS - Compiler switches required for using LibXslt
    +

    Additionally, the following two variables are set (but not required for using xslt):

    +
      LIBXSLT_EXSLT_LIBRARIES - Link to these if you need to link against the exslt library
    LIBXSLT_XSLTPROC_EXECUTABLE - Contains the full path to the xsltproc executable if found
    + +
  • +
  • + FindLua50:
    +

    Locate Lua library This module defines

    +
      LUA50_FOUND, if false, do not try to link to Lua 
    LUA_LIBRARIES, both lua and lualib
    LUA_INCLUDE_DIR, where to find lua.h and lualib.h (and probably lauxlib.h)
    +


    +

    Note that the expected include convention is

    +
      #include "lua.h"
    +

    and not

    +
      #include <lua/lua.h>
    +

    This is because, the lua location is not standardized and may exist in locations other than lua/

    + +
  • +
  • + FindLua51:
    +

    Locate Lua library This module defines

    +
      LUA51_FOUND, if false, do not try to link to Lua 
    LUA_LIBRARIES
    LUA_INCLUDE_DIR, where to find lua.h
    +


    +

    Note that the expected include convention is

    +
      #include "lua.h"
    +

    and not

    +
      #include <lua/lua.h>
    +

    This is because, the lua location is not standardized and may exist in locations other than lua/

    + +
  • +
  • + FindMFC: Find MFC on Windows
    +

    Find the native MFC - i.e. decide if an application can link to the MFC libraries.

    +
      MFC_FOUND - Was MFC support found
    +

    You don't need to include anything or link anything to use it.

    + +
  • +
  • + FindMPEG: Find the native MPEG includes and library
    +

    This module defines

    +
      MPEG_INCLUDE_DIR, where to find MPEG.h, etc.
    MPEG_LIBRARIES, the libraries required to use MPEG.
    MPEG_FOUND, If false, do not try to use MPEG.
    +

    also defined, but not for general use are

    +
      MPEG_mpeg2_LIBRARY, where to find the MPEG library.
    MPEG_vo_LIBRARY, where to find the vo library.
    + +
  • +
  • + FindMPEG2: Find the native MPEG2 includes and library
    +

    This module defines

    +
      MPEG2_INCLUDE_DIR, path to mpeg2dec/mpeg2.h, etc.
    MPEG2_LIBRARIES, the libraries required to use MPEG2.
    MPEG2_FOUND, If false, do not try to use MPEG2.
    +

    also defined, but not for general use are

    +
      MPEG2_mpeg2_LIBRARY, where to find the MPEG2 library.
    MPEG2_vo_LIBRARY, where to find the vo library.
    + +
  • +
  • + FindMPI: Find a Message Passing Interface (MPI) implementation
    +

    The Message Passing Interface (MPI) is a library used to write high-performance distributed-memory parallel applications, and is typically deployed on a cluster. MPI is a standard interface (defined by the MPI forum) for which many implementations are available. All of them have somewhat different include paths, libraries to link against, etc., and this module tries to smooth out those differences.

    +

    === Variables ===

    +

    This module will set the following variables per language in your project, where <lang> is one of C, CXX, or Fortran:

    +
       MPI_<lang>_FOUND           TRUE if FindMPI found MPI flags for <lang>
    MPI_<lang>_COMPILER MPI Compiler wrapper for <lang>
    MPI_<lang>_COMPILE_FLAGS Compilation flags for MPI programs
    MPI_<lang>_INCLUDE_PATH Include path(s) for MPI header
    MPI_<lang>_LINK_FLAGS Linking flags for MPI programs
    MPI_<lang>_LIBRARIES All libraries to link MPI programs against
    +

    Additionally, FindMPI sets the following variables for running MPI programs from the command line:

    +
       MPIEXEC                    Executable for running MPI programs
    MPIEXEC_NUMPROC_FLAG Flag to pass to MPIEXEC before giving
    it the number of processors to run on
    MPIEXEC_PREFLAGS Flags to pass to MPIEXEC directly
    before the executable to run.
    MPIEXEC_POSTFLAGS Flags to pass to MPIEXEC after other flags
    +

    === Usage ===

    +

    To use this module, simply call FindMPI from a CMakeLists.txt file, or run find_package(MPI), then run CMake. If you are happy with the auto- detected configuration for your language, then you're done. If not, you have two options:

    +
       1. Set MPI_<lang>_COMPILER to the MPI wrapper (mpicc, etc.) of your
    choice and reconfigure. FindMPI will attempt to determine all the
    necessary variables using THAT compiler's compile and link flags.
    2. If this fails, or if your MPI implementation does not come with
    a compiler wrapper, then set both MPI_<lang>_LIBRARIES and
    MPI_<lang>_INCLUDE_PATH. You may also set any other variables
    listed above, but these two are required. This will circumvent
    autodetection entirely.
    +

    When configuration is successful, MPI_<lang>_COMPILER will be set to the compiler wrapper for <lang>, if it was found. MPI_<lang>_FOUND and other variables above will be set if any MPI implementation was found for <lang>, regardless of whether a compiler was found.

    +

    When using MPIEXEC to execute MPI applications, you should typically use all of the MPIEXEC flags as follows:

    +
       ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} PROCS
    ${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS
    +

    where PROCS is the number of processors on which to execute the program, EXECUTABLE is the MPI program, and ARGS are the arguments to pass to the MPI program.

    +

    === Backward Compatibility ===

    +

    For backward compatibility with older versions of FindMPI, these variables are set, but deprecated:

    +
       MPI_FOUND           MPI_COMPILER        MPI_LIBRARY
    MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_EXTRA_LIBRARY
    MPI_LINK_FLAGS MPI_LIBRARIES
    +

    In new projects, please use the MPI_<lang>_XXX equivalents.

    + +
  • +
  • + FindMatlab: this module looks for Matlab
    +

    Defines:

    +
      MATLAB_INCLUDE_DIR: include path for mex.h, engine.h
    MATLAB_LIBRARIES: required libraries: libmex, etc
    MATLAB_MEX_LIBRARY: path to libmex.lib
    MATLAB_MX_LIBRARY: path to libmx.lib
    MATLAB_ENG_LIBRARY: path to libeng.lib
    + +
  • +
  • + FindMotif: Try to find Motif (or lesstif)
    +

    Once done this will define:

    +
      MOTIF_FOUND        - system has MOTIF
    MOTIF_INCLUDE_DIR - include paths to use Motif
    MOTIF_LIBRARIES - Link these to use Motif
    + +
  • +
  • + FindOpenAL:
    +

    Locate OpenAL This module defines OPENAL_LIBRARY OPENAL_FOUND, if false, do not try to link to OpenAL OPENAL_INCLUDE_DIR, where to find the headers

    +

    $OPENALDIR is an environment variable that would correspond to the ./configure --prefix=$OPENALDIR used in building OpenAL.

    +

    Created by Eric Wing. This was influenced by the FindSDL.cmake module.

    + +
  • +
  • + FindOpenGL: Try to find OpenGL
    +

    Once done this will define

    +
      
    OPENGL_FOUND - system has OpenGL
    OPENGL_XMESA_FOUND - system has XMESA
    OPENGL_GLU_FOUND - system has GLU
    OPENGL_INCLUDE_DIR - the GL include directory
    OPENGL_LIBRARIES - Link these to use OpenGL and GLU

    +

    If you want to use just GL you can use these values

    +
      OPENGL_gl_LIBRARY   - Path to OpenGL Library
    OPENGL_glu_LIBRARY - Path to GLU Library

    +

    On OSX default to using the framework version of opengl People will have to change the cache values of OPENGL_glu_LIBRARY and OPENGL_gl_LIBRARY to use OpenGL with X11 on OSX

    + +
  • +
  • + FindOpenMP: Finds OpenMP support
    +

    This module can be used to detect OpenMP support in a compiler. If the compiler supports OpenMP, the flags required to compile with openmp support are set.

    +

    The following variables are set:

    +
       OpenMP_C_FLAGS - flags to add to the C compiler for OpenMP support
    OpenMP_CXX_FLAGS - flags to add to the CXX compiler for OpenMP support
    OPENMP_FOUND - true if openmp is detected
    +


    +

    Supported compilers can be found at http://openmp.org/wp/openmp-compilers/

    + +
  • +
  • + FindOpenSSL: Try to find the OpenSSL encryption library
    +

    Once done this will define

    +
      OPENSSL_ROOT_DIR - Set this variable to the root installation of OpenSSL
    +


    +

    Read-Only variables:

    +
      OPENSSL_FOUND - system has the OpenSSL library
    OPENSSL_INCLUDE_DIR - the OpenSSL include directory
    OPENSSL_LIBRARIES - The libraries needed to use OpenSSL
    OPENSSL_VERSION - This is set to $major.$minor.$revision (eg. 0.9.8)
    + +
  • +
  • + FindOpenSceneGraph: Find OpenSceneGraph
    +

    This module searches for the OpenSceneGraph core "osg" library as well as OpenThreads, and whatever additional COMPONENTS (nodekits) that you specify.

    +
        See http://www.openscenegraph.org
    +


    +

    NOTE: To use this module effectively you must either require CMake >= 2.6.3 with cmake_minimum_required(VERSION 2.6.3) or download and place FindOpenThreads.cmake, Findosg_functions.cmake, Findosg.cmake, and Find<etc>.cmake files into your CMAKE_MODULE_PATH.

    +

    ==================================

    +

    This module accepts the following variables (note mixed case)

    +
        OpenSceneGraph_DEBUG - Enable debugging output
    +


    +
        OpenSceneGraph_MARK_AS_ADVANCED - Mark cache variables as advanced 
    automatically
    +


    +

    The following environment variables are also respected for finding the OSG and it's various components. CMAKE_PREFIX_PATH can also be used for this (see find_library() CMake documentation).

    +
        <MODULE>_DIR (where MODULE is of the form "OSGVOLUME" and there is a FindosgVolume.cmake file)
    OSG_DIR
    OSGDIR
    OSG_ROOT
    +


    +

    This module defines the following output variables:

    +
        OPENSCENEGRAPH_FOUND - Was the OSG and all of the specified components found?
    +


    +
        OPENSCENEGRAPH_VERSION - The version of the OSG which was found
    +


    +
        OPENSCENEGRAPH_INCLUDE_DIRS - Where to find the headers
    +


    +
        OPENSCENEGRAPH_LIBRARIES - The OSG libraries
    +


    +

    ================================== Example Usage:

    +
      find_package(OpenSceneGraph 2.0.0 REQUIRED osgDB osgUtil)
    # libOpenThreads & libosg automatically searched
    include_directories(${OPENSCENEGRAPH_INCLUDE_DIRS})
    +


    +
      add_executable(foo foo.cc)
    target_link_libraries(foo ${OPENSCENEGRAPH_LIBRARIES})
    +


    + +
  • +
  • + FindOpenThreads:
    +

    OpenThreads is a C++ based threading library. Its largest userbase seems to OpenSceneGraph so you might notice I accept OSGDIR as an environment path. I consider this part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module.

    +

    Locate OpenThreads This module defines OPENTHREADS_LIBRARY OPENTHREADS_FOUND, if false, do not try to link to OpenThreads OPENTHREADS_INCLUDE_DIR, where to find the headers

    +

    $OPENTHREADS_DIR is an environment variable that would correspond to the ./configure --prefix=$OPENTHREADS_DIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindPHP4: Find PHP4
    +

    This module finds if PHP4 is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      PHP4_INCLUDE_PATH       = path to where php.h can be found
    PHP4_EXECUTABLE = full path to the php4 binary
    +


    + +
  • +
  • + FindPNG: Find the native PNG includes and library
    +


    +

    This module searches libpng, the library for working with PNG images.

    +

    It defines the following variables

    +
      PNG_INCLUDE_DIRS, where to find png.h, etc.
    PNG_LIBRARIES, the libraries to link against to use PNG.
    PNG_DEFINITIONS - You should add_definitons(${PNG_DEFINITIONS}) before compiling code that includes png library files.
    PNG_FOUND, If false, do not try to use PNG.
    +

    Also defined, but not for general use are

    +
      PNG_LIBRARY, where to find the PNG library.
    +

    For backward compatiblity the variable PNG_INCLUDE_DIR is also set. It has the same value as PNG_INCLUDE_DIRS.

    +

    Since PNG depends on the ZLib compression library, none of the above will be defined unless ZLib can be found.

    + +
  • +
  • + FindPackageHandleStandardArgs:
    +

    FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name> ... )

    +

    This function is intended to be used in FindXXX.cmake modules files. It handles the REQUIRED, QUIET and version-related arguments to FIND_PACKAGE(). It also sets the <UPPERCASED_NAME>_FOUND variable. The package is considered found if all variables <var1>... listed contain valid results, e.g. valid filepaths.

    +

    There are two modes of this function. The first argument in both modes is the name of the Find-module where it is called (in original casing).

    +

    The first simple mode looks like this:

    +
        FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name> (DEFAULT_MSG|"Custom failure message") <var1>...<varN> )
    +

    If the variables <var1> to <varN> are all valid, then <UPPERCASED_NAME>_FOUND will be set to TRUE. If DEFAULT_MSG is given as second argument, then the function will generate itself useful success and error messages. You can also supply a custom error message for the failure case. This is not recommended.

    +

    The second mode is more powerful and also supports version checking:

    +
        FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME [REQUIRED_VARS <var1>...<varN>]
    [VERSION_VAR <versionvar>
    [CONFIG_MODE]
    [FAIL_MESSAGE "Custom failure message"] )
    +


    +

    As above, if <var1> through <varN> are all valid, <UPPERCASED_NAME>_FOUND will be set to TRUE. After REQUIRED_VARS the variables which are required for this package are listed. Following VERSION_VAR the name of the variable can be specified which holds the version of the package which has been found. If this is done, this version will be checked against the (potentially) specified required version used in the find_package() call. The EXACT keyword is also handled. The default messages include information about the required version and the version which has been actually found, both if the version is ok or not. Use the option CONFIG_MODE if your FindXXX.cmake module is a wrapper for a find_package(... NO_MODULE) call, in this case all the information provided by the config-mode of find_package() will be evaluated automatically. Via FAIL_MESSAGE a custom failure message can be specified, if this is not used, the default message will be displayed.

    +

    Example for mode 1:

    +
        FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2  DEFAULT_MSG  LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
    +


    +

    LibXml2 is considered to be found, if both LIBXML2_LIBRARY and LIBXML2_INCLUDE_DIR are valid. Then also LIBXML2_FOUND is set to TRUE. If it is not found and REQUIRED was used, it fails with FATAL_ERROR, independent whether QUIET was used or not. If it is found, success will be reported, including the content of <var1>. On repeated Cmake runs, the same message won't be printed again.

    +

    Example for mode 2:

    +
        FIND_PACKAGE_HANDLE_STANDARD_ARGS(BISON  REQUIRED_VARS BISON_EXECUTABLE
    VERSION_VAR BISON_VERSION)
    +

    In this case, BISON is considered to be found if the variable(s) listed after REQUIRED_VAR are all valid, i.e. BISON_EXECUTABLE in this case. Also the version of BISON will be checked by using the version contained in BISON_VERSION. Since no FAIL_MESSAGE is given, the default messages will be printed.

    +

    Another example for mode 2:

    +
        FIND_PACKAGE(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
    FIND_PACKAGE_HANDLE_STANDARD_ARGS(Automoc4 CONFIG_MODE)
    +

    In this case, FindAutmoc4.cmake wraps a call to FIND_PACKAGE(Automoc4 NO_MODULE) and adds an additional search directory for automoc4. The following FIND_PACKAGE_HANDLE_STANDARD_ARGS() call produces a proper success/error message.

    + +
  • +
  • + FindPackageMessage:
    +

    FIND_PACKAGE_MESSAGE(<name> "message for user" "find result details")

    +

    This macro is intended to be used in FindXXX.cmake modules files. It will print a message once for each unique find result. This is useful for telling the user where a package was found. The first argument specifies the name (XXX) of the package. The second argument specifies the message to display. The third argument lists details about the find result so that if they change the message will be displayed again. The macro also obeys the QUIET argument to the find_package command.

    +

    Example:

    +
      IF(X11_FOUND)
    FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}"
    "[${X11_X11_LIB}][${X11_INCLUDE_DIR}]")
    ELSE(X11_FOUND)
    ...
    ENDIF(X11_FOUND)
    + +
  • +
  • + FindPerl: Find perl
    +

    this module looks for Perl

    +
      PERL_EXECUTABLE - the full path to perl
    PERL_FOUND - If false, don't attempt to use perl.
    + +
  • +
  • + FindPerlLibs: Find Perl libraries
    +

    This module finds if PERL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      PERLLIBS_FOUND    = True if perl.h & libperl were found
    PERL_INCLUDE_PATH = path to where perl.h is found
    PERL_LIBRARY = path to libperl
    PERL_EXECUTABLE = full path to the perl binary
    +


    +

    The minimum required version of Perl can be specified using the standard syntax, e.g. FIND_PACKAGE(PerlLibs 6.0)

    +
      The following variables are also available if needed
    (introduced after CMake 2.6.4)
    +


    +
      PERL_SITESEARCH    = path to the sitesearch install dir
    PERL_SITELIB = path to the sitelib install directory
    PERL_VENDORARCH = path to the vendor arch install directory
    PERL_VENDORLIB = path to the vendor lib install directory
    PERL_ARCHLIB = path to the arch lib install directory
    PERL_PRIVLIB = path to the priv lib install directory
    PERL_EXTRA_C_FLAGS = Compilation flags used to build perl
    +


    + +
  • +
  • + FindPhysFS:
    +

    Locate PhysFS library This module defines PHYSFS_LIBRARY, the name of the library to link against PHYSFS_FOUND, if false, do not try to link to PHYSFS PHYSFS_INCLUDE_DIR, where to find physfs.h

    +

    $PHYSFSDIR is an environment variable that would correspond to the ./configure --prefix=$PHYSFSDIR used in building PHYSFS.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindPike: Find Pike
    +

    This module finds if PIKE is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      PIKE_INCLUDE_PATH       = path to where program.h is found
    PIKE_EXECUTABLE = full path to the pike binary
    +


    + +
  • +
  • + FindPkgConfig: a pkg-config module for CMake
    +


    +

    Usage:

    +
       pkg_check_modules(<PREFIX> [REQUIRED] [QUIET] <MODULE> [<MODULE>]*)
    checks for all the given modules
    +


    +
       pkg_search_module(<PREFIX> [REQUIRED] [QUIET] <MODULE> [<MODULE>]*)
    checks for given modules and uses the first working one
    +


    +

    When the 'REQUIRED' argument was set, macros will fail with an error when module(s) could not be found

    +

    When the 'QUIET' argument is set, no status messages will be printed.

    +

    It sets the following variables:

    +
       PKG_CONFIG_FOUND         ... true if pkg-config works on the system
    PKG_CONFIG_EXECUTABLE ... pathname of the pkg-config program
    <PREFIX>_FOUND ... set to 1 if module(s) exist
    +


    +

    For the following variables two sets of values exist; first one is the common one and has the given PREFIX. The second set contains flags which are given out when pkgconfig was called with the '--static' option.

    +
       <XPREFIX>_LIBRARIES      ... only the libraries (w/o the '-l')
    <XPREFIX>_LIBRARY_DIRS ... the paths of the libraries (w/o the '-L')
    <XPREFIX>_LDFLAGS ... all required linker flags
    <XPREFIX>_LDFLAGS_OTHER ... all other linker flags
    <XPREFIX>_INCLUDE_DIRS ... the '-I' preprocessor flags (w/o the '-I')
    <XPREFIX>_CFLAGS ... all required cflags
    <XPREFIX>_CFLAGS_OTHER ... the other compiler flags
    +


    +
       <XPREFIX> = <PREFIX>        for common case
    <XPREFIX> = <PREFIX>_STATIC for static linking
    +


    +

    There are some special variables whose prefix depends on the count of given modules. When there is only one module, <PREFIX> stays unchanged. When there are multiple modules, the prefix will be changed to <PREFIX>_<MODNAME>:

    +
       <XPREFIX>_VERSION    ... version of the module
    <XPREFIX>_PREFIX ... prefix-directory of the module
    <XPREFIX>_INCLUDEDIR ... include-dir of the module
    <XPREFIX>_LIBDIR ... lib-dir of the module
    +


    +
       <XPREFIX> = <PREFIX>  when |MODULES| == 1, else
    <XPREFIX> = <PREFIX>_<MODNAME>
    +


    +

    A <MODULE> parameter can have the following formats:

    +
       {MODNAME}            ... matches any version
    {MODNAME}>={VERSION} ... at least version <VERSION> is required
    {MODNAME}={VERSION} ... exactly version <VERSION> is required
    {MODNAME}<={VERSION} ... modules must not be newer than <VERSION>
    +


    +

    Examples

    +
       pkg_check_modules (GLIB2   glib-2.0)
    +


    +
       pkg_check_modules (GLIB2   glib-2.0>=2.10)
    requires at least version 2.10 of glib2 and defines e.g.
    GLIB2_VERSION=2.10.3
    +


    +
       pkg_check_modules (FOO     glib-2.0>=2.10 gtk+-2.0)
    requires both glib2 and gtk2, and defines e.g.
    FOO_glib-2.0_VERSION=2.10.3
    FOO_gtk+-2.0_VERSION=2.8.20
    +


    +
       pkg_check_modules (XRENDER REQUIRED xrender)
    defines e.g.:
    XRENDER_LIBRARIES=Xrender;X11
    XRENDER_STATIC_LIBRARIES=Xrender;X11;pthread;Xau;Xdmcp
    +


    +
       pkg_search_module (BAR     libxml-2.0 libxml2 libxml>=2)
    + +
  • +
  • + FindPostgreSQL: Find the PostgreSQL installation.
    +

    Usage: In your CMakeLists.txt file do something like this: ... # PostgreSQL FIND_PACKAGE(PostgreSQL) ... if( PostgreSQL_FOUND )

    +
       include_directories(${PostgreSQL_INCLUDE_DIRS})
    +

    endif( PostgreSQL_FOUND ) ... Remember to include ${PostgreSQL_LIBRARIES} in the target_link_libraries() statement.

    +


    +

    In Windows, we make the assumption that, if the PostgreSQL files are installed, the default directory will be C:\Program Files\PostgreSQL.

    + +
  • +
  • + FindProducer:
    +

    Though Producer isn't directly part of OpenSceneGraph, its primary user is OSG so I consider this part of the Findosg* suite used to find OpenSceneGraph components. You'll notice that I accept OSGDIR as an environment path.

    +

    Each component is separate and you must opt in to each module. You must also opt into OpenGL (and OpenThreads?) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate Producer This module defines PRODUCER_LIBRARY PRODUCER_FOUND, if false, do not try to link to Producer PRODUCER_INCLUDE_DIR, where to find the headers

    +

    $PRODUCER_DIR is an environment variable that would correspond to the ./configure --prefix=$PRODUCER_DIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindProtobuf:
    +

    Locate and configure the Google Protocol Buffers library.

    +

    The following variables can be set and are optional:

    +
       PROTOBUF_SRC_ROOT_FOLDER - When compiling with MSVC, if this cache variable is set
    the protobuf-default VS project build locations
    (vsprojects/Debug & vsprojects/Release) will be searched
    for libraries and binaries.
    +


    +

    Defines the following variables:

    +
       PROTOBUF_FOUND - Found the Google Protocol Buffers library (libprotobuf & header files)
    PROTOBUF_INCLUDE_DIRS - Include directories for Google Protocol Buffers
    PROTOBUF_LIBRARIES - The protobuf libraries
    +

    [New in CMake 2.8.5]

    +
       PROTOBUF_PROTOC_LIBRARIES - The protoc libraries
    PROTOBUF_LITE_LIBRARIES - The protobuf-lite libraries
    +


    +

    The following cache variables are also available to set or use:

    +
       PROTOBUF_LIBRARY - The protobuf library
    PROTOBUF_PROTOC_LIBRARY - The protoc library
    PROTOBUF_INCLUDE_DIR - The include directory for protocol buffers
    PROTOBUF_PROTOC_EXECUTABLE - The protoc compiler
    +

    [New in CMake 2.8.5]

    +
       PROTOBUF_LIBRARY_DEBUG - The protobuf library (debug)
    PROTOBUF_PROTOC_LIBRARY_DEBUG - The protoc library (debug)
    PROTOBUF_LITE_LIBRARY - The protobuf lite library
    PROTOBUF_LITE_LIBRARY_DEBUG - The protobuf lite library (debug)
    +


    +
      ====================================================================
    Example:
    +


    +
       find_package(Protobuf REQUIRED)
    include_directories(${PROTOBUF_INCLUDE_DIRS})
    +


    +
       include_directories(${CMAKE_CURRENT_BINARY_DIR})
    PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS foo.proto)
    add_executable(bar bar.cc ${PROTO_SRCS} ${PROTO_HDRS})
    target_link_libraries(bar ${PROTOBUF_LIBRARIES})
    +


    +

    NOTE: You may need to link against pthreads, depending

    +
           on the platform.
    +


    +

    NOTE: The PROTOBUF_GENERATE_CPP macro & add_executable() or add_library()

    +
           calls only work properly within the same directory.
    +


    +
      ====================================================================
    +


    +

    PROTOBUF_GENERATE_CPP (public function)

    +
       SRCS = Variable to define with autogenerated
    source files
    HDRS = Variable to define with autogenerated
    header files
    ARGN = proto files
    +


    +
      ====================================================================
    + +
  • +
  • + FindPythonInterp: Find python interpreter
    +

    This module finds if Python interpreter is installed and determines where the executables are. This code sets the following variables:

    +
      PYTHONINTERP_FOUND         - Was the Python executable found
    PYTHON_EXECUTABLE - path to the Python interpreter
    +


    +
      PYTHON_VERSION_STRING      - Python version found e.g. 2.5.2
    PYTHON_VERSION_MAJOR - Python major version found e.g. 2
    PYTHON_VERSION_MINOR - Python minor version found e.g. 5
    PYTHON_VERSION_PATCH - Python patch version found e.g. 2
    +


    +
      Python_ADDITIONAL_VERSIONS - list of additional Python versions to search for
    + +
  • +
  • + FindPythonLibs: Find python libraries
    +

    This module finds if Python is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      PYTHONLIBS_FOUND           - have the Python libs been found
    PYTHON_LIBRARIES - path to the python library
    PYTHON_INCLUDE_PATH - path to where Python.h is found (deprecated)
    PYTHON_INCLUDE_DIRS - path to where Python.h is found
    PYTHON_DEBUG_LIBRARIES - path to the debug library
    Python_ADDITIONAL_VERSIONS - list of additional Python versions to search for
    + +
  • +
  • + FindQt: Searches for all installed versions of QT.
    +

    This should only be used if your project can work with multiple versions of QT. If not, you should just directly use FindQt4 or FindQt3. If multiple versions of QT are found on the machine, then The user must set the option DESIRED_QT_VERSION to the version they want to use. If only one version of qt is found on the machine, then the DESIRED_QT_VERSION is set to that version and the matching FindQt3 or FindQt4 module is included. Once the user sets DESIRED_QT_VERSION, then the FindQt3 or FindQt4 module is included.

    +
      QT_REQUIRED if this is set to TRUE then if CMake can 
    not find QT4 or QT3 an error is raised
    and a message is sent to the user.
    +


    +
      DESIRED_QT_VERSION OPTION is created
    QT4_INSTALLED is set to TRUE if qt4 is found.
    QT3_INSTALLED is set to TRUE if qt3 is found.
    + +
  • +
  • + FindQt3: Locate Qt include paths and libraries
    +

    This module defines:

    +
      QT_INCLUDE_DIR - where to find qt.h, etc.
    QT_LIBRARIES - the libraries to link against to use Qt.
    QT_DEFINITIONS - definitions to use when
    compiling code that uses Qt.
    QT_FOUND - If false, don't try to use Qt.
    +


    +

    If you need the multithreaded version of Qt, set QT_MT_REQUIRED to TRUE

    +

    Also defined, but not for general use are:

    +
      QT_MOC_EXECUTABLE, where to find the moc tool.
    QT_UIC_EXECUTABLE, where to find the uic tool.
    QT_QT_LIBRARY, where to find the Qt library.
    QT_QTMAIN_LIBRARY, where to find the qtmain
    library. This is only required by Qt3 on Windows.
    + +
  • +
  • + FindQt4: Find QT 4
    +

    This module can be used to find Qt4. The most important issue is that the Qt4 qmake is available via the system path. This qmake is then used to detect basically everything else. This module defines a number of key variables and macros. The variable QT_USE_FILE is set which is the path to a CMake file that can be included to compile Qt 4 applications and libraries. It sets up the compilation environment for include directories, preprocessor defines and populates a QT_LIBRARIES variable.

    +

    Typical usage could be something like:

    +
       find_package(Qt4 4.4.3 REQUIRED QtCore QtGui QtXml)
    include(${QT_USE_FILE})
    add_executable(myexe main.cpp)
    target_link_libraries(myexe ${QT_LIBRARIES})
    +


    +

    The minimum required version can be specified using the standard find_package()-syntax (see example above). For compatibility with older versions of FindQt4.cmake it is also possible to set the variable QT_MIN_VERSION to the minimum required version of Qt4 before the find_package(Qt4) command. If both are used, the version used in the find_package() command overrides the one from QT_MIN_VERSION.

    +

    When using the components argument, QT_USE_QT* variables are automatically set for the QT_USE_FILE to pick up. If one wishes to manually set them, the available ones to set include:

    +
                        QT_DONT_USE_QTCORE
    QT_DONT_USE_QTGUI
    QT_USE_QT3SUPPORT
    QT_USE_QTASSISTANT
    QT_USE_QAXCONTAINER
    QT_USE_QAXSERVER
    QT_USE_QTDESIGNER
    QT_USE_QTMOTIF
    QT_USE_QTMAIN
    QT_USE_QTMULTIMEDIA
    QT_USE_QTNETWORK
    QT_USE_QTNSPLUGIN
    QT_USE_QTOPENGL
    QT_USE_QTSQL
    QT_USE_QTXML
    QT_USE_QTSVG
    QT_USE_QTTEST
    QT_USE_QTUITOOLS
    QT_USE_QTDBUS
    QT_USE_QTSCRIPT
    QT_USE_QTASSISTANTCLIENT
    QT_USE_QTHELP
    QT_USE_QTWEBKIT
    QT_USE_QTXMLPATTERNS
    QT_USE_PHONON
    QT_USE_QTSCRIPTTOOLS
    QT_USE_QTDECLARATIVE
    +


    +
      QT_USE_IMPORTED_TARGETS 
    If this variable is set to TRUE, FindQt4.cmake will create imported
    library targets for the various Qt libraries and set the
    library variables like QT_QTCORE_LIBRARY to point at these imported
    targets instead of the library file on disk. This provides much better
    handling of the release and debug versions of the Qt libraries and is
    also always backwards compatible, except for the case that dependencies
    of libraries are exported, these will then also list the names of the
    imported targets as dependency and not the file location on disk. This
    is much more flexible, but requires that FindQt4.cmake is executed before
    such an exported dependency file is processed.
    +


    +

    There are also some files that need processing by some Qt tools such as moc and uic. Listed below are macros that may be used to process those files.

    +
      
    macro QT4_WRAP_CPP(outfiles inputfile ... OPTIONS ...)
    create moc code from a list of files containing Qt class with
    the Q_OBJECT declaration. Per-direcotry preprocessor definitions
    are also added. Options may be given to moc, such as those found
    when executing "moc -help".
    +


    +
      macro QT4_WRAP_UI(outfiles inputfile ... OPTIONS ...)
    create code from a list of Qt designer ui files.
    Options may be given to uic, such as those found
    when executing "uic -help"
    +


    +
      macro QT4_ADD_RESOURCES(outfiles inputfile ... OPTIONS ...)
    create code from a list of Qt resource files.
    Options may be given to rcc, such as those found
    when executing "rcc -help"
    +


    +
      macro QT4_GENERATE_MOC(inputfile outputfile )
    creates a rule to run moc on infile and create outfile.
    Use this if for some reason QT4_WRAP_CPP() isn't appropriate, e.g.
    because you need a custom filename for the moc file or something similar.
    +


    +
      macro QT4_AUTOMOC(sourcefile1 sourcefile2 ... )
    This macro is still experimental.
    It can be used to have moc automatically handled.
    So if you have the files foo.h and foo.cpp, and in foo.h a
    a class uses the Q_OBJECT macro, moc has to run on it. If you don't
    want to use QT4_WRAP_CPP() (which is reliable and mature), you can insert
    #include "foo.moc"
    in foo.cpp and then give foo.cpp as argument to QT4_AUTOMOC(). This will the
    scan all listed files at cmake-time for such included moc files and if it finds
    them cause a rule to be generated to run moc at build time on the
    accompanying header file foo.h.
    If a source file has the SKIP_AUTOMOC property set it will be ignored by this macro.
    +


    +
      macro QT4_ADD_DBUS_INTERFACE(outfiles interface basename)
    create a the interface header and implementation files with the
    given basename from the given interface xml file and add it to
    the list of sources
    +


    +
      macro QT4_ADD_DBUS_INTERFACES(outfiles inputfile ... )
    create the interface header and implementation files
    for all listed interface xml files
    the name will be automatically determined from the name of the xml file
    +


    +
      macro QT4_ADD_DBUS_ADAPTOR(outfiles xmlfile parentheader parentclassname [basename] [classname])
    create a dbus adaptor (header and implementation file) from the xml file
    describing the interface, and add it to the list of sources. The adaptor
    forwards the calls to a parent class, defined in parentheader and named
    parentclassname. The name of the generated files will be
    <basename>adaptor.{cpp,h} where basename defaults to the basename of the xml file.
    If <classname> is provided, then it will be used as the classname of the
    adaptor itself.
    +


    +
      macro QT4_GENERATE_DBUS_INTERFACE( header [interfacename] OPTIONS ...)
    generate the xml interface file from the given header.
    If the optional argument interfacename is omitted, the name of the
    interface file is constructed from the basename of the header with
    the suffix .xml appended.
    Options may be given to qdbuscpp2xml, such as those found when executing "qdbuscpp2xml --help"
    +


    +
      macro QT4_CREATE_TRANSLATION( qm_files directories ... sources ... 
    ts_files ... OPTIONS ...)
    out: qm_files
    in: directories sources ts_files
    options: flags to pass to lupdate, such as -extensions to specify
    extensions for a directory scan.
    generates commands to create .ts (vie lupdate) and .qm
    (via lrelease) - files from directories and/or sources. The ts files are
    created and/or updated in the source tree (unless given with full paths).
    The qm files are generated in the build tree.
    Updating the translations can be done by adding the qm_files
    to the source list of your library/executable, so they are
    always updated, or by adding a custom target to control when
    they get updated/generated.
    +


    +
      macro QT4_ADD_TRANSLATION( qm_files ts_files ... )
    out: qm_files
    in: ts_files
    generates commands to create .qm from .ts - files. The generated
    filenames can be found in qm_files. The ts_files
    must exists and are not updated in any way.
    +


    +


    +
      Below is a detailed list of variables that FindQt4.cmake sets.
    QT_FOUND If false, don't try to use Qt.
    QT4_FOUND If false, don't try to use Qt 4.
    +


    +
      QT_VERSION_MAJOR The major version of Qt found.
    QT_VERSION_MINOR The minor version of Qt found.
    QT_VERSION_PATCH The patch version of Qt found.
    +


    +
      QT_EDITION               Set to the edition of Qt (i.e. DesktopLight)
    QT_EDITION_DESKTOPLIGHT True if QT_EDITION == DesktopLight
    QT_QTCORE_FOUND True if QtCore was found.
    QT_QTGUI_FOUND True if QtGui was found.
    QT_QT3SUPPORT_FOUND True if Qt3Support was found.
    QT_QTASSISTANT_FOUND True if QtAssistant was found.
    QT_QTASSISTANTCLIENT_FOUND True if QtAssistantClient was found.
    QT_QAXCONTAINER_FOUND True if QAxContainer was found (Windows only).
    QT_QAXSERVER_FOUND True if QAxServer was found (Windows only).
    QT_QTDBUS_FOUND True if QtDBus was found.
    QT_QTDESIGNER_FOUND True if QtDesigner was found.
    QT_QTDESIGNERCOMPONENTS True if QtDesignerComponents was found.
    QT_QTHELP_FOUND True if QtHelp was found.
    QT_QTMOTIF_FOUND True if QtMotif was found.
    QT_QTMULTIMEDIA_FOUND True if QtMultimedia was found (since Qt 4.6.0).
    QT_QTNETWORK_FOUND True if QtNetwork was found.
    QT_QTNSPLUGIN_FOUND True if QtNsPlugin was found.
    QT_QTOPENGL_FOUND True if QtOpenGL was found.
    QT_QTSQL_FOUND True if QtSql was found.
    QT_QTSVG_FOUND True if QtSvg was found.
    QT_QTSCRIPT_FOUND True if QtScript was found.
    QT_QTSCRIPTTOOLS_FOUND True if QtScriptTools was found.
    QT_QTTEST_FOUND True if QtTest was found.
    QT_QTUITOOLS_FOUND True if QtUiTools was found.
    QT_QTWEBKIT_FOUND True if QtWebKit was found.
    QT_QTXML_FOUND True if QtXml was found.
    QT_QTXMLPATTERNS_FOUND True if QtXmlPatterns was found.
    QT_PHONON_FOUND True if phonon was found.
    QT_QTDECLARATIVE_FOUND True if QtDeclarative was found.
    +


    +
      QT_MAC_USE_COCOA    For Mac OS X, its whether Cocoa or Carbon is used.
    In general, this should not be used, but its useful
    when having platform specific code.
    +


    +
      QT_DEFINITIONS   Definitions to use when compiling code that uses Qt.
    You do not need to use this if you include QT_USE_FILE.
    The QT_USE_FILE will also define QT_DEBUG and QT_NO_DEBUG
    to fit your current build type. Those are not contained
    in QT_DEFINITIONS.

    QT_INCLUDES List of paths to all include directories of
    Qt4 QT_INCLUDE_DIR and QT_QTCORE_INCLUDE_DIR are
    always in this variable even if NOTFOUND,
    all other INCLUDE_DIRS are
    only added if they are found.
    You do not need to use this if you include QT_USE_FILE.

    +


    +
      Include directories for the Qt modules are listed here.
    You do not need to use these variables if you include QT_USE_FILE.
    +


    +
      QT_INCLUDE_DIR              Path to "include" of Qt4
    QT_QT3SUPPORT_INCLUDE_DIR Path to "include/Qt3Support"
    QT_QTASSISTANT_INCLUDE_DIR Path to "include/QtAssistant"
    QT_QTASSISTANTCLIENT_INCLUDE_DIR Path to "include/QtAssistant"
    QT_QAXCONTAINER_INCLUDE_DIR Path to "include/ActiveQt" (Windows only)
    QT_QAXSERVER_INCLUDE_DIR Path to "include/ActiveQt" (Windows only)
    QT_QTCORE_INCLUDE_DIR Path to "include/QtCore"
    QT_QTDBUS_INCLUDE_DIR Path to "include/QtDBus"
    QT_QTDESIGNER_INCLUDE_DIR Path to "include/QtDesigner"
    QT_QTDESIGNERCOMPONENTS_INCLUDE_DIR Path to "include/QtDesigner"
    QT_QTGUI_INCLUDE_DIR Path to "include/QtGui"
    QT_QTHELP_INCLUDE_DIR Path to "include/QtHelp"
    QT_QTMOTIF_INCLUDE_DIR Path to "include/QtMotif"
    QT_QTMULTIMEDIA_INCLUDE_DIR Path to "include/QtMultimedia"
    QT_QTNETWORK_INCLUDE_DIR Path to "include/QtNetwork"
    QT_QTNSPLUGIN_INCLUDE_DIR Path to "include/QtNsPlugin"
    QT_QTOPENGL_INCLUDE_DIR Path to "include/QtOpenGL"
    QT_QTSCRIPT_INCLUDE_DIR Path to "include/QtScript"
    QT_QTSQL_INCLUDE_DIR Path to "include/QtSql"
    QT_QTSVG_INCLUDE_DIR Path to "include/QtSvg"
    QT_QTTEST_INCLUDE_DIR Path to "include/QtTest"
    QT_QTWEBKIT_INCLUDE_DIR Path to "include/QtWebKit"
    QT_QTXML_INCLUDE_DIR Path to "include/QtXml"
    QT_QTXMLPATTERNS_INCLUDE_DIR Path to "include/QtXmlPatterns"
    QT_PHONON_INCLUDE_DIR Path to "include/phonon"
    QT_QTSCRIPTTOOLS_INCLUDE_DIR Path to "include/QtScriptTools"
    QT_QTDECLARATIVE_INCLUDE_DIR Path to "include/QtDeclarative"
    +


    +
      QT_BINARY_DIR               Path to "bin" of Qt4
    QT_LIBRARY_DIR Path to "lib" of Qt4
    QT_PLUGINS_DIR Path to "plugins" for Qt4
    QT_TRANSLATIONS_DIR Path to "translations" of Qt4
    QT_IMPORTS_DIR Path to "imports" of Qt4
    QT_DOC_DIR Path to "doc" of Qt4
    QT_MKSPECS_DIR Path to "mkspecs" of Qt4
    +


    +


    +

    The Qt toolkit may contain both debug and release libraries. In that case, the following library variables will contain both. You do not need to use these variables if you include QT_USE_FILE, and use QT_LIBRARIES.

    +
      QT_QT3SUPPORT_LIBRARY            The Qt3Support library
    QT_QTASSISTANT_LIBRARY The QtAssistant library
    QT_QTASSISTANTCLIENT_LIBRARY The QtAssistantClient library
    QT_QAXCONTAINER_LIBRARY The QAxContainer library (Windows only)
    QT_QAXSERVER_LIBRARY The QAxServer library (Windows only)
    QT_QTCORE_LIBRARY The QtCore library
    QT_QTDBUS_LIBRARY The QtDBus library
    QT_QTDESIGNER_LIBRARY The QtDesigner library
    QT_QTDESIGNERCOMPONENTS_LIBRARY The QtDesignerComponents library
    QT_QTGUI_LIBRARY The QtGui library
    QT_QTHELP_LIBRARY The QtHelp library
    QT_QTMOTIF_LIBRARY The QtMotif library
    QT_QTMULTIMEDIA_LIBRARY The QtMultimedia library
    QT_QTNETWORK_LIBRARY The QtNetwork library
    QT_QTNSPLUGIN_LIBRARY The QtNsPLugin library
    QT_QTOPENGL_LIBRARY The QtOpenGL library
    QT_QTSCRIPT_LIBRARY The QtScript library
    QT_QTSQL_LIBRARY The QtSql library
    QT_QTSVG_LIBRARY The QtSvg library
    QT_QTTEST_LIBRARY The QtTest library
    QT_QTUITOOLS_LIBRARY The QtUiTools library
    QT_QTWEBKIT_LIBRARY The QtWebKit library
    QT_QTXML_LIBRARY The QtXml library
    QT_QTXMLPATTERNS_LIBRARY The QtXmlPatterns library
    QT_QTMAIN_LIBRARY The qtmain library for Windows
    QT_PHONON_LIBRARY The phonon library
    QT_QTSCRIPTTOOLS_LIBRARY The QtScriptTools library

    +

    The QtDeclarative library: QT_QTDECLARATIVE_LIBRARY

    +

    also defined, but NOT for general use are

    +
      QT_MOC_EXECUTABLE                   Where to find the moc tool.
    QT_UIC_EXECUTABLE Where to find the uic tool.
    QT_UIC3_EXECUTABLE Where to find the uic3 tool.
    QT_RCC_EXECUTABLE Where to find the rcc tool
    QT_DBUSCPP2XML_EXECUTABLE Where to find the qdbuscpp2xml tool.
    QT_DBUSXML2CPP_EXECUTABLE Where to find the qdbusxml2cpp tool.
    QT_LUPDATE_EXECUTABLE Where to find the lupdate tool.
    QT_LRELEASE_EXECUTABLE Where to find the lrelease tool.
    QT_QCOLLECTIONGENERATOR_EXECUTABLE Where to find the qcollectiongenerator tool.
    QT_DESIGNER_EXECUTABLE Where to find the Qt designer tool.
    QT_LINGUIST_EXECUTABLE Where to find the Qt linguist tool.

    +


    +

    These are around for backwards compatibility they will be set

    +
      QT_WRAP_CPP  Set true if QT_MOC_EXECUTABLE is found
    QT_WRAP_UI Set true if QT_UIC_EXECUTABLE is found

    +

    These variables do _NOT_ have any effect anymore (compared to FindQt.cmake)

    +
      QT_MT_REQUIRED         Qt4 is now always multithreaded

    +

    These variables are set to "" Because Qt structure changed (They make no sense in Qt4)

    +
      QT_QT_LIBRARY        Qt-Library is now split
    + +
  • +
  • + FindQuickTime:
    +

    Locate QuickTime This module defines QUICKTIME_LIBRARY QUICKTIME_FOUND, if false, do not try to link to gdal QUICKTIME_INCLUDE_DIR, where to find the headers

    +

    $QUICKTIME_DIR is an environment variable that would correspond to the ./configure --prefix=$QUICKTIME_DIR

    +

    Created by Eric Wing.

    + +
  • +
  • + FindRTI: Try to find M&S HLA RTI libraries
    +

    This module finds if any HLA RTI is installed and locates the standard RTI include files and libraries.

    +

    RTI is a simulation infrastructure standardized by IEEE and SISO. It has a well defined C++ API that assures that simulation applications are independent on a particular RTI implementation.

    +
      http://en.wikipedia.org/wiki/Run-Time_Infrastructure_(simulation)
    +


    +

    This code sets the following variables:

    +
      RTI_INCLUDE_DIR = the directory where RTI includes file are found
    RTI_LIBRARIES = The libraries to link against to use RTI
    RTI_DEFINITIONS = -DRTI_USES_STD_FSTREAM
    RTI_FOUND = Set to FALSE if any HLA RTI was not found
    +


    +

    Report problems to <certi-devel@nongnu.org>

    + +
  • +
  • + FindRuby: Find Ruby
    +

    This module finds if Ruby is installed and determines where the include files and libraries are. Ruby 1.8 and 1.9 are supported.

    +

    The minimum required version of Ruby can be specified using the standard syntax, e.g. FIND_PACKAGE(Ruby 1.8)

    +

    It also determines what the name of the library is. This code sets the following variables:

    +
      RUBY_EXECUTABLE   = full path to the ruby binary
    RUBY_INCLUDE_DIRS = include dirs to be used when using the ruby library
    RUBY_LIBRARY = full path to the ruby library
    RUBY_VERSION = the version of ruby which was found, e.g. "1.8.7"
    RUBY_FOUND = set to true if ruby ws found successfully
    +


    +
      RUBY_INCLUDE_PATH = same as RUBY_INCLUDE_DIRS, only provided for compatibility reasons, don't use it
    + +
  • +
  • + FindSDL:
    +

    Locate SDL library This module defines SDL_LIBRARY, the name of the library to link against SDL_FOUND, if false, do not try to link to SDL SDL_INCLUDE_DIR, where to find SDL.h

    +

    This module responds to the the flag: SDL_BUILDING_LIBRARY If this is defined, then no SDL_main will be linked in because only applications need main(). Otherwise, it is assumed you are building an application and this module will attempt to locate and set the the proper link flags as part of the returned SDL_LIBRARY variable.

    +

    Don't forget to include SDLmain.h and SDLmain.m your project for the OS X framework based version. (Other versions link to -lSDLmain which this module will try to find on your behalf.) Also for OS X, this module will automatically add the -framework Cocoa on your behalf.

    +


    +

    Additional Note: If you see an empty SDL_LIBRARY_TEMP in your configuration and no SDL_LIBRARY, it means CMake did not find your SDL library (SDL.dll, libsdl.so, SDL.framework, etc). Set SDL_LIBRARY_TEMP to point to your SDL library, and configure again. Similarly, if you see an empty SDLMAIN_LIBRARY, you should set this value as appropriate. These values are used to generate the final SDL_LIBRARY variable, but when these values are unset, SDL_LIBRARY does not get created.

    +


    +

    $SDLDIR is an environment variable that would correspond to the ./configure --prefix=$SDLDIR used in building SDL. l.e.galup 9-20-02

    +

    Modified by Eric Wing. Added code to assist with automated building by using environmental variables and providing a more controlled/consistent search behavior. Added new modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc). Also corrected the header search path to follow "proper" SDL guidelines. Added a search for SDLmain which is needed by some platforms. Added a search for threads which is needed by some platforms. Added needed compile switches for MinGW.

    +

    On OSX, this will prefer the Framework version (if found) over others. People will have to manually change the cache values of SDL_LIBRARY to override this selection or set the CMake environment CMAKE_INCLUDE_PATH to modify the search paths.

    +

    Note that the header path has changed from SDL/SDL.h to just SDL.h This needed to change because "proper" SDL convention is #include "SDL.h", not <SDL/SDL.h>. This is done for portability reasons because not all systems place things in SDL/ (see FreeBSD).

    + +
  • +
  • + FindSDL_image:
    +

    Locate SDL_image library This module defines SDLIMAGE_LIBRARY, the name of the library to link against SDLIMAGE_FOUND, if false, do not try to link to SDL SDLIMAGE_INCLUDE_DIR, where to find SDL/SDL.h

    +

    $SDLDIR is an environment variable that would correspond to the ./configure --prefix=$SDLDIR used in building SDL.

    +

    Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).

    + +
  • +
  • + FindSDL_mixer:
    +

    Locate SDL_mixer library This module defines SDLMIXER_LIBRARY, the name of the library to link against SDLMIXER_FOUND, if false, do not try to link to SDL SDLMIXER_INCLUDE_DIR, where to find SDL/SDL.h

    +

    $SDLDIR is an environment variable that would correspond to the ./configure --prefix=$SDLDIR used in building SDL.

    +

    Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).

    + +
  • +
  • + FindSDL_net:
    +

    Locate SDL_net library This module defines SDLNET_LIBRARY, the name of the library to link against SDLNET_FOUND, if false, do not try to link against SDLNET_INCLUDE_DIR, where to find the headers

    +

    $SDLDIR is an environment variable that would correspond to the ./configure --prefix=$SDLDIR used in building SDL.

    +

    Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).

    + +
  • +
  • + FindSDL_sound:
    +

    Locates the SDL_sound library

    + +
  • +
  • + FindSDL_ttf:
    +

    Locate SDL_ttf library This module defines SDLTTF_LIBRARY, the name of the library to link against SDLTTF_FOUND, if false, do not try to link to SDL SDLTTF_INCLUDE_DIR, where to find SDL/SDL.h

    +

    $SDLDIR is an environment variable that would correspond to the ./configure --prefix=$SDLDIR used in building SDL.

    +

    Created by Eric Wing. This was influenced by the FindSDL.cmake module, but with modifications to recognize OS X frameworks and additional Unix paths (FreeBSD, etc).

    + +
  • +
  • + FindSWIG: Find SWIG
    +

    This module finds an installed SWIG. It sets the following variables:

    +
      SWIG_FOUND - set to true if SWIG is found
    SWIG_DIR - the directory where swig is installed
    SWIG_EXECUTABLE - the path to the swig executable
    SWIG_VERSION - the version number of the swig executable
    +


    +

    The minimum required version of SWIG can be specified using the standard syntax, e.g. FIND_PACKAGE(SWIG 1.1)

    +

    All information is collected from the SWIG_EXECUTABLE so the version to be found can be changed from the command line by means of setting SWIG_EXECUTABLE

    + +
  • +
  • + FindSelfPackers: Find upx
    +

    This module looks for some executable packers (i.e. softwares that compress executables or shared libs into on-the-fly self-extracting executables or shared libs. Examples:

    +
      UPX: http://wildsau.idv.uni-linz.ac.at/mfx/upx.html
    + +
  • +
  • + FindSquish: -- Typical Use
    +


    +

    This module can be used to find Squish (currently support is aimed at version 3).

    +
      SQUISH_FOUND                    If false, don't try to use Squish
    +


    +
      SQUISH_INSTALL_DIR              The Squish installation directory (containing bin, lib, etc)
    SQUISH_SERVER_EXECUTABLE The squishserver executable
    SQUISH_CLIENT_EXECUTABLE The squishrunner executable
    +


    +
      SQUISH_INSTALL_DIR_FOUND        Was the install directory found?
    SQUISH_SERVER_EXECUTABLE_FOUND Was the server executable found?
    SQUISH_CLIENT_EXECUTABLE_FOUND Was the client executable found?
    +


    +

    macro SQUISH_ADD_TEST(testName applicationUnderTest testSuite testCase)

    +
      ENABLE_TESTING()
    FIND_PACKAGE(Squish)
    IF (SQUISH_FOUND)
    SQUISH_ADD_TEST(myTestName myApplication testSuiteName testCaseName)
    ENDIF (SQUISH_FOUND)
    +


    + +
  • +
  • + FindSubversion: Extract information from a subversion working copy
    +

    The module defines the following variables:

    +
      Subversion_SVN_EXECUTABLE - path to svn command line client
    Subversion_VERSION_SVN - version of svn command line client
    Subversion_FOUND - true if the command line client was found
    SUBVERSION_FOUND - same as Subversion_FOUND, set for compatiblity reasons
    +


    +

    The minimum required version of Subversion can be specified using the standard syntax, e.g. FIND_PACKAGE(Subversion 1.4)

    +

    If the command line client executable is found two macros are defined:

    +
      Subversion_WC_INFO(<dir> <var-prefix>)
    Subversion_WC_LOG(<dir> <var-prefix>)
    +

    Subversion_WC_INFO extracts information of a subversion working copy at a given location. This macro defines the following variables:

    +
      <var-prefix>_WC_URL - url of the repository (at <dir>)
    <var-prefix>_WC_ROOT - root url of the repository
    <var-prefix>_WC_REVISION - current revision
    <var-prefix>_WC_LAST_CHANGED_AUTHOR - author of last commit
    <var-prefix>_WC_LAST_CHANGED_DATE - date of last commit
    <var-prefix>_WC_LAST_CHANGED_REV - revision of last commit
    <var-prefix>_WC_INFO - output of command `svn info <dir>'
    +

    Subversion_WC_LOG retrieves the log message of the base revision of a subversion working copy at a given location. This macro defines the variable:

    +
      <var-prefix>_LAST_CHANGED_LOG - last log of base revision
    +

    Example usage:

    +
      FIND_PACKAGE(Subversion)
    IF(SUBVERSION_FOUND)
    Subversion_WC_INFO(${PROJECT_SOURCE_DIR} Project)
    MESSAGE("Current revision is ${Project_WC_REVISION}")
    Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project)
    MESSAGE("Last changed log is ${Project_LAST_CHANGED_LOG}")
    ENDIF(SUBVERSION_FOUND)
    + +
  • +
  • + FindTCL: TK_INTERNAL_PATH was removed.
    +

    This module finds if Tcl is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      TCL_FOUND              = Tcl was found
    TK_FOUND = Tk was found
    TCLTK_FOUND = Tcl and Tk were found
    TCL_LIBRARY = path to Tcl library (tcl tcl80)
    TCL_INCLUDE_PATH = path to where tcl.h can be found
    TCL_TCLSH = path to tclsh binary (tcl tcl80)
    TK_LIBRARY = path to Tk library (tk tk80 etc)
    TK_INCLUDE_PATH = path to where tk.h can be found
    TK_WISH = full path to the wish executable
    +


    +

    In an effort to remove some clutter and clear up some issues for people who are not necessarily Tcl/Tk gurus/developpers, some variables were moved or removed. Changes compared to CMake 2.4 are:

    +
       => they were only useful for people writing Tcl/Tk extensions.
    => these libs are not packaged by default with Tcl/Tk distributions.
    Even when Tcl/Tk is built from source, several flavors of debug libs
    are created and there is no real reason to pick a single one
    specifically (say, amongst tcl84g, tcl84gs, or tcl84sgx).
    Let's leave that choice to the user by allowing him to assign
    TCL_LIBRARY to any Tcl library, debug or not.
    => this ended up being only a Win32 variable, and there is a lot of
    confusion regarding the location of this file in an installed Tcl/Tk
    tree anyway (see 8.5 for example). If you need the internal path at
    this point it is safer you ask directly where the *source* tree is
    and dig from there.
    + +
  • +
  • + FindTIFF: Find TIFF library
    +

    Find the native TIFF includes and library This module defines

    +
      TIFF_INCLUDE_DIR, where to find tiff.h, etc.
    TIFF_LIBRARIES, libraries to link against to use TIFF.
    TIFF_FOUND, If false, do not try to use TIFF.
    +

    also defined, but not for general use are

    +
      TIFF_LIBRARY, where to find the TIFF library.
    + +
  • +
  • + FindTclStub: TCL_STUB_LIBRARY_DEBUG and TK_STUB_LIBRARY_DEBUG were removed.
    +

    This module finds Tcl stub libraries. It first finds Tcl include files and libraries by calling FindTCL.cmake. How to Use the Tcl Stubs Library:

    +
       http://tcl.activestate.com/doc/howto/stubs.html
    +

    Using Stub Libraries:

    +
       http://safari.oreilly.com/0130385603/ch48lev1sec3
    +

    This code sets the following variables:

    +
      TCL_STUB_LIBRARY       = path to Tcl stub library
    TK_STUB_LIBRARY = path to Tk stub library
    TTK_STUB_LIBRARY = path to ttk stub library
    +


    +

    In an effort to remove some clutter and clear up some issues for people who are not necessarily Tcl/Tk gurus/developpers, some variables were moved or removed. Changes compared to CMake 2.4 are:

    +
       => these libs are not packaged by default with Tcl/Tk distributions. 
    Even when Tcl/Tk is built from source, several flavors of debug libs
    are created and there is no real reason to pick a single one
    specifically (say, amongst tclstub84g, tclstub84gs, or tclstub84sgx).
    Let's leave that choice to the user by allowing him to assign
    TCL_STUB_LIBRARY to any Tcl library, debug or not.
    + +
  • +
  • + FindTclsh: Find tclsh
    +

    This module finds if TCL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      TCLSH_FOUND = TRUE if tclsh has been found
    TCL_TCLSH = the path to the tclsh executable
    +

    In cygwin, look for the cygwin version first. Don't look for it later to avoid finding the cygwin version on a Win32 build.

    + +
  • +
  • + FindThreads: This module determines the thread library of the system.
    +

    The following variables are set

    +
      CMAKE_THREAD_LIBS_INIT     - the thread library
    CMAKE_USE_SPROC_INIT - are we using sproc?
    CMAKE_USE_WIN32_THREADS_INIT - using WIN32 threads?
    CMAKE_USE_PTHREADS_INIT - are we using pthreads
    CMAKE_HP_PTHREADS_INIT - are we using hp pthreads
    +

    For systems with multiple thread libraries, caller can set

    +
      CMAKE_THREAD_PREFER_PTHREAD
    + +
  • +
  • + FindUnixCommands: Find unix commands from cygwin
    +

    This module looks for some usual Unix commands.

    + +
  • +
  • + FindVTK: Find a VTK installation or build tree.
    +

    The following variables are set if VTK is found. If VTK is not found, VTK_FOUND is set to false.

    +
      VTK_FOUND         - Set to true when VTK is found.
    VTK_USE_FILE - CMake file to use VTK.
    VTK_MAJOR_VERSION - The VTK major version number.
    VTK_MINOR_VERSION - The VTK minor version number
    (odd non-release).
    VTK_BUILD_VERSION - The VTK patch level
    (meaningless for odd minor).
    VTK_INCLUDE_DIRS - Include directories for VTK
    VTK_LIBRARY_DIRS - Link directories for VTK libraries
    VTK_KITS - List of VTK kits, in CAPS
    (COMMON,IO,) etc.
    VTK_LANGUAGES - List of wrapped languages, in CAPS
    (TCL, PYHTON,) etc.
    +

    The following cache entries must be set by the user to locate VTK:

    +
      VTK_DIR  - The directory containing VTKConfig.cmake.  
    This is either the root of the build tree,
    or the lib/vtk directory. This is the
    only cache entry.
    +

    The following variables are set for backward compatibility and should not be used in new code:

    +
      USE_VTK_FILE - The full path to the UseVTK.cmake file.
    This is provided for backward
    compatibility. Use VTK_USE_FILE
    instead.
    +


    + +
  • +
  • + FindWget: Find wget
    +

    This module looks for wget. This module defines the following values:

    +
      WGET_EXECUTABLE: the full path to the wget tool.
    WGET_FOUND: True if wget has been found.
    + +
  • +
  • + FindWish: Find wish installation
    +

    This module finds if TCL is installed and determines where the include files and libraries are. It also determines what the name of the library is. This code sets the following variables:

    +
      TK_WISH = the path to the wish executable
    +


    +

    if UNIX is defined, then it will look for the cygwin version first

    + +
  • +
  • + FindX11: Find X11 installation
    +

    Try to find X11 on UNIX systems. The following values are defined

    +
      X11_FOUND        - True if X11 is available
    X11_INCLUDE_DIR - include directories to use X11
    X11_LIBRARIES - link against these to use X11
    +


    +

    and also the following more fine grained variables: Include paths: X11_ICE_INCLUDE_PATH, X11_ICE_LIB, X11_ICE_FOUND

    +
                    X11_SM_INCLUDE_PATH,           X11_SM_LIB,         X11_SM_FOUND
    X11_X11_INCLUDE_PATH, X11_X11_LIB
    X11_Xaccessrules_INCLUDE_PATH, X11_Xaccess_FOUND
    X11_Xaccessstr_INCLUDE_PATH, X11_Xaccess_FOUND
    X11_Xau_INCLUDE_PATH, X11_Xau_LIB, X11_Xau_FOUND
    X11_Xcomposite_INCLUDE_PATH, X11_Xcomposite_LIB, X11_Xcomposite_FOUND
    X11_Xcursor_INCLUDE_PATH, X11_Xcursor_LIB, X11_Xcursor_FOUND
    X11_Xdamage_INCLUDE_PATH, X11_Xdamage_LIB, X11_Xdamage_FOUND
    X11_Xdmcp_INCLUDE_PATH, X11_Xdmcp_LIB, X11_Xdmcp_FOUND
    X11_Xext_LIB, X11_Xext_FOUND
    X11_dpms_INCLUDE_PATH, (in X11_Xext_LIB), X11_dpms_FOUND
    X11_XShm_INCLUDE_PATH, (in X11_Xext_LIB), X11_XShm_FOUND
    X11_Xshape_INCLUDE_PATH, (in X11_Xext_LIB), X11_Xshape_FOUND
    X11_xf86misc_INCLUDE_PATH, X11_Xxf86misc_LIB, X11_xf86misc_FOUND
    X11_xf86vmode_INCLUDE_PATH, X11_xf86vmode_FOUND
    X11_Xfixes_INCLUDE_PATH, X11_Xfixes_LIB, X11_Xfixes_FOUND
    X11_Xft_INCLUDE_PATH, X11_Xft_LIB, X11_Xft_FOUND
    X11_Xi_INCLUDE_PATH, X11_Xi_LIB, X11_Xi_FOUND
    X11_Xinerama_INCLUDE_PATH, X11_Xinerama_LIB, X11_Xinerama_FOUND
    X11_Xinput_INCLUDE_PATH, X11_Xinput_LIB, X11_Xinput_FOUND
    X11_Xkb_INCLUDE_PATH, X11_Xkb_FOUND
    X11_Xkblib_INCLUDE_PATH, X11_Xkb_FOUND
    X11_Xkbfile_INCLUDE_PATH, X11_Xkbfile_LIB, X11_Xkbfile_FOUND
    X11_Xpm_INCLUDE_PATH, X11_Xpm_LIB, X11_Xpm_FOUND
    X11_XTest_INCLUDE_PATH, X11_XTest_LIB, X11_XTest_FOUND
    X11_Xrandr_INCLUDE_PATH, X11_Xrandr_LIB, X11_Xrandr_FOUND
    X11_Xrender_INCLUDE_PATH, X11_Xrender_LIB, X11_Xrender_FOUND
    X11_Xscreensaver_INCLUDE_PATH, X11_Xscreensaver_LIB, X11_Xscreensaver_FOUND
    X11_Xt_INCLUDE_PATH, X11_Xt_LIB, X11_Xt_FOUND
    X11_Xutil_INCLUDE_PATH, X11_Xutil_FOUND
    X11_Xv_INCLUDE_PATH, X11_Xv_LIB, X11_Xv_FOUND
    X11_XSync_INCLUDE_PATH, (in X11_Xext_LIB), X11_XSync_FOUND
    + +
  • +
  • + FindXMLRPC: Find xmlrpc
    +

    Find the native XMLRPC headers and libraries.

    +
      XMLRPC_INCLUDE_DIRS      - where to find xmlrpc.h, etc.
    XMLRPC_LIBRARIES - List of libraries when using xmlrpc.
    XMLRPC_FOUND - True if xmlrpc found.
    +

    XMLRPC modules may be specified as components for this find module. Modules may be listed by running "xmlrpc-c-config". Modules include:

    +
      c++            C++ wrapper code
    libwww-client libwww-based client
    cgi-server CGI-based server
    abyss-server ABYSS-based server
    +

    Typical usage:

    +
      FIND_PACKAGE(XMLRPC REQUIRED libwww-client)
    + +
  • +
  • + FindZLIB: Find zlib
    +

    Find the native ZLIB includes and library. Once done this will define

    +
      ZLIB_INCLUDE_DIRS   - where to find zlib.h, etc.
    ZLIB_LIBRARIES - List of libraries when using zlib.
    ZLIB_FOUND - True if zlib found.
    +


    +
      ZLIB_VERSION_STRING - The version of zlib found (x.y.z)
    ZLIB_VERSION_MAJOR - The major version of zlib
    ZLIB_VERSION_MINOR - The minor version of zlib
    ZLIB_VERSION_PATCH - The patch version of zlib
    ZLIB_VERSION_TWEAK - The tweak version of zlib
    +


    +

    The following variable are provided for backward compatibility

    +
      ZLIB_MAJOR_VERSION  - The major version of zlib
    ZLIB_MINOR_VERSION - The minor version of zlib
    ZLIB_PATCH_VERSION - The patch version of zlib
    +


    +

    An includer may set ZLIB_ROOT to a zlib installation root to tell this module where to look.

    + +
  • +
  • + Findosg:
    +


    +

    NOTE: It is highly recommended that you use the new FindOpenSceneGraph.cmake introduced in CMake 2.6.3 and not use this Find module directly.

    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osg This module defines

    +

    OSG_FOUND - Was the Osg found? OSG_INCLUDE_DIR - Where to find the headers OSG_LIBRARIES - The libraries to link against for the OSG (use this)

    +

    OSG_LIBRARY - The OSG library OSG_LIBRARY_DEBUG - The OSG debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgAnimation:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgAnimation This module defines

    +

    OSGANIMATION_FOUND - Was osgAnimation found? OSGANIMATION_INCLUDE_DIR - Where to find the headers OSGANIMATION_LIBRARIES - The libraries to link against for the OSG (use this)

    +

    OSGANIMATION_LIBRARY - The OSG library OSGANIMATION_LIBRARY_DEBUG - The OSG debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgDB:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgDB This module defines

    +

    OSGDB_FOUND - Was osgDB found? OSGDB_INCLUDE_DIR - Where to find the headers OSGDB_LIBRARIES - The libraries to link against for the osgDB (use this)

    +

    OSGDB_LIBRARY - The osgDB library OSGDB_LIBRARY_DEBUG - The osgDB debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgFX:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgFX This module defines

    +

    OSGFX_FOUND - Was osgFX found? OSGFX_INCLUDE_DIR - Where to find the headers OSGFX_LIBRARIES - The libraries to link against for the osgFX (use this)

    +

    OSGFX_LIBRARY - The osgFX library OSGFX_LIBRARY_DEBUG - The osgFX debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgGA:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgGA This module defines

    +

    OSGGA_FOUND - Was osgGA found? OSGGA_INCLUDE_DIR - Where to find the headers OSGGA_LIBRARIES - The libraries to link against for the osgGA (use this)

    +

    OSGGA_LIBRARY - The osgGA library OSGGA_LIBRARY_DEBUG - The osgGA debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgIntrospection:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgINTROSPECTION This module defines

    +

    OSGINTROSPECTION_FOUND - Was osgIntrospection found? OSGINTROSPECTION_INCLUDE_DIR - Where to find the headers OSGINTROSPECTION_LIBRARIES - The libraries to link for osgIntrospection (use this)

    +

    OSGINTROSPECTION_LIBRARY - The osgIntrospection library OSGINTROSPECTION_LIBRARY_DEBUG - The osgIntrospection debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgManipulator:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgManipulator This module defines

    +

    OSGMANIPULATOR_FOUND - Was osgManipulator found? OSGMANIPULATOR_INCLUDE_DIR - Where to find the headers OSGMANIPULATOR_LIBRARIES - The libraries to link for osgManipulator (use this)

    +

    OSGMANIPULATOR_LIBRARY - The osgManipulator library OSGMANIPULATOR_LIBRARY_DEBUG - The osgManipulator debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgParticle:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgParticle This module defines

    +

    OSGPARTICLE_FOUND - Was osgParticle found? OSGPARTICLE_INCLUDE_DIR - Where to find the headers OSGPARTICLE_LIBRARIES - The libraries to link for osgParticle (use this)

    +

    OSGPARTICLE_LIBRARY - The osgParticle library OSGPARTICLE_LIBRARY_DEBUG - The osgParticle debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgProducer:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgProducer This module defines

    +

    OSGPRODUCER_FOUND - Was osgProducer found? OSGPRODUCER_INCLUDE_DIR - Where to find the headers OSGPRODUCER_LIBRARIES - The libraries to link for osgProducer (use this)

    +

    OSGPRODUCER_LIBRARY - The osgProducer library OSGPRODUCER_LIBRARY_DEBUG - The osgProducer debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgShadow:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgShadow This module defines

    +

    OSGSHADOW_FOUND - Was osgShadow found? OSGSHADOW_INCLUDE_DIR - Where to find the headers OSGSHADOW_LIBRARIES - The libraries to link for osgShadow (use this)

    +

    OSGSHADOW_LIBRARY - The osgShadow library OSGSHADOW_LIBRARY_DEBUG - The osgShadow debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgSim:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgSim This module defines

    +

    OSGSIM_FOUND - Was osgSim found? OSGSIM_INCLUDE_DIR - Where to find the headers OSGSIM_LIBRARIES - The libraries to link for osgSim (use this)

    +

    OSGSIM_LIBRARY - The osgSim library OSGSIM_LIBRARY_DEBUG - The osgSim debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgTerrain:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgTerrain This module defines

    +

    OSGTERRAIN_FOUND - Was osgTerrain found? OSGTERRAIN_INCLUDE_DIR - Where to find the headers OSGTERRAIN_LIBRARIES - The libraries to link for osgTerrain (use this)

    +

    OSGTERRAIN_LIBRARY - The osgTerrain library OSGTERRAIN_LIBRARY_DEBUG - The osgTerrain debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgText:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgText This module defines

    +

    OSGTEXT_FOUND - Was osgText found? OSGTEXT_INCLUDE_DIR - Where to find the headers OSGTEXT_LIBRARIES - The libraries to link for osgText (use this)

    +

    OSGTEXT_LIBRARY - The osgText library OSGTEXT_LIBRARY_DEBUG - The osgText debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgUtil:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgUtil This module defines

    +

    OSGUTIL_FOUND - Was osgUtil found? OSGUTIL_INCLUDE_DIR - Where to find the headers OSGUTIL_LIBRARIES - The libraries to link for osgUtil (use this)

    +

    OSGUTIL_LIBRARY - The osgUtil library OSGUTIL_LIBRARY_DEBUG - The osgUtil debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgViewer:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgViewer This module defines

    +

    OSGVIEWER_FOUND - Was osgViewer found? OSGVIEWER_INCLUDE_DIR - Where to find the headers OSGVIEWER_LIBRARIES - The libraries to link for osgViewer (use this)

    +

    OSGVIEWER_LIBRARY - The osgViewer library OSGVIEWER_LIBRARY_DEBUG - The osgViewer debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgVolume:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgVolume This module defines

    +

    OSGVOLUME_FOUND - Was osgVolume found? OSGVOLUME_INCLUDE_DIR - Where to find the headers OSGVOLUME_LIBRARIES - The libraries to link for osgVolume (use this)

    +

    OSGVOLUME_LIBRARY - The osgVolume library OSGVOLUME_LIBRARY_DEBUG - The osgVolume debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    Created by Eric Wing.

    + +
  • +
  • + FindosgWidget:
    +

    This is part of the Findosg* suite used to find OpenSceneGraph components. Each component is separate and you must opt in to each module. You must also opt into OpenGL and OpenThreads (and Producer if needed) as these modules won't do it for you. This is to allow you control over your own system piece by piece in case you need to opt out of certain components or change the Find behavior for a particular module (perhaps because the default FindOpenGL.cmake module doesn't work with your system as an example). If you want to use a more convenient module that includes everything, use the FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

    +

    Locate osgWidget This module defines

    +

    OSGWIDGET_FOUND - Was osgWidget found? OSGWIDGET_INCLUDE_DIR - Where to find the headers OSGWIDGET_LIBRARIES - The libraries to link for osgWidget (use this)

    +

    OSGWIDGET_LIBRARY - The osgWidget library OSGWIDGET_LIBRARY_DEBUG - The osgWidget debug library

    +

    $OSGDIR is an environment variable that would correspond to the ./configure --prefix=$OSGDIR used in building osg.

    +

    FindosgWidget.cmake tweaked from Findosg* suite as created by Eric Wing.

    + +
  • +
  • + Findosg_functions:
    +


    +

    This CMake file contains two macros to assist with searching for OSG libraries and nodekits.

    + +
  • +
  • + FindwxWidgets: Find a wxWidgets (a.k.a., wxWindows) installation.
    +

    This module finds if wxWidgets is installed and selects a default configuration to use. wxWidgets is a modular library. To specify the modules that you will use, you need to name them as components to the package:

    +

    FIND_PACKAGE(wxWidgets COMPONENTS core base ...)

    +

    There are two search branches: a windows style and a unix style. For windows, the following variables are searched for and set to defaults in case of multiple choices. Change them if the defaults are not desired (i.e., these are the only variables you should change to select a configuration):

    +
      wxWidgets_ROOT_DIR      - Base wxWidgets directory
    (e.g., C:/wxWidgets-2.6.3).
    wxWidgets_LIB_DIR - Path to wxWidgets libraries
    (e.g., C:/wxWidgets-2.6.3/lib/vc_lib).
    wxWidgets_CONFIGURATION - Configuration to use
    (e.g., msw, mswd, mswu, mswunivud, etc.)
    wxWidgets_EXCLUDE_COMMON_LIBRARIES
    - Set to TRUE to exclude linking of
    commonly required libs (e.g., png tiff
    jpeg zlib regex expat).
    +


    +

    For unix style it uses the wx-config utility. You can select between debug/release, unicode/ansi, universal/non-universal, and static/shared in the QtDialog or ccmake interfaces by turning ON/OFF the following variables:

    +
      wxWidgets_USE_DEBUG
    wxWidgets_USE_UNICODE
    wxWidgets_USE_UNIVERSAL
    wxWidgets_USE_STATIC
    +


    +

    There is also a wxWidgets_CONFIG_OPTIONS variable for all other options that need to be passed to the wx-config utility. For example, to use the base toolkit found in the /usr/local path, set the variable (before calling the FIND_PACKAGE command) as such:

    +
      SET(wxWidgets_CONFIG_OPTIONS --toolkit=base --prefix=/usr)
    +


    +

    The following are set after the configuration is done for both windows and unix style:

    +
      wxWidgets_FOUND            - Set to TRUE if wxWidgets was found.
    wxWidgets_INCLUDE_DIRS - Include directories for WIN32
    i.e., where to find "wx/wx.h" and
    "wx/setup.h"; possibly empty for unices.
    wxWidgets_LIBRARIES - Path to the wxWidgets libraries.
    wxWidgets_LIBRARY_DIRS - compile time link dirs, useful for
    rpath on UNIX. Typically an empty string
    in WIN32 environment.
    wxWidgets_DEFINITIONS - Contains defines required to compile/link
    against WX, e.g. WXUSINGDLL
    wxWidgets_DEFINITIONS_DEBUG- Contains defines required to compile/link
    against WX debug builds, e.g. __WXDEBUG__
    wxWidgets_CXX_FLAGS - Include dirs and compiler flags for
    unices, empty on WIN32. Essentially
    "`wx-config --cxxflags`".
    wxWidgets_USE_FILE - Convenience include file.
    +


    +

    Sample usage:

    +
       # Note that for MinGW users the order of libs is important!
    FIND_PACKAGE(wxWidgets COMPONENTS net gl core base)
    IF(wxWidgets_FOUND)
    INCLUDE(${wxWidgets_USE_FILE})
    # and for each of your dependent executable/library targets:
    TARGET_LINK_LIBRARIES(<YourTarget> ${wxWidgets_LIBRARIES})
    ENDIF(wxWidgets_FOUND)
    +


    +

    If wxWidgets is required (i.e., not an optional part):

    +
       FIND_PACKAGE(wxWidgets REQUIRED net gl core base)
    INCLUDE(${wxWidgets_USE_FILE})
    # and for each of your dependent executable/library targets:
    TARGET_LINK_LIBRARIES(<YourTarget> ${wxWidgets_LIBRARIES})
    + +
  • +
  • + FindwxWindows: Find wxWindows (wxWidgets) installation
    +

    This module finds if wxWindows/wxWidgets is installed and determines where the include files and libraries are. It also determines what the name of the library is. Please note this file is DEPRECATED and replaced by FindwxWidgets.cmake. This code sets the following variables:

    +
      WXWINDOWS_FOUND     = system has WxWindows
    WXWINDOWS_LIBRARIES = path to the wxWindows libraries
    on Unix/Linux with additional
    linker flags from
    "wx-config --libs"
    CMAKE_WXWINDOWS_CXX_FLAGS = Compiler flags for wxWindows,
    essentially "`wx-config --cxxflags`"
    on Linux
    WXWINDOWS_INCLUDE_DIR = where to find "wx/wx.h" and "wx/setup.h"
    WXWINDOWS_LINK_DIRECTORIES = link directories, useful for rpath on
    Unix
    WXWINDOWS_DEFINITIONS = extra defines
    +


    +

    OPTIONS If you need OpenGL support please

    +
      SET(WXWINDOWS_USE_GL 1)
    +

    in your CMakeLists.txt *before* you include this file.

    +
      HAVE_ISYSTEM      - true required to replace -I by -isystem on g++
    +


    +

    For convenience include Use_wxWindows.cmake in your project's CMakeLists.txt using INCLUDE(Use_wxWindows).

    +

    USAGE

    +
      SET(WXWINDOWS_USE_GL 1)
    FIND_PACKAGE(wxWindows)
    +


    +

    NOTES wxWidgets 2.6.x is supported for monolithic builds e.g. compiled in wx/build/msw dir as:

    +
      nmake -f makefile.vc BUILD=debug SHARED=0 USE_OPENGL=1 MONOLITHIC=1
    +


    +

    DEPRECATED

    +
      CMAKE_WX_CAN_COMPILE
    WXWINDOWS_LIBRARY
    CMAKE_WX_CXX_FLAGS
    WXWINDOWS_INCLUDE_PATH
    +


    +

    AUTHOR Jan Woetzel <http://www.mip.informatik.uni-kiel.de/~jw> (07/2003-01/2006)

    + +
  • +
  • + FortranCInterface: Fortran/C Interface Detection
    +

    This module automatically detects the API by which C and Fortran languages interact. Variables indicate if the mangling is found:

    +
       FortranCInterface_GLOBAL_FOUND = Global subroutines and functions
    FortranCInterface_MODULE_FOUND = Module subroutines and functions
    (declared by "MODULE PROCEDURE")
    +

    A function is provided to generate a C header file containing macros to mangle symbol names:

    +
       FortranCInterface_HEADER(<file>
    [MACRO_NAMESPACE <macro-ns>]
    [SYMBOL_NAMESPACE <ns>]
    [SYMBOLS [<module>:]<function> ...])
    +

    It generates in <file> definitions of the following macros:

    +
       #define FortranCInterface_GLOBAL (name,NAME) ...
    #define FortranCInterface_GLOBAL_(name,NAME) ...
    #define FortranCInterface_MODULE (mod,name, MOD,NAME) ...
    #define FortranCInterface_MODULE_(mod,name, MOD,NAME) ...
    +

    These macros mangle four categories of Fortran symbols, respectively:

    +
       - Global symbols without '_': call mysub()
    - Global symbols with '_' : call my_sub()
    - Module symbols without '_': use mymod; call mysub()
    - Module symbols with '_' : use mymod; call my_sub()
    +

    If mangling for a category is not known, its macro is left undefined. All macros require raw names in both lower case and upper case. The MACRO_NAMESPACE option replaces the default "FortranCInterface_" prefix with a given namespace "<macro-ns>".

    +

    The SYMBOLS option lists symbols to mangle automatically with C preprocessor definitions:

    +
       <function>          ==> #define <ns><function> ...
    <module>:<function> ==> #define <ns><module>_<function> ...
    +

    If the mangling for some symbol is not known then no preprocessor definition is created, and a warning is displayed. The SYMBOL_NAMESPACE option prefixes all preprocessor definitions generated by the SYMBOLS option with a given namespace "<ns>".

    +

    Example usage:

    +
       include(FortranCInterface)
    FortranCInterface_HEADER(FC.h MACRO_NAMESPACE "FC_")
    +

    This creates a "FC.h" header that defines mangling macros FC_GLOBAL(), FC_GLOBAL_(), FC_MODULE(), and FC_MODULE_().

    +

    Example usage:

    +
       include(FortranCInterface)
    FortranCInterface_HEADER(FCMangle.h
    MACRO_NAMESPACE "FC_"
    SYMBOL_NAMESPACE "FC_"
    SYMBOLS mysub mymod:my_sub)
    +

    This creates a "FCMangle.h" header that defines the same FC_*() mangling macros as the previous example plus preprocessor symbols FC_mysub and FC_mymod_my_sub.

    +

    Another function is provided to verify that the Fortran and C/C++ compilers work together:

    +
       FortranCInterface_VERIFY([CXX] [QUIET])
    +

    It tests whether a simple test executable using Fortran and C (and C++ when the CXX option is given) compiles and links successfully. The result is stored in the cache entry FortranCInterface_VERIFIED_C (or FortranCInterface_VERIFIED_CXX if CXX is given) as a boolean. If the check fails and QUIET is not given the function terminates with a FATAL_ERROR message describing the problem. The purpose of this check is to stop a build early for incompatible compiler combinations.

    +

    FortranCInterface is aware of possible GLOBAL and MODULE manglings for many Fortran compilers, but it also provides an interface to specify new possible manglings. Set the variables

    +
       FortranCInterface_GLOBAL_SYMBOLS
    FortranCInterface_MODULE_SYMBOLS
    +

    before including FortranCInterface to specify manglings of the symbols "MySub", "My_Sub", "MyModule:MySub", and "My_Module:My_Sub". For example, the code:

    +
       set(FortranCInterface_GLOBAL_SYMBOLS mysub_ my_sub__ MYSUB_)
    # ^^^^^ ^^^^^^ ^^^^^
    set(FortranCInterface_MODULE_SYMBOLS
    __mymodule_MOD_mysub __my_module_MOD_my_sub)
    # ^^^^^^^^ ^^^^^ ^^^^^^^^^ ^^^^^^
    include(FortranCInterface)
    +

    tells FortranCInterface to try given GLOBAL and MODULE manglings. (The carets point at raw symbol names for clarity in this example but are not needed.)

    + +
  • +
  • + GNUInstallDirs: Define GNU standard installation directories
    +

    Provides install directory variables as defined for GNU software:

    +
      http://www.gnu.org/prep/standards/html_node/Directory-Variables.html
    +

    Inclusion of this module defines the following variables:

    +
      CMAKE_INSTALL_<dir>      - destination for files of a given type
    CMAKE_INSTALL_FULL_<dir> - corresponding absolute path
    +

    where <dir> is one of:

    +
      BINDIR           - user executables (bin)
    SBINDIR - system admin executables (sbin)
    LIBEXECDIR - program executables (libexec)
    SYSCONFDIR - read-only single-machine data (etc)
    SHAREDSTATEDIR - modifiable architecture-independent data (com)
    LOCALSTATEDIR - modifiable single-machine data (var)
    LIBDIR - object code libraries (lib or lib64)
    INCLUDEDIR - C header files (include)
    OLDINCLUDEDIR - C header files for non-gcc (/usr/include)
    DATAROOTDIR - read-only architecture-independent data root (share)
    DATADIR - read-only architecture-independent data (DATAROOTDIR)
    INFODIR - info documentation (DATAROOTDIR/info)
    LOCALEDIR - locale-dependent data (DATAROOTDIR/locale)
    MANDIR - man documentation (DATAROOTDIR/man)
    DOCDIR - documentation root (DATAROOTDIR/doc/PROJECT_NAME)
    +

    Each CMAKE_INSTALL_<dir> value may be passed to the DESTINATION options of install() commands for the corresponding file type. If the includer does not define a value the above-shown default will be used and the value will appear in the cache for editing by the user. Each CMAKE_INSTALL_FULL_<dir> value contains an absolute path constructed from the corresponding destination by prepending (if necessary) the value of CMAKE_INSTALL_PREFIX.

    + +
  • +
  • + GenerateExportHeader: Function for generation of export macros for libraries
    +

    This module provides the function GENERATE_EXPORT_HEADER() and the accompanying ADD_COMPILER_EXPORT_FLAGS() function.

    +

    The GENERATE_EXPORT_HEADER function can be used to generate a file suitable for preprocessor inclusion which contains EXPORT macros to be used in library classes.

    +

    GENERATE_EXPORT_HEADER( LIBRARY_TARGET

    +
                 [BASE_NAME <base_name>]
    [EXPORT_MACRO_NAME <export_macro_name>]
    [EXPORT_FILE_NAME <export_file_name>]
    [DEPRECATED_MACRO_NAME <deprecated_macro_name>]
    [NO_EXPORT_MACRO_NAME <no_export_macro_name>]
    [STATIC_DEFINE <static_define>]
    [NO_DEPRECATED_MACRO_NAME <no_deprecated_macro_name>]
    [DEFINE_NO_DEPRECATED]
    [PREFIX_NAME <prefix_name>]
    +

    )

    +

    ADD_COMPILER_EXPORT_FLAGS( [FATAL_WARNINGS] )

    +

    By default GENERATE_EXPORT_HEADER() generates macro names in a file name determined by the name of the library. The ADD_COMPILER_EXPORT_FLAGS function adds -fvisibility=hidden to CMAKE_CXX_FLAGS if supported, and is a no-op on Windows which does not need extra compiler flags for exporting support. You may optionally pass a single argument to ADD_COMPILER_EXPORT_FLAGS that will be populated with the required CXX_FLAGS required to enable visibility support for the compiler/architecture in use.

    +

    This means that in the simplest case, users of these functions will be equivalent to:

    +
       add_compiler_export_flags()
    add_library(somelib someclass.cpp)
    generate_export_header(somelib)
    install(TARGETS somelib DESTINATION ${LIBRARY_INSTALL_DIR})
    install(FILES
    someclass.h
    ${PROJECT_BINARY_DIR}/somelib_export.h DESTINATION ${INCLUDE_INSTALL_DIR}
    )
    +


    +

    And in the ABI header files:

    +
       #include "somelib_export.h"
    class SOMELIB_EXPORT SomeClass {
    ...
    };
    +


    +

    The CMake fragment will generate a file in the ${CMAKE_CURRENT_BUILD_DIR} called somelib_export.h containing the macros SOMELIB_EXPORT, SOMELIB_NO_EXPORT, SOMELIB_DEPRECATED, SOMELIB_DEPRECATED_EXPORT and SOMELIB_DEPRECATED_NO_EXPORT. The resulting file should be installed with other headers in the library.

    +

    The BASE_NAME argument can be used to override the file name and the names used for the macros

    +
       add_library(somelib someclass.cpp)
    generate_export_header(somelib
    BASE_NAME other_name
    )
    +


    +

    Generates a file called other_name_export.h containing the macros OTHER_NAME_EXPORT, OTHER_NAME_NO_EXPORT and OTHER_NAME_DEPRECATED etc.

    +

    The BASE_NAME may be overridden by specifiying other options in the function. For example:

    +
       add_library(somelib someclass.cpp)
    generate_export_header(somelib
    EXPORT_MACRO_NAME OTHER_NAME_EXPORT
    )
    +


    +

    creates the macro OTHER_NAME_EXPORT instead of SOMELIB_EXPORT, but other macros and the generated file name is as default.

    +
       add_library(somelib someclass.cpp)
    generate_export_header(somelib
    DEPRECATED_MACRO_NAME KDE_DEPRECATED
    )
    +


    +

    creates the macro KDE_DEPRECATED instead of SOMELIB_DEPRECATED.

    +

    If LIBRARY_TARGET is a static library, macros are defined without values.

    +

    If the same sources are used to create both a shared and a static library, the uppercased symbol ${BASE_NAME}_STATIC_DEFINE should be used when building the static library

    +
       add_library(shared_variant SHARED ${lib_SRCS})
    add_library(static_variant ${lib_SRCS})
    generate_export_header(shared_variant BASE_NAME libshared_and_static)
    set_target_properties(static_variant PROPERTIES
    COMPILE_FLAGS -DLIBSHARED_AND_STATIC_STATIC_DEFINE)
    +


    +

    This will cause the export macros to expand to nothing when building the static library.

    +

    If DEFINE_NO_DEPRECATED is specified, then a macro ${BASE_NAME}_NO_DEPRECATED will be defined This macro can be used to remove deprecated code from preprocessor output.

    +
       option(EXCLUDE_DEPRECATED "Exclude deprecated parts of the library" FALSE)
    if (EXCLUDE_DEPRECATED)
    set(NO_BUILD_DEPRECATED DEFINE_NO_DEPRECATED)
    endif()
    generate_export_header(somelib ${NO_BUILD_DEPRECATED})
    +


    +

    And then in somelib:

    +
       class SOMELIB_EXPORT SomeClass
    {
    public:
    #ifndef SOMELIB_NO_DEPRECATED
    SOMELIB_DEPRECATED void oldMethod();
    #endif
    };
    +


    +
       #ifndef SOMELIB_NO_DEPRECATED
    void SomeClass::oldMethod() { }
    #endif
    +


    +

    If PREFIX_NAME is specified, the argument will be used as a prefix to all generated macros.

    +

    For example:

    +
       generate_export_header(somelib PREFIX_NAME VTK_)
    +


    +

    Generates the macros VTK_SOMELIB_EXPORT etc.

    + +
  • +
  • + GetPrerequisites: Functions to analyze and list executable file prerequisites.
    +

    This module provides functions to list the .dll, .dylib or .so files that an executable or shared library file depends on. (Its prerequisites.)

    +

    It uses various tools to obtain the list of required shared library files:

    +
       dumpbin (Windows)
    ldd (Linux/Unix)
    otool (Mac OSX)
    +

    The following functions are provided by this module:

    +
       get_prerequisites
    list_prerequisites
    list_prerequisites_by_glob
    gp_append_unique
    is_file_executable
    gp_item_default_embedded_path
    (projects can override with gp_item_default_embedded_path_override)
    gp_resolve_item
    (projects can override with gp_resolve_item_override)
    gp_resolved_file_type
    (projects can override with gp_resolved_file_type_override)
    gp_file_type
    +

    Requires CMake 2.6 or greater because it uses function, break, return and PARENT_SCOPE.

    +
      GET_PREREQUISITES(<target> <prerequisites_var> <exclude_system> <recurse>
    <exepath> <dirs>)
    +

    Get the list of shared library files required by <target>. The list in the variable named <prerequisites_var> should be empty on first entry to this function. On exit, <prerequisites_var> will contain the list of required shared library files.

    +

    <target> is the full path to an executable file. <prerequisites_var> is the name of a CMake variable to contain the results. <exclude_system> must be 0 or 1 indicating whether to include or exclude "system" prerequisites. If <recurse> is set to 1 all prerequisites will be found recursively, if set to 0 only direct prerequisites are listed. <exepath> is the path to the top level executable used for @executable_path replacment on the Mac. <dirs> is a list of paths where libraries might be found: these paths are searched first when a target without any path info is given. Then standard system locations are also searched: PATH, Framework locations, /usr/lib...

    +
      LIST_PREREQUISITES(<target> [<recurse> [<exclude_system> [<verbose>]]])
    +

    Print a message listing the prerequisites of <target>.

    +

    <target> is the name of a shared library or executable target or the full path to a shared library or executable file. If <recurse> is set to 1 all prerequisites will be found recursively, if set to 0 only direct prerequisites are listed. <exclude_system> must be 0 or 1 indicating whether to include or exclude "system" prerequisites. With <verbose> set to 0 only the full path names of the prerequisites are printed, set to 1 extra informatin will be displayed.

    +
      LIST_PREREQUISITES_BY_GLOB(<glob_arg> <glob_exp>)
    +

    Print the prerequisites of shared library and executable files matching a globbing pattern. <glob_arg> is GLOB or GLOB_RECURSE and <glob_exp> is a globbing expression used with "file(GLOB" or "file(GLOB_RECURSE" to retrieve a list of matching files. If a matching file is executable, its prerequisites are listed.

    +

    Any additional (optional) arguments provided are passed along as the optional arguments to the list_prerequisites calls.

    +
      GP_APPEND_UNIQUE(<list_var> <value>)
    +

    Append <value> to the list variable <list_var> only if the value is not already in the list.

    +
      IS_FILE_EXECUTABLE(<file> <result_var>)
    +

    Return 1 in <result_var> if <file> is a binary executable, 0 otherwise.

    +
      GP_ITEM_DEFAULT_EMBEDDED_PATH(<item> <default_embedded_path_var>)
    +

    Return the path that others should refer to the item by when the item is embedded inside a bundle.

    +

    Override on a per-project basis by providing a project-specific gp_item_default_embedded_path_override function.

    +
      GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>)
    +

    Resolve an item into an existing full path file.

    +

    Override on a per-project basis by providing a project-specific gp_resolve_item_override function.

    +
      GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>)
    +

    Return the type of <file> with respect to <original_file>. String describing type of prerequisite is returned in variable named <type_var>.

    +

    Use <exepath> and <dirs> if necessary to resolve non-absolute <file> values -- but only for non-embedded items.

    +

    Possible types are:

    +
       system
    local
    embedded
    other
    +

    Override on a per-project basis by providing a project-specific gp_resolved_file_type_override function.

    +
      GP_FILE_TYPE(<original_file> <file> <type_var>)
    +

    Return the type of <file> with respect to <original_file>. String describing type of prerequisite is returned in variable named <type_var>.

    +

    Possible types are:

    +
       system
    local
    embedded
    other
    + +
  • +
  • + InstallRequiredSystemLibraries:
    +

    By including this file, all library files listed in the variable CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS will be installed with INSTALL(PROGRAMS ...) into bin for WIN32 and lib for non-WIN32. If CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP is set to TRUE before including this file, then the INSTALL command is not called. The user can use the variable CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS to use a custom install command and install them however they want. If it is the MSVC compiler, then the microsoft run time libraries will be found and automatically added to the CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS, and installed. If CMAKE_INSTALL_DEBUG_LIBRARIES is set and it is the MSVC compiler, then the debug libraries are installed when available. If CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY is set then only the debug libraries are installed when both debug and release are available. If CMAKE_INSTALL_MFC_LIBRARIES is set then the MFC run time libraries are installed as well as the CRT run time libraries. If CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION is set then the libraries are installed to that directory rather than the default. If CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS is NOT set, then this file warns about required files that do not exist. You can set this variable to ON before including this file to avoid the warning. For example, the Visual Studio Express editions do not include the redistributable files, so if you include this file on a machine with only VS Express installed, you'll get the warning.

    + +
  • +
  • + MacroAddFileDependencies: MACRO_ADD_FILE_DEPENDENCIES(<_file> depend_files...)
    +

    Using the macro MACRO_ADD_FILE_DEPENDENCIES() is discouraged. There are usually better ways to specify the correct dependencies.

    +

    MACRO_ADD_FILE_DEPENDENCIES(<_file> depend_files...) is just a convenience wrapper around the OBJECT_DEPENDS source file property. You can just use SET_PROPERTY(SOURCE <file> APPEND PROPERTY OBJECT_DEPENDS depend_files) instead.

    + +
  • +
  • + ProcessorCount: ProcessorCount(var)
    +

    Determine the number of processors/cores and save value in ${var}

    +

    Sets the variable named ${var} to the number of physical cores available on the machine if the information can be determined. Otherwise it is set to 0. Currently this functionality is implemented for AIX, cygwin, FreeBSD, HPUX, IRIX, Linux, Mac OS X, QNX, Sun and Windows.

    +

    This function is guaranteed to return a positive integer (>=1) if it succeeds. It returns 0 if there's a problem determining the processor count.

    +

    Example use, in a ctest -S dashboard script:

    +
       include(ProcessorCount)
    ProcessorCount(N)
    if(NOT N EQUAL 0)
    set(CTEST_BUILD_FLAGS -j${N})
    set(ctest_test_args ${ctest_test_args} PARALLEL_LEVEL ${N})
    endif()
    +


    +

    This function is intended to offer an approximation of the value of the number of compute cores available on the current machine, such that you may use that value for parallel building and parallel testing. It is meant to help utilize as much of the machine as seems reasonable. Of course, knowledge of what else might be running on the machine simultaneously should be used when deciding whether to request a machine's full capacity all for yourself.

    + +
  • +
  • + Qt4ConfigDependentSettings:
    +

    This file is included by FindQt4.cmake, don't include it directly.

    + +
  • +
  • + Qt4Macros:
    +

    This file is included by FindQt4.cmake, don't include it directly.

    + +
  • +
  • + SelectLibraryConfigurations:
    +

    select_library_configurations( basename )

    +

    This macro takes a library base name as an argument, and will choose good values for basename_LIBRARY, basename_LIBRARIES, basename_LIBRARY_DEBUG, and basename_LIBRARY_RELEASE depending on what has been found and set. If only basename_LIBRARY_RELEASE is defined, basename_LIBRARY, basename_LIBRARY_DEBUG, and basename_LIBRARY_RELEASE will be set to the release value. If only basename_LIBRARY_DEBUG is defined, then basename_LIBRARY, basename_LIBRARY_DEBUG and basename_LIBRARY_RELEASE will take the debug value.

    +

    If the generator supports configuration types, then basename_LIBRARY and basename_LIBRARIES will be set with debug and optimized flags specifying the library to be used for the given configuration. If no build type has been set or the generator in use does not support configuration types, then basename_LIBRARY and basename_LIBRARIES will take only the release values.

    + +
  • +
  • + SquishTestScript:
    +


    +

    This script launches a GUI test using Squish. You should not call the script directly; instead, you should access it via the SQUISH_ADD_TEST macro that is defined in FindSquish.cmake.

    +

    This script starts the Squish server, launches the test on the client, and finally stops the squish server. If any of these steps fail (including if the tests do not pass) then a fatal error is raised.

    + +
  • +
  • + TestBigEndian: Define macro to determine endian type
    +

    Check if the system is big endian or little endian

    +
      TEST_BIG_ENDIAN(VARIABLE)
    VARIABLE - variable to store the result to
    +


    + +
  • +
  • + TestCXXAcceptsFlag: Test CXX compiler for a flag
    +

    Check if the CXX compiler accepts a flag

    +
      Macro CHECK_CXX_ACCEPTS_FLAG(FLAGS VARIABLE) -
    checks if the function exists
    FLAGS - the flags to try
    VARIABLE - variable to store the result
    +


    + +
  • +
  • + TestForANSIForScope: Check for ANSI for scope support
    +

    Check if the compiler restricts the scope of variables declared in a for-init-statement to the loop body.

    +
      CMAKE_NO_ANSI_FOR_SCOPE - holds result
    +


    + +
  • +
  • + TestForANSIStreamHeaders: Test for compiler support of ANSI stream headers iostream, etc.
    +

    check if the compiler supports the standard ANSI iostream header (without the .h)

    +
      CMAKE_NO_ANSI_STREAM_HEADERS - defined by the results
    +


    + +
  • +
  • + TestForSSTREAM: Test for compiler support of ANSI sstream header
    +

    check if the compiler supports the standard ANSI sstream header

    +
      CMAKE_NO_ANSI_STRING_STREAM - defined by the results
    +


    + +
  • +
  • + TestForSTDNamespace: Test for std:: namespace support
    +

    check if the compiler supports std:: on stl classes

    +
      CMAKE_NO_STD_NAMESPACE - defined by the results
    +


    + +
  • +
  • + UseEcos: This module defines variables and macros required to build eCos application.
    +

    This file contains the following macros: ECOS_ADD_INCLUDE_DIRECTORIES() - add the eCos include dirs ECOS_ADD_EXECUTABLE(name source1 ... sourceN ) - create an eCos executable ECOS_ADJUST_DIRECTORY(VAR source1 ... sourceN ) - adjusts the path of the source files and puts the result into VAR

    +

    Macros for selecting the toolchain: ECOS_USE_ARM_ELF_TOOLS() - enable the ARM ELF toolchain for the directory where it is called ECOS_USE_I386_ELF_TOOLS() - enable the i386 ELF toolchain for the directory where it is called ECOS_USE_PPC_EABI_TOOLS() - enable the PowerPC toolchain for the directory where it is called

    +

    It contains the following variables: ECOS_DEFINITIONS ECOSCONFIG_EXECUTABLE ECOS_CONFIG_FILE - defaults to ecos.ecc, if your eCos configuration file has a different name, adjust this variable for internal use only:

    +
      ECOS_ADD_TARGET_LIB
    + +
  • +
  • + UseJava: Use Module for Java
    +

    This file provides functions for Java. It is assumed that FindJava.cmake has already been loaded. See FindJava.cmake for information on how to load Java into your CMake project.

    +

    add_jar(TARGET_NAME SRC1 SRC2 .. SRCN RCS1 RCS2 .. RCSN)

    +

    This command creates a <TARGET_NAME>.jar. It compiles the given source files (SRC) and adds the given resource files (RCS) to the jar file. If only resource files are given then just a jar file is created.

    +

    Additional instructions:

    +
       To add compile flags to the target you can set these flags with
    the following variable:
    +


    +
           set(CMAKE_JAVA_COMPILE_FLAGS -nowarn)
    +


    +
       To add a path or a jar file to the class path you can do this
    with the CMAKE_JAVA_INCLUDE_PATH variable.
    +


    +
           set(CMAKE_JAVA_INCLUDE_PATH /usr/share/java/shibboleet.jar)
    +


    +
       To use a different output name for the target you can set it with:
    +


    +
           set(CMAKE_JAVA_TARGET_OUTPUT_NAME shibboleet.jar)
    add_jar(foobar foobar.java)
    +


    +
       To add a VERSION to the target output name you can set it using
    CMAKE_JAVA_TARGET_VERSION. This will create a jar file with the name
    shibboleet-1.0.0.jar and will create a symlink shibboleet.jar
    pointing to the jar with the version information.
    +


    +
           set(CMAKE_JAVA_TARGET_VERSION 1.2.0)
    add_jar(shibboleet shibbotleet.java)
    +


    +
        If the target is a JNI library, utilize the following commands to
    create a JNI symbolic link:
    +


    +
           set(CMAKE_JNI_TARGET TRUE)
    set(CMAKE_JAVA_TARGET_VERSION 1.2.0)
    add_jar(shibboleet shibbotleet.java)
    install_jar(shibboleet ${LIB_INSTALL_DIR}/shibboleet)
    install_jni_symlink(shibboleet ${JAVA_LIB_INSTALL_DIR})
    +


    +
        If a single target needs to produce more than one jar from its
    java source code, to prevent the accumulation of duplicate class
    files in subsequent jars, set/reset CMAKE_JAR_CLASSES_PREFIX prior
    to calling the add_jar() function:
    +


    +
           set(CMAKE_JAR_CLASSES_PREFIX com/redhat/foo)
    add_jar(foo foo.java)
    +


    +
           set(CMAKE_JAR_CLASSES_PREFIX com/redhat/bar)
    add_jar(bar bar.java)
    +


    +

    Target Properties:

    +
       The add_jar() functions sets some target properties. You can get these
    properties with the
    get_property(TARGET <target_name> PROPERTY <propery_name>)
    command.
    +


    +
       INSTALL_FILES      The files which should be installed. This is used by
    install_jar().
    JNI_SYMLINK The JNI symlink which should be installed.
    This is used by install_jni_symlink().
    JAR_FILE The location of the jar file so that you can include
    it.
    CLASS_DIR The directory where the class files can be found. For
    example to use them with javah.
    +


    +

    find_jar(<VAR>

    +
              name | NAMES name1 [name2 ...]
    [PATHS path1 [path2 ... ENV var]]
    [VERSIONS version1 [version2]]
    [DOC "cache documentation string"]
    )
    +


    +

    This command is used to find a full path to the named jar. A cache entry named by <VAR> is created to stor the result of this command. If the full path to a jar is found the result is stored in the variable and the search will not repeated unless the variable is cleared. If nothing is found, the result will be <VAR>-NOTFOUND, and the search will be attempted again next time find_jar is invoked with the same variable. The name of the full path to a file that is searched for is specified by the names listed after NAMES argument. Additional search locations can be specified after the PATHS argument. If you require special a version of a jar file you can specify it with the VERSIONS argument. The argument after DOC will be used for the documentation string in the cache.

    +

    install_jar(TARGET_NAME DESTINATION)

    +

    This command installs the TARGET_NAME files to the given DESTINATION. It should be called in the same scope as add_jar() or it will fail.

    +

    install_jni_symlink(TARGET_NAME DESTINATION)

    +

    This command installs the TARGET_NAME JNI symlinks to the given DESTINATION. It should be called in the same scope as add_jar() or it will fail.

    +

    create_javadoc(<VAR>

    +
                    PACKAGES pkg1 [pkg2 ...]
    [SOURCEPATH <sourcepath>]
    [CLASSPATH <classpath>]
    [INSTALLPATH <install path>]
    [DOCTITLE "the documentation title"]
    [WINDOWTITLE "the title of the document"]
    [AUTHOR TRUE|FALSE]
    [USE TRUE|FALSE]
    [VERSION TRUE|FALSE]
    )
    +


    +

    Create jave documentation based on files or packages. For more details please read the javadoc manpage.

    +

    There are two main signatures for create_javadoc. The first signature works with package names on a path with source files:

    +
       Example:
    create_javadoc(my_example_doc
    PACKAGES com.exmaple.foo com.example.bar
    SOURCEPATH ${CMAKE_CURRENT_SOURCE_PATH}
    CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
    WINDOWTITLE "My example"
    DOCTITLE "<h1>My example</h1>"
    AUTHOR TRUE
    USE TRUE
    VERSION TRUE
    )
    +


    +

    The second signature for create_javadoc works on a given list of files.

    +
       create_javadoc(<VAR>
    FILES file1 [file2 ...]
    [CLASSPATH <classpath>]
    [INSTALLPATH <install path>]
    [DOCTITLE "the documentation title"]
    [WINDOWTITLE "the title of the document"]
    [AUTHOR TRUE|FALSE]
    [USE TRUE|FALSE]
    [VERSION TRUE|FALSE]
    )
    +


    +

    Example:

    +
       create_javadoc(my_example_doc
    FILES ${example_SRCS}
    CLASSPATH ${CMAKE_JAVA_INCLUDE_PATH}
    WINDOWTITLE "My example"
    DOCTITLE "<h1>My example</h1>"
    AUTHOR TRUE
    USE TRUE
    VERSION TRUE
    )
    +


    +

    Both signatures share most of the options. These options are the same as what you can find in the javadoc manpage. Please look at the manpage for CLASSPATH, DOCTITLE, WINDOWTITLE, AUTHOR, USE and VERSION.

    +

    The documentation will be by default installed to

    +
       ${CMAKE_INSTALL_PREFIX}/share/javadoc/<VAR>
    +


    +

    if you don't set the INSTALLPATH.

    + +
  • +
  • + UseJavaClassFilelist:
    +


    +

    This script create a list of compiled Java class files to be added to a jar file. This avoids including cmake files which get created in the binary directory.

    + +
  • +
  • + UseJavaSymlinks:
    +


    +

    Helper script for UseJava.cmake

    + +
  • +
  • + UsePkgConfig: Obsolete pkg-config module for CMake, use FindPkgConfig instead.
    +


    +

    This module defines the following macro:

    +

    PKGCONFIG(package includedir libdir linkflags cflags)

    +

    Calling PKGCONFIG will fill the desired information into the 4 given arguments, e.g. PKGCONFIG(libart-2.0 LIBART_INCLUDE_DIR LIBART_LINK_DIR LIBART_LINK_FLAGS LIBART_CFLAGS) if pkg-config was NOT found or the specified software package doesn't exist, the variable will be empty when the function returns, otherwise they will contain the respective information

    + +
  • +
  • + UseQt4: Use Module for QT4
    +

    Sets up C and C++ to use Qt 4. It is assumed that FindQt.cmake has already been loaded. See FindQt.cmake for information on how to load Qt 4 into your CMake project.

    + +
  • +
  • + UseSWIG: SWIG module for CMake
    +

    Defines the following macros:

    +
       SWIG_ADD_MODULE(name language [ files ])
    - Define swig module with given name and specified language
    SWIG_LINK_LIBRARIES(name [ libraries ])
    - Link libraries to swig module
    +

    All other macros are for internal use only. To get the actual name of the swig module, use: ${SWIG_MODULE_${name}_REAL_NAME}. Set Source files properties such as CPLUSPLUS and SWIG_FLAGS to specify special behavior of SWIG. Also global CMAKE_SWIG_FLAGS can be used to add special flags to all swig calls. Another special variable is CMAKE_SWIG_OUTDIR, it allows one to specify where to write all the swig generated module (swig -outdir option) The name-specific variable SWIG_MODULE_<name>_EXTRA_DEPS may be used to specify extra dependencies for the generated modules. If the source file generated by swig need some special flag you can use SET_SOURCE_FILES_PROPERTIES( ${swig_generated_file_fullname}

    +
            PROPERTIES COMPILE_FLAGS "-bla")
    + +
  • +
  • + Use_wxWindows: ---------------------------------------------------
    +


    +

    This convenience include finds if wxWindows is installed and set the appropriate libs, incdirs, flags etc. author Jan Woetzel <jw -at- mip.informatik.uni-kiel.de> (07/2003)

    +

    USAGE:

    +
       just include Use_wxWindows.cmake
    in your projects CMakeLists.txt
    +

    INCLUDE( ${CMAKE_MODULE_PATH}/Use_wxWindows.cmake)

    +
       if you are sure you need GL then
    +

    SET(WXWINDOWS_USE_GL 1)

    +
       *before* you include this file.
    + +
  • +
  • + UsewxWidgets: Convenience include for using wxWidgets library.
    +

    Determines if wxWidgets was FOUND and sets the appropriate libs, incdirs, flags, etc. INCLUDE_DIRECTORIES and LINK_DIRECTORIES are called.

    +

    USAGE

    +
      # Note that for MinGW users the order of libs is important!
    FIND_PACKAGE(wxWidgets REQUIRED net gl core base)
    INCLUDE(${wxWidgets_USE_FILE})
    # and for each of your dependent executable/library targets:
    TARGET_LINK_LIBRARIES(<YourTarget> ${wxWidgets_LIBRARIES})
    +


    +

    DEPRECATED

    +
      LINK_LIBRARIES is not called in favor of adding dependencies per target.
    +


    +

    AUTHOR

    +
      Jan Woetzel <jw -at- mip.informatik.uni-kiel.de>
    + +
  • +
  • + WriteBasicConfigVersionFile:
    +
      WRITE_BASIC_CONFIG_VERSION_FILE( filename VERSION major.minor.patch COMPATIBILITY (AnyNewerVersion|SameMajorVersion) )
    +


    +

    Writes a file for use as <package>ConfigVersion.cmake file to <filename>. See the documentation of FIND_PACKAGE() for details on this.

    +
        filename is the output filename, it should be in the build tree.
    major.minor.patch is the version number of the project to be installed
    +

    The COMPATIBILITY mode AnyNewerVersion means that the installed package version will be considered compatible if it is newer or exactly the same as the requested version. If SameMajorVersion is used instead, then the behaviour differs from AnyNewerVersion in that the major version number must be the same as requested, e.g. version 2.0 will not be considered compatible if 1.0 is requested. If your project has more elaborated version matching rules, you will need to write your own custom ConfigVersion.cmake file instead of using this macro.

    +

    Example:

    +
         write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
    VERSION 1.2.3
    COMPATIBILITY SameMajorVersion )
    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
    DESTINATION lib/cmake/Foo )
    +


    +

    Internally, this macro executes configure_file() to create the resulting version file. Depending on the COMPATIBLITY, either the file BasicConfigVersion-SameMajorVersion.cmake.in or BasicConfigVersion-AnyNewerVersion.cmake.in is used. Please note that these two files are internal to CMake and you should not call configure_file() on them yourself, but they can be used as starting point to create more sophisticted custom ConfigVersion.cmake files.

    + +
  • +
+

Policies

+ +
    +
  • + CMP0000: A minimum required CMake version must be specified.
    +

    CMake requires that projects specify the version of CMake to which they have been written. This policy has been put in place so users trying to build the project may be told when they need to update their CMake. Specifying a version also helps the project build with CMake versions newer than that specified. Use the cmake_minimum_required command at the top of your main CMakeLists.txt file:

    +
      cmake_minimum_required(VERSION <major>.<minor>)
    +

    where "<major>.<minor>" is the version of CMake you want to support (such as "2.6"). The command will ensure that at least the given version of CMake is running and help newer versions be compatible with the project. See documentation of cmake_minimum_required for details.

    +

    Note that the command invocation must appear in the CMakeLists.txt file itself; a call in an included file is not sufficient. However, the cmake_policy command may be called to set policy CMP0000 to OLD or NEW behavior explicitly. The OLD behavior is to silently ignore the missing invocation. The NEW behavior is to issue an error instead of a warning. An included file may set CMP0000 explicitly to affect how this policy is enforced for the main CMakeLists.txt file.

    +

    This policy was introduced in CMake version 2.6.0.

    + +
  • +
  • + CMP0001: CMAKE_BACKWARDS_COMPATIBILITY should no longer be used.
    +

    The OLD behavior is to check CMAKE_BACKWARDS_COMPATIBILITY and present it to the user. The NEW behavior is to ignore CMAKE_BACKWARDS_COMPATIBILITY completely.

    +

    In CMake 2.4 and below the variable CMAKE_BACKWARDS_COMPATIBILITY was used to request compatibility with earlier versions of CMake. In CMake 2.6 and above all compatibility issues are handled by policies and the cmake_policy command. However, CMake must still check CMAKE_BACKWARDS_COMPATIBILITY for projects written for CMake 2.4 and below.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0002: Logical target names must be globally unique.
    +

    Targets names created with add_executable, add_library, or add_custom_target are logical build target names. Logical target names must be globally unique because:

    +
      - Unique names may be referenced unambiguously both in CMake
    code and on make tool command lines.
    - Logical names are used by Xcode and VS IDE generators
    to produce meaningful project names for the targets.
    +

    The logical name of executable and library targets does not have to correspond to the physical file names built. Consider using the OUTPUT_NAME target property to create two targets with the same physical name while keeping logical names distinct. Custom targets must simply have globally unique names (unless one uses the global property ALLOW_DUPLICATE_CUSTOM_TARGETS with a Makefiles generator).

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0003: Libraries linked via full path no longer produce linker search paths.
    +

    This policy affects how libraries whose full paths are NOT known are found at link time, but was created due to a change in how CMake deals with libraries whose full paths are known. Consider the code

    +
      target_link_libraries(myexe /path/to/libA.so)
    +

    CMake 2.4 and below implemented linking to libraries whose full paths are known by splitting them on the link line into separate components consisting of the linker search path and the library name. The example code might have produced something like

    +
      ... -L/path/to -lA ...
    +

    in order to link to library A. An analysis was performed to order multiple link directories such that the linker would find library A in the desired location, but there are cases in which this does not work. CMake versions 2.6 and above use the more reliable approach of passing the full path to libraries directly to the linker in most cases. The example code now produces something like

    +
      ... /path/to/libA.so ....
    +

    Unfortunately this change can break code like

    +
      target_link_libraries(myexe /path/to/libA.so B)
    +

    where "B" is meant to find "/path/to/libB.so". This code is wrong because the user is asking the linker to find library B but has not provided a linker search path (which may be added with the link_directories command). However, with the old linking implementation the code would work accidentally because the linker search path added for library A allowed library B to be found.

    +

    In order to support projects depending on linker search paths added by linking to libraries with known full paths, the OLD behavior for this policy will add the linker search paths even though they are not needed for their own libraries. When this policy is set to OLD, CMake will produce a link line such as

    +
      ... -L/path/to /path/to/libA.so -lB ...
    +

    which will allow library B to be found as it was previously. When this policy is set to NEW, CMake will produce a link line such as

    +
      ... /path/to/libA.so -lB ...
    +

    which more accurately matches what the project specified.

    +

    The setting for this policy used when generating the link line is that in effect when the target is created by an add_executable or add_library command. For the example described above, the code

    +
      cmake_policy(SET CMP0003 OLD) # or cmake_policy(VERSION 2.4)
    add_executable(myexe myexe.c)
    target_link_libraries(myexe /path/to/libA.so B)
    +

    will work and suppress the warning for this policy. It may also be updated to work with the corrected linking approach:

    +
      cmake_policy(SET CMP0003 NEW) # or cmake_policy(VERSION 2.6)
    link_directories(/path/to) # needed to find library B
    add_executable(myexe myexe.c)
    target_link_libraries(myexe /path/to/libA.so B)
    +

    Even better, library B may be specified with a full path:

    +
      add_executable(myexe myexe.c)
    target_link_libraries(myexe /path/to/libA.so /path/to/libB.so)
    +

    When all items on the link line have known paths CMake does not check this policy so it has no effect.

    +

    Note that the warning for this policy will be issued for at most one target. This avoids flooding users with messages for every target when setting the policy once will probably fix all targets.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0004: Libraries linked may not have leading or trailing whitespace.
    +

    CMake versions 2.4 and below silently removed leading and trailing whitespace from libraries linked with code like

    +
      target_link_libraries(myexe " A ")
    +

    This could lead to subtle errors in user projects.

    +

    The OLD behavior for this policy is to silently remove leading and trailing whitespace. The NEW behavior for this policy is to diagnose the existence of such whitespace as an error. The setting for this policy used when checking the library names is that in effect when the target is created by an add_executable or add_library command.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0005: Preprocessor definition values are now escaped automatically.
    +

    This policy determines whether or not CMake should generate escaped preprocessor definition values added via add_definitions. CMake versions 2.4 and below assumed that only trivial values would be given for macros in add_definitions calls. It did not attempt to escape non-trivial values such as string literals in generated build rules. CMake versions 2.6 and above support escaping of most values, but cannot assume the user has not added escapes already in an attempt to work around limitations in earlier versions.

    +

    The OLD behavior for this policy is to place definition values given to add_definitions directly in the generated build rules without attempting to escape anything. The NEW behavior for this policy is to generate correct escapes for all native build tools automatically. See documentation of the COMPILE_DEFINITIONS target property for limitations of the escaping implementation.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0006: Installing MACOSX_BUNDLE targets requires a BUNDLE DESTINATION.
    +

    This policy determines whether the install(TARGETS) command must be given a BUNDLE DESTINATION when asked to install a target with the MACOSX_BUNDLE property set. CMake 2.4 and below did not distinguish application bundles from normal executables when installing targets. CMake 2.6 provides a BUNDLE option to the install(TARGETS) command that specifies rules specific to application bundles on the Mac. Projects should use this option when installing a target with the MACOSX_BUNDLE property set.

    +

    The OLD behavior for this policy is to fall back to the RUNTIME DESTINATION if a BUNDLE DESTINATION is not given. The NEW behavior for this policy is to produce an error if a bundle target is installed without a BUNDLE DESTINATION.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0007: list command no longer ignores empty elements.
    +

    This policy determines whether the list command will ignore empty elements in the list. CMake 2.4 and below list commands ignored all empty elements in the list. For example, a;b;;c would have length 3 and not 4. The OLD behavior for this policy is to ignore empty list elements. The NEW behavior for this policy is to correctly count empty elements in a list.

    +

    This policy was introduced in CMake version 2.6.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0008: Libraries linked by full-path must have a valid library file name.
    +

    In CMake 2.4 and below it is possible to write code like

    +
      target_link_libraries(myexe /full/path/to/somelib)
    +

    where "somelib" is supposed to be a valid library file name such as "libsomelib.a" or "somelib.lib". For Makefile generators this produces an error at build time because the dependency on the full path cannot be found. For VS IDE and Xcode generators this used to work by accident because CMake would always split off the library directory and ask the linker to search for the library by name (-lsomelib or somelib.lib). Despite the failure with Makefiles, some projects have code like this and build only with VS and/or Xcode. This version of CMake prefers to pass the full path directly to the native build tool, which will fail in this case because it does not name a valid library file.

    +

    This policy determines what to do with full paths that do not appear to name a valid library file. The OLD behavior for this policy is to split the library name from the path and ask the linker to search for it. The NEW behavior for this policy is to trust the given path and pass it directly to the native build tool unchanged.

    +

    This policy was introduced in CMake version 2.6.1. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0009: FILE GLOB_RECURSE calls should not follow symlinks by default.
    +

    In CMake 2.6.1 and below, FILE GLOB_RECURSE calls would follow through symlinks, sometimes coming up with unexpectedly large result sets because of symlinks to top level directories that contain hundreds of thousands of files.

    +

    This policy determines whether or not to follow symlinks encountered during a FILE GLOB_RECURSE call. The OLD behavior for this policy is to follow the symlinks. The NEW behavior for this policy is not to follow the symlinks by default, but only if FOLLOW_SYMLINKS is given as an additional argument to the FILE command.

    +

    This policy was introduced in CMake version 2.6.2. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0010: Bad variable reference syntax is an error.
    +

    In CMake 2.6.2 and below, incorrect variable reference syntax such as a missing close-brace ("${FOO") was reported but did not stop processing of CMake code. This policy determines whether a bad variable reference is an error. The OLD behavior for this policy is to warn about the error, leave the string untouched, and continue. The NEW behavior for this policy is to report an error.

    +

    This policy was introduced in CMake version 2.6.3. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0011: Included scripts do automatic cmake_policy PUSH and POP.
    +

    In CMake 2.6.2 and below, CMake Policy settings in scripts loaded by the include() and find_package() commands would affect the includer. Explicit invocations of cmake_policy(PUSH) and cmake_policy(POP) were required to isolate policy changes and protect the includer. While some scripts intend to affect the policies of their includer, most do not. In CMake 2.6.3 and above, include() and find_package() by default PUSH and POP an entry on the policy stack around an included script, but provide a NO_POLICY_SCOPE option to disable it. This policy determines whether or not to imply NO_POLICY_SCOPE for compatibility. The OLD behavior for this policy is to imply NO_POLICY_SCOPE for include() and find_package() commands. The NEW behavior for this policy is to allow the commands to do their default cmake_policy PUSH and POP.

    +

    This policy was introduced in CMake version 2.6.3. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0012: if() recognizes numbers and boolean constants.
    +

    In CMake versions 2.6.4 and lower the if() command implicitly dereferenced arguments corresponding to variables, even those named like numbers or boolean constants, except for 0 and 1. Numbers and boolean constants such as true, false, yes, no, on, off, y, n, notfound, ignore (all case insensitive) were recognized in some cases but not all. For example, the code "if(TRUE)" might have evaluated as false. Numbers such as 2 were recognized only in boolean expressions like "if(NOT 2)" (leading to false) but not as a single-argument like "if(2)" (also leading to false). Later versions of CMake prefer to treat numbers and boolean constants literally, so they should not be used as variable names.

    +

    The OLD behavior for this policy is to implicitly dereference variables named like numbers and boolean constants. The NEW behavior for this policy is to recognize numbers and boolean constants without dereferencing variables with such names.

    +

    This policy was introduced in CMake version 2.8.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0013: Duplicate binary directories are not allowed.
    +

    CMake 2.6.3 and below silently permitted add_subdirectory() calls to create the same binary directory multiple times. During build system generation files would be written and then overwritten in the build tree and could lead to strange behavior. CMake 2.6.4 and above explicitly detect duplicate binary directories. CMake 2.6.4 always considers this case an error. In CMake 2.8.0 and above this policy determines whether or not the case is an error. The OLD behavior for this policy is to allow duplicate binary directories. The NEW behavior for this policy is to disallow duplicate binary directories with an error.

    +

    This policy was introduced in CMake version 2.8.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0014: Input directories must have CMakeLists.txt.
    +

    CMake versions before 2.8 silently ignored missing CMakeLists.txt files in directories referenced by add_subdirectory() or subdirs(), treating them as if present but empty. In CMake 2.8.0 and above this policy determines whether or not the case is an error. The OLD behavior for this policy is to silently ignore the problem. The NEW behavior for this policy is to report an error.

    +

    This policy was introduced in CMake version 2.8.0. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0015: link_directories() treats paths relative to the source dir.
    +

    In CMake 2.8.0 and lower the link_directories() command passed relative paths unchanged to the linker. In CMake 2.8.1 and above the link_directories() command prefers to interpret relative paths with respect to CMAKE_CURRENT_SOURCE_DIR, which is consistent with include_directories() and other commands. The OLD behavior for this policy is to use relative paths verbatim in the linker command. The NEW behavior for this policy is to convert relative paths to absolute paths by appending the relative path to CMAKE_CURRENT_SOURCE_DIR.

    +

    This policy was introduced in CMake version 2.8.1. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0016: target_link_libraries() reports error if only argument is not a target.
    +

    In CMake 2.8.2 and lower the target_link_libraries() command silently ignored if it was called with only one argument, and this argument wasn't a valid target. In CMake 2.8.3 and above it reports an error in this case.

    +

    This policy was introduced in CMake version 2.8.3. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
  • + CMP0017: Prefer files from the CMake module directory when including from there.
    +

    Starting with CMake 2.8.4, if a cmake-module shipped with CMake (i.e. located in the CMake module directory) calls include() or find_package(), the files located in the the CMake module directory are preferred over the files in CMAKE_MODULE_PATH. This makes sure that the modules belonging to CMake always get those files included which they expect, and against which they were developed and tested. In call other cases, the files found in CMAKE_MODULE_PATH still take precedence over the ones in the CMake module directory. The OLD behaviour is to always prefer files from CMAKE_MODULE_PATH over files from the CMake modules directory.

    +

    This policy was introduced in CMake version 2.8.4. CMake version 2.8.7 warns when the policy is not set and uses OLD behavior. Use the cmake_policy command to set it to OLD or NEW explicitly.

    + +
  • +
+

Variables

+

Variables That Change Behavior

+ +
    +
  • + BUILD_SHARED_LIBS: Global flag to cause add_library to create shared libraries if on.
    +

    If present and true, this will cause all libraries to be built shared unless the library was explicitly added as a static library. This variable is often added to projects as an OPTION so that each user of a project can decide if they want to build the project using shared or static libraries.

    + +
  • +
  • + CMAKE_AUTOMOC_RELAXED_MODE: Switch between strict and relaxed automoc mode.
    +

    By default, automoc behaves exactly as described in the documentation of the AUTOMOC target property. When set to TRUE, it accepts more input and tries to find the correct input file for moc even if it differs from the documented behaviour. In this mode it e.g. also checks whether a header file is intended to be processed by moc when a "foo.moc" file has been included.

    +

    Relaxed mode has to be enabled for KDE4 compatibility.

    + +
  • +
  • + CMAKE_BACKWARDS_COMPATIBILITY: Version of cmake required to build project
    +

    From the point of view of backwards compatibility, this specifies what version of CMake should be supported. By default this value is the version number of CMake that you are running. You can set this to an older version of CMake to support deprecated commands of CMake in projects that were written to use older versions of CMake. This can be set by the user or set at the beginning of a CMakeLists file.

    + +
  • +
  • + CMAKE_BUILD_TYPE: Specifies the build type for make based generators.
    +

    This specifies what build type will be built in this tree. Possible values are empty, Debug, Release, RelWithDebInfo and MinSizeRel. This variable is only supported for make based generators. If this variable is supported, then CMake will also provide initial values for the variables with the name CMAKE_C_FLAGS_[DEBUG|RELEASE|RELWITHDEBINFO|MINSIZEREL]. For example, if CMAKE_BUILD_TYPE is Debug, then CMAKE_C_FLAGS_DEBUG will be added to the CMAKE_C_FLAGS.

    + +
  • +
  • + CMAKE_COLOR_MAKEFILE: Enables color output when using the Makefile generator.
    +

    When enabled, the generated Makefiles will produce colored output. Default is ON.

    + +
  • +
  • + CMAKE_CONFIGURATION_TYPES: Specifies the available build types.
    +

    This specifies what build types will be available such as Debug, Release, RelWithDebInfo etc. This has reasonable defaults on most platforms. But can be extended to provide other build types. See also CMAKE_BUILD_TYPE.

    + +
  • +
  • + CMAKE_DISABLE_FIND_PACKAGE_<PackageName>: Variable for disabling find_package() calls.
    +

    Every non-REQUIRED find_package() call in a project can be disabled by setting the variable CMAKE_DISABLE_FIND_PACKAGE_<PackageName> to TRUE. This can be used to build a project without an optional package, although that package is installed.

    +

    This switch should be used during the initial CMake run. Otherwise if the package has already been found in a previous CMake run, the variables which have been stored in the cache will still be there. In the case it is recommended to remove the cache variables for this package from the cache using the cache editor or cmake -U

    + +
  • +
  • + CMAKE_FIND_LIBRARY_PREFIXES: Prefixes to prepend when looking for libraries.
    +

    This specifies what prefixes to add to library names when the find_library command looks for libraries. On UNIX systems this is typically lib, meaning that when trying to find the foo library it will look for libfoo.

    + +
  • +
  • + CMAKE_FIND_LIBRARY_SUFFIXES: Suffixes to append when looking for libraries.
    +

    This specifies what suffixes to add to library names when the find_library command looks for libraries. On Windows systems this is typically .lib and .dll, meaning that when trying to find the foo library it will look for foo.dll etc.

    + +
  • +
  • + CMAKE_IGNORE_PATH: Path to be ignored by FIND_XXX() commands.
    +

    Specifies directories to be ignored by searches in FIND_XXX() commands This is useful in cross-compiled environments where some system directories contain incompatible but possibly linkable libraries. For example, on cross-compiled cluster environments, this allows a user to ignore directories containing libraries meant for the front-end machine that modules like FindX11 (and others) would normally search. By default this is empty; it is intended to be set by the project. Note that CMAKE_IGNORE_PATH takes a list of directory names, NOT a list of prefixes. If you want to ignore paths under prefixes (bin, include, lib, etc.), you'll need to specify them explicitly. See also CMAKE_PREFIX_PATH, CMAKE_LIBRARY_PATH, CMAKE_INCLUDE_PATH, CMAKE_PROGRAM_PATH.

    + +
  • +
  • + CMAKE_INCLUDE_PATH: Path used for searching by FIND_FILE() and FIND_PATH().
    +

    Specifies a path which will be used both by FIND_FILE() and FIND_PATH(). Both commands will check each of the contained directories for the existence of the file which is currently searched. By default it is empty, it is intended to be set by the project. See also CMAKE_SYSTEM_INCLUDE_PATH, CMAKE_PREFIX_PATH.

    + +
  • +
  • + CMAKE_INSTALL_PREFIX: Install directory used by install.
    +

    If "make install" is invoked or INSTALL is built, this directory is pre-pended onto all install directories. This variable defaults to /usr/local on UNIX and c:/Program Files on Windows.

    + +
  • +
  • + CMAKE_LIBRARY_PATH: Path used for searching by FIND_LIBRARY().
    +

    Specifies a path which will be used by FIND_LIBRARY(). FIND_LIBRARY() will check each of the contained directories for the existence of the library which is currently searched. By default it is empty, it is intended to be set by the project. See also CMAKE_SYSTEM_LIBRARY_PATH, CMAKE_PREFIX_PATH.

    + +
  • +
  • + CMAKE_MFC_FLAG: Tell cmake to use MFC for an executable or dll.
    +

    This can be set in a CMakeLists.txt file and will enable MFC in the application. It should be set to 1 for static the static MFC library, and 2 for the shared MFC library. This is used in visual studio 6 and 7 project files. The CMakeSetup dialog used MFC and the CMakeLists.txt looks like this:

    +

    add_definitions(-D_AFXDLL)

    +

    set(CMAKE_MFC_FLAG 2)

    +

    add_executable(CMakeSetup WIN32 ${SRCS})

    + +
  • +
  • + CMAKE_MODULE_PATH: List of directories to search for CMake modules.
    +

    Commands like include() and find_package() search for files in directories listed by this variable before checking the default modules that come with CMake.

    + +
  • +
  • + CMAKE_NOT_USING_CONFIG_FLAGS: Skip _BUILD_TYPE flags if true.
    +

    This is an internal flag used by the generators in CMake to tell CMake to skip the _BUILD_TYPE flags.

    + +
  • +
  • + CMAKE_POLICY_DEFAULT_CMP<NNNN>: Default for CMake Policy CMP<NNNN> when it is otherwise left unset.
    +

    Commands cmake_minimum_required(VERSION) and cmake_policy(VERSION) by default leave policies introduced after the given version unset. Set CMAKE_POLICY_DEFAULT_CMP<NNNN> to OLD or NEW to specify the default for policy CMP<NNNN>, where <NNNN> is the policy number.

    +

    This variable should not be set by a project in CMake code; use cmake_policy(SET) instead. Users running CMake may set this variable in the cache (e.g. -DCMAKE_POLICY_DEFAULT_CMP<NNNN>=<OLD|NEW>) to set a policy not otherwise set by the project. Set to OLD to quiet a policy warning while using old behavior or to NEW to try building the project with new behavior.

    + +
  • +
  • + CMAKE_PREFIX_PATH: Path used for searching by FIND_XXX(), with appropriate suffixes added.
    +

    Specifies a path which will be used by the FIND_XXX() commands. It contains the "base" directories, the FIND_XXX() commands append appropriate subdirectories to the base directories. So FIND_PROGRAM() adds /bin to each of the directories in the path, FIND_LIBRARY() appends /lib to each of the directories, and FIND_PATH() and FIND_FILE() append /include . By default it is empty, it is intended to be set by the project. See also CMAKE_SYSTEM_PREFIX_PATH, CMAKE_INCLUDE_PATH, CMAKE_LIBRARY_PATH, CMAKE_PROGRAM_PATH.

    + +
  • +
  • + CMAKE_PROGRAM_PATH: Path used for searching by FIND_PROGRAM().
    +

    Specifies a path which will be used by FIND_PROGRAM(). FIND_PROGRAM() will check each of the contained directories for the existence of the program which is currently searched. By default it is empty, it is intended to be set by the project. See also CMAKE_SYSTEM_PROGRAM_PATH, CMAKE_PREFIX_PATH.

    + +
  • +
  • + CMAKE_SKIP_INSTALL_ALL_DEPENDENCY: Don't make the install target depend on the all target.
    +

    By default, the "install" target depends on the "all" target. This has the effect, that when "make install" is invoked or INSTALL is built, first the "all" target is built, then the installation starts. If CMAKE_SKIP_INSTALL_ALL_DEPENDENCY is set to TRUE, this dependency is not created, so the installation process will start immediately, independent from whether the project has been completely built or not.

    + +
  • +
  • + CMAKE_SYSTEM_IGNORE_PATH: Path to be ignored by FIND_XXX() commands.
    +

    Specifies directories to be ignored by searches in FIND_XXX() commands This is useful in cross-compiled environments where some system directories contain incompatible but possibly linkable libraries. For example, on cross-compiled cluster environments, this allows a user to ignore directories containing libraries meant for the front-end machine that modules like FindX11 (and others) would normally search. By default this contains a list of directories containing incompatible binaries for the host system. See also CMAKE_SYSTEM_PREFIX_PATH, CMAKE_SYSTEM_LIBRARY_PATH, CMAKE_SYSTEM_INCLUDE_PATH, and CMAKE_SYSTEM_PROGRAM_PATH.

    + +
  • +
  • + CMAKE_SYSTEM_INCLUDE_PATH: Path used for searching by FIND_FILE() and FIND_PATH().
    +

    Specifies a path which will be used both by FIND_FILE() and FIND_PATH(). Both commands will check each of the contained directories for the existence of the file which is currently searched. By default it contains the standard directories for the current system. It is NOT intended to be modified by the project, use CMAKE_INCLUDE_PATH for this. See also CMAKE_SYSTEM_PREFIX_PATH.

    + +
  • +
  • + CMAKE_SYSTEM_LIBRARY_PATH: Path used for searching by FIND_LIBRARY().
    +

    Specifies a path which will be used by FIND_LIBRARY(). FIND_LIBRARY() will check each of the contained directories for the existence of the library which is currently searched. By default it contains the standard directories for the current system. It is NOT intended to be modified by the project, use CMAKE_LIBRARY_PATH for this. See also CMAKE_SYSTEM_PREFIX_PATH.

    + +
  • +
  • + CMAKE_SYSTEM_PREFIX_PATH: Path used for searching by FIND_XXX(), with appropriate suffixes added.
    +

    Specifies a path which will be used by the FIND_XXX() commands. It contains the "base" directories, the FIND_XXX() commands append appropriate subdirectories to the base directories. So FIND_PROGRAM() adds /bin to each of the directories in the path, FIND_LIBRARY() appends /lib to each of the directories, and FIND_PATH() and FIND_FILE() append /include . By default this contains the standard directories for the current system. It is NOT intended to be modified by the project, use CMAKE_PREFIX_PATH for this. See also CMAKE_SYSTEM_INCLUDE_PATH, CMAKE_SYSTEM_LIBRARY_PATH, CMAKE_SYSTEM_PROGRAM_PATH, and CMAKE_SYSTEM_IGNORE_PATH.

    + +
  • +
  • + CMAKE_SYSTEM_PROGRAM_PATH: Path used for searching by FIND_PROGRAM().
    +

    Specifies a path which will be used by FIND_PROGRAM(). FIND_PROGRAM() will check each of the contained directories for the existence of the program which is currently searched. By default it contains the standard directories for the current system. It is NOT intended to be modified by the project, use CMAKE_PROGRAM_PATH for this. See also CMAKE_SYSTEM_PREFIX_PATH.

    + +
  • +
  • + CMAKE_USER_MAKE_RULES_OVERRIDE: Specify a CMake file that overrides platform information.
    +

    CMake loads the specified file while enabling support for each language from either the project() or enable_language() commands. It is loaded after CMake's builtin compiler and platform information modules have been loaded but before the information is used. The file may set platform information variables to override CMake's defaults.

    +

    This feature is intended for use only in overriding information variables that must be set before CMake builds its first test project to check that the compiler for a language works. It should not be used to load a file in cases that a normal include() will work. Use it only as a last resort for behavior that cannot be achieved any other way. For example, one may set CMAKE_C_FLAGS_INIT to change the default value used to initialize CMAKE_C_FLAGS before it is cached. The override file should NOT be used to set anything that could be set after languages are enabled, such as variables like CMAKE_RUNTIME_OUTPUT_DIRECTORY that affect the placement of binaries. Information set in the file will be used for try_compile and try_run builds too.

    + +
  • +
+

Variables That Describe the System

+ +
    +
  • + APPLE: True if running on Mac OSX.
    +

    Set to true on Mac OSX.

    + +
  • +
  • + BORLAND: True of the borland compiler is being used.
    +

    This is set to true if the Borland compiler is being used.

    + +
  • +
  • + CMAKE_CL_64: Using the 64 bit compiler from Microsoft
    +

    Set to true when using the 64 bit cl compiler from Microsoft.

    + +
  • +
  • + CMAKE_COMPILER_2005: Using the Visual Studio 2005 compiler from Microsoft
    +

    Set to true when using the Visual Studio 2005 compiler from Microsoft.

    + +
  • +
  • + CMAKE_HOST_APPLE: True for Apple OSXoperating systems.
    +

    Set to true when the host system is Apple OSX.

    + +
  • +
  • + CMAKE_HOST_SYSTEM: Name of system cmake is being run on.
    +

    The same as CMAKE_SYSTEM but for the host system instead of the target system when cross compiling.

    + +
  • +
  • + CMAKE_HOST_SYSTEM_NAME: Name of the OS CMake is running on.
    +

    The same as CMAKE_SYSTEM_NAME but for the host system instead of the target system when cross compiling.

    + +
  • +
  • + CMAKE_HOST_SYSTEM_PROCESSOR: The name of the CPU CMake is running on.
    +

    The same as CMAKE_SYSTEM_PROCESSOR but for the host system instead of the target system when cross compiling.

    + +
  • +
  • + CMAKE_HOST_SYSTEM_VERSION: OS version CMake is running on.
    +

    The same as CMAKE_SYSTEM_VERSION but for the host system instead of the target system when cross compiling.

    + +
  • +
  • + CMAKE_HOST_UNIX: True for UNIX and UNIX like operating systems.
    +

    Set to true when the host system is UNIX or UNIX like (i.e. APPLE and CYGWIN).

    + +
  • +
  • + CMAKE_HOST_WIN32: True on windows systems, including win64.
    +

    Set to true when the host system is Windows and on cygwin.

    + +
  • +
  • + CMAKE_LIBRARY_ARCHITECTURE: Target architecture library directory name, if detected.
    +

    This is the value of CMAKE_<lang>_LIBRARY_ARCHITECTURE as detected for one of the enabled languages.

    + +
  • +
  • + CMAKE_LIBRARY_ARCHITECTURE_REGEX: Regex matching possible target architecture library directory names.
    +

    This is used to detect CMAKE_<lang>_LIBRARY_ARCHITECTURE from the implicit linker search path by matching the <arch> name.

    + +
  • +
  • + CMAKE_OBJECT_PATH_MAX: Maximum object file full-path length allowed by native build tools.
    +

    CMake computes for every source file an object file name that is unique to the source file and deterministic with respect to the full path to the source file. This allows multiple source files in a target to share the same name if they lie in different directories without rebuilding when one is added or removed. However, it can produce long full paths in a few cases, so CMake shortens the path using a hashing scheme when the full path to an object file exceeds a limit. CMake has a built-in limit for each platform that is sufficient for common tools, but some native tools may have a lower limit. This variable may be set to specify the limit explicitly. The value must be an integer no less than 128.

    + +
  • +
  • + CMAKE_SYSTEM: Name of system cmake is compiling for.
    +

    This variable is the composite of CMAKE_SYSTEM_NAME and CMAKE_SYSTEM_VERSION, like this ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_VERSION}. If CMAKE_SYSTEM_VERSION is not set, then CMAKE_SYSTEM is the same as CMAKE_SYSTEM_NAME.

    + +
  • +
  • + CMAKE_SYSTEM_NAME: Name of the OS CMake is building for.
    +

    This is the name of the operating system on which CMake is targeting. On systems that have the uname command, this variable is set to the output of uname -s. Linux, Windows, and Darwin for Mac OSX are the values found on the big three operating systems.

    + +
  • +
  • + CMAKE_SYSTEM_PROCESSOR: The name of the CPU CMake is building for.
    +

    On systems that support uname, this variable is set to the output of uname -p, on windows it is set to the value of the environment variable PROCESSOR_ARCHITECTURE

    + +
  • +
  • + CMAKE_SYSTEM_VERSION: OS version CMake is building for.
    +

    A numeric version string for the system, on systems that support uname, this variable is set to the output of uname -r. On other systems this is set to major-minor version numbers.

    + +
  • +
  • + CYGWIN: True for cygwin.
    +

    Set to true when using CYGWIN.

    + +
  • +
  • + MSVC: True when using Microsoft Visual C
    +

    Set to true when the compiler is some version of Microsoft Visual C.

    + +
  • +
  • + MSVC80: True when using Microsoft Visual C 8.0
    +

    Set to true when the compiler is version 8.0 of Microsoft Visual C.

    + +
  • +
  • + MSVC_IDE: True when using the Microsoft Visual C IDE
    +

    Set to true when the target platform is the Microsoft Visual C IDE, as opposed to the command line compiler.

    + +
  • +
  • + MSVC_VERSION: The version of Microsoft Visual C/C++ being used if any.
    +

    Known version numbers are:

    +
      1200 = VS  6.0
    1300 = VS 7.0
    1310 = VS 7.1
    1400 = VS 8.0
    1500 = VS 9.0
    1600 = VS 10.0
    + +
  • +
  • + UNIX: True for UNIX and UNIX like operating systems.
    +

    Set to true when the target system is UNIX or UNIX like (i.e. APPLE and CYGWIN).

    + +
  • +
  • + WIN32: True on windows systems, including win64.
    +

    Set to true when the target system is Windows.

    + +
  • +
  • + XCODE_VERSION: Version of Xcode (Xcode generator only).
    +

    Under the Xcode generator, this is the version of Xcode as specified in "Xcode.app/Contents/version.plist" (such as "3.1.2").

    + +
  • +
+

Variables for Languages

+ +
    +
  • + CMAKE_<LANG>_ARCHIVE_APPEND: Rule variable to append to a static archive.
    +

    This is a rule variable that tells CMake how to append to a static archive. It is used in place of CMAKE_<LANG>_CREATE_STATIC_LIBRARY on some platforms in order to support large object counts. See also CMAKE_<LANG>_ARCHIVE_CREATE and CMAKE_<LANG>_ARCHIVE_FINISH.

    + +
  • +
  • + CMAKE_<LANG>_ARCHIVE_CREATE: Rule variable to create a new static archive.
    +

    This is a rule variable that tells CMake how to create a static archive. It is used in place of CMAKE_<LANG>_CREATE_STATIC_LIBRARY on some platforms in order to support large object counts. See also CMAKE_<LANG>_ARCHIVE_APPEND and CMAKE_<LANG>_ARCHIVE_FINISH.

    + +
  • +
  • + CMAKE_<LANG>_ARCHIVE_FINISH: Rule variable to finish an existing static archive.
    +

    This is a rule variable that tells CMake how to finish a static archive. It is used in place of CMAKE_<LANG>_CREATE_STATIC_LIBRARY on some platforms in order to support large object counts. See also CMAKE_<LANG>_ARCHIVE_CREATE and CMAKE_<LANG>_ARCHIVE_APPEND.

    + +
  • +
  • + CMAKE_<LANG>_COMPILER: The full path to the compiler for LANG.
    +

    This is the command that will be used as the <LANG> compiler. Once set, you can not change this variable.

    + +
  • +
  • + CMAKE_<LANG>_COMPILER_ABI: An internal variable subject to change.
    +

    This is used in determining the compiler ABI and is subject to change.

    + +
  • +
  • + CMAKE_<LANG>_COMPILER_ID: An internal variable subject to change.
    +

    This is used in determining the compiler and is subject to change.

    + +
  • +
  • + CMAKE_<LANG>_COMPILER_LOADED: Defined to true if the language is enabled.
    +

    When language <LANG> is enabled by project() or enable_language() this variable is defined to 1.

    + +
  • +
  • + CMAKE_<LANG>_COMPILE_OBJECT: Rule variable to compile a single object file.
    +

    This is a rule variable that tells CMake how to compile a single object file for for the language <LANG>.

    + +
  • +
  • + CMAKE_<LANG>_CREATE_SHARED_LIBRARY: Rule variable to create a shared library.
    +

    This is a rule variable that tells CMake how to create a shared library for the language <LANG>.

    + +
  • +
  • + CMAKE_<LANG>_CREATE_SHARED_MODULE: Rule variable to create a shared module.
    +

    This is a rule variable that tells CMake how to create a shared library for the language <LANG>.

    + +
  • +
  • + CMAKE_<LANG>_CREATE_STATIC_LIBRARY: Rule variable to create a static library.
    +

    This is a rule variable that tells CMake how to create a static library for the language <LANG>.

    + +
  • +
  • + CMAKE_<LANG>_FLAGS_DEBUG: Flags for Debug build type or configuration.
    +

    <LANG> flags used when CMAKE_BUILD_TYPE is Debug.

    + +
  • +
  • + CMAKE_<LANG>_FLAGS_MINSIZEREL: Flags for MinSizeRel build type or configuration.
    +

    <LANG> flags used when CMAKE_BUILD_TYPE is MinSizeRel.Short for minimum size release.

    + +
  • +
  • + CMAKE_<LANG>_FLAGS_RELEASE: Flags for Release build type or configuration.
    +

    <LANG> flags used when CMAKE_BUILD_TYPE is Release

    + +
  • +
  • + CMAKE_<LANG>_FLAGS_RELWITHDEBINFO: Flags for RelWithDebInfo type or configuration.
    +

    <LANG> flags used when CMAKE_BUILD_TYPE is RelWithDebInfo. Short for Release With Debug Information.

    + +
  • +
  • + CMAKE_<LANG>_IGNORE_EXTENSIONS: File extensions that should be ignored by the build.
    +

    This is a list of file extensions that may be part of a project for a given language but are not compiled.

    + +
  • +
  • + CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES: Directories implicitly searched by the compiler for header files.
    +

    CMake does not explicitly specify these directories on compiler command lines for language <LANG>. This prevents system include directories from being treated as user include directories on some compilers.

    + +
  • +
  • + CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES: Implicit linker search path detected for language <LANG>.
    +

    Compilers typically pass directories containing language runtime libraries and default library search paths when they invoke a linker. These paths are implicit linker search directories for the compiler's language. CMake automatically detects these directories for each language and reports the results in this variable.

    + +
  • +
  • + CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES: Implicit link libraries and flags detected for language <LANG>.
    +

    Compilers typically pass language runtime library names and other flags when they invoke a linker. These flags are implicit link options for the compiler's language. CMake automatically detects these libraries and flags for each language and reports the results in this variable.

    + +
  • +
  • + CMAKE_<LANG>_LIBRARY_ARCHITECTURE: Target architecture library directory name detected for <lang>.
    +

    If the <lang> compiler passes to the linker an architecture-specific system library search directory such as <prefix>/lib/<arch> this variable contains the <arch> name if/as detected by CMake.

    + +
  • +
  • + CMAKE_<LANG>_LINKER_PREFERENCE: Preference value for linker language selection.
    +

    The "linker language" for executable, shared library, and module targets is the language whose compiler will invoke the linker. The LINKER_LANGUAGE target property sets the language explicitly. Otherwise, the linker language is that whose linker preference value is highest among languages compiled and linked into the target. See also the CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES variable.

    + +
  • +
  • + CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES: True if CMAKE_<LANG>_LINKER_PREFERENCE propagates across targets.
    +

    This is used when CMake selects a linker language for a target. Languages compiled directly into the target are always considered. A language compiled into static libraries linked by the target is considered if this variable is true.

    + +
  • +
  • + CMAKE_<LANG>_LINK_EXECUTABLE : Rule variable to link and executable.
    +

    Rule variable to link and executable for the given language.

    + +
  • +
  • + CMAKE_<LANG>_OUTPUT_EXTENSION: Extension for the output of a compile for a single file.
    +

    This is the extension for an object file for the given <LANG>. For example .obj for C on Windows.

    + +
  • +
  • + CMAKE_<LANG>_PLATFORM_ID: An internal variable subject to change.
    +

    This is used in determining the platform and is subject to change.

    + +
  • +
  • + CMAKE_<LANG>_SIZEOF_DATA_PTR: Size of pointer-to-data types for language <LANG>.
    +

    This holds the size (in bytes) of pointer-to-data types in the target platform ABI. It is defined for languages C and CXX (C++).

    + +
  • +
  • + CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS: Extensions of source files for the given language.
    +

    This is the list of extensions for a given languages source files.

    + +
  • +
  • + CMAKE_COMPILER_IS_GNU<LANG>: True if the compiler is GNU.
    +

    If the selected <LANG> compiler is the GNU compiler then this is TRUE, if not it is FALSE.

    + +
  • +
  • + CMAKE_Fortran_MODDIR_DEFAULT: Fortran default module output directory.
    +

    Most Fortran compilers write .mod files to the current working directory. For those that do not, this is set to "." and used when the Fortran_MODULE_DIRECTORY target property is not set.

    + +
  • +
  • + CMAKE_Fortran_MODDIR_FLAG: Fortran flag for module output directory.
    +

    This stores the flag needed to pass the value of the Fortran_MODULE_DIRECTORY target property to the compiler.

    + +
  • +
  • + CMAKE_Fortran_MODOUT_FLAG: Fortran flag to enable module output.
    +

    Most Fortran compilers write .mod files out by default. For others, this stores the flag needed to enable module output.

    + +
  • +
  • + CMAKE_INTERNAL_PLATFORM_ABI: An internal variable subject to change.
    +

    This is used in determining the compiler ABI and is subject to change.

    + +
  • +
  • + CMAKE_USER_MAKE_RULES_OVERRIDE_<LANG>: Specify a CMake file that overrides platform information for <LANG>.
    +

    This is a language-specific version of CMAKE_USER_MAKE_RULES_OVERRIDE loaded only when enabling language <LANG>.

    + +
  • +
+

Variables that Control the Build

+ +
    +
  • + CMAKE_<CONFIG>_POSTFIX: Default filename postfix for libraries under configuration <CONFIG>.
    +

    When a non-executable target is created its <CONFIG>_POSTFIX target property is initialized with the value of this variable if it is set.

    + +
  • +
  • + CMAKE_ARCHIVE_OUTPUT_DIRECTORY: Where to put all the ARCHIVE targets when built.
    +

    This variable is used to initialize the ARCHIVE_OUTPUT_DIRECTORY property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_AUTOMOC: Whether to handle moc automatically for Qt targets.
    +

    This variable is used to initialize the AUTOMOC property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_AUTOMOC_MOC_OPTIONS: Additional options for moc when using automoc (see CMAKE_AUTOMOC).
    +

    This variable is used to initialize the AUTOMOC_MOC_OPTIONS property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_BUILD_WITH_INSTALL_RPATH: Use the install path for the RPATH
    +

    Normally CMake uses the build tree for the RPATH when building executables etc on systems that use RPATH. When the software is installed the executables etc are relinked by CMake to have the install RPATH. If this variable is set to true then the software is always built with the install path for the RPATH and does not need to be relinked when installed.

    + +
  • +
  • + CMAKE_DEBUG_POSTFIX: See variable CMAKE_<CONFIG>_POSTFIX.
    +

    This variable is a special case of the more-general CMAKE_<CONFIG>_POSTFIX variable for the DEBUG configuration.

    + +
  • +
  • + CMAKE_EXE_LINKER_FLAGS: Linker flags used to create executables.
    +

    Flags used by the linker when creating an executable.

    + +
  • +
  • + CMAKE_EXE_LINKER_FLAGS_[CMAKE_BUILD_TYPE]: Flag used when linking an executable.
    +

    Same as CMAKE_C_FLAGS_* but used by the linker when creating executables.

    + +
  • +
  • + CMAKE_Fortran_FORMAT: Set to FIXED or FREE to indicate the Fortran source layout.
    +

    This variable is used to initialize the Fortran_FORMAT property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_Fortran_MODULE_DIRECTORY: Fortran module output directory.
    +

    This variable is used to initialize the Fortran_MODULE_DIRECTORY property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_GNUtoMS: Convert GNU import libraries (.dll.a) to MS format (.lib).
    +

    This variable is used to initialize the GNUtoMS property on targets when they are created. See that target property for additional information.

    + +
  • +
  • + CMAKE_INCLUDE_CURRENT_DIR: Automatically add the current source- and build directories to the include path.
    +

    If this variable is enabled, CMake automatically adds in each directory ${CMAKE_CURRENT_SOURCE_DIR} and ${CMAKE_CURRENT_BINARY_DIR} to the include path for this directory. These additional include directories do not propagate down to subdirectories. This is useful mainly for out-of-source builds, where files generated into the build tree are included by files located in the source tree.

    +

    By default CMAKE_INCLUDE_CURRENT_DIR is OFF.

    + +
  • +
  • + CMAKE_INSTALL_NAME_DIR: Mac OSX directory name for installed targets.
    +

    CMAKE_INSTALL_NAME_DIR is used to initialize the INSTALL_NAME_DIR property on all targets. See that target property for more information.

    + +
  • +
  • + CMAKE_INSTALL_RPATH: The rpath to use for installed targets.
    +

    A semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it). This is used to initialize the target property INSTALL_RPATH for all targets.

    + +
  • +
  • + CMAKE_INSTALL_RPATH_USE_LINK_PATH: Add paths to linker search and installed rpath.
    +

    CMAKE_INSTALL_RPATH_USE_LINK_PATH is a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL_RPATH. This is used to initialize the target property INSTALL_RPATH_USE_LINK_PATH for all targets.

    + +
  • +
  • + CMAKE_LIBRARY_OUTPUT_DIRECTORY: Where to put all the LIBRARY targets when built.
    +

    This variable is used to initialize the LIBRARY_OUTPUT_DIRECTORY property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_LIBRARY_PATH_FLAG: The flag used to add a library search path to a compiler.
    +

    The flag used to specify a library directory to the compiler. On most compilers this is "-L".

    + +
  • +
  • + CMAKE_LINK_DEF_FILE_FLAG : Linker flag used to specify a .def file for dll creation.
    +

    The flag used to add a .def file when creating a dll on Windows, this is only defined on Windows.

    + +
  • +
  • + CMAKE_LINK_INTERFACE_LIBRARIES: Default value for LINK_INTERFACE_LIBRARIES of targets.
    +

    This variable is used to initialize the LINK_INTERFACE_LIBRARIES property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_LINK_LIBRARY_FILE_FLAG: Flag used to link a library specified by a path to its file.
    +

    The flag used before a library file path is given to the linker. This is needed only on very few platforms.

    + +
  • +
  • + CMAKE_LINK_LIBRARY_FLAG: Flag used to link a library into an executable.
    +

    The flag used to specify a library to link to an executable. On most compilers this is "-l".

    + +
  • +
  • + CMAKE_NO_BUILTIN_CHRPATH: Do not use the builtin ELF editor to fix RPATHs on installation.
    +

    When an ELF binary needs to have a different RPATH after installation than it does in the build tree, CMake uses a builtin editor to change the RPATH in the installed copy. If this variable is set to true then CMake will relink the binary before installation instead of using its builtin editor.

    + +
  • +
  • + CMAKE_RUNTIME_OUTPUT_DIRECTORY: Where to put all the RUNTIME targets when built.
    +

    This variable is used to initialize the RUNTIME_OUTPUT_DIRECTORY property on all the targets. See that target property for additional information.

    + +
  • +
  • + CMAKE_SKIP_BUILD_RPATH: Do not include RPATHs in the build tree.
    +

    Normally CMake uses the build tree for the RPATH when building executables etc on systems that use RPATH. When the software is installed the executables etc are relinked by CMake to have the install RPATH. If this variable is set to true then the software is always built with no RPATH.

    + +
  • +
  • + CMAKE_TRY_COMPILE_CONFIGURATION: Build configuration used for try_compile and try_run projects.
    +

    Projects built by try_compile and try_run are built synchronously during the CMake configuration step. Therefore a specific build configuration must be chosen even if the generated build system supports multiple configurations.

    + +
  • +
  • + CMAKE_USE_RELATIVE_PATHS: Use relative paths (May not work!).
    +

    If this is set to TRUE, then the CMake will use relative paths between the source and binary tree. This option does not work for more complicated projects, and relative paths are used when possible. In general, it is not possible to move CMake generated makefiles to a different location regardless of the value of this variable.

    + +
  • +
  • + EXECUTABLE_OUTPUT_PATH: Old executable location variable.
    +

    The target property RUNTIME_OUTPUT_DIRECTORY supercedes this variable for a target if it is set. Executable targets are otherwise placed in this directory.

    + +
  • +
  • + LIBRARY_OUTPUT_PATH: Old library location variable.
    +

    The target properties ARCHIVE_OUTPUT_DIRECTORY, LIBRARY_OUTPUT_DIRECTORY, and RUNTIME_OUTPUT_DIRECTORY supercede this variable for a target if they are set. Library targets are otherwise placed in this directory.

    + +
  • +
+

Variables that Provide Information

+ +

variables defined by cmake, that give information about the project, and cmake

+ +
    +
  • + CMAKE_AR: Name of archiving tool for static libraries.
    +

    This specifies name of the program that creates archive or static libraries.

    + +
  • +
  • + CMAKE_ARGC: Number of command line arguments passed to CMake in script mode.
    +

    When run in -P script mode, CMake sets this variable to the number of command line arguments. See also CMAKE_ARGV0, 1, 2 ...

    + +
  • +
  • + CMAKE_ARGV0: Command line argument passed to CMake in script mode.
    +

    When run in -P script mode, CMake sets this variable to the first command line argument. It then also sets CMAKE_ARGV1, CMAKE_ARGV2, ... and so on, up to the number of command line arguments given. See also CMAKE_ARGC.

    + +
  • +
  • + CMAKE_BINARY_DIR: The path to the top level of the build tree.
    +

    This is the full path to the top level of the current CMake build tree. For an in-source build, this would be the same as CMAKE_SOURCE_DIR.

    + +
  • +
  • + CMAKE_BUILD_TOOL: Tool used for the actual build process.
    +

    This variable is set to the program that will be needed to build the output of CMake. If the generator selected was Visual Studio 6, the CMAKE_BUILD_TOOL will be set to msdev, for Unix makefiles it will be set to make or gmake, and for Visual Studio 7 it set to devenv. For Nmake Makefiles the value is nmake. This can be useful for adding special flags and commands based on the final build environment.

    + +
  • +
  • + CMAKE_CACHEFILE_DIR: The directory with the CMakeCache.txt file.
    +

    This is the full path to the directory that has the CMakeCache.txt file in it. This is the same as CMAKE_BINARY_DIR.

    + +
  • +
  • + CMAKE_CACHE_MAJOR_VERSION: Major version of CMake used to create the CMakeCache.txt file
    +

    This is stores the major version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.

    + +
  • +
  • + CMAKE_CACHE_MINOR_VERSION: Minor version of CMake used to create the CMakeCache.txt file
    +

    This is stores the minor version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.

    + +
  • +
  • + CMAKE_CACHE_PATCH_VERSION: Patch version of CMake used to create the CMakeCache.txt file
    +

    This is stores the patch version of CMake used to write a CMake cache file. It is only different when a different version of CMake is run on a previously created cache file.

    + +
  • +
  • + CMAKE_CFG_INTDIR: Build-time reference to per-configuration output subdirectory.
    +

    For native build systems supporting multiple configurations in the build tree (such as Visual Studio and Xcode), the value is a reference to a build-time variable specifying the name of the per-configuration output subdirectory. On Makefile generators this evaluates to "." because there is only one configuration in a build tree. Example values:

    +
      $(IntDir)        = Visual Studio 6
    $(OutDir) = Visual Studio 7, 8, 9
    $(Configuration) = Visual Studio 10
    $(CONFIGURATION) = Xcode
    . = Make-based tools
    +

    Since these values are evaluated by the native build system, this variable is suitable only for use in command lines that will be evaluated at build time. Example of intended usage:

    +
      add_executable(mytool mytool.c)
    add_custom_command(
    OUTPUT out.txt
    COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/mytool
    ${CMAKE_CURRENT_SOURCE_DIR}/in.txt out.txt
    DEPENDS mytool in.txt
    )
    add_custom_target(drive ALL DEPENDS out.txt)
    +

    Note that CMAKE_CFG_INTDIR is no longer necessary for this purpose but has been left for compatibility with existing projects. Instead add_custom_command() recognizes executable target names in its COMMAND option, so "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/mytool" can be replaced by just "mytool".

    +

    This variable is read-only. Setting it is undefined behavior. In multi-configuration build systems the value of this variable is passed as the value of preprocessor symbol "CMAKE_INTDIR" to the compilation of all source files.

    + +
  • +
  • + CMAKE_COMMAND: The full path to the cmake executable.
    +

    This is the full path to the CMake executable cmake which is useful from custom commands that want to use the cmake -E option for portable system commands. (e.g. /usr/local/bin/cmake

    + +
  • +
  • + CMAKE_CROSSCOMPILING: Is CMake currently cross compiling.
    +

    This variable will be set to true by CMake if CMake is cross compiling. Specifically if the build platform is different from the target platform.

    + +
  • +
  • + CMAKE_CTEST_COMMAND: Full path to ctest command installed with cmake.
    +

    This is the full path to the CTest executable ctest which is useful from custom commands that want to use the cmake -E option for portable system commands.

    + +
  • +
  • + CMAKE_CURRENT_BINARY_DIR: The path to the binary directory currently being processed.
    +

    This the full path to the build directory that is currently being processed by cmake. Each directory added by add_subdirectory will create a binary directory in the build tree, and as it is being processed this variable will be set. For in-source builds this is the current source directory being processed.

    + +
  • +
  • + CMAKE_CURRENT_LIST_DIR: Full directory of the listfile currently being processed.
    +

    As CMake processes the listfiles in your project this variable will always be set to the directory where the listfile which is currently being processed (CMAKE_CURRENT_LIST_FILE) is located. The value has dynamic scope. When CMake starts processing commands in a source file it sets this variable to the directory where this file is located. When CMake finishes processing commands from the file it restores the previous value. Therefore the value of the variable inside a macro or function is the directory of the file invoking the bottom-most entry on the call stack, not the directory of the file containing the macro or function definition.

    +

    See also CMAKE_CURRENT_LIST_FILE.

    + +
  • +
  • + CMAKE_CURRENT_LIST_FILE: Full path to the listfile currently being processed.
    +

    As CMake processes the listfiles in your project this variable will always be set to the one currently being processed. The value has dynamic scope. When CMake starts processing commands in a source file it sets this variable to the location of the file. When CMake finishes processing commands from the file it restores the previous value. Therefore the value of the variable inside a macro or function is the file invoking the bottom-most entry on the call stack, not the file containing the macro or function definition.

    +

    See also CMAKE_PARENT_LIST_FILE.

    + +
  • +
  • + CMAKE_CURRENT_LIST_LINE: The line number of the current file being processed.
    +

    This is the line number of the file currently being processed by cmake.

    + +
  • +
  • + CMAKE_CURRENT_SOURCE_DIR: The path to the source directory currently being processed.
    +

    This the full path to the source directory that is currently being processed by cmake.

    + +
  • +
  • + CMAKE_DL_LIBS: Name of library containing dlopen and dlcose.
    +

    The name of the library that has dlopen and dlclose in it, usually -ldl on most UNIX machines.

    + +
  • +
  • + CMAKE_EDIT_COMMAND: Full path to cmake-gui or ccmake.
    +

    This is the full path to the CMake executable that can graphically edit the cache. For example, cmake-gui, ccmake, or cmake -i.

    + +
  • +
  • + CMAKE_EXECUTABLE_SUFFIX: The suffix for executables on this platform.
    +

    The suffix to use for the end of an executable if any, .exe on Windows.

    +

    CMAKE_EXECUTABLE_SUFFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_EXTRA_GENERATOR: The extra generator used to build the project.
    +

    When using the Eclipse, CodeBlocks or KDevelop generators, CMake generates Makefiles (CMAKE_GENERATOR) and additionally project files for the respective IDE. This IDE project file generator is stored in CMAKE_EXTRA_GENERATOR (e.g. "Eclipse CDT4").

    + +
  • +
  • + CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES: Additional suffixes for shared libraries.
    +

    Extensions for shared libraries other than that specified by CMAKE_SHARED_LIBRARY_SUFFIX, if any. CMake uses this to recognize external shared library files during analysis of libraries linked by a target.

    + +
  • +
  • + CMAKE_GENERATOR: The generator used to build the project.
    +

    The name of the generator that is being used to generate the build files. (e.g. "Unix Makefiles", "Visual Studio 6", etc.)

    + +
  • +
  • + CMAKE_HOME_DIRECTORY: Path to top of source tree.
    +

    This is the path to the top level of the source tree.

    + +
  • +
  • + CMAKE_IMPORT_LIBRARY_PREFIX: The prefix for import libraries that you link to.
    +

    The prefix to use for the name of an import library if used on this platform.

    +

    CMAKE_IMPORT_LIBRARY_PREFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_IMPORT_LIBRARY_SUFFIX: The suffix for import libraries that you link to.
    +

    The suffix to use for the end of an import library if used on this platform.

    +

    CMAKE_IMPORT_LIBRARY_SUFFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_LINK_LIBRARY_SUFFIX: The suffix for libraries that you link to.
    +

    The suffix to use for the end of a library, .lib on Windows.

    + +
  • +
  • + CMAKE_MAJOR_VERSION: The Major version of cmake (i.e. the 2 in 2.X.X)
    +

    This specifies the major version of the CMake executable being run.

    + +
  • +
  • + CMAKE_MAKE_PROGRAM: See CMAKE_BUILD_TOOL.
    +

    This variable is around for backwards compatibility, see CMAKE_BUILD_TOOL.

    + +
  • +
  • + CMAKE_MINOR_VERSION: The Minor version of cmake (i.e. the 4 in X.4.X).
    +

    This specifies the minor version of the CMake executable being run.

    + +
  • +
  • + CMAKE_PARENT_LIST_FILE: Full path to the parent listfile of the one currently being processed.
    +

    As CMake processes the listfiles in your project this variable will always be set to the listfile that included or somehow invoked the one currently being processed. See also CMAKE_CURRENT_LIST_FILE.

    + +
  • +
  • + CMAKE_PATCH_VERSION: The patch version of cmake (i.e. the 3 in X.X.3).
    +

    This specifies the patch version of the CMake executable being run.

    + +
  • +
  • + CMAKE_PROJECT_NAME: The name of the current project.
    +

    This specifies name of the current project from the closest inherited PROJECT command.

    + +
  • +
  • + CMAKE_RANLIB: Name of randomizing tool for static libraries.
    +

    This specifies name of the program that randomizes libraries on UNIX, not used on Windows, but may be present.

    + +
  • +
  • + CMAKE_ROOT: Install directory for running cmake.
    +

    This is the install root for the running CMake and the Modules directory can be found here. This is commonly used in this format: ${CMAKE_ROOT}/Modules

    + +
  • +
  • + CMAKE_SCRIPT_MODE_FILE: Full path to the -P script file currently being processed.
    +

    When run in -P script mode, CMake sets this variable to the full path of the script file. When run to configure a CMakeLists.txt file, this variable is not set.

    + +
  • +
  • + CMAKE_SHARED_LIBRARY_PREFIX: The prefix for shared libraries that you link to.
    +

    The prefix to use for the name of a shared library, lib on UNIX.

    +

    CMAKE_SHARED_LIBRARY_PREFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_SHARED_LIBRARY_SUFFIX: The suffix for shared libraries that you link to.
    +

    The suffix to use for the end of a shared library, .dll on Windows.

    +

    CMAKE_SHARED_LIBRARY_SUFFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_SHARED_MODULE_PREFIX: The prefix for loadable modules that you link to.
    +

    The prefix to use for the name of a loadable module on this platform.

    +

    CMAKE_SHARED_MODULE_PREFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_SHARED_MODULE_SUFFIX: The suffix for shared libraries that you link to.
    +

    The suffix to use for the end of a loadable module on this platform

    +

    CMAKE_SHARED_MODULE_SUFFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_SIZEOF_VOID_P: Size of a void pointer.
    +

    This is set to the size of a pointer on the machine, and is determined by a try compile. If a 64 bit size is found, then the library search path is modified to look for 64 bit libraries first.

    + +
  • +
  • + CMAKE_SKIP_RPATH: If true, do not add run time path information.
    +

    If this is set to TRUE, then the rpath information is not added to compiled executables. The default is to add rpath information if the platform supports it.This allows for easy running from the build tree.

    + +
  • +
  • + CMAKE_SOURCE_DIR: The path to the top level of the source tree.
    +

    This is the full path to the top level of the current CMake source tree. For an in-source build, this would be the same as CMAKE_BINARY_DIR.

    + +
  • +
  • + CMAKE_STANDARD_LIBRARIES: Libraries linked into every executable and shared library.
    +

    This is the list of libraries that are linked into all executables and libraries.

    + +
  • +
  • + CMAKE_STATIC_LIBRARY_PREFIX: The prefix for static libraries that you link to.
    +

    The prefix to use for the name of a static library, lib on UNIX.

    +

    CMAKE_STATIC_LIBRARY_PREFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_STATIC_LIBRARY_SUFFIX: The suffix for static libraries that you link to.
    +

    The suffix to use for the end of a static library, .lib on Windows.

    +

    CMAKE_STATIC_LIBRARY_SUFFIX_<LANG> overrides this for language <LANG>.

    + +
  • +
  • + CMAKE_TWEAK_VERSION: The tweak version of cmake (i.e. the 1 in X.X.X.1).
    +

    This specifies the tweak version of the CMake executable being run. Releases use tweak < 20000000 and development versions use the date format CCYYMMDD for the tweak level.

    + +
  • +
  • + CMAKE_USING_VC_FREE_TOOLS: True if free visual studio tools being used.
    +

    This is set to true if the compiler is Visual Studio free tools.

    + +
  • +
  • + CMAKE_VERBOSE_MAKEFILE: Create verbose makefiles if on.
    +

    This variable defaults to false. You can set this variable to true to make CMake produce verbose makefiles that show each command line as it is used.

    + +
  • +
  • + CMAKE_VERSION: The full version of cmake in major.minor.patch[.tweak[-id]] format.
    +

    This specifies the full version of the CMake executable being run. This variable is defined by versions 2.6.3 and higher. See variables CMAKE_MAJOR_VERSION, CMAKE_MINOR_VERSION, CMAKE_PATCH_VERSION, and CMAKE_TWEAK_VERSION for individual version components. The [-id] component appears in non-release versions and may be arbitrary text.

    + +
  • +
  • + PROJECT_BINARY_DIR: Full path to build directory for project.
    +

    This is the binary directory of the most recent PROJECT command.

    + +
  • +
  • + PROJECT_NAME: Name of the project given to the project command.
    +

    This is the name given to the most recent PROJECT command.

    + +
  • +
  • + PROJECT_SOURCE_DIR: Top level source directory for the current project.
    +

    This is the source directory of the most recent PROJECT command.

    + +
  • +
  • + [Project name]_BINARY_DIR: Top level binary directory for the named project.
    +

    A variable is created with the name used in the PROJECT command, and is the binary directory for the project. This can be useful when SUBDIR is used to connect several projects.

    + +
  • +
  • + [Project name]_SOURCE_DIR: Top level source directory for the named project.
    +

    A variable is created with the name used in the PROJECT command, and is the source directory for the project. This can be useful when add_subdirectory is used to connect several projects.

    + +
  • +
+

Copyright

+

Copyright 2000-2009 Kitware, Inc., Insight Software Consortium. All rights reserved.

+ +

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

+ +

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

+ +

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

+ +

Neither the names of Kitware, Inc., the Insight Software Consortium, nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission.

+ +

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ +

See Also

+ +

The following resources are available to get help using CMake:

+ + +

Summary of helpful links:

+
  Home: http://www.cmake.org
Docs: http://www.cmake.org/HTML/Documentation.html
Mail: http://www.cmake.org/HTML/MailingLists.html
FAQ: http://www.cmake.org/Wiki/CMake_FAQ
+ + diff --git a/doc/lua/contents.html b/doc/lua/contents.html new file mode 100644 index 0000000..564377c --- /dev/null +++ b/doc/lua/contents.html @@ -0,0 +1,405 @@ + + +Lua 5.1 reference manual - contents + + + + + +
+

+Lua +Lua 5.1 Reference Manual +

+ + +Copyright +© 2006 Lua.org, PUC-Rio. All rights reserved. + +
+ +

Contents

+ + +

Quick index

+ + + + + + +
+

Functions

+_G
+_VERSION
+assert
+collectgarbage
+coroutine.create
+coroutine.resume
+coroutine.running
+coroutine.status
+coroutine.wrap
+coroutine.yield
+debug.debug
+debug.getfenv
+debug.gethook
+debug.getinfo
+debug.getlocal
+debug.getmetatable
+debug.getregistry
+debug.getupvalue
+debug.setfenv
+debug.sethook
+debug.setlocal
+debug.setmetatable
+debug.setupvalue
+debug.traceback
+dofile
+error
+file:close
+file:flush
+file:lines
+file:read
+file:seek
+file:setvbuf
+file:write
+getfenv
+getmetatable
+io.close
+io.flush
+io.input
+io.lines
+io.open
+io.output
+io.popen
+io.read
+io.tmpfile
+io.type
+io.write
+ipairs
+load
+loadfile
+loadstring
+math.abs
+math.acos
+math.asin
+math.atan2
+math.atan
+math.ceil
+math.cosh
+math.cos
+math.deg
+math.exp
+math.floor
+math.fmod
+math.frexp
+math.ldexp
+math.log10
+math.log
+math.max
+math.min
+math.modf
+math.pow
+math.rad
+math.random
+math.randomseed
+math.sinh
+math.sin
+math.sqrt
+math.tanh
+math.tan
+module
+next
+os.clock
+os.date
+os.difftime
+os.execute
+os.exit
+os.getenv
+os.remove
+os.rename
+os.setlocale
+os.time
+os.tmpname
+package.cpath
+package.loaded
+package.loadlib
+package.path
+package.preload
+package.seeall
+pairs
+pcall
+print
+rawequal
+rawget
+rawset
+require
+select
+setfenv
+setmetatable
+string.byte
+string.char
+string.dump
+string.find
+string.format
+string.gmatch
+string.gsub
+string.len
+string.lower
+string.match
+string.rep
+string.reverse
+string.sub
+string.upper
+table.concat
+table.insert
+table.maxn
+table.remove
+table.sort
+tonumber
+tostring
+type
+unpack
+xpcall
+ +
+

API

+lua_Alloc
+lua_CFunction
+lua_Debug
+lua_Hook
+lua_Integer
+lua_Number
+lua_Reader
+lua_State
+lua_Writer
+lua_atpanic
+lua_call
+lua_checkstack
+lua_close
+lua_concat
+lua_cpcall
+lua_createtable
+lua_dump
+lua_equal
+lua_error
+lua_gc
+lua_getallocf
+lua_getfenv
+lua_getfield
+lua_getglobal
+lua_gethook
+lua_gethookcount
+lua_gethookmask
+lua_getinfo
+lua_getlocal
+lua_getmetatable
+lua_getstack
+lua_gettable
+lua_gettop
+lua_getupvalue
+lua_insert
+lua_isboolean
+lua_iscfunction
+lua_isfunction
+lua_islightuserdata
+lua_isnil
+lua_isnumber
+lua_isstring
+lua_istable
+lua_isthread
+lua_isuserdata
+lua_lessthan
+lua_load
+lua_newstate
+lua_newtable
+lua_newthread
+lua_newuserdata
+lua_next
+lua_objlen
+lua_pcall
+lua_pop
+lua_pushboolean
+lua_pushcclosure
+lua_pushcfunction
+lua_pushfstring
+lua_pushinteger
+lua_pushlightuserdata
+lua_pushlstring
+lua_pushnil
+lua_pushnumber
+lua_pushstring
+lua_pushthread
+lua_pushvalue
+lua_pushvfstring
+lua_rawequal
+lua_rawget
+lua_rawgeti
+lua_rawset
+lua_rawseti
+lua_register
+lua_remove
+lua_replace
+lua_resume
+lua_setallocf
+lua_setfenv
+lua_setfield
+lua_setglobal
+lua_sethook
+lua_setlocal
+lua_setmetatable
+lua_settable
+lua_settop
+lua_setupvalue
+lua_status
+lua_toboolean
+lua_tocfunction
+lua_tointeger
+lua_tolstring
+lua_tonumber
+lua_topointer
+lua_tostring
+lua_tothread
+lua_touserdata
+lua_type
+lua_typename
+lua_xmove
+lua_yield
+ +
+

Auxiliary library

+luaL_Buffer
+luaL_Reg
+luaL_addchar
+luaL_addlstring
+luaL_addsize
+luaL_addstring
+luaL_addvalue
+luaL_argcheck
+luaL_argerror
+luaL_buffinit
+luaL_callmeta
+luaL_checkany
+luaL_checkint
+luaL_checkinteger
+luaL_checklong
+luaL_checklstring
+luaL_checknumber
+luaL_checkoption
+luaL_checkstack
+luaL_checkstring
+luaL_checktype
+luaL_checkudata
+luaL_error
+luaL_getmetafield
+luaL_getmetatable
+luaL_gsub
+luaL_loadbuffer
+luaL_loadfile
+luaL_loadstring
+luaL_newmetatable
+luaL_newstate
+luaL_openlibs
+luaL_optint
+luaL_optinteger
+luaL_optlong
+luaL_optlstring
+luaL_optnumber
+luaL_optstring
+luaL_prepbuffer
+luaL_pushresult
+luaL_ref
+luaL_register
+luaL_typename
+luaL_typerror
+luaL_unref
+luaL_where
+ +
+

+ +


+ +Last update: +Fri Feb 10 17:15:37 BRST 2006 + + + + diff --git a/doc/lua/logo.gif b/doc/lua/logo.gif new file mode 100644 index 0000000000000000000000000000000000000000..2f5e4ac2e742fbb7675e739879211553758aea9c GIT binary patch literal 4232 zcmeH``9G8i;K!fm@ywWE@XWZzZ5SF?A>^uN#>^O6HI%DVL*tw8h1>$H%uPC0$QQ=txe!o}PX)Ev+jn>*nFZ-TC=<^76WcLZL(=DJm)| zEiIKwrInSHXU?3duCC_u@5try#>U2`rlw1mF15F}U%!66tE;QKyIUmcDJ<+QF77*W zFJd#&)VAl)kJ6K zi<>tmZ{3>g>+2gB7#JQNe(>OdLh;A=`1q42PbMZNCMPF*dXxhLZw3aYhlZwyhu@Bj z%#4n{d-Q1b$&i4QMce4L#8^!oMdw{PDnm4D66&3*dxX=-YIX6DQL_g`jbzkd4k zZDCoLf=%jL&vIeE zO=XcZ9fxt`f}-DQ^%H*PHMUs(JN%UWkI|Y8h9#6~I$Cw@{RqzO4&P-x;jHCPJ6Ks2 zoU%foi)nXd_sdkiuJa@@5J4RrreKfWSnz5>eMa5yTP=)16uu)TIdx~Fhho))6jZl) z($*i>QrIX4u}u3>m{WSn_ehkUGQ& zs})aUlTH1Cj1g3ZE3=MPXsSniEwJ{e6C3N#HjD=B4`8rWIsz!a7ecYpec?WuH+y?Wsm18^$cS4WmHhH3_=r zh*ILlm*X1dB^E5($KVl&zT524%l}vpHg%;Y+LezV_&TAJCmH`idhuj-n$4FZ)UE|jXLayXa-&O3Q z?Iyo!x*$5hD_HfFnDfGYj-RD|eIb7I?%>Y_kf%}Nbd`BXb4l1(Pc+}zoUR|9%_!7f zum2T;wbx&pohtI+&@~wm3nH9xLbOYkg*`phY~TK5iC#3tZNXo9s`cahx+8j2)rh5C zQgZh6D7Ekgib|hpdhxYf{r!PTJc z!vsYG@{hA}l5kL)g)0N_)(nC<*L0qdUi*3fD5<0sn58>zklX@6Tyv3*X^}m=Cqc40 zQ6GfjG@kd1mFIm`qaubWunm_?P>WUZ`9|f_z%gGHi{n|uu(N8!L=aw5(qAcDj$-QK zu;D#j6e42OXTQD>)i zlvM$LX`$n9EEjxM$_QDF&a z7cme_rat}aXmiN&7`6Q98}dh4Z@8L_uAb#nK&GQiZOOUnA9kAEVb-csuN1AWL=sXt z{z9GCN%%l0N9QvJM;tl1nf?rrhT{*sE%4WqR?{0~aIrfCcCPxf4eh_*jjQ=`$p53Y z@_|Rsx2i}|3dNFetMQQ5y8agTK-E0D&7;@3-LUxfvZ7 z7~!p@&mFe^oca2^F|CBt+4Ly?^ViUVSAhAH>JH1GN{^TQb3QnM*x0ZiZgDyNI@_c3 z@{}(WH4*e3T~}n_^0}da4ElIxAf9B!IaL7z9X0Icvj@cIkE*~W--17&WN`Ea5)Gn> z#gpfRb#44;jVTOS{FuaZgd(-ZD848=fQzgST2MxR>wSLc1P=2HDvByz$B$IsNCC6L zCM?nK*OHj6JA9gz4|b<~2%RqelN^1Y)jIqnRs!mDKV^BQTfo@hOtz7*Ug}Ee^cbsj zNNlumRgAmt`1$b5MO;&X#5-EP<}AaY;52ihIpem&MTea$?3!DrwbYa?V`NjEfWF3z zUq5JY8Ch;L{kx&J<1K&Fe_Vn;8gk{%c;n?nA2(%(f%DCRHko3uT~VI7RE^JWEqaCq z)i|%nfj(*4|V*XhY3W%M# z*yn6SN4eUOHFxAD7B&9E_PO`G5bqgs^@J{9bk>&;PlUAiqo`j3rjQDgD!}mqLUtb` zCB}ZD@m@s#pf7bV4jreOC*JVfHZ|hyHkX!rauVdd_I9FL45d{gWH!DNYu;i(|8wVx z!)eLY6YXxZ2{Coae0xuTnxo1ACb5wtED?VJAz&@114$Ao6uG9YSy*!K;m5_mj=0^j zw%?b%AOs}ql@$TGC-!^^*_#RT5+y_kTzQG9?LPPZNAtt6cJ%d2$q(I)ws21*?xF%p zN+NeGnWRQ<5w70Rc(bl|S0Xr&5@WrmdurS|IgPB|EyuZO#=tf!35)G!HJ`E1jh^lH zTBu~rL#DhQO*XAWtBt}JHH$lc>3%r0yD|maW_(W=B_J+y164F>O4dO|@&@N3Z3p=B zmVl{|^Z&#atHY|9n&la)SBo}=3AFIF=_~LDJk6MTlA73CXtX+4bnn+c!}N}IPa5pp zwyqbqIkN|I3j_3vD6$zlu{Ps(N-J|*qzEt<$5Soh;s^AuKv_ z-Tz+O1_~6*9CJh4r}`}mbUtjbf#fX58RIIkP6&@*y9kI|5fK*_eZ%jv3U$5*x<>D_ za2M(TV8?XY+9xy>0En#Te<6X4$0&dbyd(go$~eq4u(u)EA2msyF<5ssLZ zDP|I}=~Bi_q)whWv=Ri~L1TYaNrR;5cMB@s78HF1{w&r(6GJ;_2@bD?#1p&P4n_?n0#9Vx~$qjMX=Lk?*!@aKo8m&$iPO7S{g3sFUwr`*<53(68xx7?z`2xf# zGSicy_zI(PJ|%qc2VxT+6bOE--a{k&aq7$<<= zFt)C<@|TPs`+eycPGoGL1Wn9|Ed&a2JyAmjnkm3DQBECX&`bt~odH9cUPq4M{#$-q?G3!)qO-it*&YHw+j-O* zYy78V*`4Q=kQ@^Yz*b6Tal4(Me7BGeS^;phWAW8+L^5A(=D)t?k!rLIwVAKtq=f7h z&^n&VX1-T$ScvN~639QLZ^d@niMaS{C-Q)8oHHBhwD*r~-1Ze#Q)GFOFptW32a-uF z;M@ux%i%a25NwIgXt*=GHX$3~aZfwovGL!}sf?j9TsVo^cn(%&a<--0mIXYqGe>c PWz_J}_#7St0k8iB@FZjZ literal 0 HcmV?d00001 diff --git a/doc/lua/lua.1 b/doc/lua/lua.1 new file mode 100644 index 0000000..24809cc --- /dev/null +++ b/doc/lua/lua.1 @@ -0,0 +1,163 @@ +.\" $Id: lua.man,v 1.11 2006/01/06 16:03:34 lhf Exp $ +.TH LUA 1 "$Date: 2006/01/06 16:03:34 $" +.SH NAME +lua \- Lua interpreter +.SH SYNOPSIS +.B lua +[ +.I options +] +[ +.I script +[ +.I args +] +] +.SH DESCRIPTION +.B lua +is the stand-alone 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 +The given +.I options +(see below) +are executed and then +the Lua program in file +.I script +is loaded and executed. +The given +.I args +are available to +.I script +as strings in a global table named +.BR arg . +If these arguments contain spaces or other characters special to the shell, +then they should be quoted +(but note that the quotes will be removed by the shell). +The arguments in +.B arg +start at 0, +which contains the string +.RI ' script '. +The index of the last argument is stored in +.BR arg.n . +The arguments given in the command line before +.IR script , +including the name of the interpreter, +are available in negative indices in +.BR arg . +.LP +At the very start, +before even handling the command line, +.B lua +executes the contents of the environment variable +.BR LUA_INIT , +if it is defined. +If the value of +.B LUA_INIT +is of the form +.RI '@ filename ', +then +.I filename +is executed. +Otherwise, the string is assumed to be a Lua statement and is executed. +.LP +Options start with +.B '\-' +and are described below. +You can use +.B "'\--'" +to signal the end of options. +.LP +If no arguments are given, +then +.B "\-v \-i" +is assumed when the standard input is a terminal; +otherwise, +.B "\-" +is assumed. +.LP +In interactive mode, +.B lua +prompts the user, +reads lines from the standard input, +and executes them as they are read. +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. +So, one way to interrupt the reading of an incomplete statement is +to force a syntax error: +adding a +.B ';' +in the middle of a statement is a sure way of forcing a syntax error +(except inside multiline strings and comments; these must be closed explicitly). +If a line starts with +.BR '=' , +then +.B lua +displays the values of all the expressions in the remainder of the +line. The expressions must be separated by commas. +The primary prompt is the value of the global variable +.BR _PROMPT , +if this value is a string; +otherwise, the default prompt is used. +Similarly, the secondary prompt is the value of the global variable +.BR _PROMPT2 . +So, +to change the prompts, +set the corresponding variable to a string of your choice. +You can do that after calling the interpreter +or on the command line +(but in this case you have to be careful with quotes +if the prompt string contains a space; otherwise you may confuse the shell.) +The default prompts are "> " and ">> ". +.SH OPTIONS +.TP +.B \- +load and execute the standard input as a file, +that is, +not interactively, +even when the standard input is a terminal. +.TP +.BI \-e " stat" +execute statement +.IR stat . +You need to quote +.I stat +if it contains spaces, quotes, +or other characters special to the shell. +.TP +.B \-i +enter interactive mode after +.I script +is executed. +.TP +.BI \-l " name" +call +.BI require(' name ') +before executing +.IR script . +Typically used to load libraries. +.TP +.B \-v +show version information. +.SH "SEE ALSO" +.BR luac (1) +.br +http://www.lua.org/ +.SH DIAGNOSTICS +Error messages should be self explanatory. +.SH AUTHORS +R. Ierusalimschy, +L. H. de Figueiredo, +and +W. Celes +.\" EOF diff --git a/doc/lua/lua.css b/doc/lua/lua.css new file mode 100644 index 0000000..90f6231 --- /dev/null +++ b/doc/lua/lua.css @@ -0,0 +1,15 @@ +body { + color: #000000 ; + background-color: #FFFFFF ; + font-family: sans-serif ; +} + +a:link { + color: #000080 ; +} + +a:link:hover, a:visited:hover { + color: #000080 ; + background-color: #E0E0FF ; +} + diff --git a/doc/lua/lua.html b/doc/lua/lua.html new file mode 100644 index 0000000..1d435ab --- /dev/null +++ b/doc/lua/lua.html @@ -0,0 +1,172 @@ + + + +LUA man page + + + + + +

NAME

+lua - Lua interpreter +

SYNOPSIS

+lua +[ +options +] +[ +script +[ +args +] +] +

DESCRIPTION

+lua +is the stand-alone Lua interpreter. +It loads and executes Lua programs, +either in textual source form or +in precompiled binary form. +(Precompiled binaries are output by +luac, +the Lua compiler.) +lua +can be used as a batch interpreter and also interactively. +

+The given +options +(see below) +are executed and then +the Lua program in file +script +is loaded and executed. +The given +args +are available to +script +as strings in a global table named +arg. +If these arguments contain spaces or other characters special to the shell, +then they should be quoted +(but note that the quotes will be removed by the shell). +The arguments in +arg +start at 0, +which contains the string +'script'. +The index of the last argument is stored in +arg.n. +The arguments given in the command line before +script, +including the name of the interpreter, +are available in negative indices in +arg. +

+At the very start, +before even handling the command line, +lua +executes the contents of the environment variable +LUA_INIT, +if it is defined. +If the value of +LUA_INIT +is of the form +'@filename', +then +filename +is executed. +Otherwise, the string is assumed to be a Lua statement and is executed. +

+Options start with +'-' +and are described below. +You can use +'--' +to signal the end of options. +

+If no arguments are given, +then +"-v -i" +is assumed when the standard input is a terminal; +otherwise, +"-" +is assumed. +

+In interactive mode, +lua +prompts the user, +reads lines from the standard input, +and executes them as they are read. +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. +So, one way to interrupt the reading of an incomplete statement is +to force a syntax error: +adding a +';' +in the middle of a statement is a sure way of forcing a syntax error +(except inside multiline strings and comments; these must be closed explicitly). +If a line starts with +'=', +then +lua +displays the values of all the expressions in the remainder of the +line. The expressions must be separated by commas. +The primary prompt is the value of the global variable +_PROMPT, +if this value is a string; +otherwise, the default prompt is used. +Similarly, the secondary prompt is the value of the global variable +_PROMPT2. +So, +to change the prompts, +set the corresponding variable to a string of your choice. +You can do that after calling the interpreter +or on the command line +(but in this case you have to be careful with quotes +if the prompt string contains a space; otherwise you may confuse the shell.) +The default prompts are "> " and ">> ". +

OPTIONS

+

+- +load and execute the standard input as a file, +that is, +not interactively, +even when the standard input is a terminal. +

+-e stat +execute statement +stat. +You need to quote +stat +if it contains spaces, quotes, +or other characters special to the shell. +

+-i +enter interactive mode after +script +is executed. +

+-l name +call +require('name') +before executing +script. +Typically used to load libraries. +

+-v +show version information. +

SEE ALSO

+luac(1) +
+http://www.lua.org/ +

DIAGNOSTICS

+Error messages should be self explanatory. +

AUTHORS

+R. Ierusalimschy, +L. H. de Figueiredo, +and +W. Celes + + + diff --git a/doc/lua/luac.1 b/doc/lua/luac.1 new file mode 100644 index 0000000..d814678 --- /dev/null +++ b/doc/lua/luac.1 @@ -0,0 +1,136 @@ +.\" $Id: luac.man,v 1.28 2006/01/06 16:03:34 lhf Exp $ +.TH LUAC 1 "$Date: 2006/01/06 16:03:34 $" +.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 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. +.LP +Pre-compiling 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. +.LP +Pre-compiled chunks are not necessarily smaller than the corresponding source. +The main goal in pre-compiling is faster loading. +.LP +The binary files created by +.B luac +are portable only among architectures with the same word size and byte order. +.LP +.B luac +produces a single output file containing the bytecodes +for all source files given. +By default, +the output file is named +.BR luac.out , +but you can change this with the +.B \-o +option. +.LP +In the command line, +you can mix +text files containing Lua source and +binary files containing precompiled chunks. +This is useful to combine several precompiled chunks, +even from different (but compatible) platforms, +into a single precompiled chunk. +.LP +You can use +.B "'\-'" +to indicate the standard input as a source file +and +.B "'\--'" +to signal the end of options +(that is, +all remaining arguments will be treated as files even if they start with +.BR "'\-'" ). +.LP +The internal format of the binary files produced by +.B luac +is likely to change when a new version of Lua is released. +So, +save the source files of all Lua programs that you precompile. +.LP +.SH OPTIONS +Options must be separate. +.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. +.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 a source file 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. +Lua always performs a thorough integrity test on precompiled chunks. +Bytecode that passes this test is completely safe, +in the sense that it will not break the interpreter. +However, +there is no guarantee that such code does anything sensible. +(None can be given, because the halting problem is unsolvable.) +If no files are given, then +.B luac +loads +.B luac.out +and tests its contents. +No messages are displayed if the file passes the integrity test. +.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. +For instance, +line numbers and names of local variables are lost. +.TP +.B \-v +show version information. +.SH FILES +.TP 15 +.B luac.out +default output file +.SH "SEE ALSO" +.BR lua (1) +.br +http://www.lua.org/ +.SH DIAGNOSTICS +Error messages should be self explanatory. +.SH AUTHORS +L. H. de Figueiredo, +R. Ierusalimschy and +W. Celes +.\" EOF diff --git a/doc/lua/luac.html b/doc/lua/luac.html new file mode 100644 index 0000000..179ffe8 --- /dev/null +++ b/doc/lua/luac.html @@ -0,0 +1,145 @@ + + + +LUAC man page + + + + + +

NAME

+luac - Lua compiler +

SYNOPSIS

+luac +[ +options +] [ +filenames +] +

DESCRIPTION

+luac +is the Lua compiler. +It translates programs written in the Lua programming language +into binary files that can be later loaded and executed. +

+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. +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. +

+The binary files created by +luac +are portable only among architectures with the same word size and byte order. +

+luac +produces a single output file containing the bytecodes +for all source files given. +By default, +the output file is named +luac.out, +but you can change this with the +-o +option. +

+In the command line, +you can mix +text files containing Lua source and +binary files containing precompiled chunks. +This is useful because several precompiled chunks, +even from different (but compatible) platforms, +can be combined into a single precompiled chunk. +

+You can use +'-' +to indicate the standard input as a source file +and +'--' +to signal the end of options +(that is, +all remaining arguments will be treated as files even if they start with +'-'). +

+The internal format of the binary files produced by +luac +is likely to change when a new version of Lua is released. +So, +save the source files of all Lua programs that you precompile. +

+

OPTIONS

+Options must be separate. +

+-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 +luac +loads +luac.out +and lists its contents. +

+-o file +output to +file, +instead of the default +luac.out. +(You can use +'-' +for standard output, +but not on platforms that open standard output in text mode.) +The output file may be a source file because +all files are loaded before the output file is written. +Be careful not to overwrite precious files. +

+-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. +Lua always performs a thorough integrity test on precompiled chunks. +Bytecode that passes this test is completely safe, +in the sense that it will not break the interpreter. +However, +there is no guarantee that such code does anything sensible. +(None can be given, because the halting problem is unsolvable.) +If no files are given, then +luac +loads +luac.out +and tests its contents. +No messages are displayed if the file passes the integrity test. +

+-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. +For instance, +line numbers and names of local variables are lost. +

+-v +show version information. +

FILES

+

+luac.out +default output file +

SEE ALSO

+lua(1) +
+http://www.lua.org/ +

DIAGNOSTICS

+Error messages should be self explanatory. +

AUTHORS

+L. H. de Figueiredo, +R. Ierusalimschy and +W. Celes + + + diff --git a/doc/lua/manual.html b/doc/lua/manual.html new file mode 100644 index 0000000..a44d2e8 --- /dev/null +++ b/doc/lua/manual.html @@ -0,0 +1,6247 @@ + + + + +Lua 5.1 Reference Manual + + + + + +
+

+[Lua logo] +Lua 5.1 Reference Manual +

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

+ +Copyright +© 2006 Lua.org, PUC-Rio. All rights reserved. + +


+ +

+

+ + + +

1 - Introduction

+ +

Lua is an extension programming language designed to support +general procedural programming with data description +facilities. +It also offers good support for object-oriented programming, +functional programming, and data-driven programming. +Lua is intended to be used as a powerful, light-weight +scripting language for any program that needs one. +Lua is implemented as a library, written in clean C +(that is, in the common subset of ANSI C and C++). + +

Being an extension language, Lua has no notion of a "main" program: +it only works embedded in a host client, +called the embedding program or simply the host. +This 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. +The Lua distribution includes a sample host program called lua, +which uses the Lua library to offer a complete, stand-alone Lua interpreter. + +

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 - 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. + +

The 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 in italics, +keywords are shown in bold, +and other terminal symbols are shown in typewriter font, +enclosed in single quotes. +The complete syntax of Lua can be found at the end of this manual. + +

2.1 - Lexical Conventions

+ +

Names +(also called identifiers) +in Lua can be any string of letters, +digits, and underscores, +not beginning with a digit. +This coincides with the definition of names in most languages. +(The definition of letter depends on the current locale: +any character considered alphabetic by the current locale +can be used in an identifier.) +Identifiers are used to name variables and table fields. + +

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

+       and       break     do        else      elseif
+       end       false     for       function  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, names starting with an underscore followed by +uppercase letters (such as _VERSION) +are reserved for internal global variables used by Lua. + +

The following strings denote other tokens: +

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

Literal strings +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) +
  • \' --- apostrophe (single quote) +
+Moreover, a `\newline´ +(that is, a backslash followed by a real newline) +results in a newline in the string. +A character in a string may also be specified by its numerical value +using the escape sequence `\ddd´, +where ddd is a sequence of up to three decimal digits. +(Note that if a numerical escape is to be followed by a digit, +it must be expressed using exactly three digits.) +Strings in Lua may contain any 8-bit value, including embedded zeros, +which can be specified as `\0´. + +

To put a double (single) quote, a newline, a backslash, +or an embedded zero +inside a literal string enclosed by double (single) quotes +you must use an escape sequence. +Any other character may be directly inserted into the literal. +(Some control characters may cause problems for the file system, +but Lua has no problem with them.) + +

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 string starts with an opening long bracket of any level and +ends at the first closing long bracket of the same level. +Literals in this bracketed form may run for several lines, +do not interpret any escape sequences, +and ignore long brackets of any other level. +They may contain anything except a closing bracket of the proper level +or embedded zeros. + +

For convenience, +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 four literals below denote the same string: +

+      (1)   'alo\n123"'
+      (2)   "alo\n123\""
+      (3)   '\97lo\10\04923"'
+      (4)   [[alo
+            123"]]
+      (5)   [==[
+            alo
+            123"]==]
+
+ +

Numerical constants may be written with an optional decimal part +and an optional decimal exponent. +Lua also accepts integer hexadecimal constants, +by prefixing them with 0x. +Examples of valid numerical constants are +

+       3       3.0     3.1416  314.16e-2   0.31416E1  0xff  0x56
+
+ +

Comments start 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. +Long comments are frequently used to disable code temporarily. + +

2.2 - 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. +Nil is the type of the value nil, +whose main property is to be different from any other value; +it usually represents the absence of a useful value. +Boolean is the type of the values false and true. +Both nil and false make a condition false; +any other value makes it true. +Number represents real (double-precision floating-point) numbers. +(It is easy to build Lua interpreters that use other +internal representations for numbers, +such as single-precision float or long integers. +See file luaconf.h.) +String represents arrays of characters. + +Lua is 8-bit clean: +Strings may contain any 8-bit character, +including embedded zeros (`\0´) (see 2.1). + +

Lua can call (and manipulate) functions written in Lua and +functions written in C +(see 2.5.8). + +

The type userdata is provided to allow arbitrary C data to +be stored in Lua variables. +This type corresponds to a block of raw memory +and has no pre-defined operations in Lua, +except assignment and identity test. +However, by using metatables, +the programmer can define operations for userdata values +(see 2.8). +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. + +

The type thread represents independent threads of execution +and it is used to implement coroutines (see 2.11). +Do not confuse Lua threads with operating-system threads. +Lua supports coroutines on all systems, +even those that do not support threads. + +

The type table implements associative arrays, +that is, arrays that can be indexed not only with numbers, +but with any value (except nil). +Tables can be heterogeneous; +that is, they can contain values of all types (except nil). +Tables are the sole data structuring mechanism in Lua; +they may be used to represent ordinary arrays, +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 2.5.7). + +

Like indices, +the value of a table field can be of any type (except nil). +In particular, +because functions are first-class values, +table fields may contain functions. +Thus tables may also carry methods (see 2.5.9). + +

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. + +

2.2.1 - Coercion

+ +

Lua provides automatic conversion between +string and number values at run time. +Any arithmetic operation applied to a string tries to convert +this string to a number, following the usual conversion rules. +Conversely, whenever a number is used where a string is expected, +the number is converted to a string, in a reasonable format. +For complete control over how numbers are converted to strings, +use the format function from the string library +(see string.format). + +

2.3 - 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, as defined in (see 2.1). + +

Variables are assumed to be global unless explicitly declared local +(see 2.4.7). +Local variables are lexically scoped: +Local variables can be freely accessed by functions +defined inside their scope (see 2.6). + +

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

Square brackets are used to index a table: +

+	var ::= prefixexp `[´ exp `]´
+
+The first expression (prefixexp) should result in a table value; +the second expression (exp) +identifies a specific entry in this table. +The expression denoting the table to be indexed has a restricted syntax; +see 2.5 for details. + +

The syntax var.Name is just syntactic sugar for +var["Name"] and is used to denote table fields: +

+	var ::= prefixexp `.´ Name
+
+ +

The meaning of accesses to global variables +and table fields can be changed via metatables. +An access to an indexed variable t[i] is equivalent to +a call gettable_event(t,i). +(See 2.8 for a complete description of the +gettable_event function. +This function is not defined or callable in Lua. +We use it here only for explanatory purposes.) + +

All global variables live as fields in ordinary Lua tables, +called environment tables or simply +environments (see 2.9). +Each function has its own reference to an environment, +so that all global variables in this function +will refer to this environment table. +When a function is created, +it inherits the environment from the function that created it. +To get the environment table of a Lua function, +you call getfenv. +To replace it, +you call setfenv. +(You can only manipulate the environment of C functions +through the debug library; (see 5.9).) + +

An access to a global variable x +is equivalent to _env.x, +which in turn is equivalent to +

+       gettable_event(_env, "x")
+
+where _env is the environment of the running function. +(See 2.8 for a complete description of the +gettable_event function. +This function is not defined or callable in Lua. +Similarly, the _env variable is not defined in Lua. +We use them here only for explanatory purposes.) + +

2.4 - Statements

+ +

Lua supports an almost conventional set of statements, +similar to those in Pascal or C. +This set includes +assignment, control structures, function calls, +table constructors, and variable declarations. + +

2.4.1 - Chunks

+ +

The unit of execution of Lua is called a chunk. +A chunk is simply a sequence of statements, +which are executed sequentially. +Each statement can be optionally followed by a semicolon: +

+	chunk ::= {stat [`;´]}
+
+There are no empty statements and thus `;;´ is not legal. + +

Lua handles a chunk as the body of an anonymous function +with a variable number of arguments +(see 2.5.9). +As such, chunks can define local variables, +receive arguments, and return values. + +

A chunk may be stored in a file or in a string inside the host program. +When a chunk is executed, first it is pre-compiled into instructions for +a virtual machine, +and then the compiled code is executed +by an interpreter for the virtual machine. + +

Chunks may also be pre-compiled into binary form; +see program luac for details. +Programs in source and compiled forms are interchangeable; +Lua automatically detects the file type and acts accordingly. + + +

2.4.2 - Blocks

+A block is a list of statements; +syntactically, a block is the same as a chunk: +
+	block ::= chunk
+
+ +

A block may 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 or break statement in the middle +of another block (see 2.4.4). + + +

2.4.3 - Assignment

+ +

Lua allows multiple assignment. +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 ::= varlist1 `=´ explist1
+	varlist1 ::= var {`,´ var}
+	explist1 ::= exp {`,´ exp}
+
+Expressions are discussed in 2.5. + +

Before the assignment, +the list of values is adjusted to the length of +the list of variables. +If there are more values than needed, +the excess values are thrown away. +If there are fewer values than needed, +the list is extended with as many nil's as needed. +If the list of expressions ends with a function call, +then all values returned by this call enter in the list of values, +before the adjustment +(except when the call is enclosed in parentheses; see 2.5). + +

The assignment statement first evaluates all its expressions +and only then are the assignments performed. +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. + +

The meaning of assignments to global variables +and table fields can be changed via metatables. +An assignment to an indexed variable t[i] = val is equivalent to +settable_event(t,i,val). +(See 2.8 for a complete description of the +settable_event function. +This function is not defined or callable in Lua. +We use it here only for explanatory purposes.) + +

An assignment to a global variable x = val +is equivalent to the assignment +_env.x = val, +which in turn is equivalent to +

+       settable_event(_env, "x", val)
+
+where _env is the environment of the running function. +(The _env variable is not defined in Lua. +We use it here only for explanatory purposes.) + +

2.4.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 2.4.5). + +

The condition expression of a +control structure may return any value. +Both false and nil are considered false. +All values different from nil and false are considered true +(in particular, the number 0 and the empty string are also true). + +

In the repeat--until 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 return statement is used to return values +from a function or a chunk (which is just a function). + +Functions and chunks may return more than one value, +so the syntax for the return statement is +

+	stat ::= return [explist1]
+
+ +

The break statement is used to terminate 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 and break +statements can only be written as the last statement of a block. +If it is really necessary to return or break in the +middle of a block, +then an explicit inner block can be used, +as in the idioms +`do return end´ and +`do break end´, +because now return and break are the last statements in +their (inner) blocks. + +

2.4.5 - For Statement

+ +

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

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

+	stat ::= for Name `=´ exp `,´ exp [`,´ exp] do block end
+
+The block is repeated for name starting at the value of +the first exp, until it passes the second exp by steps of the +third exp. +More precisely, a for statement like +
+       for var = e1, e2, e3 do block end
+
+is equivalent to the code: +
+       do
+         local _var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
+         if not (_var and _limit and _step) then error() end
+         while (_step>0 and _var<=_limit) or (_step<=0 and _var>=_limit) do
+           local var = _var
+           block
+           _var = _var + _step
+         end
+       end
+
+Note the following: +
    +
  • All three control expressions are evaluated only once, +before the loop starts. +They must all result in numbers. +
  • _var, _limit, and _step are invisible variables. +The names are here for explanatory purposes only. +
  • If the third expression (the step) is absent, +then a step of 1 is used. +
  • You can use break to exit a for loop. +
  • The loop variable var is local to the loop; +you cannot use its value after the for ends or is broken. +If you need the value of the loop variable var, +then assign it to another variable before breaking or exiting the 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 explist1 do block end
+	namelist ::= Name {`,´ Name}
+
+A for statement like +
+       for var_1, ..., var_n in explist do block end
+
+is equivalent to the code: +
+       do
+         local _f, _s, _var = explist
+         while true do
+           local var_1, ... , var_n = _f(_s, _var)
+           _var = var_1
+           if _var == nil then break end
+           block
+         end
+       end
+
+Note the following: +
    +
  • explist is evaluated only once. +Its results are an iterator function, +a state, and an initial value for the first iterator variable. +
  • _f, _s, and _var are invisible variables. +The names are here for explanatory purposes only. +
  • You can use break to exit a for loop. +
  • The loop variables var_i are local to the loop; +you cannot use their values after the for ends. +If you need these values, +then assign them to other variables before breaking or exiting the loop. +
+ +

2.4.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 2.5.8. + +

2.4.7 - Local Declarations

+Local variables may be declared anywhere inside a block. +The declaration may include an initial assignment: +
+	stat ::= local namelist [`=´ explist1]
+
+If present, an initial assignment has the same semantics +of a multiple assignment (see 2.4.3). +Otherwise, all variables are initialized with nil. + +

A chunk is also a block (see 2.4.1), +and so local variables can be declared in a chunk outside any explicit block. +The scope of such local variables extends until the end of the chunk. + +

The visibility rules for local variables are explained in 2.6. + +

2.5 - Expressions

+ +

+The basic expressions in Lua are the following: +

+	exp ::= prefixexp
+	exp ::= nil  |  false  |  true
+	exp ::= Number
+	exp ::= String
+	exp ::= function
+	exp ::= tableconstructor
+	exp ::= `...´
+	exp ::= exp binop exp
+	exp ::= unop exp
+	prefixexp ::= var  |  functioncall  |  `(´ exp `)´
+
+ +

Numbers and literal strings are explained in 2.1; +variables are explained in 2.3; +function definitions are explained in 2.5.9; +function calls are explained in 2.5.8; +table constructors are explained in 2.5.7. +Vararg expressions, +denoted by three dots (`...´), can only be used inside +vararg functions; +they are explained in 2.5.9. + + +

Binary operators comprise arithmetic operators (see 2.5.1), +relational operators (see 2.5.2), and logical operators (see 2.5.3). +Unary operators comprise the unary minus (see 2.5.1), +the unary not (see 2.5.3), +and the unary length operator (see 2.5.5). + +

Both function calls and vararg expressions may result in multiple values. +If the expression is used as a statement (see 2.4.6) +(only possible for function calls), +then its return list is adjusted to zero elements, +thus discarding all returned values. +If the expression is used inside another expression +or in the middle of a list of expressions, +then its result list is adjusted to one element, +thus discarding all values except the first one. +If the expression is used as the last element of a list of expressions, +then no adjustment is made, +unless the call is enclosed in parentheses. + +

Here are some examples: +

+       f()                -- adjusted to 0 results
+       g(f(), x)          -- f() is adjusted to 1 result
+       g(x, f())          -- g gets x plus all values returned by f()
+       a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
+       a,b = ...          -- a gets the first vararg parameter, b gets
+                          -- the second (both a and b may get nil if there is
+                          -- no corresponding vararg parameter)
+       a,b,c = x, f()     -- f() is adjusted to 2 results
+       a,b,c = f()        -- f() is adjusted to 3 results
+       return f()         -- returns all values returned by f()
+       return ...         -- returns all received vararg parameters
+       return x,y,f()     -- returns x, y, and all values returned by f()
+       {f()}              -- creates a list with all values returned by f()
+       {...}              -- creates a list with all vararg parameters
+       {f(), nil}         -- f() is adjusted to 1 result
+
+ +

An expression enclosed in parentheses always results in only one value. +Thus, +(f(x,y,z)) is always a single value, +even if f returns several values. +(The value of (f(x,y,z)) is the first value returned by f +or nil if f does not return any values.) + +

2.5.1 - Arithmetic Operators

+Lua supports the usual arithmetic operators: +the binary + (addition), +- (subtraction), * (multiplication), +/ (division), % (modulo), and ^ (exponentiation); +and unary - (negation). +If the operands are numbers, or strings that can be converted to +numbers (see 2.2.1), +then all operations have the usual meaning. +Exponentiation works for any exponent. +For instance, x^(-0.5) computes the inverse of the square root of x. +Modulus is defined as +
+       a % b == a - math.floor(a/b)*b
+
+That is, it is the remainder of a division that rounds +the quotient towards minus infinity. + +

2.5.2 - Relational Operators

+The relational operators in Lua are +
+       ==    ~=    <     >     <=    >=
+
+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. +Numbers and strings are compared in the usual way. +Objects (tables, userdata, threads, and functions) +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, userdata, thread, or function), +this new object is different from any previously existing object. + +

You can change the way that Lua compares tables and userdata +by using the "eq" metamethod (see 2.8). + +

The conversion rules of 2.2.1 +do not apply to equality comparisons. +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 as such. +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.8). + +

2.5.3 - Logical Operators

+The logical operators in Lua are + +
+       and   or    not
+
+Like the control structures (see 2.4.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-cut 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
+
+(In this manual, +`-->´ indicates the result of the preceding expression.) + +

2.5.4 - Concatenation

+The string concatenation operator in Lua is +denoted by two dots (`..´). +If both operands are strings or numbers, then they are converted to +strings according to the rules mentioned in 2.2.1. +Otherwise, the "concat" metamethod is called (see 2.8). + +

2.5.5 - The Length Operator

+ +

The length operator is denoted by the unary 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 of a table t is defined to be any +integer index n +such that t[n] is not nil and t[n+1] is nil; +moreover, if t[1] is nil, n may be zero. +For a regular array, with non-nil values from 1 to a given n, +its length is exactly that n, +the index of its last value. +If the array has "holes" +(that is, nil values between other non-nil values), +then #t may be any of the indices that +directly precedes a nil value +(that is, it may consider any such nil value as the end of +the array). + +

2.5.6 - Precedence

+Operator precedence in Lua follows the table below, +from lower to higher priority: +
+       or
+       and
+       <     >     <=    >=    ~=    ==
+       ..
+       +     -
+       *     /     %
+       not   #     - (unary)
+       ^
+
+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. + +

2.5.7 - Table Constructors

+Table constructors are expressions that create tables. +Every time a constructor is evaluated, a new table is created. +Constructors can be used to create empty tables, +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. +Finally, fields of the form exp are equivalent to +[i] = exp, where i are consecutive numerical 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
+
+ +

If the last field in the list has the form exp +and the expression is a function call or a vararg expression, +then all values returned by this expression enter the list consecutively +(see 2.5.8). +To avoid this, +enclose the function call (or the vararg expression) +in parentheses (see 2.5). + +

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

2.5.8 - 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, the prefixexp "call" metamethod is called, +having as first parameter the value of prefixexp, +followed by the original call arguments +(see 2.8). + +

The form +

+	functioncall ::= prefixexp `:´ Name args
+
+can be used to call "methods". +A call v:name(...) +is syntactic sugar for v.name(v,...), +except that v is evaluated only once. + +

Arguments have the following syntax: +

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

As an exception to the free-format syntax of Lua, +you cannot put a line break before the `(´ in a function call. +This restriction avoids some ambiguities in the language. +If you write +

+       a = f
+       (g).x(a)
+
+Lua would see that as a single statement, a = f(g).x(a). +So, if you want two statements, you must add a semi-colon between them. +If you actually want to call f, +you must remove the line break before (g). + +

A call of the form return functioncall 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; +this syntax makes the calling function return exactly +the returns of the called function. +So, none of the following examples are tail calls: +

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

2.5.9 - Function Definitions

+ +

The syntax for function definition is +

+	function ::= function funcbody
+	funcbody ::= `(´ [parlist1] `)´ 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 () ... end
+
+translates to +
+       f = function () ... end
+
+The statement +
+       function t.a.b.c.f () ... end
+
+translates to +
+       t.a.b.c.f = function () ... end
+
+The statement +
+       local function f () ... end
+
+translates to +
+       local f; f = function () ... end
+
+not this: +
+       local f = function () ... 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 pre-compiles a chunk, +all its function bodies are pre-compiled too. +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. +Different instances of the same function +may refer to different external local variables +and may have different environment tables. + +

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

+	parlist1 ::= namelist [`,´ `...´]  |  `...´
+
+When a function is called, +the list of arguments is adjusted to +the length of the list of parameters, +unless the function is a variadic or vararg function, +which is +indicated by three dots (`...´) at the end of its parameter list. +A vararg 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. +If a vararg expression is used inside another expression +or in the middle of a list of expressions, +then its return list is adjusted to one element. +If the expression is used as the last element of a list of expressions, +then no adjustment is made +(unless the call is enclosed in parentheses). + +

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 2.4.4). +If control reaches the end of a function +without encountering a return statement, +then the function returns with no results. + +

The colon syntax +is used for defining methods, +that is, functions that have an implicit extra parameter self. +Thus, the statement +

+       function t.a.b.c:f (...) ... end
+
+is syntactic sugar for +
+       t.a.b.c.f = function (self, ...) ... end
+
+ +

2.6 - Visibility Rules

+ + +

Lua is a lexically scoped language. +The scope of variables begins at the first statement after +their declaration and lasts until the end of the innermost block that +includes the declaration. +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, +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. + +

2.7 - Error Handling

+ +

Because Lua is an embedded extension language, +all Lua actions start from C code in the host program +calling a function from the Lua library (see lua_pcall). +Whenever an error occurs during Lua compilation or execution, +control returns to C, +which can take appropriate measures +(such as printing an error message). + +

Lua code can explicitly generate an error by calling the +error function. +If you need to catch errors in Lua, +you can use the pcall function. + +

2.8 - Metatables

+ +

Every value in Lua may have a metatable. +This metatable is an ordinary Lua table +that defines the behavior of the original value +under certain special operations. +You can change several aspects of the behavior +of operations over 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" in its metatable. +If it finds one, +Lua calls this function to perform the addition. + +

We call the keys in a metatable events +and the values metamethods. +In the previous example, the event is "add" +and the metamethod is the function that performs the addition. + +

You can query the metatable of any value +through the getmetatable function. + +

You can replace the metatable of tables +through the setmetatable +function. +You cannot change the metatable of other types from Lua +(except using the debug library); +you must use the C API for that. + +

Tables and userdata have individual metatables +(although multiple tables and userdata can share +a same table as their metatable); +values of all other types share one single metatable per type. +So, there is one single metatable for all numbers, +and for all strings, etc. + +

A metatable may control how an object behaves in arithmetic operations, +order comparisons, concatenation, length operation, and indexing. +A metatable can also define a function to be called when a userdata +is garbage collected. +For each of these operations Lua associates a specific key +called an event. +When Lua performs one of these operations over a value, +it checks whether this value has a metatable with the corresponding event. +If so, the value associated with that key (the metamethod) +controls how Lua will perform the operation. + +

Metatables control the operations listed next. +Each operation is identified by its corresponding name. +The key for each operation is a string with its name prefixed by +two underscores, `__´; +for instance, the key for operation "add" is the +string "__add". +The semantics of these operations is better explained by a Lua function +describing how the interpreter executes the operation. + +

The code shown here in Lua is only illustrative; +the real behavior is hard coded in the interpreter +and it is much more efficient than this simulation. +All functions used in these descriptions +(rawget, tonumber, etc.) +are described in 5.1. +In particular, to retrieve the metamethod of a given object, +we use the expression +

+       metatable(obj)[event]
+
+This should be read as +
+       rawget(getmetatable(obj) or {}, event)
+
+That is, the access to a metamethod does not invoke other metamethods, +and the access to objects with no metatables does not fail +(it simply results in nil). + +

    +
  • "add": +the + operation. + +

    The function getbinhandler below defines how Lua chooses a handler +for a binary operation. +First, Lua tries the first operand. +If its type does not define a handler for the operation, +then Lua tries the second operand. +

    + function getbinhandler (op1, op2, event)
    +   return metatable(op1)[event] or metatable(op2)[event]
    + end
    +
    +Using this function, +the behavior of the op1 + op2 is +
    + function add_event (op1, op2)
    +   local o1, o2 = tonumber(op1), tonumber(op2)
    +   if o1 and o2 then  -- both operands are numeric?
    +     return o1 + o2   -- `+' here is the primitive `add'
    +   else  -- at least one of the operands is not numeric
    +     local h = getbinhandler(op1, op2, "__add")
    +     if h then
    +       -- call the handler with both operands
    +       return h(op1, op2)
    +     else  -- no handler available: default behavior
    +       error("...")
    +     end
    +   end
    + end
    +
    + +

  • "sub": +the - operation. +Behavior similar to the "add" operation. + +

  • "mul": +the * operation. +Behavior similar to the "add" operation. + +

  • "div": +the / operation. +Behavior similar to the "add" operation. + +

  • "mod": +the % operation. +Behavior similar to the "add" operation, +with the operation +o1 - floor(o1/o2)*o2 as the primitive operation. + +

  • "pow": +the ^ (exponentiation) operation. +Behavior similar to the "add" operation, +with the function pow (from the C math library) +as the primitive operation. + +

  • "unm": +the unary - operation. +
    + function unm_event (op)
    +   local o = tonumber(op)
    +   if o then  -- operand is numeric?
    +     return -o  -- `-' here is the primitive `unm'
    +   else  -- the operand is not numeric.
    +     -- Try to get a handler from the operand
    +     local h = metatable(op).__unm
    +     if h then
    +       -- call the handler with the operand
    +       return h(op)
    +     else  -- no handler available: default behavior
    +       error("...")
    +     end
    +   end
    + end
    +
    + +

  • "concat": +the .. (concatenation) operation. +
    + function concat_event (op1, op2)
    +   if (type(op1) == "string" or type(op1) == "number") and
    +      (type(op2) == "string" or type(op2) == "number") then
    +     return op1 .. op2  -- primitive string concatenation
    +   else
    +     local h = getbinhandler(op1, op2, "__concat")
    +     if h then
    +       return h(op1, op2)
    +     else
    +       error("...")
    +     end
    +   end
    + end
    +
    + +

  • "len": +the # operation. +
    + function len_event (op)
    +   if type(op) == "string" then
    +     return strlen(op)         -- primitive string length
    +   elseif type(op) == "table" then
    +     return #op                -- primitive table length
    +   else
    +     local h = metatable(op).__len
    +     if h then
    +       -- call the handler with the operand
    +       return h(op)
    +     else  -- no handler available: default behavior
    +       error("...")
    +     end
    +   end
    + end
    +
    +See 2.5.5 for a description of the length of a table. + +

  • "eq": +the == operation. +The function getcomphandler defines how Lua chooses a metamethod +for comparison operators. +A metamethod only is selected when both objects +being compared have the same type +and the same metamethod for the selected operation. +
    + function getcomphandler (op1, op2, event)
    +   if type(op1) ~= type(op2) then return nil end
    +   local mm1 = metatable(op1)[event]
    +   local mm2 = metatable(op2)[event]
    +   if mm1 == mm2 then return mm1 else return nil end
    + end
    +
    +The "eq" event is defined as follows: +
    + function eq_event (op1, op2)
    +   if type(op1) ~= type(op2) then  -- different types?
    +     return false   -- different objects
    +   end
    +   if op1 == op2 then   -- primitive equal?
    +     return true   -- objects are equal
    +   end
    +   -- try metamethod
    +   local h = getcomphandler(op1, op2, "__eq")
    +   if h then
    +     return h(op1, op2)
    +   else
    +     return false
    +   end
    + end
    +
    +a ~= b is equivalent to not (a == b). + +

  • "lt": +the < operation. +
    + function lt_event (op1, op2)
    +   if type(op1) == "number" and type(op2) == "number" then
    +     return op1 < op2   -- numeric comparison
    +   elseif type(op1) == "string" and type(op2) == "string" then
    +     return op1 < op2   -- lexicographic comparison
    +   else
    +     local h = getcomphandler(op1, op2, "__lt")
    +     if h then
    +       return h(op1, op2)
    +     else
    +       error("...");
    +     end
    +   end
    + end
    +
    +a > b is equivalent to b < a. + +

  • "le": +the <= operation. +
    + function le_event (op1, op2)
    +   if type(op1) == "number" and type(op2) == "number" then
    +     return op1 <= op2   -- numeric comparison
    +   elseif type(op1) == "string" and type(op2) == "string" then
    +     return op1 <= op2   -- lexicographic comparison
    +   else
    +     local h = getcomphandler(op1, op2, "__le")
    +     if h then
    +       return h(op1, op2)
    +     else
    +       h = getcomphandler(op1, op2, "__lt")
    +       if h then
    +         return not h(op2, op1)
    +       else
    +         error("...");
    +       end
    +     end
    +   end
    + end
    +
    +a >= b is equivalent to b <= a. +Note that, in the absence of a "le" metamethod, +Lua tries the "lt", assuming that a <= b is +equivalent to not (b < a). + +

  • "index": +The indexing access table[key]. +
    + function gettable_event (table, key)
    +   local h
    +   if type(table) == "table" then
    +     local v = rawget(table, key)
    +     if v ~= nil then return v end
    +     h = metatable(table).__index
    +     if h == nil then return nil end
    +   else
    +     h = metatable(table).__index
    +     if h == nil then
    +       error("...");
    +     end
    +   end
    +   if type(h) == "function" then
    +     return h(table, key)      -- call the handler
    +   else return h[key]          -- or repeat operation on it
    +   end
    + end
    +
    + +

  • "newindex": +The indexing assignment table[key] = value. +
    + function settable_event (table, key, value)
    +   local h
    +   if type(table) == "table" then
    +     local v = rawget(table, key)
    +     if v ~= nil then rawset(table, key, value); return end
    +     h = metatable(table).__newindex
    +     if h == nil then rawset(table, key, value); return end
    +   else
    +     h = metatable(table).__newindex
    +     if h == nil then
    +       error("...");
    +     end
    +   end
    +   if type(h) == "function" then
    +     return h(table, key,value)    -- call the handler
    +   else h[key] = value             -- or repeat operation on it
    +   end
    + end
    +
    + +

  • "call": +called when Lua calls a value. +
    + function function_event (func, ...)
    +   if type(func) == "function" then
    +     return func(...)   -- primitive call
    +   else
    +     local h = metatable(func).__call
    +     if h then
    +       return h(func, ...)
    +     else
    +       error("...")
    +     end
    +   end
    + end
    +
    + +

+ +

2.9 - Environments

+ +

Besides metatables, +objects of types thread, function, and userdata +have another table associated with them, +called their environment. +Like metatables, environments are regular tables and +multiple objects can share the same environment. + +

Environments associated with userdata have no meaning for Lua. +It is only a feature for programmers to associate a table to +a userdata. + +

Environments associated with threads are called +global environments. +They are used as the default environment for threads and +non-nested functions created by the thread +(through loadfile, loadstring or load) +and can be directly accessed by C code (see 3.3). + +

Environments associated with C functions can be directly +accessed by C code (see 3.3). +They are used as the default environment for other C functions +created by the function. + +

Environments associated with Lua functions are used to resolve +all accesses to global variables within the function (see 2.3). +They are used as the default environment for other Lua functions +created by the function. + +

You can change the environment of a Lua function or the +running thread by calling setfenv. +You can get the environment of a Lua function or the running thread +by calling getfenv. +To manipulate the environment of other objects +(userdata, C functions, other threads) you must +use the C API. + +

2.10 - Garbage Collection

+ +

Lua performs automatic memory management. +This means that +you have to worry neither about allocating memory for new objects +nor about freeing it when the objects are no longer needed. +Lua manages memory automatically by running +a garbage collector from time to time +to collect all dead objects +(that is, these objects that are no longer accessible from Lua). +All objects in Lua are subject to automatic management: +tables, userdata, functions, threads, and strings. + +

Lua implements an incremental mark-and-sweep collector. +It uses two numbers to control its garbage-collection cycles: +the garbage-collector pause and +the garbage-collector step multiplier. + +

The garbage-collector pause +controls how long the collector waits before starting a new cycle. +Larger values make the collector less aggressive. +Values smaller than 1 mean the collector will not wait to +start a new cycle. +A value of 2 means that the collector waits for the total memory in use +to double before starting a new cycle. + +

The step multiplier +controls the relative speed of the collector relative to +memory allocation. +Larger values make the collector more aggressive but also increases +the size of each incremental step. +Values smaller than 1 make the collector too slow and +may result in the collector never finishing a cycle. +The default, 2, means that the collector runs at "twice" +the speed of memory allocation. + +

You can change these numbers by calling lua_gc in C +or collectgarbage in Lua. +Both get as arguments percentage points +(so an argument 100 means a real value of 1). +With these functions you can also control +the collector directly (e.g., stop and restart it). + +

2.10.1 - Garbage-Collection Metamethods

+ +

Using the C API, +you can set garbage-collector metamethods for userdata (see 2.8). +These metamethods are also called finalizers. +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). + +

Garbage userdata with a field __gc in their metatables are not +collected immediately by the garbage collector. +Instead, Lua puts them in a list. +After the collection, +Lua does the equivalent of the following function +for each userdata in that list: +

+ function gc_event (udata)
+   local h = metatable(udata).__gc
+   if h then
+     h(udata)
+   end
+ end
+
+ +

At the end of each garbage-collection cycle, +the finalizers for userdata are called in reverse +order of their creation, +among those collected in that cycle. +That is, the first finalizer to be called is the one associated +with the userdata created last in the program. + +

2.10.2 - 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 this object. + +

A weak table can have weak keys, weak values, or both. +A table with weak keys allows the collection of its keys, +but prevents the collection of its values. +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 value of the +__mode field of its metatable. +If the __mode field is a string containing the character `k´, +the keys in the table are weak. +If __mode contains `v´, +the values in the table are weak. + +

After you use a table as a metatable, +you should not change the value of its field __mode. +Otherwise, the weak behavior of the tables controlled by this +metatable is undefined. + +

2.11 - 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 with a call to 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 execution. + +

When you first call coroutine.resume, +passing as its first argument +the thread returned by coroutine.create, +the coroutine starts its execution, +at the first line of its main function. +Extra arguments passed to coroutine.resume are passed on +to the coroutine main 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 the first case, coroutine.resume returns true, +plus any values returned by the coroutine main function. +In case of errors, coroutine.resume returns false +plus an error message. + +

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. + +

The coroutine.wrap function creates a coroutine, +just like coroutine.create, +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, +coroutine.wrap does not catch errors; +any error is propagated to the caller. + +

As an example, +consider the next 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
+
+ +

+

3 - 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. +All such macros use each of its 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 a proper definition for the macro luai_apicheck, +in file luaconf.h. + +

3.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.). + +

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 pushes 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); +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. +We say that an index is valid +if it lies between 1 and the stack top +(that is, if 1 <= abs(index) <= top). + + +

3.2 - Stack Size

+ +

When you interact with Lua API, +you are responsible for ensuring consistency. +In particular, +you are responsible for controlling stack overflow. +You can use the function lua_checkstack +to grow the stack size. + +

Whenever Lua calls C, +it ensures that at least LUA_MINSTACK stack positions are available. +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. + +

Most query functions accept as indices any value inside the +available stack space, that is, indices up to the maximum stack size +you have set through lua_checkstack. +Such indices are called acceptable indices. +More formally, we define an acceptable index +as follows: +

+       (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
+
+Note that 0 is never an acceptable index. + +

3.3 - Pseudo-Indices

+ +

Unless otherwise noted, +any function that accepts valid indices can also be called with +pseudo-indices, +which represent some Lua values that are accessible to C code +but which are not in the stack. +Pseudo-indices are used to access the thread environment, +the function environment, +the registry, +and the upvalues of a C function (see 3.4). + +

The thread environment (where global variables live) is +always at pseudo-index LUA_GLOBALSINDEX. +The environment of the running C function is always +at pseudo-index LUA_ENVIRONINDEX. + +

To access and change the value of global variables, +you can use regular table operations over an environment table. +For instance, to access the value of a global variable, do +

+       lua_getfield(L, LUA_GLOBALSINDEX, varname);
+
+ +

3.4 - C Closures

+ +

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

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 value associated with a function is at position +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, +produces an acceptable (but invalid) index. + +

3.5 - Registry

+ +

Lua provides a registry, +a pre-defined table that can be used by any C code to +store whatever Lua value it needs to store. +This table is always located at pseudo-index +LUA_REGISTRYINDEX. +Any C library can store data into this table, +but it should take care to choose keys 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. + +

The integer keys in the registry are used by the reference mechanism, +implemented by the auxiliary library, +and therefore should not be used for other purposes. + +

3.6 - Error Handling in C

+ +

Internally, Lua uses the C longjmp facility to handle errors. +(You can also choose to use exceptions if you use C++; +See file luaconf.h.) +When Lua faces any error +(such as memory allocation errors, type errors, syntax errors, +and runtime errors) +it raises an error; +that is, it does a long jump. +A protected environment uses setjmp +to set a recover point; +any error jumps to the most recent active recover point. + +

Almost any function in the API may raise an error, +for instance due to a memory allocation error. +The following functions run in protected mode +(that is, they create a protected environment to run), +so they never raise an error: +lua_newstate, lua_close, lua_load, +lua_pcall, and lua_cpcall. + +

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

3.7 - Functions and Types

+ +

Here we list all functions and types from the C API in +alphabetical order. + +

+


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; +nsize, the new size of the block. +ptr is NULL if and only if osize is zero. +When nsize is zero, the allocator must return NULL; +if osize is not zero, +it should free the block pointed to by ptr. +When nsize is not zero, the allocator returns NULL +if and only if it cannot fill the request. +When nsize is not zero and osize is zero, +the allocator should behave like malloc. +When nsize and osize are not zero, +the allocator behaves like realloc. +Lua assumes that the allocator never fails when +osize >= nsize. + +

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

+static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
+  (void)ud;     /* not used */
+  (void)osize;  /* not used */
+  if (nsize == 0) {
+    free(ptr);  /* ANSI requires that free(NULL) has no effect */
+    return NULL;
+  }
+  else
+    /* ANSI requires that realloc(NULL, size) == malloc(size) */
+    return realloc(ptr, nsize);
+}
+
+ +

+


lua_atpanic

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

Sets a new panic function and returns the old one. + +

If an error happens outside any protected environment, +Lua calls a panic function +and then calls exit(EXIT_FAILURE), +thus exiting the host application. +Your panic function may avoid this exit by +never returning (e.g., doing a long jump). + +

The panic function can access the error message at the top of the stack. + +

+


lua_call

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

Calls a function. + +

To call a function you must use the following protocol: +First, the function to be called is pushed onto the stack; +then, the arguments to the function 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. +All arguments and the function value are popped from the stack +when the function is called. +The function results are pushed onto the stack when the function returns. +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. +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 inside the called function is propagated upwards +(with a longjmp). + +

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

+       a = f("how", t.x, 14)
+
+Here it is in C: +
+    lua_getfield(L, LUA_GLOBALSINDEX, "f");          /* function to be called */
+    lua_pushstring(L, "how");                                 /* 1st argument */
+    lua_getfield(L, LUA_GLOBALSINDEX, "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 function with 3 arguments and 1 result */
+    lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global variable `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_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 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 numerical arguments and returns their average and sum: +

+       static int foo (lua_State *L) {
+         int n = lua_gettop(L);    /* number of arguments */
+         lua_Number sum = 0;
+         int i;
+         for (i = 1; i <= n; i++) {
+           if (!lua_isnumber(L, i)) {
+             lua_pushstring(L, "incorrect argument to function `average'");
+             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

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

Ensures that there are at least extra free stack slots in the stack. +It returns false if it cannot grow the stack to that size. +This function never shrinks the stack; +if the stack is already larger than the new size, +it is left unchanged. + +

+


lua_close

+
+          void lua_close (lua_State *L);
+
+ + +

Destroys 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, +such as a daemon or a web server, +might need to release states as soon as they are not needed, +to avoid growing too large. + +

+


lua_concat

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

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

+


lua_cpcall

+
+          int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
+
+ + +

Calls the C function func in protected mode. +func starts with only one element in its stack, +a light userdata containing ud. +In case of errors, +lua_cpcall returns the same error codes as lua_pcall, +plus the error object on the top of the stack; +otherwise, it returns zero, and does not change the stack. +All values returned by func are discarded. + +

+


lua_createtable

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

Creates a new empty table and pushes it onto the stack. +The new table has space pre-allocated +for narr array elements and nrec non-array elements. +This pre-allocation is useful when you know exactly how many elements +the table will have. +Otherwise you can use the function lua_newtable. + +

+


lua_dump

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

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. + +

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_equal

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

Returns 1 if the two values in acceptable indices index1 and +index2 are equal, +following the semantics of the Lua == operator +(that is, may call metamethods). +Otherwise returns 0. +Also returns 0 if any of the indices is non valid. + +

+


lua_error

+
+          int lua_error (lua_State *L);
+
+ + +

Generates a Lua error. +The error message (which can actually be a Lua value of any type) +must be on the stack top. +This function does a long jump, +and therefore never returns. +(see luaL_error). + +

+


lua_gc

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

Controls the garbage collector. + +

This function performs several tasks, +according to the value of the parameter what: +

    +
  • LUA_GCSTOP--- stops the garbage collector. +
  • LUA_GCRESTART--- restarts the garbage collector. +
  • LUA_GCCOLLECT--- performs a full garbage-collection cycle. +
  • 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--- performs an incremental step of +garbage collection. +The step "size" is controlled by data +(larger values mean more steps) in a non-specified way. +If you want to control the step size +you must tune experimentally the value of data. +The function returns 1 if the step finished a +garbage-collection cycle. +
  • LUA_GCSETPAUSE--- +sets data/100 as the new value +for the pause of the collector (see 2.10). +The function returns the previous value of the pause. +
  • LUA_GCSETSTEPMUL--- +sets arg/100 as the new value for the step multiplier of +the collector (see 2.10). +The function returns the previous value of the step multiplier. +
+ +

+


lua_getallocf

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

Returns the memory allocator function of a given state. +If ud is not NULL, Lua stores in *ud the +opaque pointer passed to lua_newstate. + +

+


lua_getfenv

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

Pushes on the stack the environment table of +the value at the given index. + +

+


lua_getfield

+
+          void 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 valid index index. +As in Lua, this function may trigger a metamethod +for the "index" event (see 2.8). + +

+


lua_getglobal

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

Pushes onto the stack the value of the global name. +It is defined as a macro: +

+#define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
+
+ +

+


lua_getmetatable

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

Pushes onto the stack the metatable of the value at the given +acceptable index. +If the index is not valid, +or if the value does not have a metatable, +the function returns 0 and pushes nothing on the stack. + +

+


lua_gettable

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

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

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

+


lua_gettop

+
+          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 +(and so 0 means an empty stack). + +

+


lua_insert

+
+          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. +Cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + +

+


lua_Integer

+
+          typedef ptrdiff_t lua_Integer;
+
+ + +

The type used by the Lua API to represent integral values. + +

By default it is a ptrdiff_t, +which is usually the largest integral type the machine handles +"comfortably". + +

+


lua_isboolean

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

Returns 1 if the value at the given acceptable index has type boolean, +and 0 otherwise. + +

+


lua_iscfunction

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

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

+


lua_isfunction

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

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

+


lua_islightuserdata

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

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

+


lua_isnil

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

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

+


lua_isnumber

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

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

+


lua_isstring

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

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

+


lua_istable

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

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

+


lua_isthread

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

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

+


lua_isuserdata

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

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

+


lua_lessthan

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

Returns 1 if the value at acceptable index index1 is smaller +than the value at acceptable index index2, +following the semantics of the Lua < operator +(that is, may call metamethods). +Otherwise returns 0. +Also returns 0 if any of the indices is non valid. + +

+


lua_load

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

Loads a Lua chunk. +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 return values of lua_load are: +

    +
  • 0 --- no errors; +
  • LUA_ERRSYNTAX --- +syntax error during pre-compilation. +
  • LUA_ERRMEM --- +memory allocation error. +
+ +

lua_load automatically detects whether the chunk is text or binary, +and loads it accordingly (see program luac). + +

lua_load 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 3.8). + +

+


lua_newstate

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

Creates a new, independent state. +Returns NULL if cannot create the state +(due to lack of memory). +The argument f is the allocator function; +Lua does all memory allocation for this state through this function. +The second argument, ud, is an opaque pointer that Lua +simply passes to the allocator in every call. + +

+


lua_newtable

+
+          void lua_newtable (lua_State *L);
+
+ + +

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

+


lua_newthread

+
+          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 state returned by this function shares with the original state +all global objects (such as tables), +but has an independent execution stack. + +

There is no explicit function to close or to destroy a thread. +Threads are subject to garbage collection, +like any Lua object. + +

+


lua_newuserdata

+
+          void *lua_newuserdata (lua_State *L, size_t size);
+
+ + +

This function allocates a new block of memory with the given size, +pushes on the stack a new full userdata with the block address, +and returns this address. + +

Userdata represents C values in Lua. +A full userdata represents a block of memory. +It is an object (like a table): +You must create it, it can have its own metatable, +and you can detect when it is being collected. +A full userdata is only equal to itself (under raw equality). + +

When Lua collects a full userdata with a gc metamethod, +Lua calls the metamethod and marks the userdata as finalized. +When this userdata is collected again then +Lua frees its corresponding memory. + +

+


lua_next

+
+          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 traversal looks like this: +

+       /* table is in the stack at index `t' */
+       lua_pushnil(L);  /* first key */
+       while (lua_next(L, t) != 0) {
+         /* `key' is 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)));
+         lua_pop(L, 1);  /* removes `value'; keeps `key' for next iteration */
+       }
+
+ +

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

+


lua_Number

+
+          typedef double lua_Number;
+
+ + +

The type of numbers in Lua. +By default, it is double, but that can be changed in luaconf.h. + +

Through the configuration file you can change +Lua to operate with another type for numbers (e.g., float or long). + +

+


lua_objlen

+
+          size_t lua_objlen (lua_State *L, int index);
+
+ + +

Returns the "length" of the value at the given acceptable index: +for strings, this is the string length; +for tables, this is the result of the length operator (`#´); +for userdata, this is the size of the block of memory allocated +for the userdata; +for other values, it is 0. + +

+


lua_pcall

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

Calls a function 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 message), +and returns an error code. +Like lua_call, +lua_pcall always removes the function +and its arguments from the stack. + +

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

Typically, the error handler function is used to add more debug +information to the error message, 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 0 in case of success +or one of the following error codes +(defined in lua.h): +

    +
  • LUA_ERRRUN --- a runtime error. +
  • LUA_ERRMEM --- memory allocation error. +For such errors, Lua does not call the error handler function. +
  • LUA_ERRERR --- +error while running the error handler function. +
+ +

+


lua_pop

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

Pops n elements from the stack. + +

+


lua_pushboolean

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

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

+


lua_pushcclosure

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

Pushes a new C closure onto the stack. + +

When a C function is created, +it is possible to associate some values with it, +thus creating a C closure (see 3.4); +these values are then accessible to the function whenever it is called. +To associate values with a C function, +first these values should be pushed onto the stack +(when there are multiple values, 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 should be +associated with the function. +lua_pushcclosure also pops these values from the stack. + +

+


lua_pushcfunction

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

Pushes a C function onto the stack. +This function receives a pointer to a C function +and pushes on the stack a Lua value of type function that, +when called, invokes the corresponding C function. + +

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

The call lua_pushcfunction(L, f) is equivalent to +lua_pushcclosure(L, f, 0). + +

+


lua_pushfstring

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

Pushes onto the stack a formatted string +and returns a pointer to this string. +It is similar to the C function sprintf, +but has some important differences: +

    +
  • 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). +
  • The conversion specifiers are quite restricted. +There are no flags, widths, or precisions. +The conversion specifiers can only be +`%%´ (inserts a `%´ in the string), +`%s´ (inserts a zero-terminated string, with no size restrictions), +`%f´ (inserts a lua_Number), +`%p´ (inserts a pointer as a hexadecimal numeral), +`%d´ (inserts an int), and +`%c´ (inserts an int as a character). +
+ +

+


lua_pushinteger

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

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

+


lua_pushlightuserdata

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

Pushes a light userdata onto the stack. + +

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

+


lua_pushlstring

+
+          void 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 makes (or reuses) 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 embedded zeros. + +

+


lua_pushnil

+
+          void lua_pushnil (lua_State *L);
+
+ + +

Pushes a nil value onto the stack. + +

+


lua_pushnumber

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

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

+


lua_pushstring

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

Pushes the zero-terminated string pointed to by s +onto the stack. +Lua makes (or reuses) an internal copy of the given string, +so the memory at s can be freed or reused immediately after +the function returns. +The string cannot contain embedded zeros; +it is assumed to end at the first zero. + +

+


lua_pushthread

+
+          void lua_pushthread (lua_State *L);
+
+ + +

Pushes the thread represented by L onto the stack. + +

+


lua_pushvalue

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

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

+


lua_pushvfstring

+
+          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

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

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

+


lua_rawget

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

Similar to lua_gettable, but does a raw access +(i.e., without metamethods). + +

+


lua_rawgeti

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

Pushes onto the stack the value t[n], +where t is the value at the given valid index index. +The access is raw; +that is, it does not invoke metamethods. + +

+


lua_rawset

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

Similar to lua_settable, but does a raw assignment +(i.e., without metamethods). + +

+


lua_rawseti

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

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

This function pops the value from the stack. +The assignment is raw; +that is, it does not invoke metamethods. + +

+


lua_Reader

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

The reader function used by lua_load. +Every time it needs another piece of the chunk, +lua_load 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. +The reader function may return pieces of any size greater than zero. + +

+


lua_register

+
+          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

+
+          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. +Cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + +

+


lua_replace

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

Moves the top element into the given position (and pops it), +without shifting any element +(therefore replacing the value at the given position). + +

+


lua_resume

+
+          int lua_resume (lua_State *L, int narg);
+
+ + +

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

To start a coroutine, you first create a new thread +(see lua_newthread); +then you push on its stack the main function plus any eventual arguments; +then you call lua_resume, +with narg being the number of arguments. +This call returns when the coroutine suspends or finishes its execution. +When it returns, the stack contains all values passed to lua_yield, +or all values returned by the body function. +lua_resume returns +LUA_YIELD if the coroutine yields, +0 if the coroutine finishes its execution +without errors, +or an error code in case of errors (see lua_pcall). +In case of errors, +the stack is not unwound, +so you can use the debug API over it. +The error message is on the top of the stack. +To restart a coroutine, you put on its stack only the values to +be passed as results from yield, +and then call lua_resume. + +

+


lua_setallocf

+
+          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_setfenv

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

Pops a table from the stack and sets it as +the new environment for the value at the given index. +If the value at the given index is +neither a function nor a thread nor a userdata, +lua_setfenv returns 0. +Otherwise it returns 1. + +

+


lua_setfield

+
+          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 valid index index +and v is the value at 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.8). + +

+


lua_setglobal

+
+          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. +It is defined as a macro: +

+#define lua_setglobal(L,s)   lua_setfield(L, LUA_GLOBALSINDEX, s)
+
+ +

+


lua_setmetatable

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

Pops a table from the stack and +sets it as the new metatable for the value at the given +acceptable index. + +

+


lua_settable

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

Does the equivalent to t[k] = v, +where t is the value at the given valid index index, +v is the value at 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.8). + +

+


lua_settop

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

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

+


lua_State

+
+          typedef struct lua_State lua_State;
+
+ + +

Opaque structure that keeps the whole state of a Lua interpreter. +The Lua library is fully reentrant: +it has no global variables. +All information about a state is kept in this structure. + +

A pointer to this state 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

+
+          int lua_status (lua_State *L);
+
+ + +

Returns the status of the thread L. + +

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

+


lua_toboolean

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

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

+


lua_tocfunction

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

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

+


lua_tointeger

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

Converts the Lua value at the given acceptable index +to the signed integral type lua_Integer. +The Lua value must be a number or a string convertible to a number +(see 2.2.1); +otherwise, lua_tointeger returns 0. + +

If the number is not an integer, +it is truncated in some non-specified way. + +

+


lua_tolstring

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

Converts the Lua value at the given acceptable index to a string +(const char*). +If len is not NULL, +it also 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 fully aligned pointer +to a string inside the Lua state. +This string always has a zero (`\0´) +after its last character (as in C), +but may contain other zeros in its body. +Because Lua has garbage collection, +there is no guarantee that the pointer returned by lua_tolstring +will be valid after the corresponding value is removed from the stack. + +

+


lua_tonumber

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

Converts the Lua value at the given acceptable index +to a number (see lua_Number). +The Lua value must be a number or a string convertible to a number +(see 2.2.1); +otherwise, lua_tonumber returns 0. + +

+


lua_topointer

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

Converts the value at the given acceptable index to a generic +C pointer (void*). +The value may be a userdata, a table, a thread, or a function; +otherwise, lua_topointer returns NULL. +Lua ensures that different objects return different pointers. +There is no direct way to convert the pointer back to its original value. + +

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

+


lua_tostring

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

Equivalent to lua_tolstring with len equal to NULL. + +

+


lua_tothread

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

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

+


lua_touserdata

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

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

+


lua_type

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

Returns the type of the value in the given acceptable index, +or LUA_TNONE for a non-valid index +(that is, an index to an "empty" stack position). +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

+
+          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_Writer

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

The writer function used by lua_dump. +Every time it produces another piece of chunk, +lua_dump calls the writer, +passing along the buffer to be written (p), +its size (sz), +and the data 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 global state. + +

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

+


lua_yield

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

Yields a coroutine. + +

This function should only be called as the +return expression of a C function, as follows: +

+       return lua_yield (L, nresults);
+
+When a C function calls lua_yield in that way, +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 are passed as results to lua_resume. + +

+

3.8 - 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) */
+            int currentline;            /* (l) */
+            int nups;                   /* (u) number of upvalues */
+            int linedefined;            /* (S) */
+            int lastlinedefined;        /* (S) */
+            char short_src[LUA_IDSIZE]; /* (S) */
+            /* private part */
+            ...
+          } lua_Debug;
+
+
+ + +

A structure used to carry different pieces of +information about an active function. +lua_getstack fills only the private part +of this structure, for later use. +To fill the other fields of lua_Debug with useful information, +call lua_getinfo. + +

The fields of lua_Debug have the following meaning: +

    +
  • source --- +If the function was defined in a string, +then source is that string. +If the function was defined in a file, +then source starts with a `@´ followed by the file name. + +

  • 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, +and "tail" if it was a function that did a tail call. +In the latter case, +Lua has no other information about the function. + +

  • 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 may be the value of multiple global variables, +while others may 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.) + +

  • nups --- +the number of upvalues of the function. + +

+ +

+


lua_gethook

+
+          lua_Hook lua_gethook (lua_State *L);
+
+ + +

Returns the current hook function. + +

+


lua_gethookcount

+
+          int lua_gethookcount (lua_State *L);
+
+ + +

Returns the current hook count. + +

+


lua_gethookmask

+
+          int lua_gethookmask (lua_State *L);
+
+ + +

Returns the current hook mask. + +

+


lua_getinfo

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

Fills the fields of lua_Debug with useful information. + +

This function returns 0 on error +(for instance, an invalid option in what). +Each character in the string what +selects some fields of the structure ar to be filled, +as indicated by the letter in parentheses in the definition of lua_Debug: +`S´ fills in the fields source, linedefined, +lastlinedefined, +and what; +`l´ fills in the field currentline, etc. +Moreover, `f´ pushes onto the stack the function that is +running at the given level. + +

To get information about a function that is not active +(that is, not in the stack), +you push it onto the stack +and start the what string with the character `>´. +For instance, to know in which line a function f was defined, +you can write the following code: +

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

+


lua_getlocal

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

Gets information about a local variable of a given activation record. +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 +(1 is the first parameter or active local variable, and so on, +until the last active local variable). +lua_getlocal pushes the variable's value onto the stack +and returns its name. + +

Variable names starting with `(´ (open parentheses) +represent internal variables +(loop control variables, temporaries, and C function locals). + +

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

+


lua_getstack

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

Get 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. +When there are no errors, lua_getstack returns 1; +when called with a level greater than the stack depth, +it returns 0. + +

+


lua_getupvalue

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

Gets information about a closure's upvalue. +(For Lua functions, +upvalues are the external local variables that the function uses, +and that are consequently included in its closure.) +lua_getupvalue gets the index n of an upvalue, +pushes the upvalue's value onto the stack, +and returns its name. +funcindex points to the closure in the stack. +(Upvalues have no particular order, +as they are active through the whole function. +So, they are numbered in an arbitrary order.) + +

Returns NULL (and pushes nothing) +when the index is greater than the number of upvalues. +For C functions, this function uses the empty string "" +as a name for all 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_HOOKTAILRET, 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 return events, event may be LUA_HOOKRET, +the normal value, or LUA_HOOKTAILRET. +In the latter case, Lua is simulating a return from +a function that did a tail call; +in this case, it is useless to call lua_getinfo. + +

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. + +

+


lua_sethook

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

Sets the debugging hook function. + +

func 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, +before the function gets its arguments. +
  • The return hook is called when the interpreter returns from a function. +The hook is called just before Lua leaves the function. +You have no access to the values to be returned by 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.) +
+ +

A hook is disabled by setting mask to zero. + +

+


lua_setlocal

+
+          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. +Parameters ar and n are as in lua_getlocal +(see lua_getlocal). +lua_setlocal assigns the value at 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. + +

+


lua_setupvalue

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

Sets the value of a closure's upvalue. +Parameters funcindex and n are as in lua_getupvalue +(see lua_getupvalue). +It assigns the value at 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 is greater than the number of upvalues. + +

+

4 - 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 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 this API. + +

Several functions in the auxiliary library are used to +check C function arguments. +Their names are always luaL_check* or luaL_opt*. +All of these functions raise an error if the check is not satisfied. +Because the error message is formatted for arguments +(e.g., "bad argument #1"), +you should not use these functions for other stack values. + +

4.1 - Functions and Types

+ +

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

+


luaL_addchar

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

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

+


luaL_addlstring

+
+          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 may contain embedded zeros. + +

+


luaL_addsize

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

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

+


luaL_addstring

+
+          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). +The string may not contain embedded zeros. + +

+


luaL_addvalue

+
+          void luaL_addvalue (luaL_Buffer *B);
+
+ + +

Adds the value at 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

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

Checks whether cond is true. +If not, raises an error with message +"bad argument #<numarg> to <func> (<extramsg>)", +where func is retrieved from the call stack. + +

+


luaL_argerror

+
+          int luaL_argerror (lua_State *L, int numarg, const char *extramsg);
+
+ + +

Raises an error with message +"bad argument #<numarg> to <func> (<extramsg>)", +where func is retrieved from the call stack. + +

This function never returns, +but it is an idiom to use it as return luaL_argerror ... +in C functions. + +

+


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 you declare a variable b of type luaL_Buffer. +
  • Then you initialize it with a call luaL_buffinit(L, &b). +
  • Then you add string pieces to the buffer calling any of +the luaL_add* functions. +
  • You finish by calling luaL_pushresult(&b). +This call leaves the final string on the top of the stack. +
+ +

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_buffinit

+
+          void luaL_buffinit (lua_State *L, luaL_Buffer *B);
+
+ + +

Initializes a buffer B. +This function does not allocate any space; +the buffer must be declared as a variable +(see luaL_Buffer). + +

+


luaL_callmeta

+
+          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 and passes the object as its only argument. +In this case this function returns 1 and pushes on the +stack the value returned by the call. +If there is no metatable or no metamethod, +this function returns 0 (without pushing any value on the stack). + +

+


luaL_checkany

+
+          void luaL_checkany (lua_State *L, int narg);
+
+ + +

Checks whether the function has an argument +of any type (including nil) at position narg. + +

+


luaL_checkint

+
+          int luaL_checkint (lua_State *L, int narg);
+
+ + +

Checks whether the function argument narg is a number +and returns this number cast to an int. + +

+


luaL_checkinteger

+
+          lua_Integer luaL_checkinteger (lua_State *L, int narg);
+
+ + +

Checks whether the function argument narg is a number +and returns this number cast to a lua_Integer. + +

+


luaL_checklong

+
+          long luaL_checklong (lua_State *L, int narg);
+
+ + +

Checks whether the function argument narg is a number +and returns this number cast to a long. + +

+


luaL_checklstring

+
+          const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
+
+ + +

Checks whether the function argument narg is a string +and returns this string; +if l is not NULL fills *l +with the string's length. + +

+


luaL_checknumber

+
+          lua_Number luaL_checknumber (lua_State *L, int narg);
+
+ + +

Checks whether the function argument narg is a number +and returns this number. + +

+


luaL_checkoption

+
+          int luaL_checkoption (lua_State *L, int narg, const char *def,
+                                const char *const lst[]);
+
+ + +

Checks whether the function argument narg is a string and +searches for this string in the array lst +(which must be NULL-terminated). +If def is not NULL, +uses def as a default value when +the function has no argument narg or if this argument is nil. + +

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. + +

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

+
+          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. + +

+


luaL_checkstring

+
+          const char *luaL_checkstring (lua_State *L, int narg);
+
+ + +

Checks whether the function argument narg is a string +and returns this string. + +

+


luaL_checktype

+
+          void luaL_checktype (lua_State *L, int narg, int t);
+
+ + +

Checks whether the function argument narg has type t. + +

+


luaL_checkudata

+
+          void *luaL_checkudata (lua_State *L, int narg, const char *tname);
+
+ + +

Checks whether the function argument narg is a userdata +of the type tname (see luaL_newmetatable). + +

+


luaL_error

+
+          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 as return luaL_error ... +in C functions. + +

+


luaL_getmetafield

+
+          int luaL_getmetafield (lua_State *L, int obj, const char *e);
+
+ + +

Pushes on the stack the field e from the metatable +of the object at index obj. +If the object does not have a metatable, +or if the metatable does not have this field, +returns 0 and pushes nothing. + +

+


luaL_getmetatable

+
+          void luaL_getmetatable (lua_State *L, const char *tname);
+
+ + +

Pushes on the stack the metatable associated with name tname +in the registry (see luaL_newmetatable). + +

+


luaL_gsub

+
+          const char *luaL_gsub (lua_State *L, const char *s,
+                                 const char *p, const char *r);
+
+ + +

Creates a copy of string s by replacing +any occurrence of the string p +with the string r. +Pushes the resulting string on the stack and returns it. + +

+


luaL_loadbuffer

+
+          int luaL_loadbuffer (lua_State *L, const char *buff,
+                               size_t sz, const char *name);
+
+ + +

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. + +

+


luaL_loadfile

+
+          int luaL_loadfile (lua_State *L, const char *filename);
+
+ + +

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 #. + +

This function returns the same results as lua_load, +but it has an extra error code LUA_ERRFILE +if it cannot open/read the file. + +

+


luaL_loadstring

+
+          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. + +

+


luaL_newmetatable

+
+          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 it to the registry with key tname, +and returns 1. + +

In both cases pushes on the stack the final value associated +with tname in the registry. + +

+


luaL_newstate

+
+          lua_State *luaL_newstate (void);
+
+ + +

Creates a new Lua state, calling lua_newstate with an +allocation function based on the standard C realloc function +and setting a panic function (see lua_atpanic) that prints +an error message to the standard error output in case of fatal +errors. + +

Returns the new state, +or NULL if there is a memory allocation error. + +

+


luaL_openlibs

+
+          void luaL_openlibs (lua_State *L);
+
+ + +

Opens all standard Lua libraries into the given state. + +

+


luaL_optint

+
+          int luaL_optint (lua_State *L, int narg, int d);
+
+ + +

If the function argument narg is a number, +returns this number cast to an int. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + +

+


luaL_optinteger

+
+          lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);
+
+ + +

If the function argument narg is a number, +returns this number cast to a lua_Integer. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + +

+


luaL_optlong

+
+          long luaL_optlong (lua_State *L, int narg, long d);
+
+ + +

If the function argument narg is a number, +returns this number cast to a long. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + +

+


luaL_optlstring

+
+          const char *luaL_optlstring (lua_State *L, int narg,
+                                       const char *d, size_t *l);
+
+ + +

If the function argument narg 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 the position *l with the results's length. + +

+


luaL_optnumber

+
+          lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
+
+ + +

If the function argument narg is a number, +returns this number. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + +

+


luaL_optstring

+
+          const char *luaL_optstring (lua_State *L, int narg, const char *d);
+
+ + +

If the function argument narg is a string, +returns this string. +If this argument is absent or is nil, +returns d. +Otherwise, raises an error. + +

+


luaL_prepbuffer

+
+          char *luaL_prepbuffer (luaL_Buffer *B);
+
+ + +

Returns an address to a space of size LUAL_BUFFERSIZE +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_pushresult

+
+          void luaL_pushresult (luaL_Buffer *B);
+
+ + +

Finishes the use of buffer B leaving the final string on +the top of the stack. + +

+


luaL_ref

+
+          int luaL_ref (lua_State *L, int t);
+
+ + +

Creates and returns a reference, +in the table at index t, +for the object at 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 table t, +luaL_ref ensures the uniqueness of the key it returns. +You can retrieve an object referred by reference r +by calling lua_rawgeti(L, t, r). +Function luaL_unref frees a reference and its associated object. + +

If the object at 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_register. +name is the function name and func is a pointer to +the function. +Any array of luaL_Reg must end with an sentinel entry +in which both name and func are NULL. + +

+


luaL_register

+
+          void luaL_register (lua_State *L, const char *libname,
+                              const luaL_Reg *l);
+
+ + +

Opens a library. + +

When called with libname equal to NULL, +simply registers all functions in the list l +(see luaL_Reg) into the table on the top of the stack. + +

When called with a non-null libname, +creates a new table t, +sets it as the value of the global variable libname, +sets it as the value of package.loaded[libname], +and registers on it all functions in the list l. +If there is a table in package.loaded[libname] or in +variable libname, +reuses this table instead of creating a new one. + +

In any case the function leaves the table +on the top of the stack. + +

+


luaL_typename

+
+          const char *luaL_typename (lua_State *L, int idx);
+
+ + +

Returns the name of the type of the value at index idx. + +

+


luaL_typerror

+
+          int luaL_typerror (lua_State *L, int narg, const char *tname);
+
+ + +

Generates an error with a message like +

+<location>: bad argument <narg> to <function> (<tname> expected, got <realt>)
+
+where <location> is produced by luaL_where, +<function> is the name of the current function, +and <realt> is the type name of the actual argument. + +

+


luaL_unref

+
+          void luaL_unref (lua_State *L, int t, int ref);
+
+ + +

Releases 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

+
+          void luaL_where (lua_State *L, int lvl);
+
+ + +

Pushes on the stack a string identifying the current position +of the control at level lvl in the call stack. +Typically this string has the 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. + +

+

5 - Standard Libraries

+ +

The standard Lua libraries provide useful functions +that are implemented directly 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 are quite useful or have critical performance requirements that +deserve an implementation in C (e.g., sort). + +

All libraries are implemented through the official C API +and are provided as separate C modules. +Currently, Lua has the following standard libraries: +

    +
  • basic library; +
  • package library; +
  • string manipulation; +
  • table manipulation; +
  • mathematical functions (sin, log, etc.); +
  • input and output; +
  • operating system facilities; +
  • debug facilities. +
+Except for the basic and 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 must call +luaL_openlibs, +which open all standard libraries. +Alternatively, +it can open them individually by calling +luaopen_base (for the basic library), +luaopen_package (for the package library), +luaopen_string (for the string library), +luaopen_table (for the table library), +luaopen_math (for the mathematical library), +luaopen_io (for the I/O and the Operating System libraries), +and luaopen_debug (for the debug library). +These functions are declared in lualib.h +and should not be called directly: +you must call them like any other Lua C function, +e.g., by using lua_call. + +

5.1 - Basic Functions

+ +

The basic library provides some 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])

+Issues an error when +the value of its argument v is false (i.e., nil or false); +otherwise, returns all its arguments. +message is an error message; +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: +

    +
  • "stop" --- stops the garbage collector. +
  • "restart" --- restarts the garbage collector. +
  • "collect" --- performs a full garbage-collection cycle. +
  • "count" --- returns the total memory in use by Lua (in Kbytes). +
  • "step" --- performs a garbage-collection step. +The step "size" is controlled by arg +(larger values mean more steps) in a non-specified way. +If you want to control the step size +you must tune experimentally the value of arg. +Returns true if the step finished a collection cycle. +
  • "steppause" --- +sets arg/100 as the new value for the pause of +the collector (see 2.10). +
  • "setstepmul" --- +sets arg/100 as the new value for the step multiplier of +the collector (see 2.10). +
+ +


dofile (filename)

+Opens the named file and executes its contents as a Lua chunk. +When called without arguments, +dofile executes the contents 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])

+Terminates the last protected function called +and returns message as the error message. +Function error never returns. + +

Usually, error adds some information about the error position +at the beginning of the message. +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 (that is, _G._G = _G). +Lua itself does not use this variable; +changing its value does not affect any environment, +nor vice-versa. +(Use setfenv to change environments.) + +


getfenv (f)

+Returns the current environment in use by the function. +f can be a Lua function or a number +that specifies the function at that stack level: +Level 1 is the function calling getfenv. +If the given function is not a Lua function, +or if f is 0, +getfenv returns the global environment. +The default for f is 1. + +


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 ... end
+
+will iterate over the pairs (1,t[1]), (2,t[2]), ..., +up to the first integer key with a nil value in the table. + +

See next for the caveats of modifying the table during its traversal. + +


load (func [, chunkname])

+ +

Loads a chunk using function func to get its pieces. +Each call to func must return a string that concatenates +with previous results. +A return of nil (or no value) signals the end of the chunk. + +

If there are no errors, +returns the compiled chunk as a function; +otherwise, returns nil plus the error message. +The environment of the returned function is the global environment. + +

chunkname is used as the chunk name for error messages +and debug information. + +


loadfile ([filename])

+ +

Similar to load, +but gets the chunk from file filename +or from the standard input, +if no file name is given. + +


loadstring (string [, chunkname])

+ +

Similar to load, +but gets the chunk from the given string. + +

To load and run a given string, use the idiom +

+      assert(loadstring(s))()
+
+ +


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. +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. + +

Lua has no declaration of fields. +There is no difference between a +field not present in a table or a field with value nil. +Therefore, next only considers fields with non-nil values. +The order in which the indices are enumerated is not specified, +even for numeric indices. +(To traverse a table in numeric order, +use a numerical for or the ipairs function.) + +

The behavior of next is undefined if, +during the traversal, +you assign any value to a non-existent field in the table. +You may however modify existing fields. +In particular, you may clear existing fields. + +


pairs (t)

+ +

Returns three values: the next function, the table t, and nil, +so that the construction +

+       for k,v in pairs(t) do ... end
+
+will iterate over all key--value pairs of table t. + +

See next for the caveats of modifying the table during its traversal. + +


pcall (f, arg1, arg2, ...)

+ +

Calls 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 message. + +


print (e1, e2, ...)

+Receives any number of arguments, +and prints their values to stdout, +using the tostring function to convert them to strings. +print is not intended for formatted output, +but only as a quick way to show a value, +typically for debugging. +For formatted output, use string.format. + +


rawequal (v1, v2)

+Checks whether v1 is equal to v2, +without invoking any metamethod. +Returns a boolean. + +


rawget (table, index)

+Gets the real value of table[index], +without invoking any metamethod. +table must be a table and +index any value different from nil. + +


rawset (table, index, value)

+Sets the real value of table[index] to value, +without invoking any metamethod. +table must be a table, +index any value different from nil, +and value any Lua value. + +


select (index, ...)

+ +

If index is a number, +returns all arguments after argument number index. +Otherwise, index must be the string "#", +and select returns the total number of extra arguments it received. + +


setfenv (f, table)

+ +

Sets the environment to be used by the given function. +f can be a Lua function or a number +that specifies the function at that stack level: +Level 1 is the function calling setfenv. +setfenv returns the given function. + +

As a special case, when f is 0 setfenv changes +the environment of the running thread. +In this case, setfenv returns no values. + +


setmetatable (table, metatable)

+ +

Sets the metatable for the given table. +(You cannot change the metatable of other types from Lua, only from C.) +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. + +


tonumber (e [, base])

+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 nil. + +

An optional argument specifies the base to interpret the numeral. +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. +In base 10 (the default), the number may have a decimal part, +as well as an optional exponent part (see 2.1). +In other bases, only unsigned integers are accepted. + +


tostring (e)

+Receives an argument of any type and +converts it to a string in a reasonable format. +For complete control of how numbers are converted, +use string.format. + +

If the metatable of e has a "__tostring" field, +then tostring calls the corresponding value +with e as argument, +and uses the result of the call as its result. + +


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". + +


unpack (list [, i [, j]])

+Returns the elements from the given table. +This function is equivalent to +
+  return list[i], list[i+1], ..., list[j]
+
+except that the above code can be written only for a fixed number +of elements. +By default, i is 1 and j is the length of the list, +as defined by the length operator (see 2.5.5). + +


_VERSION

+A global variable (not a function) that +holds a string containing the current interpreter version. +The current contents of this variable is "Lua 5.1". + +


xpcall (f, err)

+ +

This function is similar to pcall, +except that you can set a new error handler. + +

xpcall calls function f in protected mode, +using err as the error handler. +Any error inside f is not propagated; +instead, xpcall catches the error, +calls the err function with the original error object, +and returns a status code. +Its first result is the status code (a boolean), +which is true if the call succeeds without errors. +In this case, xpcall also returns all results from the call, +after this first result. +In case of any error, +xpcall returns false plus the result from err. + +

5.2 - Coroutine Manipulation

+ +

The operations related to coroutines comprise a sub-library of +the basic library and come inside the table coroutine. +See 2.11 for a general description of coroutines. + +


coroutine.create (f)

+ +

Creates a new coroutine, with body f. +f must be a Lua function. +Returns this new coroutine, +an object with type "thread". + +


coroutine.resume (co [, val1, ..., valn])

+ +

Starts or continues the execution of coroutine co. +The first time you resume a coroutine, +it starts running its body. +The values val1, ..., valn are passed +as the arguments to the body function. +If the coroutine has yielded, +resume restarts it; +the values val1, ..., valn are passed +as the results from the yield. + +

If the coroutine runs without any errors, +resume returns true plus any values passed to yield +(if the coroutine yields) or any values returned by the body function +(if the coroutine terminates). +If there is any error, +resume returns false plus the error message. + +


coroutine.running ()

+ +

Returns the running coroutine, +or nil when called by the main thread. + +


coroutine.status (co)

+ +

Returns the status of coroutine co, as a string: +"running", +if the coroutine is running (that is, it 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 Lua function. +Returns a function that resumes the coroutine each time it is called. +Any arguments passed to the function behave as the +extra arguments to resume. +Returns the same values returned by resume, +except the first boolean. +In case of error, propagates the error. + +


coroutine.yield ([val1, ..., valn])

+ +

Suspends the execution of the calling coroutine. +The coroutine cannot be running a C function, +a metamethod, or an iterator. +Any arguments to yield are passed as extra results to resume. + +

5.3 - Modules

+ +

The package library provides basic +facilities for loading and building modules in Lua. +It exports two of its functions directly in the global environment: +require and module. +Everything else is exported in a table package. + +


module (name [, ...])

+ +

Creates a module. +If there is a table in package.loaded[name], +this table is the module. +Otherwise, if there is a global table t with the given name, +this table is the module. +Otherwise creates a new table t and +sets it as the value of the global name and +the value of package.loaded[name]. +This function also initializes t._NAME with the given name, +t._M with the module (t itself), +and t._PACKAGE with the package name +(the full module name minus last component; see below). +Finally, module sets t as the new environment +of the current function and the new value of package.loaded[name], +so that require returns t. + +

If name is a compound name +(that is, one with components separated by dots), +module creates (or reuses, if they already exist) +tables for each component. +For instance, if name is a.b.c, +then module stores the module table in field c of +field b of global a. + +

This function may receive optional options after +the module name, +where each option is a function to be applied over the module. + +


require (modname)

+ +

Loads the given module. +The function starts by looking into the table package.loaded +to determine whether modname is already loaded. +If it is, then require returns the value stored +at package.loaded[modname]. +Otherwise, it tries to find a loader for the module. + +

To find a loader, +first require queries package.preload[modname]. +If it has a value, +this value (which should 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 below). + +

When loading a C library, +require first uses a dynamic link facility to link the +application with the library. +Then it tries to find a C function inside this 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 prefix up to (and including) the first hyphen is removed. +For instance, if the module name is a.v1-b.c, +the function name will be luaopen_b_c. + +

If require finds neither a Lua library nor a +C library for a module, +it calls the all-in-one loader. +This loader 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. + +

Once a loader is found, +require calls the loader with a single argument, modname. +If the loader returns any value, +require assigns it to package.loaded[modname]. +If the loader returns no 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]. + +

If there is any error loading or running the module, +or if it cannot find any loader for the module, +then require signals an error. + +


package.cpath

+ +

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 +(plus another 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. + +


package.loadlib (libname, funcname)

+ +

Dynamically links the host program with the C library libname. +Inside this library, looks for a function funcname +and returns this function as a C function. +(So, funcname must follow the protocol (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 extension. +funcname must be the exact name exported by the C library +(which may depend on the C compiler and linker used). + +

This function is not supported by ANSI 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). + +


package.path

+ +

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 or +with a default path defined in luaconf.h, +if the environment variable is not defined. +Any ";;" in the value of the environment variable +is replaced by the default path. + +

A path is a sequence of templates separated by semicolons. +For each template, require will change each interrogation +mark in the template by filename, +which is modname with each dot replaced by a +"directory separator" (such as "/" in Unix); +then it will try to load the resulting file name. +So, for instance, if the Lua path is +

+  "./?.lua;./?.lc;/usr/local/?/init.lua"
+
+the search for a Lua loader for module foo +will try to load the files +./foo.lua, ./foo.lc, and +/usr/local/foo/init.lua, in that order. + +


package.preload

+ +

A table to store loaders for specific modules +(see require). + +


package.seeall (module)

+ +

Sets a metatable for module with +its __index field referring to the global environment, +so that this module inherits values +from the global environment. +To be used as an option to function module. + +

5.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 metatable itself. +Therefore, you can use the string functions in object-oriented style. +For instance, string.byte(s, i) +can be written as s:byte(i). + +


string.byte (s [, i [, j]])

+Returns the internal numerical 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. + +

Note that numerical codes are not necessarily portable across platforms. + +


string.char (i1, i2, ...)

+Receives 0 or more integers. +Returns a string with length equal to the number of arguments, +in which each character has the internal numerical code equal +to its corresponding argument. + +

Note that numerical codes are not necessarily portable across platforms. + +


string.dump (function)

+ +

Returns a string containing a binary representation of the given function, +so that a later loadstring on this string returns +a copy of the function. +function must be a Lua function without upvalues. + +


string.find (s, pattern [, init [, plain]])

+Looks for the first match of +pattern 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 nil. +A third, optional numerical argument init specifies +where to start the search; +its default value is 1 and may be negative. +A value of 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". +Note that if plain is given, then init must be given as well. + +

If the pattern has captures, +then in a successful match +the captured values are also returned, +after the two indices. + +


string.format (formatstring, e1, e2, ...)

+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 printf family of +standard C functions. +The only differences are that the options/modifiers +*, l, L, n, p, +and h are not supported +and that there is an extra option, q. +The q option formats a string in a form suitable to be safely read +back by the Lua interpreter: +The string is written between double quotes, +and all double quotes, newlines, embedded zeros, +and backslashes in the string +are correctly escaped when written. +For instance, the call +
+       string.format('%q', 'a string with "quotes" and \n new line')
+
+will produce the string: +
+"a string with \"quotes\" and \
+ new line"
+
+ +

The options c, d, E, e, f, +g, G, i, o, u, X, and x all +expect a number as argument, +whereas q and s expect a string. + +

This function does not accept string values +containing embedded zeros. + +


string.gmatch (s, pattern)

+Returns an iterator function that, +each time it is called, +returns the next captures from pattern over string s. + +

If pattern specifies no captures, +then the whole match is produced in each call. + +

As an example, the following loop +

+  s = "hello world from Lua"
+  for w in string.gmatch(s, "%a+") do
+    print(w)
+  end
+
+will iterate over all the words from string s, +printing one per line. +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
+
+ +


string.gsub (s, pattern, repl [, n])

+Returns a copy of s +in which all occurrences of the pattern have been +replaced by a replacement string specified by repl, +which may be a string, a table, or a function. +gsub also returns, as its second value, +the total number of substitutions made. + +

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 %n, +with n between 1 and 9, +stands for the value of the n-th captured substring (see below). +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 the pattern specifies no captures, +then the whole match is used 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; +if the pattern specifies no captures, +then the whole match is passed as a sole argument. + +

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). + +

The optional last parameter n limits +the maximum number of substitutions to occur. +For instance, when n is 1 only the first occurrence of +pattern is replaced. + +

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 loadstring(s)()
+       end)
+   --> x="4+5 = 9"
+
+   local t = {name="lua", version="5.1"}
+   x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
+   --> x="lua-5.1.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 +pattern in the string s. +If it finds one, then match returns +the captures from the pattern; +otherwise it returns nil. +If pattern specifies no captures, +then the whole match is returned. +A third, optional numerical argument init specifies +where to start the search; +its default value is 1 and may be negative. + +


string.rep (s, n)

+Returns a string that is the concatenation of n copies of +the string s. + +


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 may 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) returns a suffix of s +with length i. + +


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. + +

Patterns

+ +

+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. +
  • %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. +
  • %z --- represents the character with representation 0. +
  • %x (where x is any non-alphanumeric character) --- +represents the character x. +This is the standard way to escape the magic characters. +Any punctuation character (even the non magic) +can be preceded by a `%´ +when used to represent itself in a pattern. + +

  • [set] --- +represents the class which is the union of all +characters in set. +A range of characters may be specified by +separating the end characters of the range with a `-´. +All classes %x described above may 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. + +

    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. + +

+A pattern item may be +

    +
  • +a single character class, +which matches any single character in the class; +
  • +a single character class followed by `*´, +which matches 0 or more repetitions of characters in the class. +These repetition items will always match the longest possible sequence; +
  • +a single character class followed by `+´, +which matches 1 or more repetitions of characters in the class. +These repetition items will always match the longest possible sequence; +
  • +a single character class followed by `-´, +which also matches 0 or more repetitions of characters in the class. +Unlike `*´, +these repetition items will always match the shortest possible sequence; +
  • +a single character class followed by `?´, +which matches 0 or 1 occurrence of a character in the class; +
  • +%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. +
+ +

+A pattern is a sequence of pattern items. +A `^´ 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. + +

+A pattern may 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 empty 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. + +

A pattern cannot contain embedded zeros. Use %z instead. + +

5.5 - Table Manipulation

+This library provides generic functions for table manipulation. +It provides all its functions inside the table table. + +

Most functions in the table library assume that the table +represents an array or a list. +For these functions, when we talk about the "length" of a table +we mean the result of the length operator. + +


table.concat (table [, sep [, i [, j]]])

+Returns table[i]..sep..table[i+1] ... sep..table[j]. +The default value for sep is the empty string, +the default for i is 1, +and the default for j is the length of the table. +If i is greater than j, returns the empty string. + +


table.insert (table, [pos,] value)

+ +

Inserts element value at position pos in table, +shifting up other elements to open space, if necessary. +The default value for pos is n+1, +where n is the length of the table (see 2.5.5), +so that a call table.insert(t,x) inserts x at the end +of table t. + +


table.maxn (table)

+ +

Returns the largest positive numerical index of the given table, +or zero if the table has no positive numerical indices. +(To do its job this function does a linear traversal of +the whole table.) + +


table.remove (table [, pos])

+ +

Removes from table the element at position pos, +shifting down other elements to close the space, if necessary. +Returns the value of the removed element. +The default value for pos is n, +where n is the length of the table, +so that a call table.remove(t) removes the last element +of table t. + +


table.sort (table [, comp])

+Sorts table elements in a given order, in-place, +from table[1] to table[n], +where n is the length of the table. +If comp is given, +then it must be a function that receives two table elements, +and returns true +when the first is less than the second +(so that not comp(a[i+1],a[i]) will be true after the sort). +If comp is not given, +then the standard Lua operator < is used instead. + +

The sort algorithm is not stable; +that is, elements considered equal by the given order +may have their relative positions changed by the sort. + +

5.6 - Mathematical Functions

+ +

This library is an interface to the standard C math library. +It provides all its functions inside the table math. +The library provides the following functions: + + + + + + + + +

+       math.abs     math.acos    math.asin    math.atan    math.atan2
+       math.ceil    math.cos     math.cosh    math.deg     math.exp
+       math.floor   math.fmod    math.frexp   math.ldexp   math.log
+       math.log10   math.max     math.min     math.modf    math.pow
+       math.rad     math.random  math.randomseed           math.sin
+       math.sinh    math.sqrt    math.tan     math.tanh
+
+plus a variable math.pi and +a variable math.huge, +with the value HUGE_VAL. +Most of these functions +are only interfaces to the corresponding functions in the C library. +All trigonometric functions work in radians. +The functions math.deg and math.rad convert +between radians and degrees. + +

The function math.max returns the maximum +value of its numeric arguments. +Similarly, math.min computes the minimum. +Both can be used with 1, 2, or more arguments. + +

The function math.modf corresponds to the modf C function. +It returns two values: +The integral part and the fractional part of its argument. +The function math.frexp also returns 2 values: +The normalized fraction and the exponent of its argument. + +

The functions math.random and math.randomseed +are interfaces to the simple random generator functions +rand and srand that are provided by ANSI C. +(No guarantees can be given for their statistical properties.) +When called without arguments, +math.random returns a pseudo-random real number +in the range [0,1). +When called with a number n, +math.random returns +a pseudo-random integer in the range [1,n]. +When called with two arguments, +l and u, +math.random returns a pseudo-random +integer in the range [l,u]. +The math.randomseed function sets a "seed" +for the pseudo-random generator: +Equal seeds produce equal sequences of numbers. + +

5.7 - Input and Output Facilities

+ +

The I/O library provides two different styles for file manipulation. +The first one uses implicit file descriptors; +that is, there are operations to set a default input file and a +default output file, +and all input/output operations are over these default files. +The second style uses explicit file descriptors. + +

When using implicit file descriptors, +all operations are supplied by table io. +When using explicit file descriptors, +the operation io.open returns a file descriptor +and then all operations are supplied as methods of the file descriptor. + +

The table io also provides +three predefined file descriptors with their usual meanings from C: +io.stdin, io.stdout, and io.stderr. + +

Unless otherwise stated, +all I/O functions return nil on failure +(plus an error message as a second result) +and some value different from nil on success. + +


io.close ([file])

+ +

Equivalent to file:close(). +Without a file, closes the default output file. + +


io.flush ()

+ +

Equivalent to file:flush over the default output file. + +


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 parameters, +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, +each time it is called, +returns a new line from the file. +Therefore, the construction +

+       for line in io.lines(filename) do ... end
+
+will iterate over all lines of the file. +When the iterator function detects the end of file, +it returns nil (to finish the loop) and automatically closes the file. + +

The call io.lines() (without a file name) is equivalent +to io.input():lines(); +that is, it iterates over the lines of the default input file. +In this case it does not close the file when the loop ends. + +


io.open (filename [, mode])

+ +

This function opens a file, +in the mode specified in the string mode. +It returns a new file handle, +or, in case of errors, nil plus an error message. + +

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 may also have a `b´ at the end, +which is needed in some systems to open the file in binary mode. +This string is exactly what is used in the +standard C function fopen. + +


io.output ([file])

+ +

Similar to io.input, but operates over the default output file. + +


io.popen ([prog [, mode]])

+ +

Starts 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"). + +

This function is system dependent and is not available +on all platforms. + +


io.read (format1, ...)

+ +

Equivalent to io.input():read. + +


io.tmpfile ()

+ +

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 nil if obj is not a file handle. + +


io.write (value1, ...)

+ +

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. + +


file:flush ()

+ +

Saves any written data to file. + +


file:lines ()

+ +

Returns an iterator function that, +each time it is called, +returns a new line from the file. +Therefore, the construction +

+       for line in file:lines() do ... end
+
+will iterate over all lines of the file. +(Unlike io.lines, this function does not close the file +when the loop ends.) + +


file:read (format1, ...)

+ +

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 nil if it cannot read data with the specified format. +When called without formats, +it uses a default format that reads the entire next line +(see below). + +

The available formats are +

    +
  • "*n" reads a number; +this is the only format that returns a number instead of a string. +
  • "*a" reads the whole file, starting at the current position. +On end of file, it returns the empty string. +
  • "*l" reads the next line (skipping the end of line), +returning nil on end of file. +This is the default format. +
  • number reads a string with up to this number of characters, +returning nil on end of file. +If number is zero, +it reads nothing and returns an empty string, +or nil on end of file. +
+ +


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, function seek returns the final file position, +measured in bytes from the beginning of the file. +If this function fails, it returns nil, +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 an output file. +There are three available modes: +

    +
  • "no" --- +no buffering; the result of any output operation appears immediately. +
  • "full" --- +full buffering; output operation is performed only +when the buffer is full (or when you explicitly flush the file (see 5.7)). +
  • "line" --- +line buffering; output is buffered until a newline is output +or there is any input from some special files +(such as a terminal device). +
+For the last two cases, sizes +specifies the size of the buffer, in bytes. +The default is an appropriate size. + +


file:write (value1, ...)

+ +

Writes the value of each of its arguments to +the file. +The arguments must be strings or numbers. +To write other values, +use tostring or string.format before write. + +

5.8 - 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. + +


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 *t, +then date returns a table with the following fields: +year (four digits), month (1--12), day (1--31), +hour (0--23), min (0--59), sec (0--61), +wday (weekday, Sunday is 1), +yday (day of the year), +and isdst (daylight saving flag, a boolean). + +

If format is not *t, +then date returns the date as a string, +formatted according to the same rules as the C function strftime. + +

When called without arguments, +date returns a reasonable date and time representation that depends on +the host system and on the current locale +(that is, os.date() is equivalent to os.date("%c")). + +


os.difftime (t2, t1)

+ +

Returns the number of seconds from time t1 to time t2. +In POSIX, Windows, and some other systems, +this value is exactly t2-t1. + +


os.execute ([command])

+ +

This function is equivalent to the C function system. +It passes command to be executed by an operating system shell. +It returns a status code, which is system-dependent. +If command is absent, then it returns nonzero if a shell is available +and zero otherwise. + +


os.exit ([code])

+ +

Calls the C function exit, +with an optional code, +to terminate the host program. +The default value for code is the success code. + +


os.getenv (varname)

+ +

Returns the value of the process environment variable varname, +or nil if the variable is not defined. + +


os.remove (filename)

+ +

Deletes the file or directory with the given name. +Directories must be empty to be removed. +If this function fails, it returns nil, +plus a string describing the error. + +


os.rename (oldname, newname)

+ +

Renames file or directory named oldname to newname. +If this function fails, it returns nil, +plus a string describing the error. + +


os.setlocale (locale [, category])

+ +

Sets the current locale of the program. +locale is a 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 nil if the request cannot be honored. + +


os.time ([table])

+ +

Returns the current time when called without arguments, +or a time representing the date and time specified by the given table. +This table must have fields year, month, and day, +and may have fields hour, min, sec, and isdst +(for a description of these fields, see the os.date function). + +

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 +date and difftime. + +


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. + +

5.9 - The Debug Library

+ +

This library provides +the functionality of the debug interface to Lua programs. +You should exert care when using this library. +The functions provided here should be used exclusively for debugging +and similar tasks, such as profiling. +Please resist the temptation to use them as a +usual programming tool: +They can be very slow. +Moreover, several of its functions +violate some assumptions about Lua code +(e.g., that variables local to a function +cannot be accessed from outside or +that userdata metatables cannot be changed by Lua code) +and therefore can compromise otherwise secure code. + +

All functions in this library are provided +inside the debug table. + +


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.getfenv (o)

+Returns the environment of object o. + +


debug.gethook ()

+ +

Returns the current hook settings, as three values: +the current hook function, the current hook mask, +and the current hook count +(as set by the debug.sethook function). + +


debug.getinfo (function [, 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 function, +which means the function running at level function of the call stack: +Level 0 is the current function (getinfo itself); +level 1 is the function that called getinfo; +and so on. +If function is a number larger than the number of active functions, +then getinfo returns nil. + +

The returned table contains 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. +If present, +the option `f´ +adds a field named func with the function itself. + +

For instance, the expression debug.getinfo(1,"n").name returns +a name of the current function, if a reasonable name can be found, +and debug.getinfo(print) returns a table with all available information +about the print function. + +


debug.getlocal (level, local)

+ +

This function returns the name and the value of the local variable +with index local of the function at level level of the stack. +(The first parameter or local variable has index 1, and so on, +until the last active local variable.) +The function returns nil 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 debug.getinfo to check whether the level is valid.) + +

Variable names starting with `(´ (open parentheses) +represent internal variables +(loop control variables, temporaries, and C function locals). + +


debug.getmetatable (object)

+ +

Returns the metatable of the given object +or nil if it does not have a metatable. + +


debug.getregistry ()

+ +

Returns the registry table (see 3.5). + +


debug.getupvalue (func, up)

+ +

This function returns the name and the value of the upvalue +with index up of the function func. +The function returns nil if there is no upvalue with the given index. + +


debug.setfenv (object, table)

+ +

Sets the environment of the given object to the given table. + +


debug.sethook (hook, mask [, count])

+ +

Sets the given function as a hook. +The string mask and the number count describe +when the hook will be called. +The string mask may have 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. +
+With a count different from zero, +the hook is called 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", "return" (or "tail 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), +unless the event is "tail return". +In this case, Lua is only simulating the return, +and a call to getinfo will return invalid data. + +


debug.setlocal (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 nil 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. + +


debug.setmetatable (object, table)

+ +

Sets the metatable for the given object to the given table +(which can be nil). + +


debug.setupvalue (func, up, value)

+ +

This function assigns the value value to the upvalue +with index up of the function func. +The function returns nil if there is no upvalue +with the given index. +Otherwise, it returns the name of the upvalue. + +


debug.traceback ([message])

+ +

Returns a string with a traceback of the call stack. +An optional message string is appended +at the beginning of the traceback. +This function is typically used with xpcall to produce +better error messages. + +

+

6 - Lua Stand-alone

+ +

Although Lua has been designed as an extension language, +to be embedded in a host C program, +it is also frequently used as a stand-alone language. +An interpreter for Lua as a stand-alone language, +called simply lua, +is provided with the standard distribution. +The stand-alone interpreter includes +all standard libraries, including the debug library. +Its usage is: +

+      lua [options] [script [args]]
+
+The options are: +
    +
  • -e stat executes string stat; +
  • -l mod "requires" mod; +
  • -i enters interactive mode after running script; +
  • -v prints version information; +
  • -- stops handling options; +
  • - executes stdin as a file and stops handling options. +
+After handling its options, lua runs the given script, +passing to it the given args as string arguments. +When called without arguments, +lua behaves as lua -v -i +when the standard input (stdin) is a terminal, +and as lua - otherwise. + +

Before running any argument, +the interpreter checks for an environment variable LUA_INIT. +If its format is @filename, +then lua executes the file. +Otherwise, lua executes the string itself. + +

All options are handled in order, except -i. +For instance, an invocation like +

+       $ lua -e'a=1' -e 'print(a)' script.lua
+
+will first set a to 1, then print the value of a (which is `1´), +and finally run the file script.lua with no arguments. +(Here $ is the shell prompt. Your prompt may be different.) + +

Before starting to run the script, +lua collects all arguments in the command line +in a global table called arg. +The script name is stored at 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 the options) +go to negative indices. +For instance, in the call +

+       $ lua -la b.lua t1 t2
+
+the interpreter first runs the file a.lua, +then creates a table +
+       arg = { [-2] = "lua", [-1] = "-la",
+               [0] = "b.lua",
+               [1] = "t1", [2] = "t2" }
+
+and finally runs the file b.lua. +The script is called with arg[1], arg[2], ... +as arguments; +it can also access these arguments with the vararg expression `...´. + +

In interactive mode, +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). +Therefore, both prompts can be changed directly on the command line. +For instance, +

+       $ lua -e"_PROMPT='myprompt> '" -i
+
+(the outer pair of quotes is for the shell, +the inner pair is for Lua), +or in any Lua programs by assigning to _PROMPT. +Note the use of -i to enter interactive mode; otherwise, +the program would just end silently right after the assignment to _PROMPT. + +

To allow the use of Lua as a +script interpreter in Unix systems, +the stand-alone interpreter skips +the first line of a 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.) + +


+ +

Incompatibilities with the Previous Version

+ + +

Here we list the incompatibilities that may be found when moving a program +from Lua 5.0 to Lua 5.1. +You can avoid most of the incompatibilities compiling Lua with +appropriate options (see file luaconf.h). +However, +all these compatibility options will be removed in the next version of Lua. + +

Incompatibilities with version 5.0

+ +

Changes in the Language

+
    +
  • +The vararg system changed from the pseudo-argument arg with a +table with the extra arguments to the vararg expression. +(Option LUA_COMPAT_VARARG in luaconf.h.) + +

  • +There was a subtle change in the scope of the implicit +variables of the for statement and for the repeat statement. + +

  • +The long string/long comment syntax ([[...]]) does not allow nesting. +You can use the new syntax ([=[...]=]) in these cases. +(Option LUA_COMPAT_LSTR in luaconf.h.) + +

+ +

Changes in the Libraries

+
    + +

  • +Function string.gfind was renamed string.gmatch. +(Option LUA_COMPAT_GFIND) + +

  • +When string.gsub is called with a function as its +third argument, +whenever this function returns nil or false the +replacement string is the whole match, +instead of the empty string. + +

  • +Function table.setn was deprecated. +Function table.getn corresponds +to the new length operator (#); +use the operator instead of the function. +(Option LUA_COMPAT_GETN) + +

  • +Function loadlib was renamed package.loadlib. +(Option LUA_COMPAT_LOADLIB) + +

  • +Function math.mod was renamed math.fmod. +(Option LUA_COMPAT_MOD) + +

  • +Functions table.foreach and table.foreachi are deprecated. +You can use a for loop with pairs or ipairs instead. + +

  • +There were substantial changes in function require due to +the new module system. +However, the new behavior is mostly compatible with the old, +but require gets the path from package.path instead +of from LUA_PATH. + +

  • +Function collectgarbage has different arguments. +Function gcinfo is deprecated; +use collectgarbage("count") instead. + +

+ +

Changes in the API

+
    + +

  • +The luaopen_* functions (to open libraries) +cannot be called directly, +like a regular C function. +They must be called through Lua, +like a Lua function. + +

  • +Function lua_open was replaced by lua_newstate to +allow the user to set a memory allocation function. +You can use luaL_newstate from the standard library to +create a state with a standard allocation function +(based on realloc). + +

  • +Functions luaL_getn and luaL_setn +(from the auxiliary library) are deprecated. +Use lua_objlen instead of luaL_getn +and nothing instead of luaL_setn. + +

  • +Function luaL_openlib was replaced by luaL_register. + +

+ +

+ +

The Complete Syntax of Lua

+ + +

Here is the complete syntax of Lua in extended BNF. +It does not describe operator priorities or some syntactical restrictions, +such as return and break statements +can only appear as the last statement of a block. + +

+ +

+
+	chunk ::= {stat [`;´]} [laststat[`;´]]
+
+	block ::= chunk
+
+	stat ::=  varlist1 `=´ explist1  | 
+		 functioncall  | 
+		 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 explist1 do block end  | 
+		 function funcname funcbody  | 
+		 local function Name funcbody  | 
+		 local namelist [`=´ explist1] 
+
+	laststat ::= return [explist1]  |  break
+
+	funcname ::= Name {`.´ Name} [`:´ Name]
+
+	varlist1 ::= var {`,´ var}
+
+	var ::=  Name  |  prefixexp `[´ exp `]´  |  prefixexp `.´ Name 
+
+	namelist ::= Name {`,´ Name}
+
+	explist1 ::= {exp `,´} exp
+
+	exp ::=  nil  |  false  |  true  |  Number  |  String  |  `...´  | 
+		 function  |  prefixexp  |  tableconstructor  |  exp binop exp  |  unop exp 
+
+	prefixexp ::= var  |  functioncall  |  `(´ exp `)´
+
+	functioncall ::=  prefixexp args  |  prefixexp `:´ Name args 
+
+	args ::=  `(´ [explist1] `)´  |  tableconstructor  |  String 
+
+	function ::= function funcbody
+
+	funcbody ::= `(´ [parlist1] `)´ block end
+
+	parlist1 ::= namelist [`,´ `...´]  |  `...´
+
+	tableconstructor ::= `{´ [fieldlist] `}´
+
+	fieldlist ::= field {fieldsep field} [fieldsep]
+
+	field ::= `[´ exp `]´ `=´ exp  |  Name `=´ exp  |  exp
+
+	fieldsep ::= `,´  |  `;´
+
+	binop ::= `+´  |  `-´  |  `*´  |  `/´  |  `^´  |  `%´  |  `..´  | 
+		 `<´  |  `<=´  |  `>´  |  `>=´  |  `==´  |  `~=´  | 
+		 and  |  or
+
+	unop ::= `-´  |  not  |  `#´
+
+
+ +

+ +

+ + + diff --git a/doc/lua/readme.html b/doc/lua/readme.html new file mode 100644 index 0000000..db20a69 --- /dev/null +++ b/doc/lua/readme.html @@ -0,0 +1,32 @@ + + +Lua documentation + + + + + +


+

+Lua +Documentation +

+ + + +
+ +Last update: +Wed Sep 7 12:57:50 BRST 2005 + + + + diff --git a/doc/luairc/LICENSE b/doc/luairc/LICENSE new file mode 100644 index 0000000..fe30b8a --- /dev/null +++ b/doc/luairc/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2007 Jesse Luehrs + +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/doc/luairc/README b/doc/luairc/README new file mode 100644 index 0000000..50112b9 --- /dev/null +++ b/doc/luairc/README @@ -0,0 +1,31 @@ +LuaIRC v0.3 +Jesse Luehrs (jluehrs2@uiuc.edu) + +OVERVIEW +======== +LuaIRC is a fully featured IRC framework written entirely in Lua. It provides an event driven system for connecting to IRC servers and responding to actions such as messages, joins/parts, and channel mode changes, among other things. DCC SEND is also fully implemented, both for sending and receiving files. + +INSTALL +======= +This module requires LuaSocket (http://www.cs.princeton.edu/~diego/professional/luasocket/) and Lua 5.1. To install, modify the Make.config file with paths appropriate to your system and run 'make install'. + +DOCUMENTATION +============= +Documentation of the API can be found in the doc/ directory. It was autogenerated from the source files by LuaDoc (http://luadoc.luaforge.net/). + +LuaIRC has only been tested on Freenode so far, but I plan to expand this to other servers in the future. It's quite possible that it works on other servers anyway, however, so feel free to try it out, and send in bug reports for things that break. + +CHANGES +======= +0.3 +- Major cleanup and restructuring again, documentation added, first public release +0.2 +- Major cleanup and restructuring +0.1 +- Initial implementation, enough to get it talking to the IRC server + +COPYRIGHT AND LICENSE +===================== +Copyright (C) 2007 Jesse Luehrs + +This code is distributed under the MIT license; a copy is in the LICENSE file distributed with the source. diff --git a/doc/luairc/TODO b/doc/luairc/TODO new file mode 100644 index 0000000..7fafb6e --- /dev/null +++ b/doc/luairc/TODO @@ -0,0 +1,20 @@ +- Reorganize the modules a bit more... we should have a src/irc/dcc/send.lua, src/irc/ctcp/base.lua, src/irc/ctcp/dcc.lua, etc. also, most (all?) of the handlers should be moved out of irc.lua into, say, src/irc/base.lua +- Separate out the DCC module some more so that the callbacks aren't registered unless the module is loaded +- Also separate out all of the CTCP commands/callbacks into the CTCP module +- Rework the way irc.lua uses things from modules - the whole underscore but public thing... do i want to keep that? i suppose it's not horrible... look into this more +- Implement callbacks for user mode changes (need to figure out how to represent users in the callback info) +- Allow a server parameter in whois() so that the returned data can include the user's idle time +- chan:ban()/chan:unban() should take a usermask, not a nick, or be able to generate a usermask from a nick, or something like that +- Clean up misc.split +- Implement DCC CHAT +- Implement DCC XMIT/OFFER +- Implement some more of the newer CTCP commands +- Implement more information requests + - who + - whowas + - info + - stats + - links + - trace (not freenode supported) +- Implement XDCC (?) +- Handle endianness in the IP address conversion functions diff --git a/doc/luairc/index.html b/doc/luairc/index.html new file mode 100644 index 0000000..7636da2 --- /dev/null +++ b/doc/luairc/index.html @@ -0,0 +1,156 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ + + +

Modules

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbacksThese are the callbacks that are available to register.
ircLuaIRC - IRC framework written in Lua
irc.channelThis module implements a channel object representing a single channel we have joined.
irc.constantsThis module holds various constants used by the IRC protocol.
irc.ctcpThis module implements the various quoting and escaping requirements of the CTCP protocol.
irc.dccThis module implements the DCC protocol.
irc.debugThis module implements a few useful debug functions for use throughout the rest of the code.
irc.messageThis module contains parsing functions for IRC server messages.
irc.miscThis module contains various useful functions which didn't fit in any of the other modules.
+ + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/luadoc.css b/doc/luairc/luadoc.css new file mode 100644 index 0000000..bc0f98a --- /dev/null +++ b/doc/luairc/luadoc.css @@ -0,0 +1,286 @@ +body { + margin-left: 1em; + margin-right: 1em; + font-family: arial, helvetica, geneva, sans-serif; + background-color:#ffffff; margin:0px; +} + +code { + font-family: "Andale Mono", monospace; +} + +tt { + font-family: "Andale Mono", monospace; +} + +body, td, th { font-size: 11pt; } + +h1, h2, h3, h4 { margin-left: 0em; } + +textarea, pre, tt { font-size:10pt; } +body, td, th { color:#000000; } +small { font-size:0.85em; } +h1 { font-size:1.5em; } +h2 { font-size:1.25em; } +h3 { font-size:1.15em; } +h4 { font-size:1.06em; } + +a:link { font-weight:bold; color: #004080; text-decoration: none; } +a:visited { font-weight:bold; color: #006699; text-decoration: none; } +a:link:hover { text-decoration:underline; } +hr { color:#cccccc } +img { border-width: 0px; } + + +h3 { padding-top: 1em; } + +p { margin-left: 1em; } + +p.name { + font-family: "Andale Mono", monospace; + padding-top: 1em; + margin-left: 0em; +} + +blockquote { margin-left: 3em; } + +pre.example { + background-color: rgb(245, 245, 245); + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-style: solid; + border-right-style: solid; + border-bottom-style: solid; + border-left-style: solid; + border-top-color: silver; + border-right-color: silver; + border-bottom-color: silver; + border-left-color: silver; + padding: 1em; + margin-left: 1em; + margin-right: 1em; + font-family: "Andale Mono", monospace; + font-size: smaller; +} + + +hr { + margin-left: 0em; + background: #00007f; + border: 0px; + height: 1px; +} + +ul { list-style-type: disc; } + +table.index { border: 1px #00007f; } +table.index td { text-align: left; vertical-align: top; } +table.index ul { padding-top: 0em; margin-top: 0em; } + +table { + border: 1px solid black; + border-collapse: collapse; + margin-left: auto; + margin-right: auto; +} +th { + border: 1px solid black; + padding: 0.5em; +} +td { + border: 1px solid black; + padding: 0.5em; +} +div.header, div.footer { margin-left: 0em; } + +#container +{ + margin-left: 1em; + margin-right: 1em; + background-color: #f0f0f0; +} + +#product +{ + text-align: center; + border-bottom: 1px solid #cccccc; + background-color: #ffffff; +} + +#product big { + font-size: 2em; +} + +#product_logo +{ +} + +#product_name +{ +} + +#product_description +{ +} + +#main +{ + background-color: #f0f0f0; + border-left: 2px solid #cccccc; +} + +#navigation +{ + float: left; + width: 18em; + margin: 0; + vertical-align: top; + background-color: #f0f0f0; + overflow:visible; +} + +#navigation h1 { + background-color:#e7e7e7; + font-size:1.1em; + color:#000000; + text-align:left; + margin:0px; + padding:0.2em; + border-top:1px solid #dddddd; + border-bottom:1px solid #dddddd; +} + +#navigation ul +{ + font-size:1em; + list-style-type: none; + padding: 0; + margin: 1px; +} + +#navigation li +{ + text-indent: -1em; + margin: 0em 0em 0em 0.5em; + display: block; + padding: 3px 0px 0px 12px; +} + +#navigation li li a +{ + padding: 0px 3px 0px -1em; +} + +#content +{ + margin-left: 18em; + padding: 1em; + border-left: 2px solid #cccccc; + border-right: 2px solid #cccccc; + background-color: #ffffff; +} + +#about +{ + clear: both; + margin: 0; + padding: 5px; + border-top: 2px solid #cccccc; + background-color: #ffffff; +} + +@media print { + body { + font: 12pt "Times New Roman", "TimeNR", Times, serif; + } + a { font-weight:bold; color: #004080; text-decoration: underline; } + + #main { background-color: #ffffff; border-left: 0px; } + #container { margin-left: 2%; margin-right: 2%; background-color: #ffffff; } + + #content { margin-left: 0px; padding: 1em; border-left: 0px; border-right: 0px; background-color: #ffffff; } + + #navigation { display: none; + } + pre.example { + font-family: "Andale Mono", monospace; + font-size: 10pt; + page-break-inside: avoid; + } +} + +table.module_list td +{ + border-width: 1px; + padding: 3px; + border-style: solid; + border-color: #cccccc; +} +table.module_list td.name { background-color: #f0f0f0; } +table.module_list td.summary { width: 100%; } + +table.file_list +{ + border-width: 1px; + border-style: solid; + border-color: #cccccc; + border-collapse: collapse; +} +table.file_list td +{ + border-width: 1px; + padding: 3px; + border-style: solid; + border-color: #cccccc; +} +table.file_list td.name { background-color: #f0f0f0; } +table.file_list td.summary { width: 100%; } + + +table.function_list +{ + border-width: 1px; + border-style: solid; + border-color: #cccccc; + border-collapse: collapse; +} +table.function_list td +{ + border-width: 1px; + padding: 3px; + border-style: solid; + border-color: #cccccc; +} +table.function_list td.name { background-color: #f0f0f0; } +table.function_list td.summary { width: 100%; } + + +table.table_list +{ + border-width: 1px; + border-style: solid; + border-color: #cccccc; + border-collapse: collapse; +} +table.table_list td +{ + border-width: 1px; + padding: 3px; + border-style: solid; + border-color: #cccccc; +} +table.table_list td.name { background-color: #f0f0f0; } +table.table_list td.summary { width: 100%; } + +dl.function dt {border-top: 1px solid #ccc; padding-top: 1em;} +dl.function dd {padding-bottom: 1em;} +dl.function h3 {padding: 0; margin: 0; font-size: medium;} + +dl.table dt {border-top: 1px solid #ccc; padding-top: 1em;} +dl.table dd {padding-bottom: 1em;} +dl.table h3 {padding: 0; margin: 0; font-size: medium;} + +#TODO: make module_list, file_list, function_list, table_list inherit from a list + diff --git a/doc/luairc/modules/callbacks.html b/doc/luairc/modules/callbacks.html new file mode 100644 index 0000000..f633e1d --- /dev/null +++ b/doc/luairc/modules/callbacks.html @@ -0,0 +1,858 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module callbacks

+ +

These are the callbacks that are available to register.

+ + + +

Functions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
channel_act (channel, from, message)This callback is triggered whenever a user performs a CTCP ACTION in a channel.
channel_msg (channel, from, message)This callback is triggered whenever a user sends a message to a channel.
channel_notice (channel, from, message)This callback is triggered whenever a user sends a notice to a channel.
connect ()This callback is triggered when the connection has completed.
ctcp_error (from, to, message)This callback is triggered when a CTCP command resulted in an error (for example, if the remote client doesn't implement that CTCP command).
dcc_send (from, to, filename, address, port, filesize)This callback is triggered when a user offers to send you a file using DCC SEND.
deop (channel, from, to)This callback is triggered whenever somebody loses ops.
devoice (channel, from, to)This callback is triggered whenever somebody loses voice.
invite (from, channel)This callback is triggered whenever an invite to a channel is received.
join (channel, from)This callback is triggered when a user joins a channel.
kick (channel, to, from)This callback is triggered when a user is kicked from a channel.
me_join (channel)This callback is triggered after a join() command completes.
nick_change (from, old_nick)This callback is triggered when a user changes their nick.
op (channel, from, to)This callback is triggered when a user is opped.
part (channel, from, message)This callback is triggered when a user leaves a channel.
private_act (from, message)This callback is triggered when a user sends a CTCP ACTION in a private message.
private_msg (from, message)This callback is triggered when a user sends a private message.
private_notice (from, message)This callback is triggered when a user sends a private notice.
quit (from, message)This callback is triggered when a user quits.
topic_change (channel)This callback is triggered when a user changes the topic in a channel.
voice (channel, from, to)This callback is triggered when a user is voiced.
+ + + + + + +
+
+ + + +

Functions

+
+ + + +
channel_act (channel, from, message)
+
+This callback is triggered whenever a user performs a CTCP ACTION in a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where the action was performed +
  • + +
  • + from: User who performed the action +
  • + +
  • + message: The action which was performed +
  • + +
+ + + + + + +
+ + + + +
channel_msg (channel, from, message)
+
+This callback is triggered whenever a user sends a message to a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where the message was sent +
  • + +
  • + from: User who sent the message +
  • + +
  • + message: The message which was sent +
  • + +
+ + + + + + +
+ + + + +
channel_notice (channel, from, message)
+
+This callback is triggered whenever a user sends a notice to a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where the notice was sent +
  • + +
  • + from: User who sent the message +
  • + +
  • + message: The notice which was sent +
  • + +
+ + + + + + +
+ + + + +
connect ()
+
+This callback is triggered when the connection has completed. + + + + + + + +
+ + + + +
ctcp_error (from, to, message)
+
+This callback is triggered when a CTCP command resulted in an error (for example, if the remote client doesn't implement that CTCP command). + + +

Parameters

+
    + +
  • + from: User who sent the error response +
  • + +
  • + to: Who the response was sent to (either you or a channel you are in) +
  • + +
  • + message: A description of the error +
  • + +
+ + + + + + +
+ + + + +
dcc_send (from, to, filename, address, port, filesize)
+
+This callback is triggered when a user offers to send you a file using DCC SEND. It allows you to determine whether or not you want to accept the file. + + +

Parameters

+
    + +
  • + from: User offering the file +
  • + +
  • + to: User who is being offered the file (likely yourself) +
  • + +
  • + filename: Name of the file being offered +
  • + +
  • + address: IP address of the user offering the file +
  • + +
  • + port: Port to connect to at that address +
  • + +
  • + filesize: Size of the file being offered +
  • + +
+ + + + +

Return value:

+True to accept the file, false to reject it + + + +
+ + + + +
deop (channel, from, to)
+
+This callback is triggered whenever somebody loses ops. + + +

Parameters

+
    + +
  • + channel: Channel object for where the user lost ops +
  • + +
  • + from: User who removed the ops +
  • + +
  • + to: User who lost ops +
  • + +
+ + + + + + +
+ + + + +
devoice (channel, from, to)
+
+This callback is triggered whenever somebody loses voice. + + +

Parameters

+
    + +
  • + channel: Channel object for where the user lost voice +
  • + +
  • + from: User who removed the voice +
  • + +
  • + to: User who lost voice +
  • + +
+ + + + + + +
+ + + + +
invite (from, channel)
+
+This callback is triggered whenever an invite to a channel is received. + + +

Parameters

+
    + +
  • + from: User who sent the invite +
  • + +
  • + channel: Channel name that the invite was to +
  • + +
+ + + + + + +
+ + + + +
join (channel, from)
+
+This callback is triggered when a user joins a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where there was a join +
  • + +
  • + from: User who joined +
  • + +
+ + + + + + +
+ + + + +
kick (channel, to, from)
+
+This callback is triggered when a user is kicked from a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where there was a kick +
  • + +
  • + to: User who was kicked +
  • + +
  • + from: User who did the kicking +
  • + +
+ + + + + + +
+ + + + +
me_join (channel)
+
+This callback is triggered after a join() command completes. + + +

Parameters

+
    + +
  • + channel: Channel object for the joined channel +
  • + +
+ + + + + + +
+ + + + +
nick_change (from, old_nick)
+
+This callback is triggered when a user changes their nick. + + +

Parameters

+
    + +
  • + from: User who changed their nick +
  • + +
  • + old_nick: The previous nick of that user +
  • + +
+ + + + + + +
+ + + + +
op (channel, from, to)
+
+This callback is triggered when a user is opped. + + +

Parameters

+
    + +
  • + channel: Channel object for where the user was opped +
  • + +
  • + from: User who gave the ops +
  • + +
  • + to: User who was opped +
  • + +
+ + + + + + +
+ + + + +
part (channel, from, message)
+
+This callback is triggered when a user leaves a channel. + + +

Parameters

+
    + +
  • + channel: Channel object for where the part occurred +
  • + +
  • + from: User who left +
  • + +
  • + message: Part message from the user +
  • + +
+ + + + + + +
+ + + + +
private_act (from, message)
+
+This callback is triggered when a user sends a CTCP ACTION in a private message. + + +

Parameters

+
    + +
  • + from: User who sent the action +
  • + +
  • + message: The action that was sent +
  • + +
+ + + + + + +
+ + + + +
private_msg (from, message)
+
+This callback is triggered when a user sends a private message. + + +

Parameters

+
    + +
  • + from: User who sent the message +
  • + +
  • + message: The message that was sent +
  • + +
+ + + + + + +
+ + + + +
private_notice (from, message)
+
+This callback is triggered when a user sends a private notice. + + +

Parameters

+
    + +
  • + from: User who sent the notice +
  • + +
  • + message: The notice that was sent +
  • + +
+ + + + + + +
+ + + + +
quit (from, message)
+
+This callback is triggered when a user quits. + + +

Parameters

+
    + +
  • + from: User who quit +
  • + +
  • + message: The user's quit message +
  • + +
+ + + + + + +
+ + + + +
topic_change (channel)
+
+This callback is triggered when a user changes the topic in a channel. The contents of the topic can be seen in the topic field of the channel object. + + +

Parameters

+
    + +
  • + channel: Channel object for where the topic was changed. +
  • + +
+ + + + + + +
+ + + + +
voice (channel, from, to)
+
+This callback is triggered when a user is voiced. + + +

Parameters

+
    + +
  • + channel: Channel object for where the user was voiced +
  • + +
  • + from: User who gave the voice +
  • + +
  • + to: User who was voiced +
  • + +
+ + + + + + +
+ + +
+ + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.channel.html b/doc/luairc/modules/irc.channel.html new file mode 100644 index 0000000..f061a3c --- /dev/null +++ b/doc/luairc/modules/irc.channel.html @@ -0,0 +1,945 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.channel

+ +

This module implements a channel object representing a single channel we have joined.

+ + + +

Functions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ban (self, name)Ban a user from a channel.
contains (self, nick)Test if a user is in the channel.
deop (self, name)Remove ops from a user.
devoice (self, name)Remove voice from a user.
each_member (self)Iterator over all users in the channel
each_op (self)Iterator over the ops in the channel
each_user (self)Iterator over the normal users in the channel
each_voice (self)Iterator over the voiced users in the channel
members (self)Gets an array of all the users in the channel.
new (chan)Creates a new Channel object.
op (self, name)Give a user ops on a channel.
ops (self)Gets an array of all the ops in the channel.
set_invite_only (self, set)Set whether joining the channel requires an invite.
set_key (self, key)Set a channel password.
set_limit (self, new_limit)Set a channel limit.
set_moderated (self, set)Set whether voice is required to speak.
set_no_outside_messages (self, set)If true, users must be in the channel to send messages to it.
set_private (self, set)Set the private state of a channel.
set_secret (self, set)Set the secret state of a channel.
set_topic_lock (self, set)If true, the topic can only be changed by an op.
unban (self, name)Remove a ban on a user.
users (self)Gets an array of all the normal users in the channel.
voice (self, name)Give a user voice on a channel.
voices (self)Gets an array of all the voiced users in the channel.
+ + + + +

Tables

+ + + + + + + +
ChannelAn object of the Channel class represents a single joined channel.
+ + + +
+
+ + + +

Functions

+
+ + + +
ban (self, name)
+
+Ban a user from a channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to ban +
  • + +
+ + + + + + +
+ + + + +
contains (self, nick)
+
+Test if a user is in the channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + nick: Nick to search for +
  • + +
+ + + + +

Return value:

+True if the nick is in the channel, false otherwise + + + +
+ + + + +
deop (self, name)
+
+Remove ops from a user. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to remove ops from +
  • + +
+ + + + + + +
+ + + + +
devoice (self, name)
+
+Remove voice from a user. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to remove voice from +
  • + +
+ + + + + + +
+ + + + +
each_member (self)
+
+Iterator over all users in the channel + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + + + +
+ + + + +
each_op (self)
+
+Iterator over the ops in the channel + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + + + +
+ + + + +
each_user (self)
+
+Iterator over the normal users in the channel + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + + + +
+ + + + +
each_voice (self)
+
+Iterator over the voiced users in the channel + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + + + +
+ + + + +
members (self)
+
+Gets an array of all the users in the channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + +

Return value:

+Array of channel users + + + +
+ + + + +
new (chan)
+
+Creates a new Channel object. + + +

Parameters

+
    + +
  • + chan: Name of the new channel +
  • + +
+ + + + +

Return value:

+The new channel instance + + + +
+ + + + +
op (self, name)
+
+Give a user ops on a channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to op +
  • + +
+ + + + + + +
+ + + + +
ops (self)
+
+Gets an array of all the ops in the channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + +

Return value:

+Array of channel ops + + + +
+ + + + +
set_invite_only (self, set)
+
+Set whether joining the channel requires an invite. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to set the channel invite only, false to unset it +
  • + +
+ + + + + + +
+ + + + +
set_key (self, key)
+
+Set a channel password. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + key: New channel password (optional; password is unset if this argument isn't passed) +
  • + +
+ + + + + + +
+ + + + +
set_limit (self, new_limit)
+
+Set a channel limit. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + new_limit: New value for the channel limit (optional; limit is unset if this argument isn't passed) +
  • + +
+ + + + + + +
+ + + + +
set_moderated (self, set)
+
+Set whether voice is required to speak. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to set the channel as moderated, false to unset it +
  • + +
+ + + + + + +
+ + + + +
set_no_outside_messages (self, set)
+
+If true, users must be in the channel to send messages to it. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to require users to be in the channel to send messages to it, false to remove this restriction +
  • + +
+ + + + + + +
+ + + + +
set_private (self, set)
+
+Set the private state of a channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to set the channel as private, false to unset it +
  • + +
+ + + + + + +
+ + + + +
set_secret (self, set)
+
+Set the secret state of a channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to set the channel as secret, false to unset it +
  • + +
+ + + + + + +
+ + + + +
set_topic_lock (self, set)
+
+If true, the topic can only be changed by an op. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + set: True to lock the topic, false to unlock it +
  • + +
+ + + + + + +
+ + + + +
unban (self, name)
+
+Remove a ban on a user. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to unban +
  • + +
+ + + + + + +
+ + + + +
users (self)
+
+Gets an array of all the normal users in the channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + +

Return value:

+Array of channel normal users + + + +
+ + + + +
voice (self, name)
+
+Give a user voice on a channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
  • + name: User to give voice to +
  • + +
+ + + + + + +
+ + + + +
voices (self)
+
+Gets an array of all the voiced users in the channel. + + +

Parameters

+
    + +
  • + self: Channel object +
  • + +
+ + + + +

Return value:

+Array of channel voiced users + + + +
+ + +
+ + + + +

Tables

+
+ +
Channel
+
An object of the Channel class represents a single joined channel. It has several table fields, and can be used in string contexts (returning the channel name).
+ + +Fields +
    + +
  • + name: Name of the channel (read only) +
  • + +
  • + topic: Channel topic, if set (read/write, writing to this sends a topic change request to the server for this channel) +
  • + +
  • + chanmode: Channel mode (public/private/secret) (read only) +
  • + +
  • + members: Array of all members of this channel +
  • + +
+ + +
+ + +
+ + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.constants.html b/doc/luairc/modules/irc.constants.html new file mode 100644 index 0000000..8a7aa74 --- /dev/null +++ b/doc/luairc/modules/irc.constants.html @@ -0,0 +1,117 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.constants

+ +

This module holds various constants used by the IRC protocol.

+ + + + + + + + +
+
+ + + + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.ctcp.html b/doc/luairc/modules/irc.ctcp.html new file mode 100644 index 0000000..02e6aae --- /dev/null +++ b/doc/luairc/modules/irc.ctcp.html @@ -0,0 +1,117 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.ctcp

+ +

This module implements the various quoting and escaping requirements of the CTCP protocol.

+ + + + + + + + +
+
+ + + + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.dcc.html b/doc/luairc/modules/irc.dcc.html new file mode 100644 index 0000000..0dc0a6d --- /dev/null +++ b/doc/luairc/modules/irc.dcc.html @@ -0,0 +1,164 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.dcc

+ +

This module implements the DCC protocol. File transfers (DCC SEND) are handled, but DCC CHAT is not, as of yet.

+ + + +

Functions

+ + + + + + + +
send (nick, filename, port)Offers a file to a remote user.
+ + + + + + +
+
+ + + +

Functions

+
+ + + +
send (nick, filename, port)
+
+Offers a file to a remote user. + + +

Parameters

+
    + +
  • + nick: User to offer the file to +
  • + +
  • + filename: Filename to offer +
  • + +
  • + port: Port to accept connections on (optional, defaults to choosing an available port between FIRST_PORT and LAST_PORT above) +
  • + +
+ + + + + + +
+ + +
+ + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.debug.html b/doc/luairc/modules/irc.debug.html new file mode 100644 index 0000000..b6377e0 --- /dev/null +++ b/doc/luairc/modules/irc.debug.html @@ -0,0 +1,196 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.debug

+ +

This module implements a few useful debug functions for use throughout the rest of the code.

+ + + +

Functions

+ + + + + + + + + + + + + + + + + +
disable ()Turns off debug output.
enable ()Turns on debug output.
set_output (file)Redirects output to a file rather than stdout.
+ + + + + + +
+
+ + + +

Functions

+
+ + + +
disable ()
+
+Turns off debug output. + + + + + + + +
+ + + + +
enable ()
+
+Turns on debug output. + + + + + + + +
+ + + + +
set_output (file)
+
+Redirects output to a file rather than stdout. + + +

Parameters

+
    + +
  • + file: File to write debug output to +
  • + +
+ + + + + + +
+ + +
+ + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.html b/doc/luairc/modules/irc.html new file mode 100644 index 0000000..0556fef --- /dev/null +++ b/doc/luairc/modules/irc.html @@ -0,0 +1,683 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc

+ +

LuaIRC - IRC framework written in Lua

+ +

Release: 0.3

+ + + +

Functions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
act (name, action)Perform a /me action.
channels ()Iterate over currently joined channels.
connect (args)Start a connection to the irc server.
ctcp_ping (cb, nick)Send a CTCP ping request.
ctcp_time (cb, nick)Send a localtime request.
ctcp_version (cb, nick)Send a client version request.
get_ip ()Get the local IP address for the server connection.
join (channel)Join a channel.
notice (name, message)Send a notice to a user or channel.
part (channel)Leave a channel.
quit (message)Close the connection to the irc server.
register_callback (name, fn)Register a user function to be called when a specific event occurs.
say (name, message)Send a message to a user or channel.
send (command, ...)Send a raw IRC command.
server_time (cb)Request the current time of the server you are connected to.
server_version (cb)Request the version of the IRC server you are currently connected to.
set_ip (new_ip)Set the local IP manually (to allow for NAT workarounds)
whois (cb, nick)Request WHOIS information about a given user.
+ + + + + + +
+
+ + + +

Functions

+
+ + + +
act (name, action)
+
+Perform a /me action. + + +

Parameters

+
    + +
  • + name: User or channel to send the action to +
  • + +
  • + action: Action to send +
  • + +
+ + + + + + +
+ + + + +
channels ()
+
+Iterate over currently joined channels. channels() is an iterator function for use in for loops. For example,
for chan in irc.channels() do print(chan:name) end
+ + + + + + + +See also: + + + irc.channel + + + + +
+ + + + +
connect (args)
+
+Start a connection to the irc server. + + +

Parameters

+
    + +
  • + args: Table of named arguments containing connection parameters. Defaults are the all-caps versions of these parameters given at the top of the file, and are overridable by setting them as well, i.e.
    irc.NETWORK = irc.freenode.net
    Possible options are:
    • network: address of the irc network to connect to (default: 'localhost')
    • port: port to connect to (default: '6667')
    • pass: irc server password (default: don't send)
    • nick: nickname to connect as (default: 'luabot')
    • username: username to connect with (default: 'LuaIRC')
    • realname: realname to connect with (default: 'LuaIRC')
    • timeout: amount of time in seconds to wait before dropping an idle connection (default: '60')
    +
  • + +
+ + + + + + +
+ + + + +
ctcp_ping (cb, nick)
+
+Send a CTCP ping request. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • time: the roundtrip ping time, in seconds
    +
  • + +
  • + nick: User to ping +
  • + +
+ + + + + + +
+ + + + +
ctcp_time (cb, nick)
+
+Send a localtime request. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • time: the localtime reported by the remote client
    +
  • + +
  • + nick: User to request the localtime from +
  • + +
+ + + + + + +
+ + + + +
ctcp_version (cb, nick)
+
+Send a client version request. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • nick: the nick which responded to the request
    • version: the version reported by the remote client
    +
  • + +
  • + nick: User to request the client version from +
  • + +
+ + + + + + +
+ + + + +
get_ip ()
+
+Get the local IP address for the server connection. + + + + + +

Return value:

+A string representation of the local IP address that the IRC server connection is communicating on + + + +
+ + + + +
join (channel)
+
+Join a channel. + + +

Parameters

+
    + +
  • + channel: Channel to join +
  • + +
+ + + + + + +
+ + + + +
notice (name, message)
+
+Send a notice to a user or channel. + + +

Parameters

+
    + +
  • + name: User or channel to send the notice to +
  • + +
  • + message: Message to send +
  • + +
+ + + + + + +
+ + + + +
part (channel)
+
+Leave a channel. + + +

Parameters

+
    + +
  • + channel: Channel to leave +
  • + +
+ + + + + + +
+ + + + +
quit (message)
+
+Close the connection to the irc server. + + +

Parameters

+
    + +
  • + message: Quit message (optional, defaults to 'Leaving') +
  • + +
+ + + + + + +
+ + + + +
register_callback (name, fn)
+
+Register a user function to be called when a specific event occurs. + + +

Parameters

+
    + +
  • + name: Name of the event +
  • + +
  • + fn: Function to call when the event occurs, or nil to clear the callback for this event +
  • + +
+ + + + +

Return value:

+Value of the original callback for this event (or nil if no previous callback had been set) + + + +
+ + + + +
say (name, message)
+
+Send a message to a user or channel. + + +

Parameters

+
    + +
  • + name: User or channel to send the message to +
  • + +
  • + message: Message to send +
  • + +
+ + + + + + +
+ + + + +
send (command, ...)
+
+Send a raw IRC command. + + +

Parameters

+
    + +
  • + command: String containing the raw IRC command +
  • + +
  • + ...: Arguments to the command. Each argument is either a string or an array. Strings are sent literally, arrays are CTCP quoted as a group. The last argument (if it exists) is preceded by a : (so it may contain spaces). +
  • + +
+ + + + + + +
+ + + + +
server_time (cb)
+
+Request the current time of the server you are connected to. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • server: the server which responded to the request
    • time: the time reported by the server
    +
  • + +
+ + + + + + +
+ + + + +
server_version (cb)
+
+Request the version of the IRC server you are currently connected to. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback will contain the fields:
    • server: the server which responded to the request
    • version: the server version
    • comments: other data provided by the server
    +
  • + +
+ + + + + + +
+ + + + +
set_ip (new_ip)
+
+Set the local IP manually (to allow for NAT workarounds) + + +

Parameters

+
    + +
  • + new_ip: IP address to set +
  • + +
+ + + + + + +
+ + + + +
whois (cb, nick)
+
+Request WHOIS information about a given user. + + +

Parameters

+
    + +
  • + cb: Callback to call when the information is available. The single table parameter to this callback may contain any or all of the fields:
    • nick: the nick that was passed to this function (this field will always be here)
    • user: the IRC username of the user
    • host: the user's hostname
    • realname: the IRC realname of the user
    • server: the IRC server the user is connected to
    • serverinfo: arbitrary information about the above server
    • awaymsg: set to the user's away message if they are away
    • is_oper: true if the user is an IRCop
    • idle_time: amount of time the user has been idle
    • channels: array containing the channels the user has joined
    +
  • + +
  • + nick: User to request WHOIS information about +
  • + +
+ + + + + + +
+ + +
+ + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.message.html b/doc/luairc/modules/irc.message.html new file mode 100644 index 0000000..a4ed396 --- /dev/null +++ b/doc/luairc/modules/irc.message.html @@ -0,0 +1,117 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.message

+ +

This module contains parsing functions for IRC server messages.

+ + + + + + + + +
+
+ + + + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luairc/modules/irc.misc.html b/doc/luairc/modules/irc.misc.html new file mode 100644 index 0000000..df87d89 --- /dev/null +++ b/doc/luairc/modules/irc.misc.html @@ -0,0 +1,117 @@ + + + + Reference + + + + + +
+ +
+ +
+
+
+ +
+ + + +
+ +

Module irc.misc

+ +

This module contains various useful functions which didn't fit in any of the other modules.

+ + + + + + + + +
+
+ + + + + + + + +
+ +
+ +
+

Valid XHTML 1.0!

+
+ +
+ + diff --git a/doc/luasocket/LICENSE b/doc/luasocket/LICENSE new file mode 100644 index 0000000..90d88e7 --- /dev/null +++ b/doc/luasocket/LICENSE @@ -0,0 +1,20 @@ +LuaSocket 2.0 license +Copyright © 2004-2005 Diego Nehab + +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/doc/luasocket/NEW b/doc/luasocket/NEW new file mode 100644 index 0000000..7c94368 --- /dev/null +++ b/doc/luasocket/NEW @@ -0,0 +1,54 @@ +What's New + +There is no big change for the 2.0 (final) release. It is +basically a bug fix release. The main improvement is in the +non-blocking support. + + * New: sample module dispatch.lua implements a coroutine + based dispatcher; + * New: sample check-links.lua works both in blocking and + non-blocking mode using coroutines (using the new + dispatcher); + * New: sample forward.lua implements a coroutine based + forward server (using the new dispatcher); + * Improved: tcp:send(data, i, j) to return (i+sent-1). This + is great for non-blocking I/O, but might break some code; + * Improved: HTTP, SMTP, and FTP functions to accept a new + field create that overrides the function used to create + socket objects; + * Improved: smtp.message now supports multipart/alternative + (for the HTML messages we all love so much); + * Fixed: smtp.send was hanging on errors returned by LTN12 + sources; + * Fixed: url.absolute() to work when base_url is in parsed + form; + * Fixed: http.request() not to redirect when the location + header is empty (naughty servers...); + * Fixed: tcp{client}:shutdown() to check for class instead + of group; + * Fixed: The manual to stop using socket.try() in place of + assert(), since it can't; + * Improved: Got rid of package.loaded.base = _G kludge; + * Fixed: Parts of the manual referred to require("http") + instead of require("socket.http"); + * Improved: Socket and MIME binaries are called 'core' each + inside their directory (ex. "socket/core.dll"). The 'l' + prefix was just a bad idea; + * Improved: Using bundles in Mac OS X, instead of dylibs; + * Fixed: luasocket.h to export luaopen_socket_core; + * Fixed: udp:setpeername() so you can "disconnect" an UDP + socket; + * Fixed: A weird bug in HTTP support that caused some + requests to fail (Florian Berger); + * Fixed: Bug in socket.select() that caused sockets with + descriptor 0 to be ignored (Renato Maia); + * Fixed: "Bug" that caused dns.toip() to crash under uLinux + (William Trenker); + * Fixed: "Bug" that caused gethostbyname to crash under VMS + (Renato Maia); + * Fixed: tcp:send("") to return 0 bytes sent (Alexander + Marinov); + * Improved: socket.DEBUG and socket.VERSION became + socket._DEBUGs and socket._VERSION for uniformity with other + libraries; + * Improved: socket.select now works on empty sets on Windows. diff --git a/doc/luasocket/README b/doc/luasocket/README new file mode 100644 index 0000000..acb4dfe --- /dev/null +++ b/doc/luasocket/README @@ -0,0 +1,6 @@ +This is the LuaSocket 2.0. It has been tested on WinXP, Mac OS X, +and Linux. Please use the Lua mailing list to report any bugs +(or "features") you encounter. + +Have fun, +Diego Nehab. diff --git a/doc/luasocket/dns.html b/doc/luasocket/dns.html new file mode 100644 index 0000000..826e4a2 --- /dev/null +++ b/doc/luasocket/dns.html @@ -0,0 +1,132 @@ + + + + + + +LuaSocket: DNS support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

DNS

+ +

+Name resolution functions return all information obtained from the +resolver in a table of the form: +

+ +
+resolved = {
+  name = canonic-name,
+  alias = alias-list,
+  ip = ip-address-list
+} +
+ +

+Note that the alias list can be empty. +

+ + + +

+socket.dns.gethostname() +

+ +

+Returns the standard host name for the machine as a string. +

+ + + +

+socket.dns.tohostname(address) +

+ +

+Converts from IP address to host name. +

+ +

+Address can be an IP address or host name. +

+ +

+The function returns a string with the canonic host name of the given +address, followed by a table with all information returned by +the resolver. In case of error, the function returns nil +followed by an error message. +

+ + + +

+socket.dns.toip(address) +

+ +

+Converts from host name to IP address. +

+ +

+Address can be an IP address or host name. +

+ +

+Returns a string with the first IP address found for address, +followed by a table with all information returned by the resolver. +In case of error, the function returns nil followed by an error +message. +

+ + + + + + + diff --git a/doc/luasocket/ftp.html b/doc/luasocket/ftp.html new file mode 100644 index 0000000..4398a2a --- /dev/null +++ b/doc/luasocket/ftp.html @@ -0,0 +1,289 @@ + + + + + + +LuaSocket: FTP support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

FTP

+ +

+FTP (File Transfer Protocol) is a protocol used to transfer files +between hosts. The ftp namespace offers thorough support +to FTP, under a simple interface. The implementation conforms to +RFC 959. +

+ +

+High level functions are provided supporting the most common operations. +These high level functions are implemented on top of a lower level +interface. Using the low-level interface, users can easily create their +own functions to access any operation supported by the FTP +protocol. For that, check the implementation. +

+ +

+To really benefit from this module, a good understanding of + +LTN012, Filters sources and sinks is necessary. +

+ +

+To obtain the ftp namespace, run: +

+ +
+-- loads the FTP module and any libraries it requires
+local ftp = require("socket.ftp")
+
+ +

+URLs MUST conform to +RFC +1738, that is, an URL is a string in the form: +

+ +
+ +[ftp://][<user>[:<password>]@]<host>[:<port>][/<path>][type=a|i] +
+ +

+The following constants in the namespace can be set to control the default behavior of +the FTP module: +

+ +
    +
  • PASSWORD: default anonymous password. +
  • PORT: default port used for the control connection; +
  • TIMEOUT: sets the timeout for all I/O operations; +
  • USER: default anonymous user; +
+ + + + +

+ftp.get(url)
+ftp.get{
+  host = string,
+  sink = LTN12 sink,
+  argument or path = string,
+  [user = string,]
+  [password = string]
+  [command = string,]
+  [port = number,]
+  [type = string,]
+  [step = LTN12 pump step,]
+  [create = function]
+} +

+ +

+The get function has two forms. The simple form has fixed +functionality: it downloads the contents of a URL and returns it as a +string. The generic form allows a lot more control, as explained +below. +

+ +

+If the argument of the get function is a table, the function +expects at least the fields host, sink, and one of +argument or path (argument takes +precedence). Host is the server to connect to. Sink is +the simple +LTN12 +sink that will receive the downloaded data. Argument or +path give the target path to the resource in the server. The +optional arguments are the following: +

+
    +
  • user, password: User name and password used for +authentication. Defaults to "ftp:anonymous@anonymous.org"; +
  • command: The FTP command used to obtain data. Defaults to +"retr", but see example below; +
  • port: The port to used for the control connection. Defaults to 21; +
  • type: The transfer mode. Can take values "i" or +"a". Defaults to whatever is the server default; +
  • step: +LTN12 +pump step function used to pass data from the +server to the sink. Defaults to the LTN12 pump.step function; +
  • create: An optional function to be used instead of +socket.tcp when the communications socket is created. +
+ +

+If successful, the simple version returns the URL contents as a +string, and the generic function returns 1. In case of error, both +functions return nil and an error message describing the +error. +

+ +
+-- load the ftp support
+local ftp = require("socket.ftp")
+
+-- Log as user "anonymous" on server "ftp.tecgraf.puc-rio.br",
+-- and get file "lua.tar.gz" from directory "pub/lua" as binary.
+f, e = ftp.get("ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz;type=i")
+
+ +
+-- load needed modules
+local ftp = require("socket.ftp")
+local ltn12 = require("ltn12")
+local url = require("socket.url")
+
+-- a function that returns a directory listing
+function nlst(u)
+    local t = {}
+    local p = url.parse(u)
+    p.command = "nlst"
+    p.sink = ltn12.sink.table(t)
+    local r, e = ftp.get(p)
+    return r and table.concat(t), e
+end
+
+ + + +

+ftp.put(url, content)
+ftp.put{
+  host = string,
+  source = LTN12 sink,
+  argument or path = string,
+  [user = string,]
+  [password = string]
+  [command = string,]
+  [port = number,]
+  [type = string,]
+  [step = LTN12 pump step,]
+  [create = function]
+} +

+ +

+The put function has two forms. The simple form has fixed +functionality: it uploads a string of content into a URL. The generic form +allows a lot more control, as explained below. +

+ +

+If the argument of the put function is a table, the function +expects at least the fields host, source, and one of +argument or path (argument takes +precedence). Host is the server to connect to. Source is +the simple +LTN12 +source that will provide the contents to be uploaded. +Argument or +path give the target path to the resource in the server. The +optional arguments are the following: +

+
    +
  • user, password: User name and password used for +authentication. Defaults to "ftp:anonymous@anonymous.org"; +
  • command: The FTP command used to send data. Defaults to +"stor", but see example below; +
  • port: The port to used for the control connection. Defaults to 21; +
  • type: The transfer mode. Can take values "i" or +"a". Defaults to whatever is the server default; +
  • step: +LTN12 +pump step function used to pass data from the +server to the sink. Defaults to the LTN12 pump.step function; +
  • create: An optional function to be used instead of +socket.tcp when the communications socket is created. +
+ +

+Both functions return 1 if successful, or nil and an error +message describing the reason for failure. +

+ +
+-- load the ftp support
+local ftp = require("socket.ftp")
+
+-- Log as user "fulano" on server "ftp.example.com",
+-- using password "silva", and store a file "README" with contents 
+-- "wrong password, of course"
+f, e = ftp.put("ftp://fulano:silva@ftp.example.com/README", 
+    "wrong password, of course")
+
+ +
+-- load the ftp support
+local ftp = require("socket.ftp")
+local ltn12 = require("ltn12")
+
+-- Log as user "fulano" on server "ftp.example.com",
+-- using password "silva", and append to the remote file "LOG", sending the
+-- contents of the local file "LOCAL-LOG"
+f, e = ftp.put{
+  host = "ftp.example.com", 
+  user = "fulano",
+  password = "silva",
+  command = "appe",
+  argument = "LOG",
+  source = ltn12.source.file(io.open("LOCAL-LOG", "r"))
+}
+
+ + + + + + + + diff --git a/doc/luasocket/home.html b/doc/luasocket/home.html new file mode 100644 index 0000000..06369a7 --- /dev/null +++ b/doc/luasocket/home.html @@ -0,0 +1,256 @@ + + + + + + +LuaSocket: Network support for the Lua language + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

What is LuaSocket?

+ +

+LuaSocket is a Lua extension library +that is composed by two parts: a C core that provides support for the TCP +and UDP transport layers, and a set of Lua modules that add support for +functionality commonly needed by applications that deal with the Internet. +

+ +

+The core support has been implemented so that it is both efficient and +simple to use. It is available to any Lua application once it has been +properly initialized by the interpreter in use. The code has been tested +and runs well on several Windows and Unix platforms.

+ +

+Among the support modules, the most commonly used implement the +SMTP +(sending e-mails), +HTTP +(WWW access) and +FTP +(uploading and downloading files) client +protocols. These provide a very natural and generic interface to the +functionality defined by each protocol. +In addition, you will find that the +MIME (common encodings), +URL +(anything you could possible want to do with one) and +LTN12 +(filters, sinks, sources and pumps) modules can be very handy. +

+ +

+The library is available under the same + +terms and conditions as the Lua language, the MIT license. The idea is +that if you can use Lua in a project, you should also be able to use +LuaSocket. +

+ +

+Copyright © 2004-2005 Diego Nehab. All rights reserved.
+Author: Diego Nehab +

+ + + +

Download

+ +

+LuaSocket version 2.0 (final) is now available for download! It is +compatible with Lua 5.0 and has been tested on +Windows XP, Linux, and Mac OS X. +

+ +

+The library can be downloaded in source code from the +LuaSocket +project page at LuaForge. +Besides the full C and Lua source code for the library, the distribution +contains several examples, this user's manual and basic test procedures. +

+ +

+Danilo Tuler is maintaining Win32 binaries for LuaSocket, which are also +available from LuaForge. These are compatible with the +LuaBinaries +available from LuaForge. +

+ +

+For those that want to give LuaSocket a quick try, download the +stand-alone archive and unpack everything into +a directory, say c:\luasocket. Then set LUA_INIT to load +the compat-5.1.lua and set LUA_PATH and +LUA_CPATH to look for files in the current directory: +

+ +
+c:\luasocket\> set LUA_INIT=@c:\luasocket\compat-5.1.lua
+c:\luasocket\> set LUA_CPATH=?.dll
+c:\luasocket\> set LUA_PATH=?.lua
+
+ +

+From that directory, you can then run the interpreter and it should find all +files it needs. To download this manual page from the Internet, for example, +do the following: +

+ +
+c:\luasocket\> lua50
+Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
+> http = require"socket.http"
+> print(http.request"http://www.cs.princeton.edu/~diego/professional/luasocket/")
+--> the source to this web page gets dumped to terminal
+
+ +

When you are done playing, take a look at the +installation section of the manual to find out +how to properly install the library.

+ + + +

Special thanks

+ +

+Throughout LuaSocket's history, many people gave suggestions that helped +improve it. For that, I thank the Lua community. +Special thanks go to +David Burgess, who has helped push the library to a new level of quality and +from whom I have learned a lot of stuff that doesn't show up in RFCs. +Special thanks also to Carlos Cassino, who played a big part in the +extensible design seen in the C core of LuaSocket 2.0. Recently, Mike Pall +has been helping a lot too! Thanks to you all! +

+ + + +

What's New

+ +

+There is no big change for the 2.0 (final) release. It is basically a +bug fix release. The only improvement is in the non-blocking +support. +

+ +
    +
  • New: sample module dispatch.lua implements a +coroutine based dispatcher; +
  • New: sample check-links.lua works +both in blocking and non-blocking mode using coroutines +(using the new dispatcher); +
  • New: sample forward.lua implements a coroutine +based forward server (using the new dispatcher); +
  • Improved: tcp:send(data, i, j) to return (i+sent-1). This is great for non-blocking I/O, but might break some code; +
  • Improved: HTTP, SMTP, and FTP functions to accept a new field +create that overrides the function used to create socket objects; +
  • Improved: smtp.message now supports multipart/alternative +(for the HTML messages we all love so much); +
  • Fixed: smtp.send was hanging on errors returned by LTN12 sources; +
  • Fixed: url.absolute() to work when base_url is in +parsed form; +
  • Fixed: http.request() not to redirect when the location +header is empty (naughty servers...); +
  • Fixed: tcp{client}:shutdown() to check for class instead of +group; +
  • Fixed: The manual to stop using socket.try() in place of +assert(), since it can't; +
  • Improved: Got rid of package.loaded.base = _G kludge; +
  • Fixed: Parts of the manual referred to require("http") instead of +require("socket.http"); +
  • Improved: Socket and MIME binaries are called 'core' each inside their +directory (ex. "socket/core.dll"). The 'l' prefix was just a bad idea; +
  • Improved: Using bundles in Mac OS X, instead of dylibs; +
  • Fixed: luasocket.h to export luaopen_socket_core; +
  • Fixed: udp:setpeername() so you can "disconnect" an +UDP socket; +
  • Fixed: A weird bug in HTTP support that caused some requests to +fail (Florian Berger); +
  • Fixed: Bug in socket.select() that caused sockets +with descriptor 0 to be ignored (Renato Maia); +
  • Fixed: "Bug" that caused dns.toip() to crash under uLinux +(William Trenker); +
  • Fixed: "Bug" that caused gethostbyname to crash under VMS +(Renato Maia); +
  • Fixed: tcp:send("") to return 0 bytes sent (Alexander Marinov); +
  • Improved: socket.DEBUG and socket.VERSION became socket._DEBUGs and socket._VERSION for uniformity with other libraries; +
  • Improved: socket.select now works on empty sets on Windows. +
+ + + +

Incompatibilities with previous versions

+ +
    +
  • If you use the return value of tcp:send() and you +use the extra parameters to select only part of the string to be sent, your +code is now broken, but when you fix it, it will be much simpler; +
  • If you check socket.DEBUG or socket.VERSION, +change it to socket._DEBUG or socket._VERSION. +
+ + + +

Old Versions

+ +

+All previous versions of the LuaSocket library can be downloaded +here. Although these versions are no longer supported, they are +still available for those that have compatibility issues. +

+ + + + + + + diff --git a/doc/luasocket/http.html b/doc/luasocket/http.html new file mode 100644 index 0000000..a60ed25 --- /dev/null +++ b/doc/luasocket/http.html @@ -0,0 +1,325 @@ + + + + + + +LuaSocket: HTTP support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +introduction · +introduction · +reference +

+
+
+
+ + + +

HTTP

+ +

+HTTP (Hyper Text Transfer Protocol) is the protocol used to exchange +information between web-browsers and servers. The http +namespace offers full support for the client side of the HTTP +protocol (i.e., +the facilities that would be used by a web-browser implementation). The +implementation conforms to the HTTP/1.1 standard, +RFC +2616. +

+ +

+The module exports functions that provide HTTP functionality in different +levels of abstraction. From the simple +string oriented requests, through generic +LTN12 based, down to even lower-level if you bother to look through the source code. +

+ +

+To obtain the http namespace, run: +

+ +
+-- loads the HTTP module and any libraries it requires
+local http = require("socket.http")
+
+ +

+URLs must conform to +RFC +1738, +that is, an URL is a string in the form: +

+ +
+
+[http://][<user>[:<password>]@]<host>[:<port>][/<path>] 
+
+
+ +

+MIME headers are represented as a Lua table in the form: +

+ +
+ + +
+headers = {
+  field-1-name = field-1-value,
+  field-2-name = field-2-value,
+  field-3-name = field-3-value,
+  ...
+  field-n-name = field-n-value
+} +
+
+ +

+Field names are case insensitive (as specified by the standard) and all +functions work with lowercase field names. +Field values are left unmodified. +

+ +

+Note: MIME headers are independent of order. Therefore, there is no problem +in representing them in a Lua table. +

+ +

+The following constants can be set to control the default behavior of +the HTTP module: +

+ +
    +
  • PORT: default port used for connections; +
  • PROXY: default proxy used for connections; +
  • TIMEOUT: sets the timeout for all I/O operations; +
  • USERAGENT: default user agent reported to server. +
+ + + +

+http.request(url [, body])
+http.request{
+  url = string,
+  [sink = LTN12 sink,]
+  [method = string,]
+  [headers = header-table,]
+  [source = LTN12 source],
+  [step = LTN12 pump step,]
+  [proxy = string,]
+  [redirect = boolean,]
+  [create = function]
+} +

+ +

+The request function has two forms. The simple form downloads +a URL using the GET or POST method and is based +on strings. The generic form performs any HTTP method and is +LTN12 based. +

+ +

+If the first argument of the request function is a string, it +should be an url. In that case, if a body +is provided as a string, the function will perform a POST method +in the url. Otherwise, it performs a GET in the +url +

+ +

+If the first argument is instead a table, the most important fields are +the url and the simple +LTN12 +sink that will receive the downloaded content. +Any part of the url can be overridden by including +the appropriate field in the request table. +If authentication information is provided, the function +uses the Basic Authentication Scheme (see note) +to retrieve the document. If sink is nil, the +function discards the downloaded data. The optional parameters are the +following: +

+
    +
  • method: The HTTP request method. Defaults to "GET"; +
  • headers: Any additional HTTP headers to send with the request; +
  • source: simple +LTN12 +source to provide the request body. If there +is a body, you need to provide an appropriate "content-length" +request header field, or the function will attempt to send the body as +"chunked" (something few servers support). Defaults to the empty source; +
  • step: +LTN12 +pump step function used to move data. +Defaults to the LTN12 pump.step function. +
  • proxy: The URL of a proxy server to use. Defaults to no proxy; +
  • redirect: Set to false to prevent the +function from automatically following 301 or 302 server redirect messages; +
  • create: An optional function to be used instead of +socket.tcp when the communications socket is created. +
+ +

+In case of failure, the function returns nil followed by an +error message. If successful, the simple form returns the response +body as a string, followed by the response status code, the response +headers and the response status line. The complex function returns the same +information, except the first return value is just the number 1 (the body +goes to the sink). +

+ +

+Even when the server fails to provide the contents of the requested URL (URL not found, for example), +it usually returns a message body (a web page informing the +URL was not found or some other useless page). To make sure the +operation was successful, check the returned status code. For +a list of the possible values and their meanings, refer to RFC +2616. +

+ +

+Here are a few examples with the simple interface: +

+ +
+-- load the http module
+local io = require("io")
+local http = require("socket.http")
+local ltn12 = require("ltn12")
+
+-- connect to server "www.cs.princeton.edu" and retrieves this manual
+-- file from "~diego/professional/luasocket/http.html" and print it to stdout
+http.request{ 
+    url = "http://www.cs.princeton.edu/~diego/professional/luasocket/http.html", 
+    sink = ltn12.sink.file(io.stdout)
+}
+
+-- connect to server "www.example.com" and tries to retrieve
+-- "/private/index.html". Fails because authentication is needed.
+b, c, h = http.request("http://www.example.com/private/index.html")
+-- b returns some useless page telling about the denied access, 
+-- h returns authentication information
+-- and c returns with value 401 (Authentication Required)
+
+-- tries to connect to server "wrong.host" to retrieve "/"
+-- and fails because the host does not exist.
+r, e = http.request("http://wrong.host/")
+-- r is nil, and e returns with value "host not found"
+
+ +

+And here is an example using the generic interface: +

+ +
+-- load the http module
+http = require("socket.http")
+
+-- Requests information about a document, without downloading it.
+-- Useful, for example, if you want to display a download gauge and need
+-- to know the size of the document in advance
+r, c, h = http.request {
+  method = "HEAD",
+  url = "http://www.tecgraf.puc-rio.br/~diego"
+}
+-- r is 1, c is 200, and h would return the following headers:
+-- h = {
+--   date = "Tue, 18 Sep 2001 20:42:21 GMT",
+--   server = "Apache/1.3.12 (Unix)  (Red Hat/Linux)",
+--   ["last-modified"] = "Wed, 05 Sep 2001 06:11:20 GMT",
+--   ["content-length"] = 15652,
+--   ["connection"] = "close",
+--   ["content-Type"] = "text/html"
+-- }
+
+ +

+Note: Some URLs are protected by their +servers from anonymous download. For those URLs, the server must receive +some sort of authentication along with the request or it will deny +download and return status "401 Authentication Required". +

+ +

+The HTTP/1.1 standard defines two authentication methods: the Basic +Authentication Scheme and the Digest Authentication Scheme, both +explained in detail in +RFC 2068. +

+ +

The Basic Authentication Scheme sends +<user> and +<password> unencrypted to the server and is therefore +considered unsafe. Unfortunately, by the time of this implementation, +the wide majority of servers and browsers support the Basic Scheme only. +Therefore, this is the method used by the toolkit whenever +authentication is required. +

+ +
+-- load required modules
+http = require("socket.http")
+mime = require("mime")
+
+-- Connect to server "www.example.com" and tries to retrieve
+-- "/private/index.html", using the provided name and password to
+-- authenticate the request
+b, c, h = http.request("http://fulano:silva@www.example.com/private/index.html")
+
+-- Alternatively, one could fill the appropriate header and authenticate
+-- the request directly.
+r, c = http.request {
+  url = "http://www.example.com/private/index.html",
+  headers = { authentication = "Basic " .. (mime.b64("fulano:silva")) }
+}
+
+ + + + + + + diff --git a/doc/luasocket/installation.html b/doc/luasocket/installation.html new file mode 100644 index 0000000..fa1d96f --- /dev/null +++ b/doc/luasocket/installation.html @@ -0,0 +1,161 @@ + + + + + + +LuaSocket: Installation + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

Installation

+ +

LuaSocket 2.0 uses the new package proposal for Lua 5.1. +All Lua library developers are encouraged to update their libraries so that +all libraries can coexist peacefully and users can benefit from the +standardization and flexibility of the standard. +

+ +

+The proposal was considered important enough by some of us to justify +early adoption, even before release of Lua 5.1. +Thus, a compatibility module +compat-5.1 +has been released in conjunction with Roberto Ierusalimschy and The Kepler Project team. +It implements the Lua 5.1 package proposal on top of Lua 5.0.

+ +

As far as LuaSocket is concerned, this means that whoever is +deploying a non-standard distribution of LuaSocket will probably +have no problems customizing it. Here we will only describe the standard distribution. If the standard doesn't meet your +needs, we refer you to the Lua discussion list, where any question about +the package scheme will likely already have been answered. +

+ +

Directory structure

+ +

On Unix systems, the standard distribution uses two base +directories, one for system dependent files, and another for system +independent files. Let's call these directories <CDIR> +and <LDIR>, respectively. +For instance, in my laptop, I use '/usr/local/lib/lua/5.0' for +<CDIR> and '/usr/local/share/lua/5.0' for +<LDIR>. On Windows, sometimes only one directory is used, say +'c:\program files\lua\5.0'. Here is the standard LuaSocket +distribution directory structure:

+ +
+<LDIR>/compat-5.1.lua
+<LDIR>/ltn12.lua
+<LDIR>/socket.lua
+<CDIR>/socket/core.dll
+<LDIR>/socket/http.lua
+<LDIR>/socket/tp.lua
+<LDIR>/socket/ftp.lua
+<LDIR>/socket/smtp.lua
+<LDIR>/socket/url.lua
+<LDIR>/mime.lua
+<CDIR>/mime/core.dll
+
+ +

Naturally, on Unix systems, core.dll +would be replaced by core.so. +

+ +

In order for the interpreter to find all LuaSocket components, three +environment variables need to be set. The first environment variable tells +the interpreter to load the compat-5.1.lua module at startup:

+ +
+LUA_INIT=@<LDIR>/compat-5.1.lua
+
+ +

+The other two environment variables instruct the compatibility module to +look for dynamic libraries and extension modules in the appropriate +directories and with the appropriate filename extensions. +

+ +
+LUA_PATH=<LDIR>/?.lua;?.lua
+LUA_CPATH=<CDIR>/?.dll;?.dll
+
+ +

Again, naturally, on Unix systems the shared library extension would be +.so instead of .dll.

+ +

Using LuaSocket

+ +

With the above setup, and an interpreter with shared library support, +it should be easy to use LuaSocket. Just fire the interpreter and use the +require function to gain access to whatever module you need:

+ +
+Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
+> socket = require("socket")
+> print(socket._VERSION)
+--> LuaSocket 2.0
+
+ +

Each module loads their dependencies automatically, so you only need to +load the modules you directly depend upon:

+ +
+Lua 5.0.2  Copyright (C) 1994-2004 Tecgraf, PUC-Rio
+> http = require("socket.http")
+> print(http.request("http://www.cs.princeton.edu/~diego/professional/luasocket"))
+--> homepage gets dumped to terminal
+
+ + + + + + + diff --git a/doc/luasocket/introduction.html b/doc/luasocket/introduction.html new file mode 100644 index 0000000..bb55762 --- /dev/null +++ b/doc/luasocket/introduction.html @@ -0,0 +1,333 @@ + + + + + + +LuaSocket: Introduction to the core + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

Introduction

+ +

+LuaSocket is a Lua extension library +that is composed by two parts: a C core that provides support for the TCP +and UDP transport layers, and a set of Lua modules that add support for +the SMTP (sending e-mails), HTTP (WWW access) and FTP (uploading and +downloading files) protocols and other functionality commonly needed by +applications that deal with the Internet. This introduction is about the C +core. +

+ +

+Communication in LuaSocket is performed via I/O objects. These can +represent different network domains. Currently, support is provided for TCP +and UDP, but nothing prevents other developers from implementing SSL, Local +Domain, Pipes, File Descriptors etc. I/O objects provide a standard +interface to I/O across different domains and operating systems. +

+ +

+The API design had two goals in mind. First, users +experienced with the C API to sockets should feel comfortable using LuaSocket. +Second, the simplicity and the feel of the Lua language should be +preserved. To achieve these goals, the LuaSocket API keeps the function names and semantics the C API whenever possible, but their usage in Lua has been greatly simplified. +

+ + +

+One of the simplifications is the receive pattern capability. +Applications can read data from stream domains (such as TCP) +line by line, block by block, or until the connection is closed. +All I/O reads are buffered and the performance differences between +different receive patterns are negligible. +

+ +

+Another advantage is the flexible timeout control +mechanism. As in C, all I/O operations are blocking by default. For +example, the send, +receive and +accept methods +of the TCP domain will block the caller application until +the operation is completed (if ever!). However, with a call to the +settimeout +method, an application can specify upper limits on +the time it can be blocked by LuaSocket (the "total" timeout), on +the time LuaSocket can internally be blocked by any OS call (the +"block" timeout) or a combination of the two. Each LuaSocket +call might perform several OS calls, so that the two timeout values are +not equivalent. +

+ +

+Finally, the host name resolution is transparent, meaning that most +functions and methods accept both IP addresses and host names. In case a +host name is given, the library queries the system's resolver and +tries the main IP address returned. Note that direct use of IP addresses +is more efficient, of course. The +toip +and tohostname +functions from the DNS module are provided to convert between host names and IP addresses. +

+ +

+Together, these changes make network programming in LuaSocket much simpler +than it is in C, as the following sections will show. +

+ + + +

TCP

+ +

+TCP (Transfer Control Protocol) is reliable stream protocol. In other +words, applications communicating through TCP can send and receive data as +an error free stream of bytes. Data is split in one end and +reassembled transparently on the other end. There are no boundaries in +the data transfers. The library allows users to read data from the +sockets in several different granularities: patterns are available for +lines, arbitrary sized blocks or "read up to connection closed", all with +good performance. +

+ +

+The library distinguishes three types of TCP sockets: master, +client and server sockets. +

+ +

+Master sockets are newly created TCP sockets returned by the function +socket.tcp. A master socket is +transformed into a server socket +after it is associated with a local address by a call to the +bind method followed by a call to the +listen. Conversely, a master socket +can be changed into a client socket with the method +connect, +which associates it with a remote address. +

+ +

+On server sockets, applications can use the +accept method +to wait for a client connection. Once a connection is established, a +client socket object is returned representing this connection. The +other methods available for server socket objects are +getsockname, +setoption, +settimeout, and +close. +

+ +

+Client sockets are used to exchange data between two applications over +the Internet. Applications can call the methods +send and +receive +to send and receive data. The other methods +available for client socket objects are +getsockname, +getpeername, +setoption, +settimeout, +shutdown, and +close. +

+ +

+Example: +

+
+

+A simple echo server, using LuaSocket. The program binds to an ephemeral +port (one that is chosen by the operating system) on the local host and +awaits client connections on that port. When a connection is established, +the program reads a line from the remote end and sends it back, closing +the connection immediately. You can test it using the telnet +program. +

+ +
+-- load namespace
+local socket = require("socket")
+-- create a TCP socket and bind it to the local host, at any port
+local server = assert(socket.bind("*", 0))
+-- find out which port the OS chose for us
+local ip, port = server:getsockname()
+-- print a message informing what's up
+print("Please telnet to localhost on port " .. port)
+print("After connecting, you have 10s to enter a line to be echoed")
+-- loop forever waiting for clients
+while 1 do
+  -- wait for a connection from any client
+  local client = server:accept()
+  -- make sure we don't block waiting for this client's line
+  client:settimeout(10)
+  -- receive the line
+  local line, err = client:receive()
+  -- if there was no error, send it back to the client
+  if not err then client:send(line .. "\n") end
+  -- done with client, close the object
+  client:close()
+end
+
+
+ + + +

UDP

+ +

+UDP (User Datagram Protocol) is a non-reliable datagram protocol. In +other words, applications communicating through UDP send and receive +data as independent blocks, which are not guaranteed to reach the other +end. Even when they do reach the other end, they are not guaranteed to be +error free. Data transfers are atomic, one datagram at a time. Reading +only part of a datagram discards the rest, so that the following read +operation will act on the next datagram. The advantages are in +simplicity (no connection setup) and performance (no error checking or +error correction). +

+ +

+Note that although no guarantees are made, these days +networks are so good that, under normal circumstances, few errors +happen in practice. +

+ +

+An UDP socket object is created by the +socket.udp function. UDP +sockets do not need to be connected before use. The method +sendto +can be used immediately after creation to +send a datagram to IP address and port. Host names are not allowed +because performing name resolution for each packet would be forbiddingly +slow. Methods +receive and +receivefrom +can be used to retrieve datagrams, the latter returning the IP and port of +the sender as extra return values (thus being slightly less +efficient). +

+ +

+When communication is performed repeatedly with a single peer, an +application should call the +setpeername method to specify a +permanent partner. Methods +sendto and +receivefrom +can no longer be used, but the method +send can be used to send data +directly to the peer, and the method +receive +will only return datagrams originating +from that peer. There is about 30% performance gain due to this practice. +

+ +

+To associate an UDP socket with a local address, an application calls the +setsockname +method before sending any datagrams. Otherwise, the socket is +automatically bound to an ephemeral address before the first data +transmission and once bound the local address cannot be changed. +The other methods available for UDP sockets are +getpeername, +getsockname, +settimeout, +setoption and +close. +

+ +

+Example: +

+
+

+A simple daytime client, using LuaSocket. The program connects to a remote +server and tries to retrieve the daytime, printing the answer it got or an +error message. +

+ +
+-- change here to the host an port you want to contact
+local host, port = "localhost", 13
+-- load namespace
+local socket = require("socket")
+-- convert host name to ip address
+local ip = assert(socket.dns.toip(host))
+-- create a new UDP object
+local udp = assert(socket.udp())
+-- contact daytime host
+assert(udp:sendto("anything", ip, port))
+-- retrieve the answer and print results
+io.write(assert(udp:receive()))
+
+
+ + + +

Support modules

+ +

Although not covered in the introduction, LuaSocket offers +much more than TCP and UDP functionality. As the library +evolved, support for HTTP, FTP, +and SMTP were built on top of these. These modules +and many others are covered by the reference manual. +

+ + + + + + + diff --git a/doc/luasocket/ltn12.html b/doc/luasocket/ltn12.html new file mode 100644 index 0000000..7d2842e --- /dev/null +++ b/doc/luasocket/ltn12.html @@ -0,0 +1,430 @@ + + + + + + +LuaSocket: LTN12 module + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

LTN12

+ +

The ltn12 namespace implements the ideas described in + +LTN012, Filters sources and sinks. This manual simply describes the +functions. Please refer to the LTN for a deeper explanation of the +functionality provided by this module. +

+ +

+To obtain the ltn12 namespace, run: +

+ +
+-- loads the LTN21 module
+local ltn12 = require("ltn12")
+
+ + + +

Filters

+ + + +

+ltn12.filter.chain(filter1, filter2 +[, ... filterN]) +

+ +

+Returns a filter that passes all data it receives through each of a +series of given filters. +

+ +

+Filter1 to filterN are simple +filters. +

+ +

+The function returns the chained filter. +

+ +

+The nesting of filters can be arbitrary. For instance, the useless filter +below doesn't do anything but return the data that was passed to it, +unaltered. +

+ +
+-- load required modules
+local ltn12 = require("ltn12")
+local mime = require("mime")
+
+-- create a silly identity filter
+id = ltn12.filter.chain(
+  mime.encode("quoted-printable"),
+  mime.encode("base64"),
+  mime.decode("base64"),
+  mime.decode("quoted-printable")
+)
+
+ + + +

+ltn12.filter.cycle(low [, ctx, extra]) +

+ +

+Returns a high-level filter that cycles though a low-level filter by +passing it each chunk and updating a context between calls. +

+ +

+Low is the low-level filter to be cycled, +ctx is the initial context and extra is any extra +argument the low-level filter might take. +

+ +

+The function returns the high-level filter. +

+ +
+-- load the ltn12 module
+local ltn12 = require("ltn12")
+
+-- the base64 mime filter factory
+encodet['base64'] = function()
+    return ltn12.filter.cycle(b64, "")
+end
+
+ + + +

Pumps

+ + + +

+ltn12.pump.all(source, sink) +

+ +

+Pumps all data from a source to a sink. +

+ +

+If successful, the function returns a value that evaluates to +true. In case +of error, the function returns a false value, followed by an error message. +

+ + + +

+ltn12.pump.step(source, sink) +

+ +

+Pumps one chunk of data from a source to a sink. +

+ +

+If successful, the function returns a value that evaluates to +true. In case +of error, the function returns a false value, followed by an error message. +

+ + + +

Sinks

+ + + +

+ltn12.sink.chain(filter, sink) +

+ +

+Creates and returns a new sink that passes data through a filter before sending it to a given sink. +

+ + + +

+ltn12.sink.error(message) +

+ +

+Creates and returns a sink that aborts transmission with the error +message. +

+ + + +

+ltn12.sink.file(handle, message) +

+ +

+Creates a sink that sends data to a file. +

+ +

+Handle is a file handle. If handle is nil, +message should give the reason for failure. +

+ +

+The function returns a sink that sends all data to the given handle +and closes the file when done, or a sink that aborts the transmission with +the error message +

+ +

+In the following example, notice how the prototype is designed to +fit nicely with the io.open function. +

+ +
+-- load the ltn12 module
+local ltn12 = require("ltn12")
+
+-- copy a file
+ltn12.pump.all(
+  ltn12.source.file(io.open("original.png")),
+  ltn12.sink.file(io.open("copy.png"))
+)
+
+ + + +

+ltn12.sink.null() +

+ +

+Returns a sink that ignores all data it receives. +

+ + + +

+ltn12.sink.simplify(sink) +

+ +

+Creates and returns a simple sink given a fancy sink. +

+ + + +

+ltn12.sink.table([table]) +

+ +

+Creates a sink that stores all chunks in a table. The chunks can later be +efficiently concatenated into a single string. +

+ +

+Table is used to hold the chunks. If +nil, the function creates its own table. +

+ +

+The function returns the sink and the table used to store the chunks. +

+ +
+-- load needed modules
+local http = require("socket.http")
+local ltn12 = require("ltn12")
+
+-- a simplified http.get function
+function http.get(u)
+  local t = {}
+  local respt = request{
+    url = u,
+    sink = ltn12.sink.table(t)
+  }
+  return table.concat(t), respt.headers, respt.code
+end
+
+ + + +

Sources

+ + + +

+ltn12.source.cat(source1 [, source2, ..., +sourceN]) +

+ +

+Creates a new source that produces the concatenation of the data produced +by a number of sources. +

+ +

+Source1 to sourceN are the original +sources. +

+ +

+The function returns the new source. +

+ + + +

+ltn12.source.chain(source, filter) +

+ +

+Creates a new source that passes data through a filter +before returning it. +

+ +

+The function returns the new source. +

+ + + +

+ltn12.source.empty() +

+ +

+Creates and returns an empty source. +

+ + + +

+ltn12.source.error(message) +

+ +

+Creates and returns a source that aborts transmission with the error +message. +

+ + + +

+ltn12.source.file(handle, message) +

+ +

+Creates a source that produces the contents of a file. +

+ +

+Handle is a file handle. If handle is nil, +message should give the reason for failure. +

+ +

+The function returns a source that reads chunks of data from +given handle and returns it to the user, +closing the file when done, or a source that aborts the transmission with +the error message +

+ +

+In the following example, notice how the prototype is designed to +fit nicely with the io.open function. +

+ +
+-- load the ltn12 module
+local ltn12 = require("ltn12")
+
+-- copy a file
+ltn12.pump.all(
+  ltn12.source.file(io.open("original.png")),
+  ltn12.sink.file(io.open("copy.png"))
+)
+
+ + + +

+ltn12.source.simplify(source) +

+ +

+Creates and returns a simple source given a fancy source. +

+ + + +

+ltn12.source.string(string) +

+ +

+Creates and returns a source that produces the contents of a +string, chunk by chunk. +

+ + + + + + + diff --git a/doc/luasocket/luasocket.png b/doc/luasocket/luasocket.png new file mode 100644 index 0000000000000000000000000000000000000000..d24a95495b55894b96aec1b01d0b7c02cc43f168 GIT binary patch literal 11732 zcmW++1ymGm7oH`T4vD3t6_iHlmKN!jUJ*q)M0$ml4r%F-?(Rkw1f;uDI;HcU@1L`A z&hG3xbMD^v-Y0Ibx~c*JE;TLy00c^kvYOyK;=d;p4SZEGI!^%rPAw%_Y3(nw``+#@ z+H#YZC52O;q6g)Bl}USLraK2Qg7$Fz@nAnRBwR5Zr4vbf)|SIW2J?Idh4}}=@OJR~ zcy=JN4uB*Ju0|~DuW}aRuPic(GQG-Br7ezyI}@F|`~1_jk<vF(q$U3K0YJ;ImxnqIVrJD)*0_au!r(hC8CxFA^2o+Lf5kb64 z>*Yn$i0Rh3b7WNR<^N^eVjo458Ow};G)uUWX2%9(ymGEf6aj91t+u_Hs=Ug|Xw4l5 zAs3N_E+R=AzC;)twpOH9_IG_c}6sn**$rhYO2AIsRqMas}{!22RRMUY#g>}f0?5`f$9U(DgE z=VgXql9O04ZEkM*-X8aKbaasX|5!tXhlYinTGkel)y(ZDa2ZFlus?gIObmlJTMeaM zUtcT5JOOWrDqP-FC_2O&kb>S{4c#V~%$gc|;{Xsv00V$H0EF$pJK%-Ohk;LJe;PK^ z$dsvMdhrOZV*tZ=rhX?mIXNSv6c(k`r$rO9WWqwU$>w$cDeEf95Z3$eFJ*3j(Y$qdwfl`bQ^=sXA%1DG(9vj>cBLpN-5eSL4ffuDoJX7yJv7|$wwj%Q5T1wc#o zT9b&0l~f+A(q^ihH*r$Aq%_EYaq@G~-Y!@S%i8uBrHl;P=qQ#( zAMa0X`ERuU5Jm3efR#ou8vMlUfz=PkhtF& zy|AXR`-vxzeUnf66P}rg^7Av5S9tqNWH{m=cg|0n10ELnSp0gYs4PvwoBBnH;jny> z!g-=bhh>f9;3HB}-4esIf9VhN!sGxjS$Y@YjE#b2G?7WAILl-Q1mvFWMxrCsbBqq_ z-I=wmCUagV)Y>nZn3zbo9n2SK<>5BC?dsc$EQCTQa%v|C+c(EGAJ%KUFE`XW7U;1%C zZf!LMA|)-&33S04oQamc63Z5>4J5uUC?Mf#Ie3Hifwi!Ikd2Qon)eAyiEi6z&dWjR zX@Ex_X$C|PpWjz!#Hz25e+y~J&j?Y&;`?Ju$!*f&C?8IYW)>Hx*YW53;wOw@i*#a5 zefd!DZb|S?XV1bTq+2W4SR=SXe|({^#t>7TglHwv}Dd5UH}KPh#xa z0WJL>OBvE%M@AsLyc97?fy5LW;CHqvC z!pzLCh=G)5@@8wHXYypu-6i=S?r;CmOWYJ+_C_feP2fsFf-V`dyYvqW3>YQZEx~|1 zd%oLtS4)hzyunsUB5N^|?(@TZwYKW_3-@QNJCpzL5`;lQLb3SA!EVMBf|n4nw&ve% zi+dhHT{ue}NhezC{_n44e|-33aYIW{<17={46i(l*&x^RJhs?0{b53nRp2cifHiEc zg5>S*zTBY07^6Ii;l*V@=kf2bKi@<4Jf;DQb+n0EGwgu;n-b|@-?K!~3sV@4oh%gH zK}p7H@Rm>59YKt2Q36U>cl+X=>y;WQsi^ElZx>yY=2$QX%*}0t)8H+BVXmvMCj|g} zBr$@Jek>fF5ejH1L-qhLjx8Rpvt2}y=l{lvyn#Q~#PUJ8Pv(wRK7Fz-hMt){#Rm|) z76TF=HTR;JpU>L{304z1?0hpy?PX+S#KFO7H8cGX7{ZjzNPoSyyN1Ojh7^V6itQ4U+12{z zhre^r*2t?xk57xI+sD>r59YZYW2Le?h8(q9vJ_Vr!2@6q2qo8;9XV% zlsFj}8YU$t7m>c=saI`i)14;uo12R>y*~*(J-s+N>4P4>QdDE#f3$}VScGXQlSD(0 zx!Ll6@WSsNsqNX>x(4Me)1tBAzE;6^KkhaFY(bWfi9*4E0h;2Rx^wMxwYi`usmI{ zTUqs-1xKq7QyKlLzISJbEI4@Y*(M>IUSqj(Zi~Y5@yV=8Hof9e(#Ra*um+B|=^oa9Kb0+HS}f5? ziW@=DG7}RMb8^7)$Q8$;RQ^+yHDt0NoY!MDc*ysx$QRu#>?}6qkGZ57J)<5vNe&rY z95u>6v}aVi$8Ro8YT`O5oyYue)AriuZda77TeX0I@jHu5P`QJP7gRc0mUuO`)&jq* zt#xa`?T~Ex@J~KeCwgzLj+=+ap%aNy7}fJ=i83vGQuoSAa_)K~0W+E`gRM9jZ6E6^ zIzz>NmNt?*=qo&o7iHl&@0iSDE>|&_ChpV|al=XBztud=t4J#0Rlj<*c|j+pk89?3 zK+w$w12D~yKMq?xr|BPrK3yL1$eAzx^!HE%)EJ>Ap{YDOo0<`aQ5;SN zumrOy@BRw*ud0m4!lde!0;GxxnUL=iYwMmvzs?jpn_w7F2#`naToRB-*^YSH1bI|( zREZwWU!F~Ui(X&aobCZ|H~WTsCGIy8tg^H59S*BPdiLi+O}?z`j*e2x48%GCTpxIB z4Nn$Zh-mQXR>YTI2;xNN$EtIa`tedogq7Nsw&I%G0v-2vH=jOz5`}I}G_qF*DbU{) zo0doN{+%a*eVA_ew^H(!^6Aq+&Awls^=>j_`}tTg!1V9c%F~rN=_OO1gF=98HtpzJ z!pFDf+oN@V<4>nL0WWr3Q^DyyM`*_xu3mW9`2 zs*^)F9c8T^W@{+sJH895n4ei3*hCVo4(1^oS}UU@`eQy&X%RXSPcHwjHq+(Hae9BX zth->sAD7!)cPl7O=M|v2+Hts~`1rr8e_gQCbrFpR zswqMmT3Y;8gS3Yic&;V6xf{VxCD5f(+@_FDKM}lW4$W78Q`dSFglV;rVV(*|XZuKK zM_9#_Npf;pn(W7>@(xErU{p)(&R$Ngip8A!ob)(k&c3aswpM_fTdjK$OoeaGn}ctD z@R%>Rf3>)7TFRJJfGlt4x#{V=B+lAw<`!)1ythn#`DyE9V~yQXgzi9-v~gGpItN|? zj{yfAXETi0*w}cj%%^6~^2b3t41~2bl0MDLGRDp03Y@*aCkwLJX1xM;54U+%lt~vW zH^zPMrryh_#GcnALKuHFi1Ryd-(LOB;%|M5U+^I(_BH8X?{uZJ6@>9gCK-tzyY0t&oyW*RT_?i($Nm??qi~d>u9i>w5xm`JEPNZu~I`R zY{FADWn4`4lr?f6mNChD$MyLJtd4mRZ=;(!N&$%A6EyTviB8~OsN?(TjyS@Jej zeo3{R2BLjeP*}KgdAt_Q;@Z9@ z8S{&Y$7WVr-DHu4;wvQux6+6&pZ4jcE)fo?{5y_78Vw8cnj2pmr~+-OBN1) z#5np#RrCmh3DL8nu8qIQFl`eur?QGv)ZLvRlITSr3YCKT|M>5Kkwh)AyGR2So*d7f zQH!{+eIaIEO=2+*^tYSU1~PVuHnT)*fD9(wM_%O^U+6^95Fp?LxSCCl%pA}S7UuU;D%unrrP2U7$P(R1}XX=!QYwS6uLz{0>NHfa$N z5TFq2cNu9>lN2YAl8fJbgQ~0}L|44INZ>^^54>5L{W?D%N&`1pIL0`?f{j{DIe2ZYhc5?xQ-$*cPfNsv=2D7x)vpM6EAY%hvm#Tn1w z1*V&?Jo9jWEtq0tJY4UNqEMgJuJZwzpx^IK)@hCu0oPTYvN?m75j)crg?)X`q1)F@ z=SUa}xpmf-id(8`ET2**CT0!DLa6}soKzL|K?uB{w3J=2jx>YWzvFd(+B~{(Kd_E* zv~`OHOxKl>No~J4&9R5@qDc6>@2|FP=Tu*l>XJpSP}`w5#3up3kaz-XzW_H$u;1v- zdFq9q2qi}2D@u$HHZ~kwT$7WSTiG~a0K?PGtfumvr^J>t*>TS$CEZHF?p~>);~U>& zl`@@R`9$e5(pT&VY$Z@$_nBdbK}fILlCgHw^2%egFfaj$!o$NC7!Xn(=H@H4wsXzb zbP)LX^t8|40aoB}M-m%Q>Rk0dCXk!=#5C85=Q6Ebbe%$lguItVpHSM(9d)@aVhhtO zor-CDxSKxoZKH&1^oUlLLdf*Jj`>dAA-wpijvIm@AxL~z*xBW)M=zF7T3bP$Gb zyF4Gpgjic!%ZF2M!~wLxV0s%`d-M9SSr`mXLUM24Dy$Y?psH|xySdjD=*#enAq*uL zi3Qyj+5|hnLl@CMN-kQkLxQ-OWM$z_D_Y^5CpNLvUfPm zqgN8X_qbn7AghftHWY+>lrKI@BR+!YQBF=;Z{_dC#+z25DWOd!9@#wRmLKjbbaE;D zgCvYTx<%e=sQGZ3$Ss$@IS`aif4k6njofNfW1_z%0<-Mb^UQKbu2K>9S3PDD|S2d9eNHc=`$9EBJkbHp%dC z+0dau#BM415l4Q_1Y_2;chiH&5z4RHYw7iFn4`e~`e9SA-u4e^CY4P7!lrqY*wQPu zjTEgYqCF$3AH<_Na(sF=zxm){o|W3Z5|(?3y)a-~4js(2 zAd>!={OG2+YL0Bvc0b7@V28l(r>5M;m3g}tJIu`f78Wv0OlWVOh;LSARXeCQ#XZ_y zAZGDtblT_xR|6@IG4TecmP!0Z%u}`8oSbjpzPTTNGY>&fuABFD%yD1zA9)>hnc6$yPd&NM~?VNv2s{eEeuLy^R3C#kF4YJp6&>4`nnP zIREu%+xKqQ$k%rYcpBPGOis?@?Qv`GE9!c6GE{5N4I-~ptWJlLsYj-z!5 z1tCpzgn@c!E-o!ZDLl_mav{h~F5{~G58UuDp}M>D2Y%ay#-?z2C4Hs2+4Yl?T<1+{ zYwKc}?;^D07Q8ldpOKQc8_9*LO$?MzSa7~ePI>vxagU^(ZJb`2 zDmvnL?I#-AZHX?8%wnC8n8<8aRwo_CPIPqiW8YiHi{Uh`TL@SZW$?euehWT3DBd1j z`fz}Y3Jb;nstnwgrDoE^tytK56W4+O9!4x+?P+=nnc!OvEMH%7gy83=Hqu#y;cgs> zD!D;H&g-v{eAoMo=r`EpLce3i609oCw4G|)6r-c z8irPsmhBCQLk6Wa$P8)||3Kh9Pr@J5Nw{nwI{d*6%K_F`bgUm|AZ6C8_n-b829gA2 zi2|x(D5FMZLrID4=3pw3*bzdpa5>2%dZ%)$lb#p`>lH35DIp*t!X~niQn{kyU#+v3 z99e>$2Y4ZQHY?lO%>N|K^e04yN7UA@i{WLDPt*{?%;H&0zp$e%kLC3gDJ~CYMPU;? z9vB>q2n(w=ECFS8P!pyIm1C*nL-qCbWo2dkIwn~JSDXLvBH-J%xP$~yPMzh?5du`w zC19EN12|h~I#5S01v!KBJp&QzaVhf_X=qJdzmCpiUtf`>Ww_Olz}}LnD!ZuDI`2_O zwH!P8@KA~{Ohmt8*$D>Zsw9%q)2GM9b;E9M{|(s+BzIc`hlD7rsNmz{-(IdorhAR9509!2|8UM_-;hW*}k6cE~^2xVns%WrHH zVPdja?~U3VN^kpey!s7~^89dVX?Xa1bTlay6%LnA@Zk67+5@rY=bvjHE9bds_OaqD zIIAg}m{7^cBa)j4n^}_4j(Qa(6N-=w%KI@-i4q05f3IZ7|2(a0^S(%4+LH-#EY;dI zBlV*rY+^f|B@bePo*26kbi;z9*;JL?96l;mXLn2Oo4-tFhM zf+$93Ymq&f=j#*%+A$UOab=SN9FJE?4pJTCIom;vzOTRk6_kMb#fP2o0;cw-FJ5TJ z{Y&}BC1zpRlbwf@Trd73?DXz(Z^j=&+ls-)gapc|^ENit=9!Gqe`@e08qL$w8C0WV zV-2PVXOE2_18+j@H#YQ&b*bP=vY!eB6-glu_%sxSR80zaVhC?k*rnrI);O8~*Oxhv zJimYc9z^RPXHZp*=vonSKgr%P(x_obFE*ToONvq5VJ`Wej^J1eHa|i*Q)S3$7*42j zs?iUUZ)Uv*GT1o8=6&bup+K_9lE$TUG?WpRaVFT-VA~E<e%GuCfhlIdI_Jb-O=u?>sggFDV`2Yynt|Oa_=2&0+feZmVR;M@fx=HN$)-c zf>mbVYsRP4a1p7_KWoicWq$DX z3};4#QiKC_M}%KucKr5ijpW^LwX8Z@Q7yfxtf?3z@;fG;=0P+6Z?o?p!U&iD z{XrJX|Fp<7r|nqY?o-jvhMB*#cs($!Lb1EkcPrY&FDt6^0YFl+4J1(_w1k81mX;gE z230`2MFlKep7J52%)Qg2<-X~#waT!>+U#4N+|lqWxTY4i#%%EOS6jtk0Kexw^GgHZ z810kAGjpS>JTMl6T(ISq7>i1Z-b67gJf3TIAE9$&0oqL;lK%BQzwz@A&j{B4OUv^F zG&G9zeAz37sn&?ZUwBNFvMNM~rKPsqb`gOt-46>M#jC5A+uJmKebgi}pPMSJbqsYT z_=zONu-fIJq6=?QM*41Obn&8cS;-t@=M-;ZNu*n#e~u~%c!WW z#RQ(?c1=6nUVbyElDOQIq|D6?C~_RklKk^$pS#U#`Hx^*aAc&IOMa)#WU7d((i|BI zH83#dyy;VIw;=v107G<>m{MabfxE8t?tEm*RC0WFw%NQZxb4oi)G$m+$SAdgpk3Je zxI6Jl%rn~b50kTO&Kg#nC9# zb67IK1CPMOlV5aJ3;E5WqhkPCZns%khDa79F?`?oZ?@Ojgyw#S%`+Ly^R~;?P)t0E zEf*1kcr`F2VD-Dc_NbakNlW7zWS&s9ONTNXl$Mn(HM;Ibv%W??*=5(&!=RxgpHNG= zjGWZ%4sIf(K5hT_Q#Xd}L6}Io0zF?kMP_hNV({4q4)lowtN?5r3x?UBz!Gsj5 zD_}eWJf0RU%QN@=G3NDfK^hWh(_G3!Kib%M?UvN(7VCq~w=}z}B=k{fkDnU5^6Kjk zAGTuDB(^bc=r}F1*+5CMT+bvC-OQO6Kgd|EPJ(N}Jj{_031j`8PR!5v?k-kP+rax1;eNA zZYe2wW6UJggv(wf?s>D4c-o)!0eQ?CgIz1A5W#w}vypnFI_(-J-{H zF)=Y7p5b?VS65e5_yObNnZy*H!Z+=aj?(?+Uh-#^rjjb6=ofN>+A1qL4{*vq9w^OD-I;& zbxS^PF&bTz+X$_ak>uarBvaIxcQFA?`37J5Q6(-SMkIZ`4R?1JhpFP8LHVs)T-unj z3JPWVV9y942g5osF#-CDA3lC0dFKC}D^+#Uj@~Mi7#9ae*z3|kOKa?CrE7v>f&Ufg zbDGIz!h7VeZ;~$##NPznd&K?K#Uezo;AqTV_ed@_SnDJy?rp!o&TVPAs~VD+tAHzL zXpCel#pHrF_2`k7wsve>oMqh{91fQg)6FxGUtmTIySs`Q>+4UK8aILP0mJkkaZ<=H zVfomT(^Gw!()jRc$9-e%fO z3NbUh{;>b|m4q^q2bD5){v8sLHN14kCC>7z+M=6qke9LXt)}1x?9rg5 z^0w$92Pm~4q`_+D682oj7I6YhRKl)m;$VUSm5v4Q>1KH+fpisT7JsO8ae2N!99 zmRooXmVW&9T4dzINxuSE+GA^9M>`bGGg%n0oIFC!qNCxb`?k7l^aWR{7?+n3#t09^ zhK7U`=I4K~wIz=l3d!1XX#}fuX!bbQki(t;q`E~TlG8DG@8~p$#oPd7iBD)H@5e!t zg*@jQ@z(a0QA?P27%yW68z&s~>#^khy0IH8UTV)6fWv4}3EIGuHUhqvD}h;>MfLwq zHu|monl32a-s1V~_Va~sgEKFhWZm!h+(r6j$Lx#QIKVjA%;-0zzOzc-G-8xJJl#4M zSJ>&Lgb#EG8@G7;eVWekSZLUEOKkSo`YuQyc^}L*g~-P>h9x5-Bg_gBAi$USa+G0G zmcYU;D0l&W3jzUC&{9aiUy4B4vlJ-4jJ2CC@35|sxH}ztX4@QU>1Y-z6lvKVvXG~i z!2Ir)zEkOLD<6LLI%{wRL) z`}gnMZMT&f8B+0#4k<^SljyvxoQng! z#`B$`o8%4&Ocd&Xg!OY%OG}G51B28{zt2<~(~l@z=pZB(VN~HL^R9sXnX1jz?oe>X;QZc# zQ=Ifr328yj1YrZo=?6;7jPWaRaCAQ7BXB9RG` zXLd?++7yphXb(?&TKxHin3&hq$p)yZlyt4|!0?w{>GH>vQ;;B{mv0VWv*Y+ z9aP&|!8x3juE0k!WO5J$IR7LQv|xuF-qNA4q*X?@Ra|OR((Kf>y5dOeWgu>1fS=Jg z+vsNhJ58KbSeWwp^JL%`yIJQec8RH%+b^7WHWh46Pc<~8wQ}*31i2j#=70V85s~rX z4Epf`wv9re+HN?uFWc_zc+ugps zclu?E3J`}sH7m!)&CSik#3Ulp*uP&d%E-O}H5M%@YB9cF2@Gg%-Z^Y5d(Kf@R^05d ztywg&^WD=IZq|A5@f(uY3@(JY5@`=aI6EYs)y}g(Hn@Uj8pL&DD@DyJ4dY`jw%EH)dJC1{b>8XxbgO>&T<48c2Z=p(ouFJv|T)aQ+3_$jiVa%Cc#WqZGFDIy|bu(y}Eav$qvsf+nf zi@!+IH@?C*m1F^At{2O{eWnsJtc7MaX(c#+{J2eN>ZPHf@n1{~s@?}l`?pP>OS&x*dCX-rHKT=`WQqbmSfzw^bd5Dt zU--|lb1~UJ=jA=l417!~%D&IcMJhwy-O|K%qk!%>b&k;mmfAfq+C%A*_BDoMqoaI$ zd>-WuZW>IOF9Zekbag2xC?e=3B^Vi{Ej^w!?N-X{yzy&&3o&$XvqnR(D1keY1|0Ut zVguzgXA*RU2wJdGQoZ<~Zf2IzZGl5bNI`?gnMDN;$x>IA3uktHS`Y6bG>FGx1k(vT zlS^DfCqshxJ~boD*VO@HNQkE@pSiKXq_jU>0VfRXdSCUsvKds_x3)g;M$OI5O_iB0 zjgB%EL&44jPGMo>nKytD1~CPg@ljDxGK+}hnL>Iuzd8&E#)rJB&qc+Sx?vTQle$F{ zB4+J?EyFlyv69HF0%I8&8Pn7HB}j)TiaWkB@eWQ|KrN%ut$LR65}}YFZkqr>ze9U~ zU=U~QTjkl&a~dvudbd=0ME?r$ptq6>Tl2wKT6sWQ(d-$zSLUV$r>w4cb*_o + + + + + +LuaSocket: MIME module + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

MIME

+ +

+The mime namespace offers filters that apply and remove common +content transfer encodings, such as Base64 and Quoted-Printable. +It also provides functions to break text into lines and change +the end-of-line convention. +MIME is described mainly in +RFC 2045, +2046, +2047, +2048, and +2049. +

+ +

+All functionality provided by the MIME module +follows the ideas presented in + +LTN012, Filters sources and sinks. +

+ +

+To obtain the mime namespace, run: +

+ +
+-- loads the MIME module and everything it requires
+local mime = require("mime")
+
+ + + + +

High-level filters

+ + + +

+mime.normalize([marker]) +

+ +

+Converts most common end-of-line markers to a specific given marker. +

+ +

+Marker is the new marker. It defaults to CRLF, the canonic +end-of-line marker defined by the MIME standard. +

+ +

+The function returns a filter that performs the conversion. +

+ +

+Note: There is no perfect solution to this problem. Different end-of-line +markers are an evil that will probably plague developers forever. +This function, however, will work perfectly for text created with any of +the most common end-of-line markers, i.e. the Mac OS (CR), the Unix (LF), +or the DOS (CRLF) conventions. Even if the data has mixed end-of-line +markers, the function will still work well, although it doesn't +guarantee that the number of empty lines will be correct. +

+ + + +

+mime.decode("base64")
+mime.decode("quoted-printable") +

+ +

+Returns a filter that decodes data from a given transfer content +encoding. +

+ + + +

+mime.encode("base64")
+mime.encode("quoted-printable" [, mode]) +

+ +

+Returns a filter that encodes data according to a given transfer content +encoding. +

+ +

+In the Quoted-Printable case, the user can specify whether the data is +textual or binary, by passing the mode strings "text" or +"binary". Mode defaults to "text". +

+ +

+Although both transfer content encodings specify a limit for the line +length, the encoding filters do not break text into lines (for +added flexibility). +Below is a filter that converts binary data to the Base64 transfer content +encoding and breaks it into lines of the correct size. +

+ +
+base64 = ltn12.filter.chain(
+  mime.encode("base64"),
+  mime.wrap("base64")
+)
+
+ +

+Note: Text data has to be converted to canonic form +before being encoded. +

+ +
+base64 = ltn12.filter.chain(
+  mime.normalize(),
+  mime.encode("base64"),
+  mime.wrap("base64")
+)
+
+ + + +

+mime.stuff()
+

+ +

+Creates and returns a filter that performs stuffing of SMTP messages. +

+ +

+Note: The smtp.send function +uses this filter automatically. You don't need to chain it with your +source, or apply it to your message body. +

+ + + +

+mime.wrap("text" [, length])
+mime.wrap("base64")
+mime.wrap("quoted-printable") +

+ +

+Returns a filter that breaks data into lines. +

+ +

+The "text" line-wrap filter simply breaks text into lines by +inserting CRLF end-of-line markers at appropriate positions. +Length defaults 76. +The "base64" line-wrap filter works just like the default +"text" line-wrap filter with default length. +The function can also wrap "quoted-printable" lines, taking care +not to break lines in the middle of an escaped character. In that case, the +line length is fixed at 76. +

+ +

+For example, to create an encoding filter for the Quoted-Printable transfer content encoding of text data, do the following: +

+ +
+qp = ltn12.filter.chain(
+  mime.normalize(),
+  mime.encode("quoted-printable"),
+  mime.wrap("quoted-printable")
+)
+
+ +

+Note: To break into lines with a different end-of-line convention, apply +a normalization filter after the line break filter. +

+ + + +

Low-level filters

+ + + +

+A, B = mime.b64(C [, D]) +

+ +

+Low-level filter to perform Base64 encoding. +

+ +

+A is the encoded version of the largest prefix of +C..D +that can be encoded unambiguously. B has the remaining bytes of +C..D, before encoding. +If D is nil, A is padded with +the encoding of the remaining bytes of C. +

+ +

+Note: The simplest use of this function is to encode a string into it's +Base64 transfer content encoding. Notice the extra parenthesis around the +call to mime.b64, to discard the second return value. +

+ +
+print((mime.b64("diego:password")))
+--> ZGllZ286cGFzc3dvcmQ=
+
+ + +

+A, n = mime.dot(m [, B]) +

+ +

+Low-level filter to perform SMTP stuffing and enable transmission of +messages containing the sequence "CRLF.CRLF". +

+ +

+A is the stuffed version of B. 'n' gives the +number of characters from the sequence CRLF seen in the end of B. +'m' should tell the same, but for the previous chunk. +

+ +

Note: The message body is defined to begin with +an implicit CRLF. Therefore, to stuff a message correctly, the +first m should have the value 2. +

+ +
+print((string.gsub(mime.dot(2, ".\r\nStuffing the message.\r\n.\r\n."), "\r\n", "\\n")))
+--> ..\nStuffing the message.\n..\n..
+
+ +

+Note: The smtp.send function +uses this filter automatically. You don't need to +apply it again. +

+ + + +

+A, B = mime.eol(C [, D, marker]) +

+ +

+Low-level filter to perform end-of-line marker translation. +For each chunk, the function needs to know if the last character of the +previous chunk could be part of an end-of-line marker or not. This is the +context the function receives besides the chunk. An updated version of +the context is returned after each new chunk. +

+ +

+A is the translated version of D. C is the +ASCII value of the last character of the previous chunk, if it was a +candidate for line break, or 0 otherwise. +B is the same as C, but for the current +chunk. Marker gives the new end-of-line marker and defaults to CRLF. +

+ +
+-- translates the end-of-line marker to UNIX
+unix = mime.eol(0, dos, "\n") 
+
+ + + +

+A, B = mime.qp(C [, D, marker]) +

+ +

+Low-level filter to perform Quoted-Printable encoding. +

+ +

+A is the encoded version of the largest prefix of +C..D +that can be encoded unambiguously. B has the remaining bytes of +C..D, before encoding. +If D is nil, A is padded with +the encoding of the remaining bytes of C. +Throughout encoding, occurrences of CRLF are replaced by the +marker, which itself defaults to CRLF. +

+ +

+Note: The simplest use of this function is to encode a string into it's +Quoted-Printable transfer content encoding. +Notice the extra parenthesis around the call to mime.qp, to discard the second return value. +

+ +
+print((mime.qp("maçã")))
+--> ma=E7=E3=
+
+ + + +

+A, m = mime.qpwrp(n [, B, length]) +

+ +

+Low-level filter to break Quoted-Printable text into lines. +

+ +

+A is a copy of B, broken into lines of at most +length bytes (defaults to 76). +'n' should tell how many bytes are left for the first +line of B and 'm' returns the number of bytes +left in the last line of A. +

+ +

+Note: Besides breaking text into lines, this function makes sure the line +breaks don't fall in the middle of an escaped character combination. Also, +this function only breaks lines that are bigger than length bytes. +

+ + + +

+A, B = mime.unb64(C [, D]) +

+ +

+Low-level filter to perform Base64 decoding. +

+ +

+A is the decoded version of the largest prefix of +C..D +that can be decoded unambiguously. B has the remaining bytes of +C..D, before decoding. +If D is nil, A is the empty string +and B returns whatever couldn't be decoded. +

+ +

+Note: The simplest use of this function is to decode a string from it's +Base64 transfer content encoding. +Notice the extra parenthesis around the call to mime.unqp, to discard the second return value. +

+ +
+print((mime.unb64("ZGllZ286cGFzc3dvcmQ=")))
+--> diego:password
+
+ + + +

+A, B = mime.unqp(C [, D]) +

+ +

+Low-level filter to remove the Quoted-Printable transfer content encoding +from data. +

+ +

+A is the decoded version of the largest prefix of +C..D +that can be decoded unambiguously. B has the remaining bytes of +C..D, before decoding. +If D is nil, A is augmented with +the encoding of the remaining bytes of C. +

+ +

+Note: The simplest use of this function is to decode a string from it's +Quoted-Printable transfer content encoding. +Notice the extra parenthesis around the call to mime.unqp, to discard the second return value. +

+ +
+print((mime.qp("ma=E7=E3=")))
+--> maçã
+
+ + + +

+A, m = mime.wrp(n [, B, length]) +

+ +

+Low-level filter to break text into lines with CRLF marker. +Text is assumed to be in the normalize form. +

+ +

+A is a copy of B, broken into lines of at most +length bytes (defaults to 76). +'n' should tell how many bytes are left for the first +line of B and 'm' returns the number of bytes +left in the last line of A. +

+ +

+Note: This function only breaks lines that are bigger than +length bytes. The resulting line length does not include the CRLF +marker. +

+ + + + + + + + diff --git a/doc/luasocket/reference.css b/doc/luasocket/reference.css new file mode 100644 index 0000000..b1dd25d --- /dev/null +++ b/doc/luasocket/reference.css @@ -0,0 +1,54 @@ +body { + margin-left: 1em; + margin-right: 1em; + font-family: "Verdana", sans-serif; +} + +tt { + font-family: "Andale Mono", monospace; +} + +h1, h2, h3, h4 { margin-left: 0em; } + + +h3 { padding-top: 1em; } + +p { margin-left: 1em; } + +p.name { + font-family: "Andale Mono", monospace; + padding-top: 1em; + margin-left: 0em; +} + +a[href] { color: #00007f; } + +blockquote { margin-left: 3em; } + +pre.example { + background: #ccc; + padding: 1em; + margin-left: 1em; + font-family: "Andale Mono", monospace; + font-size: small; +} + +hr { + margin-left: 0em; + background: #00007f; + border: 0px; + height: 1px; +} + +ul { list-style-type: disc; } + +table.index { border: 1px #00007f; } +table.index td { text-align: left; vertical-align: top; } +table.index ul { padding-top: 0em; margin-top: 0em; } + +h1:first-letter, +h2:first-letter, +h2:first-letter, +h3:first-letter { color: #00007f; } + +div.header, div.footer { margin-left: 0em; } diff --git a/doc/luasocket/reference.html b/doc/luasocket/reference.html new file mode 100644 index 0000000..ed1702d --- /dev/null +++ b/doc/luasocket/reference.html @@ -0,0 +1,239 @@ + + + + + + +LuaSocket: Index to reference manual + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

Reference

+ +
+DNS (in socket) +
+toip, +tohostname, +gethostname. +
+
+ + + +
+FTP +
+get, +put. +
+
+ + + +
+HTTP +
+request. +
+
+ + + +
+LTN12 +
+filter: +chain, +cycle. +
+
+pump: +all, +step. +
+
+sink: +chain, +error, +file, +null, +simplify, +table. +
+
+source: +cat, +chain, +empty, +error, +file, +simplify, +string. +
+
+ + + +
+MIME +
+high-level: +normalize, +decode, +encode, +stuff, +wrap. +
+
+low-level: +b64, +dot, +eol, +qp, +wrp, +qpwrp. +unb64, +unqp, +
+
+ + + +
+SMTP +
+message, +send. +
+
+ + + +
+Socket +
+_DEBUG, +dns, +gettime, +newtry, +protect, +select, +sink, +skip, +sleep, +source, +tcp, +try, +udp, +_VERSION. +
+
+ + + +
+TCP (in socket) +
+accept, +bind, +close, +connect, +getpeername, +getsockname, +getstats, +receive, +send, +setoption, +setstats, +settimeout, +shutdown. +
+
+ + + +
+UDP (in socket) +
+close, +getpeername, +getsockname, +receive, +receivefrom, +send, +sendto, +setpeername, +setsockname, +setoption, +settimeout. +
+
+ + + +
+URL +
+absolute, +build, +build_path, +escape, +parse, +parse_path, +unescape. +
+
+ + + + + + + diff --git a/doc/luasocket/smtp.html b/doc/luasocket/smtp.html new file mode 100644 index 0000000..833aa83 --- /dev/null +++ b/doc/luasocket/smtp.html @@ -0,0 +1,417 @@ + + + + + + +LuaSocket: SMTP support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

SMTP

+ +

The smtp namespace provides functionality to send e-mail +messages. The high-level API consists of two functions: one to +define an e-mail message, and another to actually send the message. +Although almost all users will find that these functions provide more than +enough functionality, the underlying implementation allows for even more +control (if you bother to read the code). +

+ +

The implementation conforms to the Simple Mail Transfer Protocol, +RFC 2821. +Another RFC of interest is RFC 2822, +which governs the Internet Message Format. +Multipart messages (those that contain attachments) are part +of the MIME standard, but described mainly +in RFC +2046 + +

In the description below, good understanding of LTN012, Filters +sources and sinks and the MIME module is +assumed. In fact, the SMTP module was the main reason for their +creation.

+ +

+To obtain the smtp namespace, run: +

+ +
+-- loads the SMTP module and everything it requires
+local smtp = require("socket.smtp")
+
+ +

+MIME headers are represented as a Lua table in the form: +

+ +
+ + +
+headers = {
+  field-1-name = field-1-value,
+  field-2-name = field-2-value,
+  field-3-name = field-3-value,
+  ...
+  field-n-name = field-n-value
+} +
+
+ +

+Field names are case insensitive (as specified by the standard) and all +functions work with lowercase field names. +Field values are left unmodified. +

+ +

+Note: MIME headers are independent of order. Therefore, there is no problem +in representing them in a Lua table. +

+ +

+The following constants can be set to control the default behavior of +the SMTP module: +

+ +
    +
  • DOMAIN: domain used to greet the server; +
  • PORT: default port used for the connection; +
  • SERVER: default server used for the connection; +
  • TIMEOUT: default timeout for all I/O operations; +
  • ZONE: default time zone. +
+ + + +

+smtp.send{
+  from = string,
+  rcpt = string or string-table,
+  source = LTN12 source,
+  [user = string,]
+  [password = string,]
+  [server = string,]
+  [port = number,]
+  [domain = string,]
+  [step = LTN12 pump step,]
+  [create = function]
+} +

+ +

+Sends a message to a recipient list. Since sending messages is not as +simple as downloading an URL from a FTP or HTTP server, this function +doesn't have a simple interface. However, see the +message source factory for +a very powerful way to define the message contents. +

+ + +

+The sender is given by the e-mail address in the from field. +Rcpt is a Lua table with one entry for each recipient e-mail +address, or a string +in case there is just one recipient. +The contents of the message are given by a simple +LTN12 +source. Several arguments are optional: +

+
    +
  • user, password: User and password for +authentication. The function will attempt LOGIN and PLAIN authentication +methods if supported by the server (both are unsafe); +
  • server: Server to connect to. Defaults to "localhost"; +
  • port: Port to connect to. Defaults to 25; +
  • domain: Domain name used to greet the server; Defaults to the +local machine host name; +
  • step: +LTN12 +pump step function used to pass data from the +source to the server. Defaults to the LTN12 pump.step function; +
  • create: An optional function to be used instead of +socket.tcp when the communications socket is created. +
+ +

+If successful, the function returns 1. Otherwise, the function returns +nil followed by an error message. +

+ +

+Note: SMTP servers can be very picky with the format of e-mail +addresses. To be safe, use only addresses of the form +"<fulano@example.com>" in the from and +rcpt arguments to the send function. In headers, e-mail +addresses can take whatever form you like.

+ +

+Big note: There is a good deal of misconception with the use of the +destination address field headers, i.e., the 'To', 'Cc', +and, more importantly, the 'Bcc' headers. Do not add a +'Bcc' header to your messages because it will probably do the +exact opposite of what you expect. +

+ +

+Only recipients specified in the rcpt list will receive a copy of the +message. Each recipient of an SMTP mail message receives a copy of the +message body along with the headers, and nothing more. The headers +are part of the message and should be produced by the +LTN12 +source function. The rcpt list is not +part of the message and will not be sent to anyone. +

+ +

+RFC 2822 +has two important and short sections, "3.6.3. Destination address +fields" and "5. Security considerations", explaining the proper +use of these headers. Here is a summary of what it says: +

+ +
    +
  • To: contains the address(es) of the primary recipient(s) +of the message; +
  • Cc: (where the "Cc" means "Carbon Copy" in the sense of +making a copy on a typewriter using carbon paper) contains the +addresses of others who are to receive the message, though the +content of the message may not be directed at them; +
  • Bcc: (where the "Bcc" means "Blind Carbon +Copy") contains addresses of recipients of the message whose addresses are not to be revealed to other recipients of the message. +
+ +

+The LuaSocket send function does not care or interpret the +headers you send, but it gives you full control over what is sent and +to whom it is sent: +

+
    +
  • If someone is to receive the message, the e-mail address has +to be in the recipient list. This is the only parameter that controls who +gets a copy of the message; +
  • If there are multiple recipients, none of them will automatically +know that someone else got that message. That is, the default behavior is +similar to the Bcc field of popular e-mail clients; +
  • It is up to you to add the To header with the list of primary +recipients so that other recipients can see it; +
  • It is also up to you to add the Cc header with the +list of additional recipients so that everyone else sees it; +
  • Adding a header Bcc is nonsense, unless it is +empty. Otherwise, everyone receiving the message will see it and that is +exactly what you don't want to happen! +
+ +

+I hope this clarifies the issue. Otherwise, please refer to +RFC 2821 +and +RFC 2822. +

+ +
+-- load the smtp support
+local smtp = require("socket.smtp")
+
+-- Connects to server "localhost" and sends a message to users
+-- "fulano@example.com",  "beltrano@example.com", 
+-- and "sicrano@example.com".
+-- Note that "fulano" is the primary recipient, "beltrano" receives a
+-- carbon copy and neither of them knows that "sicrano" received a blind
+-- carbon copy of the message.
+from = "<luasocket@example.com>"
+
+rcpt = {
+  "<fulano@example.com>",
+  "<beltrano@example.com>",
+  "<sicrano@example.com>"
+}
+
+mesgt = {
+  headers = {
+    to = "Fulano da Silva <fulano@example.com>",
+    cc = '"Beltrano F. Nunes" <beltrano@example.com>',
+    subject = "My first message"
+  },
+  body = "I hope this works. If it does, I can send you another 1000 copies."
+}
+
+r, e = smtp.send{
+  from = from,
+  rcpt = rcpt, 
+  source = smtp.message(mesgt)
+}
+
+ + + +

+smtp.message(mesgt) +

+ +

+Returns a simple +LTN12 source that sends an SMTP message body, possibly multipart (arbitrarily deep). +

+ +

+The only parameter of the function is a table describing the message. +Mesgt has the following form (notice the recursive structure): +

+ +
+ + +
+mesgt = {
+  headers = header-table,
+  body = LTN12 source or string or +multipart-mesgt
+}

+multipart-mesgt = {
+  [preamble = string,]
+  [1] = mesgt,
+  [2] = mesgt,
+  ...
+  [n] = mesgt,
+  [epilogue = string,]
+}
+
+
+ +

+For a simple message, all that is needed is a set of headers +and the body. The message body can be given as a string +or as a simple +LTN12 +source. For multipart messages, the body is a table that +recursively defines each part as an independent message, plus an optional +preamble and epilogue. +

+ +

+The function returns a simple +LTN12 +source that produces the +message contents as defined by mesgt, chunk by chunk. +Hopefully, the following +example will make things clear. When in doubt, refer to the appropriate RFC +as listed in the introduction.

+ +
+-- load the smtp support and its friends
+local smtp = require("socket.smtp")
+local mime = require("mime")
+local ltn12 = require("ltn12")
+
+-- creates a source to send a message with two parts. The first part is 
+-- plain text, the second part is a PNG image, encoded as base64.
+source = smtp.message{
+  headers = {
+     -- Remember that headers are *ignored* by smtp.send. 
+     from = "Sicrano de Oliveira <sicrano@example.com>",
+     to = "Fulano da Silva <fulano@example.com>",
+     subject = "Here is a message with attachments"
+  },
+  body = {
+    preamble = "If your client doesn't understand attachments, \r\n" ..
+               "it will still display the preamble and the epilogue.\r\n" ..
+               "Preamble will probably appear even in a MIME enabled client.",
+    -- first part: no headers means plain text, us-ascii.
+    -- The mime.eol low-level filter normalizes end-of-line markers.
+    [1] = { 
+      body = mime.eol(0, [[
+        Lines in a message body should always end with CRLF. 
+        The smtp module will *NOT* perform translation. However, the 
+        send function *DOES* perform SMTP stuffing, whereas the message
+        function does *NOT*.
+      ]])
+    },
+    -- second part: headers describe content to be a png image, 
+    -- sent under the base64 transfer content encoding.
+    -- notice that nothing happens until the message is actually sent. 
+    -- small chunks are loaded into memory right before transmission and 
+    -- translation happens on the fly.
+    [2] = { 
+      headers = {
+        ["content-type"] = 'image/png; name="image.png"',
+        ["content-disposition"] = 'attachment; filename="image.png"',
+        ["content-description"] = 'a beautiful image',
+        ["content-transfer-encoding"] = "BASE64"
+      },
+      body = ltn12.source.chain(
+        ltn12.source.file(io.open("image.png", "rb")),
+        ltn12.filter.chain(
+          mime.encode("base64"),
+          mime.wrap()
+        )
+      )
+    },
+    epilogue = "This might also show up, but after the attachments"
+  }
+}
+
+-- finally send it
+r, e = smtp.send{
+    from = "<sicrano@example.com>",
+    rcpt = "<fulano@example.com>",
+    source = source,
+}
+
+ + + + + + + diff --git a/doc/luasocket/socket.html b/doc/luasocket/socket.html new file mode 100644 index 0000000..d050a42 --- /dev/null +++ b/doc/luasocket/socket.html @@ -0,0 +1,398 @@ + + + + + + +LuaSocket: The socket namespace + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

The socket namespace

+ +

+The socket namespace contains the core functionality of LuaSocket. +

+ +

+To obtain the socket namespace, run: +

+ +
+-- loads the socket module 
+local socket = require("socket")
+
+ + + +

+socket.bind(address, port [, backlog]) +

+ +

+This function is a shortcut that creates and returns a TCP server object +bound to a local address and port, ready to +accept client connections. Optionally, +user can also specify the backlog argument to the +listen method (defaults to 32). +

+ +

+Note: The server object returned will have the option "reuseaddr" +set to true. +

+ + + +

+socket.connect(address, port [, locaddr, locport]) +

+ +

+This function is a shortcut that creates and returns a TCP client object +connected to a remote host at a given port. Optionally, +the user can also specify the local address and port to bind +(locaddr and locport). +

+ + + +

+socket._DEBUG +

+ +

+This constant is set to true if the library was compiled +with debug support. +

+ + + +

+socket.newtry(finalizer) +

+ +

+Creates and returns a clean +try +function that allows for cleanup before the exception +is raised. +

+ +

+Finalizer is a function that will be called before +try throws the exception. It will be called +in protected mode. +

+ +

+The function returns your customized try function. +

+ +

+Note: This idea saved a lot of work with the +implementation of protocols in LuaSocket: +

+ +
+foo = socket.protect(function()
+    -- connect somewhere
+    local c = socket.try(socket.connect("somewhere", 42))
+    -- create a try function that closes 'c' on error
+    local try = socket.newtry(function() c:close() end)
+    -- do everything reassured c will be closed 
+    try(c:send("hello there?\r\n"))
+    local answer = try(c:receive())
+    ...
+    try(c:send("good bye\r\n"))
+    c:close()
+end)
+
+ + + + +

+socket.protect(func) +

+ +

+Converts a function that throws exceptions into a safe function. This +function only catches exceptions thrown by the try +and newtry functions. It does not catch normal +Lua errors. +

+ +

+Func is a function that calls +try (or assert, or error) +to throw exceptions. +

+ +

+Returns an equivalent function that instead of throwing exceptions, +returns nil followed by an error message. +

+ +

+Note: Beware that if your function performs some illegal operation that +raises an error, the protected function will catch the error and return it +as a string. This is because the try function +uses errors as the mechanism to throw exceptions. +

+ + + +

+socket.select(recvt, sendt [, timeout]) +

+ +

+Waits for a number of sockets to change status. +

+ +

+Recvt is an array with the sockets to test for characters +available for reading. Sockets in the sendt array are watched to +see if it is OK to immediately write on them. Timeout is the +maximum amount of time (in seconds) to wait for a change in status. A +nil, negative or omitted timeout value allows the +function to block indefinitely. Recvt and sendt can also +be empty tables or nil. Non-socket values (or values with +non-numeric indices) in the arrays will be silently ignored. +

+ +

The function returns a table with the sockets ready for +reading, a table with the sockets ready for writing and an error message. +The error message is "timeout" if a timeout condition was met and +nil otherwise. The returned tables are associative, to +simplify the test if a specific socket has changed status. +

+ +

+Important note: a known bug in WinSock causes select to fail +on non-blocking TCP sockets. The function may return a socket as +writable even though the socket is not ready for sending. +

+ +

+Another important note: calling select with a server socket in the receive parameter before a call to accept does not guarantee +accept will return immediately. +Use the settimeout +method or accept might block forever. +

+ + + +

+socket.sink(mode, socket) +

+ +

+Creates an +LTN12 +sink from a stream socket object. +

+ +

+Mode defines the behavior of the sink. The following +options are available: +

+
    +
  • "http-chunked": sends data through socket after applying the +chunked transfer coding, closing the socket when done; +
  • "close-when-done": sends all received data through the +socket, closing the socket when done; +
  • "keep-open": sends all received data through the +socket, leaving it open when done. +
+

+Socket is the stream socket object used to send the data. +

+ +

+The function returns a sink with the appropriate behavior. +

+ + + +

+socket.skip(d [, ret1, ret2 ... retN]) +

+ +

+Drops a number of arguments and returns the remaining. +

+ +

+D is the number of arguments to drop. Ret1 to +retN are the arguments. +

+ +

+The function returns retd+1 to retN. +

+ +

+Note: This function is useful to avoid creation of dummy variables: +

+ +
+-- get the status code and separator from SMTP server reply 
+local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
+
+ + + +

+socket.sleep(time) +

+ +

+Freezes the program execution during a given amount of time. +

+ +

+Time is the number of seconds to sleep for. +The function truncates time down to the nearest integer. +

+ + + +

+socket.source(mode, socket [, length]) +

+ +

+Creates an +LTN12 +source from a stream socket object. +

+ +

+Mode defines the behavior of the source. The following +options are available: +

+
    +
  • "http-chunked": receives data from socket and removes the +chunked transfer coding before returning the data; +
  • "by-length": receives a fixed number of bytes from the +socket. This mode requires the extra argument length; +
  • "until-closed": receives data from a socket until the other +side closes the connection. +
+

+Socket is the stream socket object used to receive the data. +

+ +

+The function returns a source with the appropriate behavior. +

+ + + +

+socket.gettime() +

+ +

+Returns the time in seconds, relative to the origin of the +universe. You should subtract the values returned by this function +to get meaningful values. +

+ +
+t = socket.gettime()
+-- do stuff
+print(socket.gettime() - t .. " seconds elapsed")
+
+ + + +

+socket.try(ret1 [, ret2 ... retN]) +

+ +

+Throws an exception in case of error. The exception can only be caught +by the protect function. It does not explode +into an error message. +

+ +

+Ret1 to retN can be arbitrary +arguments, but are usually the return values of a function call +nested with try. +

+ +

+The function returns ret1 to retN if +ret1 is not nil. Otherwise, it calls error passing ret2. +

+ +
+-- connects or throws an exception with the appropriate error message
+c = socket.try(socket.connect("localhost", 80))
+
+ + + +

+socket._VERSION +

+ +

+This constant has a string describing the current LuaSocket version. +

+ + + + + + + diff --git a/doc/luasocket/tcp.html b/doc/luasocket/tcp.html new file mode 100644 index 0000000..39fa6b7 --- /dev/null +++ b/doc/luasocket/tcp.html @@ -0,0 +1,532 @@ + + + + + + +LuaSocket: TCP/IP support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

TCP

+ + + +

+socket.tcp() +

+ +

+Creates and returns a TCP master object. A master object can +be transformed into a server object with the method +listen (after a call to bind) or into a client object with +the method connect. The only other +method supported by a master object is the +close method.

+ +

+In case of success, a new master object is returned. In case of error, +nil is returned, followed by an error message. +

+ + + +

+server:accept() +

+ +

+Waits for a remote connection on the server +object and returns a client object representing that connection. +

+ +

+If a connection is successfully initiated, a client object is returned. +If a timeout condition is met, the method returns nil +followed by the error string 'timeout'. Other errors are +reported by nil followed by a message describing the error. +

+ +

+Note: calling socket.select +with a server object in +the recvt parameter before a call to accept does +not guarantee accept will return immediately. Use the settimeout method or accept +might block until another client shows up. +

+ + + +

+master:bind(address, port) +

+ +

+Binds a master object to address and port on the +local host. + +

+Address can be an IP address or a host name. +Port must be an integer number in the range [0..64K). +If address +is '*', the system binds to all local interfaces +using the INADDR_ANY constant. If port is 0, the system automatically +chooses an ephemeral port. +

+ +

+In case of success, the method returns 1. In case of error, the +method returns nil followed by an error message. +

+ +

+Note: The function socket.bind +is available and is a shortcut for the creation of server sockets. +

+ + + +

+master:close()
+client:close()
+server:close() +

+ +

+Closes a TCP object. The internal socket used by the object is closed +and the local address to which the object was +bound is made available to other applications. No further operations +(except for further calls to the close method) are allowed on +a closed socket. +

+ +

+Note: It is important to close all used sockets once they are not +needed, since, in many systems, each socket uses a file descriptor, +which are limited system resources. Garbage-collected objects are +automatically closed before destruction, though. +

+ + + +

+master:connect(address, port) +

+ +

+Attempts to connect a master object to a remote host, transforming it into a +client object. +Client objects support methods +send, +receive, +getsockname, +getpeername, +settimeout, +and close. +

+ +

+Address can be an IP address or a host name. +Port must be an integer number in the range [1..64K). +

+ +

+In case of error, the method returns nil followed by a string +describing the error. In case of success, the method returns 1. +

+ +

+Note: The function socket.connect +is available and is a shortcut for the creation of client sockets. +

+ +

+Note: Starting with LuaSocket 2.0, +the settimeout +method affects the behavior of connect, causing it to return +with an error in case of a timeout. If that happens, you can still call socket.select with the socket in the +sendt table. The socket will be writable when the connection is +established. +

+ + + +

+client:getpeername() +

+ +

+Returns information about the remote side of a connected client object. +

+ +

+Returns a string with the IP address of the peer, followed by the +port number that peer is using for the connection. +In case of error, the method returns nil. +

+ +

+Note: It makes no sense to call this method on server objects. +

+ + + +

+master:getsockname()
+client:getsockname()
+server:getsockname() +

+ +

+Returns the local address information associated to the object. +

+ +

+The method returns a string with local IP address and a number with +the port. In case of error, the method returns nil. +

+ + + +

+master:getstats()
+client:getstats()
+server:getstats()
+

+ +

+Returns accounting information on the socket, useful for throttling +of bandwidth. +

+ +

+The method returns the number of bytes received, the number of bytes sent, +and the age of the socket object in seconds. +

+ + + +

+master:listen(backlog) +

+ +

+Specifies the socket is willing to receive connections, transforming the +object into a server object. Server objects support the +accept, +getsockname, +setoption, +settimeout, +and close methods. +

+ +

+The parameter backlog specifies the number of client +connections that can +be queued waiting for service. If the queue is full and another client +attempts connection, the connection is refused. +

+ +

+In case of success, the method returns 1. In case of error, the +method returns nil followed by an error message. +

+ + + +

+client:receive([pattern [, prefix]]) +

+ +

+Reads data from a client object, according to the specified read +pattern. Patterns follow the Lua file I/O format, and the difference in performance between all patterns is negligible. +

+ +

+Pattern can be any of the following: +

+ +
    +
  • '*a': reads from the socket until the connection is +closed. No end-of-line translation is performed; +
  • '*l': reads a line of text from the socket. The line is +terminated by a LF character (ASCII 10), optionally preceded by a +CR character (ASCII 13). The CR and LF characters are not included in +the returned line. This is the default pattern; +
  • number: causes the method to read a specified number +of bytes from the socket. +
+ +

+Prefix is an optional string to be concatenated to the beginning +of any received data before return. +

+ +

+If successful, the method returns the received pattern. In case of error, +the method returns nil followed by an error message which +can be the string 'closed' in case the connection was +closed before the transmission was completed or the string +'timeout' in case there was a timeout during the operation. +Also, after the error message, the function returns the partial result of +the transmission. +

+ +

+Important note: This function was changed severely. It used +to support multiple patterns (but I have never seen this feature used) and +now it doesn't anymore. Partial results used to be returned in the same +way as successful results. This last feature violated the idea that all +functions should return nil on error. Thus it was changed +too. +

+ + + +

+client:send(data [, i [, j]]) +

+ +

+Sends data through client object. +

+ +

+Data is the string to be sent. The optional arguments +i and j work exactly like the standard +string.sub Lua function to allow the selection of a +substring to be sent. +

+ +

+If successful, the method returns the index of the last byte +within [i, j] that has been sent. Notice that, if +i is 1 or absent, this is effectively the total +number of bytes sent. In case of error, the method returns +nil, followed by an error message, followed +by the index of the last byte within [i, j] that +has been sent. You might want to try again from the byte +following that. The error message can be 'closed' +in case the connection was closed before the transmission +was completed or the string 'timeout' in case +there was a timeout during the operation. +

+ +

+Note: Output is not buffered. For small strings, +it is always better to concatenate them in Lua +(with the '..' operator) and send the result in one call +instead of calling the method several times. +

+ + + +

+client:setoption(option [, value])
+server:setoption(option [, value]) +

+ +

+Sets options for the TCP object. Options are only needed by low-level or +time-critical applications. You should only modify an option if you +are sure you need it. +

+ +

+Option is a string with the option name, and value +depends on the option being set: + +

    + +
  • 'keepalive': Setting this option to true enables +the periodic transmission of messages on a connected socket. Should the +connected party fail to respond to these messages, the connection is +considered broken and processes using the socket are notified; + +
  • 'linger': Controls the action taken when unsent data are +queued on a socket and a close is performed. The value is a table with a +boolean entry 'on' and a numeric entry for the time interval +'timeout' in seconds. If the 'on' field is set to +true, the system will block the process on the close attempt until +it is able to transmit the data or until 'timeout' has passed. If +'on' is false and a close is issued, the system will +process the close in a manner that allows the process to continue as +quickly as possible. I do not advise you to set this to anything other than +zero; + +
  • 'reuseaddr': Setting this option indicates that the rules +used in validating addresses supplied in a call to +bind should allow reuse of local addresses; + +
  • 'tcp-nodelay': Setting this option to true +disables the Nagle's algorithm for the connection. + +
+ +

+The method returns 1 in case of success, or nil otherwise. +

+ +

+Note: The descriptions above come from the man pages. +

+ + + +

+master:setstats(received, sent, age)
+client:setstats(received, sent, age)
+server:setstats(received, sent, age)
+

+ +

+Resets accounting information on the socket, useful for throttling +of bandwidth. +

+ +

+Received is a number with the new number of bytes received. +Sent is a number with the new number of bytes sent. +Age is the new age in seconds. +

+ +

+The method returns 1 in case of success and nil otherwise. +

+ + + +

+master:settimeout(value [, mode])
+client:settimeout(value [, mode])
+server:settimeout(value [, mode]) +

+ +

+Changes the timeout values for the object. By default, +all I/O operations are blocking. That is, any call to the methods +send, +receive, and +accept +will block indefinitely, until the operation completes. The +settimeout method defines a limit on the amount of time the +I/O methods can block. When a timeout is set and the specified amount of +time has elapsed, the affected methods give up and fail with an error code. +

+ +

+The amount of time to wait is specified as the +value parameter, in seconds. There are two timeout modes and +both can be used together for fine tuning: +

+ +
    +
  • 'b': block timeout. Specifies the upper limit on +the amount of time LuaSocket can be blocked by the operating system +while waiting for completion of any single I/O operation. This is the +default mode;
  • + +
  • 't': total timeout. Specifies the upper limit on +the amount of time LuaSocket can block a Lua script before returning from +a call.
  • +
+ +

+The nil timeout value allows operations to block +indefinitely. Negative timeout values have the same effect. +

+ +

+Note: although timeout values have millisecond precision in LuaSocket, +large blocks can cause I/O functions not to respect timeout values due +to the time the library takes to transfer blocks to and from the OS +and to and from the Lua interpreter. Also, function that accept host names +and perform automatic name resolution might be blocked by the resolver for +longer than the specified timeout value. +

+ +

+Note: The old timeout method is deprecated. The name has been +changed for sake of uniformity, since all other method names already +contained verbs making their imperative nature obvious. +

+ + + +

+client:shutdown(mode)
+

+ +

+Shuts down part of a full-duplex connection. +

+ +

+Mode tells which way of the connection should be shut down and can +take the value: +

    +
  • "both": disallow further sends and receives on the object. +This is the default mode; +
  • "send": disallow further sends on the object; +
  • "receive": disallow further receives on the object. +
+ +

+This function returns 1. +

+ + + + + + + diff --git a/doc/luasocket/udp.html b/doc/luasocket/udp.html new file mode 100644 index 0000000..60c5ba3 --- /dev/null +++ b/doc/luasocket/udp.html @@ -0,0 +1,416 @@ + + + + + + +LuaSocket: UDP support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + + +

UDP

+ + + +

+socket.udp() +

+ +

+Creates and returns an unconnected UDP object. Unconnected objects support the +sendto, +receive, +receivefrom, +getsockname, +setoption, +settimeout, +setpeername, +setsockname, and +close. +The setpeername +is used to connect the object. +

+ +

+In case of success, a new unconnected UDP object +returned. In case of error, nil is returned, followed by +an error message. +

+ + + +

+connected:close()
+unconnected:close() +

+ +

+Closes a UDP object. The internal socket +used by the object is closed and the local address to which the +object was bound is made available to other applications. No +further operations (except for further calls to the close +method) are allowed on a closed socket. +

+ +

+Note: It is important to close all used sockets +once they are not needed, since, in many systems, each socket uses +a file descriptor, which are limited system resources. +Garbage-collected objects are automatically closed before +destruction, though. +

+ + + +

+connected:getpeername() +

+ +

+Retrieves information about the peer +associated with a connected UDP object. +

+ +

+Returns the IP address and port number of the peer. +

+ +

+Note: It makes no sense to call this method on unconnected objects. +

+ + + +

+connected:getsockname()
+unconnected:getsockname() +

+ +

+Returns the local address information associated to the object. +

+ +

+The method returns a string with local IP +address and a number with the port. In case of error, the method +returns nil. +

+ +

+Note: UDP sockets are not bound to any address +until the setsockname or the +sendto method is called for the +first time (in which case it is bound to an ephemeral port and the +wild-card address). +

+ + + +

+connected:receive([size])
+unconnected:receive([size]) +

+ +

+Receives a datagram from the UDP object. If +the UDP object is connected, only datagrams coming from the peer +are accepted. Otherwise, the returned datagram can come from any +host. +

+ +

+The optional size parameter +specifies the maximum size of the datagram to be retrieved. If +there are more than size bytes available in the datagram, +the excess bytes are discarded. If there are less then +size bytes available in the current datagram, the +available bytes are returned. If size is omitted, the +maximum datagram size is used (which is currently limited by the +implementation to 8192 bytes). +

+ +

+In case of success, the method returns the +received datagram. In case of timeout, the method returns +nil followed by the string 'timeout'. +

+ + + +

+unconnected:receivefrom([size]) +

+ +

+Works exactly as the receive +method, except it returns the IP +address and port as extra return values (and is therefore slightly less +efficient). +

+ + + +

+connected:send(datagram) +

+ +

+Sends a datagram to the UDP peer of a connected object. +

+ +

+Datagram is a string with the datagram contents. +The maximum datagram size for UDP is 64K minus IP layer overhead. +However datagrams larger than the link layer packet size will be +fragmented, which may deteriorate performance and/or reliability. +

+ +

+If successful, the method returns 1. In case of +error, the method returns nil followed by an error message. +

+ +

+Note: In UDP, the send method never blocks +and the only way it can fail is if the underlying transport layer +refuses to send a message to the specified address (i.e. no +interface accepts the address). +

+ + + +

+unconnected:sendto(datagram, ip, port) +

+ +

+Sends a datagram to the specified IP address and port number. +

+ +

+Datagram is a string with the +datagram contents. +The maximum datagram size for UDP is 64K minus IP layer overhead. +However datagrams larger than the link layer packet size will be +fragmented, which may deteriorate performance and/or reliability. +Ip is the IP address of the recipient. +Host names are not allowed for performance reasons. + +Port is the port number at the recipient. +

+ +

+If successful, the method returns 1. In case of +error, the method returns nil followed by an error message. +

+ +

+Note: In UDP, the send method never blocks +and the only way it can fail is if the underlying transport layer +refuses to send a message to the specified address (i.e. no +interface accepts the address). +

+ + + +

+connected:setpeername('*')
+unconnected:setpeername(address, port) +

+ +

+Changes the peer of a UDP object. This +method turns an unconnected UDP object into a connected UDP +object or vice versa. +

+ +

+For connected objects, outgoing datagrams +will be sent to the specified peer, and datagrams received from +other peers will be discarded by the OS. Connected UDP objects must +use the send and +receive methods instead of +sendto and +receivefrom. +

+ +

+Address can be an IP address or a +host name. Port is the port number. If address is +'*' and the object is connected, the peer association is +removed and the object becomes an unconnected object again. In that +case, the port argument is ignored. +

+ +

+In case of error the method returns +nil followed by an error message. In case of success, the +method returns 1. +

+ +

+Note: Since the address of the peer does not have +to be passed to and from the OS, the use of connected UDP objects +is recommended when the same peer is used for several transmissions +and can result in up to 30% performance gains. +

+ + + +

+unconnected:setsockname(address, port) +

+ +

+Binds the UDP object to a local address. +

+ +

+Address can be an IP address or a +host name. If address is '*' the system binds to +all local interfaces using the constant INADDR_ANY. If +port is 0, the system chooses an ephemeral port. +

+ +

+If successful, the method returns 1. In case of +error, the method returns nil followed by an error +message. +

+ +

+Note: This method can only be called before any +datagram is sent through the UDP object, and only once. Otherwise, +the system automatically binds the object to all local interfaces +and chooses an ephemeral port as soon as the first datagram is +sent. After the local address is set, either automatically by the +system or explicitly by setsockname, it cannot be +changed. +

+ + + +

+connected:setoption(option [, value])
+unconnected:setoption(option [, value]) +

+ +

+Sets options for the UDP object. Options are +only needed by low-level or time-critical applications. You should +only modify an option if you are sure you need it.

+

Option is a string with the option +name, and value depends on the option being set: +

+ +
    +
  • 'dontroute': Setting this option to true +indicates that outgoing messages should bypass the standard routing +facilities;
  • +
  • 'broadcast': Setting this option to true +requests permission to send broadcast datagrams on the +socket.
  • +
+ +

+The method returns 1 in case of success, or +nil followed by an error message otherwise. +

+ +

+Note: The descriptions above come from the man +pages. +

+ + + +

+connected:settimeout(value)
+unconnected:settimeout(value) +

+ +

+Changes the timeout values for the object. By default, the +receive and +receivefrom +operations are blocking. That is, any call to the methods will block +indefinitely, until data arrives. The settimeout function defines +a limit on the amount of time the functions can block. When a timeout is +set and the specified amount of time has elapsed, the affected methods +give up and fail with an error code. +

+ +

+The amount of time to wait is specified as +the value parameter, in seconds. The nil timeout +value allows operations to block indefinitely. Negative +timeout values have the same effect. +

+ +

+Note: In UDP, the send +and sendto methods never block (the +datagram is just passed to the OS and the call returns +immediately). Therefore, the settimeout method has no +effect on them. +

+ +

+Note: The old timeout method is +deprecated. The name has been changed for sake of uniformity, since +all other method names already contained verbs making their +imperative nature obvious. +

+ + + + + + + diff --git a/doc/luasocket/url.html b/doc/luasocket/url.html new file mode 100644 index 0000000..5785224 --- /dev/null +++ b/doc/luasocket/url.html @@ -0,0 +1,329 @@ + + + + + + +LuaSocket: URL support + + + + + + + +
+
+
+ + + +
+LuaSocket +
Network support for the Lua language +
+

+home · +download · +installation · +introduction · +reference +

+
+
+
+ + + +

URL

+ +

+The url namespace provides functions to parse, protect, +and build URLs, as well as functions to compose absolute URLs +from base and relative URLs, according to +RFC +2396. +

+ +

+To obtain the url namespace, run: +

+ +
+-- loads the URL module 
+local url = require("socket.url")
+
+ +

+An URL is defined by the following grammar: +

+ +
+ +<url> ::= [<scheme>:][//<authority>][/<path>][;<params>][?<query>][#<fragment>]
+<authority> ::= [<userinfo>@]<host>[:<port>]
+<userinfo> ::= <user>[:<password>]
+<path> ::= {<segment>/}<segment>
+
+
+ + + +

+url.absolute(base, relative) +

+ +

+Builds an absolute URL from a base URL and a relative URL. +

+ +

+Base is a string with the base URL or +a parsed URL table. Relative is a +string with the relative URL. +

+ +

+The function returns a string with the absolute URL. +

+ +

+Note: The rules that +govern the composition are fairly complex, and are described in detail in +RFC 2396. +The example bellow should give an idea of what the rules are. +

+ +
+http://a/b/c/d;p?q
+
++
+
+g:h      =  g:h
+g        =  http://a/b/c/g
+./g      =  http://a/b/c/g
+g/       =  http://a/b/c/g/
+/g       =  http://a/g
+//g      =  http://g
+?y       =  http://a/b/c/?y
+g?y      =  http://a/b/c/g?y
+#s       =  http://a/b/c/d;p?q#s
+g#s      =  http://a/b/c/g#s
+g?y#s    =  http://a/b/c/g?y#s
+;x       =  http://a/b/c/;x
+g;x      =  http://a/b/c/g;x
+g;x?y#s  =  http://a/b/c/g;x?y#s
+.        =  http://a/b/c/
+./       =  http://a/b/c/
+..       =  http://a/b/
+../      =  http://a/b/
+../g     =  http://a/b/g
+../..    =  http://a/
+../../   =  http://a/
+../../g  =  http://a/g
+
+ + + +

+url.build(parsed_url) +

+ +

+Rebuilds an URL from its parts. +

+ +

+Parsed_url is a table with same components returned by +parse. +Lower level components, if specified, +take precedence over high level components of the URL grammar. +

+ +

+The function returns a string with the built URL. +

+ + + +

+url.build_path(segments, unsafe) +

+ +

+Builds a <path> component from a list of +<segment> parts. +Before composition, any reserved characters found in a segment are escaped into +their protected form, so that the resulting path is a valid URL path +component. +

+ +

+Segments is a list of strings with the <segment> +parts. If unsafe is anything but nil, reserved +characters are left untouched. +

+ +

+The function returns a string with the +built <path> component. +

+ + + +

+url.escape(content) +

+ +

+Applies the URL escaping content coding to a string +Each byte is encoded as a percent character followed +by the two byte hexadecimal representation of its integer +value. +

+ +

+Content is the string to be encoded. +

+ +

+The function returns the encoded string. +

+ +
+-- load url module
+url = require("socket.url")
+
+code = url.escape("/#?;")
+-- code = "%2f%23%3f%3b"
+
+ + + +

+url.parse(url, default) +

+ +

+Parses an URL given as a string into a Lua table with its components. +

+ +

+Url is the URL to be parsed. If the default table is +present, it is used to store the parsed fields. Only fields present in the +URL are overwritten. Therefore, this table can be used to pass default +values for each field. +

+ +

+The function returns a table with all the URL components: +

+ +
+parsed_url = {
+  url = string,
+  scheme = string,
+  authority = string,
+  path = string,
+  params = string,
+  query = string,
+  fragment = string,
+  userinfo = string,
+  host = string,
+  port = string,
+  user = string,
+  password = string
+} +
+ +
+-- load url module
+url = require("socket.url")
+
+parsed_url = url.parse("http://www.example.com/cgilua/index.lua?a=2#there")
+-- parsed_url = {
+--   scheme = "http",
+--   authority = "www.example.com",
+--   path = "/cgilua/index.lua"
+--   query = "a=2",
+--   fragment = "there",
+--   host = "www.puc-rio.br",
+-- }
+
+parsed_url = url.parse("ftp://root:passwd@unsafe.org/pub/virus.exe;type=i")
+-- parsed_url = {
+--   scheme = "ftp",
+--   authority = "root:passwd@unsafe.org",
+--   path = "/pub/virus.exe",
+--   params = "type=i",
+--   userinfo = "root:passwd",
+--   host = "unsafe.org",
+--   user = "root",
+--   password = "passwd",
+-- }
+
+ + + +

+url.parse_path(path) +

+ +

+Breaks a <path> URL component into all its +<segment> parts. +

+ +

+Path is a string with the path to be parsed. +

+ +

+Since some characters are reserved in URLs, they must be escaped +whenever present in a <path> component. Therefore, before +returning a list with all the parsed segments, the function removes +escaping from all of them. +

+ + + +

+url.unescape(content) +

+ +

+Removes the URL escaping content coding from a string. +

+ +

+Content is the string to be decoded. +

+ +

+The function returns the decoded string. +

+ + + + + + + diff --git a/etc/luasocket-samples/README b/etc/luasocket-samples/README new file mode 100644 index 0000000..e63a6f5 --- /dev/null +++ b/etc/luasocket-samples/README @@ -0,0 +1,50 @@ +This directory contains some sample programs using +LuaSocket. This code is not supported. + + listener.lua -- socket to stdout + talker.lua -- stdin to socket + +listener.lua and talker.lua are about the simplest +applications you can write using LuaSocket. Run + + 'lua listener.lua' and 'lua talker.lua' + +on different terminals. Whatever you type on talk.lua will +be printed by listen.lua. + + lpr.lua -- lpr client + +This is a cool program written by David Burgess to print +files using the Line Printer Daemon protocol, widely used in +Unix machines. It uses the lp.lua implementation, in the +etc directory. Just run 'lua lpr.lua +queue=' and the file will print! + + cddb.lua -- CDDB client + +This is the first try on a simple CDDB client. Not really +useful, but one day it might become a module. + + daytimeclnt.lua -- day time client + +Just run the program to retrieve the hour and date in +readable form from any server running an UDP daytime daemon. + + echoclnt.lua -- UDP echo client + echosrvr.lua -- UDP echo server + +These are a UDP echo client/server pair. They work with +other client and servers as well. + + tinyirc.lua -- irc like broadcast server + +This is a simple server that waits simultaneously on two +server sockets for telnet connections. Everything it +receives from the telnet clients is broadcasted to every +other connected client. It tests the select function and +shows how to create a simple server whith LuaSocket. Just +run tinyirc.lua and then open as many telnet connections +as you want to ports 8080 and 8081. + +Good luck, +Diego. diff --git a/etc/luasocket-samples/cddb.lua b/etc/luasocket-samples/cddb.lua new file mode 100644 index 0000000..883730c --- /dev/null +++ b/etc/luasocket-samples/cddb.lua @@ -0,0 +1,46 @@ +local socket = require("socket") +local http = require("socket.http") + +if not arg or not arg[1] or not arg[2] then + print("luasocket cddb.lua []") + os.exit(1) +end + +local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" + +function parse(body) + local lines = string.gfind(body, "(.-)\r\n") + local status = lines() + local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)")) + if tonumber(code) ~= 210 then + return nil, code, message + end + local data = {} + for l in lines do + local c = string.sub(l, 1, 1) + if c ~= '#' and c ~= '.' then + local key, value = socket.skip(2, string.find(l, "(.-)=(.*)")) + value = string.gsub(value, "\\n", "\n") + value = string.gsub(value, "\\\\", "\\") + value = string.gsub(value, "\\t", "\t") + data[key] = value + end + end + return data, code, message +end + +local host = socket.dns.gethostname() +local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" +local url = string.format(query, server, arg[1], arg[2], host) +local body, headers, code = http.get(url) + +if code == 200 then + local data, code, error = parse(body) + if not data then + print(error or code) + else + for i,v in pairs(data) do + io.write(i, ': ', v, '\n') + end + end +else print(error) end diff --git a/etc/luasocket-samples/daytimeclnt.lua b/etc/luasocket-samples/daytimeclnt.lua new file mode 100644 index 0000000..90ab39e --- /dev/null +++ b/etc/luasocket-samples/daytimeclnt.lua @@ -0,0 +1,23 @@ +----------------------------------------------------------------------------- +-- UDP sample: daytime protocol client +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: daytimeclnt.lua,v 1.11 2004/06/21 06:07:57 diego Exp $ +----------------------------------------------------------------------------- +local socket = require"socket" +host = host or "127.0.0.1" +port = port or 13 +if arg then + host = arg[1] or host + port = arg[2] or port +end +host = socket.dns.toip(host) +udp = socket.udp() +print("Using host '" ..host.. "' and port " ..port.. "...") +udp:setpeername(host, port) +udp:settimeout(3) +sent, err = udp:send("anything") +if err then print(err) os.exit() end +dgram, err = udp:receive() +if not dgram then print(err) os.exit() end +io.write(dgram) diff --git a/etc/luasocket-samples/echoclnt.lua b/etc/luasocket-samples/echoclnt.lua new file mode 100644 index 0000000..038be4c --- /dev/null +++ b/etc/luasocket-samples/echoclnt.lua @@ -0,0 +1,24 @@ +----------------------------------------------------------------------------- +-- UDP sample: echo protocol client +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: echoclnt.lua,v 1.10 2005/01/02 22:44:00 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +host = host or "localhost" +port = port or 7 +if arg then + host = arg[1] or host + port = arg[2] or port +end +host = socket.dns.toip(host) +udp = assert(socket.udp()) +assert(udp:setpeername(host, port)) +print("Using remote host '" ..host.. "' and port " .. port .. "...") +while 1 do + line = io.read() + if not line or line == "" then os.exit() end + assert(udp:send(line)) + dgram = assert(udp:receive()) + print(dgram) +end diff --git a/etc/luasocket-samples/echosrvr.lua b/etc/luasocket-samples/echosrvr.lua new file mode 100644 index 0000000..2697ca4 --- /dev/null +++ b/etc/luasocket-samples/echosrvr.lua @@ -0,0 +1,29 @@ +----------------------------------------------------------------------------- +-- UDP sample: echo protocol server +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: echosrvr.lua,v 1.12 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +host = host or "127.0.0.1" +port = port or 7 +if arg then + host = arg[1] or host + port = arg[2] or port +end +print("Binding to host '" ..host.. "' and port " ..port.. "...") +udp = assert(socket.udp()) +assert(udp:setsockname(host, port)) +assert(udp:settimeout(5)) +ip, port = udp:getsockname() +assert(ip, port) +print("Waiting packets on " .. ip .. ":" .. port .. "...") +while 1 do + dgram, ip, port = udp:receivefrom() + if dgram then + print("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port) + udp:sendto(dgram, ip, port) + else + print(ip) + end +end diff --git a/etc/luasocket-samples/listener.lua b/etc/luasocket-samples/listener.lua new file mode 100644 index 0000000..9260fbb --- /dev/null +++ b/etc/luasocket-samples/listener.lua @@ -0,0 +1,26 @@ +----------------------------------------------------------------------------- +-- TCP sample: Little program to dump lines received at a given port +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: listener.lua,v 1.11 2005/01/02 22:44:00 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +host = host or "*" +port = port or 8080 +if arg then + host = arg[1] or host + port = arg[2] or port +end +print("Binding to host '" ..host.. "' and port " ..port.. "...") +s = assert(socket.bind(host, port)) +i, p = s:getsockname() +assert(i, p) +print("Waiting connection from talker on " .. i .. ":" .. p .. "...") +c = assert(s:accept()) +print("Connected. Here is the stuff:") +l, e = c:receive() +while not e do + print(l) + l, e = c:receive() +end +print(e) diff --git a/etc/luasocket-samples/lpr.lua b/etc/luasocket-samples/lpr.lua new file mode 100644 index 0000000..2b059b1 --- /dev/null +++ b/etc/luasocket-samples/lpr.lua @@ -0,0 +1,51 @@ +local lp = require("socket.lp") + +local function usage() + print('\nUsage: lua lpr.lua [filename] [keyword=val...]\n') + print('Valid keywords are :') + print( + ' host=remote host or IP address (default "localhost")\n' .. + ' queue=remote queue or printer name (default "printer")\n' .. + ' port=remote port number (default 515)\n' .. + ' user=sending user name\n' .. + ' format=["binary" | "text" | "ps" | "pr" | "fortran"] (default "binary")\n' .. + ' banner=true|false\n' .. + ' indent=number of columns to indent\n' .. + ' mail=email of address to notify when print is complete\n' .. + ' title=title to use for "pr" format\n' .. + ' width=width for "text" or "pr" formats\n' .. + ' class=\n' .. + ' job=\n' .. + ' name=\n' .. + ' localbind=true|false\n' + ) + return nil +end + +if not arg or not arg[1] then + return usage() +end + +do + local opt = {} + local pat = "[%s%c%p]*([%w]*)=([\"]?[%w%s_!@#$%%^&*()<>:;]+[\"]\?\.?)" + for i = 2, table.getn(arg), 1 do + string.gsub(arg[i], pat, function(name, value) opt[name] = value end) + end + if not arg[2] then + return usage() + end + if arg[1] ~= "query" then + opt.file = arg[1] + r,e=lp.send(opt) + io.stdout:write(tostring(r or e),'\n') + else + r,e=lp.query(opt) + io.stdout:write(tostring(r or e), '\n') + end +end + +-- trivial tests +--lua lp.lua lp.lua queue=default host=localhost +--lua lp.lua lp.lua queue=default host=localhost format=binary localbind=1 +--lua lp.lua query queue=default host=localhost diff --git a/etc/luasocket-samples/talker.lua b/etc/luasocket-samples/talker.lua new file mode 100644 index 0000000..607ff31 --- /dev/null +++ b/etc/luasocket-samples/talker.lua @@ -0,0 +1,21 @@ +----------------------------------------------------------------------------- +-- TCP sample: Little program to send text lines to a given host/port +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: talker.lua,v 1.9 2005/01/02 22:44:00 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +host = host or "localhost" +port = port or 8080 +if arg then + host = arg[1] or host + port = arg[2] or port +end +print("Attempting connection to host '" ..host.. "' and port " ..port.. "...") +c = assert(socket.connect(host, port)) +print("Connected! Please type stuff (empty line to stop):") +l = io.read() +while l and l ~= "" and not e do + assert(c:send(l .. "\n")) + l = io.read() +end diff --git a/etc/luasocket-samples/tinyirc.lua b/etc/luasocket-samples/tinyirc.lua new file mode 100644 index 0000000..f474302 --- /dev/null +++ b/etc/luasocket-samples/tinyirc.lua @@ -0,0 +1,90 @@ +----------------------------------------------------------------------------- +-- Select sample: simple text line server +-- LuaSocket sample files. +-- Author: Diego Nehab +-- RCS ID: $Id: tinyirc.lua,v 1.14 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +host = host or "*" +port1 = port1 or 8080 +port2 = port2 or 8181 +if arg then + host = arg[1] or host + port1 = arg[2] or port1 + port2 = arg[3] or port2 +end + +server1 = assert(socket.bind(host, port1)) +server2 = assert(socket.bind(host, port2)) +server1:settimeout(1) -- make sure we don't block in accept +server2:settimeout(1) + +io.write("Servers bound\n") + +-- simple set implementation +-- the select function doesn't care about what is passed to it as long as +-- it behaves like a table +-- creates a new set data structure +function newset() + local reverse = {} + local set = {} + return setmetatable(set, {__index = { + insert = function(set, value) + if not reverse[value] then + table.insert(set, value) + reverse[value] = table.getn(set) + end + end, + remove = function(set, value) + local index = reverse[value] + if index then + reverse[value] = nil + local top = table.remove(set) + if top ~= value then + reverse[top] = index + set[index] = top + end + end + end + }}) +end + +set = newset() + +io.write("Inserting servers in set\n") +set:insert(server1) +set:insert(server2) + +while 1 do + local readable, _, error = socket.select(set, nil) + for _, input in ipairs(readable) do + -- is it a server socket? + if input == server1 or input == server2 then + io.write("Waiting for clients\n") + local new = input:accept() + if new then + new:settimeout(1) + io.write("Inserting client in set\n") + set:insert(new) + end + -- it is a client socket + else + local line, error = input:receive() + if error then + input:close() + io.write("Removing client from set\n") + set:remove(input) + else + io.write("Broadcasting line '", line, "'\n") + writable, error = socket.skip(1, socket.select(nil, set, 1)) + if not error then + for __, output in ipairs(writable) do + if output ~= input then + output:send(line .. "\n") + end + end + else io.write("No client ready to receive!!!\n") end + end + end + end +end diff --git a/etc/luasocket/README b/etc/luasocket/README new file mode 100644 index 0000000..5a919cd --- /dev/null +++ b/etc/luasocket/README @@ -0,0 +1,89 @@ +This directory contains code that is more useful than the +samples. This code *is* supported. + + tftp.lua -- Trivial FTP client + +This module implements file retrieval by the TFTP protocol. +Its main use was to test the UDP code, but since someone +found it usefull, I turned it into a module that is almost +official (no uploads, yet). + + dict.lua -- Dict client + +The dict.lua module started with a cool simple client +for the DICT protocol, written by Luiz Henrique Figueiredo. +This new version has been converted into a library, similar +to the HTTP and FTP libraries, that can be used from within +any luasocket application. Take a look on the source code +and you will be able to figure out how to use it. + + lp.lua -- LPD client library + +The lp.lua module implements the client part of the Line +Printer Daemon protocol, used to print files on Unix +machines. It is courtesy of David Burgess! See the source +code and the lpr.lua in the examples directory. + + b64.lua + qp.lua + eol.lua + +These are tiny programs that perform Base64, +Quoted-Printable and end-of-line marker conversions. + + get.lua -- file retriever + +This little program is a client that uses the FTP and +HTTP code to implement a command line file graber. Just +run + + lua get.lua [] + +to download a remote file (either ftp:// or http://) to +the specified local file. The program also prints the +download throughput, elapsed time, bytes already downloaded +etc during download. + + check-memory.lua -- checks memory consumption + +This is just to see how much memory each module uses. + + dispatch.lua -- coroutine based dispatcher + +This is a first try at a coroutine based non-blocking +dispatcher for LuaSocket. Take a look at 'check-links.lua' +and at 'forward.lua' to see how to use it. + + check-links.lua -- HTML link checker program + +This little program scans a HTML file and checks for broken +links. It is similar to check-links.pl by Jamie Zawinski, +but uses all facilities of the LuaSocket library and the Lua +language. It has not been thoroughly tested, but it should +work. Just run + + lua check-links.lua [-n] {} > output + +and open the result to see a list of broken links. You can +also use the '-n' switch to run the same program in +non-blocking mode to see how much faster things can get. + + forward.lua -- coroutine based forward server + +This is a forward server that can accept several connections +and transfers simultaneously using non-blocking I/O and the +coroutine-based dispatcher. You can run, for example + + lua forward.lua 8080:proxy.com:3128 + +to redirect all local conections to port 8080 to the host +'proxy.com' at port 3128. + + unix.c and unix.h + +This is an implementation of Unix local domain sockets and +demonstrates how to extend LuaSocket with a new type of +transport. It has been tested on Linux and on Mac OS X. + +Good luck, +Diego. diff --git a/etc/luasocket/b64.lua b/etc/luasocket/b64.lua new file mode 100644 index 0000000..f75c423 --- /dev/null +++ b/etc/luasocket/b64.lua @@ -0,0 +1,20 @@ +----------------------------------------------------------------------------- +-- Little program to convert to and from Base64 +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: b64.lua,v 1.8 2004/06/16 04:28:21 diego Exp $ +----------------------------------------------------------------------------- +local ltn12 = require("ltn12") +local mime = require("mime") +local source = ltn12.source.file(io.stdin) +local sink = ltn12.sink.file(io.stdout) +local convert +if arg and arg[1] == '-d' then + convert = mime.decode("base64") +else + local base64 = mime.encode("base64") + local wrap = mime.wrap() + convert = ltn12.filter.chain(base64, wrap) +end +sink = ltn12.sink.chain(convert, sink) +ltn12.pump.all(source, sink) diff --git a/etc/luasocket/check-links.lua b/etc/luasocket/check-links.lua new file mode 100644 index 0000000..a989f8c --- /dev/null +++ b/etc/luasocket/check-links.lua @@ -0,0 +1,112 @@ +----------------------------------------------------------------------------- +-- Little program that checks links in HTML files, using coroutines and +-- non-blocking I/O via the dispatcher module. +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $$ +----------------------------------------------------------------------------- +local url = require("socket.url") +local dispatch = require("dispatch") +local http = require("socket.http") +dispatch.TIMEOUT = 10 + +-- make sure the user knows how to invoke us +arg = arg or {} +if table.getn(arg) < 1 then + print("Usage:\n luasocket check-links.lua [-n] {}") + exit() +end + +-- '-n' means we are running in non-blocking mode +if arg[1] == "-n" then + -- if non-blocking I/O was requested, use real dispatcher interface + table.remove(arg, 1) + handler = dispatch.newhandler("coroutine") +else + -- if using blocking I/O, use fake dispatcher interface + handler = dispatch.newhandler("sequential") +end + +local nthreads = 0 + +-- get the status of a URL using the dispatcher +function getstatus(link) + local parsed = url.parse(link, {scheme = "file"}) + if parsed.scheme == "http" then + nthreads = nthreads + 1 + handler:start(function() + local r, c, h, s = http.request{ + method = "HEAD", + url = link, + create = handler.tcp + } + if r and c == 200 then io.write('\t', link, '\n') + else io.write('\t', link, ': ', tostring(c), '\n') end + nthreads = nthreads - 1 + end) + end +end + +function readfile(path) + path = url.unescape(path) + local file, error = io.open(path, "r") + if file then + local body = file:read("*a") + file:close() + return body + else return nil, error end +end + +function load(u) + local parsed = url.parse(u, { scheme = "file" }) + local body, headers, code, error + local base = u + if parsed.scheme == "http" then + body, code, headers = http.request(u) + if code == 200 then + -- if there was a redirect, update base to reflect it + base = headers.location or base + end + if not body then + error = code + end + elseif parsed.scheme == "file" then + body, error = readfile(parsed.path) + else error = string.format("unhandled scheme '%s'", parsed.scheme) end + return base, body, error +end + +function getlinks(body, base) + -- get rid of comments + body = string.gsub(body, "%<%!%-%-.-%-%-%>", "") + local links = {} + -- extract links + body = string.gsub(body, '[Hh][Rr][Ee][Ff]%s*=%s*"([^"]*)"', function(href) + table.insert(links, url.absolute(base, href)) + end) + body = string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*'([^']*)'", function(href) + table.insert(links, url.absolute(base, href)) + end) + string.gsub(body, "[Hh][Rr][Ee][Ff]%s*=%s*(.-)>", function(href) + table.insert(links, url.absolute(base, href)) + end) + return links +end + +function checklinks(address) + local base, body, error = load(address) + if not body then print(error) return end + print("Checking ", base) + local links = getlinks(body, base) + for _, link in ipairs(links) do + getstatus(link) + end +end + +for _, address in ipairs(arg) do + checklinks(url.absolute("file:", address)) +end + +while nthreads > 0 do + handler:step() +end diff --git a/etc/luasocket/check-memory.lua b/etc/luasocket/check-memory.lua new file mode 100644 index 0000000..7bd984d --- /dev/null +++ b/etc/luasocket/check-memory.lua @@ -0,0 +1,17 @@ +function load(s) + collectgarbage() + local a = gcinfo() + _G[s] = require(s) + collectgarbage() + local b = gcinfo() + print(s .. ":\t " .. (b-a) .. "k") +end + +load("socket.url") +load("ltn12") +load("socket") +load("mime") +load("socket.tp") +load("socket.smtp") +load("socket.http") +load("socket.ftp") diff --git a/etc/luasocket/dict.lua b/etc/luasocket/dict.lua new file mode 100644 index 0000000..c082c24 --- /dev/null +++ b/etc/luasocket/dict.lua @@ -0,0 +1,152 @@ +----------------------------------------------------------------------------- +-- Little program to download DICT word definitions +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: dict.lua,v 1.22 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Load required modules +----------------------------------------------------------------------------- +local base = _G +local string = require("string") +local table = require("table") +local socket = require("socket") +local url = require("socket.url") +local tp = require("socket.tp") +module("socket.dict") + +----------------------------------------------------------------------------- +-- Globals +----------------------------------------------------------------------------- +HOST = "dict.org" +PORT = 2628 +TIMEOUT = 10 + +----------------------------------------------------------------------------- +-- Low-level dict API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function open(host, port) + local tp = socket.try(tp.connect(host or HOST, port or PORT, TIMEOUT)) + return base.setmetatable({tp = tp}, metat) +end + +function metat.__index:greet() + return socket.try(self.tp:check(220)) +end + +function metat.__index:check(ok) + local code, status = socket.try(self.tp:check(ok)) + return code, + base.tonumber(socket.skip(2, string.find(status, "^%d%d%d (%d*)"))) +end + +function metat.__index:getdef() + local line = socket.try(self.tp:receive()) + local def = {} + while line ~= "." do + table.insert(def, line) + line = socket.try(self.tp:receive()) + end + return table.concat(def, "\n") +end + +function metat.__index:define(database, word) + database = database or "!" + socket.try(self.tp:command("DEFINE", database .. " " .. word)) + local code, count = self:check(150) + local defs = {} + for i = 1, count do + self:check(151) + table.insert(defs, self:getdef()) + end + self:check(250) + return defs +end + +function metat.__index:match(database, strat, word) + database = database or "!" + strat = strat or "." + socket.try(self.tp:command("MATCH", database .." ".. strat .." ".. word)) + self:check(152) + local mat = {} + local line = socket.try(self.tp:receive()) + while line ~= '.' do + database, word = socket.skip(2, string.find(line, "(%S+) (.*)")) + if not mat[database] then mat[database] = {} end + table.insert(mat[database], word) + line = socket.try(self.tp:receive()) + end + self:check(250) + return mat +end + +function metat.__index:quit() + self.tp:command("QUIT") + return self:check(221) +end + +function metat.__index:close() + return self.tp:close() +end + +----------------------------------------------------------------------------- +-- High-level dict API +----------------------------------------------------------------------------- +local default = { + scheme = "dict", + host = "dict.org" +} + +local function there(f) + if f == "" then return nil + else return f end +end + +local function parse(u) + local t = socket.try(url.parse(u, default)) + socket.try(t.scheme == "dict", "invalid scheme '" .. t.scheme .. "'") + socket.try(t.path, "invalid path in url") + local cmd, arg = socket.skip(2, string.find(t.path, "^/(.)(.*)$")) + socket.try(cmd == "d" or cmd == "m", " should be 'm' or 'd'") + socket.try(arg and arg ~= "", "need at least in URL") + t.command, t.argument = cmd, arg + arg = string.gsub(arg, "^:([^:]+)", function(f) t.word = f end) + socket.try(t.word, "need at least in URL") + arg = string.gsub(arg, "^:([^:]*)", function(f) t.database = there(f) end) + if cmd == "m" then + arg = string.gsub(arg, "^:([^:]*)", function(f) t.strat = there(f) end) + end + string.gsub(arg, ":([^:]*)$", function(f) t.n = base.tonumber(f) end) + return t +end + +local function tget(gett) + local con = open(gett.host, gett.port) + con:greet() + if gett.command == "d" then + local def = con:define(gett.database, gett.word) + con:quit() + con:close() + if gett.n then return def[gett.n] + else return def end + elseif gett.command == "m" then + local mat = con:match(gett.database, gett.strat, gett.word) + con:quit() + con:close() + return mat + else return nil, "invalid command" end +end + +local function sget(u) + local gett = parse(u) + return tget(gett) +end + +get = socket.protect(function(gett) + if base.type(gett) == "string" then return sget(gett) + else return tget(gett) end +end) + diff --git a/etc/luasocket/dispatch.lua b/etc/luasocket/dispatch.lua new file mode 100644 index 0000000..dd76d6d --- /dev/null +++ b/etc/luasocket/dispatch.lua @@ -0,0 +1,301 @@ +----------------------------------------------------------------------------- +-- A hacked dispatcher module +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $$ +----------------------------------------------------------------------------- +local base = _G +local socket = require("socket") +local coroutine = require("coroutine") +module("dispatch") + +-- if too much time goes by without any activity in one of our sockets, we +-- just kill it +TIMEOUT = 60 + +----------------------------------------------------------------------------- +-- We implement 3 types of dispatchers: +-- sequential +-- coroutine +-- threaded +-- The user can choose whatever one is needed +----------------------------------------------------------------------------- +local handlert = {} + +-- default handler is coroutine +function newhandler(mode) + mode = mode or "coroutine" + return handlert[mode]() +end + +local function seqstart(self, func) + return func() +end + +-- sequential handler simply calls the functions and doesn't wrap I/O +function handlert.sequential() + return { + tcp = socket.tcp, + start = seqstart + } +end + +----------------------------------------------------------------------------- +-- Mega hack. Don't try to do this at home. +----------------------------------------------------------------------------- +-- we can't yield across calls to protect, so we rewrite it with coxpcall +-- make sure you don't require any module that uses socket.protect before +-- loading our hack +function socket.protect(f) + return function(...) + local co = coroutine.create(f) + while true do + local results = {coroutine.resume(co, unpack(arg))} + local status = table.remove(results, 1) + if not status then + if type(results[1]) == 'table' then + return nil, results[1][1] + else error(results[1]) end + end + if coroutine.status(co) == "suspended" then + arg = {coroutine.yield(unpack(results))} + else + return unpack(results) + end + end + end +end + +----------------------------------------------------------------------------- +-- Simple set data structure. O(1) everything. +----------------------------------------------------------------------------- +local function newset() + local reverse = {} + local set = {} + return setmetatable(set, {__index = { + insert = function(set, value) + if not reverse[value] then + table.insert(set, value) + reverse[value] = table.getn(set) + end + end, + remove = function(set, value) + local index = reverse[value] + if index then + reverse[value] = nil + local top = table.remove(set) + if top ~= value then + reverse[top] = index + set[index] = top + end + end + end + }}) +end + +----------------------------------------------------------------------------- +-- socket.tcp() wrapper for the coroutine dispatcher +----------------------------------------------------------------------------- +local function cowrap(dispatcher, tcp, error) + if not tcp then return nil, error end + -- put it in non-blocking mode right away + tcp:settimeout(0) + -- metatable for wrap produces new methods on demand for those that we + -- don't override explicitly. + local metat = { __index = function(table, key) + table[key] = function(...) + arg[1] = tcp + return tcp[key](unpack(arg)) + end + return table[key] + end} + -- does our user want to do his own non-blocking I/O? + local zero = false + -- create a wrap object that will behave just like a real socket object + local wrap = { } + -- we ignore settimeout to preserve our 0 timeout, but record whether + -- the user wants to do his own non-blocking I/O + function wrap:settimeout(value, mode) + if value == 0 then zero = true + else zero = false end + return 1 + end + -- send in non-blocking mode and yield on timeout + function wrap:send(data, first, last) + first = (first or 1) - 1 + local result, error + while true do + -- return control to dispatcher and tell it we want to send + -- if upon return the dispatcher tells us we timed out, + -- return an error to whoever called us + if coroutine.yield(dispatcher.sending, tcp) == "timeout" then + return nil, "timeout" + end + -- try sending + result, error, first = tcp:send(data, first+1, last) + -- if we are done, or there was an unexpected error, + -- break away from loop + if error ~= "timeout" then return result, error, first end + end + end + -- receive in non-blocking mode and yield on timeout + -- or simply return partial read, if user requested timeout = 0 + function wrap:receive(pattern, partial) + local error = "timeout" + local value + while true do + -- return control to dispatcher and tell it we want to receive + -- if upon return the dispatcher tells us we timed out, + -- return an error to whoever called us + if coroutine.yield(dispatcher.receiving, tcp) == "timeout" then + return nil, "timeout" + end + -- try receiving + value, error, partial = tcp:receive(pattern, partial) + -- if we are done, or there was an unexpected error, + -- break away from loop. also, if the user requested + -- zero timeout, return all we got + if (error ~= "timeout") or zero then + return value, error, partial + end + end + end + -- connect in non-blocking mode and yield on timeout + function wrap:connect(host, port) + local result, error = tcp:connect(host, port) + if error == "timeout" then + -- return control to dispatcher. we will be writable when + -- connection succeeds. + -- if upon return the dispatcher tells us we have a + -- timeout, just abort + if coroutine.yield(dispatcher.sending, tcp) == "timeout" then + return nil, "timeout" + end + -- when we come back, check if connection was successful + result, error = tcp:connect(host, port) + if result or error == "already connected" then return 1 + else return nil, "non-blocking connect failed" end + else return result, error end + end + -- accept in non-blocking mode and yield on timeout + function wrap:accept() + while 1 do + -- return control to dispatcher. we will be readable when a + -- connection arrives. + -- if upon return the dispatcher tells us we have a + -- timeout, just abort + if coroutine.yield(dispatcher.receiving, tcp) == "timeout" then + return nil, "timeout" + end + local client, error = tcp:accept() + if error ~= "timeout" then + return cowrap(dispatcher, client, error) + end + end + end + -- remove cortn from context + function wrap:close() + dispatcher.stamp[tcp] = nil + dispatcher.sending.set:remove(tcp) + dispatcher.sending.cortn[tcp] = nil + dispatcher.receiving.set:remove(tcp) + dispatcher.receiving.cortn[tcp] = nil + return tcp:close() + end + return setmetatable(wrap, metat) +end + + +----------------------------------------------------------------------------- +-- Our coroutine dispatcher +----------------------------------------------------------------------------- +local cometat = { __index = {} } + +function schedule(cortn, status, operation, tcp) + if status then + if cortn and operation then + operation.set:insert(tcp) + operation.cortn[tcp] = cortn + operation.stamp[tcp] = socket.gettime() + end + else error(operation) end +end + +function kick(operation, tcp) + operation.cortn[tcp] = nil + operation.set:remove(tcp) +end + +function wakeup(operation, tcp) + local cortn = operation.cortn[tcp] + -- if cortn is still valid, wake it up + if cortn then + kick(operation, tcp) + return cortn, coroutine.resume(cortn) + -- othrewise, just get scheduler not to do anything + else + return nil, true + end +end + +function abort(operation, tcp) + local cortn = operation.cortn[tcp] + if cortn then + kick(operation, tcp) + coroutine.resume(cortn, "timeout") + end +end + +-- step through all active cortns +function cometat.__index:step() + -- check which sockets are interesting and act on them + local readable, writable = socket.select(self.receiving.set, + self.sending.set, 1) + -- for all readable connections, resume their cortns and reschedule + -- when they yield back to us + for _, tcp in ipairs(readable) do + schedule(wakeup(self.receiving, tcp)) + end + -- for all writable connections, do the same + for _, tcp in ipairs(writable) do + schedule(wakeup(self.sending, tcp)) + end + -- politely ask replacement I/O functions in idle cortns to + -- return reporting a timeout + local now = socket.gettime() + for tcp, stamp in pairs(self.stamp) do + if tcp.class == "tcp{client}" and now - stamp > TIMEOUT then + abort(self.sending, tcp) + abort(self.receiving, tcp) + end + end +end + +function cometat.__index:start(func) + local cortn = coroutine.create(func) + schedule(cortn, coroutine.resume(cortn)) +end + +function handlert.coroutine() + local stamp = {} + local dispatcher = { + stamp = stamp, + sending = { + name = "sending", + set = newset(), + cortn = {}, + stamp = stamp + }, + receiving = { + name = "receiving", + set = newset(), + cortn = {}, + stamp = stamp + }, + } + function dispatcher.tcp() + return cowrap(dispatcher, socket.tcp()) + end + return setmetatable(dispatcher, cometat) +end + diff --git a/etc/luasocket/eol.lua b/etc/luasocket/eol.lua new file mode 100644 index 0000000..b90be79 --- /dev/null +++ b/etc/luasocket/eol.lua @@ -0,0 +1,14 @@ +----------------------------------------------------------------------------- +-- Little program to adjust end of line markers. +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: eol.lua,v 1.8 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- +local mime = require("mime") +local ltn12 = require("ltn12") +local marker = '\n' +if arg and arg[1] == '-d' then marker = '\r\n' end +local filter = mime.normalize(marker) +local source = ltn12.source.chain(ltn12.source.file(io.stdin), filter) +local sink = ltn12.sink.file(io.stdout) +ltn12.pump.all(source, sink) diff --git a/etc/luasocket/forward.lua b/etc/luasocket/forward.lua new file mode 100644 index 0000000..9073ac4 --- /dev/null +++ b/etc/luasocket/forward.lua @@ -0,0 +1,65 @@ +-- load our favourite library +local dispatch = require("dispatch") +local handler = dispatch.newhandler() + +-- make sure the user knows how to invoke us +if table.getn(arg) < 1 then + print("Usage") + print(" lua forward.lua ...") + os.exit(1) +end + +-- function to move data from one socket to the other +local function move(foo, bar) + local live + while 1 do + local data, error, partial = foo:receive(2048) + live = data or error == "timeout" + data = data or partial + local result, error = bar:send(data) + if not live or not result then + foo:close() + bar:close() + break + end + end +end + +-- for each tunnel, start a new server +for i, v in ipairs(arg) do + -- capture forwarding parameters + local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") + assert(iport, "invalid arguments") + -- create our server socket + local server = assert(handler.tcp()) + assert(server:setoption("reuseaddr", true)) + assert(server:bind("*", iport)) + assert(server:listen(32)) + -- handler for the server object loops accepting new connections + handler:start(function() + while 1 do + local client = assert(server:accept()) + assert(client:settimeout(0)) + -- for each new connection, start a new client handler + handler:start(function() + -- handler tries to connect to peer + local peer = assert(handler.tcp()) + assert(peer:settimeout(0)) + assert(peer:connect(ohost, oport)) + -- if sucessful, starts a new handler to send data from + -- client to peer + handler:start(function() + move(client, peer) + end) + -- afte starting new handler, enter in loop sending data from + -- peer to client + move(peer, client) + end) + end + end) +end + +-- simply loop stepping the server +while 1 do + handler:step() +end diff --git a/etc/luasocket/get.lua b/etc/luasocket/get.lua new file mode 100644 index 0000000..f259ea9 --- /dev/null +++ b/etc/luasocket/get.lua @@ -0,0 +1,140 @@ +----------------------------------------------------------------------------- +-- Little program to download files from URLs +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: get.lua,v 1.24 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- +local socket = require("socket") +local http = require("socket.http") +local ftp = require("socket.ftp") +local url = require("socket.url") +local ltn12 = require("ltn12") + +-- formats a number of seconds into human readable form +function nicetime(s) + local l = "s" + if s > 60 then + s = s / 60 + l = "m" + if s > 60 then + s = s / 60 + l = "h" + if s > 24 then + s = s / 24 + l = "d" -- hmmm + end + end + end + if l == "s" then return string.format("%5.0f%s", s, l) + else return string.format("%5.2f%s", s, l) end +end + +-- formats a number of bytes into human readable form +function nicesize(b) + local l = "B" + if b > 1024 then + b = b / 1024 + l = "KB" + if b > 1024 then + b = b / 1024 + l = "MB" + if b > 1024 then + b = b / 1024 + l = "GB" -- hmmm + end + end + end + return string.format("%7.2f%2s", b, l) +end + +-- returns a string with the current state of the download +local remaining_s = "%s received, %s/s throughput, %2.0f%% done, %s remaining" +local elapsed_s = "%s received, %s/s throughput, %s elapsed " +function gauge(got, delta, size) + local rate = got / delta + if size and size >= 1 then + return string.format(remaining_s, nicesize(got), nicesize(rate), + 100*got/size, nicetime((size-got)/rate)) + else + return string.format(elapsed_s, nicesize(got), + nicesize(rate), nicetime(delta)) + end +end + +-- creates a new instance of a receive_cb that saves to disk +-- kind of copied from luasocket's manual callback examples +function stats(size) + local start = socket.gettime() + local got = 0 + return function(chunk) + -- elapsed time since start + local delta = socket.gettime() - start + if chunk then + -- total bytes received + got = got + string.len(chunk) + -- not enough time for estimate + if delta > 0.1 then + io.stderr:write("\r", gauge(got, delta, size)) + io.stderr:flush() + end + else + -- close up + io.stderr:write("\r", gauge(got, delta), "\n") + end + return chunk + end +end + +-- determines the size of a http file +function gethttpsize(u) + local r, c, h = http.request {method = "HEAD", url = u} + if c == 200 then + return tonumber(h["content-length"]) + end +end + +-- downloads a file using the http protocol +function getbyhttp(u, file) + local save = ltn12.sink.file(file or io.stdout) + -- only print feedback if output is not stdout + if file then save = ltn12.sink.chain(stats(gethttpsize(u)), save) end + local r, c, h, s = http.request {url = u, sink = save } + if c ~= 200 then io.stderr:write(s or c, "\n") end +end + +-- downloads a file using the ftp protocol +function getbyftp(u, file) + local save = ltn12.sink.file(file or io.stdout) + -- only print feedback if output is not stdout + -- and we don't know how big the file is + if file then save = ltn12.sink.chain(stats(), save) end + local gett = url.parse(u) + gett.sink = save + gett.type = "i" + local ret, err = ftp.get(gett) + if err then print(err) end +end + +-- determines the scheme +function getscheme(u) + -- this is an heuristic to solve a common invalid url poblem + if not string.find(u, "//") then u = "//" .. u end + local parsed = url.parse(u, {scheme = "http"}) + return parsed.scheme +end + +-- gets a file either by http or ftp, saving as +function get(u, name) + local fout = name and io.open(name, "wb") + local scheme = getscheme(u) + if scheme == "ftp" then getbyftp(u, fout) + elseif scheme == "http" then getbyhttp(u, fout) + else print("unknown scheme" .. scheme) end +end + +-- main program +arg = arg or {} +if table.getn(arg) < 1 then + io.write("Usage:\n lua get.lua []\n") + os.exit(1) +else get(arg[1], arg[2]) end diff --git a/etc/luasocket/lp.lua b/etc/luasocket/lp.lua new file mode 100644 index 0000000..3269920 --- /dev/null +++ b/etc/luasocket/lp.lua @@ -0,0 +1,324 @@ +----------------------------------------------------------------------------- +-- LPD support for the Lua language +-- LuaSocket toolkit. +-- Author: David Burgess +-- Modified by Diego Nehab, but David is in charge +-- RCS ID: $Id: lp.lua,v 1.14 2005/11/21 07:04:44 diego Exp $ +----------------------------------------------------------------------------- +--[[ + if you have any questions: RFC 1179 +]] +-- make sure LuaSocket is loaded +local io = require("io") +local base = _G +local os = require("os") +local math = require("math") +local string = require("string") +local socket = require("socket") +local ltn12 = require("ltn12") +module("socket.lp") + +-- default port +PORT = 515 +SERVER = os.getenv("SERVER_NAME") or os.getenv("COMPUTERNAME") or "localhost" +PRINTER = os.getenv("PRINTER") or "printer" + +local function connect(localhost, option) + local host = option.host or SERVER + local port = option.port or PORT + local skt + local try = socket.newtry(function() if skt then skt:close() end end) + if option.localbind then + -- bind to a local port (if we can) + local localport = 721 + local done, err + repeat + skt = socket.try(socket.tcp()) + try(skt:settimeout(30)) + done, err = skt:bind(localhost, localport) + if not done then + localport = localport + 1 + skt:close() + skt = nil + else break end + until localport > 731 + socket.try(skt, err) + else skt = socket.try(socket.tcp()) end + try(skt:connect(host, port)) + return { skt = skt, try = try } +end + +--[[ +RFC 1179 +5.3 03 - Send queue state (short) + + +----+-------+----+------+----+ + | 03 | Queue | SP | List | LF | + +----+-------+----+------+----+ + Command code - 3 + Operand 1 - Printer queue name + Other operands - User names or job numbers + + If the user names or job numbers or both are supplied then only those + jobs for those users or with those numbers will be sent. + + The response is an ASCII stream which describes the printer queue. + The stream continues until the connection closes. Ends of lines are + indicated with ASCII LF control characters. The lines may also + contain ASCII HT control characters. + +5.4 04 - Send queue state (long) + + +----+-------+----+------+----+ + | 04 | Queue | SP | List | LF | + +----+-------+----+------+----+ + Command code - 4 + Operand 1 - Printer queue name + Other operands - User names or job numbers + + If the user names or job numbers or both are supplied then only those + jobs for those users or with those numbers will be sent. + + The response is an ASCII stream which describes the printer queue. + The stream continues until the connection closes. Ends of lines are + indicated with ASCII LF control characters. The lines may also + contain ASCII HT control characters. +]] + +-- gets server acknowledement +local function recv_ack(con) + local ack = con.skt:receive(1) + con.try(string.char(0) == ack, "failed to receive server acknowledgement") +end + +-- sends client acknowledement +local function send_ack(con) + local sent = con.skt:send(string.char(0)) + con.try(sent == 1, "failed to send acknowledgement") +end + +-- sends queue request +-- 5.2 02 - Receive a printer job +-- +-- +----+-------+----+ +-- | 02 | Queue | LF | +-- +----+-------+----+ +-- Command code - 2 +-- Operand - Printer queue name +-- +-- Receiving a job is controlled by a second level of commands. The +-- daemon is given commands by sending them over the same connection. +-- The commands are described in the next section (6). +-- +-- After this command is sent, the client must read an acknowledgement +-- octet from the daemon. A positive acknowledgement is an octet of +-- zero bits. A negative acknowledgement is an octet of any other +-- pattern. +local function send_queue(con, queue) + queue = queue or PRINTER + local str = string.format("\2%s\10", queue) + local sent = con.skt:send(str) + con.try(sent == string.len(str), "failed to send print request") + recv_ack(con) +end + +-- sends control file +-- 6.2 02 - Receive control file +-- +-- +----+-------+----+------+----+ +-- | 02 | Count | SP | Name | LF | +-- +----+-------+----+------+----+ +-- Command code - 2 +-- Operand 1 - Number of bytes in control file +-- Operand 2 - Name of control file +-- +-- The control file must be an ASCII stream with the ends of lines +-- indicated by ASCII LF. The total number of bytes in the stream is +-- sent as the first operand. The name of the control file is sent as +-- the second. It should start with ASCII "cfA", followed by a three +-- digit job number, followed by the host name which has constructed the +-- control file. Acknowledgement processing must occur as usual after +-- the command is sent. +-- +-- The next "Operand 1" octets over the same TCP connection are the +-- intended contents of the control file. Once all of the contents have +-- been delivered, an octet of zero bits is sent as an indication that +-- the file being sent is complete. A second level of acknowledgement +-- processing must occur at this point. + +-- sends data file +-- 6.3 03 - Receive data file +-- +-- +----+-------+----+------+----+ +-- | 03 | Count | SP | Name | LF | +-- +----+-------+----+------+----+ +-- Command code - 3 +-- Operand 1 - Number of bytes in data file +-- Operand 2 - Name of data file +-- +-- The data file may contain any 8 bit values at all. The total number +-- of bytes in the stream may be sent as the first operand, otherwise +-- the field should be cleared to 0. The name of the data file should +-- start with ASCII "dfA". This should be followed by a three digit job +-- number. The job number should be followed by the host name which has +-- constructed the data file. Interpretation of the contents of the +-- data file is determined by the contents of the corresponding control +-- file. If a data file length has been specified, the next "Operand 1" +-- octets over the same TCP connection are the intended contents of the +-- data file. In this case, once all of the contents have been +-- delivered, an octet of zero bits is sent as an indication that the +-- file being sent is complete. A second level of acknowledgement +-- processing must occur at this point. + + +local function send_hdr(con, control) + local sent = con.skt:send(control) + con.try(sent and sent >= 1 , "failed to send header file") + recv_ack(con) +end + +local function send_control(con, control) + local sent = con.skt:send(control) + con.try(sent and sent >= 1, "failed to send control file") + send_ack(con) +end + +local function send_data(con,fh,size) + local buf + while size > 0 do + buf,message = fh:read(8192) + if buf then + st = con.try(con.skt:send(buf)) + size = size - st + else + con.try(size == 0, "file size mismatch") + end + end + recv_ack(con) -- note the double acknowledgement + send_ack(con) + recv_ack(con) + return size +end + + +--[[ +local control_dflt = { + "H"..string.sub(socket.hostname,1,31).."\10", -- host + "C"..string.sub(socket.hostname,1,31).."\10", -- class + "J"..string.sub(filename,1,99).."\10", -- jobname + "L"..string.sub(user,1,31).."\10", -- print banner page + "I"..tonumber(indent).."\10", -- indent column count ('f' only) + "M"..string.sub(mail,1,128).."\10", -- mail when printed user@host + "N"..string.sub(filename,1,131).."\10", -- name of source file + "P"..string.sub(user,1,31).."\10", -- user name + "T"..string.sub(title,1,79).."\10", -- title for banner ('p' only) + "W"..tonumber(width or 132).."\10", -- width of print f,l,p only + + "f"..file.."\10", -- formatted print (remove control chars) + "l"..file.."\10", -- print + "o"..file.."\10", -- postscript + "p"..file.."\10", -- pr format - requires T, L + "r"..file.."\10", -- fortran format + "U"..file.."\10", -- Unlink (data file only) +} +]] + +-- generate a varying job number +local seq = 0 +local function newjob(connection) + seq = seq + 1 + return math.floor(socket.gettime() * 1000 + seq)%1000 +end + + +local format_codes = { + binary = 'l', + text = 'f', + ps = 'o', + pr = 'p', + fortran = 'r', + l = 'l', + r = 'r', + o = 'o', + p = 'p', + f = 'f' +} + +-- lp.send{option} +-- requires option.file + +send = socket.protect(function(option) + socket.try(option and base.type(option) == "table", "invalid options") + local file = option.file + socket.try(file, "invalid file name") + local fh = socket.try(io.open(file,"rb")) + local datafile_size = fh:seek("end") -- get total size + fh:seek("set") -- go back to start of file + local localhost = socket.dns.gethostname() or os.getenv("COMPUTERNAME") + or "localhost" + local con = connect(localhost, option) +-- format the control file + local jobno = newjob() + local localip = socket.dns.toip(localhost) + localhost = string.sub(localhost,1,31) + local user = string.sub(option.user or os.getenv("LPRUSER") or + os.getenv("USERNAME") or os.getenv("USER") or "anonymous", 1,31) + local lpfile = string.format("dfA%3.3d%-s", jobno, localhost); + local fmt = format_codes[option.format] or 'l' + local class = string.sub(option.class or localip or localhost,1,31) + local _,_,ctlfn = string.find(file,".*[%/%\\](.*)") + ctlfn = string.sub(ctlfn or file,1,131) + local cfile = + string.format("H%-s\nC%-s\nJ%-s\nP%-s\n%.1s%-s\nU%-s\nN%-s\n", + localhost, + class, + option.job or "LuaSocket", + user, + fmt, lpfile, + lpfile, + ctlfn); -- mandatory part of ctl file + if (option.banner) then cfile = cfile .. 'L'..user..'\10' end + if (option.indent) then cfile = cfile .. 'I'..base.tonumber(option.indent)..'\10' end + if (option.mail) then cfile = cfile .. 'M'..string.sub((option.mail),1,128)..'\10' end + if (fmt == 'p' and option.title) then cfile = cfile .. 'T'..string.sub((option.title),1,79)..'\10' end + if ((fmt == 'p' or fmt == 'l' or fmt == 'f') and option.width) then + cfile = cfile .. 'W'..base.tonumber(option,width)..'\10' + end + + con.skt:settimeout(option.timeout or 65) +-- send the queue header + send_queue(con, option.queue) +-- send the control file header + local cfilecmd = string.format("\2%d cfA%3.3d%-s\n",string.len(cfile), jobno, localhost); + send_hdr(con,cfilecmd) + +-- send the control file + send_control(con,cfile) + +-- send the data file header + local dfilecmd = string.format("\3%d dfA%3.3d%-s\n",datafile_size, jobno, localhost); + send_hdr(con,dfilecmd) + +-- send the data file + send_data(con,fh,datafile_size) + fh:close() + con.skt:close(); + return jobno, datafile_size +end) + +-- +-- lp.query({host=,queue=printer|'*', format='l'|'s', list=}) +-- +query = socket.protect(function(p) + p = p or {} + local localhost = socket.dns.gethostname() or os.getenv("COMPUTERNAME") + or "localhost" + local con = connect(localhost,p) + local fmt + if string.sub(p.format or 's',1,1) == 's' then fmt = 3 else fmt = 4 end + con.try(con.skt:send(string.format("%c%s %s\n", fmt, p.queue or "*", + p.list or ""))) + local data = con.try(con.skt:receive("*a")) + con.skt:close() + return data +end) diff --git a/etc/luasocket/qp.lua b/etc/luasocket/qp.lua new file mode 100644 index 0000000..a4c0cad --- /dev/null +++ b/etc/luasocket/qp.lua @@ -0,0 +1,24 @@ +----------------------------------------------------------------------------- +-- Little program to convert to and from Quoted-Printable +-- LuaSocket sample files +-- Author: Diego Nehab +-- RCS ID: $Id: qp.lua,v 1.5 2004/06/17 21:46:22 diego Exp $ +----------------------------------------------------------------------------- +local ltn12 = require("ltn12") +local mime = require("mime") +local convert +arg = arg or {} +local mode = arg and arg[1] or "-et" +if mode == "-et" then + local normalize = mime.normalize() + local qp = mime.encode("quoted-printable") + local wrap = mime.wrap("quoted-printable") + convert = ltn12.filter.chain(normalize, qp, wrap) +elseif mode == "-eb" then + local qp = mime.encode("quoted-printable", "binary") + local wrap = mime.wrap("quoted-printable") + convert = ltn12.filter.chain(qp, wrap) +else convert = mime.decode("quoted-printable") end +local source = ltn12.source.chain(ltn12.source.file(io.stdin), convert) +local sink = ltn12.sink.file(io.stdout) +ltn12.pump.all(source, sink) diff --git a/etc/luasocket/tftp.lua b/etc/luasocket/tftp.lua new file mode 100644 index 0000000..94eaf34 --- /dev/null +++ b/etc/luasocket/tftp.lua @@ -0,0 +1,155 @@ +----------------------------------------------------------------------------- +-- TFTP support for the Lua language +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: tftp.lua,v 1.16 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Load required files +----------------------------------------------------------------------------- +local base = _G +local table = require("table") +local math = require("math") +local string = require("string") +local socket = require("socket") +local ltn12 = require("ltn12") +local url = require("socket.url") +module("socket.tftp") + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +local char = string.char +local byte = string.byte + +PORT = 69 +local OP_RRQ = 1 +local OP_WRQ = 2 +local OP_DATA = 3 +local OP_ACK = 4 +local OP_ERROR = 5 +local OP_INV = {"RRQ", "WRQ", "DATA", "ACK", "ERROR"} + +----------------------------------------------------------------------------- +-- Packet creation functions +----------------------------------------------------------------------------- +local function RRQ(source, mode) + return char(0, OP_RRQ) .. source .. char(0) .. mode .. char(0) +end + +local function WRQ(source, mode) + return char(0, OP_RRQ) .. source .. char(0) .. mode .. char(0) +end + +local function ACK(block) + local low, high + low = math.mod(block, 256) + high = (block - low)/256 + return char(0, OP_ACK, high, low) +end + +local function get_OP(dgram) + local op = byte(dgram, 1)*256 + byte(dgram, 2) + return op +end + +----------------------------------------------------------------------------- +-- Packet analysis functions +----------------------------------------------------------------------------- +local function split_DATA(dgram) + local block = byte(dgram, 3)*256 + byte(dgram, 4) + local data = string.sub(dgram, 5) + return block, data +end + +local function get_ERROR(dgram) + local code = byte(dgram, 3)*256 + byte(dgram, 4) + local msg + _,_, msg = string.find(dgram, "(.*)\000", 5) + return string.format("error code %d: %s", code, msg) +end + +----------------------------------------------------------------------------- +-- The real work +----------------------------------------------------------------------------- +local function tget(gett) + local retries, dgram, sent, datahost, dataport, code + local last = 0 + socket.try(gett.host, "missing host") + local con = socket.try(socket.udp()) + local try = socket.newtry(function() con:close() end) + -- convert from name to ip if needed + gett.host = try(socket.dns.toip(gett.host)) + con:settimeout(1) + -- first packet gives data host/port to be used for data transfers + local path = string.gsub(gett.path or "", "^/", "") + path = url.unescape(path) + retries = 0 + repeat + sent = try(con:sendto(RRQ(path, "octet"), gett.host, gett.port)) + dgram, datahost, dataport = con:receivefrom() + retries = retries + 1 + until dgram or datahost ~= "timeout" or retries > 5 + try(dgram, datahost) + -- associate socket with data host/port + try(con:setpeername(datahost, dataport)) + -- default sink + local sink = gett.sink or ltn12.sink.null() + -- process all data packets + while 1 do + -- decode packet + code = get_OP(dgram) + try(code ~= OP_ERROR, get_ERROR(dgram)) + try(code == OP_DATA, "unhandled opcode " .. code) + -- get data packet parts + local block, data = split_DATA(dgram) + -- if not repeated, write + if block == last+1 then + try(sink(data)) + last = block + end + -- last packet brings less than 512 bytes of data + if string.len(data) < 512 then + try(con:send(ACK(block))) + try(con:close()) + try(sink(nil)) + return 1 + end + -- get the next packet + retries = 0 + repeat + sent = try(con:send(ACK(last))) + dgram, err = con:receive() + retries = retries + 1 + until dgram or err ~= "timeout" or retries > 5 + try(dgram, err) + end +end + +local default = { + port = PORT, + path ="/", + scheme = "tftp" +} + +local function parse(u) + local t = socket.try(url.parse(u, default)) + socket.try(t.scheme == "tftp", "invalid scheme '" .. t.scheme .. "'") + socket.try(t.host, "invalid host") + return t +end + +local function sget(u) + local gett = parse(u) + local t = {} + gett.sink = ltn12.sink.table(t) + tget(gett) + return table.concat(t) +end + +get = socket.protect(function(gett) + if base.type(gett) == "string" then return sget(gett) + else return tget(gett) end +end) + diff --git a/etc/tests/luairc/luabot.lua b/etc/tests/luairc/luabot.lua new file mode 100755 index 0000000..d65cc51 --- /dev/null +++ b/etc/tests/luairc/luabot.lua @@ -0,0 +1,109 @@ +#!/usr/bin/env lua + +local irc = require 'irc' +irc.DEBUG = true + +local nick = "doylua" + +local envs = {} + +local function create_env() + return { + _VERSION = _VERSION, + assert = assert, + collectgarbage = collectgarbage, + error = error, + getfenv = getfenv, + getmetatable = getmetatable, + ipairs = ipairs, + loadstring = loadstring, + next = next, + pairs = pairs, + pcall = pcall, + rawequal = rawequal, + rawget = rawget, + rawset = rawset, + select = select, + setfenv = setfenv, + setmetatable = setmetatable, + tonumber = tonumber, + tostring = tostring, + type = type, + unpack = unpack, + xpcall = xpcall, + coroutine = coroutine, + math = math, + string = string, + table = table, + } +end + +local commands = { + eval = function(target, from, code) + code = code:gsub("^=", "return ") + local fn, err = loadstring(code) + if not fn then + irc.say(target, from .. ": Error loading code: " .. code .. err:match(".*(:.-)$")) + return + else + setfenv(fn, envs[from]) + local result = {pcall(fn)} + local success = table.remove(result, 1) + if not success then + irc.say(target, from .. ": Error running code: " .. code .. result[1]:match(".*(:.-)$")) + else + if result[1] == nil then + irc.say(target, from .. ": nil") + else + irc.say(target, from .. ": " .. table.concat(result, ", ")) + end + end + end + end, + clear = function(target, from) + irc.say(target, from .. ": Clearing your environment") + envs[from] = create_env() + end, + help = function(target, from, arg) + if arg == "" or not arg then + irc.say(target, from .. ": Commands: !clear, !eval, !help") + elseif arg == "eval" then + irc.say(target, from .. ": Evaluates a Lua statement in your own persistent environment") + elseif arg == "clear" then + irc.say(target, from .. ": Clears your personal environment") + end + end +} + +irc.register_callback("connect", function() + irc.join("#doytest") +end) + +irc.register_callback("channel_msg", function(channel, from, message) + message = message:gsub("^" .. nick .. "[:,>] ", "!eval ") + local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$") + if is_cmd and commands[cmd] then + envs[from] = envs[from] or create_env() + commands[cmd](channel.name, from, arg) + end +end) + +irc.register_callback("private_msg", function(from, message) + message = message:gsub("^" .. nick .. "[:,>] ", "!eval ") + local is_cmd, cmd, arg = message:match("^(!)([%w_]+) ?(.-)$") + envs[from] = envs[from] or create_env() + if is_cmd and commands[cmd] then + commands[cmd](from, from, arg) + else + commands["eval"](from, from, message) + end +end) + +irc.register_callback("nick_change", function(from, old_nick) + if envs[old_nick] and not envs[from] then + envs[from] = envs[old_nick] + envs[old_nick] = nil + end +end) + +irc.connect{network = "irc.freenode.net", nick = nick, pass = "doylua"} diff --git a/etc/tests/luairc/test.lua b/etc/tests/luairc/test.lua new file mode 100755 index 0000000..865c5bc --- /dev/null +++ b/etc/tests/luairc/test.lua @@ -0,0 +1,228 @@ +#!/usr/bin/lua + +local irc = require "irc" +local dcc = require "irc.dcc" + +irc.DEBUG = true + +local ip_prog = io.popen("get_ip") +local ip = ip_prog:read() +ip_prog:close() +irc.set_ip(ip) + +local function print_state() + for chan in irc.channels() do + print(chan..": Channel ops: "..table.concat(chan:ops(), " ")) + print(chan..": Channel voices: "..table.concat(chan:voices(), " ")) + print(chan..": Channel normal users: "..table.concat(chan:users(), " ")) + print(chan..": All channel members: "..table.concat(chan:members(), " ")) + end +end + +local function on_connect() + print("Joining channel #doytest...") + irc.join("#doytest") + print("Joining channel #doytest2...") + irc.join("#doytest2") +end +irc.register_callback("connect", on_connect) + +local function on_me_join(chan) + print("Join to " .. chan .. " complete.") + print(chan .. ": Channel type: " .. chan.chanmode) + if chan.topic.text and chan.topic.text ~= "" then + print(chan .. ": Channel topic: " .. chan.topic.text) + print(" Set by " .. chan.topic.user .. + " at " .. os.date("%c", chan.topic.time)) + end + irc.act(chan.name, "is here") + print_state() +end +irc.register_callback("me_join", on_me_join) + +local function on_join(chan, user) + print("I saw a join to " .. chan) + if tostring(user) ~= "doylua" then + irc.say(tostring(chan), "Hi, " .. user) + end + print_state() +end +irc.register_callback("join", on_join) + +local function on_part(chan, user, part_msg) + print("I saw a part from " .. chan .. " saying " .. part_msg) + print_state() +end +irc.register_callback("part", on_part) + +local function on_nick_change(new_nick, old_nick) + print("I saw a nick change: " .. old_nick .. " -> " .. new_nick) + print_state() +end +irc.register_callback("nick_change", on_nick_change) + +local function on_kick(chan, user) + print("I saw a kick in " .. chan) + print_state() +end +irc.register_callback("kick", on_kick) + +local function on_quit(chan, user) + print("I saw a quit from " .. chan) + print_state() +end +irc.register_callback("quit", on_quit) + +local function whois_cb(cb_data) + print("WHOIS data for " .. cb_data.nick) + if cb_data.user then print("Username: " .. cb_data.user) end + if cb_data.host then print("Host: " .. cb_data.host) end + if cb_data.realname then print("Realname: " .. cb_data.realname) end + if cb_data.server then print("Server: " .. cb_data.server) end + if cb_data.serverinfo then print("Serverinfo: " .. cb_data.serverinfo) end + if cb_data.away_msg then print("Awaymsg: " .. cb_data.away_msg) end + if cb_data.is_oper then print(nick .. "is an IRCop") end + if cb_data.idle_time then print("Idletime: " .. cb_data.idle_time) end + if cb_data.channels then + print("Channel list for " .. cb_data.nick .. ":") + for _, channel in ipairs(cb_data.channels) do print(channel) end + end +end + +local function serverversion_cb(cb_data) + print("VERSION data for " .. cb_data.server) + print("Version: " .. cb_data.version) + print("Comments: " .. cb_data.comments) +end + +local function ping_cb(cb_data) + print("CTCP PING for " .. cb_data.nick) + print("Roundtrip time: " .. cb_data.time .. "s") +end + +local function time_cb(cb_data) + print("CTCP TIME for " .. cb_data.nick) + print("Localtime: " .. cb_data.time) +end + +local function version_cb(cb_data) + print("CTCP VERSION for " .. cb_data.nick) + print("Version: " .. cb_data.version) +end + +local function stime_cb(cb_data) + print("TIME for " .. cb_data.server) + print("Server time: " .. cb_data.time) +end + +local function on_channel_msg(chan, from, msg) + if from == "doy" then + if msg == "leave" then + irc.part(chan.name) + return + elseif msg:sub(1, 3) == "op " then + chan:op(msg:sub(4)) + return + elseif msg:sub(1, 5) == "deop " then + chan:deop(msg:sub(6)) + return + elseif msg:sub(1, 6) == "voice " then + chan:voice(msg:sub(7)) + return + elseif msg:sub(1, 8) == "devoice " then + chan:devoice(msg:sub(9)) + return + elseif msg:sub(1, 5) == "kick " then + chan:kick(msg:sub(6)) + return + elseif msg:sub(1, 5) == "send " then + dcc.send(from, msg:sub(6)) + return + elseif msg:sub(1, 6) == "whois " then + irc.whois(whois_cb, msg:sub(7)) + return + elseif msg:sub(1, 8) == "sversion" then + irc.server_version(serverversion_cb) + return + elseif msg:sub(1, 5) == "ping " then + irc.ctcp_ping(ping_cb, msg:sub(6)) + return + elseif msg:sub(1, 5) == "time " then + irc.ctcp_time(time_cb, msg:sub(6)) + return + elseif msg:sub(1, 8) == "version " then + irc.ctcp_version(version_cb, msg:sub(9)) + return + elseif msg:sub(1, 5) == "stime" then + irc.server_time(stime_cb) + return + elseif msg:sub(1, 6) == "trace " then + irc.trace(trace_cb, msg:sub(7)) + return + elseif msg:sub(1, 5) == "trace" then + irc.trace(trace_cb) + return + end + end + if from ~= "doylua" then + irc.say(chan.name, from .. ": " .. msg) + end +end +irc.register_callback("channel_msg", on_channel_msg) + +local function on_private_msg(from, msg) + if from == "doy" then + if msg == "leave" then + irc.quit("gone") + return + elseif msg:sub(1, 5) == "send " then + dcc.send(from, msg:sub(6)) + return + end + end + if from ~= "doylua" then + irc.say(from, msg) + end +end +irc.register_callback("private_msg", on_private_msg) + +local function on_channel_act(chan, from, msg) + irc.act(chan.name, "jumps on " .. from) +end +irc.register_callback("channel_act", on_channel_act) + +local function on_private_act(from, msg) + irc.act(from, "jumps on you") +end +irc.register_callback("private_act", on_private_act) + +local function on_op(chan, from, nick) + print(nick .. " was opped in " .. chan .. " by " .. from) + print_state() +end +irc.register_callback("op", on_op) + +local function on_deop(chan, from, nick) + print(nick .. " was deopped in " .. chan .. " by " .. from) + print_state() +end +irc.register_callback("deop", on_deop) + +local function on_voice(chan, from, nick) + print(nick .. " was voiced in " .. chan .. " by " .. from) + print_state() +end +irc.register_callback("voice", on_voice) + +local function on_devoice(chan, from, nick) + print(nick .. " was devoiced in " .. chan .. " by " .. from) + print_state() +end +irc.register_callback("devoice", on_devoice) + +local function on_dcc_send() + return true +end +irc.register_callback("dcc_send", on_dcc_send) + +irc.connect{network = "irc.freenode.net", nick = "doylua"} diff --git a/etc/tests/luasocket/README b/etc/tests/luasocket/README new file mode 100644 index 0000000..180fa27 --- /dev/null +++ b/etc/tests/luasocket/README @@ -0,0 +1,12 @@ +This provides the automated test scripts used to make sure the library +is working properly. + +The files provided are: + + testsrvr.lua -- test server + testclnt.lua -- test client + +To run these tests, just run lua on the server and then on the client. + +Good luck, +Diego. diff --git a/etc/tests/luasocket/testclnt.lua b/etc/tests/luasocket/testclnt.lua new file mode 100644 index 0000000..cf71c9f --- /dev/null +++ b/etc/tests/luasocket/testclnt.lua @@ -0,0 +1,655 @@ +local socket = require"socket" + +host = host or "localhost" +port = port or "8383" + +function pass(...) + local s = string.format(unpack(arg)) + io.stderr:write(s, "\n") +end + +function fail(...) + local s = string.format(unpack(arg)) + io.stderr:write("ERROR: ", s, "!\n") +socket.sleep(3) + os.exit() +end + +function warn(...) + local s = string.format(unpack(arg)) + io.stderr:write("WARNING: ", s, "\n") +end + +function remote(...) + local s = string.format(unpack(arg)) + s = string.gsub(s, "\n", ";") + s = string.gsub(s, "%s+", " ") + s = string.gsub(s, "^%s*", "") + control:send(s .. "\n") + control:receive() +end + +function test(test) + io.stderr:write("----------------------------------------------\n", + "testing: ", test, "\n", + "----------------------------------------------\n") +end + +function check_timeout(tm, sl, elapsed, err, opp, mode, alldone) + if tm < sl then + if opp == "send" then + if not err then warn("must be buffered") + elseif err == "timeout" then pass("proper timeout") + else fail("unexpected error '%s'", err) end + else + if err ~= "timeout" then fail("should have timed out") + else pass("proper timeout") end + end + else + if mode == "total" then + if elapsed > tm then + if err ~= "timeout" then fail("should have timed out") + else pass("proper timeout") end + elseif elapsed < tm then + if err then fail(err) + else pass("ok") end + else + if alldone then + if err then fail("unexpected error '%s'", err) + else pass("ok") end + else + if err ~= "timeout" then fail(err) + else pass("proper timeoutk") end + end + end + else + if err then fail(err) + else pass("ok") end + end + end +end + +if not socket._DEBUG then + fail("Please define LUASOCKET_DEBUG and recompile LuaSocket") +end + +io.stderr:write("----------------------------------------------\n", +"LuaSocket Test Procedures\n", +"----------------------------------------------\n") + +start = socket.gettime() + +function reconnect() + io.stderr:write("attempting data connection... ") + if data then data:close() end + remote [[ + if data then data:close() data = nil end + data = server:accept() + data:setoption("tcp-nodelay", true) + ]] + data, err = socket.connect(host, port) + if not data then fail(err) + else pass("connected!") end + data:setoption("tcp-nodelay", true) +end + +pass("attempting control connection...") +control, err = socket.connect(host, port) +if err then fail(err) +else pass("connected!") end +control:setoption("tcp-nodelay", true) + +------------------------------------------------------------------------ +function test_methods(sock, methods) + for _, v in methods do + if type(sock[v]) ~= "function" then + fail(sock.class .. " method '" .. v .. "' not registered") + end + end + pass(sock.class .. " methods are ok") +end + +------------------------------------------------------------------------ +function test_mixed(len) + reconnect() + local inter = math.ceil(len/4) + local p1 = "unix " .. string.rep("x", inter) .. "line\n" + local p2 = "dos " .. string.rep("y", inter) .. "line\r\n" + local p3 = "raw " .. string.rep("z", inter) .. "bytes" + local p4 = "end" .. string.rep("w", inter) .. "bytes" + local bp1, bp2, bp3, bp4 +remote (string.format("str = data:receive(%d)", + string.len(p1)+string.len(p2)+string.len(p3)+string.len(p4))) + sent, err = data:send(p1..p2..p3..p4) + if err then fail(err) end +remote "data:send(str); data:close()" + bp1, err = data:receive() + if err then fail(err) end + bp2, err = data:receive() + if err then fail(err) end + bp3, err = data:receive(string.len(p3)) + if err then fail(err) end + bp4, err = data:receive("*a") + if err then fail(err) end + if bp1.."\n" == p1 and bp2.."\r\n" == p2 and bp3 == p3 and bp4 == p4 then + pass("patterns match") + else fail("patterns don't match") end +end + +------------------------------------------------------------------------ +function test_asciiline(len) + reconnect() + local str, str10, back, err + str = string.rep("x", math.mod(len, 10)) + str10 = string.rep("aZb.c#dAe?", math.floor(len/10)) + str = str .. str10 +remote "str = data:receive()" + sent, err = data:send(str.."\n") + if err then fail(err) end +remote "data:send(str ..'\\n')" + back, err = data:receive() + if err then fail(err) end + if back == str then pass("lines match") + else fail("lines don't match") end +end + +------------------------------------------------------------------------ +function test_rawline(len) + reconnect() + local str, str10, back, err + str = string.rep(string.char(47), math.mod(len, 10)) + str10 = string.rep(string.char(120,21,77,4,5,0,7,36,44,100), + math.floor(len/10)) + str = str .. str10 +remote "str = data:receive()" + sent, err = data:send(str.."\n") + if err then fail(err) end +remote "data:send(str..'\\n')" + back, err = data:receive() + if err then fail(err) end + if back == str then pass("lines match") + else fail("lines don't match") end +end + +------------------------------------------------------------------------ +function test_raw(len) + reconnect() + local half = math.floor(len/2) + local s1, s2, back, err + s1 = string.rep("x", half) + s2 = string.rep("y", len-half) +remote (string.format("str = data:receive(%d)", len)) + sent, err = data:send(s1) + if err then fail(err) end + sent, err = data:send(s2) + if err then fail(err) end +remote "data:send(str)" + back, err = data:receive(len) + if err then fail(err) end + if back == s1..s2 then pass("blocks match") + else fail("blocks don't match") end +end + +------------------------------------------------------------------------ +function test_totaltimeoutreceive(len, tm, sl) + reconnect() + local str, err, partial + pass("%d bytes, %ds total timeout, %ds pause", len, tm, sl) + remote (string.format ([[ + data:settimeout(%d) + str = string.rep('a', %d) + data:send(str) + print('server: sleeping for %ds') + socket.sleep(%d) + print('server: woke up') + data:send(str) + ]], 2*tm, len, sl, sl)) + data:settimeout(tm, "total") +local t = socket.gettime() + str, err, partial, elapsed = data:receive(2*len) + check_timeout(tm, sl, elapsed, err, "receive", "total", + string.len(str or partial) == 2*len) +end + +------------------------------------------------------------------------ +function test_totaltimeoutsend(len, tm, sl) + reconnect() + local str, err, total + pass("%d bytes, %ds total timeout, %ds pause", len, tm, sl) + remote (string.format ([[ + data:settimeout(%d) + str = data:receive(%d) + print('server: sleeping for %ds') + socket.sleep(%d) + print('server: woke up') + str = data:receive(%d) + ]], 2*tm, len, sl, sl, len)) + data:settimeout(tm, "total") + str = string.rep("a", 2*len) + total, err, partial, elapsed = data:send(str) + check_timeout(tm, sl, elapsed, err, "send", "total", + total == 2*len) +end + +------------------------------------------------------------------------ +function test_blockingtimeoutreceive(len, tm, sl) + reconnect() + local str, err, partial + pass("%d bytes, %ds blocking timeout, %ds pause", len, tm, sl) + remote (string.format ([[ + data:settimeout(%d) + str = string.rep('a', %d) + data:send(str) + print('server: sleeping for %ds') + socket.sleep(%d) + print('server: woke up') + data:send(str) + ]], 2*tm, len, sl, sl)) + data:settimeout(tm) + str, err, partial, elapsed = data:receive(2*len) + check_timeout(tm, sl, elapsed, err, "receive", "blocking", + string.len(str or partial) == 2*len) +end + +------------------------------------------------------------------------ +function test_blockingtimeoutsend(len, tm, sl) + reconnect() + local str, err, total + pass("%d bytes, %ds blocking timeout, %ds pause", len, tm, sl) + remote (string.format ([[ + data:settimeout(%d) + str = data:receive(%d) + print('server: sleeping for %ds') + socket.sleep(%d) + print('server: woke up') + str = data:receive(%d) + ]], 2*tm, len, sl, sl, len)) + data:settimeout(tm) + str = string.rep("a", 2*len) + total, err, partial, elapsed = data:send(str) + check_timeout(tm, sl, elapsed, err, "send", "blocking", + total == 2*len) +end + +------------------------------------------------------------------------ +function empty_connect() + reconnect() + if data then data:close() data = nil end + remote [[ + if data then data:close() data = nil end + data = server:accept() + ]] + data, err = socket.connect("", port) + if not data then + pass("ok") + data = socket.connect(host, port) + else + pass("gethostbyname returns localhost on empty string...") + end +end + +------------------------------------------------------------------------ +function isclosed(c) + return c:getfd() == -1 or c:getfd() == (2^32-1) +end + +function active_close() + reconnect() + if isclosed(data) then fail("should not be closed") end + data:close() + if not isclosed(data) then fail("should be closed") end + data = nil + local udp = socket.udp() + if isclosed(udp) then fail("should not be closed") end + udp:close() + if not isclosed(udp) then fail("should be closed") end + pass("ok") +end + +------------------------------------------------------------------------ +function test_closed() + local back, partial, err + local str = 'little string' + reconnect() + pass("trying read detection") + remote (string.format ([[ + data:send('%s') + data:close() + data = nil + ]], str)) + -- try to get a line + back, err, partial = data:receive() + if not err then fail("should have gotten 'closed'.") + elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.") + elseif str ~= partial then fail("didn't receive partial result.") + else pass("graceful 'closed' received") end + reconnect() + pass("trying write detection") + remote [[ + data:close() + data = nil + ]] + total, err, partial = data:send(string.rep("ugauga", 100000)) + if not err then + pass("failed: output buffer is at least %d bytes long!", total) + elseif err ~= "closed" then + fail("got '"..err.."' instead of 'closed'.") + else + pass("graceful 'closed' received after %d bytes were sent", partial) + end +end + +------------------------------------------------------------------------ +function test_selectbugs() + local r, s, e = socket.select(nil, nil, 0.1) + assert(type(r) == "table" and type(s) == "table" and + (e == "timeout" or e == "error")) + pass("both nil: ok") + local udp = socket.udp() + udp:close() + r, s, e = socket.select({ udp }, { udp }, 0.1) + assert(type(r) == "table" and type(s) == "table" and + (e == "timeout" or e == "error")) + pass("closed sockets: ok") + e = pcall(socket.select, "wrong", 1, 0.1) + assert(e == false) + e = pcall(socket.select, {}, 1, 0.1) + assert(e == false) + pass("invalid input: ok") +end + +------------------------------------------------------------------------ +function accept_timeout() + io.stderr:write("accept with timeout (if it hangs, it failed): ") + local s, e = socket.bind("*", 0, 0) + assert(s, e) + local t = socket.gettime() + s:settimeout(1) + local c, e = s:accept() + assert(not c, "should not accept") + assert(e == "timeout", string.format("wrong error message (%s)", e)) + t = socket.gettime() - t + assert(t < 2, string.format("took to long to give up (%gs)", t)) + s:close() + pass("good") +end + +------------------------------------------------------------------------ +function connect_timeout() + io.stderr:write("connect with timeout (if it hangs, it failed!): ") + local t = socket.gettime() + local c, e = socket.tcp() + assert(c, e) + c:settimeout(0.1) + local t = socket.gettime() + local r, e = c:connect("10.0.0.1", 81) +print(r, e) + assert(not r, "should not connect") + assert(socket.gettime() - t < 2, "took too long to give up.") + c:close() + print("ok") +end + +------------------------------------------------------------------------ +function accept_errors() + io.stderr:write("not listening: ") + local d, e = socket.bind("*", 0) + assert(d, e); + local c, e = socket.tcp(); + assert(c, e); + d:setfd(c:getfd()) + d:settimeout(2) + local r, e = d:accept() + assert(not r and e) + print("ok: ", e) + io.stderr:write("not supported: ") + local c, e = socket.udp() + assert(c, e); + d:setfd(c:getfd()) + local r, e = d:accept() + assert(not r and e) + print("ok: ", e) +end + +------------------------------------------------------------------------ +function connect_errors() + io.stderr:write("connection refused: ") + local c, e = socket.connect("localhost", 1); + assert(not c and e) + print("ok: ", e) + io.stderr:write("host not found: ") + local c, e = socket.connect("host.is.invalid", 1); + assert(not c and e, e) + print("ok: ", e) +end + +------------------------------------------------------------------------ +function rebind_test() + local c = socket.bind("localhost", 0) + local i, p = c:getsockname() + local s, e = socket.tcp() + assert(s, e) + s:setoption("reuseaddr", false) + r, e = s:bind("localhost", p) + assert(not r, "managed to rebind!") + assert(e) + print("ok: ", e) +end + +------------------------------------------------------------------------ +function getstats_test() + reconnect() + local t = 0 + for i = 1, 25 do + local c = math.random(1, 100) + remote (string.format ([[ + str = data:receive(%d) + data:send(str) + ]], c)) + data:send(string.rep("a", c)) + data:receive(c) + t = t + c + local r, s, a = data:getstats() + assert(r == t, "received count failed" .. tostring(r) + .. "/" .. tostring(t)) + assert(s == t, "sent count failed" .. tostring(s) + .. "/" .. tostring(t)) + end + print("ok") +end + + +------------------------------------------------------------------------ +function test_nonblocking(size) + reconnect() +print("Testing " .. 2*size .. " bytes") +remote(string.format([[ + data:send(string.rep("a", %d)) + socket.sleep(0.5) + data:send(string.rep("b", %d) .. "\n") +]], size, size)) + local err = "timeout" + local part = "" + local str + data:settimeout(0) + while 1 do + str, err, part = data:receive("*l", part) + if err ~= "timeout" then break end + end + assert(str == (string.rep("a", size) .. string.rep("b", size))) + reconnect() +remote(string.format([[ + str = data:receive(%d) + socket.sleep(0.5) + str = data:receive(2*%d, str) + data:send(str) +]], size, size)) + data:settimeout(0) + local start = 0 + while 1 do + ret, err, start = data:send(str, start+1) + if err ~= "timeout" then break end + end + data:send("\n") + data:settimeout(-1) + local back = data:receive(2*size) + assert(back == str, "'" .. back .. "' vs '" .. str .. "'") + print("ok") +end + +------------------------------------------------------------------------ + + +test("method registration") +test_methods(socket.tcp(), { + "accept", + "bind", + "close", + "connect", + "dirty", + "getfd", + "getpeername", + "getsockname", + "getstats", + "setstats", + "listen", + "receive", + "send", + "setfd", + "setoption", + "setpeername", + "setsockname", + "settimeout", + "shutdown", +}) + +test_methods(socket.udp(), { + "close", + "getpeername", + "dirty", + "getfd", + "getpeername", + "getsockname", + "receive", + "receivefrom", + "send", + "sendto", + "setfd", + "setoption", + "setpeername", + "setsockname", + "settimeout" +}) + +test("select function") +test_selectbugs() + +test("connect function") +connect_timeout() +empty_connect() +connect_errors() + +test("rebinding: ") +rebind_test() + +test("active close: ") +active_close() + +test("closed connection detection: ") +test_closed() + +test("accept function: ") +accept_timeout() +accept_errors() + +test("getstats test") +getstats_test() + +test("character line") +test_asciiline(1) +test_asciiline(17) +test_asciiline(200) +test_asciiline(4091) +test_asciiline(80199) +test_asciiline(8000000) +test_asciiline(80199) +test_asciiline(4091) +test_asciiline(200) +test_asciiline(17) +test_asciiline(1) + +test("mixed patterns") +test_mixed(1) +test_mixed(17) +test_mixed(200) +test_mixed(4091) +test_mixed(801990) +test_mixed(4091) +test_mixed(200) +test_mixed(17) +test_mixed(1) + +test("binary line") +test_rawline(1) +test_rawline(17) +test_rawline(200) +test_rawline(4091) +test_rawline(80199) +test_rawline(8000000) +test_rawline(80199) +test_rawline(4091) +test_rawline(200) +test_rawline(17) +test_rawline(1) + +test("raw transfer") +test_raw(1) +test_raw(17) +test_raw(200) +test_raw(4091) +test_raw(80199) +test_raw(8000000) +test_raw(80199) +test_raw(4091) +test_raw(200) +test_raw(17) +test_raw(1) + +test("non-blocking transfer") +test_nonblocking(1) +test_nonblocking(17) +test_nonblocking(200) +test_nonblocking(4091) +test_nonblocking(80199) +test_nonblocking(800000) +test_nonblocking(80199) +test_nonblocking(4091) +test_nonblocking(200) +test_nonblocking(17) +test_nonblocking(1) + +test("total timeout on send") +test_totaltimeoutsend(800091, 1, 3) +test_totaltimeoutsend(800091, 2, 3) +test_totaltimeoutsend(800091, 5, 2) +test_totaltimeoutsend(800091, 3, 1) + +test("total timeout on receive") +test_totaltimeoutreceive(800091, 1, 3) +test_totaltimeoutreceive(800091, 2, 3) +test_totaltimeoutreceive(800091, 3, 2) +test_totaltimeoutreceive(800091, 3, 1) + +test("blocking timeout on send") +test_blockingtimeoutsend(800091, 1, 3) +test_blockingtimeoutsend(800091, 2, 3) +test_blockingtimeoutsend(800091, 3, 2) +test_blockingtimeoutsend(800091, 3, 1) + +test("blocking timeout on receive") +test_blockingtimeoutreceive(800091, 1, 3) +test_blockingtimeoutreceive(800091, 2, 3) +test_blockingtimeoutreceive(800091, 3, 2) +test_blockingtimeoutreceive(800091, 3, 1) + +test(string.format("done in %.2fs", socket.gettime() - start)) diff --git a/etc/tests/luasocket/testsrvr.lua b/etc/tests/luasocket/testsrvr.lua new file mode 100644 index 0000000..f1972c2 --- /dev/null +++ b/etc/tests/luasocket/testsrvr.lua @@ -0,0 +1,15 @@ +socket = require("socket"); +host = host or "localhost"; +port = port or "8383"; +server = assert(socket.bind(host, port)); +ack = "\n"; +while 1 do + print("server: waiting for client connection..."); + control = assert(server:accept()); + while 1 do + command = assert(control:receive()); + assert(control:send(ack)); + print(command); + (loadstring(command))(); + end +end diff --git a/etc/tests/luasocket/testsupport.lua b/etc/tests/luasocket/testsupport.lua new file mode 100644 index 0000000..acad8f5 --- /dev/null +++ b/etc/tests/luasocket/testsupport.lua @@ -0,0 +1,37 @@ +function readfile(name) + local f = io.open(name, "rb") + if not f then return nil end + local s = f:read("*a") + f:close() + return s +end + +function similar(s1, s2) + return string.lower(string.gsub(s1 or "", "%s", "")) == + string.lower(string.gsub(s2 or "", "%s", "")) +end + +function fail(msg) + msg = msg or "failed" + error(msg, 2) +end + +function compare(input, output) + local original = readfile(input) + local recovered = readfile(output) + if original ~= recovered then fail("comparison failed") + else print("ok") end +end + +local G = _G +local set = rawset +local warn = print + +local setglobal = function(table, key, value) + warn("changed " .. key) + set(table, key, value) +end + +setmetatable(G, { + __newindex = setglobal +}) diff --git a/packmod.sh b/packmod.sh new file mode 100644 index 0000000..2a84d54 --- /dev/null +++ b/packmod.sh @@ -0,0 +1,71 @@ +#! /bin/sh + +echo "Detecting directories..."; +if [ -f "CMakeLists.txt" ]; then + srcdir="."; + bindir="Build"; +elif [ -f "../CMakeLists.txt" ]; then + srcdir=".."; + bindir="."; +else + echo "Error: Couldn't find CMakeLists.txt." >&2; + exit 1; +fi + +if [ -e "$bindir/src/luasocket/libluasocket.dll" ]; then + lib="$bindir/src/luasocket/libluasocket.dll; +elif [ -e "$bindir/src/luasocket/libluasocket.so" ]; then + lib="$bindir/src/luasocket/libluasocket.so; +else + echo "Error: Couldn't find luasocket lib." >&2; + echo " Did you compile before running this script?" >&2; + exit 1; +fi + +version="`cat "$srcdir/CMakeLists.txt" \ + | grep 'MINETEST_IRC_VERSION' \ + | sed -e 's/^set(MINETEST_IRC_VERSION \([^)]*\)/\1/'`"; + +mkdir "$srcdir/irc-$version"; + +files_luairc="\ +$srcdir/src/luairc/irc.lua +$srcdir/src/luairc/irc/channel.lua +$srcdir/src/luairc/irc/constants.lua +$srcdir/src/luairc/irc/ctcp.lua +$srcdir/src/luairc/irc/dcc.lua +$srcdir/src/luairc/irc/debug.lua +$srcdir/src/luairc/irc/message.lua +$srcdir/src/luairc/irc/misc.lua +"; + +files_luasocket="\ +$srcdir/src/luasocket/ftp.lua +$srcdir/src/luasocket/http.lua +$srcdir/src/luasocket/ltn12.lua +$srcdir/src/luasocket/mime.lua +$srcdir/src/luasocket/smtp.lua +$srcdir/src/luasocket/socket.lua +$srcdir/src/luasocket/tp.lua +$srcdir/src/luasocket/url.lua +$lib +"; + +files="\ +$srcdir/src/init.lua +$files_luairc +$files_luasocket +"; + +oIFS="$IFS"; +IFS=' +'; + +echo "Copying files..."; +for file in $files; do + IFS="$oIFS"; + cp "$file" "$srcdir/irc-$version/"; +done + +echo "Operation completed successfully!"; +exit 0; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..a2acd87 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,5 @@ + +# :mode=cmake:noTabs=true: + +add_subdirectory(lua) +add_subdirectory(luasocket) diff --git a/src/dummy.c b/src/dummy.c new file mode 100644 index 0000000..e69de29 diff --git a/src/init.lua b/src/init.lua new file mode 100644 index 0000000..6001bb3 --- /dev/null +++ b/src/init.lua @@ -0,0 +1,118 @@ + +-- IRC Mod for Minetest +-- (C) 2012 Diego Martínez +-- +-- This mod allows to tie a Minetest server to an IRC channel. +-- +-- This program is free software. It comes without any warranty, to +-- the extent permitted by applicable law. You can redistribute it +-- and/or modify it under the terms of the Do What The Fuck You Want +-- To Public License, Version 2, as published by Sam Hocevar. See +-- http://sam.zoy.org/wtfpl/COPYING for more details. +-- + +-- ************************* +-- ** BEGIN USER SETTINGS ** +-- ************************* + +-- Server to connect on joinplayer (string, default "irc.freenode.net") +local SERVER = "irc.freenode.net"; + +-- Channel to connect on joinplayer (string, default "#minetest-irc-testing") +local CHANNEL = "#minetest-irc-testing"; + +-- Time between chat updates in seconds (number, default 0.2). +local DTIME = 0.5; + +-- Enable debug output (boolean, default false) +local DEBUG = false; + +local SERVER_NICK = "mt_game"; + +-- *********************** +-- ** END USER SETTINGS ** +-- *********************** + +-- ********************************************************************** +-- ** DO NOT EDIT ANYTHING BELOW UNLESS YOU KNOW WHAT YOU ARE DOING!!! ** +-- ********************************************************************** + + +local MODPATH = minetest.get_modpath("irc"); + +package.path = MODPATH.."/?.lua;"..package.path; +package.cpath = MODPATH.."/lib?.so;"..MODPATH.."/?.dll;"..package.cpath; + +local irc = require 'irc'; + +irc.DEBUG = ((DEBUG and true) or false); + +-- This could be made local. +mt_irc = { + cur_time = 0; + buffered_messages = { }; +}; + +SERVER = (SERVER or "irc.freenode.net"); +CHANNEL = (CHANNEL or "#minetest-irc-testing"); +DTIME = (DTIME or 0.2); + +minetest.register_globalstep(function ( dtime ) + mt_irc.cur_time = mt_irc.cur_time + dtime; + if (mt_irc.cur_time >= DTIME) then + if (mt_irc.buffered_messages) then + for _, t in ipairs(mt_irc.buffered_messages) do + irc.say(CHANNEL, "<"..t.name.."> "..(t.message or "")); + end + mt_irc.buffered_messages = nil; + end + irc.poll(); + mt_irc.cur_time = mt_irc.cur_time - DTIME; + local plys = minetest.get_connected_players(); + if (#plys <= 0) then -- Just in case :) + irc.quit("Closing."); + end + end +end); + +minetest.register_on_joinplayer(function ( player ) + + print("PLAYER JOINED: "..player:get_player_name()); + minetest.chat_send_all("PLAYER JOINED: "..player:get_player_name()); + + irc.register_callback("connect", function ( ) + irc.join(CHANNEL); + end); + + irc.register_callback("channel_msg", function ( channel, from, message ) + minetest.chat_send_all(from.."[IRC:"..channel.."]: "..message); + end); + + irc.register_callback("private_msg", function ( from, message ) + end); + + irc.register_callback("nick_change", function ( from, old_nick ) + end); + +end); + +minetest.register_on_leaveplayer(function ( player ) + irc.say(CHANNEL, "*** "..player:get_player_name().." left the game"); +end); + +minetest.register_on_chat_message(function ( name, message ) + if (not mt_irc.buffered_messages) then + mt_irc.buffered_messages = { }; + end + mt_irc.buffered_messages[#mt_irc.buffered_messages + 1] = { + name = name; + message = message; + }; +end); + +irc.connect({ + network = SERVER; + nick = SERVER_NICK; + pass = "1234"; + timeout = 1.0; +}); diff --git a/src/lua/CMakeLists.txt b/src/lua/CMakeLists.txt new file mode 100644 index 0000000..1196374 --- /dev/null +++ b/src/lua/CMakeLists.txt @@ -0,0 +1,16 @@ + +# :mode=cmake:noTabs=true:tabSize=4: + +set(LUA_SRCS + lapi.c lcode.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 ldblib.c liolib.c lmathlib.c loslib.c ltablib.c + lstrlib.c loadlib.c linit.c +) + +add_library(lua_lib ${LUA_SRCS}) +set_target_properties(lua_lib + PROPERTIES + OUTPUT_NAME lua51-minetest-irc +) diff --git a/src/lua/lapi.c b/src/lua/lapi.c new file mode 100644 index 0000000..ce7bcf6 --- /dev/null +++ b/src/lua/lapi.c @@ -0,0 +1,1077 @@ +/* +** $Id: lapi.c,v 2.53 2006/01/10 12:50:00 roberto Exp $ +** Lua API +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include + +#define lapi_c +#define LUA_CORE + +#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[] = + "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n" + "$Authors: " LUA_AUTHORS " $\n" + "$URL: www.lua.org $\n"; + + + +#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base)) + +#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject) + +#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;} + + + +static TValue *index2adr (lua_State *L, int idx) { + if (idx > 0) { + TValue *o = L->base + (idx - 1); + api_check(L, idx <= L->ci->top - L->base); + if (o >= L->top) return cast(TValue *, luaO_nilobject); + else return o; + } + else if (idx > LUA_REGISTRYINDEX) { + api_check(L, idx != 0 && -idx <= L->top - L->base); + return L->top + idx; + } + else switch (idx) { /* pseudo-indices */ + case LUA_REGISTRYINDEX: return registry(L); + case LUA_ENVIRONINDEX: { + Closure *func = curr_func(L); + sethvalue(L, &L->env, func->c.env); + return &L->env; + } + case LUA_GLOBALSINDEX: return gt(L); + default: { + Closure *func = curr_func(L); + idx = LUA_GLOBALSINDEX - idx; + return (idx <= func->c.nupvalues) + ? &func->c.upvalue[idx-1] + : cast(TValue *, luaO_nilobject); + } + } +} + + +static Table *getcurrenv (lua_State *L) { + if (L->ci == L->base_ci) /* no enclosing function? */ + return hvalue(gt(L)); /* use global table as environment */ + else { + Closure *func = curr_func(L); + return func->c.env; + } +} + + +void luaA_pushobject (lua_State *L, const TValue *o) { + setobj2s(L, L->top, o); + api_incr_top(L); +} + + +LUA_API int lua_checkstack (lua_State *L, int size) { + int res; + lua_lock(L); + if ((L->top - L->base + size) > LUAI_MAXCSTACK) + res = 0; /* stack overflow */ + else { + luaD_checkstack(L, size); + if (L->ci->top < L->top + size) + L->ci->top = L->top + size; + res = 1; + } + 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)); + api_check(from, to->ci->top - to->top >= n); + from->top -= n; + for (i = 0; i < n; i++) { + setobj2s(to, to->top++, from->top + i); + } + 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_State *lua_newthread (lua_State *L) { + lua_State *L1; + lua_lock(L); + luaC_checkGC(L); + L1 = luaE_newthread(L); + setthvalue(L, L->top, L1); + api_incr_top(L); + lua_unlock(L); + luai_userstatethread(L, L1); + return L1; +} + + + +/* +** basic stack manipulation +*/ + + +LUA_API int lua_gettop (lua_State *L) { + return cast_int(L->top - L->base); +} + + +LUA_API void lua_settop (lua_State *L, int idx) { + lua_lock(L); + if (idx >= 0) { + api_check(L, idx <= L->stack_last - L->base); + while (L->top < L->base + idx) + setnilvalue(L->top++); + L->top = L->base + idx; + } + else { + api_check(L, -(idx+1) <= (L->top - L->base)); + L->top += idx+1; /* `subtract' index (index is negative) */ + } + lua_unlock(L); +} + + +LUA_API void lua_remove (lua_State *L, int idx) { + StkId p; + lua_lock(L); + p = index2adr(L, idx); + api_checkvalidindex(L, p); + while (++p < L->top) setobjs2s(L, p-1, p); + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_insert (lua_State *L, int idx) { + StkId p; + StkId q; + lua_lock(L); + p = index2adr(L, idx); + api_checkvalidindex(L, p); + for (q = L->top; q>p; q--) setobjs2s(L, q, q-1); + setobjs2s(L, p, L->top); + lua_unlock(L); +} + + +LUA_API void lua_replace (lua_State *L, int idx) { + StkId o; + lua_lock(L); + api_checknelems(L, 1); + o = index2adr(L, idx); + api_checkvalidindex(L, o); + if (idx == LUA_ENVIRONINDEX) { + Closure *func = curr_func(L); + api_check(L, ttistable(L->top - 1)); + func->c.env = hvalue(L->top - 1); + luaC_barrier(L, func, L->top - 1); + } + else { + setobj(L, o, L->top - 1); + if (idx < LUA_GLOBALSINDEX) /* function upvalue? */ + luaC_barrier(L, curr_func(L), L->top - 1); + } + L->top--; + lua_unlock(L); +} + + +LUA_API void lua_pushvalue (lua_State *L, int idx) { + lua_lock(L); + setobj2s(L, L->top, index2adr(L, idx)); + api_incr_top(L); + lua_unlock(L); +} + + + +/* +** access functions (stack -> C) +*/ + + +LUA_API int lua_type (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); +} + + +LUA_API const char *lua_typename (lua_State *L, int t) { + UNUSED(L); + return (t == LUA_TNONE) ? "no value" : luaT_typenames[t]; +} + + +LUA_API int lua_iscfunction (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + return iscfunction(o); +} + + +LUA_API int lua_isnumber (lua_State *L, int idx) { + TValue n; + const TValue *o = index2adr(L, idx); + return tonumber(o, &n); +} + + +LUA_API int lua_isstring (lua_State *L, int idx) { + int t = lua_type(L, idx); + return (t == LUA_TSTRING || t == LUA_TNUMBER); +} + + +LUA_API int lua_isuserdata (lua_State *L, int idx) { + const TValue *o = index2adr(L, idx); + return (ttisuserdata(o) || ttislightuserdata(o)); +} + + +LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { + StkId o1 = index2adr(L, index1); + StkId o2 = index2adr(L, index2); + return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 + : luaO_rawequalObj(o1, o2); +} + + +LUA_API int lua_equal (lua_State *L, int index1, int index2) { + StkId o1, o2; + int i; + lua_lock(L); /* may call tag method */ + o1 = index2adr(L, index1); + o2 = index2adr(L, index2); + i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); + lua_unlock(L); + return i; +} + + +LUA_API int lua_lessthan (lua_State *L, int index1, int index2) { + StkId o1, o2; + int i; + lua_lock(L); /* may call tag method */ + o1 = index2adr(L, index1); + o2 = index2adr(L, index2); + i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 + : luaV_lessthan(L, o1, o2); + lua_unlock(L); + return i; +} + + + +LUA_API lua_Number lua_tonumber (lua_State *L, int idx) { + TValue n; + const TValue *o = index2adr(L, idx); + if (tonumber(o, &n)) + return nvalue(o); + else + return 0; +} + + +LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) { + TValue n; + const TValue *o = index2adr(L, idx); + if (tonumber(o, &n)) { + lua_Integer res; + lua_Number num = nvalue(o); + lua_number2integer(res, num); + return res; + } + else + return 0; +} + + +LUA_API int lua_toboolean (lua_State *L, int idx) { + const TValue *o = index2adr(L, idx); + return !l_isfalse(o); +} + + +LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { + StkId o = index2adr(L, idx); + if (!ttisstring(o)) { + lua_lock(L); /* `luaV_tostring' may create a new string */ + if (!luaV_tostring(L, o)) { /* conversion failed? */ + if (len != NULL) *len = 0; + lua_unlock(L); + return NULL; + } + luaC_checkGC(L); + o = index2adr(L, idx); /* previous call may reallocate the stack */ + lua_unlock(L); + } + if (len != NULL) *len = tsvalue(o)->len; + return svalue(o); +} + + +LUA_API size_t lua_objlen (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + switch (ttype(o)) { + case LUA_TSTRING: return tsvalue(o)->len; + case LUA_TUSERDATA: return uvalue(o)->len; + case LUA_TTABLE: return luaH_getn(hvalue(o)); + case LUA_TNUMBER: { + size_t l; + lua_lock(L); /* `luaV_tostring' may create a new string */ + l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0); + lua_unlock(L); + return l; + } + default: return 0; + } +} + + +LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + return (!iscfunction(o)) ? NULL : clvalue(o)->c.f; +} + + +LUA_API void *lua_touserdata (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + switch (ttype(o)) { + case LUA_TUSERDATA: return (rawuvalue(o) + 1); + case LUA_TLIGHTUSERDATA: return pvalue(o); + default: return NULL; + } +} + + +LUA_API lua_State *lua_tothread (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + return (!ttisthread(o)) ? NULL : thvalue(o); +} + + +LUA_API const void *lua_topointer (lua_State *L, int idx) { + StkId o = index2adr(L, idx); + switch (ttype(o)) { + case LUA_TTABLE: return hvalue(o); + case LUA_TFUNCTION: return clvalue(o); + case LUA_TTHREAD: return thvalue(o); + case LUA_TUSERDATA: + case LUA_TLIGHTUSERDATA: + return lua_touserdata(L, idx); + default: return NULL; + } +} + + + +/* +** push functions (C -> stack) +*/ + + +LUA_API void lua_pushnil (lua_State *L) { + lua_lock(L); + setnilvalue(L->top); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { + lua_lock(L); + setnvalue(L->top, n); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { + lua_lock(L); + setnvalue(L->top, cast_num(n)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { + lua_lock(L); + luaC_checkGC(L); + setsvalue2s(L, L->top, luaS_newlstr(L, s, len)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushstring (lua_State *L, const char *s) { + if (s == NULL) + lua_pushnil(L); + else + lua_pushlstring(L, s, strlen(s)); +} + + +LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, + va_list argp) { + const char *ret; + lua_lock(L); + luaC_checkGC(L); + ret = luaO_pushvfstring(L, fmt, argp); + 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); + luaC_checkGC(L); + va_start(argp, fmt); + ret = luaO_pushvfstring(L, fmt, argp); + va_end(argp); + lua_unlock(L); + return ret; +} + + +LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { + Closure *cl; + lua_lock(L); + luaC_checkGC(L); + api_checknelems(L, n); + cl = luaF_newCclosure(L, n, getcurrenv(L)); + cl->c.f = fn; + L->top -= n; + while (n--) + setobj2n(L, &cl->c.upvalue[n], L->top+n); + setclvalue(L, L->top, cl); + lua_assert(iswhite(obj2gco(cl))); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushboolean (lua_State *L, int b) { + lua_lock(L); + setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { + lua_lock(L); + setpvalue(L->top, p); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API int lua_pushthread (lua_State *L) { + lua_lock(L); + setthvalue(L, L->top, L); + api_incr_top(L); + lua_unlock(L); + return (G(L)->mainthread == L); +} + + + +/* +** get functions (Lua -> stack) +*/ + + +LUA_API void lua_gettable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2adr(L, idx); + api_checkvalidindex(L, t); + luaV_gettable(L, t, L->top - 1, L->top - 1); + lua_unlock(L); +} + + +LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { + StkId t; + TValue key; + lua_lock(L); + t = index2adr(L, idx); + api_checkvalidindex(L, t); + setsvalue(L, &key, luaS_new(L, k)); + luaV_gettable(L, t, &key, L->top); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_rawget (lua_State *L, int idx) { + StkId t; + lua_lock(L); + t = index2adr(L, idx); + api_check(L, ttistable(t)); + setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); + lua_unlock(L); +} + + +LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { + StkId o; + lua_lock(L); + o = index2adr(L, idx); + api_check(L, ttistable(o)); + setobj2s(L, L->top, luaH_getnum(hvalue(o), n)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { + lua_lock(L); + luaC_checkGC(L); + sethvalue(L, L->top, luaH_new(L, narray, nrec)); + api_incr_top(L); + lua_unlock(L); +} + + +LUA_API int lua_getmetatable (lua_State *L, int objindex) { + const TValue *obj; + Table *mt = NULL; + int res; + lua_lock(L); + obj = index2adr(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) + res = 0; + else { + sethvalue(L, L->top, mt); + api_incr_top(L); + res = 1; + } + lua_unlock(L); + return res; +} + + +LUA_API void lua_getfenv (lua_State *L, int idx) { + StkId o; + lua_lock(L); + o = index2adr(L, idx); + api_checkvalidindex(L, o); + switch (ttype(o)) { + case LUA_TFUNCTION: + sethvalue(L, L->top, clvalue(o)->c.env); + break; + case LUA_TUSERDATA: + sethvalue(L, L->top, uvalue(o)->env); + break; + case LUA_TTHREAD: + setobj2s(L, L->top, gt(thvalue(o))); + break; + default: + setnilvalue(L->top); + break; + } + api_incr_top(L); + lua_unlock(L); +} + + +/* +** set functions (stack -> Lua) +*/ + + +LUA_API void lua_settable (lua_State *L, int idx) { + StkId t; + lua_lock(L); + api_checknelems(L, 2); + t = index2adr(L, idx); + api_checkvalidindex(L, t); + luaV_settable(L, t, L->top - 2, L->top - 1); + L->top -= 2; /* pop index and value */ + lua_unlock(L); +} + + +LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { + StkId t; + TValue key; + lua_lock(L); + api_checknelems(L, 1); + t = index2adr(L, idx); + api_checkvalidindex(L, t); + setsvalue(L, &key, luaS_new(L, k)); + luaV_settable(L, t, &key, L->top - 1); + L->top--; /* pop value */ + lua_unlock(L); +} + + +LUA_API void lua_rawset (lua_State *L, int idx) { + StkId t; + lua_lock(L); + api_checknelems(L, 2); + t = index2adr(L, idx); + api_check(L, ttistable(t)); + setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); + luaC_barriert(L, hvalue(t), L->top-1); + L->top -= 2; + lua_unlock(L); +} + + +LUA_API void lua_rawseti (lua_State *L, int idx, int n) { + StkId o; + lua_lock(L); + api_checknelems(L, 1); + o = index2adr(L, idx); + api_check(L, ttistable(o)); + setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1); + luaC_barriert(L, hvalue(o), L->top-1); + L->top--; + 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 = index2adr(L, objindex); + api_checkvalidindex(L, obj); + if (ttisnil(L->top - 1)) + mt = NULL; + else { + api_check(L, ttistable(L->top - 1)); + mt = hvalue(L->top - 1); + } + switch (ttype(obj)) { + case LUA_TTABLE: { + hvalue(obj)->metatable = mt; + if (mt) + luaC_objbarriert(L, hvalue(obj), mt); + break; + } + case LUA_TUSERDATA: { + uvalue(obj)->metatable = mt; + if (mt) + luaC_objbarrier(L, rawuvalue(obj), mt); + break; + } + default: { + G(L)->mt[ttype(obj)] = mt; + break; + } + } + L->top--; + lua_unlock(L); + return 1; +} + + +LUA_API int lua_setfenv (lua_State *L, int idx) { + StkId o; + int res = 1; + lua_lock(L); + api_checknelems(L, 1); + o = index2adr(L, idx); + api_checkvalidindex(L, o); + api_check(L, ttistable(L->top - 1)); + switch (ttype(o)) { + case LUA_TFUNCTION: + clvalue(o)->c.env = hvalue(L->top - 1); + break; + case LUA_TUSERDATA: + uvalue(o)->env = hvalue(L->top - 1); + break; + case LUA_TTHREAD: + sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1)); + break; + default: + res = 0; + break; + } + luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); + L->top--; + lua_unlock(L); + return res; +} + + +/* +** `load' and `call' functions (run Lua code) +*/ + + +#define adjustresults(L,nres) \ + { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; } + + +#define checkresults(L,na,nr) \ + api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na))) + + +LUA_API void lua_call (lua_State *L, int nargs, int nresults) { + StkId func; + lua_lock(L); + api_checknelems(L, nargs+1); + checkresults(L, nargs, nresults); + func = L->top - (nargs+1); + luaD_call(L, func, nresults); + 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_call(L, c->func, c->nresults); +} + + + +LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) { + struct CallS c; + int status; + ptrdiff_t func; + lua_lock(L); + api_checknelems(L, nargs+1); + checkresults(L, nargs, nresults); + if (errfunc == 0) + func = 0; + else { + StkId o = index2adr(L, errfunc); + api_checkvalidindex(L, o); + func = savestack(L, o); + } + c.func = L->top - (nargs+1); /* function to be called */ + c.nresults = nresults; + status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); + adjustresults(L, nresults); + lua_unlock(L); + return status; +} + + +/* +** Execute a protected C call. +*/ +struct CCallS { /* data to `f_Ccall' */ + lua_CFunction func; + void *ud; +}; + + +static void f_Ccall (lua_State *L, void *ud) { + struct CCallS *c = cast(struct CCallS *, ud); + Closure *cl; + cl = luaF_newCclosure(L, 0, getcurrenv(L)); + cl->c.f = c->func; + setclvalue(L, L->top, cl); /* push function */ + api_incr_top(L); + setpvalue(L->top, c->ud); /* push only argument */ + api_incr_top(L); + luaD_call(L, L->top - 2, 0); +} + + +LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) { + struct CCallS c; + int status; + lua_lock(L); + c.func = func; + c.ud = ud; + status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0); + lua_unlock(L); + return status; +} + + +LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, + const char *chunkname) { + ZIO z; + int status; + lua_lock(L); + if (!chunkname) chunkname = "?"; + luaZ_init(L, &z, reader, data); + status = luaD_protectedparser(L, &z, chunkname); + lua_unlock(L); + return status; +} + + +LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { + int status; + TValue *o; + lua_lock(L); + api_checknelems(L, 1); + o = L->top - 1; + if (isLfunction(o)) + status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0); + 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, int data) { + int res = 0; + global_State *g; + lua_lock(L); + g = G(L); + switch (what) { + case LUA_GCSTOP: { + g->GCthreshold = MAX_LUMEM; + break; + } + case LUA_GCRESTART: { + g->GCthreshold = g->totalbytes; + break; + } + case LUA_GCCOLLECT: { + luaC_fullgc(L); + break; + } + case LUA_GCCOUNT: { + /* GC values are expressed in Kbytes: #bytes/2^10 */ + res = cast_int(g->totalbytes >> 10); + break; + } + case LUA_GCCOUNTB: { + res = cast_int(g->totalbytes & 0x3ff); + break; + } + case LUA_GCSTEP: { + lu_mem a = (cast(lu_mem, data) << 10); + if (a <= g->totalbytes) + g->GCthreshold = g->totalbytes - a; + else + g->GCthreshold = 0; + while (g->GCthreshold <= g->totalbytes) + luaC_step(L); + if (g->gcstate == GCSpause) /* end of cycle? */ + res = 1; /* signal it */ + break; + } + case LUA_GCSETPAUSE: { + res = g->gcpause; + g->gcpause = data; + break; + } + case LUA_GCSETSTEPMUL: { + res = g->gcstepmul; + g->gcstepmul = data; + break; + } + default: res = -1; /* invalid option */ + } + lua_unlock(L); + return res; +} + + + +/* +** miscellaneous functions +*/ + + +LUA_API int lua_error (lua_State *L) { + lua_lock(L); + api_checknelems(L, 1); + luaG_errormsg(L); + lua_unlock(L); + return 0; /* to avoid warnings */ +} + + +LUA_API int lua_next (lua_State *L, int idx) { + StkId t; + int more; + lua_lock(L); + t = index2adr(L, idx); + api_check(L, ttistable(t)); + more = luaH_next(L, hvalue(t), L->top - 1); + if (more) { + api_incr_top(L); + } + else /* no more elements */ + L->top -= 1; /* remove key */ + lua_unlock(L); + return more; +} + + +LUA_API void lua_concat (lua_State *L, int n) { + lua_lock(L); + api_checknelems(L, n); + if (n >= 2) { + luaC_checkGC(L); + luaV_concat(L, n, cast_int(L->top - L->base) - 1); + L->top -= (n-1); + } + else if (n == 0) { /* push empty string */ + setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); + api_incr_top(L); + } + /* else n == 1; nothing to do */ + 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); +} + + +LUA_API void *lua_newuserdata (lua_State *L, size_t size) { + Udata *u; + lua_lock(L); + luaC_checkGC(L); + u = luaS_newudata(L, size, getcurrenv(L)); + setuvalue(L, L->top, u); + api_incr_top(L); + lua_unlock(L); + return u + 1; +} + + + + +static const char *aux_upvalue (StkId fi, int n, TValue **val) { + Closure *f; + if (!ttisfunction(fi)) return NULL; + f = clvalue(fi); + if (f->c.isC) { + if (!(1 <= n && n <= f->c.nupvalues)) return NULL; + *val = &f->c.upvalue[n-1]; + return ""; + } + else { + Proto *p = f->l.p; + if (!(1 <= n && n <= p->sizeupvalues)) return NULL; + *val = f->l.upvals[n-1]->v; + return getstr(p->upvalues[n-1]); + } +} + + +LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { + const char *name; + TValue *val; + lua_lock(L); + name = aux_upvalue(index2adr(L, funcindex), n, &val); + if (name) { + setobj2s(L, L->top, 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; + StkId fi; + lua_lock(L); + fi = index2adr(L, funcindex); + api_checknelems(L, 1); + name = aux_upvalue(fi, n, &val); + if (name) { + L->top--; + setobj(L, val, L->top); + luaC_barrier(L, clvalue(fi), L->top); + } + lua_unlock(L); + return name; +} + diff --git a/src/lua/lapi.h b/src/lua/lapi.h new file mode 100644 index 0000000..9d1d435 --- /dev/null +++ b/src/lua/lapi.h @@ -0,0 +1,16 @@ +/* +** $Id: lapi.h,v 2.2 2005/04/25 19:24:10 roberto Exp $ +** Auxiliary functions from Lua API +** See Copyright Notice in lua.h +*/ + +#ifndef lapi_h +#define lapi_h + + +#include "lobject.h" + + +LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o); + +#endif diff --git a/src/lua/lauxlib.c b/src/lua/lauxlib.c new file mode 100644 index 0000000..317a48d --- /dev/null +++ b/src/lua/lauxlib.c @@ -0,0 +1,647 @@ +/* +** $Id: lauxlib.c,v 1.158 2006/01/16 12:42:21 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#include +#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. +*/ + +#define lauxlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" + + +#define FREELIST_REF 0 /* free list of references */ + + +/* convert a stack index to positive */ +#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ + lua_gettop(L) + (i) + 1) + + +/* +** {====================================================== +** Error-report functions +** ======================================================= +*/ + + +LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { + lua_Debug ar; + if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ + return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); + lua_getinfo(L, "n", &ar); + if (strcmp(ar.namewhat, "method") == 0) { + narg--; /* do not count `self' */ + if (narg == 0) /* error is in the self argument itself? */ + return luaL_error(L, "calling " LUA_QS " on bad self (%s)", + ar.name, extramsg); + } + if (ar.name == NULL) + ar.name = "?"; + return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", + narg, ar.name, extramsg); +} + + +LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) { + const char *msg = lua_pushfstring(L, "%s expected, got %s", + tname, luaL_typename(L, narg)); + return luaL_argerror(L, narg, msg); +} + + +static void tag_error (lua_State *L, int narg, int tag) { + luaL_typerror(L, narg, lua_typename(L, tag)); +} + + +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_pushliteral(L, ""); /* else, no information available... */ +} + + +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_checkoption (lua_State *L, int narg, const char *def, + const char *const lst[]) { + const char *name = (def) ? luaL_optstring(L, narg, def) : + luaL_checkstring(L, narg); + int i; + for (i=0; lst[i]; i++) + if (strcmp(lst[i], name) == 0) + return i; + return luaL_argerror(L, narg, + lua_pushfstring(L, "invalid option " LUA_QS, name)); +} + + +LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { + lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ + if (!lua_isnil(L, -1)) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + lua_newtable(L); /* create metatable */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ + return 1; +} + + +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = lua_touserdata(L, ud); + lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ + if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2)) + luaL_typerror(L, ud, tname); + lua_pop(L, 2); /* remove both metatables */ + return p; +} + + +LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { + if (!lua_checkstack(L, space)) + luaL_error(L, "stack overflow (%s)", mes); +} + + +LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { + if (lua_type(L, narg) != t) + tag_error(L, narg, t); +} + + +LUALIB_API void luaL_checkany (lua_State *L, int narg) { + if (lua_type(L, narg) == LUA_TNONE) + luaL_argerror(L, narg, "value expected"); +} + + +LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { + const char *s = lua_tolstring(L, narg, len); + if (!s) tag_error(L, narg, LUA_TSTRING); + return s; +} + + +LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, + const char *def, size_t *len) { + if (lua_isnoneornil(L, narg)) { + if (len) + *len = (def ? strlen(def) : 0); + return def; + } + else return luaL_checklstring(L, narg, len); +} + + +LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { + lua_Number d = lua_tonumber(L, narg); + if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ + tag_error(L, narg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { + return luaL_opt(L, luaL_checknumber, narg, def); +} + + +LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { + lua_Integer d = lua_tointeger(L, narg); + if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ + tag_error(L, narg, LUA_TNUMBER); + return d; +} + + +LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, + lua_Integer def) { + return luaL_opt(L, luaL_checkinteger, narg, def); +} + + +LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { + if (!lua_getmetatable(L, obj)) /* no metatable? */ + return 0; + lua_pushstring(L, event); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { + lua_pop(L, 2); /* remove metatable and metafield */ + return 0; + } + else { + lua_remove(L, -2); /* remove only metatable */ + return 1; + } +} + + +LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { + obj = abs_index(L, obj); + if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ + return 0; + lua_pushvalue(L, obj); + lua_call(L, 1, 1); + return 1; +} + + +LUALIB_API void (luaL_register) (lua_State *L, const char *libname, + const luaL_Reg *l) { + luaI_openlib(L, libname, l, 0); +} + + +static int libsize (const luaL_Reg *l) { + int size = 0; + for (; l->name; l++) size++; + return size; +} + + +LUALIB_API void luaI_openlib (lua_State *L, const char *libname, + const luaL_Reg *l, int nup) { + if (libname) { + int size = libsize(l); + /* check whether lib already exists */ + luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", size); + lua_getfield(L, -1, libname); /* get _LOADED[libname] */ + if (!lua_istable(L, -1)) { /* not found? */ + lua_pop(L, 1); /* remove previous result */ + /* try global variable (and create one if it does not exist) */ + if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL) + luaL_error(L, "name conflict for module " LUA_QS, libname); + lua_pushvalue(L, -1); + lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */ + } + lua_remove(L, -2); /* remove _LOADED table */ + lua_insert(L, -(nup+1)); /* move library table to below upvalues */ + } + for (; l->name; l++) { + int i; + for (i=0; ifunc, nup); + lua_setfield(L, -(nup+2), l->name); + } + lua_pop(L, nup); /* remove upvalues */ +} + + + +/* +** {====================================================== +** getn-setn: size for arrays +** ======================================================= +*/ + +#if defined(LUA_COMPAT_GETN) + +static int checkint (lua_State *L, int topop) { + int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1; + lua_pop(L, topop); + return n; +} + + +static void getsizes (lua_State *L) { + lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); + if (lua_isnil(L, -1)) { /* no `size' table? */ + lua_pop(L, 1); /* remove nil */ + lua_newtable(L); /* create it */ + lua_pushvalue(L, -1); /* `size' will be its own metatable */ + lua_setmetatable(L, -2); + lua_pushliteral(L, "kv"); + lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */ + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */ + } +} + + +LUALIB_API void luaL_setn (lua_State *L, int t, int n) { + t = abs_index(L, t); + lua_pushliteral(L, "n"); + lua_rawget(L, t); + if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ + lua_pushliteral(L, "n"); /* use it */ + lua_pushinteger(L, n); + lua_rawset(L, t); + } + else { /* use `sizes' */ + getsizes(L); + lua_pushvalue(L, t); + lua_pushinteger(L, n); + lua_rawset(L, -3); /* sizes[t] = n */ + lua_pop(L, 1); /* remove `sizes' */ + } +} + + +LUALIB_API int luaL_getn (lua_State *L, int t) { + int n; + t = abs_index(L, t); + lua_pushliteral(L, "n"); /* try t.n */ + lua_rawget(L, t); + if ((n = checkint(L, 1)) >= 0) return n; + getsizes(L); /* else try sizes[t] */ + lua_pushvalue(L, t); + lua_rawget(L, -2); + if ((n = checkint(L, 2)) >= 0) return n; + return (int)lua_objlen(L, t); +} + +#endif + +/* }====================================================== */ + + + +LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, + const char *r) { + const char *wild; + size_t l = strlen(p); + luaL_Buffer b; + luaL_buffinit(L, &b); + 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 */ + luaL_pushresult(&b); + return lua_tostring(L, -1); +} + + +LUALIB_API const char *luaL_findtable (lua_State *L, int idx, + const char *fname, int szhint) { + const char *e; + lua_pushvalue(L, idx); + do { + e = strchr(fname, '.'); + if (e == NULL) e = fname + strlen(fname); + lua_pushlstring(L, fname, e - fname); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { /* no such field? */ + lua_pop(L, 1); /* remove this nil */ + lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ + lua_pushlstring(L, fname, e - fname); + lua_pushvalue(L, -2); + lua_settable(L, -4); /* set new table into field */ + } + else if (!lua_istable(L, -1)) { /* field has a non-table value? */ + lua_pop(L, 2); /* remove table and value */ + return fname; /* return problematic part of the name */ + } + lua_remove(L, -2); /* remove previous table */ + fname = e + 1; + } while (*e == '.'); + return NULL; +} + + + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + + +#define bufflen(B) ((B)->p - (B)->buffer) +#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B))) + +#define LIMIT (LUA_MINSTACK/2) + + +static int emptybuffer (luaL_Buffer *B) { + size_t l = bufflen(B); + if (l == 0) return 0; /* put nothing on stack */ + else { + lua_pushlstring(B->L, B->buffer, l); + B->p = B->buffer; + B->lvl++; + return 1; + } +} + + +static void adjuststack (luaL_Buffer *B) { + if (B->lvl > 1) { + lua_State *L = B->L; + int toget = 1; /* number of levels to concat */ + size_t toplen = lua_strlen(L, -1); + do { + size_t l = lua_strlen(L, -(toget+1)); + if (B->lvl - toget + 1 >= LIMIT || toplen > l) { + toplen += l; + toget++; + } + else break; + } while (toget < B->lvl); + lua_concat(L, toget); + B->lvl = B->lvl - toget + 1; + } +} + + +LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) { + if (emptybuffer(B)) + adjuststack(B); + return B->buffer; +} + + +LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { + while (l--) + luaL_addchar(B, *s++); +} + + +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) { + emptybuffer(B); + lua_concat(B->L, B->lvl); + B->lvl = 1; +} + + +LUALIB_API void luaL_addvalue (luaL_Buffer *B) { + lua_State *L = B->L; + size_t vl; + const char *s = lua_tolstring(L, -1, &vl); + if (vl <= bufffree(B)) { /* fit into buffer? */ + memcpy(B->p, s, vl); /* put it there */ + B->p += vl; + lua_pop(L, 1); /* remove from stack */ + } + else { + if (emptybuffer(B)) + lua_insert(L, -2); /* put buffer before new value */ + B->lvl++; /* add new value into B stack */ + adjuststack(B); + } +} + + +LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { + B->L = L; + B->p = B->buffer; + B->lvl = 0; +} + +/* }====================================================== */ + + +LUALIB_API int luaL_ref (lua_State *L, int t) { + int ref; + t = abs_index(L, t); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); /* remove from stack */ + return LUA_REFNIL; /* `nil' has a unique fixed reference */ + } + lua_rawgeti(L, t, FREELIST_REF); /* get first free element */ + ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */ + lua_pop(L, 1); /* remove it from stack */ + if (ref != 0) { /* any free element? */ + lua_rawgeti(L, t, ref); /* remove it from list */ + lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */ + } + else { /* no free elements */ + ref = (int)lua_objlen(L, t); + ref++; /* create 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 = abs_index(L, t); + lua_rawgeti(L, t, FREELIST_REF); + lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */ + lua_pushinteger(L, ref); + lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */ + } +} + + + +/* +** {====================================================== +** Load functions +** ======================================================= +*/ + +typedef struct LoadF { + int extraline; + FILE *f; + char buff[LUAL_BUFFERSIZE]; +} LoadF; + + +static const char *getF (lua_State *L, void *ud, size_t *size) { + LoadF *lf = (LoadF *)ud; + (void)L; + if (lf->extraline) { + lf->extraline = 0; + *size = 1; + return "\n"; + } + if (feof(lf->f)) return NULL; + *size = fread(lf->buff, 1, LUAL_BUFFERSIZE, lf->f); + return (*size > 0) ? lf->buff : NULL; +} + + +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; +} + + +LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { + LoadF lf; + int status, readstatus; + int c; + int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ + lf.extraline = 0; + 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); + } + c = getc(lf.f); + if (c == '#') { /* Unix exec. file? */ + lf.extraline = 1; + while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ + if (c == '\n') c = getc(lf.f); + } + if (c == LUA_SIGNATURE[0] && lf.f != stdin) { /* binary file? */ + fclose(lf.f); + lf.f = fopen(filename, "rb"); /* reopen in binary mode */ + if (lf.f == NULL) return errfile(L, "reopen", fnameindex); + /* skip eventual `#!...' */ + while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ; + lf.extraline = 0; + } + ungetc(c, lf.f); + status = lua_load(L, getF, &lf, lua_tostring(L, -1)); + readstatus = ferror(lf.f); + if (lf.f != stdin) 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; + if (ls->size == 0) return NULL; + *size = ls->size; + ls->size = 0; + return ls->s; +} + + +LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size, + const char *name) { + LoadS ls; + ls.s = buff; + ls.size = size; + return lua_load(L, getS, &ls, name); +} + + +LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) { + return luaL_loadbuffer(L, s, strlen(s), s); +} + + + +/* }====================================================== */ + + +static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { + (void)ud; + (void)osize; + if (nsize == 0) { + free(ptr); + return NULL; + } + else + return realloc(ptr, nsize); +} + + +static int panic (lua_State *L) { + (void)L; /* to avoid warnings */ + fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", + lua_tostring(L, -1)); + return 0; +} + + +LUALIB_API lua_State *luaL_newstate (void) { + lua_State *L = lua_newstate(l_alloc, NULL); + if (L) lua_atpanic(L, &panic); + return L; +} + diff --git a/src/lua/lauxlib.h b/src/lua/lauxlib.h new file mode 100644 index 0000000..1bba1c0 --- /dev/null +++ b/src/lua/lauxlib.h @@ -0,0 +1,172 @@ +/* +** $Id: lauxlib.h,v 1.87 2005/12/29 15:32:11 roberto Exp $ +** Auxiliary functions for building Lua libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lauxlib_h +#define lauxlib_h + + +#include +#include + +#include "lua.h" + + +#if defined(LUA_COMPAT_GETN) +LUALIB_API int (luaL_getn) (lua_State *L, int t); +LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); +#else +#define luaL_getn(L,i) ((int)lua_objlen(L, i)) +#define luaL_setn(L,i,j) ((void)0) /* no op! */ +#endif + +#if defined(LUA_COMPAT_OPENLIB) +#define luaI_openlib luaL_openlib +#endif + + +/* extra error code for `luaL_load' */ +#define LUA_ERRFILE (LUA_ERRERR+1) + + +typedef struct luaL_Reg { + const char *name; + lua_CFunction func; +} luaL_Reg; + + + +LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname, + const luaL_Reg *l, int nup); +LUALIB_API void (luaL_register) (lua_State *L, const char *libname, + const luaL_Reg *l); +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 int (luaL_typerror) (lua_State *L, int narg, const char *tname); +LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); +LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, + size_t *l); +LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, + const char *def, size_t *l); +LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); +LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); + +LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); +LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, + 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 narg, int t); +LUALIB_API void (luaL_checkany) (lua_State *L, int narg); + +LUALIB_API int (luaL_newmetatable) (lua_State *L, 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 narg, const char *def, + const char *const lst[]); + +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_loadfile) (lua_State *L, const char *filename); +LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, + const char *name); +LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); + +LUALIB_API lua_State *(luaL_newstate) (void); + + +LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, + const char *r); + +LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, + const char *fname, int szhint); + + + + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + +#define luaL_argcheck(L, cond,numarg,extramsg) \ + ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) +#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) +#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))) + +#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, 0, 0)) + +#define luaL_dostring(L, s) (luaL_loadstring(L, s) || lua_pcall(L, 0, 0, 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))) + +/* +** {====================================================== +** Generic Buffer manipulation +** ======================================================= +*/ + + + +typedef struct luaL_Buffer { + char *p; /* current position in buffer */ + int lvl; /* number of strings in the stack (level) */ + lua_State *L; + char buffer[LUAL_BUFFERSIZE]; +} luaL_Buffer; + +#define luaL_addchar(B,c) \ + ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ + (*(B)->p++ = (char)(c))) + +/* compatibility only */ +#define luaL_putchar(B,c) luaL_addchar(B,c) + +#define luaL_addsize(B,n) ((B)->p += (n)) + +LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); +LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); +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); + + +/* }====================================================== */ + + +/* compatibility with ref system */ + +/* pre-defined references */ +#define LUA_NOREF (-2) +#define LUA_REFNIL (-1) + +#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ + (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) + +#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) + +#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) + + +#define luaL_reg luaL_Reg + +#endif + + diff --git a/src/lua/lbaselib.c b/src/lua/lbaselib.c new file mode 100644 index 0000000..1d922a8 --- /dev/null +++ b/src/lua/lbaselib.c @@ -0,0 +1,643 @@ +/* +** $Id: lbaselib.c,v 1.189 2006/01/18 11:49:12 roberto Exp $ +** Basic library +** See Copyright Notice in lua.h +*/ + + + +#include +#include +#include +#include + +#define lbaselib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + + + +/* +** If your system does not support `stdout', you can just remove this function. +** If you need, you can define your own `print' function, following this +** model but changing `fputs' to put the strings at a proper place +** (a console window or a log file, for instance). +*/ +static int luaB_print (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tostring(L, -1); /* get result */ + if (s == NULL) + return luaL_error(L, LUA_QL("tostring") " must return a string to " + LUA_QL("print")); + if (i>1) fputs("\t", stdout); + fputs(s, stdout); + lua_pop(L, 1); /* pop result */ + } + fputs("\n", stdout); + return 0; +} + + +static int luaB_tonumber (lua_State *L) { + int base = luaL_optint(L, 2, 10); + if (base == 10) { /* standard conversion */ + luaL_checkany(L, 1); + if (lua_isnumber(L, 1)) { + lua_pushnumber(L, lua_tonumber(L, 1)); + return 1; + } + } + else { + const char *s1 = luaL_checkstring(L, 1); + char *s2; + unsigned long n; + luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); + n = strtoul(s1, &s2, base); + if (s1 != s2) { /* at least one valid digit? */ + while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */ + if (*s2 == '\0') { /* no invalid trailing characters? */ + lua_pushnumber(L, (lua_Number)n); + return 1; + } + } + } + lua_pushnil(L); /* else not a number */ + return 1; +} + + +static int luaB_error (lua_State *L) { + int level = luaL_optint(L, 2, 1); + lua_settop(L, 1); + if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ + luaL_where(L, level); + 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_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + if (luaL_getmetafield(L, 1, "__metatable")) + luaL_error(L, "cannot change a protected metatable"); + lua_settop(L, 2); + lua_setmetatable(L, 1); + return 1; +} + + +static void getfunc (lua_State *L) { + if (lua_isfunction(L, 1)) lua_pushvalue(L, 1); + else { + lua_Debug ar; + int level = luaL_optint(L, 1, 1); + luaL_argcheck(L, level >= 0, 1, "level must be non-negative"); + if (lua_getstack(L, level, &ar) == 0) + luaL_argerror(L, 1, "invalid level"); + lua_getinfo(L, "f", &ar); + if (lua_isnil(L, -1)) + luaL_error(L, "no function environment for tail call at level %d", + level); + } +} + + +static int luaB_getfenv (lua_State *L) { + getfunc(L); + if (lua_iscfunction(L, -1)) /* is a C function? */ + lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */ + else + lua_getfenv(L, -1); + return 1; +} + + +static int luaB_setfenv (lua_State *L) { + luaL_checktype(L, 2, LUA_TTABLE); + getfunc(L); + lua_pushvalue(L, 2); + if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) { + /* change environment of current thread */ + lua_pushthread(L); + lua_insert(L, -2); + lua_setfenv(L, -2); + return 0; + } + else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0) + luaL_error(L, + LUA_QL("setfenv") " cannot change environment of given object"); + 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_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 luaB_gcinfo (lua_State *L) { + lua_pushinteger(L, lua_getgccount(L)); + return 1; +} + + +static int luaB_collectgarbage (lua_State *L) { + static const char *const opts[] = {"stop", "restart", "collect", + "count", "step", "setpause", "setstepmul", NULL}; + static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, + LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL}; + int o = luaL_checkoption(L, 1, "collect", opts); + int ex = luaL_optint(L, 2, 0); + int res = lua_gc(L, optsnum[o], ex); + switch (optsnum[o]) { + case LUA_GCCOUNT: { + int b = lua_gc(L, LUA_GCCOUNTB, 0); + lua_pushnumber(L, res + ((lua_Number)b/1024)); + return 1; + } + case LUA_GCSTEP: { + lua_pushboolean(L, res); + return 1; + } + default: { + lua_pushnumber(L, res); + return 1; + } + } +} + + +static int luaB_type (lua_State *L) { + luaL_checkany(L, 1); + lua_pushstring(L, luaL_typename(L, 1)); + 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 luaB_pairs (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ + lua_pushvalue(L, 1); /* state, */ + lua_pushnil(L); /* and initial value */ + return 3; +} + + +static int ipairsaux (lua_State *L) { + int i = luaL_checkint(L, 2); + luaL_checktype(L, 1, LUA_TTABLE); + i++; /* next value */ + lua_pushinteger(L, i); + lua_rawgeti(L, 1, i); + return (lua_isnil(L, -1)) ? 0 : 2; +} + + +static int luaB_ipairs (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ + lua_pushvalue(L, 1); /* state, */ + lua_pushinteger(L, 0); /* and initial value */ + return 3; +} + + +static int load_aux (lua_State *L, int status) { + if (status == 0) /* OK? */ + return 1; + else { + lua_pushnil(L); + lua_insert(L, -2); /* put before error message */ + return 2; /* return nil plus error message */ + } +} + + +static int luaB_loadstring (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + const char *chunkname = luaL_optstring(L, 2, s); + return load_aux(L, luaL_loadbuffer(L, s, l, chunkname)); +} + + +static int luaB_loadfile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + return load_aux(L, luaL_loadfile(L, fname)); +} + + +/* +** 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; /* to avoid warnings */ + 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)) { + *size = 0; + return NULL; + } + else if (lua_isstring(L, -1)) { + lua_replace(L, 3); /* save string in a reserved stack slot */ + return lua_tolstring(L, 3, size); + } + else luaL_error(L, "reader function must return a string"); + return NULL; /* to avoid warnings */ +} + + +static int luaB_load (lua_State *L) { + int status; + const char *cname = luaL_optstring(L, 2, "=(load)"); + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, 3); /* function, eventual name, plus one reserved slot */ + status = lua_load(L, generic_reader, NULL, cname); + return load_aux(L, status); +} + + +static int luaB_dofile (lua_State *L) { + const char *fname = luaL_optstring(L, 1, NULL); + int n = lua_gettop(L); + if (luaL_loadfile(L, fname) != 0) lua_error(L); + lua_call(L, 0, LUA_MULTRET); + return lua_gettop(L) - n; +} + + +static int luaB_assert (lua_State *L) { + luaL_checkany(L, 1); + if (!lua_toboolean(L, 1)) + return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); + return lua_gettop(L); +} + + +static int luaB_unpack (lua_State *L) { + int i, e, n; + luaL_checktype(L, 1, LUA_TTABLE); + i = luaL_optint(L, 2, 1); + e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1)); + n = e - i + 1; /* number of elements */ + if (n <= 0) return 0; /* empty range */ + luaL_checkstack(L, n, "table too big to unpack"); + for (; i<=e; i++) /* push arg[i...e] */ + lua_rawgeti(L, 1, i); + return n; +} + + +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 { + int i = luaL_checkint(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 - i; + } +} + + +static int luaB_pcall (lua_State *L) { + int status; + luaL_checkany(L, 1); + status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0); + lua_pushboolean(L, (status == 0)); + lua_insert(L, 1); + return lua_gettop(L); /* return status + all results */ +} + + +static int luaB_xpcall (lua_State *L) { + int status; + luaL_checkany(L, 2); + lua_settop(L, 2); + lua_insert(L, 1); /* put error function under function to be called */ + status = lua_pcall(L, 0, LUA_MULTRET, 1); + lua_pushboolean(L, (status == 0)); + lua_replace(L, 1); + return lua_gettop(L); /* return status + all results */ +} + + +static int luaB_tostring (lua_State *L) { + luaL_checkany(L, 1); + if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */ + return 1; /* use its value */ + switch (lua_type(L, 1)) { + case LUA_TNUMBER: + lua_pushstring(L, lua_tostring(L, 1)); + break; + case LUA_TSTRING: + lua_pushvalue(L, 1); + break; + case LUA_TBOOLEAN: + lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false")); + break; + case LUA_TNIL: + lua_pushliteral(L, "nil"); + break; + default: + lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1)); + break; + } + return 1; +} + + +static int luaB_newproxy (lua_State *L) { + lua_settop(L, 1); + lua_newuserdata(L, 0); /* create proxy */ + if (lua_toboolean(L, 1) == 0) + return 1; /* no metatable */ + else if (lua_isboolean(L, 1)) { + lua_newtable(L); /* create a new metatable `m' ... */ + lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */ + lua_pushboolean(L, 1); + lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */ + } + else { + int validproxy = 0; /* to check if weaktable[metatable(u)] == true */ + if (lua_getmetatable(L, 1)) { + lua_rawget(L, lua_upvalueindex(1)); + validproxy = lua_toboolean(L, -1); + lua_pop(L, 1); /* remove value */ + } + luaL_argcheck(L, validproxy, 1, "boolean or proxy expected"); + lua_getmetatable(L, 1); /* metatable is valid; get it */ + } + lua_setmetatable(L, 2); + return 1; +} + + +static const luaL_Reg base_funcs[] = { + {"assert", luaB_assert}, + {"collectgarbage", luaB_collectgarbage}, + {"dofile", luaB_dofile}, + {"error", luaB_error}, + {"gcinfo", luaB_gcinfo}, + {"getfenv", luaB_getfenv}, + {"getmetatable", luaB_getmetatable}, + {"loadfile", luaB_loadfile}, + {"load", luaB_load}, + {"loadstring", luaB_loadstring}, + {"next", luaB_next}, + {"pcall", luaB_pcall}, + {"print", luaB_print}, + {"rawequal", luaB_rawequal}, + {"rawget", luaB_rawget}, + {"rawset", luaB_rawset}, + {"select", luaB_select}, + {"setfenv", luaB_setfenv}, + {"setmetatable", luaB_setmetatable}, + {"tonumber", luaB_tonumber}, + {"tostring", luaB_tostring}, + {"type", luaB_type}, + {"unpack", luaB_unpack}, + {"xpcall", luaB_xpcall}, + {NULL, NULL} +}; + + +/* +** {====================================================== +** Coroutine library +** ======================================================= +*/ + +static int auxresume (lua_State *L, lua_State *co, int narg) { + int status; + if (!lua_checkstack(co, narg)) + luaL_error(L, "too many arguments to resume"); + if (lua_status(co) == 0 && lua_gettop(co) == 0) { + lua_pushliteral(L, "cannot resume dead coroutine"); + return -1; /* error flag */ + } + lua_xmove(L, co, narg); + status = lua_resume(co, narg); + if (status == 0 || status == LUA_YIELD) { + int nres = lua_gettop(co); + if (!lua_checkstack(L, nres)) + luaL_error(L, "too many results to resume"); + 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 = lua_tothread(L, 1); + int r; + luaL_argcheck(L, co, 1, "coroutine expected"); + r = auxresume(L, co, lua_gettop(L) - 1); + if (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 (r < 0) { + if (lua_isstring(L, -1)) { /* error object is a string? */ + luaL_where(L, 1); /* add extra info */ + lua_insert(L, -2); + lua_concat(L, 2); + } + lua_error(L); /* propagate error */ + } + return r; +} + + +static int luaB_cocreate (lua_State *L) { + lua_State *NL = lua_newthread(L); + luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, + "Lua function expected"); + 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)); +} + + +static int luaB_costatus (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, co, 1, "coroutine expected"); + if (L == co) lua_pushliteral(L, "running"); + else { + switch (lua_status(co)) { + case LUA_YIELD: + lua_pushliteral(L, "suspended"); + break; + case 0: { + lua_Debug ar; + if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ + lua_pushliteral(L, "normal"); /* it is running */ + else if (lua_gettop(co) == 0) + lua_pushliteral(L, "dead"); + else + lua_pushliteral(L, "suspended"); /* initial state */ + break; + } + default: /* some error occured */ + lua_pushliteral(L, "dead"); + break; + } + } + return 1; +} + + +static int luaB_corunning (lua_State *L) { + if (lua_pushthread(L)) + return 0; /* main thread is not a coroutine */ + else + return 1; +} + + +static const luaL_Reg co_funcs[] = { + {"create", luaB_cocreate}, + {"resume", luaB_coresume}, + {"running", luaB_corunning}, + {"status", luaB_costatus}, + {"wrap", luaB_cowrap}, + {"yield", luaB_yield}, + {NULL, NULL} +}; + +/* }====================================================== */ + + +static void auxopen (lua_State *L, const char *name, + lua_CFunction f, lua_CFunction u) { + lua_pushcfunction(L, u); + lua_pushcclosure(L, f, 1); + lua_setfield(L, -2, name); +} + + +static void base_open (lua_State *L) { + /* set global _G */ + lua_pushvalue(L, LUA_GLOBALSINDEX); + lua_setglobal(L, "_G"); + /* open lib into global table */ + luaL_register(L, "_G", base_funcs); + lua_pushliteral(L, LUA_VERSION); + lua_setglobal(L, "_VERSION"); /* set global _VERSION */ + /* `ipairs' and `pairs' need auxliliary functions as upvalues */ + auxopen(L, "ipairs", luaB_ipairs, ipairsaux); + auxopen(L, "pairs", luaB_pairs, luaB_next); + /* `newproxy' needs a weaktable as upvalue */ + lua_createtable(L, 0, 1); /* new table `w' */ + lua_pushvalue(L, -1); /* `w' will be its own metatable */ + lua_setmetatable(L, -2); + lua_pushliteral(L, "kv"); + lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */ + lua_pushcclosure(L, luaB_newproxy, 1); + lua_setglobal(L, "newproxy"); /* set global `newproxy' */ +} + + +LUALIB_API int luaopen_base (lua_State *L) { + base_open(L); + luaL_register(L, LUA_COLIBNAME, co_funcs); + return 2; +} + diff --git a/src/lua/lcode.c b/src/lua/lcode.c new file mode 100644 index 0000000..dd3e37e --- /dev/null +++ b/src/lua/lcode.c @@ -0,0 +1,825 @@ +/* +** $Id: lcode.c,v 2.24 2005/12/22 16:19:56 roberto Exp $ +** Code generator for Lua +** See Copyright Notice in lua.h +*/ + + +#include + +#define lcode_c +#define LUA_CORE + +#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 "ltable.h" + + +#define hasjumps(e) ((e)->t != (e)->f) + + +static int isnumeral(expdesc *e) { + return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); +} + + +void luaK_nil (FuncState *fs, int from, int n) { + Instruction *previous; + if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ + if (fs->pc == 0) /* function start? */ + return; /* positions are already clean */ + if (GET_OPCODE(*(previous = &fs->f->code[fs->pc-1])) == OP_LOADNIL) { + int pfrom = GETARG_A(*previous); + int pto = GETARG_B(*previous); + if (pfrom <= from && from <= pto+1) { /* can connect both? */ + if (from+n-1 > pto) + SETARG_B(*previous, from+n-1); + return; + } + } + } + luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */ +} + + +int luaK_jump (FuncState *fs) { + int jpc = fs->jpc; /* save list of jumps to here */ + int j; + fs->jpc = NO_JUMP; + j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); + luaK_concat(fs, &j, jpc); /* keep them on hold */ + return j; +} + + +void luaK_ret (FuncState *fs, int first, int nret) { + luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); +} + + +static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { + luaK_codeABC(fs, op, A, B, C); + return luaK_jump(fs); +} + + +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 (abs(offset) > MAXARG_sBx) + luaX_syntaxerror(fs->ls, "control structure too long"); + SETARG_sBx(*jmp, offset); +} + + +/* +** 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; +} + + +static int getjump (FuncState *fs, int pc) { + int offset = GETARG_sBx(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 */ +} + + +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; +} + + +/* +** 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 */ +} + + +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 */ + *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); + + return 1; +} + + +static void removevalues (FuncState *fs, int list) { + for (; list != NO_JUMP; list = getjump(fs, list)) + patchtestreg(fs, list, NO_REG); +} + + +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; + } +} + + +static void dischargejpc (FuncState *fs) { + patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); + fs->jpc = NO_JUMP; +} + + +void luaK_patchlist (FuncState *fs, int list, int target) { + if (target == fs->pc) + luaK_patchtohere(fs, list); + else { + lua_assert(target < fs->pc); + patchlistaux(fs, list, target, NO_REG, target); + } +} + + +void luaK_patchtohere (FuncState *fs, int list) { + luaK_getlabel(fs); + luaK_concat(fs, &fs->jpc, list); +} + + +void luaK_concat (FuncState *fs, int *l1, int l2) { + if (l2 == NO_JUMP) return; + else if (*l1 == NO_JUMP) + *l1 = l2; + else { + int list = *l1; + int next; + while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ + list = next; + fixjump(fs, list, l2); + } +} + + +void luaK_checkstack (FuncState *fs, int n) { + int newstack = fs->freereg + n; + if (newstack > fs->f->maxstacksize) { + if (newstack >= MAXSTACK) + luaX_syntaxerror(fs->ls, "function or expression too complex"); + fs->f->maxstacksize = cast_byte(newstack); + } +} + + +void luaK_reserveregs (FuncState *fs, int n) { + luaK_checkstack(fs, n); + fs->freereg += n; +} + + +static void freereg (FuncState *fs, int reg) { + if (!ISK(reg) && reg >= fs->nactvar) { + fs->freereg--; + lua_assert(reg == fs->freereg); + } +} + + +static void freeexp (FuncState *fs, expdesc *e) { + if (e->k == VNONRELOC) + freereg(fs, e->u.s.info); +} + + +static int addk (FuncState *fs, TValue *k, TValue *v) { + lua_State *L = fs->L; + TValue *idx = luaH_set(L, fs->h, k); + Proto *f = fs->f; + int oldsize = f->sizek; + if (ttisnumber(idx)) { + lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v)); + return cast_int(nvalue(idx)); + } + else { /* constant not found; create a new entry */ + setnvalue(idx, cast_num(fs->nk)); + luaM_growvector(L, f->k, fs->nk, f->sizek, TValue, + MAXARG_Bx, "constant table overflow"); + while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); + setobj(L, &f->k[fs->nk], v); + luaC_barrier(L, f, v); + return fs->nk++; + } +} + + +int luaK_stringK (FuncState *fs, TString *s) { + TValue o; + setsvalue(fs->L, &o, s); + return addk(fs, &o, &o); +} + + +int luaK_numberK (FuncState *fs, lua_Number r) { + TValue o; + setnvalue(&o, r); + return addk(fs, &o, &o); +} + + +static int boolK (FuncState *fs, int b) { + TValue o; + setbvalue(&o, b); + return addk(fs, &o, &o); +} + + +static int nilK (FuncState *fs) { + TValue k, v; + setnilvalue(&v); + /* cannot use nil as key; instead use table itself to represent nil */ + sethvalue(fs->L, &k, fs->h); + return addk(fs, &k, &v); +} + + +void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { + if (e->k == VCALL) { /* expression is an open function call? */ + SETARG_C(getcode(fs, e), nresults+1); + } + else if (e->k == VVARARG) { + SETARG_B(getcode(fs, e), nresults+1); + SETARG_A(getcode(fs, e), fs->freereg); + luaK_reserveregs(fs, 1); + } +} + + +void luaK_setoneret (FuncState *fs, expdesc *e) { + if (e->k == VCALL) { /* expression is an open function call? */ + e->k = VNONRELOC; + e->u.s.info = GETARG_A(getcode(fs, e)); + } + else if (e->k == VVARARG) { + SETARG_B(getcode(fs, e), 2); + e->k = VRELOCABLE; /* can relocate its simple result */ + } +} + + +void luaK_dischargevars (FuncState *fs, expdesc *e) { + switch (e->k) { + case VLOCAL: { + e->k = VNONRELOC; + break; + } + case VUPVAL: { + e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0); + e->k = VRELOCABLE; + break; + } + case VGLOBAL: { + e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info); + e->k = VRELOCABLE; + break; + } + case VINDEXED: { + freereg(fs, e->u.s.aux); + freereg(fs, e->u.s.info); + e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux); + e->k = VRELOCABLE; + break; + } + case VVARARG: + case VCALL: { + luaK_setoneret(fs, e); + break; + } + default: break; /* there is one value available (somewhere) */ + } +} + + +static int code_label (FuncState *fs, int A, int b, int jump) { + luaK_getlabel(fs); /* those instructions may be jump targets */ + return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); +} + + +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: case VTRUE: { + luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); + break; + } + case VK: { + luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info); + break; + } + case VKNUM: { + luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval)); + break; + } + case VRELOCABLE: { + Instruction *pc = &getcode(fs, e); + SETARG_A(*pc, reg); + break; + } + case VNONRELOC: { + if (reg != e->u.s.info) + luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0); + break; + } + default: { + lua_assert(e->k == VVOID || e->k == VJMP); + return; /* nothing to do... */ + } + } + e->u.s.info = reg; + e->k = VNONRELOC; +} + + +static void discharge2anyreg (FuncState *fs, expdesc *e) { + if (e->k != VNONRELOC) { + luaK_reserveregs(fs, 1); + discharge2reg(fs, e, fs->freereg-1); + } +} + + +static void exp2reg (FuncState *fs, expdesc *e, int reg) { + discharge2reg(fs, e, reg); + if (e->k == VJMP) + luaK_concat(fs, &e->t, e->u.s.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_label(fs, reg, 0, 1); + p_t = code_label(fs, reg, 1, 0); + 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.s.info = reg; + e->k = VNONRELOC; +} + + +void luaK_exp2nextreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + freeexp(fs, e); + luaK_reserveregs(fs, 1); + exp2reg(fs, e, fs->freereg - 1); +} + + +int luaK_exp2anyreg (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + if (e->k == VNONRELOC) { + if (!hasjumps(e)) return e->u.s.info; /* exp is already in a register */ + if (e->u.s.info >= fs->nactvar) { /* reg. is not a local? */ + exp2reg(fs, e, e->u.s.info); /* put value on it */ + return e->u.s.info; + } + } + luaK_exp2nextreg(fs, e); /* default */ + return e->u.s.info; +} + + +void luaK_exp2val (FuncState *fs, expdesc *e) { + if (hasjumps(e)) + luaK_exp2anyreg(fs, e); + else + luaK_dischargevars(fs, e); +} + + +int luaK_exp2RK (FuncState *fs, expdesc *e) { + luaK_exp2val(fs, e); + switch (e->k) { + case VKNUM: + case VTRUE: + case VFALSE: + case VNIL: { + if (fs->nk <= MAXINDEXRK) { /* constant fit in RK operand? */ + e->u.s.info = (e->k == VNIL) ? nilK(fs) : + (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) : + boolK(fs, (e->k == VTRUE)); + e->k = VK; + return RKASK(e->u.s.info); + } + else break; + } + case VK: { + if (e->u.s.info <= MAXINDEXRK) /* constant fit in argC? */ + return RKASK(e->u.s.info); + else break; + } + default: break; + } + /* not a constant in the right range: put it in a register */ + return luaK_exp2anyreg(fs, e); +} + + +void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { + switch (var->k) { + case VLOCAL: { + freeexp(fs, ex); + exp2reg(fs, ex, var->u.s.info); + return; + } + case VUPVAL: { + int e = luaK_exp2anyreg(fs, ex); + luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0); + break; + } + case VGLOBAL: { + int e = luaK_exp2anyreg(fs, ex); + luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info); + break; + } + case VINDEXED: { + int e = luaK_exp2RK(fs, ex); + luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e); + break; + } + default: { + lua_assert(0); /* invalid var kind to store */ + break; + } + } + freeexp(fs, ex); +} + + +void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { + int func; + luaK_exp2anyreg(fs, e); + freeexp(fs, e); + func = fs->freereg; + luaK_reserveregs(fs, 2); + luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key)); + freeexp(fs, key); + e->u.s.info = func; + e->k = VNONRELOC; +} + + +static void invertjump (FuncState *fs, expdesc *e) { + Instruction *pc = getjumpcontrol(fs, e->u.s.info); + lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && + GET_OPCODE(*pc) != OP_TEST); + SETARG_A(*pc, !(GETARG_A(*pc))); +} + + +static int jumponcond (FuncState *fs, expdesc *e, int cond) { + if (e->k == VRELOCABLE) { + Instruction ie = getcode(fs, e); + if (GET_OPCODE(ie) == OP_NOT) { + fs->pc--; /* remove previous OP_NOT */ + return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); + } + /* else go through */ + } + discharge2anyreg(fs, e); + freeexp(fs, e); + return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond); +} + + +void luaK_goiftrue (FuncState *fs, expdesc *e) { + int pc; /* pc of last jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VK: case VKNUM: case VTRUE: { + pc = NO_JUMP; /* always true; do nothing */ + break; + } + case VFALSE: { + pc = luaK_jump(fs); /* always jump */ + break; + } + case VJMP: { + invertjump(fs, e); + pc = e->u.s.info; + break; + } + default: { + pc = jumponcond(fs, e, 0); + break; + } + } + luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ + luaK_patchtohere(fs, e->t); + e->t = NO_JUMP; +} + + +static void luaK_goiffalse (FuncState *fs, expdesc *e) { + int pc; /* pc of last jump */ + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: case VFALSE: { + pc = NO_JUMP; /* always false; do nothing */ + break; + } + case VTRUE: { + pc = luaK_jump(fs); /* always jump */ + break; + } + case VJMP: { + pc = e->u.s.info; + break; + } + default: { + pc = jumponcond(fs, e, 1); + break; + } + } + luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ + luaK_patchtohere(fs, e->f); + e->f = NO_JUMP; +} + + +static void codenot (FuncState *fs, expdesc *e) { + luaK_dischargevars(fs, e); + switch (e->k) { + case VNIL: case VFALSE: { + e->k = VTRUE; + break; + } + case VK: case VKNUM: case VTRUE: { + e->k = VFALSE; + break; + } + case VJMP: { + invertjump(fs, e); + break; + } + case VRELOCABLE: + case VNONRELOC: { + discharge2anyreg(fs, e); + freeexp(fs, e); + e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0); + e->k = VRELOCABLE; + break; + } + default: { + lua_assert(0); /* cannot happen */ + break; + } + } + /* interchange true and false lists */ + { int temp = e->f; e->f = e->t; e->t = temp; } + removevalues(fs, e->f); + removevalues(fs, e->t); +} + + +void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { + t->u.s.aux = luaK_exp2RK(fs, k); + t->k = VINDEXED; +} + + +static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { + lua_Number v1, v2, r; + if (!isnumeral(e1) || !isnumeral(e2)) return 0; + v1 = e1->u.nval; + v2 = e2->u.nval; + switch (op) { + case OP_ADD: r = luai_numadd(v1, v2); break; + case OP_SUB: r = luai_numsub(v1, v2); break; + case OP_MUL: r = luai_nummul(v1, v2); break; + case OP_DIV: + if (v2 == 0) return 0; /* do not attempt to divide by 0 */ + r = luai_numdiv(v1, v2); break; + case OP_MOD: + if (v2 == 0) return 0; /* do not attempt to divide by 0 */ + r = luai_nummod(v1, v2); break; + case OP_POW: r = luai_numpow(v1, v2); break; + case OP_UNM: r = luai_numunm(v1); break; + case OP_LEN: return 0; /* no constant folding for 'len' */ + default: lua_assert(0); r = 0; break; + } + if (luai_numisnan(r)) return 0; /* do not attempt to produce NaN */ + e1->u.nval = r; + return 1; +} + + +static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { + if (constfolding(op, e1, e2)) + return; + else { + int o1 = luaK_exp2RK(fs, e1); + int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0; + freeexp(fs, e2); + freeexp(fs, e1); + e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2); + e1->k = VRELOCABLE; + } +} + + +static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, + expdesc *e2) { + int o1 = luaK_exp2RK(fs, e1); + int o2 = luaK_exp2RK(fs, e2); + freeexp(fs, e2); + freeexp(fs, e1); + if (cond == 0 && op != OP_EQ) { + int temp; /* exchange args to replace by `<' or `<=' */ + temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ + cond = 1; + } + e1->u.s.info = condjump(fs, op, cond, o1, o2); + e1->k = VJMP; +} + + +void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) { + expdesc e2; + e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; + switch (op) { + case OPR_MINUS: { + if (e->k == VK) + luaK_exp2anyreg(fs, e); /* cannot operate on non-numeric constants */ + codearith(fs, OP_UNM, e, &e2); + break; + } + case OPR_NOT: codenot(fs, e); break; + case OPR_LEN: { + luaK_exp2anyreg(fs, e); /* cannot operate on constants */ + codearith(fs, OP_LEN, e, &e2); + break; + } + default: lua_assert(0); + } +} + + +void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { + switch (op) { + case OPR_AND: { + luaK_goiftrue(fs, v); + break; + } + case OPR_OR: { + luaK_goiffalse(fs, v); + break; + } + case OPR_CONCAT: { + luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ + break; + } + default: { + if (!isnumeral(v)) luaK_exp2RK(fs, v); + break; + } + } +} + + +void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { + switch (op) { + case OPR_AND: { + lua_assert(e1->t == NO_JUMP); /* list must be closed */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e1->f, e2->f); + e1->k = e2->k; e1->u.s.info = e2->u.s.info; + e1->u.s.aux = e2->u.s.aux; e1->t = e2->t; + break; + } + case OPR_OR: { + lua_assert(e1->f == NO_JUMP); /* list must be closed */ + luaK_dischargevars(fs, e2); + luaK_concat(fs, &e1->t, e2->t); + e1->k = e2->k; e1->u.s.info = e2->u.s.info; + e1->u.s.aux = e2->u.s.aux; e1->f = e2->f; + break; + } + case OPR_CONCAT: { + luaK_exp2val(fs, e2); + if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { + lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1); + freeexp(fs, e1); + SETARG_B(getcode(fs, e2), e1->u.s.info); + e1->k = e2->k; e1->u.s.info = e2->u.s.info; + } + else { + luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ + codearith(fs, OP_CONCAT, e1, e2); + } + break; + } + case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break; + case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break; + case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break; + case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break; + case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break; + case OPR_POW: codearith(fs, OP_POW, e1, e2); break; + case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break; + case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break; + case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break; + case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break; + case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break; + case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break; + default: lua_assert(0); + } +} + + +void luaK_fixline (FuncState *fs, int line) { + fs->f->lineinfo[fs->pc - 1] = line; +} + + +static int luaK_code (FuncState *fs, Instruction i, int line) { + Proto *f = fs->f; + dischargejpc(fs); /* `pc' will change */ + /* put new instruction in code array */ + luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction, + MAX_INT, "code size overflow"); + f->code[fs->pc] = i; + /* save corresponding line information */ + luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int, + MAX_INT, "code size overflow"); + f->lineinfo[fs->pc] = line; + return fs->pc++; +} + + +int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { + lua_assert(getOpMode(o) == iABC); + lua_assert(getBMode(o) != OpArgN || b == 0); + lua_assert(getCMode(o) != OpArgN || c == 0); + return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline); +} + + +int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { + lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); + lua_assert(getCMode(o) == OpArgN); + return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline); +} + + +void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { + int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; + int b = (tostore == LUA_MULTRET) ? 0 : tostore; + lua_assert(tostore != 0); + if (c <= MAXARG_C) + luaK_codeABC(fs, OP_SETLIST, base, b, c); + else { + luaK_codeABC(fs, OP_SETLIST, base, b, 0); + luaK_code(fs, cast(Instruction, c), fs->ls->lastline); + } + fs->freereg = base + 1; /* free registers with list values */ +} + diff --git a/src/lua/lcode.h b/src/lua/lcode.h new file mode 100644 index 0000000..b5668f2 --- /dev/null +++ b/src/lua/lcode.h @@ -0,0 +1,77 @@ +/* +** $Id: lcode.h,v 1.47 2005/11/08 19:44:31 roberto Exp $ +** 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 +*/ +typedef enum BinOpr { + OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, + OPR_CONCAT, + OPR_NE, OPR_EQ, + OPR_LT, OPR_LE, OPR_GT, OPR_GE, + OPR_AND, OPR_OR, + OPR_NOBINOPR +} BinOpr; + +#define binopistest(op) ((op) >= OPR_NE) + +typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; + + +#define getcode(fs,e) ((fs)->f->code[(e)->u.s.info]) + +#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) + +#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) + +LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); +LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); +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 int luaK_stringK (FuncState *fs, TString *s); +LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r); +LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); +LUAI_FUNC int luaK_exp2anyreg (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_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); +LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); +LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2); +LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); + + +#endif diff --git a/src/lua/ldblib.c b/src/lua/ldblib.c new file mode 100644 index 0000000..26a19b6 --- /dev/null +++ b/src/lua/ldblib.c @@ -0,0 +1,397 @@ +/* +** $Id: ldblib.c,v 1.104 2005/12/29 15:32:11 roberto Exp $ +** Interface from Lua to its debug API +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define ldblib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + + +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_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, + "nil or table expected"); + lua_settop(L, 2); + lua_pushboolean(L, lua_setmetatable(L, 1)); + return 1; +} + + +static int db_getfenv (lua_State *L) { + lua_getfenv(L, 1); + return 1; +} + + +static int db_setfenv (lua_State *L) { + luaL_checktype(L, 2, LUA_TTABLE); + lua_settop(L, 2); + if (lua_setfenv(L, 1) == 0) + luaL_error(L, LUA_QL("setfenv") + " cannot change environment of given object"); + return 1; +} + + +static void settabss (lua_State *L, const char *i, const char *v) { + lua_pushstring(L, v); + lua_setfield(L, -2, i); +} + + +static void settabsi (lua_State *L, const char *i, int v) { + lua_pushinteger(L, v); + lua_setfield(L, -2, i); +} + + +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; + } +} + + +static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { + if (L == L1) { + lua_pushvalue(L, -2); + lua_remove(L, -3); + } + else + lua_xmove(L1, L, 1); + lua_setfield(L, -2, fname); +} + + +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, "flnSu"); + if (lua_isnumber(L, arg+1)) { + if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { + lua_pushnil(L); /* level out of range */ + return 1; + } + } + else if (lua_isfunction(L, arg+1)) { + lua_pushfstring(L, ">%s", options); + options = lua_tostring(L, -1); + lua_pushvalue(L, arg+1); + lua_xmove(L, L1, 1); + } + else + return luaL_argerror(L, arg+1, "function or level expected"); + if (!lua_getinfo(L1, options, &ar)) + return luaL_argerror(L, arg+2, "invalid option"); + lua_createtable(L, 0, 2); + if (strchr(options, 'S')) { + settabss(L, "source", ar.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); + if (strchr(options, 'n')) { + settabss(L, "name", ar.name); + settabss(L, "namewhat", ar.namewhat); + } + 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); + lua_Debug ar; + const char *name; + if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + name = lua_getlocal(L1, &ar, luaL_checkint(L, arg+2)); + if (name) { + lua_xmove(L1, L, 1); + lua_pushstring(L, name); + lua_pushvalue(L, -2); + return 2; + } + else { + lua_pushnil(L); + return 1; + } +} + + +static int db_setlocal (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ + return luaL_argerror(L, arg+1, "level out of range"); + luaL_checkany(L, arg+3); + lua_settop(L, arg+3); + lua_xmove(L, L1, 1); + lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); + return 1; +} + + +static int auxupvalue (lua_State *L, int get) { + const char *name; + int n = luaL_checkint(L, 2); + luaL_checktype(L, 1, LUA_TFUNCTION); + if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */ + 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)); + 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); +} + + + +static const char KEY_HOOK = 'h'; + + +static void hookf (lua_State *L, lua_Debug *ar) { + static const char *const hooknames[] = + {"call", "return", "line", "count", "tail return"}; + lua_pushlightuserdata(L, (void *)&KEY_HOOK); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, L); + lua_rawget(L, -2); + if (lua_isfunction(L, -1)) { + lua_pushstring(L, hooknames[(int)ar->event]); + if (ar->currentline >= 0) + lua_pushinteger(L, ar->currentline); + else lua_pushnil(L); + lua_assert(lua_getinfo(L, "lS", ar)); + lua_call(L, 2, 0); + } +} + + +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; +} + + +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 void gethooktable (lua_State *L) { + lua_pushlightuserdata(L, (void *)&KEY_HOOK); + lua_rawget(L, LUA_REGISTRYINDEX); + if (!lua_istable(L, -1)) { + lua_pop(L, 1); + lua_createtable(L, 0, 1); + lua_pushlightuserdata(L, (void *)&KEY_HOOK); + lua_pushvalue(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + + +static int db_sethook (lua_State *L) { + int arg; + lua_State *L1 = getthread(L, &arg); + if (lua_isnoneornil(L, arg+1)) { + lua_settop(L, arg+1); + lua_sethook(L1, NULL, 0, 0); /* turn off hooks */ + } + else { + const char *smask = luaL_checkstring(L, arg+2); + int count = luaL_optint(L, arg+3, 0); + luaL_checktype(L, arg+1, LUA_TFUNCTION); + lua_sethook(L1, hookf, makemask(smask, count), count); + } + gethooktable(L1); + lua_pushlightuserdata(L1, L1); + lua_pushvalue(L, arg+1); + lua_xmove(L, L1, 1); + lua_rawset(L1, -3); /* set new hook */ + lua_pop(L1, 1); /* remove hook table */ + 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 && hook != hookf) /* external hook? */ + lua_pushliteral(L, "external hook"); + else { + gethooktable(L1); + lua_pushlightuserdata(L1, L1); + lua_rawget(L1, -2); /* get hook */ + lua_remove(L1, -2); /* remove hook table */ + lua_xmove(L1, L, 1); + } + lua_pushstring(L, unmakemask(mask, buff)); + lua_pushinteger(L, lua_gethookcount(L1)); + return 3; +} + + +static int db_debug (lua_State *L) { + for (;;) { + char buffer[250]; + fputs("lua_debug> ", stderr); + if (fgets(buffer, sizeof(buffer), stdin) == 0 || + strcmp(buffer, "cont\n") == 0) + return 0; + if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || + lua_pcall(L, 0, 0, 0)) { + fputs(lua_tostring(L, -1), stderr); + fputs("\n", stderr); + } + lua_settop(L, 0); /* remove eventual returns */ + } +} + + +#define LEVELS1 12 /* size of the first part of the stack */ +#define LEVELS2 10 /* size of the second part of the stack */ + +static int db_errorfb (lua_State *L) { + int level; + int firstpart = 1; /* still before eventual `...' */ + int arg; + lua_State *L1 = getthread(L, &arg); + lua_Debug ar; + if (lua_isnumber(L, arg+2)) { + level = (int)lua_tointeger(L, arg+2); + lua_pop(L, 1); + } + else + level = (L == L1) ? 1 : 0; /* level 0 may be this own function */ + if (lua_gettop(L) == arg) + lua_pushliteral(L, ""); + else if (!lua_isstring(L, arg+1)) return 1; /* message is not a string */ + else lua_pushliteral(L, "\n"); + lua_pushliteral(L, "stack traceback:"); + while (lua_getstack(L1, level++, &ar)) { + if (level > LEVELS1 && firstpart) { + /* no more than `LEVELS2' more levels? */ + if (!lua_getstack(L1, level+LEVELS2, &ar)) + level--; /* keep going */ + else { + lua_pushliteral(L, "\n\t..."); /* too many levels */ + while (lua_getstack(L1, level+LEVELS2, &ar)) /* find last levels */ + level++; + } + firstpart = 0; + continue; + } + lua_pushliteral(L, "\n\t"); + lua_getinfo(L1, "Snl", &ar); + lua_pushfstring(L, "%s:", ar.short_src); + if (ar.currentline > 0) + lua_pushfstring(L, "%d:", ar.currentline); + if (*ar.namewhat != '\0') /* is there a name? */ + lua_pushfstring(L, " in function " LUA_QS, ar.name); + else { + if (*ar.what == 'm') /* main? */ + lua_pushfstring(L, " in main chunk"); + else if (*ar.what == 'C' || *ar.what == 't') + lua_pushliteral(L, " ?"); /* C function or tail call */ + else + lua_pushfstring(L, " in function <%s:%d>", + ar.short_src, ar.linedefined); + } + lua_concat(L, lua_gettop(L) - arg); + } + lua_concat(L, lua_gettop(L) - arg); + return 1; +} + + +static const luaL_Reg dblib[] = { + {"debug", db_debug}, + {"getfenv", db_getfenv}, + {"gethook", db_gethook}, + {"getinfo", db_getinfo}, + {"getlocal", db_getlocal}, + {"getregistry", db_getregistry}, + {"getmetatable", db_getmetatable}, + {"getupvalue", db_getupvalue}, + {"setfenv", db_setfenv}, + {"sethook", db_sethook}, + {"setlocal", db_setlocal}, + {"setmetatable", db_setmetatable}, + {"setupvalue", db_setupvalue}, + {"traceback", db_errorfb}, + {NULL, NULL} +}; + + +LUALIB_API int luaopen_debug (lua_State *L) { + luaL_register(L, LUA_DBLIBNAME, dblib); + return 1; +} + diff --git a/src/lua/ldebug.c b/src/lua/ldebug.c new file mode 100644 index 0000000..8919a01 --- /dev/null +++ b/src/lua/ldebug.c @@ -0,0 +1,620 @@ +/* +** $Id: ldebug.c,v 2.29 2005/12/22 16:19:56 roberto Exp $ +** Debug Interface +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + + +#define ldebug_c +#define LUA_CORE + +#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" + + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); + + +static int currentpc (lua_State *L, CallInfo *ci) { + if (!isLua(ci)) return -1; /* function is not a Lua function? */ + if (ci == L->ci) + ci->savedpc = L->savedpc; + return pcRel(ci->savedpc, ci_func(ci)->l.p); +} + + +static int currentline (lua_State *L, CallInfo *ci) { + int pc = currentpc(L, ci); + if (pc < 0) + return -1; /* only active lua functions have current-line information */ + else + return getline(ci_func(ci)->l.p, pc); +} + + +/* +** this function can be called asynchronous (e.g. during a signal) +*/ +LUA_API int 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); + return 1; +} + + +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; + lua_lock(L); + for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) { + level--; + if (f_isLua(ci)) /* Lua function? */ + level -= ci->tailcalls; /* skip lost tail calls */ + } + if (level == 0 && ci > L->base_ci) { /* level found? */ + status = 1; + ar->i_ci = cast_int(ci - L->base_ci); + } + else if (level < 0) { /* level is of a lost tail call? */ + status = 1; + ar->i_ci = 0; + } + else status = 0; /* no such level */ + lua_unlock(L); + return status; +} + + +static Proto *getluaproto (CallInfo *ci) { + return (isLua(ci) ? ci_func(ci)->l.p : NULL); +} + + +static const char *findlocal (lua_State *L, CallInfo *ci, int n) { + const char *name; + Proto *fp = getluaproto(ci); + if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL) + return name; /* is a local variable in a Lua function */ + else { + StkId limit = (ci == L->ci) ? L->top : (ci+1)->func; + if (limit - ci->base >= n && n > 0) /* is 'n' inside 'ci' stack? */ + return "(*temporary)"; + else + return NULL; + } +} + + +LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { + CallInfo *ci = L->base_ci + ar->i_ci; + const char *name = findlocal(L, ci, n); + lua_lock(L); + if (name) + luaA_pushobject(L, ci->base + (n - 1)); + lua_unlock(L); + return name; +} + + +LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { + CallInfo *ci = L->base_ci + ar->i_ci; + const char *name = findlocal(L, ci, n); + lua_lock(L); + if (name) + setobjs2s(L, ci->base + (n - 1), L->top - 1); + L->top--; /* pop value */ + lua_unlock(L); + return name; +} + + +static void funcinfo (lua_Debug *ar, Closure *cl) { + if (cl->c.isC) { + ar->source = "=[C]"; + ar->linedefined = -1; + ar->lastlinedefined = -1; + ar->what = "C"; + } + else { + ar->source = getstr(cl->l.p->source); + ar->linedefined = cl->l.p->linedefined; + ar->lastlinedefined = cl->l.p->lastlinedefined; + ar->what = (ar->linedefined == 0) ? "main" : "Lua"; + } + luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); +} + + +static void info_tailcall (lua_Debug *ar) { + ar->name = ar->namewhat = ""; + ar->what = "tail"; + ar->lastlinedefined = ar->linedefined = ar->currentline = -1; + ar->source = "=(tail call)"; + luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); + ar->nups = 0; +} + + +static void collectvalidlines (lua_State *L, Closure *f) { + if (f == NULL || f->c.isC) { + setnilvalue(L->top); + } + else { + Table *t = luaH_new(L, 0, 0); + int *lineinfo = f->l.p->lineinfo; + int i; + for (i=0; il.p->sizelineinfo; i++) + setbvalue(luaH_setnum(L, t, lineinfo[i]), 1); + sethvalue(L, L->top, t); + } + incr_top(L); +} + + +static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, + Closure *f, CallInfo *ci) { + int status = 1; + if (f == NULL) { + info_tailcall(ar); + return status; + } + for (; *what; what++) { + switch (*what) { + case 'S': { + funcinfo(ar, f); + break; + } + case 'l': { + ar->currentline = (ci) ? currentline(L, ci) : -1; + break; + } + case 'u': { + ar->nups = f->c.nupvalues; + break; + } + case 'n': { + ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL; + if (ar->namewhat == NULL) { + ar->namewhat = ""; /* not found */ + ar->name = NULL; + } + 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 *f = NULL; + CallInfo *ci = NULL; + lua_lock(L); + if (*what == '>') { + StkId func = L->top - 1; + luai_apicheck(L, ttisfunction(func)); + what++; /* skip the '>' */ + f = clvalue(func); + L->top--; /* pop function */ + } + else if (ar->i_ci != 0) { /* no tail call? */ + ci = L->base_ci + ar->i_ci; + lua_assert(ttisfunction(ci->func)); + f = clvalue(ci->func); + } + status = auxgetinfo(L, what, ar, f, ci); + if (strchr(what, 'f')) { + if (f == NULL) setnilvalue(L->top); + else setclvalue(L, L->top, f); + incr_top(L); + } + if (strchr(what, 'L')) + collectvalidlines(L, f); + lua_unlock(L); + return status; +} + + +/* +** {====================================================== +** Symbolic Execution and code checker +** ======================================================= +*/ + +#define check(x) if (!(x)) return 0; + +#define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode) + +#define checkreg(pt,reg) check((reg) < (pt)->maxstacksize) + + + +static int precheck (const Proto *pt) { + check(pt->maxstacksize <= MAXSTACK); + lua_assert(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize); + lua_assert(!(pt->is_vararg & VARARG_NEEDSARG) || + (pt->is_vararg & VARARG_HASARG)); + check(pt->sizeupvalues <= pt->nups); + check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0); + check(GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN); + return 1; +} + + +#define checkopenop(pt,pc) luaG_checkopenop((pt)->code[(pc)+1]) + +int luaG_checkopenop (Instruction i) { + switch (GET_OPCODE(i)) { + case OP_CALL: + case OP_TAILCALL: + case OP_RETURN: + case OP_SETLIST: { + check(GETARG_B(i) == 0); + return 1; + } + default: return 0; /* invalid instruction after an open call */ + } +} + + +static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) { + switch (mode) { + case OpArgN: check(r == 0); break; + case OpArgU: break; + case OpArgR: checkreg(pt, r); break; + case OpArgK: + check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize); + break; + } + return 1; +} + + +static Instruction symbexec (const Proto *pt, int lastpc, int reg) { + int pc; + int last; /* stores position of last instruction that changed `reg' */ + last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */ + check(precheck(pt)); + for (pc = 0; pc < lastpc; pc++) { + Instruction i = pt->code[pc]; + OpCode op = GET_OPCODE(i); + int a = GETARG_A(i); + int b = 0; + int c = 0; + check(op < NUM_OPCODES); + checkreg(pt, a); + switch (getOpMode(op)) { + case iABC: { + b = GETARG_B(i); + c = GETARG_C(i); + check(checkArgMode(pt, b, getBMode(op))); + check(checkArgMode(pt, c, getCMode(op))); + break; + } + case iABx: { + b = GETARG_Bx(i); + if (getBMode(op) == OpArgK) check(b < pt->sizek); + break; + } + case iAsBx: { + b = GETARG_sBx(i); + if (getBMode(op) == OpArgR) { + int dest = pc+1+b; + check(0 <= dest && dest < pt->sizecode); + if (dest > 0) { + /* cannot jump to a setlist count */ + Instruction d = pt->code[dest-1]; + check(!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)); + } + } + break; + } + } + if (testAMode(op)) { + if (a == reg) last = pc; /* change register `a' */ + } + if (testTMode(op)) { + check(pc+2 < pt->sizecode); /* check skip */ + check(GET_OPCODE(pt->code[pc+1]) == OP_JMP); + } + switch (op) { + case OP_LOADBOOL: { + check(c == 0 || pc+2 < pt->sizecode); /* check its jump */ + break; + } + case OP_LOADNIL: { + if (a <= reg && reg <= b) + last = pc; /* set registers from `a' to `b' */ + break; + } + case OP_GETUPVAL: + case OP_SETUPVAL: { + check(b < pt->nups); + break; + } + case OP_GETGLOBAL: + case OP_SETGLOBAL: { + check(ttisstring(&pt->k[b])); + break; + } + case OP_SELF: { + checkreg(pt, a+1); + if (reg == a+1) last = pc; + break; + } + case OP_CONCAT: { + check(b < c); /* at least two operands */ + break; + } + case OP_TFORLOOP: { + check(c >= 1); /* at least one result (control variable) */ + checkreg(pt, a+2+c); /* space for results */ + if (reg >= a+2) last = pc; /* affect all regs above its base */ + break; + } + case OP_FORLOOP: + case OP_FORPREP: + checkreg(pt, a+3); + /* go through */ + case OP_JMP: { + int dest = pc+1+b; + /* not full check and jump is forward and do not skip `lastpc'? */ + if (reg != NO_REG && pc < dest && dest <= lastpc) + pc += b; /* do the jump */ + break; + } + case OP_CALL: + case OP_TAILCALL: { + if (b != 0) { + checkreg(pt, a+b-1); + } + c--; /* c = num. returns */ + if (c == LUA_MULTRET) { + check(checkopenop(pt, pc)); + } + else if (c != 0) + checkreg(pt, a+c-1); + if (reg >= a) last = pc; /* affect all registers above base */ + break; + } + case OP_RETURN: { + b--; /* b = num. returns */ + if (b > 0) checkreg(pt, a+b-1); + break; + } + case OP_SETLIST: { + if (b > 0) checkreg(pt, a + b); + if (c == 0) pc++; + break; + } + case OP_CLOSURE: { + int nup; + check(b < pt->sizep); + nup = pt->p[b]->nups; + check(pc + nup < pt->sizecode); + for (; nup>0; nup--) { + OpCode op1 = GET_OPCODE(pt->code[pc+nup]); + check(op1 == OP_GETUPVAL || op1 == OP_MOVE); + } + break; + } + case OP_VARARG: { + check((pt->is_vararg & VARARG_ISVARARG) && + !(pt->is_vararg & VARARG_NEEDSARG)); + b--; + if (b == LUA_MULTRET) check(checkopenop(pt, pc)); + checkreg(pt, a+b-1); + break; + } + default: break; + } + } + return pt->code[last]; +} + +#undef check +#undef checkjump +#undef checkreg + +/* }====================================================== */ + + +int luaG_checkcode (const Proto *pt) { + return (symbexec(pt, pt->sizecode, NO_REG) != 0); +} + + +static const char *kname (Proto *p, int c) { + if (ISK(c) && ttisstring(&p->k[INDEXK(c)])) + return svalue(&p->k[INDEXK(c)]); + else + return "?"; +} + + +static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos, + const char **name) { + if (isLua(ci)) { /* a Lua function? */ + Proto *p = ci_func(ci)->l.p; + int pc = currentpc(L, ci); + Instruction i; + *name = luaF_getlocalname(p, stackpos+1, pc); + if (*name) /* is a local? */ + return "local"; + i = symbexec(p, pc, stackpos); /* try symbolic execution */ + lua_assert(pc != -1); + switch (GET_OPCODE(i)) { + case OP_GETGLOBAL: { + int g = GETARG_Bx(i); /* global index */ + lua_assert(ttisstring(&p->k[g])); + *name = svalue(&p->k[g]); + return "global"; + } + case OP_MOVE: { + int a = GETARG_A(i); + int b = GETARG_B(i); /* move from `b' to `a' */ + if (b < a) + return getobjname(L, ci, b, name); /* get name for `b' */ + break; + } + case OP_GETTABLE: { + int k = GETARG_C(i); /* key index */ + *name = kname(p, k); + return "field"; + } + case OP_GETUPVAL: { + int u = GETARG_B(i); /* upvalue index */ + *name = p->upvalues ? getstr(p->upvalues[u]) : "?"; + return "upvalue"; + } + case OP_SELF: { + int k = GETARG_C(i); /* key index */ + *name = kname(p, k); + return "method"; + } + default: break; + } + } + return NULL; /* no useful name found */ +} + + +static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { + Instruction i; + if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1)) + return NULL; /* calling function is not Lua (or is unknown) */ + ci--; /* calling function */ + i = ci_func(ci)->l.p->code[currentpc(L, ci)]; + if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL || + GET_OPCODE(i) == OP_TFORLOOP) + return getobjname(L, ci, GETARG_A(i), name); + else + return NULL; /* no useful name can be found */ +} + + +/* only ANSI way to check whether a pointer points to an array */ +static int isinstack (CallInfo *ci, const TValue *o) { + StkId p; + for (p = ci->base; p < ci->top; p++) + if (o == p) return 1; + return 0; +} + + +void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { + const char *name = NULL; + const char *t = luaT_typenames[ttype(o)]; + const char *kind = (isinstack(L->ci, o)) ? + getobjname(L, L->ci, cast_int(o - L->base), &name) : + NULL; + if (kind) + luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", + op, kind, name, t); + else + luaG_runerror(L, "attempt to %s a %s value", op, t); +} + + +void luaG_concaterror (lua_State *L, StkId p1, StkId p2) { + if (ttisstring(p1)) p1 = p2; + lua_assert(!ttisstring(p1)); + luaG_typeerror(L, p1, "concatenate"); +} + + +void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { + TValue temp; + if (luaV_tonumber(p1, &temp) == NULL) + p2 = p1; /* first operand is wrong */ + luaG_typeerror(L, p2, "perform arithmetic on"); +} + + +int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { + const char *t1 = luaT_typenames[ttype(p1)]; + const char *t2 = luaT_typenames[ttype(p2)]; + if (t1[2] == t2[2]) + luaG_runerror(L, "attempt to compare two %s values", t1); + else + luaG_runerror(L, "attempt to compare %s with %s", t1, t2); + return 0; +} + + +static void addinfo (lua_State *L, const char *msg) { + CallInfo *ci = L->ci; + if (isLua(ci)) { /* is Lua code? */ + char buff[LUA_IDSIZE]; /* add file:line information */ + int line = currentline(L, ci); + luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE); + luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); + } +} + + +void luaG_errormsg (lua_State *L) { + if (L->errfunc != 0) { /* is there an error handling function? */ + StkId errfunc = restorestack(L, L->errfunc); + if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); + setobjs2s(L, L->top, L->top - 1); /* move argument */ + setobjs2s(L, L->top - 1, errfunc); /* push function */ + incr_top(L); + luaD_call(L, L->top - 2, 1); /* call it */ + } + luaD_throw(L, LUA_ERRRUN); +} + + +void luaG_runerror (lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + addinfo(L, luaO_pushvfstring(L, fmt, argp)); + va_end(argp); + luaG_errormsg(L); +} + diff --git a/src/lua/ldebug.h b/src/lua/ldebug.h new file mode 100644 index 0000000..9c76aa1 --- /dev/null +++ b/src/lua/ldebug.h @@ -0,0 +1,33 @@ +/* +** $Id: ldebug.h,v 2.3 2005/04/25 19:24:10 roberto Exp $ +** 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) + +#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) + +#define resethookcount(L) (L->hookcount = L->basehookcount) + + +LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o, + const char *opname); +LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2); +LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1, + const TValue *p2); +LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); +LUAI_FUNC void luaG_errormsg (lua_State *L); +LUAI_FUNC int luaG_checkcode (const Proto *pt); +LUAI_FUNC int luaG_checkopenop (Instruction i); + +#endif diff --git a/src/lua/ldo.c b/src/lua/ldo.c new file mode 100644 index 0000000..b8eb1a8 --- /dev/null +++ b/src/lua/ldo.c @@ -0,0 +1,515 @@ +/* +** $Id: ldo.c,v 2.37 2005/12/22 16:19:56 roberto Exp $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define ldo_c +#define LUA_CORE + +#include "lua.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" + + + + +/* +** {====================================================== +** Error-recovery functions +** ======================================================= +*/ + + +/* 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: { + setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); + break; + } + case LUA_ERRERR: { + setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); + break; + } + case LUA_ERRSYNTAX: + case LUA_ERRRUN: { + setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ + break; + } + } + L->top = oldtop + 1; +} + + +static void restore_stack_limit (lua_State *L) { + lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); + if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ + int inuse = cast_int(L->ci - L->base_ci); + if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ + luaD_reallocCI(L, LUAI_MAXCALLS); + } +} + + +static void resetstack (lua_State *L, int status) { + L->ci = L->base_ci; + L->base = L->ci->base; + luaF_close(L, L->base); /* close eventual pending closures */ + luaD_seterrorobj(L, status, L->base); + L->nCcalls = 0; + L->allowhook = 1; + restore_stack_limit(L); + L->errfunc = 0; + L->errorJmp = NULL; +} + + +void luaD_throw (lua_State *L, int errcode) { + if (L->errorJmp) { + L->errorJmp->status = errcode; + LUAI_THROW(L, L->errorJmp); + } + else { + L->status = cast_byte(errcode); + if (G(L)->panic) { + resetstack(L, errcode); + lua_unlock(L); + G(L)->panic(L); + } + exit(EXIT_FAILURE); + } +} + + +int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { + struct lua_longjmp lj; + lj.status = 0; + 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 */ + return lj.status; +} + +/* }====================================================== */ + + +static void correctstack (lua_State *L, TValue *oldstack) { + CallInfo *ci; + GCObject *up; + L->top = (L->top - oldstack) + L->stack; + for (up = L->openupval; up != NULL; up = up->gch.next) + gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; + for (ci = L->base_ci; ci <= L->ci; ci++) { + ci->top = (ci->top - oldstack) + L->stack; + ci->base = (ci->base - oldstack) + L->stack; + ci->func = (ci->func - oldstack) + L->stack; + } + L->base = (L->base - oldstack) + L->stack; +} + + +void luaD_reallocstack (lua_State *L, int newsize) { + TValue *oldstack = L->stack; + int realsize = newsize + 1 + EXTRA_STACK; + lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); + luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue); + L->stacksize = realsize; + L->stack_last = L->stack+newsize; + correctstack(L, oldstack); +} + + +void luaD_reallocCI (lua_State *L, int newsize) { + CallInfo *oldci = L->base_ci; + luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo); + L->size_ci = newsize; + L->ci = (L->ci - oldci) + L->base_ci; + L->end_ci = L->base_ci + L->size_ci - 1; +} + + +void luaD_growstack (lua_State *L, int n) { + if (n <= L->stacksize) /* double size is enough? */ + luaD_reallocstack(L, 2*L->stacksize); + else + luaD_reallocstack(L, L->stacksize + n); +} + + +static CallInfo *growCI (lua_State *L) { + if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ + luaD_throw(L, LUA_ERRERR); + else { + luaD_reallocCI(L, 2*L->size_ci); + if (L->size_ci > LUAI_MAXCALLS) + luaG_runerror(L, "stack overflow"); + } + return ++L->ci; +} + + +void luaD_callhook (lua_State *L, int event, int line) { + lua_Hook hook = L->hook; + if (hook && L->allowhook) { + ptrdiff_t top = savestack(L, L->top); + ptrdiff_t ci_top = savestack(L, L->ci->top); + lua_Debug ar; + ar.event = event; + ar.currentline = line; + if (event == LUA_HOOKTAILRET) + ar.i_ci = 0; /* tail call; no debug information about it */ + else + ar.i_ci = cast_int(L->ci - L->base_ci); + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + L->ci->top = L->top + LUA_MINSTACK; + lua_assert(L->ci->top <= L->stack_last); + L->allowhook = 0; /* cannot call hooks inside a hook */ + lua_unlock(L); + (*hook)(L, &ar); + lua_lock(L); + lua_assert(!L->allowhook); + L->allowhook = 1; + L->ci->top = restorestack(L, ci_top); + L->top = restorestack(L, top); + } +} + + +static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { + int i; + int nfixargs = p->numparams; + Table *htab = NULL; + StkId base, fixed; + for (; actual < nfixargs; ++actual) + setnilvalue(L->top++); +#if defined(LUA_COMPAT_VARARG) + if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */ + int nvar = actual - nfixargs; /* number of extra arguments */ + lua_assert(p->is_vararg & VARARG_HASARG); + luaC_checkGC(L); + htab = luaH_new(L, nvar, 1); /* create `arg' table */ + for (i=0; itop - nvar + i); + /* store counter in field `n' */ + setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); + } +#endif + /* move fixed parameters to final position */ + fixed = L->top - actual; /* first fixed argument */ + base = L->top; /* final position of first argument */ + for (i=0; itop++, fixed+i); + setnilvalue(fixed+i); + } + /* add `arg' parameter */ + if (htab) { + sethvalue(L, L->top++, htab); + lua_assert(iswhite(obj2gco(htab))); + } + return base; +} + + +static StkId tryfuncTM (lua_State *L, StkId func) { + const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); + StkId p; + ptrdiff_t funcr = savestack(L, func); + if (!ttisfunction(tm)) + luaG_typeerror(L, func, "call"); + /* Open a hole inside the stack at `func' */ + for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); + incr_top(L); + func = restorestack(L, funcr); /* previous call may change stack */ + setobj2s(L, func, tm); /* tag method is the new function to be called */ + return func; +} + + + +#define inc_ci(L) \ + ((L->ci == L->end_ci) ? growCI(L) : \ + (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci)) + + +int luaD_precall (lua_State *L, StkId func, int nresults) { + LClosure *cl; + ptrdiff_t funcr; + if (!ttisfunction(func)) /* `func' is not a function? */ + func = tryfuncTM(L, func); /* check the `function' tag method */ + funcr = savestack(L, func); + cl = &clvalue(func)->l; + L->ci->savedpc = L->savedpc; + if (!cl->isC) { /* Lua function? prepare its call */ + CallInfo *ci; + StkId st, base; + Proto *p = cl->p; + luaD_checkstack(L, p->maxstacksize); + func = restorestack(L, funcr); + if (!p->is_vararg) { /* no varargs? */ + base = func + 1; + if (L->top > base + p->numparams) + L->top = base + p->numparams; + } + else { /* vararg function */ + int nargs = cast_int(L->top - func) - 1; + base = adjust_varargs(L, p, nargs); + func = restorestack(L, funcr); /* previous call may change the stack */ + } + ci = inc_ci(L); /* now `enter' new function */ + ci->func = func; + L->base = ci->base = base; + ci->top = L->base + p->maxstacksize; + lua_assert(ci->top <= L->stack_last); + L->savedpc = p->code; /* starting point */ + ci->tailcalls = 0; + ci->nresults = nresults; + for (st = L->top; st < ci->top; st++) + setnilvalue(st); + L->top = ci->top; + if (L->hookmask & LUA_MASKCALL) { + L->savedpc++; /* hooks assume 'pc' is already incremented */ + luaD_callhook(L, LUA_HOOKCALL, -1); + L->savedpc--; /* correct 'pc' */ + } + return PCRLUA; + } + else { /* if is a C function, call it */ + CallInfo *ci; + int n; + luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + ci = inc_ci(L); /* now `enter' new function */ + ci->func = restorestack(L, funcr); + L->base = ci->base = ci->func + 1; + ci->top = L->top + LUA_MINSTACK; + lua_assert(ci->top <= L->stack_last); + ci->nresults = nresults; + if (L->hookmask & LUA_MASKCALL) + luaD_callhook(L, LUA_HOOKCALL, -1); + lua_unlock(L); + n = (*curr_func(L)->c.f)(L); /* do the actual call */ + lua_lock(L); + if (n < 0) /* yielding? */ + return PCRYIELD; + else { + luaD_poscall(L, L->top - n); + return PCRC; + } + } +} + + +static StkId callrethooks (lua_State *L, StkId firstResult) { + ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ + luaD_callhook(L, LUA_HOOKRET, -1); + if (f_isLua(L->ci)) { /* Lua function? */ + while (L->ci->tailcalls--) /* call hook for eventual tail calls */ + luaD_callhook(L, LUA_HOOKTAILRET, -1); + } + return restorestack(L, fr); +} + + +int luaD_poscall (lua_State *L, StkId firstResult) { + StkId res; + int wanted, i; + CallInfo *ci; + if (L->hookmask & LUA_MASKRET) + firstResult = callrethooks(L, firstResult); + ci = L->ci--; + res = ci->func; /* res == final position of 1st result */ + wanted = ci->nresults; + L->base = (ci - 1)->base; /* restore base */ + L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ + /* move results to correct place */ + for (i = wanted; i != 0 && firstResult < L->top; i--) + setobjs2s(L, res++, firstResult++); + while (i-- > 0) + setnilvalue(res++); + L->top = res; + return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ +} + + +/* +** Call a function (C or Lua). The function to be called is at *func. +** The arguments are on the stack, right after the function. +** When returns, all the results are on the stack, starting at the original +** function position. +*/ +void luaD_call (lua_State *L, StkId func, int nResults) { + if (++L->nCcalls >= LUAI_MAXCCALLS) { + if (L->nCcalls == LUAI_MAXCCALLS) + luaG_runerror(L, "C stack overflow"); + else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) + luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ + } + if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ + luaV_execute(L, 1); /* call it */ + L->nCcalls--; + luaC_checkGC(L); +} + + +static void resume (lua_State *L, void *ud) { + StkId firstArg = cast(StkId, ud); + CallInfo *ci = L->ci; + if (L->status != LUA_YIELD) { /* start coroutine */ + lua_assert(ci == L->base_ci && firstArg > L->base); + if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) + return; + } + else { /* resuming from previous yield */ + if (!f_isLua(ci)) { /* `common' yield? */ + /* finish interrupted execution of `OP_CALL' */ + lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL || + GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL); + if (luaD_poscall(L, firstArg)) /* complete it... */ + L->top = L->ci->top; /* and correct top if not multiple results */ + } + else /* yielded inside a hook: just continue its execution */ + L->base = L->ci->base; + } + L->status = 0; + luaV_execute(L, cast_int(L->ci - L->base_ci)); +} + + +static int resume_error (lua_State *L, const char *msg) { + L->top = L->ci->base; + setsvalue2s(L, L->top, luaS_new(L, msg)); + incr_top(L); + lua_unlock(L); + return LUA_ERRRUN; +} + + +LUA_API int lua_resume (lua_State *L, int nargs) { + int status; + lua_lock(L); + if (L->status != LUA_YIELD) { + if (L->status != 0) + return resume_error(L, "cannot resume dead coroutine"); + else if (L->ci != L->base_ci) + return resume_error(L, "cannot resume non-suspended coroutine"); + } + luai_userstateresume(L, nargs); + lua_assert(L->errfunc == 0 && L->nCcalls == 0); + status = luaD_rawrunprotected(L, resume, L->top - nargs); + if (status != 0) { /* error? */ + L->status = cast_byte(status); /* mark thread as `dead' */ + luaD_seterrorobj(L, status, L->top); + L->ci->top = L->top; + } + else + status = L->status; + lua_unlock(L); + return status; +} + + +LUA_API int lua_yield (lua_State *L, int nresults) { + luai_userstateyield(L, nresults); + lua_lock(L); + if (L->nCcalls > 0) + luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); + L->base = L->top - nresults; /* protect stack slots below */ + L->status = LUA_YIELD; + lua_unlock(L); + return -1; +} + + +int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t old_top, ptrdiff_t ef) { + int status; + unsigned short oldnCcalls = L->nCcalls; + ptrdiff_t old_ci = saveci(L, L->ci); + lu_byte old_allowhooks = L->allowhook; + ptrdiff_t old_errfunc = L->errfunc; + L->errfunc = ef; + status = luaD_rawrunprotected(L, func, u); + if (status != 0) { /* an error occurred? */ + StkId oldtop = restorestack(L, old_top); + luaF_close(L, oldtop); /* close eventual pending closures */ + luaD_seterrorobj(L, status, oldtop); + L->nCcalls = oldnCcalls; + L->ci = restoreci(L, old_ci); + L->base = L->ci->base; + L->savedpc = L->ci->savedpc; + L->allowhook = old_allowhooks; + restore_stack_limit(L); + } + L->errfunc = old_errfunc; + return status; +} + + + +/* +** Execute a protected parser. +*/ +struct SParser { /* data to `f_parser' */ + ZIO *z; + Mbuffer buff; /* buffer to be used by the scanner */ + const char *name; +}; + +static void f_parser (lua_State *L, void *ud) { + int i; + Proto *tf; + Closure *cl; + struct SParser *p = cast(struct SParser *, ud); + int c = luaZ_lookahead(p->z); + luaC_checkGC(L); + tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, + &p->buff, p->name); + cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); + cl->l.p = tf; + for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ + cl->l.upvals[i] = luaF_newupval(L); + setclvalue(L, L->top, cl); + incr_top(L); +} + + +int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { + struct SParser p; + int status; + p.z = z; p.name = name; + luaZ_initbuffer(L, &p.buff); + status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); + luaZ_freebuffer(L, &p.buff); + return status; +} + + diff --git a/src/lua/ldo.h b/src/lua/ldo.h new file mode 100644 index 0000000..b2de92b --- /dev/null +++ b/src/lua/ldo.h @@ -0,0 +1,57 @@ +/* +** $Id: ldo.h,v 2.7 2005/08/24 16:15:49 roberto Exp $ +** Stack and Call structure of Lua +** See Copyright Notice in lua.h +*/ + +#ifndef ldo_h +#define ldo_h + + +#include "lobject.h" +#include "lstate.h" +#include "lzio.h" + + +#define luaD_checkstack(L,n) \ + if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \ + luaD_growstack(L, n); \ + else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); + + +#define incr_top(L) {luaD_checkstack(L,1); L->top++;} + +#define savestack(L,p) ((char *)(p) - (char *)L->stack) +#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) + +#define saveci(L,p) ((char *)(p) - (char *)L->base_ci) +#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n))) + + +/* results from luaD_precall */ +#define PCRLUA 0 /* initiated a call to a Lua function */ +#define PCRC 1 /* did a call to a C function */ +#define PCRYIELD 2 /* C funtion yielded */ + + +/* type of protected functions, to be ran by `runprotected' */ +typedef void (*Pfunc) (lua_State *L, void *ud); + +LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name); +LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line); +LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); +LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); +LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, + ptrdiff_t oldtop, ptrdiff_t ef); +LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult); +LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize); +LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); +LUAI_FUNC void luaD_growstack (lua_State *L, int n); + +LUAI_FUNC void luaD_throw (lua_State *L, int errcode); +LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); + +LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); + +#endif + diff --git a/src/lua/ldump.c b/src/lua/ldump.c new file mode 100644 index 0000000..f08277d --- /dev/null +++ b/src/lua/ldump.c @@ -0,0 +1,164 @@ +/* +** $Id: ldump.c,v 1.15 2006/02/16 15:53:49 lhf Exp $ +** save precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#include + +#define ldump_c +#define LUA_CORE + +#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; + +#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D) +#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D) + +static void DumpBlock(const void* b, size_t size, DumpState* D) +{ + if (D->status==0) + { + lua_unlock(D->L); + D->status=(*D->writer)(D->L,b,size,D->data); + lua_lock(D->L); + } +} + +static void DumpChar(int y, DumpState* D) +{ + char x=(char)y; + DumpVar(x,D); +} + +static void DumpInt(int x, DumpState* D) +{ + DumpVar(x,D); +} + +static void DumpNumber(lua_Number x, DumpState* D) +{ + DumpVar(x,D); +} + +static void DumpVector(const void* b, int n, size_t size, DumpState* D) +{ + DumpInt(n,D); + DumpMem(b,n,size,D); +} + +static void DumpString(const TString* s, DumpState* D) +{ + if (s==NULL || getstr(s)==NULL) + { + size_t size=0; + DumpVar(size,D); + } + else + { + size_t size=s->tsv.len+1; /* include trailing '\0' */ + DumpVar(size,D); + DumpBlock(getstr(s),size,D); + } +} + +#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D) + +static void DumpFunction(const Proto* f, const TString* p, DumpState* D); + +static void DumpConstants(const Proto* f, DumpState* D) +{ + int i,n=f->sizek; + DumpInt(n,D); + for (i=0; ik[i]; + DumpChar(ttype(o),D); + switch (ttype(o)) + { + case LUA_TNIL: + break; + case LUA_TBOOLEAN: + DumpChar(bvalue(o),D); + break; + case LUA_TNUMBER: + DumpNumber(nvalue(o),D); + break; + case LUA_TSTRING: + DumpString(rawtsvalue(o),D); + break; + default: + lua_assert(0); /* cannot happen */ + break; + } + } + n=f->sizep; + DumpInt(n,D); + for (i=0; ip[i],f->source,D); +} + +static void DumpDebug(const Proto* f, DumpState* D) +{ + int i,n; + n= (D->strip) ? 0 : f->sizelineinfo; + DumpVector(f->lineinfo,n,sizeof(int),D); + n= (D->strip) ? 0 : f->sizelocvars; + DumpInt(n,D); + for (i=0; ilocvars[i].varname,D); + DumpInt(f->locvars[i].startpc,D); + DumpInt(f->locvars[i].endpc,D); + } + n= (D->strip) ? 0 : f->sizeupvalues; + DumpInt(n,D); + for (i=0; iupvalues[i],D); +} + +static void DumpFunction(const Proto* f, const TString* p, DumpState* D) +{ + DumpString((f->source==p || D->strip) ? NULL : f->source,D); + DumpInt(f->linedefined,D); + DumpInt(f->lastlinedefined,D); + DumpChar(f->nups,D); + DumpChar(f->numparams,D); + DumpChar(f->is_vararg,D); + DumpChar(f->maxstacksize,D); + DumpCode(f,D); + DumpConstants(f,D); + DumpDebug(f,D); +} + +static void DumpHeader(DumpState* D) +{ + char h[LUAC_HEADERSIZE]; + luaU_header(h); + DumpBlock(h,LUAC_HEADERSIZE,D); +} + +/* +** 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); + DumpFunction(f,NULL,&D); + return D.status; +} diff --git a/src/lua/lfunc.c b/src/lua/lfunc.c new file mode 100644 index 0000000..b8cd67b --- /dev/null +++ b/src/lua/lfunc.c @@ -0,0 +1,174 @@ +/* +** $Id: lfunc.c,v 2.12 2005/12/22 16:19:56 roberto Exp $ +** Auxiliary functions to manipulate prototypes and closures +** See Copyright Notice in lua.h +*/ + + +#include + +#define lfunc_c +#define LUA_CORE + +#include "lua.h" + +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" + + + +Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) { + Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems))); + luaC_link(L, obj2gco(c), LUA_TFUNCTION); + c->c.isC = 1; + c->c.env = e; + c->c.nupvalues = cast_byte(nelems); + return c; +} + + +Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) { + Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems))); + luaC_link(L, obj2gco(c), LUA_TFUNCTION); + c->l.isC = 0; + c->l.env = e; + c->l.nupvalues = cast_byte(nelems); + while (nelems--) c->l.upvals[nelems] = NULL; + return c; +} + + +UpVal *luaF_newupval (lua_State *L) { + UpVal *uv = luaM_new(L, UpVal); + luaC_link(L, obj2gco(uv), LUA_TUPVAL); + uv->v = &uv->u.value; + setnilvalue(uv->v); + return uv; +} + + +UpVal *luaF_findupval (lua_State *L, StkId level) { + global_State *g = G(L); + GCObject **pp = &L->openupval; + UpVal *p; + UpVal *uv; + while ((p = ngcotouv(*pp)) != NULL && p->v >= level) { + lua_assert(p->v != &p->u.value); + if (p->v == level) { /* found a corresponding upvalue? */ + if (isdead(g, obj2gco(p))) /* is it dead? */ + changewhite(obj2gco(p)); /* ressurect it */ + return p; + } + pp = &p->next; + } + uv = luaM_new(L, UpVal); /* not found: create a new one */ + uv->tt = LUA_TUPVAL; + uv->marked = luaC_white(g); + uv->v = level; /* current value lives in the stack */ + uv->next = *pp; /* chain it in the proper position */ + *pp = obj2gco(uv); + uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */ + uv->u.l.next = g->uvhead.u.l.next; + uv->u.l.next->u.l.prev = uv; + g->uvhead.u.l.next = uv; + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + return uv; +} + + +static void unlinkupval (UpVal *uv) { + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */ + uv->u.l.prev->u.l.next = uv->u.l.next; +} + + +void luaF_freeupval (lua_State *L, UpVal *uv) { + if (uv->v != &uv->u.value) /* is it open? */ + unlinkupval(uv); /* remove from open list */ + luaM_free(L, uv); /* free upvalue */ +} + + +void luaF_close (lua_State *L, StkId level) { + UpVal *uv; + global_State *g = G(L); + while ((uv = ngcotouv(L->openupval)) != NULL && uv->v >= level) { + GCObject *o = obj2gco(uv); + lua_assert(!isblack(o) && uv->v != &uv->u.value); + L->openupval = uv->next; /* remove from `open' list */ + if (isdead(g, o)) + luaF_freeupval(L, uv); /* free upvalue */ + else { + unlinkupval(uv); + setobj(L, &uv->u.value, uv->v); + uv->v = &uv->u.value; /* now current value lives here */ + luaC_linkupval(L, uv); /* link upvalue into `gcroot' list */ + } + } +} + + +Proto *luaF_newproto (lua_State *L) { + Proto *f = luaM_new(L, Proto); + luaC_link(L, obj2gco(f), LUA_TPROTO); + f->k = NULL; + f->sizek = 0; + f->p = NULL; + f->sizep = 0; + f->code = NULL; + f->sizecode = 0; + f->sizelineinfo = 0; + f->sizeupvalues = 0; + f->nups = 0; + f->upvalues = NULL; + f->numparams = 0; + f->is_vararg = 0; + f->maxstacksize = 0; + f->lineinfo = NULL; + f->sizelocvars = 0; + f->locvars = NULL; + 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, Instruction); + luaM_freearray(L, f->p, f->sizep, Proto *); + luaM_freearray(L, f->k, f->sizek, TValue); + luaM_freearray(L, f->lineinfo, f->sizelineinfo, int); + luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); + luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); + luaM_free(L, f); +} + + +void luaF_freeclosure (lua_State *L, Closure *c) { + int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) : + sizeLclosure(c->l.nupvalues); + luaM_freemem(L, c, size); +} + + +/* +** 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/lua/lfunc.h b/src/lua/lfunc.h new file mode 100644 index 0000000..2e02419 --- /dev/null +++ b/src/lua/lfunc.h @@ -0,0 +1,34 @@ +/* +** $Id: lfunc.h,v 2.4 2005/04/25 19:24:10 roberto Exp $ +** 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, sizeof(CClosure)) + \ + cast(int, sizeof(TValue)*((n)-1))) + +#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ + cast(int, sizeof(TValue *)*((n)-1))) + + +LUAI_FUNC Proto *luaF_newproto (lua_State *L); +LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); +LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); +LUAI_FUNC UpVal *luaF_newupval (lua_State *L); +LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); +LUAI_FUNC void luaF_close (lua_State *L, StkId level); +LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); +LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); +LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); +LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, + int pc); + + +#endif diff --git a/src/lua/lgc.c b/src/lua/lgc.c new file mode 100644 index 0000000..691565d --- /dev/null +++ b/src/lua/lgc.c @@ -0,0 +1,707 @@ +/* +** $Id: lgc.c,v 2.37 2005/12/22 16:19:56 roberto Exp $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#include + +#define lgc_c +#define LUA_CORE + +#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" + + +#define GCSTEPSIZE 1024u +#define GCSWEEPMAX 40 +#define GCSWEEPCOST 10 +#define GCFINALIZECOST 100 + + +#define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS)) + +#define makewhite(g,x) \ + ((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g))) + +#define white2gray(x) reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) +#define black2gray(x) resetbit((x)->gch.marked, BLACKBIT) + +#define stringmark(s) reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT) + + +#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT) +#define markfinalized(u) l_setbit((u)->marked, FINALIZEDBIT) + + +#define KEYWEAK bitmask(KEYWEAKBIT) +#define VALUEWEAK bitmask(VALUEWEAKBIT) + + + +#define markvalue(g,o) { checkconsistency(o); \ + if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); } + +#define markobject(g,t) { if (iswhite(obj2gco(t))) \ + reallymarkobject(g, obj2gco(t)); } + + +#define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause) + + +static void removeentry (Node *n) { + lua_assert(ttisnil(gval(n))); + if (iscollectable(gkey(n))) + setttype(gkey(n), LUA_TDEADKEY); /* dead key; remove it */ +} + + +static void reallymarkobject (global_State *g, GCObject *o) { + lua_assert(iswhite(o) && !isdead(g, o)); + white2gray(o); + switch (o->gch.tt) { + case LUA_TSTRING: { + return; + } + case LUA_TUSERDATA: { + Table *mt = gco2u(o)->metatable; + gray2black(o); /* udata are never gray */ + if (mt) markobject(g, mt); + markobject(g, gco2u(o)->env); + return; + } + case LUA_TUPVAL: { + UpVal *uv = gco2uv(o); + markvalue(g, uv->v); + if (uv->v == &uv->u.value) /* closed? */ + gray2black(o); /* open upvalues are never black */ + return; + } + case LUA_TFUNCTION: { + gco2cl(o)->c.gclist = g->gray; + g->gray = o; + break; + } + case LUA_TTABLE: { + gco2h(o)->gclist = g->gray; + g->gray = o; + break; + } + case LUA_TTHREAD: { + gco2th(o)->gclist = g->gray; + g->gray = o; + break; + } + case LUA_TPROTO: { + gco2p(o)->gclist = g->gray; + g->gray = o; + break; + } + default: lua_assert(0); + } +} + + +static void marktmu (global_State *g) { + GCObject *u = g->tmudata; + if (u) { + do { + u = u->gch.next; + makewhite(g, u); /* may be marked, if left from previous GC */ + reallymarkobject(g, u); + } while (u != g->tmudata); + } +} + + +/* move `dead' udata that need finalization to list `tmudata' */ +size_t luaC_separateudata (lua_State *L, int all) { + global_State *g = G(L); + size_t deadmem = 0; + GCObject **p = &g->mainthread->next; + GCObject *curr; + while ((curr = *p) != NULL) { + if (!(iswhite(curr) || all) || isfinalized(gco2u(curr))) + p = &curr->gch.next; /* don't bother with them */ + else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) { + markfinalized(gco2u(curr)); /* don't need finalization */ + p = &curr->gch.next; + } + else { /* must call its gc method */ + deadmem += sizeudata(gco2u(curr)); + markfinalized(gco2u(curr)); + *p = curr->gch.next; + /* link `curr' at the end of `tmudata' list */ + if (g->tmudata == NULL) /* list is empty? */ + g->tmudata = curr->gch.next = curr; /* creates a circular list */ + else { + curr->gch.next = g->tmudata->gch.next; + g->tmudata->gch.next = curr; + g->tmudata = curr; + } + } + } + return deadmem; +} + + +static int traversetable (global_State *g, Table *h) { + int i; + int weakkey = 0; + int weakvalue = 0; + const TValue *mode; + if (h->metatable) + markobject(g, h->metatable); + mode = gfasttm(g, h->metatable, TM_MODE); + if (mode && ttisstring(mode)) { /* is there a weak mode? */ + weakkey = (strchr(svalue(mode), 'k') != NULL); + weakvalue = (strchr(svalue(mode), 'v') != NULL); + if (weakkey || weakvalue) { /* is really weak? */ + h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */ + h->marked |= cast_byte((weakkey << KEYWEAKBIT) | + (weakvalue << VALUEWEAKBIT)); + h->gclist = g->weak; /* must be cleared after GC, ... */ + g->weak = obj2gco(h); /* ... so put in the appropriate list */ + } + } + if (weakkey && weakvalue) return 1; + if (!weakvalue) { + i = h->sizearray; + while (i--) + markvalue(g, &h->array[i]); + } + i = sizenode(h); + while (i--) { + Node *n = gnode(h, i); + lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n))); + if (ttisnil(gval(n))) + removeentry(n); /* remove empty entries */ + else { + lua_assert(!ttisnil(gkey(n))); + if (!weakkey) markvalue(g, gkey(n)); + if (!weakvalue) markvalue(g, gval(n)); + } + } + return weakkey || weakvalue; +} + + +/* +** All marks are conditional because a GC may happen while the +** prototype is still being created +*/ +static void traverseproto (global_State *g, Proto *f) { + int i; + if (f->source) stringmark(f->source); + for (i=0; isizek; i++) /* mark literals */ + markvalue(g, &f->k[i]); + for (i=0; isizeupvalues; i++) { /* mark upvalue names */ + if (f->upvalues[i]) + stringmark(f->upvalues[i]); + } + for (i=0; isizep; i++) { /* mark nested protos */ + if (f->p[i]) + markobject(g, f->p[i]); + } + for (i=0; isizelocvars; i++) { /* mark local-variable names */ + if (f->locvars[i].varname) + stringmark(f->locvars[i].varname); + } +} + + + +static void traverseclosure (global_State *g, Closure *cl) { + markobject(g, cl->c.env); + if (cl->c.isC) { + int i; + for (i=0; ic.nupvalues; i++) /* mark its upvalues */ + markvalue(g, &cl->c.upvalue[i]); + } + else { + int i; + lua_assert(cl->l.nupvalues == cl->l.p->nups); + markobject(g, cl->l.p); + for (i=0; il.nupvalues; i++) /* mark its upvalues */ + markobject(g, cl->l.upvals[i]); + } +} + + +static void checkstacksizes (lua_State *L, StkId max) { + int ci_used = cast_int(L->ci - L->base_ci); /* number of `ci' in use */ + int s_used = cast_int(max - L->stack); /* part of stack in use */ + if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */ + return; /* do not touch the stacks */ + if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci) + luaD_reallocCI(L, L->size_ci/2); /* still big enough... */ + condhardstacktests(luaD_reallocCI(L, ci_used + 1)); + if (4*s_used < L->stacksize && + 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize) + luaD_reallocstack(L, L->stacksize/2); /* still big enough... */ + condhardstacktests(luaD_reallocstack(L, s_used)); +} + + +static void traversestack (global_State *g, lua_State *l) { + StkId o, lim; + CallInfo *ci; + markvalue(g, gt(l)); + lim = l->top; + for (ci = l->base_ci; ci <= l->ci; ci++) { + lua_assert(ci->top <= l->stack_last); + if (lim < ci->top) lim = ci->top; + } + for (o = l->stack; o < l->top; o++) + markvalue(g, o); + for (; o <= lim; o++) + setnilvalue(o); + checkstacksizes(l, lim); +} + + +/* +** traverse one gray object, turning it to black. +** Returns `quantity' traversed. +*/ +static l_mem propagatemark (global_State *g) { + GCObject *o = g->gray; + lua_assert(isgray(o)); + gray2black(o); + switch (o->gch.tt) { + case LUA_TTABLE: { + Table *h = gco2h(o); + g->gray = h->gclist; + if (traversetable(g, h)) /* table is weak? */ + black2gray(o); /* keep it gray */ + return sizeof(Table) + sizeof(TValue) * h->sizearray + + sizeof(Node) * sizenode(h); + } + case LUA_TFUNCTION: { + Closure *cl = gco2cl(o); + g->gray = cl->c.gclist; + traverseclosure(g, cl); + return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) : + sizeLclosure(cl->l.nupvalues); + } + case LUA_TTHREAD: { + lua_State *th = gco2th(o); + g->gray = th->gclist; + th->gclist = g->grayagain; + g->grayagain = o; + black2gray(o); + traversestack(g, th); + return sizeof(lua_State) + sizeof(TValue) * th->stacksize + + sizeof(CallInfo) * th->size_ci; + } + case LUA_TPROTO: { + Proto *p = gco2p(o); + g->gray = p->gclist; + traverseproto(g, p); + return sizeof(Proto) + sizeof(Instruction) * p->sizecode + + sizeof(Proto *) * p->sizep + + sizeof(TValue) * p->sizek + + sizeof(int) * p->sizelineinfo + + sizeof(LocVar) * p->sizelocvars + + sizeof(TString *) * p->sizeupvalues; + } + default: lua_assert(0); return 0; + } +} + + +static void propagateall (global_State *g) { + while (g->gray) propagatemark(g); +} + + +/* +** The next function 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 userdata +** being finalized, keep them in keys, but not in values +*/ +static int iscleared (const TValue *o, int iskey) { + if (!iscollectable(o)) return 0; + if (ttisstring(o)) { + stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */ + return 0; + } + return iswhite(gcvalue(o)) || + (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o)))); +} + + +/* +** clear collected entries from weaktables +*/ +static void cleartable (GCObject *l) { + while (l) { + Table *h = gco2h(l); + int i = h->sizearray; + lua_assert(testbit(h->marked, VALUEWEAKBIT) || + testbit(h->marked, KEYWEAKBIT)); + if (testbit(h->marked, VALUEWEAKBIT)) { + while (i--) { + TValue *o = &h->array[i]; + if (iscleared(o, 0)) /* value was collected? */ + setnilvalue(o); /* remove value */ + } + } + i = sizenode(h); + while (i--) { + Node *n = gnode(h, i); + if (!ttisnil(gval(n)) && /* non-empty entry? */ + (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) { + setnilvalue(gval(n)); /* remove value ... */ + removeentry(n); /* remove entry from table */ + } + } + l = h->gclist; + } +} + + +static void freeobj (lua_State *L, GCObject *o) { + switch (o->gch.tt) { + case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; + case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break; + case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; + case LUA_TTABLE: luaH_free(L, gco2h(o)); break; + case LUA_TTHREAD: { + lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread); + luaE_freethread(L, gco2th(o)); + break; + } + case LUA_TSTRING: { + G(L)->strt.nuse--; + luaM_freemem(L, o, sizestring(gco2ts(o))); + break; + } + case LUA_TUSERDATA: { + luaM_freemem(L, o, sizeudata(gco2u(o))); + break; + } + default: lua_assert(0); + } +} + + + +#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) + + +static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { + GCObject *curr; + global_State *g = G(L); + int deadmask = otherwhite(g); + while ((curr = *p) != NULL && count-- > 0) { + if (curr->gch.tt == LUA_TTHREAD) /* sweep open upvalues of each thread */ + sweepwholelist(L, &gco2th(curr)->openupval); + if ((curr->gch.marked ^ WHITEBITS) & deadmask) { /* not dead? */ + lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT)); + makewhite(g, curr); /* make it white (for next cycle) */ + p = &curr->gch.next; + } + else { /* must erase `curr' */ + lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT)); + *p = curr->gch.next; + if (curr == g->rootgc) /* is the first element of the list? */ + g->rootgc = curr->gch.next; /* adjust first */ + freeobj(L, curr); + } + } + return p; +} + + +static void checkSizes (lua_State *L) { + global_State *g = G(L); + /* check size of string hash */ + if (g->strt.nuse < cast(lu_int32, g->strt.size/4) && + g->strt.size > MINSTRTABSIZE*2) + luaS_resize(L, g->strt.size/2); /* table is too big */ + /* check size of buffer */ + if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) { /* buffer too big? */ + size_t newsize = luaZ_sizebuffer(&g->buff) / 2; + luaZ_resizebuffer(L, &g->buff, newsize); + } +} + + +static void GCTM (lua_State *L) { + global_State *g = G(L); + GCObject *o = g->tmudata->gch.next; /* get first element */ + Udata *udata = rawgco2u(o); + const TValue *tm; + /* remove udata from `tmudata' */ + if (o == g->tmudata) /* last element? */ + g->tmudata = NULL; + else + g->tmudata->gch.next = udata->uv.next; + udata->uv.next = g->mainthread->next; /* return it to `root' list */ + g->mainthread->next = o; + makewhite(g, o); + tm = fasttm(L, udata->uv.metatable, TM_GC); + if (tm != NULL) { + lu_byte oldah = L->allowhook; + lu_mem oldt = g->GCthreshold; + L->allowhook = 0; /* stop debug hooks during GC tag method */ + g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */ + setobj2s(L, L->top, tm); + setuvalue(L, L->top+1, udata); + L->top += 2; + luaD_call(L, L->top - 2, 0); + L->allowhook = oldah; /* restore hooks */ + g->GCthreshold = oldt; /* restore threshold */ + } +} + + +/* +** Call all GC tag methods +*/ +void luaC_callGCTM (lua_State *L) { + while (G(L)->tmudata) + GCTM(L); +} + + +void luaC_freeall (lua_State *L) { + global_State *g = G(L); + int i; + g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT); /* mask to collect all elements */ + sweepwholelist(L, &g->rootgc); + for (i = 0; i < g->strt.size; i++) /* free all string lists */ + sweepwholelist(L, &g->strt.hash[i]); +} + + +static void markmt (global_State *g) { + int i; + for (i=0; imt[i]) markobject(g, g->mt[i]); +} + + +/* mark root set */ +static void markroot (lua_State *L) { + global_State *g = G(L); + g->gray = NULL; + g->grayagain = NULL; + g->weak = NULL; + markobject(g, g->mainthread); + /* make global table be traversed before main stack */ + markvalue(g, gt(g->mainthread)); + markvalue(g, registry(L)); + markmt(g); + g->gcstate = GCSpropagate; +} + + +static void remarkupvals (global_State *g) { + UpVal *uv; + for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { + lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); + if (isgray(obj2gco(uv))) + markvalue(g, uv->v); + } +} + + +static void atomic (lua_State *L) { + global_State *g = G(L); + size_t udsize; /* total size of userdata to be finalized */ + /* remark occasional upvalues of (maybe) dead threads */ + remarkupvals(g); + /* traverse objects cautch by write barrier and by 'remarkupvals' */ + propagateall(g); + /* remark weak tables */ + g->gray = g->weak; + g->weak = NULL; + lua_assert(!iswhite(obj2gco(g->mainthread))); + markobject(g, L); /* mark running thread */ + markmt(g); /* mark basic metatables (again) */ + propagateall(g); + /* remark gray again */ + g->gray = g->grayagain; + g->grayagain = NULL; + propagateall(g); + udsize = luaC_separateudata(L, 0); /* separate userdata to be finalized */ + marktmu(g); /* mark `preserved' userdata */ + propagateall(g); /* remark, to propagate `preserveness' */ + cleartable(g->weak); /* remove collected objects from weak tables */ + /* flip current white */ + g->currentwhite = cast_byte(otherwhite(g)); + g->sweepstrgc = 0; + g->sweepgc = &g->rootgc; + g->gcstate = GCSsweepstring; + g->estimate = g->totalbytes - udsize; /* first estimate */ +} + + +static l_mem singlestep (lua_State *L) { + global_State *g = G(L); + /*lua_checkmemory(L);*/ + switch (g->gcstate) { + case GCSpause: { + markroot(L); /* start a new collection */ + return 0; + } + case GCSpropagate: { + if (g->gray) + return propagatemark(g); + else { /* no more `gray' objects */ + atomic(L); /* finish mark phase */ + return 0; + } + } + case GCSsweepstring: { + lu_mem old = g->totalbytes; + sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]); + if (g->sweepstrgc >= g->strt.size) /* nothing more to sweep? */ + g->gcstate = GCSsweep; /* end sweep-string phase */ + lua_assert(old >= g->totalbytes); + g->estimate -= old - g->totalbytes; + return GCSWEEPCOST; + } + case GCSsweep: { + lu_mem old = g->totalbytes; + g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); + if (*g->sweepgc == NULL) { /* nothing more to sweep? */ + checkSizes(L); + g->gcstate = GCSfinalize; /* end sweep phase */ + } + lua_assert(old >= g->totalbytes); + g->estimate -= old - g->totalbytes; + return GCSWEEPMAX*GCSWEEPCOST; + } + case GCSfinalize: { + if (g->tmudata) { + GCTM(L); + return GCFINALIZECOST; + } + else { + g->gcstate = GCSpause; /* end collection */ + g->gcdept = 0; + return 0; + } + } + default: lua_assert(0); return 0; + } +} + + +void luaC_step (lua_State *L) { + global_State *g = G(L); + l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul; + if (lim == 0) + lim = (MAX_LUMEM-1)/2; /* no limit */ + g->gcdept += g->totalbytes - g->GCthreshold; + do { + lim -= singlestep(L); + if (g->gcstate == GCSpause) + break; + } while (lim > 0); + if (g->gcstate != GCSpause) { + if (g->gcdept < GCSTEPSIZE) + g->GCthreshold = g->totalbytes + GCSTEPSIZE; /* - lim/g->gcstepmul;*/ + else { + g->gcdept -= GCSTEPSIZE; + g->GCthreshold = g->totalbytes; + } + } + else { + lua_assert(g->totalbytes >= g->estimate); + setthreshold(g); + } +} + + +void luaC_fullgc (lua_State *L) { + global_State *g = G(L); + if (g->gcstate <= GCSpropagate) { + /* reset sweep marks to sweep all elements (returning them to white) */ + g->sweepstrgc = 0; + g->sweepgc = &g->rootgc; + /* reset other collector lists */ + g->gray = NULL; + g->grayagain = NULL; + g->weak = NULL; + g->gcstate = GCSsweepstring; + } + lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate); + /* finish any pending sweep phase */ + while (g->gcstate != GCSfinalize) { + lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep); + singlestep(L); + } + markroot(L); + while (g->gcstate != GCSpause) { + singlestep(L); + } + setthreshold(g); +} + + +void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) { + global_State *g = G(L); + lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); + lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); + lua_assert(ttype(&o->gch) != LUA_TTABLE); + /* must keep invariant? */ + if (g->gcstate == GCSpropagate) + reallymarkobject(g, v); /* restore invariant */ + else /* don't mind */ + makewhite(g, o); /* mark as white just to avoid other barriers */ +} + + +void luaC_barrierback (lua_State *L, Table *t) { + global_State *g = G(L); + GCObject *o = obj2gco(t); + lua_assert(isblack(o) && !isdead(g, o)); + lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); + black2gray(o); /* make table gray (again) */ + t->gclist = g->grayagain; + g->grayagain = o; +} + + +void luaC_link (lua_State *L, GCObject *o, lu_byte tt) { + global_State *g = G(L); + o->gch.next = g->rootgc; + g->rootgc = o; + o->gch.marked = luaC_white(g); + o->gch.tt = tt; +} + + +void luaC_linkupval (lua_State *L, UpVal *uv) { + global_State *g = G(L); + GCObject *o = obj2gco(uv); + o->gch.next = g->rootgc; /* link upvalue into `rootgc' list */ + g->rootgc = o; + if (isgray(o)) { + if (g->gcstate == GCSpropagate) { + gray2black(o); /* closed upvalues need barrier */ + luaC_barrier(L, uv, uv->v); + } + else { /* sweep phase: sweep it (turning it into white) */ + makewhite(g, o); + lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); + } + } +} + diff --git a/src/lua/lgc.h b/src/lua/lgc.h new file mode 100644 index 0000000..5f69acb --- /dev/null +++ b/src/lua/lgc.h @@ -0,0 +1,110 @@ +/* +** $Id: lgc.h,v 2.15 2005/08/24 16:15:49 roberto Exp $ +** Garbage Collector +** See Copyright Notice in lua.h +*/ + +#ifndef lgc_h +#define lgc_h + + +#include "lobject.h" + + +/* +** Possible states of the Garbage Collector +*/ +#define GCSpause 0 +#define GCSpropagate 1 +#define GCSsweepstring 2 +#define GCSsweep 3 +#define GCSfinalize 4 + + +/* +** some userful bit tricks +*/ +#define resetbits(x,m) ((x) &= cast(lu_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)) +#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2))) +#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2))) +#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2))) + + + +/* +** Layout for bit use in `marked' field: +** bit 0 - object is white (type 0) +** bit 1 - object is white (type 1) +** bit 2 - object is black +** bit 3 - for userdata: has been finalized +** bit 3 - for tables: has weak keys +** bit 4 - for tables: has weak values +** bit 5 - object is fixed (should not be collected) +** bit 6 - object is "super" fixed (only the main thread) +*/ + + +#define WHITE0BIT 0 +#define WHITE1BIT 1 +#define BLACKBIT 2 +#define FINALIZEDBIT 3 +#define KEYWEAKBIT 3 +#define VALUEWEAKBIT 4 +#define FIXEDBIT 5 +#define SFIXEDBIT 6 +#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) + + +#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) +#define isblack(x) testbit((x)->gch.marked, BLACKBIT) +#define isgray(x) (!isblack(x) && !iswhite(x)) + +#define otherwhite(g) (g->currentwhite ^ WHITEBITS) +#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS) + +#define changewhite(x) ((x)->gch.marked ^= WHITEBITS) +#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) + +#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) + +#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) + + +#define luaC_checkGC(L) { \ + condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \ + if (G(L)->totalbytes >= G(L)->GCthreshold) \ + luaC_step(L); } + + +#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ + luaC_barrierf(L,obj2gco(p),gcvalue(v)); } + +#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \ + luaC_barrierback(L,t); } + +#define luaC_objbarrier(L,p,o) \ + { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ + luaC_barrierf(L,obj2gco(p),obj2gco(o)); } + +#define luaC_objbarriert(L,t,o) \ + { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); } + +LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all); +LUAI_FUNC void luaC_callGCTM (lua_State *L); +LUAI_FUNC void luaC_freeall (lua_State *L); +LUAI_FUNC void luaC_step (lua_State *L); +LUAI_FUNC void luaC_fullgc (lua_State *L); +LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt); +LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv); +LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v); +LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t); + + +#endif diff --git a/src/lua/linit.c b/src/lua/linit.c new file mode 100644 index 0000000..483d9c8 --- /dev/null +++ b/src/lua/linit.c @@ -0,0 +1,38 @@ +/* +** $Id: linit.c,v 1.14 2005/12/29 15:32:11 roberto Exp $ +** Initialization of libraries for lua.c +** See Copyright Notice in lua.h +*/ + + +#define linit_c +#define LUA_LIB + +#include "lua.h" + +#include "lualib.h" +#include "lauxlib.h" + + +static const luaL_Reg lualibs[] = { + {"", luaopen_base}, + {LUA_LOADLIBNAME, luaopen_package}, + {LUA_TABLIBNAME, luaopen_table}, + {LUA_IOLIBNAME, luaopen_io}, + {LUA_OSLIBNAME, luaopen_os}, + {LUA_STRLIBNAME, luaopen_string}, + {LUA_MATHLIBNAME, luaopen_math}, + {LUA_DBLIBNAME, luaopen_debug}, + {NULL, NULL} +}; + + +LUALIB_API void luaL_openlibs (lua_State *L) { + const luaL_Reg *lib = lualibs; + for (; lib->func; lib++) { + lua_pushcfunction(L, lib->func); + lua_pushstring(L, lib->name); + lua_call(L, 1, 0); + } +} + diff --git a/src/lua/liolib.c b/src/lua/liolib.c new file mode 100644 index 0000000..bb3b519 --- /dev/null +++ b/src/lua/liolib.c @@ -0,0 +1,532 @@ +/* +** $Id: liolib.c,v 2.72 2006/01/28 12:59:13 roberto Exp $ +** Standard I/O (and system) library +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include + +#define liolib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + + +#define IO_INPUT 1 +#define IO_OUTPUT 2 + + +static const char *const fnames[] = {"input", "output"}; + + +static int pushresult (lua_State *L, int i, const char *filename) { + int en = errno; /* calls to Lua API may change this value */ + if (i) { + lua_pushboolean(L, 1); + return 1; + } + else { + lua_pushnil(L); + if (filename) + lua_pushfstring(L, "%s: %s", filename, strerror(en)); + else + lua_pushfstring(L, "%s", strerror(en)); + lua_pushinteger(L, en); + return 3; + } +} + + +static void fileerror (lua_State *L, int arg, const char *filename) { + lua_pushfstring(L, "%s: %s", filename, strerror(errno)); + luaL_argerror(L, arg, lua_tostring(L, -1)); +} + + +#define topfile(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE)) + + +static int io_type (lua_State *L) { + void *ud; + luaL_checkany(L, 1); + ud = lua_touserdata(L, 1); + lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE); + if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1)) + lua_pushnil(L); /* not a file */ + else if (*((FILE **)ud) == NULL) + lua_pushliteral(L, "closed file"); + else + lua_pushliteral(L, "file"); + return 1; +} + + +static FILE *tofile (lua_State *L) { + FILE **f = topfile(L); + if (*f == NULL) + luaL_error(L, "attempt to use a closed file"); + return *f; +} + + + +/* +** When creating file handles, always creates a `closed' file handle +** before opening the actual file; so, if there is a memory error, the +** file is not left opened. +*/ +static FILE **newfile (lua_State *L) { + FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); + *pf = NULL; /* file handle is currently `closed' */ + luaL_getmetatable(L, LUA_FILEHANDLE); + lua_setmetatable(L, -2); + return pf; +} + + +/* +** this function has a separated environment, which defines the +** correct __close for 'popen' files +*/ +static int io_pclose (lua_State *L) { + FILE **p = topfile(L); + int ok = lua_pclose(L, *p); + if (ok) *p = NULL; + return pushresult(L, ok, NULL); +} + + +static int io_fclose (lua_State *L) { + FILE **p = topfile(L); + int ok = (fclose(*p) == 0); + if (ok) *p = NULL; + return pushresult(L, ok, NULL); +} + + +static int aux_close (lua_State *L) { + lua_getfenv(L, 1); + lua_getfield(L, -1, "__close"); + return (lua_tocfunction(L, -1))(L); +} + + +static int io_close (lua_State *L) { + if (lua_isnone(L, 1)) + lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT); + tofile(L); /* make sure argument is a file */ + return aux_close(L); +} + + +static int io_gc (lua_State *L) { + FILE *f = *topfile(L); + /* ignore closed files and standard files */ + if (f != NULL && f != stdin && f != stdout && f != stderr) + aux_close(L); + return 0; +} + + +static int io_tostring (lua_State *L) { + FILE *f = *topfile(L); + if (f == NULL) + lua_pushstring(L, "file (closed)"); + else + lua_pushfstring(L, "file (%p)", f); + return 1; +} + + +static int io_open (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + const char *mode = luaL_optstring(L, 2, "r"); + FILE **pf = newfile(L); + *pf = fopen(filename, mode); + return (*pf == NULL) ? pushresult(L, 0, filename) : 1; +} + + +static int io_popen (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + const char *mode = luaL_optstring(L, 2, "r"); + FILE **pf = newfile(L); + *pf = lua_popen(L, filename, mode); + return (*pf == NULL) ? pushresult(L, 0, filename) : 1; +} + + +static int io_tmpfile (lua_State *L) { + FILE **pf = newfile(L); + *pf = tmpfile(); + return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; +} + + +static FILE *getiofile (lua_State *L, int findex) { + FILE *f; + lua_rawgeti(L, LUA_ENVIRONINDEX, findex); + f = *(FILE **)lua_touserdata(L, -1); + if (f == NULL) + luaL_error(L, "standard %s file is closed", fnames[findex - 1]); + return f; +} + + +static int g_iofile (lua_State *L, int f, const char *mode) { + if (!lua_isnoneornil(L, 1)) { + const char *filename = lua_tostring(L, 1); + if (filename) { + FILE **pf = newfile(L); + *pf = fopen(filename, mode); + if (*pf == NULL) + fileerror(L, 1, filename); + } + else { + tofile(L); /* check that it's a valid file handle */ + lua_pushvalue(L, 1); + } + lua_rawseti(L, LUA_ENVIRONINDEX, f); + } + /* return current value */ + lua_rawgeti(L, LUA_ENVIRONINDEX, 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); + + +static void aux_lines (lua_State *L, int idx, int toclose) { + lua_pushvalue(L, idx); + lua_pushboolean(L, toclose); /* close/not close file when finished */ + lua_pushcclosure(L, io_readline, 2); +} + + +static int f_lines (lua_State *L) { + tofile(L); /* check that it's a valid file handle */ + aux_lines(L, 1, 0); + return 1; +} + + +static int io_lines (lua_State *L) { + if (lua_isnoneornil(L, 1)) { /* no arguments? */ + /* will iterate over default input */ + lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT); + return f_lines(L); + } + else { + const char *filename = luaL_checkstring(L, 1); + FILE **pf = newfile(L); + *pf = fopen(filename, "r"); + if (*pf == NULL) + fileerror(L, 1, filename); + aux_lines(L, lua_gettop(L), 1); + return 1; + } +} + + +/* +** {====================================================== +** READ +** ======================================================= +*/ + + +static int read_number (lua_State *L, FILE *f) { + lua_Number d; + if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { + lua_pushnumber(L, d); + return 1; + } + else return 0; /* read fails */ +} + + +static int test_eof (lua_State *L, FILE *f) { + int c = getc(f); + ungetc(c, f); + lua_pushlstring(L, NULL, 0); + return (c != EOF); +} + + +static int read_line (lua_State *L, FILE *f) { + luaL_Buffer b; + luaL_buffinit(L, &b); + for (;;) { + size_t l; + char *p = luaL_prepbuffer(&b); + if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ + luaL_pushresult(&b); /* close buffer */ + return (lua_strlen(L, -1) > 0); /* check whether read something */ + } + l = strlen(p); + if (l == 0 || p[l-1] != '\n') + luaL_addsize(&b, l); + else { + luaL_addsize(&b, l - 1); /* do not include `eol' */ + luaL_pushresult(&b); /* close buffer */ + return 1; /* read at least an `eol' */ + } + } +} + + +static int read_chars (lua_State *L, FILE *f, size_t n) { + size_t rlen; /* how much to read */ + size_t nr; /* number of chars actually read */ + luaL_Buffer b; + luaL_buffinit(L, &b); + rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ + do { + char *p = luaL_prepbuffer(&b); + if (rlen > n) rlen = n; /* cannot read more than asked */ + nr = fread(p, sizeof(char), rlen, f); + luaL_addsize(&b, nr); + n -= nr; /* still have to read `n' chars */ + } while (n > 0 && nr == rlen); /* until end of count or eof */ + luaL_pushresult(&b); /* close buffer */ + return (n == 0 || lua_strlen(L, -1) > 0); +} + + +static int g_read (lua_State *L, FILE *f, int first) { + int nargs = lua_gettop(L) - 1; + int success; + int n; + clearerr(f); + if (nargs == 0) { /* no arguments? */ + success = read_line(L, f); + 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)lua_tointeger(L, n); + success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); + } + else { + const char *p = lua_tostring(L, n); + luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); + switch (p[1]) { + case 'n': /* number */ + success = read_number(L, f); + break; + case 'l': /* line */ + success = read_line(L, f); + break; + case 'a': /* file */ + read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */ + success = 1; /* always success */ + break; + default: + return luaL_argerror(L, n, "invalid format"); + } + } + } + } + if (ferror(f)) + return pushresult(L, 0, NULL); + if (!success) { + lua_pop(L, 1); /* remove last result */ + lua_pushnil(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); +} + + +static int io_readline (lua_State *L) { + FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); + int sucess; + if (f == NULL) /* file is already closed? */ + luaL_error(L, "file is already closed"); + sucess = read_line(L, f); + if (ferror(f)) + return luaL_error(L, "%s", strerror(errno)); + if (sucess) return 1; + else { /* EOF */ + if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */ + lua_settop(L, 0); + lua_pushvalue(L, lua_upvalueindex(1)); + aux_close(L); /* close it */ + } + return 0; + } +} + +/* }====================================================== */ + + +static int g_write (lua_State *L, FILE *f, int arg) { + int nargs = lua_gettop(L) - 1; + int status = 1; + for (; nargs--; arg++) { + if (lua_type(L, arg) == LUA_TNUMBER) { + /* optimization: could be done exactly as for strings */ + status = status && + fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; + } + else { + size_t l; + const char *s = luaL_checklstring(L, arg, &l); + status = status && (fwrite(s, sizeof(char), l, f) == l); + } + } + return pushresult(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) { + return g_write(L, tofile(L), 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); + long offset = luaL_optlong(L, 3, 0); + op = fseek(f, offset, mode[op]); + if (op) + return pushresult(L, 0, NULL); /* error */ + else { + lua_pushinteger(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], sz); + return pushresult(L, res == 0, NULL); +} + + + +static int io_flush (lua_State *L) { + return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); +} + + +static int f_flush (lua_State *L) { + return pushresult(L, fflush(tofile(L)) == 0, NULL); +} + + +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} +}; + + +static const luaL_Reg flib[] = { + {"close", io_close}, + {"flush", f_flush}, + {"lines", f_lines}, + {"read", f_read}, + {"seek", f_seek}, + {"setvbuf", f_setvbuf}, + {"write", f_write}, + {"__gc", io_gc}, + {"__tostring", io_tostring}, + {NULL, NULL} +}; + + +static void createmeta (lua_State *L) { + luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ + lua_pushvalue(L, -1); /* push metatable */ + lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ + luaL_register(L, NULL, flib); /* file methods */ +} + + +static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) { + *newfile(L) = f; + if (k > 0) { + lua_pushvalue(L, -1); + lua_rawseti(L, LUA_ENVIRONINDEX, k); + } + lua_setfield(L, -2, fname); +} + + +LUALIB_API int luaopen_io (lua_State *L) { + createmeta(L); + /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */ + lua_createtable(L, 2, 1); + lua_replace(L, LUA_ENVIRONINDEX); + /* open library */ + luaL_register(L, LUA_IOLIBNAME, iolib); + /* create (and set) default files */ + createstdfile(L, stdin, IO_INPUT, "stdin"); + createstdfile(L, stdout, IO_OUTPUT, "stdout"); + createstdfile(L, stderr, 0, "stderr"); + /* create environment for 'popen' */ + lua_getfield(L, -1, "popen"); + lua_createtable(L, 0, 1); + lua_pushcfunction(L, io_pclose); + lua_setfield(L, -2, "__close"); + lua_setfenv(L, -2); + lua_pop(L, 1); /* pop 'popen' */ + /* set default close function */ + lua_pushcfunction(L, io_fclose); + lua_setfield(L, LUA_ENVIRONINDEX, "__close"); + return 1; +} + diff --git a/src/lua/llex.c b/src/lua/llex.c new file mode 100644 index 0000000..f3022df --- /dev/null +++ b/src/lua/llex.c @@ -0,0 +1,460 @@ +/* +** $Id: llex.c,v 2.19 2006/02/06 18:28:16 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define llex_c +#define LUA_CORE + +#include "lua.h" + +#include "ldo.h" +#include "llex.h" +#include "lobject.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "lzio.h" + + + +#define next(ls) (ls->current = zgetc(ls->z)) + + + + +#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') + + +/* ORDER RESERVED */ +const char *const luaX_tokens [] = { + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "if", + "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "..", "...", "==", ">=", "<=", "~=", + "", "", "", "", + NULL +}; + + +#define save_and_next(ls) (save(ls, ls->current), next(ls)) + + +static void save (LexState *ls, int c) { + Mbuffer *b = ls->buff; + if (b->n + 1 > b->buffsize) { + size_t newsize; + if (b->buffsize >= MAX_SIZET/2) + luaX_lexerror(ls, "lexical element too long", 0); + newsize = b->buffsize * 2; + luaZ_resizebuffer(ls->L, b, newsize); + } + b->buffer[b->n++] = cast(char, c); +} + + +void luaX_init (lua_State *L) { + int i; + for (i=0; itsv.reserved = cast_byte(i+1); /* reserved word */ + } +} + + +#define MAXSRC 80 + + +const char *luaX_token2str (LexState *ls, int token) { + if (token < FIRST_RESERVED) { + lua_assert(token == cast(unsigned char, token)); + return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) : + luaO_pushfstring(ls->L, "%c", token); + } + else + return luaX_tokens[token-FIRST_RESERVED]; +} + + +static const char *txtToken (LexState *ls, int token) { + switch (token) { + case TK_NAME: + case TK_STRING: + case TK_NUMBER: + save(ls, '\0'); + return luaZ_buffer(ls->buff); + default: + return luaX_token2str(ls, token); + } +} + + +void luaX_lexerror (LexState *ls, const char *msg, int token) { + char buff[MAXSRC]; + luaO_chunkid(buff, getstr(ls->source), MAXSRC); + msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); + if (token) + luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token)); + luaD_throw(ls->L, LUA_ERRSYNTAX); +} + + +void luaX_syntaxerror (LexState *ls, const char *msg) { + luaX_lexerror(ls, msg, ls->t.token); +} + + +TString *luaX_newstring (LexState *ls, const char *str, size_t l) { + lua_State *L = ls->L; + TString *ts = luaS_newlstr(L, str, l); + TValue *o = luaH_setstr(L, ls->fs->h, ts); /* entry for `str' */ + if (ttisnil(o)) + setbvalue(o, 1); /* make sure `str' will not be collected */ + return ts; +} + + +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) + luaX_syntaxerror(ls, "chunk has too many lines"); +} + + +void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { + ls->decpoint = '.'; + ls->L = L; + ls->lookahead.token = TK_EOS; /* no look-ahead token */ + ls->z = z; + ls->fs = NULL; + ls->linenumber = 1; + ls->lastline = 1; + ls->source = source; + luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ + next(ls); /* read first char */ +} + + + +/* +** ======================================================= +** LEXICAL ANALYZER +** ======================================================= +*/ + + + +static int check_next (LexState *ls, const char *set) { + if (!strchr(set, ls->current)) + return 0; + save_and_next(ls); + return 1; +} + + +static void buffreplace (LexState *ls, char from, char to) { + size_t n = luaZ_bufflen(ls->buff); + char *p = luaZ_buffer(ls->buff); + while (n--) + if (p[n] == from) p[n] = to; +} + + +static void trydecpoint (LexState *ls, SemInfo *seminfo) { + /* format error: try to update decimal point separator */ + struct lconv *cv = localeconv(); + char old = ls->decpoint; + ls->decpoint = (cv ? cv->decimal_point[0] : '.'); + buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */ + if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) { + /* format error with correct decimal point: no more options */ + buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ + luaX_lexerror(ls, "malformed number", TK_NUMBER); + } +} + + +/* LUA_NUMBER */ +static void read_numeral (LexState *ls, SemInfo *seminfo) { + lua_assert(isdigit(ls->current)); + do { + save_and_next(ls); + } while (isdigit(ls->current) || ls->current == '.'); + if (check_next(ls, "Ee")) /* `E'? */ + check_next(ls, "+-"); /* optional exponent sign */ + while (isalnum(ls->current) || ls->current == '_') + save_and_next(ls); + save(ls, '\0'); + buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ + if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */ + trydecpoint(ls, seminfo); /* try to update decimal point separator */ +} + + +static int skip_sep (LexState *ls) { + int 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 : (-count) - 1; +} + + +static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { + int cont = 0; + (void)(cont); /* avoid warnings when `cont' is not used */ + save_and_next(ls); /* skip 2nd `[' */ + if (currIsNewline(ls)) /* string starts with a newline? */ + inclinenumber(ls); /* skip it */ + for (;;) { + switch (ls->current) { + case EOZ: + luaX_lexerror(ls, (seminfo) ? "unfinished long string" : + "unfinished long comment", TK_EOS); + break; /* to avoid warnings */ +#if defined(LUA_COMPAT_LSTR) + case '[': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd `[' */ + cont++; +#if LUA_COMPAT_LSTR == 1 + if (sep == 0) + luaX_lexerror(ls, "nesting of [[...]] is deprecated", '['); +#endif + } + break; + } +#endif + case ']': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd `]' */ +#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2 + cont--; + if (sep == 0 && cont >= 0) break; +#endif + 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) + (2 + sep), + luaZ_bufflen(ls->buff) - 2*(2 + sep)); +} + + +static void read_string (LexState *ls, int del, SemInfo *seminfo) { + save_and_next(ls); + while (ls->current != del) { + switch (ls->current) { + case EOZ: + luaX_lexerror(ls, "unfinished string", TK_EOS); + continue; /* to avoid warnings */ + case '\n': + case '\r': + luaX_lexerror(ls, "unfinished string", TK_STRING); + continue; /* to avoid warnings */ + case '\\': { + int c; + next(ls); /* do not save the `\' */ + switch (ls->current) { + case 'a': c = '\a'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'v': c = '\v'; break; + case '\n': /* go through */ + case '\r': save(ls, '\n'); inclinenumber(ls); continue; + case EOZ: continue; /* will raise an error next loop */ + default: { + if (!isdigit(ls->current)) + save_and_next(ls); /* handles \\, \", \', and \? */ + else { /* \xxx */ + int i = 0; + c = 0; + do { + c = 10*c + (ls->current-'0'); + next(ls); + } while (++i<3 && isdigit(ls->current)); + if (c > UCHAR_MAX) + luaX_lexerror(ls, "escape sequence too large", TK_STRING); + save(ls, c); + } + continue; + } + } + save(ls, c); + next(ls); + continue; + } + 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': { + inclinenumber(ls); + continue; + } + case '-': { + next(ls); + if (ls->current != '-') return '-'; + /* else is a comment */ + next(ls); + if (ls->current == '[') { + int sep = skip_sep(ls); + luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ + if (sep >= 0) { + read_long_string(ls, NULL, sep); /* long comment */ + luaZ_resetbuffer(ls->buff); + continue; + } + } + /* else short comment */ + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); + continue; + } + case '[': { + int sep = skip_sep(ls); + if (sep >= 0) { + read_long_string(ls, seminfo, sep); + return TK_STRING; + } + else if (sep == -1) return '['; + else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING); + } + case '=': { + next(ls); + if (ls->current != '=') return '='; + else { next(ls); return TK_EQ; } + } + case '<': { + next(ls); + if (ls->current != '=') return '<'; + else { next(ls); return TK_LE; } + } + case '>': { + next(ls); + if (ls->current != '=') return '>'; + else { next(ls); return TK_GE; } + } + case '~': { + next(ls); + if (ls->current != '=') return '~'; + else { next(ls); return TK_NE; } + } + case '"': + case '\'': { + read_string(ls, ls->current, seminfo); + return TK_STRING; + } + case '.': { + save_and_next(ls); + if (check_next(ls, ".")) { + if (check_next(ls, ".")) + return TK_DOTS; /* ... */ + else return TK_CONCAT; /* .. */ + } + else if (!isdigit(ls->current)) return '.'; + else { + read_numeral(ls, seminfo); + return TK_NUMBER; + } + } + case EOZ: { + return TK_EOS; + } + default: { + if (isspace(ls->current)) { + lua_assert(!currIsNewline(ls)); + next(ls); + continue; + } + else if (isdigit(ls->current)) { + read_numeral(ls, seminfo); + return TK_NUMBER; + } + else if (isalpha(ls->current) || ls->current == '_') { + /* identifier or reserved word */ + TString *ts; + do { + save_and_next(ls); + } while (isalnum(ls->current) || ls->current == '_'); + ts = luaX_newstring(ls, luaZ_buffer(ls->buff), + luaZ_bufflen(ls->buff)); + if (ts->tsv.reserved > 0) /* reserved word? */ + return ts->tsv.reserved - 1 + FIRST_RESERVED; + else { + seminfo->ts = ts; + return TK_NAME; + } + } + else { + int c = ls->current; + next(ls); + return c; /* single-char tokens (+ - / ...) */ + } + } + } + } +} + + +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 */ +} + + +void luaX_lookahead (LexState *ls) { + lua_assert(ls->lookahead.token == TK_EOS); + ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); +} + diff --git a/src/lua/llex.h b/src/lua/llex.h new file mode 100644 index 0000000..d4ca7f2 --- /dev/null +++ b/src/lua/llex.h @@ -0,0 +1,81 @@ +/* +** $Id: llex.h,v 1.57 2005/12/07 15:43:05 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + +#ifndef llex_h +#define llex_h + +#include "lobject.h" +#include "lzio.h" + + +#define FIRST_RESERVED 257 + +/* maximum length of a reserved word */ +#define TOKEN_LEN (sizeof("function")/sizeof(char)) + + +/* +* 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_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_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER, + TK_NAME, TK_STRING, TK_EOS +}; + +/* number of reserved words */ +#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) + + +/* array with token `names' */ +LUAI_DATA const char *const luaX_tokens []; + + +typedef union { + lua_Number r; + TString *ts; +} SemInfo; /* semantics information */ + + +typedef struct Token { + int token; + SemInfo seminfo; +} Token; + + +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; /* `FuncState' is private to the parser */ + struct lua_State *L; + ZIO *z; /* input stream */ + Mbuffer *buff; /* buffer for tokens */ + TString *source; /* current source name */ + char decpoint; /* locale decimal point */ +} LexState; + + +LUAI_FUNC void luaX_init (lua_State *L); +LUAI_FUNC void luaX_setinput (lua_State *L, LexState *LS, ZIO *z, + TString *source); +LUAI_FUNC TString *luaX_newstring (LexState *LS, const char *str, size_t l); +LUAI_FUNC void luaX_next (LexState *ls); +LUAI_FUNC void luaX_lookahead (LexState *ls); +LUAI_FUNC void luaX_lexerror (LexState *ls, const char *msg, int token); +LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s); +LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); + + +#endif diff --git a/src/lua/llimits.h b/src/lua/llimits.h new file mode 100644 index 0000000..b03221a --- /dev/null +++ b/src/lua/llimits.h @@ -0,0 +1,128 @@ +/* +** $Id: llimits.h,v 1.69 2005/12/27 17:12:00 roberto Exp $ +** 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" + + +typedef LUAI_UINT32 lu_int32; + +typedef LUAI_UMEM lu_mem; + +typedef LUAI_MEM l_mem; + + + +/* chars used as small naturals (so that `char' is reserved for characters) */ +typedef unsigned char lu_byte; + + +#define MAX_SIZET ((size_t)(~(size_t)0)-2) + +#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) + + +#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ + +/* +** conversion of pointer to integer +** this is for hashing only; there is no problem if the integer +** cannot hold the whole pointer value +*/ +#define IntPoint(p) ((unsigned int)(lu_mem)(p)) + + + +/* type to ensure maximum alignment */ +typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; + + +/* result of a `usual argument conversion' over lua_Number */ +typedef LUAI_UACNUMBER l_uacNumber; + + +/* internal assertions for in-house debugging */ +#ifdef lua_assert + +#define check_exp(c,e) (lua_assert(c), (e)) +#define api_check(l,e) lua_assert(e) + +#else + +#define lua_assert(c) ((void)0) +#define check_exp(c,e) (e) +#define api_check luai_apicheck + +#endif + + +#ifndef UNUSED +#define UNUSED(x) ((void)(x)) /* to avoid warnings */ +#endif + + +#ifndef cast +#define cast(t, exp) ((t)(exp)) +#endif + +#define cast_byte(i) cast(lu_byte, (i)) +#define cast_num(i) cast(lua_Number, (i)) +#define cast_int(i) cast(int, (i)) + + + +/* +** type for virtual-machine instructions +** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) +*/ +typedef lu_int32 Instruction; + + + +/* maximum stack for a Lua function */ +#define MAXSTACK 250 + + + +/* minimum size for the string table (must be power of 2) */ +#ifndef MINSTRTABSIZE +#define MINSTRTABSIZE 32 +#endif + + +/* minimum size for string buffer */ +#ifndef LUA_MINBUFFER +#define LUA_MINBUFFER 32 +#endif + + +#ifndef lua_lock +#define lua_lock(L) ((void) 0) +#define lua_unlock(L) ((void) 0) +#endif + +#ifndef luai_threadyield +#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} +#endif + + +/* +** macro to control inclusion of some hard tests on stack reallocation +*/ +#ifndef HARDSTACKTESTS +#define condhardstacktests(x) ((void)0) +#else +#define condhardstacktests(x) x +#endif + +#endif diff --git a/src/lua/lmathlib.c b/src/lua/lmathlib.c new file mode 100644 index 0000000..d181a73 --- /dev/null +++ b/src/lua/lmathlib.c @@ -0,0 +1,263 @@ +/* +** $Id: lmathlib.c,v 1.67 2005/08/26 17:36:32 roberto Exp $ +** Standard mathematical library +** See Copyright Notice in lua.h +*/ + + +#include +#include + +#define lmathlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#undef PI +#define PI (3.14159265358979323846) +#define RADIANS_PER_DEGREE (PI/180.0) + + + +static int math_abs (lua_State *L) { + lua_pushnumber(L, fabs(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sin (lua_State *L) { + lua_pushnumber(L, sin(luaL_checknumber(L, 1))); + return 1; +} + +static int math_sinh (lua_State *L) { + lua_pushnumber(L, sinh(luaL_checknumber(L, 1))); + return 1; +} + +static int math_cos (lua_State *L) { + lua_pushnumber(L, cos(luaL_checknumber(L, 1))); + return 1; +} + +static int math_cosh (lua_State *L) { + lua_pushnumber(L, cosh(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tan (lua_State *L) { + lua_pushnumber(L, tan(luaL_checknumber(L, 1))); + return 1; +} + +static int math_tanh (lua_State *L) { + lua_pushnumber(L, tanh(luaL_checknumber(L, 1))); + return 1; +} + +static int math_asin (lua_State *L) { + lua_pushnumber(L, asin(luaL_checknumber(L, 1))); + return 1; +} + +static int math_acos (lua_State *L) { + lua_pushnumber(L, acos(luaL_checknumber(L, 1))); + return 1; +} + +static int math_atan (lua_State *L) { + lua_pushnumber(L, atan(luaL_checknumber(L, 1))); + return 1; +} + +static int math_atan2 (lua_State *L) { + lua_pushnumber(L, atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); + return 1; +} + +static int math_ceil (lua_State *L) { + lua_pushnumber(L, ceil(luaL_checknumber(L, 1))); + return 1; +} + +static int math_floor (lua_State *L) { + lua_pushnumber(L, floor(luaL_checknumber(L, 1))); + return 1; +} + +static int math_fmod (lua_State *L) { + lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); + return 1; +} + +static int math_modf (lua_State *L) { + double ip; + double fp = modf(luaL_checknumber(L, 1), &ip); + lua_pushnumber(L, ip); + lua_pushnumber(L, fp); + return 2; +} + +static int math_sqrt (lua_State *L) { + lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); + return 1; +} + +static int math_pow (lua_State *L) { + lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); + return 1; +} + +static int math_log (lua_State *L) { + lua_pushnumber(L, log(luaL_checknumber(L, 1))); + return 1; +} + +static int math_log10 (lua_State *L) { + lua_pushnumber(L, log10(luaL_checknumber(L, 1))); + return 1; +} + +static int math_exp (lua_State *L) { + lua_pushnumber(L, exp(luaL_checknumber(L, 1))); + return 1; +} + +static int math_deg (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE); + return 1; +} + +static int math_rad (lua_State *L) { + lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE); + return 1; +} + +static int math_frexp (lua_State *L) { + int e; + lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e)); + lua_pushinteger(L, e); + return 2; +} + +static int math_ldexp (lua_State *L) { + lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2))); + return 1; +} + + + +static int math_min (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + lua_Number dmin = luaL_checknumber(L, 1); + int i; + for (i=2; i<=n; i++) { + lua_Number d = luaL_checknumber(L, i); + if (d < dmin) + dmin = d; + } + lua_pushnumber(L, dmin); + return 1; +} + + +static int math_max (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + lua_Number dmax = luaL_checknumber(L, 1); + int i; + for (i=2; i<=n; i++) { + lua_Number d = luaL_checknumber(L, i); + if (d > dmax) + dmax = d; + } + lua_pushnumber(L, dmax); + return 1; +} + + +static int math_random (lua_State *L) { + /* the `%' avoids the (rare) case of r==1, and is needed also because on + some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ + lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX; + switch (lua_gettop(L)) { /* check number of arguments */ + case 0: { /* no arguments */ + lua_pushnumber(L, r); /* Number between 0 and 1 */ + break; + } + case 1: { /* only upper limit */ + int u = luaL_checkint(L, 1); + luaL_argcheck(L, 1<=u, 1, "interval is empty"); + lua_pushnumber(L, floor(r*u)+1); /* int between 1 and `u' */ + break; + } + case 2: { /* lower and upper limits */ + int l = luaL_checkint(L, 1); + int u = luaL_checkint(L, 2); + luaL_argcheck(L, l<=u, 2, "interval is empty"); + lua_pushnumber(L, floor(r*(u-l+1))+l); /* int between `l' and `u' */ + break; + } + default: return luaL_error(L, "wrong number of arguments"); + } + return 1; +} + + +static int math_randomseed (lua_State *L) { + srand(luaL_checkint(L, 1)); + return 0; +} + + +static const luaL_Reg mathlib[] = { + {"abs", math_abs}, + {"acos", math_acos}, + {"asin", math_asin}, + {"atan2", math_atan2}, + {"atan", math_atan}, + {"ceil", math_ceil}, + {"cosh", math_cosh}, + {"cos", math_cos}, + {"deg", math_deg}, + {"exp", math_exp}, + {"floor", math_floor}, + {"fmod", math_fmod}, + {"frexp", math_frexp}, + {"ldexp", math_ldexp}, + {"log10", math_log10}, + {"log", math_log}, + {"max", math_max}, + {"min", math_min}, + {"modf", math_modf}, + {"pow", math_pow}, + {"rad", math_rad}, + {"random", math_random}, + {"randomseed", math_randomseed}, + {"sinh", math_sinh}, + {"sin", math_sin}, + {"sqrt", math_sqrt}, + {"tanh", math_tanh}, + {"tan", math_tan}, + {NULL, NULL} +}; + + +/* +** Open math library +*/ +LUALIB_API int luaopen_math (lua_State *L) { + luaL_register(L, LUA_MATHLIBNAME, mathlib); + lua_pushnumber(L, PI); + lua_setfield(L, -2, "pi"); + lua_pushnumber(L, HUGE_VAL); + lua_setfield(L, -2, "huge"); +#if defined(LUA_COMPAT_MOD) + lua_getfield(L, -1, "fmod"); + lua_setfield(L, -2, "mod"); +#endif + return 1; +} + diff --git a/src/lua/lmem.c b/src/lua/lmem.c new file mode 100644 index 0000000..cef2bc5 --- /dev/null +++ b/src/lua/lmem.c @@ -0,0 +1,86 @@ +/* +** $Id: lmem.c,v 1.70 2005/12/26 13:35:47 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + + +#include + +#define lmem_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.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) +** +** Lua ensures that (ptr == NULL) iff (osize == 0). +** +** * frealloc(ud, NULL, 0, x) creates a new block of size `x' +** +** * frealloc(ud, p, x, 0) frees the block `p' +** (in this specific case, frealloc must return NULL). +** particularly, frealloc(ud, NULL, 0, 0) does nothing +** (which is equivalent to free(NULL) in ANSI C) +** +** frealloc returns NULL if it cannot create or reallocate the area +** (any reallocation to an equal or smaller size cannot fail!) +*/ + + + +#define MINSIZEARRAY 4 + + +void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, + int limit, const char *errormsg) { + void *newblock; + int newsize; + if (*size >= limit/2) { /* cannot double it? */ + if (*size >= limit) /* cannot grow even a little? */ + luaG_runerror(L, errormsg); + newsize = limit; /* still have at least one free place */ + } + else { + newsize = (*size)*2; + if (newsize < MINSIZEARRAY) + newsize = MINSIZEARRAY; /* minimum size */ + } + newblock = luaM_reallocv(L, block, *size, newsize, size_elems); + *size = newsize; /* update only when everything else is OK */ + return newblock; +} + + +void *luaM_toobig (lua_State *L) { + luaG_runerror(L, "memory allocation error: block too big"); + return NULL; /* to avoid warnings */ +} + + + +/* +** generic allocation routine. +*/ +void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { + global_State *g = G(L); + lua_assert((osize == 0) == (block == NULL)); + block = (*g->frealloc)(g->ud, block, osize, nsize); + if (block == NULL && nsize > 0) + luaD_throw(L, LUA_ERRMEM); + lua_assert((nsize == 0) == (block == NULL)); + g->totalbytes = (g->totalbytes - osize) + nsize; + return block; +} + diff --git a/src/lua/lmem.h b/src/lua/lmem.h new file mode 100644 index 0000000..19df1fb --- /dev/null +++ b/src/lua/lmem.h @@ -0,0 +1,49 @@ +/* +** $Id: lmem.h,v 1.31 2005/04/25 19:24:10 roberto Exp $ +** Interface to Memory Manager +** See Copyright Notice in lua.h +*/ + +#ifndef lmem_h +#define lmem_h + + +#include + +#include "llimits.h" +#include "lua.h" + +#define MEMERRMSG "not enough memory" + + +#define luaM_reallocv(L,b,on,n,e) \ + ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \ + luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \ + luaM_toobig(L)) + +#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) +#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) +#define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t)) + +#define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t)) +#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) +#define luaM_newvector(L,n,t) \ + cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) + +#define luaM_growvector(L,v,nelems,size,t,limit,e) \ + if ((nelems)+1 > (size)) \ + ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) + +#define luaM_reallocvector(L, v,oldn,n,t) \ + ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) + + +LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, + size_t size); +LUAI_FUNC void *luaM_toobig (lua_State *L); +LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, + size_t size_elem, int limit, + const char *errormsg); + +#endif + diff --git a/src/lua/loadlib.c b/src/lua/loadlib.c new file mode 100644 index 0000000..19edaca --- /dev/null +++ b/src/lua/loadlib.c @@ -0,0 +1,667 @@ +/* +** $Id: loadlib.c,v 1.51 2005/12/29 15:32:11 roberto Exp $ +** 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 Darwin (Mac OS X), an +** implementation for Windows, and a stub for other systems. +*/ + + +#include +#include + + +#define loadlib_c +#define LUA_LIB + +#include "lauxlib.h" +#include "lobject.h" +#include "lua.h" +#include "lualib.h" + + +/* environment variables that hold the search path for packages */ +#define LUA_PATH "LUA_PATH" +#define LUA_CPATH "LUA_CPATH" + +/* prefix for open functions in C libraries */ +#define LUA_POF "luaopen_" + +/* separator for open functions in C libraries */ +#define LUA_OFSEP "_" + + +#define LIBPREFIX "LOADLIB: " + +#define POF LUA_POF +#define LIB_FAIL "open" + + +/* error codes for ll_loadfunc */ +#define ERRLIB 1 +#define ERRFUNC 2 + +#define setprogdir(L) ((void)0) + + +static void ll_unloadlib (void *lib); +static void *ll_load (lua_State *L, const char *path); +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym); + + + +#if defined(LUA_DL_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 + +static void ll_unloadlib (void *lib) { + dlclose(lib); +} + + +static void *ll_load (lua_State *L, const char *path) { + void *lib = dlopen(path, RTLD_NOW); + if (lib == NULL) lua_pushstring(L, dlerror()); + return lib; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)dlsym(lib, sym); + if (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 + + +#undef setprogdir + +static void setprogdir (lua_State *L) { + char buff[MAX_PATH + 1]; + char *lb; + DWORD nsize = sizeof(buff)/sizeof(char); + DWORD n = GetModuleFileName(NULL, buff, nsize); + if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) + luaL_error(L, "unable to get ModuleFileName"); + else { + *lb = '\0'; + luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff); + lua_remove(L, -2); /* remove original string */ + } +} + + +static void pusherror (lua_State *L) { + int error = GetLastError(); + char buffer[128]; + if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, error, 0, buffer, sizeof(buffer), NULL)) + lua_pushstring(L, buffer); + else + lua_pushfstring(L, "system error %d\n", error); +} + +static void ll_unloadlib (void *lib) { + FreeLibrary((HINSTANCE)lib); +} + + +static void *ll_load (lua_State *L, const char *path) { + HINSTANCE lib = LoadLibrary(path); + if (lib == NULL) pusherror(L); + return lib; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym); + if (f == NULL) pusherror(L); + return f; +} + +/* }====================================================== */ + + + +#elif defined(LUA_DL_DYLD) +/* +** {====================================================================== +** Native Mac OS X / Darwin Implementation +** ======================================================================= +*/ + +#include + + +/* Mac appends a `_' before C function names */ +#undef POF +#define POF "_" LUA_POF + + +static void pusherror (lua_State *L) { + const char *err_str; + const char *err_file; + NSLinkEditErrors err; + int err_num; + NSLinkEditError(&err, &err_num, &err_file, &err_str); + lua_pushstring(L, err_str); +} + + +static const char *errorfromcode (NSObjectFileImageReturnCode ret) { + switch (ret) { + case NSObjectFileImageInappropriateFile: + return "file is not a bundle"; + case NSObjectFileImageArch: + return "library is for wrong CPU type"; + case NSObjectFileImageFormat: + return "bad format"; + case NSObjectFileImageAccess: + return "cannot access file"; + case NSObjectFileImageFailure: + default: + return "unable to load library"; + } +} + + +static void ll_unloadlib (void *lib) { + NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES); +} + + +static void *ll_load (lua_State *L, const char *path) { + NSObjectFileImage img; + NSObjectFileImageReturnCode ret; + /* this would be a rare case, but prevents crashing if it happens */ + if(!_dyld_present()) { + lua_pushliteral(L, "dyld not present"); + return NULL; + } + ret = NSCreateObjectFileImageFromFile(path, &img); + if (ret == NSObjectFileImageSuccess) { + NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE | + NSLINKMODULE_OPTION_RETURN_ON_ERROR); + NSDestroyObjectFileImage(img); + if (mod == NULL) pusherror(L); + return mod; + } + lua_pushstring(L, errorfromcode(ret)); + return NULL; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym); + if (nss == NULL) { + lua_pushfstring(L, "symbol " LUA_QS " not found", sym); + return NULL; + } + return (lua_CFunction)NSAddressOfSymbol(nss); +} + +/* }====================================================== */ + + + +#else +/* +** {====================================================== +** Fallback for other systems +** ======================================================= +*/ + +#undef LIB_FAIL +#define LIB_FAIL "absent" + + +#define DLMSG "dynamic libraries not enabled; check your Lua installation" + + +static void ll_unloadlib (void *lib) { + (void)lib; /* to avoid warnings */ +} + + +static void *ll_load (lua_State *L, const char *path) { + (void)path; /* to avoid warnings */ + lua_pushliteral(L, DLMSG); + return NULL; +} + + +static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { + (void)lib; (void)sym; /* to avoid warnings */ + lua_pushliteral(L, DLMSG); + return NULL; +} + +/* }====================================================== */ +#endif + + + +static void **ll_register (lua_State *L, const char *path) { + void **plib; + lua_pushfstring(L, "%s%s", LIBPREFIX, path); + lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */ + if (!lua_isnil(L, -1)) /* is there an entry? */ + plib = (void **)lua_touserdata(L, -1); + else { /* no entry yet; create one */ + lua_pop(L, 1); + plib = (void **)lua_newuserdata(L, sizeof(const void *)); + *plib = NULL; + luaL_getmetatable(L, "_LOADLIB"); + lua_setmetatable(L, -2); + lua_pushfstring(L, "%s%s", LIBPREFIX, path); + lua_pushvalue(L, -2); + lua_settable(L, LUA_REGISTRYINDEX); + } + return plib; +} + + +/* +** __gc tag method: calls library's `ll_unloadlib' function with the lib +** handle +*/ +static int gctm (lua_State *L) { + void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB"); + if (*lib) ll_unloadlib(*lib); + *lib = NULL; /* mark library as closed */ + return 0; +} + + +static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { + void **reg = ll_register(L, path); + if (*reg == NULL) *reg = ll_load(L, path); + if (*reg == NULL) + return ERRLIB; /* unable to load library */ + else { + lua_CFunction f = ll_sym(L, *reg, sym); + if (f == NULL) + return ERRFUNC; /* unable to find function */ + lua_pushcfunction(L, f); + return 0; /* return function */ + } +} + + +static int ll_loadlib (lua_State *L) { + const char *path = luaL_checkstring(L, 1); + const char *init = luaL_checkstring(L, 2); + int stat = ll_loadfunc(L, path, init); + if (stat == 0) /* no errors? */ + return 1; /* return the loaded function */ + else { /* error; error message is on stack top */ + lua_pushnil(L); + lua_insert(L, -2); + lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); + return 3; /* return nil, 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; +} + + +static const char *pushnexttemplate (lua_State *L, const char *path) { + const char *l; + while (*path == *LUA_PATHSEP) path++; /* skip separators */ + if (*path == '\0') return NULL; /* no more templates */ + l = strchr(path, *LUA_PATHSEP); /* find next separator */ + if (l == NULL) l = path + strlen(path); + lua_pushlstring(L, path, l - path); /* template */ + return l; +} + + +static const char *findfile (lua_State *L, const char *name, + const char *pname) { + const char *path; + name = luaL_gsub(L, name, ".", LUA_DIRSEP); + lua_getfield(L, LUA_ENVIRONINDEX, pname); + path = lua_tostring(L, -1); + if (path == NULL) + luaL_error(L, LUA_QL("package.%s") " must be a string", pname); + lua_pushstring(L, ""); /* error accumulator */ + while ((path = pushnexttemplate(L, path)) != NULL) { + const char *filename; + filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); + if (readable(filename)) /* does file exist and is readable? */ + return filename; /* return that file name */ + lua_pop(L, 2); /* remove path template and file name */ + luaO_pushfstring(L, "\n\tno file " LUA_QS, filename); + lua_concat(L, 2); + } + return NULL; /* not found */ +} + + +static void loaderror (lua_State *L, const char *filename) { + luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", + lua_tostring(L, 1), filename, lua_tostring(L, -1)); +} + + +static int loader_Lua (lua_State *L) { + const char *filename; + const char *name = luaL_checkstring(L, 1); + filename = findfile(L, name, "path"); + if (filename == NULL) return 1; /* library not found in this path */ + if (luaL_loadfile(L, filename) != 0) + loaderror(L, filename); + return 1; /* library loaded successfully */ +} + + +static const char *mkfuncname (lua_State *L, const char *modname) { + const char *funcname; + const char *mark = strchr(modname, *LUA_IGMARK); + if (mark) modname = mark + 1; + funcname = luaL_gsub(L, modname, ".", LUA_OFSEP); + funcname = lua_pushfstring(L, POF"%s", funcname); + lua_remove(L, -2); /* remove 'gsub' result */ + return funcname; +} + + +static int loader_C (lua_State *L) { + const char *funcname; + const char *name = luaL_checkstring(L, 1); + const char *filename = findfile(L, name, "cpath"); + if (filename == NULL) return 1; /* library not found in this path */ + funcname = mkfuncname(L, name); + if (ll_loadfunc(L, filename, funcname) != 0) + loaderror(L, filename); + return 1; /* library loaded successfully */ +} + + +static int loader_Croot (lua_State *L) { + const char *funcname; + 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"); + if (filename == NULL) return 1; /* root not found */ + funcname = mkfuncname(L, name); + if ((stat = ll_loadfunc(L, filename, funcname)) != 0) { + if (stat != ERRFUNC) loaderror(L, filename); /* real error */ + luaO_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, + name, filename); + return 1; /* function not found */ + } + return 1; +} + + +static int loader_preload (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + lua_getfield(L, LUA_ENVIRONINDEX, "preload"); + if (!lua_istable(L, -1)) + luaL_error(L, LUA_QL("package.preload") " must be a table"); + lua_getfield(L, -1, name); + if (lua_isnil(L, -1)) /* not found? */ + luaO_pushfstring(L, "\n\tno field package.preload['%s']", name); + return 1; +} + + +static const int sentinel_ = 0; +#define sentinel ((void *)&sentinel_) + + +static int ll_require (lua_State *L) { + const char *name = luaL_checkstring(L, 1); + int i; + lua_settop(L, 1); /* _LOADED table will be at index 2 */ + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_getfield(L, 2, name); + if (lua_toboolean(L, -1)) { /* is it there? */ + if (lua_touserdata(L, -1) == sentinel) /* check loops */ + luaL_error(L, "loop or previous error loading module " LUA_QS, name); + return 1; /* package is already loaded */ + } + /* else must load it; iterate over available loaders */ + lua_getfield(L, LUA_ENVIRONINDEX, "loaders"); + if (!lua_istable(L, -1)) + luaL_error(L, LUA_QL("package.loaders") " must be a table"); + lua_pushstring(L, ""); /* error message accumulator */ + for (i=1; ; i++) { + lua_rawgeti(L, -2, i); /* get a loader */ + if (lua_isnil(L, -1)) + luaL_error(L, "module " LUA_QS " not found:%s", + name, lua_tostring(L, -2)); + lua_pushstring(L, name); + lua_call(L, 1, 1); /* call it */ + if (lua_isfunction(L, -1)) /* did it find module? */ + break; /* module loaded successfully */ + else if (lua_isstring(L, -1)) /* loader returned error message? */ + lua_concat(L, 2); /* accumulate it */ + else + lua_pop(L, 1); + } + lua_pushlightuserdata(L, sentinel); + lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */ + lua_pushstring(L, name); /* pass name as argument to module */ + lua_call(L, 1, 1); /* run loaded module */ + if (!lua_isnil(L, -1)) /* non-nil return? */ + lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ + lua_getfield(L, 2, name); + if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */ + lua_pushboolean(L, 1); /* use true as result */ + lua_pushvalue(L, -1); /* extra copy to be returned */ + lua_setfield(L, 2, name); /* _LOADED[name] = true */ + } + return 1; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** 'module' function +** ======================================================= +*/ + + +static void setfenv (lua_State *L) { + lua_Debug ar; + lua_getstack(L, 1, &ar); + lua_getinfo(L, "f", &ar); + lua_pushvalue(L, -2); + lua_setfenv(L, -2); + lua_pop(L, 1); +} + + +static void dooptions (lua_State *L, int n) { + int i; + for (i = 2; i <= n; i++) { + lua_pushvalue(L, i); /* get option (a function) */ + lua_pushvalue(L, -2); /* module */ + lua_call(L, 1, 0); + } +} + + +static void modinit (lua_State *L, const char *modname) { + const char *dot; + lua_pushvalue(L, -1); + lua_setfield(L, -2, "_M"); /* module._M = module */ + lua_pushstring(L, modname); + lua_setfield(L, -2, "_NAME"); + dot = strrchr(modname, '.'); /* look for last dot in module name */ + if (dot == NULL) dot = modname; + else dot++; + /* set _PACKAGE as package name (full module name minus last part) */ + lua_pushlstring(L, modname, dot - modname); + lua_setfield(L, -2, "_PACKAGE"); +} + + +static int ll_module (lua_State *L) { + const char *modname = luaL_checkstring(L, 1); + int loaded = lua_gettop(L) + 1; /* index of _LOADED table */ + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_getfield(L, loaded, modname); /* get _LOADED[modname] */ + if (!lua_istable(L, -1)) { /* not found? */ + lua_pop(L, 1); /* remove previous result */ + /* try global variable (and create one if it does not exist) */ + if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL) + return luaL_error(L, "name conflict for module " LUA_QS, modname); + lua_pushvalue(L, -1); + lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */ + } + /* check whether table already has a _NAME field */ + lua_getfield(L, -1, "_NAME"); + if (!lua_isnil(L, -1)) /* is table an initialized module? */ + lua_pop(L, 1); + else { /* no; initialize it */ + lua_pop(L, 1); + modinit(L, modname); + } + lua_pushvalue(L, -1); + setfenv(L); + dooptions(L, loaded - 1); + return 0; +} + + +static int ll_seeall (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + if (!lua_getmetatable(L, 1)) { + lua_createtable(L, 0, 1); /* create new metatable */ + lua_pushvalue(L, -1); + lua_setmetatable(L, 1); + } + lua_pushvalue(L, LUA_GLOBALSINDEX); + lua_setfield(L, -2, "__index"); /* mt.__index = _G */ + return 0; +} + + +/* }====================================================== */ + + + +/* auxiliary mark (for internal use) */ +#define AUXMARK "\1" + +static void setpath (lua_State *L, const char *fieldname, const char *envname, + const char *def) { + const char *path = getenv(envname); + if (path == NULL) /* no environment variable? */ + lua_pushstring(L, def); /* use default */ + else { + /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ + path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP, + LUA_PATHSEP AUXMARK LUA_PATHSEP); + luaL_gsub(L, path, AUXMARK, def); + lua_remove(L, -2); + } + setprogdir(L); + lua_setfield(L, -2, fieldname); +} + + +static const luaL_Reg pk_funcs[] = { + {"loadlib", ll_loadlib}, + {"seeall", ll_seeall}, + {NULL, NULL} +}; + + +static const luaL_Reg ll_funcs[] = { + {"module", ll_module}, + {"require", ll_require}, + {NULL, NULL} +}; + + +static const lua_CFunction loaders[] = + {loader_preload, loader_Lua, loader_C, loader_Croot, NULL}; + + +LUALIB_API int luaopen_package (lua_State *L) { + int i; + /* create new type _LOADLIB */ + luaL_newmetatable(L, "_LOADLIB"); + lua_pushcfunction(L, gctm); + lua_setfield(L, -2, "__gc"); + /* create `package' table */ + luaL_register(L, LUA_LOADLIBNAME, pk_funcs); +#if defined(LUA_COMPAT_LOADLIB) + lua_getfield(L, -1, "loadlib"); + lua_setfield(L, LUA_GLOBALSINDEX, "loadlib"); +#endif + lua_pushvalue(L, -1); + lua_replace(L, LUA_ENVIRONINDEX); + /* create `loaders' table */ + lua_createtable(L, 0, sizeof(loaders)/sizeof(loaders[0]) - 1); + /* fill it with pre-defined loaders */ + for (i=0; loaders[i] != NULL; i++) { + lua_pushcfunction(L, loaders[i]); + lua_rawseti(L, -2, i+1); + } + lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */ + setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */ + setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */ + /* store config information */ + lua_pushstring(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" + LUA_EXECDIR "\n" LUA_IGMARK); + lua_setfield(L, -2, "config"); + /* set field `loaded' */ + luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2); + lua_setfield(L, -2, "loaded"); + /* set field `preload' */ + lua_newtable(L); + lua_setfield(L, -2, "preload"); + lua_pushvalue(L, LUA_GLOBALSINDEX); + luaL_register(L, NULL, ll_funcs); /* open lib into global table */ + lua_pop(L, 1); + return 1; /* return 'package' table */ +} + diff --git a/src/lua/lobject.c b/src/lua/lobject.c new file mode 100644 index 0000000..acde82c --- /dev/null +++ b/src/lua/lobject.c @@ -0,0 +1,214 @@ +/* +** $Id: lobject.c,v 2.22 2006/02/10 17:43:52 roberto Exp $ +** Some generic functions over Lua objects +** See Copyright Notice in lua.h +*/ + +#include +#include +#include +#include +#include + +#define lobject_c +#define LUA_CORE + +#include "lua.h" + +#include "ldo.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "lvm.h" + + + +const TValue luaO_nilobject_ = {{NULL}, LUA_TNIL}; + + +/* +** converts an integer to a "floating point byte", represented as +** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if +** eeeee != 0 and (xxx) otherwise. +*/ +int luaO_int2fb (unsigned int x) { + int e = 0; /* expoent */ + while (x >= 16) { + x = (x+1) >> 1; + e++; + } + if (x < 8) return x; + else return ((e+1) << 3) | (cast_int(x) - 8); +} + + +/* converts back */ +int luaO_fb2int (int x) { + int e = (x >> 3) & 31; + if (e == 0) return x; + else return ((x & 7)+8) << (e - 1); +} + + +int luaO_log2 (unsigned int x) { + static const lu_byte log_2[256] = { + 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 = -1; + while (x >= 256) { l += 8; x >>= 8; } + return l + log_2[x]; + +} + + +int luaO_rawequalObj (const TValue *t1, const TValue *t2) { + if (ttype(t1) != ttype(t2)) return 0; + else switch (ttype(t1)) { + case LUA_TNIL: + return 1; + case LUA_TNUMBER: + return luai_numeq(nvalue(t1), nvalue(t2)); + case LUA_TBOOLEAN: + return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */ + case LUA_TLIGHTUSERDATA: + return pvalue(t1) == pvalue(t2); + default: + lua_assert(iscollectable(t1)); + return gcvalue(t1) == gcvalue(t2); + } +} + + +int luaO_str2d (const char *s, lua_Number *result) { + char *endptr; + *result = lua_str2number(s, &endptr); + if (endptr == s) return 0; /* conversion failed */ + if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */ + *result = cast_num(strtoul(s, &endptr, 16)); + if (*endptr == '\0') return 1; /* most common case */ + while (isspace(cast(unsigned char, *endptr))) endptr++; + if (*endptr != '\0') return 0; /* invalid trailing characters? */ + return 1; +} + + + +static void pushstr (lua_State *L, const char *str) { + setsvalue2s(L, L->top, luaS_new(L, str)); + incr_top(L); +} + + +/* this function handles only `%d', `%c', %f, %p, and `%s' formats */ +const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { + int n = 1; + pushstr(L, ""); + for (;;) { + const char *e = strchr(fmt, '%'); + if (e == NULL) break; + setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt)); + incr_top(L); + switch (*(e+1)) { + case 's': { + const char *s = va_arg(argp, char *); + if (s == NULL) s = "(null)"; + pushstr(L, s); + break; + } + case 'c': { + char buff[2]; + buff[0] = cast(char, va_arg(argp, int)); + buff[1] = '\0'; + pushstr(L, buff); + break; + } + case 'd': { + setnvalue(L->top, cast_num(va_arg(argp, int))); + incr_top(L); + break; + } + case 'f': { + setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber))); + incr_top(L); + break; + } + case 'p': { + char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ + sprintf(buff, "%p", va_arg(argp, void *)); + pushstr(L, buff); + break; + } + case '%': { + pushstr(L, "%"); + break; + } + default: { + char buff[3]; + buff[0] = '%'; + buff[1] = *(e+1); + buff[2] = '\0'; + pushstr(L, buff); + break; + } + } + n += 2; + fmt = e+2; + } + pushstr(L, fmt); + luaV_concat(L, n+1, cast_int(L->top - L->base) - 1); + L->top -= n; + return svalue(L->top - 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; +} + + +void luaO_chunkid (char *out, const char *source, size_t bufflen) { + if (*source == '=') { + strncpy(out, source+1, bufflen); /* remove first char */ + out[bufflen-1] = '\0'; /* ensures null termination */ + } + else { /* out = "source", or "...source" */ + if (*source == '@') { + size_t l; + source++; /* skip the `@' */ + bufflen -= sizeof(" '...' "); + l = strlen(source); + strcpy(out, ""); + if (l > bufflen) { + source += (l-bufflen); /* get last part of file name */ + strcat(out, "..."); + } + strcat(out, source); + } + else { /* out = [string "string"] */ + size_t len = strcspn(source, "\n\r"); /* stop at first newline */ + bufflen -= sizeof(" [string \"...\"] "); + if (len > bufflen) len = bufflen; + strcpy(out, "[string \""); + if (source[len] != '\0') { /* must truncate? */ + strncat(out, source, len); + strcat(out, "..."); + } + else + strcat(out, source); + strcat(out, "\"]"); + } + } +} diff --git a/src/lua/lobject.h b/src/lua/lobject.h new file mode 100644 index 0000000..8ce4405 --- /dev/null +++ b/src/lua/lobject.h @@ -0,0 +1,381 @@ +/* +** $Id: lobject.h,v 2.20 2006/01/18 11:37:34 roberto Exp $ +** Type definitions for Lua objects +** See Copyright Notice in lua.h +*/ + + +#ifndef lobject_h +#define lobject_h + + +#include + + +#include "llimits.h" +#include "lua.h" + + +/* tags for values visible from Lua */ +#define LAST_TAG LUA_TTHREAD + +#define NUM_TAGS (LAST_TAG+1) + + +/* +** Extra tags for non-values +*/ +#define LUA_TPROTO (LAST_TAG+1) +#define LUA_TUPVAL (LAST_TAG+2) +#define LUA_TDEADKEY (LAST_TAG+3) + + +/* +** Union of all collectable objects +*/ +typedef union GCObject GCObject; + + +/* +** Common Header for all collectable objects (in macro form, to be +** included in other objects) +*/ +#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked + + +/* +** Common header in struct form +*/ +typedef struct GCheader { + CommonHeader; +} GCheader; + + + + +/* +** Union of all Lua values +*/ +typedef union { + GCObject *gc; + void *p; + lua_Number n; + int b; +} Value; + + +/* +** Tagged Values +*/ + +#define TValuefields Value value; int tt + +typedef struct lua_TValue { + TValuefields; +} TValue; + + +/* Macros to test type */ +#define ttisnil(o) (ttype(o) == LUA_TNIL) +#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) +#define ttisstring(o) (ttype(o) == LUA_TSTRING) +#define ttistable(o) (ttype(o) == LUA_TTABLE) +#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) +#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) +#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) +#define ttisthread(o) (ttype(o) == LUA_TTHREAD) +#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) + +/* Macros to access values */ +#define ttype(o) ((o)->tt) +#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) +#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) +#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) +#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) +#define tsvalue(o) (&rawtsvalue(o)->tsv) +#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) +#define uvalue(o) (&rawuvalue(o)->uv) +#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) +#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) +#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) +#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) + +#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) + +/* +** for internal debug only +*/ +#define checkconsistency(obj) \ + lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) + +#define checkliveness(g,obj) \ + lua_assert(!iscollectable(obj) || \ + ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) + + +/* Macros to set values */ +#define setnilvalue(obj) ((obj)->tt=LUA_TNIL) + +#define setnvalue(obj,x) \ + { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; } + +#define setpvalue(obj,x) \ + { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; } + +#define setbvalue(obj,x) \ + { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; } + +#define setsvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \ + checkliveness(G(L),i_o); } + +#define setuvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \ + checkliveness(G(L),i_o); } + +#define setthvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \ + checkliveness(G(L),i_o); } + +#define setclvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \ + checkliveness(G(L),i_o); } + +#define sethvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \ + checkliveness(G(L),i_o); } + +#define setptvalue(L,obj,x) \ + { TValue *i_o=(obj); \ + i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \ + checkliveness(G(L),i_o); } + + + + +#define setobj(L,obj1,obj2) \ + { const TValue *o2=(obj2); TValue *o1=(obj1); \ + o1->value = o2->value; o1->tt=o2->tt; \ + checkliveness(G(L),o1); } + + +/* +** different types of sets, according to destination +*/ + +/* from stack to (same) stack */ +#define setobjs2s setobj +/* to stack (not from same stack) */ +#define setobj2s setobj +#define setsvalue2s setsvalue +#define sethvalue2s sethvalue +#define setptvalue2s setptvalue +/* from table to same table */ +#define setobjt2t setobj +/* to table */ +#define setobj2t setobj +/* to new object */ +#define setobj2n setobj +#define setsvalue2n setsvalue + +#define setttype(obj, tt) (ttype(obj) = (tt)) + + +#define iscollectable(o) (ttype(o) >= LUA_TSTRING) + + + +typedef TValue *StkId; /* index to stack elements */ + + +/* +** String headers for string table +*/ +typedef union TString { + L_Umaxalign dummy; /* ensures maximum alignment for strings */ + struct { + CommonHeader; + lu_byte reserved; + unsigned int hash; + size_t len; + } tsv; +} TString; + + +#define getstr(ts) cast(const char *, (ts) + 1) +#define svalue(o) getstr(tsvalue(o)) + + + +typedef union Udata { + L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ + struct { + CommonHeader; + struct Table *metatable; + struct Table *env; + size_t len; + } uv; +} Udata; + + + + +/* +** Function Prototypes +*/ +typedef struct Proto { + CommonHeader; + TValue *k; /* constants used by the function */ + Instruction *code; + struct Proto **p; /* functions defined inside the function */ + int *lineinfo; /* map from opcodes to source lines */ + struct LocVar *locvars; /* information about local variables */ + TString **upvalues; /* upvalue names */ + TString *source; + int sizeupvalues; + int sizek; /* size of `k' */ + int sizecode; + int sizelineinfo; + int sizep; /* size of `p' */ + int sizelocvars; + int linedefined; + int lastlinedefined; + GCObject *gclist; + lu_byte nups; /* number of upvalues */ + lu_byte numparams; + lu_byte is_vararg; + lu_byte maxstacksize; +} Proto; + + +/* masks for new-style vararg */ +#define VARARG_HASARG 1 +#define VARARG_ISVARARG 2 +#define VARARG_NEEDSARG 4 + + +typedef struct LocVar { + TString *varname; + int startpc; /* first point where variable is active */ + int endpc; /* first point where variable is dead */ +} LocVar; + + + +/* +** Upvalues +*/ + +typedef struct UpVal { + CommonHeader; + TValue *v; /* points to stack or to its own value */ + union { + TValue value; /* the value (when closed) */ + struct { /* double linked list (when open) */ + struct UpVal *prev; + struct UpVal *next; + } l; + } u; +} UpVal; + + +/* +** Closures +*/ + +#define ClosureHeader \ + CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ + struct Table *env + +typedef struct CClosure { + ClosureHeader; + lua_CFunction f; + TValue upvalue[1]; +} CClosure; + + +typedef struct LClosure { + ClosureHeader; + struct Proto *p; + UpVal *upvals[1]; +} LClosure; + + +typedef union Closure { + CClosure c; + LClosure l; +} Closure; + + +#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) +#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) + + +/* +** Tables +*/ + +typedef union TKey { + struct { + TValuefields; + struct Node *next; /* for chaining */ + } nk; + TValue tvk; +} TKey; + + +typedef struct Node { + TValue i_val; + TKey i_key; +} Node; + + +typedef struct Table { + CommonHeader; + lu_byte flags; /* 1<

lsizenode)) + + +#define luaO_nilobject (&luaO_nilobject_) + +LUAI_DATA const TValue luaO_nilobject_; + +#define ceillog2(x) (luaO_log2((x)-1) + 1) + +LUAI_FUNC int luaO_log2 (unsigned int x); +LUAI_FUNC int luaO_int2fb (unsigned int x); +LUAI_FUNC int luaO_fb2int (int x); +LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); +LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); +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 len); + + +#endif + diff --git a/src/lua/lopcodes.c b/src/lua/lopcodes.c new file mode 100644 index 0000000..bf9cd52 --- /dev/null +++ b/src/lua/lopcodes.c @@ -0,0 +1,102 @@ +/* +** $Id: lopcodes.c,v 1.37 2005/11/08 19:45:36 roberto Exp $ +** See Copyright Notice in lua.h +*/ + + +#define lopcodes_c +#define LUA_CORE + + +#include "lopcodes.h" + + +/* ORDER OP */ + +const char *const luaP_opnames[NUM_OPCODES+1] = { + "MOVE", + "LOADK", + "LOADBOOL", + "LOADNIL", + "GETUPVAL", + "GETGLOBAL", + "GETTABLE", + "SETGLOBAL", + "SETUPVAL", + "SETTABLE", + "NEWTABLE", + "SELF", + "ADD", + "SUB", + "MUL", + "DIV", + "MOD", + "POW", + "UNM", + "NOT", + "LEN", + "CONCAT", + "JMP", + "EQ", + "LT", + "LE", + "TEST", + "TESTSET", + "CALL", + "TAILCALL", + "RETURN", + "FORLOOP", + "FORPREP", + "TFORLOOP", + "SETLIST", + "CLOSE", + "CLOSURE", + "VARARG", + NULL +}; + + +#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) + +const lu_byte luaP_opmodes[NUM_OPCODES] = { +/* T A B C mode opcode */ + opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ + ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ + ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_GETGLOBAL */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ + ,opmode(0, 0, OpArgK, OpArgN, iABx) /* OP_SETGLOBAL */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ + ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ + ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ + ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ + ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ + ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ + ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ + ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ + ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */ + ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ + ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ + ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ + ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ + ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TFORLOOP */ + ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ + ,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */ + ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ + ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ +}; + diff --git a/src/lua/lopcodes.h b/src/lua/lopcodes.h new file mode 100644 index 0000000..2834b1d --- /dev/null +++ b/src/lua/lopcodes.h @@ -0,0 +1,268 @@ +/* +** $Id: lopcodes.h,v 1.124 2005/12/02 18:42:08 roberto Exp $ +** 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 numbers. + All instructions have an opcode in the first 6 bits. + Instructions can have the following fields: + `A' : 8 bits + `B' : 9 bits + `C' : 9 bits + `Bx' : 18 bits (`B' and `C' together) + `sBx' : signed Bx + + A signed argument is represented in excess K; that is, the number + value is the unsigned value minus K. K is exactly the maximum value + for that argument (so that -max is represented by 0, and +max is + represented by 2*max), which is half the maximum for the corresponding + unsigned argument. +===========================================================================*/ + + +enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */ + + +/* +** size and position of opcode arguments. +*/ +#define SIZE_C 9 +#define SIZE_B 9 +#define SIZE_Bx (SIZE_C + SIZE_B) +#define SIZE_A 8 + +#define SIZE_OP 6 + +#define POS_OP 0 +#define POS_A (POS_OP + SIZE_OP) +#define POS_C (POS_A + SIZE_A) +#define POS_B (POS_C + SIZE_C) +#define POS_Bx POS_C + + +/* +** limits for opcode arguments. +** we use (signed) int to manipulate most arguments, +** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) +*/ +#if SIZE_Bx < LUAI_BITSINT-1 +#define MAXARG_Bx ((1<>1) /* `sBx' is signed */ +#else +#define MAXARG_Bx MAX_INT +#define MAXARG_sBx MAX_INT +#endif + + +#define MAXARG_A ((1<>POS_OP) & MASK1(SIZE_OP,0))) +#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ + ((cast(Instruction, o)<>POS_A) & MASK1(SIZE_A,0))) +#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \ + ((cast(Instruction, u)<>POS_B) & MASK1(SIZE_B,0))) +#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \ + ((cast(Instruction, b)<>POS_C) & MASK1(SIZE_C,0))) +#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \ + ((cast(Instruction, b)<>POS_Bx) & MASK1(SIZE_Bx,0))) +#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \ + ((cast(Instruction, b)< C) then pc++ */ +OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ + +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 return R(A)(R(A+1), ... ,R(A+B-1)) */ +OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ + +OP_FORLOOP,/* A sBx R(A)+=R(A+2); + if R(A) =) R(A)*/ +OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */ + +OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ +} OpCode; + + +#define NUM_OPCODES (cast(int, OP_VARARG) + 1) + + + +/*=========================================================================== + Notes: + (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, + and can be 0: OP_CALL then sets `top' to last_result+1, so + next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. + + (*) In OP_VARARG, if (B == 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_SETLIST, if (B == 0) then B = `top'; + if (C == 0) then next `instruction' is real C + + (*) For comparisons, A specifies what condition the test should accept + (true or false). + + (*) All `skips' (pc++) assume that next instruction is a jump +===========================================================================*/ + + +/* +** masks for instruction properties. The format is: +** bits 0-1: op mode +** bits 2-3: C arg mode +** bits 4-5: B arg mode +** bit 6: instruction set register A +** bit 7: operator is a test +*/ + +enum OpArgMask { + OpArgN, /* argument is not used */ + OpArgU, /* argument is used */ + OpArgR, /* argument is a register or a jump offset */ + OpArgK /* argument is a constant or register/constant */ +}; + +LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES]; + +#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3)) +#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3)) +#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) +#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) +#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) + + +LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */ + + +/* number of list items to accumulate before a SETLIST instruction */ +#define LFIELDS_PER_FLUSH 50 + + +#endif diff --git a/src/lua/loslib.c b/src/lua/loslib.c new file mode 100644 index 0000000..509d7b7 --- /dev/null +++ b/src/lua/loslib.c @@ -0,0 +1,238 @@ +/* +** $Id: loslib.c,v 1.17 2006/01/27 13:54:31 roberto Exp $ +** Standard Operating System library +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include +#include + +#define loslib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +static int os_pushresult (lua_State *L, int i, const char *filename) { + int en = errno; /* calls to Lua API may change this value */ + if (i) { + lua_pushboolean(L, 1); + return 1; + } + else { + lua_pushnil(L); + if (filename) + lua_pushfstring(L, "%s: %s", filename, strerror(en)); + else + lua_pushfstring(L, "%s", strerror(en)); + lua_pushinteger(L, en); + return 3; + } +} + + +static int os_execute (lua_State *L) { + lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); + return 1; +} + + +static int os_remove (lua_State *L) { + const char *filename = luaL_checkstring(L, 1); + return os_pushresult(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 os_pushresult(L, rename(fromname, toname) == 0, fromname); +} + + +static int os_tmpname (lua_State *L) { + char buff[LUA_TMPNAMBUFSIZE]; + int err; + lua_tmpnam(buff, err); + if (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=? } +** ======================================================= +*/ + +static void setfield (lua_State *L, const char *key, int value) { + lua_pushinteger(L, value); + 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); +} + +static int getboolfield (lua_State *L, const char *key) { + int res; + lua_getfield(L, -1, key); + res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); + lua_pop(L, 1); + return res; +} + + +static int getfield (lua_State *L, const char *key, int d) { + int res; + lua_getfield(L, -1, key); + if (lua_isnumber(L, -1)) + res = (int)lua_tointeger(L, -1); + else { + if (d < 0) + return luaL_error(L, "field " LUA_QS " missing in date table", key); + res = d; + } + lua_pop(L, 1); + return res; +} + + +static int os_date (lua_State *L) { + const char *s = luaL_optstring(L, 1, "%c"); + time_t t = lua_isnoneornil(L, 2) ? time(NULL) : + (time_t)luaL_checknumber(L, 2); + struct tm *stm; + if (*s == '!') { /* UTC? */ + stm = gmtime(&t); + s++; /* skip `!' */ + } + else + stm = localtime(&t); + if (stm == NULL) /* invalid date? */ + lua_pushnil(L); + else if (strcmp(s, "*t") == 0) { + lua_createtable(L, 0, 9); /* 9 = number of fields */ + setfield(L, "sec", stm->tm_sec); + setfield(L, "min", stm->tm_min); + setfield(L, "hour", stm->tm_hour); + setfield(L, "day", stm->tm_mday); + setfield(L, "month", stm->tm_mon+1); + setfield(L, "year", stm->tm_year+1900); + setfield(L, "wday", stm->tm_wday+1); + setfield(L, "yday", stm->tm_yday+1); + setboolfield(L, "isdst", stm->tm_isdst); + } + else { + char b[256]; + if (strftime(b, sizeof(b), s, stm)) + lua_pushstring(L, b); + else + return luaL_error(L, LUA_QL("date") " format too long"); + } + 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_sec = getfield(L, "sec", 0); + ts.tm_min = getfield(L, "min", 0); + ts.tm_hour = getfield(L, "hour", 12); + ts.tm_mday = getfield(L, "day", -1); + ts.tm_mon = getfield(L, "month", -1) - 1; + ts.tm_year = getfield(L, "year", -1) - 1900; + ts.tm_isdst = getboolfield(L, "isdst"); + t = mktime(&ts); + } + if (t == (time_t)(-1)) + lua_pushnil(L); + else + lua_pushnumber(L, (lua_Number)t); + return 1; +} + + +static int os_difftime (lua_State *L) { + lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)), + (time_t)(luaL_optnumber(L, 2, 0)))); + 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 = lua_tostring(L, 1); + int op = luaL_checkoption(L, 2, "all", catnames); + luaL_argcheck(L, l || lua_isnoneornil(L, 1), 1, "string expected"); + lua_pushstring(L, setlocale(cat[op], l)); + return 1; +} + + +static int os_exit (lua_State *L) { + exit(luaL_optint(L, 1, EXIT_SUCCESS)); + return 0; /* to avoid warnings */ +} + +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} +}; + +/* }====================================================== */ + + + +LUALIB_API int luaopen_os (lua_State *L) { + luaL_register(L, LUA_OSLIBNAME, syslib); + return 1; +} + diff --git a/src/lua/lparser.c b/src/lua/lparser.c new file mode 100644 index 0000000..b40ee79 --- /dev/null +++ b/src/lua/lparser.c @@ -0,0 +1,1336 @@ +/* +** $Id: lparser.c,v 2.40 2005/12/22 16:19:56 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + + +#include + +#define lparser_c +#define LUA_CORE + +#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" + + + + +#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) + +#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]]) + +#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m) + + +/* +** nodes for block list (list of active blocks) +*/ +typedef struct BlockCnt { + struct BlockCnt *previous; /* chain */ + int breaklist; /* list of jumps out of this loop */ + lu_byte nactvar; /* # active locals outside the breakable structure */ + lu_byte upval; /* true if some variable in the block is an upvalue */ + lu_byte isbreakable; /* true if `block' is a loop */ +} BlockCnt; + + + +/* +** prototypes for recursive non-terminal functions +*/ +static void chunk (LexState *ls); +static void expr (LexState *ls, expdesc *v); + + +static void anchor_token (LexState *ls) { + if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { + TString *ts = ls->t.seminfo.ts; + luaX_newstring(ls, getstr(ts), ts->tsv.len); + } +} + + +static void error_expected (LexState *ls, int token) { + luaX_syntaxerror(ls, + luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token))); +} + + +static void errorlimit (FuncState *fs, int limit, const char *what) { + const char *msg = (fs->f->linedefined == 0) ? + luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) : + luaO_pushfstring(fs->L, "function at line %d has more than %d %s", + fs->f->linedefined, limit, what); + luaX_lexerror(fs->ls, msg, 0); +} + + +static int testnext (LexState *ls, int c) { + if (ls->t.token == c) { + luaX_next(ls); + return 1; + } + else return 0; +} + + +static void check (LexState *ls, int c) { + if (ls->t.token != c) + error_expected(ls, c); +} + +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); } + + + +static void check_match (LexState *ls, int what, int who, int where) { + if (!testnext(ls, what)) { + if (where == ls->linenumber) + error_expected(ls, what); + else { + luaX_syntaxerror(ls, luaO_pushfstring(ls->L, + LUA_QS " expected (to close " LUA_QS " 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.s.info = i; +} + + +static void codestring (LexState *ls, expdesc *e, TString *s) { + init_exp(e, VK, luaK_stringK(ls->fs, s)); +} + + +static void checkname(LexState *ls, expdesc *e) { + codestring(ls, e, str_checkname(ls)); +} + + +static int registerlocalvar (LexState *ls, TString *varname) { + FuncState *fs = ls->fs; + Proto *f = fs->f; + int oldsize = f->sizelocvars; + luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, + LocVar, SHRT_MAX, "too many local variables"); + while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; + f->locvars[fs->nlocvars].varname = varname; + luaC_objbarrier(ls->L, f, varname); + return fs->nlocvars++; +} + + +#define new_localvarliteral(ls,v,n) \ + new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n) + + +static void new_localvar (LexState *ls, TString *name, int n) { + FuncState *fs = ls->fs; + luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables"); + fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name)); +} + + +static void adjustlocalvars (LexState *ls, int nvars) { + FuncState *fs = ls->fs; + fs->nactvar = cast_byte(fs->nactvar + nvars); + for (; nvars; nvars--) { + getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc; + } +} + + +static void removevars (LexState *ls, int tolevel) { + FuncState *fs = ls->fs; + while (fs->nactvar > tolevel) + getlocvar(fs, --fs->nactvar).endpc = fs->pc; +} + + +static int indexupvalue (FuncState *fs, TString *name, expdesc *v) { + int i; + Proto *f = fs->f; + int oldsize = f->sizeupvalues; + for (i=0; inups; i++) { + if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) { + lua_assert(f->upvalues[i] == name); + return i; + } + } + /* new one */ + luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues"); + luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues, + TString *, MAX_INT, ""); + while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL; + f->upvalues[f->nups] = name; + luaC_objbarrier(fs->L, f, name); + lua_assert(v->k == VLOCAL || v->k == VUPVAL); + fs->upvalues[f->nups].k = cast_byte(v->k); + fs->upvalues[f->nups].info = cast_byte(v->u.s.info); + return f->nups++; +} + + +static int searchvar (FuncState *fs, TString *n) { + int i; + for (i=fs->nactvar-1; i >= 0; i--) { + if (n == getlocvar(fs, i).varname) + return i; + } + return -1; /* not found */ +} + + +static void markupval (FuncState *fs, int level) { + BlockCnt *bl = fs->bl; + while (bl && bl->nactvar > level) bl = bl->previous; + if (bl) bl->upval = 1; +} + + +static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { + if (fs == NULL) { /* no more levels? */ + init_exp(var, VGLOBAL, NO_REG); /* default is global variable */ + return VGLOBAL; + } + else { + int v = searchvar(fs, n); /* look up at current level */ + if (v >= 0) { + init_exp(var, VLOCAL, v); + if (!base) + markupval(fs, v); /* local will be used as an upval */ + return VLOCAL; + } + else { /* not found at current level; try upper one */ + if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL) + return VGLOBAL; + var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */ + var->k = VUPVAL; /* upvalue in this level */ + return VUPVAL; + } + } +} + + +static void singlevar (LexState *ls, expdesc *var) { + TString *varname = str_checkname(ls); + FuncState *fs = ls->fs; + if (singlevaraux(fs, varname, var, 1) == VGLOBAL) + var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */ +} + + +static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { + FuncState *fs = ls->fs; + int extra = nvars - nexps; + if (hasmultret(e->k)) { + extra++; /* includes call itself */ + if (extra < 0) extra = 0; + luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ + if (extra > 1) luaK_reserveregs(fs, extra-1); + } + else { + if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ + if (extra > 0) { + int reg = fs->freereg; + luaK_reserveregs(fs, extra); + luaK_nil(fs, reg, extra); + } + } +} + + +static void enterlevel (LexState *ls) { + if (++ls->L->nCcalls > LUAI_MAXCCALLS) + luaX_lexerror(ls, "chunk has too many syntax levels", 0); +} + + +#define leavelevel(ls) ((ls)->L->nCcalls--) + + +static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) { + bl->breaklist = NO_JUMP; + bl->isbreakable = isbreakable; + bl->nactvar = fs->nactvar; + bl->upval = 0; + bl->previous = fs->bl; + fs->bl = bl; + lua_assert(fs->freereg == fs->nactvar); +} + + +static void leaveblock (FuncState *fs) { + BlockCnt *bl = fs->bl; + fs->bl = bl->previous; + removevars(fs->ls, bl->nactvar); + if (bl->upval) + luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); + lua_assert(!bl->isbreakable || !bl->upval); /* loops have no body */ + lua_assert(bl->nactvar == fs->nactvar); + fs->freereg = fs->nactvar; /* free registers */ + luaK_patchtohere(fs, bl->breaklist); +} + + +static void pushclosure (LexState *ls, FuncState *func, expdesc *v) { + FuncState *fs = ls->fs; + Proto *f = fs->f; + int oldsize = f->sizep; + int i; + luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *, + MAXARG_Bx, "constant table overflow"); + while (oldsize < f->sizep) f->p[oldsize++] = NULL; + f->p[fs->np++] = func->f; + luaC_objbarrier(ls->L, f, func->f); + init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1)); + for (i=0; if->nups; i++) { + OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; + luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0); + } +} + + +static void open_func (LexState *ls, FuncState *fs) { + lua_State *L = ls->L; + Proto *f = luaF_newproto(L); + fs->f = f; + fs->prev = ls->fs; /* linked list of funcstates */ + fs->ls = ls; + fs->L = L; + ls->fs = fs; + fs->pc = 0; + fs->lasttarget = -1; + fs->jpc = NO_JUMP; + fs->freereg = 0; + fs->nk = 0; + fs->np = 0; + fs->nlocvars = 0; + fs->nactvar = 0; + fs->bl = NULL; + f->source = ls->source; + f->maxstacksize = 2; /* registers 0/1 are always valid */ + fs->h = luaH_new(L, 0, 0); + /* anchor table of constants and prototype (to avoid being collected) */ + sethvalue2s(L, L->top, fs->h); + incr_top(L); + setptvalue2s(L, L->top, f); + incr_top(L); +} + + +static void close_func (LexState *ls) { + lua_State *L = ls->L; + FuncState *fs = ls->fs; + Proto *f = fs->f; + removevars(ls, 0); + luaK_ret(fs, 0, 0); /* final return */ + luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); + f->sizecode = fs->pc; + luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); + f->sizelineinfo = fs->pc; + luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); + f->sizek = fs->nk; + luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); + f->sizep = fs->np; + luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); + f->sizelocvars = fs->nlocvars; + luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *); + f->sizeupvalues = f->nups; + lua_assert(luaG_checkcode(f)); + lua_assert(fs->bl == NULL); + ls->fs = fs->prev; + L->top -= 2; /* remove table and prototype from the stack */ + /* last token read was anchored in defunct function; must reanchor it */ + if (fs) anchor_token(ls); +} + + +Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) { + struct LexState lexstate; + struct FuncState funcstate; + lexstate.buff = buff; + luaX_setinput(L, &lexstate, z, luaS_new(L, name)); + open_func(&lexstate, &funcstate); + funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */ + luaX_next(&lexstate); /* read first token */ + chunk(&lexstate); + check(&lexstate, TK_EOS); + close_func(&lexstate); + lua_assert(funcstate.prev == NULL); + lua_assert(funcstate.f->nups == 0); + lua_assert(lexstate.fs == NULL); + return funcstate.f; +} + + + +/*============================================================*/ +/* GRAMMAR RULES */ +/*============================================================*/ + + +static void field (LexState *ls, expdesc *v) { + /* field -> ['.' | ':'] NAME */ + FuncState *fs = ls->fs; + expdesc key; + luaK_exp2anyreg(fs, v); + luaX_next(ls); /* skip the dot or colon */ + checkname(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 +** ======================================================================= +*/ + + +struct ConsControl { + expdesc v; /* last list item read */ + expdesc *t; /* table descriptor */ + int nh; /* total number of `record' elements */ + int na; /* total number of array elements */ + int tostore; /* number of array elements pending to be stored */ +}; + + +static void recfield (LexState *ls, struct ConsControl *cc) { + /* recfield -> (NAME | `['exp1`]') = exp1 */ + FuncState *fs = ls->fs; + int reg = ls->fs->freereg; + expdesc key, val; + if (ls->t.token == TK_NAME) { + luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); + checkname(ls, &key); + } + else /* ls->t.token == '[' */ + yindex(ls, &key); + cc->nh++; + checknext(ls, '='); + luaK_exp2RK(fs, &key); + expr(ls, &val); + luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, luaK_exp2RK(fs, &key), + luaK_exp2RK(fs, &val)); + fs->freereg = reg; /* free registers */ +} + + +static void closelistfield (FuncState *fs, struct 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.s.info, cc->na, cc->tostore); /* flush */ + cc->tostore = 0; /* no more items pending */ + } +} + + +static void lastlistfield (FuncState *fs, struct ConsControl *cc) { + if (cc->tostore == 0) return; + if (hasmultret(cc->v.k)) { + luaK_setmultret(fs, &cc->v); + luaK_setlist(fs, cc->t->u.s.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.s.info, cc->na, cc->tostore); + } +} + + +static void listfield (LexState *ls, struct ConsControl *cc) { + expr(ls, &cc->v); + luaY_checklimit(ls->fs, cc->na, MAXARG_Bx, "items in a constructor"); + cc->na++; + cc->tostore++; +} + + +static void constructor (LexState *ls, expdesc *t) { + /* constructor -> ?? */ + FuncState *fs = ls->fs; + int line = ls->linenumber; + int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); + struct ConsControl cc; + cc.na = cc.nh = cc.tostore = 0; + cc.t = t; + init_exp(t, VRELOCABLE, pc); + init_exp(&cc.v, VVOID, 0); /* no value (yet) */ + luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */ + checknext(ls, '{'); + do { + lua_assert(cc.v.k == VVOID || cc.tostore > 0); + if (ls->t.token == '}') break; + closelistfield(fs, &cc); + switch(ls->t.token) { + case TK_NAME: { /* may be listfields or recfields */ + luaX_lookahead(ls); + if (ls->lookahead.token != '=') /* expression? */ + listfield(ls, &cc); + else + recfield(ls, &cc); + break; + } + case '[': { /* constructor_item -> recfield */ + recfield(ls, &cc); + break; + } + default: { /* constructor_part -> listfield */ + listfield(ls, &cc); + break; + } + } + } while (testnext(ls, ',') || testnext(ls, ';')); + check_match(ls, '}', '{', line); + lastlistfield(fs, &cc); + SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ + SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ +} + +/* }====================================================================== */ + + + +static void parlist (LexState *ls) { + /* parlist -> [ param { `,' param } ] */ + FuncState *fs = ls->fs; + Proto *f = fs->f; + int nparams = 0; + f->is_vararg = 0; + if (ls->t.token != ')') { /* is `parlist' not empty? */ + do { + switch (ls->t.token) { + case TK_NAME: { /* param -> NAME */ + new_localvar(ls, str_checkname(ls), nparams++); + break; + } + case TK_DOTS: { /* param -> `...' */ + luaX_next(ls); +#if defined(LUA_COMPAT_VARARG) + /* use `arg' as default name */ + new_localvarliteral(ls, "arg", nparams++); + f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG; +#endif + f->is_vararg |= VARARG_ISVARARG; + break; + } + default: luaX_syntaxerror(ls, " or " LUA_QL("...") " expected"); + } + } while (!f->is_vararg && testnext(ls, ',')); + } + adjustlocalvars(ls, nparams); + f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG)); + luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ +} + + +static void body (LexState *ls, expdesc *e, int needself, int line) { + /* body -> `(' parlist `)' chunk END */ + FuncState new_fs; + open_func(ls, &new_fs); + new_fs.f->linedefined = line; + checknext(ls, '('); + if (needself) { + new_localvarliteral(ls, "self", 0); + adjustlocalvars(ls, 1); + } + parlist(ls); + checknext(ls, ')'); + chunk(ls); + new_fs.f->lastlinedefined = ls->linenumber; + check_match(ls, TK_END, TK_FUNCTION, line); + close_func(ls); + pushclosure(ls, &new_fs, e); +} + + +static int explist1 (LexState *ls, expdesc *v) { + /* explist1 -> 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) { + FuncState *fs = ls->fs; + expdesc args; + int base, nparams; + int line = ls->linenumber; + switch (ls->t.token) { + case '(': { /* funcargs -> `(' [ explist1 ] `)' */ + if (line != ls->lastline) + luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)"); + luaX_next(ls); + if (ls->t.token == ')') /* arg list is empty? */ + args.k = VVOID; + else { + explist1(ls, &args); + luaK_setmultret(fs, &args); + } + check_match(ls, ')', '(', line); + break; + } + case '{': { /* funcargs -> constructor */ + constructor(ls, &args); + break; + } + case TK_STRING: { /* funcargs -> STRING */ + codestring(ls, &args, ls->t.seminfo.ts); + luaX_next(ls); /* must use `seminfo' before `next' */ + break; + } + default: { + luaX_syntaxerror(ls, "function arguments expected"); + return; + } + } + lua_assert(f->k == VNONRELOC); + base = f->u.s.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 prefixexp (LexState *ls, expdesc *v) { + /* prefixexp -> 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"); + return; + } + } +} + + +static void primaryexp (LexState *ls, expdesc *v) { + /* primaryexp -> + prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */ + FuncState *fs = ls->fs; + prefixexp(ls, v); + for (;;) { + switch (ls->t.token) { + case '.': { /* field */ + field(ls, v); + break; + } + case '[': { /* `[' exp1 `]' */ + expdesc key; + luaK_exp2anyreg(fs, v); + yindex(ls, &key); + luaK_indexed(fs, v, &key); + break; + } + case ':': { /* `:' NAME funcargs */ + expdesc key; + luaX_next(ls); + checkname(ls, &key); + luaK_self(fs, v, &key); + funcargs(ls, v); + break; + } + case '(': case TK_STRING: case '{': { /* funcargs */ + luaK_exp2nextreg(fs, v); + funcargs(ls, v); + break; + } + default: return; + } + } +} + + +static void simpleexp (LexState *ls, expdesc *v) { + /* simpleexp -> NUMBER | STRING | NIL | true | false | ... | + constructor | FUNCTION body | primaryexp */ + switch (ls->t.token) { + case TK_NUMBER: { + init_exp(v, VKNUM, 0); + v->u.nval = ls->t.seminfo.r; + break; + } + case TK_STRING: { + codestring(ls, 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 " LUA_QL("...") " outside a vararg function"); + fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */ + init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); + break; + } + case '{': { /* constructor */ + constructor(ls, v); + return; + } + case TK_FUNCTION: { + luaX_next(ls); + body(ls, v, 0, ls->linenumber); + return; + } + default: { + primaryexp(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_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_DIV; + case '%': return OPR_MOD; + case '^': return OPR_POW; + 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; + } +} + + +static const struct { + lu_byte left; /* left priority for each binary operator */ + lu_byte right; /* right priority */ +} priority[] = { /* ORDER OPR */ + {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */ + {10, 9}, {5, 4}, /* power and concat (right associative) */ + {3, 3}, {3, 3}, /* equality and inequality */ + {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */ + {2, 2}, {1, 1} /* logical (and/or) */ +}; + +#define UNARY_PRIORITY 8 /* 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, unsigned int limit) { + BinOpr op; + UnOpr uop; + enterlevel(ls); + uop = getunopr(ls->t.token); + if (uop != OPR_NOUNOPR) { + luaX_next(ls); + subexpr(ls, v, UNARY_PRIORITY); + luaK_prefix(ls->fs, uop, v); + } + 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; + luaX_next(ls); + 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); + 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 int block_follow (int token) { + switch (token) { + case TK_ELSE: case TK_ELSEIF: case TK_END: + case TK_UNTIL: case TK_EOS: + return 1; + default: return 0; + } +} + + +static void block (LexState *ls) { + /* block -> chunk */ + FuncState *fs = ls->fs; + BlockCnt bl; + enterblock(fs, &bl, 0); + chunk(ls); + lua_assert(bl.breaklist == NO_JUMP); + 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 a local variable, the local variable +** is needed in a previous assignment (to a table). If so, save original +** 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) { + if (lh->v.k == VINDEXED) { + if (lh->v.u.s.info == v->u.s.info) { /* conflict? */ + conflict = 1; + lh->v.u.s.info = extra; /* previous assignment will use safe copy */ + } + if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */ + conflict = 1; + lh->v.u.s.aux = extra; /* previous assignment will use safe copy */ + } + } + } + if (conflict) { + luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */ + luaK_reserveregs(fs, 1); + } +} + + +static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { + expdesc e; + check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED, + "syntax error"); + if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */ + struct LHS_assign nv; + nv.prev = lh; + primaryexp(ls, &nv.v); + if (nv.v.k == VLOCAL) + check_conflict(ls, lh, &nv.v); + assignment(ls, &nv, nvars+1); + } + else { /* assignment -> `=' explist1 */ + int nexps; + checknext(ls, '='); + nexps = explist1(ls, &e); + if (nexps != nvars) { + adjust_assign(ls, nvars, nexps, &e); + if (nexps > nvars) + ls->fs->freereg -= nexps - nvars; /* remove extra values */ + } + 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 breakstat (LexState *ls) { + FuncState *fs = ls->fs; + BlockCnt *bl = fs->bl; + int upval = 0; + while (bl && !bl->isbreakable) { + upval |= bl->upval; + bl = bl->previous; + } + if (!bl) + luaX_syntaxerror(ls, "no loop to break"); + if (upval) + luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); + luaK_concat(fs, &bl->breaklist, luaK_jump(fs)); +} + + +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_patchlist(fs, luaK_jump(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 */ + chunk(ls); + check_match(ls, TK_UNTIL, TK_REPEAT, line); + condexit = cond(ls); /* read condition (inside scope block) */ + if (!bl2.upval) { /* no upvalues? */ + leaveblock(fs); /* finish scope */ + luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */ + } + else { /* complete semantics when there are upvalues */ + breakstat(ls); /* if condition then break */ + luaK_patchtohere(ls->fs, condexit); /* else... */ + leaveblock(fs); /* finish scope... */ + luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */ + } + leaveblock(fs); /* finish loop */ +} + + +static int exp1 (LexState *ls) { + expdesc e; + int k; + expr(ls, &e); + k = e.k; + luaK_exp2nextreg(ls->fs, &e); + return k; +} + + +static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { + /* forbody -> DO block */ + BlockCnt bl; + FuncState *fs = ls->fs; + int prep, endfor; + adjustlocalvars(ls, 3); /* control variables */ + checknext(ls, TK_DO); + prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); + 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 */ + luaK_patchtohere(fs, prep); + endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) : + luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars); + luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */ + luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1); +} + + +static void fornum (LexState *ls, TString *varname, int line) { + /* fornum -> NAME = exp1,exp1[,exp1] forbody */ + FuncState *fs = ls->fs; + int base = fs->freereg; + new_localvarliteral(ls, "(for index)", 0); + new_localvarliteral(ls, "(for limit)", 1); + new_localvarliteral(ls, "(for step)", 2); + new_localvar(ls, varname, 3); + checknext(ls, '='); + exp1(ls); /* initial value */ + checknext(ls, ','); + exp1(ls); /* limit */ + if (testnext(ls, ',')) + exp1(ls); /* optional step */ + else { /* default step = 1 */ + luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1)); + luaK_reserveregs(fs, 1); + } + forbody(ls, base, line, 1, 1); +} + + +static void forlist (LexState *ls, TString *indexname) { + /* forlist -> NAME {,NAME} IN explist1 forbody */ + FuncState *fs = ls->fs; + expdesc e; + int nvars = 0; + int line; + int base = fs->freereg; + /* create control variables */ + new_localvarliteral(ls, "(for generator)", nvars++); + new_localvarliteral(ls, "(for state)", nvars++); + new_localvarliteral(ls, "(for control)", nvars++); + /* create declared variables */ + new_localvar(ls, indexname, nvars++); + while (testnext(ls, ',')) + new_localvar(ls, str_checkname(ls), nvars++); + checknext(ls, TK_IN); + line = ls->linenumber; + adjust_assign(ls, 3, explist1(ls, &e), &e); + luaK_checkstack(fs, 3); /* extra space to call generator */ + forbody(ls, base, line, nvars - 3, 0); +} + + +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, LUA_QL("=") " or " LUA_QL("in") " expected"); + } + check_match(ls, TK_END, TK_FOR, line); + leaveblock(fs); /* loop scope (`break' jumps to this point) */ +} + + +static int test_then_block (LexState *ls) { + /* test_then_block -> [IF | ELSEIF] cond THEN block */ + int condexit; + luaX_next(ls); /* skip IF or ELSEIF */ + condexit = cond(ls); + checknext(ls, TK_THEN); + block(ls); /* `then' part */ + return condexit; +} + + +static void ifstat (LexState *ls, int line) { + /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ + FuncState *fs = ls->fs; + int flist; + int escapelist = NO_JUMP; + flist = test_then_block(ls); /* IF cond THEN block */ + while (ls->t.token == TK_ELSEIF) { + luaK_concat(fs, &escapelist, luaK_jump(fs)); + luaK_patchtohere(fs, flist); + flist = test_then_block(ls); /* ELSEIF cond THEN block */ + } + if (ls->t.token == TK_ELSE) { + luaK_concat(fs, &escapelist, luaK_jump(fs)); + luaK_patchtohere(fs, flist); + luaX_next(ls); /* skip ELSE (after patch, for correct line info) */ + block(ls); /* `else' part */ + } + else + luaK_concat(fs, &escapelist, flist); + luaK_patchtohere(fs, escapelist); + check_match(ls, TK_END, TK_IF, line); +} + + +static void localfunc (LexState *ls) { + expdesc v, b; + FuncState *fs = ls->fs; + new_localvar(ls, str_checkname(ls), 0); + init_exp(&v, VLOCAL, fs->freereg); + luaK_reserveregs(fs, 1); + adjustlocalvars(ls, 1); + body(ls, &b, 0, ls->linenumber); + luaK_storevar(fs, &v, &b); + /* debug information will only see the variable after this point! */ + getlocvar(fs, fs->nactvar - 1).startpc = fs->pc; +} + + +static void localstat (LexState *ls) { + /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ + int nvars = 0; + int nexps; + expdesc e; + do { + new_localvar(ls, str_checkname(ls), nvars++); + } while (testnext(ls, ',')); + if (testnext(ls, '=')) + nexps = explist1(ls, &e); + else { + e.k = VVOID; + nexps = 0; + } + adjust_assign(ls, nvars, nexps, &e); + adjustlocalvars(ls, nvars); +} + + +static int funcname (LexState *ls, expdesc *v) { + /* funcname -> NAME {field} [`:' NAME] */ + int needself = 0; + singlevar(ls, v); + while (ls->t.token == '.') + field(ls, v); + if (ls->t.token == ':') { + needself = 1; + field(ls, v); + } + return needself; +} + + +static void funcstat (LexState *ls, int line) { + /* funcstat -> FUNCTION funcname body */ + int needself; + expdesc v, b; + luaX_next(ls); /* skip FUNCTION */ + needself = funcname(ls, &v); + body(ls, &b, needself, line); + 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; + primaryexp(ls, &v.v); + if (v.v.k == VCALL) /* stat -> func */ + SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ + else { /* stat -> assignment */ + v.prev = NULL; + assignment(ls, &v, 1); + } +} + + +static void retstat (LexState *ls) { + /* stat -> RETURN explist */ + FuncState *fs = ls->fs; + expdesc e; + int first, nret; /* registers with returned values */ + luaX_next(ls); /* skip RETURN */ + if (block_follow(ls->t.token) || ls->t.token == ';') + first = nret = 0; /* return no values */ + else { + nret = explist1(ls, &e); /* optional return values */ + if (hasmultret(e.k)) { + luaK_setmultret(fs, &e); + if (e.k == VCALL && nret == 1) { /* tail call? */ + SET_OPCODE(getcode(fs,&e), OP_TAILCALL); + lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); + } + first = fs->nactvar; + nret = LUA_MULTRET; /* return all values */ + } + else { + if (nret == 1) /* only one single value? */ + first = luaK_exp2anyreg(fs, &e); + else { + luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ + first = fs->nactvar; /* return all `active' values */ + lua_assert(nret == fs->freereg - first); + } + } + } + luaK_ret(fs, first, nret); +} + + +static int statement (LexState *ls) { + int line = ls->linenumber; /* may be needed for error messages */ + switch (ls->t.token) { + case TK_IF: { /* stat -> ifstat */ + ifstat(ls, line); + return 0; + } + case TK_WHILE: { /* stat -> whilestat */ + whilestat(ls, line); + return 0; + } + case TK_DO: { /* stat -> DO block END */ + luaX_next(ls); /* skip DO */ + block(ls); + check_match(ls, TK_END, TK_DO, line); + return 0; + } + case TK_FOR: { /* stat -> forstat */ + forstat(ls, line); + return 0; + } + case TK_REPEAT: { /* stat -> repeatstat */ + repeatstat(ls, line); + return 0; + } + case TK_FUNCTION: { + funcstat(ls, line); /* stat -> funcstat */ + return 0; + } + case TK_LOCAL: { /* stat -> localstat */ + luaX_next(ls); /* skip LOCAL */ + if (testnext(ls, TK_FUNCTION)) /* local function? */ + localfunc(ls); + else + localstat(ls); + return 0; + } + case TK_RETURN: { /* stat -> retstat */ + retstat(ls); + return 1; /* must be last statement */ + } + case TK_BREAK: { /* stat -> breakstat */ + luaX_next(ls); /* skip BREAK */ + breakstat(ls); + return 1; /* must be last statement */ + } + default: { + exprstat(ls); + return 0; /* to avoid warnings */ + } + } +} + + +static void chunk (LexState *ls) { + /* chunk -> { stat [`;'] } */ + int islast = 0; + enterlevel(ls); + while (!islast && !block_follow(ls->t.token)) { + islast = statement(ls); + testnext(ls, ';'); + lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && + ls->fs->freereg >= ls->fs->nactvar); + ls->fs->freereg = ls->fs->nactvar; /* free registers */ + } + leavelevel(ls); +} + +/* }====================================================================== */ diff --git a/src/lua/lparser.h b/src/lua/lparser.h new file mode 100644 index 0000000..d5e6e81 --- /dev/null +++ b/src/lua/lparser.h @@ -0,0 +1,83 @@ +/* +** $Id: lparser.h,v 1.56 2005/10/03 14:02:40 roberto Exp $ +** Lua Parser +** See Copyright Notice in lua.h +*/ + +#ifndef lparser_h +#define lparser_h + +#include "llimits.h" +#include "lobject.h" +#include "ltable.h" +#include "lzio.h" + + +/* +** Expression descriptor +*/ + +typedef enum { + VVOID, /* no value */ + VNIL, + VTRUE, + VFALSE, + VK, /* info = index of constant in `k' */ + VKNUM, /* nval = numerical value */ + VLOCAL, /* info = local register */ + VUPVAL, /* info = index of upvalue in `upvalues' */ + VGLOBAL, /* info = index of table; aux = index of global name in `k' */ + VINDEXED, /* info = table register; aux = index register (or `k') */ + VJMP, /* info = instruction pc */ + VRELOCABLE, /* info = instruction pc */ + VNONRELOC, /* info = result register */ + VCALL, /* info = instruction pc */ + VVARARG /* info = instruction pc */ +} expkind; + +typedef struct expdesc { + expkind k; + union { + struct { int info, aux; } s; + lua_Number nval; + } u; + int t; /* patch list of `exit when true' */ + int f; /* patch list of `exit when false' */ +} expdesc; + + +typedef struct upvaldesc { + lu_byte k; + lu_byte info; +} upvaldesc; + + +struct BlockCnt; /* defined in lparser.c */ + + +/* state needed to generate code for a given function */ +typedef struct FuncState { + Proto *f; /* current function header */ + Table *h; /* table to find (and reuse) elements in `k' */ + struct FuncState *prev; /* enclosing function */ + struct LexState *ls; /* lexical state */ + struct lua_State *L; /* copy of the Lua state */ + struct BlockCnt *bl; /* chain of current blocks */ + int pc; /* next position to code (equivalent to `ncode') */ + int lasttarget; /* `pc' of last `jump target' */ + int jpc; /* list of pending jumps to `pc' */ + int freereg; /* first free register */ + int nk; /* number of elements in `k' */ + int np; /* number of elements in `p' */ + short nlocvars; /* number of elements in `locvars' */ + lu_byte nactvar; /* number of active local variables */ + upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */ + unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */ +} FuncState; + + +LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, + const char *name); + + +#endif diff --git a/src/lua/lstate.c b/src/lua/lstate.c new file mode 100644 index 0000000..77e93fb --- /dev/null +++ b/src/lua/lstate.c @@ -0,0 +1,214 @@ +/* +** $Id: lstate.c,v 2.35 2005/10/06 20:46:25 roberto Exp $ +** Global State +** See Copyright Notice in lua.h +*/ + + +#include + +#define lstate_c +#define LUA_CORE + +#include "lua.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" + + +#define state_size(x) (sizeof(x) + LUAI_EXTRASPACE) +#define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE) +#define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE)) + + +/* +** Main thread combines a thread state and the global state +*/ +typedef struct LG { + lua_State l; + global_State g; +} LG; + + + +static void stack_init (lua_State *L1, lua_State *L) { + /* initialize CallInfo array */ + L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo); + L1->ci = L1->base_ci; + L1->size_ci = BASIC_CI_SIZE; + L1->end_ci = L1->base_ci + L1->size_ci - 1; + /* initialize stack array */ + L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue); + L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK; + L1->top = L1->stack; + L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1; + /* initialize first ci */ + L1->ci->func = L1->top; + setnilvalue(L1->top++); /* `function' entry for this `ci' */ + L1->base = L1->ci->base = L1->top; + L1->ci->top = L1->top + LUA_MINSTACK; +} + + +static void freestack (lua_State *L, lua_State *L1) { + luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo); + luaM_freearray(L, L1->stack, L1->stacksize, TValue); +} + + +/* +** open parts 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 */ + sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */ + sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */ + luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ + luaT_init(L); + luaX_init(L); + luaS_fix(luaS_newliteral(L, MEMERRMSG)); + g->GCthreshold = 4*g->totalbytes; +} + + +static void preinit_state (lua_State *L, global_State *g) { + G(L) = g; + L->stack = NULL; + L->stacksize = 0; + L->errorJmp = NULL; + L->hook = NULL; + L->hookmask = 0; + L->basehookcount = 0; + L->allowhook = 1; + resethookcount(L); + L->openupval = NULL; + L->size_ci = 0; + L->nCcalls = 0; + L->status = 0; + L->base_ci = L->ci = NULL; + L->savedpc = NULL; + L->errfunc = 0; + setnilvalue(gt(L)); +} + + +static void close_state (lua_State *L) { + global_State *g = G(L); + luaF_close(L, L->stack); /* close all upvalues for this thread */ + luaC_freeall(L); /* collect all objects */ + lua_assert(g->rootgc == obj2gco(L)); + lua_assert(g->strt.nuse == 0); + luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *); + luaZ_freebuffer(L, &g->buff); + freestack(L, L); + lua_assert(g->totalbytes == sizeof(LG)); + (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0); +} + + +lua_State *luaE_newthread (lua_State *L) { + lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State))); + luaC_link(L, obj2gco(L1), LUA_TTHREAD); + preinit_state(L1, G(L)); + stack_init(L1, L); /* init stack */ + setobj2n(L, gt(L1), gt(L)); /* share table of globals */ + L1->hookmask = L->hookmask; + L1->basehookcount = L->basehookcount; + L1->hook = L->hook; + resethookcount(L1); + lua_assert(iswhite(obj2gco(L1))); + return L1; +} + + +void luaE_freethread (lua_State *L, lua_State *L1) { + luaF_close(L1, L1->stack); /* close all upvalues for this thread */ + lua_assert(L1->openupval == NULL); + luai_userstatefree(L1); + freestack(L, L1); + luaM_freemem(L, fromstate(L1), state_size(lua_State)); +} + + +LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { + int i; + lua_State *L; + global_State *g; + void *l = (*f)(ud, NULL, 0, state_size(LG)); + if (l == NULL) return NULL; + L = tostate(l); + g = &((LG *)L)->g; + L->next = NULL; + L->tt = LUA_TTHREAD; + g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); + L->marked = luaC_white(g); + set2bits(L->marked, FIXEDBIT, SFIXEDBIT); + preinit_state(L, g); + g->frealloc = f; + g->ud = ud; + g->mainthread = L; + g->uvhead.u.l.prev = &g->uvhead; + g->uvhead.u.l.next = &g->uvhead; + g->GCthreshold = 0; /* mark it as unfinished state */ + g->strt.size = 0; + g->strt.nuse = 0; + g->strt.hash = NULL; + setnilvalue(registry(L)); + luaZ_initbuffer(L, &g->buff); + g->panic = NULL; + g->gcstate = GCSpause; + g->rootgc = obj2gco(L); + g->sweepstrgc = 0; + g->sweepgc = &g->rootgc; + g->gray = NULL; + g->grayagain = NULL; + g->weak = NULL; + g->tmudata = NULL; + g->totalbytes = sizeof(LG); + g->gcpause = LUAI_GCPAUSE; + g->gcstepmul = LUAI_GCMUL; + g->gcdept = 0; + for (i=0; imt[i] = NULL; + if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { + /* memory allocation error: free partial state */ + close_state(L); + L = NULL; + } + else + luai_userstateopen(L); + return L; +} + + +static void callallgcTM (lua_State *L, void *ud) { + UNUSED(ud); + luaC_callGCTM(L); /* call GC metamethods for all udata */ +} + + +LUA_API void lua_close (lua_State *L) { + L = G(L)->mainthread; /* only the main thread can be closed */ + luai_userstateclose(L); + lua_lock(L); + luaF_close(L, L->stack); /* close all upvalues for this thread */ + luaC_separateudata(L, 1); /* separate udata that have GC metamethods */ + L->errfunc = 0; /* no error function during GC metamethods */ + do { /* repeat until no more errors */ + L->ci = L->base_ci; + L->base = L->top = L->ci->base; + L->nCcalls = 0; + } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0); + lua_assert(G(L)->tmudata == NULL); + close_state(L); +} + diff --git a/src/lua/lstate.h b/src/lua/lstate.h new file mode 100644 index 0000000..d296a4c --- /dev/null +++ b/src/lua/lstate.h @@ -0,0 +1,168 @@ +/* +** $Id: lstate.h,v 2.24 2006/02/06 18:27:59 roberto Exp $ +** Global State +** See Copyright Notice in lua.h +*/ + +#ifndef lstate_h +#define lstate_h + +#include "lua.h" + +#include "lobject.h" +#include "ltm.h" +#include "lzio.h" + + + +struct lua_longjmp; /* defined in ldo.c */ + + +/* table of globals */ +#define gt(L) (&L->l_gt) + +/* registry */ +#define registry(L) (&G(L)->l_registry) + + +/* extra stack space to handle TM calls and some other extras */ +#define EXTRA_STACK 5 + + +#define BASIC_CI_SIZE 8 + +#define BASIC_STACK_SIZE (2*LUA_MINSTACK) + + + +typedef struct stringtable { + GCObject **hash; + lu_int32 nuse; /* number of elements */ + int size; +} stringtable; + + +/* +** informations about a call +*/ +typedef struct CallInfo { + StkId base; /* base for this function */ + StkId func; /* function index in the stack */ + StkId top; /* top for this function */ + const Instruction *savedpc; + int nresults; /* expected number of results from this function */ + int tailcalls; /* number of tail calls lost under this entry */ +} CallInfo; + + + +#define curr_func(L) (clvalue(L->ci->func)) +#define ci_func(ci) (clvalue((ci)->func)) +#define f_isLua(ci) (!ci_func(ci)->c.isC) +#define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) + + +/* +** `global state', shared by all threads of this state +*/ +typedef struct global_State { + stringtable strt; /* hash table for strings */ + lua_Alloc frealloc; /* function to reallocate memory */ + void *ud; /* auxiliary data to `frealloc' */ + lu_byte currentwhite; + lu_byte gcstate; /* state of garbage collector */ + int sweepstrgc; /* position of sweep in `strt' */ + GCObject *rootgc; /* list of all collectable objects */ + GCObject **sweepgc; /* position of sweep in `rootgc' */ + GCObject *gray; /* list of gray objects */ + GCObject *grayagain; /* list of objects to be traversed atomically */ + GCObject *weak; /* list of weak tables (to be cleared) */ + GCObject *tmudata; /* last element of list of userdata to be GC */ + Mbuffer buff; /* temporary buffer for string concatentation */ + lu_mem GCthreshold; + lu_mem totalbytes; /* number of bytes currently allocated */ + lu_mem estimate; /* an estimate of number of bytes actually in use */ + lu_mem gcdept; /* how much GC is `behind schedule' */ + int gcpause; /* size of pause between successive GCs */ + int gcstepmul; /* GC `granularity' */ + lua_CFunction panic; /* to be called in unprotected errors */ + TValue l_registry; + struct lua_State *mainthread; + UpVal uvhead; /* head of double-linked list of all open upvalues */ + struct Table *mt[NUM_TAGS]; /* metatables for basic types */ + TString *tmname[TM_N]; /* array with tag-method names */ +} global_State; + + +/* +** `per thread' state +*/ +struct lua_State { + CommonHeader; + lu_byte status; + StkId top; /* first free slot in the stack */ + StkId base; /* base of current function */ + global_State *l_G; + CallInfo *ci; /* call info for current function */ + const Instruction *savedpc; /* `savedpc' of current function */ + StkId stack_last; /* last free slot in the stack */ + StkId stack; /* stack base */ + CallInfo *end_ci; /* points after end of ci array*/ + CallInfo *base_ci; /* array of CallInfo's */ + int stacksize; + int size_ci; /* size of array `base_ci' */ + unsigned short nCcalls; /* number of nested C calls */ + lu_byte hookmask; + lu_byte allowhook; + int basehookcount; + int hookcount; + lua_Hook hook; + TValue l_gt; /* table of globals */ + TValue env; /* temporary place for environments */ + GCObject *openupval; /* list of open upvalues in this stack */ + GCObject *gclist; + struct lua_longjmp *errorJmp; /* current error recover point */ + ptrdiff_t errfunc; /* current error handling function (stack index) */ +}; + + +#define G(L) (L->l_G) + + +/* +** Union of all collectable objects +*/ +union GCObject { + GCheader gch; + union TString ts; + union Udata u; + union Closure cl; + struct Table h; + struct Proto p; + struct UpVal uv; + struct lua_State th; /* thread */ +}; + + +/* macros to convert a GCObject into a specific value */ +#define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts)) +#define gco2ts(o) (&rawgco2ts(o)->tsv) +#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) +#define gco2u(o) (&rawgco2u(o)->uv) +#define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) +#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) +#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) +#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) +#define ngcotouv(o) \ + check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv)) +#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) + +/* macro to convert any Lua object into a GCObject */ +#define obj2gco(v) (cast(GCObject *, (v))) + + +LUAI_FUNC lua_State *luaE_newthread (lua_State *L); +LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); + +#endif + diff --git a/src/lua/lstring.c b/src/lua/lstring.c new file mode 100644 index 0000000..4319930 --- /dev/null +++ b/src/lua/lstring.c @@ -0,0 +1,111 @@ +/* +** $Id: lstring.c,v 2.8 2005/12/22 16:19:56 roberto Exp $ +** String table (keeps all strings handled by Lua) +** See Copyright Notice in lua.h +*/ + + +#include + +#define lstring_c +#define LUA_CORE + +#include "lua.h" + +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" + + + +void luaS_resize (lua_State *L, int newsize) { + GCObject **newhash; + stringtable *tb; + int i; + if (G(L)->gcstate == GCSsweepstring) + return; /* cannot resize during GC traverse */ + newhash = luaM_newvector(L, newsize, GCObject *); + tb = &G(L)->strt; + for (i=0; isize; i++) { + GCObject *p = tb->hash[i]; + while (p) { /* for each node in the list */ + GCObject *next = p->gch.next; /* save next */ + unsigned int h = gco2ts(p)->hash; + int h1 = lmod(h, newsize); /* new position */ + lua_assert(cast_int(h%newsize) == lmod(h, newsize)); + p->gch.next = newhash[h1]; /* chain it */ + newhash[h1] = p; + p = next; + } + } + luaM_freearray(L, tb->hash, tb->size, TString *); + tb->size = newsize; + tb->hash = newhash; +} + + +static TString *newlstr (lua_State *L, const char *str, size_t l, + unsigned int h) { + TString *ts; + stringtable *tb; + if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) + luaM_toobig(L); + ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString))); + ts->tsv.len = l; + ts->tsv.hash = h; + ts->tsv.marked = luaC_white(G(L)); + ts->tsv.tt = LUA_TSTRING; + ts->tsv.reserved = 0; + memcpy(ts+1, str, l*sizeof(char)); + ((char *)(ts+1))[l] = '\0'; /* ending 0 */ + tb = &G(L)->strt; + h = lmod(h, tb->size); + ts->tsv.next = tb->hash[h]; /* chain new entry */ + tb->hash[h] = obj2gco(ts); + tb->nuse++; + if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2) + luaS_resize(L, tb->size*2); /* too crowded */ + return ts; +} + + +TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { + GCObject *o; + unsigned int h = cast(unsigned int, l); /* seed */ + size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */ + size_t l1; + for (l1=l; l1>=step; l1-=step) /* compute hash */ + h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1])); + for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)]; + o != NULL; + o = o->gch.next) { + TString *ts = rawgco2ts(o); + if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) { + /* string may be dead */ + if (isdead(G(L), o)) changewhite(o); + return ts; + } + } + return newlstr(L, str, l, h); /* not found */ +} + + +Udata *luaS_newudata (lua_State *L, size_t s, Table *e) { + Udata *u; + if (s > MAX_SIZET - sizeof(Udata)) + luaM_toobig(L); + u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata))); + u->uv.marked = luaC_white(G(L)); /* is not finalized */ + u->uv.tt = LUA_TUSERDATA; + u->uv.len = s; + u->uv.metatable = NULL; + u->uv.env = e; + /* chain it on udata list (after main thread) */ + u->uv.next = G(L)->mainthread->next; + G(L)->mainthread->next = obj2gco(u); + return u; +} + diff --git a/src/lua/lstring.h b/src/lua/lstring.h new file mode 100644 index 0000000..1d2e91e --- /dev/null +++ b/src/lua/lstring.h @@ -0,0 +1,31 @@ +/* +** $Id: lstring.h,v 1.43 2005/04/25 19:24:10 roberto Exp $ +** 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" + + +#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) + +#define sizeudata(u) (sizeof(union Udata)+(u)->len) + +#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s))) +#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ + (sizeof(s)/sizeof(char))-1)) + +#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT) + +LUAI_FUNC void luaS_resize (lua_State *L, int newsize); +LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e); +LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); + + +#endif diff --git a/src/lua/lstrlib.c b/src/lua/lstrlib.c new file mode 100644 index 0000000..84478fd --- /dev/null +++ b/src/lua/lstrlib.c @@ -0,0 +1,863 @@ +/* +** $Id: lstrlib.c,v 1.130 2005/12/29 15:32:11 roberto Exp $ +** Standard library for string operations and pattern-matching +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include +#include + +#define lstrlib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* macro to `unsign' a character */ +#define uchar(c) ((unsigned char)(c)) + + + +static int str_len (lua_State *L) { + size_t l; + luaL_checklstring(L, 1, &l); + lua_pushinteger(L, l); + return 1; +} + + +static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) { + /* relative string position: negative means back from end */ + return (pos>=0) ? pos : (ptrdiff_t)len+pos+1; +} + + +static int str_sub (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l); + ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l); + if (start < 1) start = 1; + if (end > (ptrdiff_t)l) end = (ptrdiff_t)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; + luaL_Buffer b; + const char *s = luaL_checklstring(L, 1, &l); + luaL_buffinit(L, &b); + while (l--) luaL_addchar(&b, s[l]); + luaL_pushresult(&b); + 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); + luaL_buffinit(L, &b); + for (i=0; i 0) + luaL_addlstring(&b, s, l); + luaL_pushresult(&b); + return 1; +} + + +static int str_byte (lua_State *L) { + size_t l; + const char *s = luaL_checklstring(L, 1, &l); + ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l); + ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l); + int n, i; + if (posi <= 0) posi = 1; + if ((size_t)pose > l) pose = l; + if (posi > pose) return 0; /* empty interval; return no values */ + n = (int)(pose - posi + 1); + if (posi + n <= pose) /* overflow? */ + luaL_error(L, "string slice too long"); + luaL_checkstack(L, n, "string slice too long"); + for (i=0; i= ms->level || ms->capture[l].len == CAP_UNFINISHED) + return luaL_error(ms->L, "invalid capture index"); + 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 (*p == '\0') + luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); + return p+1; + } + case '[': { + if (*p == '^') p++; + do { /* look for a `]' */ + if (*p == '\0') + luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); + if (*(p++) == L_ESC && *p != '\0') + 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 '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; + 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 (int c, const char *p, const char *ep) { + 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 *match (MatchState *ms, const char *s, const char *p); + + +static const char *matchbalance (MatchState *ms, const char *s, + const char *p) { + if (*p == 0 || *(p+1) == 0) + luaL_error(ms->L, "unbalanced pattern"); + 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 ((s+i)src_end && singlematch(uchar(*(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 (ssrc_end && singlematch(uchar(*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) { + init: /* using goto's to optimize tail recursion */ + switch (*p) { + case '(': { /* start capture */ + if (*(p+1) == ')') /* position capture? */ + return start_capture(ms, s, p+2, CAP_POSITION); + else + return start_capture(ms, s, p+1, CAP_UNFINISHED); + } + case ')': { /* end capture */ + return end_capture(ms, s, p+1); + } + case L_ESC: { + switch (*(p+1)) { + case 'b': { /* balanced string? */ + s = matchbalance(ms, s, p+2); + if (s == NULL) return NULL; + p+=4; goto init; /* else return match(ms, s, p+4); */ + } + case 'f': { /* frontier? */ + const char *ep; char previous; + p += 2; + if (*p != '[') + luaL_error(ms->L, "missing " LUA_QL("[") " after " + LUA_QL("%%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)) return NULL; + p=ep; goto init; /* else return match(ms, s, ep); */ + } + default: { + if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */ + s = match_capture(ms, s, uchar(*(p+1))); + if (s == NULL) return NULL; + p+=2; goto init; /* else return match(ms, s, p+2) */ + } + goto dflt; /* case default */ + } + } + } + case '\0': { /* end of pattern */ + return s; /* match succeeded */ + } + case '$': { + if (*(p+1) == '\0') /* is the `$' the last char in pattern? */ + return (s == ms->src_end) ? s : NULL; /* check end of string */ + else goto dflt; + } + default: dflt: { /* it is a pattern item */ + const char *ep = classend(ms, p); /* points to what is next */ + int m = ssrc_end && singlematch(uchar(*s), p, ep); + switch (*ep) { + case '?': { /* optional */ + const char *res; + if (m && ((res=match(ms, s+1, ep+1)) != NULL)) + return res; + p=ep+1; goto init; /* else return match(ms, s, ep+1); */ + } + case '*': { /* 0 or more repetitions */ + return max_expand(ms, s, p, ep); + } + case '+': { /* 1 or more repetitions */ + return (m ? max_expand(ms, s+1, p, ep) : NULL); + } + case '-': { /* 0 or more repetitions (minimum) */ + return min_expand(ms, s, p, ep); + } + default: { + if (!m) return NULL; + s++; p=ep; goto init; /* else return match(ms, s+1, ep); */ + } + } + } + } +} + + + +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 */ + } +} + + +static void push_onecapture (MatchState *ms, int i, const char *s, + const char *e) { + if (i >= ms->level) { + if (i == 0) /* ms->level == 0, too */ + lua_pushlstring(ms->L, s, e - s); /* add whole match */ + else + luaL_error(ms->L, "invalid capture index"); + } + else { + ptrdiff_t l = ms->capture[i].len; + if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); + if (l == CAP_POSITION) + lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); + else + lua_pushlstring(ms->L, ms->capture[i].init, l); + } +} + + +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 */ +} + + +static int str_find_aux (lua_State *L, int find) { + size_t l1, l2; + const char *s = luaL_checklstring(L, 1, &l1); + const char *p = luaL_checklstring(L, 2, &l2); + ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1; + if (init < 0) init = 0; + else if ((size_t)(init) > l1) init = (ptrdiff_t)l1; + if (find && (lua_toboolean(L, 4) || /* explicit request? */ + strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */ + /* do a plain search */ + const char *s2 = lmemfind(s+init, l1-init, p, l2); + if (s2) { + lua_pushinteger(L, s2-s+1); + lua_pushinteger(L, s2-s+l2); + return 2; + } + } + else { + MatchState ms; + int anchor = (*p == '^') ? (p++, 1) : 0; + const char *s1=s+init; + ms.L = L; + ms.src_init = s; + ms.src_end = s+l1; + do { + const char *res; + ms.level = 0; + 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); + } + lua_pushnil(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); +} + + +static int gmatch_aux (lua_State *L) { + MatchState ms; + size_t ls; + const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); + const char *p = lua_tostring(L, lua_upvalueindex(2)); + const char *src; + ms.L = L; + ms.src_init = s; + ms.src_end = s+ls; + for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); + src <= ms.src_end; + src++) { + const char *e; + ms.level = 0; + if ((e = match(&ms, src, p)) != NULL) { + lua_Integer newstart = e-s; + if (e == src) newstart++; /* empty match? go at least one position */ + lua_pushinteger(L, newstart); + lua_replace(L, lua_upvalueindex(3)); + return push_captures(&ms, src, e); + } + } + return 0; /* not found */ +} + + +static int gmatch (lua_State *L) { + luaL_checkstring(L, 1); + luaL_checkstring(L, 2); + lua_settop(L, 2); + lua_pushinteger(L, 0); + lua_pushcclosure(L, gmatch_aux, 3); + return 1; +} + + +static int gfind_nodef (lua_State *L) { + return luaL_error(L, LUA_QL("string.gfind") " was renamed to " + LUA_QL("string.gmatch")); +} + + +static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e) { + size_t l, i; + const char *news = lua_tolstring(ms->L, 3, &l); + for (i = 0; i < l; i++) { + if (news[i] != L_ESC) + luaL_addchar(b, news[i]); + else { + i++; /* skip ESC */ + if (!isdigit(uchar(news[i]))) + luaL_addchar(b, news[i]); + else if (news[i] == '0') + luaL_addlstring(b, s, e - s); + else { + push_onecapture(ms, news[i] - '1', s, e); + luaL_addvalue(b); /* add capture to accumulated result */ + } + } + } +} + + +static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, + const char *e) { + lua_State *L = ms->L; + switch (lua_type(L, 3)) { + case LUA_TNUMBER: + case LUA_TSTRING: { + add_s(ms, b, s, e); + return; + } + case LUA_TFUNCTION: { + int n; + lua_pushvalue(L, 3); + n = push_captures(ms, s, e); + lua_call(L, n, 1); + break; + } + case LUA_TTABLE: { + push_onecapture(ms, 0, s, e); + lua_gettable(L, 3); + break; + } + default: { + luaL_argerror(L, 3, "string/function/table expected"); + return; + } + } + if (!lua_toboolean(L, -1)) { /* nil or false? */ + lua_pop(L, 1); + lua_pushlstring(L, s, e - s); /* keep original text */ + } + else if (!lua_isstring(L, -1)) + luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); + luaL_addvalue(b); /* add result to accumulator */ +} + + +static int str_gsub (lua_State *L) { + size_t srcl; + const char *src = luaL_checklstring(L, 1, &srcl); + const char *p = luaL_checkstring(L, 2); + int max_s = luaL_optint(L, 4, srcl+1); + int anchor = (*p == '^') ? (p++, 1) : 0; + int n = 0; + MatchState ms; + luaL_Buffer b; + luaL_buffinit(L, &b); + ms.L = L; + ms.src_init = src; + ms.src_end = src+srcl; + while (n < max_s) { + const char *e; + ms.level = 0; + e = match(&ms, src, p); + if (e) { + n++; + add_value(&ms, &b, src, e); + } + if (e && e>src) /* non empty match? */ + src = e; /* skip it */ + else if (src < ms.src_end) + luaL_addchar(&b, *src++); + else break; + if (anchor) break; + } + luaL_addlstring(&b, src, ms.src_end-src); + luaL_pushresult(&b); + lua_pushinteger(L, n); /* number of substitutions */ + return 2; +} + +/* }====================================================== */ + + +/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ +#define MAX_ITEM 512 +/* valid flags in a format specification */ +#define FLAGS "-+ #0" +/* +** maximum size of each format specification (such as '%-099.99d') +** (+10 accounts for %99.99x plus margin of error) +*/ +#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) + + +static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { + size_t l; + const char *s = luaL_checklstring(L, arg, &l); + luaL_addchar(b, '"'); + while (l--) { + switch (*s) { + case '"': case '\\': case '\n': { + luaL_addchar(b, '\\'); + luaL_addchar(b, *s); + break; + } + case '\0': { + luaL_addlstring(b, "\\000", 4); + break; + } + default: { + luaL_addchar(b, *s); + break; + } + } + s++; + } + luaL_addchar(b, '"'); +} + +static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { + const char *p = strfrmt; + while (strchr(FLAGS, *p)) p++; /* skip flags */ + if ((size_t)(p - strfrmt) >= sizeof(FLAGS)) + luaL_error(L, "invalid format (repeated flags)"); + if (isdigit(uchar(*p))) p++; /* skip width */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + if (*p == '.') { + p++; + if (isdigit(uchar(*p))) p++; /* skip precision */ + if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ + } + if (isdigit(uchar(*p))) + luaL_error(L, "invalid format (width or precision too long)"); + *(form++) = '%'; + strncpy(form, strfrmt, p - strfrmt + 1); + form += p - strfrmt + 1; + *form = '\0'; + return p; +} + + +static void addintlen (char *form) { + size_t l = strlen(form); + char spec = form[l - 1]; + strcpy(form + l - 1, LUA_INTFRMLEN); + form[l + sizeof(LUA_INTFRMLEN) - 2] = spec; + form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0'; +} + + +static int str_format (lua_State *L) { + int arg = 1; + size_t sfl; + const char *strfrmt = luaL_checklstring(L, arg, &sfl); + const char *strfrmt_end = strfrmt+sfl; + 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 (`%...') */ + char buff[MAX_ITEM]; /* to store the formatted item */ + arg++; + strfrmt = scanformat(L, strfrmt, form); + switch (*strfrmt++) { + case 'c': { + sprintf(buff, form, (int)luaL_checknumber(L, arg)); + break; + } + case 'd': case 'i': { + addintlen(form); + sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); + break; + } + case 'o': case 'u': case 'x': case 'X': { + addintlen(form); + sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); + break; + } + case 'e': case 'E': case 'f': + case 'g': case 'G': { + sprintf(buff, form, (double)luaL_checknumber(L, arg)); + break; + } + case 'q': { + addquoted(L, &b, arg); + continue; /* skip the 'addsize' at the end */ + } + case 's': { + size_t l; + const char *s = luaL_checklstring(L, arg, &l); + if (!strchr(form, '.') && l >= 100) { + /* no precision and string is too long to be formatted; + keep original string */ + lua_pushvalue(L, arg); + luaL_addvalue(&b); + continue; /* skip the `addsize' at the end */ + } + else { + sprintf(buff, form, s); + break; + } + } + default: { /* also treat cases `pnLlh' */ + return luaL_error(L, "invalid option to " LUA_QL("format")); + } + } + luaL_addlstring(&b, buff, strlen(buff)); + } + } + luaL_pushresult(&b); + return 1; +} + + +static const luaL_Reg strlib[] = { + {"byte", str_byte}, + {"char", str_char}, + {"dump", str_dump}, + {"find", str_find}, + {"format", str_format}, + {"gfind", gfind_nodef}, + {"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}, + {NULL, NULL} +}; + + +static void createmetatable (lua_State *L) { + lua_createtable(L, 0, 1); /* create metatable for strings */ + lua_pushliteral(L, ""); /* dummy string */ + lua_pushvalue(L, -2); + lua_setmetatable(L, -2); /* set string metatable */ + lua_pop(L, 1); /* pop dummy string */ + lua_pushvalue(L, -2); /* string library... */ + lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */ + lua_pop(L, 1); /* pop metatable */ +} + + +/* +** Open string library +*/ +LUALIB_API int luaopen_string (lua_State *L) { + luaL_register(L, LUA_STRLIBNAME, strlib); +#if defined(LUA_COMPAT_GFIND) + lua_getfield(L, -1, "gmatch"); + lua_setfield(L, -2, "gfind"); +#endif + createmetatable(L); + return 1; +} + diff --git a/src/lua/ltable.c b/src/lua/ltable.c new file mode 100644 index 0000000..bc91cac --- /dev/null +++ b/src/lua/ltable.c @@ -0,0 +1,588 @@ +/* +** $Id: ltable.c,v 2.32 2006/01/18 11:49:02 roberto Exp $ +** Lua tables (hash) +** See Copyright Notice in lua.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 at +** least half the slots between 0 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 + +#define ltable_c +#define LUA_CORE + +#include "lua.h" + +#include "ldebug.h" +#include "ldo.h" +#include "lgc.h" +#include "lmem.h" +#include "lobject.h" +#include "lstate.h" +#include "ltable.h" + + +/* +** max size of array part is 2^MAXBITS +*/ +#if LUAI_BITSINT > 26 +#define MAXBITS 26 +#else +#define MAXBITS (LUAI_BITSINT-2) +#endif + +#define MAXASIZE (1 << MAXBITS) + + +#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) + +#define hashstr(t,str) hashpow2(t, (str)->tsv.hash) +#define hashboolean(t,p) hashpow2(t, p) + + +/* +** for some types, it is better to avoid modulus by power of 2, as +** they tend to have many 2 factors. +*/ +#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) + + +#define hashpointer(t,p) hashmod(t, IntPoint(p)) + + +/* +** number of ints inside a lua_Number +*/ +#define numints cast_int(sizeof(lua_Number)/sizeof(int)) + + + +#define dummynode (&dummynode_) + +static const Node dummynode_ = { + {{NULL}, LUA_TNIL}, /* value */ + {{{NULL}, LUA_TNIL, NULL}} /* key */ +}; + + +/* +** hash for lua_Numbers +*/ +static Node *hashnum (const Table *t, lua_Number n) { + unsigned int a[numints]; + int i; + n += 1; /* normalize number (avoid -0) */ + lua_assert(sizeof(a) <= sizeof(n)); + memcpy(a, &n, sizeof(a)); + for (i = 1; i < numints; i++) a[0] += a[i]; + return hashmod(t, a[0]); +} + + + +/* +** returns the `main' position of an element in a table (that is, the index +** of its hash value) +*/ +static Node *mainposition (const Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TNUMBER: + return hashnum(t, nvalue(key)); + case LUA_TSTRING: + return hashstr(t, rawtsvalue(key)); + case LUA_TBOOLEAN: + return hashboolean(t, bvalue(key)); + case LUA_TLIGHTUSERDATA: + return hashpointer(t, pvalue(key)); + default: + return hashpointer(t, gcvalue(key)); + } +} + + +/* +** returns the index for `key' if `key' is an appropriate key to live in +** the array part of the table, -1 otherwise. +*/ +static int arrayindex (const TValue *key) { + if (ttisnumber(key)) { + lua_Number n = nvalue(key); + int k; + lua_number2int(k, n); + if (luai_numeq(cast_num(k), n)) + return k; + } + return -1; /* `key' did not match some condition */ +} + + +/* +** 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 signalled by -1. +*/ +static int findindex (lua_State *L, Table *t, StkId key) { + int i; + if (ttisnil(key)) return -1; /* first iteration */ + i = arrayindex(key); + if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ + return i-1; /* yes; that's the index (corrected to C) */ + else { + Node *n = mainposition(t, key); + do { /* check whether `key' is somewhere in the chain */ + /* key may be dead already, but it is ok to use it in `next' */ + if (luaO_rawequalObj(key2tval(n), key) || + (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && + gcvalue(gkey(n)) == gcvalue(key))) { + i = cast_int(n - gnode(t, 0)); /* key index in hash table */ + /* hash elements are numbered after array ones */ + return i + t->sizearray; + } + else n = gnext(n); + } while (n); + luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ + return 0; /* to avoid warnings */ + } +} + + +int luaH_next (lua_State *L, Table *t, StkId key) { + int i = findindex(L, t, key); /* find original element */ + for (i++; i < t->sizearray; i++) { /* try first array part */ + if (!ttisnil(&t->array[i])) { /* a non-nil value? */ + setnvalue(key, cast_num(i+1)); + setobj2s(L, key+1, &t->array[i]); + return 1; + } + } + for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ + if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ + setobj2s(L, key, key2tval(gnode(t, i))); + setobj2s(L, key+1, gval(gnode(t, i))); + return 1; + } + } + return 0; /* no more elements */ +} + + +/* +** {============================================================= +** Rehash +** ============================================================== +*/ + + +static int computesizes (int nums[], int *narray) { + int i; + int twotoi; /* 2^i */ + int a = 0; /* number of elements smaller than 2^i */ + int na = 0; /* number of elements to go to array part */ + int n = 0; /* optimal size for array part */ + for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { + if (nums[i] > 0) { + a += nums[i]; + if (a > twotoi/2) { /* more than half elements present? */ + n = twotoi; /* optimal size (till now) */ + na = a; /* all elements smaller than n will go to array part */ + } + } + if (a == *narray) break; /* all elements already counted */ + } + *narray = n; + lua_assert(*narray/2 <= na && na <= *narray); + return na; +} + + +static int countint (const TValue *key, int *nums) { + int k = arrayindex(key); + if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ + nums[ceillog2(k)]++; /* count as such */ + return 1; + } + else + return 0; +} + + +static int numusearray (const Table *t, int *nums) { + int lg; + int ttlg; /* 2^lg */ + int ause = 0; /* summation of `nums' */ + int i = 1; /* count to traverse all array keys */ + for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ + int lc = 0; /* counter */ + int lim = ttlg; + if (lim > t->sizearray) { + lim = t->sizearray; /* 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 (!ttisnil(&t->array[i-1])) + lc++; + } + nums[lg] += lc; + ause += lc; + } + return ause; +} + + +static int numusehash (const Table *t, int *nums, int *pnasize) { + int totaluse = 0; /* total number of elements */ + int ause = 0; /* summation of `nums' */ + int i = sizenode(t); + while (i--) { + Node *n = &t->node[i]; + if (!ttisnil(gval(n))) { + ause += countint(key2tval(n), nums); + totaluse++; + } + } + *pnasize += ause; + return totaluse; +} + + +static void setarrayvector (lua_State *L, Table *t, int size) { + int i; + luaM_reallocvector(L, t->array, t->sizearray, size, TValue); + for (i=t->sizearray; iarray[i]); + t->sizearray = size; +} + + +static void setnodevector (lua_State *L, Table *t, int size) { + int lsize; + if (size == 0) { /* no elements to hash part? */ + t->node = cast(Node *, dummynode); /* use common `dummynode' */ + lsize = 0; + } + else { + int i; + lsize = ceillog2(size); + if (lsize > MAXBITS) + luaG_runerror(L, "table overflow"); + size = twoto(lsize); + t->node = luaM_newvector(L, size, Node); + for (i=0; ilsizenode = cast_byte(lsize); + t->lastfree = gnode(t, size); /* all positions are free */ +} + + +static void resize (lua_State *L, Table *t, int nasize, int nhsize) { + int i; + int oldasize = t->sizearray; + int oldhsize = t->lsizenode; + Node *nold = t->node; /* save old hash ... */ + if (nasize > oldasize) /* array part must grow? */ + setarrayvector(L, t, nasize); + /* create new hash part with appropriate size */ + setnodevector(L, t, nhsize); + if (nasize < oldasize) { /* array part must shrink? */ + t->sizearray = nasize; + /* re-insert elements from vanishing slice */ + for (i=nasize; iarray[i])) + setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]); + } + /* shrink array */ + luaM_reallocvector(L, t->array, oldasize, nasize, TValue); + } + /* re-insert elements from hash part */ + for (i = twoto(oldhsize) - 1; i >= 0; i--) { + Node *old = nold+i; + if (!ttisnil(gval(old))) + setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old)); + } + if (nold != dummynode) + luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */ +} + + +void luaH_resizearray (lua_State *L, Table *t, int nasize) { + int nsize = (t->node == dummynode) ? 0 : sizenode(t); + resize(L, t, nasize, nsize); +} + + +static void rehash (lua_State *L, Table *t, const TValue *ek) { + int nasize, na; + int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ + int i; + int totaluse; + for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ + nasize = numusearray(t, nums); /* count keys in array part */ + totaluse = nasize; /* all those keys are integer keys */ + totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ + /* count extra key */ + nasize += countint(ek, nums); + totaluse++; + /* compute new size for array part */ + na = computesizes(nums, &nasize); + /* resize the table to new computed sizes */ + resize(L, t, nasize, totaluse - na); +} + + + +/* +** }============================================================= +*/ + + +Table *luaH_new (lua_State *L, int narray, int nhash) { + Table *t = luaM_new(L, Table); + luaC_link(L, obj2gco(t), LUA_TTABLE); + t->metatable = NULL; + t->flags = cast_byte(~0); + /* temporary values (kept only if some malloc fails) */ + t->array = NULL; + t->sizearray = 0; + t->lsizenode = 0; + t->node = cast(Node *, dummynode); + setarrayvector(L, t, narray); + setnodevector(L, t, nhash); + return t; +} + + +void luaH_free (lua_State *L, Table *t) { + if (t->node != dummynode) + luaM_freearray(L, t->node, sizenode(t), Node); + luaM_freearray(L, t->array, t->sizearray, TValue); + luaM_free(L, t); +} + + +static Node *getfreepos (Table *t) { + while (t->lastfree-- > t->node) { + if (ttisnil(gkey(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. +*/ +static TValue *newkey (lua_State *L, Table *t, const TValue *key) { + Node *mp = mainposition(t, key); + if (!ttisnil(gval(mp)) || mp == dummynode) { + Node *othern; + Node *n = getfreepos(t); /* get a free place */ + if (n == NULL) { /* cannot find a free place? */ + rehash(L, t, key); /* grow table */ + return luaH_set(L, t, key); /* re-insert key into grown table */ + } + lua_assert(n != dummynode); + othern = mainposition(t, key2tval(mp)); + if (othern != mp) { /* is colliding node out of its main position? */ + /* yes; move colliding node into free position */ + while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ + gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ + *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ + gnext(mp) = NULL; /* now `mp' is free */ + setnilvalue(gval(mp)); + } + else { /* colliding node is in its own main position */ + /* new node will go into free position */ + gnext(n) = gnext(mp); /* chain new position */ + gnext(mp) = n; + mp = n; + } + } + gkey(mp)->value = key->value; gkey(mp)->tt = key->tt; + luaC_barriert(L, t, key); + lua_assert(ttisnil(gval(mp))); + return gval(mp); +} + + +/* +** search function for integers +*/ +const TValue *luaH_getnum (Table *t, int key) { + /* (1 <= key && key <= t->sizearray) */ + if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) + return &t->array[key-1]; + else { + lua_Number nk = cast_num(key); + Node *n = hashnum(t, nk); + do { /* check whether `key' is somewhere in the chain */ + if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; + } +} + + +/* +** search function for strings +*/ +const TValue *luaH_getstr (Table *t, TString *key) { + Node *n = hashstr(t, key); + do { /* check whether `key' is somewhere in the chain */ + if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; +} + + +/* +** main search function +*/ +const TValue *luaH_get (Table *t, const TValue *key) { + switch (ttype(key)) { + case LUA_TNIL: return luaO_nilobject; + case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); + case LUA_TNUMBER: { + int k; + lua_Number n = nvalue(key); + lua_number2int(k, n); + if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ + return luaH_getnum(t, k); /* use specialized version */ + /* else go through */ + } + default: { + Node *n = mainposition(t, key); + do { /* check whether `key' is somewhere in the chain */ + if (luaO_rawequalObj(key2tval(n), key)) + return gval(n); /* that's it */ + else n = gnext(n); + } while (n); + return luaO_nilobject; + } + } +} + + +TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { + const TValue *p = luaH_get(t, key); + t->flags = 0; + if (p != luaO_nilobject) + return cast(TValue *, p); + else { + if (ttisnil(key)) luaG_runerror(L, "table index is nil"); + else if (ttisnumber(key) && luai_numisnan(nvalue(key))) + luaG_runerror(L, "table index is NaN"); + return newkey(L, t, key); + } +} + + +TValue *luaH_setnum (lua_State *L, Table *t, int key) { + const TValue *p = luaH_getnum(t, key); + if (p != luaO_nilobject) + return cast(TValue *, p); + else { + TValue k; + setnvalue(&k, cast_num(key)); + return newkey(L, t, &k); + } +} + + +TValue *luaH_setstr (lua_State *L, Table *t, TString *key) { + const TValue *p = luaH_getstr(t, key); + if (p != luaO_nilobject) + return cast(TValue *, p); + else { + TValue k; + setsvalue(L, &k, key); + return newkey(L, t, &k); + } +} + + +static int unbound_search (Table *t, unsigned int j) { + unsigned int i = j; /* i is zero or a present index */ + j++; + /* find `i' and `j' such that i is present and j is not */ + while (!ttisnil(luaH_getnum(t, j))) { + i = j; + j *= 2; + if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ + /* table was built with bad purposes: resort to linear search */ + i = 1; + while (!ttisnil(luaH_getnum(t, i))) i++; + return i - 1; + } + } + /* now do a binary search between them */ + while (j - i > 1) { + unsigned int m = (i+j)/2; + if (ttisnil(luaH_getnum(t, m))) 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 non-nil and t[i+1] is nil (and 0 if t[1] is nil). +*/ +int luaH_getn (Table *t) { + unsigned int j = t->sizearray; + if (j > 0 && ttisnil(&t->array[j - 1])) { + /* there is a boundary in the array part: (binary) search for it */ + unsigned int i = 0; + while (j - i > 1) { + unsigned int m = (i+j)/2; + if (ttisnil(&t->array[m - 1])) j = m; + else i = m; + } + return i; + } + /* else must find a boundary in hash part */ + else if (t->node == dummynode) /* hash part is empty? */ + return j; /* that is easy... */ + else return unbound_search(t, j); +} + + + +#if defined(LUA_DEBUG) + +Node *luaH_mainposition (const Table *t, const TValue *key) { + return mainposition(t, key); +} + +int luaH_isdummy (Node *n) { return n == dummynode; } + +#endif diff --git a/src/lua/ltable.h b/src/lua/ltable.h new file mode 100644 index 0000000..09193cd --- /dev/null +++ b/src/lua/ltable.h @@ -0,0 +1,40 @@ +/* +** $Id: ltable.h,v 2.10 2006/01/10 13:13:06 roberto Exp $ +** 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 gkey(n) (&(n)->i_key.nk) +#define gval(n) (&(n)->i_val) +#define gnext(n) ((n)->i_key.nk.next) + +#define key2tval(n) (&(n)->i_key.tvk) + + +LUAI_FUNC const TValue *luaH_getnum (Table *t, int key); +LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key); +LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); +LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key); +LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); +LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); +LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash); +LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, 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 int luaH_getn (Table *t); + + +#if defined(LUA_DEBUG) +LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); +LUAI_FUNC int luaH_isdummy (Node *n); +#endif + + +#endif diff --git a/src/lua/ltablib.c b/src/lua/ltablib.c new file mode 100644 index 0000000..453b23b --- /dev/null +++ b/src/lua/ltablib.c @@ -0,0 +1,278 @@ +/* +** $Id: ltablib.c,v 1.38 2005/10/23 17:38:15 roberto Exp $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + + +#include + +#define ltablib_c +#define LUA_LIB + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n)) + + +static int foreachi (lua_State *L) { + int i; + int n = aux_getn(L, 1); + luaL_checktype(L, 2, LUA_TFUNCTION); + for (i=1; i <= n; i++) { + lua_pushvalue(L, 2); /* function */ + lua_pushinteger(L, i); /* 1st argument */ + lua_rawgeti(L, 1, i); /* 2nd argument */ + lua_call(L, 2, 1); + if (!lua_isnil(L, -1)) + return 1; + lua_pop(L, 1); /* remove nil result */ + } + return 0; +} + + +static int foreach (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); + luaL_checktype(L, 2, LUA_TFUNCTION); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pushvalue(L, 2); /* function */ + lua_pushvalue(L, -3); /* key */ + lua_pushvalue(L, -3); /* value */ + lua_call(L, 2, 1); + if (!lua_isnil(L, -1)) + return 1; + lua_pop(L, 2); /* remove value and result */ + } + return 0; +} + + +static int maxn (lua_State *L) { + lua_Number max = 0; + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pop(L, 1); /* remove value */ + if (lua_type(L, -1) == LUA_TNUMBER) { + lua_Number v = lua_tonumber(L, -1); + if (v > max) max = v; + } + } + lua_pushnumber(L, max); + return 1; +} + + +static int getn (lua_State *L) { + lua_pushinteger(L, aux_getn(L, 1)); + return 1; +} + + +static int setn (lua_State *L) { + luaL_checktype(L, 1, LUA_TTABLE); +#ifndef luaL_setn + luaL_setn(L, 1, luaL_checkint(L, 2)); +#else + luaL_error(L, LUA_QL("setn") " is obsolete"); +#endif + lua_pushvalue(L, 1); + return 1; +} + + +static int tinsert (lua_State *L) { + int e = aux_getn(L, 1) + 1; /* first empty element */ + int pos; /* where to insert new element */ + switch (lua_gettop(L)) { + case 2: { /* called with only 2 arguments */ + pos = e; /* insert new element at the end */ + break; + } + case 3: { + int i; + pos = luaL_checkint(L, 2); /* 2nd argument is the position */ + if (pos > e) e = pos; /* `grow' array if necessary */ + for (i = e; i > pos; i--) { /* move up elements */ + lua_rawgeti(L, 1, i-1); + lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ + } + break; + } + default: { + return luaL_error(L, "wrong number of arguments to " LUA_QL("insert")); + } + } + luaL_setn(L, 1, e); /* new size */ + lua_rawseti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int tremove (lua_State *L) { + int e = aux_getn(L, 1); + int pos = luaL_optint(L, 2, e); + if (e == 0) return 0; /* table is `empty' */ + luaL_setn(L, 1, e - 1); /* t.n = n-1 */ + lua_rawgeti(L, 1, pos); /* result = t[pos] */ + for ( ;pos= P */ + while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (i>u) luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* repeat --j until a[j] <= P */ + while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { + if (j + +#define ltm_c +#define LUA_CORE + +#include "lua.h" + +#include "lobject.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "ltm.h" + + + +const char *const luaT_typenames[] = { + "nil", "boolean", "userdata", "number", + "string", "table", "function", "userdata", "thread", + "proto", "upval" +}; + + +void luaT_init (lua_State *L) { + static const char *const luaT_eventname[] = { /* ORDER TM */ + "__index", "__newindex", + "__gc", "__mode", "__eq", + "__add", "__sub", "__mul", "__div", "__mod", + "__pow", "__unm", "__len", "__lt", "__le", + "__concat", "__call" + }; + int i; + for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); + luaS_fix(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_getstr(events, ename); + lua_assert(event <= TM_EQ); + if (ttisnil(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_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); +} + diff --git a/src/lua/ltm.h b/src/lua/ltm.h new file mode 100644 index 0000000..866c796 --- /dev/null +++ b/src/lua/ltm.h @@ -0,0 +1,54 @@ +/* +** $Id: ltm.h,v 2.6 2005/06/06 13:30:25 roberto Exp $ +** Tag methods +** See Copyright Notice in lua.h +*/ + +#ifndef ltm_h +#define ltm_h + + +#include "lobject.h" + + +/* +* WARNING: if you change the order of this enumeration, +* grep "ORDER TM" +*/ +typedef enum { + TM_INDEX, + TM_NEWINDEX, + TM_GC, + TM_MODE, + TM_EQ, /* last tag method with `fast' access */ + TM_ADD, + TM_SUB, + TM_MUL, + TM_DIV, + TM_MOD, + TM_POW, + TM_UNM, + TM_LEN, + TM_LT, + TM_LE, + TM_CONCAT, + TM_CALL, + TM_N /* number of elements in the enum */ +} TMS; + + + +#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) + +LUAI_DATA const char *const luaT_typenames[]; + + +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); + +#endif diff --git a/src/lua/lua.c b/src/lua/lua.c new file mode 100644 index 0000000..6df527d --- /dev/null +++ b/src/lua/lua.c @@ -0,0 +1,377 @@ +/* +** $Id: lua.c,v 1.157 2005/12/29 16:23:32 roberto Exp $ +** Lua stand-alone interpreter +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include +#include + +#define lua_c + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + + +static lua_State *globalL = NULL; + +static const char *progname = LUA_PROGNAME; + + + +static void lstop (lua_State *L, lua_Debug *ar) { + (void)ar; /* unused arg. */ + lua_sethook(L, NULL, 0, 0); + luaL_error(L, "interrupted!"); +} + + +static void laction (int i) { + signal(i, SIG_DFL); /* if another SIGINT happens before lstop, + terminate process (default action) */ + lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); +} + + +static void print_usage (void) { + fprintf(stderr, + "usage: %s [options] [script [args]].\n" + "Available options are:\n" + " -e stat execute string " LUA_QL("stat") "\n" + " -l name require library " LUA_QL("name") "\n" + " -i enter interactive mode after executing " LUA_QL("script") "\n" + " -v show version information\n" + " -- stop handling options\n" + " - execute stdin and stop handling options\n" + , + progname); + fflush(stderr); +} + + +static void l_message (const char *pname, const char *msg) { + if (pname) fprintf(stderr, "%s: ", pname); + fprintf(stderr, "%s\n", msg); + fflush(stderr); +} + + +static int report (lua_State *L, int status) { + if (status && !lua_isnil(L, -1)) { + const char *msg = lua_tostring(L, -1); + if (msg == NULL) msg = "(error object is not a string)"; + l_message(progname, msg); + lua_pop(L, 1); + } + return status; +} + + +static int traceback (lua_State *L) { + lua_getfield(L, LUA_GLOBALSINDEX, "debug"); + if (!lua_istable(L, -1)) { + lua_pop(L, 1); + return 1; + } + lua_getfield(L, -1, "traceback"); + if (!lua_isfunction(L, -1)) { + lua_pop(L, 2); + return 1; + } + lua_pushvalue(L, 1); /* pass error message */ + lua_pushinteger(L, 2); /* skip this function and traceback */ + lua_call(L, 2, 1); /* call debug.traceback */ + return 1; +} + + +static int docall (lua_State *L, int narg, int clear) { + int status; + int base = lua_gettop(L) - narg; /* function index */ + lua_pushcfunction(L, traceback); /* push traceback function */ + lua_insert(L, base); /* put it under chunk and args */ + signal(SIGINT, laction); + status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); + signal(SIGINT, SIG_DFL); + lua_remove(L, base); /* remove traceback function */ + /* force a complete garbage collection in case of errors */ + if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); + return status; +} + + +static void print_version (void) { + l_message(NULL, LUA_VERSION " " LUA_COPYRIGHT); +} + + +static int getargs (lua_State *L, char **argv, int n) { + int narg; + int i; + int argc = 0; + while (argv[argc]) argc++; /* count total number of arguments */ + narg = argc - (n + 1); /* number of arguments to the script */ + luaL_checkstack(L, narg + 3, "too many arguments to script"); + for (i=n+1; i < argc; i++) + lua_pushstring(L, argv[i]); + lua_createtable(L, narg, n + 1); + for (i=0; i < argc; i++) { + lua_pushstring(L, argv[i]); + lua_rawseti(L, -2, i - n); + } + return narg; +} + + +static int dofile (lua_State *L, const char *name) { + int status = luaL_loadfile(L, name) || docall(L, 0, 1); + return report(L, status); +} + + +static int dostring (lua_State *L, const char *s, const char *name) { + int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); + return report(L, status); +} + + +static int dolibrary (lua_State *L, const char *name) { + lua_getglobal(L, "require"); + lua_pushstring(L, name); + return report(L, lua_pcall(L, 1, 0, 0)); +} + + +static const char *get_prompt (lua_State *L, int firstline) { + const char *p; + lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); + p = lua_tostring(L, -1); + if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); + lua_pop(L, 1); /* remove global */ + return p; +} + + +static int incomplete (lua_State *L, int status) { + if (status == LUA_ERRSYNTAX) { + size_t lmsg; + const char *msg = lua_tolstring(L, -1, &lmsg); + const char *tp = msg + lmsg - (sizeof(LUA_QL("")) - 1); + if (strstr(msg, LUA_QL("")) == tp) { + lua_pop(L, 1); + return 1; + } + } + return 0; /* else... */ +} + + +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); + if (lua_readline(L, b, prmt) == 0) + return 0; /* no input */ + l = strlen(b); + if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ + b[l-1] = '\0'; /* remove it */ + if (firstline && b[0] == '=') /* first line starts with `=' ? */ + lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ + else + lua_pushstring(L, b); + lua_freeline(L, b); + return 1; +} + + +static int loadline (lua_State *L) { + int status; + lua_settop(L, 0); + if (!pushline(L, 1)) + return -1; /* no input */ + for (;;) { /* repeat until gets a complete line */ + status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); + if (!incomplete(L, status)) break; /* cannot try to add lines? */ + if (!pushline(L, 0)) /* no more input? */ + return -1; + lua_pushliteral(L, "\n"); /* add a new line... */ + lua_insert(L, -2); /* ...between the two lines */ + lua_concat(L, 3); /* join them */ + } + lua_saveline(L, 1); + lua_remove(L, 1); /* remove line */ + return status; +} + + +static void dotty (lua_State *L) { + int status; + const char *oldprogname = progname; + progname = NULL; + while ((status = loadline(L)) != -1) { + if (status == 0) status = docall(L, 0, 0); + report(L, status); + if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ + lua_getglobal(L, "print"); + lua_insert(L, 1); + if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) + l_message(progname, lua_pushfstring(L, + "error calling " LUA_QL("print") " (%s)", + lua_tostring(L, -1))); + } + } + lua_settop(L, 0); /* clear stack */ + fputs("\n", stdout); + fflush(stdout); + progname = oldprogname; +} + + +static int handle_script (lua_State *L, char **argv, int n) { + int status; + const char *fname; + int narg = getargs(L, argv, n); /* collect arguments */ + lua_setglobal(L, "arg"); + fname = argv[n]; + if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) + fname = NULL; /* stdin */ + status = luaL_loadfile(L, fname); + lua_insert(L, -(narg+1)); + if (status == 0) + status = docall(L, narg, 0); + else + lua_pop(L, narg); + return report(L, status); +} + + +static int collectargs (char **argv, int *pi, int *pv, int *pe) { + int i; + for (i = 1; argv[i] != NULL; i++) { + if (argv[i][0] != '-') /* not an option? */ + return i; + switch (argv[i][1]) { /* option */ + case '-': return (argv[i+1] != NULL ? i+1 : 0); + case '\0': return i; + case 'i': *pi = 1; /* go through */ + case 'v': *pv = 1; break; + case 'e': *pe = 1; /* go through */ + case 'l': + if (argv[i][2] == '\0') { + i++; + if (argv[i] == NULL) return -1; + } + break; + default: return -1; /* invalid option */ + } + } + return 0; +} + + +static int runargs (lua_State *L, char **argv, int n) { + int i; + for (i = 1; i < n; i++) { + if (argv[i] == NULL) continue; + lua_assert(argv[i][0] == '-'); + switch (argv[i][1]) { /* option */ + case 'e': { + const char *chunk = argv[i] + 2; + if (*chunk == '\0') chunk = argv[++i]; + lua_assert(chunk != NULL); + if (dostring(L, chunk, "=(command line)") != 0) + return 1; + break; + } + case 'l': { + const char *filename = argv[i] + 2; + if (*filename == '\0') filename = argv[++i]; + lua_assert(filename != NULL); + if (dolibrary(L, filename)) + return 1; /* stop if file fails */ + break; + } + default: break; + } + } + return 0; +} + + +static int handle_luainit (lua_State *L) { + const char *init = getenv("LUA_INIT"); + if (init == NULL) return 0; /* status OK */ + else if (init[0] == '@') + return dofile(L, init+1); + else + return dostring(L, init, "=LUA_INIT"); +} + + +struct Smain { + int argc; + char **argv; + int status; +}; + + +static int pmain (lua_State *L) { + struct Smain *s = (struct Smain *)lua_touserdata(L, 1); + char **argv = s->argv; + int script; + int has_i = 0, has_v = 0, has_e = 0; + globalL = L; + if (argv[0] && argv[0][0]) progname = argv[0]; + lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ + luaL_openlibs(L); /* open libraries */ + lua_gc(L, LUA_GCRESTART, 0); + s->status = handle_luainit(L); + if (s->status != 0) return 0; + script = collectargs(argv, &has_i, &has_v, &has_e); + if (script < 0) { /* invalid args? */ + print_usage(); + s->status = 1; + return 0; + } + if (has_v) print_version(); + s->status = runargs(L, argv, (script > 0) ? script : s->argc); + if (s->status != 0) return 0; + if (script) + s->status = handle_script(L, argv, script); + if (s->status != 0) return 0; + if (has_i) + dotty(L); + else if (script == 0 && !has_e && !has_v) { + if (lua_stdin_is_tty()) { + print_version(); + dotty(L); + } + else dofile(L, NULL); /* executes stdin as a file */ + } + return 0; +} + + +int main (int argc, char **argv) { + int status; + struct Smain s; + lua_State *L = lua_open(); /* create state */ + if (L == NULL) { + l_message(argv[0], "cannot create state: not enough memory"); + return EXIT_FAILURE; + } + s.argc = argc; + s.argv = argv; + status = lua_cpcall(L, &pmain, &s); + report(L, status); + lua_close(L); + return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; +} + diff --git a/src/lua/lua.h b/src/lua/lua.h new file mode 100644 index 0000000..881f834 --- /dev/null +++ b/src/lua/lua.h @@ -0,0 +1,384 @@ +/* +** $Id: lua.h,v 1.216 2006/01/10 12:50:13 roberto Exp $ +** Lua - An Extensible Extension 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 "Lua 5.1" +#define LUA_VERSION_NUM 501 +#define LUA_COPYRIGHT "Copyright (C) 1994-2006 Lua.org, PUC-Rio" +#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" + + +/* mark for precompiled code (`Lua') */ +#define LUA_SIGNATURE "\033Lua" + +/* option for multiple returns in `lua_pcall' and `lua_call' */ +#define LUA_MULTRET (-1) + + +/* +** pseudo-indices +*/ +#define LUA_REGISTRYINDEX (-10000) +#define LUA_ENVIRONINDEX (-10001) +#define LUA_GLOBALSINDEX (-10002) +#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) + + +/* thread status; 0 is OK */ +#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; + +typedef int (*lua_CFunction) (lua_State *L); + + +/* +** 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); + + +/* +** prototype for memory-allocation functions +*/ +typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); + + +/* +** 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 + + + +/* minimum Lua stack available to a C function */ +#define LUA_MINSTACK 20 + + +/* +** generic extra include file +*/ +#if defined(LUA_USER_H) +#include LUA_USER_H +#endif + + +/* type of numbers in Lua */ +typedef LUA_NUMBER lua_Number; + + +/* type for integer functions */ +typedef LUA_INTEGER lua_Integer; + + + +/* +** 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 lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); + + +/* +** basic stack manipulation +*/ +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_remove) (lua_State *L, int idx); +LUA_API void (lua_insert) (lua_State *L, int idx); +LUA_API void (lua_replace) (lua_State *L, int idx); +LUA_API int (lua_checkstack) (lua_State *L, int sz); + +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_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 int (lua_equal) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); +LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); + +LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); +LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); +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 size_t (lua_objlen) (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); + + +/* +** 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 void (lua_pushlstring) (lua_State *L, const char *s, size_t l); +LUA_API void (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 void (lua_gettable) (lua_State *L, int idx); +LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); +LUA_API void (lua_rawget) (lua_State *L, int idx); +LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); +LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); +LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); +LUA_API int (lua_getmetatable) (lua_State *L, int objindex); +LUA_API void (lua_getfenv) (lua_State *L, int idx); + + +/* +** set functions (stack -> Lua) +*/ +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_rawset) (lua_State *L, int idx); +LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); +LUA_API int (lua_setmetatable) (lua_State *L, int objindex); +LUA_API int (lua_setfenv) (lua_State *L, int idx); + + +/* +** `load' and `call' functions (load and run Lua code) +*/ +LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); +LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); +LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); +LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, + const char *chunkname); + +LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); + + +/* +** coroutine functions +*/ +LUA_API int (lua_yield) (lua_State *L, int nresults); +LUA_API int (lua_resume) (lua_State *L, int narg); +LUA_API int (lua_status) (lua_State *L); + +/* +** 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 + +LUA_API int (lua_gc) (lua_State *L, int what, int data); + + +/* +** 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 lua_Alloc (lua_getallocf) (lua_State *L, void **ud); +LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); + + + +/* +** =============================================================== +** some useful macros +** =============================================================== +*/ + +#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_strlen(L,i) lua_objlen(L, (i)) + +#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_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) + +#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) +#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) + +#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) + + + +/* +** compatibility macros and functions +*/ + +#define lua_open() luaL_newstate() + +#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) + +#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) + +#define lua_Chunkreader lua_Reader +#define lua_Chunkwriter lua_Writer + + + +/* +** {====================================================================== +** Debug API +** ======================================================================= +*/ + + +/* +** Event codes +*/ +#define LUA_HOOKCALL 0 +#define LUA_HOOKRET 1 +#define LUA_HOOKLINE 2 +#define LUA_HOOKCOUNT 3 +#define LUA_HOOKTAILRET 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) + +typedef struct lua_Debug lua_Debug; /* activation record */ + + +/* Functions to be called by the debuger in specific events */ +typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); + + +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 int 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); + + +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) */ + int currentline; /* (l) */ + int nups; /* (u) number of upvalues */ + int linedefined; /* (S) */ + int lastlinedefined; /* (S) */ + char short_src[LUA_IDSIZE]; /* (S) */ + /* private part */ + int i_ci; /* active function */ +}; + +/* }====================================================================== */ + + +/****************************************************************************** +* Copyright (C) 1994-2006 Lua.org, PUC-Rio. 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. +******************************************************************************/ + + +#endif diff --git a/src/lua/luac.c b/src/lua/luac.c new file mode 100644 index 0000000..2dd76b7 --- /dev/null +++ b/src/lua/luac.c @@ -0,0 +1,196 @@ +/* +** $Id: luac.c,v 1.52 2005/11/11 14:03:13 lhf Exp $ +** Lua compiler (saves bytecodes to files; also list bytecodes) +** See Copyright Notice in lua.h +*/ + +#include +#include +#include +#include + +#define luac_c +#define LUA_CORE + +#include "lua.h" +#include "lauxlib.h" + +#include "ldo.h" +#include "lfunc.h" +#include "lmem.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lstring.h" +#include "lundump.h" + +#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 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 " LUA_QS "\n",progname,message); + else + fprintf(stderr,"%s: %s\n",progname,message); + fprintf(stderr, + "usage: %s [options] [filenames].\n" + "Available options are:\n" + " - process stdin\n" + " -l list\n" + " -o name output to file " LUA_QL("name") " (default is \"%s\")\n" + " -p parse only\n" + " -s strip debug information\n" + " -v show version information\n" + " -- stop handling options\n", + progname,Output); + exit(EXIT_FAILURE); +} + +#define IS(s) (strcmp(argv[i],s)==0) + +static int doargs(int argc, char* argv[]) +{ + int i; + if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; + for (i=1; itop+(i))->l.p) + +static Proto* combine(lua_State* L, int n) +{ + if (n==1) + return toproto(L,-1); + else + { + int i,pc; + Proto* f=luaF_newproto(L); + setptvalue2s(L,L->top,f); incr_top(L); + f->source=luaS_newliteral(L,"=(" PROGNAME ")"); + f->maxstacksize=1; + pc=2*n+1; + f->code=luaM_newvector(L,pc,Instruction); + f->sizecode=pc; + f->p=luaM_newvector(L,n,Proto*); + f->sizep=n; + pc=0; + for (i=0; ip[i]=toproto(L,i-n-1); + f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,i); + f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1); + } + f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,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); +} + +struct Smain { + int argc; + char** argv; +}; + +static int pmain(lua_State* L) +{ + struct Smain* s = (struct Smain*)lua_touserdata(L, 1); + int argc=s->argc; + char** argv=s->argv; + Proto* f; + int i; + 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; + struct Smain s; + int i=doargs(argc,argv); + argc-=i; argv+=i; + if (argc<=0) usage("no input files given"); + L=lua_open(); + if (L==NULL) fatal("not enough memory for state"); + s.argc=argc; + s.argv=argv; + if (lua_cpcall(L,pmain,&s)!=0) fatal(lua_tostring(L,-1)); + lua_close(L); + return EXIT_SUCCESS; +} diff --git a/src/lua/luaconf.h b/src/lua/luaconf.h new file mode 100644 index 0000000..97a3e30 --- /dev/null +++ b/src/lua/luaconf.h @@ -0,0 +1,736 @@ +/* +** $Id: luaconf.h,v 1.81 2006/02/10 17:44:06 roberto Exp $ +** Configuration file for Lua +** See Copyright Notice in lua.h +*/ + + +#ifndef lconfig_h +#define lconfig_h + +#include +#include + + +/* +** ================================================================== +** Search for "@@" to find all configurable definitions. +** =================================================================== +*/ + + +/* +@@ LUA_ANSI controls the use of non-ansi features. +** CHANGE it (define it) if you want Lua to avoid the use of any +** non-ansi feature or library. +*/ +#if defined(__STRICT_ANSI__) +#define LUA_ANSI +#endif + + +#if !defined(LUA_ANSI) && defined(_WIN32) +#define LUA_WIN +#endif + +#if defined(LUA_USE_LINUX) +#define LUA_USE_POSIX +#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ +#define LUA_USE_READLINE /* needs some extra libraries */ +#endif + +#if defined(LUA_USE_MACOSX) +#define LUA_USE_POSIX +#define LUA_DL_DYLD /* does not need extra library */ +#endif + + + +/* +@@ LUA_USE_POSIX includes all functionallity listed as X/Open System +@* Interfaces Extension (XSI). +** CHANGE it (define it) if your system is XSI compatible. +*/ +#if defined(LUA_USE_POSIX) +#define LUA_USE_MKSTEMP +#define LUA_USE_ISATTY +#define LUA_USE_POPEN +#define LUA_USE_ULONGJMP +#endif + + +/* +@@ 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. +*/ +#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_PATH_DEFAULT \ + ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" +#define LUA_CPATH_DEFAULT \ + ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" + +#else +#define LUA_ROOT "/usr/local/" +#define LUA_LDIR LUA_ROOT "share/lua/5.1/" +#define LUA_CDIR LUA_ROOT "lib/lua/5.1/" +#define LUA_PATH_DEFAULT \ + "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua" +#define LUA_CPATH_DEFAULT \ + "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so" +#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(_WIN32) +#define LUA_DIRSEP "\\" +#else +#define LUA_DIRSEP "/" +#endif + + +/* +@@ LUA_PATHSEP is the character that separates templates in a path. +@@ LUA_PATH_MARK is the string that marks the substitution points in a +@* template. +@@ LUA_EXECDIR in a Windows path is replaced by the executable's +@* directory. +@@ LUA_IGMARK is a mark to ignore all before it when bulding the +@* luaopen_ function name. +** CHANGE them if for some reason your system cannot use those +** characters. (E.g., if one of those characters is a common character +** in file/directory names.) Probably you do not need to change them. +*/ +#define LUA_PATHSEP ";" +#define LUA_PATH_MARK "?" +#define LUA_EXECDIR "!" +#define LUA_IGMARK "-" + + +/* +@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. +** CHANGE that if ptrdiff_t is not adequate on your machine. (On most +** machines, ptrdiff_t gives a good choice between int or long.) +*/ +#define LUA_INTEGER ptrdiff_t + + +/* +@@ LUA_API is a mark for all core API functions. +@@ LUALIB_API is a mark for all standard library 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 + + +/* +@@ LUAI_FUNC is a mark for all extern functions that are not to be +@* exported to outside modules. +@@ LUAI_DATA is a mark for all extern (const) variables that are not to +@* be exported to outside modules. +** 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. +*/ +#if defined(luaall_c) +#define LUAI_FUNC static +#define LUAI_DATA /* empty */ + +#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ + defined(__ELF__) +#define LUAI_FUNC __attribute__((visibility("hidden"))) extern +#define LUAI_DATA LUAI_FUNC + +#else +#define LUAI_FUNC extern +#define LUAI_DATA extern +#endif + + + +/* +@@ LUA_QL describes how error messages quote program elements. +** CHANGE it if you want a different appearance. +*/ +#define LUA_QL(x) "'" x "'" +#define LUA_QS LUA_QL("%s") + + +/* +@@ 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 + + +/* +** {================================================================== +** Stand-alone configuration +** =================================================================== +*/ + +#if defined(lua_c) || defined(luaall_c) + +/* +@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that +@* is, whether we're running lua interactively). +** CHANGE it if you have a better definition for non-POSIX/non-Windows +** systems. +*/ +#if defined(LUA_USE_ISATTY) +#include +#define lua_stdin_is_tty() isatty(0) +#elif defined(LUA_WIN) +#include +#include +#define lua_stdin_is_tty() _isatty(_fileno(stdin)) +#else +#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ +#endif + + +/* +@@ LUA_PROMPT is the default prompt used by stand-alone Lua. +@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. +** CHANGE them if you want different prompts. (You can also change the +** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) +*/ +#define LUA_PROMPT "> " +#define LUA_PROMPT2 ">> " + + +/* +@@ LUA_PROGNAME is the default name for the stand-alone Lua program. +** CHANGE it if your stand-alone interpreter has a different name and +** your system is not able to detect that name automatically. +*/ +#define LUA_PROGNAME "lua" + + +/* +@@ LUA_MAXINPUT is the maximum length for an input line in the +@* stand-alone interpreter. +** CHANGE it if you need longer lines. +*/ +#define LUA_MAXINPUT 512 + + +/* +@@ 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. +** CHANGE them if you want to improve this functionality (e.g., by using +** GNU readline and history facilities). +*/ +#if defined(LUA_USE_READLINE) +#include +#include +#include +#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) +#define lua_saveline(L,idx) \ + if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ + add_history(lua_tostring(L, idx)); /* add it to history */ +#define lua_freeline(L,b) ((void)L, free(b)) +#else +#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,idx) { (void)L; (void)idx; } +#define lua_freeline(L,b) { (void)L; (void)b; } +#endif + +#endif + +/* }================================================================== */ + + +/* +@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles +@* as a percentage. +** CHANGE it if you want the GC to run faster or slower (higher values +** mean larger pauses which mean slower collection.) You can also change +** this value dynamically. +*/ +#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ + + +/* +@@ LUAI_GCMUL defines the default speed of garbage collection relative to +@* memory allocation as a percentage. +** CHANGE it if you want to change the granularity of the garbage +** collection. (Higher values mean coarser collections. 0 represents +** infinity, where each step performs a full collection.) You can also +** change this value dynamically. +*/ +#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ + + + +/* +@@ LUA_COMPAT_GETN controls compatibility with old getn behavior. +** CHANGE it (define it) if you want exact compatibility with the +** behavior of setn/getn in Lua 5.0. +*/ +#undef LUA_COMPAT_GETN + +/* +@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. +** CHANGE it to undefined as soon as you do not need a global 'loadlib' +** function (the function is still available as 'package.loadlib'). +*/ +#undef LUA_COMPAT_LOADLIB + +/* +@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature. +** CHANGE it to undefined as soon as your programs use only '...' to +** access vararg parameters (instead of the old 'arg' table). +*/ +#define LUA_COMPAT_VARARG + +/* +@@ LUA_COMPAT_MOD controls compatibility with old math.mod function. +** CHANGE it to undefined as soon as your programs use 'math.fmod' or +** the new '%' operator instead of 'math.mod'. +*/ +#define LUA_COMPAT_MOD + +/* +@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting +@* facility. +** CHANGE it to 2 if you want the old behaviour, or undefine it to turn +** off the advisory error when nesting [[...]]. +*/ +#define LUA_COMPAT_LSTR 1 + +/* +@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. +** CHANGE it to undefined as soon as you rename 'string.gfind' to +** 'string.gmatch'. +*/ +#define LUA_COMPAT_GFIND + +/* +@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' +@* behavior. +** CHANGE it to undefined as soon as you replace to 'luaL_registry' +** your uses of 'luaL_openlib' +*/ +#define LUA_COMPAT_OPENLIB + + + +/* +@@ luai_apicheck is the assert macro used by the Lua-C API. +** CHANGE luai_apicheck if you want Lua to perform some checks in the +** parameters it gets from API calls. This may slow down the interpreter +** a bit, but may be quite useful when debugging C code that interfaces +** with Lua. A useful redefinition is to use assert.h. +*/ +#if defined(LUA_USE_APICHECK) +#include +#define luai_apicheck(L,o) { (void)L; assert(o); } +#else +#define luai_apicheck(L,o) { (void)L; } +#endif + + +/* +@@ LUAI_BITSINT defines the number of bits in an int. +** CHANGE here if Lua cannot automatically detect the number of bits of +** your machine. Probably you do not need to change this. +*/ +/* avoid overflows in comparison */ +#if INT_MAX-20 < 32760 +#define LUAI_BITSINT 16 +#elif INT_MAX > 2147483640L +/* int has at least 32 bits */ +#define LUAI_BITSINT 32 +#else +#error "you must define LUA_BITSINT with number of bits in an integer" +#endif + + +/* +@@ LUAI_UINT32 is an unsigned integer with at least 32 bits. +@@ LUAI_INT32 is an signed integer with at least 32 bits. +@@ LUAI_UMEM is an unsigned integer big enough to count the total +@* memory used by Lua. +@@ LUAI_MEM is a signed integer big enough to count the total memory +@* used by Lua. +** CHANGE here if for some weird reason the default definitions are not +** good enough for your machine. (The definitions in the 'else' +** part always works, but may waste space on machines with 64-bit +** longs.) Probably you do not need to change this. +*/ +#if LUAI_BITSINT >= 32 +#define LUAI_UINT32 unsigned int +#define LUAI_INT32 int +#define LUAI_MAXINT32 INT_MAX +#define LUAI_UMEM size_t +#define LUAI_MEM ptrdiff_t +#else +/* 16-bit ints */ +#define LUAI_UINT32 unsigned long +#define LUAI_INT32 long +#define LUAI_MAXINT32 LONG_MAX +#define LUAI_UMEM unsigned long +#define LUAI_MEM long +#endif + + +/* +@@ LUAI_MAXCALLS limits the number of nested calls. +** CHANGE it if you need really deep recursive calls. This limit is +** arbitrary; its only purpose is to stop infinite recursion before +** exhausting memory. +*/ +#define LUAI_MAXCALLS 20000 + + +/* +@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function +@* can use. +** CHANGE it if you need lots of (Lua) stack space for your C +** functions. This limit is arbitrary; its only purpose is to stop C +** functions to consume unlimited stack space. +*/ +#define LUAI_MAXCSTACK 2048 + + + +/* +** {================================================================== +** CHANGE (to smaller values) the following definitions if your system +** has a small C stack. (Or you may want to change them to larger +** values if your system has a large C stack and these limits are +** too rigid for you.) Some of these constants control the size of +** stack-allocated arrays used by the compiler or the interpreter, while +** others limit the maximum number of recursive calls that the compiler +** or the interpreter can perform. Values too large may cause a C stack +** overflow for some forms of deep constructs. +** =================================================================== +*/ + + +/* +@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and +@* syntactical nested non-terminals in a program. +*/ +#define LUAI_MAXCCALLS 200 + + +/* +@@ LUAI_MAXVARS is the maximum number of local variables per function +@* (must be smaller than 250). +*/ +#define LUAI_MAXVARS 200 + + +/* +@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function +@* (must be smaller than 250). +*/ +#define LUAI_MAXUPVALUES 60 + + +/* +@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. +*/ +#define LUAL_BUFFERSIZE BUFSIZ + +/* }================================================================== */ + + + + +/* +** {================================================================== +@@ LUA_NUMBER is the type of numbers in Lua. +** CHANGE the following definitions only if you want to build Lua +** with a number type different from double. You may also need to +** change lua_number2int & lua_number2integer. +** =================================================================== +*/ + +#define LUA_NUMBER_DOUBLE +#define LUA_NUMBER double + +/* +@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' +@* over a number. +*/ +#define LUAI_UACNUMBER double + + +/* +@@ LUA_NUMBER_SCAN is the format for reading numbers. +@@ LUA_NUMBER_FMT is the format for writing numbers. +@@ lua_number2str converts a number to a string. +@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. +@@ lua_str2number converts a string to a number. +*/ +#define LUA_NUMBER_SCAN "%lf" +#define LUA_NUMBER_FMT "%.14g" +#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) +#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ +#define lua_str2number(s,p) strtod((s), (p)) + + +/* +@@ The luai_num* macros define the primitive operations over numbers. +*/ +#if defined(LUA_CORE) +#include +#define luai_numadd(a,b) ((a)+(b)) +#define luai_numsub(a,b) ((a)-(b)) +#define luai_nummul(a,b) ((a)*(b)) +#define luai_numdiv(a,b) ((a)/(b)) +#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) +#define luai_numpow(a,b) (pow(a,b)) +#define luai_numunm(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_numisnan(a) (!luai_numeq((a), (a))) +#endif + + +/* +@@ lua_number2int is a macro to convert lua_Number to int. +@@ lua_number2integer is a macro to convert lua_Number to lua_Integer. +** CHANGE them if you know a faster way to convert a lua_Number to +** int (with any rounding method and without throwing errors) in your +** system. In Pentium machines, a naive typecast from double to int +** in C is extremely slow, so any alternative is worth trying. +*/ + +/* On a Pentium, resort to a trick */ +#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ + (defined(__i386) || defined (_M_IX86) || defined(__i386__)) +union luai_Cast { double l_d; long l_l; }; +#define lua_number2int(i,d) \ + { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } +#define lua_number2integer(i,n) lua_number2int(i, n) + +/* this option always works, but may be slow */ +#else +#define lua_number2int(i,d) ((i)=(int)(d)) +#define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) + +#endif + +/* }================================================================== */ + + +/* +@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. +** CHANGE it if your system requires alignments larger than double. (For +** instance, if your system supports long doubles and they must be +** aligned in 16-byte boundaries, then you should add long double in the +** union.) Probably you do not need to change this. +*/ +#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } + + +/* +@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. +** CHANGE them if you prefer to use longjmp/setjmp even with C++ +** or if want/don't to use _longjmp/_setjmp instead of regular +** longjmp/setjmp. 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(__cplusplus) +/* 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_ULONGJMP) +/* in Unix, 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 +/* default 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 + + +/* +@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern +@* can do during pattern-matching. +** CHANGE it if you need more captures. This limit is arbitrary. +*/ +#define LUA_MAXCAPTURES 32 + + +/* +@@ lua_tmpnam is the function that the OS library uses to create a +@* temporary name. +@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. +** CHANGE them if you have an alternative to tmpnam (which is considered +** insecure) or if you want the original tmpnam anyway. By default, Lua +** uses tmpnam except when POSIX is available, where it uses mkstemp. +*/ +#if defined(loslib_c) || defined(luaall_c) + +#if defined(LUA_USE_MKSTEMP) +#include +#define LUA_TMPNAMBUFSIZE 32 +#define lua_tmpnam(b,e) { \ + strcpy(b, "/tmp/lua_XXXXXX"); \ + e = mkstemp(b); \ + if (e != -1) close(e); \ + e = (e == -1); } + +#else +#define LUA_TMPNAMBUFSIZE L_tmpnam +#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } +#endif + +#endif + + +/* +@@ lua_popen spawns a new process connected to the current one through +@* the file streams. +** CHANGE it if you have a way to implement it in your system. +*/ +#if defined(LUA_USE_POPEN) + +#define lua_popen(L,c,m) ((void)L, popen(c,m)) +#define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) + +#elif defined(LUA_WIN) + +#define lua_popen(L,c,m) ((void)L, _popen(c,m)) +#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) + +#else + +#define lua_popen(L,c,m) ((void)((void)c, m), \ + luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) +#define lua_pclose(L,file) ((void)((void)L, file), 0) + +#endif + +/* +@@ LUA_DL_* define which dynamic-library system Lua should use. +** CHANGE here if Lua has problems choosing the appropriate +** dynamic-library system for your platform (either Windows' DLL, Mac's +** dyld, or Unix's dlopen). If your system is some kind of Unix, there +** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for +** it. To use dlopen you also need to adapt the src/Makefile (probably +** adding -ldl to the linker options), so Lua does not select it +** automatically. (When you change the makefile to add -ldl, you must +** also add -DLUA_USE_DLOPEN.) +** If you do not want any kind of dynamic library, undefine all these +** options. +** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD. +*/ +#if defined(LUA_USE_DLOPEN) +#define LUA_DL_DLOPEN +#endif + +#if defined(LUA_WIN) +#define LUA_DL_DLL +#endif + + +/* +@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State +@* (the data goes just *before* the lua_State pointer). +** CHANGE (define) this if you really need that. This value must be +** a multiple of the maximum alignment required for your machine. +*/ +#define LUAI_EXTRASPACE 0 + + +/* +@@ luai_userstate* allow user-specific actions on threads. +** CHANGE them if you defined LUAI_EXTRASPACE and need to do something +** extra when a thread is created/deleted/resumed/yielded. +*/ +#define luai_userstateopen(L) ((void)L) +#define luai_userstateclose(L) ((void)L) +#define luai_userstatethread(L,L1) ((void)L) +#define luai_userstatefree(L) ((void)L) +#define luai_userstateresume(L,n) ((void)L) +#define luai_userstateyield(L,n) ((void)L) + + +/* +@@ LUA_INTFRMLEN is the length modifier for integer conversions +@* in 'string.format'. +@@ LUA_INTFRM_T is the integer type correspoding to the previous length +@* modifier. +** CHANGE them if your system supports long long or does not support long. +*/ + +#if defined(LUA_USELONGLONG) + +#define LUA_INTFRMLEN "ll" +#define LUA_INTFRM_T long long + +#else + +#define LUA_INTFRMLEN "l" +#define LUA_INTFRM_T long + +#endif + + + +/* =================================================================== */ + +/* +** Local configuration. You can use this space to add your redefinitions +** without modifying the main part of the file. +*/ + + + +#endif + diff --git a/src/lua/lualib.h b/src/lua/lualib.h new file mode 100644 index 0000000..0c76232 --- /dev/null +++ b/src/lua/lualib.h @@ -0,0 +1,53 @@ +/* +** $Id: lualib.h,v 1.36 2005/12/27 17:12:00 roberto Exp $ +** Lua standard libraries +** See Copyright Notice in lua.h +*/ + + +#ifndef lualib_h +#define lualib_h + +#include "lua.h" + + +/* Key to file-handle type */ +#define LUA_FILEHANDLE "FILE*" + + +#define LUA_COLIBNAME "coroutine" +LUALIB_API int (luaopen_base) (lua_State *L); + +#define LUA_TABLIBNAME "table" +LUALIB_API int (luaopen_table) (lua_State *L); + +#define LUA_IOLIBNAME "io" +LUALIB_API int (luaopen_io) (lua_State *L); + +#define LUA_OSLIBNAME "os" +LUALIB_API int (luaopen_os) (lua_State *L); + +#define LUA_STRLIBNAME "string" +LUALIB_API int (luaopen_string) (lua_State *L); + +#define LUA_MATHLIBNAME "math" +LUALIB_API int (luaopen_math) (lua_State *L); + +#define LUA_DBLIBNAME "debug" +LUALIB_API int (luaopen_debug) (lua_State *L); + +#define LUA_LOADLIBNAME "package" +LUALIB_API int (luaopen_package) (lua_State *L); + + +/* open all previous libraries */ +LUALIB_API void (luaL_openlibs) (lua_State *L); + + + +#ifndef lua_assert +#define lua_assert(x) ((void)0) +#endif + + +#endif diff --git a/src/lua/lundump.c b/src/lua/lundump.c new file mode 100644 index 0000000..7fc635e --- /dev/null +++ b/src/lua/lundump.c @@ -0,0 +1,223 @@ +/* +** $Id: lundump.c,v 1.60 2006/02/16 15:53:49 lhf Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#include + +#define lundump_c +#define LUA_CORE + +#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" + +typedef struct { + lua_State* L; + ZIO* Z; + Mbuffer* b; + const char* name; +} LoadState; + +#ifdef LUAC_TRUST_BINARIES +#define IF(c,s) +#else +#define IF(c,s) if (c) error(S,s) + +static void error(LoadState* S, const char* why) +{ + luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why); + luaD_throw(S->L,LUA_ERRSYNTAX); +} +#endif + +#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size)) +#define LoadByte(S) (lu_byte)LoadChar(S) +#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x)) +#define LoadVector(S,b,n,size) LoadMem(S,b,n,size) + +static void LoadBlock(LoadState* S, void* b, size_t size) +{ + size_t r=luaZ_read(S->Z,b,size); + IF (r!=0, "unexpected end"); +} + +static int LoadChar(LoadState* S) +{ + char x; + LoadVar(S,x); + return x; +} + +static int LoadInt(LoadState* S) +{ + int x; + LoadVar(S,x); + IF (x<0, "bad integer"); + return x; +} + +static lua_Number LoadNumber(LoadState* S) +{ + lua_Number x; + LoadVar(S,x); + return x; +} + +static TString* LoadString(LoadState* S) +{ + size_t size; + LoadVar(S,size); + if (size==0) + return NULL; + else + { + char* s=luaZ_openspace(S->L,S->b,size); + LoadBlock(S,s,size); + return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ + } +} + +static void LoadCode(LoadState* S, Proto* f) +{ + int n=LoadInt(S); + f->code=luaM_newvector(S->L,n,Instruction); + f->sizecode=n; + LoadVector(S,f->code,n,sizeof(Instruction)); +} + +static Proto* LoadFunction(LoadState* S, TString* p); + +static void LoadConstants(LoadState* S, Proto* f) +{ + int i,n; + n=LoadInt(S); + f->k=luaM_newvector(S->L,n,TValue); + f->sizek=n; + for (i=0; ik[i]); + for (i=0; ik[i]; + int t=LoadChar(S); + switch (t) + { + case LUA_TNIL: + setnilvalue(o); + break; + case LUA_TBOOLEAN: + setbvalue(o,LoadChar(S)); + break; + case LUA_TNUMBER: + setnvalue(o,LoadNumber(S)); + break; + case LUA_TSTRING: + setsvalue2n(S->L,o,LoadString(S)); + break; + default: + IF (1, "bad constant"); + break; + } + } + n=LoadInt(S); + f->p=luaM_newvector(S->L,n,Proto*); + f->sizep=n; + for (i=0; ip[i]=NULL; + for (i=0; ip[i]=LoadFunction(S,f->source); +} + +static void LoadDebug(LoadState* S, Proto* f) +{ + int i,n; + n=LoadInt(S); + f->lineinfo=luaM_newvector(S->L,n,int); + f->sizelineinfo=n; + LoadVector(S,f->lineinfo,n,sizeof(int)); + n=LoadInt(S); + f->locvars=luaM_newvector(S->L,n,LocVar); + f->sizelocvars=n; + for (i=0; ilocvars[i].varname=NULL; + for (i=0; ilocvars[i].varname=LoadString(S); + f->locvars[i].startpc=LoadInt(S); + f->locvars[i].endpc=LoadInt(S); + } + n=LoadInt(S); + f->upvalues=luaM_newvector(S->L,n,TString*); + f->sizeupvalues=n; + for (i=0; iupvalues[i]=NULL; + for (i=0; iupvalues[i]=LoadString(S); +} + +static Proto* LoadFunction(LoadState* S, TString* p) +{ + Proto* f=luaF_newproto(S->L); + setptvalue2s(S->L,S->L->top,f); incr_top(S->L); + f->source=LoadString(S); if (f->source==NULL) f->source=p; + f->linedefined=LoadInt(S); + f->lastlinedefined=LoadInt(S); + f->nups=LoadByte(S); + f->numparams=LoadByte(S); + f->is_vararg=LoadByte(S); + f->maxstacksize=LoadByte(S); + LoadCode(S,f); + LoadConstants(S,f); + LoadDebug(S,f); + IF (!luaG_checkcode(f), "bad code"); + S->L->top--; + return f; +} + +static void LoadHeader(LoadState* S) +{ + char h[LUAC_HEADERSIZE]; + char s[LUAC_HEADERSIZE]; + luaU_header(h); + LoadBlock(S,s,LUAC_HEADERSIZE); + IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header"); +} + +/* +** load precompiled chunk +*/ +Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name) +{ + LoadState S; + 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; + S.b=buff; + LoadHeader(&S); + return LoadFunction(&S,luaS_newliteral(L,"=?")); +} + +/* +* make header +*/ +void luaU_header (char* h) +{ + int x=1; + memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1); + h+=sizeof(LUA_SIGNATURE)-1; + *h++=(char)LUAC_VERSION; + *h++=(char)LUAC_FORMAT; + *h++=(char)*(char*)&x; /* endianness */ + *h++=(char)sizeof(int); + *h++=(char)sizeof(size_t); + *h++=(char)sizeof(Instruction); + *h++=(char)sizeof(lua_Number); + *h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */ +} diff --git a/src/lua/lundump.h b/src/lua/lundump.h new file mode 100644 index 0000000..58cca5d --- /dev/null +++ b/src/lua/lundump.h @@ -0,0 +1,36 @@ +/* +** $Id: lundump.h,v 1.40 2005/11/11 14:03:13 lhf Exp $ +** load precompiled Lua chunks +** See Copyright Notice in lua.h +*/ + +#ifndef lundump_h +#define lundump_h + +#include "lobject.h" +#include "lzio.h" + +/* load one chunk; from lundump.c */ +LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); + +/* make header; from lundump.c */ +LUAI_FUNC void luaU_header (char* h); + +/* dump one chunk; from ldump.c */ +LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); + +#ifdef luac_c +/* print one chunk; from print.c */ +LUAI_FUNC void luaU_print (const Proto* f, int full); +#endif + +/* for header of binary files -- this is Lua 5.1 */ +#define LUAC_VERSION 0x51 + +/* for header of binary files -- this is the official format */ +#define LUAC_FORMAT 0 + +/* size of header of binary files */ +#define LUAC_HEADERSIZE 12 + +#endif diff --git a/src/lua/lvm.c b/src/lua/lvm.c new file mode 100644 index 0000000..6f4c029 --- /dev/null +++ b/src/lua/lvm.c @@ -0,0 +1,762 @@ +/* +** $Id: lvm.c,v 2.62 2006/01/23 19:51:43 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define lvm_c +#define LUA_CORE + +#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" + + + +/* limit for table tag-method chains (to avoid loops) */ +#define MAXTAGLOOP 100 + + +const TValue *luaV_tonumber (const TValue *obj, TValue *n) { + lua_Number num; + if (ttisnumber(obj)) return obj; + if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) { + setnvalue(n, num); + return n; + } + else + return NULL; +} + + +int luaV_tostring (lua_State *L, StkId obj) { + if (!ttisnumber(obj)) + return 0; + else { + char s[LUAI_MAXNUMBER2STR]; + lua_Number n = nvalue(obj); + lua_number2str(s, n); + setsvalue2s(L, obj, luaS_new(L, s)); + return 1; + } +} + + +static void traceexec (lua_State *L, const Instruction *pc) { + lu_byte mask = L->hookmask; + const Instruction *oldpc = L->savedpc; + L->savedpc = pc; + if (mask > LUA_MASKLINE) { /* instruction-hook set? */ + if (L->hookcount == 0) { + resethookcount(L); + luaD_callhook(L, LUA_HOOKCOUNT, -1); + } + } + if (mask & LUA_MASKLINE) { + Proto *p = ci_func(L->ci)->l.p; + int npc = pcRel(pc, p); + int newline = getline(p, npc); + /* call linehook when enter a new function, when jump back (loop), + or when enter a new line */ + if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p))) + luaD_callhook(L, LUA_HOOKLINE, newline); + } +} + + +static void callTMres (lua_State *L, StkId res, const TValue *f, + const TValue *p1, const TValue *p2) { + ptrdiff_t result = savestack(L, res); + setobj2s(L, L->top, f); /* push function */ + setobj2s(L, L->top+1, p1); /* 1st argument */ + setobj2s(L, L->top+2, p2); /* 2nd argument */ + luaD_checkstack(L, 3); + L->top += 3; + luaD_call(L, L->top - 3, 1); + res = restorestack(L, result); + L->top--; + setobjs2s(L, res, L->top); +} + + + +static void callTM (lua_State *L, const TValue *f, const TValue *p1, + const TValue *p2, const TValue *p3) { + setobj2s(L, L->top, f); /* push function */ + setobj2s(L, L->top+1, p1); /* 1st argument */ + setobj2s(L, L->top+2, p2); /* 2nd argument */ + setobj2s(L, L->top+3, p3); /* 3th argument */ + luaD_checkstack(L, 4); + L->top += 4; + luaD_call(L, L->top - 4, 0); +} + + +void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { + int loop; + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; + if (ttistable(t)) { /* `t' is a table? */ + Table *h = hvalue(t); + const TValue *res = luaH_get(h, key); /* do a primitive get */ + if (!ttisnil(res) || /* result is no nil? */ + (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ + setobj2s(L, val, res); + return; + } + /* else will try the tag method */ + } + else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) + luaG_typeerror(L, t, "index"); + if (ttisfunction(tm)) { + callTMres(L, val, tm, t, key); + return; + } + t = tm; /* else repeat with `tm' */ + } + luaG_runerror(L, "loop in gettable"); +} + + +void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { + int loop; + for (loop = 0; loop < MAXTAGLOOP; loop++) { + const TValue *tm; + if (ttistable(t)) { /* `t' is a table? */ + Table *h = hvalue(t); + TValue *oldval = luaH_set(L, h, key); /* do a primitive set */ + if (!ttisnil(oldval) || /* result is no nil? */ + (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */ + setobj2t(L, oldval, val); + luaC_barriert(L, h, val); + return; + } + /* else will try the tag method */ + } + else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) + luaG_typeerror(L, t, "index"); + if (ttisfunction(tm)) { + callTM(L, tm, t, key, val); + return; + } + t = tm; /* else repeat with `tm' */ + } + luaG_runerror(L, "loop in settable"); +} + + +static int call_binTM (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 (ttisnil(tm)) + tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ + if (!ttisfunction(tm)) return 0; + callTMres(L, res, tm, p1, p2); + return 1; +} + + +static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2, + TMS event) { + const TValue *tm1 = fasttm(L, mt1, event); + const TValue *tm2; + if (tm1 == NULL) return NULL; /* no metamethod */ + if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ + tm2 = fasttm(L, mt2, event); + if (tm2 == NULL) return NULL; /* no metamethod */ + if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */ + return tm1; + return NULL; +} + + +static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, + TMS event) { + const TValue *tm1 = luaT_gettmbyobj(L, p1, event); + const TValue *tm2; + if (ttisnil(tm1)) return -1; /* no metamethod? */ + tm2 = luaT_gettmbyobj(L, p2, event); + if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */ + return -1; + callTMres(L, L->top, tm1, p1, p2); + return !l_isfalse(L->top); +} + + +static int l_strcmp (const TString *ls, const TString *rs) { + const char *l = getstr(ls); + size_t ll = ls->tsv.len; + const char *r = getstr(rs); + size_t lr = rs->tsv.len; + for (;;) { + int temp = strcoll(l, r); + if (temp != 0) return temp; + else { /* strings are equal up to a `\0' */ + size_t len = strlen(l); /* index of first `\0' in both strings */ + if (len == lr) /* r is finished? */ + return (len == ll) ? 0 : 1; + else if (len == ll) /* l is finished? */ + return -1; /* l is smaller than r (because r is not finished) */ + /* both strings longer than `len'; go on comparing (after the `\0') */ + len++; + l += len; ll -= len; r += len; lr -= len; + } + } +} + + +int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { + int res; + if (ttype(l) != ttype(r)) + return luaG_ordererror(L, l, r); + else if (ttisnumber(l)) + return luai_numlt(nvalue(l), nvalue(r)); + else if (ttisstring(l)) + return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; + else if ((res = call_orderTM(L, l, r, TM_LT)) != -1) + return res; + return luaG_ordererror(L, l, r); +} + + +static int lessequal (lua_State *L, const TValue *l, const TValue *r) { + int res; + if (ttype(l) != ttype(r)) + return luaG_ordererror(L, l, r); + else if (ttisnumber(l)) + return luai_numle(nvalue(l), nvalue(r)); + else if (ttisstring(l)) + return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; + else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */ + return res; + else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */ + return !res; + return luaG_ordererror(L, l, r); +} + + +int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { + const TValue *tm; + lua_assert(ttype(t1) == ttype(t2)); + switch (ttype(t1)) { + case LUA_TNIL: return 1; + case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); + case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ + case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); + case LUA_TUSERDATA: { + if (uvalue(t1) == uvalue(t2)) return 1; + tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, + TM_EQ); + break; /* will try TM */ + } + case LUA_TTABLE: { + if (hvalue(t1) == hvalue(t2)) return 1; + tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); + break; /* will try TM */ + } + default: return gcvalue(t1) == gcvalue(t2); + } + if (tm == NULL) return 0; /* no TM? */ + callTMres(L, L->top, tm, t1, t2); /* call TM */ + return !l_isfalse(L->top); +} + + +void luaV_concat (lua_State *L, int total, int last) { + do { + StkId top = L->base + last + 1; + int n = 2; /* number of elements handled in this pass (at least 2) */ + if (!tostring(L, top-2) || !tostring(L, top-1)) { + if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) + luaG_concaterror(L, top-2, top-1); + } else if (tsvalue(top-1)->len > 0) { /* if len=0, do nothing */ + /* at least two string values; get as many as possible */ + size_t tl = tsvalue(top-1)->len; + char *buffer; + int i; + /* collect total length */ + for (n = 1; n < total && tostring(L, top-n-1); n++) { + size_t l = tsvalue(top-n-1)->len; + if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow"); + tl += l; + } + buffer = luaZ_openspace(L, &G(L)->buff, tl); + tl = 0; + for (i=n; i>0; i--) { /* concat all strings */ + size_t l = tsvalue(top-i)->len; + memcpy(buffer+tl, svalue(top-i), l); + tl += l; + } + setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); + } + total -= n-1; /* got `n' strings to create 1 new */ + last -= n-1; + } while (total > 1); /* repeat until only 1 result left */ +} + + +static void Arith (lua_State *L, StkId ra, const TValue *rb, + const TValue *rc, TMS op) { + TValue tempb, tempc; + const TValue *b, *c; + if ((b = luaV_tonumber(rb, &tempb)) != NULL && + (c = luaV_tonumber(rc, &tempc)) != NULL) { + lua_Number nb = nvalue(b), nc = nvalue(c); + switch (op) { + case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break; + case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break; + case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break; + case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break; + case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break; + case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break; + case TM_UNM: setnvalue(ra, luai_numunm(nb)); break; + default: lua_assert(0); break; + } + } + else if (!call_binTM(L, rb, rc, ra, op)) + luaG_aritherror(L, rb, rc); +} + + + +/* +** some macros for common tasks in `luaV_execute' +*/ + +#define runtime_check(L, c) { if (!(c)) break; } + +#define RA(i) (base+GETARG_A(i)) +/* to be used after possible stack reallocation */ +#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) +#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) +#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) +#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ + ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) +#define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i)) + + +#define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);} + + +#define Protect(x) { L->savedpc = pc; {x;}; base = L->base; } + + +#define arith_op(op,tm) { \ + TValue *rb = RKB(i); \ + TValue *rc = RKC(i); \ + if (ttisnumber(rb) && ttisnumber(rc)) { \ + lua_Number nb = nvalue(rb), nc = nvalue(rc); \ + setnvalue(ra, op(nb, nc)); \ + } \ + else \ + Protect(Arith(L, ra, rb, rc, tm)); \ + } + + + +void luaV_execute (lua_State *L, int nexeccalls) { + LClosure *cl; + StkId base; + TValue *k; + const Instruction *pc; + reentry: /* entry point */ + pc = L->savedpc; + cl = &clvalue(L->ci->func)->l; + base = L->base; + k = cl->p->k; + /* main loop of interpreter */ + for (;;) { + const Instruction i = *pc++; + StkId ra; + if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && + (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { + traceexec(L, pc); + if (L->status == LUA_YIELD) { /* did hook yield? */ + L->savedpc = pc - 1; + return; + } + base = L->base; + } + /* warning!! several calls may realloc the stack and invalidate `ra' */ + ra = RA(i); + lua_assert(base == L->base && L->base == L->ci->base); + lua_assert(base <= L->top && L->top <= L->stack + L->stacksize); + lua_assert(L->top == L->ci->top || luaG_checkopenop(i)); + switch (GET_OPCODE(i)) { + case OP_MOVE: { + setobjs2s(L, ra, RB(i)); + continue; + } + case OP_LOADK: { + setobj2s(L, ra, KBx(i)); + continue; + } + case OP_LOADBOOL: { + setbvalue(ra, GETARG_B(i)); + if (GETARG_C(i)) pc++; /* skip next instruction (if C) */ + continue; + } + case OP_LOADNIL: { + TValue *rb = RB(i); + do { + setnilvalue(rb--); + } while (rb >= ra); + continue; + } + case OP_GETUPVAL: { + int b = GETARG_B(i); + setobj2s(L, ra, cl->upvals[b]->v); + continue; + } + case OP_GETGLOBAL: { + TValue g; + TValue *rb = KBx(i); + sethvalue(L, &g, cl->env); + lua_assert(ttisstring(rb)); + Protect(luaV_gettable(L, &g, rb, ra)); + continue; + } + case OP_GETTABLE: { + Protect(luaV_gettable(L, RB(i), RKC(i), ra)); + continue; + } + case OP_SETGLOBAL: { + TValue g; + sethvalue(L, &g, cl->env); + lua_assert(ttisstring(KBx(i))); + Protect(luaV_settable(L, &g, KBx(i), ra)); + continue; + } + case OP_SETUPVAL: { + UpVal *uv = cl->upvals[GETARG_B(i)]; + setobj(L, uv->v, ra); + luaC_barrier(L, uv, ra); + continue; + } + case OP_SETTABLE: { + Protect(luaV_settable(L, ra, RKB(i), RKC(i))); + continue; + } + case OP_NEWTABLE: { + int b = GETARG_B(i); + int c = GETARG_C(i); + sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c))); + Protect(luaC_checkGC(L)); + continue; + } + case OP_SELF: { + StkId rb = RB(i); + setobjs2s(L, ra+1, rb); + Protect(luaV_gettable(L, rb, RKC(i), ra)); + continue; + } + case OP_ADD: { + arith_op(luai_numadd, TM_ADD); + continue; + } + case OP_SUB: { + arith_op(luai_numsub, TM_SUB); + continue; + } + case OP_MUL: { + arith_op(luai_nummul, TM_MUL); + continue; + } + case OP_DIV: { + arith_op(luai_numdiv, TM_DIV); + continue; + } + case OP_MOD: { + arith_op(luai_nummod, TM_MOD); + continue; + } + case OP_POW: { + arith_op(luai_numpow, TM_POW); + continue; + } + case OP_UNM: { + TValue *rb = RB(i); + if (ttisnumber(rb)) { + lua_Number nb = nvalue(rb); + setnvalue(ra, luai_numunm(nb)); + } + else { + Protect(Arith(L, ra, rb, rb, TM_UNM)); + } + continue; + } + case OP_NOT: { + int res = l_isfalse(RB(i)); /* next assignment may change this value */ + setbvalue(ra, res); + continue; + } + case OP_LEN: { + const TValue *rb = RB(i); + switch (ttype(rb)) { + case LUA_TTABLE: { + setnvalue(ra, cast_num(luaH_getn(hvalue(rb)))); + break; + } + case LUA_TSTRING: { + setnvalue(ra, cast_num(tsvalue(rb)->len)); + break; + } + default: { /* try metamethod */ + Protect( + if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN)) + luaG_typeerror(L, rb, "get length of"); + ) + } + } + continue; + } + case OP_CONCAT: { + int b = GETARG_B(i); + int c = GETARG_C(i); + Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L)); + setobjs2s(L, RA(i), base+b); + continue; + } + case OP_JMP: { + dojump(L, pc, GETARG_sBx(i)); + continue; + } + case OP_EQ: { + TValue *rb = RKB(i); + TValue *rc = RKC(i); + Protect( + if (equalobj(L, rb, rc) == GETARG_A(i)) + dojump(L, pc, GETARG_sBx(*pc)); + ) + pc++; + continue; + } + case OP_LT: { + Protect( + if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i)) + dojump(L, pc, GETARG_sBx(*pc)); + ) + pc++; + continue; + } + case OP_LE: { + Protect( + if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) + dojump(L, pc, GETARG_sBx(*pc)); + ) + pc++; + continue; + } + case OP_TEST: { + if (l_isfalse(ra) != GETARG_C(i)) + dojump(L, pc, GETARG_sBx(*pc)); + pc++; + continue; + } + case OP_TESTSET: { + TValue *rb = RB(i); + if (l_isfalse(rb) != GETARG_C(i)) { + setobjs2s(L, ra, rb); + dojump(L, pc, GETARG_sBx(*pc)); + } + pc++; + continue; + } + case OP_CALL: { + int b = GETARG_B(i); + int nresults = GETARG_C(i) - 1; + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + L->savedpc = pc; + switch (luaD_precall(L, ra, nresults)) { + case PCRLUA: { + nexeccalls++; + goto reentry; /* restart luaV_execute over new Lua function */ + } + case PCRC: { + /* it was a C function (`precall' called it); adjust results */ + if (nresults >= 0) L->top = L->ci->top; + base = L->base; + continue; + } + default: { + return; /* yield */ + } + } + } + case OP_TAILCALL: { + int b = GETARG_B(i); + if (b != 0) L->top = ra+b; /* else previous instruction set top */ + L->savedpc = pc; + lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); + switch (luaD_precall(L, ra, LUA_MULTRET)) { + case PCRLUA: { + /* tail call: put new frame in place of previous one */ + CallInfo *ci = L->ci - 1; /* previous frame */ + int aux; + StkId func = ci->func; + StkId pfunc = (ci+1)->func; /* previous function index */ + if (L->openupval) luaF_close(L, ci->base); + L->base = ci->base = ci->func + ((ci+1)->base - pfunc); + for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */ + setobjs2s(L, func+aux, pfunc+aux); + ci->top = L->top = func+aux; /* correct top */ + lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize); + ci->savedpc = L->savedpc; + ci->tailcalls++; /* one more call lost */ + L->ci--; /* remove new frame */ + goto reentry; + } + case PCRC: { /* it was a C function (`precall' called it) */ + base = L->base; + continue; + } + default: { + return; /* yield */ + } + } + } + case OP_RETURN: { + int b = GETARG_B(i); + if (b != 0) L->top = ra+b-1; + if (L->openupval) luaF_close(L, base); + L->savedpc = pc; + b = luaD_poscall(L, ra); + if (--nexeccalls == 0) /* was previous function running `here'? */ + return; /* no: return */ + else { /* yes: continue its execution */ + if (b) L->top = L->ci->top; + lua_assert(isLua(L->ci)); + lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL); + goto reentry; + } + } + case OP_FORLOOP: { + lua_Number step = nvalue(ra+2); + lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */ + lua_Number limit = nvalue(ra+1); + if (luai_numlt(0, step) ? luai_numle(idx, limit) + : luai_numle(limit, idx)) { + dojump(L, pc, GETARG_sBx(i)); /* jump back */ + setnvalue(ra, idx); /* update internal index... */ + setnvalue(ra+3, idx); /* ...and external index */ + } + continue; + } + case OP_FORPREP: { + const TValue *init = ra; + const TValue *plimit = ra+1; + const TValue *pstep = ra+2; + L->savedpc = pc; /* next steps may throw errors */ + if (!tonumber(init, ra)) + luaG_runerror(L, LUA_QL("for") " initial value must be a number"); + else if (!tonumber(plimit, ra+1)) + luaG_runerror(L, LUA_QL("for") " limit must be a number"); + else if (!tonumber(pstep, ra+2)) + luaG_runerror(L, LUA_QL("for") " step must be a number"); + setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep))); + dojump(L, pc, GETARG_sBx(i)); + continue; + } + case OP_TFORLOOP: { + StkId cb = ra + 3; /* call base */ + setobjs2s(L, cb+2, ra+2); + setobjs2s(L, cb+1, ra+1); + setobjs2s(L, cb, ra); + L->top = cb+3; /* func. + 2 args (state and index) */ + Protect(luaD_call(L, cb, GETARG_C(i))); + L->top = L->ci->top; + cb = RA(i) + 3; /* previous call may change the stack */ + if (!ttisnil(cb)) { /* continue loop? */ + setobjs2s(L, cb-1, cb); /* save control variable */ + dojump(L, pc, GETARG_sBx(*pc)); /* jump back */ + } + pc++; + continue; + } + case OP_SETLIST: { + int n = GETARG_B(i); + int c = GETARG_C(i); + int last; + Table *h; + if (n == 0) { + n = cast_int(L->top - ra) - 1; + L->top = L->ci->top; + } + if (c == 0) c = cast_int(*pc++); + runtime_check(L, ttistable(ra)); + h = hvalue(ra); + last = ((c-1)*LFIELDS_PER_FLUSH) + n; + if (last > h->sizearray) /* needs more space? */ + luaH_resizearray(L, h, last); /* pre-alloc it at once */ + for (; n > 0; n--) { + TValue *val = ra+n; + setobj2t(L, luaH_setnum(L, h, last--), val); + luaC_barriert(L, h, val); + } + continue; + } + case OP_CLOSE: { + luaF_close(L, ra); + continue; + } + case OP_CLOSURE: { + Proto *p; + Closure *ncl; + int nup, j; + p = cl->p->p[GETARG_Bx(i)]; + nup = p->nups; + ncl = luaF_newLclosure(L, nup, cl->env); + ncl->l.p = p; + for (j=0; jl.upvals[j] = cl->upvals[GETARG_B(*pc)]; + else { + lua_assert(GET_OPCODE(*pc) == OP_MOVE); + ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc)); + } + } + setclvalue(L, ra, ncl); + Protect(luaC_checkGC(L)); + continue; + } + case OP_VARARG: { + int b = GETARG_B(i) - 1; + int j; + CallInfo *ci = L->ci; + int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1; + if (b == LUA_MULTRET) { + Protect(luaD_checkstack(L, n)); + ra = RA(i); /* previous call may change the stack */ + b = n; + L->top = ra + n; + } + for (j = 0; j < b; j++) { + if (j < n) { + setobjs2s(L, ra + j, ci->base - n + j); + } + else { + setnilvalue(ra + j); + } + } + continue; + } + } + } +} + diff --git a/src/lua/lvm.h b/src/lua/lvm.h new file mode 100644 index 0000000..788423f --- /dev/null +++ b/src/lua/lvm.h @@ -0,0 +1,36 @@ +/* +** $Id: lvm.h,v 2.5 2005/08/22 18:54:49 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lvm_h +#define lvm_h + + +#include "ldo.h" +#include "lobject.h" +#include "ltm.h" + + +#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o))) + +#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \ + (((o) = luaV_tonumber(o,n)) != NULL)) + +#define equalobj(L,o1,o2) \ + (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2)) + + +LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2); +LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); +LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); +LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, + StkId val); +LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, + StkId val); +LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls); +LUAI_FUNC void luaV_concat (lua_State *L, int total, int last); + +#endif diff --git a/src/lua/lzio.c b/src/lua/lzio.c new file mode 100644 index 0000000..5121ada --- /dev/null +++ b/src/lua/lzio.c @@ -0,0 +1,82 @@ +/* +** $Id: lzio.c,v 1.31 2005/06/03 20:15:29 roberto Exp $ +** a generic input stream interface +** See Copyright Notice in lua.h +*/ + + +#include + +#define lzio_c +#define LUA_CORE + +#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; + z->p = buff; + return char2int(*(z->p++)); +} + + +int luaZ_lookahead (ZIO *z) { + if (z->n == 0) { + if (luaZ_fill(z) == EOZ) + return EOZ; + else { + z->n++; /* luaZ_fill removed first byte; put back it */ + z->p--; + } + } + return char2int(*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 (luaZ_lookahead(z) == EOZ) + return n; /* return number of missing bytes */ + 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; +} + +/* ------------------------------------------------------------------------ */ +char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) { + if (n > buff->buffsize) { + if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; + luaZ_resizebuffer(L, buff, n); + } + return buff->buffer; +} + + diff --git a/src/lua/lzio.h b/src/lua/lzio.h new file mode 100644 index 0000000..8f403b8 --- /dev/null +++ b/src/lua/lzio.h @@ -0,0 +1,67 @@ +/* +** $Id: lzio.h,v 1.21 2005/05/17 19:49:15 roberto Exp $ +** 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 char2int(c) cast(int, cast(unsigned char, (c))) + +#define zgetc(z) (((z)->n--)>0 ? char2int(*(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_resetbuffer(buff) ((buff)->n = 0) + + +#define luaZ_resizebuffer(L, buff, size) \ + (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \ + (buff)->buffsize = size) + +#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) + + +LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); +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 */ +LUAI_FUNC int luaZ_lookahead (ZIO *z); + + + +/* --------- Private Part ------------------ */ + +struct Zio { + size_t n; /* bytes still unread */ + const char *p; /* current position in buffer */ + lua_Reader reader; + void* data; /* additional data */ + lua_State *L; /* Lua state (for reader) */ +}; + + +LUAI_FUNC int luaZ_fill (ZIO *z); + +#endif diff --git a/src/lua/print.c b/src/lua/print.c new file mode 100644 index 0000000..1c3a445 --- /dev/null +++ b/src/lua/print.c @@ -0,0 +1,224 @@ +/* +** $Id: print.c,v 1.54 2006/01/11 22:49:27 lhf Exp $ +** print bytecodes +** See Copyright Notice in lua.h +*/ + +#include +#include + +#define luac_c +#define LUA_CORE + +#include "ldebug.h" +#include "lobject.h" +#include "lopcodes.h" +#include "lundump.h" + +#define PrintFunction luaU_print + +#define Sizeof(x) ((int)sizeof(x)) +#define VOID(p) ((const void*)(p)) + +static void PrintString(const Proto* f, int n) +{ + const char* s=svalue(&f->k[n]); + putchar('"'); + for (; *s; s++) + { + switch (*s) + { + case '"': printf("\\\""); break; + case '\a': printf("\\a"); break; + case '\b': printf("\\b"); break; + case '\f': printf("\\f"); break; + case '\n': printf("\\n"); break; + case '\r': printf("\\r"); break; + case '\t': printf("\\t"); break; + case '\v': printf("\\v"); break; + default: if (isprint((unsigned char)*s)) + printf("%c",*s); + else + printf("\\%03u",(unsigned char)*s); + } + } + putchar('"'); +} + +static void PrintConstant(const Proto* f, int i) +{ + const TValue* o=&f->k[i]; + switch (ttype(o)) + { + case LUA_TNIL: + printf("nil"); + break; + case LUA_TBOOLEAN: + printf(bvalue(o) ? "true" : "false"); + break; + case LUA_TNUMBER: + printf(LUA_NUMBER_FMT,nvalue(o)); + break; + case LUA_TSTRING: + PrintString(f,i); + break; + default: /* cannot happen */ + printf("? type=%d",ttype(o)); + break; + } +} + +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",luaP_opnames[o]); + switch (getOpMode(o)) + { + case iABC: + printf("%d",a); + if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b); + if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c); + break; + case iABx: + if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx); + break; + case iAsBx: + if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx); + break; + } + switch (o) + { + case OP_LOADK: + printf("\t; "); PrintConstant(f,bx); + break; + case OP_GETUPVAL: + case OP_SETUPVAL: + printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-"); + break; + case OP_GETGLOBAL: + case OP_SETGLOBAL: + printf("\t; %s",svalue(&f->k[bx])); + break; + case OP_GETTABLE: + case OP_SELF: + if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); } + break; + case OP_SETTABLE: + case OP_ADD: + case OP_SUB: + case OP_MUL: + case OP_DIV: + case OP_POW: + case OP_EQ: + case OP_LT: + case OP_LE: + if (ISK(b) || ISK(c)) + { + printf("\t; "); + if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-"); + printf(" "); + if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-"); + } + break; + case OP_JMP: + case OP_FORLOOP: + case OP_FORPREP: + printf("\t; to %d",sbx+pc+2); + break; + case OP_CLOSURE: + printf("\t; %p",VOID(f->p[bx])); + break; + case OP_SETLIST: + if (c==0) printf("\t; %d",(int)code[++pc]); + else printf("\t; %d",c); + break; + default: + break; + } + printf("\n"); + } +} + +#define SS(x) (x==1)?"":"s" +#define S(x) x,SS(x) + +static void PrintHeader(const Proto* f) +{ + const char* s=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, %d bytes at %p)\n", + (f->linedefined==0)?"main":"function",s, + f->linedefined,f->lastlinedefined, + S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f)); + printf("%d%s param%s, %d slot%s, %d upvalue%s, ", + f->numparams,f->is_vararg?"+":"",SS(f->numparams), + S(f->maxstacksize),S(f->nups)); + printf("%d local%s, %d constant%s, %d function%s\n", + S(f->sizelocvars),S(f->sizek),S(f->sizep)); +} + +static void PrintConstants(const Proto* f) +{ + int i,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); + } +} + +static void PrintUpvalues(const Proto* f) +{ + int i,n=f->sizeupvalues; + printf("upvalues (%d) for %p:\n",n,VOID(f)); + if (f->upvalues==NULL) return; + for (i=0; iupvalues[i])); + } +} + +void PrintFunction(const Proto* f, int full) +{ + int i,n=f->sizep; + PrintHeader(f); + PrintCode(f); + if (full) + { + PrintConstants(f); + PrintLocals(f); + PrintUpvalues(f); + } + for (i=0; ip[i],full); +} diff --git a/src/luairc/irc.lua b/src/luairc/irc.lua new file mode 100644 index 0000000..a0c22b4 --- /dev/null +++ b/src/luairc/irc.lua @@ -0,0 +1,994 @@ +--- +-- Implementation of the main LuaIRC module + +-- initialization {{{ +local base = _G +local constants = require 'irc.constants' +local ctcp = require 'irc.ctcp' +local c = ctcp._ctcp_quote +local irc_debug = require 'irc.debug' +local message = require 'irc.message' +local misc = require 'irc.misc' +local socket = require 'socket' +local os = require 'os' +local string = require 'string' +local table = require 'table' +-- }}} + +--- +-- LuaIRC - IRC framework written in Lua +-- @release 0.3 +module 'irc' + +-- constants {{{ +_VERSION = 'LuaIRC 0.3' +-- }}} + +-- classes {{{ +local Channel = base.require 'irc.channel' +-- }}} + +-- local variables {{{ +local irc_sock = nil +local rsockets = {} +local wsockets = {} +local rcallbacks = {} +local wcallbacks = {} +local icallbacks = { + whois = {}, + serverversion = {}, + servertime = {}, + ctcp_ping = {}, + ctcp_time = {}, + ctcp_version = {}, +} +local requestinfo = {whois = {}} +local handlers = {} +local ctcp_handlers = {} +local user_handlers = {} +local serverinfo = {} +local ip = nil +-- }}} + +-- defaults {{{ +TIMEOUT = 60 -- connection timeout +NETWORK = "localhost" -- default network +PORT = 6667 -- default port +NICK = "luabot" -- default nick +USERNAME = "LuaIRC" -- default username +REALNAME = "LuaIRC" -- default realname +DEBUG = false -- whether we want extra debug information +OUTFILE = nil -- file to send debug output to - nil is stdout +-- }}} + +-- private functions {{{ +-- main_loop_iter {{{ +local function main_loop_iter() + if #rsockets == 0 and #wsockets == 0 then return false end + local rready, wready, err = socket.select(rsockets, wsockets) + if err then irc_debug._err(err); return false; end + + for _, sock in base.ipairs(rready) do + local cb = socket.protect(rcallbacks[sock]) + local ret, err = cb(sock) + if not ret then + irc_debug._warn("socket error: " .. err) + _unregister_socket(sock, 'r') + end + end + + for _, sock in base.ipairs(wready) do + local cb = socket.protect(wcallbacks[sock]) + local ret, err = cb(sock) + if not ret then + irc_debug._warn("socket error: " .. err) + _unregister_socket(sock, 'w') + end + end + + return true +end +-- }}} + +-- begin_main_loop {{{ +local function begin_main_loop() + while main_loop_iter() do end +end +-- }}} + +-- incoming_message {{{ +local function incoming_message(sock) + local raw_msg = socket.try(sock:receive()) + irc_debug._message("RECV", raw_msg) + local msg = message._parse(raw_msg) + misc._try_call_warn("Unhandled server message: " .. msg.command, + handlers["on_" .. msg.command:lower()], + (misc._parse_user(msg.from)), base.unpack(msg.args)) + return true +end +-- }}} + +-- callback {{{ +local function callback(name, ...) + return misc._try_call(user_handlers[name], ...) +end +-- }}} +-- }}} + +-- internal message handlers {{{ +-- command handlers {{{ +-- on_nick {{{ +function handlers.on_nick(from, new_nick) + for chan in channels() do + chan:_change_nick(from, new_nick) + end + callback("nick_change", new_nick, from) +end +-- }}} + +-- on_join {{{ +function handlers.on_join(from, chan) + base.assert(serverinfo.channels[chan], + "Received join message for unknown channel: " .. chan) + if serverinfo.channels[chan].join_complete then + serverinfo.channels[chan]:_add_user(from) + callback("join", serverinfo.channels[chan], from) + end +end +-- }}} + +-- on_part {{{ +function handlers.on_part(from, chan, part_msg) + -- don't assert on chan here, since we get part messages for ourselves + -- after we remove the channel from the channel list + if not serverinfo.channels[chan] then return end + if serverinfo.channels[chan].join_complete then + serverinfo.channels[chan]:_remove_user(from) + callback("part", serverinfo.channels[chan], from, part_msg) + end +end +-- }}} + +-- on_mode {{{ +function handlers.on_mode(from, to, mode_string, ...) + local dir = mode_string:sub(1, 1) + mode_string = mode_string:sub(2) + local args = {...} + + if to:sub(1, 1) == "#" then + -- handle channel mode requests {{{ + base.assert(serverinfo.channels[to], + "Received mode change for unknown channel: " .. to) + local chan = serverinfo.channels[to] + local ind = 1 + for i = 1, mode_string:len() do + local mode = mode_string:sub(i, i) + local target = args[ind] + -- channel modes other than op/voice will be implemented as + -- information request commands + if mode == "o" then -- channel op {{{ + chan:_change_status(target, dir == "+", "o") + callback(({["+"] = "op", ["-"] = "deop"})[dir], + chan, from, target) + ind = ind + 1 + -- }}} + elseif mode == "v" then -- voice {{{ + chan:_change_status(target, dir == "+", "v") + callback(({["+"] = "voice", ["-"] = "devoice"})[dir], + chan, from, target) + ind = ind + 1 + -- }}} + end + end + -- }}} + elseif from == to then + -- handle user mode requests {{{ + -- TODO: make users more easily accessible so this is actually + -- reasonably possible + for i = 1, mode_string:len() do + local mode = mode_string:sub(i, i) + if mode == "i" then -- invisible {{{ + -- }}} + elseif mode == "s" then -- server messages {{{ + -- }}} + elseif mode == "w" then -- wallops messages {{{ + -- }}} + elseif mode == "o" then -- ircop {{{ + -- }}} + end + end + -- }}} + end +end +-- }}} + +-- on_topic {{{ +function handlers.on_topic(from, chan, new_topic) + base.assert(serverinfo.channels[chan], + "Received topic message for unknown channel: " .. chan) + serverinfo.channels[chan]._topic.text = new_topic + serverinfo.channels[chan]._topic.user = from + serverinfo.channels[chan]._topic.time = os.time() + if serverinfo.channels[chan].join_complete then + callback("topic_change", serverinfo.channels[chan]) + end +end +-- }}} + +-- on_invite {{{ +function handlers.on_invite(from, to, chan) + callback("invite", from, chan) +end +-- }}} + +-- on_kick {{{ +function handlers.on_kick(from, chan, to) + base.assert(serverinfo.channels[chan], + "Received kick message for unknown channel: " .. chan) + if serverinfo.channels[chan].join_complete then + serverinfo.channels[chan]:_remove_user(to) + callback("kick", serverinfo.channels[chan], to, from) + end +end +-- }}} + +-- on_privmsg {{{ +function handlers.on_privmsg(from, to, msg) + local msgs = ctcp._ctcp_split(msg) + for _, v in base.ipairs(msgs) do + local msg = v.str + if v.ctcp then + -- ctcp message {{{ + local words = misc._split(msg) + local received_command = words[1] + local cb = "on_" .. received_command:lower() + table.remove(words, 1) + -- not using try_call here because the ctcp specification requires + -- an error response to nonexistant commands + if base.type(ctcp_handlers[cb]) == "function" then + ctcp_handlers[cb](from, to, table.concat(words, " ")) + else + notice(from, c("ERRMSG", received_command, ":Unknown query")) + end + -- }}} + else + -- normal message {{{ + if to:sub(1, 1) == "#" then + base.assert(serverinfo.channels[to], + "Received channel msg from unknown channel: " .. to) + callback("channel_msg", serverinfo.channels[to], from, msg) + else + callback("private_msg", from, msg) + end + -- }}} + end + end +end +-- }}} + +-- on_notice {{{ +function handlers.on_notice(from, to, msg) + local msgs = ctcp._ctcp_split(msg) + for _, v in base.ipairs(msgs) do + local msg = v.str + if v.ctcp then + -- ctcp message {{{ + local words = misc._split(msg) + local command = words[1]:lower() + table.remove(words, 1) + misc._try_call_warn("Unknown CTCP message: " .. command, + ctcp_handlers["on_rpl_"..command], from, to, + table.concat(words, ' ')) + -- }}} + else + -- normal message {{{ + if to:sub(1, 1) == "#" then + base.assert(serverinfo.channels[to], + "Received channel msg from unknown channel: " .. to) + callback("channel_notice", serverinfo.channels[to], from, msg) + else + callback("private_notice", from, msg) + end + -- }}} + end + end +end +-- }}} + +-- on_quit {{{ +function handlers.on_quit(from, quit_msg) + for name, chan in base.pairs(serverinfo.channels) do + chan:_remove_user(from) + end + callback("quit", from, quit_msg) +end +-- }}} + +-- on_ping {{{ +-- respond to server pings to make sure it knows we are alive +function handlers.on_ping(from, respond_to) + send("PONG", respond_to) +end +-- }}} +-- }}} + +-- server replies {{{ +-- on_rpl_topic {{{ +-- catch topic changes +function handlers.on_rpl_topic(from, chan, topic) + base.assert(serverinfo.channels[chan], + "Received topic information about unknown channel: " .. chan) + serverinfo.channels[chan]._topic.text = topic +end +-- }}} + +-- on_rpl_notopic {{{ +function handlers.on_rpl_notopic(from, chan) + base.assert(serverinfo.channels[chan], + "Received topic information about unknown channel: " .. chan) + serverinfo.channels[chan]._topic.text = "" +end +-- }}} + +-- on_rpl_topicdate {{{ +-- "topic was set by at

irc.NETWORK = irc.freenode.net
+-- Possible options are: +--
    +--
  • network: address of the irc network to connect to +-- (default: 'localhost')
  • +--
  • port: port to connect to +-- (default: '6667')
  • +--
  • pass: irc server password +-- (default: don't send)
  • +--
  • nick: nickname to connect as +-- (default: 'luabot')
  • +--
  • username: username to connect with +-- (default: 'LuaIRC')
  • +--
  • realname: realname to connect with +-- (default: 'LuaIRC')
  • +--
  • timeout: amount of time in seconds to wait before +-- dropping an idle connection +-- (default: '60')
  • +--
+function connect(args) + local network = args.network or NETWORK + local port = args.port or PORT + local nick = args.nick or NICK + local username = args.username or USERNAME + local realname = args.realname or REALNAME + local timeout = args.timeout or TIMEOUT + serverinfo.connecting = true + if OUTFILE then irc_debug.set_output(OUTFILE) end + if DEBUG then irc_debug.enable() end + irc_sock = base.assert(socket.connect(network, port)) + irc_sock:settimeout(timeout) + _register_socket(irc_sock, 'r', incoming_message) + if args.pass then send("PASS", args.pass) end + send("NICK", nick) + send("USER", username, get_ip(), network, realname) + begin_main_loop() +end +-- }}} + +-- quit {{{ +--- +-- Close the connection to the irc server. +-- @param message Quit message (optional, defaults to 'Leaving') +function quit(message) + message = message or "Leaving" + send("QUIT", message) + serverinfo.connected = false +end +-- }}} + +-- join {{{ +--- +-- Join a channel. +-- @param channel Channel to join +function join(channel) + if not channel then return end + serverinfo.channels[channel] = Channel.new(channel) + send("JOIN", channel) +end +-- }}} + +-- part {{{ +--- +-- Leave a channel. +-- @param channel Channel to leave +function part(channel) + if not channel then return end + serverinfo.channels[channel] = nil + send("PART", channel) +end +-- }}} + +-- say {{{ +--- +-- Send a message to a user or channel. +-- @param name User or channel to send the message to +-- @param message Message to send +function say(name, message) + if not name then return end + message = message or "" + send("PRIVMSG", name, message) +end +-- }}} + +-- notice {{{ +--- +-- Send a notice to a user or channel. +-- @param name User or channel to send the notice to +-- @param message Message to send +function notice(name, message) + if not name then return end + message = message or "" + send("NOTICE", name, message) +end +-- }}} + +-- act {{{ +--- +-- Perform a /me action. +-- @param name User or channel to send the action to +-- @param action Action to send +function act(name, action) + if not name then return end + action = action or "" + send("PRIVMSG", name, c("ACTION", action)) +end +-- }}} +-- }}} + +-- information requests {{{ +-- server_version {{{ +--- +-- Request the version of the IRC server you are currently connected to. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback will contain the fields: +--
    +--
  • server: the server which responded to the request
  • +--
  • version: the server version
  • +--
  • comments: other data provided by the server
  • +--
+function server_version(cb) + -- apparently the optional server parameter isn't supported for servers + -- which you are not directly connected to (freenode specific?) + local server = serverinfo.host + if not icallbacks.serverversion[server] then + icallbacks.serverversion[server] = {cb} + send("VERSION", server) + else + table.insert(icallbacks.serverversion[server], cb) + end +end +-- }}} + +-- whois {{{ +-- TODO: allow server parameter (to get user idle time) +--- +-- Request WHOIS information about a given user. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback may contain any or all of the +-- fields: +--
    +--
  • nick: the nick that was passed to this function +-- (this field will always be here)
  • +--
  • user: the IRC username of the user
  • +--
  • host: the user's hostname
  • +--
  • realname: the IRC realname of the user
  • +--
  • server: the IRC server the user is connected to
  • +--
  • serverinfo: arbitrary information about the above +-- server
  • +--
  • awaymsg: set to the user's away message if they are +-- away
  • +--
  • is_oper: true if the user is an IRCop
  • +--
  • idle_time: amount of time the user has been idle
  • +--
  • channels: array containing the channels the user has +-- joined
  • +--
+-- @param nick User to request WHOIS information about +function whois(cb, nick) + nick = nick:lower() + requestinfo.whois[nick] = {} + if not icallbacks.whois[nick] then + icallbacks.whois[nick] = {cb} + send("WHOIS", nick) + else + table.insert(icallbacks.whois[nick], cb) + end +end +-- }}} + +-- server_time {{{ +--- +-- Request the current time of the server you are connected to. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback will contain the fields: +--
    +--
  • server: the server which responded to the request
  • +--
  • time: the time reported by the server
  • +--
+function server_time(cb) + -- apparently the optional server parameter isn't supported for servers + -- which you are not directly connected to (freenode specific?) + local server = serverinfo.host + if not icallbacks.servertime[server] then + icallbacks.servertime[server] = {cb} + send("TIME", server) + else + table.insert(icallbacks.servertime[server], cb) + end +end +-- }}} +-- }}} + +-- ctcp commands {{{ +-- ctcp_ping {{{ +--- +-- Send a CTCP ping request. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback will contain the fields: +--
    +--
  • nick: the nick which responded to the request
  • +--
  • time: the roundtrip ping time, in seconds
  • +--
+-- @param nick User to ping +function ctcp_ping(cb, nick) + nick = nick:lower() + if not icallbacks.ctcp_ping[nick] then + icallbacks.ctcp_ping[nick] = {cb} + say(nick, c("PING", os.time())) + else + table.insert(icallbacks.ctcp_ping[nick], cb) + end +end +-- }}} + +-- ctcp_time {{{ +--- +-- Send a localtime request. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback will contain the fields: +--
    +--
  • nick: the nick which responded to the request
  • +--
  • time: the localtime reported by the remote client
  • +--
+-- @param nick User to request the localtime from +function ctcp_time(cb, nick) + nick = nick:lower() + if not icallbacks.ctcp_time[nick] then + icallbacks.ctcp_time[nick] = {cb} + say(nick, c("TIME")) + else + table.insert(icallbacks.ctcp_time[nick], cb) + end +end +-- }}} + +-- ctcp_version {{{ +--- +-- Send a client version request. +-- @param cb Callback to call when the information is available. The single +-- table parameter to this callback will contain the fields: +--
    +--
  • nick: the nick which responded to the request
  • +--
  • version: the version reported by the remote client
  • +--
+-- @param nick User to request the client version from +function ctcp_version(cb, nick) + nick = nick:lower() + if not icallbacks.ctcp_version[nick] then + icallbacks.ctcp_version[nick] = {cb} + say(nick, c("VERSION")) + else + table.insert(icallbacks.ctcp_version[nick], cb) + end +end +-- }}} +-- }}} + +-- callback functions {{{ +-- register_callback {{{ +--- +-- Register a user function to be called when a specific event occurs. +-- @param name Name of the event +-- @param fn Function to call when the event occurs, or nil to clear the +-- callback for this event +-- @return Value of the original callback for this event (or nil if no previous +-- callback had been set) +function register_callback(name, fn) + local old_handler = user_handlers[name] + user_handlers[name] = fn + return old_handler +end +-- }}} +-- }}} + +-- misc functions {{{ +-- send {{{ +-- TODO: CTCP quoting should be explicit, this table thing is quite ugly (if +-- convenient) +--- +-- Send a raw IRC command. +-- @param command String containing the raw IRC command +-- @param ... Arguments to the command. Each argument is either a string or +-- an array. Strings are sent literally, arrays are CTCP quoted +-- as a group. The last argument (if it exists) is preceded by +-- a : (so it may contain spaces). +function send(command, ...) + if not serverinfo.connected and not serverinfo.connecting then return end + local message = command + for i, v in base.ipairs({...}) do + if i == #{...} then + v = ":" .. v + end + message = message .. " " .. v + end + message = ctcp._low_quote(message) + -- we just truncate for now. -2 to account for the \r\n + message = message:sub(1, constants.IRC_MAX_MSG - 2) + irc_debug._message("SEND", message) + irc_sock:send(message .. "\r\n") +end +-- }}} + +-- get_ip {{{ +--- +-- Get the local IP address for the server connection. +-- @return A string representation of the local IP address that the IRC server +-- connection is communicating on +function get_ip() + return (ip or irc_sock:getsockname()) +end +-- }}} + +-- set_ip {{{ +--- +-- Set the local IP manually (to allow for NAT workarounds) +-- @param new_ip IP address to set +function set_ip(new_ip) + ip = new_ip +end +-- }}} + +-- channels {{{ +-- TODO: @see doesn't currently work for files/modules +--- +-- Iterate over currently joined channels. +-- channels() is an iterator function for use in for loops. +-- For example,
for chan in irc.channels() do print(chan:name) end
+-- @see irc.channel +function channels() + return function(state, arg) + return misc._value_iter(state, arg, + function(v) + return v.join_complete + end) + end, + serverinfo.channels, + nil +end +-- }}} +-- }}} +-- }}} diff --git a/src/luairc/irc/channel.lua b/src/luairc/irc/channel.lua new file mode 100644 index 0000000..82bca71 --- /dev/null +++ b/src/luairc/irc/channel.lua @@ -0,0 +1,475 @@ +--- +-- Implementation of the Channel class + +-- initialization {{{ +local base = _G +local irc = require 'irc' +local misc = require 'irc.misc' +local socket = require 'socket' +local table = require 'table' +-- }}} + +--- +-- This module implements a channel object representing a single channel we +-- have joined. +module 'irc.channel' + +-- object metatable {{{ +-- TODO: this
shouldn't be necessary - bug in luadoc +--- +-- An object of the Channel class represents a single joined channel. It has +-- several table fields, and can be used in string contexts (returning the +-- channel name).
+-- @class table +-- @name Channel +-- @field name Name of the channel (read only) +-- @field topic Channel topic, if set (read/write, writing to this sends a +-- topic change request to the server for this channel) +-- @field chanmode Channel mode (public/private/secret) (read only) +-- @field members Array of all members of this channel +local mt = { + -- __index() {{{ + __index = function(self, key) + if key == "name" then + return self._name + elseif key == "topic" then + return self._topic + elseif key == "chanmode" then + return self._chanmode + else + return _M[key] + end + end, + -- }}} + -- __newindex() {{{ + __newindex = function(self, key, value) + if key == "name" then + return + elseif key == "topic" then + irc.send("TOPIC", self._name, value) + elseif key == "chanmode" then + return + else + base.rawset(self, key, value) + end + end, + -- }}} + -- __concat() {{{ + __concat = function(first, second) + local first_str, second_str + + if base.type(first) == "table" then + first_str = first._name + else + first_str = first + end + if base.type(second) == "table" then + second_str = second._name + else + second_str = second + end + + return first_str .. second_str + end, + -- }}} + -- __tostring() {{{ + __tostring = function(self) + return self._name + end + -- }}} +} +-- }}} + +-- private methods {{{ +-- set_basic_mode {{{ +-- +-- Sets a no-arg mode on a channel. +-- @name chan:set_basic_mode +-- @param self Channel object +-- @param set True to set the mode, false to unset it +-- @param letter Letter of the mode +local function set_basic_mode(self, set, letter) + if set then + irc.send("MODE", self.name, "+" .. letter) + else + irc.send("MODE", self.name, "-" .. letter) + end +end +-- }}} +-- }}} + +-- internal methods {{{ +-- TODO: is there a better way to do this? also, storing op/voice as initial +-- substrings of the username is just ugly +-- _add_user {{{ +-- +-- Add a user to the channel's internal user list. +-- @param self Channel object +-- @param user Nick of the user to add +-- @param mode Mode (op/voice) of the user, in symbolic form (@/+) +function _add_user(self, user, mode) + mode = mode or '' + self._members[user] = mode .. user +end +-- }}} + +-- _remove_user {{{ +-- +-- Remove a user from the channel's internal user list. +-- @param self Channel object +-- @param user Nick of the user to remove +function _remove_user(self, user) + self._members[user] = nil +end +-- }}} + +-- _change_status {{{ +-- +-- Change the op/voice status of a user in the channel's internal user list. +-- @param self Channel object +-- @param user Nick of the user to affect +-- @param on True if the mode is being set, false if it's being unset +-- @param mode 'o' for op, 'v' for voice +function _change_status(self, user, on, mode) + if on then + if mode == 'o' then + self._members[user] = '@' .. user + elseif mode == 'v' then + self._members[user] = '+' .. user + end + else + if (mode == 'o' and self._members[user]:sub(1, 1) == '@') or + (mode == 'v' and self._members[user]:sub(1, 1) == '+') then + self._members[user] = user + end + end +end +-- }}} + +-- _change_nick {{{ +-- +-- Change the nick of a user in the channel's internal user list. +-- @param self Channel object +-- @param old_nick User's old nick +-- @param new_nick User's new nick +function _change_nick(self, old_nick, new_nick) + for member in self:each_member() do + local member_nick = member:gsub('@+', '') + if member_nick == old_nick then + local mode = self._members[old_nick]:sub(1, 1) + if mode ~= '@' and mode ~= '+' then mode = "" end + self._members[old_nick] = nil + self._members[new_nick] = mode .. new_nick + break + end + end +end +-- }}} +-- }}} + +-- constructor {{{ +--- +-- Creates a new Channel object. +-- @param chan Name of the new channel +-- @return The new channel instance +function new(chan) + return base.setmetatable({_name = chan, _topic = {}, _chanmode = "", + _members = {}}, mt) +end +-- }}} + +-- public methods {{{ +-- iterators {{{ +-- each_op {{{ +--- +-- Iterator over the ops in the channel +-- @param self Channel object +function each_op(self) + return function(state, arg) + return misc._value_iter(state, arg, + function(v) + return v:sub(1, 1) == "@" + end) + end, + self._members, + nil +end +-- }}} + +-- each_voice {{{ +--- +-- Iterator over the voiced users in the channel +-- @param self Channel object +function each_voice(self) + return function(state, arg) + return misc._value_iter(state, arg, + function(v) + return v:sub(1, 1) == "+" + end) + end, + self._members, + nil +end +-- }}} + +-- each_user {{{ +--- +-- Iterator over the normal users in the channel +-- @param self Channel object +function each_user(self) + return function(state, arg) + return misc._value_iter(state, arg, + function(v) + return v:sub(1, 1) ~= "@" and + v:sub(1, 1) ~= "+" + end) + end, + self._members, + nil +end +-- }}} + +-- each_member {{{ +--- +-- Iterator over all users in the channel +-- @param self Channel object +function each_member(self) + return misc._value_iter, self._members, nil +end +-- }}} +-- }}} + +-- return tables of users {{{ +-- ops {{{ +--- +-- Gets an array of all the ops in the channel. +-- @param self Channel object +-- @return Array of channel ops +function ops(self) + local ret = {} + for nick in self:each_op() do + table.insert(ret, nick) + end + return ret +end +-- }}} + +-- voices {{{ +--- +-- Gets an array of all the voiced users in the channel. +-- @param self Channel object +-- @return Array of channel voiced users +function voices(self) + local ret = {} + for nick in self:each_voice() do + table.insert(ret, nick) + end + return ret +end +-- }}} + +-- users {{{ +--- +-- Gets an array of all the normal users in the channel. +-- @param self Channel object +-- @return Array of channel normal users +function users(self) + local ret = {} + for nick in self:each_user() do + table.insert(ret, nick) + end + return ret +end +-- }}} + +-- members {{{ +--- +-- Gets an array of all the users in the channel. +-- @param self Channel object +-- @return Array of channel users +function members(self) + local ret = {} + -- not just returning self._members, since the return value shouldn't be + -- modifiable + for nick in self:each_member() do + table.insert(ret, nick) + end + return ret +end +-- }}} +-- }}} + +-- setting modes {{{ +-- ban {{{ +-- TODO: hmmm, this probably needs an appropriate mask, rather than a nick +--- +-- Ban a user from a channel. +-- @param self Channel object +-- @param name User to ban +function ban(self, name) + irc.send("MODE", self.name, "+b", name) +end +-- }}} + +-- unban {{{ +-- TODO: same here +--- +-- Remove a ban on a user. +-- @param self Channel object +-- @param name User to unban +function unban(self, name) + irc.send("MODE", self.name, "-b", name) +end +-- }}} + +-- voice {{{ +--- +-- Give a user voice on a channel. +-- @param self Channel object +-- @param name User to give voice to +function voice(self, name) + irc.send("MODE", self.name, "+v", name) +end +-- }}} + +-- devoice {{{ +--- +-- Remove voice from a user. +-- @param self Channel object +-- @param name User to remove voice from +function devoice(self, name) + irc.send("MODE", self.name, "-v", name) +end +-- }}} + +-- op {{{ +--- +-- Give a user ops on a channel. +-- @param self Channel object +-- @param name User to op +function op(self, name) + irc.send("MODE", self.name, "+o", name) +end +-- }}} + +-- deop {{{ +--- +-- Remove ops from a user. +-- @param self Channel object +-- @param name User to remove ops from +function deop(self, name) + irc.send("MODE", self.name, "-o", name) +end +-- }}} + +-- set_limit {{{ +--- +-- Set a channel limit. +-- @param self Channel object +-- @param new_limit New value for the channel limit (optional; limit is unset +-- if this argument isn't passed) +function set_limit(self, new_limit) + if new_limit then + irc.send("MODE", self.name, "+l", new_limit) + else + irc.send("MODE", self.name, "-l") + end +end +-- }}} + +-- set_key {{{ +--- +-- Set a channel password. +-- @param self Channel object +-- @param key New channel password (optional; password is unset if this +-- argument isn't passed) +function set_key(self, key) + if key then + irc.send("MODE", self.name, "+k", key) + else + irc.send("MODE", self.name, "-k") + end +end +-- }}} + +-- set_private {{{ +--- +-- Set the private state of a channel. +-- @param self Channel object +-- @param set True to set the channel as private, false to unset it +function set_private(self, set) + set_basic_mode(self, set, "p") +end +-- }}} + +-- set_secret {{{ +--- +-- Set the secret state of a channel. +-- @param self Channel object +-- @param set True to set the channel as secret, false to unset it +function set_secret(self, set) + set_basic_mode(self, set, "s") +end +-- }}} + +-- set_invite_only {{{ +--- +-- Set whether joining the channel requires an invite. +-- @param self Channel object +-- @param set True to set the channel invite only, false to unset it +function set_invite_only(self, set) + set_basic_mode(self, set, "i") +end +-- }}} + +-- set_topic_lock {{{ +--- +-- If true, the topic can only be changed by an op. +-- @param self Channel object +-- @param set True to lock the topic, false to unlock it +function set_topic_lock(self, set) + set_basic_mode(self, set, "t") +end +-- }}} + +-- set_no_outside_messages {{{ +--- +-- If true, users must be in the channel to send messages to it. +-- @param self Channel object +-- @param set True to require users to be in the channel to send messages to +-- it, false to remove this restriction +function set_no_outside_messages(self, set) + set_basic_mode(self, set, "n") +end +-- }}} + +-- set moderated {{{ +--- +-- Set whether voice is required to speak. +-- @param self Channel object +-- @param set True to set the channel as moderated, false to unset it +function set_moderated(self, set) + set_basic_mode(self, set, "m") +end +-- }}} +-- }}} + +-- accessors {{{ +-- contains {{{ +--- +-- Test if a user is in the channel. +-- @param self Channel object +-- @param nick Nick to search for +-- @return True if the nick is in the channel, false otherwise +function contains(self, nick) + for member in self:each_member() do + local member_nick = member:gsub('@+', '') + if member_nick == nick then + return true + end + end + return false +end +-- }}} +-- }}} +-- }}} diff --git a/src/luairc/irc/constants.lua b/src/luairc/irc/constants.lua new file mode 100644 index 0000000..b26cecb --- /dev/null +++ b/src/luairc/irc/constants.lua @@ -0,0 +1,191 @@ +--- +-- This module holds various constants used by the IRC protocol. +module "irc.constants" + +-- protocol constants {{{ +IRC_MAX_MSG = 512 +-- }}} + +-- server replies {{{ +replies = { +-- Command responses {{{ + [001] = "RPL_WELCOME", + [002] = "RPL_YOURHOST", + [003] = "RPL_CREATED", + [004] = "RPL_MYINFO", + [005] = "RPL_BOUNCE", + [302] = "RPL_USERHOST", + [303] = "RPL_ISON", + [301] = "RPL_AWAY", + [305] = "RPL_UNAWAY", + [306] = "RPL_NOWAWAY", + [311] = "RPL_WHOISUSER", + [312] = "RPL_WHOISSERVER", + [313] = "RPL_WHOISOPERATOR", + [317] = "RPL_WHOISIDLE", + [318] = "RPL_ENDOFWHOIS", + [319] = "RPL_WHOISCHANNELS", + [314] = "RPL_WHOWASUSER", + [369] = "RPL_ENDOFWHOWAS", + [321] = "RPL_LISTSTART", + [322] = "RPL_LIST", + [323] = "RPL_LISTEND", + [325] = "RPL_UNIQOPIS", + [324] = "RPL_CHANNELMODEIS", + [331] = "RPL_NOTOPIC", + [332] = "RPL_TOPIC", + [341] = "RPL_INVITING", + [342] = "RPL_SUMMONING", + [346] = "RPL_INVITELIST", + [347] = "RPL_ENDOFINVITELIST", + [348] = "RPL_EXCEPTLIST", + [349] = "RPL_ENDOFEXCEPTLIST", + [351] = "RPL_VERSION", + [352] = "RPL_WHOREPLY", + [315] = "RPL_ENDOFWHO", + [353] = "RPL_NAMREPLY", + [366] = "RPL_ENDOFNAMES", + [364] = "RPL_LINKS", + [365] = "RPL_ENDOFLINKS", + [367] = "RPL_BANLIST", + [368] = "RPL_ENDOFBANLIST", + [371] = "RPL_INFO", + [374] = "RPL_ENDOFINFO", + [375] = "RPL_MOTDSTART", + [372] = "RPL_MOTD", + [376] = "RPL_ENDOFMOTD", + [381] = "RPL_YOUREOPER", + [382] = "RPL_REHASHING", + [383] = "RPL_YOURESERVICE", + [391] = "RPL_TIME", + [392] = "RPL_USERSSTART", + [393] = "RPL_USERS", + [394] = "RPL_ENDOFUSERS", + [395] = "RPL_NOUSERS", + [200] = "RPL_TRACELINK", + [201] = "RPL_TRACECONNECTING", + [202] = "RPL_TRACEHANDSHAKE", + [203] = "RPL_TRACEUNKNOWN", + [204] = "RPL_TRACEOPERATOR", + [205] = "RPL_TRACEUSER", + [206] = "RPL_TRACESERVER", + [207] = "RPL_TRACESERVICE", + [208] = "RPL_TRACENEWTYPE", + [209] = "RPL_TRACECLASS", + [210] = "RPL_TRACERECONNECT", + [261] = "RPL_TRACELOG", + [262] = "RPL_TRACEEND", + [211] = "RPL_STATSLINKINFO", + [212] = "RPL_STATSCOMMANDS", + [219] = "RPL_ENDOFSTATS", + [242] = "RPL_STATSUPTIME", + [243] = "RPL_STATSOLINE", + [221] = "RPL_UMODEIS", + [234] = "RPL_SERVLIST", + [235] = "RPL_SERVLISTEND", + [221] = "RPL_UMODEIS", + [251] = "RPL_LUSERCLIENT", + [252] = "RPL_LUSEROP", + [253] = "RPL_LUSERUNKNOWN", + [254] = "RPL_LUSERCHANNELS", + [255] = "RPL_LUSERME", + [256] = "RPL_ADMINME", + [257] = "RPL_ADMINLOC1", + [258] = "RPL_ADMINLOC2", + [259] = "RPL_ADMINEMAIL", + [263] = "RPL_TRYAGAIN", +-- }}} +-- Error codes {{{ + [401] = "ERR_NOSUCHNICK", -- No such nick/channel + [402] = "ERR_NOSUCHSERVER", -- No such server + [403] = "ERR_NOSUCHCHANNEL", -- No such channel + [404] = "ERR_CANNOTSENDTOCHAN", -- Cannot send to channel + [405] = "ERR_TOOMANYCHANNELS", -- You have joined too many channels + [406] = "ERR_WASNOSUCHNICK", -- There was no such nickname + [407] = "ERR_TOOMANYTARGETS", -- Duplicate recipients. No message delivered + [408] = "ERR_NOSUCHSERVICE", -- No such service + [409] = "ERR_NOORIGIN", -- No origin specified + [411] = "ERR_NORECIPIENT", -- No recipient given + [412] = "ERR_NOTEXTTOSEND", -- No text to send + [413] = "ERR_NOTOPLEVEL", -- No toplevel domain specified + [414] = "ERR_WILDTOPLEVEL", -- Wildcard in toplevel domain + [415] = "ERR_BADMASK", -- Bad server/host mask + [421] = "ERR_UNKNOWNCOMMAND", -- Unknown command + [422] = "ERR_NOMOTD", -- MOTD file is missing + [423] = "ERR_NOADMININFO", -- No administrative info available + [424] = "ERR_FILEERROR", -- File error + [431] = "ERR_NONICKNAMEGIVEN", -- No nickname given + [432] = "ERR_ERRONEUSNICKNAME", -- Erroneus nickname + [433] = "ERR_NICKNAMEINUSE", -- Nickname is already in use + [436] = "ERR_NICKCOLLISION", -- Nickname collision KILL + [437] = "ERR_UNAVAILRESOURCE", -- Nick/channel is temporarily unavailable + [441] = "ERR_USERNOTINCHANNEL", -- They aren't on that channel + [442] = "ERR_NOTONCHANNEL", -- You're not on that channel + [443] = "ERR_USERONCHANNEL", -- User is already on channel + [444] = "ERR_NOLOGIN", -- User not logged in + [445] = "ERR_SUMMONDISABLED", -- SUMMON has been disabled + [446] = "ERR_USERSDISABLED", -- USERS has been disabled + [451] = "ERR_NOTREGISTERED", -- You have not registered + [461] = "ERR_NEEDMOREPARAMS", -- Not enough parameters + [462] = "ERR_ALREADYREGISTERED", -- You may not reregister + [463] = "ERR_NOPERMFORHOST", -- Your host isn't among the privileged + [464] = "ERR_PASSWDMISMATCH", -- Password incorrect + [465] = "ERR_YOUREBANNEDCREEP", -- You are banned from this server + [466] = "ERR_YOUWILLBEBANNED", + [467] = "ERR_KEYSET", -- Channel key already set + [471] = "ERR_CHANNELISFULL", -- Cannot join channel (+l) + [472] = "ERR_UNKNOWNMODE", -- Unknown mode char + [473] = "ERR_INVITEONLYCHAN", -- Cannot join channel (+i) + [474] = "ERR_BANNEDFROMCHAN", -- Cannot join channel (+b) + [475] = "ERR_BADCHANNELKEY", -- Cannot join channel (+k) + [476] = "ERR_BADCHANMASK", -- Bad channel mask + [477] = "ERR_NOCHANMODES", -- Channel doesn't support modes + [478] = "ERR_BANLISTFULL", -- Channel list is full + [481] = "ERR_NOPRIVILEGES", -- Permission denied- You're not an IRC operator + [482] = "ERR_CHANOPRIVSNEEDED", -- You're not channel operator + [483] = "ERR_CANTKILLSERVER", -- You can't kill a server! + [484] = "ERR_RESTRICTED", -- Your connection is restricted! + [485] = "ERR_UNIQOPPRIVSNEEDED", -- You're not the original channel operator + [491] = "ERR_NOOPERHOST", -- No O-lines for your host + [501] = "ERR_UMODEUNKNOWNFLAG", -- Unknown MODE flag + [502] = "ERR_USERSDONTMATCH", -- Can't change mode for other users +-- }}} +-- unused {{{ + [231] = "RPL_SERVICEINFO", + [232] = "RPL_ENDOFSERVICES", + [233] = "RPL_SERVICE", + [300] = "RPL_NONE", + [316] = "RPL_WHOISCHANOP", + [361] = "RPL_KILLDONE", + [362] = "RPL_CLOSING", + [363] = "RPL_CLOSEEND", + [373] = "RPL_INFOSTART", + [384] = "RPL_MYPORTIS", + [213] = "RPL_STATSCLINE", + [214] = "RPL_STATSNLINE", + [215] = "RPL_STATSILINE", + [216] = "RPL_STATSKLINE", + [217] = "RPL_STATSQLINE", + [218] = "RPL_STATSYLINE", + [240] = "RPL_STATSVLINE", + [241] = "RPL_STATSLLINE", + [244] = "RPL_STATSHLINE", + [246] = "RPL_STATSPING", + [247] = "RPL_STATSBLINE", + [250] = "RPL_STATSDLINE", + [492] = "ERR_NOSERVICEHOST", +-- }}} +-- guesses {{{ + [333] = "RPL_TOPICDATE", -- date the topic was set, in seconds since the epoch + [505] = "ERR_NOTREGISTERED" -- freenode blocking privmsg from unreged users +-- }}} +} +-- }}} + +-- chanmodes {{{ +chanmodes = { + ["@"] = "secret", + ["*"] = "private", + ["="] = "public" +} +-- }}} diff --git a/src/luairc/irc/ctcp.lua b/src/luairc/irc/ctcp.lua new file mode 100644 index 0000000..c77cae8 --- /dev/null +++ b/src/luairc/irc/ctcp.lua @@ -0,0 +1,115 @@ +--- +-- Implementation of the CTCP protocol +-- initialization {{{ +local base = _G +local table = require "table" +-- }}} + +--- +-- This module implements the various quoting and escaping requirements of the +-- CTCP protocol. +module "irc.ctcp" + +-- internal functions {{{ +-- _low_quote {{{ +-- +-- Applies low level quoting to a string (escaping characters which are illegal +-- to appear in an IRC packet). +-- @param ... Strings to quote together, space separated +-- @return Quoted string +function _low_quote(...) + local str = table.concat({...}, " ") + return str:gsub("[%z\n\r\020]", {["\000"] = "\0200", + ["\n"] = "\020n", + ["\r"] = "\020r", + ["\020"] = "\020\020"}) +end +-- }}} + +-- _low_dequote {{{ +-- +-- Removes low level quoting done by low_quote. +-- @param str String with low level quoting applied to it +-- @return String with those quoting methods stripped off +function _low_dequote(str) + return str:gsub("\020(.?)", function(s) + if s == "0" then return "\000" end + if s == "n" then return "\n" end + if s == "r" then return "\r" end + if s == "\020" then return "\020" end + return "" + end) +end +-- }}} + +-- _ctcp_quote {{{ +-- +-- Applies CTCP quoting to a block of text which has been identified as CTCP +-- data (by the calling program). +-- @param ... Strings to apply CTCP quoting to together, space separated +-- @return String with CTCP quoting applied +function _ctcp_quote(...) + local str = table.concat({...}, " ") + local ret = str:gsub("[\001\\]", {["\001"] = "\\a", + ["\\"] = "\\\\"}) + return "\001" .. ret .. "\001" +end +-- }}} + +-- _ctcp_dequote {{{ +-- +-- Removes CTCP quoting from a block of text which has been identified as CTCP +-- data (likely by ctcp_split). +-- @param str String with CTCP quoting +-- @return String with all CTCP quoting stripped +function _ctcp_dequote(str) + local ret = str:gsub("^\001", ""):gsub("\001$", "") + return ret:gsub("\\(.?)", function(s) + if s == "a" then return "\001" end + if s == "\\" then return "\\" end + return "" + end) +end +-- }}} + +-- _ctcp_split {{{ +-- +-- Splits a low level dequoted string into normal text and unquoted CTCP +-- messages. +-- @param str Low level dequoted string +-- @return Array of tables, with each entry in the array corresponding to one +-- part of the split message. These tables will have these fields: +--
    +--
  • str: The text of the split section
  • +--
  • ctcp: True if the section was a CTCP message, false +-- otherwise
  • +--
+function _ctcp_split(str) + local ret = {} + local iter = 1 + while true do + local s, e = str:find("\001.*\001", iter) + + local plain_string, ctcp_string + if not s then + plain_string = str:sub(iter, -1) + else + plain_string = str:sub(iter, s - 1) + ctcp_string = str:sub(s, e) + end + + if plain_string ~= "" then + table.insert(ret, {str = plain_string, ctcp = false}) + end + if not s then break end + if ctcp_string ~= "" then + table.insert(ret, {str = _ctcp_dequote(ctcp_string), ctcp = true}) + end + + iter = e + 1 + end + + return ret +end +-- }}} +-- }}} diff --git a/src/luairc/irc/dcc.lua b/src/luairc/irc/dcc.lua new file mode 100644 index 0000000..6e8537e --- /dev/null +++ b/src/luairc/irc/dcc.lua @@ -0,0 +1,196 @@ +--- +-- Implementation of the DCC protocol +-- initialization {{{ +local base = _G +local irc = require 'irc' +local ctcp = require 'irc.ctcp' +local c = ctcp._ctcp_quote +local irc_debug = require 'irc.debug' +local misc = require 'irc.misc' +local socket = require 'socket' +local coroutine = require 'coroutine' +local io = require 'io' +local string = require 'string' +-- }}} + +--- +-- This module implements the DCC protocol. File transfers (DCC SEND) are +-- handled, but DCC CHAT is not, as of yet. +module 'irc.dcc' + +-- defaults {{{ +FIRST_PORT = 1028 +LAST_PORT = 5000 +-- }}} + +-- private functions {{{ +-- debug_dcc {{{ +-- +-- Prints a debug message about DCC events similar to irc.debug.warn, etc. +-- @param msg Debug message +local function debug_dcc(msg) + irc_debug._message("DCC", msg, "\027[0;32m") +end +-- }}} + +-- send_file {{{ +-- +-- Sends a file to a remote user, after that user has accepted our DCC SEND +-- invitation +-- @param sock Socket to send the file on +-- @param file Lua file object corresponding to the file we want to send +-- @param packet_size Size of the packets to send the file in +local function send_file(sock, file, packet_size) + local bytes = 0 + while true do + local packet = file:read(packet_size) + if not packet then break end + bytes = bytes + packet:len() + local index = 1 + while true do + local skip = false + sock:send(packet, index) + local new_bytes, err = sock:receive(4) + if not new_bytes then + if err == "timeout" then + skip = true + else + irc_debug._warn(err) + break + end + else + new_bytes = misc._int_to_str(new_bytes) + end + if not skip then + if new_bytes ~= bytes then + index = packet_size - bytes + new_bytes + 1 + else + break + end + end + end + coroutine.yield(true) + end + debug_dcc("File completely sent") + file:close() + sock:close() + irc._unregister_socket(sock, 'w') + return true +end +-- }}} + +-- handle_connect {{{ +-- +-- Handle the connection attempt by a remote user to get our file. Basically +-- just swaps out the server socket we were listening on for a client socket +-- that we can send data on +-- @param ssock Server socket that the remote user connected to +-- @param file Lua file object corresponding to the file we want to send +-- @param packet_size Size of the packets to send the file in +local function handle_connect(ssock, file, packet_size) + debug_dcc("Offer accepted, beginning to send") + packet_size = packet_size or 1024 + local sock = ssock:accept() + sock:settimeout(0.1) + ssock:close() + irc._unregister_socket(ssock, 'r') + irc._register_socket(sock, 'w', + coroutine.wrap(function(s) + return send_file(s, file, packet_size) + end)) + return true +end +-- }}} + +-- accept_file {{{ +-- +-- Accepts a file from a remote user which has offered it to us. +-- @param sock Socket to receive the file on +-- @param file Lua file object corresponding to the file we want to save +-- @param packet_size Size of the packets to receive the file in +local function accept_file(sock, file, packet_size) + local bytes = 0 + while true do + local packet, err, partial_packet = sock:receive(packet_size) + if not packet and err == "timeout" then packet = partial_packet end + if not packet then break end + if packet:len() == 0 then break end + bytes = bytes + packet:len() + sock:send(misc._str_to_int(bytes)) + file:write(packet) + coroutine.yield(true) + end + debug_dcc("File completely received") + file:close() + sock:close() + irc._unregister_socket(sock, 'r') + return true +end +-- }}} +-- }}} + +-- internal functions {{{ +-- _accept {{{ +-- +-- Accepts a file offer from a remote user. Called when the on_dcc callback +-- retuns true. +-- @param filename Name to save the file as +-- @param address IP address of the remote user in low level int form +-- @param port Port to connect to at the remote user +-- @param packet_size Size of the packets the remote user will be sending +function _accept(filename, address, port, packet_size) + debug_dcc("Accepting a DCC SEND request from " .. address .. ":" .. port) + packet_size = packet_size or 1024 + local sock = base.assert(socket.tcp()) + base.assert(sock:connect(address, port)) + sock:settimeout(0.1) + local file = base.assert(io.open(misc._get_unique_filename(filename), "w")) + irc._register_socket(sock, 'r', + coroutine.wrap(function(s) + return accept_file(s, file, packet_size) + end)) +end +-- }}} +-- }}} + +-- public functions {{{ +-- send {{{ +--- +-- Offers a file to a remote user. +-- @param nick User to offer the file to +-- @param filename Filename to offer +-- @param port Port to accept connections on (optional, defaults to +-- choosing an available port between FIRST_PORT and LAST_PORT +-- above) +function send(nick, filename, port) + port = port or FIRST_PORT + local sock + repeat + sock = base.assert(socket.tcp()) + err, msg = sock:bind('*', port) + port = port + 1 + until msg ~= "address already in use" and port <= LAST_PORT + 1 + port = port - 1 + base.assert(err, msg) + base.assert(sock:listen(1)) + local ip = misc._ip_str_to_int(irc.get_ip()) + local file, err = io.open(filename) + if not file then + irc_debug._warn(err) + sock:close() + return + end + local size = file:seek("end") + file:seek("set") + irc._register_socket(sock, 'r', + coroutine.wrap(function(s) + return handle_connect(s, file) + end)) + filename = misc._basename(filename) + if filename:find(" ") then filename = '"' .. filename .. '"' end + debug_dcc("Offering " .. filename .. " to " .. nick .. " from " .. + irc.get_ip() .. ":" .. port) + irc.send("PRIVMSG", nick, c("DCC", "SEND", filename, ip, port, size)) +end +-- }}} +-- }}} diff --git a/src/luairc/irc/debug.lua b/src/luairc/irc/debug.lua new file mode 100644 index 0000000..414b49d --- /dev/null +++ b/src/luairc/irc/debug.lua @@ -0,0 +1,92 @@ +--- +-- Basic debug output +-- initialization {{{ +local base = _G +local io = require 'io' +-- }}} + +--- +-- This module implements a few useful debug functions for use throughout the +-- rest of the code. +module 'irc.debug' + +-- defaults {{{ +COLOR = true +-- }}} + +-- local variables {{{ +local ON = false +local outfile = io.output() +-- }}} + +-- internal functions {{{ +-- _message {{{ +-- +-- Output a debug message. +-- @param msg_type Arbitrary string corresponding to the type of message +-- @param msg Message text +-- @param color Which terminal code to use for color output (defaults to +-- dark gray) +function _message(msg_type, msg, color) + if ON then + local endcolor = "" + if COLOR and outfile == io.stdout then + color = color or "\027[1;30m" + endcolor = "\027[0m" + else + color = "" + endcolor = "" + end + outfile:write(color .. msg_type .. ": " .. msg .. endcolor .. "\n") + end +end +-- }}} + +-- _err {{{ +-- +-- Signal an error. Writes the error message to the screen in red and calls +-- error(). +-- @param msg Error message +-- @see error +function _err(msg) + _message("ERR", msg, "\027[0;31m") + base.error(msg, 2) +end +-- }}} + +-- _warn {{{ +-- +-- Signal a warning. Writes the warning message to the screen in yellow. +-- @param msg Warning message +function _warn(msg) + _message("WARN", msg, "\027[0;33m") +end +-- }}} +-- }}} + +-- public functions {{{ +-- enable {{{ +--- +-- Turns on debug output. +function enable() + ON = true +end +-- }}} + +-- disable {{{ +--- +-- Turns off debug output. +function disable() + ON = false +end +-- }}} + +-- set_output {{{ +--- +-- Redirects output to a file rather than stdout. +-- @param file File to write debug output to +function set_output(file) + outfile = base.assert(io.open(file)) +end +-- }}} +-- }}} diff --git a/src/luairc/irc/message.lua b/src/luairc/irc/message.lua new file mode 100644 index 0000000..e05e87e --- /dev/null +++ b/src/luairc/irc/message.lua @@ -0,0 +1,69 @@ +--- +-- Implementation of IRC server message parsing +-- initialization {{{ +local base = _G +local constants = require 'irc.constants' +local ctcp = require 'irc.ctcp' +local irc_debug = require 'irc.debug' +local misc = require 'irc.misc' +local socket = require 'socket' +local string = require 'string' +local table = require 'table' +-- }}} + +--- +-- This module contains parsing functions for IRC server messages. +module 'irc.message' + +-- internal functions {{{ +-- _parse {{{ +-- +-- Parse a server command. +-- @param str Command to parse +-- @return Table containing the parsed message. It contains: +--
    +--
  • from: The source of this message, in full usermask +-- form (nick!user@host) for messages originating +-- from users, and as a hostname for messages from +-- servers
  • +--
  • command: The command sent, in name form if possible, +-- otherwise as a numeric code
  • +--
  • args: Array of strings corresponding to the arguments +-- to the received command
  • +-- +--
+function _parse(str) + -- low-level ctcp quoting {{{ + str = ctcp._low_dequote(str) + -- }}} + -- parse the from field, if it exists (leading :) {{{ + local from = "" + if str:sub(1, 1) == ":" then + local e + e, from = socket.skip(1, str:find("^:([^ ]*) ")) + str = str:sub(e + 1) + end + -- }}} + -- get the command name or numerical reply value {{{ + local command, argstr = socket.skip(2, str:find("^([^ ]*) ?(.*)")) + local reply = false + if command:find("^%d%d%d$") then + reply = true + if constants.replies[base.tonumber(command)] then + command = constants.replies[base.tonumber(command)] + else + irc_debug._warn("Unknown server reply: " .. command) + end + end + -- }}} + -- get the args {{{ + local args = misc._split(argstr, " ", ":") + -- the first arg in a reply is always your nick + if reply then table.remove(args, 1) end + -- }}} + -- return the parsed message {{{ + return {from = from, command = command, args = args} + -- }}} +end +-- }}} +-- }}} diff --git a/src/luairc/irc/misc.lua b/src/luairc/irc/misc.lua new file mode 100644 index 0000000..92c3ac4 --- /dev/null +++ b/src/luairc/irc/misc.lua @@ -0,0 +1,303 @@ +--- +-- Various useful functions that didn't fit anywhere else +-- initialization {{{ +local base = _G +local irc_debug = require 'irc.debug' +local socket = require 'socket' +local math = require 'math' +local os = require 'os' +local string = require 'string' +local table = require 'table' +-- }}} + +--- +-- This module contains various useful functions which didn't fit in any of the +-- other modules. +module 'irc.misc' + +-- defaults {{{ +DELIM = ' ' +PATH_SEP = '/' +ENDIANNESS = "big" +INT_BYTES = 4 +-- }}} + +-- private functions {{{ +-- +-- Check for existence of a file. This returns true if renaming a file to +-- itself succeeds. This isn't ideal (I think anyway) but it works here, and +-- lets me not have to bring in LFS as a dependency. +-- @param filename File to check for existence +-- @return True if the file exists, false otherwise +local function exists(filename) + local _, err = os.rename(filename, filename) + if not err then return true end + return not err:find("No such file or directory") +end +-- }}} + +-- internal functions {{{ +-- _split {{{ +-- +-- Splits str into substrings based on several options. +-- @param str String to split +-- @param delim String of characters to use as the beginning of substring +-- delimiter +-- @param end_delim String of characters to use as the end of substring +-- delimiter +-- @param lquotes String of characters to use as opening quotes (quoted strings +-- in str will be considered one substring) +-- @param rquotes String of characters to use as closing quotes +-- @return Array of strings, one for each substring that was separated out +function _split(str, delim, end_delim, lquotes, rquotes) + -- handle arguments {{{ + delim = "["..(delim or DELIM).."]" + if end_delim then end_delim = "["..end_delim.."]" end + if lquotes then lquotes = "["..lquotes.."]" end + if rquotes then rquotes = "["..rquotes.."]" end + local optdelim = delim .. "?" + -- }}} + + local ret = {} + local instring = false + while str:len() > 0 do + -- handle case for not currently in a string {{{ + if not instring then + local end_delim_ind, lquote_ind, delim_ind + if end_delim then end_delim_ind = str:find(optdelim..end_delim) end + if lquotes then lquote_ind = str:find(optdelim..lquotes) end + local delim_ind = str:find(delim) + if not end_delim_ind then end_delim_ind = str:len() + 1 end + if not lquote_ind then lquote_ind = str:len() + 1 end + if not delim_ind then delim_ind = str:len() + 1 end + local next_ind = math.min(end_delim_ind, lquote_ind, delim_ind) + if next_ind == str:len() + 1 then + table.insert(ret, str) + break + elseif next_ind == end_delim_ind then + -- TODO: hackish here + if str:sub(next_ind, next_ind) == end_delim:gsub('[%[%]]', '') then + table.insert(ret, str:sub(next_ind + 1)) + else + table.insert(ret, str:sub(1, next_ind - 1)) + table.insert(ret, str:sub(next_ind + 2)) + end + break + elseif next_ind == lquote_ind then + table.insert(ret, str:sub(1, next_ind - 1)) + str = str:sub(next_ind + 2) + instring = true + else -- last because the top two contain it + table.insert(ret, str:sub(1, next_ind - 1)) + str = str:sub(next_ind + 1) + end + -- }}} + -- handle case for currently in a string {{{ + else + local endstr = str:find(rquotes..optdelim) + table.insert(ret, str:sub(1, endstr - 1)) + str = str:sub(endstr + 2) + instring = false + end + -- }}} + end + return ret +end +-- }}} + +-- _basename {{{ +-- +-- Returns the basename of a file (the part after the last directory separator). +-- @param path Path to the file +-- @param sep Directory separator (optional, defaults to PATH_SEP) +-- @return The basename of the file +function _basename(path, sep) + sep = sep or PATH_SEP + if not path:find(sep) then return path end + return socket.skip(2, path:find(".*" .. sep .. "(.*)")) +end +-- }}} + +-- _dirname {{{ +-- +-- Returns the dirname of a file (the part before the last directory separator). +-- @param path Path to the file +-- @param sep Directory separator (optional, defaults to PATH_SEP) +-- @return The dirname of the file +function _dirname(path, sep) + sep = sep or PATH_SEP + if not path:find(sep) then return "." end + return socket.skip(2, path:find("(.*)" .. sep .. ".*")) +end +-- }}} + +-- _str_to_int {{{ +-- +-- Converts a number to a low-level int. +-- @param str String representation of the int +-- @param bytes Number of bytes in an int (defaults to INT_BYTES) +-- @param endian Which endianness to use (big, little, host, network) (defaultsi +-- to ENDIANNESS) +-- @return A string whose first INT_BYTES characters make a low-level int +function _str_to_int(str, bytes, endian) + bytes = bytes or INT_BYTES + endian = endian or ENDIANNESS + local ret = "" + for i = 0, bytes - 1 do + local new_byte = string.char(math.fmod(str / (2^(8 * i)), 256)) + if endian == "big" or endian == "network" then ret = new_byte .. ret + else ret = ret .. new_byte + end + end + return ret +end +-- }}} + +-- _int_to_str {{{ +-- +-- Converts a low-level int to a number. +-- @param int String whose bytes correspond to the bytes of a low-level int +-- @param endian Endianness of the int argument (defaults to ENDIANNESS) +-- @return String representation of the low-level int argument +function _int_to_str(int, endian) + endian = endian or ENDIANNESS + local ret = 0 + for i = 1, int:len() do + if endian == "big" or endian == "network" then ind = int:len() - i + 1 + else ind = i + end + ret = ret + string.byte(int:sub(ind, ind)) * 2^(8 * (i - 1)) + end + return ret +end +-- }}} + +-- _ip_str_to_int {{{ +-- TODO: handle endianness here +-- +-- Converts a string IP address to a low-level int. +-- @param ip_str String representation of an IP address +-- @return Low-level int representation of that IP address +function _ip_str_to_int(ip_str) + local i = 3 + local ret = 0 + for num in ip_str:gmatch("%d+") do + ret = ret + num * 2^(i * 8) + i = i - 1 + end + return ret +end +-- }}} + +-- _ip_int_to_str {{{ +-- TODO: handle endianness here +-- +-- Converts an int to a string IP address. +-- @param ip_int Low-level int representation of an IP address +-- @return String representation of that IP address +function _ip_int_to_str(ip_int) + local ip = {} + for i = 3, 0, -1 do + local new_num = math.floor(ip_int / 2^(i * 8)) + table.insert(ip, new_num) + ip_int = ip_int - new_num * 2^(i * 8) + end + return table.concat(ip, ".") +end +-- }}} + +-- _get_unique_filename {{{ +-- +-- Returns a unique filename. +-- @param filename Filename to start with +-- @return Filename (same as the one we started with, except possibly with some +-- numbers appended) which does not currently exist on the filesystem +function _get_unique_filename(filename) + if not exists(filename) then return filename end + + local count = 1 + while true do + if not exists(filename .. "." .. count) then + return filename .. "." .. count + end + count = count + 1 + end +end +-- }}} + +-- _try_call {{{ +-- +-- Call a function, if it exists. +-- @param fn Function to try to call +-- @param ... Arguments to fn +-- @return The return values of fn, if it was successfully called +function _try_call(fn, ...) + if base.type(fn) == "function" then + return fn(...) + end +end +-- }}} + +-- _try_call_warn {{{ +-- +-- Same as try_call, but complain if the function doesn't exist. +-- @param msg Warning message to use if the function doesn't exist +-- @param fn Function to try to call +-- @param ... Arguments to fn +-- @return The return values of fn, if it was successfully called +function _try_call_warn(msg, fn, ...) + if base.type(fn) == "function" then + return fn(...) + else + irc_debug._warn(msg) + end +end +-- }}} + +-- _value_iter {{{ +-- +-- Iterator to iterate over just the values of a table. +function _value_iter(state, arg, pred) + for k, v in base.pairs(state) do + if arg == v then arg = k end + end + local key, val = base.next(state, arg) + if not key then return end + + if base.type(pred) == "function" then + while not pred(val) do + key, val = base.next(state, key) + if not key then return end + end + end + return val +end +-- }}} + +-- _parse_user {{{ +-- +-- Gets the various parts of a full username. +-- @param user A usermask (i.e. returned in the from field of a callback) +-- @return nick +-- @return username (if it exists) +-- @return hostname (if it exists) +function _parse_user(user) + local found, bang, nick = user:find("^([^!]*)!") + if found then + user = user:sub(bang + 1) + else + return user + end + local found, equals = user:find("^.=") + if found then + user = user:sub(3) + end + local found, at, username = user:find("^([^@]*)@") + if found then + return nick, username, user:sub(at + 1) + else + return nick, user + end +end +-- }}} +-- }}} diff --git a/src/luasocket/CMakeLists.txt b/src/luasocket/CMakeLists.txt new file mode 100644 index 0000000..48c2c17 --- /dev/null +++ b/src/luasocket/CMakeLists.txt @@ -0,0 +1,50 @@ + +# :mode=cmake:noTabs=true:tabSize=4: + +set(TO_SOCKET_SHARE + http.lua + url.lua + tp.lua + ftp.lua + smtp.lua +) + +set(TO_TOP_SHARE + compat51.lua + ltn12.lua + socket.lua + mime.lua +) + +set(LUASOCKET_SRCS + compat51.c + luasocket.c + timeout.c + buffer.c + io.c + auxiliar.c + options.c + inet.c + tcp.c + udp.c + except.c + select.c + usocket.c + buffer.c + auxiliar.c + options.c + timeout.c + io.c + usocket.c + unix.c + mime.c +) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +add_library(luasocket_lib MODULE ${LUASOCKET_SRCS}) +set_target_properties(luasocket_lib + PROPERTIES + OUTPUT_NAME luasocket + COMPILE_FLAGS "-Wall -Werror" +) diff --git a/src/luasocket/auxiliar.c b/src/luasocket/auxiliar.c new file mode 100644 index 0000000..9514970 --- /dev/null +++ b/src/luasocket/auxiliar.c @@ -0,0 +1,149 @@ +/*=========================================================================*\ +* Auxiliar routines for class hierarchy manipulation +* LuaSocket toolkit +* +* RCS ID: $Id: auxiliar.c,v 1.14 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include +#include + +#include "auxiliar.h" + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes the module +\*-------------------------------------------------------------------------*/ +int auxiliar_open(lua_State *L) { + (void) L; + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Creates a new class with given methods +* Methods whose names start with __ are passed directly to the metatable. +\*-------------------------------------------------------------------------*/ +void auxiliar_newclass(lua_State *L, const char *classname, luaL_reg *func) { + luaL_newmetatable(L, classname); /* mt */ + /* create __index table to place methods */ + lua_pushstring(L, "__index"); /* mt,"__index" */ + lua_newtable(L); /* mt,"__index",it */ + /* put class name into class metatable */ + lua_pushstring(L, "class"); /* mt,"__index",it,"class" */ + lua_pushstring(L, classname); /* mt,"__index",it,"class",classname */ + lua_rawset(L, -3); /* mt,"__index",it */ + /* pass all methods that start with _ to the metatable, and all others + * to the index table */ + for (; func->name; func++) { /* mt,"__index",it */ + lua_pushstring(L, func->name); + lua_pushcfunction(L, func->func); + lua_rawset(L, func->name[0] == '_' ? -5: -3); + } + lua_rawset(L, -3); /* mt */ + lua_pop(L, 1); +} + +/*-------------------------------------------------------------------------*\ +* Prints the value of a class in a nice way +\*-------------------------------------------------------------------------*/ +int auxiliar_tostring(lua_State *L) { + char buf[32]; + if (!lua_getmetatable(L, 1)) goto error; + lua_pushstring(L, "__index"); + lua_gettable(L, -2); + if (!lua_istable(L, -1)) goto error; + lua_pushstring(L, "class"); + lua_gettable(L, -2); + if (!lua_isstring(L, -1)) goto error; + sprintf(buf, "%p", lua_touserdata(L, 1)); + lua_pushfstring(L, "%s: %s", lua_tostring(L, -1), buf); + return 1; +error: + lua_pushstring(L, "invalid object passed to 'auxiliar.c:__tostring'"); + lua_error(L); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Insert class into group +\*-------------------------------------------------------------------------*/ +void auxiliar_add2group(lua_State *L, const char *classname, const char *groupname) { + luaL_getmetatable(L, classname); + lua_pushstring(L, groupname); + lua_pushboolean(L, 1); + lua_rawset(L, -3); + lua_pop(L, 1); +} + +/*-------------------------------------------------------------------------*\ +* Make sure argument is a boolean +\*-------------------------------------------------------------------------*/ +int auxiliar_checkboolean(lua_State *L, int objidx) { + if (!lua_isboolean(L, objidx)) + luaL_typerror(L, objidx, lua_typename(L, LUA_TBOOLEAN)); + return lua_toboolean(L, objidx); +} + +/*-------------------------------------------------------------------------*\ +* Return userdata pointer if object belongs to a given class, abort with +* error otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) { + void *data = auxiliar_getclassudata(L, classname, objidx); + if (!data) { + char msg[45]; + sprintf(msg, "%.35s expected", classname); + luaL_argerror(L, objidx, msg); + } + return data; +} + +/*-------------------------------------------------------------------------*\ +* Return userdata pointer if object belongs to a given group, abort with +* error otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) { + void *data = auxiliar_getgroupudata(L, groupname, objidx); + if (!data) { + char msg[45]; + sprintf(msg, "%.35s expected", groupname); + luaL_argerror(L, objidx, msg); + } + return data; +} + +/*-------------------------------------------------------------------------*\ +* Set object class +\*-------------------------------------------------------------------------*/ +void auxiliar_setclass(lua_State *L, const char *classname, int objidx) { + luaL_getmetatable(L, classname); + if (objidx < 0) objidx--; + lua_setmetatable(L, objidx); +} + +/*-------------------------------------------------------------------------*\ +* Get a userdata pointer if object belongs to a given group. Return NULL +* otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) { + if (!lua_getmetatable(L, objidx)) + return NULL; + lua_pushstring(L, groupname); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { + lua_pop(L, 2); + return NULL; + } else { + lua_pop(L, 2); + return lua_touserdata(L, objidx); + } +} + +/*-------------------------------------------------------------------------*\ +* Get a userdata pointer if object belongs to a given class. Return NULL +* otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) { + return luaL_checkudata(L, objidx, classname); +} diff --git a/src/luasocket/auxiliar.h b/src/luasocket/auxiliar.h new file mode 100644 index 0000000..18b8495 --- /dev/null +++ b/src/luasocket/auxiliar.h @@ -0,0 +1,48 @@ +#ifndef AUXILIAR_H +#define AUXILIAR_H +/*=========================================================================*\ +* Auxiliar routines for class hierarchy manipulation +* LuaSocket toolkit (but completely independent of other LuaSocket modules) +* +* A LuaSocket class is a name associated with Lua metatables. A LuaSocket +* group is a name associated with a class. A class can belong to any number +* of groups. This module provides the functionality to: +* +* - create new classes +* - add classes to groups +* - set the class of objects +* - check if an object belongs to a given class or group +* - get the userdata associated to objects +* - print objects in a pretty way +* +* LuaSocket class names follow the convention {}. Modules +* can define any number of classes and groups. The module tcp.c, for +* example, defines the classes tcp{master}, tcp{client} and tcp{server} and +* the groups tcp{client,server} and tcp{any}. Module functions can then +* perform type-checking on their arguments by either class or group. +* +* LuaSocket metatables define the __index metamethod as being a table. This +* table has one field for each method supported by the class, and a field +* "class" with the class name. +* +* The mapping from class name to the corresponding metatable and the +* reverse mapping are done using lauxlib. +* +* RCS ID: $Id: auxiliar.h,v 1.9 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ + +#include "lua.h" +#include "lauxlib.h" + +int auxiliar_open(lua_State *L); +void auxiliar_newclass(lua_State *L, const char *classname, luaL_reg *func); +void auxiliar_add2group(lua_State *L, const char *classname, const char *group); +void auxiliar_setclass(lua_State *L, const char *classname, int objidx); +void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx); +void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx); +void *auxiliar_getclassudata(lua_State *L, const char *groupname, int objidx); +void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx); +int auxiliar_checkboolean(lua_State *L, int objidx); +int auxiliar_tostring(lua_State *L); + +#endif /* AUXILIAR_H */ diff --git a/src/luasocket/buffer.c b/src/luasocket/buffer.c new file mode 100644 index 0000000..388315f --- /dev/null +++ b/src/luasocket/buffer.c @@ -0,0 +1,263 @@ +/*=========================================================================*\ +* Input/Output interface for Lua programs +* LuaSocket toolkit +* +* RCS ID: $Id: buffer.c,v 1.27 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" +#include "lauxlib.h" + +#include "buffer.h" + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b); +static int recvline(p_buffer buf, luaL_Buffer *b); +static int recvall(p_buffer buf, luaL_Buffer *b); +static int buffer_get(p_buffer buf, const char **data, size_t *count); +static void buffer_skip(p_buffer buf, size_t count); +static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent); + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int buffer_open(lua_State *L) { + (void) L; + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Initializes C structure +\*-------------------------------------------------------------------------*/ +void buffer_init(p_buffer buf, p_io io, p_timeout tm) { + buf->first = buf->last = 0; + buf->io = io; + buf->tm = tm; + buf->received = buf->sent = 0; + buf->birthday = timeout_gettime(); +} + +/*-------------------------------------------------------------------------*\ +* object:getstats() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_getstats(lua_State *L, p_buffer buf) { + lua_pushnumber(L, buf->received); + lua_pushnumber(L, buf->sent); + lua_pushnumber(L, timeout_gettime() - buf->birthday); + return 3; +} + +/*-------------------------------------------------------------------------*\ +* object:setstats() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_setstats(lua_State *L, p_buffer buf) { + buf->received = (long) luaL_optnumber(L, 2, buf->received); + buf->sent = (long) luaL_optnumber(L, 3, buf->sent); + if (lua_isnumber(L, 4)) buf->birthday = timeout_gettime() - lua_tonumber(L, 4); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* object:send() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_send(lua_State *L, p_buffer buf) { + int top = lua_gettop(L); + /*p_timeout tm = timeout_markstart(buf->tm);*/ + int err = IO_DONE; + size_t size = 0, sent = 0; + const char *data = luaL_checklstring(L, 2, &size); + long start = (long) luaL_optnumber(L, 3, 1); + long end = (long) luaL_optnumber(L, 4, -1); + if (start < 0) start = (long) (size+start+1); + if (end < 0) end = (long) (size+end+1); + if (start < 1) start = (long) 1; + if (end > (long) size) end = (long) size; + if (start <= end) err = sendraw(buf, data+start-1, end-start+1, &sent); + /* check if there was an error */ + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, buf->io->error(buf->io->ctx, err)); + lua_pushnumber(L, sent+start-1); + } else { + lua_pushnumber(L, sent+start-1); + lua_pushnil(L); + lua_pushnil(L); + } +#ifdef LUASOCKET_DEBUG + /* push time elapsed during operation as the last return value */ + lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); +#endif + return lua_gettop(L) - top; +} + +/*-------------------------------------------------------------------------*\ +* object:receive() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_receive(lua_State *L, p_buffer buf) { + int err = IO_DONE, top = lua_gettop(L); + /*p_timeout tm = timeout_markstart(buf->tm);*/ + luaL_Buffer b; + size_t size; + const char *part = luaL_optlstring(L, 3, "", &size); + /* initialize buffer with optional extra prefix + * (useful for concatenating previous partial results) */ + luaL_buffinit(L, &b); + luaL_addlstring(&b, part, size); + /* receive new patterns */ + if (!lua_isnumber(L, 2)) { + const char *p= luaL_optstring(L, 2, "*l"); + if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b); + else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b); + else luaL_argcheck(L, 0, 2, "invalid receive pattern"); + /* get a fixed number of bytes (minus what was already partially + * received) */ + } else err = recvraw(buf, (size_t) lua_tonumber(L, 2)-size, &b); + /* check if there was an error */ + if (err != IO_DONE) { + /* we can't push anyting in the stack before pushing the + * contents of the buffer. this is the reason for the complication */ + luaL_pushresult(&b); + lua_pushstring(L, buf->io->error(buf->io->ctx, err)); + lua_pushvalue(L, -2); + lua_pushnil(L); + lua_replace(L, -4); + } else { + luaL_pushresult(&b); + lua_pushnil(L); + lua_pushnil(L); + } +#ifdef LUASOCKET_DEBUG + /* push time elapsed during operation as the last return value */ + lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); +#endif + return lua_gettop(L) - top; +} + +/*-------------------------------------------------------------------------*\ +* Determines if there is any data in the read buffer +\*-------------------------------------------------------------------------*/ +int buffer_isempty(p_buffer buf) { + return buf->first >= buf->last; +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Sends a block of data (unbuffered) +\*-------------------------------------------------------------------------*/ +#define STEPSIZE 8192 +static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) { + p_io io = buf->io; + p_timeout tm = buf->tm; + size_t total = 0; + int err = IO_DONE; + while (total < count && err == IO_DONE) { + size_t done; + size_t step = (count-total <= STEPSIZE)? count-total: STEPSIZE; + err = io->send(io->ctx, data+total, step, &done, tm); + total += done; + } + *sent = total; + buf->sent += total; + return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads a fixed number of bytes (buffered) +\*-------------------------------------------------------------------------*/ +static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) { + int err = IO_DONE; + size_t total = 0; + while (total < wanted && err == IO_DONE) { + size_t count; const char *data; + err = buffer_get(buf, &data, &count); + count = MIN(count, wanted - total); + luaL_addlstring(b, data, count); + buffer_skip(buf, count); + total += count; + } + return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads everything until the connection is closed (buffered) +\*-------------------------------------------------------------------------*/ +static int recvall(p_buffer buf, luaL_Buffer *b) { + int err = IO_DONE; + while (err == IO_DONE) { + const char *data; size_t count; + err = buffer_get(buf, &data, &count); + luaL_addlstring(b, data, count); + buffer_skip(buf, count); + } + if (err == IO_CLOSED) return IO_DONE; + else return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF +* are not returned by the function and are discarded from the buffer +\*-------------------------------------------------------------------------*/ +static int recvline(p_buffer buf, luaL_Buffer *b) { + int err = IO_DONE; + while (err == IO_DONE) { + size_t count, pos; const char *data; + err = buffer_get(buf, &data, &count); + pos = 0; + while (pos < count && data[pos] != '\n') { + /* we ignore all \r's */ + if (data[pos] != '\r') luaL_putchar(b, data[pos]); + pos++; + } + if (pos < count) { /* found '\n' */ + buffer_skip(buf, pos+1); /* skip '\n' too */ + break; /* we are done */ + } else /* reached the end of the buffer */ + buffer_skip(buf, pos); + } + return err; +} + +/*-------------------------------------------------------------------------*\ +* Skips a given number of bytes from read buffer. No data is read from the +* transport layer +\*-------------------------------------------------------------------------*/ +static void buffer_skip(p_buffer buf, size_t count) { + buf->received += count; + buf->first += count; + if (buffer_isempty(buf)) + buf->first = buf->last = 0; +} + +/*-------------------------------------------------------------------------*\ +* Return any data available in buffer, or get more data from transport layer +* if buffer is empty +\*-------------------------------------------------------------------------*/ +static int buffer_get(p_buffer buf, const char **data, size_t *count) { + int err = IO_DONE; + p_io io = buf->io; + p_timeout tm = buf->tm; + if (buffer_isempty(buf)) { + size_t got; + err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm); + buf->first = 0; + buf->last = got; + } + *count = buf->last - buf->first; + *data = buf->data + buf->first; + return err; +} diff --git a/src/luasocket/buffer.h b/src/luasocket/buffer.h new file mode 100644 index 0000000..baf93ca --- /dev/null +++ b/src/luasocket/buffer.h @@ -0,0 +1,47 @@ +#ifndef BUF_H +#define BUF_H +/*=========================================================================*\ +* Input/Output interface for Lua programs +* LuaSocket toolkit +* +* Line patterns require buffering. Reading one character at a time involves +* too many system calls and is very slow. This module implements the +* LuaSocket interface for input/output on connected objects, as seen by +* Lua programs. +* +* Input is buffered. Output is *not* buffered because there was no simple +* way of making sure the buffered output data would ever be sent. +* +* The module is built on top of the I/O abstraction defined in io.h and the +* timeout management is done with the timeout.h interface. +* +* RCS ID: $Id: buffer.h,v 1.12 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +#include "io.h" +#include "timeout.h" + +/* buffer size in bytes */ +#define BUF_SIZE 8192 + +/* buffer control structure */ +typedef struct t_buffer_ { + double birthday; /* throttle support info: creation time, */ + size_t sent, received; /* bytes sent, and bytes received */ + p_io io; /* IO driver used for this buffer */ + p_timeout tm; /* timeout management for this buffer */ + size_t first, last; /* index of first and last bytes of stored data */ + char data[BUF_SIZE]; /* storage space for buffer data */ +} t_buffer; +typedef t_buffer *p_buffer; + +int buffer_open(lua_State *L); +void buffer_init(p_buffer buf, p_io io, p_timeout tm); +int buffer_meth_send(lua_State *L, p_buffer buf); +int buffer_meth_receive(lua_State *L, p_buffer buf); +int buffer_meth_getstats(lua_State *L, p_buffer buf); +int buffer_meth_setstats(lua_State *L, p_buffer buf); +int buffer_isempty(p_buffer buf); + +#endif /* BUF_H */ diff --git a/src/luasocket/compat51.c b/src/luasocket/compat51.c new file mode 100644 index 0000000..38d7bdf --- /dev/null +++ b/src/luasocket/compat51.c @@ -0,0 +1,97 @@ +/* +** Compat-5.1 +** Copyright Kepler Project 2004-2005 (http://www.keplerproject.org/compat) +** $Id: compat-5.1.c,v 1.12 2005/07/08 18:25:52 carregal Exp $ +*/ + +#include +#include +#include "lua.h" +#include "lauxlib.h" +#include "compat51.h" + +static void getfield(lua_State *L, int idx, const char *name) { + const char *end = strchr(name, '.'); + lua_pushvalue(L, idx); + while (end) { + lua_pushlstring(L, name, end - name); + lua_gettable(L, -2); + lua_remove(L, -2); + if (lua_isnil(L, -1)) return; + name = end+1; + end = strchr(name, '.'); + } + lua_pushstring(L, name); + lua_gettable(L, -2); + lua_remove(L, -2); +} + +static void setfield(lua_State *L, int idx, const char *name) { + const char *end = strchr(name, '.'); + lua_pushvalue(L, idx); + while (end) { + lua_pushlstring(L, name, end - name); + lua_gettable(L, -2); + /* create table if not found */ + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_pushlstring(L, name, end - name); + lua_pushvalue(L, -2); + lua_settable(L, -4); + } + lua_remove(L, -2); + name = end+1; + end = strchr(name, '.'); + } + lua_pushstring(L, name); + lua_pushvalue(L, -3); + lua_settable(L, -3); + lua_pop(L, 2); +} + +LUALIB_API void luaL_module(lua_State *L, const char *libname, + const luaL_reg *l, int nup) { + if (libname) { + getfield(L, LUA_GLOBALSINDEX, libname); /* check whether lib already exists */ + if (lua_isnil(L, -1)) { + int env, ns; + lua_pop(L, 1); /* get rid of nil */ + lua_pushliteral(L, "require"); + lua_gettable(L, LUA_GLOBALSINDEX); /* look for require */ + lua_getfenv(L, -1); /* getfenv(require) */ + lua_remove(L, -2); /* remove function require */ + env = lua_gettop(L); + + lua_newtable(L); /* create namespace for lib */ + ns = lua_gettop(L); + getfield(L, env, "package.loaded"); /* get package.loaded table */ + if (lua_isnil(L, -1)) { /* create package.loaded table */ + lua_pop(L, 1); /* remove previous result */ + lua_newtable(L); + lua_pushvalue(L, -1); + setfield(L, env, "package.loaded"); + } + else if (!lua_istable(L, -1)) + luaL_error(L, "name conflict for library `%s'", libname); + lua_pushstring(L, libname); + lua_pushvalue(L, ns); + lua_settable(L, -3); /* package.loaded[libname] = ns */ + lua_pop(L, 1); /* get rid of package.loaded table */ + lua_pushvalue(L, ns); /* copy namespace */ + setfield(L, LUA_GLOBALSINDEX, libname); + lua_remove (L, env); /* remove env */ + } + lua_insert(L, -(nup+1)); /* move library table to below upvalues */ + } + for (; l->name; l++) { + int i; + lua_pushstring(L, l->name); + for (i=0; ifunc, nup); + lua_settable(L, -(nup+3)); + } + lua_pop(L, nup); /* remove upvalues */ +} + diff --git a/src/luasocket/compat51.h b/src/luasocket/compat51.h new file mode 100644 index 0000000..815fcbb --- /dev/null +++ b/src/luasocket/compat51.h @@ -0,0 +1,13 @@ +/* +** Compat-5.1 +** Copyright Kepler Project 2004-2005 (http://www.keplerproject.org/compat/) +** $Id: compat-5.1.h,v 1.7 2005/07/08 18:25:52 carregal Exp $ +*/ + +#ifndef COMPAT_H + +LUALIB_API void luaL_module(lua_State *L, const char *libname, + const luaL_reg *l, int nup); +#define luaL_openlib luaL_module + +#endif diff --git a/src/luasocket/compat51.lua b/src/luasocket/compat51.lua new file mode 100644 index 0000000..602df05 --- /dev/null +++ b/src/luasocket/compat51.lua @@ -0,0 +1,235 @@ +-- +-- Compat-5.1 +-- Copyright Kepler Project 2004-2005 (http://www.keplerproject.org/compat) +-- According to Lua 5.1 +-- $Id: compat-5.1.lua,v 1.19 2005/07/05 19:12:00 tomas Exp $ +-- + +_COMPAT51 = "Compat-5.1 R4" + +local LUA_DIRSEP = '/' +local LUA_OFSEP = '_' +local OLD_LUA_OFSEP = '' +local POF = 'luaopen_' + +local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type +local format, gfind, gsub = string.format, string.gfind, string.gsub + +-- +-- avoid overwriting the package table if it's already there +-- +package = package or {} + +package.path = LUA_PATH or os.getenv("LUA_PATH") or + ("./?.lua;" .. + "/usr/local/share/lua/5.0/?.lua;" .. + "/usr/local/share/lua/5.0/?/?.lua;" .. + "/usr/local/share/lua/5.0/?/init.lua" ) + +package.cpath = os.getenv("LUA_CPATH") or + "./?.so;" .. + "./l?.so;" .. + "/usr/local/lib/lua/5.0/?.so;" .. + "/usr/local/lib/lua/5.0/l?.so" + +-- +-- make sure require works with standard libraries +-- +package.loaded = package.loaded or {} +package.loaded.string = string +package.loaded.math = math +package.loaded.io = io +package.loaded.os = os +package.loaded.table = table +package.loaded.base = _G +package.loaded.coroutine = coroutine + +-- +-- avoid overwriting the package.preload table if it's already there +-- +package.preload = package.preload or {} + + +-- +-- auxiliar function to read "nested globals" +-- +local function getfield (t, f) + assert (type(f)=="string", "not a valid field name ("..tostring(f)..")") + for w in gfind(f, "[%w_]+") do + if not t then return nil end + t = rawget(t, w) + end + return t +end + + +-- +-- auxiliar function to write "nested globals" +-- +local function setfield (t, f, v) + for w in gfind(f, "([%w_]+)%.") do + t[w] = t[w] or {} -- create table if absent + t = t[w] -- get the table + end + local w = gsub(f, "[%w_]+%.", "") -- get last field name + t[w] = v -- do the assignment +end + + +-- +-- looks for a file `name' in given path +-- +local function search (path, name) + for c in gfind(path, "[^;]+") do + c = gsub(c, "%?", name) + local f = io.open(c) + if f then -- file exist? + f:close() + return c + end + end + return nil -- file not found +end + + +-- +-- check whether library is already loaded +-- +local function loader_preload (name) + assert (type(name) == "string", format ( + "bad argument #1 to `require' (string expected, got %s)", type(name))) + if type(package.preload) ~= "table" then + error ("`package.preload' must be a table") + end + return package.preload[name] +end + + +-- +-- C library loader +-- +local function loader_C (name) + assert (type(name) == "string", format ( + "bad argument #1 to `require' (string expected, got %s)", type(name))) + local fname = gsub (name, "%.", LUA_DIRSEP) + fname = search (package.cpath, fname) + if not fname then + return false + end + local funcname = POF .. gsub (name, "%.", LUA_OFSEP) + local f, err = loadlib (fname, funcname) + if not f then + funcname = POF .. gsub (name, "%.", OLD_LUA_OFSEP) + f, err = loadlib (fname, funcname) + if not f then + error (format ("error loading package `%s' (%s)", name, err)) + end + end + return f +end + + +-- +-- Lua library loader +-- +local function loader_Lua (name) + assert (type(name) == "string", format ( + "bad argument #1 to `require' (string expected, got %s)", type(name))) + local path = LUA_PATH + if not path then + path = assert (package.path, "`package.path' must be a string") + end + local fname = gsub (name, "%.", LUA_DIRSEP) + fname = search (path, fname) + if not fname then + return false + end + local f, err = loadfile (fname) + if not f then + error (format ("error loading package `%s' (%s)", name, err)) + end + return f +end + + +-- create `loaders' table +package.loaders = package.loaders or { loader_preload, loader_C, loader_Lua, } + + +-- +-- iterate over available loaders +-- +local function load (name, loaders) + -- iterate over available loaders + assert (type (loaders) == "table", "`package.loaders' must be a table") + for i, loader in ipairs (loaders) do + local f = loader (name) + if f then + return f + end + end + error (format ("package `%s' not found", name)) +end + + +-- +-- new require +-- +function _G.require (name) + assert (type(name) == "string", format ( + "bad argument #1 to `require' (string expected, got %s)", type(name))) + local p = loaded[name] -- is it there? + if p then + return p + end + -- first mark it as loaded + loaded[name] = true + -- load and run init function + local actual_arg = _G.arg + _G.arg = { name } + local res = load(name, loaders)(name) + if res then + loaded[name] = res -- store result + end + _G.arg = actual_arg + -- return value should be in loaded[name] + return loaded[name] +end + + +-- +-- new module function +-- +function _G.module (name) + local _G = getfenv(0) -- simulate C function environment + local ns = getfield(_G, name) -- search for namespace + if not ns then + ns = {} -- create new namespace + setfield(_G, name, ns) + elseif type(ns) ~= "table" then + error("name conflict for module `"..name.."'") + end + if not ns._NAME then + ns._NAME = name + ns._M = ns + ns._PACKAGE = gsub(name, "[^.]*$", "") + end + setmetatable(ns, {__index = _G}) + loaded[name] = ns + setfenv(2, ns) + return ns +end + + +-- +-- define functions' environments +-- +local env = { + loaded = package.loaded, + loaders = package.loaders, + package = package, + _G = _G, +} +for i, f in ipairs { _G.module, _G.require, load, loader_preload, loader_C, loader_Lua, } do + setfenv (f, env) +end diff --git a/src/luasocket/except.c b/src/luasocket/except.c new file mode 100644 index 0000000..5faa5be --- /dev/null +++ b/src/luasocket/except.c @@ -0,0 +1,99 @@ +/*=========================================================================*\ +* Simple exception support +* LuaSocket toolkit +* +* RCS ID: $Id: except.c,v 1.8 2005/09/29 06:11:41 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "except.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int global_protect(lua_State *L); +static int global_newtry(lua_State *L); +static int protected_(lua_State *L); +static int finalize(lua_State *L); +static int do_nothing(lua_State *L); + +/* except functions */ +static luaL_reg func[] = { + {"newtry", global_newtry}, + {"protect", global_protect}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Try factory +\*-------------------------------------------------------------------------*/ +static void wrap(lua_State *L) { + lua_newtable(L); + lua_pushnumber(L, 1); + lua_pushvalue(L, -3); + lua_settable(L, -3); + lua_insert(L, -2); + lua_pop(L, 1); +} + +static int finalize(lua_State *L) { + if (!lua_toboolean(L, 1)) { + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pcall(L, 0, 0, 0); + lua_settop(L, 2); + wrap(L); + lua_error(L); + return 0; + } else return lua_gettop(L); +} + +static int do_nothing(lua_State *L) { + (void) L; + return 0; +} + +static int global_newtry(lua_State *L) { + lua_settop(L, 1); + if (lua_isnil(L, 1)) lua_pushcfunction(L, do_nothing); + lua_pushcclosure(L, finalize, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Protect factory +\*-------------------------------------------------------------------------*/ +static int unwrap(lua_State *L) { + if (lua_istable(L, -1)) { + lua_pushnumber(L, 1); + lua_gettable(L, -2); + lua_pushnil(L); + lua_insert(L, -2); + return 1; + } else return 0; +} + +static int protected_(lua_State *L) { + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + if (lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0) != 0) { + if (unwrap(L)) return 2; + else lua_error(L); + return 0; + } else return lua_gettop(L); +} + +static int global_protect(lua_State *L) { + lua_pushcclosure(L, protected_, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Init module +\*-------------------------------------------------------------------------*/ +int except_open(lua_State *L) { + luaL_openlib(L, NULL, func, 0); + return 0; +} diff --git a/src/luasocket/except.h b/src/luasocket/except.h new file mode 100644 index 0000000..81efb29 --- /dev/null +++ b/src/luasocket/except.h @@ -0,0 +1,35 @@ +#ifndef EXCEPT_H +#define EXCEPT_H +/*=========================================================================*\ +* Exception control +* LuaSocket toolkit (but completely independent from other modules) +* +* This provides support for simple exceptions in Lua. During the +* development of the HTTP/FTP/SMTP support, it became aparent that +* error checking was taking a substantial amount of the coding. These +* function greatly simplify the task of checking errors. +* +* The main idea is that functions should return nil as its first return +* value when it finds an error, and return an error message (or value) +* following nil. In case of success, as long as the first value is not nil, +* the other values don't matter. +* +* The idea is to nest function calls with the "try" function. This function +* checks the first value, and calls "error" on the second if the first is +* nil. Otherwise, it returns all values it received. +* +* The protect function returns a new function that behaves exactly like the +* function it receives, but the new function doesn't throw exceptions: it +* returns nil followed by the error message instead. +* +* With these two function, it's easy to write functions that throw +* exceptions on error, but that don't interrupt the user script. +* +* RCS ID: $Id: except.h,v 1.2 2005/09/29 06:11:41 diego Exp $ +\*=========================================================================*/ + +#include "lua.h" + +int except_open(lua_State *L); + +#endif diff --git a/src/luasocket/ftp.lua b/src/luasocket/ftp.lua new file mode 100644 index 0000000..1ddc77d --- /dev/null +++ b/src/luasocket/ftp.lua @@ -0,0 +1,280 @@ +----------------------------------------------------------------------------- +-- FTP support for the Lua language +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: ftp.lua,v 1.42 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local table = require("table") +local string = require("string") +local math = require("math") +local socket = require("socket") +local url = require("socket.url") +local tp = require("socket.tp") +local ltn12 = require("ltn12") +module("socket.ftp") + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- timeout in seconds before the program gives up on a connection +TIMEOUT = 60 +-- default port for ftp service +PORT = 21 +-- this is the default anonymous password. used when no password is +-- provided in url. should be changed to your e-mail. +USER = "ftp" +PASSWORD = "anonymous@anonymous.org" + +----------------------------------------------------------------------------- +-- Low level FTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function open(server, port, create) + local tp = socket.try(tp.connect(server, port or PORT, create, TIMEOUT)) + local f = base.setmetatable({ tp = tp }, metat) + -- make sure everything gets closed in an exception + f.try = socket.newtry(function() f:close() end) + return f +end + +function metat.__index:portconnect() + self.try(self.server:settimeout(TIMEOUT)) + self.data = self.try(self.server:accept()) + self.try(self.data:settimeout(TIMEOUT)) +end + +function metat.__index:pasvconnect() + self.data = self.try(socket.tcp()) + self.try(self.data:settimeout(TIMEOUT)) + self.try(self.data:connect(self.pasvt.ip, self.pasvt.port)) +end + +function metat.__index:login(user, password) + self.try(self.tp:command("user", user or USER)) + local code, reply = self.try(self.tp:check{"2..", 331}) + if code == 331 then + self.try(self.tp:command("pass", password or PASSWORD)) + self.try(self.tp:check("2..")) + end + return 1 +end + +function metat.__index:pasv() + self.try(self.tp:command("pasv")) + local code, reply = self.try(self.tp:check("2..")) + local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" + local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) + self.try(a and b and c and d and p1 and p2, reply) + self.pasvt = { + ip = string.format("%d.%d.%d.%d", a, b, c, d), + port = p1*256 + p2 + } + if self.server then + self.server:close() + self.server = nil + end + return self.pasvt.ip, self.pasvt.port +end + +function metat.__index:port(ip, port) + self.pasvt = nil + if not ip then + ip, port = self.try(self.tp:getcontrol():getsockname()) + self.server = self.try(socket.bind(ip, 0)) + ip, port = self.try(self.server:getsockname()) + self.try(server:settimeout(TIMEOUT)) + end + local pl = math.mod(port, 256) + local ph = (port - pl)/256 + local arg = string.gsub(string.format("%s,%d,%d", ip, ph, pl), "%.", ",") + self.try(self.tp:command("port", arg)) + self.try(self.tp:check("2..")) + return 1 +end + +function metat.__index:send(sendt) + self.try(self.pasvt or self.server, "need port or pasv first") + -- if there is a pasvt table, we already sent a PASV command + -- we just get the data connection into self.data + if self.pasvt then self:pasvconnect() end + -- get the transfer argument and command + local argument = sendt.argument or + url.unescape(string.gsub(sendt.path or "", "^[/\\]", "")) + if argument == "" then argument = nil end + local command = sendt.command or "stor" + -- send the transfer command and check the reply + self.try(self.tp:command(command, argument)) + local code, reply = self.try(self.tp:check{"2..", "1.."}) + -- if there is not a a pasvt table, then there is a server + -- and we already sent a PORT command + if not self.pasvt then self:portconnect() end + -- get the sink, source and step for the transfer + local step = sendt.step or ltn12.pump.step + local checkstep = function(src, snk) + -- check status in control connection while downloading + local readyt = socket.select(readt, nil, 0) + if readyt[tp] then self.try(self.tp:check("2..")) end + return step(src, snk) + end + local sink = socket.sink("close-when-done", self.data) + -- transfer all data and check error + self.try(ltn12.pump.all(sendt.source, sink, checkstep)) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + -- done with data connection + self.data:close() + -- find out how many bytes were sent + local sent = socket.skip(1, self.data:getstats()) + self.data = nil + return sent +end + +function metat.__index:receive(recvt) + self.try(self.pasvt or self.server, "need port or pasv first") + if self.pasvt then self:pasvconnect() end + local argument = recvt.argument or + url.unescape(string.gsub(recvt.path or "", "^[/\\]", "")) + if argument == "" then argument = nil end + local command = recvt.command or "retr" + self.try(self.tp:command(command, argument)) + local code = self.try(self.tp:check{"1..", "2.."}) + if not self.pasvt then self:portconnect() end + local source = socket.source("until-closed", self.data) + local step = recvt.step or ltn12.pump.step + self.try(ltn12.pump.all(source, recvt.sink, step)) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + self.data:close() + self.data = nil + return 1 +end + +function metat.__index:cwd(dir) + self.try(self.tp:command("cwd", dir)) + self.try(self.tp:check(250)) + return 1 +end + +function metat.__index:type(type) + self.try(self.tp:command("type", type)) + self.try(self.tp:check(200)) + return 1 +end + +function metat.__index:greet() + local code = self.try(self.tp:check{"1..", "2.."}) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + return 1 +end + +function metat.__index:quit() + self.try(self.tp:command("quit")) + self.try(self.tp:check("2..")) + return 1 +end + +function metat.__index:close() + if self.data then self.data:close() end + if self.server then self.server:close() end + return self.tp:close() +end + +----------------------------------------------------------------------------- +-- High level FTP API +----------------------------------------------------------------------------- +function override(t) + if t.url then + u = url.parse(t.url) + for i,v in base.pairs(t) do + u[i] = v + end + return u + else return t end +end + +local function tput(putt) + putt = override(putt) + socket.try(putt.host, "missing hostname") + local f = open(putt.host, putt.port, putt.create) + f:greet() + f:login(putt.user, putt.password) + if putt.type then f:type(putt.type) end + f:pasv() + local sent = f:send(putt) + f:quit() + f:close() + return sent +end + +local default = { + path = "/", + scheme = "ftp" +} + +local function parse(u) + local t = socket.try(url.parse(u, default)) + socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'") + socket.try(t.host, "missing hostname") + local pat = "^type=(.)$" + if t.params then + t.type = socket.skip(2, string.find(t.params, pat)) + socket.try(t.type == "a" or t.type == "i", + "invalid type '" .. t.type .. "'") + end + return t +end + +local function sput(u, body) + local putt = parse(u) + putt.source = ltn12.source.string(body) + return tput(putt) +end + +put = socket.protect(function(putt, body) + if base.type(putt) == "string" then return sput(putt, body) + else return tput(putt) end +end) + +local function tget(gett) + gett = override(gett) + socket.try(gett.host, "missing hostname") + local f = open(gett.host, gett.port, gett.create) + f:greet() + f:login(gett.user, gett.password) + if gett.type then f:type(gett.type) end + f:pasv() + f:receive(gett) + f:quit() + return f:close() +end + +local function sget(u) + local gett = parse(u) + local t = {} + gett.sink = ltn12.sink.table(t) + tget(gett) + return table.concat(t) +end + +command = socket.protect(function(cmdt) + cmdt = override(cmdt) + socket.try(cmdt.host, "missing hostname") + socket.try(cmdt.command, "missing command") + local f = open(cmdt.host, cmdt.port, cmdt.create) + f:greet() + f:login(cmdt.user, cmdt.password) + f.try(f.tp:command(cmdt.command, cmdt.argument)) + if cmdt.check then f.try(f.tp:check(cmdt.check)) end + f:quit() + return f:close() +end) + +get = socket.protect(function(gett) + if base.type(gett) == "string" then return sget(gett) + else return tget(gett) end +end) + diff --git a/src/luasocket/http.lua b/src/luasocket/http.lua new file mode 100644 index 0000000..a448508 --- /dev/null +++ b/src/luasocket/http.lua @@ -0,0 +1,326 @@ +----------------------------------------------------------------------------- +-- HTTP/1.1 client support for the Lua language. +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: http.lua,v 1.63 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +------------------------------------------------------------------------------- +local socket = require("socket") +local url = require("socket.url") +local ltn12 = require("ltn12") +local mime = require("mime") +local string = require("string") +local base = _G +local table = require("table") +module("socket.http") + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- connection timeout in seconds +TIMEOUT = 60 +-- default port for document retrieval +PORT = 80 +-- user agent field sent in request +USERAGENT = socket._VERSION + +----------------------------------------------------------------------------- +-- Reads MIME headers from a connection, unfolding where needed +----------------------------------------------------------------------------- +local function receiveheaders(sock, headers) + local line, name, value, err + headers = headers or {} + -- get first line + line, err = sock:receive() + if err then return nil, err end + -- headers go until a blank line is found + while line ~= "" do + -- get field-name and value + name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) + if not (name and value) then return nil, "malformed reponse headers" end + name = string.lower(name) + -- get next line (value might be folded) + line, err = sock:receive() + if err then return nil, err end + -- unfold any folded values + while string.find(line, "^%s") do + value = value .. line + line = sock:receive() + if err then return nil, err end + end + -- save pair in table + if headers[name] then headers[name] = headers[name] .. ", " .. value + else headers[name] = value end + end + return headers +end + +----------------------------------------------------------------------------- +-- Extra sources and sinks +----------------------------------------------------------------------------- +socket.sourcet["http-chunked"] = function(sock, headers) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + -- get chunk size, skip extention + local line, err = sock:receive() + if err then return nil, err end + local size = base.tonumber(string.gsub(line, ";.*", ""), 16) + if not size then return nil, "invalid chunk size" end + -- was it the last chunk? + if size > 0 then + -- if not, get chunk and skip terminating CRLF + local chunk, err, part = sock:receive(size) + if chunk then sock:receive() end + return chunk, err + else + -- if it was, read trailers into headers table + headers, err = receiveheaders(sock, headers) + if not headers then return nil, err end + end + end + }) +end + +socket.sinkt["http-chunked"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if not chunk then return sock:send("0\r\n\r\n") end + local size = string.format("%X\r\n", string.len(chunk)) + return sock:send(size .. chunk .. "\r\n") + end + }) +end + +----------------------------------------------------------------------------- +-- Low level HTTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function open(host, port, create) + -- create socket with user connect function, or with default + local c = socket.try(create or socket.tcp)() + local h = base.setmetatable({ c = c }, metat) + -- create finalized try + h.try = socket.newtry(function() h:close() end) + -- set timeout before connecting + h.try(c:settimeout(TIMEOUT)) + h.try(c:connect(host, port or PORT)) + -- here everything worked + return h +end + +function metat.__index:sendrequestline(method, uri) + local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) + return self.try(self.c:send(reqline)) +end + +function metat.__index:sendheaders(headers) + local h = "\r\n" + for i, v in base.pairs(headers) do + h = i .. ": " .. v .. "\r\n" .. h + end + self.try(self.c:send(h)) + return 1 +end + +function metat.__index:sendbody(headers, source, step) + source = source or ltn12.source.empty() + step = step or ltn12.pump.step + -- if we don't know the size in advance, send chunked and hope for the best + local mode = "http-chunked" + if headers["content-length"] then mode = "keep-open" end + return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) +end + +function metat.__index:receivestatusline() + local status = self.try(self.c:receive()) + local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) + return self.try(base.tonumber(code), status) +end + +function metat.__index:receiveheaders() + return self.try(receiveheaders(self.c)) +end + +function metat.__index:receivebody(headers, sink, step) + sink = sink or ltn12.sink.null() + step = step or ltn12.pump.step + local length = base.tonumber(headers["content-length"]) + local t = headers["transfer-encoding"] -- shortcut + local mode = "default" -- connection close + if t and t ~= "identity" then mode = "http-chunked" + elseif base.tonumber(headers["content-length"]) then mode = "by-length" end + return self.try(ltn12.pump.all(socket.source(mode, self.c, length), + sink, step)) +end + +function metat.__index:close() + return self.c:close() +end + +----------------------------------------------------------------------------- +-- High level HTTP API +----------------------------------------------------------------------------- +local function adjusturi(reqt) + local u = reqt + -- if there is a proxy, we need the full url. otherwise, just a part. + if not reqt.proxy and not PROXY then + u = { + path = socket.try(reqt.path, "invalid path 'nil'"), + params = reqt.params, + query = reqt.query, + fragment = reqt.fragment + } + end + return url.build(u) +end + +local function adjustproxy(reqt) + local proxy = reqt.proxy or PROXY + if proxy then + proxy = url.parse(proxy) + return proxy.host, proxy.port or 3128 + else + return reqt.host, reqt.port + end +end + +local function adjustheaders(headers, host) + -- default headers + local lower = { + ["user-agent"] = USERAGENT, + ["host"] = host, + ["connection"] = "close, TE", + ["te"] = "trailers" + } + -- override with user headers + for i,v in base.pairs(headers or lower) do + lower[string.lower(i)] = v + end + return lower +end + +-- default url parts +local default = { + host = "", + port = PORT, + path ="/", + scheme = "http" +} + +local function adjustrequest(reqt) + -- parse url if provided + local nreqt = reqt.url and url.parse(reqt.url, default) or {} + local t = url.parse(reqt.url, default) + -- explicit components override url + for i,v in base.pairs(reqt) do nreqt[i] = v end + socket.try(nreqt.host, "invalid host '" .. base.tostring(nreqt.host) .. "'") + -- compute uri if user hasn't overriden + nreqt.uri = reqt.uri or adjusturi(nreqt) + -- ajust host and port if there is a proxy + nreqt.host, nreqt.port = adjustproxy(nreqt) + -- adjust headers in request + nreqt.headers = adjustheaders(nreqt.headers, nreqt.host) + return nreqt +end + +local function shouldredirect(reqt, code, headers) + return headers.location and + string.gsub(headers.location, "%s", "") ~= "" and + (reqt.redirect ~= false) and + (code == 301 or code == 302) and + (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") + and (not reqt.nredirects or reqt.nredirects < 5) +end + +local function shouldauthorize(reqt, code) + -- if there has been an authorization attempt, it must have failed + if reqt.headers and reqt.headers["authorization"] then return nil end + -- if last attempt didn't fail due to lack of authentication, + -- or we don't have authorization information, we can't retry + return code == 401 and reqt.user and reqt.password +end + +local function shouldreceivebody(reqt, code) + if reqt.method == "HEAD" then return nil end + if code == 204 or code == 304 then return nil end + if code >= 100 and code < 200 then return nil end + return 1 +end + +-- forward declarations +local trequest, tauthorize, tredirect + +function tauthorize(reqt) + local auth = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) + reqt.headers["authorization"] = auth + return trequest(reqt) +end + +function tredirect(reqt, location) + local result, code, headers, status = trequest { + -- the RFC says the redirect URL has to be absolute, but some + -- servers do not respect that + url = url.absolute(reqt, location), + source = reqt.source, + sink = reqt.sink, + headers = reqt.headers, + proxy = reqt.proxy, + nredirects = (reqt.nredirects or 0) + 1, + connect = reqt.connect + } + -- pass location header back as a hint we redirected + headers.location = headers.location or location + return result, code, headers, status +end + +function trequest(reqt) + reqt = adjustrequest(reqt) + local h = open(reqt.host, reqt.port, reqt.create) + h:sendrequestline(reqt.method, reqt.uri) + h:sendheaders(reqt.headers) + if reqt.source then h:sendbody(reqt.headers, reqt.source, reqt.step) end + local code, headers, status + code, status = h:receivestatusline() + headers = h:receiveheaders() + if shouldredirect(reqt, code, headers) then + h:close() + return tredirect(reqt, headers.location) + elseif shouldauthorize(reqt, code) then + h:close() + return tauthorize(reqt) + elseif shouldreceivebody(reqt, code) then + h:receivebody(headers, reqt.sink, reqt.step) + end + h:close() + return 1, code, headers, status +end + +local function srequest(u, body) + local t = {} + local reqt = { + url = u, + sink = ltn12.sink.table(t) + } + if body then + reqt.source = ltn12.source.string(body) + reqt.headers = { ["content-length"] = string.len(body) } + reqt.method = "POST" + end + local code, headers, status = socket.skip(1, trequest(reqt)) + return table.concat(t), code, headers, status +end + +request = socket.protect(function(reqt, body) + if base.type(reqt) == "string" then return srequest(reqt, body) + else return trequest(reqt) end +end) diff --git a/src/luasocket/inet.c b/src/luasocket/inet.c new file mode 100644 index 0000000..f2cddee --- /dev/null +++ b/src/luasocket/inet.c @@ -0,0 +1,281 @@ +/*=========================================================================*\ +* Internet domain functions +* LuaSocket toolkit +* +* RCS ID: $Id: inet.c,v 1.28 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "inet.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int inet_global_toip(lua_State *L); +static int inet_global_tohostname(lua_State *L); +static void inet_pushresolved(lua_State *L, struct hostent *hp); +static int inet_global_gethostname(lua_State *L); + +/* DNS functions */ +static luaL_reg func[] = { + { "toip", inet_global_toip }, + { "tohostname", inet_global_tohostname }, + { "gethostname", inet_global_gethostname}, + { NULL, NULL} +}; + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int inet_open(lua_State *L) +{ + lua_pushstring(L, "dns"); + lua_newtable(L); + luaL_openlib(L, NULL, func, 0); + lua_settable(L, -3); + return 0; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_gethost(const char *address, struct hostent **hp) { + struct in_addr addr; + if (inet_aton(address, &addr)) + return socket_gethostbyaddr((char *) &addr, sizeof(addr), hp); + else + return socket_gethostbyname(address, hp); +} + +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_global_tohostname(lua_State *L) { + const char *address = luaL_checkstring(L, 1); + struct hostent *hp = NULL; + int err = inet_gethost(address, &hp); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_hoststrerror(err)); + return 2; + } + lua_pushstring(L, hp->h_name); + inet_pushresolved(L, hp); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_global_toip(lua_State *L) +{ + const char *address = luaL_checkstring(L, 1); + struct hostent *hp = NULL; + int err = inet_gethost(address, &hp); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_hoststrerror(err)); + return 2; + } + lua_pushstring(L, inet_ntoa(*((struct in_addr *) hp->h_addr))); + inet_pushresolved(L, hp); + return 2; +} + + +/*-------------------------------------------------------------------------*\ +* Gets the host name +\*-------------------------------------------------------------------------*/ +static int inet_global_gethostname(lua_State *L) +{ + char name[257]; + name[256] = '\0'; + if (gethostname(name, 256) < 0) { + lua_pushnil(L); + lua_pushstring(L, "gethostname failed"); + return 2; + } else { + lua_pushstring(L, name); + return 1; + } +} + + + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Retrieves socket peer name +\*-------------------------------------------------------------------------*/ +int inet_meth_getpeername(lua_State *L, p_socket ps) +{ + struct sockaddr_in peer; + socklen_t peer_len = sizeof(peer); + if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, "getpeername failed"); + } else { + lua_pushstring(L, inet_ntoa(peer.sin_addr)); + lua_pushnumber(L, ntohs(peer.sin_port)); + } + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Retrieves socket local name +\*-------------------------------------------------------------------------*/ +int inet_meth_getsockname(lua_State *L, p_socket ps) +{ + struct sockaddr_in local; + socklen_t local_len = sizeof(local); + if (getsockname(*ps, (SA *) &local, &local_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, "getsockname failed"); + } else { + lua_pushstring(L, inet_ntoa(local.sin_addr)); + lua_pushnumber(L, ntohs(local.sin_port)); + } + return 2; +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Passes all resolver information to Lua as a table +\*-------------------------------------------------------------------------*/ +static void inet_pushresolved(lua_State *L, struct hostent *hp) +{ + char **alias; + struct in_addr **addr; + int i, resolved; + lua_newtable(L); resolved = lua_gettop(L); + lua_pushstring(L, "name"); + lua_pushstring(L, hp->h_name); + lua_settable(L, resolved); + lua_pushstring(L, "ip"); + lua_pushstring(L, "alias"); + i = 1; + alias = hp->h_aliases; + lua_newtable(L); + if (alias) { + while (*alias) { + lua_pushnumber(L, i); + lua_pushstring(L, *alias); + lua_settable(L, -3); + i++; alias++; + } + } + lua_settable(L, resolved); + i = 1; + lua_newtable(L); + addr = (struct in_addr **) hp->h_addr_list; + if (addr) { + while (*addr) { + lua_pushnumber(L, i); + lua_pushstring(L, inet_ntoa(**addr)); + lua_settable(L, -3); + i++; addr++; + } + } + lua_settable(L, resolved); +} + +/*-------------------------------------------------------------------------*\ +* Tries to create a new inet socket +\*-------------------------------------------------------------------------*/ +const char *inet_trycreate(p_socket ps, int type) { + return socket_strerror(socket_create(ps, AF_INET, type, 0)); +} + +/*-------------------------------------------------------------------------*\ +* Tries to connect to remote address (address, port) +\*-------------------------------------------------------------------------*/ +const char *inet_tryconnect(p_socket ps, const char *address, + unsigned short port, p_timeout tm) +{ + struct sockaddr_in remote; + int err; + memset(&remote, 0, sizeof(remote)); + remote.sin_family = AF_INET; + remote.sin_port = htons(port); + if (strcmp(address, "*")) { + if (!inet_aton(address, &remote.sin_addr)) { + struct hostent *hp = NULL; + struct in_addr **addr; + err = socket_gethostbyname(address, &hp); + if (err != IO_DONE) return socket_hoststrerror(err); + addr = (struct in_addr **) hp->h_addr_list; + memcpy(&remote.sin_addr, *addr, sizeof(struct in_addr)); + } + } else remote.sin_family = AF_UNSPEC; + err = socket_connect(ps, (SA *) &remote, sizeof(remote), tm); + return socket_strerror(err); +} + +/*-------------------------------------------------------------------------*\ +* Tries to bind socket to (address, port) +\*-------------------------------------------------------------------------*/ +const char *inet_trybind(p_socket ps, const char *address, unsigned short port) +{ + struct sockaddr_in local; + int err; + memset(&local, 0, sizeof(local)); + /* address is either wildcard or a valid ip address */ + local.sin_addr.s_addr = htonl(INADDR_ANY); + local.sin_port = htons(port); + local.sin_family = AF_INET; + if (strcmp(address, "*") && !inet_aton(address, &local.sin_addr)) { + struct hostent *hp = NULL; + struct in_addr **addr; + err = socket_gethostbyname(address, &hp); + if (err != IO_DONE) return socket_hoststrerror(err); + addr = (struct in_addr **) hp->h_addr_list; + memcpy(&local.sin_addr, *addr, sizeof(struct in_addr)); + } + err = socket_bind(ps, (SA *) &local, sizeof(local)); + if (err != IO_DONE) socket_destroy(ps); + return socket_strerror(err); +} + +/*-------------------------------------------------------------------------*\ +* Some systems do not provide this so that we provide our own. It's not +* marvelously fast, but it works just fine. +\*-------------------------------------------------------------------------*/ +#ifdef INET_ATON +int inet_aton(const char *cp, struct in_addr *inp) +{ + unsigned int a = 0, b = 0, c = 0, d = 0; + int n = 0, r; + unsigned long int addr = 0; + r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n); + if (r == 0 || n == 0) return 0; + cp += n; + if (*cp) return 0; + if (a > 255 || b > 255 || c > 255 || d > 255) return 0; + if (inp) { + addr += a; addr <<= 8; + addr += b; addr <<= 8; + addr += c; addr <<= 8; + addr += d; + inp->s_addr = htonl(addr); + } + return 1; +} +#endif + + diff --git a/src/luasocket/inet.h b/src/luasocket/inet.h new file mode 100644 index 0000000..7662266 --- /dev/null +++ b/src/luasocket/inet.h @@ -0,0 +1,42 @@ +#ifndef INET_H +#define INET_H +/*=========================================================================*\ +* Internet domain functions +* LuaSocket toolkit +* +* This module implements the creation and connection of internet domain +* sockets, on top of the socket.h interface, and the interface of with the +* resolver. +* +* The function inet_aton is provided for the platforms where it is not +* available. The module also implements the interface of the internet +* getpeername and getsockname functions as seen by Lua programs. +* +* The Lua functions toip and tohostname are also implemented here. +* +* RCS ID: $Id: inet.h,v 1.16 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" +#include "socket.h" +#include "timeout.h" + +#ifdef _WIN32 +#define INET_ATON +#endif + +int inet_open(lua_State *L); + +const char *inet_trycreate(p_socket ps, int type); +const char *inet_tryconnect(p_socket ps, const char *address, + unsigned short port, p_timeout tm); +const char *inet_trybind(p_socket ps, const char *address, + unsigned short port); + +int inet_meth_getpeername(lua_State *L, p_socket ps); +int inet_meth_getsockname(lua_State *L, p_socket ps); + +#ifdef INET_ATON +int inet_aton(const char *cp, struct in_addr *inp); +#endif + +#endif /* INET_H */ diff --git a/src/luasocket/io.c b/src/luasocket/io.c new file mode 100644 index 0000000..06dc50e --- /dev/null +++ b/src/luasocket/io.c @@ -0,0 +1,32 @@ +/*=========================================================================*\ +* Input/Output abstraction +* LuaSocket toolkit +* +* RCS ID: $Id: io.c,v 1.6 2005/09/29 06:11:41 diego Exp $ +\*=========================================================================*/ +#include "io.h" + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes C structure +\*-------------------------------------------------------------------------*/ +void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx) { + io->send = send; + io->recv = recv; + io->error = error; + io->ctx = ctx; +} + +/*-------------------------------------------------------------------------*\ +* I/O error strings +\*-------------------------------------------------------------------------*/ +const char *io_strerror(int err) { + switch (err) { + case IO_DONE: return NULL; + case IO_CLOSED: return "closed"; + case IO_TIMEOUT: return "timeout"; + default: return "unknown error"; + } +} diff --git a/src/luasocket/io.h b/src/luasocket/io.h new file mode 100644 index 0000000..cce3aaf --- /dev/null +++ b/src/luasocket/io.h @@ -0,0 +1,67 @@ +#ifndef IO_H +#define IO_H +/*=========================================================================*\ +* Input/Output abstraction +* LuaSocket toolkit +* +* This module defines the interface that LuaSocket expects from the +* transport layer for streamed input/output. The idea is that if any +* transport implements this interface, then the buffer.c functions +* automatically work on it. +* +* The module socket.h implements this interface, and thus the module tcp.h +* is very simple. +* +* RCS ID: $Id: io.h,v 1.11 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include +#include "lua.h" + +#include "timeout.h" + +/* IO error codes */ +enum { + IO_DONE = 0, /* operation completed successfully */ + IO_TIMEOUT = -1, /* operation timed out */ + IO_CLOSED = -2, /* the connection has been closed */ + IO_UNKNOWN = -3 +}; + +/* interface to error message function */ +typedef const char *(*p_error) ( + void *ctx, /* context needed by send */ + int err /* error code */ +); + +/* interface to send function */ +typedef int (*p_send) ( + void *ctx, /* context needed by send */ + const char *data, /* pointer to buffer with data to send */ + size_t count, /* number of bytes to send from buffer */ + size_t *sent, /* number of bytes sent uppon return */ + p_timeout tm /* timeout control */ +); + +/* interface to recv function */ +typedef int (*p_recv) ( + void *ctx, /* context needed by recv */ + char *data, /* pointer to buffer where data will be writen */ + size_t count, /* number of bytes to receive into buffer */ + size_t *got, /* number of bytes received uppon return */ + p_timeout tm /* timeout control */ +); + +/* IO driver definition */ +typedef struct t_io_ { + void *ctx; /* context needed by send/recv */ + p_send send; /* send function pointer */ + p_recv recv; /* receive function pointer */ + p_error error; /* strerror function */ +} t_io; +typedef t_io *p_io; + +void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx); +const char *io_strerror(int err); + +#endif /* IO_H */ + diff --git a/src/luasocket/ltn12.lua b/src/luasocket/ltn12.lua new file mode 100644 index 0000000..8acdec0 --- /dev/null +++ b/src/luasocket/ltn12.lua @@ -0,0 +1,291 @@ +----------------------------------------------------------------------------- +-- LTN12 - Filters, sources, sinks and pumps. +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: ltn12.lua,v 1.30 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module +----------------------------------------------------------------------------- +local string = require("string") +local table = require("table") +local base = _G +module("ltn12") + +filter = {} +source = {} +sink = {} +pump = {} + +-- 2048 seems to be better in windows... +BLOCKSIZE = 2048 + +----------------------------------------------------------------------------- +-- Filter stuff +----------------------------------------------------------------------------- +-- returns a high level filter that cycles a low-level filter +function filter.cycle(low, ctx, extra) + base.assert(low) + return function(chunk) + local ret + ret, ctx = low(ctx, chunk, extra) + return ret + end +end + +-- chains a bunch of filters together +-- (thanks to Wim Couwenberg) +function filter.chain(...) + local n = table.getn(arg) + local top, index = 1, 1 + local retry = "" + return function(chunk) + retry = chunk and retry + while true do + if index == top then + chunk = arg[index](chunk) + if chunk == "" or top == n then return chunk + elseif chunk then index = index + 1 + else + top = top+1 + index = top + end + else + chunk = arg[index](chunk or "") + if chunk == "" then + index = index - 1 + chunk = retry + elseif chunk then + if index == n then return chunk + else index = index + 1 end + else base.error("filter returned inappropriate nil") end + end + end + end +end + +----------------------------------------------------------------------------- +-- Source stuff +----------------------------------------------------------------------------- +-- create an empty source +local function empty() + return nil +end + +function source.empty() + return empty +end + +-- returns a source that just outputs an error +function source.error(err) + return function() + return nil, err + end +end + +-- creates a file source +function source.file(handle, io_err) + if handle then + return function() + local chunk = handle:read(BLOCKSIZE) + if not chunk then handle:close() end + return chunk + end + else return source.error(io_err or "unable to open file") end +end + +-- turns a fancy source into a simple source +function source.simplify(src) + base.assert(src) + return function() + local chunk, err_or_new = src() + src = err_or_new or src + if not chunk then return nil, err_or_new + else return chunk end + end +end + +-- creates string source +function source.string(s) + if s then + local i = 1 + return function() + local chunk = string.sub(s, i, i+BLOCKSIZE-1) + i = i + BLOCKSIZE + if chunk ~= "" then return chunk + else return nil end + end + else return source.empty() end +end + +-- creates rewindable source +function source.rewind(src) + base.assert(src) + local t = {} + return function(chunk) + if not chunk then + chunk = table.remove(t) + if not chunk then return src() + else return chunk end + else + table.insert(t, chunk) + end + end +end + +function source.chain(src, f) + base.assert(src and f) + local last_in, last_out = "", "" + local state = "feeding" + local err + return function() + if not last_out then + base.error('source is empty!', 2) + end + while true do + if state == "feeding" then + last_in, err = src() + if err then return nil, err end + last_out = f(last_in) + if not last_out then + if last_in then + base.error('filter returned inappropriate nil') + else + return nil + end + elseif last_out ~= "" then + state = "eating" + if last_in then last_in = "" end + return last_out + end + else + last_out = f(last_in) + if last_out == "" then + if last_in == "" then + state = "feeding" + else + base.error('filter returned ""') + end + elseif not last_out then + if last_in then + base.error('filter returned inappropriate nil') + else + return nil + end + else + return last_out + end + end + end + end +end + +-- creates a source that produces contents of several sources, one after the +-- other, as if they were concatenated +-- (thanks to Wim Couwenberg) +function source.cat(...) + local src = table.remove(arg, 1) + return function() + while src do + local chunk, err = src() + if chunk then return chunk end + if err then return nil, err end + src = table.remove(arg, 1) + end + end +end + +----------------------------------------------------------------------------- +-- Sink stuff +----------------------------------------------------------------------------- +-- creates a sink that stores into a table +function sink.table(t) + t = t or {} + local f = function(chunk, err) + if chunk then table.insert(t, chunk) end + return 1 + end + return f, t +end + +-- turns a fancy sink into a simple sink +function sink.simplify(snk) + base.assert(snk) + return function(chunk, err) + local ret, err_or_new = snk(chunk, err) + if not ret then return nil, err_or_new end + snk = err_or_new or snk + return 1 + end +end + +-- creates a file sink +function sink.file(handle, io_err) + if handle then + return function(chunk, err) + if not chunk then + handle:close() + return 1 + else return handle:write(chunk) end + end + else return sink.error(io_err or "unable to open file") end +end + +-- creates a sink that discards data +local function null() + return 1 +end + +function sink.null() + return null +end + +-- creates a sink that just returns an error +function sink.error(err) + return function() + return nil, err + end +end + +-- chains a sink with a filter +function sink.chain(f, snk) + base.assert(f and snk) + return function(chunk, err) + if chunk ~= "" then + local filtered = f(chunk) + local done = chunk and "" + while true do + local ret, snkerr = snk(filtered, err) + if not ret then return nil, snkerr end + if filtered == done then return 1 end + filtered = f(done) + end + else return 1 end + end +end + +----------------------------------------------------------------------------- +-- Pump stuff +----------------------------------------------------------------------------- +-- pumps one chunk from the source to the sink +function pump.step(src, snk) + local chunk, src_err = src() + local ret, snk_err = snk(chunk, src_err) + if chunk and ret then return 1 + else return nil, src_err or snk_err end +end + +-- pumps all data from a source to a sink, using a step function +function pump.all(src, snk, step) + base.assert(src and snk) + step = step or pump.step + while true do + local ret, err = step(src, snk) + if not ret then + if err then return nil, err + else return 1 end + end + end +end + diff --git a/src/luasocket/luasocket.c b/src/luasocket/luasocket.c new file mode 100644 index 0000000..27e83d4 --- /dev/null +++ b/src/luasocket/luasocket.c @@ -0,0 +1,118 @@ +/*=========================================================================*\ +* LuaSocket toolkit +* Networking support for the Lua language +* Diego Nehab +* 26/11/1999 +* +* This library is part of an effort to progressively increase the network +* connectivity of the Lua language. The Lua interface to networking +* functions follows the Sockets API closely, trying to simplify all tasks +* involved in setting up both client and server connections. The provided +* IO routines, however, follow the Lua style, being very similar to the +* standard Lua read and write functions. +* +* RCS ID: $Id: luasocket.c,v 1.53 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ + +/*=========================================================================*\ +* Standard include files +\*=========================================================================*/ +#include "lua.h" +#include "lauxlib.h" + +#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) +#include "compat-5.1.h" +#endif + +/*=========================================================================*\ +* LuaSocket includes +\*=========================================================================*/ +#include "luasocket.h" +#include "auxiliar.h" +#include "except.h" +#include "timeout.h" +#include "buffer.h" +#include "inet.h" +#include "tcp.h" +#include "udp.h" +#include "select.h" + +/*-------------------------------------------------------------------------*\ +* Internal function prototypes +\*-------------------------------------------------------------------------*/ +static int global_skip(lua_State *L); +static int global_unload(lua_State *L); +static int base_open(lua_State *L); + +/*-------------------------------------------------------------------------*\ +* Modules and functions +\*-------------------------------------------------------------------------*/ +static const luaL_reg mod[] = { + {"auxiliar", auxiliar_open}, + {"except", except_open}, + {"timeout", timeout_open}, + {"buffer", buffer_open}, + {"inet", inet_open}, + {"tcp", tcp_open}, + {"udp", udp_open}, + {"select", select_open}, + {NULL, NULL} +}; + +static luaL_reg func[] = { + {"skip", global_skip}, + {"__unload", global_unload}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Skip a few arguments +\*-------------------------------------------------------------------------*/ +static int global_skip(lua_State *L) { + int amount = luaL_checkint(L, 1); + int ret = lua_gettop(L) - amount - 1; + return ret >= 0 ? ret : 0; +} + +/*-------------------------------------------------------------------------*\ +* Unloads the library +\*-------------------------------------------------------------------------*/ +static int global_unload(lua_State *L) { + (void) L; + socket_close(); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Setup basic stuff. +\*-------------------------------------------------------------------------*/ +static int base_open(lua_State *L) { + if (socket_open()) { + /* export functions (and leave namespace table on top of stack) */ + luaL_openlib(L, "socket", func, 0); +#ifdef LUASOCKET_DEBUG + lua_pushstring(L, "_DEBUG"); + lua_pushboolean(L, 1); + lua_rawset(L, -3); +#endif + /* make version string available to scripts */ + lua_pushstring(L, "_VERSION"); + lua_pushstring(L, LUASOCKET_VERSION); + lua_rawset(L, -3); + return 1; + } else { + lua_pushstring(L, "unable to initialize library"); + lua_error(L); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Initializes all library modules. +\*-------------------------------------------------------------------------*/ +LUASOCKET_API int luaopen_luasocket(lua_State *L) { + int i; + base_open(L); + for (i = 0; mod[i].name; i++) mod[i].func(L); + return 1; +} diff --git a/src/luasocket/luasocket.h b/src/luasocket/luasocket.h new file mode 100644 index 0000000..aad142d --- /dev/null +++ b/src/luasocket/luasocket.h @@ -0,0 +1,32 @@ +#ifndef LUASOCKET_H +#define LUASOCKET_H +/*=========================================================================*\ +* LuaSocket toolkit +* Networking support for the Lua language +* Diego Nehab +* 9/11/1999 +* +* RCS ID: $Id: luasocket.h,v 1.23 2005/09/29 06:11:41 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +/*-------------------------------------------------------------------------*\ +* Current socket library version +\*-------------------------------------------------------------------------*/ +#define LUASOCKET_VERSION "LuaSocket 2.0" +#define LUASOCKET_COPYRIGHT "Copyright (C) 2004-2005 Diego Nehab" +#define LUASOCKET_AUTHORS "Diego Nehab" + +/*-------------------------------------------------------------------------*\ +* This macro prefixes all exported API functions +\*-------------------------------------------------------------------------*/ +#ifndef LUASOCKET_API +#define LUASOCKET_API extern +#endif + +/*-------------------------------------------------------------------------*\ +* Initializes the library. +\*-------------------------------------------------------------------------*/ +LUASOCKET_API int luaopen_socket_core(lua_State *L); + +#endif /* LUASOCKET_H */ diff --git a/src/luasocket/makefile b/src/luasocket/makefile new file mode 100644 index 0000000..9a97dd3 --- /dev/null +++ b/src/luasocket/makefile @@ -0,0 +1,88 @@ +#------ +# Load configuration +# +include ../config + +#------ +# Hopefully no need to change anything below this line +# + +#------ +# Modules belonging to socket-core +# +SOCKET_OBJS:= \ + $(COMPAT)/compat-5.1.o \ + luasocket.o \ + timeout.o \ + buffer.o \ + io.o \ + auxiliar.o \ + options.o \ + inet.o \ + tcp.o \ + udp.o \ + except.o \ + select.o \ + usocket.o + +#------ +# Modules belonging mime-core +# +MIME_OBJS:=\ + $(COMPAT)/compat-5.1.o \ + mime.o + + +#------ +# Modules belonging unix (local domain sockets) +# +UNIX_OBJS:=\ + buffer.o \ + auxiliar.o \ + options.o \ + timeout.o \ + io.o \ + usocket.o \ + unix.o + +all: $(SOCKET_SO) $(MIME_SO) + +$(SOCKET_SO): $(SOCKET_OBJS) + $(LD) $(LDFLAGS) -o $@ $^ + +$(MIME_SO): $(MIME_OBJS) + $(LD) $(LDFLAGS) -o $@ $^ + +$(UNIX_SO): $(UNIX_OBJS) + $(LD) $(LDFLAGS) -o $@ $^ + +#------ +# List of dependencies +# +auxiliar.o: auxiliar.c auxiliar.h +buffer.o: buffer.c buffer.h io.h timeout.h +except.o: except.c except.h +inet.o: inet.c inet.h socket.h io.h timeout.h usocket.h +io.o: io.c io.h timeout.h +luasocket.o: luasocket.c luasocket.h auxiliar.h except.h timeout.h \ + buffer.h io.h inet.h socket.h usocket.h tcp.h udp.h select.h +mime.o: mime.c mime.h +options.o: options.c auxiliar.h options.h socket.h io.h timeout.h \ + usocket.h inet.h +select.o: select.c socket.h io.h timeout.h usocket.h select.h +tcp.o: tcp.c auxiliar.h socket.h io.h timeout.h usocket.h inet.h \ + options.h tcp.h buffer.h +timeout.o: timeout.c auxiliar.h timeout.h +udp.o: udp.c auxiliar.h socket.h io.h timeout.h usocket.h inet.h \ + options.h udp.h +unix.o: unix.c auxiliar.h socket.h io.h timeout.h usocket.h options.h \ + unix.h buffer.h +usocket.o: usocket.c socket.h io.h timeout.h usocket.h + +clean: + rm -f $(SOCKET_SO) $(SOCKET_OBJS) + rm -f $(MIME_SO) $(UNIX_SO) $(MIME_OBJS) $(UNIX_OBJS) + +#------ +# End of makefile configuration +# diff --git a/src/luasocket/mime.c b/src/luasocket/mime.c new file mode 100644 index 0000000..700fa05 --- /dev/null +++ b/src/luasocket/mime.c @@ -0,0 +1,711 @@ +/*=========================================================================*\ +* MIME support functions +* LuaSocket toolkit +* +* RCS ID: $Id: mime.c,v 1.28 2005/11/20 07:20:23 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) +#include "compat-5.1.h" +#endif + +#include "mime.h" + +/*=========================================================================*\ +* Don't want to trust escape character constants +\*=========================================================================*/ +typedef unsigned char UC; +static const char CRLF[] = "\r\n"; +static const char EQCRLF[] = "=\r\n"; + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int mime_global_wrp(lua_State *L); +static int mime_global_b64(lua_State *L); +static int mime_global_unb64(lua_State *L); +static int mime_global_qp(lua_State *L); +static int mime_global_unqp(lua_State *L); +static int mime_global_qpwrp(lua_State *L); +static int mime_global_eol(lua_State *L); +static int mime_global_dot(lua_State *L); + +static size_t dot(int c, size_t state, luaL_Buffer *buffer); +static void b64setup(UC *b64unbase); +static size_t b64encode(UC c, UC *input, size_t size, luaL_Buffer *buffer); +static size_t b64pad(const UC *input, size_t size, luaL_Buffer *buffer); +static size_t b64decode(UC c, UC *input, size_t size, luaL_Buffer *buffer); + +static void qpsetup(UC *qpclass, UC *qpunbase); +static void qpquote(UC c, luaL_Buffer *buffer); +static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer); +static size_t qpencode(UC c, UC *input, size_t size, + const char *marker, luaL_Buffer *buffer); +static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer); + +/* code support functions */ +static luaL_reg func[] = { + { "dot", mime_global_dot }, + { "b64", mime_global_b64 }, + { "eol", mime_global_eol }, + { "qp", mime_global_qp }, + { "qpwrp", mime_global_qpwrp }, + { "unb64", mime_global_unb64 }, + { "unqp", mime_global_unqp }, + { "wrp", mime_global_wrp }, + { NULL, NULL } +}; + +/*-------------------------------------------------------------------------*\ +* Quoted-printable globals +\*-------------------------------------------------------------------------*/ +static UC qpclass[256]; +static UC qpbase[] = "0123456789ABCDEF"; +static UC qpunbase[256]; +enum {QP_PLAIN, QP_QUOTED, QP_CR, QP_IF_LAST}; + +/*-------------------------------------------------------------------------*\ +* Base64 globals +\*-------------------------------------------------------------------------*/ +static const UC b64base[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static UC b64unbase[256]; + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +MIME_API int luaopen_mime_core(lua_State *L) +{ + luaL_openlib(L, "mime", func, 0); + /* make version string available to scripts */ + lua_pushstring(L, "_VERSION"); + lua_pushstring(L, MIME_VERSION); + lua_rawset(L, -3); + /* initialize lookup tables */ + qpsetup(qpclass, qpunbase); + b64setup(b64unbase); + return 1; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Incrementaly breaks a string into lines. The string can have CRLF breaks. +* A, n = wrp(l, B, length) +* A is a copy of B, broken into lines of at most 'length' bytes. +* 'l' is how many bytes are left for the first line of B. +* 'n' is the number of bytes left in the last line of A. +\*-------------------------------------------------------------------------*/ +static int mime_global_wrp(lua_State *L) +{ + size_t size = 0; + int left = (int) luaL_checknumber(L, 1); + const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); + const UC *last = input + size; + int length = (int) luaL_optnumber(L, 3, 76); + luaL_Buffer buffer; + /* end of input black-hole */ + if (!input) { + /* if last line has not been terminated, add a line break */ + if (left < length) lua_pushstring(L, CRLF); + /* otherwise, we are done */ + else lua_pushnil(L); + lua_pushnumber(L, length); + return 2; + } + luaL_buffinit(L, &buffer); + while (input < last) { + switch (*input) { + case '\r': + break; + case '\n': + luaL_addstring(&buffer, CRLF); + left = length; + break; + default: + if (left <= 0) { + left = length; + luaL_addstring(&buffer, CRLF); + } + luaL_putchar(&buffer, *input); + left--; + break; + } + input++; + } + luaL_pushresult(&buffer); + lua_pushnumber(L, left); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Fill base64 decode map. +\*-------------------------------------------------------------------------*/ +static void b64setup(UC *b64unbase) +{ + int i; + for (i = 0; i <= 255; i++) b64unbase[i] = (UC) 255; + for (i = 0; i < 64; i++) b64unbase[b64base[i]] = (UC) i; + b64unbase['='] = 0; +} + +/*-------------------------------------------------------------------------*\ +* Acumulates bytes in input buffer until 3 bytes are available. +* Translate the 3 bytes into Base64 form and append to buffer. +* Returns new number of bytes in buffer. +\*-------------------------------------------------------------------------*/ +static size_t b64encode(UC c, UC *input, size_t size, + luaL_Buffer *buffer) +{ + input[size++] = c; + if (size == 3) { + UC code[4]; + unsigned long value = 0; + value += input[0]; value <<= 8; + value += input[1]; value <<= 8; + value += input[2]; + code[3] = b64base[value & 0x3f]; value >>= 6; + code[2] = b64base[value & 0x3f]; value >>= 6; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + size = 0; + } + return size; +} + +/*-------------------------------------------------------------------------*\ +* Encodes the Base64 last 1 or 2 bytes and adds padding '=' +* Result, if any, is appended to buffer. +* Returns 0. +\*-------------------------------------------------------------------------*/ +static size_t b64pad(const UC *input, size_t size, + luaL_Buffer *buffer) +{ + unsigned long value = 0; + UC code[4] = {'=', '=', '=', '='}; + switch (size) { + case 1: + value = input[0] << 4; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + break; + case 2: + value = input[0]; value <<= 8; + value |= input[1]; value <<= 2; + code[2] = b64base[value & 0x3f]; value >>= 6; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + break; + default: + break; + } + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Acumulates bytes in input buffer until 4 bytes are available. +* Translate the 4 bytes from Base64 form and append to buffer. +* Returns new number of bytes in buffer. +\*-------------------------------------------------------------------------*/ +static size_t b64decode(UC c, UC *input, size_t size, + luaL_Buffer *buffer) +{ + /* ignore invalid characters */ + if (b64unbase[c] > 64) return size; + input[size++] = c; + /* decode atom */ + if (size == 4) { + UC decoded[3]; + int valid, value = 0; + value = b64unbase[input[0]]; value <<= 6; + value |= b64unbase[input[1]]; value <<= 6; + value |= b64unbase[input[2]]; value <<= 6; + value |= b64unbase[input[3]]; + decoded[2] = (UC) (value & 0xff); value >>= 8; + decoded[1] = (UC) (value & 0xff); value >>= 8; + decoded[0] = (UC) value; + /* take care of paddding */ + valid = (input[2] == '=') ? 1 : (input[3] == '=') ? 2 : 3; + luaL_addlstring(buffer, (char *) decoded, valid); + return 0; + /* need more data */ + } else return size; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally applies the Base64 transfer content encoding to a string +* A, B = b64(C, D) +* A is the encoded version of the largest prefix of C .. D that is +* divisible by 3. B has the remaining bytes of C .. D, *without* encoding. +* The easiest thing would be to concatenate the two strings and +* encode the result, but we can't afford that or Lua would dupplicate +* every chunk we received. +\*-------------------------------------------------------------------------*/ +static int mime_global_b64(lua_State *L) +{ + UC atom[3]; + size_t isize = 0, asize = 0; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* process first part of the input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = b64encode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + asize = b64pad(atom, asize, &buffer); + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process the second part */ + last = input + isize; + while (input < last) + asize = b64encode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally removes the Base64 transfer content encoding from a string +* A, B = b64(C, D) +* A is the encoded version of the largest prefix of C .. D that is +* divisible by 4. B has the remaining bytes of C .. D, *without* encoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_unb64(lua_State *L) +{ + UC atom[4]; + size_t isize = 0, asize = 0; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* process first part of the input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = b64decode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second is nil, we are done */ + if (!input) { + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise, process the rest of the input */ + last = input + isize; + while (input < last) + asize = b64decode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Quoted-printable encoding scheme +* all (except CRLF in text) can be =XX +* CLRL in not text must be =XX=XX +* 33 through 60 inclusive can be plain +* 62 through 126 inclusive can be plain +* 9 and 32 can be plain, unless in the end of a line, where must be =XX +* encoded lines must be no longer than 76 not counting CRLF +* soft line-break are =CRLF +* To encode one byte, we need to see the next two. +* Worst case is when we see a space, and wonder if a CRLF is comming +\*-------------------------------------------------------------------------*/ +/*-------------------------------------------------------------------------*\ +* Split quoted-printable characters into classes +* Precompute reverse map for encoding +\*-------------------------------------------------------------------------*/ +static void qpsetup(UC *qpclass, UC *qpunbase) +{ + int i; + for (i = 0; i < 256; i++) qpclass[i] = QP_QUOTED; + for (i = 33; i <= 60; i++) qpclass[i] = QP_PLAIN; + for (i = 62; i <= 126; i++) qpclass[i] = QP_PLAIN; + qpclass['\t'] = QP_IF_LAST; + qpclass[' '] = QP_IF_LAST; + qpclass['\r'] = QP_CR; + for (i = 0; i < 256; i++) qpunbase[i] = 255; + qpunbase['0'] = 0; qpunbase['1'] = 1; qpunbase['2'] = 2; + qpunbase['3'] = 3; qpunbase['4'] = 4; qpunbase['5'] = 5; + qpunbase['6'] = 6; qpunbase['7'] = 7; qpunbase['8'] = 8; + qpunbase['9'] = 9; qpunbase['A'] = 10; qpunbase['a'] = 10; + qpunbase['B'] = 11; qpunbase['b'] = 11; qpunbase['C'] = 12; + qpunbase['c'] = 12; qpunbase['D'] = 13; qpunbase['d'] = 13; + qpunbase['E'] = 14; qpunbase['e'] = 14; qpunbase['F'] = 15; + qpunbase['f'] = 15; +} + +/*-------------------------------------------------------------------------*\ +* Output one character in form =XX +\*-------------------------------------------------------------------------*/ +static void qpquote(UC c, luaL_Buffer *buffer) +{ + luaL_putchar(buffer, '='); + luaL_putchar(buffer, qpbase[c >> 4]); + luaL_putchar(buffer, qpbase[c & 0x0F]); +} + +/*-------------------------------------------------------------------------*\ +* Accumulate characters until we are sure about how to deal with them. +* Once we are sure, output to the buffer, in the correct form. +\*-------------------------------------------------------------------------*/ +static size_t qpencode(UC c, UC *input, size_t size, + const char *marker, luaL_Buffer *buffer) +{ + input[size++] = c; + /* deal with all characters we can have */ + while (size > 0) { + switch (qpclass[input[0]]) { + /* might be the CR of a CRLF sequence */ + case QP_CR: + if (size < 2) return size; + if (input[1] == '\n') { + luaL_addstring(buffer, marker); + return 0; + } else qpquote(input[0], buffer); + break; + /* might be a space and that has to be quoted if last in line */ + case QP_IF_LAST: + if (size < 3) return size; + /* if it is the last, quote it and we are done */ + if (input[1] == '\r' && input[2] == '\n') { + qpquote(input[0], buffer); + luaL_addstring(buffer, marker); + return 0; + } else luaL_putchar(buffer, input[0]); + break; + /* might have to be quoted always */ + case QP_QUOTED: + qpquote(input[0], buffer); + break; + /* might never have to be quoted */ + default: + luaL_putchar(buffer, input[0]); + break; + } + input[0] = input[1]; input[1] = input[2]; + size--; + } + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Deal with the final characters +\*-------------------------------------------------------------------------*/ +static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer) +{ + size_t i; + for (i = 0; i < size; i++) { + if (qpclass[input[i]] == QP_PLAIN) luaL_putchar(buffer, input[i]); + else qpquote(input[i], buffer); + } + if (size > 0) luaL_addstring(buffer, EQCRLF); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally converts a string to quoted-printable +* A, B = qp(C, D, marker) +* Marker is the text to be used to replace CRLF sequences found in A. +* A is the encoded version of the largest prefix of C .. D that +* can be encoded without doubts. +* B has the remaining bytes of C .. D, *without* encoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_qp(lua_State *L) +{ + + size_t asize = 0, isize = 0; + UC atom[3]; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + const char *marker = luaL_optstring(L, 3, CRLF); + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* process first part of input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = qpencode(*input++, atom, asize, marker, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + asize = qppad(atom, asize, &buffer); + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process rest of input */ + last = input + isize; + while (input < last) + asize = qpencode(*input++, atom, asize, marker, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Accumulate characters until we are sure about how to deal with them. +* Once we are sure, output the to the buffer, in the correct form. +\*-------------------------------------------------------------------------*/ +static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer) { + int d; + input[size++] = c; + /* deal with all characters we can deal */ + switch (input[0]) { + /* if we have an escape character */ + case '=': + if (size < 3) return size; + /* eliminate soft line break */ + if (input[1] == '\r' && input[2] == '\n') return 0; + /* decode quoted representation */ + c = qpunbase[input[1]]; d = qpunbase[input[2]]; + /* if it is an invalid, do not decode */ + if (c > 15 || d > 15) luaL_addlstring(buffer, (char *)input, 3); + else luaL_putchar(buffer, (c << 4) + d); + return 0; + case '\r': + if (size < 2) return size; + if (input[1] == '\n') luaL_addlstring(buffer, (char *)input, 2); + return 0; + default: + if (input[0] == '\t' || (input[0] > 31 && input[0] < 127)) + luaL_putchar(buffer, input[0]); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Incrementally decodes a string in quoted-printable +* A, B = qp(C, D) +* A is the decoded version of the largest prefix of C .. D that +* can be decoded without doubts. +* B has the remaining bytes of C .. D, *without* decoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_unqp(lua_State *L) +{ + size_t asize = 0, isize = 0; + UC atom[3]; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* process first part of input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = qpdecode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process rest of input */ + last = input + isize; + while (input < last) + asize = qpdecode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally breaks a quoted-printed string into lines +* A, n = qpwrp(l, B, length) +* A is a copy of B, broken into lines of at most 'length' bytes. +* 'l' is how many bytes are left for the first line of B. +* 'n' is the number of bytes left in the last line of A. +* There are two complications: lines can't be broken in the middle +* of an encoded =XX, and there might be line breaks already +\*-------------------------------------------------------------------------*/ +static int mime_global_qpwrp(lua_State *L) +{ + size_t size = 0; + int left = (int) luaL_checknumber(L, 1); + const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); + const UC *last = input + size; + int length = (int) luaL_optnumber(L, 3, 76); + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + if (left < length) lua_pushstring(L, EQCRLF); + else lua_pushnil(L); + lua_pushnumber(L, length); + return 2; + } + /* process all input */ + luaL_buffinit(L, &buffer); + while (input < last) { + switch (*input) { + case '\r': + break; + case '\n': + left = length; + luaL_addstring(&buffer, CRLF); + break; + case '=': + if (left <= 3) { + left = length; + luaL_addstring(&buffer, EQCRLF); + } + luaL_putchar(&buffer, *input); + left--; + break; + default: + if (left <= 1) { + left = length; + luaL_addstring(&buffer, EQCRLF); + } + luaL_putchar(&buffer, *input); + left--; + break; + } + input++; + } + luaL_pushresult(&buffer); + lua_pushnumber(L, left); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Here is what we do: \n, and \r are considered candidates for line +* break. We issue *one* new line marker if any of them is seen alone, or +* followed by a different one. That is, \n\n and \r\r will issue two +* end of line markers each, but \r\n, \n\r etc will only issue *one* +* marker. This covers Mac OS, Mac OS X, VMS, Unix and DOS, as well as +* probably other more obscure conventions. +* +* c is the current character being processed +* last is the previous character +\*-------------------------------------------------------------------------*/ +#define eolcandidate(c) (c == '\r' || c == '\n') +static int eolprocess(int c, int last, const char *marker, + luaL_Buffer *buffer) +{ + if (eolcandidate(c)) { + if (eolcandidate(last)) { + if (c == last) luaL_addstring(buffer, marker); + return 0; + } else { + luaL_addstring(buffer, marker); + return c; + } + } else { + luaL_putchar(buffer, c); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Converts a string to uniform EOL convention. +* A, n = eol(o, B, marker) +* A is the converted version of the largest prefix of B that can be +* converted unambiguously. 'o' is the context returned by the previous +* call. 'n' is the new context. +\*-------------------------------------------------------------------------*/ +static int mime_global_eol(lua_State *L) +{ + int ctx = luaL_checkint(L, 1); + size_t isize = 0; + const char *input = luaL_optlstring(L, 2, NULL, &isize); + const char *last = input + isize; + const char *marker = luaL_optstring(L, 3, CRLF); + luaL_Buffer buffer; + luaL_buffinit(L, &buffer); + /* end of input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnumber(L, 0); + return 2; + } + /* process all input */ + while (input < last) + ctx = eolprocess(*input++, ctx, marker, &buffer); + luaL_pushresult(&buffer); + lua_pushnumber(L, ctx); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Takes one byte and stuff it if needed. +\*-------------------------------------------------------------------------*/ +static size_t dot(int c, size_t state, luaL_Buffer *buffer) +{ + luaL_putchar(buffer, c); + switch (c) { + case '\r': + return 1; + case '\n': + return (state == 1)? 2: 0; + case '.': + if (state == 2) + luaL_putchar(buffer, '.'); + default: + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Incrementally applies smtp stuffing to a string +* A, n = dot(l, D) +\*-------------------------------------------------------------------------*/ +static int mime_global_dot(lua_State *L) +{ + size_t isize = 0, state = (size_t) luaL_checknumber(L, 1); + const char *input = luaL_optlstring(L, 2, NULL, &isize); + const char *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnumber(L, 2); + return 2; + } + /* process all input */ + luaL_buffinit(L, &buffer); + while (input < last) + state = dot(*input++, state, &buffer); + luaL_pushresult(&buffer); + lua_pushnumber(L, state); + return 2; +} + diff --git a/src/luasocket/mime.h b/src/luasocket/mime.h new file mode 100644 index 0000000..a322cd2 --- /dev/null +++ b/src/luasocket/mime.h @@ -0,0 +1,31 @@ +#ifndef MIME_H +#define MIME_H +/*=========================================================================*\ +* Core MIME support +* LuaSocket toolkit +* +* This module provides functions to implement transfer content encodings +* and formatting conforming to RFC 2045. It is used by mime.lua, which +* provide a higher level interface to this functionality. +* +* RCS ID: $Id: mime.h,v 1.13 2005/09/29 06:11:42 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +/*-------------------------------------------------------------------------*\ +* Current MIME library version +\*-------------------------------------------------------------------------*/ +#define MIME_VERSION "MIME 1.0" +#define MIME_COPYRIGHT "Copyright (C) 2004-2005 Diego Nehab" +#define MIME_AUTHORS "Diego Nehab" + +/*-------------------------------------------------------------------------*\ +* This macro prefixes all exported API functions +\*-------------------------------------------------------------------------*/ +#ifndef MIME_API +#define MIME_API extern +#endif + +MIME_API int luaopen_mime_core(lua_State *L); + +#endif /* MIME_H */ diff --git a/src/luasocket/mime.lua b/src/luasocket/mime.lua new file mode 100644 index 0000000..293f5f1 --- /dev/null +++ b/src/luasocket/mime.lua @@ -0,0 +1,86 @@ +----------------------------------------------------------------------------- +-- MIME support for the Lua language. +-- Author: Diego Nehab +-- Conforming to RFCs 2045-2049 +-- RCS ID: $Id: mime.lua,v 1.28 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local ltn12 = require("ltn12") +local mime = require("mime.core") +local io = require("io") +local string = require("string") +module("mime") + +-- encode, decode and wrap algorithm tables +encodet = {} +decodet = {} +wrapt = {} + +-- creates a function that chooses a filter by name from a given table +local function choose(table) + return function(name, opt1, opt2) + if base.type(name) ~= "string" then + name, opt1, opt2 = "default", name, opt1 + end + local f = table[name or "nil"] + if not f then error("unknown key (" .. base.tostring(name) .. ")", 3) + else return f(opt1, opt2) end + end +end + +-- define the encoding filters +encodet['base64'] = function() + return ltn12.filter.cycle(b64, "") +end + +encodet['quoted-printable'] = function(mode) + return ltn12.filter.cycle(qp, "", + (mode == "binary") and "=0D=0A" or "\r\n") +end + +-- define the decoding filters +decodet['base64'] = function() + return ltn12.filter.cycle(unb64, "") +end + +decodet['quoted-printable'] = function() + return ltn12.filter.cycle(unqp, "") +end + +local function format(chunk) + if chunk then + if chunk == "" then return "''" + else return string.len(chunk) end + else return "nil" end +end + +-- define the line-wrap filters +wrapt['text'] = function(length) + length = length or 76 + return ltn12.filter.cycle(wrp, length, length) +end +wrapt['base64'] = wrapt['text'] +wrapt['default'] = wrapt['text'] + +wrapt['quoted-printable'] = function() + return ltn12.filter.cycle(qpwrp, 76, 76) +end + +-- function that choose the encoding, decoding or wrap algorithm +encode = choose(encodet) +decode = choose(decodet) +wrap = choose(wrapt) + +-- define the end-of-line normalization filter +function normalize(marker) + return ltn12.filter.cycle(eol, 0, marker) +end + +-- high level stuffing filter +function stuff() + return ltn12.filter.cycle(dot, 2) +end diff --git a/src/luasocket/mycompat.h b/src/luasocket/mycompat.h new file mode 100644 index 0000000..2c4dff7 --- /dev/null +++ b/src/luasocket/mycompat.h @@ -0,0 +1,59 @@ + +#ifndef FUCK_THAT +#define FUCK_THAT + +typedef t_buffer t_buf; +typedef t_socket t_sock; +typedef t_timeout t_tm; + +typedef p_buffer p_buf; +typedef p_socket p_sock; +typedef p_timeout p_tm; + +#define aux_add2group auxiliar_add2group +#define aux_checkboolean auxiliar_checkboolean +#define aux_checkclass auxiliar_checkclass +#define aux_checkgroup auxiliar_checkgroup +#define aux_newclass auxiliar_newclass +#define aux_open auxiliar_open +#define aux_setclass auxiliar_setclass +#define aux_tostring auxiliar_tostring +#define buf_init buffer_init +#define buf_isempty buffer_isempty +#define buf_meth_getstats buffer_meth_getstats +#define buf_meth_receive buffer_meth_receive +#define buf_meth_send buffer_meth_send +#define buf_meth_setstats buffer_meth_setstats +#define buf_open buffer_open +#define sock_accept socket_accept +#define sock_bind socket_bind +#define sock_close socket_close +#define sock_connect socket_connect +#define sock_create socket_create +#define sock_destroy socket_destroy +#define sock_gethostbyaddr socket_gethostbyaddr +#define sock_gethostbyname socket_gethostbyname +#define sock_ioerror socket_ioerror +#define sock_listen socket_listen +#define sock_open socket_open +#define sock_recvfrom socket_recvfrom +#define sock_recv socket_recv +#define sock_select socket_select +#define sock_send socket_send +#define sock_sendto socket_sendto +#define sock_setblocking socket_setblocking +#define sock_setnonblocking socket_setnonblocking +#define sock_shutdown socket_shutdown +#define sock_strerror socket_strerror +#define sock_waitfd socket_waitfd +#define tm_getretry timeout_getretry +#define tm_getstart timeout_getstart +#define tm_get timeout_get +#define tm_gettime timeout_gettime +#define tm_init timeout_init +#define tm_lua_sleep timeout_lua_sleep +#define tm_markstart timeout_markstart +#define tm_meth_settimeout timeout_meth_settimeout +#define tm_open timeout_open + +#endif /* FUCK_THAT */ diff --git a/src/luasocket/options.c b/src/luasocket/options.c new file mode 100644 index 0000000..5da3c51 --- /dev/null +++ b/src/luasocket/options.c @@ -0,0 +1,149 @@ +/*=========================================================================*\ +* Common option interface +* LuaSocket toolkit +* +* RCS ID: $Id: options.c,v 1.6 2005/11/20 07:20:23 diego Exp $ +\*=========================================================================*/ +#include + +#include "lauxlib.h" + +#include "auxiliar.h" +#include "options.h" +#include "inet.h" + + +/*=========================================================================*\ +* Internal functions prototypes +\*=========================================================================*/ +static int opt_setmembership(lua_State *L, p_socket ps, int level, int name); +static int opt_setboolean(lua_State *L, p_socket ps, int level, int name); +static int opt_set(lua_State *L, p_socket ps, int level, int name, + void *val, int len); + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Calls appropriate option handler +\*-------------------------------------------------------------------------*/ +int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps) +{ + const char *name = luaL_checkstring(L, 2); /* obj, name, ... */ + while (opt->name && strcmp(name, opt->name)) + opt++; + if (!opt->func) { + char msg[45]; + sprintf(msg, "unsupported option `%.35s'", name); + luaL_argerror(L, 2, msg); + } + return opt->func(L, ps); +} + +/* enables reuse of local address */ +int opt_reuseaddr(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR); +} + +/* disables the Naggle algorithm */ +int opt_tcp_nodelay(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY); +} + +int opt_keepalive(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE); +} + +int opt_dontroute(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_DONTROUTE); +} + +int opt_broadcast(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_BROADCAST); +} + +int opt_ip_multicast_loop(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP); +} + +int opt_linger(lua_State *L, p_socket ps) +{ + struct linger li; /* obj, name, table */ + if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE)); + lua_pushstring(L, "on"); + lua_gettable(L, 3); + if (!lua_isboolean(L, -1)) + luaL_argerror(L, 3, "boolean 'on' field expected"); + li.l_onoff = (u_short) lua_toboolean(L, -1); + lua_pushstring(L, "timeout"); + lua_gettable(L, 3); + if (!lua_isnumber(L, -1)) + luaL_argerror(L, 3, "number 'timeout' field expected"); + li.l_linger = (u_short) lua_tonumber(L, -1); + return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li)); +} + +int opt_ip_multicast_ttl(lua_State *L, p_socket ps) +{ + int val = (int) luaL_checknumber(L, 3); /* obj, name, int */ + return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &val, sizeof(val)); +} + +int opt_ip_add_membership(lua_State *L, p_socket ps) +{ + return opt_setmembership(L, ps, IPPROTO_IP, IP_ADD_MEMBERSHIP); +} + +int opt_ip_drop_membersip(lua_State *L, p_socket ps) +{ + return opt_setmembership(L, ps, IPPROTO_IP, IP_DROP_MEMBERSHIP); +} + +/*=========================================================================*\ +* Auxiliar functions +\*=========================================================================*/ +static int opt_setmembership(lua_State *L, p_socket ps, int level, int name) +{ + struct ip_mreq val; /* obj, name, table */ + if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE)); + lua_pushstring(L, "multiaddr"); + lua_gettable(L, 3); + if (!lua_isstring(L, -1)) + luaL_argerror(L, 3, "string 'multiaddr' field expected"); + if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr)) + luaL_argerror(L, 3, "invalid 'multiaddr' ip address"); + lua_pushstring(L, "interface"); + lua_gettable(L, 3); + if (!lua_isstring(L, -1)) + luaL_argerror(L, 3, "string 'interface' field expected"); + val.imr_interface.s_addr = htonl(INADDR_ANY); + if (strcmp(lua_tostring(L, -1), "*") && + !inet_aton(lua_tostring(L, -1), &val.imr_interface)) + luaL_argerror(L, 3, "invalid 'interface' ip address"); + return opt_set(L, ps, level, name, (char *) &val, sizeof(val)); +} + +static +int opt_set(lua_State *L, p_socket ps, int level, int name, void *val, int len) +{ + if (setsockopt(*ps, level, name, (char *) val, len) < 0) { + lua_pushnil(L); + lua_pushstring(L, "setsockopt failed"); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +static int opt_setboolean(lua_State *L, p_socket ps, int level, int name) +{ + int val = auxiliar_checkboolean(L, 3); /* obj, name, bool */ + return opt_set(L, ps, level, name, (char *) &val, sizeof(val)); +} + diff --git a/src/luasocket/options.h b/src/luasocket/options.h new file mode 100644 index 0000000..4981cf2 --- /dev/null +++ b/src/luasocket/options.h @@ -0,0 +1,39 @@ +#ifndef OPTIONS_H +#define OPTIONS_H +/*=========================================================================*\ +* Common option interface +* LuaSocket toolkit +* +* This module provides a common interface to socket options, used mainly by +* modules UDP and TCP. +* +* RCS ID: $Id: options.h,v 1.4 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ + +#include "lua.h" +#include "socket.h" + +/* option registry */ +typedef struct t_opt { + const char *name; + int (*func)(lua_State *L, p_socket ps); +} t_opt; +typedef t_opt *p_opt; + +/* supported options */ +int opt_dontroute(lua_State *L, p_socket ps); +int opt_broadcast(lua_State *L, p_socket ps); +int opt_reuseaddr(lua_State *L, p_socket ps); +int opt_tcp_nodelay(lua_State *L, p_socket ps); +int opt_keepalive(lua_State *L, p_socket ps); +int opt_linger(lua_State *L, p_socket ps); +int opt_reuseaddr(lua_State *L, p_socket ps); +int opt_ip_multicast_ttl(lua_State *L, p_socket ps); +int opt_ip_multicast_loop(lua_State *L, p_socket ps); +int opt_ip_add_membership(lua_State *L, p_socket ps); +int opt_ip_drop_membersip(lua_State *L, p_socket ps); + +/* invokes the appropriate option handler */ +int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps); + +#endif diff --git a/src/luasocket/select.c b/src/luasocket/select.c new file mode 100644 index 0000000..d70f662 --- /dev/null +++ b/src/luasocket/select.c @@ -0,0 +1,200 @@ +/*=========================================================================*\ +* Select implementation +* LuaSocket toolkit +* +* RCS ID: $Id: select.c,v 1.22 2005/11/20 07:20:23 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "socket.h" +#include "timeout.h" +#include "select.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static t_socket getfd(lua_State *L); +static int dirty(lua_State *L); +static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd, + int itab, fd_set *set); +static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set); +static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, + int itab, int tab, int start); +static void make_assoc(lua_State *L, int tab); +static int global_select(lua_State *L); + +/* functions in library namespace */ +static luaL_reg func[] = { + {"select", global_select}, + {NULL, NULL} +}; + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int select_open(lua_State *L) { + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Waits for a set of sockets until a condition is met or timeout. +\*-------------------------------------------------------------------------*/ +static int global_select(lua_State *L) { + int rtab, wtab, itab, ret, ndirty; + t_socket max_fd; + fd_set rset, wset; + t_timeout tm; + double t = luaL_optnumber(L, 3, -1); + FD_ZERO(&rset); FD_ZERO(&wset); + lua_settop(L, 3); + lua_newtable(L); itab = lua_gettop(L); + lua_newtable(L); rtab = lua_gettop(L); + lua_newtable(L); wtab = lua_gettop(L); + max_fd = collect_fd(L, 1, SOCKET_INVALID, itab, &rset); + ndirty = check_dirty(L, 1, rtab, &rset); + t = ndirty > 0? 0.0: t; + timeout_init(&tm, t, -1); + timeout_markstart(&tm); + max_fd = collect_fd(L, 2, max_fd, itab, &wset); + ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm); + if (ret > 0 || ndirty > 0) { + return_fd(L, &rset, max_fd+1, itab, rtab, ndirty); + return_fd(L, &wset, max_fd+1, itab, wtab, 0); + make_assoc(L, rtab); + make_assoc(L, wtab); + return 2; + } else if (ret == 0) { + lua_pushstring(L, "timeout"); + return 3; + } else { + lua_pushstring(L, "error"); + return 3; + } +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +static t_socket getfd(lua_State *L) { + t_socket fd = SOCKET_INVALID; + lua_pushstring(L, "getfd"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + if (lua_isnumber(L, -1)) + fd = (t_socket) lua_tonumber(L, -1); + } + lua_pop(L, 1); + return fd; +} + +static int dirty(lua_State *L) { + int is = 0; + lua_pushstring(L, "dirty"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + is = lua_toboolean(L, -1); + } + lua_pop(L, 1); + return is; +} + +static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd, + int itab, fd_set *set) { + int i = 1; + if (lua_isnil(L, tab)) + return max_fd; + while (1) { + t_socket fd; + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + break; + } + fd = getfd(L); + if (fd != SOCKET_INVALID) { + FD_SET(fd, set); + if (max_fd == SOCKET_INVALID || max_fd < fd) + max_fd = fd; + lua_pushnumber(L, fd); + lua_pushvalue(L, -2); + lua_settable(L, itab); + } + lua_pop(L, 1); + i = i + 1; + } + return max_fd; +} + +static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) { + int ndirty = 0, i = 1; + if (lua_isnil(L, tab)) + return 0; + while (1) { + t_socket fd; + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + break; + } + fd = getfd(L); + if (fd != SOCKET_INVALID && dirty(L)) { + lua_pushnumber(L, ++ndirty); + lua_pushvalue(L, -2); + lua_settable(L, dtab); + FD_CLR(fd, set); + } + lua_pop(L, 1); + i = i + 1; + } + return ndirty; +} + +static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, + int itab, int tab, int start) { + t_socket fd; + for (fd = 0; fd < max_fd; fd++) { + if (FD_ISSET(fd, set)) { + lua_pushnumber(L, ++start); + lua_pushnumber(L, fd); + lua_gettable(L, itab); + lua_settable(L, tab); + } + } +} + +static void make_assoc(lua_State *L, int tab) { + int i = 1, atab; + lua_newtable(L); atab = lua_gettop(L); + while (1) { + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (!lua_isnil(L, -1)) { + lua_pushnumber(L, i); + lua_pushvalue(L, -2); + lua_settable(L, atab); + lua_pushnumber(L, i); + lua_settable(L, atab); + } else { + lua_pop(L, 1); + break; + } + i = i+1; + } +} + diff --git a/src/luasocket/select.h b/src/luasocket/select.h new file mode 100644 index 0000000..aa3db4a --- /dev/null +++ b/src/luasocket/select.h @@ -0,0 +1,17 @@ +#ifndef SELECT_H +#define SELECT_H +/*=========================================================================*\ +* Select implementation +* LuaSocket toolkit +* +* Each object that can be passed to the select function has to export +* method getfd() which returns the descriptor to be passed to the +* underlying select function. Another method, dirty(), should return +* true if there is data ready for reading (required for buffered input). +* +* RCS ID: $Id: select.h,v 1.7 2004/06/16 01:02:07 diego Exp $ +\*=========================================================================*/ + +int select_open(lua_State *L); + +#endif /* SELECT_H */ diff --git a/src/luasocket/smtp.lua b/src/luasocket/smtp.lua new file mode 100644 index 0000000..11aa451 --- /dev/null +++ b/src/luasocket/smtp.lua @@ -0,0 +1,245 @@ +----------------------------------------------------------------------------- +-- SMTP client support for the Lua language. +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: smtp.lua,v 1.44 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local coroutine = require("coroutine") +local string = require("string") +local math = require("math") +local os = require("os") +local socket = require("socket") +local tp = require("socket.tp") +local ltn12 = require("ltn12") +local mime = require("mime") +module("socket.smtp") + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- timeout for connection +TIMEOUT = 60 +-- default server used to send e-mails +SERVER = "localhost" +-- default port +PORT = 25 +-- domain used in HELO command and default sendmail +-- If we are under a CGI, try to get from environment +DOMAIN = os.getenv("SERVER_NAME") or "localhost" +-- default time zone (means we don't know) +ZONE = "-0000" + +--------------------------------------------------------------------------- +-- Low level SMTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function metat.__index:greet(domain) + self.try(self.tp:check("2..")) + self.try(self.tp:command("EHLO", domain or DOMAIN)) + return socket.skip(1, self.try(self.tp:check("2.."))) +end + +function metat.__index:mail(from) + self.try(self.tp:command("MAIL", "FROM:" .. from)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:rcpt(to) + self.try(self.tp:command("RCPT", "TO:" .. to)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:data(src, step) + self.try(self.tp:command("DATA")) + self.try(self.tp:check("3..")) + self.try(self.tp:source(src, step)) + self.try(self.tp:send("\r\n.\r\n")) + return self.try(self.tp:check("2..")) +end + +function metat.__index:quit() + self.try(self.tp:command("QUIT")) + return self.try(self.tp:check("2..")) +end + +function metat.__index:close() + return self.tp:close() +end + +function metat.__index:login(user, password) + self.try(self.tp:command("AUTH", "LOGIN")) + self.try(self.tp:check("3..")) + self.try(self.tp:command(mime.b64(user))) + self.try(self.tp:check("3..")) + self.try(self.tp:command(mime.b64(password))) + return self.try(self.tp:check("2..")) +end + +function metat.__index:plain(user, password) + local auth = "PLAIN " .. mime.b64("\0" .. user .. "\0" .. password) + self.try(self.tp:command("AUTH", auth)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:auth(user, password, ext) + if not user or not password then return 1 end + if string.find(ext, "AUTH[^\n]+LOGIN") then + return self:login(user, password) + elseif string.find(ext, "AUTH[^\n]+PLAIN") then + return self:plain(user, password) + else + self.try(nil, "authentication not supported") + end +end + +-- send message or throw an exception +function metat.__index:send(mailt) + self:mail(mailt.from) + if base.type(mailt.rcpt) == "table" then + for i,v in base.ipairs(mailt.rcpt) do + self:rcpt(v) + end + else + self:rcpt(mailt.rcpt) + end + self:data(ltn12.source.chain(mailt.source, mime.stuff()), mailt.step) +end + +function open(server, port, create) + local tp = socket.try(tp.connect(server or SERVER, port or PORT, + create, TIMEOUT)) + local s = base.setmetatable({tp = tp}, metat) + -- make sure tp is closed if we get an exception + s.try = socket.newtry(function() + s:close() + end) + return s +end + +--------------------------------------------------------------------------- +-- Multipart message source +----------------------------------------------------------------------------- +-- returns a hopefully unique mime boundary +local seqno = 0 +local function newboundary() + seqno = seqno + 1 + return string.format('%s%05d==%05u', os.date('%d%m%Y%H%M%S'), + math.random(0, 99999), seqno) +end + +-- send_message forward declaration +local send_message + +-- yield the headers all at once, it's faster +local function send_headers(headers) + local h = "\r\n" + for i,v in base.pairs(headers) do + h = i .. ': ' .. v .. "\r\n" .. h + end + coroutine.yield(h) +end + +-- yield multipart message body from a multipart message table +local function send_multipart(mesgt) + -- make sure we have our boundary and send headers + local bd = newboundary() + local headers = mesgt.headers or {} + headers['content-type'] = headers['content-type'] or 'multipart/mixed' + headers['content-type'] = headers['content-type'] .. + '; boundary="' .. bd .. '"' + send_headers(headers) + -- send preamble + if mesgt.body.preamble then + coroutine.yield(mesgt.body.preamble) + coroutine.yield("\r\n") + end + -- send each part separated by a boundary + for i, m in base.ipairs(mesgt.body) do + coroutine.yield("\r\n--" .. bd .. "\r\n") + send_message(m) + end + -- send last boundary + coroutine.yield("\r\n--" .. bd .. "--\r\n\r\n") + -- send epilogue + if mesgt.body.epilogue then + coroutine.yield(mesgt.body.epilogue) + coroutine.yield("\r\n") + end +end + +-- yield message body from a source +local function send_source(mesgt) + -- make sure we have a content-type + local headers = mesgt.headers or {} + headers['content-type'] = headers['content-type'] or + 'text/plain; charset="iso-8859-1"' + send_headers(headers) + -- send body from source + while true do + local chunk, err = mesgt.body() + if err then coroutine.yield(nil, err) + elseif chunk then coroutine.yield(chunk) + else break end + end +end + +-- yield message body from a string +local function send_string(mesgt) + -- make sure we have a content-type + local headers = mesgt.headers or {} + headers['content-type'] = headers['content-type'] or + 'text/plain; charset="iso-8859-1"' + send_headers(headers) + -- send body from string + coroutine.yield(mesgt.body) +end + +-- message source +function send_message(mesgt) + if base.type(mesgt.body) == "table" then send_multipart(mesgt) + elseif base.type(mesgt.body) == "function" then send_source(mesgt) + else send_string(mesgt) end +end + +-- set defaul headers +local function adjust_headers(mesgt) + local lower = {} + for i,v in base.pairs(mesgt.headers or lower) do + lower[string.lower(i)] = v + end + lower["date"] = lower["date"] or + os.date("!%a, %d %b %Y %H:%M:%S ") .. (mesgt.zone or ZONE) + lower["x-mailer"] = lower["x-mailer"] or socket._VERSION + -- this can't be overriden + lower["mime-version"] = "1.0" + mesgt.headers = lower +end + +function message(mesgt) + adjust_headers(mesgt) + -- create and return message source + local co = coroutine.create(function() send_message(mesgt) end) + return function() + local ret, a, b = coroutine.resume(co) + if ret then return a, b + else return nil, a end + end +end + +--------------------------------------------------------------------------- +-- High level SMTP API +----------------------------------------------------------------------------- +send = socket.protect(function(mailt) + local s = open(mailt.server, mailt.port, mailt.create) + local ext = s:greet(mailt.domain) + s:auth(mailt.user, mailt.password, ext) + s:send(mailt) + s:quit() + return s:close() +end) diff --git a/src/luasocket/socket.h b/src/luasocket/socket.h new file mode 100644 index 0000000..656c7f5 --- /dev/null +++ b/src/luasocket/socket.h @@ -0,0 +1,76 @@ +#ifndef SOCKET_H +#define SOCKET_H +/*=========================================================================*\ +* Socket compatibilization module +* LuaSocket toolkit +* +* BSD Sockets and WinSock are similar, but there are a few irritating +* differences. Also, not all *nix platforms behave the same. This module +* (and the associated usocket.h and wsocket.h) factor these differences and +* creates a interface compatible with the io.h module. +* +* RCS ID: $Id: socket.h,v 1.20 2005/11/20 07:20:23 diego Exp $ +\*=========================================================================*/ +#include "io.h" + +/*=========================================================================*\ +* Platform specific compatibilization +\*=========================================================================*/ +#ifdef _WIN32 +#include "wsocket.h" +#else +#include "usocket.h" +#endif + +/*=========================================================================*\ +* The connect and accept functions accept a timeout and their +* implementations are somewhat complicated. We chose to move +* the timeout control into this module for these functions in +* order to simplify the modules that use them. +\*=========================================================================*/ +#include "timeout.h" + +/* we are lazy... */ +typedef struct sockaddr SA; + +/*=========================================================================*\ +* Functions bellow implement a comfortable platform independent +* interface to sockets +\*=========================================================================*/ +int socket_open(void); +int socket_close(void); +void socket_destroy(p_socket ps); +void socket_shutdown(p_socket ps, int how); +int socket_sendto(p_socket ps, const char *data, size_t count, + size_t *sent, SA *addr, socklen_t addr_len, p_timeout tm); +int socket_recvfrom(p_socket ps, char *data, size_t count, + size_t *got, SA *addr, socklen_t *addr_len, p_timeout tm); + +void socket_setnonblocking(p_socket ps); +void socket_setblocking(p_socket ps); + +int socket_waitfd(p_socket ps, int sw, p_timeout tm); +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm); + +int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm); +int socket_create(p_socket ps, int domain, int type, int protocol); +int socket_bind(p_socket ps, SA *addr, socklen_t addr_len); +int socket_listen(p_socket ps, int backlog); +int socket_accept(p_socket ps, p_socket pa, SA *addr, + socklen_t *addr_len, p_timeout tm); + +const char *socket_hoststrerror(int err); +const char *socket_strerror(int err); + +/* these are perfect to use with the io abstraction module + and the buffered input module */ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm); +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm); +const char *socket_ioerror(p_socket ps, int err); + +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp); +int socket_gethostbyname(const char *addr, struct hostent **hp); + +#endif /* SOCKET_H */ diff --git a/src/luasocket/socket.lua b/src/luasocket/socket.lua new file mode 100644 index 0000000..211adcd --- /dev/null +++ b/src/luasocket/socket.lua @@ -0,0 +1,133 @@ +----------------------------------------------------------------------------- +-- LuaSocket helper module +-- Author: Diego Nehab +-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local string = require("string") +local math = require("math") +local socket = require("socket.core") +module("socket") + +----------------------------------------------------------------------------- +-- Exported auxiliar functions +----------------------------------------------------------------------------- +function connect(address, port, laddress, lport) + local sock, err = socket.tcp() + if not sock then return nil, err end + if laddress then + local res, err = sock:bind(laddress, lport, -1) + if not res then return nil, err end + end + local res, err = sock:connect(address, port) + if not res then return nil, err end + return sock +end + +function bind(host, port, backlog) + local sock, err = socket.tcp() + if not sock then return nil, err end + sock:setoption("reuseaddr", true) + local res, err = sock:bind(host, port) + if not res then return nil, err end + res, err = sock:listen(backlog) + if not res then return nil, err end + return sock +end + +try = newtry() + +function choose(table) + return function(name, opt1, opt2) + if base.type(name) ~= "string" then + name, opt1, opt2 = "default", name, opt1 + end + local f = table[name or "nil"] + if not f then base.error("unknown key (".. base.tostring(name) ..")", 3) + else return f(opt1, opt2) end + end +end + +----------------------------------------------------------------------------- +-- Socket sources and sinks, conforming to LTN12 +----------------------------------------------------------------------------- +-- create namespaces inside LuaSocket namespace +sourcet = {} +sinkt = {} + +BLOCKSIZE = 2048 + +sinkt["close-when-done"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if not chunk then + sock:close() + return 1 + else return sock:send(chunk) end + end + }) +end + +sinkt["keep-open"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if chunk then return sock:send(chunk) + else return 1 end + end + }) +end + +sinkt["default"] = sinkt["keep-open"] + +sink = choose(sinkt) + +sourcet["by-length"] = function(sock, length) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + if length <= 0 then return nil end + local size = math.min(socket.BLOCKSIZE, length) + local chunk, err = sock:receive(size) + if err then return nil, err end + length = length - string.len(chunk) + return chunk + end + }) +end + +sourcet["until-closed"] = function(sock) + local done + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + if done then return nil end + local chunk, err, partial = sock:receive(socket.BLOCKSIZE) + if not err then return chunk + elseif err == "closed" then + sock:close() + done = 1 + return partial + else return nil, err end + end + }) +end + + +sourcet["default"] = sourcet["until-closed"] + +source = choose(sourcet) + diff --git a/src/luasocket/tcp.c b/src/luasocket/tcp.c new file mode 100644 index 0000000..6b8a79b --- /dev/null +++ b/src/luasocket/tcp.c @@ -0,0 +1,339 @@ +/*=========================================================================*\ +* TCP object +* LuaSocket toolkit +* +* RCS ID: $Id: tcp.c,v 1.41 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "inet.h" +#include "options.h" +#include "tcp.h" + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int meth_connect(lua_State *L); +static int meth_listen(lua_State *L); +static int meth_bind(lua_State *L); +static int meth_send(lua_State *L); +static int meth_getstats(lua_State *L); +static int meth_setstats(lua_State *L); +static int meth_getsockname(lua_State *L); +static int meth_getpeername(lua_State *L); +static int meth_shutdown(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_accept(lua_State *L); +static int meth_close(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); + +/* tcp object methods */ +static luaL_reg tcp[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"accept", meth_accept}, + {"bind", meth_bind}, + {"close", meth_close}, + {"connect", meth_connect}, + {"dirty", meth_dirty}, + {"getfd", meth_getfd}, + {"getpeername", meth_getpeername}, + {"getsockname", meth_getsockname}, + {"getstats", meth_getstats}, + {"setstats", meth_setstats}, + {"listen", meth_listen}, + {"receive", meth_receive}, + {"send", meth_send}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"setpeername", meth_connect}, + {"setsockname", meth_bind}, + {"settimeout", meth_settimeout}, + {"shutdown", meth_shutdown}, + {NULL, NULL} +}; + +/* socket option handlers */ +static t_opt opt[] = { + {"keepalive", opt_keepalive}, + {"reuseaddr", opt_reuseaddr}, + {"tcp-nodelay", opt_tcp_nodelay}, + {"linger", opt_linger}, + {NULL, NULL} +}; + +/* functions in library namespace */ +static luaL_reg func[] = { + {"tcp", global_create}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int tcp_open(lua_State *L) +{ + /* create classes */ + auxiliar_newclass(L, "tcp{master}", tcp); + auxiliar_newclass(L, "tcp{client}", tcp); + auxiliar_newclass(L, "tcp{server}", tcp); + /* create class groups */ + auxiliar_add2group(L, "tcp{master}", "tcp{any}"); + auxiliar_add2group(L, "tcp{client}", "tcp{any}"); + auxiliar_add2group(L, "tcp{server}", "tcp{any}"); + /* define library functions */ + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Just call buffered IO methods +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_send(L, &tcp->buf); +} + +static int meth_receive(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_receive(L, &tcp->buf); +} + +static int meth_getstats(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_getstats(L, &tcp->buf); +} + +static int meth_setstats(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_setstats(L, &tcp->buf); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_setoption(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return opt_meth_setoption(L, opt, &tcp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + lua_pushnumber(L, (int) tcp->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + tcp->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + lua_pushboolean(L, !buffer_isempty(&tcp->buf)); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Waits for and returns a client object attempting connection to the +* server object +\*-------------------------------------------------------------------------*/ +static int meth_accept(lua_State *L) +{ + p_tcp server = (p_tcp) auxiliar_checkclass(L, "tcp{server}", 1); + p_timeout tm = timeout_markstart(&server->tm); + t_socket sock; + int err = socket_accept(&server->sock, &sock, NULL, NULL, tm); + /* if successful, push client socket */ + if (err == IO_DONE) { + p_tcp clnt = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); + auxiliar_setclass(L, "tcp{client}", -1); + /* initialize structure fields */ + socket_setnonblocking(&sock); + clnt->sock = sock; + io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &clnt->sock); + timeout_init(&clnt->tm, -1, -1); + buffer_init(&clnt->buf, &clnt->io, &clnt->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Binds an object to an address +\*-------------------------------------------------------------------------*/ +static int meth_bind(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1); + const char *address = luaL_checkstring(L, 2); + unsigned short port = (unsigned short) luaL_checknumber(L, 3); + const char *err = inet_trybind(&tcp->sock, address, port); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master tcp object into a client object. +\*-------------------------------------------------------------------------*/ +static int meth_connect(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + const char *address = luaL_checkstring(L, 2); + unsigned short port = (unsigned short) luaL_checknumber(L, 3); + p_timeout tm = timeout_markstart(&tcp->tm); + const char *err = inet_tryconnect(&tcp->sock, address, port, tm); + /* have to set the class even if it failed due to non-blocking connects */ + auxiliar_setclass(L, "tcp{client}", 1); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + /* turn master object into a client object */ + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + socket_destroy(&tcp->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Puts the sockt in listen mode +\*-------------------------------------------------------------------------*/ +static int meth_listen(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1); + int backlog = (int) luaL_optnumber(L, 2, 32); + int err = socket_listen(&tcp->sock, backlog); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } + /* turn master object into a server object */ + auxiliar_setclass(L, "tcp{server}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Shuts the connection down partially +\*-------------------------------------------------------------------------*/ +static int meth_shutdown(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + const char *how = luaL_optstring(L, 2, "both"); + switch (how[0]) { + case 'b': + if (strcmp(how, "both")) goto error; + socket_shutdown(&tcp->sock, 2); + break; + case 's': + if (strcmp(how, "send")) goto error; + socket_shutdown(&tcp->sock, 1); + break; + case 'r': + if (strcmp(how, "receive")) goto error; + socket_shutdown(&tcp->sock, 0); + break; + } + lua_pushnumber(L, 1); + return 1; +error: + luaL_argerror(L, 2, "invalid shutdown method"); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Just call inet methods +\*-------------------------------------------------------------------------*/ +static int meth_getpeername(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return inet_meth_getpeername(L, &tcp->sock); +} + +static int meth_getsockname(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return inet_meth_getsockname(L, &tcp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return timeout_meth_settimeout(L, &tcp->tm); +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master tcp object +\*-------------------------------------------------------------------------*/ +static int global_create(lua_State *L) +{ + t_socket sock; + const char *err = inet_trycreate(&sock, SOCK_STREAM); + /* try to allocate a system socket */ + if (!err) { + /* allocate tcp object */ + p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); + /* set its type as master object */ + auxiliar_setclass(L, "tcp{master}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + tcp->sock = sock; + io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &tcp->sock); + timeout_init(&tcp->tm, -1, -1); + buffer_init(&tcp->buf, &tcp->io, &tcp->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } +} diff --git a/src/luasocket/tcp.h b/src/luasocket/tcp.h new file mode 100644 index 0000000..511357f --- /dev/null +++ b/src/luasocket/tcp.h @@ -0,0 +1,36 @@ +#ifndef TCP_H +#define TCP_H +/*=========================================================================*\ +* TCP object +* LuaSocket toolkit +* +* The tcp.h module is basicly a glue that puts together modules buffer.h, +* timeout.h socket.h and inet.h to provide the LuaSocket TCP (AF_INET, +* SOCK_STREAM) support. +* +* Three classes are defined: master, client and server. The master class is +* a newly created tcp object, that has not been bound or connected. Server +* objects are tcp objects bound to some local address. Client objects are +* tcp objects either connected to some address or returned by the accept +* method of a server object. +* +* RCS ID: $Id: tcp.h,v 1.7 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +#include "buffer.h" +#include "timeout.h" +#include "socket.h" + +typedef struct t_tcp_ { + t_socket sock; + t_io io; + t_buffer buf; + t_timeout tm; +} t_tcp; + +typedef t_tcp *p_tcp; + +int tcp_open(lua_State *L); + +#endif /* TCP_H */ diff --git a/src/luasocket/timeout.c b/src/luasocket/timeout.c new file mode 100644 index 0000000..c1df102 --- /dev/null +++ b/src/luasocket/timeout.c @@ -0,0 +1,207 @@ +/*=========================================================================*\ +* Timeout management functions +* LuaSocket toolkit +* +* RCS ID: $Id: timeout.c,v 1.30 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "timeout.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int timeout_lua_gettime(lua_State *L); +static int timeout_lua_sleep(lua_State *L); + +static luaL_reg func[] = { + { "gettime", timeout_lua_gettime }, + { "sleep", timeout_lua_sleep }, + { NULL, NULL } +}; + +/*=========================================================================*\ +* Exported functions. +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initialize structure +\*-------------------------------------------------------------------------*/ +void timeout_init(p_timeout tm, double block, double total) { + tm->block = block; + tm->total = total; +} + +/*-------------------------------------------------------------------------*\ +* Determines how much time we have left for the next system call, +* if the previous call was successful +* Input +* tm: timeout control structure +* Returns +* the number of ms left or -1 if there is no time limit +\*-------------------------------------------------------------------------*/ +double timeout_get(p_timeout tm) { + if (tm->block < 0.0 && tm->total < 0.0) { + return -1; + } else if (tm->block < 0.0) { + double t = tm->total - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else if (tm->total < 0.0) { + return tm->block; + } else { + double t = tm->total - timeout_gettime() + tm->start; + return MIN(tm->block, MAX(t, 0.0)); + } +} + +/*-------------------------------------------------------------------------*\ +* Returns time since start of operation +* Input +* tm: timeout control structure +* Returns +* start field of structure +\*-------------------------------------------------------------------------*/ +double timeout_getstart(p_timeout tm) { + return tm->start; +} + +/*-------------------------------------------------------------------------*\ +* Determines how much time we have left for the next system call, +* if the previous call was a failure +* Input +* tm: timeout control structure +* Returns +* the number of ms left or -1 if there is no time limit +\*-------------------------------------------------------------------------*/ +double timeout_getretry(p_timeout tm) { + if (tm->block < 0.0 && tm->total < 0.0) { + return -1; + } else if (tm->block < 0.0) { + double t = tm->total - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else if (tm->total < 0.0) { + double t = tm->block - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else { + double t = tm->total - timeout_gettime() + tm->start; + return MIN(tm->block, MAX(t, 0.0)); + } +} + +/*-------------------------------------------------------------------------*\ +* Marks the operation start time in structure +* Input +* tm: timeout control structure +\*-------------------------------------------------------------------------*/ +p_timeout timeout_markstart(p_timeout tm) { + tm->start = timeout_gettime(); + return tm; +} + +/*-------------------------------------------------------------------------*\ +* Gets time in s, relative to January 1, 1970 (UTC) +* Returns +* time in s. +\*-------------------------------------------------------------------------*/ +#ifdef _WIN32 +double timeout_gettime(void) { + FILETIME ft; + double t; + GetSystemTimeAsFileTime(&ft); + /* Windows file time (time since January 1, 1601 (UTC)) */ + t = ft.dwLowDateTime/1.0e7 + ft.dwHighDateTime*(4294967296.0/1.0e7); + /* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */ + return (t - 11644473600.0); +} +#else +double timeout_gettime(void) { + struct timeval v; + gettimeofday(&v, (struct timezone *) NULL); + /* Unix Epoch time (time since January 1, 1970 (UTC)) */ + return v.tv_sec + v.tv_usec/1.0e6; +} +#endif + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int timeout_open(lua_State *L) { + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Sets timeout values for IO operations +* Lua Input: base, time [, mode] +* time: time out value in seconds +* mode: "b" for block timeout, "t" for total timeout. (default: b) +\*-------------------------------------------------------------------------*/ +int timeout_meth_settimeout(lua_State *L, p_timeout tm) { + double t = luaL_optnumber(L, 2, -1); + const char *mode = luaL_optstring(L, 3, "b"); + switch (*mode) { + case 'b': + tm->block = t; + break; + case 'r': case 't': + tm->total = t; + break; + default: + luaL_argcheck(L, 0, 3, "invalid timeout mode"); + break; + } + lua_pushnumber(L, 1); + return 1; +} + +/*=========================================================================*\ +* Test support functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Returns the time the system has been up, in secconds. +\*-------------------------------------------------------------------------*/ +static int timeout_lua_gettime(lua_State *L) +{ + lua_pushnumber(L, timeout_gettime()); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Sleep for n seconds. +\*-------------------------------------------------------------------------*/ +int timeout_lua_sleep(lua_State *L) +{ + double n = luaL_checknumber(L, 1); +#ifdef _WIN32 + Sleep((int)(n*1000)); +#else + struct timespec t, r; + t.tv_sec = (int) n; + n -= t.tv_sec; + t.tv_nsec = (int) (n * 1000000000); + if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999; + while (nanosleep(&t, &r) != 0) { + t.tv_sec = r.tv_sec; + t.tv_nsec = r.tv_nsec; + } +#endif + return 0; +} diff --git a/src/luasocket/timeout.h b/src/luasocket/timeout.h new file mode 100644 index 0000000..d2d8964 --- /dev/null +++ b/src/luasocket/timeout.h @@ -0,0 +1,30 @@ +#ifndef TIMEOUT_H +#define TIMEOUT_H +/*=========================================================================*\ +* Timeout management functions +* LuaSocket toolkit +* +* RCS ID: $Id: timeout.h,v 1.14 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +/* timeout control structure */ +typedef struct t_timeout_ { + double block; /* maximum time for blocking calls */ + double total; /* total number of miliseconds for operation */ + double start; /* time of start of operation */ +} t_timeout; +typedef t_timeout *p_timeout; + +int timeout_open(lua_State *L); +void timeout_init(p_timeout tm, double block, double total); +double timeout_get(p_timeout tm); +double timeout_getretry(p_timeout tm); +p_timeout timeout_markstart(p_timeout tm); +double timeout_getstart(p_timeout tm); +double timeout_gettime(void); +int timeout_meth_settimeout(lua_State *L, p_timeout tm); + +#define timeout_iszero(tm) ((tm)->block == 0.0) + +#endif /* TIMEOUT_H */ diff --git a/src/luasocket/tmp/list b/src/luasocket/tmp/list new file mode 100644 index 0000000..c75d467 --- /dev/null +++ b/src/luasocket/tmp/list @@ -0,0 +1,115 @@ + +#ifndef FUCK_THAT +#define FUCK_THAT + +typedef t_sock t_socket; +typedef t_timeout t_tm; +typedef t_buffer t_buf; + +#define sock_open socket_open +#define sock_close socket_close +#define sock_destroy socket_destroy +#define sock_shutdown socket_shutdown +#define sock_sendto socket_sendto +#define sock_recvfrom socket_recvfrom +#define sock_setnonblocking socket_setnonblocking +#define sock_setblocking socket_setblocking +#define sock_waitfd socket_waitfd +#define sock_select socket_select +#define sock_connect socket_connect +#define sock_create socket_create +#define sock_bind socket_bind +#define sock_listen socket_listen +#define sock_accept socket_accept +#define sock_send socket_send +#define sock_recv socket_recv +#define sock_gethostbyaddr socket_gethostbyaddr +#define sock_gethostbyname socket_gethostbyname +#define sock_waitfd socket_waitfd +#define sock_waitfd socket_waitfd +#define sock_open socket_open +#define sock_close socket_close +#define sock_destroy socket_destroy +#define sock_select socket_select +#define sock_create socket_create +#define sock_bind socket_bind +#define sock_listen socket_listen +#define sock_shutdown socket_shutdown +#define sock_connect socket_connect +#define sock_accept socket_accept +#define sock_send socket_send +#define sock_sendto socket_sendto +#define sock_recv socket_recv +#define sock_recvfrom socket_recvfrom +#define sock_setblocking socket_setblocking +#define sock_setnonblocking socket_setnonblocking +#define sock_gethostbyaddr socket_gethostbyaddr +#define sock_gethostbyname socket_gethostbyname +#define sock_open socket_open +#define sock_close socket_close +#define sock_waitfd socket_waitfd +#define sock_select socket_select +#define sock_destroy socket_destroy +#define sock_shutdown socket_shutdown +#define sock_create socket_create +#define sock_connect socket_connect +#define sock_bind socket_bind +#define sock_listen socket_listen +#define sock_accept socket_accept +#define sock_send socket_send +#define sock_sendto socket_sendto +#define sock_recv socket_recv +#define sock_recvfrom socket_recvfrom +#define sock_setblocking socket_setblocking +#define sock_setnonblocking socket_setnonblocking +#define sock_gethostbyaddr socket_gethostbyaddr +#define sock_gethostbyname socket_gethostbyname + +#define aux_open auxiliar_open +#define aux_newclass auxiliar_newclass +#define aux_tostring auxiliar_tostring +#define aux_add2group auxiliar_add2group +#define aux_checkboolean auxiliar_checkboolean +#define aux_setclass auxiliar_setclass +#define aux_open auxiliar_open +#define aux_newclass auxiliar_newclass +#define aux_add2group auxiliar_add2group +#define aux_setclass auxiliar_setclass +#define aux_checkboolean auxiliar_checkboolean +#define aux_tostring auxiliar_tostring + +#define tm_init timeout_init +#define tm_get timeout_get +#define tm_getstart timeout_getstart +#define tm_getretry timeout_getretry +#define tm_markstart timeout_markstart +#define tm_gettime timeout_gettime +#define tm_gettime timeout_gettime +#define tm_open timeout_open +#define tm_meth_settimeout timeout_meth_settimeout +#define tm_lua_sleep timeout_lua_sleep +#define tm_open timeout_open +#define tm_init timeout_init +#define tm_get timeout_get +#define tm_getretry timeout_getretry +#define tm_markstart timeout_markstart +#define tm_getstart timeout_getstart +#define tm_gettime timeout_gettime +#define tm_meth_settimeout timeout_meth_settimeout + +#define buf_open buffer_open +#define buf_init buffer_init +#define buf_meth_getstats buffer_meth_getstats +#define buf_meth_setstats buffer_meth_setstats +#define buf_meth_send buffer_meth_send +#define buf_meth_receive buffer_meth_receive +#define buf_isempty buffer_isempty +#define buf_open buffer_open +#define buf_init buffer_init +#define buf_meth_send buffer_meth_send +#define buf_meth_receive buffer_meth_receive +#define buf_meth_getstats buffer_meth_getstats +#define buf_meth_setstats buffer_meth_setstats +#define buf_isempty buffer_isempty + +#endif /* FUCK_THAT */ diff --git a/src/luasocket/tp.lua b/src/luasocket/tp.lua new file mode 100644 index 0000000..1475614 --- /dev/null +++ b/src/luasocket/tp.lua @@ -0,0 +1,123 @@ +----------------------------------------------------------------------------- +-- Unified SMTP/FTP subsystem +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: tp.lua,v 1.21 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local string = require("string") +local socket = require("socket") +local ltn12 = require("ltn12") +module("socket.tp") + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +TIMEOUT = 60 + +----------------------------------------------------------------------------- +-- Implementation +----------------------------------------------------------------------------- +-- gets server reply (works for SMTP and FTP) +local function get_reply(c) + local code, current, sep + local line, err = c:receive() + local reply = line + if err then return nil, err end + code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) + if not code then return nil, "invalid server reply" end + if sep == "-" then -- reply is multiline + repeat + line, err = c:receive() + if err then return nil, err end + current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) + reply = reply .. "\n" .. line + -- reply ends with same code + until code == current and sep == " " + end + return code, reply +end + +-- metatable for sock object +local metat = { __index = {} } + +function metat.__index:check(ok) + local code, reply = get_reply(self.c) + if not code then return nil, reply end + if base.type(ok) ~= "function" then + if base.type(ok) == "table" then + for i, v in base.ipairs(ok) do + if string.find(code, v) then + return base.tonumber(code), reply + end + end + return nil, reply + else + if string.find(code, ok) then return base.tonumber(code), reply + else return nil, reply end + end + else return ok(base.tonumber(code), reply) end +end + +function metat.__index:command(cmd, arg) + if arg then + return self.c:send(cmd .. " " .. arg.. "\r\n") + else + return self.c:send(cmd .. "\r\n") + end +end + +function metat.__index:sink(snk, pat) + local chunk, err = c:receive(pat) + return snk(chunk, err) +end + +function metat.__index:send(data) + return self.c:send(data) +end + +function metat.__index:receive(pat) + return self.c:receive(pat) +end + +function metat.__index:getfd() + return self.c:getfd() +end + +function metat.__index:dirty() + return self.c:dirty() +end + +function metat.__index:getcontrol() + return self.c +end + +function metat.__index:source(source, step) + local sink = socket.sink("keep-open", self.c) + local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) + return ret, err +end + +-- closes the underlying c +function metat.__index:close() + self.c:close() + return 1 +end + +-- connect with server and return c object +function connect(host, port, create, timeout) + local c, e = (create or socket.tcp()) + if not c then return nil, e end + c:settimeout(timeout or TIMEOUT) + local r, e = c:connect(host, port) + if not r then + c:close() + return nil, e + end + return base.setmetatable({c = c}, metat) +end + diff --git a/src/luasocket/udp.c b/src/luasocket/udp.c new file mode 100644 index 0000000..fc25aa0 --- /dev/null +++ b/src/luasocket/udp.c @@ -0,0 +1,336 @@ +/*=========================================================================*\ +* UDP object +* LuaSocket toolkit +* +* RCS ID: $Id: udp.c,v 1.29 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "inet.h" +#include "options.h" +#include "udp.h" + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int meth_send(lua_State *L); +static int meth_sendto(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_receivefrom(lua_State *L); +static int meth_getsockname(lua_State *L); +static int meth_getpeername(lua_State *L); +static int meth_setsockname(lua_State *L); +static int meth_setpeername(lua_State *L); +static int meth_close(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); + +/* udp object methods */ +static luaL_reg udp[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"close", meth_close}, + {"dirty", meth_dirty}, + {"getfd", meth_getfd}, + {"getpeername", meth_getpeername}, + {"getsockname", meth_getsockname}, + {"receive", meth_receive}, + {"receivefrom", meth_receivefrom}, + {"send", meth_send}, + {"sendto", meth_sendto}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"setpeername", meth_setpeername}, + {"setsockname", meth_setsockname}, + {"settimeout", meth_settimeout}, + {NULL, NULL} +}; + +/* socket options */ +static t_opt opt[] = { + {"dontroute", opt_dontroute}, + {"broadcast", opt_broadcast}, + {"reuseaddr", opt_reuseaddr}, + {"ip-multicast-ttl", opt_ip_multicast_ttl}, + {"ip-multicast-loop", opt_ip_multicast_loop}, + {"ip-add-membership", opt_ip_add_membership}, + {"ip-drop-membership", opt_ip_drop_membersip}, + {NULL, NULL} +}; + +/* functions in library namespace */ +static luaL_reg func[] = { + {"udp", global_create}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int udp_open(lua_State *L) +{ + /* create classes */ + auxiliar_newclass(L, "udp{connected}", udp); + auxiliar_newclass(L, "udp{unconnected}", udp); + /* create class groups */ + auxiliar_add2group(L, "udp{connected}", "udp{any}"); + auxiliar_add2group(L, "udp{unconnected}", "udp{any}"); + auxiliar_add2group(L, "udp{connected}", "select{able}"); + auxiliar_add2group(L, "udp{unconnected}", "select{able}"); + /* define library functions */ + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +const char *udp_strerror(int err) { + /* a 'closed' error on an unconnected means the target address was not + * accepted by the transport layer */ + if (err == IO_CLOSED) return "refused"; + else return socket_strerror(err); +} + +/*-------------------------------------------------------------------------*\ +* Send data through connected udp socket +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1); + p_timeout tm = &udp->tm; + size_t count, sent = 0; + int err; + const char *data = luaL_checklstring(L, 2, &count); + timeout_markstart(tm); + err = socket_send(&udp->sock, data, count, &sent, tm); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushnumber(L, sent); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Send data through unconnected udp socket +\*-------------------------------------------------------------------------*/ +static int meth_sendto(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + size_t count, sent = 0; + const char *data = luaL_checklstring(L, 2, &count); + const char *ip = luaL_checkstring(L, 3); + unsigned short port = (unsigned short) luaL_checknumber(L, 4); + p_timeout tm = &udp->tm; + struct sockaddr_in addr; + int err; + memset(&addr, 0, sizeof(addr)); + if (!inet_aton(ip, &addr.sin_addr)) + luaL_argerror(L, 3, "invalid ip address"); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + timeout_markstart(tm); + err = socket_sendto(&udp->sock, data, count, &sent, + (SA *) &addr, sizeof(addr), tm); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushnumber(L, sent); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Receives data from a UDP socket +\*-------------------------------------------------------------------------*/ +static int meth_receive(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + char buffer[UDP_DATAGRAMSIZE]; + size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer)); + int err; + p_timeout tm = &udp->tm; + count = MIN(count, sizeof(buffer)); + timeout_markstart(tm); + err = socket_recv(&udp->sock, buffer, count, &got, tm); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushlstring(L, buffer, got); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Receives data and sender from a UDP socket +\*-------------------------------------------------------------------------*/ +static int meth_receivefrom(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + struct sockaddr_in addr; + socklen_t addr_len = sizeof(addr); + char buffer[UDP_DATAGRAMSIZE]; + size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer)); + int err; + p_timeout tm = &udp->tm; + timeout_markstart(tm); + count = MIN(count, sizeof(buffer)); + err = socket_recvfrom(&udp->sock, buffer, count, &got, + (SA *) &addr, &addr_len, tm); + if (err == IO_DONE) { + lua_pushlstring(L, buffer, got); + lua_pushstring(L, inet_ntoa(addr.sin_addr)); + lua_pushnumber(L, ntohs(addr.sin_port)); + return 3; + } else { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + lua_pushnumber(L, (int) udp->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + udp->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + (void) udp; + lua_pushboolean(L, 0); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Just call inet methods +\*-------------------------------------------------------------------------*/ +static int meth_getpeername(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1); + return inet_meth_getpeername(L, &udp->sock); +} + +static int meth_getsockname(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return inet_meth_getsockname(L, &udp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_setoption(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return opt_meth_setoption(L, opt, &udp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return timeout_meth_settimeout(L, &udp->tm); +} + +/*-------------------------------------------------------------------------*\ +* Turns a master udp object into a client object. +\*-------------------------------------------------------------------------*/ +static int meth_setpeername(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + p_timeout tm = &udp->tm; + const char *address = luaL_checkstring(L, 2); + int connecting = strcmp(address, "*"); + unsigned short port = connecting ? + (unsigned short) luaL_checknumber(L, 3) : + (unsigned short) luaL_optnumber(L, 3, 0); + const char *err = inet_tryconnect(&udp->sock, address, port, tm); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + /* change class to connected or unconnected depending on address */ + if (connecting) auxiliar_setclass(L, "udp{connected}", 1); + else auxiliar_setclass(L, "udp{unconnected}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + socket_destroy(&udp->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master object into a server object +\*-------------------------------------------------------------------------*/ +static int meth_setsockname(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + const char *address = luaL_checkstring(L, 2); + unsigned short port = (unsigned short) luaL_checknumber(L, 3); + const char *err = inet_trybind(&udp->sock, address, port); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master udp object +\*-------------------------------------------------------------------------*/ +static int global_create(lua_State *L) { + t_socket sock; + const char *err = inet_trycreate(&sock, SOCK_DGRAM); + /* try to allocate a system socket */ + if (!err) { + /* allocate tcp object */ + p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp)); + auxiliar_setclass(L, "udp{unconnected}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + udp->sock = sock; + timeout_init(&udp->tm, -1, -1); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } +} diff --git a/src/luasocket/udp.h b/src/luasocket/udp.h new file mode 100644 index 0000000..2801712 --- /dev/null +++ b/src/luasocket/udp.h @@ -0,0 +1,33 @@ +#ifndef UDP_H +#define UDP_H +/*=========================================================================*\ +* UDP object +* LuaSocket toolkit +* +* The udp.h module provides LuaSocket with support for UDP protocol +* (AF_INET, SOCK_DGRAM). +* +* Two classes are defined: connected and unconnected. UDP objects are +* originally unconnected. They can be "connected" to a given address +* with a call to the setpeername function. The same function can be used to +* break the connection. +* +* RCS ID: $Id: udp.h,v 1.10 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +#include "timeout.h" +#include "socket.h" + +/* can't be larger than wsocket.c MAXCHUNK!!! */ +#define UDP_DATAGRAMSIZE 8192 + +typedef struct t_udp_ { + t_socket sock; + t_timeout tm; +} t_udp; +typedef t_udp *p_udp; + +int udp_open(lua_State *L); + +#endif /* UDP_H */ diff --git a/src/luasocket/unix.c b/src/luasocket/unix.c new file mode 100644 index 0000000..5c0d6f7 --- /dev/null +++ b/src/luasocket/unix.c @@ -0,0 +1,348 @@ +/*=========================================================================*\ +* Unix domain socket +* LuaSocket toolkit +* +* RCS ID: $Id: unix.c,v 1.12 2005/10/05 03:17:29 diego Exp $ +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "options.h" +#include "unix.h" +#include + +#include "mycompat.h" + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int meth_connect(lua_State *L); +static int meth_listen(lua_State *L); +static int meth_bind(lua_State *L); +static int meth_send(lua_State *L); +static int meth_shutdown(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_accept(lua_State *L); +static int meth_close(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); +static int meth_getstats(lua_State *L); +static int meth_setstats(lua_State *L); + +static const char *unix_tryconnect(p_unix un, const char *path); +static const char *unix_trybind(p_unix un, const char *path); + +/* unix object methods */ +static luaL_reg un[] = { + {"__gc", meth_close}, + {"__tostring", aux_tostring}, + {"accept", meth_accept}, + {"bind", meth_bind}, + {"close", meth_close}, + {"connect", meth_connect}, + {"dirty", meth_dirty}, + {"getfd", meth_getfd}, + {"getstats", meth_getstats}, + {"setstats", meth_setstats}, + {"listen", meth_listen}, + {"receive", meth_receive}, + {"send", meth_send}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"setpeername", meth_connect}, + {"setsockname", meth_bind}, + {"settimeout", meth_settimeout}, + {"shutdown", meth_shutdown}, + {NULL, NULL} +}; + +/* socket option handlers */ +static t_opt opt[] = { + {"keepalive", opt_keepalive}, + {"reuseaddr", opt_reuseaddr}, + {"linger", opt_linger}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int luaopen_socketunix(lua_State *L) { + /* create classes */ + aux_newclass(L, "unix{master}", un); + aux_newclass(L, "unix{client}", un); + aux_newclass(L, "unix{server}", un); + /* create class groups */ + aux_add2group(L, "unix{master}", "unix{any}"); + aux_add2group(L, "unix{client}", "unix{any}"); + aux_add2group(L, "unix{server}", "unix{any}"); + /* define library functions */ + lua_pushcfunction(L, global_create); + return 1; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Just call buffered IO methods +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_unix un = (p_unix) aux_checkclass(L, "unix{client}", 1); + return buf_meth_send(L, &un->buf); +} + +static int meth_receive(lua_State *L) { + p_unix un = (p_unix) aux_checkclass(L, "unix{client}", 1); + return buf_meth_receive(L, &un->buf); +} + +static int meth_getstats(lua_State *L) { + p_unix un = (p_unix) aux_checkclass(L, "unix{client}", 1); + return buf_meth_getstats(L, &un->buf); +} + +static int meth_setstats(lua_State *L) { + p_unix un = (p_unix) aux_checkclass(L, "unix{client}", 1); + return buf_meth_setstats(L, &un->buf); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_setoption(lua_State *L) { + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + return opt_meth_setoption(L, opt, &un->sock); +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) { + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + lua_pushnumber(L, (int) un->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) { + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + un->sock = (t_sock) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) { + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + lua_pushboolean(L, !buf_isempty(&un->buf)); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Waits for and returns a client object attempting connection to the +* server object +\*-------------------------------------------------------------------------*/ +static int meth_accept(lua_State *L) { + p_unix server = (p_unix) aux_checkclass(L, "unix{server}", 1); + p_tm tm = tm_markstart(&server->tm); + t_sock sock; + int err = sock_accept(&server->sock, &sock, NULL, NULL, tm); + /* if successful, push client socket */ + if (err == IO_DONE) { + p_unix clnt = (p_unix) lua_newuserdata(L, sizeof(t_unix)); + aux_setclass(L, "unix{client}", -1); + /* initialize structure fields */ + sock_setnonblocking(&sock); + clnt->sock = sock; + io_init(&clnt->io, (p_send)sock_send, (p_recv)sock_recv, + (p_error) sock_ioerror, &clnt->sock); + tm_init(&clnt->tm, -1, -1); + buf_init(&clnt->buf, &clnt->io, &clnt->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, sock_strerror(err)); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Binds an object to an address +\*-------------------------------------------------------------------------*/ +static const char *unix_trybind(p_unix un, const char *path) { + struct sockaddr_un local; + size_t len = strlen(path); + int err; + if (len >= sizeof(local.sun_path)) return "path too long"; + memset(&local, 0, sizeof(local)); + strcpy(local.sun_path, path); + local.sun_family = AF_UNIX; +#ifdef UNIX_HAS_SUN_LEN + local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len) + + len + 1; + err = sock_bind(&un->sock, (SA *) &local, local.sun_len); + +#else + err = sock_bind(&un->sock, (SA *) &local, + sizeof(local.sun_family) + len); +#endif + if (err != IO_DONE) sock_destroy(&un->sock); + return sock_strerror(err); +} + +static int meth_bind(lua_State *L) { + p_unix un = (p_unix) aux_checkclass(L, "unix{master}", 1); + const char *path = luaL_checkstring(L, 2); + const char *err = unix_trybind(un, path); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master unix object into a client object. +\*-------------------------------------------------------------------------*/ +static const char *unix_tryconnect(p_unix un, const char *path) +{ + struct sockaddr_un remote; + int err; + size_t len = strlen(path); + if (len >= sizeof(remote.sun_path)) return "path too long"; + memset(&remote, 0, sizeof(remote)); + strcpy(remote.sun_path, path); + remote.sun_family = AF_UNIX; + tm_markstart(&un->tm); +#ifdef UNIX_HAS_SUN_LEN + remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len) + + len + 1; + err = sock_connect(&un->sock, (SA *) &remote, remote.sun_len, &un->tm); +#else + err = sock_connect(&un->sock, (SA *) &remote, + sizeof(remote.sun_family) + len, &un->tm); +#endif + if (err != IO_DONE) sock_destroy(&un->sock); + return sock_strerror(err); +} + +static int meth_connect(lua_State *L) +{ + p_unix un = (p_unix) aux_checkclass(L, "unix{master}", 1); + const char *path = luaL_checkstring(L, 2); + const char *err = unix_tryconnect(un, path); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + /* turn master object into a client object */ + aux_setclass(L, "unix{client}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) +{ + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + sock_destroy(&un->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Puts the sockt in listen mode +\*-------------------------------------------------------------------------*/ +static int meth_listen(lua_State *L) +{ + p_unix un = (p_unix) aux_checkclass(L, "unix{master}", 1); + int backlog = (int) luaL_optnumber(L, 2, 32); + int err = sock_listen(&un->sock, backlog); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, sock_strerror(err)); + return 2; + } + /* turn master object into a server object */ + aux_setclass(L, "unix{server}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Shuts the connection down partially +\*-------------------------------------------------------------------------*/ +static int meth_shutdown(lua_State *L) +{ + p_unix un = (p_unix) aux_checkclass(L, "unix{client}", 1); + const char *how = luaL_optstring(L, 2, "both"); + switch (how[0]) { + case 'b': + if (strcmp(how, "both")) goto error; + sock_shutdown(&un->sock, 2); + break; + case 's': + if (strcmp(how, "send")) goto error; + sock_shutdown(&un->sock, 1); + break; + case 'r': + if (strcmp(how, "receive")) goto error; + sock_shutdown(&un->sock, 0); + break; + } + lua_pushnumber(L, 1); + return 1; +error: + luaL_argerror(L, 2, "invalid shutdown method"); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) { + p_unix un = (p_unix) aux_checkgroup(L, "unix{any}", 1); + return tm_meth_settimeout(L, &un->tm); +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master unix object +\*-------------------------------------------------------------------------*/ +static int global_create(lua_State *L) { + t_sock sock; + int err = sock_create(&sock, AF_UNIX, SOCK_STREAM, 0); + /* try to allocate a system socket */ + if (err == IO_DONE) { + /* allocate unix object */ + p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); + /* set its type as master object */ + aux_setclass(L, "unix{master}", -1); + /* initialize remaining structure fields */ + sock_setnonblocking(&sock); + un->sock = sock; + io_init(&un->io, (p_send) sock_send, (p_recv) sock_recv, + (p_error) sock_ioerror, &un->sock); + tm_init(&un->tm, -1, -1); + buf_init(&un->buf, &un->io, &un->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, sock_strerror(err)); + return 2; + } +} diff --git a/src/luasocket/unix.h b/src/luasocket/unix.h new file mode 100644 index 0000000..67aded0 --- /dev/null +++ b/src/luasocket/unix.h @@ -0,0 +1,30 @@ +#ifndef UNIX_H +#define UNIX_H +/*=========================================================================*\ +* Unix domain object +* LuaSocket toolkit +* +* This module is just an example of how to extend LuaSocket with a new +* domain. +* +* RCS ID: $Id: unix.h,v 1.8 2005/09/29 06:11:42 diego Exp $ +\*=========================================================================*/ +#include "lua.h" + +#include "buffer.h" +#include "timeout.h" +#include "socket.h" + +#include "mycompat.h" + +typedef struct t_unix_ { + t_sock sock; + t_io io; + t_buf buf; + t_tm tm; +} t_unix; +typedef t_unix *p_unix; + +int luaopen_socketunix(lua_State *L); + +#endif /* UNIX_H */ diff --git a/src/luasocket/url.lua b/src/luasocket/url.lua new file mode 100644 index 0000000..9c1e7b5 --- /dev/null +++ b/src/luasocket/url.lua @@ -0,0 +1,297 @@ +----------------------------------------------------------------------------- +-- URI parsing, composition and relative URL resolution +-- LuaSocket toolkit. +-- Author: Diego Nehab +-- RCS ID: $Id: url.lua,v 1.37 2005/11/22 08:33:29 diego Exp $ +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module +----------------------------------------------------------------------------- +local string = require("string") +local base = _G +local table = require("table") +module("socket.url") + +----------------------------------------------------------------------------- +-- Module version +----------------------------------------------------------------------------- +_VERSION = "URL 1.0" + +----------------------------------------------------------------------------- +-- Encodes a string into its escaped hexadecimal representation +-- Input +-- s: binary string to be encoded +-- Returns +-- escaped representation of string binary +----------------------------------------------------------------------------- +function escape(s) + return string.gsub(s, "([^A-Za-z0-9_])", function(c) + return string.format("%%%02x", string.byte(c)) + end) +end + +----------------------------------------------------------------------------- +-- Protects a path segment, to prevent it from interfering with the +-- url parsing. +-- Input +-- s: binary string to be encoded +-- Returns +-- escaped representation of string binary +----------------------------------------------------------------------------- +local function make_set(t) + local s = {} + for i,v in base.ipairs(t) do + s[t[i]] = 1 + end + return s +end + +-- these are allowed withing a path segment, along with alphanum +-- other characters must be escaped +local segment_set = make_set { + "-", "_", ".", "!", "~", "*", "'", "(", + ")", ":", "@", "&", "=", "+", "$", ",", +} + +local function protect_segment(s) + return string.gsub(s, "([^A-Za-z0-9_])", function (c) + if segment_set[c] then return c + else return string.format("%%%02x", string.byte(c)) end + end) +end + +----------------------------------------------------------------------------- +-- Encodes a string into its escaped hexadecimal representation +-- Input +-- s: binary string to be encoded +-- Returns +-- escaped representation of string binary +----------------------------------------------------------------------------- +function unescape(s) + return string.gsub(s, "%%(%x%x)", function(hex) + return string.char(base.tonumber(hex, 16)) + end) +end + +----------------------------------------------------------------------------- +-- Builds a path from a base path and a relative path +-- Input +-- base_path +-- relative_path +-- Returns +-- corresponding absolute path +----------------------------------------------------------------------------- +local function absolute_path(base_path, relative_path) + if string.sub(relative_path, 1, 1) == "/" then return relative_path end + local path = string.gsub(base_path, "[^/]*$", "") + path = path .. relative_path + path = string.gsub(path, "([^/]*%./)", function (s) + if s ~= "./" then return s else return "" end + end) + path = string.gsub(path, "/%.$", "/") + local reduced + while reduced ~= path do + reduced = path + path = string.gsub(reduced, "([^/]*/%.%./)", function (s) + if s ~= "../../" then return "" else return s end + end) + end + path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) + if s ~= "../.." then return "" else return s end + end) + return path +end + +----------------------------------------------------------------------------- +-- Parses a url and returns a table with all its parts according to RFC 2396 +-- The following grammar describes the names given to the URL parts +-- ::= :///;?# +-- ::= @: +-- ::= [:] +-- :: = {/} +-- Input +-- url: uniform resource locator of request +-- default: table with default values for each field +-- Returns +-- table with the following fields, where RFC naming conventions have +-- been preserved: +-- scheme, authority, userinfo, user, password, host, port, +-- path, params, query, fragment +-- Obs: +-- the leading '/' in {/} is considered part of +----------------------------------------------------------------------------- +function parse(url, default) + -- initialize default parameters + local parsed = {} + for i,v in base.pairs(default or parsed) do parsed[i] = v end + -- empty url is parsed to nil + if not url or url == "" then return nil, "invalid url" end + -- remove whitespace + -- url = string.gsub(url, "%s", "") + -- get fragment + url = string.gsub(url, "#(.*)$", function(f) + parsed.fragment = f + return "" + end) + -- get scheme + url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", + function(s) parsed.scheme = s; return "" end) + -- get authority + url = string.gsub(url, "^//([^/]*)", function(n) + parsed.authority = n + return "" + end) + -- get query stringing + url = string.gsub(url, "%?(.*)", function(q) + parsed.query = q + return "" + end) + -- get params + url = string.gsub(url, "%;(.*)", function(p) + parsed.params = p + return "" + end) + -- path is whatever was left + if url ~= "" then parsed.path = url end + local authority = parsed.authority + if not authority then return parsed end + authority = string.gsub(authority,"^([^@]*)@", + function(u) parsed.userinfo = u; return "" end) + authority = string.gsub(authority, ":([^:]*)$", + function(p) parsed.port = p; return "" end) + if authority ~= "" then parsed.host = authority end + local userinfo = parsed.userinfo + if not userinfo then return parsed end + userinfo = string.gsub(userinfo, ":([^:]*)$", + function(p) parsed.password = p; return "" end) + parsed.user = userinfo + return parsed +end + +----------------------------------------------------------------------------- +-- Rebuilds a parsed URL from its components. +-- Components are protected if any reserved or unallowed characters are found +-- Input +-- parsed: parsed URL, as returned by parse +-- Returns +-- a stringing with the corresponding URL +----------------------------------------------------------------------------- +function build(parsed) + local ppath = parse_path(parsed.path or "") + local url = build_path(ppath) + if parsed.params then url = url .. ";" .. parsed.params end + if parsed.query then url = url .. "?" .. parsed.query end + local authority = parsed.authority + if parsed.host then + authority = parsed.host + if parsed.port then authority = authority .. ":" .. parsed.port end + local userinfo = parsed.userinfo + if parsed.user then + userinfo = parsed.user + if parsed.password then + userinfo = userinfo .. ":" .. parsed.password + end + end + if userinfo then authority = userinfo .. "@" .. authority end + end + if authority then url = "//" .. authority .. url end + if parsed.scheme then url = parsed.scheme .. ":" .. url end + if parsed.fragment then url = url .. "#" .. parsed.fragment end + -- url = string.gsub(url, "%s", "") + return url +end + +----------------------------------------------------------------------------- +-- Builds a absolute URL from a base and a relative URL according to RFC 2396 +-- Input +-- base_url +-- relative_url +-- Returns +-- corresponding absolute url +----------------------------------------------------------------------------- +function absolute(base_url, relative_url) + if base.type(base_url) == "table" then + base_parsed = base_url + base_url = build(base_parsed) + else + base_parsed = parse(base_url) + end + local relative_parsed = parse(relative_url) + if not base_parsed then return relative_url + elseif not relative_parsed then return base_url + elseif relative_parsed.scheme then return relative_url + else + relative_parsed.scheme = base_parsed.scheme + if not relative_parsed.authority then + relative_parsed.authority = base_parsed.authority + if not relative_parsed.path then + relative_parsed.path = base_parsed.path + if not relative_parsed.params then + relative_parsed.params = base_parsed.params + if not relative_parsed.query then + relative_parsed.query = base_parsed.query + end + end + else + relative_parsed.path = absolute_path(base_parsed.path or "", + relative_parsed.path) + end + end + return build(relative_parsed) + end +end + +----------------------------------------------------------------------------- +-- Breaks a path into its segments, unescaping the segments +-- Input +-- path +-- Returns +-- segment: a table with one entry per segment +----------------------------------------------------------------------------- +function parse_path(path) + local parsed = {} + path = path or "" + --path = string.gsub(path, "%s", "") + string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) + for i = 1, table.getn(parsed) do + parsed[i] = unescape(parsed[i]) + end + if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end + if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end + return parsed +end + +----------------------------------------------------------------------------- +-- Builds a path component from its segments, escaping protected characters. +-- Input +-- parsed: path segments +-- unsafe: if true, segments are not protected before path is built +-- Returns +-- path: corresponding path stringing +----------------------------------------------------------------------------- +function build_path(parsed, unsafe) + local path = "" + local n = table.getn(parsed) + if unsafe then + for i = 1, n-1 do + path = path .. parsed[i] + path = path .. "/" + end + if n > 0 then + path = path .. parsed[n] + if parsed.is_directory then path = path .. "/" end + end + else + for i = 1, n-1 do + path = path .. protect_segment(parsed[i]) + path = path .. "/" + end + if n > 0 then + path = path .. protect_segment(parsed[n]) + if parsed.is_directory then path = path .. "/" end + end + end + if parsed.is_absolute then path = "/" .. path end + return path +end diff --git a/src/luasocket/usocket.c b/src/luasocket/usocket.c new file mode 100644 index 0000000..860896e --- /dev/null +++ b/src/luasocket/usocket.c @@ -0,0 +1,370 @@ +/*=========================================================================*\ +* Socket compatibilization module for Unix +* LuaSocket toolkit +* +* The code is now interrupt-safe. +* The penalty of calling select to avoid busy-wait is only paid when +* the I/O call fail in the first place. +* +* RCS ID: $Id: usocket.c,v 1.36 2005/11/22 08:33:29 diego Exp $ +\*=========================================================================*/ +#include +#include + +#include "socket.h" + +/*-------------------------------------------------------------------------*\ +* Wait for readable/writable/connected socket with timeout +\*-------------------------------------------------------------------------*/ +#ifdef SOCKET_POLL +#include + +#define WAITFD_R POLLIN +#define WAITFD_W POLLOUT +#define WAITFD_C (POLLIN|POLLOUT) +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + struct pollfd pfd; + pfd.fd = *ps; + pfd.events = sw; + pfd.revents = 0; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + do { + int t = (int)(timeout_getretry(tm)*1e3); + ret = poll(&pfd, 1, t >= 0? t: -1); + } while (ret == -1 && errno == EINTR); + if (ret == -1) return errno; + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && (pfd.revents & (POLLIN|POLLERR))) return IO_CLOSED; + return IO_DONE; +} +#else + +#define WAITFD_R 1 +#define WAITFD_W 2 +#define WAITFD_C (WAITFD_R|WAITFD_W) + +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + fd_set rfds, wfds, *rp, *wp; + struct timeval tv, *tp; + double t; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + do { + /* must set bits within loop, because select may have modifed them */ + rp = wp = NULL; + if (sw & WAITFD_R) { FD_ZERO(&rfds); FD_SET(*ps, &rfds); rp = &rfds; } + if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; } + t = timeout_getretry(tm); + tp = NULL; + if (t >= 0.0) { + tv.tv_sec = (int)t; + tv.tv_usec = (int)((t-tv.tv_sec)*1.0e6); + tp = &tv; + } + ret = select(*ps+1, rp, wp, NULL, tp); + } while (ret == -1 && errno == EINTR); + if (ret == -1) return errno; + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && FD_ISSET(*ps, &rfds)) return IO_CLOSED; + return IO_DONE; +} +#endif + + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int socket_open(void) { + /* instals a handler to ignore sigpipe or it will crash us */ + signal(SIGPIPE, SIG_IGN); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close module +\*-------------------------------------------------------------------------*/ +int socket_close(void) { + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close and inutilize socket +\*-------------------------------------------------------------------------*/ +void socket_destroy(p_socket ps) { + if (*ps != SOCKET_INVALID) { + socket_setblocking(ps); + close(*ps); + *ps = SOCKET_INVALID; + } +} + +/*-------------------------------------------------------------------------*\ +* Select with timeout control +\*-------------------------------------------------------------------------*/ +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm) { + int ret; + do { + struct timeval tv; + double t = timeout_getretry(tm); + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6); + /* timeout = 0 means no wait */ + ret = select(n, rfds, wfds, efds, t >= 0.0 ? &tv: NULL); + } while (ret < 0 && errno == EINTR); + return ret; +} + +/*-------------------------------------------------------------------------*\ +* Creates and sets up a socket +\*-------------------------------------------------------------------------*/ +int socket_create(p_socket ps, int domain, int type, int protocol) { + *ps = socket(domain, type, protocol); + if (*ps != SOCKET_INVALID) return IO_DONE; + else return errno; +} + +/*-------------------------------------------------------------------------*\ +* Binds or returns error message +\*-------------------------------------------------------------------------*/ +int socket_bind(p_socket ps, SA *addr, socklen_t len) { + int err = IO_DONE; + socket_setblocking(ps); + if (bind(*ps, addr, len) < 0) err = errno; + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +int socket_listen(p_socket ps, int backlog) { + int err = IO_DONE; + socket_setblocking(ps); + if (listen(*ps, backlog)) err = errno; + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +void socket_shutdown(p_socket ps, int how) { + socket_setblocking(ps); + shutdown(*ps, how); + socket_setnonblocking(ps); +} + +/*-------------------------------------------------------------------------*\ +* Connects or returns error message +\*-------------------------------------------------------------------------*/ +int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) { + int err; + /* avoid calling on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* call connect until done or failed without being interrupted */ + do if (connect(*ps, addr, len) == 0) return IO_DONE; + while ((err = errno) == EINTR); + /* if connection failed immediately, return error code */ + if (err != EINPROGRESS && err != EAGAIN) return err; + /* zero timeout case optimization */ + if (timeout_iszero(tm)) return IO_TIMEOUT; + /* wait until we have the result of the connection attempt or timeout */ + err = socket_waitfd(ps, WAITFD_C, tm); + if (err == IO_CLOSED) { + if (recv(*ps, (char *) &err, 0, 0) == 0) return IO_DONE; + else return errno; + } else return err; +} + +/*-------------------------------------------------------------------------*\ +* Accept with timeout +\*-------------------------------------------------------------------------*/ +int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout tm) { + SA daddr; + socklen_t dlen = sizeof(daddr); + if (*ps == SOCKET_INVALID) return IO_CLOSED; + if (!addr) addr = &daddr; + if (!len) len = &dlen; + for ( ;; ) { + int err; + if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE; + err = errno; + if (err == EINTR) continue; + if (err != EAGAIN && err != ECONNABORTED) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Send with timeout +\*-------------------------------------------------------------------------*/ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm) +{ + int err; + /* avoid making system calls on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* loop until we send something or we give up on error */ + *sent = 0; + for ( ;; ) { + long put = (long) send(*ps, data, count, 0); + /* if we sent anything, we are done */ + if (put > 0) { + *sent = put; + return IO_DONE; + } + err = errno; + /* send can't really return 0, but EPIPE means the connection was + closed */ + if (put == 0 || err == EPIPE) return IO_CLOSED; + /* we call was interrupted, just try again */ + if (err == EINTR) continue; + /* if failed fatal reason, report error */ + if (err != EAGAIN) return err; + /* wait until we can send something or we timeout */ + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Sendto with timeout +\*-------------------------------------------------------------------------*/ +int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, + SA *addr, socklen_t len, p_timeout tm) +{ + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + *sent = 0; + for ( ;; ) { + long put = (long) sendto(*ps, data, count, 0, addr, len); + if (put > 0) { + *sent = put; + return IO_DONE; + } + err = errno; + if (put == 0 || err == EPIPE) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Receive with timeout +\*-------------------------------------------------------------------------*/ +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long taken = (long) recv(*ps, data, count, 0); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + err = errno; + *got = 0; + if (taken == 0) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Recvfrom with timeout +\*-------------------------------------------------------------------------*/ +int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, + SA *addr, socklen_t *len, p_timeout tm) { + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long taken = (long) recvfrom(*ps, data, count, 0, addr, len); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + err = errno; + *got = 0; + if (taken == 0) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Put socket into blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setblocking(p_socket ps) { + int flags = fcntl(*ps, F_GETFL, 0); + flags &= (~(O_NONBLOCK)); + fcntl(*ps, F_SETFL, flags); +} + +/*-------------------------------------------------------------------------*\ +* Put socket into non-blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setnonblocking(p_socket ps) { + int flags = fcntl(*ps, F_GETFL, 0); + flags |= O_NONBLOCK; + fcntl(*ps, F_SETFL, flags); +} + +/*-------------------------------------------------------------------------*\ +* DNS helpers +\*-------------------------------------------------------------------------*/ +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) { + *hp = gethostbyaddr(addr, len, AF_INET); + if (*hp) return IO_DONE; + else if (h_errno) return h_errno; + else if (errno) return errno; + else return IO_UNKNOWN; +} + +int socket_gethostbyname(const char *addr, struct hostent **hp) { + *hp = gethostbyname(addr); + if (*hp) return IO_DONE; + else if (h_errno) return h_errno; + else if (errno) return errno; + else return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Error translation functions +* Make sure important error messages are standard +\*-------------------------------------------------------------------------*/ +const char *socket_hoststrerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case HOST_NOT_FOUND: return "host not found"; + default: return hstrerror(err); + } +} + +const char *socket_strerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case EADDRINUSE: return "address already in use"; + case EISCONN: return "already connected"; + case EACCES: return "permission denied"; + case ECONNREFUSED: return "connection refused"; + case ECONNABORTED: return "closed"; + case ECONNRESET: return "closed"; + case ETIMEDOUT: return "timedout"; + default: return strerror(errno); + } +} + +const char *socket_ioerror(p_socket ps, int err) { + (void) ps; + return socket_strerror(err); +} diff --git a/src/luasocket/usocket.h b/src/luasocket/usocket.h new file mode 100644 index 0000000..f2a89aa --- /dev/null +++ b/src/luasocket/usocket.h @@ -0,0 +1,40 @@ +#ifndef USOCKET_H +#define USOCKET_H +/*=========================================================================*\ +* Socket compatibilization module for Unix +* LuaSocket toolkit +* +* RCS ID: $Id: usocket.h,v 1.7 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ + +/*=========================================================================*\ +* BSD include files +\*=========================================================================*/ +/* error codes */ +#include +/* close function */ +#include +/* fnctnl function and associated constants */ +#include +/* struct sockaddr */ +#include +/* socket function */ +#include +/* struct timeval */ +#include +/* gethostbyname and gethostbyaddr functions */ +#include +/* sigpipe handling */ +#include +/* IP stuff*/ +#include +#include +/* TCP options (nagle algorithm disable) */ +#include + +typedef int t_socket; +typedef t_socket *p_socket; + +#define SOCKET_INVALID (-1) + +#endif /* USOCKET_H */ diff --git a/src/luasocket/wsocket.c b/src/luasocket/wsocket.c new file mode 100644 index 0000000..faa72ff --- /dev/null +++ b/src/luasocket/wsocket.c @@ -0,0 +1,401 @@ +/*=========================================================================*\ +* Socket compatibilization module for Win32 +* LuaSocket toolkit +* +* The penalty of calling select to avoid busy-wait is only paid when +* the I/O call fail in the first place. +* +* RCS ID: $Id: wsocket.c,v 1.35 2005/11/20 07:20:23 diego Exp $ +\*=========================================================================*/ +#include + +#include "socket.h" + +/* WinSock doesn't have a strerror... */ +static const char *wstrerror(int err); + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int socket_open(void) { + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(2, 0); + int err = WSAStartup(wVersionRequested, &wsaData ); + if (err != 0) return 0; + if ((LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) && + (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)) { + WSACleanup(); + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close module +\*-------------------------------------------------------------------------*/ +int socket_close(void) { + WSACleanup(); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Wait for readable/writable/connected socket with timeout +\*-------------------------------------------------------------------------*/ +#define WAITFD_R 1 +#define WAITFD_W 2 +#define WAITFD_E 4 +#define WAITFD_C (WAITFD_E|WAITFD_W) + +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + fd_set rfds, wfds, efds, *rp = NULL, *wp = NULL, *ep = NULL; + struct timeval tv, *tp = NULL; + double t; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + if (sw & WAITFD_R) { + FD_ZERO(&rfds); + FD_SET(*ps, &rfds); + rp = &rfds; + } + if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; } + if (sw & WAITFD_C) { FD_ZERO(&efds); FD_SET(*ps, &efds); ep = &efds; } + if ((t = timeout_get(tm)) >= 0.0) { + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t-tv.tv_sec)*1.0e6); + tp = &tv; + } + ret = select(0, rp, wp, ep, tp); + if (ret == -1) return WSAGetLastError(); + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && FD_ISSET(*ps, &efds)) return IO_CLOSED; + return IO_DONE; +} + +/*-------------------------------------------------------------------------*\ +* Select with int timeout in ms +\*-------------------------------------------------------------------------*/ +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm) { + struct timeval tv; + double t = timeout_get(tm); + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6); + if (n <= 0) { + Sleep((DWORD) (1000*t)); + return 0; + } else return select(0, rfds, wfds, efds, t >= 0.0? &tv: NULL); +} + +/*-------------------------------------------------------------------------*\ +* Close and inutilize socket +\*-------------------------------------------------------------------------*/ +void socket_destroy(p_socket ps) { + if (*ps != SOCKET_INVALID) { + socket_setblocking(ps); /* close can take a long time on WIN32 */ + closesocket(*ps); + *ps = SOCKET_INVALID; + } +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +void socket_shutdown(p_socket ps, int how) { + socket_setblocking(ps); + shutdown(*ps, how); + socket_setnonblocking(ps); +} + +/*-------------------------------------------------------------------------*\ +* Creates and sets up a socket +\*-------------------------------------------------------------------------*/ +int socket_create(p_socket ps, int domain, int type, int protocol) { + *ps = socket(domain, type, protocol); + if (*ps != SOCKET_INVALID) return IO_DONE; + else return WSAGetLastError(); +} + +/*-------------------------------------------------------------------------*\ +* Connects or returns error message +\*-------------------------------------------------------------------------*/ +int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) { + int err; + /* don't call on closed socket */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* ask system to connect */ + if (connect(*ps, addr, len) == 0) return IO_DONE; + /* make sure the system is trying to connect */ + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK && err != WSAEINPROGRESS) return err; + /* zero timeout case optimization */ + if (timeout_iszero(tm)) return IO_TIMEOUT; + /* we wait until something happens */ + err = socket_waitfd(ps, WAITFD_C, tm); + if (err == IO_CLOSED) { + int len = sizeof(err); + /* give windows time to set the error (yes, disgusting) */ + Sleep(10); + /* find out why we failed */ + getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len); + /* we KNOW there was an error. if 'why' is 0, we will return + * "unknown error", but it's not really our fault */ + return err > 0? err: IO_UNKNOWN; + } else return err; + +} + +/*-------------------------------------------------------------------------*\ +* Binds or returns error message +\*-------------------------------------------------------------------------*/ +int socket_bind(p_socket ps, SA *addr, socklen_t len) { + int err = IO_DONE; + socket_setblocking(ps); + if (bind(*ps, addr, len) < 0) err = WSAGetLastError(); + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +int socket_listen(p_socket ps, int backlog) { + int err = IO_DONE; + socket_setblocking(ps); + if (listen(*ps, backlog) < 0) err = WSAGetLastError(); + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* Accept with timeout +\*-------------------------------------------------------------------------*/ +int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, + p_timeout tm) { + SA daddr; + socklen_t dlen = sizeof(daddr); + if (*ps == SOCKET_INVALID) return IO_CLOSED; + if (!addr) addr = &daddr; + if (!len) len = &dlen; + for ( ;; ) { + int err; + /* try to get client socket */ + if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE; + /* find out why we failed */ + err = WSAGetLastError(); + /* if we failed because there was no connectoin, keep trying */ + if (err != WSAEWOULDBLOCK && err != WSAECONNABORTED) return err; + /* call select to avoid busy wait */ + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Send with timeout +* On windows, if you try to send 10MB, the OS will buffer EVERYTHING +* this can take an awful lot of time and we will end up blocked. +* Therefore, whoever calls this function should not pass a huge buffer. +\*-------------------------------------------------------------------------*/ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm) +{ + int err; + /* avoid making system calls on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* loop until we send something or we give up on error */ + *sent = 0; + for ( ;; ) { + /* try to send something */ + int put = send(*ps, data, (int) count, 0); + /* if we sent something, we are done */ + if (put > 0) { + *sent = put; + return IO_DONE; + } + /* deal with failure */ + err = WSAGetLastError(); + /* we can only proceed if there was no serious error */ + if (err != WSAEWOULDBLOCK) return err; + /* avoid busy wait */ + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Sendto with timeout +\*-------------------------------------------------------------------------*/ +int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, + SA *addr, socklen_t len, p_timeout tm) +{ + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + *sent = 0; + for ( ;; ) { + int put = sendto(*ps, data, (int) count, 0, addr, len); + if (put > 0) { + *sent = put; + return IO_DONE; + } + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Receive with timeout +\*-------------------------------------------------------------------------*/ +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + *got = 0; + for ( ;; ) { + int taken = recv(*ps, data, (int) count, 0); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + if (taken == 0) return IO_CLOSED; + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Recvfrom with timeout +\*-------------------------------------------------------------------------*/ +int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, + SA *addr, socklen_t *len, p_timeout tm) { + int err; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + *got = 0; + for ( ;; ) { + int taken = recvfrom(*ps, data, (int) count, 0, addr, len); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + if (taken == 0) return IO_CLOSED; + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Put socket into blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setblocking(p_socket ps) { + u_long argp = 0; + ioctlsocket(*ps, FIONBIO, &argp); +} + +/*-------------------------------------------------------------------------*\ +* Put socket into non-blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setnonblocking(p_socket ps) { + u_long argp = 1; + ioctlsocket(*ps, FIONBIO, &argp); +} + +/*-------------------------------------------------------------------------*\ +* DNS helpers +\*-------------------------------------------------------------------------*/ +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) { + *hp = gethostbyaddr(addr, len, AF_INET); + if (*hp) return IO_DONE; + else return WSAGetLastError(); +} + +int socket_gethostbyname(const char *addr, struct hostent **hp) { + *hp = gethostbyname(addr); + if (*hp) return IO_DONE; + else return WSAGetLastError(); +} + +/*-------------------------------------------------------------------------*\ +* Error translation functions +\*-------------------------------------------------------------------------*/ +const char *socket_hoststrerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case WSAHOST_NOT_FOUND: return "host not found"; + default: return wstrerror(err); + } +} + +const char *socket_strerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case WSAEADDRINUSE: return "address already in use"; + case WSAECONNREFUSED: return "connection refused"; + case WSAEISCONN: return "already connected"; + case WSAEACCES: return "permission denied"; + case WSAECONNABORTED: return "closed"; + case WSAECONNRESET: return "closed"; + case WSAETIMEDOUT: return "timeout"; + default: return wstrerror(err); + } +} + +const char *socket_ioerror(p_socket ps, int err) { + (void) ps; + return socket_strerror(err); +} + +static const char *wstrerror(int err) { + switch (err) { + case WSAEINTR: return "Interrupted function call"; + case WSAEACCES: return "Permission denied"; + case WSAEFAULT: return "Bad address"; + case WSAEINVAL: return "Invalid argument"; + case WSAEMFILE: return "Too many open files"; + case WSAEWOULDBLOCK: return "Resource temporarily unavailable"; + case WSAEINPROGRESS: return "Operation now in progress"; + case WSAEALREADY: return "Operation already in progress"; + case WSAENOTSOCK: return "Socket operation on nonsocket"; + case WSAEDESTADDRREQ: return "Destination address required"; + case WSAEMSGSIZE: return "Message too long"; + case WSAEPROTOTYPE: return "Protocol wrong type for socket"; + case WSAENOPROTOOPT: return "Bad protocol option"; + case WSAEPROTONOSUPPORT: return "Protocol not supported"; + case WSAESOCKTNOSUPPORT: return "Socket type not supported"; + case WSAEOPNOTSUPP: return "Operation not supported"; + case WSAEPFNOSUPPORT: return "Protocol family not supported"; + case WSAEAFNOSUPPORT: + return "Address family not supported by protocol family"; + case WSAEADDRINUSE: return "Address already in use"; + case WSAEADDRNOTAVAIL: return "Cannot assign requested address"; + case WSAENETDOWN: return "Network is down"; + case WSAENETUNREACH: return "Network is unreachable"; + case WSAENETRESET: return "Network dropped connection on reset"; + case WSAECONNABORTED: return "Software caused connection abort"; + case WSAECONNRESET: return "Connection reset by peer"; + case WSAENOBUFS: return "No buffer space available"; + case WSAEISCONN: return "Socket is already connected"; + case WSAENOTCONN: return "Socket is not connected"; + case WSAESHUTDOWN: return "Cannot send after socket shutdown"; + case WSAETIMEDOUT: return "Connection timed out"; + case WSAECONNREFUSED: return "Connection refused"; + case WSAEHOSTDOWN: return "Host is down"; + case WSAEHOSTUNREACH: return "No route to host"; + case WSAEPROCLIM: return "Too many processes"; + case WSASYSNOTREADY: return "Network subsystem is unavailable"; + case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range"; + case WSANOTINITIALISED: + return "Successful WSAStartup not yet performed"; + case WSAEDISCON: return "Graceful shutdown in progress"; + case WSAHOST_NOT_FOUND: return "Host not found"; + case WSATRY_AGAIN: return "Nonauthoritative host not found"; + case WSANO_RECOVERY: return "Nonrecoverable name lookup error"; + case WSANO_DATA: return "Valid name, no data record of requested type"; + default: return "Unknown error"; + } +} diff --git a/src/luasocket/wsocket.h b/src/luasocket/wsocket.h new file mode 100644 index 0000000..b536683 --- /dev/null +++ b/src/luasocket/wsocket.h @@ -0,0 +1,21 @@ +#ifndef WSOCKET_H +#define WSOCKET_H +/*=========================================================================*\ +* Socket compatibilization module for Win32 +* LuaSocket toolkit +* +* RCS ID: $Id: wsocket.h,v 1.4 2005/10/07 04:40:59 diego Exp $ +\*=========================================================================*/ + +/*=========================================================================*\ +* WinSock include files +\*=========================================================================*/ +#include + +typedef int socklen_t; +typedef SOCKET t_socket; +typedef t_socket *p_socket; + +#define SOCKET_INVALID (INVALID_SOCKET) + +#endif /* WSOCKET_H */