├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── History.txt ├── LICENSE ├── dist.info ├── doc └── index.html ├── include └── xml │ └── Parser.h ├── readme.md ├── scripts ├── bind.lua ├── build.lua └── doc.lua ├── src ├── Parser.cpp ├── bind │ ├── dub │ │ ├── dub.cpp │ │ └── dub.h │ ├── xml_Parser.cpp │ └── xml_core.cpp └── vendor │ ├── license.txt │ ├── manual.html │ ├── rapidxml.hpp │ ├── rapidxml_iterators.hpp │ ├── rapidxml_print.hpp │ └── rapidxml_utils.hpp ├── test ├── Parser_test.lua ├── all.lua ├── fixtures │ ├── doxy.xml │ ├── foo.xml │ └── large.xml └── xml_test.lua ├── xml-1.1.3-1.rockspec ├── xml.lua └── xml ├── Parser.lua └── init.lua /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.o 3 | *.so 4 | *.swp 5 | /html 6 | /build 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: erlang 2 | 3 | # Try using multiple Lua Implementations 4 | env: 5 | - LUA_VERSION='5.1' LUA="lua5.1" 6 | - LUA_VERSION='5.1' LUA="luajit" # Wee need to install lua5.1 or luarocks won't build 7 | - LUA_VERSION='5.2' LUA="lua5.2" 8 | - LUA_VERSION='5.3' LUA="lua" 9 | 10 | branches: 11 | only: 12 | - master 13 | 14 | install: 15 | - test "$LUA_VERSION" = "5.3" || sudo apt-get install lua$LUA_VERSION liblua$LUA_VERSION-dev 16 | - test "$LUA" = "luajit" && git clone http://luajit.org/git/luajit-2.0.git && cd luajit-2.0/ && sudo make install && cd .. || true 17 | - test "$LUA_VERSION" = "5.3" && wget http://www.lua.org/ftp/lua-5.3.0.tar.gz && tar xzf lua-5.3.0.tar.gz && cd lua-5.3.0 && make linux && sudo make install && cd .. || true 18 | - git clone git://github.com/keplerproject/luarocks.git 19 | - cd luarocks 20 | - ./configure --lua-version=$LUA_VERSION --versioned-rocks-dir 21 | - make build 22 | - sudo make install 23 | - cd .. 24 | # Install testing dependency 25 | - sudo luarocks-$LUA_VERSION install lut 26 | # Build module 27 | - sudo luarocks-$LUA_VERSION make 28 | 29 | # Run tests 30 | script: 31 | - $LUA -v && $LUA test/all.lua 32 | 33 | notifications: 34 | recipients: 35 | - gaspard@teti.ch 36 | email: 37 | on_success: change 38 | on_failure: always 39 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # MACHINE GENERATED FILE. DO NOT EDIT. 3 | # 4 | # CMake build file for xml 5 | # 6 | # This file has been generated by lut.Builder 1.2.1 7 | # 8 | 9 | cmake_minimum_required(VERSION 2.8) 10 | # -------------------------------------------------------------- 11 | # xml 12 | # -------------------------------------------------------------- 13 | set(MODULE_NAME xml) 14 | 15 | # Where to install Lua files 16 | if(LUA_INSTALL_DIR) 17 | set(INSTALL_PATH ${LUA_INSTALL_DIR}) 18 | else(LUA_INSTALL_DIR) 19 | set(INSTALL_PATH "${CMAKE_BINARY_DIR}/lib" CACHE STRING "Install directory path") 20 | endif(LUA_INSTALL_DIR) 21 | message("INSTALL Lua 'xml' TO '${INSTALL_PATH}'") 22 | 23 | # Where to install binary modules 24 | if(LUA_INSTALL_BINDIR) 25 | set(INSTALL_BINPATH ${LUA_INSTALL_BINDIR}) 26 | else(LUA_INSTALL_BINDIR) 27 | set(INSTALL_BINPATH "${CMAKE_BINARY_DIR}/lib" CACHE STRING "Install directory path") 28 | endif(LUA_INSTALL_BINDIR) 29 | message("INSTALL binary 'xml' TO '${INSTALL_BINPATH}'") 30 | 31 | # -------------------------------------------------------------- 32 | # module 33 | # -------------------------------------------------------------- 34 | add_custom_target(${MODULE_NAME} true) 35 | 36 | 37 | # -------- PLAT 38 | set(LINK_LIBS ) 39 | 40 | if(UNIX) 41 | if(APPLE) 42 | set(PLAT "macosx") 43 | set(LINK_FLAGS "-bundle -undefined dynamic_lookup -all_load") 44 | set(LINK_LIBS "stdc++") 45 | else(APPLE) 46 | set(PLAT "linux") 47 | set(LINK_FLAGS "-shared") 48 | set(LINK_LIBS "stdc++") 49 | endif(APPLE) 50 | else(UNIX) 51 | if(WIN32) 52 | set(PLAT "win32") 53 | else(WIN32) 54 | set(PLAT "unsupported") 55 | endif(WIN32) 56 | endif(UNIX) 57 | 58 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -fPIC -O2") 59 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -fPIC -O2") 60 | if (RELEASE) 61 | add_definitions(-O2 -DNDEBUG) 62 | endif(RELEASE) 63 | 64 | # -------------------------------------------------------------- 65 | # xml.core 66 | # -------------------------------------------------------------- 67 | set(core "${MODULE_NAME}_core") 68 | 69 | include_directories(/usr/local/include include src/bind src/vendor) 70 | 71 | file(GLOB CORE_SOURCES src/*.c src/*.cpp src/bind/dub/*.cpp src/bind/*.cpp src/${PLAT}/*.cpp src/${PLAT}/*.mm) 72 | 73 | add_library(${core} MODULE ${CORE_SOURCES}) 74 | if(LINK_LIBS) 75 | target_link_libraries(${core} ${LINK_LIBS}) 76 | endif(LINK_LIBS) 77 | set_target_properties(${core} 78 | PROPERTIES OUTPUT_NAME core 79 | LINK_FLAGS ${LINK_FLAGS} 80 | PREFIX "" 81 | SUFFIX ".so" 82 | ) 83 | 84 | 85 | add_dependencies(${MODULE_NAME} ${core}) 86 | 87 | # -------------------------------------------------------------- 88 | # install 89 | # -------------------------------------------------------------- 90 | install(TARGETS ${core} 91 | DESTINATION ${INSTALL_BINPATH}/${MODULE_NAME} 92 | ) 93 | 94 | # -------------------------------------------------------------- 95 | # install 96 | # -------------------------------------------------------------- 97 | install(DIRECTORY ${MODULE_NAME} 98 | DESTINATION ${INSTALL_PATH} 99 | ) 100 | 101 | 102 | -------------------------------------------------------------------------------- /History.txt: -------------------------------------------------------------------------------- 1 | == 1.1.3 2015-05-11 2 | 3 | * Added support for lua 5.3. 4 | 5 | == 1.1.2 2015-05-05 6 | 7 | * Fix build on Windows. 8 | 9 | == 1.1.1 2014-08-15 10 | 11 | * Fixed lub dependency information. 12 | * Using lut.Builder to update build files. 13 | 14 | == 1.1.0 2014-02-01 15 | 16 | * Changes in API to reflect yaml library. 'parse' is now 'load' and 'load' 17 | is 'loadpath'. 18 | * Fixed bindings by using latest dub binder. 19 | * Added support for CMake build. 20 | 21 | == 1.0.0 2014-01-26 22 | 23 | * Initial release. 24 | * When 'xml' tag name is missing, use 'table' as tag name. 25 | * Added option to trim whitespace. 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Lubyk is licensed under the terms of the MIT license reproduced below. 3 | This means that Lubyk is free software and can be used for both academic 4 | and commercial purposes at absolutely no cost. 5 | 6 | This project uses RapidXML Copyright (c) 2006, 2007 Marcin Kalicinski also 7 | released under the MIT license. 8 | 9 | =============================================================================== 10 | 11 | This file is part of the LUBYK project (http://lubyk.org) 12 | Copyright (c) 2007-2013 by Gaspard Bucher (http://teti.ch). 13 | 14 | rapidxml 15 | Copyright (c) 2006, 2007 Marcin Kalicinski 16 | 17 | ------------------------------------------------------------------------------ 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | 37 | =============================================================================== 38 | 39 | -------------------------------------------------------------------------------- /dist.info: -------------------------------------------------------------------------------- 1 | name = "xml" 2 | version = "1.1.2" 3 | 4 | desc = "Very fast xml parser based on RapidXML" 5 | author = "Gaspard Bucher" 6 | license = "MIT" 7 | url = "http://doc.lubyk.org/xml.html" 8 | maintainer = "Gaspard Bucher" 9 | 10 | depends = { 11 | "lua >= 5.1, < 5.4", 12 | "lub >= 1.0.3, < 2", 13 | } 14 | 15 | -------------------------------------------------------------------------------- /doc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | xml 5 | 6 | 7 |

Online documentation

8 |

doc.lubyk.org/xml.html

9 | 10 |

Generate

11 |
lua scripts/makedoc.lua && open html/index.html
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /include/xml/Parser.h: -------------------------------------------------------------------------------- 1 | /* 2 | ============================================================================== 3 | 4 | This file is part of the LUBYK project (http://lubyk.org) 5 | Copyright (c) 2007-2014 by Gaspard Bucher (http://teti.ch). 6 | 7 | ------------------------------------------------------------------------------ 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in 17 | all copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | THE SOFTWARE. 26 | 27 | ============================================================================== 28 | */ 29 | 30 | #ifndef LUBYK_INCLUDE_XML_PARSER_H_ 31 | #define LUBYK_INCLUDE_XML_PARSER_H_ 32 | 33 | #include "dub/dub.h" // dub::Exception 34 | 35 | namespace xml { 36 | 37 | /** Simple xml parser (singleton). 38 | */ 39 | class Parser { 40 | public: 41 | enum Type { 42 | Default = 0, 43 | TrimWhitespace, 44 | NonDestructive, 45 | Fastest, 46 | }; 47 | 48 | Parser(Type type = Default); 49 | ~Parser(); 50 | 51 | // Receive an xml string and return a Lua table. The received string can be 52 | // modified in place. 53 | LuaStackSize load(lua_State *L); 54 | private: 55 | Type type_; 56 | 57 | class Implementation; 58 | Implementation *impl_; 59 | 60 | }; 61 | 62 | } // xml 63 | 64 | #endif // LUBYK_INCLUDE_XML_PARSER_H_ 65 | 66 | 67 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | xml for lua [![Build Status](https://travis-ci.org/lubyk/xml.png)](https://travis-ci.org/lubyk/xml) 2 | =========== 3 | 4 | Very fast and simple XML parser for Lua based on RapidXML 1.13. 5 | 6 | [Documentation](http://doc.lubyk.org/xml.html). 7 | 8 | install 9 | ------- 10 | 11 | luarocks install xml 12 | 13 | install on Windows 14 | ------------------ 15 | 16 | luarocks install xml CC=g++ LD=g++ 17 | -------------------------------------------------------------------------------- /scripts/bind.lua: -------------------------------------------------------------------------------- 1 | -- 2 | -- Update binding files for this project 3 | -- 4 | local lub = require 'lub' 5 | local dub = require 'dub' 6 | 7 | local ins = dub.Inspector { 8 | INPUT = { 9 | lub.path '|../include/xml', 10 | }, 11 | --doc_dir = base .. '/tmp', 12 | --html = true, 13 | --keep_xml = true, 14 | } 15 | 16 | local binder = dub.LuaBinder() 17 | 18 | binder:bind(ins, { 19 | output_directory = lub.path '|../src/bind', 20 | -- Remove this part in included headers 21 | header_base = lub.path '|../include', 22 | -- Create a single library. 23 | single_lib = 'xml', 24 | -- Open the library with require 'xml.core' (not 'xml') 25 | luaopen = 'xml_core', 26 | }) 27 | -------------------------------------------------------------------------------- /scripts/build.lua: -------------------------------------------------------------------------------- 1 | -- 2 | -- Update build files for this project 3 | -- 4 | package.path = './?.lua;'..package.path 5 | package.cpath = './?.so;' ..package.cpath 6 | 7 | local lut = require 'lut' 8 | local lib = require 'xml' 9 | 10 | lut.Builder(lib):make() 11 | -------------------------------------------------------------------------------- /scripts/doc.lua: -------------------------------------------------------------------------------- 1 | -- 2 | -- Generate documentation for this project into 'html' folder 3 | -- 4 | local lut = require 'lut' 5 | lut.Doc.make { 6 | sources = { 7 | 'xml', 8 | }, 9 | target = 'html', 10 | format = 'html', 11 | header = [[

Lubyk documentation

]], 12 | index = [=[ 13 | --[[-- 14 | # Lubyk documentation 15 | 16 | ## List of available modules 17 | --]]-- 18 | ]=] 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/Parser.cpp: -------------------------------------------------------------------------------- 1 | #include "xml/Parser.h" 2 | #include "rapidxml.hpp" 3 | 4 | #include 5 | 6 | 7 | xml::Parser::Parser(Type type) 8 | : type_(type) { 9 | } 10 | 11 | xml::Parser::~Parser() { 12 | } 13 | 14 | static void parseDom(lua_State *L, rapidxml::xml_node<> *node) { 15 | lua_newtable(L); 16 | // 17 | int tbl_pos = lua_gettop(L); 18 | 19 | lua_pushlstring(L, node->name(), node->name_size()); 20 | // "tag" 21 | lua_setfield(L, -2, "xml"); 22 | // 23 | 24 | // Parse attributes 25 | for (rapidxml::xml_attribute<> *attr = node->first_attribute(); 26 | attr; attr = attr->next_attribute()) { 27 | // 28 | lua_pushlstring(L, attr->name(), attr->name_size()); 29 | // "key" 30 | lua_pushlstring(L, attr->value(), attr->value_size()); 31 | // "key" "value" 32 | lua_rawset(L, tbl_pos); 33 | } 34 | // 35 | 36 | // Parse children nodes 37 | int pos = 0; 38 | for(rapidxml::xml_node<> *child = node->first_node(); 39 | child; child = child->next_sibling()) { 40 | // 41 | switch(child->type()) { 42 | case rapidxml::node_element: 43 | parseDom(L, child); 44 | break; 45 | case rapidxml::node_data: // continue 46 | case rapidxml::node_cdata: 47 | lua_pushlstring(L, child->value(), child->value_size()); 48 | break; 49 | case rapidxml::node_comment: // continue 50 | case rapidxml::node_declaration: // continue 51 | case rapidxml::node_doctype: // continue 52 | case rapidxml::node_pi: // continue 53 | default: 54 | // ignore 55 | continue; 56 | } 57 | 58 | // 59 | lua_rawseti(L, tbl_pos, ++pos); 60 | } 61 | // 62 | } 63 | 64 | // Simple helper class to handle copy and auto freeing. 65 | struct String { 66 | char *text_; 67 | String(const char *text, size_t len) : text_(NULL) { 68 | text_ = (char*)malloc(len * sizeof(char)); 69 | if (text_) { 70 | strncpy(text_, text, len); 71 | } 72 | } 73 | 74 | ~String() { 75 | if (text_) { 76 | free(text_); 77 | } 78 | } 79 | }; 80 | 81 | // Receive an xml string and return a Lua table. 82 | LuaStackSize xml::Parser::load(lua_State *L) { 83 | size_t len; 84 | const char *xml_str = dub::checklstring(L, 2, &len); 85 | ++len; // for \0 termination 86 | rapidxml::xml_document<> doc; // character type defaults to char 87 | 88 | switch(type_) { 89 | case NonDestructive: 90 | doc.parse(const_cast(xml_str)); 91 | parseDom(L, doc.first_node()); 92 | return 1; 93 | case TrimWhitespace: { 94 | // Parsing is destructive: make an exception safe copy. 95 | String text(xml_str, len); 96 | if (!text.text_) return 0; 97 | doc.parse(text.text_); 98 | parseDom(L, doc.first_node()); 99 | // 100 | return 1; 101 | } 102 | case Default: // continue 103 | default: { 104 | // Parsing is destructive: make an exception safe copy. 105 | String text(xml_str, len); 106 | if (!text.text_) return 0; 107 | doc.parse(text.text_); 108 | parseDom(L, doc.first_node()); 109 | // 110 | return 1; 111 | } 112 | } 113 | } 114 | 115 | -------------------------------------------------------------------------------- /src/bind/dub/dub.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ============================================================================== 3 | 4 | This file is part of the DUB bindings generator (http://lubyk.org/dub) 5 | Copyright (c) 2007-2012 by Gaspard Bucher (http://teti.ch). 6 | 7 | ------------------------------------------------------------------------------ 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in 17 | all copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | THE SOFTWARE. 26 | 27 | ============================================================================== 28 | */ 29 | #include "dub/dub.h" 30 | 31 | #include // malloc 32 | #include // strlen strcmp 33 | #include // assert 34 | 35 | #define DUB_EXCEPTION_BUFFER_SIZE 256 36 | #define TYPE_EXCEPTION_MSG "expected %s, found %s" 37 | #define TYPE_EXCEPTION_SMSG "expected %s, found %s (using super)" 38 | #define DEAD_EXCEPTION_MSG "using deleted %s" 39 | #define DUB_MAX_IN_SHIFT 4294967296 40 | 41 | #if LUA_VERSION_NUM > 501 42 | #define DUB_LUA_FIVE_TWO 43 | #else 44 | #define DUB_LUA_FIVE_ONE 45 | #endif 46 | 47 | #define DUB_INIT_CODE "local class = ...\nif class.new then\nsetmetatable(class, {\n __call = function(lib, ...)\n return lib.new(...)\n end,\n})\nend\n" 48 | #define DUB_INIT_ERR "[string \"Dub init code\"]" 49 | // Define the callback error function. We store the error function in 50 | // self._errfunc so that it can also be used from Lua (this error function 51 | // captures the currently global 'print' which is useful for remote network objects). 52 | #define DUB_ERRFUNC "local self, print = ...\n\ 53 | local errfunc = function(...)\n\ 54 | local err = self.error\n\ 55 | if err then\n\ 56 | err(self, ...)\n\ 57 | else\n\ 58 | print('error', ...)\n\ 59 | end\n\ 60 | end\n\ 61 | self._errfunc = errfunc\n\ 62 | return errfunc" 63 | 64 | using namespace dub; 65 | 66 | void dub::printStack(lua_State *L, const char *msg) { 67 | int top = lua_gettop(L); 68 | if (msg) { 69 | printf("============ %s (%i)\n", msg, top); 70 | } else { 71 | printf("============ (%i)\n", top); 72 | } 73 | for(int i=1; i<=top; ++i) { 74 | if (lua_isstring(L, i)) { 75 | printf(" \"%s\"\n", lua_tostring(L, i)); 76 | } else { 77 | printf(" %s\n", lua_typename(L, lua_type(L, i))); 78 | } 79 | 80 | } 81 | printf("===============================\n"); 82 | } 83 | 84 | // ====================================================================== 85 | // =============================================== dub::Exception 86 | // ====================================================================== 87 | Exception::Exception(const char *format, ...) { 88 | char buffer[DUB_EXCEPTION_BUFFER_SIZE]; 89 | va_list args; 90 | va_start(args, format); 91 | vsnprintf(buffer, DUB_EXCEPTION_BUFFER_SIZE, format, args); 92 | va_end(args); 93 | message_ = buffer; 94 | } 95 | 96 | Exception::~Exception() throw() {} 97 | 98 | const char* Exception::what() const throw() { 99 | return message_.c_str(); 100 | } 101 | 102 | 103 | TypeException::TypeException(lua_State *L, int narg, const char *type, bool is_super) : 104 | Exception(is_super ? TYPE_EXCEPTION_SMSG : TYPE_EXCEPTION_MSG, type, luaL_typename(L, narg)) {} 105 | 106 | // ====================================================================== 107 | // =============================================== dub::Object 108 | // ====================================================================== 109 | void Object::dub_pushobject(lua_State *L, void *ptr, const char *tname, bool gc) { 110 | DubUserdata *udata = (DubUserdata*)lua_newuserdata(L, sizeof(DubUserdata)); 111 | udata->ptr = ptr; 112 | udata->gc = gc; 113 | if (dub_userdata_) { 114 | // We already have a userdata. Push a new userdata (copy to this item, 115 | // should never gc). 116 | assert(!gc); 117 | udata->gc = false; 118 | } else { 119 | // First initialization. 120 | dub_userdata_ = udata; 121 | } 122 | // the userdata is now on top of the stack 123 | 124 | // set metatable (contains methods) 125 | lua_getfield(L, LUA_REGISTRYINDEX, tname); 126 | lua_setmetatable(L, -2); 127 | // 128 | } 129 | 130 | // ====================================================================== 131 | // =============================================== dub::Thread 132 | // ====================================================================== 133 | void Thread::dub_pushobject(lua_State *L, void *ptr, const char *tname, bool gc) { 134 | if (dub_L) { 135 | if (!strcmp(tname, dub_typename_)) { 136 | // Pushing same type again. 137 | 138 | // We do not care about gc being false here since we share the same userdata 139 | // object. 140 | // push self 141 | lua_pushvalue(dub_L, 1); 142 | lua_xmove(dub_L, L, 1); 143 | // 144 | } else { 145 | // Type cast. 146 | assert(!gc); 147 | dub::pushudata(L, ptr, tname, gc); 148 | // 149 | } 150 | return; 151 | } 152 | 153 | // initialization 154 | 155 | //--=============================================== setup super 156 | lua_newtable(L); 157 | // 158 | Object::dub_pushobject(L, ptr, tname, gc); 159 | // 160 | dub_typename_ = tname; 161 | lua_pushlstring(L, "super", 5); 162 | // 'super' 163 | lua_pushvalue(L, -2); 164 | // 'super' 165 | lua_rawset(L, -4); // .super = 166 | // 167 | 168 | //--=============================================== setup metatable on self 169 | lua_getfield(L, LUA_REGISTRYINDEX, tname); 170 | // 171 | lua_setmetatable(L, -3); // setmetatable(self, mt) 172 | // 173 | 174 | //--=============================================== setup lua thread 175 | // Create env table used for garbage collection protection. 176 | lua_newtable(L); 177 | // 178 | lua_pushvalue(L, -1); 179 | // 180 | #ifdef DUB_LUA_FIVE_ONE 181 | if (!lua_setfenv(L, -3)) { // setfenv(udata, env) 182 | // 183 | lua_pop(L, 3); 184 | // 185 | throw Exception("Could not set userdata env on '%s'.", lua_typename(L, lua_type(L, -3))); 186 | } 187 | #else 188 | lua_setuservalue(L, -3); 189 | // 190 | #endif 191 | 192 | // 193 | dub_L = lua_newthread(L); 194 | // 195 | 196 | // Store the thread in the userdata environment table so it is not 197 | // garbage collected too soon. 198 | luaL_ref(L, -2); 199 | // 200 | 201 | //--=============================================== prepare error function 202 | int error = luaL_loadbuffer(L, DUB_ERRFUNC, strlen(DUB_ERRFUNC), "Dub error function"); 203 | if (error) { 204 | throw Exception("Error evaluating error function code (%s).", lua_tostring(L, -1)); 205 | } 206 | // (errloader) 207 | 208 | lua_pushvalue(L, -4); 209 | // (errloader) 210 | 211 | #ifdef DUB_LUA_FIVE_ONE 212 | lua_getfield(L, LUA_GLOBALSINDEX, "print"); 213 | #else 214 | lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); 215 | // <_G> 216 | lua_getfield(L, -1, "print"); 217 | // (errloader) <_G> (print) 218 | lua_remove(L, -2); 219 | #endif 220 | 221 | // (errloader) (print) 222 | 223 | error = lua_pcall(L, 2, 1, 0); 224 | if (error) { 225 | throw Exception("Error executing error function code (%s).", lua_tostring(L, -1)); 226 | } 227 | 228 | 229 | // 230 | lua_remove(L, -2); 231 | // 232 | lua_remove(L, -2); 233 | // 234 | 235 | //--=============================================== prepare thread stack 236 | // Transfer a copy of to thread stack 237 | lua_pushvalue(L, -2); 238 | // 239 | lua_pushvalue(L, -2); 240 | // 241 | lua_xmove(L, dub_L, 2); 242 | lua_pop(L, 1); 243 | 244 | // dub_L: 245 | // L: 246 | } 247 | 248 | bool Thread::dub_pushcallback(const char *name) const { 249 | lua_State *L = const_cast(dub_L); 250 | lua_getfield(L, 1, name); 251 | if (lua_isnil(L, -1)) { 252 | lua_pop(L, 1); 253 | return false; 254 | } else { 255 | lua_pushvalue(L, 1); 256 | // ... 257 | return true; 258 | } 259 | } 260 | 261 | void Thread::dub_pushvalue(const char *name) const { 262 | lua_State *L = const_cast(dub_L); 263 | lua_getfield(L, 1, name); 264 | } 265 | 266 | bool Thread::dub_call(int param_count, int retval_count) const { 267 | lua_State *L = const_cast(dub_L); 268 | int status = lua_pcall(L, param_count, retval_count, 2); 269 | if (status) { 270 | if (status == LUA_ERRRUN) { 271 | // failure properly handled by the error handler 272 | } else if (status == LUA_ERRMEM) { 273 | // memory allocation failure 274 | fprintf(stderr, "Memory allocation failure (%s).\n", lua_tostring(dub_L, -1)); 275 | } else { 276 | // error in error handler 277 | fprintf(stderr, "Error in error handler (%s).\n", lua_tostring(dub_L, -1)); 278 | } 279 | lua_pop(dub_L, 1); 280 | return false; 281 | } 282 | return true; 283 | } 284 | 285 | 286 | 287 | 288 | // ====================================================================== 289 | // =============================================== dub::error 290 | // ====================================================================== 291 | // This calls lua_Error after preparing the error message with line 292 | // and number. 293 | int dub::error(lua_State *L) { 294 | // ... 295 | luaL_where(L, 1); 296 | // ... 297 | // Does it match 'Dub init code' ? 298 | const char *w = lua_tostring(L, -1); 299 | if (!strncmp(w, DUB_INIT_ERR, strlen(DUB_INIT_ERR))) { 300 | // error in ctor, show calling place, not dub init code. 301 | lua_pop(L, 1); 302 | luaL_where(L, 2); 303 | } 304 | // ... 305 | lua_pushvalue(L, -2); 306 | // ... 307 | lua_remove(L, -3); 308 | // ... 309 | lua_concat(L, 2); 310 | return lua_error(L); 311 | } 312 | 313 | 314 | 315 | 316 | // ====================================================================== 317 | // =============================================== dub::protect 318 | // ====================================================================== 319 | 320 | // TODO: Can we make this faster ? 321 | inline void push_own_env(lua_State *L, int ud) { 322 | #ifdef DUB_LUA_FIVE_ONE 323 | lua_getfenv(L, ud); 324 | // ... ... 325 | lua_pushstring(L, "."); 326 | // ... ... "." 327 | lua_rawget(L, -2); // ["."] 328 | // ... ... 329 | if (!lua_rawequal(L, -1, ud)) { 330 | // ... ... 331 | // does not have it's own env table 332 | lua_pop(L, 2); 333 | // ... ... 334 | #else 335 | lua_getuservalue(L, ud); 336 | // ... ... 337 | if (lua_isnil(L, -1)) { 338 | lua_pop(L, 1); 339 | #endif 340 | // ... ... 341 | // Create env table 342 | lua_newtable(L); 343 | // ... ... 344 | lua_pushstring(L, "."); 345 | // ... ... "." 346 | lua_pushvalue(L, ud); 347 | // ... ... "." 348 | lua_rawset(L, -3); // env["."] = udata 349 | // ... ... 350 | lua_pushvalue(L, -1); 351 | // ... ... 352 | #ifdef DUB_LUA_FIVE_ONE 353 | if (!lua_setfenv(L, ud)) { 354 | luaL_error(L, "Could not set userdata env on '%s'.", lua_typename(L, lua_type(L, ud))); 355 | } 356 | #else 357 | lua_setuservalue(L, ud); 358 | #endif 359 | // ... ... 360 | } else { 361 | // ... ... 362 | // has its own env table 363 | lua_pop(L, 1); 364 | // ... ... 365 | } 366 | } 367 | 368 | void dub::protect(lua_State *L, int owner, int original, const char *key) { 369 | // Point to original to avoid original gc before owner. 370 | push_own_env(L, owner); 371 | // ... 372 | lua_pushvalue(L, original); 373 | // ... 374 | lua_setfield(L, -2, key); // env["key"] = 375 | // ... 376 | lua_pop(L, 1); 377 | // ... 378 | } 379 | 380 | // ====================================================================== 381 | // =============================================== dub::pushudata 382 | // ====================================================================== 383 | 384 | void dub::pushudata(lua_State *L, const void *cptr, const char *tname, bool gc) { 385 | // To avoid users spending time with const issues. 386 | void *ptr = const_cast(cptr); 387 | // If anything is changed here, it must be reflected in dub::Object::dub_pushobject. 388 | DubUserdata *userdata = (DubUserdata*)lua_newuserdata(L, sizeof(DubUserdata)); 389 | userdata->ptr = ptr; 390 | if (!gc) { 391 | // Point to original (self) to avoid original gc. 392 | dub::protect(L, lua_gettop(L), 1, "_"); 393 | } 394 | 395 | userdata->gc = gc; 396 | 397 | // the userdata is now on top of the stack 398 | luaL_getmetatable(L, tname); 399 | if (lua_isnil(L, -1)) { 400 | lua_pop(L, 1); 401 | // create empty metatable on the fly for opaque types. 402 | luaL_newmetatable(L, tname); 403 | } 404 | // 405 | 406 | // set metatable (contains methods) 407 | lua_setmetatable(L, -2); 408 | } 409 | 410 | // ====================================================================== 411 | // =============================================== dub::check ... 412 | // ====================================================================== 413 | // These methods are slight adaptations from luaxlib.c 414 | // Copyright (C) 1994-2008 Lua.org, PUC-Rio. 415 | 416 | lua_Number dub::checknumber(lua_State *L, int narg) noexcept(false) { 417 | #ifdef DUB_LUA_FIVE_ONE 418 | lua_Number d = lua_tonumber(L, narg); 419 | if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ 420 | throw TypeException(L, narg, lua_typename(L, LUA_TNUMBER)); 421 | return d; 422 | #else 423 | int isnum = 0; 424 | lua_Number d = lua_tonumberx(L, narg, &isnum); 425 | if (!isnum) 426 | throw TypeException(L, narg, lua_typename(L, LUA_TNUMBER)); 427 | return d; 428 | #endif 429 | } 430 | 431 | lua_Integer dub::checkinteger(lua_State *L, int narg) noexcept(false) { 432 | #ifdef DUB_LUA_FIVE_ONE 433 | lua_Integer d = lua_tointeger(L, narg); 434 | if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ 435 | throw TypeException(L, narg, lua_typename(L, LUA_TNUMBER)); 436 | return d; 437 | #else 438 | int isnum = 0; 439 | lua_Integer d = lua_tointegerx(L, narg, &isnum); 440 | if (!isnum) 441 | throw TypeException(L, narg, lua_typename(L, LUA_TNUMBER)); 442 | return d; 443 | #endif 444 | } 445 | 446 | const char *dub::checklstring(lua_State *L, int narg, size_t *len) noexcept(false) { 447 | const char *s = lua_tolstring(L, narg, len); 448 | if (!s) throw TypeException(L, narg, lua_typename(L, LUA_TSTRING)); 449 | return s; 450 | } 451 | 452 | void **dub::checkudata(lua_State *L, int ud, const char *tname, bool keep_mt) noexcept(false) { 453 | void **p = (void**)lua_touserdata(L, ud); 454 | if (p != NULL) { /* value is a userdata? */ 455 | if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ 456 | lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ 457 | if (lua_rawequal(L, -1, -2)) { 458 | // same (correct) metatable 459 | if (!keep_mt) { 460 | lua_pop(L, 2); 461 | } else { 462 | // keep 1 metatable on top (needed by bindings) 463 | lua_pop(L, 1); 464 | } 465 | if (!*p) { 466 | throw dub::Exception(DEAD_EXCEPTION_MSG, tname); 467 | } 468 | return p; 469 | } 470 | } 471 | } 472 | throw TypeException(L, ud, tname); /* else error */ 473 | return NULL; /* to avoid warnings */ 474 | } 475 | 476 | 477 | static inline void **dub_cast_ud(lua_State *L, int ud, const char *tname) { 478 | // .. ... 479 | lua_pop(L, 1); 480 | // ... ... 481 | // TODO: optmize by putting this cast value in the registry. 482 | lua_pushlstring(L, "_cast_", 6); 483 | // ... ... "_cast_" 484 | lua_rawget(L, -2); 485 | if (lua_isfunction(L, -1)) { 486 | lua_pushvalue(L, ud); 487 | lua_pushstring(L, tname); 488 | // ... ... cast_func "OtherType" 489 | lua_call(L, 2, 1); 490 | // ... ... 491 | void **p = (void**)lua_touserdata(L, -1); 492 | if (p != NULL) { 493 | // done 494 | return p; 495 | } 496 | } 497 | 498 | // ... ... nil 499 | // Does not change stack size (only last element). 500 | return NULL; 501 | } 502 | 503 | static inline void **getsdata(lua_State *L, int ud, const char *tname, bool keep_mt) noexcept(false) { 504 | void **p = (void**)lua_touserdata(L, ud); 505 | if (p != NULL) { /* value is a userdata? */ 506 | if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ 507 | lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ 508 | if (lua_rawequal(L, -1, -2)) { 509 | // same (correct) metatable 510 | lua_pop(L, keep_mt ? 1 : 2); 511 | } else { 512 | p = dub_cast_ud(L, ud, tname); 513 | // ... ... 514 | if (p && keep_mt) { 515 | lua_remove(L, -2); 516 | } else { 517 | lua_pop(L, 2); 518 | } 519 | } 520 | } 521 | } else if (lua_istable(L, ud)) { 522 | if (ud < 0) { 523 | ud = lua_gettop(L) + 1 + ud; 524 | } 525 | // get p from super 526 | // ... ... 527 | // TODO: optimize by storing key in registry ? 528 | lua_pushlstring(L, "super", 5); 529 | // ... ... 'super' 530 | lua_rawget(L, ud); 531 | // ... ... 532 | p = (void**)lua_touserdata(L, -1); 533 | if (p != NULL) { 534 | // ... ... 535 | if (lua_getmetatable(L, -1)) { /* does it have a metatable? */ 536 | // ... ... 537 | lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ 538 | // ... ... 539 | if (lua_rawequal(L, -1, -2)) { 540 | // same (correct) metatable 541 | lua_remove(L, -3); 542 | // ... ... 543 | lua_pop(L, keep_mt ? 1 : 2); 544 | } else { 545 | lua_remove(L, -3); 546 | // ... ... 547 | p = dub_cast_ud(L, ud, tname); 548 | // ... ... 549 | if (p && keep_mt) { 550 | lua_remove(L, -2); 551 | // ... ... 552 | } else { 553 | lua_pop(L, 2); 554 | // ... ... 555 | } 556 | } 557 | } else { 558 | lua_pop(L, 1); 559 | // ... ... 560 | } 561 | } else { 562 | lua_pop(L, 1); 563 | // ... ... 564 | } 565 | } 566 | return p; 567 | } 568 | 569 | void **dub::checksdata_n(lua_State *L, int ud, const char *tname, bool keep_mt) { 570 | void **p = getsdata(L, ud, tname, keep_mt); 571 | if (!p) { 572 | luaL_error(L, TYPE_EXCEPTION_MSG, tname, luaL_typename(L, ud)); 573 | } else if (!*p) { 574 | // dead object 575 | luaL_error(L, DEAD_EXCEPTION_MSG, tname); 576 | } 577 | return p; 578 | } 579 | 580 | void **dub::issdata(lua_State *L, int ud, const char *tname, int type) { 581 | if (type == LUA_TUSERDATA || type == LUA_TTABLE) { 582 | void **p = getsdata(L, ud, tname, false); 583 | if (!p) { 584 | return NULL; 585 | } else if (!*p) { 586 | // dead object 587 | throw dub::Exception(DEAD_EXCEPTION_MSG, tname); 588 | } else { 589 | return p; 590 | } 591 | } else { 592 | return NULL; 593 | } 594 | } 595 | 596 | void **dub::checksdata(lua_State *L, int ud, const char *tname, bool keep_mt) noexcept(false) { 597 | void **p = getsdata(L, ud, tname, keep_mt); 598 | if (!p) { 599 | throw dub::TypeException(L, ud, tname); 600 | } else if (!*p) { 601 | // dead object 602 | throw dub::Exception(DEAD_EXCEPTION_MSG, tname); 603 | } 604 | return p; 605 | } 606 | 607 | void **dub::checksdata_d(lua_State *L, int ud, const char *tname) noexcept(false) { 608 | void **p = getsdata(L, ud, tname, false); 609 | if (!p) { 610 | throw dub::TypeException(L, ud, tname); 611 | } 612 | // do not check for dead objects 613 | return p; 614 | } 615 | 616 | // ====================================================================== 617 | // =============================================== dub::setup 618 | // ====================================================================== 619 | 620 | void dub::setup(lua_State *L, const char *type_name) { 621 | // meta-table should be on top 622 | // 623 | lua_getfield(L, -1, "__index"); 624 | if (lua_isnil(L, -1)) { 625 | lua_pop(L, 1); 626 | lua_pushvalue(L, -1); 627 | // .__index = 628 | lua_setfield(L, -2, "__index"); 629 | } else { 630 | // We already have a custom __index metamethod. 631 | lua_pop(L, 1); 632 | } 633 | // 634 | lua_pushstring(L, type_name); 635 | // "type_name" 636 | // ."type" = "type_name" 637 | lua_setfield(L, -2, "type"); 638 | 639 | // 640 | 641 | // Setup the __call meta-table with an upvalue 642 | // printf("%s\n", DUB_INIT_CODE); 643 | /* 644 | local class = ... 645 | -- new can be nil for abstract types 646 | if class.new then 647 | setmetatable(class, { 648 | __call = function(lib, ...) 649 | -- We could keep lib.new in an upvalue but this 650 | -- prevents rewriting class.new in Lua which is 651 | -- very useful. 652 | return lib.new(...) 653 | end, 654 | }) 655 | end 656 | */ 657 | int error = luaL_loadbuffer(L, DUB_INIT_CODE, strlen(DUB_INIT_CODE), "Dub init code"); 658 | if (error) { 659 | fprintf(stderr, "%s", lua_tostring(L, -1)); 660 | lua_pop(L, 1); /* pop error message from the stack */ 661 | } else { 662 | // 663 | lua_pushvalue(L, -2); 664 | // 665 | error = lua_pcall(L, 1, 0, 0); 666 | if (error) { 667 | fprintf(stderr, "%s", lua_tostring(L, -1)); 668 | lua_pop(L, 1); /* pop error message from the stack */ 669 | } 670 | } 671 | // free(lua_code); 672 | // 673 | } 674 | 675 | int dub::hash(const char *str, int sz) { 676 | unsigned int h = 0; 677 | int c; 678 | 679 | while ( (c = *str++) ) { 680 | // FIXME: integer constant is too large for 'long' type 681 | unsigned int h1 = (h << 6) % DUB_MAX_IN_SHIFT; 682 | unsigned int h2 = (h << 16) % DUB_MAX_IN_SHIFT; 683 | h = c + h1 + h2 - h; 684 | h = h % DUB_MAX_IN_SHIFT; 685 | } 686 | return h % sz; 687 | } 688 | 689 | // register constants in the table at the top 690 | void dub::register_const(lua_State *L, const dub::const_Reg*l) { 691 | for (; l->name; l++) { 692 | // push each constant into the table at top 693 | lua_pushnumber(L, l->value); 694 | lua_setfield(L, -2, l->name); 695 | } 696 | } 697 | 698 | // This is called whenever we ask for obj:deleted() in Lua 699 | int dub::isDeleted(lua_State *L) { 700 | void **p = (void**)lua_touserdata(L, 1); 701 | if (p == NULL && lua_istable(L, 1)) { 702 | // get p from super 703 | // 704 | // TODO: optimize by storing key in registry ? 705 | lua_pushlstring(L, "super", 5); 706 | // 'super' 707 | lua_rawget(L, 1); 708 | // 709 | p = (void**)lua_touserdata(L, 2); 710 | lua_pop(L, 1); 711 | // 712 | } 713 | lua_pushboolean(L, p && !*p); 714 | return 1; 715 | } 716 | 717 | // Compatibility with luaL_register on lua 5.1 and 5.2 718 | void dub::fregister(lua_State *L, const luaL_Reg *l) { 719 | #ifdef DUB_LUA_FIVE_ONE 720 | luaL_register(L, NULL, l); 721 | #else 722 | luaL_setfuncs(L, l, 0); 723 | #endif 724 | } 725 | 726 | 727 | -------------------------------------------------------------------------------- /src/bind/dub/dub.h: -------------------------------------------------------------------------------- 1 | /* 2 | ============================================================================== 3 | 4 | This file is part of the DUB bindings generator (http://lubyk.org/dub) 5 | Copyright (c) 2007-2012 by Gaspard Bucher (http://teti.ch). 6 | 7 | ------------------------------------------------------------------------------ 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in 17 | all copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | THE SOFTWARE. 26 | 27 | ============================================================================== 28 | */ 29 | #ifndef DUB_BINDING_GENERATOR_DUB_H_ 30 | #define DUB_BINDING_GENERATOR_DUB_H_ 31 | 32 | #include // strlen strcmp 33 | 34 | #ifndef DUB_ASSERT_KEY 35 | #define DUB_ASSERT_KEY(k, m) strcmp(k, m) 36 | // Use this to avoid the overhead of strcmp in get/set of public attributes. 37 | // if you avoid strcmp, bad keys can map to any other key. 38 | //#define DUB_ASSERT_KEY(k, m) false 39 | #endif 40 | #define KEY_EXCEPTION_MSG "invalid key '%s'" 41 | 42 | typedef int LuaStackSize; 43 | 44 | #ifndef DUB_EXPORT 45 | #ifdef _WIN32 46 | #define DUB_EXPORT extern "C" __declspec(dllexport) 47 | #else 48 | #define DUB_EXPORT extern "C" 49 | #endif 50 | #endif 51 | 52 | #ifdef __cplusplus 53 | extern "C" { 54 | #endif 55 | // We need C linkage because lua lib is compiled as C code 56 | #include 57 | #include 58 | #ifdef __cplusplus 59 | } 60 | #endif 61 | 62 | #include // std::string for Exception 63 | #include // std::exception 64 | 65 | // Helpers to check for explicit 'false' or 'true' return values. 66 | #define lua_isfalse(L,i) (lua_isboolean(L,i) && !lua_toboolean(L,i)) 67 | #define lua_istrue(L,i) (lua_isboolean(L,i) && lua_toboolean(L,i)) 68 | #define luaL_checkboolean(L,n) (lua_toboolean(L,n)) 69 | 70 | struct DubUserdata { 71 | void *ptr; 72 | bool gc; 73 | }; 74 | 75 | // ====================================================================== 76 | // =============================================== dub::Exception 77 | // ====================================================================== 78 | namespace dub { 79 | 80 | /** All exceptions raised by dub::check.. are instances of this class. All 81 | * exceptions deriving from std::exception have their message displayed 82 | * in Lua (through lua_error). 83 | */ 84 | class Exception : public std::exception { 85 | std::string message_; 86 | public: 87 | explicit Exception(const char *format, ...); 88 | ~Exception() throw(); 89 | const char* what() const throw(); 90 | }; 91 | 92 | class TypeException : public Exception { 93 | public: 94 | explicit TypeException(lua_State *L, int narg, const char *type, bool is_super = false); 95 | }; 96 | 97 | /** This class allows an object to be deleted from either C++ or Lua. 98 | * When Lua deletes the object, dub_destroy is called. When C++ deletes 99 | * the object, the related userdata is invalidated. 100 | */ 101 | class Object { 102 | public: 103 | Object() : dub_userdata_(NULL) {} 104 | 105 | /** The destructor marks the userdata as deleted so that Lua no 106 | * longer tries to access it. 107 | */ 108 | virtual ~Object() { 109 | if (dub_userdata_) { 110 | // Protect from gc. 111 | dub_userdata_->gc = false; 112 | // Invalidate Lua userdata. 113 | dub_userdata_->ptr = NULL; 114 | } 115 | } 116 | 117 | /** This is called on object instanciation by dub instead of 118 | * dub::pushudata to setup dub_userdata_. 119 | * 120 | */ 121 | void dub_pushobject(lua_State *L, void *ptr, const char *type_name, bool gc = true); 122 | 123 | protected: 124 | /** Pointer to the userdata. *userdata => pointer to C++ object. 125 | */ 126 | DubUserdata *dub_userdata_; 127 | }; 128 | 129 | /** This class creates a 'self' table and prepares a thread 130 | * that can be used for callbacks from C++ to Lua. 131 | */ 132 | class Thread : public Object { 133 | public: 134 | Thread() 135 | : dub_L(NULL) {} 136 | /** This is called on object instanciation by dub to create the lua 137 | * thread, prepare the table and setup metamethods. This is 138 | * called instead of dub::pushudata. 139 | * 140 | */ 141 | void dub_pushobject(lua_State *L, void *ptr, const char *type_name, bool gc = true); 142 | 143 | /** Push function 'name' found in on the stack with as 144 | * first argument. 145 | * 146 | * Constness is there to make it easy to implement callbacks like 147 | * int rowCount() const, without requiring users to fiddle with constness 148 | * which is not a notion part of Lua anyway. 149 | */ 150 | bool dub_pushcallback(const char *name) const; 151 | 152 | /** Push any lua value from self on the stack. 153 | */ 154 | void dub_pushvalue(const char *name) const; 155 | 156 | /** Execute the protected call. If an error occurs, dub tries to find 157 | * an 'error' function in and calls this function with the 158 | * error string. If no error function is found, the error message is 159 | * just printed out to stderr. 160 | */ 161 | bool dub_call(int param_count, int retval_count) const; 162 | 163 | /** Lua thread that contains on stack position 1. This lua thread 164 | * is public to ease object state manipulation from C++ (but stack *must 165 | * not* be messed up). 166 | */ 167 | lua_State *dub_L; 168 | 169 | protected: 170 | /** Type name (allows faster check for cast). 171 | */ 172 | const char *dub_typename_; 173 | }; 174 | 175 | // ====================================================================== 176 | // =============================================== dub::pushclass 177 | // ====================================================================== 178 | 179 | // To ease storing a LuaRef in a void* pointer. 180 | struct DubRef { 181 | int ref; 182 | 183 | static int set(lua_State *L, void **ptr, int id) { 184 | if (lua_isnil(L, id)) { 185 | cleanup(L, ptr); 186 | } else { 187 | DubRef *ref; 188 | if (*ptr) { 189 | ref = (DubRef*)*ptr; 190 | luaL_unref(L, LUA_REGISTRYINDEX, ref->ref); 191 | } else { 192 | ref = new DubRef(); 193 | *ptr = ref; 194 | } 195 | ref->ref = luaL_ref(L, LUA_REGISTRYINDEX); 196 | } 197 | return 0; 198 | } 199 | 200 | static int push(lua_State *L, void *ptr) { 201 | if (ptr) { 202 | DubRef *ref = (DubRef*)ptr; 203 | lua_rawgeti(L, LUA_REGISTRYINDEX, ref->ref); 204 | return 1; 205 | } else { 206 | return 0; 207 | } 208 | } 209 | 210 | static void cleanup(lua_State *L, void **ptr) { 211 | if (*ptr) { 212 | DubRef *ref = (DubRef*)*ptr; 213 | luaL_unref(L, LUA_REGISTRYINDEX, ref->ref); 214 | delete ref; 215 | *ptr = NULL; 216 | } 217 | } 218 | }; 219 | 220 | /** Push a custom type on the stack. 221 | * Since the value is passed as a pointer, we assume it has been created 222 | * using 'new' and Lua can safely call delete when it needs to garbage- 223 | * -collect it. 224 | * 225 | * Constness: we const cast all passed values to ease passing read-only 226 | * arguments without requiring users to fiddle with constness which is not 227 | * a notion part of Lua anyway. 228 | */ 229 | void pushudata(lua_State *L, const void *ptr, const char *type_name, bool gc = true); 230 | 231 | template 232 | struct DubFullUserdata { 233 | T *ptr; 234 | T obj; 235 | }; 236 | 237 | template 238 | void pushfulldata(lua_State *L, const T &obj, const char *type_name) { 239 | DubFullUserdata *copy = (DubFullUserdata*)lua_newuserdata(L, sizeof(DubFullUserdata)); 240 | copy->obj = obj; 241 | // now **copy gives back the object. 242 | copy->ptr = ©->obj; 243 | 244 | // the userdata is now on top of the stack 245 | 246 | // set metatable (contains methods) 247 | luaL_getmetatable(L, type_name); 248 | lua_setmetatable(L, -2); 249 | } 250 | 251 | template 252 | void pushclass(lua_State *L, const T &obj, const char *type_name) { 253 | T *copy = new T(obj); 254 | pushudata(L, (void*)copy, type_name); 255 | } 256 | 257 | // ====================================================================== 258 | // =============================================== dub::pushclass2 259 | // ====================================================================== 260 | 261 | /** Push a custom type on the stack and give it the pointer to the userdata. 262 | * Passing the userdata enables early deletion from C++ that safely 263 | * invalidates the userdatum by calling 264 | */ 265 | template 266 | void pushclass2(lua_State *L, T *ptr, const char *type_name) { 267 | T **userdata = (T**)lua_newuserdata(L, sizeof(T*)); 268 | *userdata = ptr; 269 | 270 | // Store pointer in class so that it can set it to NULL on destroy with 271 | // *userdata = NULL 272 | ptr->luaInit((void**)userdata); 273 | // 274 | luaL_getmetatable(L, type_name); 275 | // 276 | lua_setmetatable(L, -2); 277 | // 278 | } 279 | 280 | // ====================================================================== 281 | // =============================================== constants 282 | // ====================================================================== 283 | 284 | typedef struct const_Reg { 285 | const char *name; 286 | double value; 287 | } const_Reg; 288 | 289 | // register constants in the table at the top 290 | void register_const(lua_State *L, const const_Reg *l); 291 | 292 | // ====================================================================== 293 | // =============================================== dub_check ... 294 | // ====================================================================== 295 | 296 | // These provide the same funcionality as their equivalent luaL_check... but they 297 | // throw std::exception which can be caught (eventually to call lua_error). 298 | lua_Number checknumber(lua_State *L, int narg) noexcept(false); 299 | lua_Integer checkinteger(lua_State *L, int narg) noexcept(false); 300 | const char *checklstring(lua_State *L, int narg, size_t *len) noexcept(false); 301 | void **checkudata(lua_State *L, int ud, const char *tname, bool keep_mt = false) noexcept(false); 302 | 303 | // Super aware userdata calls (finds userdata inside provided table with table.super). 304 | void **checksdata(lua_State *L, int ud, const char *tname, bool keep_mt = false) noexcept(false); 305 | // Super aware userdata calls that DOES NOT check for dangling pointers (used in 306 | // __gc binding). 307 | void **checksdata_d(lua_State *L, int ud, const char *tname) noexcept(false); 308 | // Return pointer if the type is correct. Used to resolve overloaded functions when there 309 | // is no other alternative (arg count, native types). We return the pointer so that we can 310 | // optimize away the corresponding 'dub_checksdata'. 311 | void **issdata(lua_State *L, int ud, const char *tname, int type); 312 | // Does not throw exceptions. This method behaves exactly like luaL_checkudata but searches 313 | // for table.super before calling lua_error. We cannot use throw() because of differing 314 | // implementations for luaL_error (luajit throws an exception on luaL_error). 315 | void **checksdata_n(lua_State *L, int ud, const char *tname, bool keep_mt = false); 316 | 317 | inline const char *checkstring(lua_State *L, int narg) noexcept(false) { 318 | return checklstring(L, narg, NULL); 319 | } 320 | 321 | inline int checkboolean(lua_State *L, int narg) noexcept { 322 | return lua_toboolean(L, narg); 323 | } 324 | 325 | // This calls lua_Error after preparing the error message with line 326 | // and number. 327 | int error(lua_State *L); 328 | 329 | // This is a Lua binding called whenever we ask for obj:deleted() in Lua 330 | int isDeleted(lua_State *L); 331 | 332 | /** Protect garbage collection from pointers stored in objects or 333 | * retrieved in userdata copies. 334 | */ 335 | void protect(lua_State *L, int owner, int original, const char *key); 336 | 337 | /** Prepare index function, setup 'type' field and __call metamethod. 338 | */ 339 | void setup(lua_State *L, const char *class_name); 340 | 341 | // sdbm function: taken from http://www.cse.yorku.ca/~oz/hash.html 342 | // This version is slightly adapted to cope with different 343 | // hash sizes (and to be easy to write in Lua). 344 | int hash(const char *str, int sz); 345 | 346 | // Simple debugging function to print stack content. 347 | void printStack(lua_State *L, const char *msg = NULL); 348 | 349 | // Compatibility with luaL_register on lua 5.1 and 5.2 350 | void fregister(lua_State *L, const luaL_Reg *l); 351 | 352 | 353 | } // dub 354 | 355 | #endif // DUB_BINDING_GENERATOR_DUB_H_ 356 | 357 | -------------------------------------------------------------------------------- /src/bind/xml_Parser.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * MACHINE GENERATED FILE. DO NOT EDIT. 4 | * 5 | * Bindings for class Parser 6 | * 7 | * This file has been generated by dub 2.2.2. 8 | */ 9 | #include "dub/dub.h" 10 | #include "xml/Parser.h" 11 | 12 | using namespace xml; 13 | 14 | /** xml::Parser::Parser(Type type=Default) 15 | * include/xml/Parser.h:48 16 | */ 17 | static int Parser_Parser(lua_State *L) { 18 | try { 19 | int top__ = lua_gettop(L); 20 | if (top__ >= 1) { 21 | xml::Parser::Type type = (xml::Parser::Type)dub::checkinteger(L, 1); 22 | Parser *retval__ = new Parser(type); 23 | dub::pushudata(L, retval__, "xml.Parser", true); 24 | return 1; 25 | } else { 26 | Parser *retval__ = new Parser(); 27 | dub::pushudata(L, retval__, "xml.Parser", true); 28 | return 1; 29 | } 30 | } catch (std::exception &e) { 31 | lua_pushfstring(L, "new: %s", e.what()); 32 | } catch (...) { 33 | lua_pushfstring(L, "new: Unknown exception"); 34 | } 35 | return dub::error(L); 36 | } 37 | 38 | /** xml::Parser::~Parser() 39 | * include/xml/Parser.h:49 40 | */ 41 | static int Parser__Parser(lua_State *L) { 42 | try { 43 | DubUserdata *userdata = ((DubUserdata*)dub::checksdata_d(L, 1, "xml.Parser")); 44 | if (userdata->gc) { 45 | Parser *self = (Parser *)userdata->ptr; 46 | delete self; 47 | } 48 | userdata->gc = false; 49 | return 0; 50 | } catch (std::exception &e) { 51 | lua_pushfstring(L, "__gc: %s", e.what()); 52 | } catch (...) { 53 | lua_pushfstring(L, "__gc: Unknown exception"); 54 | } 55 | return dub::error(L); 56 | } 57 | 58 | /** LuaStackSize xml::Parser::load(lua_State *L) 59 | * include/xml/Parser.h:53 60 | */ 61 | static int Parser_load(lua_State *L) { 62 | try { 63 | Parser *self = *((Parser **)dub::checksdata(L, 1, "xml.Parser")); 64 | return self->load(L); 65 | } catch (std::exception &e) { 66 | lua_pushfstring(L, "load: %s", e.what()); 67 | } catch (...) { 68 | lua_pushfstring(L, "load: Unknown exception"); 69 | } 70 | return dub::error(L); 71 | } 72 | 73 | 74 | 75 | // --=============================================== __tostring 76 | static int Parser___tostring(lua_State *L) { 77 | Parser *self = *((Parser **)dub::checksdata_n(L, 1, "xml.Parser")); 78 | lua_pushfstring(L, "xml.Parser: %p", self); 79 | 80 | return 1; 81 | } 82 | 83 | // --=============================================== METHODS 84 | 85 | static const struct luaL_Reg Parser_member_methods[] = { 86 | { "new" , Parser_Parser }, 87 | { "__gc" , Parser__Parser }, 88 | { "load" , Parser_load }, 89 | { "__tostring" , Parser___tostring }, 90 | { "deleted" , dub::isDeleted }, 91 | { NULL, NULL}, 92 | }; 93 | 94 | // --=============================================== CONSTANTS 95 | static const struct dub::const_Reg Parser_const[] = { 96 | { "Default" , Parser::Default }, 97 | { "TrimWhitespace", Parser::TrimWhitespace }, 98 | { "NonDestructive", Parser::NonDestructive }, 99 | { "Fastest" , Parser::Fastest }, 100 | { NULL, 0}, 101 | }; 102 | 103 | DUB_EXPORT int luaopen_xml_Parser(lua_State *L) 104 | { 105 | // Create the metatable which will contain all the member methods 106 | luaL_newmetatable(L, "xml.Parser"); 107 | // 108 | // register class constants 109 | dub::register_const(L, Parser_const); 110 | 111 | // register member methods 112 | dub::fregister(L, Parser_member_methods); 113 | // setup meta-table 114 | dub::setup(L, "xml.Parser"); 115 | // 116 | return 1; 117 | } 118 | -------------------------------------------------------------------------------- /src/bind/xml_core.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * MACHINE GENERATED FILE. DO NOT EDIT. 4 | * 5 | * Bindings for library xml 6 | * 7 | * This file has been generated by dub 2.2.2. 8 | */ 9 | #include "dub/dub.h" 10 | #include "xml/Parser.h" 11 | 12 | using namespace xml; 13 | 14 | extern "C" { 15 | int luaopen_xml_Parser(lua_State *L); 16 | } 17 | 18 | // --=============================================== FUNCTIONS 19 | static const struct luaL_Reg xml_functions[] = { 20 | { NULL, NULL}, 21 | }; 22 | 23 | 24 | DUB_EXPORT int luaopen_xml_core(lua_State *L) { 25 | lua_newtable(L); 26 | // 27 | dub::fregister(L, xml_functions); 28 | // 29 | 30 | luaopen_xml_Parser(L); 31 | // 32 | lua_setfield(L, -2, "Parser"); 33 | 34 | // 35 | return 1; 36 | } 37 | -------------------------------------------------------------------------------- /src/vendor/license.txt: -------------------------------------------------------------------------------- 1 | Use of this software is granted under one of the following two licenses, 2 | to be chosen freely by the user. 3 | 4 | 1. Boost Software License - Version 1.0 - August 17th, 2003 5 | =============================================================================== 6 | 7 | Copyright (c) 2006, 2007 Marcin Kalicinski 8 | 9 | Permission is hereby granted, free of charge, to any person or organization 10 | obtaining a copy of the software and accompanying documentation covered by 11 | this license (the "Software") to use, reproduce, display, distribute, 12 | execute, and transmit the Software, and to prepare derivative works of the 13 | Software, and to permit third-parties to whom the Software is furnished to 14 | do so, all subject to the following: 15 | 16 | The copyright notices in the Software and this entire statement, including 17 | the above license grant, this restriction and the following disclaimer, 18 | must be included in all copies of the Software, in whole or in part, and 19 | all derivative works of the Software, unless such copies or derivative 20 | works are solely in the form of machine-executable object code generated by 21 | a source language processor. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 26 | SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 27 | FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 28 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 29 | DEALINGS IN THE SOFTWARE. 30 | 31 | 2. The MIT License 32 | =============================================================================== 33 | 34 | Copyright (c) 2006, 2007 Marcin Kalicinski 35 | 36 | Permission is hereby granted, free of charge, to any person obtaining a copy 37 | of this software and associated documentation files (the "Software"), to deal 38 | in the Software without restriction, including without limitation the rights 39 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 40 | of the Software, and to permit persons to whom the Software is furnished to do so, 41 | subject to the following conditions: 42 | 43 | The above copyright notice and this permission notice shall be included in all 44 | copies or substantial portions of the Software. 45 | 46 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 47 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 48 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 49 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 50 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 51 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 52 | IN THE SOFTWARE. 53 | -------------------------------------------------------------------------------- /src/vendor/manual.html: -------------------------------------------------------------------------------- 1 |

RAPIDXML Manual

Version 1.13

Copyright (C) 2006, 2009 Marcin Kalicinski
See accompanying file license.txt for license information.

Table of Contents

1. What is RapidXml?
1.1 Dependencies And Compatibility
1.2 Character Types And Encodings
1.3 Error Handling
1.4 Memory Allocation
1.5 W3C Compliance
1.6 API Design
1.7 Reliability
1.8 Acknowledgements
2. Two Minute Tutorial
2.1 Parsing
2.2 Accessing The DOM Tree
2.3 Modifying The DOM Tree
2.4 Printing XML
3. Differences From Regular XML Parsers
3.1 Lifetime Of Source Text
3.2 Ownership Of Strings
3.3 Destructive Vs Non-Destructive Mode
4. Performance
4.1 Comparison With Other Parsers
5. Reference

1. What is RapidXml?

RapidXml is an attempt to create the fastest XML DOM parser possible, while retaining useability, portability and reasonable W3C compatibility. It is an in-situ parser written in C++, with parsing speed approaching that of strlen() function executed on the same data.

89 | Entire parser is contained in a single header file, so no building or linking is neccesary. To use it you just need to copy rapidxml.hpp file to a convenient place (such as your project directory), and include it where needed. You may also want to use printing functions contained in header rapidxml_print.hpp.

1.1 Dependencies And Compatibility

RapidXml has no dependencies other than a very small subset of standard C++ library (<cassert>, <cstdlib>, <new> and <exception>, unless exceptions are disabled). It should compile on any reasonably conformant compiler, and was tested on Visual C++ 2003, Visual C++ 2005, Visual C++ 2008, gcc 3, gcc 4, and Comeau 4.3.3. Care was taken that no warnings are produced on these compilers, even with highest warning levels enabled.

1.2 Character Types And Encodings

RapidXml is character type agnostic, and can work both with narrow and wide characters. Current version does not fully support UTF-16 or UTF-32, so use of wide characters is somewhat incapacitated. However, it should succesfully parse wchar_t strings containing UTF-16 or UTF-32 if endianness of the data matches that of the machine. UTF-8 is fully supported, including all numeric character references, which are expanded into appropriate UTF-8 byte sequences (unless you enable parse_no_utf8 flag).

90 | Note that RapidXml performs no decoding - strings returned by name() and value() functions will contain text encoded using the same encoding as source file. Rapidxml understands and expands the following character references: &apos; &amp; &quot; &lt; &gt; &#...; Other character references are not expanded.

1.3 Error Handling

By default, RapidXml uses C++ exceptions to report errors. If this behaviour is undesirable, RAPIDXML_NO_EXCEPTIONS can be defined to suppress exception code. See parse_error class and parse_error_handler() function for more information.

1.4 Memory Allocation

RapidXml uses a special memory pool object to allocate nodes and attributes, because direct allocation using new operator would be far too slow. Underlying memory allocations performed by the pool can be customized by use of memory_pool::set_allocator() function. See class memory_pool for more information.

1.5 W3C Compliance

RapidXml is not a W3C compliant parser, primarily because it ignores DOCTYPE declarations. There is a number of other, minor incompatibilities as well. Still, it can successfully parse and produce complete trees of all valid XML files in W3C conformance suite (over 1000 files specially designed to find flaws in XML processors). In destructive mode it performs whitespace normalization and character entity substitution for a small set of built-in entities.

1.6 API Design

RapidXml API is minimalistic, to reduce code size as much as possible, and facilitate use in embedded environments. Additional convenience functions are provided in separate headers: rapidxml_utils.hpp and rapidxml_print.hpp. Contents of these headers is not an essential part of the library, and is currently not documented (otherwise than with comments in code).

1.7 Reliability

RapidXml is very robust and comes with a large harness of unit tests. Special care has been taken to ensure stability of the parser no matter what source text is thrown at it. One of the unit tests produces 100,000 randomly corrupted variants of XML document, which (when uncorrupted) contains all constructs recognized by RapidXml. RapidXml passes this test when it correctly recognizes that errors have been introduced, and does not crash or loop indefinitely.

91 | Another unit test puts RapidXml head-to-head with another, well estabilished XML parser, and verifies that their outputs match across a wide variety of small and large documents.

92 | Yet another test feeds RapidXml with over 1000 test files from W3C compliance suite, and verifies that correct results are obtained. There are also additional tests that verify each API function separately, and test that various parsing modes work as expected.

1.8 Acknowledgements

I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project. Additional thanks go to Kristen Wegner for creating pugxml, from which pugixml was derived. Janusz Wohlfeil kindly ran RapidXml speed tests on hardware that I did not have access to, allowing me to expand performance comparison table.

2. Two Minute Tutorial

2.1 Parsing

The following code causes RapidXml to parse a zero-terminated string named text:
using namespace rapidxml;
 93 | xml_document<> doc;    // character type defaults to char
 94 | doc.parse<0>(text);    // 0 means default parse flags
 95 | 
doc object is now a root of DOM tree containing representation of the parsed XML. Because all RapidXml interface is contained inside namespace rapidxml, users must either bring contents of this namespace into scope, or fully qualify all the names. Class xml_document represents a root of the DOM hierarchy. By means of public inheritance, it is also an xml_node and a memory_pool. Template parameter of xml_document::parse() function is used to specify parsing flags, with which you can fine-tune behaviour of the parser. Note that flags must be a compile-time constant.

2.2 Accessing The DOM Tree

To access the DOM tree, use methods of xml_node and xml_attribute classes:
cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
 96 | xml_node<> *node = doc.first_node("foobar");
 97 | cout << "Node foobar has value " << node->value() << "\n";
 98 | for (xml_attribute<> *attr = node->first_attribute();
 99 |      attr; attr = attr->next_attribute())
100 | {
101 |     cout << "Node foobar has attribute " << attr->name() << " ";
102 |     cout << "with value " << attr->value() << "\n";
103 | }
104 | 

2.3 Modifying The DOM Tree

DOM tree produced by the parser is fully modifiable. Nodes and attributes can be added/removed, and their contents changed. The below example creates a HTML document, whose sole contents is a link to google.com website:
xml_document<> doc;
105 | xml_node<> *node = doc.allocate_node(node_element, "a", "Google");
106 | doc.append_node(node);
107 | xml_attribute<> *attr = doc.allocate_attribute("href", "google.com");
108 | node->append_attribute(attr);
109 | 
One quirk is that nodes and attributes do not own the text of their names and values. This is because normally they only store pointers to the source text. So, when assigning a new name or value to the node, care must be taken to ensure proper lifetime of the string. The easiest way to achieve it is to allocate the string from the xml_document memory pool. In the above example this is not necessary, because we are only assigning character constants. But the code below uses memory_pool::allocate_string() function to allocate node name (which will have the same lifetime as the document), and assigns it to a new node:
xml_document<> doc;
110 | char *node_name = doc.allocate_string(name);        // Allocate string and copy name into it
111 | xml_node<> *node = doc.allocate_node(node_element, node_name);  // Set node name to node_name
112 | 
Check Reference section for description of the entire interface.

2.4 Printing XML

You can print xml_document and xml_node objects into an XML string. Use print() function or operator <<, which are defined in rapidxml_print.hpp header.
using namespace rapidxml;
113 | xml_document<> doc;    // character type defaults to char
114 | // ... some code to fill the document
115 | 
116 | // Print to stream using operator <<
117 | std::cout << doc;   
118 | 
119 | // Print to stream using print function, specifying printing flags
120 | print(std::cout, doc, 0);   // 0 means default printing flags
121 | 
122 | // Print to string using output iterator
123 | std::string s;
124 | print(std::back_inserter(s), doc, 0);
125 | 
126 | // Print to memory buffer using output iterator
127 | char buffer[4096];                      // You are responsible for making the buffer large enough!
128 | char *end = print(buffer, doc, 0);      // end contains pointer to character after last printed character
129 | *end = 0;                               // Add string terminator after XML
130 | 

3. Differences From Regular XML Parsers

RapidXml is an in-situ parser, which allows it to achieve very high parsing speed. In-situ means that parser does not make copies of strings. Instead, it places pointers to the source text in the DOM hierarchy.

3.1 Lifetime Of Source Text

In-situ parsing requires that source text lives at least as long as the document object. If source text is destroyed, names and values of nodes in DOM tree will become destroyed as well. Additionally, whitespace processing, character entity translation, and zero-termination of strings require that source text be modified during parsing (but see non-destructive mode). This makes the text useless for further processing once it was parsed by RapidXml.

131 | In many cases however, these are not serious issues.

3.2 Ownership Of Strings

Nodes and attributes produced by RapidXml do not own their name and value strings. They merely hold the pointers to them. This means you have to be careful when setting these values manually, by using xml_base::name(const Ch *) or xml_base::value(const Ch *) functions. Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. The easiest way to achieve it is to allocate the string from memory_pool owned by the document. Use memory_pool::allocate_string() function for this purpose.

3.3 Destructive Vs Non-Destructive Mode

By default, the parser modifies source text during the parsing process. This is required to achieve character entity translation, whitespace normalization, and zero-termination of strings.

132 | In some cases this behaviour may be undesirable, for example if source text resides in read only memory, or is mapped to memory directly from file. By using appropriate parser flags (parse_non_destructive), source text modifications can be disabled. However, because RapidXml does in-situ parsing, it obviously has the following side-effects:

4. Performance

RapidXml achieves its speed through use of several techniques:
  • In-situ parsing. When building DOM tree, RapidXml does not make copies of string data, such as node names and values. Instead, it stores pointers to interior of the source text.
  • Use of template metaprogramming techniques. This allows it to move much of the work to compile time. Through magic of the templates, C++ compiler generates a separate copy of parsing code for any combination of parser flags you use. In each copy, all possible decisions are made at compile time and all unused code is omitted.
  • Extensive use of lookup tables for parsing.
  • Hand-tuned C++ with profiling done on several most popular CPUs.
This results in a very small and fast code: a parser which is custom tailored to exact needs with each invocation.

4.1 Comparison With Other Parsers

The table below compares speed of RapidXml to some other parsers, and to strlen() function executed on the same data. On a modern CPU (as of 2007), you can expect parsing throughput to be close to 1 GB/s. As a rule of thumb, parsing speed is about 50-100x faster than Xerces DOM, 30-60x faster than TinyXml, 3-12x faster than pugxml, and about 5% - 30% faster than pugixml, the fastest XML parser I know of.
  • The test file is a real-world, 50kB large, moderately dense XML file.
  • All timing is done by using RDTSC instruction present in Pentium-compatible CPUs.
  • No profile-guided optimizations are used.
  • All parsers are running in their fastest modes.
  • The results are given in CPU cycles per character, so frequency of CPUs is irrelevant.
  • The results are minimum values from a large number of runs, to minimize effects of operating system activity, task switching, interrupt handling etc.
  • A single parse of the test file takes about 1/10th of a millisecond, so with large number of runs there is a good chance of hitting at least one no-interrupt streak, and obtaining undisturbed results.
Platform
Compiler
strlen() RapidXml pugixml 0.3 pugxml TinyXml
Pentium 4
MSVC 8.0
2.5
5.4
7.0
61.7
298.8
Pentium 4
gcc 4.1.1
0.8
6.1
9.5
67.0
413.2
Core 2
MSVC 8.0
1.0
4.5
5.0
24.6
154.8
Core 2
gcc 4.1.1
0.6
4.6
5.4
28.3
229.3
Athlon XP
MSVC 8.0
3.1
7.7
8.0
25.5
182.6
Athlon XP
gcc 4.1.1
0.9
8.2
9.2
33.7
265.2
Pentium 3
MSVC 8.0
2.0
6.3
7.0
30.9
211.9
Pentium 3
gcc 4.1.1
1.0
6.7
8.9
35.3
316.0
(*) All results are in CPU cycles per character of source text

5. Reference

This section lists all classes, functions, constants etc. and describes them in detail.
class 133 | template 134 | rapidxml::memory_pool
135 | constructor 136 | memory_pool()
137 | destructor 138 | ~memory_pool()
function allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_string(const Ch *source=0, std::size_t size=0)
function clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0)
function clear()
function set_allocator(alloc_func *af, free_func *ff)

class rapidxml::parse_error
139 | constructor 140 | parse_error(const char *what, void *where)
function what() const
function where() const

class 141 | template 142 | rapidxml::xml_attribute
143 | constructor 144 | xml_attribute()
function document() const
function previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const

class 145 | template 146 | rapidxml::xml_base
147 | constructor 148 | xml_base()
function name() const
function name_size() const
function value() const
function value_size() const
function name(const Ch *name, std::size_t size)
function name(const Ch *name)
function value(const Ch *value, std::size_t size)
function value(const Ch *value)
function parent() const

class 149 | template 150 | rapidxml::xml_document
151 | constructor 152 | xml_document()
function parse(Ch *text)
function clear()

class 153 | template 154 | rapidxml::xml_node
155 | constructor 156 | xml_node(node_type type)
function type() const
function document() const
function first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function type(node_type type)
function prepend_node(xml_node< Ch > *child)
function append_node(xml_node< Ch > *child)
function insert_node(xml_node< Ch > *where, xml_node< Ch > *child)
function remove_first_node()
function remove_last_node()
function remove_node(xml_node< Ch > *where)
function remove_all_nodes()
function prepend_attribute(xml_attribute< Ch > *attribute)
function append_attribute(xml_attribute< Ch > *attribute)
function insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute)
function remove_first_attribute()
function remove_last_attribute()
function remove_attribute(xml_attribute< Ch > *where)
function remove_all_attributes()

namespace rapidxml
enum node_type
function parse_error_handler(const char *what, void *where)
function print(OutIt out, const xml_node< Ch > &node, int flags=0)
function print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0)
function operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node)
157 | constant 158 | parse_no_data_nodes
159 | constant 160 | parse_no_element_values
161 | constant 162 | parse_no_string_terminators
163 | constant 164 | parse_no_entity_translation
165 | constant 166 | parse_no_utf8
167 | constant 168 | parse_declaration_node
169 | constant 170 | parse_comment_nodes
171 | constant 172 | parse_doctype_node
173 | constant 174 | parse_pi_nodes
175 | constant 176 | parse_validate_closing_tags
177 | constant 178 | parse_trim_whitespace
179 | constant 180 | parse_normalize_whitespace
181 | constant 182 | parse_default
183 | constant 184 | parse_non_destructive
185 | constant 186 | parse_fastest
187 | constant 188 | parse_full
189 | constant 190 | print_no_indenting


class 191 | template 192 | rapidxml::memory_pool

193 | 194 | Defined in rapidxml.hpp
195 | Base class for 196 | xml_document

Description

This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. In most cases, you will not need to use this class directly. However, if you need to create nodes manually or modify names/values of nodes, you are encouraged to use memory_pool of relevant xml_document to allocate the memory. Not only is this faster than allocating them by using new operator, but also their lifetime will be tied to the lifetime of document, possibly simplyfing memory management.

197 | Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. You can also call allocate_string() function to allocate strings. Such strings can then be used as names or values of nodes without worrying about their lifetime. Note that there is no free() function -- all allocations are freed at once when clear() function is called, or when the pool is destroyed.

198 | It is also possible to create a standalone memory_pool, and use it to allocate nodes, whose lifetime will not be tied to any document.

199 | Pool maintains RAPIDXML_STATIC_POOL_SIZE bytes of statically allocated memory. Until static memory is exhausted, no dynamic memory allocations are done. When static memory is exhausted, pool allocates additional blocks of memory of size RAPIDXML_DYNAMIC_POOL_SIZE each, by using global new[] and delete[] operators. This behaviour can be changed by setting custom allocation routines. Use set_allocator() function to set them.

200 | Allocations for nodes, attributes and strings are aligned at RAPIDXML_ALIGNMENT bytes. This value defaults to the size of pointer on target architecture.

201 | To obtain absolutely top performance from the parser, it is important that all nodes are allocated from a single, contiguous block of memory. Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. If required, you can tweak RAPIDXML_STATIC_POOL_SIZE, RAPIDXML_DYNAMIC_POOL_SIZE and RAPIDXML_ALIGNMENT to obtain best wasted memory to performance compromise. To do it, define their values before rapidxml.hpp file is included.

Parameters

Ch
Character type of created nodes.

202 | constructor 203 | memory_pool::memory_pool

Synopsis

memory_pool(); 204 |

Description

Constructs empty pool with default allocator functions.

205 | destructor 206 | memory_pool::~memory_pool

Synopsis

~memory_pool(); 207 |

Description

Destroys pool and frees all the memory. This causes memory occupied by nodes allocated by the pool to be freed. Nodes allocated from the pool are no longer valid.

function memory_pool::allocate_node

Synopsis

xml_node<Ch>* allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); 208 |

Description

Allocates a new node from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

type
Type of node to create.
name
Name to assign to the node, or 0 to assign no name.
value
Value to assign to the node, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated node. This pointer will never be NULL.

function memory_pool::allocate_attribute

Synopsis

xml_attribute<Ch>* allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); 209 |

Description

Allocates a new attribute from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

name
Name to assign to the attribute, or 0 to assign no name.
value
Value to assign to the attribute, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated attribute. This pointer will never be NULL.

function memory_pool::allocate_string

Synopsis

Ch* allocate_string(const Ch *source=0, std::size_t size=0); 210 |

Description

Allocates a char array of given size from the pool, and optionally copies a given string to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

source
String to initialize the allocated memory with, or 0 to not initialize it.
size
Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.

Returns

Pointer to allocated char array. This pointer will never be NULL.

function memory_pool::clone_node

Synopsis

xml_node<Ch>* clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0); 211 |

Description

Clones an xml_node and its hierarchy of child nodes and attributes. Nodes and attributes are allocated from this memory pool. Names and values are not cloned, they are shared between the clone and the source. Result node can be optionally specified as a second parameter, in which case its contents will be replaced with cloned source node. This is useful when you want to clone entire document.

Parameters

source
Node to clone.
result
Node to put results in, or 0 to automatically allocate result node

Returns

Pointer to cloned node. This pointer will never be NULL.

function memory_pool::clear

Synopsis

void clear(); 212 |

Description

Clears the pool. This causes memory occupied by nodes allocated by the pool to be freed. Any nodes or strings allocated from the pool will no longer be valid.

function memory_pool::set_allocator

Synopsis

void set_allocator(alloc_func *af, free_func *ff); 213 |

Description

Sets or resets the user-defined memory allocation functions for the pool. This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. Allocation function must not return invalid pointer on failure. It should either throw, stop the program, or use longjmp() function to pass control to other place of program. If it returns invalid pointer, results are undefined.

214 | User defined allocation functions must have the following forms:

215 | void *allocate(std::size_t size);
216 | void free(void *pointer);

Parameters

af
Allocation function, or 0 to restore default function
ff
Free function, or 0 to restore default function

class rapidxml::parse_error

217 | 218 | Defined in rapidxml.hpp

Description

Parse error exception. This exception is thrown by the parser when an error occurs. Use what() function to get human-readable error message. Use where() function to get a pointer to position within source text where error was detected.

219 | If throwing exceptions by the parser is undesirable, it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. This function must be defined by the user.

220 | This class derives from std::exception class.

221 | constructor 222 | parse_error::parse_error

Synopsis

parse_error(const char *what, void *where); 223 |

Description

Constructs parse error.

function parse_error::what

Synopsis

virtual const char* what() const; 224 |

Description

Gets human readable description of error.

Returns

Pointer to null terminated description of the error.

function parse_error::where

Synopsis

Ch* where() const; 225 |

Description

Gets pointer to character data where error happened. Ch should be the same as char type of xml_document that produced the error.

Returns

Pointer to location within the parsed string where error occured.

class 226 | template 227 | rapidxml::xml_attribute

228 | 229 | Defined in rapidxml.hpp
230 | Inherits from 231 | xml_base

Description

Class representing attribute node of XML document. Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). Note that after parse, both name and value of attribute will point to interior of source text used for parsing. Thus, this text must persist in memory for the lifetime of attribute.

Parameters

Ch
Character type to use.

232 | constructor 233 | xml_attribute::xml_attribute

Synopsis

xml_attribute(); 234 |

Description

Constructs an empty attribute with the specified type. Consider using memory_pool of appropriate xml_document if allocating attributes manually.

function xml_attribute::document

Synopsis

xml_document<Ch>* document() const; 235 |

Description

Gets document of which attribute is a child.

Returns

Pointer to document that contains this attribute, or 0 if there is no parent document.

function xml_attribute::previous_attribute

Synopsis

xml_attribute<Ch>* previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 236 |

Description

Gets previous attribute, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_attribute::next_attribute

Synopsis

xml_attribute<Ch>* next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 237 |

Description

Gets next attribute, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

class 238 | template 239 | rapidxml::xml_base

240 | 241 | Defined in rapidxml.hpp
242 | Base class for 243 | xml_attribute xml_node

Description

Base class for xml_node and xml_attribute implementing common functions: name(), name_size(), value(), value_size() and parent().

Parameters

Ch
Character type to use

244 | constructor 245 | xml_base::xml_base

Synopsis

xml_base(); 246 |

function xml_base::name

Synopsis

Ch* name() const; 247 |

Description

Gets name of the node. Interpretation of name depends on type of node. Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

248 | Use name_size() function to determine length of the name.

Returns

Name of node, or empty string if node has no name.

function xml_base::name_size

Synopsis

std::size_t name_size() const; 249 |

Description

Gets size of node name, not including terminator character. This function works correctly irrespective of whether name is or is not zero terminated.

Returns

Size of node name, in characters.

function xml_base::value

Synopsis

Ch* value() const; 250 |

Description

Gets value of node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

251 | Use value_size() function to determine length of the value.

Returns

Value of node, or empty string if node has no value.

function xml_base::value_size

Synopsis

std::size_t value_size() const; 252 |

Description

Gets size of node value, not including terminator character. This function works correctly irrespective of whether value is or is not zero terminated.

Returns

Size of node value, in characters.

function xml_base::name

Synopsis

void name(const Ch *name, std::size_t size); 253 |

Description

Sets name of node to a non zero-terminated string. See Ownership Of Strings .

254 | Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

255 | Size of name must be specified separately, because name does not have to be zero terminated. Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).

Parameters

name
Name of node to set. Does not have to be zero terminated.
size
Size of name, in characters. This does not include zero terminator, if one is present.

function xml_base::name

Synopsis

void name(const Ch *name); 256 |

Description

Sets name of node to a zero-terminated string. See also Ownership Of Strings and xml_node::name(const Ch *, std::size_t).

Parameters

name
Name of node to set. Must be zero terminated.

function xml_base::value

Synopsis

void value(const Ch *value, std::size_t size); 257 |

Description

Sets value of node to a non zero-terminated string. See Ownership Of Strings .

258 | Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

259 | Size of value must be specified separately, because it does not have to be zero terminated. Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).

260 | If an element has a child node of type node_data, it will take precedence over element value when printing. If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser.

Parameters

value
value of node to set. Does not have to be zero terminated.
size
Size of value, in characters. This does not include zero terminator, if one is present.

function xml_base::value

Synopsis

void value(const Ch *value); 261 |

Description

Sets value of node to a zero-terminated string. See also Ownership Of Strings and xml_node::value(const Ch *, std::size_t).

Parameters

value
Vame of node to set. Must be zero terminated.

function xml_base::parent

Synopsis

xml_node<Ch>* parent() const; 262 |

Description

Gets node parent.

Returns

Pointer to parent node, or 0 if there is no parent.

class 263 | template 264 | rapidxml::xml_document

265 | 266 | Defined in rapidxml.hpp
267 | Inherits from 268 | xml_node memory_pool

Description

This class represents root of the DOM hierarchy. It is also an xml_node and a memory_pool through public inheritance. Use parse() function to build a DOM tree from a zero-terminated XML text string. parse() function allocates memory for nodes and attributes by using functions of xml_document, which are inherited from memory_pool. To access root node of the document, use the document itself, as if it was an xml_node.

Parameters

Ch
Character type to use.

269 | constructor 270 | xml_document::xml_document

Synopsis

xml_document(); 271 |

Description

Constructs empty XML document.

function xml_document::parse

Synopsis

void parse(Ch *text); 272 |

Description

Parses zero-terminated XML string according to given flags. Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. The string must persist for the lifetime of the document. In case of error, rapidxml::parse_error exception will be thrown.

273 | If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. Make sure that data is zero-terminated.

274 | Document can be parsed into multiple times. Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.

Parameters

text
XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.

function xml_document::clear

Synopsis

void clear(); 275 |

Description

Clears the document by deleting all nodes and clearing the memory pool. All nodes owned by document pool are destroyed.

class 276 | template 277 | rapidxml::xml_node

278 | 279 | Defined in rapidxml.hpp
280 | Inherits from 281 | xml_base
282 | Base class for 283 | xml_document

Description

Class representing a node of XML document. Each node may have associated name and value strings, which are available through name() and value() functions. Interpretation of name and value depends on type of the node. Type of node can be determined by using type() function.

284 | Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. Thus, this text must persist in the memory for the lifetime of node.

Parameters

Ch
Character type to use.

285 | constructor 286 | xml_node::xml_node

Synopsis

xml_node(node_type type); 287 |

Description

Constructs an empty node with the specified type. Consider using memory_pool of appropriate document to allocate nodes manually.

Parameters

type
Type of node to construct.

function xml_node::type

Synopsis

node_type type() const; 288 |

Description

Gets type of node.

Returns

Type of node.

function xml_node::document

Synopsis

xml_document<Ch>* document() const; 289 |

Description

Gets document of which node is a child.

Returns

Pointer to document that contains this node, or 0 if there is no parent document.

function xml_node::first_node

Synopsis

xml_node<Ch>* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 290 |

Description

Gets first child node, optionally matching node name.

Parameters

name
Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::last_node

Synopsis

xml_node<Ch>* last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 291 |

Description

Gets last child node, optionally matching node name. Behaviour is undefined if node has no children. Use first_node() to test if node has children.

Parameters

name
Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::previous_sibling

Synopsis

xml_node<Ch>* previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 292 |

Description

Gets previous sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

name
Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::next_sibling

Synopsis

xml_node<Ch>* next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 293 |

Description

Gets next sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

name
Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::first_attribute

Synopsis

xml_attribute<Ch>* first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 294 |

Description

Gets first attribute of node, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::last_attribute

Synopsis

xml_attribute<Ch>* last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; 295 |

Description

Gets last attribute of node, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::type

Synopsis

void type(node_type type); 296 |

Description

Sets type of node.

Parameters

type
Type of node to set.

function xml_node::prepend_node

Synopsis

void prepend_node(xml_node< Ch > *child); 297 |

Description

Prepends a new child node. The prepended child becomes the first child, and all existing children are moved one position back.

Parameters

child
Node to prepend.

function xml_node::append_node

Synopsis

void append_node(xml_node< Ch > *child); 298 |

Description

Appends a new child node. The appended child becomes the last child.

Parameters

child
Node to append.

function xml_node::insert_node

Synopsis

void insert_node(xml_node< Ch > *where, xml_node< Ch > *child); 299 |

Description

Inserts a new child node at specified place inside the node. All children after and including the specified node are moved one position back.

Parameters

where
Place where to insert the child, or 0 to insert at the back.
child
Node to insert.

function xml_node::remove_first_node

Synopsis

void remove_first_node(); 300 |

Description

Removes first child node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_last_node

Synopsis

void remove_last_node(); 301 |

Description

Removes last child of the node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_node

Synopsis

void remove_node(xml_node< Ch > *where); 302 |

Description

Removes specified child from the node.

function xml_node::remove_all_nodes

Synopsis

void remove_all_nodes(); 303 |

Description

Removes all child nodes (but not attributes).

function xml_node::prepend_attribute

Synopsis

void prepend_attribute(xml_attribute< Ch > *attribute); 304 |

Description

Prepends a new attribute to the node.

Parameters

attribute
Attribute to prepend.

function xml_node::append_attribute

Synopsis

void append_attribute(xml_attribute< Ch > *attribute); 305 |

Description

Appends a new attribute to the node.

Parameters

attribute
Attribute to append.

function xml_node::insert_attribute

Synopsis

void insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute); 306 |

Description

Inserts a new attribute at specified place inside the node. All attributes after and including the specified attribute are moved one position back.

Parameters

where
Place where to insert the attribute, or 0 to insert at the back.
attribute
Attribute to insert.

function xml_node::remove_first_attribute

Synopsis

void remove_first_attribute(); 307 |

Description

Removes first attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_last_attribute

Synopsis

void remove_last_attribute(); 308 |

Description

Removes last attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_attribute

Synopsis

void remove_attribute(xml_attribute< Ch > *where); 309 |

Description

Removes specified attribute from node.

Parameters

where
Pointer to attribute to be removed.

function xml_node::remove_all_attributes

Synopsis

void remove_all_attributes(); 310 |

Description

Removes all attributes of node.

enum node_type

Description

Enumeration listing all node types produced by the parser. Use xml_node::type() function to query node type.

Values

node_document
A document node. Name and value are empty.
node_element
An element node. Name contains element name. Value contains text of first data node.
node_data
A data node. Name is empty. Value contains data text.
node_cdata
A CDATA node. Name is empty. Value contains data text.
node_comment
A comment node. Name is empty. Value contains comment text.
node_declaration
A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
node_doctype
A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
node_pi
A PI node. Name contains target. Value contains instructions.

function parse_error_handler

Synopsis

void rapidxml::parse_error_handler(const char *what, void *where); 311 |

Description

When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function is called to notify user about the error. It must be defined by the user.

312 | This function cannot return. If it does, the results are undefined.

313 | A very simple definition might look like that: 314 | void rapidxml::parse_error_handler(const char *what, void *where) 315 | { 316 | std::cout << "Parse error: " << what << "\n"; 317 | std::abort(); 318 | } 319 |

Parameters

what
Human readable description of the error.
where
Pointer to character data where error was detected.

function print

Synopsis

OutIt rapidxml::print(OutIt out, const xml_node< Ch > &node, int flags=0); 320 |

Description

Prints XML to given output iterator.

Parameters

out
Output iterator to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output iterator pointing to position immediately after last character of printed text.

function print

Synopsis

std::basic_ostream<Ch>& rapidxml::print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0); 321 |

Description

Prints XML to given output stream.

Parameters

out
Output stream to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output stream.

function operator<<

Synopsis

std::basic_ostream<Ch>& rapidxml::operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node); 322 |

Description

Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.

Parameters

out
Output stream to print to.
node
Node to be printed.

Returns

Output stream.

323 | constant 324 | parse_no_data_nodes

Synopsis

const int parse_no_data_nodes 325 | = 0x1; 326 |

Description

Parse flag instructing the parser to not create data nodes. Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. Can be combined with other flags by use of | operator.

327 | See xml_document::parse() function.

328 | constant 329 | parse_no_element_values

Synopsis

const int parse_no_element_values 330 | = 0x2; 331 |

Description

Parse flag instructing the parser to not use text of first data node as a value of parent element. Can be combined with other flags by use of | operator. Note that child data nodes of element node take precendence over its value when printing. That is, if element has one or more child data nodes and a value, the value will be ignored. Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.

332 | See xml_document::parse() function.

333 | constant 334 | parse_no_string_terminators

Synopsis

const int parse_no_string_terminators 335 | = 0x4; 336 |

Description

Parse flag instructing the parser to not place zero terminators after strings in the source text. By default zero terminators are placed, modifying source text. Can be combined with other flags by use of | operator.

337 | See xml_document::parse() function.

338 | constant 339 | parse_no_entity_translation

Synopsis

const int parse_no_entity_translation 340 | = 0x8; 341 |

Description

Parse flag instructing the parser to not translate entities in the source text. By default entities are translated, modifying source text. Can be combined with other flags by use of | operator.

342 | See xml_document::parse() function.

343 | constant 344 | parse_no_utf8

Synopsis

const int parse_no_utf8 345 | = 0x10; 346 |

Description

Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. By default, UTF-8 handling is enabled. Can be combined with other flags by use of | operator.

347 | See xml_document::parse() function.

348 | constant 349 | parse_declaration_node

Synopsis

const int parse_declaration_node 350 | = 0x20; 351 |

Description

Parse flag instructing the parser to create XML declaration node. By default, declaration node is not created. Can be combined with other flags by use of | operator.

352 | See xml_document::parse() function.

353 | constant 354 | parse_comment_nodes

Synopsis

const int parse_comment_nodes 355 | = 0x40; 356 |

Description

Parse flag instructing the parser to create comments nodes. By default, comment nodes are not created. Can be combined with other flags by use of | operator.

357 | See xml_document::parse() function.

358 | constant 359 | parse_doctype_node

Synopsis

const int parse_doctype_node 360 | = 0x80; 361 |

Description

Parse flag instructing the parser to create DOCTYPE node. By default, doctype node is not created. Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. Can be combined with other flags by use of | operator.

362 | See xml_document::parse() function.

363 | constant 364 | parse_pi_nodes

Synopsis

const int parse_pi_nodes 365 | = 0x100; 366 |

Description

Parse flag instructing the parser to create PI nodes. By default, PI nodes are not created. Can be combined with other flags by use of | operator.

367 | See xml_document::parse() function.

368 | constant 369 | parse_validate_closing_tags

Synopsis

const int parse_validate_closing_tags 370 | = 0x200; 371 |

Description

Parse flag instructing the parser to validate closing tag names. If not set, name inside closing tag is irrelevant to the parser. By default, closing tags are not validated. Can be combined with other flags by use of | operator.

372 | See xml_document::parse() function.

373 | constant 374 | parse_trim_whitespace

Synopsis

const int parse_trim_whitespace 375 | = 0x400; 376 |

Description

Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. By default, whitespace is not trimmed. This flag does not cause the parser to modify source text. Can be combined with other flags by use of | operator.

377 | See xml_document::parse() function.

378 | constant 379 | parse_normalize_whitespace

Synopsis

const int parse_normalize_whitespace 380 | = 0x800; 381 |

Description

Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. By default, whitespace is not normalized. If this flag is specified, source text will be modified. Can be combined with other flags by use of | operator.

382 | See xml_document::parse() function.

383 | constant 384 | parse_default

Synopsis

const int parse_default 385 | = 0; 386 |

Description

Parse flags which represent default behaviour of the parser. This is always equal to 0, so that all other flags can be simply ored together. Normally there is no need to inconveniently disable flags by anding with their negated (~) values. This also means that meaning of each flag is a negation of the default setting. For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is enabled by default, and using the flag will disable it.

387 | See xml_document::parse() function.

388 | constant 389 | parse_non_destructive

Synopsis

const int parse_non_destructive 390 | = parse_no_string_terminators | parse_no_entity_translation; 391 |

Description

A combination of parse flags that forbids any modifications of the source text. This also results in faster parsing. However, note that the following will occur:
  • names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends
  • entities will not be translated
  • whitespace will not be normalized
392 | See xml_document::parse() function.

393 | constant 394 | parse_fastest

Synopsis

const int parse_fastest 395 | = parse_non_destructive | parse_no_data_nodes; 396 |

Description

A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.

397 | See xml_document::parse() function.

398 | constant 399 | parse_full

Synopsis

const int parse_full 400 | = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; 401 |

Description

A combination of parse flags resulting in largest amount of data being extracted. This usually results in slowest parsing.

402 | See xml_document::parse() function.

403 | constant 404 | print_no_indenting

Synopsis

const int print_no_indenting 405 | = 0x1; 406 |

Description

Printer flag instructing the printer to suppress indenting of XML. See print() function.

-------------------------------------------------------------------------------- /src/vendor/rapidxml_iterators.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_ITERATORS_HPP_INCLUDED 2 | #define RAPIDXML_ITERATORS_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_iterators.hpp This file contains rapidxml iterators 8 | 9 | #include "rapidxml.hpp" 10 | 11 | namespace rapidxml 12 | { 13 | 14 | //! Iterator of child nodes of xml_node 15 | template 16 | class node_iterator 17 | { 18 | 19 | public: 20 | 21 | typedef typename xml_node value_type; 22 | typedef typename xml_node &reference; 23 | typedef typename xml_node *pointer; 24 | typedef std::ptrdiff_t difference_type; 25 | typedef std::bidirectional_iterator_tag iterator_category; 26 | 27 | node_iterator() 28 | : m_node(0) 29 | { 30 | } 31 | 32 | node_iterator(xml_node *node) 33 | : m_node(node->first_node()) 34 | { 35 | } 36 | 37 | reference operator *() const 38 | { 39 | assert(m_node); 40 | return *m_node; 41 | } 42 | 43 | pointer operator->() const 44 | { 45 | assert(m_node); 46 | return m_node; 47 | } 48 | 49 | node_iterator& operator++() 50 | { 51 | assert(m_node); 52 | m_node = m_node->next_sibling(); 53 | return *this; 54 | } 55 | 56 | node_iterator operator++(int) 57 | { 58 | node_iterator tmp = *this; 59 | ++this; 60 | return tmp; 61 | } 62 | 63 | node_iterator& operator--() 64 | { 65 | assert(m_node && m_node->previous_sibling()); 66 | m_node = m_node->previous_sibling(); 67 | return *this; 68 | } 69 | 70 | node_iterator operator--(int) 71 | { 72 | node_iterator tmp = *this; 73 | ++this; 74 | return tmp; 75 | } 76 | 77 | bool operator ==(const node_iterator &rhs) 78 | { 79 | return m_node == rhs.m_node; 80 | } 81 | 82 | bool operator !=(const node_iterator &rhs) 83 | { 84 | return m_node != rhs.m_node; 85 | } 86 | 87 | private: 88 | 89 | xml_node *m_node; 90 | 91 | }; 92 | 93 | //! Iterator of child attributes of xml_node 94 | template 95 | class attribute_iterator 96 | { 97 | 98 | public: 99 | 100 | typedef typename xml_attribute value_type; 101 | typedef typename xml_attribute &reference; 102 | typedef typename xml_attribute *pointer; 103 | typedef std::ptrdiff_t difference_type; 104 | typedef std::bidirectional_iterator_tag iterator_category; 105 | 106 | attribute_iterator() 107 | : m_attribute(0) 108 | { 109 | } 110 | 111 | attribute_iterator(xml_node *node) 112 | : m_attribute(node->first_attribute()) 113 | { 114 | } 115 | 116 | reference operator *() const 117 | { 118 | assert(m_attribute); 119 | return *m_attribute; 120 | } 121 | 122 | pointer operator->() const 123 | { 124 | assert(m_attribute); 125 | return m_attribute; 126 | } 127 | 128 | attribute_iterator& operator++() 129 | { 130 | assert(m_attribute); 131 | m_attribute = m_attribute->next_attribute(); 132 | return *this; 133 | } 134 | 135 | attribute_iterator operator++(int) 136 | { 137 | attribute_iterator tmp = *this; 138 | ++this; 139 | return tmp; 140 | } 141 | 142 | attribute_iterator& operator--() 143 | { 144 | assert(m_attribute && m_attribute->previous_attribute()); 145 | m_attribute = m_attribute->previous_attribute(); 146 | return *this; 147 | } 148 | 149 | attribute_iterator operator--(int) 150 | { 151 | attribute_iterator tmp = *this; 152 | ++this; 153 | return tmp; 154 | } 155 | 156 | bool operator ==(const attribute_iterator &rhs) 157 | { 158 | return m_attribute == rhs.m_attribute; 159 | } 160 | 161 | bool operator !=(const attribute_iterator &rhs) 162 | { 163 | return m_attribute != rhs.m_attribute; 164 | } 165 | 166 | private: 167 | 168 | xml_attribute *m_attribute; 169 | 170 | }; 171 | 172 | } 173 | 174 | #endif 175 | -------------------------------------------------------------------------------- /src/vendor/rapidxml_print.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_PRINT_HPP_INCLUDED 2 | #define RAPIDXML_PRINT_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_print.hpp This file contains rapidxml printer implementation 8 | 9 | #include "rapidxml.hpp" 10 | 11 | // Only include streams if not disabled 12 | #ifndef RAPIDXML_NO_STREAMS 13 | #include 14 | #include 15 | #endif 16 | 17 | namespace rapidxml 18 | { 19 | 20 | /////////////////////////////////////////////////////////////////////// 21 | // Printing flags 22 | 23 | const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function. 24 | 25 | /////////////////////////////////////////////////////////////////////// 26 | // Internal 27 | 28 | //! \cond internal 29 | namespace internal 30 | { 31 | 32 | /////////////////////////////////////////////////////////////////////////// 33 | // Internal character operations 34 | 35 | // Copy characters from given range to given output iterator 36 | template 37 | inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) 38 | { 39 | while (begin != end) 40 | *out++ = *begin++; 41 | return out; 42 | } 43 | 44 | // Copy characters from given range to given output iterator and expand 45 | // characters into references (< > ' " &) 46 | template 47 | inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) 48 | { 49 | while (begin != end) 50 | { 51 | if (*begin == noexpand) 52 | { 53 | *out++ = *begin; // No expansion, copy character 54 | } 55 | else 56 | { 57 | switch (*begin) 58 | { 59 | case Ch('<'): 60 | *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';'); 61 | break; 62 | case Ch('>'): 63 | *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';'); 64 | break; 65 | case Ch('\''): 66 | *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';'); 67 | break; 68 | case Ch('"'): 69 | *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';'); 70 | break; 71 | case Ch('&'): 72 | *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); 73 | break; 74 | default: 75 | *out++ = *begin; // No expansion, copy character 76 | } 77 | } 78 | ++begin; // Step to next character 79 | } 80 | return out; 81 | } 82 | 83 | // Fill given output iterator with repetitions of the same character 84 | template 85 | inline OutIt fill_chars(OutIt out, int n, Ch ch) 86 | { 87 | for (int i = 0; i < n; ++i) 88 | *out++ = ch; 89 | return out; 90 | } 91 | 92 | // Find character 93 | template 94 | inline bool find_char(const Ch *begin, const Ch *end) 95 | { 96 | while (begin != end) 97 | if (*begin++ == ch) 98 | return true; 99 | return false; 100 | } 101 | 102 | /////////////////////////////////////////////////////////////////////////// 103 | // Internal printing operations 104 | 105 | // Print node 106 | template 107 | inline OutIt print_node(OutIt out, const xml_node *node, int flags, int indent) 108 | { 109 | // Print proper node type 110 | switch (node->type()) 111 | { 112 | 113 | // Document 114 | case node_document: 115 | out = print_children(out, node, flags, indent); 116 | break; 117 | 118 | // Element 119 | case node_element: 120 | out = print_element_node(out, node, flags, indent); 121 | break; 122 | 123 | // Data 124 | case node_data: 125 | out = print_data_node(out, node, flags, indent); 126 | break; 127 | 128 | // CDATA 129 | case node_cdata: 130 | out = print_cdata_node(out, node, flags, indent); 131 | break; 132 | 133 | // Declaration 134 | case node_declaration: 135 | out = print_declaration_node(out, node, flags, indent); 136 | break; 137 | 138 | // Comment 139 | case node_comment: 140 | out = print_comment_node(out, node, flags, indent); 141 | break; 142 | 143 | // Doctype 144 | case node_doctype: 145 | out = print_doctype_node(out, node, flags, indent); 146 | break; 147 | 148 | // Pi 149 | case node_pi: 150 | out = print_pi_node(out, node, flags, indent); 151 | break; 152 | 153 | // Unknown 154 | default: 155 | assert(0); 156 | break; 157 | } 158 | 159 | // If indenting not disabled, add line break after node 160 | if (!(flags & print_no_indenting)) 161 | *out = Ch('\n'), ++out; 162 | 163 | // Return modified iterator 164 | return out; 165 | } 166 | 167 | // Print children of the node 168 | template 169 | inline OutIt print_children(OutIt out, const xml_node *node, int flags, int indent) 170 | { 171 | for (xml_node *child = node->first_node(); child; child = child->next_sibling()) 172 | out = print_node(out, child, flags, indent); 173 | return out; 174 | } 175 | 176 | // Print attributes of the node 177 | template 178 | inline OutIt print_attributes(OutIt out, const xml_node *node, int flags) 179 | { 180 | for (xml_attribute *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute()) 181 | { 182 | if (attribute->name() && attribute->value()) 183 | { 184 | // Print attribute name 185 | *out = Ch(' '), ++out; 186 | out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out); 187 | *out = Ch('='), ++out; 188 | // Print attribute value using appropriate quote type 189 | if (find_char(attribute->value(), attribute->value() + attribute->value_size())) 190 | { 191 | *out = Ch('\''), ++out; 192 | out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out); 193 | *out = Ch('\''), ++out; 194 | } 195 | else 196 | { 197 | *out = Ch('"'), ++out; 198 | out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out); 199 | *out = Ch('"'), ++out; 200 | } 201 | } 202 | } 203 | return out; 204 | } 205 | 206 | // Print data node 207 | template 208 | inline OutIt print_data_node(OutIt out, const xml_node *node, int flags, int indent) 209 | { 210 | assert(node->type() == node_data); 211 | if (!(flags & print_no_indenting)) 212 | out = fill_chars(out, indent, Ch('\t')); 213 | out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); 214 | return out; 215 | } 216 | 217 | // Print data node 218 | template 219 | inline OutIt print_cdata_node(OutIt out, const xml_node *node, int flags, int indent) 220 | { 221 | assert(node->type() == node_cdata); 222 | if (!(flags & print_no_indenting)) 223 | out = fill_chars(out, indent, Ch('\t')); 224 | *out = Ch('<'); ++out; 225 | *out = Ch('!'); ++out; 226 | *out = Ch('['); ++out; 227 | *out = Ch('C'); ++out; 228 | *out = Ch('D'); ++out; 229 | *out = Ch('A'); ++out; 230 | *out = Ch('T'); ++out; 231 | *out = Ch('A'); ++out; 232 | *out = Ch('['); ++out; 233 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 234 | *out = Ch(']'); ++out; 235 | *out = Ch(']'); ++out; 236 | *out = Ch('>'); ++out; 237 | return out; 238 | } 239 | 240 | // Print element node 241 | template 242 | inline OutIt print_element_node(OutIt out, const xml_node *node, int flags, int indent) 243 | { 244 | assert(node->type() == node_element); 245 | 246 | // Print element name and attributes, if any 247 | if (!(flags & print_no_indenting)) 248 | out = fill_chars(out, indent, Ch('\t')); 249 | *out = Ch('<'), ++out; 250 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 251 | out = print_attributes(out, node, flags); 252 | 253 | // If node is childless 254 | if (node->value_size() == 0 && !node->first_node()) 255 | { 256 | // Print childless node tag ending 257 | *out = Ch('/'), ++out; 258 | *out = Ch('>'), ++out; 259 | } 260 | else 261 | { 262 | // Print normal node tag ending 263 | *out = Ch('>'), ++out; 264 | 265 | // Test if node contains a single data node only (and no other nodes) 266 | xml_node *child = node->first_node(); 267 | if (!child) 268 | { 269 | // If node has no children, only print its value without indenting 270 | out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); 271 | } 272 | else if (child->next_sibling() == 0 && child->type() == node_data) 273 | { 274 | // If node has a sole data child, only print its value without indenting 275 | out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out); 276 | } 277 | else 278 | { 279 | // Print all children with full indenting 280 | if (!(flags & print_no_indenting)) 281 | *out = Ch('\n'), ++out; 282 | out = print_children(out, node, flags, indent + 1); 283 | if (!(flags & print_no_indenting)) 284 | out = fill_chars(out, indent, Ch('\t')); 285 | } 286 | 287 | // Print node end 288 | *out = Ch('<'), ++out; 289 | *out = Ch('/'), ++out; 290 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 291 | *out = Ch('>'), ++out; 292 | } 293 | return out; 294 | } 295 | 296 | // Print declaration node 297 | template 298 | inline OutIt print_declaration_node(OutIt out, const xml_node *node, int flags, int indent) 299 | { 300 | // Print declaration start 301 | if (!(flags & print_no_indenting)) 302 | out = fill_chars(out, indent, Ch('\t')); 303 | *out = Ch('<'), ++out; 304 | *out = Ch('?'), ++out; 305 | *out = Ch('x'), ++out; 306 | *out = Ch('m'), ++out; 307 | *out = Ch('l'), ++out; 308 | 309 | // Print attributes 310 | out = print_attributes(out, node, flags); 311 | 312 | // Print declaration end 313 | *out = Ch('?'), ++out; 314 | *out = Ch('>'), ++out; 315 | 316 | return out; 317 | } 318 | 319 | // Print comment node 320 | template 321 | inline OutIt print_comment_node(OutIt out, const xml_node *node, int flags, int indent) 322 | { 323 | assert(node->type() == node_comment); 324 | if (!(flags & print_no_indenting)) 325 | out = fill_chars(out, indent, Ch('\t')); 326 | *out = Ch('<'), ++out; 327 | *out = Ch('!'), ++out; 328 | *out = Ch('-'), ++out; 329 | *out = Ch('-'), ++out; 330 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 331 | *out = Ch('-'), ++out; 332 | *out = Ch('-'), ++out; 333 | *out = Ch('>'), ++out; 334 | return out; 335 | } 336 | 337 | // Print doctype node 338 | template 339 | inline OutIt print_doctype_node(OutIt out, const xml_node *node, int flags, int indent) 340 | { 341 | assert(node->type() == node_doctype); 342 | if (!(flags & print_no_indenting)) 343 | out = fill_chars(out, indent, Ch('\t')); 344 | *out = Ch('<'), ++out; 345 | *out = Ch('!'), ++out; 346 | *out = Ch('D'), ++out; 347 | *out = Ch('O'), ++out; 348 | *out = Ch('C'), ++out; 349 | *out = Ch('T'), ++out; 350 | *out = Ch('Y'), ++out; 351 | *out = Ch('P'), ++out; 352 | *out = Ch('E'), ++out; 353 | *out = Ch(' '), ++out; 354 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 355 | *out = Ch('>'), ++out; 356 | return out; 357 | } 358 | 359 | // Print pi node 360 | template 361 | inline OutIt print_pi_node(OutIt out, const xml_node *node, int flags, int indent) 362 | { 363 | assert(node->type() == node_pi); 364 | if (!(flags & print_no_indenting)) 365 | out = fill_chars(out, indent, Ch('\t')); 366 | *out = Ch('<'), ++out; 367 | *out = Ch('?'), ++out; 368 | out = copy_chars(node->name(), node->name() + node->name_size(), out); 369 | *out = Ch(' '), ++out; 370 | out = copy_chars(node->value(), node->value() + node->value_size(), out); 371 | *out = Ch('?'), ++out; 372 | *out = Ch('>'), ++out; 373 | return out; 374 | } 375 | 376 | } 377 | //! \endcond 378 | 379 | /////////////////////////////////////////////////////////////////////////// 380 | // Printing 381 | 382 | //! Prints XML to given output iterator. 383 | //! \param out Output iterator to print to. 384 | //! \param node Node to be printed. Pass xml_document to print entire document. 385 | //! \param flags Flags controlling how XML is printed. 386 | //! \return Output iterator pointing to position immediately after last character of printed text. 387 | template 388 | inline OutIt print(OutIt out, const xml_node &node, int flags = 0) 389 | { 390 | return internal::print_node(out, &node, flags, 0); 391 | } 392 | 393 | #ifndef RAPIDXML_NO_STREAMS 394 | 395 | //! Prints XML to given output stream. 396 | //! \param out Output stream to print to. 397 | //! \param node Node to be printed. Pass xml_document to print entire document. 398 | //! \param flags Flags controlling how XML is printed. 399 | //! \return Output stream. 400 | template 401 | inline std::basic_ostream &print(std::basic_ostream &out, const xml_node &node, int flags = 0) 402 | { 403 | print(std::ostream_iterator(out), node, flags); 404 | return out; 405 | } 406 | 407 | //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process. 408 | //! \param out Output stream to print to. 409 | //! \param node Node to be printed. 410 | //! \return Output stream. 411 | template 412 | inline std::basic_ostream &operator <<(std::basic_ostream &out, const xml_node &node) 413 | { 414 | return print(out, node); 415 | } 416 | 417 | #endif 418 | 419 | } 420 | 421 | #endif 422 | -------------------------------------------------------------------------------- /src/vendor/rapidxml_utils.hpp: -------------------------------------------------------------------------------- 1 | #ifndef RAPIDXML_UTILS_HPP_INCLUDED 2 | #define RAPIDXML_UTILS_HPP_INCLUDED 3 | 4 | // Copyright (C) 2006, 2009 Marcin Kalicinski 5 | // Version 1.13 6 | // Revision $DateTime: 2009/05/13 01:46:17 $ 7 | //! \file rapidxml_utils.hpp This file contains high-level rapidxml utilities that can be useful 8 | //! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. 9 | 10 | #include "rapidxml.hpp" 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | namespace rapidxml 17 | { 18 | 19 | //! Represents data loaded from a file 20 | template 21 | class file 22 | { 23 | 24 | public: 25 | 26 | //! Loads file into the memory. Data will be automatically destroyed by the destructor. 27 | //! \param filename Filename to load. 28 | file(const char *filename) 29 | { 30 | using namespace std; 31 | 32 | // Open stream 33 | basic_ifstream stream(filename, ios::binary); 34 | if (!stream) 35 | throw runtime_error(string("cannot open file ") + filename); 36 | stream.unsetf(ios::skipws); 37 | 38 | // Determine stream size 39 | stream.seekg(0, ios::end); 40 | size_t size = stream.tellg(); 41 | stream.seekg(0); 42 | 43 | // Load data and add terminating 0 44 | m_data.resize(size + 1); 45 | stream.read(&m_data.front(), static_cast(size)); 46 | m_data[size] = 0; 47 | } 48 | 49 | //! Loads file into the memory. Data will be automatically destroyed by the destructor 50 | //! \param stream Stream to load from 51 | file(std::basic_istream &stream) 52 | { 53 | using namespace std; 54 | 55 | // Load data and add terminating 0 56 | stream.unsetf(ios::skipws); 57 | m_data.assign(istreambuf_iterator(stream), istreambuf_iterator()); 58 | if (stream.fail() || stream.bad()) 59 | throw runtime_error("error reading stream"); 60 | m_data.push_back(0); 61 | } 62 | 63 | //! Gets file data. 64 | //! \return Pointer to data of file. 65 | Ch *data() 66 | { 67 | return &m_data.front(); 68 | } 69 | 70 | //! Gets file data. 71 | //! \return Pointer to data of file. 72 | const Ch *data() const 73 | { 74 | return &m_data.front(); 75 | } 76 | 77 | //! Gets file data size. 78 | //! \return Size of file data, in characters. 79 | std::size_t size() const 80 | { 81 | return m_data.size(); 82 | } 83 | 84 | private: 85 | 86 | std::vector m_data; // File data 87 | 88 | }; 89 | 90 | //! Counts children of node. Time complexity is O(n). 91 | //! \return Number of children of node 92 | template 93 | inline std::size_t count_children(xml_node *node) 94 | { 95 | xml_node *child = node->first_node(); 96 | std::size_t count = 0; 97 | while (child) 98 | { 99 | ++count; 100 | child = child->next_sibling(); 101 | } 102 | return count; 103 | } 104 | 105 | //! Counts attributes of node. Time complexity is O(n). 106 | //! \return Number of attributes of node 107 | template 108 | inline std::size_t count_attributes(xml_node *node) 109 | { 110 | xml_attribute *attr = node->first_attribute(); 111 | std::size_t count = 0; 112 | while (attr) 113 | { 114 | ++count; 115 | attr = attr->next_attribute(); 116 | } 117 | return count; 118 | } 119 | 120 | } 121 | 122 | #endif 123 | -------------------------------------------------------------------------------- /test/Parser_test.lua: -------------------------------------------------------------------------------- 1 | --[[------------------------------------------------------ 2 | 3 | xml.Parser test 4 | -------- 5 | 6 | ... 7 | 8 | --]]------------------------------------------------------ 9 | package.path = './?.lua;'..package.path 10 | package.cpath = './?.so;' ..package.cpath 11 | 12 | local lub = require 'lub' 13 | local lut = require 'lut' 14 | local xml = require 'xml' 15 | local should = lut.Test('xml.Parser') 16 | 17 | should.ignore.deleted = true 18 | 19 | local TEST_XML = [[ 20 | 21 | 22 | This is a 23 | This is Bob 24 | 25 | 26 |

Dear Pedro, how are you ?

27 | ]] 28 | 29 | local TEST_RES = {xml = 'document', 30 | {xml = 'nodes', 31 | {xml = 'a', 'This is a'}, 32 | {xml = 'b', rock = 'Rock\'n Roll', 'This is Bob'}, 33 | {xml = 'c'}, 34 | }, 35 | {xml = 'p', 36 | 'Dear ', 37 | {xml = 'b', 'Pedro'}, 38 | ', how are you ?', 39 | }, 40 | } 41 | 42 | function should.autoLoad() 43 | assertType('table', xml.Parser) 44 | end 45 | 46 | function should.createNew() 47 | local p = xml.Parser(xml.Parser.TrimWhitespace) 48 | assertEqual('xml.Parser', p.type) 49 | end 50 | 51 | function should.renderToString() 52 | local p = xml.Parser(xml.Parser.TrimWhitespace) 53 | assertMatch('xml.Parser: 0x', tostring(p)) 54 | end 55 | 56 | function should.loadpath() 57 | local p = xml.Parser() 58 | local data = p:loadpath(lub.path('|fixtures/foo.xml')) 59 | assertValueEqual(TEST_RES, data) 60 | end 61 | 62 | function should.load() 63 | local p = xml.Parser() 64 | assertValueEqual(TEST_RES, p:load(TEST_XML)) 65 | end 66 | 67 | function should.containConst() 68 | assertEqual(0, xml.Parser.Default) 69 | assertEqual(1, xml.Parser.TrimWhitespace) 70 | assertEqual(2, xml.Parser.NonDestructive) 71 | assertEqual(3, xml.Parser.Fastest) 72 | end 73 | 74 | 75 | should:test() 76 | 77 | -------------------------------------------------------------------------------- /test/all.lua: -------------------------------------------------------------------------------- 1 | local lub = require 'lub' 2 | local lut = require 'lut' 3 | 4 | lut.Test.files(lub.path '|') 5 | 6 | -------------------------------------------------------------------------------- /test/fixtures/doxy.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | xml::Parser 5 | Parser.h 6 | 7 | 8 | Type 9 | 10 | Default 11 | 12 | 13 | 14 | 15 | 16 | 17 | NonDestructive 18 | 19 | 20 | 21 | 22 | 23 | 24 | Fastest 25 | 26 | 27 | 28 | 29 | 30 | 31 | Full 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | Type 49 | Type xml::Parser::type_ 50 | 51 | type_ 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | Implementation * 62 | Implementation* xml::Parser::impl_ 63 | 64 | impl_ 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | xml::Parser::Parser 78 | (Type type=Default) 79 | Parser 80 | 81 | Type 82 | type 83 | Default 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | xml::Parser::~Parser 96 | () 97 | ~Parser 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | LuaStackSize 108 | LuaStackSize xml::Parser::parse 109 | (lua_State *L) 110 | parse 111 | 112 | lua_State * 113 | L 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | LuaStackSize 125 | LuaStackSize xml::Parser::dump 126 | (lua_State *L) 127 | dump 128 | 129 | lua_State * 130 | L 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | Simple xml parser (singleton). 145 | 146 | 147 | xml::ParserDefault 148 | xml::Parserdump 149 | xml::ParserFastest 150 | xml::ParserFull 151 | xml::Parserimpl_ 152 | xml::ParserNonDestructive 153 | xml::Parserparse 154 | xml::ParserParser 155 | xml::ParserType 156 | xml::Parsertype_ 157 | xml::Parser~Parser 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /test/fixtures/foo.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | This is a 6 | This is Bob 7 | 8 | 9 |

Dear Pedro, how are you ?

10 |
11 | -------------------------------------------------------------------------------- /test/xml_test.lua: -------------------------------------------------------------------------------- 1 | --[[------------------------------------------------------ 2 | 3 | xml test 4 | -------- 5 | 6 | ... 7 | 8 | --]]------------------------------------------------------ 9 | package.path = './?.lua;'..package.path 10 | package.cpath = './?.so;' ..package.cpath 11 | 12 | local lub = require 'lub' 13 | local lut = require 'lut' 14 | local xml = require 'xml' 15 | local should = lut.Test('xml') 16 | 17 | local TEST_XML = [[ 18 | 19 | 20 | This is a 21 | This is Bob 22 | 23 | 24 |

Dear Pedro, how are you ?

25 |
]] 26 | 27 | local TEST_RES = {xml = 'document', 28 | {xml = 'nodes', 29 | {xml = 'a', 'This is a'}, 30 | {xml = 'b', rock = 'Rock\'n Roll', 'This is Bob'}, 31 | {xml = 'c'}, 32 | }, 33 | {xml = 'p', 34 | 'Dear ', 35 | {xml = 'b', 'Pedro'}, 36 | ', how are you ?', 37 | }, 38 | } 39 | 40 | function should.autoLoad() 41 | assertType('table', xml) 42 | end 43 | 44 | function should.decodeXml() 45 | local data = xml.load(TEST_XML) 46 | assertValueEqual(TEST_RES, data) 47 | 48 | assertEqual('document', data.xml) 49 | local b = xml.find(data,'b') 50 | assertEqual('b', b.xml) 51 | assertEqual("Rock'n Roll", b.rock) 52 | assertEqual('This is Bob', b[1]) 53 | end 54 | 55 | function should.removeNamespace() 56 | local data = xml.load [[ 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | ]] 67 | assertTrue(data) 68 | xml.removeNamespace(data, 'DAV:') 69 | assertEqual('propfind', data.xml) 70 | local prop = xml.find(data, 'prop') 71 | assertEqual('prop', prop.xml) 72 | assertEqual('getlastmodified', prop[1].xml) 73 | end 74 | 75 | function should.dump() 76 | local data = xml.dump(TEST_RES) 77 | assertEqual(TEST_XML, data) 78 | end 79 | 80 | function should.load() 81 | local data = xml.loadpath(lub.path('|fixtures/foo.xml')) 82 | assertValueEqual(TEST_RES, data) 83 | end 84 | 85 | function should.raiseErrorOnRecursion() 86 | local data = {xml='one', 'hello'} 87 | data[2] = data 88 | assertError('Could not dump table to XML. Maximal depth of 3000 reached.', function() 89 | xml.dump(data) 90 | end) 91 | end 92 | 93 | function should.find() 94 | local data = {xml = 'document', 95 | 'blah blah', 96 | {xml = 'article', 97 | {xml = 'p', 'Blah blah', 98 | {xml = 'b', 'Bob'}, 99 | }, 100 | {xml = 'p', 'Hop hop'}, 101 | }, 102 | {xml = 'b', 'Top'}, 103 | } 104 | local r = xml.find(data, 'b') 105 | assertEqual('Top', r[1]) 106 | end 107 | 108 | function should.parserLarge() 109 | local data = xml.loadpath(lub.path '|fixtures/large.xml') 110 | local t = {} 111 | lub.search(data, function(node) 112 | if node.xml == 'MedlineCitation' and node.Status == 'In-Process' then 113 | table.insert(t, xml.find(node, 'PMID')[1]) 114 | end 115 | end) 116 | assertValueEqual({ 117 | '11056631', 118 | '18941263', 119 | }, t) 120 | end 121 | 122 | should:test() 123 | -------------------------------------------------------------------------------- /xml-1.1.3-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "xml" 2 | version = "1.1.3-1" 3 | source = { 4 | url = 'git://github.com/lubyk/xml', 5 | tag = 'REL-1.1.3', 6 | dir = 'xml', 7 | } 8 | description = { 9 | summary = "Very fast xml parser based on RapidXML", 10 | detailed = [[ 11 | This module is part of the Lubyk project. 12 | 13 | Main features are: 14 | - Fast and easy to use 15 | - Complete documentation 16 | - Based on proven code (RapidXML) 17 | - Full test coverage 18 | 19 | Read the documentation at http://doc.lubyk.org/xml.html. 20 | ]], 21 | homepage = "http://doc.lubyk.org/xml.html", 22 | license = "MIT" 23 | } 24 | 25 | dependencies = { 26 | "lua >= 5.1, < 5.4", 27 | "lub >= 1.0.3, < 2", 28 | } 29 | build = { 30 | type = 'builtin', 31 | modules = { 32 | -- Plain Lua files 33 | ['xml' ] = 'xml/init.lua', 34 | ['xml.Parser' ] = 'xml/Parser.lua', 35 | -- C module 36 | ['xml.core' ] = { 37 | sources = { 38 | 'src/Parser.cpp', 39 | 'src/bind/dub/dub.cpp', 40 | 'src/bind/xml_Parser.cpp', 41 | 'src/bind/xml_core.cpp', 42 | }, 43 | incdirs = {'include', 'src/bind', 'src/vendor'}, 44 | }, 45 | }, 46 | platforms = { 47 | freebsd = { 48 | modules = { 49 | ['xml.core'] = { 50 | sources = { 51 | }, 52 | libraries = {'c++'}, 53 | }, 54 | }, 55 | }, 56 | linux = { 57 | modules = { 58 | ['xml.core'] = { 59 | sources = { 60 | }, 61 | libraries = {'stdc++'}, 62 | }, 63 | }, 64 | }, 65 | macosx = { 66 | modules = { 67 | ['xml.core'] = { 68 | sources = { 69 | }, 70 | libraries = {'stdc++'}, 71 | }, 72 | }, 73 | }, 74 | }, 75 | } 76 | 77 | -------------------------------------------------------------------------------- /xml.lua: -------------------------------------------------------------------------------- 1 | xml/init.lua -------------------------------------------------------------------------------- /xml/Parser.lua: -------------------------------------------------------------------------------- 1 | --[[------------------------------------------------------ 2 | # Parser object 3 | 4 | The parser class is used to encapsulate parsing and settings in an object. When 5 | using default settings, it is not necessary to create parser objects and 6 | one can simply use [xml.load](xml.html#load). 7 | 8 | --]]------------------------------------------------------ 9 | local core = require 'xml.core' 10 | local lub = require 'lub' 11 | local lib = core.Parser 12 | 13 | -- ## Parser types 14 | -- The following constants can be used with #new when creating a parser. 15 | -- Depending on the type, the parser behavior is different. The default type is 16 | -- Default. 17 | 18 | -- Default parser type. Translates xml entities (needs to make an internal 19 | -- copy of the lua string). 20 | -- lib.Default 21 | 22 | -- Same as default but trims leading and trailing whitespace. 23 | -- lib.TrimWhitespace 24 | 25 | -- Faster then default, does not translate xml entities. Parses data nodes. 26 | -- lib.NonDestructive 27 | 28 | -- Like xml.NonDestructive but does not parse data nodes. 29 | -- lib.Fastest 30 | 31 | -- Create a new parser. `type` flag is optional. If you are using the default 32 | -- parser, you can simply use [xml.load](xml.html#load). 33 | -- Usage example: 34 | -- 35 | -- local xml = require 'xml' 36 | -- local parser = xml.Parser(xml.Parser.Fastest) 37 | -- function lib.new(type) 38 | 39 | -- Parse an xml string and return a Lua table. See [lua/xml](xml.html) 40 | -- for the format of the returned table. Usage: 41 | -- 42 | -- local data = parser:load(some_xml_string) 43 | -- --> lua table 44 | -- function lib:load(str) 45 | 46 | -- Parse xml from file `path` and return a Lua table. See [lua/xml](xml.html) 47 | -- for the format of the returned table. Usage: 48 | -- 49 | -- local data = parser:loadpath(path_to_file) 50 | -- --> lua table 51 | function lib:loadpath(path) 52 | return self:load(lub.content(path)) 53 | end 54 | 55 | return lib 56 | -------------------------------------------------------------------------------- /xml/init.lua: -------------------------------------------------------------------------------- 1 | --[[------------------------------------------------------ 2 | # Very fast xml parser for Lua Build Status 3 | 4 | This parser uses [RapidXML](http://rapidxml.sourceforge.net/) to parse XML 5 | content. 6 | 7 | Fork me on GitHub 8 | 9 | *MIT license* © Marcin Kalicinski 2006, 2009, Gaspard Bucher 2014. 10 | 11 | ## Installation 12 | 13 | With [luarocks](http://luarocks.org): 14 | 15 | $ luarocks install xml 16 | 17 | ## Usage example 18 | 19 | local data = xml.load(some_xml) 20 | 21 | local xml_string = xml.dump(some_table) 22 | 23 | --]]----------------------------------------------------- 24 | local lub = require 'lub' 25 | local lib = lub.Autoload 'xml' 26 | local ipairs, pairs, insert, type, 27 | match, tostring = 28 | ipairs, pairs, table.insert, type, 29 | string.match, tostring 30 | 31 | local parser = lib.Parser() 32 | 33 | 34 | -- Current version respecting [semantic versioning](http://semver.org). 35 | lib.VERSION = '1.1.2' 36 | 37 | lib.DEPENDS = { -- doc 38 | -- Compatible with Lua 5.1 to 5.3 and LuaJIT 39 | 'lua >= 5.1, < 5.4', 40 | -- Uses [Lubyk base library](http://doc.lubyk.org/lub.html) 41 | 'lub >= 1.0.3, < 2', 42 | } 43 | 44 | -- nodoc 45 | lib.DESCRIPTION = { 46 | summary = "Very fast xml parser based on RapidXML", 47 | detailed = [[ 48 | This module is part of the Lubyk project. 49 | 50 | Main features are: 51 | - Fast and easy to use 52 | - Complete documentation 53 | - Based on proven code (RapidXML) 54 | - Full test coverage 55 | 56 | Read the documentation at http://doc.lubyk.org/xml.html. 57 | ]], 58 | homepage = "http://doc.lubyk.org/"..lib.type..".html", 59 | author = "Gaspard Bucher", 60 | license = "MIT", 61 | } 62 | 63 | -- nodoc 64 | lib.BUILD = { 65 | github = 'lubyk', 66 | includes = {'include', 'src/bind', 'src/vendor'}, 67 | platlibs = { 68 | linux = {'stdc++'}, 69 | macosx = {'stdc++'}, 70 | }, 71 | -- FIXME: Implement platform flags for lut.Builder and see how it works with 72 | -- luarocks /EHsc is needed for exception handling. 73 | platflags = { 74 | win32 = {'EHsc'}, 75 | }, 76 | } 77 | 78 | --[[ 79 | 80 | # Lua table format 81 | 82 | This xml library uses string keys in Lua tables to store 83 | attributes and numerical keys for sub-nodes. Since the 'xml' 84 | attribute is not allowed in XML, we use this key to store the 85 | tag. Here is an example of Lua content: 86 | 87 | ## Lua 88 | 89 | {xml='document', 90 | {xml = 'article', 91 | {xml = 'p', 'This is the first paragraph.'}, 92 | {xml = 'h2', class = 'opt', 'Title with opt style'}, 93 | }, 94 | {xml = 'article', 95 | {xml = 'p', 'Some ', {xml = 'b', 'important'}, ' text.'}, 96 | }, 97 | } 98 | 99 | ## XML 100 | 101 | And the equivalent xml: 102 | 103 | #txt 104 | 105 |
106 |

This is the first paragraph.

107 |

Title with opt style

108 |
109 |
110 |

Some important text.

111 |
112 |
113 | 114 | # Notes on speed 115 | 116 | RapidXML is a very fast parser that uses in-place modification of the input 117 | text. Since Lua strings are immutable, we have to make a copy except for the 118 | xml.Parser.NonDestructive and xml.Parser.Fastest settings. With these types 119 | some xml entities such as `&lt;` are not translated. 120 | 121 | See [RapidXML](http://rapidxml.sourceforge.net/) for details. 122 | --]]------------------------------------------------------ 123 | 124 | -- # Class methods 125 | 126 | -- Parse a `string` containing xml content and return a table. Uses 127 | -- xml.Parser with the xml.Parser.Default type. 128 | function lib.load(string) 129 | return parser:load(string) 130 | end 131 | 132 | -- Parse the XML content of the file at `path` and return a lua table. Uses 133 | -- xml.Parser with the xml.Parser.Default type. 134 | function lib.loadpath(path) 135 | return parser:load(lub.content(path)) 136 | end 137 | 138 | local function escape(v) 139 | if type(v) == 'boolean' then 140 | return v and 'true' or 'false' 141 | else 142 | return v:gsub('&','&'):gsub('>','>'):gsub('<','<'):gsub("'",''') 143 | end 144 | end 145 | 146 | local function tagWithAttributes(data) 147 | local res = data.xml or 'table' 148 | for k,v in pairs(data) do 149 | if k ~= 'xml' and type(k) == 'string' then 150 | res = res .. ' ' .. k .. "='" .. escape(v) .. "'" 151 | end 152 | end 153 | return res 154 | end 155 | 156 | local function doDump(data, indent, output, last, depth, max_depth) 157 | if depth > max_depth then 158 | error(string.format("Could not dump table to XML. Maximal depth of %i reached.", max_depth)) 159 | end 160 | 161 | if data[1] then 162 | insert(output, (last == 'n' and indent or '')..'<'..tagWithAttributes(data)..'>') 163 | last = 'n' 164 | local ind = indent..' ' 165 | for _, child in ipairs(data) do 166 | local typ = type(child) 167 | if typ == 'table' then 168 | doDump(child, ind, output, last, depth + 1, max_depth) 169 | last = 'n' 170 | elseif typ == 'number' then 171 | insert(output, tostring(child)) 172 | else 173 | local s = escape(child) 174 | insert(output, s) 175 | last = 's' 176 | end 177 | end 178 | insert(output, (last == 'n' and indent or '')..'') 179 | last = 'n' 180 | else 181 | -- no children 182 | insert(output, (last == 'n' and indent or '')..'<'..tagWithAttributes(data)..'/>') 183 | last = 'n' 184 | end 185 | end 186 | 187 | -- Dump a lua table in the format described above and return an XML string. The 188 | -- `max_depth` parameter is used to avoid infinite recursion in case a table 189 | -- references one of its ancestors. 190 | -- 191 | -- Default maximal depth is 3000. 192 | function lib.dump(table, max_depth) 193 | local max_depth = max_depth or 3000 194 | local res = {} 195 | doDump(table, '\n', res, 's', 1, max_depth) 196 | return lub.join(res, '') 197 | end 198 | 199 | 200 | local function doRemoveNamespace(data, prefix) 201 | data.xml = match(data.xml, prefix .. ':(.*)') or data.xml 202 | for _, sub in ipairs(data) do 203 | if type(sub) == 'table' then 204 | doRemoveNamespace(sub, prefix) 205 | end 206 | end 207 | end 208 | 209 | -- This function finds the `xmlns:NAME='KEY'` declaration and removes `NAME:` from 210 | -- the tag names. 211 | -- 212 | -- Example: 213 | -- 214 | -- local data = xml.load [[ 215 | -- 216 | -- Blah 217 | -- 218 | -- ]] 219 | -- 220 | -- xml.removeNamespace(data, 'bar') 221 | -- 222 | -- -- Result 223 | -- {xml = 'document', ['xmlns:foo'] = 'bar', 224 | -- {xml = 'name', 'Blah'}, 225 | -- } 226 | function lib.removeNamespace(data, key) 227 | local nm 228 | for k, v in pairs(data) do 229 | if v == key then 230 | nm = match(k, 'xmlns:(.*)') 231 | if nm == '' then 232 | -- error 233 | return 234 | else 235 | doRemoveNamespace(data, nm) 236 | end 237 | end 238 | end 239 | end 240 | 241 | -- Recursively find the first table with a tag equal to `tag`. This 242 | -- search uses [lub.search](lub.html#search) to do an [Iterative deepening depth-first search](https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search) 243 | -- because we usually search for elements close to the surface. 244 | -- 245 | -- For more options, use [lub.search](lub.html#search) directly with a custom 246 | -- function. 247 | -- 248 | -- You can also pass an attribute key and attribute value to further filter the 249 | -- searched node. This gives this function the same arguments as LuaXML's find 250 | -- function. 251 | -- 252 | -- Usage examples: 253 | -- 254 | -- local sect = xml.find(elem, 'simplesect', 'kind', 'section') 255 | -- 256 | -- print(xml.find(sect, 'title')) 257 | function lib.find(data, tag, attr_key, attr_value) 258 | if attr_key then 259 | return lub.search(data, function(node) 260 | if node.xml == tag and node[attr_key] == attr_value then 261 | return node 262 | end 263 | end) 264 | else 265 | return lub.search(data, function(node) 266 | if node.xml == tag then 267 | return node 268 | end 269 | end) 270 | end 271 | end 272 | 273 | -- # Classes 274 | 275 | return lib 276 | --------------------------------------------------------------------------------