pax_global_header00006660000000000000000000000064126226004150014510gustar00rootroot0000000000000052 comment=28726b27af3cd0a9d3166033c6619a9c7227cb48 r3-1.3.4/000077500000000000000000000000001262260041500120415ustar00rootroot00000000000000r3-1.3.4/.gitignore000066400000000000000000000007731262260041500140400ustar00rootroot00000000000000 # cmake CMakeCache.txt CMakeFiles CTestTestfile.cmake Testing cmake_install.cmake install_manifest.txt # tags tags # autotools *.a *.lo *.la *.dylib *.o Makefile Makefile.in aclocal.m4 autom4te.cache compile config.guess config.log config.status config.sub configure depcomp gumbo.pc gumbo_test gumbo_test.log gumbo_test.trs install-sh libtool ltmain.sh m4/ missing test-driver test-suite.log config.h tests/*.log tests/*.trs configure.scan autoscan.log .libs .deps r3.pc stamp-h1 tests/bench_str.csv r3-1.3.4/.travis.yml000066400000000000000000000031711262260041500141540ustar00rootroot00000000000000language: c compiler: - gcc git: depth: 1 matrix: include: - compiler: gcc env: CONFIGURE_OPTION='--enable-debug --enable-gcov --with-malloc=jemalloc' COVERALLS=yes VALGRIND=no DEBUG=yes - compiler: gcc env: CONFIGURE_OPTION='--enable-debug --enable-gcov' COVERALLS=yes VALGRIND=yes DEBUG=yes LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/ # -D_BSD_SOURCE=1 is for asprintf - compiler: clang env: ASAN_OPTIONS=symbolize=1 ASAN_SYMBOLIZER_PATH=/usr/local/clang-3.4/bin/llvm-symbolizer CFLAGS='-fsanitize=address -g -O1 -D_BSD_SOURCE=1' CXX=clang++ CXXFLAGS='-fsanitize=address -g -O1 -D_BSD_SOURCE=1' install: - sudo apt-get update -qq - sudo apt-get install -qq automake pkg-config build-essential libtool automake autoconf m4 gnulib - sudo apt-get install -qq check libpcre3 libpcre3-dev libjemalloc-dev libjemalloc1 - sudo apt-get install -qq graphviz-dev graphviz - if [ "x$COVERALLS" == xyes ]; then sudo pip install cpp-coveralls; fi - if [ "x$VALGRIND" == xyes ]; then sudo apt-get install valgrind; fi before_script: - sudo ldconfig script: - ./autogen.sh - ./configure --enable-check $CONFIGURE_OPTION - make V=1 - sudo make install - if [ "x$VALGRIND" == xyes ]; then make check > /dev/null 2>&1; else make check V=1; fi # XXX: tracing memory leak, disabled for some mystery reason for automake... # - if [ "x$VALGRIND" == xyes && "x$DEBUG" == xyes ]; then valgrind ./tests/check_* -v --trace-children=yes --show-leak-kinds=full --leak-check=full; fi after_success: - if [ x$COVERALLS == xyes ]; then coveralls --exclude php --exclude 3rdparty; fi cache: apt: true r3-1.3.4/3rdparty/000077500000000000000000000000001262260041500136115ustar00rootroot00000000000000r3-1.3.4/3rdparty/CMakeLists.txt000066400000000000000000000004611262260041500163520ustar00rootroot00000000000000include_directories("${PROJECT_SOURCE_DIR}/3rdparty ${PROJECT_SOURCE_DIR}") set(lib3rdparty_SRCS zmalloc.c) add_library(lib3rdparty STATIC ${lib3rdparty_SRCS}) # add_library(r3 SHARED ${libr3_SRCS}) # target_link_libraries(r3 cblas) # install(FILES ${libswiftnav_HEADERS} DESTINATION include/libswiftnav) r3-1.3.4/3rdparty/Makefile.am000066400000000000000000000006721262260041500156520ustar00rootroot00000000000000AM_CFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) -I$(top_builddir) -I$(top_builddir)/include -I$(top_builddir)/3rdparty -Wall -std=c99 AM_LDFLAGS=$(DEPS_LIBS) $(GVC_DEPS_LIBS) noinst_LTLIBRARIES = libr3ext.la libr3ext_la_SOURCES = zmalloc.c libr3ext_la_LIBADD=$(DEPS_LIBS) # noinst_LIBRARIES = libr3ext.la libr3ext_la_CFLAGS=$(DEPS_CFLAGS) -I$(top_builddir) -I$(top_builddir)/3rdparty -Wall -std=c99 noinst_HEADERS = \ zmalloc.h \ $(NULL) r3-1.3.4/3rdparty/zmalloc.c000066400000000000000000000242371262260041500154260ustar00rootroot00000000000000/* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include /* This function provide us access to the original libc free(). This is useful * for instance to free results obtained by backtrace_symbols(). We need * to define this function before including zmalloc.h that may shadow the * free implementation if we use jemalloc or another non standard allocator. */ void zlibc_free(void *ptr) { free(ptr); } #include #include #include "config.h" #include "zmalloc.h" #ifdef HAVE_MALLOC_SIZE #define PREFIX_SIZE (0) #else #if defined(__sun) || defined(__sparc) || defined(__sparc__) #define PREFIX_SIZE (sizeof(long long)) #else #define PREFIX_SIZE (sizeof(size_t)) #endif #endif /* Explicitly override malloc/free etc when using tcmalloc. */ #if defined(USE_TCMALLOC) #define malloc(size) tc_malloc(size) #define calloc(count,size) tc_calloc(count,size) #define realloc(ptr,size) tc_realloc(ptr,size) #define free(ptr) tc_free(ptr) #elif defined(USE_JEMALLOC) && (JEMALLOC_VERSION_MAJOR > 2) #include #define malloc(size) je_malloc(size) #define calloc(count,size) je_calloc(count,size) #define realloc(ptr,size) je_realloc(ptr,size) #define free(ptr) je_free(ptr) #endif #ifdef HAVE_ATOMIC #define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n)) #define update_zmalloc_stat_sub(__n) __sync_sub_and_fetch(&used_memory, (__n)) #else #define update_zmalloc_stat_add(__n) do { \ pthread_mutex_lock(&used_memory_mutex); \ used_memory += (__n); \ pthread_mutex_unlock(&used_memory_mutex); \ } while(0) #define update_zmalloc_stat_sub(__n) do { \ pthread_mutex_lock(&used_memory_mutex); \ used_memory -= (__n); \ pthread_mutex_unlock(&used_memory_mutex); \ } while(0) #endif #define update_zmalloc_stat_alloc(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ update_zmalloc_stat_add(_n); \ } else { \ used_memory += _n; \ } \ } while(0) #define update_zmalloc_stat_free(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ update_zmalloc_stat_sub(_n); \ } else { \ used_memory -= _n; \ } \ } while(0) static size_t used_memory = 0; static int zmalloc_thread_safe = 0; pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; static void zmalloc_default_oom(size_t size) { fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n", size); fflush(stderr); abort(); } static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom; void *zmalloc(size_t size) { void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } void *zcalloc(size_t size) { void *ptr = calloc(1, size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } void *zrealloc(void *ptr, size_t size) { #ifndef HAVE_MALLOC_SIZE void *realptr; #endif size_t oldsize; void *newptr; if (ptr == NULL) return zmalloc(size); #ifdef HAVE_MALLOC_SIZE oldsize = zmalloc_size(ptr); newptr = realloc(ptr,size); if (!newptr) zmalloc_oom_handler(size); update_zmalloc_stat_free(oldsize); update_zmalloc_stat_alloc(zmalloc_size(newptr)); return newptr; #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); newptr = realloc(realptr,size+PREFIX_SIZE); if (!newptr) zmalloc_oom_handler(size); *((size_t*)newptr) = size; update_zmalloc_stat_free(oldsize); update_zmalloc_stat_alloc(size); return (char*)newptr+PREFIX_SIZE; #endif } /* Provide zmalloc_size() for systems where this function is not provided by * malloc itself, given that in that case we store a header with this * information as the first bytes of every allocation. */ #ifndef HAVE_MALLOC_SIZE size_t zmalloc_size(void *ptr) { void *realptr = (char*)ptr-PREFIX_SIZE; size_t size = *((size_t*)realptr); /* Assume at least that all the allocations are padded at sizeof(long) by * the underlying allocator. */ if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1)); return size+PREFIX_SIZE; } #endif void zfree(void *ptr) { #ifndef HAVE_MALLOC_SIZE void *realptr; size_t oldsize; #endif if (ptr == NULL) return; #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_free(zmalloc_size(ptr)); free(ptr); #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); update_zmalloc_stat_free(oldsize+PREFIX_SIZE); free(realptr); #endif } char *zstrdup(const char *s) { size_t l = strlen(s)+1; char *p = zmalloc(l); memcpy(p,s,l); return p; } char * zstrndup (const char *s, size_t n) { char *result; size_t len = strlen (s); if (n < len) len = n; result = (char *) zmalloc (len + 1); if (!result) return 0; result[len] = '\0'; return (char *) memcpy (result, s, len); } size_t zmalloc_used_memory(void) { size_t um; if (zmalloc_thread_safe) { #ifdef HAVE_ATOMIC um = __sync_add_and_fetch(&used_memory, 0); #else pthread_mutex_lock(&used_memory_mutex); um = used_memory; pthread_mutex_unlock(&used_memory_mutex); #endif } else { um = used_memory; } return um; } void zmalloc_enable_thread_safeness(void) { zmalloc_thread_safe = 1; } void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) { zmalloc_oom_handler = oom_handler; } /* Get the RSS information in an OS-specific way. * * WARNING: the function zmalloc_get_rss() is not designed to be fast * and may not be called in the busy loops where Redis tries to release * memory expiring or swapping out objects. * * For this kind of "fast RSS reporting" usages use instead the * function RedisEstimateRSS() that is a much faster (and less precise) * version of the function. */ #if defined(HAVE_PROC_STAT) #include #include #include #include size_t zmalloc_get_rss(void) { int page = sysconf(_SC_PAGESIZE); size_t rss; char buf[4096]; char filename[256]; int fd, count; char *p, *x; snprintf(filename,256,"/proc/%d/stat",getpid()); if ((fd = open(filename,O_RDONLY)) == -1) return 0; if (read(fd,buf,4096) <= 0) { close(fd); return 0; } close(fd); p = buf; count = 23; /* RSS is the 24th field in /proc//stat */ while(p && count--) { p = strchr(p,' '); if (p) p++; } if (!p) return 0; x = strchr(p,' '); if (!x) return 0; *x = '\0'; rss = strtoll(p,NULL,10); rss *= page; return rss; } #elif defined(HAVE_TASKINFO) #include #include #include #include #include #include #include size_t zmalloc_get_rss(void) { task_t task = MACH_PORT_NULL; struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS) return 0; task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); return t_info.resident_size; } #else size_t zmalloc_get_rss(void) { /* If we can't get the RSS in an OS-specific way for this system just * return the memory usage we estimated in zmalloc().. * * Fragmentation will appear to be always 1 (no fragmentation) * of course... */ return zmalloc_used_memory(); } #endif /* Fragmentation = RSS / allocated-bytes */ float zmalloc_get_fragmentation_ratio(size_t rss) { return (float)rss/zmalloc_used_memory(); } #if defined(HAVE_PROC_SMAPS) size_t zmalloc_get_private_dirty(void) { char line[1024]; size_t pd = 0; FILE *fp = fopen("/proc/self/smaps","r"); if (!fp) return 0; while(fgets(line,sizeof(line),fp) != NULL) { if (strncmp(line,"Private_Dirty:",14) == 0) { char *p = strchr(line,'k'); if (p) { *p = '\0'; pd += strtol(line+14,NULL,10) * 1024; } } } fclose(fp); return pd; } #else size_t zmalloc_get_private_dirty(void) { return 0; } #endif r3-1.3.4/3rdparty/zmalloc.h000066400000000000000000000064701262260041500154320ustar00rootroot00000000000000#ifndef ZMALLOC_H #define ZMALLOC_H /* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Double expansion needed for stringification of macro values. */ #define __xstr(s) __str(s) #define __str(s) #s #if defined(USE_TCMALLOC) #define ZMALLOC_LIB ("tcmalloc-" __xstr(TC_VERSION_MAJOR) "." __xstr(TC_VERSION_MINOR)) #include #if (TC_VERSION_MAJOR == 1 && TC_VERSION_MINOR >= 6) || (TC_VERSION_MAJOR > 1) #define HAVE_MALLOC_SIZE 1 #define zmalloc_size(p) tc_malloc_size(p) #else #error "Newer version of tcmalloc required" #endif #elif defined(USE_JEMALLOC) && (JEMALLOC_VERSION_MAJOR > 2) #define ZMALLOC_LIB ("jemalloc-" __xstr(JEMALLOC_VERSION_MAJOR) "." __xstr(JEMALLOC_VERSION_MINOR) "." __xstr(JEMALLOC_VERSION_BUGFIX)) #include #if (JEMALLOC_VERSION_MAJOR == 2 && JEMALLOC_VERSION_MINOR >= 1) || (JEMALLOC_VERSION_MAJOR > 2) #define HAVE_MALLOC_SIZE 1 #define zmalloc_size(p) je_malloc_usable_size(p) #else #error "Newer version of jemalloc required" #endif #elif defined(__APPLE__) #include #define HAVE_MALLOC_SIZE 1 #define zmalloc_size(p) malloc_size(p) #endif #ifndef ZMALLOC_LIB #define ZMALLOC_LIB "libc" #endif void *zmalloc(size_t size); void *zcalloc(size_t size); void *zrealloc(void *ptr, size_t size); void zfree(void *ptr); char *zstrdup(const char *s); char *zstrndup(const char *s, size_t n); size_t zmalloc_used_memory(void); void zmalloc_enable_thread_safeness(void); void zmalloc_set_oom_handler(void (*oom_handler)(size_t)); float zmalloc_get_fragmentation_ratio(size_t rss); size_t zmalloc_get_rss(void); size_t zmalloc_get_private_dirty(void); void zlibc_free(void *ptr); #ifndef HAVE_MALLOC_SIZE size_t zmalloc_size(void *ptr); #endif #endif // ZMALLOC_H r3-1.3.4/CHANGES.md000066400000000000000000000034021262260041500134320ustar00rootroot00000000000000# CHANGELOG by Yo-An Lin ### 1.3.3 - Sat Jun 28 00:53:48 2014 - Fix graphviz generator. ### 1.3.2 - Sat Jun 28 00:54:22 2014 - `HAVE_STRNDUP` and `HAVE_STRDUP` definition fix ### 1.3.0 - Tue Jun 3 18:47:14 2014 - Added Incorrect slug syntax warnings - Added error message support for pcre/pcre-jit compile - Added JSON encode support for the tree structure - Improved Graphivz Related Functions - More failing test cases ### 1.2.1 - Tue May 27 21:16:13 2014 - Bug fixes. - Function declaration improvement. - pkg-config flags update (r3.pc) ### 1.2 - Fri May 23 23:30:11 2014 - Added simple pattern optimization. - Clean up. - Bug fixes. ### 0.9999 - Mon May 19 10:03:41 2014 API changes: 1. Removed the `route` argument from `r3_tree_insert_pathl_ex`: node * r3_tree_insert_pathl_ex(node *tree, char *path, int path_len, void * data); This reduce the interface complexity, e.g., r3_tree_insert_path(n, "/user2/{id:\\d+}", &var2); 2. The original `r3_tree_insert_pathl_ex` has been moved to `r3_tree_insert_pathl_ex` as a private API. 3. Moved `r3_tree_matchl` to `r3_tree_matchl` since it require the length of the path string. m = r3_tree_matchl( n , "/foo", strlen("/foo"), entry); 4. Added `r3_tree_match` for users to match a path without the length of the path string. m = r3_tree_match( n , "/foo", entry); 5. Added `r3_tree_match_entry` for users want to match a `match_entry`, which is just a macro to simplify the use: #define r3_tree_match_entry(n, entry) r3_tree_matchl(n, entry->path, entry->path_len, entry) 6. Please note that A path that is inserted by `r3_tree_insert_route` can only be matched by `r3_tree_match_route`. 7. Added `r3_` prefix to `route` related methods. r3-1.3.4/CMakeLists.txt000066400000000000000000000021431262260041500146010ustar00rootroot00000000000000# cmake file examples # https://code.google.com/p/opencv-feature-tracker/source/browse/CMakeLists.txt?r=f804b03e704147e65183c19a50f57abedb22f45c # TODO: # cmake clean... orz # http://stackoverflow.com/questions/9680420/looking-for-a-cmake-clean-command-to-clear-up-cmake-output cmake_minimum_required(VERSION 2.8) project(r3) SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH} ) include_directories(. ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/3rdparty /opt/local/include) # include_directories(. ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/3rdparty ${PROJECT_SOURCE_DIR}) link_directories(${LINK_DIRECTORIES} /opt/local/lib) find_package(PCRE REQUIRED) # find_package(Judy REQUIRED) # set(LIBS ${LIBS} ${PCRE_LIBRARIES} ${Judy_LIBRARIES} r3) set(LIBS ${LIBS} ${PCRE_LIBRARIES} r3) # set (CMAKE_CXX_FLAGS "-std=c++0x -arch x86_64 -stdlib=libc++ -g3 -Wall -O0") enable_testing() add_subdirectory(3rdparty) add_subdirectory(src) add_subdirectory(tests) # add_test(test_tree ${CMAKE_CURRENT_BINARY_DIR}/check_tree) r3-1.3.4/COPYING000066400000000000000000000020761262260041500131010ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 yoanlin93@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. r3-1.3.4/HACKING.md000066400000000000000000000017621262260041500134350ustar00rootroot00000000000000Related Articles ===================== Judy Array ------------ - A 10-MINUTE DESCRIPTION OF HOW JUDY ARRAYS WORK AND WHY THEY ARE SO FAST - Hashtables vs Judy Arrays, Round 1 - This Hash Table Is Faster Than a Judy Array - A Performance Comparison of Judy to Hash Tables - Faster (sometimes) Associative Arrays with Node.js Jemalloc ------------ https://github.com/jemalloc/jemalloc/wiki/Getting-Started Prefix Tree / Radix Tree ------------------------- - Radix Tree: - Radix Tree in Linux Kernel: - Radix Tree in Linux Kernel (source code): r3-1.3.4/INSTALL000066400000000000000000000366101262260041500131000ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 1994-1996, 1999-2002, 2004-2013 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell command `./configure && make && make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. HP-UX `make' updates targets which have the same time stamps as their prerequisites, which makes it generally unusable when shipped generated files such as `configure' are involved. Use GNU `make' instead. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf limitation. Until the limitation is lifted, you can use this workaround: CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. r3-1.3.4/LICENSE000066400000000000000000000020761262260041500130530ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 yoanlin93@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. r3-1.3.4/Makefile.am000066400000000000000000000015621262260041500141010ustar00rootroot00000000000000SUBDIRS=3rdparty src . tests examples lib_LTLIBRARIES = libr3.la libr3_la_SOURCES = libr3_la_LIBADD = 3rdparty/libr3ext.la src/libr3core.la libr3_la_LDFLAGS = AM_CFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) -I$(top_builddir) -I$(top_builddir)/include -I$(top_builddir)/3rdparty -Wall -std=c99 AM_LDFLAGS=$(DEPS_LIBS) $(GVC_DEPS_LIBS) ACLOCAL_AMFLAGS=-I m4 if ENABLE_DEBUG AM_CFLAGS += -ggdb -fprofile-arcs -ftest-coverage endif if USE_JEMALLOC AM_LDFLAGS += -ljemalloc endif r3_includedir = $(includedir)/r3 r3_include_HEADERS = \ include/r3.h \ include/r3_define.h \ include/r3_list.h \ include/r3_str.h \ include/r3_gvc.h \ include/r3_json.h \ include/str_array.h \ include/r3.hpp \ $(NULL) pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = r3.pc EXTRA_DIST = \ autogen.sh \ bench.html \ demo.c \ gen_routes.rb \ HACKING.md \ LICENSE \ README.md \ $(NULL) r3-1.3.4/README.md000066400000000000000000000262651262260041500133330ustar00rootroot00000000000000R3 ================ [![Build Status](https://travis-ci.org/c9s/r3.svg?branch=master)](https://travis-ci.org/c9s/r3) [![Coverage Status](https://coveralls.io/repos/c9s/r3/badge.svg)](https://coveralls.io/r/c9s/r3) R3 is an URL router library with high performance, thus, it's implemented in C. It compiles your route paths into a prefix trie. By using the prefix tree constructed in the start-up time, you can dispatch the path to the controller with high efficiency. Requirement ----------------------- ### Build Requirement * autoconf * automake * check * pkg-config ### Runtime Requirement * pcre * (optional) graphviz version 2.38.0 (20140413.2041) * (optional) libjson-c-dev Pattern Syntax ----------------------- /blog/post/{id} use [^/]+ regular expression by default. /blog/post/{id:\d+} use `\d+` regular expression instead of default. API ------------------------ ```c #include // create a router tree with 10 children capacity (this capacity can grow dynamically) node *n = r3_tree_create(10); int route_data = 3; // insert the route path into the router tree r3_tree_insert_path(n, "/bar", &route_data); // ignore the length of path r3_tree_insert_pathl(n, "/zoo", strlen("/zoo"), &route_data ); r3_tree_insert_pathl(n, "/foo/bar", strlen("/foo/bar"), &route_data ); r3_tree_insert_pathl(n ,"/post/{id}", strlen("/post/{id}") , &route_data ); r3_tree_insert_pathl(n, "/user/{id:\\d+}", strlen("/user/{id:\\d+}"), &route_data ); // if you want to catch error, you may call the extended path function for insertion int data = 10; char *errstr = NULL; node *ret = r3_tree_insert_pathl_ex(n, "/foo/{name:\\d{5}", strlen("/foo/{name:\\d{5}"), NULL, &data, &errstr); if (ret == NULL) { // failed insertion printf("error: %s\n", errstr); free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // let's compile the tree! char *errstr = NULL; int err = r3_tree_compile(n, &errstr); if (err != 0) { // fail printf("error: %s\n", errstr); free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // dump the compiled tree r3_tree_dump(n, 0); // match a route node *matched_node = r3_tree_matchl(n, "/foo/bar", strlen("/foo/bar"), NULL); if (matched_node) { int ret = *( (int*) matched_node->data ); } // release the tree r3_tree_free(n); ``` **Capture Dynamic Variables** If you want to capture the variables from regular expression, you will need to create a `match_entry` object and pass the object to `r3_tree_matchl` function, the catched variables will be pushed into the match entry structure: ```c match_entry * entry = match_entry_create("/foo/bar"); // free the match entry match_entry_free(entry); ``` And you can even specify the request method restriction: ```c entry->request_method = METHOD_GET; entry->request_method = METHOD_POST; entry->request_method = METHOD_GET | METHOD_POST; ``` When using `match_entry`, you may match the route with `r3_tree_match_entry` function: ```c node *matched_node = r3_tree_match_entry(n, entry); ``` **Release Memory** To release the memory, you may call `r3_tree_free(node *tree)` to release the whole tree structure, `node*`, `edge*`, `route*` objects that were inserted into the tree will be freed. ### Routing with conditions ```c // create a router tree with 10 children capacity (this capacity can grow dynamically) n = r3_tree_create(10); int route_data = 3; // insert the route path into the router tree r3_tree_insert_routel(n, METHOD_GET | METHOD_POST, "/blog/post", sizeof("/blog/post") - 1, &route_data ); char *errstr = NULL; int err = r3_tree_compile(n, &errstr); if (err != 0) { // fail printf("error: %s\n", errstr); free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // in your http server handler // create the match entry for capturing dynamic variables. match_entry * entry = match_entry_create("/blog/post"); entry->request_method = METHOD_GET; route *matched_route = r3_tree_match_route(n, entry); matched_route->data; // get the data from matched route // free the objects at the end match_entry_free(entry); r3_tree_free(n); ``` Slug ----------------------- A slug is a placeholder, which captures the string from the URL as a variable. Slugs will be compiled into regular expression patterns. Slugs without patterns (like `/user/{userId}`) will be compiled into the `[^/]+` pattern. To specify the pattern of a slug, you may write a colon to separate the slug name and the pattern: "/user/{userId:\\d+}" The above route will use `\d+` as its pattern. Optimization ----------------------- Simple regular expressions are optimized through a regexp pattern to opcode translator, which translates simple patterns into small & fast scanners. By using this method, r3 reduces the matching overhead of pcre library. Optimized patterns are: `[a-z]+`, `[0-9]+`, `\d+`, `\w+`, `[^/]+` or `[^-]+` Slugs without specified regular expression will be compiled into the `[^/]+` pattern. therefore, it's optimized too. Complex regular expressions will still use libpcre to match URL (partially). Performance ----------------------- The routing benchmark from stevegraham/rails' PR : omg 10462.0 (±6.7%) i/s - 52417 in 5.030416s And here is the result of the router journey: omg 9932.9 (±4.8%) i/s - 49873 in 5.033452s r3 uses the same route path data for benchmarking, and here is the benchmark: 3 runs, 5000000 iterations each run, finished in 1.308894 seconds 11460057.83 i/sec ### The Route Paths Of Benchmark The route path generator is from : ```ruby #!/usr/bin/env ruby arr = ["foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply"] paths = arr.permutation(3).map { |a| "/#{a.join '/'}" } paths.each do |path| puts "r3_tree_insert_path(n, \"#{path}\", NULL);" end ``` Function prefix mapping ----------------------- |Function Prefix |Description | |------------------|------------------------------------------------------------------------------------| |`r3_tree_*` |Tree related operations, which require a node to operate a whole tree | |`r3_node_*` |Single node related operations, which do not go through its own children or parent. | |`r3_edge_*` |Edge related operations | |`r3_route_*` |Route related operations, which are needed only when the tree is defined by routes | |`match_entry_*` |Match entry related operations, a `match_entry` is just like the request parameters | Rendering Routes With Graphviz --------------------------------------- The `r3_tree_render_file` API let you render the whole route trie into a image. To use graphviz, you need to enable graphviz while you run `configure`: ./configure --enable-graphviz Here is the sample code of generating graph output: ```c node * n = r3_tree_create(1); r3_tree_insert_path(n, "/foo/bar/baz", NULL); r3_tree_insert_path(n, "/foo/bar/qux", NULL); r3_tree_insert_path(n, "/foo/bar/quux", NULL); r3_tree_insert_path(n, "/foo/bar/corge", NULL); r3_tree_insert_path(n, "/foo/bar/grault", NULL); r3_tree_insert_path(n, "/garply/grault/foo", NULL); r3_tree_insert_path(n, "/garply/grault/bar", NULL); r3_tree_insert_path(n, "/user/{id}", NULL); r3_tree_insert_path(n, "/post/{title:\\w+}", NULL); char *errstr = NULL; int err; err = r3_tree_compile(n, &errstr); if (err != 0) { // fail printf("error: %s\n", errstr); free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } r3_tree_render_file(n, "png", "check_gvc.png"); r3_tree_free(n); ``` ![Imgur](http://imgur.com/HrUoEbI.png) Or you can even export it with dot format: ```dot digraph g { graph [bb="0,0,205.1,471"]; node [label="\N"]; "{root}" [height=0.5, pos="35.097,453", width=0.97491]; "#1" [height=0.5, pos="35.097,366", width=0.75]; .... ``` ### Graphviz Related Functions ```c int r3_tree_render_file(const node * tree, const char * format, const char * filename); int r3_tree_render(const node * tree, const char *layout, const char * format, FILE *fp); int r3_tree_render_dot(const node * tree, const char *layout, FILE *fp); int r3_tree_render_file(const node * tree, const char * format, const char * filename); ``` JSON Output ---------------------------------------- You can render the whole tree structure into json format output. Please run `configure` with the `--enable-json` option. Here is the sample code to generate JSON string: ```c json_object * obj = r3_node_to_json_object(n); const char *json = r3_node_to_json_pretty_string(n); printf("Pretty JSON: %s\n",json); const char *json = r3_node_to_json_string(n); printf("JSON: %s\n",json); ``` Use case in PHP ----------------------- **not implemented yet** ```php // Here is the paths data structure $paths = [ '/blog/post/{id}' => [ 'controller' => 'PostController' , 'action' => 'item' , 'method' => 'GET' ] , '/blog/post' => [ 'controller' => 'PostController' , 'action' => 'list' , 'method' => 'GET' ] , '/blog/post' => [ 'controller' => 'PostController' , 'action' => 'create' , 'method' => 'POST' ] , '/blog' => [ 'controller' => 'BlogController' , 'action' => 'list' , 'method' => 'GET' ] , ]; $rs = r3_compile($paths, 'persisten-table-id'); $ret = r3_dispatch($rs, '/blog/post/3' ); list($complete, $route, $variables) = $ret; // matched conditions aren't done yet list($error, $message) = r3_validate($route); // validate route conditions if ( $error ) { echo $message; // "Method not allowed", "..."; } ``` Install ---------------------- sudo apt-get install check libpcre3 libpcre3-dev libjemalloc-dev libjemalloc1 build-essential libtool automake autoconf pkg-config sudo apt-get install graphviz-dev graphviz # if you want graphviz ./autogen.sh ./configure && make sudo make install And we support debian-based distro now! sudo apt-get install build-essential autoconf automake libpcre3-dev pkg-config debhelper libtool check mv dist-debian debian dpkg-buildpackage -b -us -uc sudo gdebi ../libr3*.deb #### Run Unit Tests ./configure --enable-check make check #### Enable Graphviz ./configure --enable-graphviz #### With jemalloc ./configure --with-malloc=jemalloc ubuntu PPA ---------------------- The PPA for libr3 can be found in . Binding For Other Languages --------------------------- * Perl Router::R3 by @CindyLinz * Python pyr3 by @lucemia * Python pyr3 by @thedrow * Haskell r3 by @MnO2 * Vala r3-vala by @Ronmi * Node.js node-r3 by @othree * Node.js node-libr3 by @caasi * Ruby rr3 by @tonytonyjan License -------------------- This software is released under MIT License. r3-1.3.4/autogen.sh000077500000000000000000000015171262260041500140460ustar00rootroot00000000000000#!/bin/sh set -ex rm -rf autom4te.cache Makefile.in aclocal.m4 aclocal --force # GNU libtool is named differently on some systems. This code tries several # variants like glibtoolize (MacOSX) and libtoolize1x (FreeBSD) set +ex echo "Looking for a version of libtoolize (which can have different names)..." libtoolize="" for l in glibtoolize libtoolize15 libtoolize14 libtoolize ; do $l --version > /dev/null 2>&1 if [ $? = 0 ]; then libtoolize=$l echo "Found $l" break fi echo "Did not find $l" done if [ "x$libtoolize" = "x" ]; then echo "Can't find libtoolize on your system" exit 1 fi set -ex $libtoolize -c -f autoconf -f -W all,no-obsolete autoheader -f -W all # automake -a -c -f -W all automake --add-missing --foreign --copy -c -W all rm -rf autom4te.cache exit 0 # end autogen.sh r3-1.3.4/bench.html000066400000000000000000000263631262260041500140200ustar00rootroot00000000000000 Benchmark

R3: Router Benchmark

Data Set

This testing data is from https://github.com/stevegraham/rails/pull/1

/foo/bar/baz
/foo/bar/qux
/foo/bar/quux
/foo/bar/corge
/foo/bar/grault
/foo/bar/garply
/foo/baz/bar
/foo/baz/qux
/foo/baz/quux
/foo/baz/corge
/foo/baz/grault
/foo/baz/garply
/foo/qux/bar
/foo/qux/baz
/foo/qux/quux
/foo/qux/corge
/foo/qux/grault
/foo/qux/garply
/foo/quux/bar
/foo/quux/baz
/foo/quux/qux
/foo/quux/corge
/foo/quux/grault
/foo/quux/garply
/foo/corge/bar
/foo/corge/baz
/foo/corge/qux
/foo/corge/quux
/foo/corge/grault
/foo/corge/garply
/foo/grault/bar
/foo/grault/baz
/foo/grault/qux
/foo/grault/quux
/foo/grault/corge
/foo/grault/garply
/foo/garply/bar
/foo/garply/baz
/foo/garply/qux
/foo/garply/quux
/foo/garply/corge
/foo/garply/grault
/bar/foo/baz
/bar/foo/qux
/bar/foo/quux
/bar/foo/corge
/bar/foo/grault
/bar/foo/garply
/bar/baz/foo
/bar/baz/qux
/bar/baz/quux
/bar/baz/corge
/bar/baz/grault
/bar/baz/garply
/bar/qux/foo
/bar/qux/baz
/bar/qux/quux
/bar/qux/corge
/bar/qux/grault
/bar/qux/garply
/bar/quux/foo
/bar/quux/baz
/bar/quux/qux
/bar/quux/corge
/bar/quux/grault
/bar/quux/garply
/bar/corge/foo
/bar/corge/baz
/bar/corge/qux
/bar/corge/quux
/bar/corge/grault
/bar/corge/garply
/bar/grault/foo
/bar/grault/baz
/bar/grault/qux
/bar/grault/quux
/bar/grault/corge
/bar/grault/garply
/bar/garply/foo
/bar/garply/baz
/bar/garply/qux
/bar/garply/quux
/bar/garply/corge
/bar/garply/grault
/baz/foo/bar
/baz/foo/qux
/baz/foo/quux
/baz/foo/corge
/baz/foo/grault
/baz/foo/garply
/baz/bar/foo
/baz/bar/qux
/baz/bar/quux
/baz/bar/corge
/baz/bar/grault
/baz/bar/garply
/baz/qux/foo
/baz/qux/bar
/baz/qux/quux
/baz/qux/corge
/baz/qux/grault
/baz/qux/garply
/baz/quux/foo
/baz/quux/bar
/baz/quux/qux
/baz/quux/corge
/baz/quux/grault
/baz/quux/garply
/baz/corge/foo
/baz/corge/bar
/baz/corge/qux
/baz/corge/quux
/baz/corge/grault
/baz/corge/garply
/baz/grault/foo
/baz/grault/bar
/baz/grault/qux
/baz/grault/quux
/baz/grault/corge
/baz/grault/garply
/baz/garply/foo
/baz/garply/bar
/baz/garply/qux
/baz/garply/quux
/baz/garply/corge
/baz/garply/grault
/qux/foo/bar
/qux/foo/baz
/qux/foo/quux
/qux/foo/corge
/qux/foo/grault
/qux/foo/garply
/qux/bar/foo
/qux/bar/baz
/qux/bar/quux
/qux/bar/corge
/qux/bar/grault
/qux/bar/garply
/qux/baz/foo
/qux/baz/bar
/qux/baz/quux
/qux/baz/corge
/qux/baz/grault
/qux/baz/garply
/qux/quux/foo
/qux/quux/bar
/qux/quux/baz
/qux/quux/corge
/qux/quux/grault
/qux/quux/garply
/qux/corge/foo
/qux/corge/bar
/qux/corge/baz
/qux/corge/quux
/qux/corge/grault
/qux/corge/garply
/qux/grault/foo
/qux/grault/bar
/qux/grault/baz
/qux/grault/quux
/qux/grault/corge
/qux/grault/garply
/qux/garply/foo
/qux/garply/bar
/qux/garply/baz
/qux/garply/quux
/qux/garply/corge
/qux/garply/grault
/quux/foo/bar
/quux/foo/baz
/quux/foo/qux
/quux/foo/corge
/quux/foo/grault
/quux/foo/garply
/quux/bar/foo
/quux/bar/baz
/quux/bar/qux
/quux/bar/corge
/quux/bar/grault
/quux/bar/garply
/quux/baz/foo
/quux/baz/bar
/quux/baz/qux
/quux/baz/corge
/quux/baz/grault
/quux/baz/garply
/quux/qux/foo
/quux/qux/bar
/quux/qux/baz
/quux/qux/corge
/quux/qux/grault
/quux/qux/garply
/quux/corge/foo
/quux/corge/bar
/quux/corge/baz
/quux/corge/qux
/quux/corge/grault
/quux/corge/garply
/quux/grault/foo
/quux/grault/bar
/quux/grault/baz
/quux/grault/qux
/quux/grault/corge
/quux/grault/garply
/quux/garply/foo
/quux/garply/bar
/quux/garply/baz
/quux/garply/qux
/quux/garply/corge
/quux/garply/grault
/corge/foo/bar
/corge/foo/baz
/corge/foo/qux
/corge/foo/quux
/corge/foo/grault
/corge/foo/garply
/corge/bar/foo
/corge/bar/baz
/corge/bar/qux
/corge/bar/quux
/corge/bar/grault
/corge/bar/garply
/corge/baz/foo
/corge/baz/bar
/corge/baz/qux
/corge/baz/quux
/corge/baz/grault
/corge/baz/garply
/corge/qux/foo
/corge/qux/bar
/corge/qux/baz
/corge/qux/quux
/corge/qux/grault
/corge/qux/garply
/corge/quux/foo
/corge/quux/bar
/corge/quux/baz
/corge/quux/qux
/corge/quux/grault
/corge/quux/garply
/corge/grault/foo
/corge/grault/bar
/corge/grault/baz
/corge/grault/qux
/corge/grault/quux
/corge/grault/garply
/corge/garply/foo
/corge/garply/bar
/corge/garply/baz
/corge/garply/qux
/corge/garply/quux
/corge/garply/grault
/grault/foo/bar
/grault/foo/baz
/grault/foo/qux
/grault/foo/quux
/grault/foo/corge
/grault/foo/garply
/grault/bar/foo
/grault/bar/baz
/grault/bar/qux
/grault/bar/quux
/grault/bar/corge
/grault/bar/garply
/grault/baz/foo
/grault/baz/bar
/grault/baz/qux
/grault/baz/quux
/grault/baz/corge
/grault/baz/garply
/grault/qux/foo
/grault/qux/bar
/grault/qux/baz
/grault/qux/quux
/grault/qux/corge
/grault/qux/garply
/grault/quux/foo
/grault/quux/bar
/grault/quux/baz
/grault/quux/qux
/grault/quux/corge
/grault/quux/garply
/grault/corge/foo
/grault/corge/bar
/grault/corge/baz
/grault/corge/qux
/grault/corge/quux
/grault/corge/garply
/grault/garply/foo
/grault/garply/bar
/grault/garply/baz
/grault/garply/qux
/grault/garply/quux
/grault/garply/corge
/garply/foo/bar
/garply/foo/baz
/garply/foo/qux
/garply/foo/quux
/garply/foo/corge
/garply/foo/grault
/garply/bar/foo
/garply/bar/baz
/garply/bar/qux
/garply/bar/quux
/garply/bar/corge
/garply/bar/grault
/garply/baz/foo
/garply/baz/bar
/garply/baz/qux
/garply/baz/quux
/garply/baz/corge
/garply/baz/grault
/garply/qux/foo
/garply/qux/bar
/garply/qux/baz
/garply/qux/quux
/garply/qux/corge
/garply/qux/grault
/garply/quux/foo
/garply/quux/bar
/garply/quux/baz
/garply/quux/qux
/garply/quux/corge
/garply/quux/grault
/garply/corge/foo
/garply/corge/bar
/garply/corge/baz
/garply/corge/qux
/garply/corge/quux
/garply/corge/grault
/garply/grault/foo
/garply/grault/bar
/garply/grault/baz
/garply/grault/qux
/garply/grault/quux
/garply/grault/corge
r3-1.3.4/bench_str.csv000066400000000000000000000457641262260041500145450ustar00rootroot000000000000001400242718,5649455.80 1400242784,5775186.12 1400242814,5653481.02 1400242868,5857187.70 1400242938,5732228.92 1400243193,5959689.05 1400243423,5717292.34 1400243528,5669803.44 1400243702,5880318.26 1400243875,5789509.57 1400243912,5889038.56 1400243951,5922317.92 1400243971,6069795.56 1400243982,5904973.70 1400243985,5888983.99 1400244196,5174852.68 1400244284,5821697.95 1400244307,6012282.29 1400244516,5929306.97 1400244550,5858897.69 1400244556,5998727.11 1400244574,5846792.25 1400244592,5930319.69 1400244599,5910137.48 1400244639,5936452.01 1400244648,5978607.43 1400244653,5956364.63 1400244657,5911318.61 1400244829,6362496.45 1400244887,6330902.59 1400244895,6390983.42 1400244908,6380415.58 1400244914,6346830.19 1400244932,6610181.08 1400245102,6404550.11 1400245168,6085174.66 1400245176,6400679.76 1400245216,6416409.15 1400245227,6485899.37 1400245230,5862573.02 1400245233,6526163.60 1400245281,6205337.09 1400245289,6217947.43 1400245311,6423151.81 1400251162,5826610.20 1400251172,6039034.62 1400251256,6219533.32 1400251264,6015717.76 1400278620,5733465.40 1400279249,6306920.57 1400282602,11775983.90 1400282802,11627473.22 1400282839,10222898.61 1400282930,11960583.69 1400283101,11659005.75 1400283479,11578012.31 1400283485,10742869.09 1400283755,11545078.70 1400284307,11493777.72 1400370342,11414560.92 1400370407,10759059.85 1400370448,10686226.48 1400370672,10532221.14 1400370683,10874340.04 1400370920,11307031.13 1400371092,11106355.37 1400371132,11313608.81 1400371165,10266146.59 1400371326,10644609.51 1400371371,10958943.43 1400371431,10145302.26 1400371504,11383090.96 1400371511,10023676.85 1400371561,10912042.58 1400371589,11439666.09 1400371602,11012616.42 1400371709,11058171.50 1400371751,11091926.38 1400371943,11103873.79 1400372774,10613683.19 1400372795,11841766.62 1400372820,12690699.18 1400372836,11596848.23 1400372848,11541418.97 1400372904,12034679.40 1400372910,12755936.07 1400373185,13716181.30 1400374415,13164892.40 1400382244,12226293.04 1400382299,11775631.24 1400382382,12331702.88 1400382578,13521992.76 1400382591,12607054.51 1400382780,12319337.31 1400382819,12453653.04 1400385205,13620526.43 1400385278,12130720.00 1400385318,13755788.28 1400385481,12663400.57 1400385502,12667686.69 1400385515,13077823.94 1400385528,13333901.32 1400385535,11961732.08 1400385563,12910309.71 1400385616,12105227.61 1400385713,13601851.15 1400385728,13344674.03 1400385734,13685060.22 1400385774,13223631.32 1400385951,11001406.94 1400386286,10682057.04 1400386296,11152665.22 1400386480,10908179.24 1400386496,11514008.98 1400386505,11172976.25 1400386731,11184613.82 1400387044,10760384.75 1400387138,10813584.63 1400387154,10825571.07 1400387176,9958256.23 1400387232,11035725.37 1400387264,11006703.61 1400387291,11123431.08 1400387303,10762934.26 1400387318,10842286.92 1400387384,10651069.93 1400387532,11055554.04 1400387761,10803251.35 1400387926,10854580.56 1400388003,11099634.54 1400388313,11132551.99 1400388338,11139229.93 1400388369,10898128.85 1400388529,10815527.23 1400388539,10930897.10 1400388591,10720695.10 1400388676,10571166.21 1400388683,10882166.49 1400388712,11008826.02 1400388799,10728815.96 1400388848,10409083.22 1400388867,10470546.30 1400388931,10554179.23 1400388944,10969249.80 1400388966,10116208.17 1400389070,11138537.72 1400389087,10874695.29 1400389125,10358558.63 1400389184,10999293.17 1400389215,10781509.38 1400389227,10347289.13 1400389233,10851573.79 1400389241,10631550.45 1400389267,10864289.97 1400389287,11080291.51 1400389343,11017300.69 1400389511,11126324.77 1400393822,10834745.34 1400393905,10709222.20 1400394012,10213843.65 1400394020,10789186.08 1400394033,10376120.72 1400394043,10870636.70 1400394050,10627263.79 1400394080,10766286.36 1400394087,10864430.68 1400394095,11008891.52 1400394100,10578167.34 1400394266,10622702.57 1400394385,10413209.43 1400394571,8615372.65 1400394590,10964999.94 1400394658,11173658.86 1400395575,10502560.60 1400396023,10925991.89 1400396031,10299722.97 1400396055,10781849.35 1400396123,10746610.69 1400396341,10811271.16 1400396368,10631572.01 1400396396,10442039.18 1400396467,10833155.84 1400396500,10639776.08 1400396541,9454881.65 1400396547,10795847.32 1400396725,10488850.71 1400396745,10442025.32 1400396765,10689592.72 1400406039,11164926.18 1400406130,10852846.69 1400406200,9606388.04 1400406388,10630125.97 1400406712,10901099.14 1400406757,10977776.63 1400406780,10923630.07 1400406834,10665256.26 1400406846,10841057.59 1400406860,10987088.01 1400406868,10991821.64 1400406881,11040200.72 1400406887,11491514.59 1400406950,10874497.93 1400407239,11002642.12 1400407250,10744268.90 1400407276,11144966.17 1400407292,10470853.00 1400407305,10632588.97 1400407323,11275701.84 1400407364,10827173.25 1400407380,11232917.51 1400407384,10892217.62 1400407454,10793665.50 1400407490,11078867.15 1400407498,10995093.02 1400407520,10914505.42 1400407544,10139300.12 1400407549,11140837.53 1400407572,11242381.65 1400407586,10545015.96 1400407832,11318167.86 1400407846,11412502.78 1400407864,10788301.74 1400408080,10813960.08 1400408117,11053281.53 1400408148,10925976.71 1400408157,10866706.90 1400408486,10438246.84 1400408495,10637030.99 1400408503,10998237.54 1400408743,10746673.10 1400408973,10696597.06 1400409590,10747379.89 1400409621,10925100.16 1400409674,10243836.44 1400409691,10938038.79 1400409739,10663533.54 1400409845,11063203.93 1400409863,11118679.72 1400410121,10935751.60 1400410132,10839286.96 1400410167,10427826.47 1400410180,10851581.27 1400410252,11133237.55 1400410283,10618062.83 1400410318,10166831.58 1400410399,11007341.02 1400410441,10929677.98 1400410704,10685427.91 1400411026,11125022.32 1400411267,10710017.05 1400411298,10809190.81 1400411322,10574819.37 1400411340,10536563.80 1400411381,10703727.13 1400411406,10814145.96 1400411717,10680938.12 1400411829,11149498.96 1400411833,11062632.01 1400411856,9571612.03 1400411876,11221957.84 1400411895,10599710.42 1400411903,10817749.52 1400412670,10728801.32 1400412684,10962187.64 1400412708,11267224.66 1400412723,10857559.01 1400412770,8906644.57 1400412827,10953246.38 1400412838,10923438.51 1400412848,11015834.62 1400412895,11344942.77 1400412944,10841369.57 1400412949,11040353.77 1400412961,11156072.62 1400412966,10831108.08 1400412981,10884440.74 1400413003,10862551.12 1400413012,10582158.17 1400413058,10546292.20 1400413092,10922604.09 1400413230,11067709.38 1400413269,10410991.73 1400413317,10980282.65 1400413354,10964929.24 1400413388,10650346.91 1400413435,11113745.92 1400413458,11146293.04 1400413550,10472731.92 1400413559,11177595.40 1400413586,10852453.55 1400413660,10108857.97 1400413696,10929343.81 1400413713,10824792.50 1400413729,10115599.85 1400413766,10973125.90 1400413779,9519723.81 1400413806,10690956.88 1400413819,11268613.09 1400414037,11204556.58 1400414053,10782873.08 1400414061,10921441.80 1400414081,11191230.95 1400414123,10777241.27 1400414133,11087850.62 1400414141,10921616.22 1400414173,11040258.84 1400414317,11319968.07 1400414342,10822736.73 1400414355,11015188.51 1400414389,8485410.70 1400414457,11241764.95 1400414479,11088645.99 1400414501,10750962.96 1400414556,11007510.49 1400414587,10903071.42 1400415353,10705889.14 1400415397,11505319.20 1400465549,13249817.73 1400465650,13467612.96 1400465723,13269768.49 1400465767,13374884.38 1400465776,13440016.82 1400465836,13386592.12 1400465865,13137081.39 1400465878,13376710.05 1400465928,13251983.44 1400466198,13359933.76 1400466833,13166545.46 1400466875,13515485.94 1400467139,13047096.38 1400467481,13594764.91 1400468648,13474532.60 1400570358,16277787.44 1400570442,16505301.07 1400570494,16651367.19 1400570540,16509970.21 1400571025,16271291.64 1400571045,16347991.85 1400571109,16051262.35 1400571116,16000716.18 1400571171,15655022.26 1400571314,15695138.73 1400571328,15779592.30 1400571446,16173358.85 1400571511,15816846.60 1400571580,15165532.41 1400571819,15473025.62 1400571872,14901576.43 1400571879,14751988.30 1400571889,15028402.84 1400571925,13450622.41 1400571993,13276463.85 1400572069,13113355.08 1400572160,13281786.31 1400573791,13580509.03 1400573832,10555723.33 1400573839,10582884.42 1400573847,10478482.69 1400573855,15087645.17 1400573891,15207920.79 1400592138,13289883.29 1400592160,13689866.38 1400592167,13887614.50 1400592181,12902438.30 1400592212,12711239.59 1400592282,13868279.63 1400592287,14008688.28 1400592314,13915819.27 1400592447,13857005.45 1400592453,13737673.35 1400592520,13746939.61 1400592698,13522088.67 1400592756,14069856.66 1400592898,13964804.85 1400592906,12335090.17 1400592931,14145688.00 1400592964,13071020.50 1400593034,13921007.60 1400593050,12790569.45 1400593062,13672159.26 1400593069,13522175.86 1400593171,13911803.66 1400593186,13788854.92 1400593197,13978543.79 1400593210,13568445.16 1400593219,13704926.07 1400599508,13991454.07 1400599553,13826120.84 1400599756,12099437.82 1400599972,13982492.37 1400600045,13977543.80 1400600057,13901438.41 1400600326,14049707.03 1400600677,13384789.38 1400600754,13649118.34 1400601224,13742996.84 1400603778,13736212.66 1400603800,13715365.00 1400603827,12742770.05 1400604427,13725403.62 1400604504,13787120.46 1400604527,13505264.87 1400604546,13522321.17 1400605108,13746963.64 1400605113,13899221.05 1400605117,13066929.36 1400605122,13818325.58 1400605132,13624101.24 1400605227,12992570.34 1400605241,13631407.12 1400605247,13773296.72 1400605254,13601113.09 1400605334,13477173.69 1400605341,13528406.95 1400605371,13822120.38 1400605378,13627925.89 1400605452,13704460.37 1400605482,13612516.46 1400605625,12647482.46 1400605676,13671799.76 1400605706,13269956.01 1400605735,13684822.09 1400605834,13635682.11 1400606038,13788132.68 1400606140,13834040.49 1400606400,13665833.66 1400606404,13519944.18 1400606406,13923000.83 1400606409,13742645.62 1400606411,13878225.03 1400606451,13922301.44 1400606491,14030387.83 1400606523,13157029.51 1400606567,13999364.95 1400607671,13906437.74 1400607682,13828950.20 1400607689,13932349.19 1400607695,13583203.56 1400607698,13630627.45 1400607700,13972490.11 1400659046,19754150.71 1400668268,13174604.57 1400668574,13632260.72 1400681414,10832905.89 1400685490,13185955.87 1400762875,10472029.42 1400764426,10066458.45,1590373.41 1400765068,10657617.64,2131810.12 1400766518,10259200.94,1878279.25,96697.86 1400766623,11057429.08,2113683.19,95835.70 1400815975,11316714.26,2165050.14,55188.21 1400815990,10826986.93,1780938.43,55188.21 1400816005,10584527.76,1707721.44,55924.05 1400816427,9376611.56,2006568.41,53092.46 1400816438,9096902.53,2108994.21,59074.70 1400816448,9260790.48,2131479.91,55188.21 1400816458,9303957.38,2110797.39,55924.05 1400816525,9330370.85,1985782.06,59074.70 1400816594,9389101.94,1989498.64,34663.67 1400816645,9201251.49,2105517.01,43240.25 1400816815,9228390.29,2097606.06,23301.69 1400817268,9242018.45,2109706.16,38479.85 1400817280,9320308.27,1891100.64,47662.55 1400817392,6448229.88,1994875.02,34663.67 1400817671,8654311.52,2094510.75,47662.55 1400817706,9362050.27,1981074.38,62601.55 1400818067,9247601.69,1944615.34,35848.75 1400818654,10797650.12,2550647.32,52428.80 1400818717,10964008.21,2607023.59,59074.70 1400818725,11160125.46,2574373.69,47127.01 1400818732,10829199.02,2557782.44,67650.06 1400818739,10859734.88,2538368.71,41527.76 1400820693,12547680.62,2375764.20,55924.05 1400820703,12815067.19,2375474.47,34379.54 1400820719,11693810.54,2231143.55,47662.55 1400820728,12612875.15,2357108.19,49932.19 1400820868,12158497.75,2598723.80,62601.55 1400820877,12254639.62,2583601.86,77672.30 1400820886,12274457.34,2393445.83,55188.21 1400820922,12218386.22,2604565.56,77672.30 1400820933,12443155.46,2361317.46,45590.26 1400829105,12110496.08,4797414.85,38479.85 1400829117,12258758.55,4129968.45,59074.70 1400829143,12339827.27,4775224.01,55924.05 1400831278,11421287.15,4742488.93,39945.75 1400832805,11676305.28,4832961.50,58254.22 1400832811,11785948.52,4137657.27,45590.26 1400832831,11918383.46,4859275.06,47662.55 1400832837,11650937.22,4734982.85,61680.94 1400832892,11728021.34,4274247.24,45590.26 1400832912,11580034.68,4752494.99,62601.55 1400833017,11890578.32,4501803.27,29330.80 1400833024,11715363.55,4726544.41,59074.70 1400833045,11813359.08,4828190.72,53092.46 1400833051,11082009.03,4721512.49,62601.55 1400837501,11958680.82,4777890.52,45590.26 1400837621,11423775.75,4679207.46,59074.70,2459430.07 1400837636,11534281.98,4192617.73,66576.25,2968590.57 1400837657,11693260.66,4815393.82,77672.30,2856236.96 1400837667,11834338.05,4822006.81,47662.55,3015821.63 1400837677,11999462.15,4854783.73,49932.19,3008349.32 1400837696,11814938.63,4740948.30,55188.21,3007002.06 1400837706,11535595.30,4712420.14,62601.55,2865728.03 1400837716,11928552.18,4833449.01,35848.75,2990344.18 1400837725,11873673.72,4275934.73,45590.26,3024045.98 1400837735,11805064.50,4855078.95,47662.55,3016256.98 1400837744,12041094.07,4815428.09,61680.94,2991090.14 1400837754,11766504.83,4848425.07,47662.55,2986385.66 1400837764,11979089.24,4257134.48,47662.55,3015693.70 1400837774,11190990.08,4331119.44,45590.26,2587281.10 1400837785,10306507.50,3909290.89,47662.55,2827471.10 1400837797,10323334.38,4221122.48,55924.05,2294463.55 1400922358,11238818.94,4585324.58,59074.70,2649691.23 1400922668,10605016.95,4435942.19,52428.80,2805666.62 1400922931,10906416.86,4595485.60,55924.05,2744562.44 1400922941,11009432.85,4532428.61,47662.55,2763157.51 1400922951,11053192.20,4323815.83,45590.26,2783158.56 1400922974,10151535.91,3794968.57,47662.55,2474383.18 1400922986,10218555.01,3887695.21,53092.46,2200366.58 1400922997,10051469.51,4460938.45,59074.70,2490310.13 1400923283,11180779.62,4365911.08,71089.90,2629220.52 1400923294,11193863.27,4516227.63,82241.25,2545079.35 1400923304,11423045.65,4137604.47,47662.55,2655584.06 1400923315,10840939.91,4663256.98,55924.05,2611667.47 1400923325,11091416.01,4103660.70,59074.70,2817256.97 1400923335,11435046.07,4356917.52,45100.04,2883103.51 1400928121,11717285.79,4816672.70,58254.22,2897866.52 1400928131,11343621.37,4759351.32,45100.04,2849262.65 1400928141,11268332.55,4717279.18,55188.21,2871378.81 1400928151,11308055.40,4652350.21,47662.55,2866742.89 1400928225,10802915.60,4687267.34,58254.22,2632936.94 1400928235,10661874.62,4739682.52,62601.55,2740810.88 1400928262,11033784.15,4714416.68,55188.21,2737984.12 1400928272,10649279.69,4567955.12,47662.55,2716598.01 1400928319,10230059.66,4527332.79,49932.19,2345303.39 1400928329,11085172.21,4647514.08,62601.55,2735715.15 1400929424,11030888.11,4442984.66,55924.05,2892178.39 1400929434,11544517.30,4792322.97,77672.30,2718374.75 1400929444,11729287.31,4167112.20,47662.55,2880342.59 1401713584,11611550.10,3615349.83,59074.70,2395398.52 1401713613,11497337.95,3867069.72,76260.07,2513425.94 1401713624,11012180.78,4218063.79,62601.55,2274326.51 1401713638,10375230.94,3665431.16,59074.70,1995737.34 1401713649,11430757.90,3840336.12,62601.55,2385432.38 1401713661,8970219.06,4509359.41,62601.55,2278745.62 1401713673,11040727.70,3743492.87,55188.21,2408080.74 1401785936,11348169.84,4097861.38,77672.30,2199971.87 1401785947,11312609.98,3904129.33,77672.30,2560323.79 1401785958,10537229.10,4396861.86,58254.22,2424404.69 1401785969,11206290.89,4517530.60,45100.04,2551294.60 1401785980,11248534.36,4396504.83,45100.04,2262115.57 1401785991,11198475.79,4330140.21,47662.55,2628625.68 1401786002,11160024.50,4168595.71,59074.70,2536134.48 1401786013,10430212.17,4125745.93,45590.26,2506666.43 1401786024,10213079.29,4298993.08,45100.04,2533248.03 1401786035,10579681.12,4386844.66,37117.73,2541278.85 1401882943,11243814.21,3713601.99,71089.90,2059566.22 1401882981,11134212.84,4231286.57,53092.46,2180900.77 1401882993,10950888.02,4182279.39,53092.46,2164511.15 1401883005,11123999.47,3725357.71,76260.07,2211605.54 1401883017,10773686.78,3988825.00,45590.26,2256792.94 1401883041,10991057.38,4192016.84,55924.05,2164285.17 1401883053,11253995.23,4111639.22,45100.04,2096238.88 1401883388,11153576.69,4347093.92,76260.07,2205268.76 1401883411,11501180.01,4506130.97,58254.22,2243712.66 1401883422,11156015.26,4540579.82,47662.55,2279418.81 1401883445,11195098.22,4455873.90,38479.85,2267750.98 1401883468,11467197.28,4422749.94,72315.59,2289153.70 1401883480,11087024.10,4312175.00,55188.21,2296830.48 1401925287,11654811.40,4536210.26,72315.59,2379382.00 1401925299,11573243.70,3894464.26,59074.70,2276455.83 1401925310,11944273.21,4666625.62,62601.55,2304322.33 1401925322,11775622.43,3945455.94,43690.67,2149656.21 1401925333,11539429.12,4630751.73,43240.25,2270121.49 1401925344,11312437.08,4589657.39,62601.55,2329731.93 1401926595,11633680.46,4701904.00,55924.05,2410241.02 1401926639,11630837.25,3933338.77,55924.05,2346259.71 1401926649,11822018.52,4686898.26,76260.07,2419184.30 1401926661,11800543.07,4196806.70,71089.90,2295282.55 1401926673,10529846.71,3931058.57,49932.19,2165044.18 1401926686,10117457.56,3362173.28,55924.05,1994411.93 1401926711,11029110.99,4353057.39,49932.19,2239772.42 1401926725,10862072.89,2750694.08,32263.88,2104475.43 1402402553,11294194.69,4189904.32,49932.19,2123185.29 1402402565,11164650.78,4006360.04,55924.05,2049352.49 1402402578,9943455.54,3781047.14,45590.26,2166878.84 1447151242,13847614.65,5481111.96,66576.25,2528296.71 1447151252,13478094.70,5762300.49,99864.38,2467814.73 1447151261,13318275.24,5669995.06,91180.52,2528263.08 1447151271,13328641.49,5792107.41,62601.55,2534213.23 1447151281,13603554.01,5690401.12,52428.80,2533696.10 1447151291,13893573.36,5447950.39,66576.25,2532335.35 1447151303,13091255.94,3616732.34,62601.55,2227987.21 1447151314,11690373.06,4497110.65,91180.52,2136426.50 1447151325,13580596.98,4134246.08,91180.52,2373758.39 1447151335,13974417.41,5615391.00,59074.70,2507497.84 1447152253,13474619.18,4825849.40,49932.19,2424468.13 1447152263,12626952.28,5517283.96,49932.19,2459678.52 1447152273,13712806.08,5401932.71,91180.52,2531766.93 1447152286,13674890.28,5105976.43,91180.52,1637699.37 1447152296,12598276.86,5621295.29,91180.52,2265631.05 1447152307,13427458.88,5257266.07,24966.10,2309148.88 1447152317,13658739.92,5880717.85,62601.55,2403685.89 1447152327,13697028.28,5704775.21,91180.52,2397147.59 1447152337,13854967.00,5598234.96,43690.67,2516441.18 1447152348,13446160.91,4623962.27,91180.52,2349433.72 1447154320,13805978.08,5843317.38,66576.25,2529583.04 1447154330,13794992.46,5866609.62,89240.51,2479643.35 1447154340,12999574.36,5870781.62,83886.08,2565547.20 1447154349,13813759.40,5896996.47,59074.70,2577608.73 1447154359,13646711.36,5716116.84,47662.55,2574703.24 1447154368,13664364.46,5873110.25,41527.76,2502096.76 1447154378,13345158.07,5929994.94,66576.25,2526050.75 1447154388,13619724.42,5891895.35,66576.25,2542931.44 1447154397,13274559.00,5736176.87,66576.25,2538733.05 1447154407,13445232.76,5381001.80,89240.51,2576233.33 1447155008,13277391.26,5722360.39,71089.90,2475000.02 1447155019,13581101.21,5484972.04,45100.04,2192286.64 1447155029,13116025.99,5830570.40,52428.80,2522486.73 1447155066,13645222.60,5724509.20,62601.55,2514659.99 1447155349,11915902.67,5912124.62,58254.22,2421361.02 1447155679,13951049.58,5897239.13,26379.27,2527577.97 1447155699,13781189.15,5851252.25,62601.55,2539751.33 1447156053,13415522.24,5930072.07,82241.25,2533834.67 1447156073,13492327.24,5848589.68,52428.80,2567896.99 1447156411,13229275.90,5858750.37,66576.25,2523350.73 1447156432,13556025.90,5873947.56,62601.55,2487130.01 1447156745,13744909.39,5913103.69,66576.25,2551782.92 r3-1.3.4/cmake/000077500000000000000000000000001262260041500131215ustar00rootroot00000000000000r3-1.3.4/cmake/FindCheck.cmake000066400000000000000000000033201262260041500157370ustar00rootroot00000000000000# - Try to find the CHECK libraries # Once done this will define # # CHECK_FOUND - system has check # CHECK_INCLUDE_DIRS - the check include directory # CHECK_LIBRARIES - check library # # Copyright (c) 2007 Daniel Gollub # Copyright (c) 2007-2009 Bjoern Ricks # # Redistribution and use is allowed according to the terms of the New # BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. INCLUDE( FindPkgConfig ) IF ( Check_FIND_REQUIRED ) SET( _pkgconfig_REQUIRED "REQUIRED" ) ELSE( Check_FIND_REQUIRED ) SET( _pkgconfig_REQUIRED "" ) ENDIF ( Check_FIND_REQUIRED ) IF ( CHECK_MIN_VERSION ) PKG_SEARCH_MODULE( CHECK ${_pkgconfig_REQUIRED} check>=${CHECK_MIN_VERSION} ) ELSE ( CHECK_MIN_VERSION ) PKG_SEARCH_MODULE( CHECK ${_pkgconfig_REQUIRED} check ) ENDIF ( CHECK_MIN_VERSION ) # Look for CHECK include dir and libraries IF( NOT CHECK_FOUND AND NOT PKG_CONFIG_FOUND ) FIND_PATH( CHECK_INCLUDE_DIRS check.h ) FIND_LIBRARY( CHECK_LIBRARIES NAMES check ) IF ( CHECK_INCLUDE_DIRS AND CHECK_LIBRARIES ) SET( CHECK_FOUND 1 ) IF ( NOT Check_FIND_QUIETLY ) MESSAGE ( STATUS "Found CHECK: ${CHECK_LIBRARIES}" ) ENDIF ( NOT Check_FIND_QUIETLY ) ELSE ( CHECK_INCLUDE_DIRS AND CHECK_LIBRARIES ) IF ( Check_FIND_REQUIRED ) MESSAGE( FATAL_ERROR "Could NOT find CHECK" ) ELSE ( Check_FIND_REQUIRED ) IF ( NOT Check_FIND_QUIETLY ) MESSAGE( STATUS "Could NOT find CHECK" ) ENDIF ( NOT Check_FIND_QUIETLY ) ENDIF ( Check_FIND_REQUIRED ) ENDIF ( CHECK_INCLUDE_DIRS AND CHECK_LIBRARIES ) ENDIF( NOT CHECK_FOUND AND NOT PKG_CONFIG_FOUND ) # Hide advanced variables from CMake GUIs MARK_AS_ADVANCED( CHECK_INCLUDE_DIRS CHECK_LIBRARIES ) r3-1.3.4/cmake/FindJemalloc.cmake000066400000000000000000000021741262260041500164560ustar00rootroot00000000000000# - Try to find jemalloc headers and libraries. # # Usage of this module as follows: # # find_package(JeMalloc) # # Variables used by this module, they can change the default behaviour and need # to be set before calling find_package: # # JEMALLOC_ROOT_DIR Set this variable to the root installation of # jemalloc if the module has problems finding # the proper installation path. # # Variables defined by this module: # # JEMALLOC_FOUND System has jemalloc libs/headers # JEMALLOC_LIBRARIES The jemalloc library/libraries # JEMALLOC_INCLUDE_DIR The location of jemalloc headers find_path(JEMALLOC_ROOT_DIR NAMES include/jemalloc/jemalloc.h ) find_library(JEMALLOC_LIBRARIES NAMES jemalloc HINTS ${JEMALLOC_ROOT_DIR}/lib ) find_path(JEMALLOC_INCLUDE_DIR NAMES jemalloc/jemalloc.h HINTS ${JEMALLOC_ROOT_DIR}/include ) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(JeMalloc DEFAULT_MSG JEMALLOC_LIBRARIES JEMALLOC_INCLUDE_DIR ) mark_as_advanced( JEMALLOC_ROOT_DIR JEMALLOC_LIBRARIES JEMALLOC_INCLUDE_DIR ) r3-1.3.4/cmake/FindJudy.cmake000066400000000000000000000025321262260041500156410ustar00rootroot00000000000000# Copyright (C) 2007-2009 LuaDist. # Created by Peter Kapec # Redistribution and use of this file is allowed according to the terms of the MIT license. # For details see the COPYRIGHT file distributed with LuaDist. # Note: # Searching headers and libraries is very simple and is NOT as powerful as scripts # distributed with CMake, because LuaDist defines directories to search for. # Everyone is encouraged to contact the author with improvements. Maybe this file # becomes part of CMake distribution sometimes. # - Find judy # Find the native Judy headers and libraries. # # Judy_INCLUDE_DIRS - where to find judy.h, etc. # Judy_LIBRARIES - List of libraries when using judy. # Judy_FOUND - True if judy found. # Look for the header file. FIND_PATH(Judy_INCLUDE_DIR NAMES Judy.h) # Look for the library. FIND_LIBRARY(Judy_LIBRARY NAMES judy) # Handle the QUIETLY and REQUIRED arguments and set Judy_FOUND to TRUE if all listed variables are TRUE. INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Judy DEFAULT_MSG Judy_LIBRARY Judy_INCLUDE_DIR) # Copy the results to the output variables. IF(Judy_FOUND) SET(Judy_LIBRARIES ${Judy_LIBRARY}) SET(Judy_INCLUDE_DIRS ${Judy_INCLUDE_DIR}) ELSE(Judy_FOUND) SET(Judy_LIBRARIES) SET(Judy_INCLUDE_DIRS) ENDIF(Judy_FOUND) MARK_AS_ADVANCED(Judy_INCLUDE_DIRS Judy_LIBRARIES) r3-1.3.4/cmake/FindPCRE.cmake000066400000000000000000000025321262260041500154570ustar00rootroot00000000000000# Copyright (C) 2007-2009 LuaDist. # Created by Peter Kapec # Redistribution and use of this file is allowed according to the terms of the MIT license. # For details see the COPYRIGHT file distributed with LuaDist. # Note: # Searching headers and libraries is very simple and is NOT as powerful as scripts # distributed with CMake, because LuaDist defines directories to search for. # Everyone is encouraged to contact the author with improvements. Maybe this file # becomes part of CMake distribution sometimes. # - Find pcre # Find the native PCRE headers and libraries. # # PCRE_INCLUDE_DIRS - where to find pcre.h, etc. # PCRE_LIBRARIES - List of libraries when using pcre. # PCRE_FOUND - True if pcre found. # Look for the header file. FIND_PATH(PCRE_INCLUDE_DIR NAMES pcre.h) # Look for the library. FIND_LIBRARY(PCRE_LIBRARY NAMES pcre) # Handle the QUIETLY and REQUIRED arguments and set PCRE_FOUND to TRUE if all listed variables are TRUE. INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(PCRE DEFAULT_MSG PCRE_LIBRARY PCRE_INCLUDE_DIR) # Copy the results to the output variables. IF(PCRE_FOUND) SET(PCRE_LIBRARIES ${PCRE_LIBRARY}) SET(PCRE_INCLUDE_DIRS ${PCRE_INCLUDE_DIR}) ELSE(PCRE_FOUND) SET(PCRE_LIBRARIES) SET(PCRE_INCLUDE_DIRS) ENDIF(PCRE_FOUND) MARK_AS_ADVANCED(PCRE_INCLUDE_DIRS PCRE_LIBRARIES) r3-1.3.4/configure.ac000066400000000000000000000074171262260041500143400ustar00rootroot00000000000000AC_INIT([r3], 1.3.3) AC_PREREQ([2.64]) AC_USE_SYSTEM_EXTENSIONS AC_CONFIG_HEADERS(config.h) AC_CONFIG_MACRO_DIR([m4]) AM_SILENT_RULES([yes]) AM_INIT_AUTOMAKE([foreign subdir-objects]) LT_INIT AC_PROG_CC AC_PROG_CC_STDC AC_PROG_CXX AC_PROG_INSTALL # older debian AC_PROG_LIBTOOL AM_PROG_CC_C_O AC_CHECK_HEADERS([stdlib.h string.h sys/time.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_TYPE_SIZE_T # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([gettimeofday memset strchr strdup strndup strstr]) PKG_PROG_PKG_CONFIG AC_ARG_ENABLE([gcov], [AS_HELP_STRING([--enable-gcov], [use Gcov to test the test suite])], [], [enable_gcov=no]) AM_CONDITIONAL([COND_GCOV],[test '!' "$enable_gcov" = no]) AC_ARG_WITH([malloc], AS_HELP_STRING([--without-malloc], [Use the default malloc])) AS_IF([test "x$with_malloc" == "xjemalloc"], [AC_CHECK_HEADERS([jemalloc/jemalloc.h], [ found_jemalloc=yes; break ])]) if test "x$found_jemalloc" == "xyes" ; then AC_MSG_CHECKING([Checking jemalloc version]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ #ifdef JEMALLOC_VERSION_MAJOR > 2 return 0; #endif return 1; ]])], [ AC_MSG_RESULT([yes]) AC_DEFINE_UNQUOTED([USE_JEMALLOC], 1, [Define to 1 if you have the PATH_MAX macro.]) have_jemalloc=yes ], [ AC_MSG_RESULT([no]) AC_DEFINE_UNQUOTED([USE_JEMALLOC], 0, [Define to 1 if you have the PATH_MAX macro.]) have_jemalloc=no ] ) fi AM_CONDITIONAL(USE_JEMALLOC, test "x$have_jemalloc" = "xyes") # AM_CONDITIONAL(USE_JEMALLOC, test "x$found_jemalloc" = "xyes") # AC_DEFINE(USE_JEMALLOC, test "x$found_jemalloc" = "xyes" , "use jemalloc") PKG_CHECK_MODULES(DEPS, [libpcre]) AC_SUBST(DEPS_CFLAGS) AC_SUBST(DEPS_LIBS) AC_ARG_ENABLE(debug,AS_HELP_STRING([--enable-debug],[enable debug])) if test "x$enable_debug" = "xyes"; then AC_DEFINE(DEBUG, 1, "debug") fi AM_CONDITIONAL(ENABLE_DEBUG, test "x$enable_debug" = "xyes") AC_ARG_ENABLE(graphviz, AS_HELP_STRING([--enable-graphviz],[enable graphviz support])) if test "x$enable_graphviz" = "xyes" ; then PKG_CHECK_MODULES(GVC_DEPS, [libgvc]) AC_SUBST(GVC_DEPS_CFLAGS) AC_SUBST(GVC_DEPS_LIBS) AC_DEFINE(ENABLE_GRAPHVIZ, 1, "whether graphviz is enable") fi AM_CONDITIONAL(ENABLE_GRAPHVIZ, test "x$enable_graphviz" = "xyes") AC_ARG_ENABLE(json, AS_HELP_STRING([--enable-json],[enable json encoder])) if test "x$enable_json" = "xyes"; then PKG_CHECK_MODULES(JSONC, [json-c]) AC_SUBST(JSONC_CFLAGS) AC_SUBST(JSONC_LIBS) AC_DEFINE(ENABLE_JSON, 1, [enable json]) fi AM_CONDITIONAL(ENABLE_JSON, test "x$enable_json" = "xyes") # This does not work because configure does not look into /opt/local/include... # AC_CHECK_HEADERS([check.h],[ enable_check=yes ],[ enable_check=unset ]) AC_ARG_ENABLE(check, AS_HELP_STRING([--enable-check], [enable unit testing]), , enable_check=unset) if test "x$enable_check" != "xunset" ; then PKG_CHECK_MODULES(CHECK,[check >= 0.9.4],:,[ ifdef([AM_PATH_CHECK], [AM_PATH_CHECK(,[have_check="yes"])], AC_MSG_WARN([Check not found; cannot run unit tests!]) [have_check="no"])] ]) fi AM_CONDITIONAL(HAVE_CHECK, test x"$have_check" = "xyes") AC_CONFIG_FILES([ r3.pc Makefile 3rdparty/Makefile src/Makefile tests/Makefile examples/Makefile ]) AC_OUTPUT r3-1.3.4/dist-debian/000077500000000000000000000000001262260041500142245ustar00rootroot00000000000000r3-1.3.4/dist-debian/changelog000066400000000000000000000002241262260041500160740ustar00rootroot00000000000000libr3 (1.3.1-1) unstable; urgency=low * Initial release using libr3 1.3.1. -- Ronmi Ren Thu, 12 Jun 2014 10:54:16 +0800 r3-1.3.4/dist-debian/compat000066400000000000000000000000021262260041500154220ustar00rootroot000000000000009 r3-1.3.4/dist-debian/control000066400000000000000000000016621262260041500156340ustar00rootroot00000000000000Source: libr3 Priority: optional Maintainer: Ronmi Ren Build-Depends: debhelper (>= 8.0.0), automake, autotools-dev, autoconf, libtool, libpcre3-dev, pkg-config, check Standards-Version: 3.9.4 Section: libs Homepage: https://github.com/c9s/r3 Package: libr3-dev Section: libdevel Architecture: any Depends: libr3 (= ${binary:Version}) Description: Development files for libr3 libr3 (https://github.com/c9s/r3) is an URL router library with high performance, thus, it's implemented in C. It compiles your route paths into a prefix trie. . This package contains header files for libr3. Package: libr3 Section: libs Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends} Description: High performance URL routing library written in C. libr3 (https://github.com/c9s/r3) is an URL router library with high performance, thus, it's implemented in C. It compiles your route paths into a prefix trie. r3-1.3.4/dist-debian/copyright000066400000000000000000000024541262260041500161640ustar00rootroot00000000000000Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: libr3 Source: https://github.com/c9s/r3 Files: * Copyright: 2014 yoanlin93@gmail.com License: MIT Files: debian/* Copyright: 2014 Ronmi Ren License: MIT License: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. r3-1.3.4/dist-debian/docs000066400000000000000000000000121262260041500150700ustar00rootroot00000000000000README.md r3-1.3.4/dist-debian/libr3-dev.dirs000066400000000000000000000000241262260041500166720ustar00rootroot00000000000000usr/lib usr/include r3-1.3.4/dist-debian/libr3-dev.install000066400000000000000000000001011262260041500173730ustar00rootroot00000000000000usr/include/* usr/lib/lib*.a usr/lib/lib*.so usr/lib/pkgconfig/* r3-1.3.4/dist-debian/libr3.dirs000066400000000000000000000000101262260041500161110ustar00rootroot00000000000000usr/lib r3-1.3.4/dist-debian/libr3.install000066400000000000000000000000221262260041500166210ustar00rootroot00000000000000usr/lib/lib*.so.* r3-1.3.4/dist-debian/rules000077500000000000000000000003341262260041500153040ustar00rootroot00000000000000#!/usr/bin/make -f # -*- makefile -*- # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 %: dh $@ --with autotools-dev override_dh_auto_configure: ./autogen.sh ./configure --enable-check --prefix=/usr r3-1.3.4/dist-debian/source/000077500000000000000000000000001262260041500155245ustar00rootroot00000000000000r3-1.3.4/dist-debian/source/format000066400000000000000000000000141262260041500167320ustar00rootroot000000000000003.0 (quilt) r3-1.3.4/examples/000077500000000000000000000000001262260041500136575ustar00rootroot00000000000000r3-1.3.4/examples/Makefile.am000066400000000000000000000005101262260041500157070ustar00rootroot00000000000000AM_CFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) -I$(top_builddir)/include -Wall -std=c99 AM_CXXFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) -I$(top_builddir)/include -Wall AM_LDFLAGS=$(DEPS_LIBS) $(GVC_DEPS_LIBS) $(top_builddir)/libr3.la noinst_PROGRAMS = simple simple_cpp simple_SOURCES = simple.c simple_cpp_SOURCES = simple_cpp.cpp r3-1.3.4/examples/simple.c000066400000000000000000000035671262260041500153270ustar00rootroot00000000000000/* * bench.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include #include #include "r3.h" int main() { node * n = r3_tree_create(3); r3_tree_insert_path(n, "/foo/bar/baz", NULL); r3_tree_insert_path(n, "/foo/bar/qux", NULL); r3_tree_insert_path(n, "/foo/bar/quux", NULL); r3_tree_insert_path(n, "/bar/foo/baz", NULL); r3_tree_insert_path(n, "/bar/foo/quux", NULL); r3_tree_insert_path(n, "/bar/garply/grault", NULL); r3_tree_insert_path(n, "/baz/foo/bar", NULL); r3_tree_insert_path(n, "/baz/foo/qux", NULL); r3_tree_insert_path(n, "/baz/foo/quux", NULL); r3_tree_insert_path(n, "/qux/foo/quux", NULL); r3_tree_insert_path(n, "/qux/foo/corge", NULL); r3_tree_insert_path(n, "/qux/foo/grault", NULL); r3_tree_insert_path(n, "/corge/quux/foo", NULL); r3_tree_insert_path(n, "/corge/quux/bar", NULL); r3_tree_insert_path(n, "/corge/quux/baz", NULL); r3_tree_insert_path(n, "/corge/quux/qux", NULL); r3_tree_insert_path(n, "/corge/quux/grault", NULL); r3_tree_insert_path(n, "/grault/foo/bar", NULL); r3_tree_insert_path(n, "/grault/foo/baz", NULL); r3_tree_insert_path(n, "/garply/baz/quux", NULL); r3_tree_insert_path(n, "/garply/baz/corge", NULL); r3_tree_insert_path(n, "/garply/baz/grault", NULL); r3_tree_insert_path(n, "/garply/qux/foo", NULL); char *errstr = NULL; int err = r3_tree_compile(n, &errstr); if(err) { printf("%s\n",errstr); free(errstr); return 1; } node *m; m = r3_tree_match(n , "/qux/bar/corge", NULL); match_entry * e = match_entry_createl("/garply/baz/grault", strlen("/garply/baz/grault") ); m = r3_tree_match_entry(n , e); if (m) { printf("Matched! %s\n", e->path); } match_entry_free(e); return 0; } r3-1.3.4/examples/simple_cpp.cpp000066400000000000000000000056121262260041500165220ustar00rootroot00000000000000#include #include #include #include using namespace std; void example_1() { // create a router tree with 10 children capacity (this capacity can grow dynamically) r3::Tree tree(10); // insert the route path into the router tree int route_data_1 = 1; tree.insert_path("/bar", &route_data_1); // ignore the length of path int route_data_2 = 2; tree.insert_pathl("/zoo", strlen("/zoo"), &route_data_2); int route_data_3 = 3; tree.insert_pathl("/foo/bar", strlen("/foo/bar"), &route_data_3); int route_data_4 = 4; tree.insert_pathl("/post/{id}", strlen("/post/{id}") , &route_data_4); int route_data_5 = 5; tree.insert_pathl("/user/{id:\\d+}", strlen("/user/{id:\\d+}"), &route_data_5); // if you want to catch error, you may call the extended path function for insertion int data = 10; char* errstr; r3::Node ret = tree.insert_pathl("/foo/{name:\\d{5}", strlen("/foo/{name:\\d{5}"), &data, &errstr); if (ret == NULL) { // failed insertion cout << "error: " << errstr << endl; free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // let's compile the tree! int err = tree.compile(&errstr); if (err != 0) { cout << "error: " << errstr << endl; free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // dump the compiled tree tree.dump(0); // match a route r3::Node matched_node = tree.matchl("/foo/bar", strlen("/foo/bar")); if (matched_node) { int ret = *static_cast(matched_node.data()); cout << "match path ret: " << ret << endl; } r3::MatchEntry entry("/foo/bar"); matched_node = tree.match_entry(entry); if (matched_node) { int ret = *static_cast(matched_node.data()); cout << "match entry ret: " << ret << endl; } } void example_2() { // create a router tree with 10 children capacity (this capacity can grow dynamically) r3::Tree tree(10); // insert the route path into the router tree int route_data = 1; tree.insert_routel(METHOD_GET | METHOD_POST, "/blog/post", sizeof("/blog/post") - 1, &route_data); char* errstr; int err = tree.compile(&errstr); if (err != 0) { cout << "errstr: " << errstr << endl; free(errstr); // errstr is created from `asprintf`, so you have to free it manually. } // in your http server handler // create the match entry for capturing dynamic variables. r3::MatchEntry entry("/blog/post"); entry.set_request_method(METHOD_GET); r3::Route matched_route = tree.match_route(entry); if (matched_route) { int ret = *static_cast(matched_route.data()); cout << "match route ret: " << ret << endl; } } int main() { example_1(); example_2(); return 0; } r3-1.3.4/gen_route_tests.rb000066400000000000000000000030231262260041500155750ustar00rootroot00000000000000#!/usr/bin/env ruby puts < #include #include #include #include "r3.h" #include "r3_str.h" #include "zmalloc.h" START_TEST (test_routes) { node * n = r3_tree_create(10); node * m = NULL; END arr = ["foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply"] paths = arr.permutation(3).map { |a| "/#{a.join '/'}" } paths.each_index do |idx| path = paths.fetch(idx) puts " char *data#{idx} = \"#{path}\";" puts " r3_tree_insert_path(n, \"#{path}\", (void*) data#{idx});" end puts <data == data#{idx});" puts " ck_assert(m->endpoint > 0);" end puts < * * Distributed under terms of the MIT license. */ #ifndef R3_NODE_H #define R3_NODE_H #include #include #include #include #include #include "r3_define.h" #include "str_array.h" #include "r3_str.h" #ifdef __cplusplus extern "C" { #endif struct _edge; struct _node; struct _route; typedef struct _edge edge; typedef struct _node node; typedef struct _route route; struct _node { edge ** edges; // edge ** edge_table; char * combined_pattern; pcre * pcre_pattern; // #ifdef PCRE_STUDY_JIT_COMPILE pcre_extra * pcre_extra; // #endif // edges are mostly less than 255 unsigned int edge_len; unsigned int compare_type; // compare_type: pcre, opcode, string unsigned char endpoint; // endpoint, should be zero for non-endpoint nodes unsigned char ov_cnt; // capture vector array size for pcre // almost less than 255 unsigned char edge_cap; unsigned char route_len; unsigned char route_cap; // <-- here comes a char[1] struct padding for alignment since we have 4 char above. /** compile-time variables here.... **/ /* the combined regexp pattern string from pattern_tokens */ route ** routes; /** * the pointer of route data */ void * data; }; #define r3_node_edge_pattern(node,i) node->edges[i]->pattern #define r3_node_edge_pattern_len(node,i) node->edges[i]->pattern_len struct _edge { char * pattern; // 8 bytes node * child; // 8 bytes unsigned int pattern_len; // 1 byte unsigned int opcode; // unsigned char opcode:4; // 4 bit unsigned char has_slug:1; // 1 bit }; struct _route { char * path; int path_len; int request_method; // can be (GET || POST) char * host; // required host name int host_len; void * data; char * remote_addr_pattern; int remote_addr_pattern_len; }; typedef struct { str_array * vars; const char * path; // current path to dispatch int path_len; // the length of the current path int request_method; // current request method void * data; // route ptr char * host; // the request host int host_len; char * remote_addr; int remote_addr_len; } match_entry; node * r3_tree_create(int cap); node * r3_node_create(); void r3_tree_free(node * tree); edge * r3_node_connectl(node * n, const char * pat, int len, int strdup, node *child); #define r3_node_connect(n, pat, child) r3_node_connectl(n, pat, strlen(pat), 0, child) edge * r3_node_find_edge(const node * n, const char * pat, int pat_len); void r3_node_append_edge(node *n, edge *child); edge * r3_node_find_common_prefix(node *n, const char *path, int path_len, int *prefix_len, char **errstr); node * r3_tree_insert_pathl(node *tree, const char *path, int path_len, void * data); #define r3_tree_insert_pathl(tree, path, path_len, data) r3_tree_insert_pathl_ex(tree, path, path_len, NULL , data, NULL) route * r3_tree_insert_routel(node *tree, int method, const char *path, int path_len, void *data); route * r3_tree_insert_routel_ex(node *tree, int method, const char *path, int path_len, void *data, char **errstr); #define r3_tree_insert_routel(n, method, path, path_len, data) r3_tree_insert_routel_ex(n, method, path, path_len, data, NULL) #define r3_tree_insert_path(n,p,d) r3_tree_insert_pathl_ex(n,p,strlen(p), NULL, d, NULL) #define r3_tree_insert_route(n,method,path,data) r3_tree_insert_routel(n, method, path, strlen(path), data) /** * The private API to insert a path */ node * r3_tree_insert_pathl_ex(node *tree, const char *path, int path_len, route * route, void * data, char ** errstr); void r3_tree_dump(const node * n, int level); edge * r3_node_find_edge_str(const node * n, const char * str, int str_len); int r3_tree_compile(node *n, char** errstr); int r3_tree_compile_patterns(node * n, char** errstr); node * r3_tree_matchl(const node * n, const char * path, int path_len, match_entry * entry); #define r3_tree_match(n,p,e) r3_tree_matchl(n,p, strlen(p), e) // node * r3_tree_match_entry(node * n, match_entry * entry); #define r3_tree_match_entry(n, entry) r3_tree_matchl(n, entry->path, entry->path_len, entry) bool r3_node_has_slug_edges(const node *n); edge * r3_edge_createl(const char * pattern, int pattern_len, node * child); node * r3_edge_branch(edge *e, int dl); void r3_edge_free(edge * edge); route * r3_route_create(const char * path); route * r3_route_createl(const char * path, int path_len); void r3_node_append_route(node * n, route * route); void r3_route_free(route * route); int r3_route_cmp(const route *r1, const match_entry *r2); route * r3_tree_match_route(const node *n, match_entry * entry); #define r3_route_create(p) r3_route_createl(p, strlen(p)) #define METHOD_GET 2 #define METHOD_POST 2<<1 #define METHOD_PUT 2<<2 #define METHOD_DELETE 2<<3 #define METHOD_PATCH 2<<4 #define METHOD_HEAD 2<<5 #define METHOD_OPTIONS 2<<6 int r3_pattern_to_opcode(const char * pattern, int pattern_len); enum { NODE_COMPARE_STR, NODE_COMPARE_PCRE, NODE_COMPARE_OPCODE }; enum { OP_EXPECT_MORE_DIGITS = 1, OP_EXPECT_MORE_WORDS, OP_EXPECT_NOSLASH, OP_EXPECT_NODASH, OP_EXPECT_MORE_ALPHA }; match_entry * match_entry_createl(const char * path, int path_len); #define match_entry_create(path) match_entry_createl(path,strlen(path)) void match_entry_free(match_entry * entry); #ifdef __cplusplus } #endif #endif /* !R3_NODE_H */ r3-1.3.4/include/r3.hpp000066400000000000000000000066211262260041500145260ustar00rootroot00000000000000/* * r3.hpp * Copyright (C) 2014 whitglint * * Distributed under terms of the MIT license. */ #ifndef R3_HPP #define R3_HPP #include #include namespace r3 { template class Base { public: Base(T* p) : p_(p) { } void* data() const { return p_->data; } T* get() const { return p_; } bool is_null() const { return p_ == NULL; } operator void*() const { return p_; } private: T* p_; }; typedef Base Node; typedef Base Route; class MatchEntry : public Base { public: explicit MatchEntry(const char* path) : Base(match_entry_create(path)) { } MatchEntry(const char* path, int path_len) : Base(match_entry_createl(path, path_len)) { } ~MatchEntry() { if (get()) { match_entry_free(get()); } } int request_method() const { return get()->request_method; } void set_request_method(int request_method) { get()->request_method = request_method; } private: MatchEntry(const MatchEntry&); MatchEntry& operator =(const MatchEntry&); }; class Tree : public Base { public: explicit Tree(int cap) : Base(r3_tree_create(cap)) { } ~Tree() { if (get()) { r3_tree_free(get()); } } int compile(char** errstr = NULL) { return r3_tree_compile(get(), errstr); } void dump(int level) const { r3_tree_dump(get(), level); } Node insert_path(const char* path, void* data, char** errstr = NULL) { return r3_tree_insert_pathl_ex(get(), path, std::strlen(path), NULL, data, errstr); } Node insert_pathl(const char* path, int path_len, void* data, char** errstr = NULL) { return r3_tree_insert_pathl_ex(get(), path, path_len, NULL, data, errstr); } Route insert_route(int method, const char* path, void* data, char** errstr = NULL) { return r3_tree_insert_routel_ex(get(), method, path, std::strlen(path), data, errstr); } Route insert_routel(int method, const char* path, int path_len, void* data, char** errstr = NULL) { return r3_tree_insert_routel_ex(get(), method, path, path_len, data, errstr); } Node match(const char* path, MatchEntry* entry = NULL) const { return r3_tree_match(get(), path, entry != NULL ? entry->get() : NULL); } Node matchl(const char* path, int path_len, MatchEntry* entry = NULL) const { return r3_tree_matchl(get(), path, path_len, entry != NULL ? entry->get() : NULL); } Node match_entry(MatchEntry& entry) const { return r3_tree_match_entry(get(), entry.get()); } Route match_route(MatchEntry& entry) const { return r3_tree_match_route(get(), entry.get()); } private: Tree(const Tree&); Tree& operator =(const Tree&); }; } #endif // R3_HPP r3-1.3.4/include/r3_define.h000066400000000000000000000013001262260041500154650ustar00rootroot00000000000000/* * r3_define.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef DEFINE_H #define DEFINE_H #include #if !defined(bool) && !defined(__cplusplus) typedef unsigned char bool; #endif #ifndef FALSE # define FALSE 0 #endif #ifndef TRUE # define TRUE 1 #endif // #define DEBUG 1 #ifdef DEBUG #define info(fmt, ...) \ do { fprintf(stderr, fmt, ##__VA_ARGS__); } while (0) #define debug(fmt, ...) \ do { fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, __VA_ARGS__); } while (0) #else #define info(...); #define debug(...); #endif #endif /* !DEFINE_H */ r3-1.3.4/include/r3_gvc.h000066400000000000000000000011121262260041500150130ustar00rootroot00000000000000/* * r3_gvc.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef R3_GVC_H #define R3_GVC_H #include #include #include "r3.h" void r3_tree_build_ag_nodes(Agraph_t * g, Agnode_t * ag_parent_node, const node * n, int * node_cnt); int r3_tree_render(const node * tree, const char *layout, const char * format, FILE *fp); int r3_tree_render_dot(const node * tree, const char *layout, FILE *fp); int r3_tree_render_file(const node * tree, const char * format, const char * filename); #endif /* !R3_GVC_H */ r3-1.3.4/include/r3_json.h000066400000000000000000000010751262260041500152150ustar00rootroot00000000000000/* * r3_json.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef R3_JSON_H #define R3_JSON_H #include #include "r3.h" json_object * r3_edge_to_json_object(const edge * e); json_object * r3_node_to_json_object(const node * n); json_object * r3_route_to_json_object(const route * r); const char * r3_node_to_json_string_ext(const node * n, int options); const char * r3_node_to_json_pretty_string(const node * n); const char * r3_node_to_json_string(const node * n); #endif /* !R3_JSON_H */ r3-1.3.4/include/r3_list.h000066400000000000000000000011571262260041500152200ustar00rootroot00000000000000/* * r3_list.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef R3_LIST_H #define R3_LIST_H #include typedef struct _list_item { void *value; struct _list_item *prev; struct _list_item *next; } list_item; typedef struct { int count; list_item *head; list_item *tail; pthread_mutex_t mutex; } list; list *list_create(); void list_free(list *l); list_item *list_add_element(list *l, void *ptr); int list_remove_element(list *l, void *ptr); void list_each_element(list *l, int (*func)(list_item *)); #endif /* !R3_LIST_H */ r3-1.3.4/include/r3_str.h000066400000000000000000000023361262260041500150550ustar00rootroot00000000000000/* * r3_str.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef R3_STR_H #define R3_STR_H #ifdef __cplusplus extern "C" { #endif char * r3_slug_compile(const char * str, int len); char * r3_slug_find_pattern(const char *s1, int *len); char * r3_slug_find_name(const char *s1, int *len); char * r3_slug_find_placeholder(const char *s1, int *len); int r3_slug_count(const char * needle, int len, char **errstr); char * r3_inside_slug(const char * needle, int needle_len, char *offset, char **errstr); void str_repeat(char *s, const char *c, int len); void print_indent(int level); #if _GNU_SOURCE || POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700 || __DARWIN_C_LEVEL >= 200809L #ifndef HAVE_STRNDUP #define HAVE_STRNDUP #endif #endif #if _SVID_SOURCE || _BSD_SOURCE \ || _XOPEN_SOURCE >= 500 \ || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED \ || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L \ || __DARWIN_C_LEVEL >= 200809L #ifndef HAVE_STRDUP #define HAVE_STRDUP #endif #endif #ifndef HAVE_STRDUP char *strdup(const char *s); #endif #ifndef HAVE_STRNDUP char *strndup(const char *s, int n); #endif #ifdef __cplusplus } #endif #endif /* !R3_STR_H */ r3-1.3.4/include/str_array.h000066400000000000000000000013221262260041500156410ustar00rootroot00000000000000/* * str_array.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef STR_ARRAY_H #define STR_ARRAY_H typedef struct _str_array { char **tokens; int len; int cap; } str_array; str_array * str_array_create(int cap); bool str_array_is_full(const str_array * l); bool str_array_resize(str_array *l, int new_cap); bool str_array_append(str_array * list, char * token); void str_array_free(str_array *l); void str_array_dump(const str_array *l); str_array * split_route_pattern(char *pattern, int pattern_len); #define str_array_fetch(t,i) t->tokens[i] #define str_array_len(t) t->len #define str_array_cap(t) t->cap #endif /* !STR_ARRAY_H */ r3-1.3.4/m4/000077500000000000000000000000001262260041500123615ustar00rootroot00000000000000r3-1.3.4/m4/.keep000066400000000000000000000000001262260041500132740ustar00rootroot00000000000000r3-1.3.4/package.json000066400000000000000000000011061262260041500143250ustar00rootroot00000000000000{ "name": "r3", "version": "1.3.3", "repo": "brendanashworth/r3", "description": "high-performance path dispatching library", "keywords": ["path", "dispatch", "performance", "r3", "c9s"], "license": "MIT", "src": ["3rdparty/zmalloc.c", "3rdparty/zmalloc.h", "include/r3.h", "include/r3.hpp", "include/r3_define.h", "include/r3_gvc.h", "include/r3_json.h", "include/r3_list.h", "include/r3_str.h", "include/str_array.h", "src/edge.c", "src/gvc.c", "src/json.c", "src/list.c", "src/match_entry.c", "src/node.c", "src/slug.c", "src/slug.h", "src/str.c", "src/token.c"] } r3-1.3.4/php/000077500000000000000000000000001262260041500126305ustar00rootroot00000000000000r3-1.3.4/php/r3/000077500000000000000000000000001262260041500131545ustar00rootroot00000000000000r3-1.3.4/php/r3/annotation/000077500000000000000000000000001262260041500153265ustar00rootroot00000000000000r3-1.3.4/php/r3/annotation/annot.h000066400000000000000000000033761262260041500166270ustar00rootroot00000000000000 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ typedef struct _phannot_parser_token { char *token; int opcode; int token_len; int free_flag; } phannot_parser_token; typedef struct _phannot_parser_status { zval *ret; phannot_scanner_state *scanner_state; phannot_scanner_token *token; int status; zend_uint syntax_error_len; char *syntax_error; } phannot_parser_status; #define PHANNOT_PARSING_OK 1 #define PHANNOT_PARSING_FAILED 0 extern int phannot_parse_annotations(zval *result, zval *view_code, zval *template_path, zval *line TSRMLS_DC); int phannot_internal_parse_annotations(zval **result, zval *view_code, zval *template_path, zval *line, zval **error_msg TSRMLS_DC); r3-1.3.4/php/r3/annotation/base.c000066400000000000000000000305111262260041500164040ustar00rootroot00000000000000 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ const phannot_token_names phannot_tokens[] = { { "INTEGER", PHANNOT_T_INTEGER }, { "DOUBLE", PHANNOT_T_DOUBLE }, { "STRING", PHANNOT_T_STRING }, { "IDENTIFIER", PHANNOT_T_IDENTIFIER }, { "@", PHANNOT_T_AT }, { ",", PHANNOT_T_COMMA }, { "=", PHANNOT_T_EQUALS }, { ":", PHANNOT_T_COLON }, { "(", PHANNOT_T_PARENTHESES_OPEN }, { ")", PHANNOT_T_PARENTHESES_CLOSE }, { "{", PHANNOT_T_BRACKET_OPEN }, { "}", PHANNOT_T_BRACKET_CLOSE }, { "[", PHANNOT_T_SBRACKET_OPEN }, { "]", PHANNOT_T_SBRACKET_CLOSE }, { "ARBITRARY TEXT", PHANNOT_T_ARBITRARY_TEXT }, { NULL, 0 } }; /** * Wrapper to alloc memory within the parser */ static void *phannot_wrapper_alloc(size_t bytes){ return emalloc(bytes); } /** * Wrapper to free memory within the parser */ static void phannot_wrapper_free(void *pointer){ efree(pointer); } /** * Creates a parser_token to be passed to the parser */ static void phannot_parse_with_token(void* phannot_parser, int opcode, int parsercode, phannot_scanner_token *token, phannot_parser_status *parser_status){ phannot_parser_token *pToken; pToken = emalloc(sizeof(phannot_parser_token)); pToken->opcode = opcode; pToken->token = token->value; pToken->token_len = token->len; pToken->free_flag = 1; phannot_(phannot_parser, parsercode, pToken, parser_status); token->value = NULL; token->len = 0; } /** * Creates an error message when it's triggered by the scanner */ static void phannot_scanner_error_msg(phannot_parser_status *parser_status, zval **error_msg TSRMLS_DC){ int error_length; char *error, *error_part; phannot_scanner_state *state = parser_status->scanner_state; ALLOC_INIT_ZVAL(*error_msg); if (state->start) { error_length = 128 + state->start_length + Z_STRLEN_P(state->active_file); error = emalloc(sizeof(char) * error_length); if (state->start_length > 16) { error_part = estrndup(state->start, 16); snprintf(error, 64 + state->start_length, "Scanning error before '%s...' in %s on line %d", error_part, Z_STRVAL_P(state->active_file), state->active_line); efree(error_part); } else { snprintf(error, error_length - 1, "Scanning error before '%s' in %s on line %d", state->start, Z_STRVAL_P(state->active_file), state->active_line); } error[error_length - 1] = '\0'; ZVAL_STRING(*error_msg, error, 1); } else { error_length = sizeof(char) * (64 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanning error near to EOF in %s", Z_STRVAL_P(state->active_file)); ZVAL_STRING(*error_msg, error, 1); error[error_length - 1] = '\0'; } efree(error); } /** * Receives the comment tokenizes and parses it */ int phannot_parse_annotations(zval *result, zval *comment, zval *file_path, zval *line TSRMLS_DC){ zval *error_msg = NULL; ZVAL_NULL(result); if (Z_TYPE_P(comment) != IS_STRING) { zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), ZEND_STRL("Comment must be a string"), 0 TSRMLS_CC); return FAILURE; } if(phannot_internal_parse_annotations(&result, comment, file_path, line, &error_msg TSRMLS_CC) == FAILURE){ if (error_msg != NULL) { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg), 1 TSRMLS_CC); zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg) , 0 TSRMLS_CC); } else { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, ZEND_STRL("There was an error parsing annotation"), 1 TSRMLS_CC); zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), ZEND_STRL("There was an error parsing annotation") , 0 TSRMLS_CC); } return FAILURE; } return SUCCESS; } /** * Remove comment separators from a docblock */ void phannot_remove_comment_separators(zval *return_value, char *comment, int length, int *start_lines) { int start_mode = 1, j, i, open_parentheses; smart_str processed_str = {0}; char ch; (*start_lines) = 0; for (i = 0; i < length; i++) { ch = comment[i]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (ch == '@') { smart_str_appendc(&processed_str, ch); i++; open_parentheses = 0; for (j = i; j < length; j++) { ch = comment[j]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (open_parentheses == 0) { if (isalnum(ch) || '_' == ch || '\\' == ch) { smart_str_appendc(&processed_str, ch); continue; } if (ch == '(') { smart_str_appendc(&processed_str, ch); open_parentheses++; continue; } } else { smart_str_appendc(&processed_str, ch); if (ch == '(') { open_parentheses++; } else if (ch == ')') { open_parentheses--; } else if (ch == '\n') { (*start_lines)++; start_mode = 1; } if (open_parentheses > 0) { continue; } } i = j; smart_str_appendc(&processed_str, ' '); break; } } if (ch == '\n') { (*start_lines)++; start_mode = 1; } } smart_str_0(&processed_str); if (processed_str.len) { RETURN_STRINGL(processed_str.c, processed_str.len, 0); } else { RETURN_EMPTY_STRING(); } } /** * Parses a comment returning an intermediate array representation */ int phannot_internal_parse_annotations(zval **result, zval *comment, zval *file_path, zval *line, zval **error_msg TSRMLS_DC) { char *error; phannot_scanner_state *state; phannot_scanner_token token; int scanner_status, status = SUCCESS, start_lines, error_length; phannot_parser_status *parser_status = NULL; void* phannot_parser; zval processed_comment; /** * Check if the comment has content */ if (!Z_STRVAL_P(comment)) { ZVAL_BOOL(*result, 0); return FAILURE; } if (Z_STRLEN_P(comment) < 2) { ZVAL_BOOL(*result, 0); return SUCCESS; } /** * Remove comment separators */ phannot_remove_comment_separators(&processed_comment, Z_STRVAL_P(comment), Z_STRLEN_P(comment), &start_lines); if (Z_STRLEN(processed_comment) < 2) { ZVAL_BOOL(*result, 0); efree(Z_STRVAL(processed_comment)); return SUCCESS; } /** * Start the reentrant parser */ phannot_parser = phannot_Alloc(phannot_wrapper_alloc); parser_status = emalloc(sizeof(phannot_parser_status)); state = emalloc(sizeof(phannot_scanner_state)); parser_status->status = PHANNOT_PARSING_OK; parser_status->scanner_state = state; parser_status->ret = NULL; parser_status->token = &token; parser_status->syntax_error = NULL; /** * Initialize the scanner state */ state->active_token = 0; state->start = Z_STRVAL(processed_comment); state->start_length = 0; state->mode = PHANNOT_MODE_RAW; state->active_file = file_path; token.value = NULL; token.len = 0; /** * Possible start line */ if (Z_TYPE_P(line) == IS_LONG) { state->active_line = Z_LVAL_P(line) - start_lines; } else { state->active_line = 1; } state->end = state->start; while(0 <= (scanner_status = phannot_get_token(state, &token))) { state->active_token = token.opcode; state->start_length = (Z_STRVAL(processed_comment) + Z_STRLEN(processed_comment) - state->start); switch (token.opcode) { case PHANNOT_T_IGNORE: break; case PHANNOT_T_AT: phannot_(phannot_parser, PHANNOT_AT, NULL, parser_status); break; case PHANNOT_T_COMMA: phannot_(phannot_parser, PHANNOT_COMMA, NULL, parser_status); break; case PHANNOT_T_EQUALS: phannot_(phannot_parser, PHANNOT_EQUALS, NULL, parser_status); break; case PHANNOT_T_COLON: phannot_(phannot_parser, PHANNOT_COLON, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_OPEN: phannot_(phannot_parser, PHANNOT_PARENTHESES_OPEN, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_CLOSE: phannot_(phannot_parser, PHANNOT_PARENTHESES_CLOSE, NULL, parser_status); break; case PHANNOT_T_BRACKET_OPEN: phannot_(phannot_parser, PHANNOT_BRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_BRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_BRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_SBRACKET_OPEN: phannot_(phannot_parser, PHANNOT_SBRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_SBRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_SBRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_NULL: phannot_(phannot_parser, PHANNOT_NULL, NULL, parser_status); break; case PHANNOT_T_TRUE: phannot_(phannot_parser, PHANNOT_TRUE, NULL, parser_status); break; case PHANNOT_T_FALSE: phannot_(phannot_parser, PHANNOT_FALSE, NULL, parser_status); break; case PHANNOT_T_INTEGER: phannot_parse_with_token(phannot_parser, PHANNOT_T_INTEGER, PHANNOT_INTEGER, &token, parser_status); break; case PHANNOT_T_DOUBLE: phannot_parse_with_token(phannot_parser, PHANNOT_T_DOUBLE, PHANNOT_DOUBLE, &token, parser_status); break; case PHANNOT_T_STRING: phannot_parse_with_token(phannot_parser, PHANNOT_T_STRING, PHANNOT_STRING, &token, parser_status); break; case PHANNOT_T_IDENTIFIER: phannot_parse_with_token(phannot_parser, PHANNOT_T_IDENTIFIER, PHANNOT_IDENTIFIER, &token, parser_status); break; /*case PHANNOT_T_ARBITRARY_TEXT: phannot_parse_with_token(phannot_parser, PHANNOT_T_ARBITRARY_TEXT, PHANNOT_ARBITRARY_TEXT, &token, parser_status); break;*/ default: parser_status->status = PHANNOT_PARSING_FAILED; if (!*error_msg) { error_length = sizeof(char) * (48 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanner: unknown opcode %d on in %s line %d", token.opcode, Z_STRVAL_P(state->active_file), state->active_line); error[error_length - 1] = '\0'; ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, error, 1); efree(error); } break; } if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; break; } state->end = state->start; } if (status != FAILURE) { switch (scanner_status) { case PHANNOT_SCANNER_RETCODE_ERR: case PHANNOT_SCANNER_RETCODE_IMPOSSIBLE: if (!*error_msg) { phannot_scanner_error_msg(parser_status, error_msg TSRMLS_CC); } status = FAILURE; break; default: phannot_(phannot_parser, 0, NULL, parser_status); } } state->active_token = 0; state->start = NULL; if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; if (parser_status->syntax_error) { if (!*error_msg) { ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, parser_status->syntax_error, 1); } efree(parser_status->syntax_error); } } phannot_Free(phannot_parser, phannot_wrapper_free); if (status != FAILURE) { if (parser_status->status == PHANNOT_PARSING_OK) { if (parser_status->ret) { ZVAL_ZVAL(*result, parser_status->ret, 0, 0); ZVAL_NULL(parser_status->ret); zval_ptr_dtor(&parser_status->ret); } else { array_init(*result); } } } efree(Z_STRVAL(processed_comment)); efree(parser_status); efree(state); return status; } r3-1.3.4/php/r3/annotation/lemon000077500000000000000000001667401262260041500164040ustar00rootroot00000000000000 H__PAGEZERO(__TEXT__text__TEXT | __stubs__TEXT__stub_helper__TEXTܨܨ__cstring__TEXT`"`__unwind_info__TEXT\__eh_frame__TEXT__DATA__nl_symbol_ptr__DATA%__got__DATA '__la_symbol_ptr__DATA0(0+__data__DATA`L`__bss__DATAH__LINKEDIT "0h8h P##^*P /usr/lib/dyldM2;\456.$ *(+ 8/usr/lib/libSystem.B.dylib& )+UHH%HuNHHtE(DHHTH(HuHǀHҴHHH Ǵ]H.HH=d2cff.UHHHw]K&ff.UHHHH@)uG+Fu2Gw,Ts"Fw+Ts!HNHG@@+A@]H=5fH=$gfff.UHAWAVATSIIAHHҳHuK荙HHta(fHHTH(HuHǀHHHH wH HHHD`L8ELp[A\A^A_]HHH=2記fff.UHSPHH{躘H{豘HH[]飘UH0謘Ht1H@(H@ H@H@H@H]HHH=~+JfUHAWAVSPAAHC$K(9|"K(H{HcH;HCHtGC$tD9{ }D{ D9{~D{ D{DsHKHcD@H{uDH{ uNL{8H{HtHqHC8HfMLuL[A\A^A_]%H=\H=KUHAWAVAUATSPIIIGH]ffffff.@0H@8HuMoM1Iffffff.AE0AUIM;QHH H HH H H Ht:yt41҃9~"HIHHH ڦ;|AAUHcIUHRL$MLtMfC0t9H;Hcs;w}-HGL9$u#C0% Hx H =fH[8HuLL1LHMm8MH[A\A]A^A_]UHAWAVATSIAF1@IHHr HV(Hv8HuH9|܅~VE1DIJ LaMt6I\$ fH;HLA<H[HuMd$8MuAFIA9|[A\A^A_]fUHSwE1Ʌ~8H1fff.HHRfDB0HR8HuH9|EAA9|E1EAuIcHHLPMtDAz0|MZMtk ƤfD~R1IRI3Hv1ffff.<t<u H9|ޅtI@0AM[MuAB0MR8Mlw0[]ÐUHAWAVAUATSPIAD$E1ffffff.I $NL0dAE1rAU1A$MmMzf.AD$H]H9IL$HtfADHIPHuAD$~M1DI$HHRHt.ffffff.zu HB@DHRHuAD$H9|I\$Ht9L5+f{DusI$L05AD$(H[PHuH[A\A]A^A_]H=7H=&H=DUHHmHtHH87HQHt*HHHHH8HHHǀH $]HHH=j2踄lUHHHG8H=]UHSPHϞHȞHɞHƞHHH=0JHHHtqH@*HCHtDHHKHǀf.HHƞHKH?tH跃HH[]fUHHHHHHHHSHt/xt)8~1ɐH@HHH*;|@]ffff.UHAWAVSPAIH=pOHHtRAG@k%D2!HcHHJff.H Ht$HHR@)uSD)HuHHHtHC8>袂HH֜HHCHHC8HHHǃHL;DsD=IcQIME~AGHAHOL要LsHC(HC HCHC@HC8H?HHC8H1Ha~HH[A^A_]H=EH[HH=B2萁DUHAWAVSPAIH=ЛtH=wH-HtTAG@k%D2!HcHHJffff.H Ht$HHR@)uSD)HuHH5HtHC8>HHHHCHHC8HHHǃHL;DsD=OIc葀IME~AGHAHOLLsHC(HC HCHC@HC8HHHC8HqHC@H vHHlH|HH[A^A_]H=E`H=4aHuHH=\2^ffff.UHAWAVAUATSHH}H=˙7H @HEH@8H HEL0LcxE;~}IFN$A|$ uMl$Mu8HEL;`0tI $Av(H]HHԂ0C(Ml$MtHEL`@L1LLAE;F}^IVHTHpz tC=m~&1HJ(<t<u =JH9|z0LuHcJE;Fu LH/MmHMjH[A\A]A^A_]H=DUHH=eHNtHw8 HNHK]ÐUHH=5HtHw@ H.H+]ÐUHHHH]ffff.UHHHڗHח]ffff.UHAVSHHt;H{u8H{ uBLs8H{Ht}HqHC8HfMLu[A^]H=hH=Wffffff.UHHHH=׀|n|fUHAWAVAUATSH(HHH;HH5qH =L-MI}I]HIE1AE1@Eu+<+t(<-t$H߾=N|Huffffff.AHH5?.|EDI]IHuA=DžH={HHmHtrH{HCHtEH`HKHǀ`fHHHKH=tH%{HH= {HHܕHtgH{HCHt:HHKHǀ HHHKHtHzHpH=pzHHVHtiHrzHCHt{jIIA|IAKHt2LH5pr0iL5KLHHDžHDžDž HHHHhHHHXHHJTXHP E~JH H1H`H A|0AL$1H(HxHtHp HhH|H9uHHHHPD`H@8H@0Hr~zp@HQHPHHAH@PH}YHEHEXVHHjdVA<$(Dž +VHHj@<{HEHHHe;LH5h{VHHHhHMHpHE'Hx8LtFHMHA8Dž LUFx HHiHHzgLFHHHTuHMHHiMdHEH8u4A $"t{uIL HEHtDžA$H<"uILEHiL0HHfL0lDžHHdVLH5fTHHHMHHEfHHd0Dž 6MĉH MH$%L}DHcH HcHDŽ`HxHHHǀ HMHAPHEHEDžHx0urH(IL`0LH5eSupHHHMHHE\HHgL03HHb0 LH5e.Su!HHHMHHELH5^eRuHHHELH5@eRuHHHxHMHHELH5eRu!HHHMHHEKLH5dlRu!HHHMHHELH5d8Ru!HHHMHHELH5dRuHH@HELH5dQuHHHHELH5xdQuHHPHEnLH5^dQuHH`HEGLH5BdhQuHHXHE LH5(dAQuEEDžLH5dQuEEDžLH5cPuEEDžLH5cPuDžzLH5cPu Dž[LH5c|PuHDžDž1HH\cL0賾DžALE1uLOHEHHAA(HH?[A\A]A^A_]HOgH8H5pd0\O:OfU!<,FkUHHiHuN@ OHiHtEDHHTHHi@uHǀ8HziHHH oi]HnfHH=eVANWNff.UHAVSIHH$iHuU@wNHiHt\fff.HHTHHh@uHǀ8HhHHH hH HHHL0[A^]HeHH=UAMMff.UHHtH@HNHFH7HHHu]UHHt!H8hHOHGH=)hHHHu]@UHAWAVSPILLMHLMH|IMHHt@HLrMH߾.wMHtHLHLHH[A^A_]HdHH=T%LLffff.UHAWAVSPIIHHHtLHL!HHLMLIMu+E1A>wu"HHdH8H5oT0#LC(LH[A^A_]fffff.UHAWAVAUATSPIIH=AT0LE~ E~%Mf E1KH80LI9ME9|KL1OADEԅ~wLceE1ff.H=S0KE;nM};fIF JpA9LH=Sډ0gKME;~|ο `KID;m|I^HL=SL-SL%SfHH0H=nS0 KL0K{~*E1fHCJH0L0JID;s|.JHC8Ht H0L0J JH[PH{H[A\A]A^A_]H=LP Kff.UHAWAVAUATSPIIIHHH5R0 JCxXE1L%R@E;~uH=RLICA9t#HCJHLL0ICIA9~H[A\A]A^A_]UHSPHOHH5Hc H1uHHwDFH H5RTHH H5R$HHwDF@H H5Q.HH H5QH0IHHwDF@H H5QH0HH[]{{{UHAWAVAUATSH8IH}`HHEH5QHQIMeH=QLHA~91LeDHMIHȋSLH5QQ05HAuHCHL8I8M?MIAO;Hu4D@@L1H Q0GLH5PL0GfH=P LGLLl LGAqI@M?lD LmGH[HtHLu@ L=GHMHA;NL GH^HH;EuH8[A\A]A^A_]FfDUHAWAVAUATSPUII/WGHHtWEL3GIL(GI|FIMt H OL1HMM0BFEԈH=OFHOHHEHFILFI|sFIE1Mf.;tuH߾:xFIMuHzFIIEuAEL1HH OIM0EEuLu0EIEH [LDLuMLH[A\A]A^A_]ÐUHNHw#H3Hc HHF@]ËGOD]HNGA@]ËGG]Ð@UHAWAVAUATSHHHHHIH\HHEHHDH!A@ff=%%HE1MEDAIcƊHc=ZH=YL?Lc%YL5YK<&p?AAED%YDe]HTL5YHcYAHYH VH H;Mu HH[A\A]A^A_]H=A 蔩M>ffffff.UHAWAVAUATSH(ILHHVHHEAE~HHHOH=XI]0ƅ>ƅAff.xHH UD<!@u=I;]0tEH{HxHdUDH5F@H=HNIIMDžI8HLLI_hHtpIAWpH5]>L04fL4HÊt< uIH5>L0A4MH5{?LHH5l?LH04H4HI|$8LLLH=>L3L5II$HLEA|$M|>L->ID$ HHLLLA0e3HA;\$|H=M>Lf3LMLcI|$8HLLI|$8HLLAD$H!B=H|H BH*B=HLH5<>L02AT$H55>L02AD$AL$MD=|H AHA=HLH5>LH0L2HLLHދgL{`MtJL1(HH=1L0ؠC(L==L{`H5=LL01H==L1tH={<L1HC8H{@IH:HHEH?HLL1LcL5IA@L~7IG@H|LkHxADAHHH57D0)HH57D0)*f.HH5c7D0) tAD;Du$ H})1 fIHD9L4H=7HHR)H=6%H3)HIGHH@E1E1ffffff.HFH=$Q BKWcdm{ !.fff.UHF +G ]@UHAWAVAUATSHIH/HHEI$H5#HH!IL5-HLEMLf.HA;\$}ZHLJHtAID$ HL$L1H "M0HLHKtLA9\$tnH5R"H LWIMtPA|$|@L-9"ff.ID$ HHLLLA0HA;\$|LH`.HH;EuH[A\A]A^A_]6UHAWAVAUATSPH}DGE=E1fffff.HEHN,M}E1MLAfff.xuUHpL9HtDHJH9L9 HRHtzuffffff.D9DMLOH@HuAMMAuM9wuH= IIGH@Ht'xuL9pu@H@fffff.I}HwH!{\IEHED@IE9H[A\A]A^A_]H=|@UHlj=/]fUHAVS/HcIMt&~CHHOLQL[A^]ؗUH]fDUHHcƀ<]fUH1 4/~21fffff.<t<u /H9|]fff.UH1t%H1ffffff.k ЊHDŽu]ffff.UHAWAVSPIH.HtjA1ɄtIv1k ъHƄu!HcHHXfffff.HHtL;LLHuMu,LHxfIMt!LLLLH[A^A_]Nfffff.UHSPH=- HH-HtfHHCHt9H`HC1ff.HH~-H@HtHHU-H[]fDUHAWAVAUATSHI1L-+-MAE1t#IOE1fEk AƊHuEeAD$D!HcHI]fDHHtH;L=H1uAMD9 MC$DeEHcHHI1MqL}H[M<ąۋE~DH4LA}ED@1fHIIuH֊1tH1k ߊHuL I\D!MHcI+H@HHH,+H@LHH+HpHtH[A\A]A^A_]@UHAWAVSPIH*HtgA1ɄtIv1k ъHƄu!HcHHXfffff.HHtL;LLHuE1E1LH[A^A_]f.UHAVSIHO*HtrA1Ʉt"Iv1ff.k ъHƄu!HcHHHfffff.HHt H{L\HKuHHXHHLHI>HxHw&#L<THɉK HCHCC C$HC(C0HC8HCHHHH[A^]}ffff.UHHH81ɀ?ZO瀖H6@+FH6>ZOʁဖ)]UHSPH=(| HH(HtcH HCHt6HHC1ff.HHv(H@HtHw HP(H[]fUHAWAVAUATSH(IH}1L5(M)A$E1tIL$E1Ek ANJHuE.AED!HcHI^HHtH{L, H1uAND9+M6uEHcHH< I1MLeIIMۋE~DH4L A~ED@1ɐHHMVID1tH1k HuMLI\D!M\HcI%@%B%D%F%H%J%L%N%P%R%T%V%X%Z%\%^%`%b%d%f%h%j%l%n%p%r%t%vL%AS%hhh!h6hNhbhxhhhhhxhnhdhZhPhFh%*s %s %s=%*s %s %s=%*s %s rbCan't open this file for reading.Can't allocate %d of memory to hold this file.Can't read in all %d bytes of this file.String starting on this line is not terminated before the end of the file.C code starting on this line is not terminated before the end of the file.Unable to allocate memory for a new follow-set propagation link. Can't allocate space for a filename. Can't open file "%s". // Reprint of input file "%s". // Symbols: // %3d %-*.*s%s ::= %s [%s]%s ::= *%*s shift %d%*s reduce %d%*s accept%*s error%*s reduce %-3d ** Parsing conflict **.outw State %d: (%d) %5s %s/%sPATH.:/bin:/usr/binParse%.*s%.*s.lt%s.ltCan't find the parser driver template file "%s". rCan't open the template file "%s". #line %d "%s" #line %d "%s" #line %d "%s" {(yypminor->yy%d)} #line %d "%s" %dyygotominor.yy%dyymsp[%d].majoryymsp[%d].minor.yy%dLabel "%s" for "%s(%s)" is never used.Label %s for "%s(%s)" is never used. yy_destructor(%d,&yymsp[%d].minor); Out of memory. #if INTERFACE #define %sTOKENTYPE %s void*#endif typedef union { %sTOKENTYPE yy0; %s yy%d; int yy%d; } YYMINORTYPE; .c.h#include "%s" #define %s%-30s %2d #define YYCODETYPE %s #define YYNOCODE %d #define YYACTIONTYPE %s Illegal stack size: [%s]. The stack size should be an integer constant.100#define YYSTACKDEPTH %s #define YYSTACKDEPTH 100 #define %sARG_SDECL %s; #define %sARG_PDECL ,%s #define %sARG_FETCH %s = yypParser->%s #define %sARG_STORE yypParser->%s = %s #define %sARG_SDECL #define %sARG_PDECL #define %sARG_FETCH #define %sARG_STORE #define YYNSTATE %d #define YYNRULE %d #define YYERRORSYMBOL %d #define YYERRSYMDT yy%d #define YYFALLBACK 1 static YYACTIONTYPE yy_action[] = { /* %5d */ %4d,}; static YYCODETYPE yy_lookahead[] = { #define YY_SHIFT_USE_DFLT (%d) static %s yy_shift_ofst[] = { #define YY_REDUCE_USE_DFLT (%d) static %s yy_reduce_ofst[] = { static YYACTIONTYPE yy_default[] = { 0, /* %10s => nothing */ %3d, /* %10s => %s */ "%s", %-15s /* %3d */ "%s ::=", case %d: break; { %d, %d }, case %d: break; unsigned charunsigned short intunsigned intsigned charshortintThere is not prior rule opon which to attach the code fragment which begins on this line.Code fragment beginning on this line is not the first to follow the previous rule.Token "%s" should be either "%%" or a nonterminal name.The precedence symbol must be a terminal.There is no prior rule to assign precedence "[%s]".Precedence mark on this line is not the first to follow the previous rule.Missing "]" on precedence mark.Expected to see a ":" following the LHS symbol "%s"."%s" is not a valid alias for the LHS "%s" Missing ")" following LHS alias name "%s".Missing "->" following: "%s(%s)".Can't allocate enough memory for this rule.Too many symbol on RHS or rule beginning at "%s".Illegal character on RHS of rule: "%s"."%s" is not a valid alias for the RHS symbol "%s" nameincludecodetoken_destructordefault_destructortoken_prefixsyntax_errorparse_acceptparse_failurestack_overflowextra_argumenttoken_typedefault_typestack_sizestart_symbolleftrightnonassocdestructortypefallbackUnknown declaration keyword: "%%%s".Illegal declaration keyword: "%s".Symbol name missing after %destructor keywordSymbol "%s" has already be given a precedence.Can't assign a precedence to "%s".The argument "%s" to declaration "%%%s" is not the first.Illegal argument to %%%s: %s%%fallback argument "%s" should be a tokenMore than one fallback assigned to token %s%endif%ifdef%ifndefunterminated %%ifdef starting on line %d %*s^-- here %*shere --^ %sundefined option. %soption requires an argument. %sillegal character in floating-point argument. %sillegal character in integer argument. %smissing argument on switch. out of memory Not enough precedence: %s Lemon version 1.044Xa!  LLL A@@P Pp`@`@0&'K`L MMN0QR0UU0WpXYPZZ``aЂ@Їp`А0pЖzRx  (2<FPZdnxȩҩܩ",6@JTެ3@Bgilempar.cCommand line syntax error: "0`%BSASASASASASASAS@__DefaultRuneLocaleQr@___stack_chk_guard@___stderrp@___stdoutp@dyld_stub_binderr0@___bzeror8@___maskruner@@___sprintf_chkrH@___stack_chk_failrP@___strcat_chkrX@___vsprintf_chkr`@_accessrh@_atoirp@_exitrx@_fcloser@_fgetsr@_fopenr@_fprintfr@_fputcr@_fputsr@_freadr@_freer@_fseekr@_ftellr@_fwriter@_getenvr@_mallocr@_printfr@_putcr@_putcharr@_putsr@_qsortr@_reallocr@_rewindr@_strchrr@_strcmpr@_strcpyr@_strlenr@_strncmpr@_strrchrr@_strtodr@_strtol__mh_execute_headerAction_amFindErrorMsggetstatebuildshiftsnewconfigdeleteconfigCoOptPfile_Reppcotemit_has_destructorS st newsortaddcttab_ppend_strfreeainsertllocction !yassertemory_errorainsort&RulePrecedencesFStatesLinksActions'irstSetsollowSets'+.37:;=FGnfigmpressTables list_Printcmp table_ initreaddclosuresortbasiseatGsetturnIJbasisMQTbasisUUUVWWiInitNArgsArgErrPrintmwxz~arselink_rintActionnewaddcopydeleteеmakenameopenrintortOutputTableHeader athsearchrint_stack_unionmpute_actionnfighash plt_ranslate_codexferopenprintdestructor_codecodeet t ymbol Size New Free Add Union Чrhash ate rsafe ate_ _ in find it sert Ъ_ cmpp new in find Nth count arrayof it sert мcmp hash нnew in find arrayof it sert in find clear it sert  0p0P 00000 000`0 :P P@@0 ` p0 `` @ 35%>.P= `K c i ~               ' 7 E (Y ,j 0p 8u @z H P X `  ^@%& *(/+?#P$b*uP**p`   (=I0<Q=Y6b;l0?v A}YZZ@Y^`_s@\Гp`'3?0MpXa@oP}P0p`  0)6EhQ^bnPz#mf[[g++4P@# Pan,О6@A@JdUeacli| !)07@GNU[biqy@ _actioncmp_handle_D_option_merge_errline_axset_compare_main.options_tplt_open.templatename_emsg_Action_new.freelist_freelist_current_currentend_basis_basisend_main.version_main.rpflag_main.basisflag_main.compress_main.quiet_main.statistics_main.mhflag_argv_op_errstream_plink_freelist_append_str.z_append_str.alloced_append_str.used_size_x1a_x2a_x3a_x4a_nDefine_azDefine_Action_add_Action_new_Action_sort_CompressTables_ConfigPrint_Configcmp_Configlist_add_Configlist_addbasis_Configlist_basis_Configlist_closure_Configlist_eat_Configlist_init_Configlist_reset_Configlist_return_Configlist_sort_Configlist_sortbasis_Configtable_clear_Configtable_find_Configtable_init_Configtable_insert_ErrorMsg_FindActions_FindFirstSets_FindFollowSets_FindLinks_FindRulePrecedences_FindStates_OptArg_OptErr_OptInit_OptNArgs_OptPrint_Parse_Plink_add_Plink_copy_Plink_delete_Plink_new_PrintAction_ReportHeader_ReportOutput_ReportTable_Reprint_SetAdd_SetFree_SetNew_SetSize_SetUnion_State_arrayof_State_find_State_init_State_insert_State_new_Strsafe_Strsafe_find_Strsafe_init_Strsafe_insert_Symbol_Nth_Symbol_arrayof_Symbol_count_Symbol_find_Symbol_init_Symbol_insert_Symbol_new_Symbolcmpp__mh_execute_header_acttab_action_acttab_alloc_acttab_free_acttab_insert_append_str_buildshifts_compute_action_confighash_deleteconfig_emit_code_emit_destructor_code_file_makename_file_open_getstate_has_destructor_main_memory_error_msort_myassert_newconfig_pathsearch_print_stack_union_statecmp_statehash_strhash_tplt_open_tplt_print_tplt_xfer_translate_code__DefaultRuneLocale___bzero___maskrune___sprintf_chk___stack_chk_fail___stack_chk_guard___stderrp___stdoutp___strcat_chk___vsprintf_chk_access_atoi_exit_fclose_fgets_fopen_fprintf_fputc_fputs_fread_free_fseek_ftell_fwrite_getenv_malloc_printf_putc_putchar_puts_qsort_realloc_rewind_strchr_strcmp_strcpy_strlen_strncmp_strrchr_strtod_strtoldyld_stub_binderr3-1.3.4/php/r3/annotation/lemon.c000066400000000000000000004054311262260041500166130ustar00rootroot00000000000000/* ** This file contains all sources (including headers) to the LEMON ** LALR(1) parser generator. The sources have been combined into a ** single file to make it easy to include LEMON in the source tree ** and Makefile of another program. ** ** The author of this program disclaims copyright. */ #include #include #include #include #include #ifndef __WIN32__ # if defined(_WIN32) || defined(WIN32) # define __WIN32__ # endif #endif /* #define PRIVATE static */ #define PRIVATE #ifdef TEST #define MAXRHS 5 /* Set low to exercise exception code */ #else #define MAXRHS 1000 #endif char *msort(); extern void *malloc(); /******** From the file "action.h" *************************************/ struct action *Action_new(); struct action *Action_sort(); /********* From the file "assert.h" ************************************/ void myassert(); #ifndef NDEBUG # define assert(X) if(!(X))myassert(__FILE__,__LINE__) #else # define assert(X) #endif /********** From the file "build.h" ************************************/ void FindRulePrecedences(); void FindFirstSets(); void FindStates(); void FindLinks(); void FindFollowSets(); void FindActions(); /********* From the file "configlist.h" *********************************/ void Configlist_init(/* void */); struct config *Configlist_add(/* struct rule *, int */); struct config *Configlist_addbasis(/* struct rule *, int */); void Configlist_closure(/* void */); void Configlist_sort(/* void */); void Configlist_sortbasis(/* void */); struct config *Configlist_return(/* void */); struct config *Configlist_basis(/* void */); void Configlist_eat(/* struct config * */); void Configlist_reset(/* void */); /********* From the file "error.h" ***************************************/ void ErrorMsg(const char *, int,const char *, ...); /****** From the file "option.h" ******************************************/ struct s_options { enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type; char *label; char *arg; char *message; }; int OptInit(/* char**,struct s_options*,FILE* */); int OptNArgs(/* void */); char *OptArg(/* int */); void OptErr(/* int */); void OptPrint(/* void */); /******** From the file "parse.h" *****************************************/ void Parse(/* struct lemon *lemp */); /********* From the file "plink.h" ***************************************/ struct plink *Plink_new(/* void */); void Plink_add(/* struct plink **, struct config * */); void Plink_copy(/* struct plink **, struct plink * */); void Plink_delete(/* struct plink * */); /********** From the file "report.h" *************************************/ void Reprint(/* struct lemon * */); void ReportOutput(/* struct lemon * */); void ReportTable(/* struct lemon * */); void ReportHeader(/* struct lemon * */); void CompressTables(/* struct lemon * */); /********** From the file "set.h" ****************************************/ void SetSize(/* int N */); /* All sets will be of size N */ char *SetNew(/* void */); /* A new set for element 0..N */ void SetFree(/* char* */); /* Deallocate a set */ int SetAdd(/* char*,int */); /* Add element to a set */ int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */ #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ /********** From the file "struct.h" *************************************/ /* ** Principal data structures for the LEMON parser generator. */ typedef enum {B_FALSE=0, B_TRUE} Boolean; /* Symbols (terminals and nonterminals) of the grammar are stored ** in the following: */ struct symbol { char *name; /* Name of the symbol */ int index; /* Index number for this symbol */ enum { TERMINAL, NONTERMINAL } type; /* Symbols are all either TERMINALS or NTs */ struct rule *rule; /* Linked list of rules of this (if an NT) */ struct symbol *fallback; /* fallback token in case this token doesn't parse */ int prec; /* Precedence if defined (-1 otherwise) */ enum e_assoc { LEFT, RIGHT, NONE, UNK } assoc; /* Associativity if predecence is defined */ char *firstset; /* First-set for all rules of this symbol */ Boolean lambda; /* True if NT and can generate an empty string */ char *destructor; /* Code which executes whenever this symbol is ** popped from the stack during error processing */ int destructorln; /* Line number of destructor code */ char *datatype; /* The data type of information held by this ** object. Only used if type==NONTERMINAL */ int dtnum; /* The data type number. In the parser, the value ** stack is a union. The .yy%d element of this ** union is the correct data type for this object */ }; /* Each production rule in the grammar is stored in the following ** structure. */ struct rule { struct symbol *lhs; /* Left-hand side of the rule */ char *lhsalias; /* Alias for the LHS (NULL if none) */ int ruleline; /* Line number for the rule */ int nrhs; /* Number of RHS symbols */ struct symbol **rhs; /* The RHS symbols */ char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ int line; /* Line number at which code begins */ char *code; /* The code executed when this rule is reduced */ struct symbol *precsym; /* Precedence symbol for this rule */ int index; /* An index number for this rule */ Boolean canReduce; /* True if this rule is ever reduced */ struct rule *nextlhs; /* Next rule with the same LHS */ struct rule *next; /* Next rule in the global list */ }; /* A configuration is a production rule of the grammar together with ** a mark (dot) showing how much of that rule has been processed so far. ** Configurations also contain a follow-set which is a list of terminal ** symbols which are allowed to immediately follow the end of the rule. ** Every configuration is recorded as an instance of the following: */ struct config { struct rule *rp; /* The rule upon which the configuration is based */ int dot; /* The parse point */ char *fws; /* Follow-set for this configuration only */ struct plink *fplp; /* Follow-set forward propagation links */ struct plink *bplp; /* Follow-set backwards propagation links */ struct state *stp; /* Pointer to state which contains this */ enum { COMPLETE, /* The status is used during followset and */ INCOMPLETE /* shift computations */ } status; struct config *next; /* Next configuration in the state */ struct config *bp; /* The next basis configuration */ }; /* Every shift or reduce operation is stored as one of the following */ struct action { struct symbol *sp; /* The look-ahead symbol */ enum e_action { SHIFT, ACCEPT, REDUCE, ERROR, CONFLICT, /* Was a reduce, but part of a conflict */ SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ NOT_USED /* Deleted by compression */ } type; union { struct state *stp; /* The new state, if a shift */ struct rule *rp; /* The rule, if a reduce */ } x; struct action *next; /* Next action for this state */ struct action *collide; /* Next action with the same hash */ }; /* Each state of the generated parser's finite state machine ** is encoded as an instance of the following structure. */ struct state { struct config *bp; /* The basis configurations for this state */ struct config *cfp; /* All configurations in this set */ int index; /* Sequencial number for this state */ struct action *ap; /* Array of actions for this state */ int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ int iDflt; /* Default action */ }; #define NO_OFFSET (-2147483647) /* A followset propagation link indicates that the contents of one ** configuration followset should be propagated to another whenever ** the first changes. */ struct plink { struct config *cfp; /* The configuration to which linked */ struct plink *next; /* The next propagate link */ }; /* The state vector for the entire parser generator is recorded as ** follows. (LEMON uses no global variables and makes little use of ** static variables. Fields in the following structure can be thought ** of as begin global variables in the program.) */ struct lemon { struct state **sorted; /* Table of states sorted by state number */ struct rule *rule; /* List of all rules */ int nstate; /* Number of states */ int nrule; /* Number of rules */ int nsymbol; /* Number of terminal and nonterminal symbols */ int nterminal; /* Number of terminal symbols */ struct symbol **symbols; /* Sorted array of pointers to symbols */ int errorcnt; /* Number of errors */ struct symbol *errsym; /* The error symbol */ char *name; /* Name of the generated parser */ char *arg; /* Declaration of the 3th argument to parser */ char *tokentype; /* Type of terminal symbols in the parser stack */ char *vartype; /* The default type of non-terminal symbols */ char *start; /* Name of the start symbol for the grammar */ char *stacksize; /* Size of the parser stack */ char *include; /* Code to put at the start of the C file */ int includeln; /* Line number for start of include code */ char *error; /* Code to execute when an error is seen */ int errorln; /* Line number for start of error code */ char *overflow; /* Code to execute on a stack overflow */ int overflowln; /* Line number for start of overflow code */ char *failure; /* Code to execute on parser failure */ int failureln; /* Line number for start of failure code */ char *accept; /* Code to execute when the parser excepts */ int acceptln; /* Line number for the start of accept code */ char *extracode; /* Code appended to the generated file */ int extracodeln; /* Line number for the start of the extra code */ char *tokendest; /* Code to execute to destroy token data */ int tokendestln; /* Line number for token destroyer code */ char *vardest; /* Code for the default non-terminal destructor */ int vardestln; /* Line number for default non-term destructor code*/ char *filename; /* Name of the input file */ char *outname; /* Name of the current output file */ char *tokenprefix; /* A prefix added to token names in the .h file */ int nconflict; /* Number of parsing conflicts */ int tablesize; /* Size of the parse tables */ int basisflag; /* Print only basis configurations */ int has_fallback; /* True if any %fallback is seen in the grammer */ char *argv0; /* Name of the program */ }; #define MemoryCheck(X) if((X)==0){ \ extern void memory_error(); \ memory_error(); \ } /**************** From the file "table.h" *********************************/ /* ** All code in this file has been automatically generated ** from a specification in the file ** "table.q" ** by the associative array code building program "aagen". ** Do not edit this file! Instead, edit the specification ** file, then rerun aagen. */ /* ** Code for processing tables in the LEMON parser generator. */ /* Routines for handling a strings */ char *Strsafe(); void Strsafe_init(/* void */); int Strsafe_insert(/* char * */); char *Strsafe_find(/* char * */); /* Routines for handling symbols of the grammar */ struct symbol *Symbol_new(); int Symbolcmpp(/* struct symbol **, struct symbol ** */); void Symbol_init(/* void */); int Symbol_insert(/* struct symbol *, char * */); struct symbol *Symbol_find(/* char * */); struct symbol *Symbol_Nth(/* int */); int Symbol_count(/* */); struct symbol **Symbol_arrayof(/* */); /* Routines to manage the state table */ int Configcmp(/* struct config *, struct config * */); struct state *State_new(); void State_init(/* void */); int State_insert(/* struct state *, struct config * */); struct state *State_find(/* struct config * */); struct state **State_arrayof(/* */); /* Routines used for efficiency in Configlist_add */ void Configtable_init(/* void */); int Configtable_insert(/* struct config * */); struct config *Configtable_find(/* struct config * */); void Configtable_clear(/* int(*)(struct config *) */); /****************** From the file "action.c" *******************************/ /* ** Routines processing parser actions in the LEMON parser generator. */ /* Allocate a new parser action */ struct action *Action_new(){ static struct action *freelist = 0; struct action *new; if( freelist==0 ){ int i; int amt = 100; freelist = (struct action *)malloc( sizeof(struct action)*amt ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new parser action."); exit(1); } for(i=0; inext; return new; } /* Compare two actions */ static int actioncmp(ap1,ap2) struct action *ap1; struct action *ap2; { int rc; rc = ap1->sp->index - ap2->sp->index; if( rc==0 ) rc = (int)ap1->type - (int)ap2->type; if( rc==0 ){ assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT); assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT); rc = ap1->x.rp->index - ap2->x.rp->index; } return rc; } /* Sort parser actions */ struct action *Action_sort(ap) struct action *ap; { ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp); return ap; } void Action_add(app,type,sp,arg) struct action **app; enum e_action type; struct symbol *sp; char *arg; { struct action *new; new = Action_new(); new->next = *app; *app = new; new->type = type; new->sp = sp; if( type==SHIFT ){ new->x.stp = (struct state *)arg; }else{ new->x.rp = (struct rule *)arg; } } /********************** New code to implement the "acttab" module ***********/ /* ** This module implements routines use to construct the yy_action[] table. */ /* ** The state of the yy_action table under construction is an instance of ** the following structure */ typedef struct acttab acttab; struct acttab { int nAction; /* Number of used slots in aAction[] */ int nActionAlloc; /* Slots allocated for aAction[] */ struct { int lookahead; /* Value of the lookahead token */ int action; /* Action to take on the given lookahead */ } *aAction, /* The yy_action[] table under construction */ *aLookahead; /* A single new transaction set */ int mnLookahead; /* Minimum aLookahead[].lookahead */ int mnAction; /* Action associated with mnLookahead */ int mxLookahead; /* Maximum aLookahead[].lookahead */ int nLookahead; /* Used slots in aLookahead[] */ int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ }; /* Return the number of entries in the yy_action table */ #define acttab_size(X) ((X)->nAction) /* The value for the N-th entry in yy_action */ #define acttab_yyaction(X,N) ((X)->aAction[N].action) /* The value for the N-th entry in yy_lookahead */ #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) /* Free all memory associated with the given acttab */ void acttab_free(acttab *p){ free( p->aAction ); free( p->aLookahead ); free( p ); } /* Allocate a new acttab structure */ acttab *acttab_alloc(void){ acttab *p = malloc( sizeof(*p) ); if( p==0 ){ fprintf(stderr,"Unable to allocate memory for a new acttab."); exit(1); } memset(p, 0, sizeof(*p)); return p; } /* Add a new action to the current transaction set */ void acttab_action(acttab *p, int lookahead, int action){ if( p->nLookahead>=p->nLookaheadAlloc ){ p->nLookaheadAlloc += 25; p->aLookahead = realloc( p->aLookahead, sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); if( p->aLookahead==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } } if( p->nLookahead==0 ){ p->mxLookahead = lookahead; p->mnLookahead = lookahead; p->mnAction = action; }else{ if( p->mxLookaheadmxLookahead = lookahead; if( p->mnLookahead>lookahead ){ p->mnLookahead = lookahead; p->mnAction = action; } } p->aLookahead[p->nLookahead].lookahead = lookahead; p->aLookahead[p->nLookahead].action = action; p->nLookahead++; } /* ** Add the transaction set built up with prior calls to acttab_action() ** into the current action table. Then reset the transaction set back ** to an empty set in preparation for a new round of acttab_action() calls. ** ** Return the offset into the action table of the new transaction. */ int acttab_insert(acttab *p){ int i, j, k, n; assert( p->nLookahead>0 ); /* Make sure we have enough space to hold the expanded action table ** in the worst case. The worst case occurs if the transaction set ** must be appended to the current action table */ n = p->mxLookahead + 1; if( p->nAction + n >= p->nActionAlloc ){ int oldAlloc = p->nActionAlloc; p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; p->aAction = realloc( p->aAction, sizeof(p->aAction[0])*p->nActionAlloc); if( p->aAction==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } for(i=oldAlloc; inActionAlloc; i++){ p->aAction[i].lookahead = -1; p->aAction[i].action = -1; } } /* Scan the existing action table looking for an offset where we can ** insert the current transaction set. Fall out of the loop when that ** offset is found. In the worst case, we fall out of the loop when ** i reaches p->nAction, which means we append the new transaction set. ** ** i is the index in p->aAction[] where p->mnLookahead is inserted. */ for(i=0; inAction+p->mnLookahead; i++){ if( p->aAction[i].lookahead<0 ){ for(j=0; jnLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; if( k<0 ) break; if( p->aAction[k].lookahead>=0 ) break; } if( jnLookahead ) continue; for(j=0; jnAction; j++){ if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; } if( j==p->nAction ){ break; /* Fits in empty slots */ } }else if( p->aAction[i].lookahead==p->mnLookahead ){ if( p->aAction[i].action!=p->mnAction ) continue; for(j=0; jnLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; if( k<0 || k>=p->nAction ) break; if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; if( p->aLookahead[j].action!=p->aAction[k].action ) break; } if( jnLookahead ) continue; n = 0; for(j=0; jnAction; j++){ if( p->aAction[j].lookahead<0 ) continue; if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; } if( n==p->nLookahead ){ break; /* Same as a prior transaction set */ } } } /* Insert transaction set at index i. */ for(j=0; jnLookahead; j++){ k = p->aLookahead[j].lookahead - p->mnLookahead + i; p->aAction[k] = p->aLookahead[j]; if( k>=p->nAction ) p->nAction = k+1; } p->nLookahead = 0; /* Return the offset that is added to the lookahead in order to get the ** index into yy_action of the action */ return i - p->mnLookahead; } /********************** From the file "assert.c" ****************************/ /* ** A more efficient way of handling assertions. */ void myassert(file,line) char *file; int line; { fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file); exit(1); } /********************** From the file "build.c" *****************************/ /* ** Routines to construction the finite state machine for the LEMON ** parser generator. */ /* Find a precedence symbol of every rule in the grammar. ** ** Those rules which have a precedence symbol coded in the input ** grammar using the "[symbol]" construct will already have the ** rp->precsym field filled. Other rules take as their precedence ** symbol the first RHS symbol with a defined precedence. If there ** are not RHS symbols with a defined precedence, the precedence ** symbol field is left blank. */ void FindRulePrecedences(xp) struct lemon *xp; { struct rule *rp; for(rp=xp->rule; rp; rp=rp->next){ if( rp->precsym==0 ){ int i; for(i=0; inrhs; i++){ if( rp->rhs[i]->prec>=0 ){ rp->precsym = rp->rhs[i]; break; } } } } return; } /* Find all nonterminals which will generate the empty string. ** Then go back and compute the first sets of every nonterminal. ** The first set is the set of all terminal symbols which can begin ** a string generated by that nonterminal. */ void FindFirstSets(lemp) struct lemon *lemp; { int i; struct rule *rp; int progress; for(i=0; insymbol; i++){ lemp->symbols[i]->lambda = B_FALSE; } for(i=lemp->nterminal; insymbol; i++){ lemp->symbols[i]->firstset = SetNew(); } /* First compute all lambdas */ do{ progress = 0; for(rp=lemp->rule; rp; rp=rp->next){ if( rp->lhs->lambda ) continue; for(i=0; inrhs; i++){ if( rp->rhs[i]->lambda==B_FALSE ) break; } if( i==rp->nrhs ){ rp->lhs->lambda = B_TRUE; progress = 1; } } }while( progress ); /* Now compute all first sets */ do{ struct symbol *s1, *s2; progress = 0; for(rp=lemp->rule; rp; rp=rp->next){ s1 = rp->lhs; for(i=0; inrhs; i++){ s2 = rp->rhs[i]; if( s2->type==TERMINAL ){ progress += SetAdd(s1->firstset,s2->index); break; }else if( s1==s2 ){ if( s1->lambda==B_FALSE ) break; }else{ progress += SetUnion(s1->firstset,s2->firstset); if( s2->lambda==B_FALSE ) break; } } } }while( progress ); return; } /* Compute all LR(0) states for the grammar. Links ** are added to between some states so that the LR(1) follow sets ** can be computed later. */ PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */ void FindStates(lemp) struct lemon *lemp; { struct symbol *sp; struct rule *rp; Configlist_init(); /* Find the start symbol */ if( lemp->start ){ sp = Symbol_find(lemp->start); if( sp==0 ){ ErrorMsg(lemp->filename,0, "The specified start symbol \"%s\" is not \ in a nonterminal of the grammar. \"%s\" will be used as the start \ symbol instead.",lemp->start,lemp->rule->lhs->name); lemp->errorcnt++; sp = lemp->rule->lhs; } }else{ sp = lemp->rule->lhs; } /* Make sure the start symbol doesn't occur on the right-hand side of ** any rule. Report an error if it does. (YACC would generate a new ** start symbol in this case.) */ for(rp=lemp->rule; rp; rp=rp->next){ int i; for(i=0; inrhs; i++){ if( rp->rhs[i]==sp ){ ErrorMsg(lemp->filename,0, "The start symbol \"%s\" occurs on the \ right-hand side of a rule. This will result in a parser which \ does not work properly.",sp->name); lemp->errorcnt++; } } } /* The basis configuration set for the first state ** is all rules which have the start symbol as their ** left-hand side */ for(rp=sp->rule; rp; rp=rp->nextlhs){ struct config *newcfp; newcfp = Configlist_addbasis(rp,0); SetAdd(newcfp->fws,0); } /* Compute the first state. All other states will be ** computed automatically during the computation of the first one. ** The returned pointer to the first state is not used. */ (void)getstate(lemp); return; } /* Return a pointer to a state which is described by the configuration ** list which has been built from calls to Configlist_add. */ PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */ PRIVATE struct state *getstate(lemp) struct lemon *lemp; { struct config *cfp, *bp; struct state *stp; /* Extract the sorted basis of the new state. The basis was constructed ** by prior calls to "Configlist_addbasis()". */ Configlist_sortbasis(); bp = Configlist_basis(); /* Get a state with the same basis */ stp = State_find(bp); if( stp ){ /* A state with the same basis already exists! Copy all the follow-set ** propagation links from the state under construction into the ** preexisting state, then return a pointer to the preexisting state */ struct config *x, *y; for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ Plink_copy(&y->bplp,x->bplp); Plink_delete(x->fplp); x->fplp = x->bplp = 0; } cfp = Configlist_return(); Configlist_eat(cfp); }else{ /* This really is a new state. Construct all the details */ Configlist_closure(lemp); /* Compute the configuration closure */ Configlist_sort(); /* Sort the configuration closure */ cfp = Configlist_return(); /* Get a pointer to the config list */ stp = State_new(); /* A new state structure */ MemoryCheck(stp); stp->bp = bp; /* Remember the configuration basis */ stp->cfp = cfp; /* Remember the configuration closure */ stp->index = lemp->nstate++; /* Every state gets a sequence number */ stp->ap = 0; /* No actions, yet. */ State_insert(stp,stp->bp); /* Add to the state table */ buildshifts(lemp,stp); /* Recursively compute successor states */ } return stp; } /* Construct all successor states to the given state. A "successor" ** state is any state which can be reached by a shift action. */ PRIVATE void buildshifts(lemp,stp) struct lemon *lemp; struct state *stp; /* The state from which successors are computed */ { struct config *cfp; /* For looping thru the config closure of "stp" */ struct config *bcfp; /* For the inner loop on config closure of "stp" */ struct config *new; /* */ struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ struct state *newstp; /* A pointer to a successor state */ /* Each configuration becomes complete after it contibutes to a successor ** state. Initially, all configurations are incomplete */ for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; /* Loop through all configurations of the state "stp" */ for(cfp=stp->cfp; cfp; cfp=cfp->next){ if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ Configlist_reset(); /* Reset the new config set */ sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ /* For every configuration in the state "stp" which has the symbol "sp" ** following its dot, add the same configuration to the basis set under ** construction but with the dot shifted one symbol to the right. */ for(bcfp=cfp; bcfp; bcfp=bcfp->next){ if( bcfp->status==COMPLETE ) continue; /* Already used */ if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ if( bsp!=sp ) continue; /* Must be same as for "cfp" */ bcfp->status = COMPLETE; /* Mark this config as used */ new = Configlist_addbasis(bcfp->rp,bcfp->dot+1); Plink_add(&new->bplp,bcfp); } /* Get a pointer to the state described by the basis configuration set ** constructed in the preceding loop */ newstp = getstate(lemp); /* The state "newstp" is reached from the state "stp" by a shift action ** on the symbol "sp" */ Action_add(&stp->ap,SHIFT,sp,(char *)newstp); } } /* ** Construct the propagation links */ void FindLinks(lemp) struct lemon *lemp; { int i; struct config *cfp, *other; struct state *stp; struct plink *plp; /* Housekeeping detail: ** Add to every propagate link a pointer back to the state to ** which the link is attached. */ for(i=0; instate; i++){ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ cfp->stp = stp; } } /* Convert all backlinks into forward links. Only the forward ** links are used in the follow-set computation. */ for(i=0; instate; i++){ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ for(plp=cfp->bplp; plp; plp=plp->next){ other = plp->cfp; Plink_add(&other->fplp,cfp); } } } } /* Compute all followsets. ** ** A followset is the set of all symbols which can come immediately ** after a configuration. */ void FindFollowSets(lemp) struct lemon *lemp; { int i; struct config *cfp; struct plink *plp; int progress; int change; for(i=0; instate; i++){ for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ cfp->status = INCOMPLETE; } } do{ progress = 0; for(i=0; instate; i++){ for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ if( cfp->status==COMPLETE ) continue; for(plp=cfp->fplp; plp; plp=plp->next){ change = SetUnion(plp->cfp->fws,cfp->fws); if( change ){ plp->cfp->status = INCOMPLETE; progress = 1; } } cfp->status = COMPLETE; } } }while( progress ); } static int resolve_conflict(); /* Compute the reduce actions, and resolve conflicts. */ void FindActions(lemp) struct lemon *lemp; { int i,j; struct config *cfp; struct state *stp; struct symbol *sp; struct rule *rp; /* Add all of the reduce actions ** A reduce action is added for each element of the followset of ** a configuration which has its dot at the extreme right. */ for(i=0; instate; i++){ /* Loop over all states */ stp = lemp->sorted[i]; for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ for(j=0; jnterminal; j++){ if( SetFind(cfp->fws,j) ){ /* Add a reduce action to the state "stp" which will reduce by the ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); } } } } } /* Add the accepting token */ if( lemp->start ){ sp = Symbol_find(lemp->start); if( sp==0 ) sp = lemp->rule->lhs; }else{ sp = lemp->rule->lhs; } /* Add to the first state (which is always the starting state of the ** finite state machine) an action to ACCEPT if the lookahead is the ** start nonterminal. */ Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); /* Resolve conflicts */ for(i=0; instate; i++){ struct action *ap, *nap; struct state *stp; stp = lemp->sorted[i]; assert( stp->ap ); stp->ap = Action_sort(stp->ap); for(ap=stp->ap; ap && ap->next; ap=ap->next){ for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ /* The two actions "ap" and "nap" have the same lookahead. ** Figure out which one should be used */ lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym); } } } /* Report an error for each rule that can never be reduced. */ for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = B_FALSE; for(i=0; instate; i++){ struct action *ap; for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ if( ap->type==REDUCE ) ap->x.rp->canReduce = B_TRUE; } } for(rp=lemp->rule; rp; rp=rp->next){ if( rp->canReduce ) continue; ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); lemp->errorcnt++; } } /* Resolve a conflict between the two given actions. If the ** conflict can't be resolve, return non-zero. ** ** NO LONGER TRUE: ** To resolve a conflict, first look to see if either action ** is on an error rule. In that case, take the action which ** is not associated with the error rule. If neither or both ** actions are associated with an error rule, then try to ** use precedence to resolve the conflict. ** ** If either action is a SHIFT, then it must be apx. This ** function won't work if apx->type==REDUCE and apy->type==SHIFT. */ static int resolve_conflict(apx,apy,errsym) struct action *apx; struct action *apy; struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */ { struct symbol *spx, *spy; int errcnt = 0; assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ if( apx->type==SHIFT && apy->type==REDUCE ){ spx = apx->sp; spy = apy->x.rp->precsym; if( spy==0 || spx->prec<0 || spy->prec<0 ){ /* Not enough precedence information. */ fprintf(stderr, "Not enough precedence: %s\n", errsym->name); apy->type = CONFLICT; errcnt++; }else if( spx->prec>spy->prec ){ /* Lower precedence wins */ apy->type = RD_RESOLVED; }else if( spx->precprec ){ apx->type = SH_RESOLVED; }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ apy->type = RD_RESOLVED; /* associativity */ }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ apx->type = SH_RESOLVED; }else{ assert( spx->prec==spy->prec && spx->assoc==NONE ); fprintf(stderr, "Not enough precedence: %s\n", errsym->name); apy->type = CONFLICT; errcnt++; } }else if( apx->type==REDUCE && apy->type==REDUCE ){ spx = apx->x.rp->precsym; spy = apy->x.rp->precsym; if( spx==0 || spy==0 || spx->prec<0 || spy->prec<0 || spx->prec==spy->prec ){ fprintf(stderr, "Not enough precedence: %s\n", errsym->name); apy->type = CONFLICT; errcnt++; }else if( spx->prec>spy->prec ){ apy->type = RD_RESOLVED; }else if( spx->precprec ){ apx->type = RD_RESOLVED; } }else{ assert( apx->type==SH_RESOLVED || apx->type==RD_RESOLVED || apx->type==CONFLICT || apy->type==SH_RESOLVED || apy->type==RD_RESOLVED || apy->type==CONFLICT ); /* The REDUCE/SHIFT case cannot happen because SHIFTs come before ** REDUCEs on the list. If we reach this point it must be because ** the parser conflict had already been resolved. */ } return errcnt; } /********************* From the file "configlist.c" *************************/ /* ** Routines to processing a configuration list and building a state ** in the LEMON parser generator. */ static struct config *freelist = 0; /* List of free configurations */ static struct config *current = 0; /* Top of list of configurations */ static struct config **currentend = 0; /* Last on list of configs */ static struct config *basis = 0; /* Top of list of basis configs */ static struct config **basisend = 0; /* End of list of basis configs */ /* Return a pointer to a new configuration */ PRIVATE struct config *newconfig(){ struct config *new; if( freelist==0 ){ int i; int amt = 3; freelist = (struct config *)malloc( sizeof(struct config)*amt ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new configuration."); exit(1); } for(i=0; inext; return new; } /* The configuration "old" is no longer used */ PRIVATE void deleteconfig(old) struct config *old; { old->next = freelist; freelist = old; } /* Initialized the configuration list builder */ void Configlist_init(){ current = 0; currentend = ¤t; basis = 0; basisend = &basis; Configtable_init(); return; } /* Initialized the configuration list builder */ void Configlist_reset(){ current = 0; currentend = ¤t; basis = 0; basisend = &basis; Configtable_clear(0); return; } /* Add another configuration to the configuration list */ struct config *Configlist_add(rp,dot) struct rule *rp; /* The rule */ int dot; /* Index into the RHS of the rule where the dot goes */ { struct config *cfp, model; assert( currentend!=0 ); model.rp = rp; model.dot = dot; cfp = Configtable_find(&model); if( cfp==0 ){ cfp = newconfig(); cfp->rp = rp; cfp->dot = dot; cfp->fws = SetNew(); cfp->stp = 0; cfp->fplp = cfp->bplp = 0; cfp->next = 0; cfp->bp = 0; *currentend = cfp; currentend = &cfp->next; Configtable_insert(cfp); } return cfp; } /* Add a basis configuration to the configuration list */ struct config *Configlist_addbasis(rp,dot) struct rule *rp; int dot; { struct config *cfp, model; assert( basisend!=0 ); assert( currentend!=0 ); model.rp = rp; model.dot = dot; cfp = Configtable_find(&model); if( cfp==0 ){ cfp = newconfig(); cfp->rp = rp; cfp->dot = dot; cfp->fws = SetNew(); cfp->stp = 0; cfp->fplp = cfp->bplp = 0; cfp->next = 0; cfp->bp = 0; *currentend = cfp; currentend = &cfp->next; *basisend = cfp; basisend = &cfp->bp; Configtable_insert(cfp); } return cfp; } /* Compute the closure of the configuration list */ void Configlist_closure(lemp) struct lemon *lemp; { struct config *cfp, *newcfp; struct rule *rp, *newrp; struct symbol *sp, *xsp; int i, dot; assert( currentend!=0 ); for(cfp=current; cfp; cfp=cfp->next){ rp = cfp->rp; dot = cfp->dot; if( dot>=rp->nrhs ) continue; sp = rp->rhs[dot]; if( sp->type==NONTERMINAL ){ if( sp->rule==0 && sp!=lemp->errsym ){ ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", sp->name); lemp->errorcnt++; } for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ newcfp = Configlist_add(newrp,0); for(i=dot+1; inrhs; i++){ xsp = rp->rhs[i]; if( xsp->type==TERMINAL ){ SetAdd(newcfp->fws,xsp->index); break; }else{ SetUnion(newcfp->fws,xsp->firstset); if( xsp->lambda==B_FALSE ) break; } } if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); } } } return; } /* Sort the configuration list */ void Configlist_sort(){ current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); currentend = 0; return; } /* Sort the basis configuration list */ void Configlist_sortbasis(){ basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); basisend = 0; return; } /* Return a pointer to the head of the configuration list and ** reset the list */ struct config *Configlist_return(){ struct config *old; old = current; current = 0; currentend = 0; return old; } /* Return a pointer to the head of the configuration list and ** reset the list */ struct config *Configlist_basis(){ struct config *old; old = basis; basis = 0; basisend = 0; return old; } /* Free all elements of the given configuration list */ void Configlist_eat(cfp) struct config *cfp; { struct config *nextcfp; for(; cfp; cfp=nextcfp){ nextcfp = cfp->next; assert( cfp->fplp==0 ); assert( cfp->bplp==0 ); if( cfp->fws ) SetFree(cfp->fws); deleteconfig(cfp); } return; } /***************** From the file "error.c" *********************************/ /* ** Code for printing error message. */ /* Find a good place to break "msg" so that its length is at least "min" ** but no more than "max". Make the point as close to max as possible. */ static int findbreak(msg,min,max) char *msg; int min; int max; { int i,spot; char c; for(i=spot=min; i<=max; i++){ c = msg[i]; if( c=='\t' ) msg[i] = ' '; if( c=='\n' ){ msg[i] = ' '; spot = i; break; } if( c==0 ){ spot = i; break; } if( c=='-' && i0 ){ sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno); }else{ sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename); } prefixsize = strlen(prefix); availablewidth = LINEWIDTH - prefixsize; /* Generate the error message */ vsprintf(errmsg,format,ap); va_end(ap); errmsgsize = strlen(errmsg); /* Remove trailing '\n's from the error message. */ while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){ errmsg[--errmsgsize] = 0; } /* Print the error message */ base = 0; while( errmsg[base]!=0 ){ end = restart = findbreak(&errmsg[base],0,availablewidth); restart += base; while( errmsg[restart]==' ' ) restart++; fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]); base = restart; } } /**************** From the file "main.c" ************************************/ /* ** Main program file for the LEMON parser generator. */ /* Report an out-of-memory condition and abort. This function ** is used mostly by the "MemoryCheck" macro in struct.h */ void memory_error(){ fprintf(stderr,"Out of memory. Aborting...\n"); exit(1); } static int nDefine = 0; /* Number of -D options on the command line */ static char **azDefine = 0; /* Name of the -D macros */ /* This routine is called with the argument to each -D command-line option. ** Add the macro defined to the azDefine array. */ static void handle_D_option(char *z){ char **paz; nDefine++; azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine); if( azDefine==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } paz = &azDefine[nDefine-1]; *paz = malloc( strlen(z)+1 ); if( *paz==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } strcpy(*paz, z); for(z=*paz; *z && *z!='='; z++){} *z = 0; } /* The main program. Parse the command line and do it... */ int main(argc,argv) int argc; char **argv; { static int version = 0; static int rpflag = 0; static int basisflag = 0; static int compress = 0; static int quiet = 0; static int statistics = 0; static int mhflag = 0; static struct s_options options[] = { {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."}, {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."}, {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."}, {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"}, {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."}, {OPT_FLAG, "x", (char*)&version, "Print the version number."}, {OPT_FLAG,0,0,0} }; int i; struct lemon lem; OptInit(argv,options,stderr); if( version ){ printf("Lemon version 1.0\n"); exit(0); } if( OptNArgs()!=1 ){ fprintf(stderr,"Exactly one filename argument is required.\n"); exit(1); } lem.errorcnt = 0; /* Initialize the machine */ Strsafe_init(); Symbol_init(); State_init(); lem.argv0 = argv[0]; lem.filename = OptArg(0); lem.basisflag = basisflag; lem.has_fallback = 0; lem.nconflict = 0; lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0; lem.vartype = 0; lem.stacksize = 0; lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest = lem.tokenprefix = lem.outname = lem.extracode = 0; lem.vardest = 0; lem.tablesize = 0; Symbol_new("$"); lem.errsym = Symbol_new("error"); /* Parse the input file */ Parse(&lem); if( lem.errorcnt ) exit(lem.errorcnt); if( lem.rule==0 ){ fprintf(stderr,"Empty grammar.\n"); exit(1); } /* Count and index the symbols of the grammar */ lem.nsymbol = Symbol_count(); Symbol_new("{default}"); lem.symbols = Symbol_arrayof(); for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), (int(*)())Symbolcmpp); for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; for(i=1; isupper(lem.symbols[i]->name[0]); i++); lem.nterminal = i; /* Generate a reprint of the grammar, if requested on the command line */ if( rpflag ){ Reprint(&lem); }else{ /* Initialize the size for all follow and first sets */ SetSize(lem.nterminal); /* Find the precedence for every production rule (that has one) */ FindRulePrecedences(&lem); /* Compute the lambda-nonterminals and the first-sets for every ** nonterminal */ FindFirstSets(&lem); /* Compute all LR(0) states. Also record follow-set propagation ** links so that the follow-set can be computed later */ lem.nstate = 0; FindStates(&lem); lem.sorted = State_arrayof(); /* Tie up loose ends on the propagation links */ FindLinks(&lem); /* Compute the follow set of every reducible configuration */ FindFollowSets(&lem); /* Compute the action tables */ FindActions(&lem); /* Compress the action tables */ if( compress==0 ) CompressTables(&lem); /* Generate a report of the parser generated. (the "y.output" file) */ if( !quiet ) ReportOutput(&lem); /* Generate the source code for the parser */ ReportTable(&lem, mhflag); /* Produce a header file for use by the scanner. (This step is ** omitted if the "-m" option is used because makeheaders will ** generate the file for us.) */ if( !mhflag ) ReportHeader(&lem); } if( statistics ){ printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n", lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); printf(" %d states, %d parser table entries, %d conflicts\n", lem.nstate, lem.tablesize, lem.nconflict); } if( lem.nconflict ){ fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); } exit(lem.errorcnt + lem.nconflict); return (lem.errorcnt + lem.nconflict); } /******************** From the file "msort.c" *******************************/ /* ** A generic merge-sort program. ** ** USAGE: ** Let "ptr" be a pointer to some structure which is at the head of ** a null-terminated list. Then to sort the list call: ** ** ptr = msort(ptr,&(ptr->next),cmpfnc); ** ** In the above, "cmpfnc" is a pointer to a function which compares ** two instances of the structure and returns an integer, as in ** strcmp. The second argument is a pointer to the pointer to the ** second element of the linked list. This address is used to compute ** the offset to the "next" field within the structure. The offset to ** the "next" field must be constant for all structures in the list. ** ** The function returns a new pointer which is the head of the list ** after sorting. ** ** ALGORITHM: ** Merge-sort. */ /* ** Return a pointer to the next structure in the linked list. */ #define NEXT(A) (*(char**)(((unsigned long)A)+offset)) /* ** Inputs: ** a: A sorted, null-terminated linked list. (May be null). ** b: A sorted, null-terminated linked list. (May be null). ** cmp: A pointer to the comparison function. ** offset: Offset in the structure to the "next" field. ** ** Return Value: ** A pointer to the head of a sorted list containing the elements ** of both a and b. ** ** Side effects: ** The "next" pointers for elements in the lists a and b are ** changed. */ static char *merge(a,b,cmp,offset) char *a; char *b; int (*cmp)(); int offset; { char *ptr, *head; if( a==0 ){ head = b; }else if( b==0 ){ head = a; }else{ if( (*cmp)(a,b)<0 ){ ptr = a; a = NEXT(a); }else{ ptr = b; b = NEXT(b); } head = ptr; while( a && b ){ if( (*cmp)(a,b)<0 ){ NEXT(ptr) = a; ptr = a; a = NEXT(a); }else{ NEXT(ptr) = b; ptr = b; b = NEXT(b); } } if( a ) NEXT(ptr) = a; else NEXT(ptr) = b; } return head; } /* ** Inputs: ** list: Pointer to a singly-linked list of structures. ** next: Pointer to pointer to the second element of the list. ** cmp: A comparison function. ** ** Return Value: ** A pointer to the head of a sorted list containing the elements ** orginally in list. ** ** Side effects: ** The "next" pointers for elements in list are changed. */ #define LISTSIZE 30 char *msort(list,next,cmp) char *list; char **next; int (*cmp)(); { unsigned long offset; char *ep; char *set[LISTSIZE]; int i; offset = (unsigned long)next - (unsigned long)list; for(i=0; istate = WAITING_FOR_DECL_KEYWORD; }else if( islower(x[0]) ){ psp->lhs = Symbol_new(x); psp->nrhs = 0; psp->lhsalias = 0; psp->state = WAITING_FOR_ARROW; }else if( x[0]=='{' ){ if( psp->prevrule==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "There is not prior rule opon which to attach the code \ fragment which begins on this line."); psp->errorcnt++; }else if( psp->prevrule->code!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Code fragment beginning on this line is not the first \ to follow the previous rule."); psp->errorcnt++; }else{ psp->prevrule->line = psp->tokenlineno; psp->prevrule->code = &x[1]; } }else if( x[0]=='[' ){ psp->state = PRECEDENCE_MARK_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Token \"%s\" should be either \"%%\" or a nonterminal name.", x); psp->errorcnt++; } break; case PRECEDENCE_MARK_1: if( !isupper(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "The precedence symbol must be a terminal."); psp->errorcnt++; }else if( psp->prevrule==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "There is no prior rule to assign precedence \"[%s]\".",x); psp->errorcnt++; }else if( psp->prevrule->precsym!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Precedence mark on this line is not the first \ to follow the previous rule."); psp->errorcnt++; }else{ psp->prevrule->precsym = Symbol_new(x); } psp->state = PRECEDENCE_MARK_2; break; case PRECEDENCE_MARK_2: if( x[0]!=']' ){ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \"]\" on precedence mark."); psp->errorcnt++; } psp->state = WAITING_FOR_DECL_OR_RULE; break; case WAITING_FOR_ARROW: if( x[0]==':' && x[1]==':' && x[2]=='=' ){ psp->state = IN_RHS; }else if( x[0]=='(' ){ psp->state = LHS_ALIAS_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Expected to see a \":\" following the LHS symbol \"%s\".", psp->lhs->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_1: if( isalpha(x[0]) ){ psp->lhsalias = x; psp->state = LHS_ALIAS_2; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "\"%s\" is not a valid alias for the LHS \"%s\"\n", x,psp->lhs->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_2: if( x[0]==')' ){ psp->state = LHS_ALIAS_3; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case LHS_ALIAS_3: if( x[0]==':' && x[1]==':' && x[2]=='=' ){ psp->state = IN_RHS; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \"->\" following: \"%s(%s)\".", psp->lhs->name,psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case IN_RHS: if( x[0]=='.' ){ struct rule *rp; rp = (struct rule *)malloc( sizeof(struct rule) + sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs ); if( rp==0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Can't allocate enough memory for this rule."); psp->errorcnt++; psp->prevrule = 0; }else{ int i; rp->ruleline = psp->tokenlineno; rp->rhs = (struct symbol**)&rp[1]; rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]); for(i=0; inrhs; i++){ rp->rhs[i] = psp->rhs[i]; rp->rhsalias[i] = psp->alias[i]; } rp->lhs = psp->lhs; rp->lhsalias = psp->lhsalias; rp->nrhs = psp->nrhs; rp->code = 0; rp->precsym = 0; rp->index = psp->gp->nrule++; rp->nextlhs = rp->lhs->rule; rp->lhs->rule = rp; rp->next = 0; if( psp->firstrule==0 ){ psp->firstrule = psp->lastrule = rp; }else{ psp->lastrule->next = rp; psp->lastrule = rp; } psp->prevrule = rp; } psp->state = WAITING_FOR_DECL_OR_RULE; }else if( isalpha(x[0]) ){ if( psp->nrhs>=MAXRHS ){ ErrorMsg(psp->filename,psp->tokenlineno, "Too many symbol on RHS or rule beginning at \"%s\".", x); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; }else{ psp->rhs[psp->nrhs] = Symbol_new(x); psp->alias[psp->nrhs] = 0; psp->nrhs++; } }else if( x[0]=='(' && psp->nrhs>0 ){ psp->state = RHS_ALIAS_1; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal character on RHS of rule: \"%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case RHS_ALIAS_1: if( isalpha(x[0]) ){ psp->alias[psp->nrhs-1] = x; psp->state = RHS_ALIAS_2; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", x,psp->rhs[psp->nrhs-1]->name); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case RHS_ALIAS_2: if( x[0]==')' ){ psp->state = IN_RHS; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); psp->errorcnt++; psp->state = RESYNC_AFTER_RULE_ERROR; } break; case WAITING_FOR_DECL_KEYWORD: if( isalpha(x[0]) ){ psp->declkeyword = x; psp->declargslot = 0; psp->decllnslot = 0; psp->state = WAITING_FOR_DECL_ARG; if( strcmp(x,"name")==0 ){ psp->declargslot = &(psp->gp->name); }else if( strcmp(x,"include")==0 ){ psp->declargslot = &(psp->gp->include); psp->decllnslot = &psp->gp->includeln; }else if( strcmp(x,"code")==0 ){ psp->declargslot = &(psp->gp->extracode); psp->decllnslot = &psp->gp->extracodeln; }else if( strcmp(x,"token_destructor")==0 ){ psp->declargslot = &psp->gp->tokendest; psp->decllnslot = &psp->gp->tokendestln; }else if( strcmp(x,"default_destructor")==0 ){ psp->declargslot = &psp->gp->vardest; psp->decllnslot = &psp->gp->vardestln; }else if( strcmp(x,"token_prefix")==0 ){ psp->declargslot = &psp->gp->tokenprefix; }else if( strcmp(x,"syntax_error")==0 ){ psp->declargslot = &(psp->gp->error); psp->decllnslot = &psp->gp->errorln; }else if( strcmp(x,"parse_accept")==0 ){ psp->declargslot = &(psp->gp->accept); psp->decllnslot = &psp->gp->acceptln; }else if( strcmp(x,"parse_failure")==0 ){ psp->declargslot = &(psp->gp->failure); psp->decllnslot = &psp->gp->failureln; }else if( strcmp(x,"stack_overflow")==0 ){ psp->declargslot = &(psp->gp->overflow); psp->decllnslot = &psp->gp->overflowln; }else if( strcmp(x,"extra_argument")==0 ){ psp->declargslot = &(psp->gp->arg); }else if( strcmp(x,"token_type")==0 ){ psp->declargslot = &(psp->gp->tokentype); }else if( strcmp(x,"default_type")==0 ){ psp->declargslot = &(psp->gp->vartype); }else if( strcmp(x,"stack_size")==0 ){ psp->declargslot = &(psp->gp->stacksize); }else if( strcmp(x,"start_symbol")==0 ){ psp->declargslot = &(psp->gp->start); }else if( strcmp(x,"left")==0 ){ psp->preccounter++; psp->declassoc = LEFT; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"right")==0 ){ psp->preccounter++; psp->declassoc = RIGHT; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"nonassoc")==0 ){ psp->preccounter++; psp->declassoc = NONE; psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; }else if( strcmp(x,"destructor")==0 ){ psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; }else if( strcmp(x,"type")==0 ){ psp->state = WAITING_FOR_DATATYPE_SYMBOL; }else if( strcmp(x,"fallback")==0 ){ psp->fallback = 0; psp->state = WAITING_FOR_FALLBACK_ID; }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Unknown declaration keyword: \"%%%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal declaration keyword: \"%s\".",x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } break; case WAITING_FOR_DESTRUCTOR_SYMBOL: if( !isalpha(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol name missing after %destructor keyword"); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ struct symbol *sp = Symbol_new(x); psp->declargslot = &sp->destructor; psp->decllnslot = &sp->destructorln; psp->state = WAITING_FOR_DECL_ARG; } break; case WAITING_FOR_DATATYPE_SYMBOL: if( !isalpha(x[0]) ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol name missing after %destructor keyword"); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ struct symbol *sp = Symbol_new(x); psp->declargslot = &sp->datatype; psp->decllnslot = 0; psp->state = WAITING_FOR_DECL_ARG; } break; case WAITING_FOR_PRECEDENCE_SYMBOL: if( x[0]=='.' ){ psp->state = WAITING_FOR_DECL_OR_RULE; }else if( isupper(x[0]) ){ struct symbol *sp; sp = Symbol_new(x); if( sp->prec>=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "Symbol \"%s\" has already be given a precedence.",x); psp->errorcnt++; }else{ sp->prec = psp->preccounter; sp->assoc = psp->declassoc; } }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Can't assign a precedence to \"%s\".",x); psp->errorcnt++; } break; case WAITING_FOR_DECL_ARG: if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){ if( *(psp->declargslot)!=0 ){ ErrorMsg(psp->filename,psp->tokenlineno, "The argument \"%s\" to declaration \"%%%s\" is not the first.", x[0]=='\"' ? &x[1] : x,psp->declkeyword); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; }else{ *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x; if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno; psp->state = WAITING_FOR_DECL_OR_RULE; } }else{ ErrorMsg(psp->filename,psp->tokenlineno, "Illegal argument to %%%s: %s",psp->declkeyword,x); psp->errorcnt++; psp->state = RESYNC_AFTER_DECL_ERROR; } break; case WAITING_FOR_FALLBACK_ID: if( x[0]=='.' ){ psp->state = WAITING_FOR_DECL_OR_RULE; }else if( !isupper(x[0]) ){ ErrorMsg(psp->filename, psp->tokenlineno, "%%fallback argument \"%s\" should be a token", x); psp->errorcnt++; }else{ struct symbol *sp = Symbol_new(x); if( psp->fallback==0 ){ psp->fallback = sp; }else if( sp->fallback ){ ErrorMsg(psp->filename, psp->tokenlineno, "More than one fallback assigned to token %s", x); psp->errorcnt++; }else{ sp->fallback = psp->fallback; psp->gp->has_fallback = 1; } } break; case RESYNC_AFTER_RULE_ERROR: /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; ** break; */ case RESYNC_AFTER_DECL_ERROR: if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; break; } } /* Run the proprocessor over the input file text. The global variables ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and ** comments them out. Text in between is also commented out as appropriate. */ static preprocess_input(char *z){ int i, j, k, n; int exclude = 0; int start; int lineno = 1; int start_lineno; for(i=0; z[i]; i++){ if( z[i]=='\n' ) lineno++; if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){ if( exclude ){ exclude--; if( exclude==0 ){ for(j=start; jfilename; ps.errorcnt = 0; ps.state = INITIALIZE; /* Begin by reading the input file */ fp = fopen(ps.filename,"rb"); if( fp==0 ){ ErrorMsg(ps.filename,0,"Can't open this file for reading."); gp->errorcnt++; return; } fseek(fp,0,2); filesize = ftell(fp); rewind(fp); filebuf = (char *)malloc( filesize+1 ); if( filebuf==0 ){ ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.", filesize+1); gp->errorcnt++; return; } if( fread(filebuf,1,filesize,fp)!=filesize ){ ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", filesize); free(filebuf); gp->errorcnt++; return; } fclose(fp); filebuf[filesize] = 0; /* Make an initial pass through the file to handle %ifdef and %ifndef */ preprocess_input(filebuf); /* Now scan the text of the input file */ lineno = 1; for(cp=filebuf; (c= *cp)!=0; ){ if( c=='\n' ) lineno++; /* Keep track of the line number */ if( isspace(c) ){ cp++; continue; } /* Skip all white space */ if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ cp+=2; while( (c= *cp)!=0 && c!='\n' ) cp++; continue; } if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ cp+=2; while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ if( c=='\n' ) lineno++; cp++; } if( c ) cp++; continue; } ps.tokenstart = cp; /* Mark the beginning of the token */ ps.tokenlineno = lineno; /* Linenumber on which token begins */ if( c=='\"' ){ /* String literals */ cp++; while( (c= *cp)!=0 && c!='\"' ){ if( c=='\n' ) lineno++; cp++; } if( c==0 ){ ErrorMsg(ps.filename,startline, "String starting on this line is not terminated before the end of the file."); ps.errorcnt++; nextcp = cp; }else{ nextcp = cp+1; } }else if( c=='{' ){ /* A block of C code */ int level; cp++; for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ if( c=='\n' ) lineno++; else if( c=='{' ) level++; else if( c=='}' ) level--; else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ int prevc; cp = &cp[2]; prevc = 0; while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ if( c=='\n' ) lineno++; prevc = c; cp++; } }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ cp = &cp[2]; while( (c= *cp)!=0 && c!='\n' ) cp++; if( c ) lineno++; }else if( c=='\'' || c=='\"' ){ /* String a character literals */ int startchar, prevc; startchar = c; prevc = 0; for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ if( c=='\n' ) lineno++; if( prevc=='\\' ) prevc = 0; else prevc = c; } } } if( c==0 ){ ErrorMsg(ps.filename,ps.tokenlineno, "C code starting on this line is not terminated before the end of the file."); ps.errorcnt++; nextcp = cp; }else{ nextcp = cp+1; } }else if( isalnum(c) ){ /* Identifiers */ while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++; nextcp = cp; }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ cp += 3; nextcp = cp; }else{ /* All other (one character) operators */ cp++; nextcp = cp; } c = *cp; *cp = 0; /* Null terminate the token */ parseonetoken(&ps); /* Parse the token */ *cp = c; /* Restore the buffer */ cp = nextcp; } free(filebuf); /* Release the buffer after parsing */ gp->rule = ps.firstrule; gp->errorcnt = ps.errorcnt; } /*************************** From the file "plink.c" *********************/ /* ** Routines processing configuration follow-set propagation links ** in the LEMON parser generator. */ static struct plink *plink_freelist = 0; /* Allocate a new plink */ struct plink *Plink_new(){ struct plink *new; if( plink_freelist==0 ){ int i; int amt = 100; plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt ); if( plink_freelist==0 ){ fprintf(stderr, "Unable to allocate memory for a new follow-set propagation link.\n"); exit(1); } for(i=0; inext; return new; } /* Add a plink to a plink list */ void Plink_add(plpp,cfp) struct plink **plpp; struct config *cfp; { struct plink *new; new = Plink_new(); new->next = *plpp; *plpp = new; new->cfp = cfp; } /* Transfer every plink on the list "from" to the list "to" */ void Plink_copy(to,from) struct plink **to; struct plink *from; { struct plink *nextpl; while( from ){ nextpl = from->next; from->next = *to; *to = from; from = nextpl; } } /* Delete every plink on the list */ void Plink_delete(plp) struct plink *plp; { struct plink *nextpl; while( plp ){ nextpl = plp->next; plp->next = plink_freelist; plink_freelist = plp; plp = nextpl; } } /*********************** From the file "report.c" **************************/ /* ** Procedures for generating reports and tables in the LEMON parser generator. */ /* Generate a filename with the given suffix. Space to hold the ** name comes from malloc() and must be freed by the calling ** function. */ PRIVATE char *file_makename(lemp,suffix) struct lemon *lemp; char *suffix; { char *name; char *cp; name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 ); if( name==0 ){ fprintf(stderr,"Can't allocate space for a filename.\n"); exit(1); } strcpy(name,lemp->filename); cp = strrchr(name,'.'); if( cp ) *cp = 0; strcat(name,suffix); return name; } /* Open a file with a name based on the name of the input file, ** but with a different (specified) suffix, and return a pointer ** to the stream */ PRIVATE FILE *file_open(lemp,suffix,mode) struct lemon *lemp; char *suffix; char *mode; { FILE *fp; if( lemp->outname ) free(lemp->outname); lemp->outname = file_makename(lemp, suffix); fp = fopen(lemp->outname,mode); if( fp==0 && *mode=='w' ){ fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); lemp->errorcnt++; return 0; } return fp; } /* Duplicate the input file without comments and without actions ** on rules */ void Reprint(lemp) struct lemon *lemp; { struct rule *rp; struct symbol *sp; int i, j, maxlen, len, ncolumns, skip; printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); maxlen = 10; for(i=0; insymbol; i++){ sp = lemp->symbols[i]; len = strlen(sp->name); if( len>maxlen ) maxlen = len; } ncolumns = 76/(maxlen+5); if( ncolumns<1 ) ncolumns = 1; skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; for(i=0; insymbol; j+=skip){ sp = lemp->symbols[j]; assert( sp->index==j ); printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); } printf("\n"); } for(rp=lemp->rule; rp; rp=rp->next){ printf("%s",rp->lhs->name); /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ printf(" ::="); for(i=0; inrhs; i++){ printf(" %s",rp->rhs[i]->name); /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ } printf("."); if( rp->precsym ) printf(" [%s]",rp->precsym->name); /* if( rp->code ) printf("\n %s",rp->code); */ printf("\n"); } } void ConfigPrint(fp,cfp) FILE *fp; struct config *cfp; { struct rule *rp; int i; rp = cfp->rp; fprintf(fp,"%s ::=",rp->lhs->name); for(i=0; i<=rp->nrhs; i++){ if( i==cfp->dot ) fprintf(fp," *"); if( i==rp->nrhs ) break; fprintf(fp," %s",rp->rhs[i]->name); } } /* #define TEST */ #ifdef TEST /* Print a set */ PRIVATE void SetPrint(out,set,lemp) FILE *out; char *set; struct lemon *lemp; { int i; char *spacer; spacer = ""; fprintf(out,"%12s[",""); for(i=0; interminal; i++){ if( SetFind(set,i) ){ fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); spacer = " "; } } fprintf(out,"]\n"); } /* Print a plink chain */ PRIVATE void PlinkPrint(out,plp,tag) FILE *out; struct plink *plp; char *tag; { while( plp ){ fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index); ConfigPrint(out,plp->cfp); fprintf(out,"\n"); plp = plp->next; } } #endif /* Print an action to the given file descriptor. Return FALSE if ** nothing was actually printed. */ int PrintAction(struct action *ap, FILE *fp, int indent){ int result = 1; switch( ap->type ){ case SHIFT: fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index); break; case REDUCE: fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); break; case ACCEPT: fprintf(fp,"%*s accept",indent,ap->sp->name); break; case ERROR: fprintf(fp,"%*s error",indent,ap->sp->name); break; case CONFLICT: fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", indent,ap->sp->name,ap->x.rp->index); break; case SH_RESOLVED: case RD_RESOLVED: case NOT_USED: result = 0; break; } return result; } /* Generate the "y.output" log file */ void ReportOutput(lemp) struct lemon *lemp; { int i; struct state *stp; struct config *cfp; struct action *ap; FILE *fp; fp = file_open(lemp,".out","w"); if( fp==0 ) return; fprintf(fp," \b"); for(i=0; instate; i++){ stp = lemp->sorted[i]; fprintf(fp,"State %d:\n",stp->index); if( lemp->basisflag ) cfp=stp->bp; else cfp=stp->cfp; while( cfp ){ char buf[20]; if( cfp->dot==cfp->rp->nrhs ){ sprintf(buf,"(%d)",cfp->rp->index); fprintf(fp," %5s ",buf); }else{ fprintf(fp," "); } ConfigPrint(fp,cfp); fprintf(fp,"\n"); #ifdef TEST SetPrint(fp,cfp->fws,lemp); PlinkPrint(fp,cfp->fplp,"To "); PlinkPrint(fp,cfp->bplp,"From"); #endif if( lemp->basisflag ) cfp=cfp->bp; else cfp=cfp->next; } fprintf(fp,"\n"); for(ap=stp->ap; ap; ap=ap->next){ if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); } fprintf(fp,"\n"); } fclose(fp); return; } /* Search for the file "name" which is in the same directory as ** the exacutable */ PRIVATE char *pathsearch(argv0,name,modemask) char *argv0; char *name; int modemask; { char *pathlist; char *path,*cp; char c; extern int access(); #ifdef __WIN32__ cp = strrchr(argv0,'\\'); #else cp = strrchr(argv0,'/'); #endif if( cp ){ c = *cp; *cp = 0; path = (char *)malloc( strlen(argv0) + strlen(name) + 2 ); if( path ) sprintf(path,"%s/%s",argv0,name); *cp = c; }else{ extern char *getenv(); pathlist = getenv("PATH"); if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; path = (char *)malloc( strlen(pathlist)+strlen(name)+2 ); if( path!=0 ){ while( *pathlist ){ cp = strchr(pathlist,':'); if( cp==0 ) cp = &pathlist[strlen(pathlist)]; c = *cp; *cp = 0; sprintf(path,"%s/%s",pathlist,name); *cp = c; if( c==0 ) pathlist = ""; else pathlist = &cp[1]; if( access(path,modemask)==0 ) break; } } } return path; } /* Given an action, compute the integer value for that action ** which is to be put in the action table of the generated machine. ** Return negative if no action should be generated. */ PRIVATE int compute_action(lemp,ap) struct lemon *lemp; struct action *ap; { int act; switch( ap->type ){ case SHIFT: act = ap->x.stp->index; break; case REDUCE: act = ap->x.rp->index + lemp->nstate; break; case ERROR: act = lemp->nstate + lemp->nrule; break; case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break; default: act = -1; break; } return act; } #define LINESIZE 1000 /* The next cluster of routines are for reading the template file ** and writing the results to the generated parser */ /* The first function transfers data from "in" to "out" until ** a line is seen which begins with "%%". The line number is ** tracked. ** ** if name!=0, then any word that begin with "Parse" is changed to ** begin with *name instead. */ PRIVATE void tplt_xfer(name,in,out,lineno) char *name; FILE *in; FILE *out; int *lineno; { int i, iStart; char line[LINESIZE]; while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ (*lineno)++; iStart = 0; if( name ){ for(i=0; line[i]; i++){ if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 && (i==0 || !isalpha(line[i-1])) ){ if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); fprintf(out,"%s",name); i += 4; iStart = i+1; } } } fprintf(out,"%s",&line[iStart]); } } /* The next function finds the template file and opens it, returning ** a pointer to the opened file. */ PRIVATE FILE *tplt_open(lemp) struct lemon *lemp; { static char templatename[] = "lempar.c"; char buf[1000]; FILE *in; char *tpltname; char *cp; cp = strrchr(lemp->filename,'.'); if( cp ){ sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); }else{ sprintf(buf,"%s.lt",lemp->filename); } if( access(buf,004)==0 ){ tpltname = buf; }else if( access(templatename,004)==0 ){ tpltname = templatename; }else{ tpltname = pathsearch(lemp->argv0,templatename,0); } if( tpltname==0 ){ fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", templatename); lemp->errorcnt++; return 0; } in = fopen(tpltname,"r"); if( in==0 ){ fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); lemp->errorcnt++; return 0; } return in; } /* Print a string to the file and keep the linenumber up to date */ PRIVATE void tplt_print(out,lemp,str,strln,lineno) FILE *out; struct lemon *lemp; char *str; int strln; int *lineno; { if( str==0 ) return; fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++; while( *str ){ if( *str=='\n' ) (*lineno)++; putc(*str,out); str++; } fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2; return; } /* ** The following routine emits code for the destructor for the ** symbol sp */ void emit_destructor_code(out,sp,lemp,lineno) FILE *out; struct symbol *sp; struct lemon *lemp; int *lineno; { char *cp = 0; int linecnt = 0; if( sp->type==TERMINAL ){ cp = lemp->tokendest; if( cp==0 ) return; fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename); }else if( sp->destructor ){ cp = sp->destructor; fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename); }else if( lemp->vardest ){ cp = lemp->vardest; if( cp==0 ) return; fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename); }else{ assert( 0 ); /* Cannot happen */ } for(; *cp; cp++){ if( *cp=='$' && cp[1]=='$' ){ fprintf(out,"(yypminor->yy%d)",sp->dtnum); cp++; continue; } if( *cp=='\n' ) linecnt++; fputc(*cp,out); } (*lineno) += 3 + linecnt; fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname); return; } /* ** Return TRUE (non-zero) if the given symbol has a destructor. */ int has_destructor(sp, lemp) struct symbol *sp; struct lemon *lemp; { int ret; if( sp->type==TERMINAL ){ ret = lemp->tokendest!=0; }else{ ret = lemp->vardest!=0 || sp->destructor!=0; } return ret; } /* ** Append text to a dynamically allocated string. If zText is 0 then ** reset the string to be empty again. Always return the complete text ** of the string (which is overwritten with each call). ** ** n bytes of zText are stored. If n==0 then all of zText up to the first ** \000 terminator is stored. zText can contain up to two instances of ** %d. The values of p1 and p2 are written into the first and second ** %d. ** ** If n==-1, then the previous character is overwritten. */ PRIVATE char *append_str(char *zText, int n, int p1, int p2){ static char *z = 0; static int alloced = 0; static int used = 0; int i, c; char zInt[40]; if( zText==0 ){ used = 0; return z; } if( n<=0 ){ if( n<0 ){ used += n; assert( used>=0 ); } n = strlen(zText); } if( n+sizeof(zInt)*2+used >= alloced ){ alloced = n + sizeof(zInt)*2 + used + 200; z = realloc(z, alloced); } if( z==0 ) return ""; while( n-- > 0 ){ c = *(zText++); if( c=='%' && zText[0]=='d' ){ sprintf(zInt, "%d", p1); p1 = p2; strcpy(&z[used], zInt); used += strlen(&z[used]); zText++; n--; }else{ z[used++] = c; } } z[used] = 0; return z; } /* ** zCode is a string that is the action associated with a rule. Expand ** the symbols in this string so that the refer to elements of the parser ** stack. Return a new string stored in space obtained from malloc. */ PRIVATE char *translate_code(struct lemon *lemp, struct rule *rp){ char *cp, *xp; int i; char lhsused = 0; /* True if the LHS element has been used */ char used[MAXRHS]; /* True for each RHS element which is used */ for(i=0; inrhs; i++) used[i] = 0; lhsused = 0; append_str(0,0,0,0); for(cp=rp->code; *cp; cp++){ if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){ char saved; for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++); saved = *xp; *xp = 0; if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0); cp = xp; lhsused = 1; }else{ for(i=0; inrhs; i++){ if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ if( cp!=rp->code && cp[-1]=='@' ){ /* If the argument is of the form @X then substituted ** the token number of X, not the value of X */ append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); }else{ append_str("yymsp[%d].minor.yy%d",0, i-rp->nrhs+1,rp->rhs[i]->dtnum); } cp = xp; used[i] = 1; break; } } } *xp = saved; } append_str(cp, 1, 0, 0); } /* End loop */ /* Check to make sure the LHS has been used */ if( rp->lhsalias && !lhsused ){ ErrorMsg(lemp->filename,rp->ruleline, "Label \"%s\" for \"%s(%s)\" is never used.", rp->lhsalias,rp->lhs->name,rp->lhsalias); lemp->errorcnt++; } /* Generate destructor code for RHS symbols which are not used in the ** reduce code */ for(i=0; inrhs; i++){ if( rp->rhsalias[i] && !used[i] ){ ErrorMsg(lemp->filename,rp->ruleline, "Label %s for \"%s(%s)\" is never used.", rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); lemp->errorcnt++; }else if( rp->rhsalias[i]==0 ){ if( has_destructor(rp->rhs[i],lemp) ){ append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0, rp->rhs[i]->index,i-rp->nrhs+1); }else{ /* No destructor defined for this term */ } } } cp = append_str(0,0,0,0); rp->code = Strsafe(cp); } /* ** Generate code which executes when the rule "rp" is reduced. Write ** the code to "out". Make sure lineno stays up-to-date. */ PRIVATE void emit_code(out,rp,lemp,lineno) FILE *out; struct rule *rp; struct lemon *lemp; int *lineno; { char *cp; int linecnt = 0; /* Generate code to do the reduce action */ if( rp->code ){ fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename); fprintf(out,"%s",rp->code); for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) linecnt++; } /* End loop */ (*lineno) += 3 + linecnt; fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname); } /* End if( rp->code ) */ return; } /* ** Print the definition of the union used for the parser's data stack. ** This union contains fields for every possible data type for tokens ** and nonterminals. In the process of computing and printing this ** union, also set the ".dtnum" field of every terminal and nonterminal ** symbol. */ void print_stack_union(out,lemp,plineno,mhflag) FILE *out; /* The output stream */ struct lemon *lemp; /* The main info structure for this parser */ int *plineno; /* Pointer to the line number */ int mhflag; /* True if generating makeheaders output */ { int lineno = *plineno; /* The line number of the output */ char **types; /* A hash table of datatypes */ int arraysize; /* Size of the "types" array */ int maxdtlength; /* Maximum length of any ".datatype" field. */ char *stddt; /* Standardized name for a datatype */ int i,j; /* Loop counters */ int hash; /* For hashing the name of a type */ char *name; /* Name of the parser */ /* Allocate and initialize types[] and allocate stddt[] */ arraysize = lemp->nsymbol * 2; types = (char**)malloc( arraysize * sizeof(char*) ); for(i=0; ivartype ){ maxdtlength = strlen(lemp->vartype); } for(i=0; insymbol; i++){ int len; struct symbol *sp = lemp->symbols[i]; if( sp->datatype==0 ) continue; len = strlen(sp->datatype); if( len>maxdtlength ) maxdtlength = len; } stddt = (char*)malloc( maxdtlength*2 + 1 ); if( types==0 || stddt==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } /* Build a hash table of datatypes. The ".dtnum" field of each symbol ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is ** used for terminal symbols. If there is no %default_type defined then ** 0 is also used as the .dtnum value for nonterminals which do not specify ** a datatype using the %type directive. */ for(i=0; insymbol; i++){ struct symbol *sp = lemp->symbols[i]; char *cp; if( sp==lemp->errsym ){ sp->dtnum = arraysize+1; continue; } if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ sp->dtnum = 0; continue; } cp = sp->datatype; if( cp==0 ) cp = lemp->vartype; j = 0; while( isspace(*cp) ) cp++; while( *cp ) stddt[j++] = *cp++; while( j>0 && isspace(stddt[j-1]) ) j--; stddt[j] = 0; hash = 0; for(j=0; stddt[j]; j++){ hash = hash*53 + stddt[j]; } hash = (hash & 0x7fffffff)%arraysize; while( types[hash] ){ if( strcmp(types[hash],stddt)==0 ){ sp->dtnum = hash + 1; break; } hash++; if( hash>=arraysize ) hash = 0; } if( types[hash]==0 ){ sp->dtnum = hash + 1; types[hash] = (char*)malloc( strlen(stddt)+1 ); if( types[hash]==0 ){ fprintf(stderr,"Out of memory.\n"); exit(1); } strcpy(types[hash],stddt); } } /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ name = lemp->name ? lemp->name : "Parse"; lineno = *plineno; if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } fprintf(out,"#define %sTOKENTYPE %s\n",name, lemp->tokentype?lemp->tokentype:"void*"); lineno++; if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } fprintf(out,"typedef union {\n"); lineno++; fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; for(i=0; ierrsym->dtnum); lineno++; free(stddt); free(types); fprintf(out,"} YYMINORTYPE;\n"); lineno++; *plineno = lineno; } /* ** Return the name of a C datatype able to represent values between ** lwr and upr, inclusive. */ static const char *minimum_size_type(int lwr, int upr){ if( lwr>=0 ){ if( upr<=255 ){ return "unsigned char"; }else if( upr<65535 ){ return "unsigned short int"; }else{ return "unsigned int"; } }else if( lwr>=-127 && upr<=127 ){ return "signed char"; }else if( lwr>=-32767 && upr<32767 ){ return "short"; }else{ return "int"; } } /* ** Each state contains a set of token transaction and a set of ** nonterminal transactions. Each of these sets makes an instance ** of the following structure. An array of these structures is used ** to order the creation of entries in the yy_action[] table. */ struct axset { struct state *stp; /* A pointer to a state */ int isTkn; /* True to use tokens. False for non-terminals */ int nAction; /* Number of actions */ }; /* ** Compare to axset structures for sorting purposes */ static int axset_compare(const void *a, const void *b){ struct axset *p1 = (struct axset*)a; struct axset *p2 = (struct axset*)b; return p2->nAction - p1->nAction; } /* Generate C source code for the parser */ void ReportTable(lemp, mhflag) struct lemon *lemp; int mhflag; /* Output in makeheaders format if true */ { FILE *out, *in; char line[LINESIZE]; int lineno; struct state *stp; struct action *ap; struct rule *rp; struct acttab *pActtab; int i, j, n; char *name; int mnTknOfst, mxTknOfst; int mnNtOfst, mxNtOfst; struct axset *ax; in = tplt_open(lemp); if( in==0 ) return; out = file_open(lemp,".c","w"); if( out==0 ){ fclose(in); return; } lineno = 1; tplt_xfer(lemp->name,in,out,&lineno); /* Generate the include code, if any */ tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno); if( mhflag ){ char *name = file_makename(lemp, ".h"); fprintf(out,"#include \"%s\"\n", name); lineno++; free(name); } tplt_xfer(lemp->name,in,out,&lineno); /* Generate #defines for all tokens */ if( mhflag ){ char *prefix; fprintf(out,"#if INTERFACE\n"); lineno++; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; for(i=1; interminal; i++){ fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); lineno++; } fprintf(out,"#endif\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate the defines */ fprintf(out,"#define YYCODETYPE %s\n", minimum_size_type(0, lemp->nsymbol+5)); lineno++; fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; fprintf(out,"#define YYACTIONTYPE %s\n", minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; print_stack_union(out,lemp,&lineno,mhflag); if( lemp->stacksize ){ if( atoi(lemp->stacksize)<=0 ){ ErrorMsg(lemp->filename,0, "Illegal stack size: [%s]. The stack size should be an integer constant.", lemp->stacksize); lemp->errorcnt++; lemp->stacksize = "100"; } fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; }else{ fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; } if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } name = lemp->name ? lemp->name : "Parse"; if( lemp->arg && lemp->arg[0] ){ int i; i = strlen(lemp->arg); while( i>=1 && isspace(lemp->arg[i-1]) ) i--; while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n", name,lemp->arg,&lemp->arg[i]); lineno++; fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n", name,&lemp->arg[i],&lemp->arg[i]); lineno++; }else{ fprintf(out,"#define %sARG_SDECL\n",name); lineno++; fprintf(out,"#define %sARG_PDECL\n",name); lineno++; fprintf(out,"#define %sARG_FETCH\n",name); lineno++; fprintf(out,"#define %sARG_STORE\n",name); lineno++; } if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; if( lemp->has_fallback ){ fprintf(out,"#define YYFALLBACK 1\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate the action table and its associates: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ /* Compute the actions on all states and count them up */ ax = malloc( sizeof(ax[0])*lemp->nstate*2 ); if( ax==0 ){ fprintf(stderr,"malloc failed\n"); exit(1); } for(i=0; instate; i++){ stp = lemp->sorted[i]; stp->nTknAct = stp->nNtAct = 0; stp->iDflt = lemp->nstate + lemp->nrule; stp->iTknOfst = NO_OFFSET; stp->iNtOfst = NO_OFFSET; for(ap=stp->ap; ap; ap=ap->next){ if( compute_action(lemp,ap)>=0 ){ if( ap->sp->indexnterminal ){ stp->nTknAct++; }else if( ap->sp->indexnsymbol ){ stp->nNtAct++; }else{ stp->iDflt = compute_action(lemp, ap); } } } ax[i*2].stp = stp; ax[i*2].isTkn = 1; ax[i*2].nAction = stp->nTknAct; ax[i*2+1].stp = stp; ax[i*2+1].isTkn = 0; ax[i*2+1].nAction = stp->nNtAct; } mxTknOfst = mnTknOfst = 0; mxNtOfst = mnNtOfst = 0; /* Compute the action table. In order to try to keep the size of the ** action table to a minimum, the heuristic of placing the largest action ** sets first is used. */ qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); pActtab = acttab_alloc(); for(i=0; instate*2 && ax[i].nAction>0; i++){ stp = ax[i].stp; if( ax[i].isTkn ){ for(ap=stp->ap; ap; ap=ap->next){ int action; if( ap->sp->index>=lemp->nterminal ) continue; action = compute_action(lemp, ap); if( action<0 ) continue; acttab_action(pActtab, ap->sp->index, action); } stp->iTknOfst = acttab_insert(pActtab); if( stp->iTknOfstiTknOfst; if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; }else{ for(ap=stp->ap; ap; ap=ap->next){ int action; if( ap->sp->indexnterminal ) continue; if( ap->sp->index==lemp->nsymbol ) continue; action = compute_action(lemp, ap); if( action<0 ) continue; acttab_action(pActtab, ap->sp->index, action); } stp->iNtOfst = acttab_insert(pActtab); if( stp->iNtOfstiNtOfst; if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; } } free(ax); /* Output the yy_action table */ fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++; n = acttab_size(pActtab); for(i=j=0; insymbol + lemp->nrule + 2; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", action); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_lookahead table */ fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++; for(i=j=0; insymbol; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", la); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_shift_ofst[] table */ fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; fprintf(out, "static %s yy_shift_ofst[] = {\n", minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; n = lemp->nstate; for(i=j=0; isorted[i]; ofst = stp->iTknOfst; if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", ofst); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the yy_reduce_ofst[] table */ fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; fprintf(out, "static %s yy_reduce_ofst[] = {\n", minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; n = lemp->nstate; for(i=j=0; isorted[i]; ofst = stp->iNtOfst; if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", ofst); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; /* Output the default action table */ fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++; n = lemp->nstate; for(i=j=0; isorted[i]; if( j==0 ) fprintf(out," /* %5d */ ", i); fprintf(out, " %4d,", stp->iDflt); if( j==9 || i==n-1 ){ fprintf(out, "\n"); lineno++; j = 0; }else{ j++; } } fprintf(out, "};\n"); lineno++; tplt_xfer(lemp->name,in,out,&lineno); /* Generate the table of fallback tokens. */ if( lemp->has_fallback ){ for(i=0; interminal; i++){ struct symbol *p = lemp->symbols[i]; if( p->fallback==0 ){ fprintf(out, " 0, /* %10s => nothing */\n", p->name); }else{ fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, p->name, p->fallback->name); } lineno++; } } tplt_xfer(lemp->name, in, out, &lineno); /* Generate a table containing the symbolic name of every symbol */ for(i=0; insymbol; i++){ sprintf(line,"\"%s\",",lemp->symbols[i]->name); fprintf(out," %-15s",line); if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } } if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate a table containing a text string that describes every ** rule in the rule set of the grammer. This information is used ** when tracing REDUCE actions. */ for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ assert( rp->index==i ); fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name); for(j=0; jnrhs; j++) fprintf(out," %s",rp->rhs[j]->name); fprintf(out,"\",\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes every time a symbol is popped from ** the stack while processing errors or while destroying the parser. ** (In other words, generate the %destructor actions) */ if( lemp->tokendest ){ for(i=0; insymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type!=TERMINAL ) continue; fprintf(out," case %d:\n",sp->index); lineno++; } for(i=0; insymbol && lemp->symbols[i]->type!=TERMINAL; i++); if( insymbol ){ emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); fprintf(out," break;\n"); lineno++; } } for(i=0; insymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; fprintf(out," case %d:\n",sp->index); lineno++; /* Combine duplicate destructors into a single case */ for(j=i+1; jnsymbol; j++){ struct symbol *sp2 = lemp->symbols[j]; if( sp2 && sp2->type!=TERMINAL && sp2->destructor && sp2->dtnum==sp->dtnum && strcmp(sp->destructor,sp2->destructor)==0 ){ fprintf(out," case %d:\n",sp2->index); lineno++; sp2->destructor = 0; } } emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); fprintf(out," break;\n"); lineno++; } if( lemp->vardest ){ struct symbol *dflt_sp = 0; for(i=0; insymbol; i++){ struct symbol *sp = lemp->symbols[i]; if( sp==0 || sp->type==TERMINAL || sp->index<=0 || sp->destructor!=0 ) continue; fprintf(out," case %d:\n",sp->index); lineno++; dflt_sp = sp; } if( dflt_sp!=0 ){ emit_destructor_code(out,dflt_sp,lemp,&lineno); fprintf(out," break;\n"); lineno++; } } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes whenever the parser stack overflows */ tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate the table of rule information ** ** Note: This code depends on the fact that rules are number ** sequentually beginning with 0. */ for(rp=lemp->rule; rp; rp=rp->next){ fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which execution during each REDUCE action */ for(rp=lemp->rule; rp; rp=rp->next){ if( rp->code ) translate_code(lemp, rp); } for(rp=lemp->rule; rp; rp=rp->next){ struct rule *rp2; if( rp->code==0 ) continue; fprintf(out," case %d:\n",rp->index); lineno++; for(rp2=rp->next; rp2; rp2=rp2->next){ if( rp2->code==rp->code ){ fprintf(out," case %d:\n",rp2->index); lineno++; rp2->code = 0; } } emit_code(out,rp,lemp,&lineno); fprintf(out," break;\n"); lineno++; } tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes if a parse fails */ tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when a syntax error occurs */ tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Generate code which executes when the parser accepts its input */ tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno); tplt_xfer(lemp->name,in,out,&lineno); /* Append any addition code the user desires */ tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno); fclose(in); fclose(out); return; } /* Generate a header file for the parser */ void ReportHeader(lemp) struct lemon *lemp; { FILE *out, *in; char *prefix; char line[LINESIZE]; char pattern[LINESIZE]; int i; if( lemp->tokenprefix ) prefix = lemp->tokenprefix; else prefix = ""; in = file_open(lemp,".h","r"); if( in ){ for(i=1; interminal && fgets(line,LINESIZE,in); i++){ sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); if( strcmp(line,pattern) ) break; } fclose(in); if( i==lemp->nterminal ){ /* No change in the file. Don't rewrite it. */ return; } } out = file_open(lemp,".h","w"); if( out ){ for(i=1; interminal; i++){ fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); } fclose(out); } return; } /* Reduce the size of the action tables, if possible, by making use ** of defaults. ** ** In this version, we take the most frequent REDUCE action and make ** it the default. Only default a reduce if there are more than one. */ void CompressTables(lemp) struct lemon *lemp; { struct state *stp; struct action *ap, *ap2; struct rule *rp, *rp2, *rbest; int nbest, n; int i; for(i=0; instate; i++){ stp = lemp->sorted[i]; nbest = 0; rbest = 0; for(ap=stp->ap; ap; ap=ap->next){ if( ap->type!=REDUCE ) continue; rp = ap->x.rp; if( rp==rbest ) continue; n = 1; for(ap2=ap->next; ap2; ap2=ap2->next){ if( ap2->type!=REDUCE ) continue; rp2 = ap2->x.rp; if( rp2==rbest ) continue; if( rp2==rp ) n++; } if( n>nbest ){ nbest = n; rbest = rp; } } /* Do not make a default if the number of rules to default ** is not at least 2 */ if( nbest<2 ) continue; /* Combine matching REDUCE actions into a single default */ for(ap=stp->ap; ap; ap=ap->next){ if( ap->type==REDUCE && ap->x.rp==rbest ) break; } assert( ap ); ap->sp = Symbol_new("{default}"); for(ap=ap->next; ap; ap=ap->next){ if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; } stp->ap = Action_sort(stp->ap); } } /***************** From the file "set.c" ************************************/ /* ** Set manipulation routines for the LEMON parser generator. */ static int size = 0; /* Set the set size */ void SetSize(n) int n; { size = n+1; } /* Allocate a new set */ char *SetNew(){ char *s; int i; s = (char*)malloc( size ); if( s==0 ){ extern void memory_error(); memory_error(); } for(i=0; isize = 1024; x1a->count = 0; x1a->tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*1024 ); if( x1a->tbl==0 ){ free(x1a); x1a = 0; }else{ int i; x1a->ht = (x1node**)&(x1a->tbl[1024]); for(i=0; i<1024; i++) x1a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Strsafe_insert(data) char *data; { x1node *np; int h; int ph; if( x1a==0 ) return 0; ph = strhash(data); h = ph & (x1a->size-1); np = x1a->ht[h]; while( np ){ if( strcmp(np->data,data)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x1a->count>=x1a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x1 array; array.size = size = x1a->size*2; array.count = x1a->count; array.tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x1node**)&(array.tbl[size]); for(i=0; icount; i++){ x1node *oldnp, *newnp; oldnp = &(x1a->tbl[i]); h = strhash(oldnp->data) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x1a->tbl); *x1a = array; } /* Insert the new data */ h = ph & (x1a->size-1); np = &(x1a->tbl[x1a->count++]); np->data = data; if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); np->next = x1a->ht[h]; x1a->ht[h] = np; np->from = &(x1a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ char *Strsafe_find(key) char *key; { int h; x1node *np; if( x1a==0 ) return 0; h = strhash(key) & (x1a->size-1); np = x1a->ht[h]; while( np ){ if( strcmp(np->data,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return a pointer to the (terminal or nonterminal) symbol "x". ** Create a new symbol if this is the first time "x" has been seen. */ struct symbol *Symbol_new(x) char *x; { struct symbol *sp; sp = Symbol_find(x); if( sp==0 ){ sp = (struct symbol *)malloc( sizeof(struct symbol) ); MemoryCheck(sp); sp->name = Strsafe(x); sp->type = isupper(*x) ? TERMINAL : NONTERMINAL; sp->rule = 0; sp->fallback = 0; sp->prec = -1; sp->assoc = UNK; sp->firstset = 0; sp->lambda = B_FALSE; sp->destructor = 0; sp->datatype = 0; Symbol_insert(sp,sp->name); } return sp; } /* Compare two symbols for working purposes ** ** Symbols that begin with upper case letters (terminals or tokens) ** must sort before symbols that begin with lower case letters ** (non-terminals). Other than that, the order does not matter. ** ** We find experimentally that leaving the symbols in their original ** order (the order they appeared in the grammar file) gives the ** smallest parser tables in SQLite. */ int Symbolcmpp(struct symbol **a, struct symbol **b){ int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); return i1-i2; } /* There is one instance of the following structure for each ** associative array of type "x2". */ struct s_x2 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x2node *tbl; /* The data stored here */ struct s_x2node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x2". */ typedef struct s_x2node { struct symbol *data; /* The data */ char *key; /* The key */ struct s_x2node *next; /* Next entry with the same hash */ struct s_x2node **from; /* Previous link */ } x2node; /* There is only one instance of the array, which is the following */ static struct s_x2 *x2a; /* Allocate a new associative array */ void Symbol_init(){ if( x2a ) return; x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); if( x2a ){ x2a->size = 128; x2a->count = 0; x2a->tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*128 ); if( x2a->tbl==0 ){ free(x2a); x2a = 0; }else{ int i; x2a->ht = (x2node**)&(x2a->tbl[128]); for(i=0; i<128; i++) x2a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Symbol_insert(data,key) struct symbol *data; char *key; { x2node *np; int h; int ph; if( x2a==0 ) return 0; ph = strhash(key); h = ph & (x2a->size-1); np = x2a->ht[h]; while( np ){ if( strcmp(np->key,key)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x2a->count>=x2a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x2 array; array.size = size = x2a->size*2; array.count = x2a->count; array.tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x2node**)&(array.tbl[size]); for(i=0; icount; i++){ x2node *oldnp, *newnp; oldnp = &(x2a->tbl[i]); h = strhash(oldnp->key) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->key = oldnp->key; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x2a->tbl); *x2a = array; } /* Insert the new data */ h = ph & (x2a->size-1); np = &(x2a->tbl[x2a->count++]); np->key = key; np->data = data; if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); np->next = x2a->ht[h]; x2a->ht[h] = np; np->from = &(x2a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct symbol *Symbol_find(key) char *key; { int h; x2node *np; if( x2a==0 ) return 0; h = strhash(key) & (x2a->size-1); np = x2a->ht[h]; while( np ){ if( strcmp(np->key,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return the n-th data. Return NULL if n is out of range. */ struct symbol *Symbol_Nth(n) int n; { struct symbol *data; if( x2a && n>0 && n<=x2a->count ){ data = x2a->tbl[n-1].data; }else{ data = 0; } return data; } /* Return the size of the array */ int Symbol_count() { return x2a ? x2a->count : 0; } /* Return an array of pointers to all data in the table. ** The array is obtained from malloc. Return NULL if memory allocation ** problems, or if the array is empty. */ struct symbol **Symbol_arrayof() { struct symbol **array; int i,size; if( x2a==0 ) return 0; size = x2a->count; array = (struct symbol **)malloc( sizeof(struct symbol *)*size ); if( array ){ for(i=0; itbl[i].data; } return array; } /* Compare two configurations */ int Configcmp(a,b) struct config *a; struct config *b; { int x; x = a->rp->index - b->rp->index; if( x==0 ) x = a->dot - b->dot; return x; } /* Compare two states */ PRIVATE int statecmp(a,b) struct config *a; struct config *b; { int rc; for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ rc = a->rp->index - b->rp->index; if( rc==0 ) rc = a->dot - b->dot; } if( rc==0 ){ if( a ) rc = 1; if( b ) rc = -1; } return rc; } /* Hash a state */ PRIVATE int statehash(a) struct config *a; { int h=0; while( a ){ h = h*571 + a->rp->index*37 + a->dot; a = a->bp; } return h; } /* Allocate a new state structure */ struct state *State_new() { struct state *new; new = (struct state *)malloc( sizeof(struct state) ); MemoryCheck(new); return new; } /* There is one instance of the following structure for each ** associative array of type "x3". */ struct s_x3 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x3node *tbl; /* The data stored here */ struct s_x3node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x3". */ typedef struct s_x3node { struct state *data; /* The data */ struct config *key; /* The key */ struct s_x3node *next; /* Next entry with the same hash */ struct s_x3node **from; /* Previous link */ } x3node; /* There is only one instance of the array, which is the following */ static struct s_x3 *x3a; /* Allocate a new associative array */ void State_init(){ if( x3a ) return; x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); if( x3a ){ x3a->size = 128; x3a->count = 0; x3a->tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*128 ); if( x3a->tbl==0 ){ free(x3a); x3a = 0; }else{ int i; x3a->ht = (x3node**)&(x3a->tbl[128]); for(i=0; i<128; i++) x3a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int State_insert(data,key) struct state *data; struct config *key; { x3node *np; int h; int ph; if( x3a==0 ) return 0; ph = statehash(key); h = ph & (x3a->size-1); np = x3a->ht[h]; while( np ){ if( statecmp(np->key,key)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x3a->count>=x3a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x3 array; array.size = size = x3a->size*2; array.count = x3a->count; array.tbl = (x3node*)malloc( (sizeof(x3node) + sizeof(x3node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x3node**)&(array.tbl[size]); for(i=0; icount; i++){ x3node *oldnp, *newnp; oldnp = &(x3a->tbl[i]); h = statehash(oldnp->key) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->key = oldnp->key; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x3a->tbl); *x3a = array; } /* Insert the new data */ h = ph & (x3a->size-1); np = &(x3a->tbl[x3a->count++]); np->key = key; np->data = data; if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); np->next = x3a->ht[h]; x3a->ht[h] = np; np->from = &(x3a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct state *State_find(key) struct config *key; { int h; x3node *np; if( x3a==0 ) return 0; h = statehash(key) & (x3a->size-1); np = x3a->ht[h]; while( np ){ if( statecmp(np->key,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Return an array of pointers to all data in the table. ** The array is obtained from malloc. Return NULL if memory allocation ** problems, or if the array is empty. */ struct state **State_arrayof() { struct state **array; int i,size; if( x3a==0 ) return 0; size = x3a->count; array = (struct state **)malloc( sizeof(struct state *)*size ); if( array ){ for(i=0; itbl[i].data; } return array; } /* Hash a configuration */ PRIVATE int confighash(a) struct config *a; { int h=0; h = h*571 + a->rp->index*37 + a->dot; return h; } /* There is one instance of the following structure for each ** associative array of type "x4". */ struct s_x4 { int size; /* The number of available slots. */ /* Must be a power of 2 greater than or */ /* equal to 1 */ int count; /* Number of currently slots filled */ struct s_x4node *tbl; /* The data stored here */ struct s_x4node **ht; /* Hash table for lookups */ }; /* There is one instance of this structure for every data element ** in an associative array of type "x4". */ typedef struct s_x4node { struct config *data; /* The data */ struct s_x4node *next; /* Next entry with the same hash */ struct s_x4node **from; /* Previous link */ } x4node; /* There is only one instance of the array, which is the following */ static struct s_x4 *x4a; /* Allocate a new associative array */ void Configtable_init(){ if( x4a ) return; x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); if( x4a ){ x4a->size = 64; x4a->count = 0; x4a->tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*64 ); if( x4a->tbl==0 ){ free(x4a); x4a = 0; }else{ int i; x4a->ht = (x4node**)&(x4a->tbl[64]); for(i=0; i<64; i++) x4a->ht[i] = 0; } } } /* Insert a new record into the array. Return TRUE if successful. ** Prior data with the same key is NOT overwritten */ int Configtable_insert(data) struct config *data; { x4node *np; int h; int ph; if( x4a==0 ) return 0; ph = confighash(data); h = ph & (x4a->size-1); np = x4a->ht[h]; while( np ){ if( Configcmp(np->data,data)==0 ){ /* An existing entry with the same key is found. */ /* Fail because overwrite is not allows. */ return 0; } np = np->next; } if( x4a->count>=x4a->size ){ /* Need to make the hash table bigger */ int i,size; struct s_x4 array; array.size = size = x4a->size*2; array.count = x4a->count; array.tbl = (x4node*)malloc( (sizeof(x4node) + sizeof(x4node*))*size ); if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ array.ht = (x4node**)&(array.tbl[size]); for(i=0; icount; i++){ x4node *oldnp, *newnp; oldnp = &(x4a->tbl[i]); h = confighash(oldnp->data) & (size-1); newnp = &(array.tbl[i]); if( array.ht[h] ) array.ht[h]->from = &(newnp->next); newnp->next = array.ht[h]; newnp->data = oldnp->data; newnp->from = &(array.ht[h]); array.ht[h] = newnp; } free(x4a->tbl); *x4a = array; } /* Insert the new data */ h = ph & (x4a->size-1); np = &(x4a->tbl[x4a->count++]); np->data = data; if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); np->next = x4a->ht[h]; x4a->ht[h] = np; np->from = &(x4a->ht[h]); return 1; } /* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */ struct config *Configtable_find(key) struct config *key; { int h; x4node *np; if( x4a==0 ) return 0; h = confighash(key) & (x4a->size-1); np = x4a->ht[h]; while( np ){ if( Configcmp(np->data,key)==0 ) break; np = np->next; } return np ? np->data : 0; } /* Remove all data from the table. Pass each data to the function "f" ** as it is removed. ("f" may be null to avoid this step.) */ void Configtable_clear(f) int(*f)(/* struct config * */); { int i; if( x4a==0 || x4a->count==0 ) return; if( f ) for(i=0; icount; i++) (*f)(x4a->tbl[i].data); for(i=0; isize; i++) x4a->ht[i] = 0; x4a->count = 0; return; } r3-1.3.4/php/r3/annotation/lempar.c000066400000000000000000000540021262260041500167530ustar00rootroot00000000000000/* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is include which follows the "include" declaration ** in the input file. */ #include %% /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ %% /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** ParseTOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is ParseTOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. ** ParseARG_SDECL A static variable declaration for the %extra_argument ** ParseARG_PDECL A parameter declaration for the %extra_argument ** ParseARG_STORE Code to store %extra_argument into yypParser ** ParseARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ %% #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ %% #define YY_SZ_ACTTAB (sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { %% }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ int yyerrcnt; /* Shifts left before out of the error */ ParseARG_SDECL /* A place to hold %extra_argument */ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ }; typedef struct yyParser yyParser; #ifndef NDEBUG #include static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: **
    **
  • A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. **
  • A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. **
** ** Outputs: ** None. */ void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *yyTokenName[] = { %% }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *yyRuleName[] = { %% }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *ParseTokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to Parse and ParseFree. */ void *ParseAlloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ %% default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor( yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: **
    **
  • A pointer to the parser. This should be a pointer ** obtained from ParseAlloc. **
  • A pointer to a function used to reclaim memory obtained ** from malloc. **
*/ void ParseFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; /* if( pParser->yyidx<0 ) return YY_NO_ACTION; */ i = yy_shift_ofst[stateno]; if( i==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ if( iLookAhead %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; i = yy_reduce_ofst[stateno]; if( i==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; if( yypParser->yyidx>=YYSTACKDEPTH ){ ParseARG_FETCH; yypParser->yyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = yyNewState; yytos->major = yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { %% }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ ParseARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno ** { ... } // User supplied code ** #line ** break; */ %% }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yypParser,yygoto); if( yyact < YYNSTATE ){ yy_shift(yypParser,yyact,yygoto,&yygotominor); }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ ParseARG_FETCH; #define TOKEN (yyminor.yy0) %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "ParseAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: **
    **
  • A pointer to the parser (an opaque structure.) **
  • The major token number. **
  • The minor token number. **
  • An option argument of a grammar-specified type. **
** ** Outputs: ** None. */ void Parse( void *yyp, /* The parser */ int yymajor, /* The major token code number */ ParseTOKENTYPE yyminor /* The value for the token */ ParseARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ int yyerrorhit = 0; /* True if yymajor has invoked an error */ yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ if( yymajor==0 ) return; yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); ParseARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyactyyerrcnt--; if( yyendofinput && yypParser->yyidx>=0 ){ yymajor = 0; }else{ yymajor = YYNOCODE; } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else if( yyact == YY_ERROR_ACTION ){ int yymx; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_shift_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif }else{ yy_accept(yypParser); yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } r3-1.3.4/php/r3/annotation/parser.c000066400000000000000000001407011262260041500167710ustar00rootroot00000000000000/* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is include which follows the "include" declaration ** in the input file. */ #include #line 27 "parser.lemon" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "ext/standard/php_smart_str.h" #include "Zend/zend_exceptions.h" #include "parser.h" #include "scanner.h" #include "annot.h" static zval *phannot_ret_literal_zval(int type, phannot_parser_token *T) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (T) { add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); } return ret; } static zval *phannot_ret_array(zval *items) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ARRAY); if (items) { add_assoc_zval(ret, "items", items); } return ret; } static zval *phannot_ret_zval_list(zval *list_left, zval *right_list) { zval *ret; HashPosition pos; HashTable *list; MAKE_STD_ZVAL(ret); array_init(ret); if (list_left) { list = Z_ARRVAL_P(list_left); if (zend_hash_index_exists(list, 0)) { zend_hash_internal_pointer_reset_ex(list, &pos); for (;; zend_hash_move_forward_ex(list, &pos)) { zval ** item; if (zend_hash_get_current_data_ex(list, (void**) &item, &pos) == FAILURE) { break; } Z_ADDREF_PP(item); add_next_index_zval(ret, *item); } zval_ptr_dtor(&list_left); } else { add_next_index_zval(ret, list_left); } } add_next_index_zval(ret, right_list); return ret; } static zval *phannot_ret_named_item(phannot_parser_token *name, zval *expr) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "expr", expr); if (name != NULL) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } return ret; } static zval *phannot_ret_annotation(phannot_parser_token *name, zval *arguments, phannot_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ANNOTATION); if (name) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } if (arguments) { add_assoc_zval(ret, "arguments", arguments); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } #line 132 "parser.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** phannot_TOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is phannot_TOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. ** phannot_ARG_SDECL A static variable declaration for the %extra_argument ** phannot_ARG_PDECL A parameter declaration for the %extra_argument ** phannot_ARG_STORE Code to store %extra_argument into yypParser ** phannot_ARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ #define YYCODETYPE unsigned char #define YYNOCODE 28 #define YYACTIONTYPE unsigned char #define phannot_TOKENTYPE phannot_parser_token* typedef union { phannot_TOKENTYPE yy0; zval* yy36; int yy55; } YYMINORTYPE; #define YYSTACKDEPTH 100 #define phannot_ARG_SDECL phannot_parser_status *status; #define phannot_ARG_PDECL ,phannot_parser_status *status #define phannot_ARG_FETCH phannot_parser_status *status = yypParser->status #define phannot_ARG_STORE yypParser->status = status #define YYNSTATE 40 #define YYNRULE 25 #define YYERRORSYMBOL 18 #define YYERRSYMDT yy55 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static YYACTIONTYPE yy_action[] = { /* 0 */ 4, 28, 15, 38, 12, 37, 16, 18, 20, 21, /* 10 */ 22, 23, 24, 4, 31, 4, 17, 15, 40, 19, /* 20 */ 35, 16, 18, 20, 21, 22, 23, 24, 3, 31, /* 30 */ 4, 28, 15, 6, 12, 30, 16, 18, 20, 21, /* 40 */ 22, 23, 24, 54, 31, 15, 25, 27, 11, 16, /* 50 */ 13, 36, 15, 7, 27, 11, 16, 15, 32, 27, /* 60 */ 11, 16, 15, 9, 10, 11, 16, 66, 1, 2, /* 70 */ 39, 15, 9, 5, 14, 16, 41, 26, 4, 9, /* 80 */ 29, 34, 54, 8, 54, 54, 54, 54, 33, }; static YYCODETYPE yy_lookahead[] = { /* 0 */ 2, 3, 22, 5, 6, 25, 26, 9, 10, 11, /* 10 */ 12, 13, 14, 2, 16, 2, 3, 22, 0, 6, /* 20 */ 25, 26, 9, 10, 11, 12, 13, 14, 22, 16, /* 30 */ 2, 3, 22, 4, 6, 25, 26, 9, 10, 11, /* 40 */ 12, 13, 14, 27, 16, 22, 23, 24, 25, 26, /* 50 */ 7, 8, 22, 23, 24, 25, 26, 22, 23, 24, /* 60 */ 25, 26, 22, 1, 24, 25, 26, 19, 20, 21, /* 70 */ 22, 22, 1, 3, 25, 26, 0, 15, 2, 1, /* 80 */ 7, 8, 27, 5, 27, 27, 27, 27, 17, }; #define YY_SHIFT_USE_DFLT (-3) static signed char yy_shift_ofst[] = { /* 0 */ 11, 18, 76, -3, 70, 29, -2, 78, -3, 28, /* 10 */ -3, -3, 43, 13, -3, -3, -3, -3, -3, -3, /* 20 */ -3, -3, -3, -3, 28, 62, -3, -3, 73, 13, /* 30 */ -3, 28, 71, -3, 13, -3, 13, -3, -3, -3, }; #define YY_REDUCE_USE_DFLT (-21) static signed char yy_reduce_ofst[] = { /* 0 */ 48, -21, 6, -21, -21, -21, 30, -21, -21, 40, /* 10 */ -21, -21, -21, 49, -21, -21, -21, -21, -21, -21, /* 20 */ -21, -21, -21, -21, 23, -21, -21, -21, -21, 10, /* 30 */ -21, 35, -21, -21, -5, -21, -20, -21, -21, -21, }; static YYACTIONTYPE yy_default[] = { /* 0 */ 65, 65, 65, 42, 65, 46, 65, 65, 44, 65, /* 10 */ 47, 49, 58, 65, 50, 54, 55, 56, 57, 58, /* 20 */ 59, 60, 61, 62, 65, 65, 63, 48, 56, 65, /* 30 */ 52, 65, 65, 64, 65, 53, 65, 51, 45, 43, }; #define YY_SZ_ACTTAB (sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ int yyerrcnt; /* Shifts left before out of the error */ phannot_ARG_SDECL /* A place to hold %extra_argument */ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ }; typedef struct yyParser yyParser; #ifndef NDEBUG #include static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: **
    **
  • A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. **
  • A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. **
** ** Outputs: ** None. */ void phannot_Trace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *yyTokenName[] = { "$", "COMMA", "AT", "IDENTIFIER", "PARENTHESES_OPEN", "PARENTHESES_CLOSE", "STRING", "EQUALS", "COLON", "INTEGER", "DOUBLE", "NULL", "FALSE", "TRUE", "BRACKET_OPEN", "BRACKET_CLOSE", "SBRACKET_OPEN", "SBRACKET_CLOSE", "error", "program", "annotation_language", "annotation_list", "annotation", "argument_list", "argument_item", "expr", "array", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *yyRuleName[] = { /* 0 */ "program ::= annotation_language", /* 1 */ "annotation_language ::= annotation_list", /* 2 */ "annotation_list ::= annotation_list annotation", /* 3 */ "annotation_list ::= annotation", /* 4 */ "annotation ::= AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE", /* 5 */ "annotation ::= AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE", /* 6 */ "annotation ::= AT IDENTIFIER", /* 7 */ "argument_list ::= argument_list COMMA argument_item", /* 8 */ "argument_list ::= argument_item", /* 9 */ "argument_item ::= expr", /* 10 */ "argument_item ::= STRING EQUALS expr", /* 11 */ "argument_item ::= STRING COLON expr", /* 12 */ "argument_item ::= IDENTIFIER EQUALS expr", /* 13 */ "argument_item ::= IDENTIFIER COLON expr", /* 14 */ "expr ::= annotation", /* 15 */ "expr ::= array", /* 16 */ "expr ::= IDENTIFIER", /* 17 */ "expr ::= INTEGER", /* 18 */ "expr ::= STRING", /* 19 */ "expr ::= DOUBLE", /* 20 */ "expr ::= NULL", /* 21 */ "expr ::= FALSE", /* 22 */ "expr ::= TRUE", /* 23 */ "array ::= BRACKET_OPEN argument_list BRACKET_CLOSE", /* 24 */ "array ::= SBRACKET_OPEN argument_list SBRACKET_CLOSE", }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *phannot_TokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to phannot_ and phannot_Free. */ void *phannot_Alloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: #line 214 "parser.lemon" { if ((yypminor->yy0)) { if ((yypminor->yy0)->free_flag) { efree((yypminor->yy0)->token); } efree((yypminor->yy0)); } } #line 498 "parser.c" break; case 20: case 21: case 22: case 23: case 24: case 25: #line 227 "parser.lemon" { zval_ptr_dtor(&(yypminor->yy36)); } #line 508 "parser.c" break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor( yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: **
    **
  • A pointer to the parser. This should be a pointer ** obtained from phannot_Alloc. **
  • A pointer to a function used to reclaim memory obtained ** from malloc. **
*/ void phannot_Free( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; /* if( pParser->yyidx<0 ) return YY_NO_ACTION; */ i = yy_shift_ofst[stateno]; if( i==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ if( iLookAhead %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; i = yy_reduce_ofst[stateno]; if( i==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; if( yypParser->yyidx>=YYSTACKDEPTH ){ phannot_ARG_FETCH; yypParser->yyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = yyNewState; yytos->major = yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 19, 1 }, { 20, 1 }, { 21, 2 }, { 21, 1 }, { 22, 5 }, { 22, 4 }, { 22, 2 }, { 23, 3 }, { 23, 1 }, { 24, 1 }, { 24, 3 }, { 24, 3 }, { 24, 3 }, { 24, 3 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 26, 3 }, { 26, 3 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ phannot_ARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno ** { ... } // User supplied code ** #line ** break; */ case 0: #line 223 "parser.lemon" { status->ret = yymsp[0].minor.yy36; } #line 750 "parser.c" break; case 1: case 14: case 15: #line 229 "parser.lemon" { yygotominor.yy36 = yymsp[0].minor.yy36; } #line 759 "parser.c" break; case 2: #line 235 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(yymsp[-1].minor.yy36, yymsp[0].minor.yy36); } #line 766 "parser.c" break; case 3: case 8: #line 239 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(NULL, yymsp[0].minor.yy36); } #line 774 "parser.c" break; case 4: #line 246 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[-3].minor.yy0, yymsp[-1].minor.yy36, status->scanner_state); yy_destructor(2,&yymsp[-4].minor); yy_destructor(4,&yymsp[-2].minor); yy_destructor(5,&yymsp[0].minor); } #line 784 "parser.c" break; case 5: #line 250 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[-2].minor.yy0, NULL, status->scanner_state); yy_destructor(2,&yymsp[-3].minor); yy_destructor(4,&yymsp[-1].minor); yy_destructor(5,&yymsp[0].minor); } #line 794 "parser.c" break; case 6: #line 254 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[0].minor.yy0, NULL, status->scanner_state); yy_destructor(2,&yymsp[-1].minor); } #line 802 "parser.c" break; case 7: #line 260 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(yymsp[-2].minor.yy36, yymsp[0].minor.yy36); yy_destructor(1,&yymsp[-1].minor); } #line 810 "parser.c" break; case 9: #line 270 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(NULL, yymsp[0].minor.yy36); } #line 817 "parser.c" break; case 10: case 12: #line 274 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(yymsp[-2].minor.yy0, yymsp[0].minor.yy36); yy_destructor(7,&yymsp[-1].minor); } #line 826 "parser.c" break; case 11: case 13: #line 278 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(yymsp[-2].minor.yy0, yymsp[0].minor.yy36); yy_destructor(8,&yymsp[-1].minor); } #line 835 "parser.c" break; case 16: #line 300 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_IDENTIFIER, yymsp[0].minor.yy0); } #line 842 "parser.c" break; case 17: #line 304 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_INTEGER, yymsp[0].minor.yy0); } #line 849 "parser.c" break; case 18: #line 308 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_STRING, yymsp[0].minor.yy0); } #line 856 "parser.c" break; case 19: #line 312 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_DOUBLE, yymsp[0].minor.yy0); } #line 863 "parser.c" break; case 20: #line 316 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_NULL, NULL); yy_destructor(11,&yymsp[0].minor); } #line 871 "parser.c" break; case 21: #line 320 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_FALSE, NULL); yy_destructor(12,&yymsp[0].minor); } #line 879 "parser.c" break; case 22: #line 324 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_TRUE, NULL); yy_destructor(13,&yymsp[0].minor); } #line 887 "parser.c" break; case 23: #line 328 "parser.lemon" { yygotominor.yy36 = phannot_ret_array(yymsp[-1].minor.yy36); yy_destructor(14,&yymsp[-2].minor); yy_destructor(15,&yymsp[0].minor); } #line 896 "parser.c" break; case 24: #line 332 "parser.lemon" { yygotominor.yy36 = phannot_ret_array(yymsp[-1].minor.yy36); yy_destructor(16,&yymsp[-2].minor); yy_destructor(17,&yymsp[0].minor); } #line 905 "parser.c" break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yypParser,yygoto); if( yyact < YYNSTATE ){ yy_shift(yypParser,yyact,yygoto,&yygotominor); }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ phannot_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ phannot_ARG_FETCH; #define TOKEN (yyminor.yy0) #line 151 "parser.lemon" if (status->scanner_state->start_length) { { char *token_name = NULL; const phannot_token_names *tokens = phannot_tokens; int token_found = 0; int active_token = status->scanner_state->active_token; int near_length = status->scanner_state->start_length; if (active_token) { do { if (tokens->code == active_token) { token_found = 1; token_name = tokens->name; break; } ++tokens; } while (tokens[0].code != 0); } if (!token_name) { token_found = 0; token_name = estrndup("UNKNOWN", strlen("UNKNOWN")); } status->syntax_error_len = 128 + strlen(token_name) + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); if (near_length > 0) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), near to '%s' in %s on line %d", token_name, status->token->value, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, near to '%s' in %s on line %d", token_name, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { if (active_token != PHANNOT_T_IGNORE) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), at the end of docblock in %s on line %d", token_name, status->token->value, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, at the end of docblock in %s on line %d", token_name, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected EOF, at the end of docblock in %s on line %d", Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } status->syntax_error[status->syntax_error_len-1] = '\0'; } if (!token_found) { if (token_name) { efree(token_name); } } } } else { status->syntax_error_len = 48 + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); sprintf(status->syntax_error, "Syntax error, unexpected EOF in %s", Z_STRVAL_P(status->scanner_state->active_file)); } status->status = PHANNOT_PARSING_FAILED; #line 1010 "parser.c" phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ phannot_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "phannot_Alloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: **
    **
  • A pointer to the parser (an opaque structure.) **
  • The major token number. **
  • The minor token number. **
  • An option argument of a grammar-specified type. **
** ** Outputs: ** None. */ void phannot_( void *yyp, /* The parser */ int yymajor, /* The major token code number */ phannot_TOKENTYPE yyminor /* The value for the token */ phannot_ARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ int yyerrorhit = 0; /* True if yymajor has invoked an error */ yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ if( yymajor==0 ) return; yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); phannot_ARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyactyyerrcnt--; if( yyendofinput && yypParser->yyidx>=0 ){ yymajor = 0; }else{ yymajor = YYNOCODE; } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else if( yyact == YY_ERROR_ACTION ){ int yymx; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_shift_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif }else{ yy_accept(yypParser); yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ const phannot_token_names phannot_tokens[] = { { "INTEGER", PHANNOT_T_INTEGER }, { "DOUBLE", PHANNOT_T_DOUBLE }, { "STRING", PHANNOT_T_STRING }, { "IDENTIFIER", PHANNOT_T_IDENTIFIER }, { "@", PHANNOT_T_AT }, { ",", PHANNOT_T_COMMA }, { "=", PHANNOT_T_EQUALS }, { ":", PHANNOT_T_COLON }, { "(", PHANNOT_T_PARENTHESES_OPEN }, { ")", PHANNOT_T_PARENTHESES_CLOSE }, { "{", PHANNOT_T_BRACKET_OPEN }, { "}", PHANNOT_T_BRACKET_CLOSE }, { "[", PHANNOT_T_SBRACKET_OPEN }, { "]", PHANNOT_T_SBRACKET_CLOSE }, { "ARBITRARY TEXT", PHANNOT_T_ARBITRARY_TEXT }, { NULL, 0 } }; /** * Wrapper to alloc memory within the parser */ static void *phannot_wrapper_alloc(size_t bytes){ return emalloc(bytes); } /** * Wrapper to free memory within the parser */ static void phannot_wrapper_free(void *pointer){ efree(pointer); } /** * Creates a parser_token to be passed to the parser */ static void phannot_parse_with_token(void* phannot_parser, int opcode, int parsercode, phannot_scanner_token *token, phannot_parser_status *parser_status){ phannot_parser_token *pToken; pToken = emalloc(sizeof(phannot_parser_token)); pToken->opcode = opcode; pToken->token = token->value; pToken->token_len = token->len; pToken->free_flag = 1; phannot_(phannot_parser, parsercode, pToken, parser_status); token->value = NULL; token->len = 0; } /** * Creates an error message when it's triggered by the scanner */ static void phannot_scanner_error_msg(phannot_parser_status *parser_status, zval **error_msg TSRMLS_DC){ int error_length; char *error, *error_part; phannot_scanner_state *state = parser_status->scanner_state; ALLOC_INIT_ZVAL(*error_msg); if (state->start) { error_length = 128 + state->start_length + Z_STRLEN_P(state->active_file); error = emalloc(sizeof(char) * error_length); if (state->start_length > 16) { error_part = estrndup(state->start, 16); snprintf(error, 64 + state->start_length, "Scanning error before '%s...' in %s on line %d", error_part, Z_STRVAL_P(state->active_file), state->active_line); efree(error_part); } else { snprintf(error, error_length - 1, "Scanning error before '%s' in %s on line %d", state->start, Z_STRVAL_P(state->active_file), state->active_line); } error[error_length - 1] = '\0'; ZVAL_STRING(*error_msg, error, 1); } else { error_length = sizeof(char) * (64 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanning error near to EOF in %s", Z_STRVAL_P(state->active_file)); ZVAL_STRING(*error_msg, error, 1); error[error_length - 1] = '\0'; } efree(error); } /** * Receives the comment tokenizes and parses it */ int phannot_parse_annotations(zval *result, zval *comment, zval *file_path, zval *line TSRMLS_DC){ zval *error_msg = NULL; ZVAL_NULL(result); if (Z_TYPE_P(comment) != IS_STRING) { zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Comment must be a string", 0 TSRMLS_CC); return FAILURE; } if(phannot_internal_parse_annotations(&result, comment, file_path, line, &error_msg TSRMLS_CC) == FAILURE){ if (error_msg != NULL) { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg), 1 TSRMLS_CC); zend_throw_exception(zend_exception_get_default(TSRMLS_C), Z_STRVAL_P(error_msg) , 0 TSRMLS_CC); } else { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, ZEND_STRL("There was an error parsing annotation"), 1 TSRMLS_CC); zend_throw_exception(zend_exception_get_default(TSRMLS_C), "There was an error parsing annotation" , 0 TSRMLS_CC); } return FAILURE; } return SUCCESS; } /** * Remove comment separators from a docblock */ void phannot_remove_comment_separators(zval *return_value, char *comment, int length, int *start_lines) { int start_mode = 1, j, i, open_parentheses; smart_str processed_str = {0}; char ch; (*start_lines) = 0; for (i = 0; i < length; i++) { ch = comment[i]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (ch == '@') { smart_str_appendc(&processed_str, ch); i++; open_parentheses = 0; for (j = i; j < length; j++) { ch = comment[j]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (open_parentheses == 0) { if (isalnum(ch) || '_' == ch || '\\' == ch) { smart_str_appendc(&processed_str, ch); continue; } if (ch == '(') { smart_str_appendc(&processed_str, ch); open_parentheses++; continue; } } else { smart_str_appendc(&processed_str, ch); if (ch == '(') { open_parentheses++; } else if (ch == ')') { open_parentheses--; } else if (ch == '\n') { (*start_lines)++; start_mode = 1; } if (open_parentheses > 0) { continue; } } i = j; smart_str_appendc(&processed_str, ' '); break; } } if (ch == '\n') { (*start_lines)++; start_mode = 1; } } smart_str_0(&processed_str); if (processed_str.len) { RETURN_STRINGL(processed_str.c, processed_str.len, 0); } else { RETURN_EMPTY_STRING(); } } /** * Parses a comment returning an intermediate array representation */ int phannot_internal_parse_annotations(zval **result, zval *comment, zval *file_path, zval *line, zval **error_msg TSRMLS_DC) { char *error; phannot_scanner_state *state; phannot_scanner_token token; int scanner_status, status = SUCCESS, start_lines, error_length; phannot_parser_status *parser_status = NULL; void* phannot_parser; zval processed_comment; /** * Check if the comment has content */ if (!Z_STRVAL_P(comment)) { ZVAL_BOOL(*result, 0); return FAILURE; } if (Z_STRLEN_P(comment) < 2) { ZVAL_BOOL(*result, 0); return SUCCESS; } /** * Remove comment separators */ phannot_remove_comment_separators(&processed_comment, Z_STRVAL_P(comment), Z_STRLEN_P(comment), &start_lines); if (Z_STRLEN(processed_comment) < 2) { ZVAL_BOOL(*result, 0); efree(Z_STRVAL(processed_comment)); return SUCCESS; } /** * Start the reentrant parser */ phannot_parser = phannot_Alloc(phannot_wrapper_alloc); parser_status = emalloc(sizeof(phannot_parser_status)); state = emalloc(sizeof(phannot_scanner_state)); parser_status->status = PHANNOT_PARSING_OK; parser_status->scanner_state = state; parser_status->ret = NULL; parser_status->token = &token; parser_status->syntax_error = NULL; /** * Initialize the scanner state */ state->active_token = 0; state->start = Z_STRVAL(processed_comment); state->start_length = 0; state->mode = PHANNOT_MODE_RAW; state->active_file = file_path; token.value = NULL; token.len = 0; /** * Possible start line */ if (Z_TYPE_P(line) == IS_LONG) { state->active_line = Z_LVAL_P(line) - start_lines; } else { state->active_line = 1; } state->end = state->start; while(0 <= (scanner_status = phannot_get_token(state, &token))) { state->active_token = token.opcode; state->start_length = (Z_STRVAL(processed_comment) + Z_STRLEN(processed_comment) - state->start); switch (token.opcode) { case PHANNOT_T_IGNORE: break; case PHANNOT_T_AT: phannot_(phannot_parser, PHANNOT_AT, NULL, parser_status); break; case PHANNOT_T_COMMA: phannot_(phannot_parser, PHANNOT_COMMA, NULL, parser_status); break; case PHANNOT_T_EQUALS: phannot_(phannot_parser, PHANNOT_EQUALS, NULL, parser_status); break; case PHANNOT_T_COLON: phannot_(phannot_parser, PHANNOT_COLON, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_OPEN: phannot_(phannot_parser, PHANNOT_PARENTHESES_OPEN, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_CLOSE: phannot_(phannot_parser, PHANNOT_PARENTHESES_CLOSE, NULL, parser_status); break; case PHANNOT_T_BRACKET_OPEN: phannot_(phannot_parser, PHANNOT_BRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_BRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_BRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_SBRACKET_OPEN: phannot_(phannot_parser, PHANNOT_SBRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_SBRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_SBRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_NULL: phannot_(phannot_parser, PHANNOT_NULL, NULL, parser_status); break; case PHANNOT_T_TRUE: phannot_(phannot_parser, PHANNOT_TRUE, NULL, parser_status); break; case PHANNOT_T_FALSE: phannot_(phannot_parser, PHANNOT_FALSE, NULL, parser_status); break; case PHANNOT_T_INTEGER: phannot_parse_with_token(phannot_parser, PHANNOT_T_INTEGER, PHANNOT_INTEGER, &token, parser_status); break; case PHANNOT_T_DOUBLE: phannot_parse_with_token(phannot_parser, PHANNOT_T_DOUBLE, PHANNOT_DOUBLE, &token, parser_status); break; case PHANNOT_T_STRING: phannot_parse_with_token(phannot_parser, PHANNOT_T_STRING, PHANNOT_STRING, &token, parser_status); break; case PHANNOT_T_IDENTIFIER: phannot_parse_with_token(phannot_parser, PHANNOT_T_IDENTIFIER, PHANNOT_IDENTIFIER, &token, parser_status); break; /*case PHANNOT_T_ARBITRARY_TEXT: phannot_parse_with_token(phannot_parser, PHANNOT_T_ARBITRARY_TEXT, PHANNOT_ARBITRARY_TEXT, &token, parser_status); break;*/ default: parser_status->status = PHANNOT_PARSING_FAILED; if (!*error_msg) { error_length = sizeof(char) * (48 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanner: unknown opcode %d on in %s line %d", token.opcode, Z_STRVAL_P(state->active_file), state->active_line); error[error_length - 1] = '\0'; ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, error, 1); efree(error); } break; } if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; break; } state->end = state->start; } if (status != FAILURE) { switch (scanner_status) { case PHANNOT_SCANNER_RETCODE_ERR: case PHANNOT_SCANNER_RETCODE_IMPOSSIBLE: if (!*error_msg) { phannot_scanner_error_msg(parser_status, error_msg TSRMLS_CC); } status = FAILURE; break; default: phannot_(phannot_parser, 0, NULL, parser_status); } } state->active_token = 0; state->start = NULL; if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; if (parser_status->syntax_error) { if (!*error_msg) { ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, parser_status->syntax_error, 1); } efree(parser_status->syntax_error); } } phannot_Free(phannot_parser, phannot_wrapper_free); if (status != FAILURE) { if (parser_status->status == PHANNOT_PARSING_OK) { if (parser_status->ret) { ZVAL_ZVAL(*result, parser_status->ret, 0, 0); ZVAL_NULL(parser_status->ret); zval_ptr_dtor(&parser_status->ret); } else { array_init(*result); } } } efree(Z_STRVAL(processed_comment)); efree(parser_status); efree(state); return status; } r3-1.3.4/php/r3/annotation/parser.h000066400000000000000000000015221262260041500167730ustar00rootroot00000000000000#define PHANNOT_COMMA 1 #define PHANNOT_AT 2 #define PHANNOT_IDENTIFIER 3 #define PHANNOT_PARENTHESES_OPEN 4 #define PHANNOT_PARENTHESES_CLOSE 5 #define PHANNOT_STRING 6 #define PHANNOT_EQUALS 7 #define PHANNOT_COLON 8 #define PHANNOT_INTEGER 9 #define PHANNOT_DOUBLE 10 #define PHANNOT_NULL 11 #define PHANNOT_FALSE 12 #define PHANNOT_TRUE 13 #define PHANNOT_BRACKET_OPEN 14 #define PHANNOT_BRACKET_CLOSE 15 #define PHANNOT_SBRACKET_OPEN 16 #define PHANNOT_SBRACKET_CLOSE 17 r3-1.3.4/php/r3/annotation/parser.lemon000066400000000000000000000211561262260041500176630ustar00rootroot00000000000000/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ %token_prefix PHANNOT_ %token_type {phannot_parser_token*} %default_type {zval*} %extra_argument {phannot_parser_status *status} %name phannot_ %left COMMA . %include { #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "ext/standard/php_smart_str.h" #include "Zend/zend_exceptions.h" #include "parser.h" #include "scanner.h" #include "annot.h" static zval *phannot_ret_literal_zval(int type, phannot_parser_token *T) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (T) { add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); } return ret; } static zval *phannot_ret_array(zval *items) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ARRAY); if (items) { add_assoc_zval(ret, "items", items); } return ret; } static zval *phannot_ret_zval_list(zval *list_left, zval *right_list) { zval *ret; HashPosition pos; HashTable *list; MAKE_STD_ZVAL(ret); array_init(ret); if (list_left) { list = Z_ARRVAL_P(list_left); if (zend_hash_index_exists(list, 0)) { zend_hash_internal_pointer_reset_ex(list, &pos); for (;; zend_hash_move_forward_ex(list, &pos)) { zval ** item; if (zend_hash_get_current_data_ex(list, (void**) &item, &pos) == FAILURE) { break; } Z_ADDREF_PP(item); add_next_index_zval(ret, *item); } zval_ptr_dtor(&list_left); } else { add_next_index_zval(ret, list_left); } } add_next_index_zval(ret, right_list); return ret; } static zval *phannot_ret_named_item(phannot_parser_token *name, zval *expr) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "expr", expr); if (name != NULL) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } return ret; } static zval *phannot_ret_annotation(phannot_parser_token *name, zval *arguments, phannot_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ANNOTATION); if (name) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } if (arguments) { add_assoc_zval(ret, "arguments", arguments); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } } %syntax_error { if (status->scanner_state->start_length) { { char *token_name = NULL; const phannot_token_names *tokens = phannot_tokens; int token_found = 0; int active_token = status->scanner_state->active_token; int near_length = status->scanner_state->start_length; if (active_token) { do { if (tokens->code == active_token) { token_found = 1; token_name = tokens->name; break; } ++tokens; } while (tokens[0].code != 0); } if (!token_name) { token_found = 0; token_name = estrndup("UNKNOWN", strlen("UNKNOWN")); } status->syntax_error_len = 128 + strlen(token_name) + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); if (near_length > 0) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), near to '%s' in %s on line %d", token_name, status->token->value, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, near to '%s' in %s on line %d", token_name, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { if (active_token != PHANNOT_T_IGNORE) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), at the end of docblock in %s on line %d", token_name, status->token->value, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, at the end of docblock in %s on line %d", token_name, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected EOF, at the end of docblock in %s on line %d", Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } status->syntax_error[status->syntax_error_len-1] = '\0'; } if (!token_found) { if (token_name) { efree(token_name); } } } } else { status->syntax_error_len = 48 + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); sprintf(status->syntax_error, "Syntax error, unexpected EOF in %s", Z_STRVAL_P(status->scanner_state->active_file)); } status->status = PHANNOT_PARSING_FAILED; } %token_destructor { if ($$) { if ($$->free_flag) { efree($$->token); } efree($$); } } program ::= annotation_language(Q) . { status->ret = Q; } %destructor annotation_language { zval_ptr_dtor(&$$); } annotation_language(R) ::= annotation_list(L) . { R = L; } %destructor annotation_list { zval_ptr_dtor(&$$); } annotation_list(R) ::= annotation_list(L) annotation(S) . { R = phannot_ret_zval_list(L, S); } annotation_list(R) ::= annotation(S) . { R = phannot_ret_zval_list(NULL, S); } %destructor annotation { zval_ptr_dtor(&$$); } annotation(R) ::= AT IDENTIFIER(I) PARENTHESES_OPEN argument_list(L) PARENTHESES_CLOSE . { R = phannot_ret_annotation(I, L, status->scanner_state); } annotation(R) ::= AT IDENTIFIER(I) PARENTHESES_OPEN PARENTHESES_CLOSE . { R = phannot_ret_annotation(I, NULL, status->scanner_state); } annotation(R) ::= AT IDENTIFIER(I) . { R = phannot_ret_annotation(I, NULL, status->scanner_state); } %destructor argument_list { zval_ptr_dtor(&$$); } argument_list(R) ::= argument_list(L) COMMA argument_item(I) . { R = phannot_ret_zval_list(L, I); } argument_list(R) ::= argument_item(I) . { R = phannot_ret_zval_list(NULL, I); } %destructor argument_item { zval_ptr_dtor(&$$); } argument_item(R) ::= expr(E) . { R = phannot_ret_named_item(NULL, E); } argument_item(R) ::= STRING(S) EQUALS expr(E) . { R = phannot_ret_named_item(S, E); } argument_item(R) ::= STRING(S) COLON expr(E) . { R = phannot_ret_named_item(S, E); } argument_item(R) ::= IDENTIFIER(I) EQUALS expr(E) . { R = phannot_ret_named_item(I, E); } argument_item(R) ::= IDENTIFIER(I) COLON expr(E) . { R = phannot_ret_named_item(I, E); } %destructor expr { zval_ptr_dtor(&$$); } expr(R) ::= annotation(S) . { R = S; } expr(R) ::= array(A) . { R = A; } expr(R) ::= IDENTIFIER(I) . { R = phannot_ret_literal_zval(PHANNOT_T_IDENTIFIER, I); } expr(R) ::= INTEGER(I) . { R = phannot_ret_literal_zval(PHANNOT_T_INTEGER, I); } expr(R) ::= STRING(S) . { R = phannot_ret_literal_zval(PHANNOT_T_STRING, S); } expr(R) ::= DOUBLE(D) . { R = phannot_ret_literal_zval(PHANNOT_T_DOUBLE, D); } expr(R) ::= NULL . { R = phannot_ret_literal_zval(PHANNOT_T_NULL, NULL); } expr(R) ::= FALSE . { R = phannot_ret_literal_zval(PHANNOT_T_FALSE, NULL); } expr(R) ::= TRUE . { R = phannot_ret_literal_zval(PHANNOT_T_TRUE, NULL); } array(R) ::= BRACKET_OPEN argument_list(A) BRACKET_CLOSE . { R = phannot_ret_array(A); } array(R) ::= SBRACKET_OPEN argument_list(A) SBRACKET_CLOSE . { R = phannot_ret_array(A); } r3-1.3.4/php/r3/annotation/parser.out000066400000000000000000000376711262260041500173710ustar00rootroot00000000000000 State 0: program ::= * annotation_language annotation_language ::= * annotation_list annotation_list ::= * annotation_list annotation annotation_list ::= * annotation annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER AT shift 16 program accept annotation_language shift 23 annotation_list shift 9 annotation shift 24 State 1: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= AT IDENTIFIER PARENTHESES_OPEN * argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= AT IDENTIFIER PARENTHESES_OPEN * PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_list ::= * argument_list COMMA argument_item argument_list ::= * argument_item argument_item ::= * expr argument_item ::= * STRING EQUALS expr argument_item ::= * STRING COLON expr argument_item ::= * IDENTIFIER EQUALS expr argument_item ::= * IDENTIFIER COLON expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 12 PARENTHESES_CLOSE shift 22 STRING shift 14 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 argument_list shift 10 argument_item shift 17 expr shift 28 array shift 31 State 2: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_list ::= * argument_list COMMA argument_item argument_list ::= * argument_item argument_item ::= * expr argument_item ::= * STRING EQUALS expr argument_item ::= * STRING COLON expr argument_item ::= * IDENTIFIER EQUALS expr argument_item ::= * IDENTIFIER COLON expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= BRACKET_OPEN * argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 12 STRING shift 14 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 argument_list shift 11 argument_item shift 17 expr shift 28 array shift 31 State 3: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_list ::= * argument_list COMMA argument_item argument_list ::= * argument_item argument_item ::= * expr argument_item ::= * STRING EQUALS expr argument_item ::= * STRING COLON expr argument_item ::= * IDENTIFIER EQUALS expr argument_item ::= * IDENTIFIER COLON expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE array ::= SBRACKET_OPEN * argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 12 STRING shift 14 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 argument_list shift 13 argument_item shift 17 expr shift 28 array shift 31 State 4: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_list ::= argument_list COMMA * argument_item argument_item ::= * expr argument_item ::= * STRING EQUALS expr argument_item ::= * STRING COLON expr argument_item ::= * IDENTIFIER EQUALS expr argument_item ::= * IDENTIFIER COLON expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 12 STRING shift 14 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 argument_item shift 27 expr shift 28 array shift 31 State 5: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_item ::= STRING EQUALS * expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 32 STRING shift 34 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 expr shift 29 array shift 31 State 6: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_item ::= IDENTIFIER EQUALS * expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 32 STRING shift 34 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 expr shift 18 array shift 31 State 7: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_item ::= STRING COLON * expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 32 STRING shift 34 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 expr shift 21 array shift 31 State 8: annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER argument_item ::= IDENTIFIER COLON * expr expr ::= * annotation expr ::= * array expr ::= * IDENTIFIER expr ::= * INTEGER expr ::= * STRING expr ::= * DOUBLE expr ::= * NULL expr ::= * FALSE expr ::= * TRUE array ::= * BRACKET_OPEN argument_list BRACKET_CLOSE array ::= * SBRACKET_OPEN argument_list SBRACKET_CLOSE AT shift 16 IDENTIFIER shift 32 STRING shift 34 INTEGER shift 33 DOUBLE shift 35 NULL shift 36 FALSE shift 37 TRUE shift 38 BRACKET_OPEN shift 2 SBRACKET_OPEN shift 3 annotation shift 30 expr shift 20 array shift 31 State 9: (1) annotation_language ::= annotation_list * annotation_list ::= annotation_list * annotation annotation ::= * AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= * AT IDENTIFIER AT shift 16 annotation shift 25 {default} reduce 1 State 10: annotation ::= AT IDENTIFIER PARENTHESES_OPEN argument_list * PARENTHESES_CLOSE argument_list ::= argument_list * COMMA argument_item COMMA shift 4 PARENTHESES_CLOSE shift 26 State 11: argument_list ::= argument_list * COMMA argument_item array ::= BRACKET_OPEN argument_list * BRACKET_CLOSE COMMA shift 4 BRACKET_CLOSE shift 39 State 12: argument_item ::= IDENTIFIER * EQUALS expr argument_item ::= IDENTIFIER * COLON expr (16) expr ::= IDENTIFIER * EQUALS shift 6 COLON shift 8 {default} reduce 16 State 13: argument_list ::= argument_list * COMMA argument_item array ::= SBRACKET_OPEN argument_list * SBRACKET_CLOSE COMMA shift 4 SBRACKET_CLOSE shift 19 State 14: argument_item ::= STRING * EQUALS expr argument_item ::= STRING * COLON expr (18) expr ::= STRING * EQUALS shift 5 COLON shift 7 {default} reduce 18 State 15: annotation ::= AT IDENTIFIER * PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= AT IDENTIFIER * PARENTHESES_OPEN PARENTHESES_CLOSE (6) annotation ::= AT IDENTIFIER * PARENTHESES_OPEN shift 1 {default} reduce 6 State 16: annotation ::= AT * IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE annotation ::= AT * IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE annotation ::= AT * IDENTIFIER IDENTIFIER shift 15 State 17: (8) argument_list ::= argument_item * {default} reduce 8 State 18: (12) argument_item ::= IDENTIFIER EQUALS expr * {default} reduce 12 State 19: (24) array ::= SBRACKET_OPEN argument_list SBRACKET_CLOSE * {default} reduce 24 State 20: (13) argument_item ::= IDENTIFIER COLON expr * {default} reduce 13 State 21: (11) argument_item ::= STRING COLON expr * {default} reduce 11 State 22: (5) annotation ::= AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE * {default} reduce 5 State 23: (0) program ::= annotation_language * {default} reduce 0 State 24: (3) annotation_list ::= annotation * {default} reduce 3 State 25: (2) annotation_list ::= annotation_list annotation * {default} reduce 2 State 26: (4) annotation ::= AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE * {default} reduce 4 State 27: (7) argument_list ::= argument_list COMMA argument_item * {default} reduce 7 State 28: (9) argument_item ::= expr * {default} reduce 9 State 29: (10) argument_item ::= STRING EQUALS expr * {default} reduce 10 State 30: (14) expr ::= annotation * {default} reduce 14 State 31: (15) expr ::= array * {default} reduce 15 State 32: (16) expr ::= IDENTIFIER * {default} reduce 16 State 33: (17) expr ::= INTEGER * {default} reduce 17 State 34: (18) expr ::= STRING * {default} reduce 18 State 35: (19) expr ::= DOUBLE * {default} reduce 19 State 36: (20) expr ::= NULL * {default} reduce 20 State 37: (21) expr ::= FALSE * {default} reduce 21 State 38: (22) expr ::= TRUE * {default} reduce 22 State 39: (23) array ::= BRACKET_OPEN argument_list BRACKET_CLOSE * {default} reduce 23 r3-1.3.4/php/r3/annotation/scanner.c000066400000000000000000000305041262260041500171250ustar00rootroot00000000000000/* Generated by re2c 0.13.5 on Sun Feb 16 21:59:06 2014 */ #line 1 "scanner.re" /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "scanner.h" #define YYCTYPE unsigned char #define YYCURSOR (s->start) #define YYLIMIT (s->end) #define YYMARKER q int phannot_get_token(phannot_scanner_state *s, phannot_scanner_token *token) { char next, *q = YYCURSOR, *start = YYCURSOR; int status = PHANNOT_SCANNER_RETCODE_IMPOSSIBLE; while (PHANNOT_SCANNER_RETCODE_IMPOSSIBLE == status) { if (s->mode == PHANNOT_MODE_RAW) { if (*YYCURSOR == '\n') { s->active_line++; } next = *(YYCURSOR+1); if (*YYCURSOR == '\0' || *YYCURSOR == '@') { if ((next >= 'A' && next <= 'Z') || (next >= 'a' && next <= 'z')) { s->mode = PHANNOT_MODE_ANNOTATION; continue; } } ++YYCURSOR; token->opcode = PHANNOT_T_IGNORE; return 0; } else { #line 65 "scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 96, 96, 96, 96, 96, 96, 96, 96, 104, 96, 96, 96, 104, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 104, 96, 32, 96, 96, 96, 96, 64, 96, 96, 96, 96, 96, 96, 96, 96, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 96, 96, 96, 96, 96, 96, 96, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 96, 0, 96, 96, 112, 96, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, }; yych = *YYCURSOR; switch (yych) { case 0x00: goto yy38; case '\t': case '\r': case ' ': goto yy34; case '\n': goto yy36; case '"': goto yy10; case '\'': goto yy11; case '(': goto yy14; case ')': goto yy16; case ',': goto yy32; case '-': goto yy2; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy4; case ':': goto yy30; case '=': goto yy28; case '@': goto yy26; case 'A': case 'B': case 'C': case 'D': case 'E': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'o': case 'p': case 'q': case 'r': case 's': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy13; case 'F': case 'f': goto yy8; case 'N': case 'n': goto yy6; case 'T': case 't': goto yy9; case '[': goto yy22; case '\\': goto yy12; case ']': goto yy24; case '{': goto yy18; case '}': goto yy20; default: goto yy40; } yy2: ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 128) { goto yy71; } yy3: #line 182 "scanner.re" { status = PHANNOT_SCANNER_RETCODE_ERR; break; } #line 201 "scanner.c" yy4: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); goto yy72; yy5: #line 66 "scanner.re" { token->opcode = PHANNOT_T_INTEGER; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } #line 215 "scanner.c" yy6: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy66; if (yych == 'u') goto yy66; goto yy44; yy7: #line 108 "scanner.re" { token->opcode = PHANNOT_T_IDENTIFIER; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } #line 231 "scanner.c" yy8: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'A') goto yy61; if (yych == 'a') goto yy61; goto yy44; yy9: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'R') goto yy57; if (yych == 'r') goto yy57; goto yy44; yy10: yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy3; goto yy55; yy11: yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy3; goto yy50; yy12: yych = *++YYCURSOR; if (yych <= '^') { if (yych <= '@') goto yy3; if (yych <= 'Z') goto yy43; goto yy3; } else { if (yych == '`') goto yy3; if (yych <= 'z') goto yy43; goto yy3; } yy13: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); goto yy44; yy14: ++YYCURSOR; #line 116 "scanner.re" { token->opcode = PHANNOT_T_PARENTHESES_OPEN; return 0; } #line 276 "scanner.c" yy16: ++YYCURSOR; #line 121 "scanner.re" { token->opcode = PHANNOT_T_PARENTHESES_CLOSE; return 0; } #line 284 "scanner.c" yy18: ++YYCURSOR; #line 126 "scanner.re" { token->opcode = PHANNOT_T_BRACKET_OPEN; return 0; } #line 292 "scanner.c" yy20: ++YYCURSOR; #line 131 "scanner.re" { token->opcode = PHANNOT_T_BRACKET_CLOSE; return 0; } #line 300 "scanner.c" yy22: ++YYCURSOR; #line 136 "scanner.re" { token->opcode = PHANNOT_T_SBRACKET_OPEN; return 0; } #line 308 "scanner.c" yy24: ++YYCURSOR; #line 141 "scanner.re" { token->opcode = PHANNOT_T_SBRACKET_CLOSE; return 0; } #line 316 "scanner.c" yy26: ++YYCURSOR; #line 146 "scanner.re" { token->opcode = PHANNOT_T_AT; return 0; } #line 324 "scanner.c" yy28: ++YYCURSOR; #line 151 "scanner.re" { token->opcode = PHANNOT_T_EQUALS; return 0; } #line 332 "scanner.c" yy30: ++YYCURSOR; #line 156 "scanner.re" { token->opcode = PHANNOT_T_COLON; return 0; } #line 340 "scanner.c" yy32: ++YYCURSOR; #line 161 "scanner.re" { token->opcode = PHANNOT_T_COMMA; return 0; } #line 348 "scanner.c" yy34: ++YYCURSOR; yych = *YYCURSOR; goto yy42; yy35: #line 166 "scanner.re" { token->opcode = PHANNOT_T_IGNORE; return 0; } #line 359 "scanner.c" yy36: ++YYCURSOR; #line 171 "scanner.re" { s->active_line++; token->opcode = PHANNOT_T_IGNORE; return 0; } #line 368 "scanner.c" yy38: ++YYCURSOR; #line 177 "scanner.re" { status = PHANNOT_SCANNER_RETCODE_EOF; break; } #line 376 "scanner.c" yy40: yych = *++YYCURSOR; goto yy3; yy41: ++YYCURSOR; yych = *YYCURSOR; yy42: if (yybm[0+yych] & 8) { goto yy41; } goto yy35; yy43: yyaccept = 1; YYMARKER = ++YYCURSOR; yych = *YYCURSOR; yy44: if (yybm[0+yych] & 16) { goto yy43; } if (yych != '\\') goto yy7; yy45: ++YYCURSOR; yych = *YYCURSOR; if (yych <= '^') { if (yych <= '@') goto yy46; if (yych <= 'Z') goto yy47; } else { if (yych == '`') goto yy46; if (yych <= 'z') goto yy47; } yy46: YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy5; } else { goto yy7; } } else { goto yy3; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy60; } else { goto yy65; } } else { goto yy69; } } yy47: yyaccept = 1; YYMARKER = ++YYCURSOR; yych = *YYCURSOR; if (yych <= '[') { if (yych <= '9') { if (yych <= '/') goto yy7; goto yy47; } else { if (yych <= '@') goto yy7; if (yych <= 'Z') goto yy47; goto yy7; } } else { if (yych <= '_') { if (yych <= '\\') goto yy45; if (yych <= '^') goto yy7; goto yy47; } else { if (yych <= '`') goto yy7; if (yych <= 'z') goto yy47; goto yy7; } } yy49: ++YYCURSOR; yych = *YYCURSOR; yy50: if (yybm[0+yych] & 32) { goto yy49; } if (yych <= 0x00) goto yy46; if (yych <= '[') goto yy52; ++YYCURSOR; yych = *YYCURSOR; if (yych == '\n') goto yy46; goto yy49; yy52: ++YYCURSOR; #line 99 "scanner.re" { token->opcode = PHANNOT_T_STRING; token->value = estrndup(q, YYCURSOR - q - 1); token->len = YYCURSOR - q - 1; q = YYCURSOR; return 0; } #line 477 "scanner.c" yy54: ++YYCURSOR; yych = *YYCURSOR; yy55: if (yybm[0+yych] & 64) { goto yy54; } if (yych <= 0x00) goto yy46; if (yych <= '[') goto yy52; ++YYCURSOR; yych = *YYCURSOR; if (yych == '\n') goto yy46; goto yy54; yy57: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy58; if (yych != 'u') goto yy44; yy58: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy59; if (yych != 'e') goto yy44; yy59: yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy43; } if (yych == '\\') goto yy45; yy60: #line 93 "scanner.re" { token->opcode = PHANNOT_T_TRUE; return 0; } #line 514 "scanner.c" yy61: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'L') goto yy62; if (yych != 'l') goto yy44; yy62: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'S') goto yy63; if (yych != 's') goto yy44; yy63: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy64; if (yych != 'e') goto yy44; yy64: yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy43; } if (yych == '\\') goto yy45; yy65: #line 88 "scanner.re" { token->opcode = PHANNOT_T_FALSE; return 0; } #line 543 "scanner.c" yy66: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'L') goto yy67; if (yych != 'l') goto yy44; yy67: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'L') goto yy68; if (yych != 'l') goto yy44; yy68: yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy43; } if (yych == '\\') goto yy45; yy69: #line 83 "scanner.re" { token->opcode = PHANNOT_T_NULL; return 0; } #line 567 "scanner.c" yy70: yych = *++YYCURSOR; if (yych <= '/') goto yy46; if (yych <= '9') goto yy73; goto yy46; yy71: yyaccept = 0; YYMARKER = ++YYCURSOR; yych = *YYCURSOR; yy72: if (yybm[0+yych] & 128) { goto yy71; } if (yych == '.') goto yy70; goto yy5; yy73: ++YYCURSOR; yych = *YYCURSOR; if (yych <= '/') goto yy75; if (yych <= '9') goto yy73; yy75: #line 75 "scanner.re" { token->opcode = PHANNOT_T_DOUBLE; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } #line 597 "scanner.c" } #line 187 "scanner.re" } } return status; } r3-1.3.4/php/r3/annotation/scanner.h000066400000000000000000000052731262260041500171370ustar00rootroot00000000000000 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ #define PHANNOT_SCANNER_RETCODE_EOF -1 #define PHANNOT_SCANNER_RETCODE_ERR -2 #define PHANNOT_SCANNER_RETCODE_IMPOSSIBLE -3 /** Modes */ #define PHANNOT_MODE_RAW 0 #define PHANNOT_MODE_ANNOTATION 1 #define PHANNOT_T_IGNORE 297 #define PHANNOT_T_DOCBLOCK_ANNOTATION 299 #define PHANNOT_T_ANNOTATION 300 /* Literals & Identifiers */ #define PHANNOT_T_INTEGER 301 #define PHANNOT_T_DOUBLE 302 #define PHANNOT_T_STRING 303 #define PHANNOT_T_NULL 304 #define PHANNOT_T_FALSE 305 #define PHANNOT_T_TRUE 306 #define PHANNOT_T_IDENTIFIER 307 #define PHANNOT_T_ARRAY 308 #define PHANNOT_T_ARBITRARY_TEXT 309 /* Operators */ #define PHANNOT_T_AT '@' #define PHANNOT_T_DOT '.' #define PHANNOT_T_COMMA ',' #define PHANNOT_T_EQUALS '=' #define PHANNOT_T_COLON ':' #define PHANNOT_T_BRACKET_OPEN '{' #define PHANNOT_T_BRACKET_CLOSE '}' #define PHANNOT_T_SBRACKET_OPEN '[' #define PHANNOT_T_SBRACKET_CLOSE ']' #define PHANNOT_T_PARENTHESES_OPEN '(' #define PHANNOT_T_PARENTHESES_CLOSE ')' /* List of tokens and their names */ typedef struct _phannot_token_names { char *name; unsigned int code; } phannot_token_names; /* Active token state */ typedef struct _phannot_scanner_state { char* start; char* end; int active_token; unsigned int start_length; int mode; unsigned int active_line; zval *active_file; } phannot_scanner_state; /* Extra information tokens */ typedef struct _phannot_scanner_token { char *value; int opcode; int len; } phannot_scanner_token; int phannot_get_token(phannot_scanner_state *s, phannot_scanner_token *token); extern const phannot_token_names phannot_tokens[]; r3-1.3.4/php/r3/annotation/scanner.re000066400000000000000000000100661262260041500173120ustar00rootroot00000000000000 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez | | Eduar Carvajal | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "scanner.h" #define YYCTYPE unsigned char #define YYCURSOR (s->start) #define YYLIMIT (s->end) #define YYMARKER q int phannot_get_token(phannot_scanner_state *s, phannot_scanner_token *token) { char next, *q = YYCURSOR, *start = YYCURSOR; int status = PHANNOT_SCANNER_RETCODE_IMPOSSIBLE; while (PHANNOT_SCANNER_RETCODE_IMPOSSIBLE == status) { if (s->mode == PHANNOT_MODE_RAW) { if (*YYCURSOR == '\n') { s->active_line++; } next = *(YYCURSOR+1); if (*YYCURSOR == '\0' || *YYCURSOR == '@') { if ((next >= 'A' && next <= 'Z') || (next >= 'a' && next <= 'z')) { s->mode = PHANNOT_MODE_ANNOTATION; continue; } } ++YYCURSOR; token->opcode = PHANNOT_T_IGNORE; return 0; } else { /*!re2c re2c:indent:top = 2; re2c:yyfill:enable = 0; INTEGER = [\-]?[0-9]+; INTEGER { token->opcode = PHANNOT_T_INTEGER; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } DOUBLE = ([\-]?[0-9]+[\.][0-9]+); DOUBLE { token->opcode = PHANNOT_T_DOUBLE; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } 'null' { token->opcode = PHANNOT_T_NULL; return 0; } 'false' { token->opcode = PHANNOT_T_FALSE; return 0; } 'true' { token->opcode = PHANNOT_T_TRUE; return 0; } STRING = (["] ([\\]["]|[\\].|[\001-\377]\[\\"])* ["])|(['] ([\\][']|[\\].|[\001-\377]\[\\'])* [']); STRING { token->opcode = PHANNOT_T_STRING; token->value = estrndup(q, YYCURSOR - q - 1); token->len = YYCURSOR - q - 1; q = YYCURSOR; return 0; } IDENTIFIER = ('\x5C'?[a-zA-Z_]([a-zA-Z0-9_]*)('\x5C'[a-zA-Z_]([a-zA-Z0-9_]*))*); IDENTIFIER { token->opcode = PHANNOT_T_IDENTIFIER; token->value = estrndup(start, YYCURSOR - start); token->len = YYCURSOR - start; q = YYCURSOR; return 0; } "(" { token->opcode = PHANNOT_T_PARENTHESES_OPEN; return 0; } ")" { token->opcode = PHANNOT_T_PARENTHESES_CLOSE; return 0; } "{" { token->opcode = PHANNOT_T_BRACKET_OPEN; return 0; } "}" { token->opcode = PHANNOT_T_BRACKET_CLOSE; return 0; } "[" { token->opcode = PHANNOT_T_SBRACKET_OPEN; return 0; } "]" { token->opcode = PHANNOT_T_SBRACKET_CLOSE; return 0; } "@" { token->opcode = PHANNOT_T_AT; return 0; } "=" { token->opcode = PHANNOT_T_EQUALS; return 0; } ":" { token->opcode = PHANNOT_T_COLON; return 0; } "," { token->opcode = PHANNOT_T_COMMA; return 0; } [ \t\r]+ { token->opcode = PHANNOT_T_IGNORE; return 0; } [\n] { s->active_line++; token->opcode = PHANNOT_T_IGNORE; return 0; } "\000" { status = PHANNOT_SCANNER_RETCODE_EOF; break; } [^] { status = PHANNOT_SCANNER_RETCODE_ERR; break; } */ } } return status; } r3-1.3.4/php/r3/config.m4000066400000000000000000000024161262260041500146660ustar00rootroot00000000000000dnl config.m4 for extension r3 PHP_ARG_WITH(r3, for r3 support, [ --with-r3 Include r3 support]) dnl PHP_ARG_ENABLE(r3, whether to enable r3 support, dnl Make sure that the comment is aligned: dnl [ --enable-r3 Enable r3 support]) if test "$PHP_R3" != "no"; then SEARCH_PATH="/usr/local /usr" SEARCH_FOR="/include/r3/r3.h" if test -r $PHP_R3/$SEARCH_FOR; then R3_DIR=$PHP_R3 else AC_MSG_CHECKING([for r3 files in default path]) for i in $SEARCH_PATH ; do if test -r $i/$SEARCH_FOR; then R3_DIR=$i AC_MSG_RESULT(found in $i) fi done fi if test -z "$R3_DIR"; then AC_MSG_RESULT([not found]) AC_MSG_ERROR([Please reinstall the r3 distribution]) fi echo $R3_DIR dnl # --with-r3 -> add include path PHP_ADD_INCLUDE($R3_DIR/include) LIBNAME=r3 LIBSYMBOL=r3_route_create PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL, [ PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $R3_DIR/lib, R3_SHARED_LIBADD) AC_DEFINE(HAVE_R3LIB,1,[ ]) ],[ AC_MSG_ERROR([wrong r3 lib version or lib not found]) ],[ -L$R3_DIR/lib -lm ]) PHP_SUBST(R3_SHARED_LIBADD) PHP_NEW_EXTENSION(r3, [ct_helper.c hash.c php_expandable_mux.c php_r3.c r3_controller.c r3_functions.c r3_mux.c r3_persistent.c], $ext_shared) fi r3-1.3.4/php/r3/ct_helper.c000066400000000000000000000067511262260041500152760ustar00rootroot00000000000000 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "ct_helper.h" #define ZEND_FIND_FUNC(ce, name, name_len, fe) \ zend_hash_find(&ce->function_table, name, name_len, (void **) &fe) #define ZEND_FIND_FUNC_QUICK(ce, name, name_len, fe) \ zend_hash_quick_find(&ce->function_table, name, name_len, zend_inline_hash_func(name, name_len) , (void **) &fe) /* {{{ zend_call_method Only returns the returned zval if retval_ptr != NULL */ ZEND_API zval* zend_call_method_with_3_params(zval **object_pp, zend_class_entry *obj_ce, zend_function **fn_proxy, const char *function_name, int function_name_len, zval **retval_ptr_ptr, int param_count, zval* arg1, zval* arg2, zval* arg3 TSRMLS_DC) { int result; zend_fcall_info fci; zval z_fname; zval *retval; HashTable *function_table; zval **params[3]; params[0] = &arg1; params[1] = &arg2; params[2] = &arg3; fci.size = sizeof(fci); /*fci.function_table = NULL; will be read form zend_class_entry of object if needed */ fci.object_ptr = object_pp ? *object_pp : NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; fci.param_count = param_count; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; if (!fn_proxy && !obj_ce) { /* no interest in caching and no information already present that is * needed later inside zend_call_function. */ ZVAL_STRINGL(&z_fname, function_name, function_name_len, 0); fci.function_table = !object_pp ? EG(function_table) : NULL; result = zend_call_function(&fci, NULL TSRMLS_CC); } else { zend_fcall_info_cache fcic; fcic.initialized = 1; if (!obj_ce) { obj_ce = object_pp ? Z_OBJCE_PP(object_pp) : NULL; } if (obj_ce) { function_table = &obj_ce->function_table; } else { function_table = EG(function_table); } if (!fn_proxy || !*fn_proxy) { if (zend_hash_find(function_table, function_name, function_name_len+1, (void **) &fcic.function_handler) == FAILURE) { /* error at c-level */ zend_error(E_CORE_ERROR, "Couldn't find implementation for method %s%s%s", obj_ce ? obj_ce->name : "", obj_ce ? "::" : "", function_name); } if (fn_proxy) { *fn_proxy = fcic.function_handler; } } else { fcic.function_handler = *fn_proxy; } fcic.calling_scope = obj_ce; if (object_pp) { fcic.called_scope = Z_OBJCE_PP(object_pp); } else if (obj_ce && !(EG(called_scope) && instanceof_function(EG(called_scope), obj_ce TSRMLS_CC))) { fcic.called_scope = obj_ce; } else { fcic.called_scope = EG(called_scope); } fcic.object_ptr = object_pp ? *object_pp : NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); } if (result == FAILURE) { /* error at c-level */ if (!obj_ce) { obj_ce = object_pp ? Z_OBJCE_PP(object_pp) : NULL; } if (!EG(exception)) { zend_error(E_CORE_ERROR, "Couldn't execute method %s%s%s", obj_ce ? obj_ce->name : "", obj_ce ? "::" : "", function_name); } } if (!retval_ptr_ptr) { if (retval) { zval_ptr_dtor(&retval); } return NULL; } return *retval_ptr_ptr; } /* }}} */ char * find_place_holder(char *pattern, int pattern_len) { char needle_char[2] = { ':', 0 }; return php_memnstr(pattern, needle_char, 1, pattern + pattern_len); } r3-1.3.4/php/r3/ct_helper.h000066400000000000000000000005631262260041500152760ustar00rootroot00000000000000#ifndef PHP_CT_HELPER_H #define PHP_CT_HELPER_H 1 ZEND_API zval* zend_call_method_with_3_params(zval **object_pp, zend_class_entry *obj_ce, zend_function **fn_proxy, const char *function_name, int function_name_len, zval **retval_ptr_ptr, int param_count, zval* arg1, zval* arg2, zval* arg3 TSRMLS_DC); char * find_place_holder(char *pattern, int pattern_len); #endif r3-1.3.4/php/r3/hash.c000066400000000000000000000063661262260041500142560ustar00rootroot00000000000000 #include "hash.h" HashTable * zend_hash_clone_persistent(HashTable* src TSRMLS_DC) { zval **tmp; return my_copy_hashtable(NULL, src, (ht_copy_fun_t) my_copy_zval_ptr, (void*) &tmp, sizeof(zval *), 1 TSRMLS_CC); } HashTable * zend_hash_clone(HashTable* src TSRMLS_DC) { zval **tmp; return my_copy_hashtable(NULL, src, (ht_copy_fun_t) my_copy_zval_ptr, (void*) &tmp, sizeof(zval *), 0 TSRMLS_CC); } /** * Recursively copy hash and all its value. * * This replaces zend_hash_copy */ HashTable * my_copy_hashtable(HashTable *target, HashTable *source, ht_copy_fun_t copy_fn, void *tmp, uint size, int persistent TSRMLS_DC) { Bucket *curr = NULL, *prev = NULL , *newp = NULL; void *new_entry; int first = 1; assert(source != NULL); // allocate persistent memory for target and initialize it. if (!target) { target = pemalloc(sizeof(source[0]), persistent); } memcpy(target, source, sizeof(source[0])); target->arBuckets = pemalloc(target->nTableSize * sizeof(Bucket*), persistent); memset(target->arBuckets, 0, target->nTableSize * sizeof(Bucket*)); target->pInternalPointer = NULL; target->pListHead = NULL; // since it's persistent, destructor should be NULL target->persistent = persistent; if (! target->persistent) { target->pDestructor = ZVAL_PTR_DTOR; } curr = source->pListHead; while (curr) { // hash index int n = curr->h % target->nTableSize; // allocate new bucket // from apc #ifdef ZEND_ENGINE_2_4 if (!curr->nKeyLength) { newp = (Bucket*) pemalloc(sizeof(Bucket), persistent); memcpy(newp, curr, sizeof(Bucket)); } else if (IS_INTERNED(curr->arKey)) { newp = (Bucket*) pemalloc(sizeof(Bucket), persistent); memcpy(newp, curr, sizeof(Bucket)); } else { // ugly but we need to copy newp = (Bucket*) pemalloc(sizeof(Bucket) + curr->nKeyLength, persistent); memcpy(newp, curr, sizeof(Bucket) + curr->nKeyLength ); newp->arKey = (const char*)(newp+1); } #else newp = (Bucket*) pecalloc(1, (sizeof(Bucket) + curr->nKeyLength - 1), persistent); memcpy(newp, curr, sizeof(Bucket) + curr->nKeyLength - 1); #endif /* insert 'newp' into the linked list at its hashed index */ if (target->arBuckets[n]) { newp->pNext = target->arBuckets[n]; newp->pLast = NULL; newp->pNext->pLast = newp; } else { newp->pNext = newp->pLast = NULL; } target->arBuckets[n] = newp; // now we copy the bucket data using our 'copy_fn' newp->pData = copy_fn(NULL, curr->pData, persistent TSRMLS_CC); memcpy(&newp->pDataPtr, newp->pData, sizeof(void*)); /* insert 'newp' into the table-thread linked list */ newp->pListLast = prev; newp->pListNext = NULL; if (prev) { prev->pListNext = newp; } if (first) { target->pListHead = newp; first = 0; } prev = newp; curr = curr->pListNext; } target->pListTail = newp; zend_hash_internal_pointer_reset(target); // return the newly allocated memory return target; } r3-1.3.4/php/r3/hash.h000066400000000000000000000031171262260041500142520ustar00rootroot00000000000000#ifndef HASH_H #define HASH_H 1 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_mux.h" #include "r3_functions.h" #if R3_DEBUG #define HT_OK 0 #define HT_IS_DESTROYING 1 #define HT_DESTROYED 2 #define HT_CLEANING 3 static void _zend_is_inconsistent(const HashTable *ht, const char *file, int line) { if (ht->inconsistent==HT_OK) { return; } switch (ht->inconsistent) { case HT_IS_DESTROYING: zend_output_debug_string(1, "%s(%d) : ht=%p is being destroyed", file, line, ht); break; case HT_DESTROYED: zend_output_debug_string(1, "%s(%d) : ht=%p is already destroyed", file, line, ht); break; case HT_CLEANING: zend_output_debug_string(1, "%s(%d) : ht=%p is being cleaned", file, line, ht); break; default: zend_output_debug_string(1, "%s(%d) : ht=%p is inconsistent", file, line, ht); break; } zend_bailout(); } #define IS_CONSISTENT(a) _zend_is_inconsistent(a, __FILE__, __LINE__); #define SET_INCONSISTENT(n) ht->inconsistent = n; #else #define IS_CONSISTENT(a) #define SET_INCONSISTENT(n) #endif HashTable * zend_hash_clone_persistent(HashTable* src TSRMLS_DC); HashTable * zend_hash_clone(HashTable* src TSRMLS_DC); typedef void* (*ht_copy_fun_t)(void*, void*, int TSRMLS_DC); HashTable * my_copy_hashtable(HashTable *target, HashTable *source, ht_copy_fun_t copy_fn, void *tmp, uint size, int persistent TSRMLS_DC); #endif r3-1.3.4/php/r3/php_expandable_mux.c000066400000000000000000000026751262260041500171750ustar00rootroot00000000000000#include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "r3_functions.h" #include "php_expandable_mux.h" zend_class_entry *ce_r3_expandable_mux; const zend_function_entry expandable_mux_methods[] = { PHP_ABSTRACT_ME(ExpandableMux, expand, NULL) PHP_FE_END }; /** * TODO: Use zend_class_implements to register Controller class. * * zend_class_implements(mysqli_result_class_entry TSRMLS_CC, 1, zend_ce_traversable); */ static int implement_expandable_mux_interface_handler(zend_class_entry *interface, zend_class_entry *implementor TSRMLS_DC) { if (implementor->type == ZEND_USER_CLASS && !instanceof_function(implementor, ce_r3_expandable_mux TSRMLS_CC) ) { zend_error(E_ERROR, "R3\\ExpandableMux can't be implemented by user classes"); } return SUCCESS; } void r3_init_expandable_mux(TSRMLS_D) { zend_class_entry ce_interface; INIT_CLASS_ENTRY(ce_interface, "R3\\ExpandableMux", expandable_mux_methods); // if(Z_TYPE_PP(current) == IS_OBJECT && instanceof_function(Z_OBJCE_PP(current), curl_CURLFile_class TSRMLS_CC)) ce_r3_expandable_mux = zend_register_internal_interface(&ce_interface TSRMLS_CC); ce_r3_expandable_mux->interface_gets_implemented = implement_expandable_mux_interface_handler; } r3-1.3.4/php/r3/php_expandable_mux.h000066400000000000000000000007471262260041500172000ustar00rootroot00000000000000#ifndef PHP_EXPANDABLE_MUX_H #define PHP_EXPANDABLE_MUX_H 1 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_functions.h" extern zend_class_entry *ce_r3_expandable_mux; void r3_init_expandable_mux(TSRMLS_D); #endif r3-1.3.4/php/r3/php_r3.c000066400000000000000000000046161262260041500145220ustar00rootroot00000000000000#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/standard/php_string.h" #include "php_r3.h" // #include "ct_helper.h" #include "r3_functions.h" // #include "r3_mux.h" // #include "php_expandable_mux.h" // #include "r3_controller.h" ZEND_DECLARE_MODULE_GLOBALS(r3); // persistent list entry type for HashTable int le_mux_hash_table; // persistent list entry type for boolean int le_mux_bool; // persistent list entry type for int int le_mux_int; // persistent list entry type for string int le_mux_string; zend_class_entry *ce_r3_exception; // #define DEBUG 1 static const zend_function_entry r3_functions[] = { PHP_FE(r3_match, NULL) PHP_FE_END }; void r3_init_exception(TSRMLS_D) { zend_class_entry e; INIT_CLASS_ENTRY(e, "R3Exception", NULL); ce_r3_exception = zend_register_internal_class_ex(&e, (zend_class_entry*)zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC); } void r3_mux_le_hash_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { HashTable *h = (HashTable*) rsrc->ptr; if (h) { // zend_hash_destroy(h); // pefree(h, 1); } } zend_module_entry r3_module_entry = { STANDARD_MODULE_HEADER, PHP_R3_EXTNAME, r3_functions, PHP_MINIT(r3), PHP_MSHUTDOWN(r3), PHP_RINIT(r3), NULL, NULL, PHP_R3_VERSION, STANDARD_MODULE_PROPERTIES }; PHP_INI_BEGIN() PHP_INI_ENTRY("r3.fstat", "0", PHP_INI_ALL, NULL) // STD_PHP_INI_ENTRY("r3.direction", "1", PHP_INI_ALL, OnUpdateBool, direction, zend_hello_globals, hello_globals) PHP_INI_END() #ifdef COMPILE_DL_R3 ZEND_GET_MODULE(r3) #endif static void php_r3_init_globals(zend_r3_globals *r3_globals) { // r3_globals->persistent_list = (HashTable*) // array_init(r3_globals->persistent_list); } PHP_MINIT_FUNCTION(r3) { ZEND_INIT_MODULE_GLOBALS(r3, php_r3_init_globals, NULL); REGISTER_INI_ENTRIES(); // r3_init_mux(TSRMLS_C); // r3_init_expandable_mux(TSRMLS_C); // r3_init_controller(TSRMLS_C); le_mux_hash_table = zend_register_list_destructors_ex(NULL, r3_mux_le_hash_dtor, "hash table", module_number); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(r3) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } PHP_RINIT_FUNCTION(r3) { return SUCCESS; } r3-1.3.4/php/r3/php_r3.h000066400000000000000000000054521262260041500145260ustar00rootroot00000000000000#ifndef PHP_R3_H #define PHP_R3_H 1 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/standard/php_string.h" #define PHP_R3_VERSION "1.3.1" #define PHP_R3_EXTNAME "r3" #ifdef ZTS #include "TSRM.h" #endif extern int r3_globals_id; extern int le_mux_hash_table; // global variable structure ZEND_BEGIN_MODULE_GLOBALS(r3) // zval *mux_array; HashTable * persistent_list; // zend_bool direction; ZEND_END_MODULE_GLOBALS(r3) #ifdef ZTS #define R3_G(v) TSRMG(r3_globals_id, zend_r3_globals *, v) #else #define R3_G(v) (r3_globals.v) #endif #define ZEND_HASH_FETCH(hash,key,ret) \ zend_hash_find(hash, key, sizeof(key), (void**)&ret) == SUCCESS #define PUSH_PARAM(arg) zend_vm_stack_push(arg TSRMLS_CC) #define POP_PARAM() (void)zend_vm_stack_pop(TSRMLS_C) #define PUSH_EO_PARAM() #define POP_EO_PARAM() #define CALL_METHOD_BASE(classname, name) zim_##classname##_##name #define CALL_METHOD_HELPER(classname, name, retval, thisptr, num, param) \ PUSH_PARAM(param); PUSH_PARAM((void*)num); \ PUSH_EO_PARAM(); \ CALL_METHOD_BASE(classname, name)(num, retval, NULL, thisptr, 0 TSRMLS_CC); \ POP_EO_PARAM(); \ POP_PARAM(); POP_PARAM(); #define CALL_METHOD(classname, name, retval, thisptr) \ CALL_METHOD_BASE(classname, name)(0, retval, NULL, thisptr, 0 TSRMLS_CC); #define CALL_METHOD1(classname, name, retval, thisptr, param1) \ CALL_METHOD_HELPER(classname, name, retval, thisptr, 1, param1); #define CALL_METHOD2(classname, name, retval, thisptr, param1, param2) \ PUSH_PARAM(param1); \ CALL_METHOD_HELPER(classname, name, retval, thisptr, 2, param2); \ POP_PARAM(); #define CALL_METHOD3(classname, name, retval, thisptr, param1, param2, param3) \ PUSH_PARAM(param1); PUSH_PARAM(param2); \ CALL_METHOD_HELPER(classname, name, retval, thisptr, 3, param3); \ POP_PARAM(); POP_PARAM(); PHP_MINIT_FUNCTION(r3); PHP_MSHUTDOWN_FUNCTION(r3); PHP_RINIT_FUNCTION(r3); /* zval * php_r3_match(zval *z_routes, char *path, int path_len TSRMLS_DC); zval * call_mux_method(zval * object , char * method_name , int method_name_len, int param_count, zval* arg1, zval* arg2, zval* arg3 TSRMLS_DC); zend_class_entry ** get_pattern_compiler_ce(TSRMLS_D); */ extern zend_class_entry *ce_r3_exception; extern zend_module_entry r3_module_entry; void r3_init_exception(TSRMLS_D); void r3_mux_le_hash_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC); // PHP_FUNCTION(r3_match); #define phpext_r3_ptr &r3_module_entry #endif r3-1.3.4/php/r3/r3_controller.c000066400000000000000000000342661262260041500161220ustar00rootroot00000000000000#include "string.h" #include "ctype.h" #include "php.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "Zend/zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "ext/standard/php_var.h" #include "ct_helper.h" #include "php_r3.h" #include "r3_mux.h" #include "r3_functions.h" #include "php_expandable_mux.h" #include "r3_controller.h" #include "annotation/scanner.h" #include "annotation/annot.h" zend_class_entry *ce_r3_controller; const zend_function_entry controller_methods[] = { PHP_ME(Controller, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Controller, expand, NULL, ZEND_ACC_PUBLIC) PHP_ME(Controller, getActionMethods, NULL, ZEND_ACC_PUBLIC) PHP_ME(Controller, getActionRoutes, NULL, ZEND_ACC_PUBLIC) PHP_ME(Controller, before, NULL, ZEND_ACC_PUBLIC) PHP_ME(Controller, after, NULL, ZEND_ACC_PUBLIC) PHP_ME(Controller, toJson, NULL, ZEND_ACC_PUBLIC) // PHP_ME(Controller, __destruct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_FE_END }; zend_bool phannot_fetch_argument_value(zval **arg, zval** value TSRMLS_DC) { zval **expr; if (zend_hash_find(Z_ARRVAL_PP(arg), "expr", sizeof("expr"), (void**)&expr) == FAILURE ) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(expr), "value", sizeof("value"), (void**) value); } zend_bool phannot_fetch_argument_type(zval **arg, zval **type TSRMLS_DC) { zval **expr; if (zend_hash_find(Z_ARRVAL_PP(arg), "expr", sizeof("expr"), (void**)&expr) == FAILURE ) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(expr), "type", sizeof("type"), (void**)type); } int strpos(const char *haystack, char *needle) { char *p = strstr(haystack, needle); if (p) return p - haystack; return -1; } void r3_init_controller(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "R3\\Controller", controller_methods); ce_r3_controller = zend_register_internal_class(&ce TSRMLS_CC); zend_class_implements(ce_r3_controller TSRMLS_CC, 1, ce_r3_expandable_mux); } PHP_METHOD(Controller, __construct) { } /** * Returns [ method, annotations ] */ PHP_METHOD(Controller, getActionMethods) { // get function table hash HashTable *function_table = &Z_OBJCE_P(this_ptr)->function_table; HashPosition pos; array_init(return_value); zend_function *mptr; zend_hash_internal_pointer_reset_ex(function_table, &pos); const char *fn; size_t fn_len; int p; while (zend_hash_get_current_data_ex(function_table, (void **) &mptr, &pos) == SUCCESS) { fn = mptr->common.function_name; fn_len = strlen(mptr->common.function_name); p = strpos(fn, "Action"); if ( p == -1 || (size_t)p != (fn_len - strlen("Action")) ) { zend_hash_move_forward_ex(function_table, &pos); continue; } // append the structure [method name, annotations] zval *new_item; zval *z_method_annotations; zval *z_indexed_annotations; zval *z_comment; zval *z_file; zval *z_line_start; MAKE_STD_ZVAL(new_item); array_init(new_item); add_next_index_stringl(new_item, fn, fn_len, 1); /* * @var * * if there no annotation, we pass an empty array. * * The method annotation structure * */ MAKE_STD_ZVAL(z_method_annotations); array_init(z_method_annotations); // simplified annotation information is saved to this variable. MAKE_STD_ZVAL(z_indexed_annotations); array_init(z_indexed_annotations); if ( mptr->type == ZEND_USER_FUNCTION && mptr->op_array.doc_comment ) { ALLOC_ZVAL(z_comment); ZVAL_STRING(z_comment, mptr->op_array.doc_comment, 1); ALLOC_ZVAL(z_file); ZVAL_STRING(z_file, mptr->op_array.filename, 1); ALLOC_ZVAL(z_line_start); ZVAL_LONG(z_line_start, mptr->op_array.line_start); /* zval *z_line_end; ALLOC_ZVAL(z_line_end); ZVAL_LONG(z_line_start, mptr->op_array.line_end); */ zval **z_ann = NULL, **z_ann_name = NULL, **z_ann_arguments = NULL, **z_ann_argument = NULL, **z_ann_argument_value = NULL; // TODO: make phannot_parse_annotations reads comment variable in char* type, so we don't need to create extra zval(s) if (phannot_parse_annotations(z_method_annotations, z_comment, z_file, z_line_start TSRMLS_CC) == SUCCESS) { /* * z_method_annotations is an indexed array, which contains a structure like this: * * [ * { name => ... , type => ... , arguments => ... , file => , line => }, * { name => ... , type => ... , arguments => ... , file => , line => }, * { name => ... , type => ... , arguments => ... , file => , line => }, * ] * * the actuall structure: * * array(2) { * [0]=> * array(5) { * ["type"]=> * int(300) * ["name"]=> * string(5) "Route" * ["arguments"]=> * array(1) { * [0]=> * array(1) { * ["expr"]=> * array(2) { * ["type"]=> * int(303) * ["value"]=> * string(7) "/delete" * } * } * } * ["file"]=> string(48) "...." * ["line"]=> int(54) * }, * ..... * } */ HashPosition annp; for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(z_method_annotations), &annp); zend_hash_get_current_data_ex(Z_ARRVAL_P(z_method_annotations), (void**)&z_ann, &annp) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(z_method_annotations), &annp) ) { if (zend_hash_find(Z_ARRVAL_P(*z_ann), "name", sizeof("name"), (void**)&z_ann_name) == FAILURE ) { continue; } if (zend_hash_find(Z_ARRVAL_P(*z_ann), "arguments", sizeof("arguments"), (void**)&z_ann_arguments) == FAILURE ) { continue; } // We currenly only support "@Method()" and "@Route" if ( strncmp( Z_STRVAL_PP(z_ann_name), "Method", sizeof("Method") - 1 ) != 0 && strncmp( Z_STRVAL_PP(z_ann_name), "Route", sizeof("Route") - 1 ) != 0 ) { continue; } // read the first argument (we only support for one argument currently, and should support complex syntax later.) if ( zend_hash_index_find(Z_ARRVAL_PP(z_ann_arguments), 0, (void**) &z_ann_argument) == SUCCESS ) { if ( phannot_fetch_argument_value(z_ann_argument, (zval**) &z_ann_argument_value TSRMLS_CC) == SUCCESS ) { Z_ADDREF_PP(z_ann_argument_value); add_assoc_zval(z_indexed_annotations, Z_STRVAL_PP(z_ann_name), *z_ann_argument_value); } } } } } Z_ADDREF_P(z_indexed_annotations); add_next_index_zval(new_item, z_indexed_annotations); add_next_index_zval(return_value, new_item); zend_hash_move_forward_ex(function_table, &pos); } return; } char * translate_method_name_to_path(const char *method_name) { char *p = strstr(method_name, "Action"); if ( p == NULL ) { return NULL; } if ( strncmp(method_name, "indexAction", strlen("indexAction") ) == 0 ) { // returns empty string as its path return strndup("",sizeof("")-1); } char * new_path; // XXX: this might overflow.. new_path = ecalloc( 128 , sizeof(char) ); int len = p - method_name; char * c = (char*) method_name; int x = 0; new_path[x++] = '/'; int new_path_len = 1; while( len-- ) { if ( isupper(*c) ) { new_path[x++] = '/'; new_path[x++] = tolower(*c); new_path_len += 2; } else { new_path[x++] = *c; new_path_len ++; } c++; } return new_path; } // return path => path pairs // structure: [[ path, method name ], [ ... ], [ ... ], ... ] PHP_METHOD(Controller, getActionRoutes) { zend_function *fe; if ( zend_hash_quick_find( &ce_r3_controller->function_table, "getactionmethods", sizeof("getactionmethods"), zend_inline_hash_func(ZEND_STRS("getactionmethods")), (void **) &fe) == FAILURE ) { php_error(E_ERROR, "getActionMethods method not found"); } // call export method zval *rv = NULL; zend_call_method_with_0_params( &this_ptr, ce_r3_controller, &fe, "getactionmethods", &rv ); HashTable *func_list = Z_ARRVAL_P(rv); HashPosition pointer; zval **z_method_name; zval **z_annotations; zval **z_doc_method; zval **z_doc_uri; zval **item; array_init(return_value); for(zend_hash_internal_pointer_reset_ex(func_list, &pointer); zend_hash_get_current_data_ex(func_list, (void**) &item, &pointer) == SUCCESS; zend_hash_move_forward_ex(func_list, &pointer)) { zend_hash_index_find(Z_ARRVAL_PP(item), 0, (void**)&z_method_name); const char *method_name = Z_STRVAL_PP(z_method_name); int method_name_len = Z_STRLEN_PP(z_method_name); char *path = NULL; zval *z_route_options; MAKE_STD_ZVAL(z_route_options); array_init(z_route_options); if ( zend_hash_index_find(Z_ARRVAL_PP(item), 1, (void**)&z_annotations) == SUCCESS ) { if (zend_hash_find(Z_ARRVAL_PP(z_annotations), "Route", sizeof("Route"), (void**)&z_doc_uri) == SUCCESS) { path = estrndup(Z_STRVAL_PP(z_doc_uri), Z_STRLEN_PP(z_doc_uri)); } if (zend_hash_find(Z_ARRVAL_PP(z_annotations), "Method", sizeof("Method"), (void**)&z_doc_method) == SUCCESS) { Z_ADDREF_PP(z_doc_method); add_assoc_zval(z_route_options, "method", *z_doc_method); } } if (!path) { path = translate_method_name_to_path(method_name); } // return structure [ path, method name, http method ] zval * new_item; MAKE_STD_ZVAL(new_item); array_init_size(new_item, 3); add_next_index_string(new_item, path, 1); add_next_index_stringl(new_item, method_name, method_name_len, 0); Z_ADDREF_P(z_route_options); add_next_index_zval(new_item, z_route_options); // append to the result array add_next_index_zval(return_value, new_item); } return; } PHP_METHOD(Controller, expand) { zval *new_mux; MAKE_STD_ZVAL(new_mux); object_init_ex(new_mux, ce_r3_mux); CALL_METHOD(Mux, __construct, new_mux, new_mux); Z_ADDREF_P(new_mux); // add reference zval *path_array = NULL; zend_call_method_with_0_params( &this_ptr, ce_r3_controller, NULL, "getactionroutes", &path_array ); if ( Z_TYPE_P(path_array) != IS_ARRAY ) { php_error(E_ERROR, "getActionRoutes does not return an array."); RETURN_FALSE; } const char *class_name = NULL; zend_uint class_name_len; int dup = zend_get_object_classname(this_ptr, &class_name, &class_name_len TSRMLS_CC); HashPosition pointer; zval **path_entry = NULL; for ( zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(path_array), &pointer); zend_hash_get_current_data_ex(Z_ARRVAL_P(path_array), (void**) &path_entry, &pointer) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(path_array), &pointer) ) { zval **z_path; zval **z_method; zval **z_options = NULL; if ( zend_hash_index_find(Z_ARRVAL_PP(path_entry), 0, (void**) &z_path) == FAILURE ) { continue; } if ( zend_hash_index_find(Z_ARRVAL_PP(path_entry), 1, (void**) &z_method) == FAILURE ) { continue; } zend_hash_index_find(Z_ARRVAL_PP(path_entry), 2, (void**) &z_options); zval *z_callback; MAKE_STD_ZVAL(z_callback); array_init_size(z_callback, 2); Z_ADDREF_P(z_callback); Z_ADDREF_PP(z_method); add_next_index_stringl(z_callback, class_name, class_name_len, 1); add_next_index_zval(z_callback, *z_method); zval *rv = NULL; zend_call_method_with_3_params(&new_mux, ce_r3_mux, NULL, "add", strlen("add"), &rv, 3, *z_path, z_callback, *z_options TSRMLS_CC); } zval *rv = NULL; zend_call_method_with_0_params(&new_mux, ce_r3_mux, NULL, "sort", &rv ); *return_value = *new_mux; zval_copy_ctor(return_value); } PHP_METHOD(Controller, before) { } PHP_METHOD(Controller, after) { } PHP_METHOD(Controller, toJson) { zval *z_data; long options = 0; long depth = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|ll", &z_data, &options, &depth) == FAILURE) { RETURN_FALSE; } zval *z_options; zval *z_depth; MAKE_STD_ZVAL(z_options); MAKE_STD_ZVAL(z_depth); ZVAL_LONG(z_depth, 0); ZVAL_LONG(z_options, 0); zval *rv = NULL; // zend_call_method_with_3_params(NULL, NULL, NULL, "json_encode", sizeof("json_encode"), &rv, 3, z_data, z_options, z_depth TSRMLS_CC ); zend_call_method_with_2_params(NULL, NULL, NULL, "json_encode", &rv, z_data, z_options); *return_value = *rv; zval_copy_ctor(return_value); } r3-1.3.4/php/r3/r3_controller.h000066400000000000000000000017261262260041500161220ustar00rootroot00000000000000#ifndef PHP_CONTROLLER_H #define PHP_CONTROLLER_H 1 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_functions.h" extern zend_class_entry *ce_r3_controller; void r3_init_controller(TSRMLS_D); char * translate_method_name_to_path(const char *method_name); zend_bool phannot_fetch_argument_value(zval **arg, zval** value TSRMLS_DC); zend_bool phannot_fetch_argument_type(zval **arg, zval **type TSRMLS_DC); int strpos(const char *haystack, char *needle); PHP_METHOD(Controller, __construct); PHP_METHOD(Controller, expand); PHP_METHOD(Controller, getActionMethods); PHP_METHOD(Controller, getActionRoutes); PHP_METHOD(Controller, before); PHP_METHOD(Controller, after); PHP_METHOD(Controller, toJson); #endif r3-1.3.4/php/r3/r3_functions.c000066400000000000000000000655661262260041500157560ustar00rootroot00000000000000/* vim:fdm=marker:et:sw=4:ts=4:sts=4: */ #include "php.h" #include "string.h" #include "pcre.h" #include "main/php_main.h" #include "Zend/zend_compile.h" #include "Zend/zend_alloc.h" #include "Zend/zend_operators.h" #include "Zend/zend_API.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_functions.h" // #include "r3_persistent.h" // #include "php_expandable_mux.h" #include "hash.h" /** * new_dst = ht_copy_fun_t(NULL, src); * * Can be our zval copy function */ /* {{{ my_copy_zval_ptr */ zval** my_copy_zval_ptr(zval** dst, const zval** src, int persistent TSRMLS_DC) { zval* dst_new; assert(src != NULL); if (!dst) { dst = (zval**) pemalloc(sizeof(zval*), persistent); } CHECK(dst[0] = (zval*) pemalloc(sizeof(zval), persistent)); CHECK(dst_new = my_copy_zval(*dst, *src, persistent TSRMLS_CC)); if (dst_new != *dst) { *dst = dst_new; } return dst; } /* }}} */ /* {{{ my_copy_zval */ zval* my_copy_zval(zval* dst, const zval* src, int persistent TSRMLS_DC) { zval **tmp; assert(dst != NULL); assert(src != NULL); memcpy(dst, src, sizeof(zval)); /* deep copies are refcount(1), but moved up for recursive * arrays, which end up being add_ref'd during its copy. */ Z_SET_REFCOUNT_P(dst, 1); Z_UNSET_ISREF_P(dst); switch (src->type & IS_CONSTANT_TYPE_MASK) { case IS_RESOURCE: php_error(E_ERROR, "Cannot copy resource"); break; case IS_BOOL: case IS_LONG: case IS_DOUBLE: case IS_NULL: break; case IS_CONSTANT: case IS_STRING: if (src->value.str.val) { dst->value.str.val = pestrndup(src->value.str.val, src->value.str.len, persistent); } break; case IS_ARRAY: case IS_CONSTANT_ARRAY: dst->value.ht = my_copy_hashtable(NULL, src->value.ht, (ht_copy_fun_t) my_copy_zval_ptr, (void*) &tmp, sizeof(zval *), persistent TSRMLS_CC); break; // XXX: we don't serialize object. case IS_OBJECT: php_error(E_ERROR, "Cannot copy Object."); break; #ifdef ZEND_ENGINE_2_4 case IS_CALLABLE: php_error(E_ERROR, "Cannot copy Callable."); // XXX: we don't serialize callbable object. break; #endif default: assert(0); } return dst; } /* }}} */ /* my_zval_copy_ctor_func {{{*/ void my_zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_RESOURCE: { TSRMLS_FETCH(); zend_list_addref(zvalue->value.lval); } break; case IS_BOOL: case IS_LONG: case IS_NULL: break; case IS_CONSTANT: case IS_STRING: CHECK_ZVAL_STRING_REL(zvalue); if (!IS_INTERNED(zvalue->value.str.val)) { zvalue->value.str.val = (char *) estrndup_rel(zvalue->value.str.val, zvalue->value.str.len); } break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { zval *tmp; HashTable *original_ht = zvalue->value.ht; HashTable *tmp_ht = NULL; TSRMLS_FETCH(); if (zvalue->value.ht == &EG(symbol_table)) { return; /* do nothing */ } ALLOC_HASHTABLE_REL(tmp_ht); zend_hash_init(tmp_ht, zend_hash_num_elements(original_ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(tmp_ht, original_ht, (copy_ctor_func_t) my_zval_copy_ctor_func, (void *) &tmp, sizeof(zval *)); zvalue->value.ht = tmp_ht; } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC); } break; } Z_ADDREF_P(zvalue); } /*}}}*/ // my_zval_copy_ctor_persistent_func {{{ void my_zval_copy_ctor_persistent_func(zval *zvalue ZEND_FILE_LINE_DC) { /* zval *orig_zvalue; orig_zvalue = zvalue; zvalue = pemalloc(sizeof(zval), 1); *zvalue = *zvalue; zval_copy_ctor(zvalue); Z_SET_REFCOUNT_P(zvalue, 1); Z_UNSET_ISREF_P(zvalue); // MAKE_COPY_ZVAL(&new_zvalue, zvalue); SEPARATE_ZVAL(&zvalue); */ switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_RESOURCE: case IS_BOOL: case IS_LONG: case IS_DOUBLE: case IS_NULL: break; case IS_CONSTANT: case IS_STRING: CHECK_ZVAL_STRING_REL(zvalue); zvalue->value.str.val = (char *) pestrndup(zvalue->value.str.val, zvalue->value.str.len, 1); break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { zval *tmp; HashTable *original_ht = zvalue->value.ht; HashTable *tmp_ht = NULL; TSRMLS_FETCH(); if (zvalue->value.ht == &EG(symbol_table)) { return; /* do nothing */ } tmp_ht = pemalloc(sizeof(HashTable), 1); zend_hash_init(tmp_ht, zend_hash_num_elements(original_ht), NULL, ZVAL_PTR_DTOR, 1); zend_hash_copy(tmp_ht, original_ht, (copy_ctor_func_t) my_zval_copy_ctor_persistent_func, (void *) &tmp, sizeof(zval *)); zvalue->value.ht = tmp_ht; } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC); } break; } Z_SET_REFCOUNT_P(zvalue, 1); } // }}} int _r3_store_mux(char *name, zval * mux TSRMLS_DC) { zend_rsrc_list_entry new_le, *le; // variables for copying mux object properties char *id_key, *expand_key; int status, id_key_len, expand_key_len; id_key_len = spprintf(&id_key, 0, "mux_id_%s", name); expand_key_len = spprintf(&expand_key, 0, "mux_expand_%s", name); // Z_ADDREF_P(mux); // make the hash table persistent zval *prop, *tmp; HashTable *routes, *static_routes; prop = zend_read_property(ce_r3_mux, mux, "routes", sizeof("routes")-1, 1 TSRMLS_CC); routes = zend_hash_clone_persistent( Z_ARRVAL_P(prop) TSRMLS_CC); if ( ! routes ) { php_error(E_ERROR, "Can not clone HashTable"); return FAILURE; } r3_persistent_store( name, "routes", le_mux_hash_table, (void*) routes TSRMLS_CC); return SUCCESS; prop = zend_read_property(ce_r3_mux, mux, "staticRoutes", sizeof("staticRoutes")-1, 1 TSRMLS_CC); static_routes = zend_hash_clone_persistent( Z_ARRVAL_P(prop) TSRMLS_CC); if ( ! static_routes ) { php_error(E_ERROR, "Can not clone HashTable"); return FAILURE; } r3_persistent_store(name, "static_routes", le_mux_hash_table, (void *) static_routes TSRMLS_CC) ; // copy ID /* prop = zend_read_property(ce_r3_mux, mux, "id", sizeof("id")-1, 1 TSRMLS_CC); tmp = pemalloc(sizeof(zval), 1); INIT_ZVAL(tmp); Z_TYPE_P(tmp) = IS_LONG; Z_LVAL_P(tmp) = Z_LVAL_P(prop); Z_SET_REFCOUNT_P(tmp, 1); r3_persistent_store( name, "id", (void*) tmp TSRMLS_CC); */ // We cannot copy un-expandable mux object because we don't support recursively copy for Mux object. prop = zend_read_property(ce_r3_mux, mux, "expand", sizeof("expand")-1, 1 TSRMLS_CC); if ( ! Z_BVAL_P(prop) ) { php_error(E_ERROR, "We cannot copy un-expandable mux object because we don't support recursively copy for Mux object."); } efree(id_key); efree(expand_key); return SUCCESS; } /** * Fetch mux related properties (hash tables) from EG(persistent_list) hash table and * rebless a new Mux object with these properties. * * @return Mux object */ zval * _r3_fetch_mux(char *name TSRMLS_DC) { zval *z_id, *z_routes, *z_static_routes, *z_submux, *z_routes_by_id, *tmp; HashTable *routes_hash; HashTable *static_routes_hash; // fetch related hash to this mux object. routes_hash = (HashTable*) r3_persistent_fetch(name, "routes" TSRMLS_CC); if ( ! routes_hash ) { return NULL; } static_routes_hash = (HashTable*) r3_persistent_fetch(name, "static_routes" TSRMLS_CC); if ( ! static_routes_hash ) { return NULL; } z_id = (zval*) r3_persistent_fetch(name, "id" TSRMLS_CC); MAKE_STD_ZVAL(z_routes); MAKE_STD_ZVAL(z_static_routes); MAKE_STD_ZVAL(z_routes_by_id); MAKE_STD_ZVAL(z_submux); Z_TYPE_P(z_routes) = IS_ARRAY; Z_TYPE_P(z_static_routes) = IS_ARRAY; array_init(z_routes_by_id); array_init(z_submux); // we need to clone hash table deeply because when Mux object returned to userspace, it will be freed. Z_ARRVAL_P(z_routes) = zend_hash_clone(routes_hash TSRMLS_CC); Z_ARRVAL_P(z_static_routes) = zend_hash_clone(static_routes_hash TSRMLS_CC); // create new object and return to userspace. zval *new_mux = NULL; ALLOC_INIT_ZVAL(new_mux); object_init_ex(new_mux, ce_r3_mux); // We don't need __construct because we assign the property by ourself. // CALL_METHOD(Mux, __construct, new_mux, new_mux); Z_SET_REFCOUNT_P(new_mux, 1); if ( z_id ) { Z_ADDREF_P(z_id); zend_update_property_long(ce_r3_mux, new_mux, "id" , sizeof("id")-1, Z_LVAL_P(z_id) TSRMLS_CC); } // persistent mux should always be expanded. (no recursive structure) zend_update_property_bool(ce_r3_mux , new_mux , "expand" , sizeof("expand")-1 , 1 TSRMLS_CC); zend_update_property(ce_r3_mux , new_mux , "routes" , sizeof("routes")-1 , z_routes TSRMLS_CC); zend_update_property(ce_r3_mux , new_mux , "staticRoutes" , sizeof("staticRoutes")-1 , z_static_routes TSRMLS_CC); zend_update_property(ce_r3_mux, new_mux, "routesById", sizeof("routesById")-1, z_routes_by_id TSRMLS_CC); zend_update_property(ce_r3_mux, new_mux, "submux", sizeof("submux")-1, z_submux TSRMLS_CC); return new_mux; } int mux_loader(char *path, zval *result TSRMLS_DC) { zend_file_handle file_handle; zend_op_array *op_array; char realpath[MAXPATHLEN]; if (!VCWD_REALPATH(path, realpath)) { return FAILURE; } file_handle.filename = path; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); if (op_array && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = path; } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (op_array) { zval *local_retval_ptr = NULL; R3_STORE_EG_ENVIRON(); EG(return_value_ptr_ptr) = &local_retval_ptr; EG(active_op_array) = op_array; #if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 2)) || (PHP_MAJOR_VERSION > 5) if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } #endif zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); if (!EG(exception)) { if (local_retval_ptr) { if ( result ) { COPY_PZVAL_TO_ZVAL(*result, local_retval_ptr); } else { zval_ptr_dtor(EG(return_value_ptr_ptr)); } } } R3_RESTORE_EG_ENVIRON(); return SUCCESS; } return FAILURE; } /* * r3_compile(array $routes, string $path); */ PHP_FUNCTION(r3_match) { zval *z_routes; char *path; int path_len; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "as", &z_routes, &path, &path_len ) == FAILURE) { RETURN_FALSE; } zval *z_route; z_route = php_r3_match(z_routes, path, path_len TSRMLS_CC); if ( z_route != NULL ) { *return_value = *z_route; zval_copy_ctor(return_value); return; } RETURN_NULL(); } PHP_FUNCTION(r3_store_mux) { zval *mux; char *name; int name_len; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name, &name_len, &mux ) == FAILURE) { RETURN_FALSE; } if ( _r3_store_mux(name, mux TSRMLS_CC) == SUCCESS ) { RETURN_TRUE; } RETURN_FALSE; } PHP_FUNCTION(r3_persistent_dispatch) { char *ns, *filename, *path; int ns_len, filename_len, path_len; zval *mux = NULL; zval *route = NULL; zval *z_path = NULL; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss", &ns, &ns_len, &filename, &filename_len, &path, &path_len) == FAILURE) { RETURN_FALSE; } mux = _r3_fetch_mux(ns TSRMLS_CC); if ( mux == NULL ) { ALLOC_INIT_ZVAL(mux); if ( mux_loader(filename, mux TSRMLS_CC) == FAILURE ) { php_error(E_ERROR, "Can not load Mux object from %s", filename); } // TODO: compile mux and sort routes if ( _r3_store_mux(ns, mux TSRMLS_CC) == FAILURE ) { php_error(E_ERROR, "Can not store Mux object from %s", filename); } } ALLOC_INIT_ZVAL(z_path); ZVAL_STRINGL(z_path, path ,path_len, 1); // no copy // XXX: pass return_value to the method call, so we don't need to copy route = call_mux_method(mux, "dispatch" , sizeof("dispatch"), 1 , z_path, NULL, NULL TSRMLS_CC); zval_ptr_dtor(&z_path); if ( route ) { *return_value = *route; zval_copy_ctor(return_value); return; } // route not found RETURN_FALSE; } PHP_FUNCTION(r3_delete_mux) { char *name, *persistent_key; int name_len, persistent_key_len; zend_rsrc_list_entry *le; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { RETURN_FALSE; } persistent_key_len = spprintf(&persistent_key, 0, "mux_%s", name); if ( zend_hash_find(&EG(persistent_list), persistent_key, persistent_key_len + 1, (void**) &le) == SUCCESS ) { zval_ptr_dtor((zval**) &le->ptr); zend_hash_del(&EG(persistent_list), persistent_key, persistent_key_len + 1); efree(persistent_key); RETURN_TRUE; } efree(persistent_key); RETURN_FALSE; } PHP_FUNCTION(r3_fetch_mux) { char *name; int name_len; zval * mux; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { RETURN_FALSE; } mux = _r3_fetch_mux(name TSRMLS_CC); if ( mux ) { *return_value = *mux; zval_copy_ctor(return_value); return; } RETURN_FALSE; } PHP_FUNCTION(r3_sort_routes) { zval *a; zval *b; /* parse parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &a, &b ) == FAILURE) { RETURN_FALSE; } zval **a_pcre; zval **a_pattern; zval **a_compiled_pattern; zval **a_options; zval **b_pcre; zval **b_pattern; zval **b_compiled_pattern; zval **b_options; zend_hash_index_find( Z_ARRVAL_P(a) , 0, (void**)&a_pcre); zend_hash_index_find( Z_ARRVAL_P(b) , 0, (void**)&b_pcre); zend_hash_index_find( Z_ARRVAL_P(a) , 1, (void**)&a_pattern); zend_hash_index_find( Z_ARRVAL_P(b) , 1, (void**)&b_pattern); zend_hash_index_find( Z_ARRVAL_P(a) , 3, (void**)&a_options); zend_hash_index_find( Z_ARRVAL_P(b) , 3, (void**)&b_options); // return strlen($a[3]['compiled']) > strlen($b[3]['compiled']); if ( Z_BVAL_PP(a_pcre) && Z_BVAL_PP(b_pcre) ) { zend_hash_quick_find( Z_ARRVAL_PP(a_options) , "compiled", strlen("compiled"), zend_inline_hash_func(ZEND_STRS("compiled")), (void**)&a_compiled_pattern); zend_hash_quick_find( Z_ARRVAL_PP(b_options) , "compiled", strlen("compiled"), zend_inline_hash_func(ZEND_STRS("compiled")), (void**)&b_compiled_pattern); int a_len = Z_STRLEN_PP(a_compiled_pattern); int b_len = Z_STRLEN_PP(b_compiled_pattern); if ( a_len == b_len ) { RETURN_LONG(0); } else if ( a_len > b_len ) { RETURN_LONG(-1); } else { RETURN_LONG(1); } } else if ( Z_BVAL_PP(a_pcre) ) { RETURN_LONG(-1); } else if ( Z_BVAL_PP(b_pcre) ) { RETURN_LONG(1); } int a_len = Z_STRLEN_PP(a_pattern); int b_len = Z_STRLEN_PP(b_pattern); if ( a_len == b_len ) { RETURN_LONG(0); } else if ( a_len > b_len ) { RETURN_LONG(-1); } else { RETURN_LONG(1); } } // // int zend_hash_has_key( ) // inline zval * php_r3_match(zval *z_routes, char *path, int path_len TSRMLS_DC) { int current_request_method = 0; int current_https = 0; zval * current_http_host = NULL; HashTable *server_vars_hash = fetch_server_vars_hash(TSRMLS_C); if ( server_vars_hash ) { current_request_method = get_current_request_method_const(server_vars_hash TSRMLS_CC); current_https = get_current_https(server_vars_hash TSRMLS_CC); current_http_host = get_current_http_host(server_vars_hash TSRMLS_CC); } HashPosition z_routes_pointer; // for iterating routes zval **z_route_pp; zval **z_is_pcre_pp; // route[0] zval **z_pattern_pp; // route[1] zval **z_callback_pp; // callback @ route[2] zval **z_route_options_pp; // route[3] pcre_cache_entry *pce; /* Compiled regular expression */ zval *pcre_ret = NULL; zval *pcre_subpats = NULL; /* Array for subpatterns */ HashTable * z_routes_hash = Z_ARRVAL_P(z_routes); ALLOC_INIT_ZVAL(pcre_ret); // this is required. ALLOC_INIT_ZVAL(pcre_subpats); // also required for(zend_hash_internal_pointer_reset_ex(z_routes_hash, &z_routes_pointer); zend_hash_get_current_data_ex(z_routes_hash, (void**) &z_route_pp, &z_routes_pointer) == SUCCESS; zend_hash_move_forward_ex(z_routes_hash, &z_routes_pointer)) { zend_hash_index_find( Z_ARRVAL_PP(z_route_pp), 0, (void**) &z_is_pcre_pp); zend_hash_index_find( Z_ARRVAL_PP(z_route_pp), 1, (void**) &z_pattern_pp); if ( Z_BVAL_PP(z_is_pcre_pp) ) { /* Compile regex or get it from cache. */ if ((pce = pcre_get_compiled_regex_cache(Z_STRVAL_PP(z_pattern_pp), Z_STRLEN_PP(z_pattern_pp) TSRMLS_CC)) == NULL) { zend_throw_exception(zend_exception_get_default(TSRMLS_C), "PCRE pattern compile failed.", 0 TSRMLS_CC); return NULL; } php_pcre_match_impl(pce, path, path_len, pcre_ret, pcre_subpats, 0, 0, 0, 0 TSRMLS_CC); // not matched ? if ( ! Z_BVAL_P(pcre_ret) ) { continue; } // tell garbage collector to collect it, we need to use pcre_subpats later. // check conditions only when route option is provided if ( zend_hash_index_find( Z_ARRVAL_PP(z_route_pp), 3, (void**) &z_route_options_pp) == SUCCESS ) { if ( zend_hash_num_elements(Z_ARRVAL_PP(z_route_options_pp)) ) { if ( 0 == validate_request_method( z_route_options_pp, current_request_method TSRMLS_CC) ) { continue; } if ( 0 == validate_https( z_route_options_pp, current_https TSRMLS_CC) ) { continue; } if ( 0 == validate_domain( z_route_options_pp, current_http_host TSRMLS_CC) ) { continue; } } } if ( Z_TYPE_P(pcre_subpats) == IS_NULL ) { array_init(pcre_subpats); } Z_ADDREF_P(pcre_subpats); add_assoc_zval(*z_route_options_pp , "vars" , pcre_subpats); return *z_route_pp; // Apply "default" value to "vars" /* foreach( $route['variables'] as $k ) { if( isset($regs[$k]) ) { $route['vars'][ $k ] = $regs[$k]; } else { $route['vars'][ $k ] = $route['default'][ $k ]; } } */ /* zval **z_route_default; zval **z_route_subpat_val; if ( zend_hash_find(z_route_options_pp, "default", sizeof("default"), (void**) &z_route_default ) == FAILURE ) { HashPosition default_pointer; HashTable *default_hash; variables_hash = Z_ARRVAL_PP(z_variables); // foreach variables as var, check if url contains variable or we should apply default value for(zend_hash_internal_pointer_reset_ex(variables_hash, &variables_pointer); zend_hash_get_current_data_ex(variables_hash, (void**) &z_var_name, &variables_pointer) == SUCCESS; zend_hash_move_forward_ex(variables_hash, &variables_pointer)) { } // if ( zend_hash_find(z_route_default, "default", sizeof("default"), (void**) &z_route_default ) == FAILURE ) { } */ } else { // normal string comparison // pattern-prefix match zend_hash_index_find( Z_ARRVAL_PP(z_route_pp), 2, (void**) &z_callback_pp); if ( ( Z_TYPE_PP(z_callback_pp) == IS_LONG && strncmp(Z_STRVAL_PP( z_pattern_pp ), path, Z_STRLEN_PP(z_pattern_pp) ) == 0 ) || strcmp(Z_STRVAL_PP( z_pattern_pp ), path ) == 0 ) { // check conditions if ( zend_hash_index_find( Z_ARRVAL_PP(z_route_pp), 3, (void**) &z_route_options_pp) == SUCCESS ) { if ( zend_hash_num_elements(Z_ARRVAL_PP(z_route_options_pp)) ) { if ( 0 == validate_request_method( z_route_options_pp, current_request_method TSRMLS_CC) ) { continue; } if ( 0 == validate_https( z_route_options_pp, current_https TSRMLS_CC) ) { continue; } if ( 0 == validate_domain( z_route_options_pp, current_http_host TSRMLS_CC) ) { continue; } } } // we didn't use the pcre variables zval_ptr_dtor(&pcre_subpats); zval_ptr_dtor(&pcre_ret); return *z_route_pp; } } } zval_ptr_dtor(&pcre_subpats); zval_ptr_dtor(&pcre_ret); return NULL; } inline HashTable * fetch_server_vars_hash(TSRMLS_D) { zval **z_server_hash = NULL; if ( zend_hash_quick_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), zend_inline_hash_func(ZEND_STRS("_SERVER")), (void **) &z_server_hash) == SUCCESS ) { return Z_ARRVAL_PP(z_server_hash); } return NULL; } inline zval * fetch_server_var(HashTable * server_hash, char *key , int key_len TSRMLS_DC) { zval **rv; if ( zend_hash_find(server_hash, key, key_len, (void **) &rv) == SUCCESS ) { return *rv; } return NULL; } inline zval * get_current_remote_addr(HashTable * server_vars_hash TSRMLS_DC) { // REMOTE_ADDR return fetch_server_var(server_vars_hash, "REMOTE_ADDR", sizeof("REMOTE_ADDR") TSRMLS_CC); } inline zval * get_current_http_host(HashTable * server_vars_hash TSRMLS_DC) { return fetch_server_var(server_vars_hash, "HTTP_HOST", sizeof("HTTP_HOST") TSRMLS_CC); } inline zval * get_current_request_uri(HashTable * server_vars_hash TSRMLS_DC) { return fetch_server_var(server_vars_hash, "REQUEST_URI", sizeof("REQUEST_URI") TSRMLS_CC); } inline int get_current_https(HashTable * server_vars_hash TSRMLS_DC) { zval *https = fetch_server_var(server_vars_hash, "HTTPS", sizeof("HTTPS") TSRMLS_CC); if ( https && Z_BVAL_P(https) ) { return 1; } return 0; } inline zval * get_current_request_method(HashTable * server_vars_hash TSRMLS_DC) { return fetch_server_var(server_vars_hash, "REQUEST_METHOD", sizeof("REQUEST_METHOD") TSRMLS_CC); } /* get request method type in constant value. {{{ */ inline int get_current_request_method_const(HashTable * server_vars_hash TSRMLS_DC) { char *c_request_method; zval *z_request_method = get_current_request_method(server_vars_hash TSRMLS_CC); if ( z_request_method ) { c_request_method = Z_STRVAL_P(z_request_method); if ( strncmp("GET", c_request_method , sizeof("GET") ) == 0 ) { return REQ_METHOD_GET; } else if ( strncmp("POST", c_request_method , sizeof("POST") ) == 0 ) { return REQ_METHOD_POST; } else if ( strncmp("PUT" , c_request_method , sizeof("PUT") ) == 0 ) { return REQ_METHOD_PUT; } else if ( strncmp("DELETE", c_request_method, sizeof("DELETE") ) == 0 ) { return REQ_METHOD_DELETE; } else if ( strncmp("HEAD", c_request_method, sizeof("HEAD") ) == 0 ) { return REQ_METHOD_HEAD; } else if ( strncmp("PATCH", c_request_method, sizeof("PATCH") ) == 0 ) { return REQ_METHOD_HEAD; } else if ( strncmp("OPTIONS", c_request_method, sizeof("OPTIONS") ) == 0 ) { return REQ_METHOD_OPTIONS; } } return 0; } // }}} inline int validate_https(zval **z_route_options_pp, int https TSRMLS_DC) { zval **z_route_secure = NULL; if ( zend_hash_quick_find( Z_ARRVAL_PP(z_route_options_pp) , "secure", sizeof("secure"), zend_inline_hash_func(ZEND_STRS("secure")), (void**) &z_route_secure ) == SUCCESS ) { // check HTTPS flag if ( https && ! Z_BVAL_PP(z_route_secure) ) { return 0; } } return 1; } inline int validate_domain(zval **z_route_options_pp, zval * http_host TSRMLS_DC) { zval **z_route_domain = NULL; if ( zend_hash_quick_find( Z_ARRVAL_PP(z_route_options_pp) , "domain", sizeof("domain"), zend_inline_hash_func(ZEND_STRS("domain")), (void**) &z_route_domain ) == SUCCESS ) { // check HTTP_HOST from $_SERVER if ( strncmp(Z_STRVAL_PP(z_route_domain), Z_STRVAL_P(http_host), Z_STRLEN_PP(z_route_domain) ) != 0 ) { return 0; } } return 1; } inline int validate_request_method(zval **z_route_options_pp, int current_request_method TSRMLS_DC) { zval **z_route_method = NULL; if ( zend_hash_quick_find( Z_ARRVAL_PP(z_route_options_pp) , "method", sizeof("method"), zend_inline_hash_func(ZEND_STRS("method")), (void**) &z_route_method ) == SUCCESS ) { if ( Z_TYPE_PP(z_route_method) == IS_LONG && Z_LVAL_PP(z_route_method) != current_request_method ) { return 0; } } return 1; } r3-1.3.4/php/r3/r3_functions.h000066400000000000000000000061131262260041500157420ustar00rootroot00000000000000#ifndef PHP_R3_FUNCTIONS_H #define PHP_R3_FUNCTIONS_H 1 #define REQ_METHOD_GET 1 #define REQ_METHOD_POST 2 #define REQ_METHOD_PUT 3 #define REQ_METHOD_DELETE 4 #define REQ_METHOD_PATCH 5 #define REQ_METHOD_HEAD 6 #define REQ_METHOD_OPTIONS 7 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_mux.h" #include "r3_functions.h" extern inline zval * php_r3_match(zval *z_routes, char *path, int path_len TSRMLS_DC); extern inline int get_current_request_method_const(HashTable * server_vars_hash TSRMLS_DC); extern inline int get_current_https(HashTable * server_vars_hash TSRMLS_DC); extern inline HashTable * fetch_server_vars_hash(TSRMLS_D); extern inline zval * fetch_server_var(HashTable *server_vars_hash, char *key , int key_len TSRMLS_DC); extern inline zval * get_current_http_host(HashTable * server_vars_hash TSRMLS_DC); extern inline zval * get_current_request_uri(HashTable * server_vars_hash TSRMLS_DC); extern inline zval * get_current_request_method(HashTable * server_vars_hash TSRMLS_DC); extern inline int validate_request_method(zval **z_route_options_pp, int current_request_method TSRMLS_DC); extern inline int validate_domain(zval **z_route_options_pp, zval * http_host TSRMLS_DC); extern inline int validate_https(zval **z_route_options_pp, int https TSRMLS_DC); #if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 2)) || (PHP_MAJOR_VERSION > 5) #define R3_STORE_EG_ENVIRON() \ { \ zval ** __old_return_value_pp = EG(return_value_ptr_ptr); \ zend_op ** __old_opline_ptr = EG(opline_ptr); \ zend_op_array * __old_op_array = EG(active_op_array); #define R3_RESTORE_EG_ENVIRON() \ EG(return_value_ptr_ptr) = __old_return_value_pp;\ EG(opline_ptr) = __old_opline_ptr; \ EG(active_op_array) = __old_op_array; \ } #else #define R3_STORE_EG_ENVIRON() \ { \ zval ** __old_return_value_pp = EG(return_value_ptr_ptr); \ zend_op ** __old_opline_ptr = EG(opline_ptr); \ zend_op_array * __old_op_array = EG(active_op_array); \ zend_function_state * __old_func_state = EG(function_state_ptr); #define R3_RESTORE_EG_ENVIRON() \ EG(return_value_ptr_ptr) = __old_return_value_pp;\ EG(opline_ptr) = __old_opline_ptr; \ EG(active_op_array) = __old_op_array; \ EG(function_state_ptr) = __old_func_state; \ } #endif #define CHECK(p) { if ((p) == NULL) return NULL; } zval* my_copy_zval(zval* dst, const zval* src, int persistent TSRMLS_DC); zval** my_copy_zval_ptr(zval** dst, const zval** src, int persistent TSRMLS_DC); zval * _r3_fetch_mux(char *name TSRMLS_DC); int mux_loader(char *path, zval *result TSRMLS_DC); int _r3_store_mux(char *name, zval * mux TSRMLS_DC) ; void my_zval_copy_ctor_persistent_func(zval *zvalue ZEND_FILE_LINE_DC); PHP_FUNCTION(r3_match); PHP_FUNCTION(r3_sort_routes); PHP_FUNCTION(r3_store_mux); PHP_FUNCTION(r3_fetch_mux); PHP_FUNCTION(r3_delete_mux); PHP_FUNCTION(r3_persistent_dispatch); #endif r3-1.3.4/php/r3/r3_mux.c000066400000000000000000001251501262260041500145410ustar00rootroot00000000000000 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "ext/standard/php_var.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/php_array.h" #include "php_r3.h" #include "ct_helper.h" #include "r3_functions.h" #include "r3_controller.h" #include "r3_mux.h" zend_class_entry *ce_r3_mux; const zend_function_entry mux_methods[] = { PHP_ME(Mux, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Mux, __destruct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_ME(Mux, getId, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, add, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, any, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, compile, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, sort, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, dispatch, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, length, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, mount, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, appendRoute, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, appendPCRERoute, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, match, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, getRoutes, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, setRoutes, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, getRoute, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, getSubMux, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, getRequestMethodConstant, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, export, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, get, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, post, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, put, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, delete, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, head, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, patch, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, options, NULL, ZEND_ACC_PUBLIC) PHP_ME(Mux, __set_state, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_ME(Mux, generate_id, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END }; void r3_init_mux(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "R3\\Mux", mux_methods); ce_r3_mux = zend_register_internal_class(&ce TSRMLS_CC); zend_declare_property_null(ce_r3_mux, "id", strlen("id"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(ce_r3_mux, "routes", strlen("routes"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(ce_r3_mux, "routesById", strlen("routesById"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(ce_r3_mux, "staticRoutes", strlen("staticRoutes"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(ce_r3_mux, "submux", strlen("submux"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_bool(ce_r3_mux, "expand", strlen("expand"), 1, ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_long(ce_r3_mux, "id_counter", strlen("id_counter"), 0, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC TSRMLS_CC); } zend_class_entry ** get_pattern_compiler_ce(TSRMLS_D) { zend_class_entry **ce_pattern_compiler = NULL; if ( zend_lookup_class( "R3\\PatternCompiler", strlen("R3\\PatternCompiler") , &ce_pattern_compiler TSRMLS_CC) == FAILURE ) { php_error(E_ERROR, "Class R3\\PatternCompiler not found."); return NULL; } if ( ce_pattern_compiler == NULL || *ce_pattern_compiler == NULL ) { php_error(E_ERROR, "Class R3\\PatternCompiler not found."); return NULL; } return ce_pattern_compiler; } // Returns compiled route zval zval * compile_route_pattern(zval *z_pattern, zval *z_options, zend_class_entry **ce_pattern_compiler TSRMLS_DC) { // zend_class_entry **ce_pattern_compiler; if ( ce_pattern_compiler == NULL ) { ce_pattern_compiler = get_pattern_compiler_ce(TSRMLS_C); if ( ce_pattern_compiler == NULL ) { return NULL; } } zval *z_compiled_route = NULL; // will be an array zend_call_method( NULL, *ce_pattern_compiler, NULL, "compile", strlen("compile"), &z_compiled_route, 2, z_pattern, z_options TSRMLS_CC ); if ( z_compiled_route == NULL ) { return NULL; } else if ( Z_TYPE_P(z_compiled_route) == IS_NULL ) { zval_ptr_dtor(&z_compiled_route); return NULL; } if ( Z_TYPE_P(z_compiled_route) != IS_ARRAY ) { zval_ptr_dtor(&z_compiled_route); return NULL; } return z_compiled_route; } static void var_export(zval *return_value, zval *what TSRMLS_DC) { smart_str buf = {0}; php_var_export_ex(&what, 0, &buf TSRMLS_CC); smart_str_0 (&buf); ZVAL_STRINGL(return_value, buf.c, buf.len, 0); } PHP_METHOD(Mux, __construct) { zval *z_routes = NULL, *z_routes_by_id , *z_submux = NULL, *z_static_routes = NULL; MAKE_STD_ZVAL(z_routes); MAKE_STD_ZVAL(z_routes_by_id); MAKE_STD_ZVAL(z_static_routes); MAKE_STD_ZVAL(z_submux); array_init(z_routes); array_init(z_routes_by_id); array_init(z_static_routes); array_init(z_submux); zend_update_property(ce_r3_mux, this_ptr, "routes", sizeof("routes")-1, z_routes TSRMLS_CC); zend_update_property(ce_r3_mux, this_ptr, "routesById", sizeof("routesById")-1, z_routes_by_id TSRMLS_CC); zend_update_property(ce_r3_mux, this_ptr, "staticRoutes", sizeof("staticRoutes")-1, z_static_routes TSRMLS_CC); zend_update_property(ce_r3_mux, this_ptr, "submux", sizeof("submux")-1, z_submux TSRMLS_CC); } PHP_METHOD(Mux, __destruct) { zval * val; val = zend_read_property(ce_r3_mux, getThis(), "routes", sizeof("routes")-1, 1 TSRMLS_CC); zval_ptr_dtor(&val); val = zend_read_property(ce_r3_mux, getThis(), "routesById", sizeof("routesById")-1, 1 TSRMLS_CC); zval_ptr_dtor(&val); val = zend_read_property(ce_r3_mux, getThis(), "staticRoutes", sizeof("staticRoutes")-1, 1 TSRMLS_CC); zval_ptr_dtor(&val); val = zend_read_property(ce_r3_mux, getThis(), "submux", sizeof("submux")-1, 1 TSRMLS_CC); zval_ptr_dtor(&val); } PHP_METHOD(Mux, generate_id) { zval * z_counter = NULL; long counter = 0; z_counter = zend_read_static_property(ce_r3_mux, "id_counter", strlen("id_counter") , 0 TSRMLS_CC); if ( z_counter != NULL ) { counter = Z_LVAL_P(z_counter); } counter++; Z_LVAL_P(z_counter) = counter; RETURN_LONG(counter); } PHP_METHOD(Mux, __set_state) { zval *z_array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &z_array) == FAILURE) { RETURN_FALSE; } object_init_ex(return_value, ce_r3_mux); // XXX: put this back if we have problem // CALL_METHOD(Mux, __construct, return_value, return_value); zval **z_id = NULL; zval **z_routes = NULL; zval **z_static_routes = NULL; zval **z_routes_by_id = NULL; zval **z_submux = NULL; zval **z_expand = NULL; if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "id", sizeof("id"), zend_inline_hash_func(ZEND_STRS("id")), (void**)&z_id) == SUCCESS ) { zend_update_property(ce_r3_mux, return_value, "id", sizeof("id")-1, *z_id TSRMLS_CC); } if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "routes", sizeof("routes"), zend_inline_hash_func(ZEND_STRS("routes")), (void**)&z_routes) == SUCCESS ) { Z_ADDREF_PP(z_routes); zend_update_property(ce_r3_mux, return_value, "routes", sizeof("routes")-1, *z_routes TSRMLS_CC); } if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "staticRoutes", sizeof("staticRoutes"), zend_inline_hash_func(ZEND_STRS("staticRoutes")), (void**)&z_static_routes) == SUCCESS ) { Z_ADDREF_PP(z_static_routes); zend_update_property(ce_r3_mux, return_value, "staticRoutes", sizeof("staticRoutes")-1, *z_static_routes TSRMLS_CC); } if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "routesById", sizeof("routesById"), zend_inline_hash_func(ZEND_STRS("routesById")), (void**)&z_routes_by_id) == SUCCESS ) { Z_ADDREF_PP(z_routes_by_id); zend_update_property(ce_r3_mux, return_value, "routesById", sizeof("routesById")-1, *z_routes_by_id TSRMLS_CC); } if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "submux", sizeof("submux"), zend_inline_hash_func(ZEND_STRS("submux")), (void**)&z_submux) == SUCCESS ) { Z_ADDREF_PP(z_submux); zend_update_property(ce_r3_mux, return_value, "submux", sizeof("submux")-1, *z_submux TSRMLS_CC); } if ( zend_hash_quick_find(Z_ARRVAL_P(z_array), "expand", sizeof("expand"), zend_inline_hash_func(ZEND_STRS("expand")), (void**)&z_expand) == SUCCESS ) { zend_update_property(ce_r3_mux, return_value, "expand", sizeof("expand")-1, *z_expand TSRMLS_CC); } } /** * get_mux_function_entry("method", sizeof("method"), zend_inline_hash_func(ZEND_STRS("pattern"))); */ inline zend_function * get_mux_function_entry(char * method_name, int method_name_len, ulong h) { zend_function *fe; if ( zend_hash_quick_find( &ce_r3_mux->function_table, method_name, method_name_len, h, (void **) &fe) == SUCCESS ) { return fe; } php_error(E_ERROR, "%s method not found", method_name); return NULL; } inline zval * call_mux_method(zval * object , char * method_name , int method_name_len, int param_count, zval* arg1, zval* arg2, zval* arg3 TSRMLS_DC) { zend_function *fe; if ( zend_hash_find( &ce_r3_mux->function_table, method_name, method_name_len, (void **) &fe) == FAILURE ) { php_error(E_ERROR, "%s method not found", method_name); } // call export method zval *z_retval = NULL; zend_call_method_with_3_params( &object, ce_r3_mux, &fe, method_name, method_name_len, &z_retval, param_count, arg1, arg2, arg3 TSRMLS_CC ); return z_retval; } PHP_METHOD(Mux, get) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } // $options['method'] = REQ_METHOD_GET; add_assoc_long(z_options, "method", REQ_METHOD_GET); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( this_ptr, "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } // zval_ptr_dtor(&z_retval); } PHP_METHOD(Mux, put) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_PUT); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } // zval_ptr_dtor(&z_retval); } PHP_METHOD(Mux, delete) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_DELETE); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } // zval_ptr_dtor(&z_retval); } PHP_METHOD(Mux, post) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_POST); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } } PHP_METHOD(Mux, patch) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_PATCH); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } } PHP_METHOD(Mux, head) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_HEAD); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } } PHP_METHOD(Mux, options) { zval *z_pattern = NULL, *z_callback = NULL, *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|a", &z_pattern, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init_size(z_options, 1); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init_size(z_options, 1); } add_assoc_long(z_options, "method", REQ_METHOD_OPTIONS); // $this->add($pattern, $callback, $options); zval * z_retval = call_mux_method( getThis(), "add" , sizeof("add"), 3 , z_pattern, z_callback, z_options TSRMLS_CC); if ( z_retval ) { *return_value = *z_retval; zval_copy_ctor(return_value); } } PHP_METHOD(Mux, mount) { char *pattern; int pattern_len; zval *z_mux = NULL; zval *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|a", &pattern, &pattern_len, &z_mux, &z_options) == FAILURE) { RETURN_FALSE; } if ( Z_TYPE_P(z_mux) == IS_NULL ) { RETURN_FALSE; } if ( Z_TYPE_P(z_mux) == IS_OBJECT ) { if ( instanceof_function( Z_OBJCE_P(z_mux), ce_r3_controller TSRMLS_CC) ) { zval *rv; zend_call_method(&z_mux, ce_r3_controller, NULL, "expand", strlen("expand"), &rv, 0, NULL, NULL TSRMLS_CC ); z_mux = rv; } } Z_ADDREF_P(z_mux); if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init(z_options); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init(z_options); } zend_class_entry **ce_pattern_compiler = get_pattern_compiler_ce(TSRMLS_C); if ( ce_pattern_compiler == NULL ) { RETURN_FALSE; } zval *z_routes; zval *z_expand; zval *z_mux_routes; z_routes = zend_read_property( ce_r3_mux, getThis(), "routes", sizeof("routes")-1, 1 TSRMLS_CC); z_expand = zend_read_property( ce_r3_mux, getThis(), "expand", sizeof("expand")-1, 1 TSRMLS_CC); // TODO: merge routesById and staticRoutes properties if ( Z_BVAL_P(z_expand) ) { // fetch routes from $mux // z_mux_routes = zend_read_property( ce_r3_mux, z_mux, "routes", sizeof("routes")-1, 1 TSRMLS_CC); HashPosition route_pointer; HashTable *mux_routes_hash; mux_routes_hash = Z_ARRVAL_P(z_mux_routes); zval **z_mux_route; // iterate mux for(zend_hash_internal_pointer_reset_ex(mux_routes_hash, &route_pointer); zend_hash_get_current_data_ex(mux_routes_hash, (void**) &z_mux_route, &route_pointer) == SUCCESS; zend_hash_move_forward_ex(mux_routes_hash, &route_pointer)) { // zval for new route zval *z_new_routes; // zval for route item zval **z_is_pcre; // route[0] zval **z_route_pattern; zval **z_route_callback; zval **z_route_options; zval **z_route_original_pattern; // for PCRE pattern if ( zend_hash_index_find( Z_ARRVAL_PP(z_mux_route), 0, (void**) &z_is_pcre) == FAILURE ) { continue; } if ( zend_hash_index_find( Z_ARRVAL_PP(z_mux_route), 1, (void**) &z_route_pattern) == FAILURE ) { continue; } if ( zend_hash_index_find( Z_ARRVAL_PP(z_mux_route), 2, (void**) &z_route_callback) == FAILURE ) { continue; } if ( zend_hash_index_find( Z_ARRVAL_PP(z_mux_route), 3, (void**) &z_route_options) == FAILURE ) { continue; } // Z_ADDREF_P(z_route_callback); // Z_ADDREF_P(z_route_options); // reference it so it will not be recycled. MAKE_STD_ZVAL(z_new_routes); array_init(z_new_routes); if ( Z_BVAL_PP(z_is_pcre) ) { // $newPattern = $pattern . $route[3]['pattern']; if ( zend_hash_quick_find( Z_ARRVAL_PP(z_route_options), "pattern", sizeof("pattern"), zend_inline_hash_func(ZEND_STRS("pattern")), (void**) &z_route_original_pattern) == FAILURE ) { php_error( E_ERROR, "Can not compile pattern, original pattern not found"); } char new_pattern[120] = { 0 }; int new_pattern_len; strncat( new_pattern, pattern , pattern_len ); strncat( new_pattern, Z_STRVAL_PP(z_route_original_pattern) , Z_STRLEN_PP(z_route_original_pattern) ); new_pattern_len = pattern_len + Z_STRLEN_PP(z_route_original_pattern); zval *z_new_pattern = NULL; MAKE_STD_ZVAL(z_new_pattern); ZVAL_STRINGL(z_new_pattern, new_pattern, new_pattern_len, 1); // TODO: merge options // $routeArgs = PatternCompiler::compile($newPattern, // array_merge_recursive($route[3], $options) ); zval *z_compiled_route = compile_route_pattern(z_new_pattern, *z_route_options, ce_pattern_compiler TSRMLS_CC); if ( z_compiled_route == NULL || Z_TYPE_P(z_compiled_route) == IS_NULL ) { php_error( E_ERROR, "Cannot compile pattern: %s", new_pattern); } zval **z_compiled_route_pattern; if ( zend_hash_quick_find( Z_ARRVAL_P(z_compiled_route) , "compiled", sizeof("compiled"), zend_inline_hash_func(ZEND_STRS("compiled")), (void**)&z_compiled_route_pattern) == FAILURE ) { php_error( E_ERROR, "compiled pattern not found: %s", new_pattern); } zend_hash_quick_update( Z_ARRVAL_P(z_compiled_route), "pattern", sizeof("pattern"), zend_inline_hash_func(ZEND_STRS("pattern")), &z_new_pattern, sizeof(zval *), NULL); Z_ADDREF_PP(z_compiled_route_pattern); Z_ADDREF_PP(z_route_callback); Z_ADDREF_P(z_compiled_route); Z_ADDREF_P(z_new_routes); // create new route and append to mux->routes add_index_bool(z_new_routes, 0 , 1); // pcre flag == false add_index_zval(z_new_routes, 1, *z_compiled_route_pattern); add_index_zval(z_new_routes, 2 , *z_route_callback); add_index_zval(z_new_routes, 3, z_compiled_route); add_next_index_zval(z_routes, z_new_routes); } else { // $this->routes[] = array( // false, // $pattern . $route[1], // $route[2], // $options, // ); char new_pattern[120] = { 0 }; strncat(new_pattern, pattern, pattern_len); strncat(new_pattern, Z_STRVAL_PP(z_route_pattern), Z_STRLEN_PP(z_route_pattern) ); int new_pattern_len = pattern_len + Z_STRLEN_PP(z_route_pattern); // Merge the mount options with the route options zval *z_new_route_options; MAKE_STD_ZVAL(z_new_route_options); array_init(z_new_route_options); php_array_merge(Z_ARRVAL_P(z_new_route_options), Z_ARRVAL_P(z_options), 0 TSRMLS_CC); php_array_merge(Z_ARRVAL_P(z_new_route_options), Z_ARRVAL_P(*z_route_options), 0 TSRMLS_CC); Z_ADDREF_PP(z_route_callback); Z_ADDREF_P(z_new_route_options); Z_ADDREF_P(z_new_routes); /* make the array: [ pcreFlag, pattern, callback, options ] */ add_index_bool(z_new_routes, 0 , 0); // pcre flag == false add_index_stringl(z_new_routes, 1 , new_pattern , new_pattern_len, 1); add_index_zval( z_new_routes, 2 , *z_route_callback); add_index_zval( z_new_routes, 3 , z_new_route_options); add_next_index_zval(z_routes, z_new_routes); } } } else { zend_function *fe_getid = NULL; // method entry zend_function *fe_add = NULL; // method entry if ( zend_hash_quick_find(&ce_r3_mux->function_table, "getid", sizeof("getid"), zend_inline_hash_func(ZEND_STRS("getid")), (void **) &fe_getid) == FAILURE ) { php_error(E_ERROR, "Cannot call method Mux::getid()"); RETURN_FALSE; } if ( zend_hash_quick_find(&ce_r3_mux->function_table, "add", sizeof("add"), zend_inline_hash_func(ZEND_STRS("add")), (void **) &fe_add) == FAILURE ) { php_error(E_ERROR, "Cannot call method Mux::add()"); RETURN_FALSE; } // $muxId = $mux->getId(); // $this->add($pattern, $muxId, $options); // $this->submux[ $muxId ] = $mux; // zval *z_mux_id = call_mux_method(z_mux, "getid", sizeof("getid") , ); zval *z_mux_id = NULL; zend_call_method( &z_mux, ce_r3_mux, &fe_getid, "getid", strlen("getid"), &z_mux_id, 0, NULL, NULL TSRMLS_CC ); if ( z_mux_id == NULL || Z_TYPE_P(z_mux_id) == IS_NULL ) { php_error(E_ERROR, "Mux id is required. got NULL."); } // create pattern zval *z_pattern = NULL; MAKE_STD_ZVAL(z_pattern); ZVAL_STRINGL(z_pattern, pattern, pattern_len, 1); // duplicate zval *z_retval = NULL; zend_call_method_with_3_params( &this_ptr, ce_r3_mux, &fe_add, "add", strlen("add"), &z_retval, 3, z_pattern, z_mux_id, z_options TSRMLS_CC); zval *z_submux_array = zend_read_property( ce_r3_mux, this_ptr , "submux", sizeof("submux") - 1, 1 TSRMLS_CC); add_index_zval(z_submux_array, Z_LVAL_P(z_mux_id) , z_mux); // release zvals zval_ptr_dtor(&z_mux_id); // zval_ptr_dtor(&z_pattern); } } PHP_METHOD(Mux, getSubMux) { long submux_id = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &submux_id ) == FAILURE) { RETURN_FALSE; } zval *z_submux_array; zval **z_submux; z_submux_array = zend_read_property( Z_OBJCE_P(this_ptr), this_ptr, "submux", sizeof("submux")-1, 1 TSRMLS_CC); if ( zend_hash_index_find( Z_ARRVAL_P(z_submux_array), submux_id , (void**) &z_submux) == SUCCESS ) { *return_value = **z_submux; zval_copy_ctor(return_value); return; } RETURN_FALSE; } PHP_METHOD(Mux, getRequestMethodConstant) { char *req_method = NULL, *mthit, *mthp; long req_method_const = 0; long req_method_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &req_method, &req_method_len) != FAILURE) { mthit = mthp = estrndup(req_method, strlen(req_method)); while(( *mthit = toupper(*mthit))) mthit++; if (strcmp(mthp, "GET") == 0) { req_method_const = REQ_METHOD_GET; } else if (strcmp(mthp, "POST") == 0) { req_method_const = REQ_METHOD_POST; } else if (strcmp(mthp, "PUT") == 0) { req_method_const = REQ_METHOD_PUT; } else if (strcmp(mthp, "DELETE") == 0) { req_method_const = REQ_METHOD_DELETE; } else if (strcmp(mthp, "HEAD") == 0) { req_method_const = REQ_METHOD_HEAD; } else if (strcmp(mthp, "OPTIONS") == 0) { req_method_const = REQ_METHOD_OPTIONS; } else if (strcmp(mthp, "PATCH") == 0) { req_method_const = REQ_METHOD_PATCH; } efree(req_method); } RETURN_LONG(req_method_const); } PHP_METHOD(Mux, getRoute) { char * route_id = NULL; int route_id_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &route_id, &route_id_len ) == FAILURE) { RETURN_FALSE; } zval *z_routes_by_id = NULL; zval **z_route = NULL; z_routes_by_id = zend_read_property( ce_r3_mux , this_ptr, "routesById", sizeof("routesById")-1, 1 TSRMLS_CC); // php_var_dump(&z_routes_by_id, 1 TSRMLS_CC); if ( zend_hash_find( Z_ARRVAL_P(z_routes_by_id) , route_id, route_id_len + 1, (void**) &z_route ) == SUCCESS ) { *return_value = **z_route; zval_copy_ctor(return_value); return; } RETURN_NULL(); } PHP_METHOD(Mux, setRoutes) { zval * routes; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &routes ) == FAILURE) { RETURN_FALSE; } zend_update_property(ce_r3_mux , this_ptr, "routes", sizeof("routes")-1, routes TSRMLS_CC); RETURN_TRUE; } PHP_METHOD(Mux, getRoutes) { zval *z_routes; z_routes = zend_read_property(ce_r3_mux, this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); *return_value = *z_routes; zval_copy_ctor(return_value); } PHP_METHOD(Mux, export) { smart_str buf = {0}; php_var_export_ex(&this_ptr, 0, &buf TSRMLS_CC); smart_str_0 (&buf); RETVAL_STRINGL(buf.c, buf.len, 0); } PHP_METHOD(Mux, getId) { zval *z_id; long counter = 0; z_id = zend_read_property(ce_r3_mux, getThis(), "id", sizeof("id")-1, 1 TSRMLS_CC); if ( z_id != NULL && Z_TYPE_P(z_id) != IS_NULL ) { RETURN_LONG( Z_LVAL_P(z_id) ); } zval *rv = NULL; zend_call_method( NULL, ce_r3_mux, NULL, "generate_id", strlen("generate_id"), &rv, 0, NULL, NULL TSRMLS_CC ); if ( rv ) { counter = Z_LVAL_P(rv); zend_update_property_long(ce_r3_mux, this_ptr, "id" , sizeof("id") - 1, counter TSRMLS_CC); zval_ptr_dtor(&rv); } RETURN_LONG(counter); } PHP_METHOD(Mux, length) { zval *z_routes; z_routes = zend_read_property(ce_r3_mux, this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); long length = zend_hash_num_elements( Z_ARRVAL_P(z_routes) ); RETURN_LONG(length); } PHP_METHOD(Mux, sort) { zval *z_routes; z_routes = zend_read_property(Z_OBJCE_P(this_ptr) , this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); zval *retval_ptr = NULL; zval *z_sort_callback = NULL; MAKE_STD_ZVAL(z_sort_callback); ZVAL_STRING( z_sort_callback, "r3_sort_routes" , 1 ); Z_SET_ISREF_P(z_routes); zend_call_method( NULL, NULL, NULL, "usort", strlen("usort"), &retval_ptr, 2, z_routes, z_sort_callback TSRMLS_CC ); zval_ptr_dtor(&z_sort_callback); if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } PHP_METHOD(Mux, compile) { char *filename; int filename_len; zend_bool sort_before_compile = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &filename, &filename_len, &sort_before_compile) == FAILURE) { RETURN_FALSE; } if (sort_before_compile) { zval *z_routes; z_routes = zend_read_property(ce_r3_mux, this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); Z_SET_ISREF_P(z_routes); // duplicated code to sort method zval *rv = NULL; zval *z_sort_callback = NULL; MAKE_STD_ZVAL(z_sort_callback); ZVAL_STRING( z_sort_callback, "r3_sort_routes" , 1 ); zend_call_method( NULL, NULL, NULL, "usort", strlen("usort"), &rv, 2, z_routes, z_sort_callback TSRMLS_CC ); zval_ptr_dtor(&z_sort_callback); // recycle sort callback zval // php_error(E_ERROR,"route sort failed."); // zend_update_property(ce_r3_mux, getThis(), "routes", sizeof("routes")-1, z_routes TSRMLS_CC); } // $code = 'export() . ';'; // get export method function entry zend_function *fe_export; if ( zend_hash_quick_find( &Z_OBJCE_P(this_ptr)->function_table, "export", sizeof("export"), zend_inline_hash_func(ZEND_STRS("export")), (void **) &fe_export) == FAILURE ) { php_error(E_ERROR, "export method not found"); } // call export method zval *compiled_code = NULL; zend_call_method( &this_ptr, Z_OBJCE_P(this_ptr) , &fe_export, "export", strlen("export"), &compiled_code, 0, NULL, NULL TSRMLS_CC ); if ( compiled_code == NULL || Z_TYPE_P(compiled_code) == IS_NULL ) { php_error(E_ERROR, "Cannot compile routes."); } int buf_len = Z_STRLEN_P(compiled_code) + strlen("function_table, "match", sizeof("match"), zend_inline_hash_func(ZEND_STRS("match")), (void **) &fe); zend_call_method( &this_ptr, ce_r3_mux, &fe, "match", strlen("match"), &z_return_route, 1, z_path, NULL TSRMLS_CC ); if ( ! z_return_route || Z_TYPE_P(z_return_route) == IS_NULL ) { zval_ptr_dtor(&z_path); RETURN_NULL(); } // read data from matched route zval **z_pcre; zval **z_pattern; zval **z_callback; zval **z_options; zend_hash_index_find( Z_ARRVAL_P(z_return_route) , 0 , (void**) &z_pcre ); zend_hash_index_find( Z_ARRVAL_P(z_return_route) , 1 , (void**) &z_pattern ); zend_hash_index_find( Z_ARRVAL_P(z_return_route) , 2 , (void**) &z_callback ); zend_hash_index_find( Z_ARRVAL_P(z_return_route) , 3 , (void**) &z_options ); zval *z_submux_array = NULL; zval **z_submux = NULL; zval *z_retval = NULL; // dispatch to submux if the callback is an ID. if ( Z_TYPE_PP(z_callback) == IS_LONG ) { z_submux_array = zend_read_property( ce_r3_mux, this_ptr, "submux", sizeof("submux")-1, 1 TSRMLS_CC); if ( z_submux_array == NULL ) { zend_throw_exception(ce_r3_exception, "submux property is null", 0 TSRMLS_CC); return; } if ( zend_hash_index_find( Z_ARRVAL_P(z_submux_array), Z_LVAL_PP(z_callback) , (void**) &z_submux) == FAILURE ) { zend_throw_exception(ce_r3_exception, "submux not found", 0 TSRMLS_CC); return; } if ( z_submux == NULL || *z_submux == NULL ) { zend_throw_exception(ce_r3_exception, "submux not found", 0 TSRMLS_CC); return; } // php_var_dump(z_submux, 1 TSRMLS_CC); // $matchedString = $route[3]['vars'][0]; // return $submux->dispatch(substr($path, strlen($matchedString)) if ( Z_BVAL_PP(z_pcre) ) { zval **z_route_vars = NULL; zval **z_route_vars_0 = NULL; zval *z_substr; if ( zend_hash_quick_find( Z_ARRVAL_PP(z_options) , "vars", sizeof("vars"), zend_inline_hash_func(ZEND_STRS("vars")), (void**) &z_route_vars ) == FAILURE ) { php_error(E_ERROR, "require route vars"); RETURN_FALSE; } if ( zend_hash_index_find( Z_ARRVAL_PP(z_options) , 0 , (void**) &z_route_vars_0 ) == FAILURE ) { php_error(E_ERROR, "require route vars[0]"); RETURN_FALSE; } MAKE_STD_ZVAL(z_substr); ZVAL_STRING(z_substr, path + Z_STRLEN_PP(z_route_vars_0), 1); z_retval = call_mux_method( *z_submux, "dispatch" , sizeof("dispatch"), 1 , z_substr, NULL, NULL TSRMLS_CC); zval_ptr_dtor(&z_substr); if (z_retval) { Z_ADDREF_P(z_retval); *return_value = *z_retval; zval_copy_ctor(return_value); } // zval_ptr_dtor(&z_return_route); RETURN_FALSE; return; } else { zval *z_substr; MAKE_STD_ZVAL(z_substr); ZVAL_STRING(z_substr, path + Z_STRLEN_PP(z_pattern), 1); // return $submux->dispatch( // substr($path, strlen($route[1])) // ); z_retval = call_mux_method( *z_submux, "dispatch" , sizeof("dispatch"), 1 , z_substr, NULL, NULL TSRMLS_CC); zval_ptr_dtor(&z_substr); if ( z_retval ) { Z_ADDREF_P(z_retval); *return_value = *z_retval; zval_copy_ctor(return_value); } // zval_ptr_dtor(&z_return_route); return; } } if ( z_return_route ) { *return_value = *z_return_route; zval_copy_ctor(return_value); } zval_ptr_dtor(&z_path); zval_ptr_dtor(&z_return_route); return; } PHP_METHOD(Mux, match) { char *path; int path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &path_len) == FAILURE) { RETURN_FALSE; } zval **z_route_pp = NULL; zval *z_route = NULL; if ( zend_hash_find( Z_ARRVAL_P( zend_read_property(ce_r3_mux, this_ptr, "staticRoutes", sizeof("staticRoutes") - 1, 1 TSRMLS_CC) ), path, path_len, (void**)&z_route_pp) == SUCCESS ) { if ( Z_TYPE_PP(z_route_pp) != IS_NULL ) { *return_value = **z_route_pp; Z_ADDREF_PP(z_route_pp); zval_copy_ctor(return_value); return; } } z_route = php_r3_match(zend_read_property(ce_r3_mux , this_ptr , "routes", sizeof("routes")-1, 1 TSRMLS_CC), path, path_len TSRMLS_CC); if ( z_route != NULL ) { *return_value = *z_route; zval_copy_ctor(return_value); Z_ADDREF_P(z_route); return; } RETURN_NULL(); } PHP_METHOD(Mux, appendRoute) { char *pattern; int pattern_len; zval *z_callback; zval *z_options; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sa|a", &pattern, &pattern_len, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } zval *z_routes; zval *z_new_routes; if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init(z_options); } if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init(z_options); } z_routes = zend_read_property(Z_OBJCE_P(this_ptr), this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); MAKE_STD_ZVAL(z_new_routes); array_init_size(z_new_routes, 4); add_index_bool(z_new_routes, 0 , 0); // pcre flag == false add_index_stringl( z_new_routes, 1 , pattern , pattern_len, 1); add_index_zval( z_new_routes, 2 , z_callback); add_index_zval( z_new_routes, 3 , z_options); add_next_index_zval(z_routes, z_new_routes); } PHP_METHOD(Mux, appendPCRERoute) { char *pattern; int pattern_len; zval *z_callback; zval *z_options; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sa|a", &pattern, &pattern_len, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init(z_options); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { array_init(z_options); } zval *z_pattern = NULL; zval *z_routes; MAKE_STD_ZVAL(z_pattern); ZVAL_STRINGL(z_pattern, pattern, pattern_len, 1); z_routes = zend_read_property(Z_OBJCE_P(this_ptr), getThis(), "routes", sizeof("routes")-1, 1 TSRMLS_CC); zend_class_entry **ce_pattern_compiler = get_pattern_compiler_ce(TSRMLS_C); if ( ce_pattern_compiler == NULL ) { RETURN_FALSE; } zval *rv = NULL; zend_call_method( NULL, *ce_pattern_compiler, NULL, "compile", strlen("compile"), &rv, 1, z_pattern, NULL TSRMLS_CC ); if ( rv == NULL || Z_TYPE_P(rv) == IS_NULL ) { zend_throw_exception(ce_r3_exception, "Can not compile route pattern", 0 TSRMLS_CC); RETURN_FALSE; } add_next_index_zval(z_routes, rv); } inline void mux_add_route(INTERNAL_FUNCTION_PARAMETERS) { char *pattern; int pattern_len; zval *z_callback = NULL; zval *z_options = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|a", &pattern, &pattern_len, &z_callback, &z_options) == FAILURE) { RETURN_FALSE; } // $pcre = strpos($pattern,':') !== false; char *found = find_place_holder(pattern, pattern_len); if ( z_options == NULL ) { MAKE_STD_ZVAL(z_options); array_init(z_options); } else if ( Z_TYPE_P(z_options) == IS_NULL ) { // make it as an array array_init(z_options); } // Generalize callback variable if ( Z_TYPE_P(z_callback) == IS_STRING ) { if ( strpos( Z_STRVAL_P(z_callback), ":" ) != -1 ) { zval *delim; MAKE_STD_ZVAL(delim); ZVAL_STRINGL(delim, ":" , 1 , 1); zval *rv; MAKE_STD_ZVAL(rv); array_init(rv); php_explode(delim, z_callback, rv, 2); z_callback = rv; // zval_copy_ctor(z_callback); zval_ptr_dtor(&delim); } } zval * z_routes = zend_read_property(ce_r3_mux, this_ptr, "routes", sizeof("routes")-1, 1 TSRMLS_CC); // PCRE pattern here if ( found ) { zval *z_pattern = NULL; MAKE_STD_ZVAL(z_pattern); ZVAL_STRINGL(z_pattern, pattern, pattern_len, 1); zval *z_compiled_route = compile_route_pattern(z_pattern, z_options, NULL TSRMLS_CC); if ( z_compiled_route == NULL ) { zend_throw_exception(ce_r3_exception, "Unable to compile route pattern.", 0 TSRMLS_CC); RETURN_FALSE; } zval_ptr_dtor(&z_pattern); zval **z_compiled_route_pattern; if ( zend_hash_quick_find( Z_ARRVAL_P(z_compiled_route) , "compiled", sizeof("compiled"), zend_inline_hash_func(ZEND_STRS("compiled")), (void**)&z_compiled_route_pattern) == FAILURE ) { zend_throw_exception(ce_r3_exception, "Unable to find compiled pattern.", 0 TSRMLS_CC); RETURN_FALSE; } Z_ADDREF_P(z_callback); zval *z_new_routes; MAKE_STD_ZVAL(z_new_routes); array_init_size(z_new_routes, 4); add_index_bool(z_new_routes, 0 , 1); // pcre flag == false add_index_zval(z_new_routes, 1, *z_compiled_route_pattern); add_index_zval(z_new_routes, 2 , z_callback); add_index_zval(z_new_routes, 3, z_compiled_route); add_next_index_zval(z_routes, z_new_routes); zval **z_route_id; if ( zend_hash_quick_find( Z_ARRVAL_P(z_options) , "id", sizeof("id"), zend_inline_hash_func(ZEND_STRS("id")), (void**)&z_route_id) == SUCCESS ) { zval * z_routes_by_id = zend_read_property(ce_r3_mux, this_ptr, "routesById", sizeof("routesById")-1, 1 TSRMLS_CC); add_assoc_zval(z_routes_by_id, Z_STRVAL_PP(z_route_id), z_new_routes); } } else { Z_ADDREF_P(z_options); // reference it so it will not be recycled. Z_ADDREF_P(z_callback); zval *z_new_route; MAKE_STD_ZVAL(z_new_route); array_init_size(z_new_route, 4); /* make the array: [ pcreFlag, pattern, callback, options ] */ add_index_bool(z_new_route, 0 , 0); // pcre flag == false add_index_stringl( z_new_route, 1 , pattern, pattern_len , 1 ); add_index_zval( z_new_route, 2 , z_callback); add_index_zval( z_new_route, 3 , z_options); add_next_index_zval(z_routes, z_new_route); // if there is no option specified in z_options, we can add the route to our static route hash if ( zend_hash_num_elements(Z_ARRVAL_P(z_options)) ) { zval * z_static_routes = zend_read_property(ce_r3_mux, this_ptr, "staticRoutes", sizeof("staticRoutes")-1, 1 TSRMLS_CC); if ( z_static_routes ) { add_assoc_zval(z_static_routes, pattern, z_new_route); } } zval **z_route_id; if ( zend_hash_quick_find( Z_ARRVAL_P(z_options) , "id", sizeof("id"), zend_inline_hash_func(ZEND_STRS("id")), (void**)&z_route_id) == SUCCESS ) { zval * z_routes_by_id = zend_read_property(ce_r3_mux, this_ptr, "routesById", sizeof("routesById")-1, 1 TSRMLS_CC); /* zval *id_route = NULL; ALLOC_ZVAL(id_route); ZVAL_COPY_VALUE(id_route, z_new_route); zval_copy_ctor(id_route); add_assoc_zval(z_routes_by_id, Z_STRVAL_PP(z_route_id), id_route); */ add_assoc_zval(z_routes_by_id, Z_STRVAL_PP(z_route_id), z_new_route); } } } PHP_METHOD(Mux, add) { mux_add_route(INTERNAL_FUNCTION_PARAM_PASSTHRU); } PHP_METHOD(Mux, any) { mux_add_route(INTERNAL_FUNCTION_PARAM_PASSTHRU); } r3-1.3.4/php/r3/r3_mux.h000066400000000000000000000031061262260041500145420ustar00rootroot00000000000000#ifndef PHP_MUX_H #define PHP_MUX_H 1 #include "php.h" #include "string.h" #include "main/php_main.h" #include "Zend/zend_API.h" #include "Zend/zend_variables.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_object_handlers.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_string.h" #include "php_r3.h" #include "r3_functions.h" extern zend_class_entry *ce_r3_mux; void r3_init_mux(TSRMLS_D); zend_class_entry ** get_pattern_compiler_ce(TSRMLS_D); zval * compile_route_pattern(zval *z_pattern, zval *z_options, zend_class_entry **ce_pattern_compiler TSRMLS_DC); extern inline zval * call_mux_method(zval * object , char * method_name , int method_name_len, int param_count, zval* arg1, zval* arg2, zval* arg3 TSRMLS_DC); extern inline void mux_add_route(INTERNAL_FUNCTION_PARAMETERS); PHP_METHOD(Mux, __construct); PHP_METHOD(Mux, __destruct); PHP_METHOD(Mux, getId); PHP_METHOD(Mux, add); PHP_METHOD(Mux, any); PHP_METHOD(Mux, length); PHP_METHOD(Mux, compile); PHP_METHOD(Mux, sort); PHP_METHOD(Mux, appendRoute); PHP_METHOD(Mux, appendPCRERoute); PHP_METHOD(Mux, setRoutes); PHP_METHOD(Mux, getRoutes); PHP_METHOD(Mux, getRoute); PHP_METHOD(Mux, match); PHP_METHOD(Mux, dispatch); PHP_METHOD(Mux, getSubMux); PHP_METHOD(Mux, getRequestMethodConstant); PHP_METHOD(Mux, export); PHP_METHOD(Mux, mount); PHP_METHOD(Mux, get); PHP_METHOD(Mux, post); PHP_METHOD(Mux, put); PHP_METHOD(Mux, delete); PHP_METHOD(Mux, head); PHP_METHOD(Mux, patch); PHP_METHOD(Mux, options); PHP_METHOD(Mux, __set_state); // static method PHP_METHOD(Mux, generate_id); #endif r3-1.3.4/php/r3/r3_persistent.c000066400000000000000000000030011262260041500161160ustar00rootroot00000000000000#include "php.h" #include "php_r3.h" #include "r3_persistent.h" #include "php_expandable_mux.h" inline int persistent_store(char *key, int key_len, int list_type, void * val TSRMLS_DC) { zend_rsrc_list_entry new_le; zend_rsrc_list_entry *le; // store it if it's not in persistent_list if ( zend_hash_find(&EG(persistent_list), key, key_len + 1, (void**) &le) == SUCCESS ) { zend_hash_del(&EG(persistent_list), key, key_len + 1); } new_le.type = list_type; new_le.ptr = val; return zend_hash_update(&EG(persistent_list), key, key_len + 1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL); } inline void * persistent_fetch(char *key, int key_len TSRMLS_DC) { zend_rsrc_list_entry *le; if ( zend_hash_find(&EG(persistent_list), key, key_len + 1, (void**) &le) == SUCCESS ) { return le->ptr; } return NULL; } inline void * r3_persistent_fetch(char *ns, char *key TSRMLS_DC) { char *newkey; int newkey_len; void *ptr; newkey_len = spprintf(&newkey, 0, "r3_%s_%s", ns, key); ptr = persistent_fetch(newkey, newkey_len TSRMLS_CC); efree(newkey); return ptr; } /* * Store persistent value with r3 namespace. */ inline int r3_persistent_store(char *ns, char *key, int list_type, void * val TSRMLS_DC) { char *newkey; int newkey_len; int status; newkey_len = spprintf(&newkey, 0, "r3_%s_%s", ns, key); status = persistent_store(newkey, newkey_len, list_type, val TSRMLS_CC); efree(newkey); return status; } r3-1.3.4/php/r3/r3_persistent.h000066400000000000000000000006211262260041500161300ustar00rootroot00000000000000#ifndef R3_PERSISTENT_H #define R3_PERSISTENT_H 1 extern inline int persistent_store(char *key, int key_len, int list_type, void * val TSRMLS_DC); extern inline int r3_persistent_store(char *ns, char *key, int list_type, void * val TSRMLS_DC) ; extern inline void * persistent_fetch(char *key, int key_len TSRMLS_DC); extern inline void * r3_persistent_fetch(char *ns, char *key TSRMLS_DC); #endif r3-1.3.4/r3.pc.in000066400000000000000000000003541262260041500133200ustar00rootroot00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ includedir=@includedir@/r3 libdir=@libdir@ Name: r3 Description: High-performance URL router library Version: @PACKAGE_VERSION@ Requires: libpcre Libs: -L${libdir} -lr3 CFlags: -I${includedir} r3-1.3.4/run-benchmark000077500000000000000000000001261262260041500145220ustar00rootroot00000000000000#!/bin/bash i=10 while [ $i -gt 0 ] ; do bash tests/bench i=$(($i - 1)) done r3-1.3.4/src/000077500000000000000000000000001262260041500126305ustar00rootroot00000000000000r3-1.3.4/src/CMakeLists.txt000066400000000000000000000007501262260041500153720ustar00rootroot00000000000000include_directories("${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/3rdparty ${PROJECT_SOURCE_DIR}") # install(TARGETS swiftnav-static DESTINATION lib${LIB_SUFFIX}) find_package(PCRE REQUIRED) set(libr3_SRCS node.c edge.c list.c slug.c str.c token.c match_entry.c) set(LIBS ${LIBS} ${PCRE_LIBRARIES} r3) add_library(r3 STATIC ${libr3_SRCS}) target_link_libraries(r3 lib3rdparty pcre) # install(FILES ${libswiftnav_HEADERS} DESTINATION include/libswiftnav) r3-1.3.4/src/Makefile.am000066400000000000000000000016071262260041500146700ustar00rootroot00000000000000AM_CFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) $(JSONC_CFLAGS) -I$(top_builddir) -I$(top_builddir)/include -I$(top_builddir)/3rdparty -Wall -std=c99 AM_LDFLAGS=$(DEPS_LIBS) $(GVC_DEPS_LIBS) $(JSONC_LIBS) MAYBE_COVERAGE=--coverage noinst_LTLIBRARIES = libr3core.la # lib_LIBRARIES = libr3.a libr3core_la_SOURCES = node.c edge.c str.c token.c match_entry.c slug.c if ENABLE_JSON libr3core_la_SOURCES += json.c endif if COND_GCOV # MAYBE_COVERAGE=--coverage --no-inline AM_CFLAGS += $(MAYBE_COVERAGE) endif MOSTLYCLEANFILES = *.gcov *.gcda *.gcno # libr3_la_LDFLAGS = -export-symbols-regex '^r3_|^match_' # libr3_la_LIBADD=$(DEPS_LIBS) $(LIBOBJS) $(ALLOCA) # libr3core_la_LIBADD=$(DEPS_LIBS) # libr3core_la_CFLAGS=$(DEPS_CFLAGS) -I$(top_builddir) -I$(top_builddir)/include -I$(top_builddir)/3rdparty -Wall -std=c99 if ENABLE_GRAPHVIZ libr3core_la_SOURCES += gvc.c endif # AM_CFLAGS=$(DEPS_CFLAGS) r3-1.3.4/src/edge.c000066400000000000000000000036111262260041500137010ustar00rootroot00000000000000/* * edge.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include // Jemalloc memory management // #include // PCRE #include #include "r3.h" #include "r3_str.h" #include "slug.h" #include "zmalloc.h" #define CHECK_PTR(ptr) if (ptr == NULL) return NULL; edge * r3_edge_createl(const char * pattern, int pattern_len, node * child) { edge * e = (edge*) zmalloc( sizeof(edge) ); CHECK_PTR(e); e->pattern = (char*) pattern; e->pattern_len = pattern_len; e->opcode = 0; e->child = child; e->has_slug = r3_path_contains_slug_char(e->pattern); return e; } /** * r3_edge_branch splits the edge and append the rest part as the child of the * first level child * * branch the edge pattern at "dl" offset, * and insert a dummy child between the edges. * * A -> [EDGE: abcdefg] -> B -> [EDGE:branch1], [EDGE:branch2] * A -> [EDGE: abcd] -> B1 -> [efg] -> B2 (new child with copied data from B) * */ node * r3_edge_branch(edge *e, int dl) { node * new_child; edge * new_edge; // the rest string char * s1 = e->pattern + dl; int s1_len = e->pattern_len - dl; // the suffix edge of the leaf new_child = r3_tree_create(3); new_edge = r3_edge_createl(zstrndup(s1, s1_len), s1_len, new_child); // Move child node to the new edge new_edge->child = e->child; e->child = new_child; r3_node_append_edge(new_child, new_edge); // truncate the original edge pattern char *oldpattern = e->pattern; e->pattern = zstrndup(e->pattern, dl); e->pattern_len = dl; zfree(oldpattern); return new_child; } void r3_edge_free(edge * e) { zfree(e->pattern); if ( e->child ) { r3_tree_free(e->child); } // free itself zfree(e); } r3-1.3.4/src/gvc.c000066400000000000000000000053341262260041500135600ustar00rootroot00000000000000/* * gvz.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include "r3.h" #include "r3_gvc.h" #include "zmalloc.h" void r3_tree_build_ag_nodes(Agraph_t * g, Agnode_t * ag_parent_node, const node * n, int * node_cnt) { if (!n) return; for ( int i = 0 ; i < n->edge_len ; i++ ) { edge * e = n->edges[i]; (*node_cnt)++; Agnode_t *agn_child = NULL; Agedge_t *agn_edge = NULL; char *nodename = NULL; if ( e && e->child && e->child->combined_pattern ) { asprintf(&nodename,"%s", e->child->combined_pattern); } else { asprintf(&nodename,"#%d", *node_cnt); } agn_child = agnode(g, nodename, 1); agn_edge = agedge(g, ag_parent_node, agn_child, 0, 1); agsafeset(agn_edge, "label", e->pattern, ""); if (e->child && e->child->endpoint) { agsafeset(agn_child, "shape", "doublecircle", ""); } r3_tree_build_ag_nodes(g, agn_child, e->child, node_cnt); } } /** * Render a tree to tree graph image via graphviz (dot) */ int r3_tree_render(const node * tree, const char *layout, const char * format, FILE *fp) { Agraph_t *g; /* set up a graphviz context - but only once even for multiple graphs */ GVC_t *gvc = NULL; gvc = gvContext(); /* Create a simple digraph */ // g = agopen("g", Agdirected, 0); g = agopen("g", Agundirected, 0); // create self node Agnode_t *ag_root = agnode(g, "{root}", 1); int n = 0; r3_tree_build_ag_nodes(g, ag_root, tree, &n); gvLayout(gvc, g, layout); gvRender(gvc, g, format, fp); gvFreeLayout(gvc, g); agclose(g); return 0; } /** * Render a tree to tree graph image via graphviz (dot) */ int r3_tree_render_dot(const node * tree, const char *layout, FILE *fp) { return r3_tree_render(tree, layout, "dot", fp); } /** * Render a tree to tree graph image via graphviz (dot) */ int r3_tree_render_file(const node * tree, const char * format, const char * filename) { Agraph_t *g; GVC_t *gvc = NULL; gvc = gvContext(); /* // set up a graphviz context - but only once even for multiple graphs static GVC_t *gvc; if (!gvc) { gvc = gvContext(); } */ /* Create a simple digraph */ // g = agopen("g", Agdirected, 0); g = agopen("g", Agundirected, 0); // create self node Agnode_t *ag_root = agnode(g, "{root}", 1); int n = 0; r3_tree_build_ag_nodes(g, ag_root, tree, &n); gvLayout(gvc, g, "dot"); gvRenderFilename(gvc, g, format, filename); gvFreeLayout(gvc, g); agclose(g); return 0; } r3-1.3.4/src/json.c000066400000000000000000000056311262260041500137520ustar00rootroot00000000000000/* * json.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include "r3.h" #include "r3_json.h" json_object * r3_route_to_json_object(const route * r) { json_object *obj; obj = json_object_new_object(); json_object_object_add(obj, "path", json_object_new_string(r->path)); json_object_object_add(obj, "allowed_methods", json_object_new_int(r->request_method)); if (r->host) { json_object_object_add(obj, "host", json_object_new_string(r->host)); } if (r->remote_addr_pattern) { json_object_object_add(obj, "remote_addr_pattern", json_object_new_string(r->remote_addr_pattern)); } return obj; } json_object * r3_edge_to_json_object(const edge * e) { json_object *obj; obj = json_object_new_object(); json_object_object_add(obj, "pattern", json_object_new_string(e->pattern)); json_object_object_add(obj, "opcode", json_object_new_int(e->opcode)); json_object_object_add(obj, "slug", json_object_new_boolean(e->has_slug)); if (e->child) { json_object *node_obj = r3_node_to_json_object(e->child); json_object_object_add(obj, "child", node_obj); } return obj; } json_object * r3_node_to_json_object(const node * n) { json_object *obj; obj = json_object_new_object(); if (n->combined_pattern) { json_object_object_add(obj, "re", json_object_new_string(n->combined_pattern)); } json_object_object_add(obj, "endpoint", json_object_new_int(n->endpoint)); json_object_object_add(obj, "compare", json_object_new_int(n->compare_type)); int i; if ( n->edge_len > 0 ) { json_object *edges_array = json_object_new_array(); json_object_object_add(obj, "edges", edges_array); for (i = 0 ; i < n->edge_len ; i++ ) { json_object *edge_json_obj = r3_edge_to_json_object(n->edges[i]); json_object_array_add(edges_array, edge_json_obj); } } if ( n->route_len > 0 ) { json_object *routes_array = json_object_new_array(); json_object_object_add(obj, "routes", routes_array); for (i = 0; i < n->route_len; i++ ) { json_object *route_json_obj = r3_route_to_json_object(n->routes[i]); json_object_array_add(routes_array, route_json_obj); } } return obj; } const char * r3_node_to_json_string_ext(const node * n, int options) { json_object *obj = r3_node_to_json_object(n); return json_object_to_json_string_ext(obj, options); } const char * r3_node_to_json_pretty_string(const node * n) { json_object *obj = r3_node_to_json_object(n); return json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED); } const char * r3_node_to_json_string(const node * n) { json_object *obj = r3_node_to_json_object(n); return json_object_to_json_string(obj); } r3-1.3.4/src/list.c000066400000000000000000000044061262260041500137530ustar00rootroot00000000000000/* * list.c Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include #include "r3_list.h" #include "zmalloc.h" /* Naive linked list implementation */ list * list_create() { list *l = (list *) zmalloc(sizeof(list)); l->count = 0; l->head = NULL; l->tail = NULL; pthread_mutex_init(&(l->mutex), NULL); return l; } void list_free(l) list *l; { if (l) { list_item *li, *tmp; pthread_mutex_lock(&(l->mutex)); if (l != NULL) { li = l->head; while (li != NULL) { tmp = li->next; li = tmp; } } pthread_mutex_unlock(&(l->mutex)); pthread_mutex_destroy(&(l->mutex)); zfree(l); } } list_item * list_add_element(list * l, void * ptr) { list_item *li; pthread_mutex_lock(&(l->mutex)); li = (list_item *) zmalloc(sizeof(list_item)); li->value = ptr; li->next = NULL; li->prev = l->tail; if (l->tail == NULL) { l->head = l->tail = li; } else { l->tail = li; } l->count++; pthread_mutex_unlock(&(l->mutex)); return li; } int list_remove_element(l, ptr) list *l; void *ptr; { int result = 0; list_item *li = l->head; pthread_mutex_lock(&(l->mutex)); while (li != NULL) { if (li->value == ptr) { if (li->prev == NULL) { l->head = li->next; } else { li->prev->next = li->next; } if (li->next == NULL) { l->tail = li->prev; } else { li->next->prev = li->prev; } l->count--; zfree(li); result = 1; break; } li = li->next; } pthread_mutex_unlock(&(l->mutex)); return result; } void list_each_element(l, func) list *l; int (*func) (list_item *); { list_item *li; pthread_mutex_lock(&(l->mutex)); li = l->head; while (li != NULL) { if (func(li) == 1) { break; } li = li->next; } pthread_mutex_unlock(&(l->mutex)); } r3-1.3.4/src/match_entry.c000066400000000000000000000013321262260041500153100ustar00rootroot00000000000000/* * match_entry.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include #include #include #include #include #include #include "r3.h" #include "zmalloc.h" match_entry * match_entry_createl(const char * path, int path_len) { match_entry * entry = zmalloc(sizeof(match_entry)); if(!entry) return NULL; entry->vars = str_array_create(3); entry->path = path; entry->path_len = path_len; entry->data = NULL; return entry; } void match_entry_free(match_entry * entry) { assert(entry); if (entry->vars) { str_array_free(entry->vars); } zfree(entry); } r3-1.3.4/src/node.c000066400000000000000000000567201262260041500137330ustar00rootroot00000000000000#include "config.h" #include #include #include #include #include // PCRE #include #include "r3.h" #include "r3_str.h" #include "slug.h" #include "zmalloc.h" #define CHECK_PTR(ptr) if (ptr == NULL) return NULL; // String value as the index http://judy.sourceforge.net/doc/JudySL_3x.htm static int strndiff(char * d1, char * d2, unsigned int n) { char * o = d1; while ( *d1 == *d2 && n-- > 0 ) { d1++; d2++; } return d1 - o; } /* static int strdiff(char * d1, char * d2) { char * o = d1; while( *d1 == *d2 ) { d1++; d2++; } return d1 - o; } */ /** * Create a node object */ node * r3_tree_create(int cap) { node * n = (node*) zmalloc( sizeof(node) ); CHECK_PTR(n); n->edges = (edge**) zmalloc( sizeof(edge*) * cap ); CHECK_PTR(n->edges); n->edge_len = 0; n->edge_cap = cap; n->routes = NULL; n->route_len = 0; n->route_cap = 0; n->endpoint = 0; n->combined_pattern = NULL; n->pcre_pattern = NULL; n->pcre_extra = NULL; n->data = NULL; return n; } void r3_tree_free(node * tree) { for (int i = 0 ; i < tree->edge_len ; i++ ) { if (tree->edges[i]) { r3_edge_free(tree->edges[ i ]); } } zfree(tree->edges); zfree(tree->routes); if (tree->pcre_pattern) { pcre_free(tree->pcre_pattern); } #ifdef PCRE_STUDY_JIT_COMPILE if (tree->pcre_extra) { pcre_free_study(tree->pcre_extra); } #endif zfree(tree->combined_pattern); zfree(tree); tree = NULL; } /** * Connect two node objects, and create an edge object between them. */ edge * r3_node_connectl(node * n, const char * pat, int len, int dupl, node *child) { // find the same sub-pattern, if it does not exist, create one edge * e; e = r3_node_find_edge(n, pat, len); if (e) { return e; } if (dupl) { pat = zstrndup(pat, len); } e = r3_edge_createl(pat, len, child); CHECK_PTR(e); r3_node_append_edge(n, e); return e; } void r3_node_append_edge(node *n, edge *e) { if (n->edges == NULL) { n->edge_cap = 3; n->edges = zmalloc(sizeof(edge) * n->edge_cap); } if (n->edge_len >= n->edge_cap) { n->edge_cap *= 2; edge ** p = zrealloc(n->edges, sizeof(edge) * n->edge_cap); if(p) { n->edges = p; } } n->edges[ n->edge_len++ ] = e; } /** * Find the existing edge with specified pattern (include slug) * * if "pat" is a slug, we should compare with the specified pattern. */ edge * r3_node_find_edge(const node * n, const char * pat, int pat_len) { edge * e; int i; for (i = 0 ; i < n->edge_len ; i++ ) { e = n->edges[i]; // there is a case: "{foo}" vs "{foo:xxx}", // we should return the match result: full-match or partial-match if ( strcmp(e->pattern, pat) == 0 ) { return e; } } return NULL; } int r3_tree_compile(node *n, char **errstr) { int ret = 0; bool use_slug = r3_node_has_slug_edges(n); if ( use_slug ) { if ( (ret = r3_tree_compile_patterns(n, errstr)) ) { return ret; } } else { // use normal text matching... n->combined_pattern = NULL; } for (int i = 0 ; i < n->edge_len ; i++ ) { if ( (ret = r3_tree_compile(n->edges[i]->child, errstr)) ) { return ret; // stop here if error occurs } } return 0; } /** * This function combines ['/foo', '/bar', '/{slug}'] into (/foo)|(/bar)|/([^/]+)} * * Return -1 if error occurs * Return 0 if success */ int r3_tree_compile_patterns(node * n, char **errstr) { edge * e = NULL; char * p; char * cpat = zcalloc(sizeof(char) * 64 * 3); // XXX if (!cpat) { asprintf(errstr, "Can not allocate memory"); return -1; } p = cpat; int opcode_cnt = 0; int i = 0; for (; i < n->edge_len ; i++) { e = n->edges[i]; if (e->opcode) { opcode_cnt++; } if (e->has_slug) { // compile "foo/{slug}" to "foo/[^/]+" char * slug_pat = r3_slug_compile(e->pattern, e->pattern_len); strcat(p, slug_pat); } else { strncat(p,"^(", 2); p += 2; strncat(p, e->pattern, e->pattern_len); p += e->pattern_len; strncat(p++,")", 1); } if ( i + 1 < n->edge_len && n->edge_len > 1 ) { strncat(p++,"|",1); } } info("pattern: %s\n",cpat); // if all edges use opcode, we should skip the combined_pattern. if ( opcode_cnt == n->edge_len ) { // zfree(cpat); n->compare_type = NODE_COMPARE_OPCODE; } else { n->compare_type = NODE_COMPARE_PCRE; } n->combined_pattern = cpat; const char *pcre_error; int pcre_erroffset; unsigned int option_bits = 0; n->ov_cnt = (1 + n->edge_len) * 3; if (n->pcre_pattern) { pcre_free(n->pcre_pattern); } n->pcre_pattern = pcre_compile( n->combined_pattern, /* the pattern */ option_bits, /* default options */ &pcre_error, /* for error message */ &pcre_erroffset, /* for error offset */ NULL); /* use default character tables */ if (n->pcre_pattern == NULL) { if (errstr) { asprintf(errstr, "PCRE compilation failed at offset %d: %s, pattern: %s", pcre_erroffset, pcre_error, n->combined_pattern); } return -1; } #ifdef PCRE_STUDY_JIT_COMPILE if (n->pcre_extra) { pcre_free_study(n->pcre_extra); } n->pcre_extra = pcre_study(n->pcre_pattern, 0, &pcre_error); if (n->pcre_extra == NULL) { if (errstr) { asprintf(errstr, "PCRE study failed at offset %s, pattern: %s", pcre_error, n->combined_pattern); } return -1; } #endif return 0; } /** * This function matches the URL path and return the left node * * r3_tree_matchl returns NULL when the path does not match. returns *node when the path matches. * * @param node n the root of the tree * @param char* path the URL path to dispatch * @param int path_len the length of the URL path. * @param match_entry* entry match_entry is used for saving the captured dynamic strings from pcre result. */ node * r3_tree_matchl(const node * n, const char * path, int path_len, match_entry * entry) { info("try matching: %s\n", path); edge *e; unsigned int i; unsigned int restlen; const char *pp; const char *pp_end; if (n->compare_type == NODE_COMPARE_OPCODE) { pp_end = path + path_len; for (i = n->edge_len; i--; ) { pp = path; e = n->edges[i]; switch(e->opcode) { case OP_EXPECT_NOSLASH: while (*pp != '/' && pp < pp_end) pp++; break; case OP_EXPECT_MORE_ALPHA: while ( isalpha(*pp) && pp < pp_end) pp++; break; case OP_EXPECT_MORE_DIGITS: while ( isdigit(*pp) && pp < pp_end) pp++; break; case OP_EXPECT_MORE_WORDS: while ( (isdigit(*pp) || isalpha(*pp)) && pp < pp_end) pp++; break; case OP_EXPECT_NODASH: while (*pp != '-' && pp < pp_end) pp++; break; } // check match if ( (pp - path) > 0) { if (entry) { str_array_append(entry->vars , zstrndup(path, pp - path)); } restlen = pp_end - pp; if (restlen == 0) { return e->child && e->child->endpoint > 0 ? e->child : NULL; } return r3_tree_matchl(e->child, pp, restlen, entry); } } } // if the pcre_pattern is found, and the pointer is not NULL, then it's // pcre pattern node, we use pcre_exec to match the nodes if (n->pcre_pattern) { const char *substring_start = NULL; int substring_length = 0; int ov[ n->ov_cnt ]; int rc; info("pcre matching %s on %s\n", n->combined_pattern, path); rc = pcre_exec( n->pcre_pattern, /* the compiled pattern */ n->pcre_extra, path, /* the subject string */ path_len, /* the length of the subject */ 0, /* start at offset 0 in the subject */ 0, /* default options */ ov, /* output vector for substring information */ n->ov_cnt); /* number of elements in the output vector */ // does not match all edges, return NULL; if (rc < 0) { #ifdef DEBUG printf("pcre rc: %d\n", rc ); switch(rc) { case PCRE_ERROR_NOMATCH: printf("pcre: no match '%s' on pattern '%s'\n", path, n->combined_pattern); break; // Handle other special cases if you like default: printf("pcre matching error '%d' '%s' on pattern '%s'\n", rc, path, n->combined_pattern); break; } #endif return NULL; } restlen = path_len - ov[1]; // if it's fully matched to the end (rest string length) if (restlen == 0 ) { // Check the substring to decide we should go deeper on which edge for (i = 1; i < rc; i++) { substring_length = ov[2*i+1] - ov[2*i]; // if it's not matched for this edge, just skip them quickly if (substring_length == 0) continue; substring_start = path + ov[2*i]; e = n->edges[i - 1]; if (entry && e->has_slug) { // append captured token to entry str_array_append(entry->vars , zstrndup(substring_start, substring_length)); } // since restlen == 0 return the edge quickly. return e->child && e->child->endpoint > 0 ? e->child : NULL; } } // Check the substring to decide we should go deeper on which edge for (i = 1; i < rc; i++) { substring_length = ov[2*i+1] - ov[2*i]; // if it's not matched for this edge, just skip them quickly if ( substring_length == 0) { continue; } substring_start = path + ov[2*i]; e = n->edges[i - 1]; if (entry && e->has_slug) { // append captured token to entry str_array_append(entry->vars , zstrndup(substring_start, substring_length)); } // get the length of orginal string: $0 return r3_tree_matchl( e->child, path + (ov[1] - ov[0]), restlen, entry); } // does not match return NULL; } if ( (e = r3_node_find_edge_str(n, path, path_len)) != NULL ) { restlen = path_len - e->pattern_len; if (restlen == 0) { return e->child && e->child->endpoint > 0 ? e->child : NULL; } return r3_tree_matchl(e->child, path + e->pattern_len, restlen, entry); } return NULL; } route * r3_tree_match_route(const node *tree, match_entry * entry) { node *n; int i; n = r3_tree_match_entry(tree, entry); if (n && n->routes && n->route_len > 0) { for (i = n->route_len; i--; ) { if ( r3_route_cmp(n->routes[i], entry) == 0 ) { return n->routes[i]; } } } return NULL; } inline edge * r3_node_find_edge_str(const node * n, const char * str, int str_len) { char firstbyte = *str; unsigned int i; for (i = n->edge_len; i--; ) { edge *e = n->edges[i]; if (firstbyte == e->pattern[0]) { if (strncmp(e->pattern, str, e->pattern_len) == 0 ) { return n->edges[i]; } return NULL; } } return NULL; } node * r3_node_create() { node * n = (node*) zmalloc( sizeof(node) ); CHECK_PTR(n); n->edges = NULL; n->edge_len = 0; n->edge_cap = 0; n->routes = NULL; n->route_len = 0; n->route_cap = 0; n->endpoint = 0; n->combined_pattern = NULL; n->pcre_pattern = NULL; n->pcre_extra = NULL; n->data = NULL; return n; } void r3_route_free(route * route) { zfree(route); } route * r3_route_createl(const char * path, int path_len) { route * info = zmalloc(sizeof(route)); CHECK_PTR(info); info->path = (char*) path; info->path_len = path_len; info->request_method = 0; // can be (GET || POST) info->data = NULL; info->host = NULL; // required host name info->host_len = 0; info->remote_addr_pattern = NULL; info->remote_addr_pattern_len = 0; return info; } /** * Helper function for creating routes from request URI path and request method * * method (int): METHOD_GET, METHOD_POST, METHOD_PUT, METHOD_DELETE ... */ route * r3_tree_insert_routel_ex(node *tree, int method, const char *path, int path_len, void *data, char **errstr) { route *r = r3_route_createl(path, path_len); CHECK_PTR(r); r->request_method = method; // ALLOW GET OR POST METHOD node * ret = r3_tree_insert_pathl_ex(tree, path, path_len, r, data, errstr); if (!ret) { // failed insert r3_route_free(r); return NULL; } return r; } /** * Find common prefix from the edges of the node. * * Some cases of the common prefix: * * 1. "/foo/{slug}" vs "/foo/bar" => common prefix = "/foo/" * 2. "{slug}/hate" vs "{slug}/bar" => common prefix = "{slug}/" * 2. "/z/{slug}/hate" vs "/z/{slog}/bar" => common prefix = "/z/" * 3. "{slug:xxx}/hate" vs "{slug:yyy}/bar" => common prefix = "" * 4. "aaa{slug:xxx}/hate" vs "aab{slug:yyy}/bar" => common prefix = "aa" * 5. "/foo/{slug}/hate" vs "/fo{slug}/bar" => common prefix = "/fo" */ edge * r3_node_find_common_prefix(node *n, const char *path, int path_len, int *prefix_len, char **errstr) { int i = 0; int prefix = 0; *prefix_len = 0; edge *e = NULL; for(i = 0 ; i < n->edge_len ; i++ ) { // ignore all edges with slug prefix = strndiff( (char*) path, n->edges[i]->pattern, n->edges[i]->pattern_len); // no common, consider insert a new edge if ( prefix > 0 ) { e = n->edges[i]; break; } } // found common prefix edge if (prefix > 0) { r3_slug_t *slug; int ret = 0; const char *offset = path; const char *p = path + prefix; slug = r3_slug_new(path, path_len); do { ret = r3_slug_parse(slug, path, path_len, offset, errstr); // found slug if (ret == 1) { // inside slug, backtrace to the begin of the slug if ( p >= slug->begin && p <= slug->end ) { prefix = slug->begin - path - 1; break; } else if ( p < slug->begin ) { break; } else if ( p >= slug->end && p < (path + path_len) ) { offset = slug->end + 1; prefix = p - path; continue; } else { break; } } else if (ret == -1) { r3_slug_free(slug); return NULL; } else { break; } } while(ret == 1); // free the slug r3_slug_free(slug); } *prefix_len = prefix; return e; } /** * Return the last inserted node. */ node * r3_tree_insert_pathl_ex(node *tree, const char *path, int path_len, route * route, void * data, char **errstr) { node * n = tree; // common edge edge * e = NULL; // If there is no path to insert at the node, we just increase the mount // point on the node and append the route. if (path_len == 0) { tree->endpoint++; if (route) { route->data = data; r3_node_append_route(tree, route); } return tree; } /* length of common prefix */ int prefix_len = 0; char *err = NULL; e = r3_node_find_common_prefix(tree, path, path_len, &prefix_len, &err); if (err) { // copy the error message pointer if (errstr) *errstr = err; return NULL; } const char * subpath = path + prefix_len; const int subpath_len = path_len - prefix_len; // common prefix not found, insert a new edge for this pattern if ( prefix_len == 0 ) { // there are two more slugs, we should break them into several parts int slug_cnt = r3_slug_count(path, path_len, errstr); if (slug_cnt == -1) { return NULL; } if ( slug_cnt > 1 ) { int slug_len; char *p = r3_slug_find_placeholder(path, &slug_len); #ifdef DEBUG assert(p); #endif // find the next one '{', then break there if(p) { p = r3_slug_find_placeholder(p + slug_len + 1, NULL); } #ifdef DEBUG assert(p); #endif // insert the first one edge, and break at "p" node * child = r3_tree_create(3); CHECK_PTR(child); r3_node_connect(n, zstrndup(path, (int)(p - path)), child); // and insert the rest part to the child return r3_tree_insert_pathl_ex(child, p, path_len - (int)(p - path), route, data, errstr); } else { if (slug_cnt == 1) { // there is one slug, let's see if it's optimiz-able by opcode int slug_len = 0; char *slug_p = r3_slug_find_placeholder(path, &slug_len); int slug_pattern_len = 0; char *slug_pattern = r3_slug_find_pattern(slug_p, &slug_pattern_len); int opcode = 0; // if there is a pattern defined. if (slug_pattern_len) { char *cpattern = r3_slug_compile(slug_pattern, slug_pattern_len); opcode = r3_pattern_to_opcode(cpattern, strlen(cpattern)); zfree(cpattern); } else { opcode = OP_EXPECT_NOSLASH; } // if the slug starts after one+ charactor, for example foo{slug} node *c1; if (slug_p > path) { c1 = r3_tree_create(3); CHECK_PTR(c1); r3_node_connectl(n, path, slug_p - path, 1, c1); // duplicate } else { c1 = n; } node * c2 = r3_tree_create(3); CHECK_PTR(c2); edge * op_edge = r3_node_connectl(c1, slug_p, slug_len , 1, c2); if(opcode) { op_edge->opcode = opcode; } int restlen = path_len - ((slug_p - path) + slug_len); if (restlen) { return r3_tree_insert_pathl_ex(c2, slug_p + slug_len, restlen, route, data, errstr); } c2->data = data; c2->endpoint++; if (route) { route->data = data; r3_node_append_route(c2, route); } return c2; } // only one slug node * child = r3_tree_create(3); CHECK_PTR(child); child->endpoint++; if (data) child->data = data; r3_node_connectl(n, path, path_len, 1, child); if (route) { route->data = data; r3_node_append_route(child, route); } return child; } } else if ( prefix_len == e->pattern_len ) { // fully-equal to the pattern of the edge // there are something more we can insert if ( subpath_len > 0 ) { return r3_tree_insert_pathl_ex(e->child, subpath, subpath_len, route, data, errstr); } else { // there are no more path to insert // see if there is an endpoint already, we should n't overwrite the data on child. // but we still need to append the route. if (route) { route->data = data; r3_node_append_route(e->child, route); e->child->endpoint++; // make it as an endpoint return e->child; } // insertion without route if (e->child->endpoint > 0) { // TODO: return an error code instead of NULL return NULL; } e->child->endpoint++; // make it as an endpoint e->child->data = data; // set data return e->child; } } else if ( prefix_len < e->pattern_len ) { /* it's partially matched with the pattern, * we should split the end point and make a branch here... */ r3_edge_branch(e, prefix_len); return r3_tree_insert_pathl_ex(e->child, subpath, subpath_len, route , data, errstr); } else { fprintf(stderr, "unexpected route."); return NULL; } return n; } bool r3_node_has_slug_edges(const node *n) { bool found = FALSE; edge *e; for ( int i = 0 ; i < n->edge_len ; i++ ) { e = n->edges[i]; e->has_slug = r3_path_contains_slug_char(e->pattern); if (e->has_slug) found = TRUE; } return found; } void r3_tree_dump(const node * n, int level) { print_indent(level); printf("(o)"); if ( n->combined_pattern ) { printf(" regexp:%s", n->combined_pattern); } printf(" endpoint:%d", n->endpoint); if (n->data) { printf(" data:%p", n->data); } printf("\n"); for ( int i = 0 ; i < n->edge_len ; i++ ) { edge * e = n->edges[i]; print_indent(level + 1); printf("|-\"%s\"", e->pattern); if (e->opcode ) { printf(" opcode:%d", e->opcode); } if ( e->child ) { printf("\n"); r3_tree_dump( e->child, level + 1); } printf("\n"); } } /** * return 0 == equal * * -1 == different route */ inline int r3_route_cmp(const route *r1, const match_entry *r2) { if (r1->request_method != 0) { if (0 == (r1->request_method & r2->request_method) ) { return -1; } } if ( r1->host && r2->host ) { if (strcmp(r1->host, r2->host) != 0 ) { return -1; } } if (r1->remote_addr_pattern) { /* * XXX: consider "netinet/in.h" if (r2->remote_addr) { inet_addr(r2->remote_addr); } */ if ( strcmp(r1->remote_addr_pattern, r2->remote_addr) != 0 ) { return -1; } } return 0; } /** * */ void r3_node_append_route(node * n, route * r) { if (n->routes == NULL) { n->route_cap = 3; n->routes = zmalloc(sizeof(route) * n->route_cap); } if (n->route_len >= n->route_cap) { n->route_cap *= 2; n->routes = zrealloc(n->routes, sizeof(route) * n->route_cap); } n->routes[ n->route_len++ ] = r; } r3-1.3.4/src/slug.c000066400000000000000000000100201262260041500137370ustar00rootroot00000000000000/* * slug.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include "r3.h" #include "r3_str.h" #include "slug.h" #include "zmalloc.h" r3_slug_t * r3_slug_new(const char * path, int path_len) { r3_slug_t * s = zmalloc(sizeof(r3_slug_t)); if (!s) return NULL; s->path = (char*) path; s->path_len = path_len; s->begin = NULL; s->end = NULL; s->len = 0; s->pattern = NULL; s->pattern_len = 0; return s; } void r3_slug_free(r3_slug_t * s) { zfree(s); } /** * Return 1 means OK * Return 0 means Empty * Return -1 means Error */ int r3_slug_check(r3_slug_t *s) { // if it's empty if (s->begin == NULL && s->len == 0) { return 0; } if (s->begin && s->begin == s->end && s->len == 0) { return 0; } // if the head is defined, we should also have end pointer if (s->begin && s->end == NULL) { return -1; } return 0; } char * r3_slug_to_str(const r3_slug_t *s) { char *str = NULL; asprintf(&str, "slug: '%.*s', pattern: '%.*s', path: '%.*s'", s->len, s->begin, s->pattern_len, s->pattern, s->path_len, s->path); return str; } /* r3_slug_t * r3_slug_parse_next(r3_slug_t *s, char **errstr) { return r3_slug_parse(s->end, s->path_len - (s->end - s->begin), errstr); } Return 0 => Empty, slug not found Return 1 => Slug found Return -1 => Slug parsing error */ int r3_slug_parse(r3_slug_t *s, const char *needle, int needle_len, const char *offset, char **errstr) { s->path = (char*) needle; s->path_len = needle_len; if (offset == NULL) { offset = (char*) needle; // from the begining of the needle } // there is no slug if (!r3_path_contains_slug_char(offset)) { return 0; } int cnt = 0; int state = 0; const char * p = offset; while( (p-needle) < needle_len) { // escape one character if (*p == '\\' ) { p++; p++; continue; } // slug starts with '{' if (state == 0 && *p == '{') { s->begin = ++p; state++; continue; } // in the middle of the slug (pattern) if (state == 1 && *p == ':') { // start from next s->pattern = ++p; continue; } // slug closed. if (state == 1 && *p == '}') { s->end = p; s->len = s->end - s->begin; if (s->pattern) { s->pattern_len = p - s->pattern; } cnt++; state--; p++; break; } // might be inside the pattern if ( *p == '{' ) { state++; } else if ( *p == '}' ) { state--; } p++; }; if (state != 0) { if (errstr) { char *err = NULL; asprintf(&err, "Incomplete slug pattern. PATH (%d): '%s', OFFSET: %ld, STATE: %d", needle_len, needle, p - needle, state); *errstr = err; } return -1; } info("found slug\n"); return 1; } /** * provide a quick way to count slugs, simply search for '{' */ int r3_slug_count(const char * needle, int len, char **errstr) { int cnt = 0; int state = 0; char * p = (char*) needle; while( (p-needle) < len) { if (*p == '\\' ) { p++; p++; continue; } if (state == 1 && *p == '}') { cnt++; } if ( *p == '{' ) { state++; } else if ( *p == '}' ) { state--; } p++; }; info("FOUND PATTERN: '%s' (%d), STATE: %d\n", needle, len, state); if (state != 0) { if (errstr) { char *err = NULL; asprintf(&err, "Incomplete slug pattern. PATTERN (%d): '%s', OFFSET: %ld, STATE: %d", len, needle, p - needle, state); *errstr = err; } return -1; } return cnt; } r3-1.3.4/src/slug.h000066400000000000000000000017611262260041500137600ustar00rootroot00000000000000/* * slug.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef R3_SLUG_H #define R3_SLUG_H typedef struct { /** * source path */ const char * path; int path_len; /** * slug start pointer */ const char * begin; /** * slug end pointer */ const char * end; /** * slug length */ int len; // slug pattern pointer if we have one const char * pattern; // the length of custom pattern, if the pattern is found. int pattern_len; } r3_slug_t; r3_slug_t * r3_slug_new(const char * path, int path_len); int r3_slug_check(r3_slug_t *s); int r3_slug_parse(r3_slug_t *s, const char *needle, int needle_len, const char *offset, char **errstr); char * r3_slug_to_str(const r3_slug_t *s); void r3_slug_free(r3_slug_t * s); static inline int r3_path_contains_slug_char(const char * str) { return strchr(str, '{') != NULL ? 1 : 0; } #endif /* !SLUG_H */ r3-1.3.4/src/str.c000066400000000000000000000122631262260041500136100ustar00rootroot00000000000000/* * str.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include #include "r3.h" #include "r3_str.h" #include "slug.h" #include "zmalloc.h" int r3_pattern_to_opcode(const char * pattern, int len) { if ( strncmp(pattern, "\\w+",len) == 0 ) { return OP_EXPECT_MORE_WORDS; } if ( strncmp(pattern, "[0-9a-z]+",len) == 0 || strncmp(pattern, "[a-z0-9]+",len) == 0 ) { return OP_EXPECT_MORE_WORDS; } if ( strncmp(pattern, "[a-z]+",len) == 0 ) { return OP_EXPECT_MORE_ALPHA; } if ( strncmp(pattern, "\\d+", len) == 0 ) { return OP_EXPECT_MORE_DIGITS; } if ( strncmp(pattern, "[0-9]+", len) == 0 ) { return OP_EXPECT_MORE_DIGITS; } if ( strncmp(pattern, "[^/]+", len) == 0 ) { return OP_EXPECT_NOSLASH; } if ( strncmp(pattern, "[^-]+", len) == 0 ) { return OP_EXPECT_NODASH; } return 0; } char * r3_inside_slug(const char * needle, int needle_len, char *offset, char **errstr) { char * s1 = offset; char * s2 = offset; short found_s1 = 0; short found_s2 = 0; while( s1 >= needle && (s1 - needle < needle_len) ) { if ( *s1 == '{' ) { found_s1 = 1; break; } s1--; } const char * end = needle + needle_len; while( (s2 + 1) < end ) { if ( *s2 == '}' ) { found_s2 = 1; break; } s2++; } if (found_s1 && found_s2) { return s1; } if (found_s1 || found_s2) { // wrong slug pattern if(errstr) { asprintf(errstr, "Incomplete slug pattern"); } return NULL; } return NULL; } char * r3_slug_find_placeholder(const char *s1, int *len) { char *c; char *s2; int cnt = 0; if ( NULL != (c = strchr(s1, '{')) ) { // find closing '}' s2 = c; while(*s2) { if (*s2 == '{' ) cnt++; else if (*s2 == '}' ) cnt--; if (cnt == 0) break; s2++; } } else { return NULL; } if (cnt!=0) { return NULL; } if(len) { *len = s2 - c + 1; } return c; } /** * given a slug string, duplicate the pattern string of the slug */ char * r3_slug_find_pattern(const char *s1, int *len) { char *c; char *s2; int cnt = 1; if ( NULL != (c = strchr(s1, ':')) ) { c++; // find closing '}' s2 = c; while(s2) { if (*s2 == '{' ) cnt++; else if (*s2 == '}' ) cnt--; if (cnt == 0) break; s2++; } } else { return NULL; } *len = s2 - c; return c; } /** * given a slug string, duplicate the parameter name string of the slug */ char * r3_slug_find_name(const char *s1, int *len) { char *c; char *s2; int cnt = 0; c = s1; while(1) { if(*c == '{') cnt++; if(*c == '}') cnt--; if(*c == ':') break; if(*c == '\0') return NULL; if(cnt == 0) break; c++; } // find starting '{' s2 = c; while(1) { if ( *s2 == '{' ) break; s2--; } s2++; *len = c - s2; return s2; } /** * @param char * sep separator */ char * r3_slug_compile(const char * str, int len) { char *s1 = NULL, *o = NULL; char *pat = NULL; char sep = '/'; // append prefix int s1_len; s1 = r3_slug_find_placeholder(str, &s1_len); if ( s1 == NULL ) { return zstrdup(str); } char * out = NULL; if ((out = zcalloc(sizeof(char) * 200)) == NULL) { return (NULL); } o = out; strncat(o, "^", 1); o++; strncat(o, str, s1 - str); // string before slug o += (s1 - str); int pat_len; pat = r3_slug_find_pattern(s1, &pat_len); if (pat) { *o = '('; o++; strncat(o, pat, pat_len ); o += pat_len; *o = ')'; o++; } else { sprintf(o, "([^%c]+)", sep); o+= strlen("([^*]+)"); } s1 += s1_len; strncat(o, s1, strlen(s1)); return out; } char * ltrim_slash(char* str) { char * p = str; while (*p == '/') p++; return zstrdup(p); } void str_repeat(char *s, const char *c, int len) { while(len--) { s[len - 1] = *c; } } void print_indent(int level) { int len = level * 2; while(len--) { printf(" "); } } #ifndef HAVE_STRDUP char *zstrdup(const char *s) { char *out; int count = 0; while( s[count] ) ++count; ++count; out = zmalloc(sizeof(char) * count); out[--count] = 0; while( --count >= 0 ) out[count] = s[count]; return out; } #endif #ifndef HAVE_STRNDUP char *zstrndup(const char *s, int n) { char *out; int count = 0; while( count < n && s[count] ) ++count; ++count; out = zmalloc(sizeof(char) * count); out[--count] = 0; while( --count >= 0 ) out[count] = s[count]; return out; } #endif r3-1.3.4/src/token.c000066400000000000000000000027401262260041500141170ustar00rootroot00000000000000/* * token.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include #include #include #include #include "r3.h" #include "r3_str.h" #include "str_array.h" #include "zmalloc.h" str_array * str_array_create(int cap) { str_array * list = (str_array*) zmalloc( sizeof(str_array) ); if (!list) return NULL; list->len = 0; list->cap = cap; list->tokens = (char**) zmalloc( sizeof(char*) * cap); return list; } void str_array_free(str_array *l) { assert(l); for ( int i = 0; i < l->len ; i++ ) { if (l->tokens[ i ]) { zfree(l->tokens[i]); } } zfree(l->tokens); zfree(l); } bool str_array_is_full(const str_array * l) { return l->len >= l->cap; } bool str_array_resize(str_array * l, int new_cap) { l->tokens = zrealloc(l->tokens, sizeof(char**) * new_cap); l->cap = new_cap; return l->tokens != NULL; } bool str_array_append(str_array * l, char * token) { if ( str_array_is_full(l) ) { bool ret = str_array_resize(l, l->cap + 20); if (ret == FALSE ) { return FALSE; } } l->tokens[ l->len++ ] = token; return TRUE; } void str_array_dump(const str_array *l) { printf("["); for ( int i = 0; i < l->len ; i++ ) { printf("\"%s\"", l->tokens[i] ); if ( i + 1 != l->len ) { printf(", "); } } printf("]\n"); } r3-1.3.4/tests/000077500000000000000000000000001262260041500132035ustar00rootroot00000000000000r3-1.3.4/tests/CMakeLists.txt000066400000000000000000000015231262260041500157440ustar00rootroot00000000000000# set(TEST_LIBS ${TEST_LIBS} ${CHECK_LIBRARIES} judy libr3) # set(TEST_LIBS ${TEST_LIBS} ${CHECK_LIBRARIES} judy libr3) include_directories("${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}") find_package(Check REQUIRED) find_package(PCRE REQUIRED) # find_package(Judy REQUIRED) if (NOT CHECK_FOUND) message(STATUS "Skipping unit tests, Check library not found!") else (NOT CHECK_FOUND) set(TEST_LIBS ${LIBS} ${CHECK_LIBRARIES} ${PCRE_LIBRARIES} r3) include_directories(${CHECK_INCLUDE_DIRS}) # include_directories("${PROJECT_SOURCE_DIR}/include/r2") add_executable(check_tree check_tree.c) target_link_libraries(check_tree ${TEST_LIBS}) add_custom_command( TARGET check_tree POST_BUILD COMMENT "Running unit tests" COMMAND check_tree ) endif (NOT CHECK_FOUND) r3-1.3.4/tests/Makefile.am000066400000000000000000000020461262260041500152410ustar00rootroot00000000000000TESTS = AM_CFLAGS=$(DEPS_CFLAGS) $(GVC_DEPS_CFLAGS) $(JSONC_CFLAGS) @CHECK_CFLAGS@ -I$(top_builddir) -I$(top_builddir)/include -I$(top_builddir)/src -I$(top_builddir)/3rdparty -Wall -std=c99 -ggdb -Wall AM_LDFLAGS=$(DEPS_LIBS) $(GVC_DEPS_LIBS) $(JSONC_LIBS) @CHECK_LIBS@ $(top_builddir)/libr3.la if USE_JEMALLOC AM_CFLAGS += -ljemalloc endif noinst_HEADERS = \ bench.h \ $(NULL) dist_noinst_DATA = \ $(NULL) TESTS += check_slug check_slug_SOURCES = check_slug.c TESTS += check_tree check_tree_SOURCES = check_tree.c TESTS += check_routes check_routes_SOURCES = check_routes.c TESTS += check_str_array check_str_array_SOURCES = check_str_array.c if ENABLE_JSON TESTS += check_json check_json_SOURCES = check_json.c endif if ENABLE_GRAPHVIZ TESTS += check_gvc check_gvc_SOURCES = check_gvc.c endif check_PROGRAMS = $(TESTS) noinst_PROGRAMS = bench bench_SOURCES = bench.c # AM_CFLAGS=$(DEPS_CFLAGS) -I$(top_builddir)/include # AM_CFLAGS=$(DEPS_CFLAGS) -I$(top_builddir) -I$(top_builddir)/include CLEANFILES = check_tree.log r3-1.3.4/tests/bench.c000066400000000000000000000472041262260041500144350ustar00rootroot00000000000000/* * bench.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include #include /* va_list, va_start, va_arg, va_end */ #include "r3.h" #include "r3_str.h" #include "zmalloc.h" #include "bench.h" unsigned long unixtime() { struct timeval tp; if (gettimeofday((struct timeval *) &tp, (NULL)) == 0) { return tp.tv_sec; } return 0; } double microtime() { struct timeval tp; long sec = 0L; double msec = 0.0; if (gettimeofday((struct timeval *) &tp, (NULL)) == 0) { msec = (double) (tp.tv_usec / MICRO_IN_SEC); sec = tp.tv_sec; if (msec >= 1.0) msec -= (long) msec; return sec + msec; } return 0; } void bench_start(bench *b) { b->start = microtime(); } void bench_stop(bench *b) { b->end = microtime(); } double bench_iteration_speed(bench *b) { return (b->N * b->R) / (b->end - b->start); } double bench_duration(bench *b) { return (b->end - b->start); } void bench_print_summary(bench *b) { printf("%ld runs, ", b->R); printf("%ld iterations each run, ", b->N); printf("finished in %lf seconds\n", bench_duration(b) ); printf("%.2f i/sec\n", bench_iteration_speed(b) ); } /** * Combine multiple benchmark result into one measure entry. * * bench_append_csv("benchmark.csv", 3, &b1, &b2) */ void bench_append_csv(char *filename, int countOfB, ...) { FILE *fp = fopen(filename, "a+"); if(!fp) { return; } unsigned long ts = unixtime(); fprintf(fp, "%ld", ts); int i; bench * b; va_list vl; va_start(vl,countOfB); for (i=0 ; i < countOfB ; i++) { b = va_arg(vl, bench*); fprintf(fp, ",%.2f", bench_iteration_speed(b) ); } va_end(vl); fprintf(fp, "\n"); fclose(fp); } int main() { node * n = r3_tree_create(1); int route_data = 999; r3_tree_insert_path(n, "/foo/bar/baz", NULL); r3_tree_insert_path(n, "/foo/bar/qux", NULL); r3_tree_insert_path(n, "/foo/bar/quux", NULL); r3_tree_insert_path(n, "/foo/bar/corge", NULL); r3_tree_insert_path(n, "/foo/bar/grault", NULL); r3_tree_insert_path(n, "/foo/bar/garply", NULL); r3_tree_insert_path(n, "/foo/baz/bar", NULL); r3_tree_insert_path(n, "/foo/baz/qux", NULL); r3_tree_insert_path(n, "/foo/baz/quux", NULL); r3_tree_insert_path(n, "/foo/baz/corge", NULL); r3_tree_insert_path(n, "/foo/baz/grault", NULL); r3_tree_insert_path(n, "/foo/baz/garply", NULL); r3_tree_insert_path(n, "/foo/qux/bar", NULL); r3_tree_insert_path(n, "/foo/qux/baz", NULL); r3_tree_insert_path(n, "/foo/qux/quux", NULL); r3_tree_insert_path(n, "/foo/qux/corge", NULL); r3_tree_insert_path(n, "/foo/qux/grault", NULL); r3_tree_insert_path(n, "/foo/qux/garply", NULL); r3_tree_insert_path(n, "/foo/quux/bar", NULL); r3_tree_insert_path(n, "/foo/quux/baz", NULL); r3_tree_insert_path(n, "/foo/quux/qux", NULL); r3_tree_insert_path(n, "/foo/quux/corge", NULL); r3_tree_insert_path(n, "/foo/quux/grault", NULL); r3_tree_insert_path(n, "/foo/quux/garply", NULL); r3_tree_insert_path(n, "/foo/corge/bar", NULL); r3_tree_insert_path(n, "/foo/corge/baz", NULL); r3_tree_insert_path(n, "/foo/corge/qux", NULL); r3_tree_insert_path(n, "/foo/corge/quux", NULL); r3_tree_insert_path(n, "/foo/corge/grault", NULL); r3_tree_insert_path(n, "/foo/corge/garply", NULL); r3_tree_insert_path(n, "/foo/grault/bar", NULL); r3_tree_insert_path(n, "/foo/grault/baz", NULL); r3_tree_insert_path(n, "/foo/grault/qux", NULL); r3_tree_insert_path(n, "/foo/grault/quux", NULL); r3_tree_insert_path(n, "/foo/grault/corge", NULL); r3_tree_insert_path(n, "/foo/grault/garply", NULL); r3_tree_insert_path(n, "/foo/garply/bar", NULL); r3_tree_insert_path(n, "/foo/garply/baz", NULL); r3_tree_insert_path(n, "/foo/garply/qux", NULL); r3_tree_insert_path(n, "/foo/garply/quux", NULL); r3_tree_insert_path(n, "/foo/garply/corge", NULL); r3_tree_insert_path(n, "/foo/garply/grault", NULL); r3_tree_insert_path(n, "/bar/foo/baz", NULL); r3_tree_insert_path(n, "/bar/foo/qux", NULL); r3_tree_insert_path(n, "/bar/foo/quux", NULL); r3_tree_insert_path(n, "/bar/foo/corge", NULL); r3_tree_insert_path(n, "/bar/foo/grault", NULL); r3_tree_insert_path(n, "/bar/foo/garply", NULL); r3_tree_insert_path(n, "/bar/baz/foo", NULL); r3_tree_insert_path(n, "/bar/baz/qux", NULL); r3_tree_insert_path(n, "/bar/baz/quux", NULL); r3_tree_insert_path(n, "/bar/baz/corge", NULL); r3_tree_insert_path(n, "/bar/baz/grault", NULL); r3_tree_insert_path(n, "/bar/baz/garply", NULL); r3_tree_insert_path(n, "/bar/qux/foo", NULL); r3_tree_insert_path(n, "/bar/qux/baz", NULL); r3_tree_insert_path(n, "/bar/qux/quux", NULL); r3_tree_insert_path(n, "/bar/qux/corge", NULL); r3_tree_insert_path(n, "/bar/qux/grault", NULL); r3_tree_insert_path(n, "/bar/qux/garply", NULL); r3_tree_insert_path(n, "/bar/quux/foo", NULL); r3_tree_insert_path(n, "/bar/quux/baz", NULL); r3_tree_insert_path(n, "/bar/quux/qux", NULL); r3_tree_insert_path(n, "/bar/quux/corge", NULL); r3_tree_insert_path(n, "/bar/quux/grault", NULL); r3_tree_insert_path(n, "/bar/quux/garply", NULL); r3_tree_insert_path(n, "/bar/corge/foo", NULL); r3_tree_insert_path(n, "/bar/corge/baz", NULL); r3_tree_insert_path(n, "/bar/corge/qux", NULL); r3_tree_insert_path(n, "/bar/corge/quux", NULL); r3_tree_insert_path(n, "/bar/corge/grault", NULL); r3_tree_insert_path(n, "/bar/corge/garply", NULL); r3_tree_insert_path(n, "/bar/grault/foo", NULL); r3_tree_insert_path(n, "/bar/grault/baz", NULL); r3_tree_insert_path(n, "/bar/grault/qux", NULL); r3_tree_insert_path(n, "/bar/grault/quux", NULL); r3_tree_insert_path(n, "/bar/grault/corge", NULL); r3_tree_insert_path(n, "/bar/grault/garply", NULL); r3_tree_insert_path(n, "/bar/garply/foo", NULL); r3_tree_insert_path(n, "/bar/garply/baz", NULL); r3_tree_insert_path(n, "/bar/garply/qux", NULL); r3_tree_insert_path(n, "/bar/garply/quux", NULL); r3_tree_insert_path(n, "/bar/garply/corge", NULL); r3_tree_insert_path(n, "/bar/garply/grault", NULL); r3_tree_insert_path(n, "/baz/foo/bar", NULL); r3_tree_insert_path(n, "/baz/foo/qux", NULL); r3_tree_insert_path(n, "/baz/foo/quux", NULL); r3_tree_insert_path(n, "/baz/foo/corge", NULL); r3_tree_insert_path(n, "/baz/foo/grault", NULL); r3_tree_insert_path(n, "/baz/foo/garply", NULL); r3_tree_insert_path(n, "/baz/bar/foo", NULL); r3_tree_insert_path(n, "/baz/bar/qux", NULL); r3_tree_insert_path(n, "/baz/bar/quux", NULL); r3_tree_insert_path(n, "/baz/bar/corge", NULL); r3_tree_insert_path(n, "/baz/bar/grault", NULL); r3_tree_insert_path(n, "/baz/bar/garply", NULL); r3_tree_insert_path(n, "/baz/qux/foo", NULL); r3_tree_insert_path(n, "/baz/qux/bar", NULL); r3_tree_insert_path(n, "/baz/qux/quux", NULL); r3_tree_insert_path(n, "/baz/qux/corge", NULL); r3_tree_insert_path(n, "/baz/qux/grault", NULL); r3_tree_insert_path(n, "/baz/qux/garply", NULL); r3_tree_insert_path(n, "/baz/quux/foo", NULL); r3_tree_insert_path(n, "/baz/quux/bar", NULL); r3_tree_insert_path(n, "/baz/quux/qux", NULL); r3_tree_insert_path(n, "/baz/quux/corge", NULL); r3_tree_insert_path(n, "/baz/quux/grault", NULL); r3_tree_insert_path(n, "/baz/quux/garply", NULL); r3_tree_insert_path(n, "/baz/corge/foo", NULL); r3_tree_insert_path(n, "/baz/corge/bar", NULL); r3_tree_insert_path(n, "/baz/corge/qux", NULL); r3_tree_insert_path(n, "/baz/corge/quux", NULL); r3_tree_insert_path(n, "/baz/corge/grault", NULL); r3_tree_insert_path(n, "/baz/corge/garply", NULL); r3_tree_insert_path(n, "/baz/grault/foo", NULL); r3_tree_insert_path(n, "/baz/grault/bar", NULL); r3_tree_insert_path(n, "/baz/grault/qux", NULL); r3_tree_insert_path(n, "/baz/grault/quux", NULL); r3_tree_insert_path(n, "/baz/grault/corge", NULL); r3_tree_insert_path(n, "/baz/grault/garply", NULL); r3_tree_insert_path(n, "/baz/garply/foo", NULL); r3_tree_insert_path(n, "/baz/garply/bar", NULL); r3_tree_insert_path(n, "/baz/garply/qux", NULL); r3_tree_insert_path(n, "/baz/garply/quux", NULL); r3_tree_insert_path(n, "/baz/garply/corge", NULL); r3_tree_insert_path(n, "/baz/garply/grault", NULL); r3_tree_insert_path(n, "/qux/foo/bar", NULL); r3_tree_insert_path(n, "/qux/foo/baz", NULL); r3_tree_insert_path(n, "/qux/foo/quux", NULL); r3_tree_insert_path(n, "/qux/foo/corge", NULL); r3_tree_insert_path(n, "/qux/foo/grault", NULL); r3_tree_insert_path(n, "/qux/foo/garply", NULL); r3_tree_insert_path(n, "/qux/bar/foo", NULL); r3_tree_insert_path(n, "/qux/bar/baz", NULL); r3_tree_insert_path(n, "/qux/bar/quux", NULL); r3_tree_insert_path(n, "/qux/bar/corge", &route_data); r3_tree_insert_path(n, "/qux/bar/grault", NULL); r3_tree_insert_path(n, "/qux/bar/garply", NULL); r3_tree_insert_path(n, "/qux/baz/foo", NULL); r3_tree_insert_path(n, "/qux/baz/bar", NULL); r3_tree_insert_path(n, "/qux/baz/quux", NULL); r3_tree_insert_path(n, "/qux/baz/corge", NULL); r3_tree_insert_path(n, "/qux/baz/grault", NULL); r3_tree_insert_path(n, "/qux/baz/garply", NULL); r3_tree_insert_path(n, "/qux/quux/foo", NULL); r3_tree_insert_path(n, "/qux/quux/bar", NULL); r3_tree_insert_path(n, "/qux/quux/baz", NULL); r3_tree_insert_path(n, "/qux/quux/corge", NULL); r3_tree_insert_path(n, "/qux/quux/grault", NULL); r3_tree_insert_path(n, "/qux/quux/garply", NULL); r3_tree_insert_path(n, "/qux/corge/foo", NULL); r3_tree_insert_path(n, "/qux/corge/bar", NULL); r3_tree_insert_path(n, "/qux/corge/baz", NULL); r3_tree_insert_path(n, "/qux/corge/quux", NULL); r3_tree_insert_path(n, "/qux/corge/grault", NULL); r3_tree_insert_path(n, "/qux/corge/garply", NULL); r3_tree_insert_path(n, "/qux/grault/foo", NULL); r3_tree_insert_path(n, "/qux/grault/bar", NULL); r3_tree_insert_path(n, "/qux/grault/baz", NULL); r3_tree_insert_path(n, "/qux/grault/quux", NULL); r3_tree_insert_path(n, "/qux/grault/corge", NULL); r3_tree_insert_path(n, "/qux/grault/garply", NULL); r3_tree_insert_path(n, "/qux/garply/foo", NULL); r3_tree_insert_path(n, "/qux/garply/bar", NULL); r3_tree_insert_path(n, "/qux/garply/baz", NULL); r3_tree_insert_path(n, "/qux/garply/quux", NULL); r3_tree_insert_path(n, "/qux/garply/corge", NULL); r3_tree_insert_path(n, "/qux/garply/grault", NULL); r3_tree_insert_path(n, "/quux/foo/bar", NULL); r3_tree_insert_path(n, "/quux/foo/baz", NULL); r3_tree_insert_path(n, "/quux/foo/qux", NULL); r3_tree_insert_path(n, "/quux/foo/corge", NULL); r3_tree_insert_path(n, "/quux/foo/grault", NULL); r3_tree_insert_path(n, "/quux/foo/garply", NULL); r3_tree_insert_path(n, "/quux/bar/foo", NULL); r3_tree_insert_path(n, "/quux/bar/baz", NULL); r3_tree_insert_path(n, "/quux/bar/qux", NULL); r3_tree_insert_path(n, "/quux/bar/corge", NULL); r3_tree_insert_path(n, "/quux/bar/grault", NULL); r3_tree_insert_path(n, "/quux/bar/garply", NULL); r3_tree_insert_path(n, "/quux/baz/foo", NULL); r3_tree_insert_path(n, "/quux/baz/bar", NULL); r3_tree_insert_path(n, "/quux/baz/qux", NULL); r3_tree_insert_path(n, "/quux/baz/corge", NULL); r3_tree_insert_path(n, "/quux/baz/grault", NULL); r3_tree_insert_path(n, "/quux/baz/garply", NULL); r3_tree_insert_path(n, "/quux/qux/foo", NULL); r3_tree_insert_path(n, "/quux/qux/bar", NULL); r3_tree_insert_path(n, "/quux/qux/baz", NULL); r3_tree_insert_path(n, "/quux/qux/corge", NULL); r3_tree_insert_path(n, "/quux/qux/grault", NULL); r3_tree_insert_path(n, "/quux/qux/garply", NULL); r3_tree_insert_path(n, "/quux/corge/foo", NULL); r3_tree_insert_path(n, "/quux/corge/bar", NULL); r3_tree_insert_path(n, "/quux/corge/baz", NULL); r3_tree_insert_path(n, "/quux/corge/qux", NULL); r3_tree_insert_path(n, "/quux/corge/grault", NULL); r3_tree_insert_path(n, "/quux/corge/garply", NULL); r3_tree_insert_path(n, "/quux/grault/foo", NULL); r3_tree_insert_path(n, "/quux/grault/bar", NULL); r3_tree_insert_path(n, "/quux/grault/baz", NULL); r3_tree_insert_path(n, "/quux/grault/qux", NULL); r3_tree_insert_path(n, "/quux/grault/corge", NULL); r3_tree_insert_path(n, "/quux/grault/garply", NULL); r3_tree_insert_path(n, "/quux/garply/foo", NULL); r3_tree_insert_path(n, "/quux/garply/bar", NULL); r3_tree_insert_path(n, "/quux/garply/baz", NULL); r3_tree_insert_path(n, "/quux/garply/qux", NULL); r3_tree_insert_path(n, "/quux/garply/corge", NULL); r3_tree_insert_path(n, "/quux/garply/grault", NULL); r3_tree_insert_path(n, "/corge/foo/bar", NULL); r3_tree_insert_path(n, "/corge/foo/baz", NULL); r3_tree_insert_path(n, "/corge/foo/qux", NULL); r3_tree_insert_path(n, "/corge/foo/quux", NULL); r3_tree_insert_path(n, "/corge/foo/grault", NULL); r3_tree_insert_path(n, "/corge/foo/garply", NULL); r3_tree_insert_path(n, "/corge/bar/foo", NULL); r3_tree_insert_path(n, "/corge/bar/baz", NULL); r3_tree_insert_path(n, "/corge/bar/qux", NULL); r3_tree_insert_path(n, "/corge/bar/quux", NULL); r3_tree_insert_path(n, "/corge/bar/grault", NULL); r3_tree_insert_path(n, "/corge/bar/garply", NULL); r3_tree_insert_path(n, "/corge/baz/foo", NULL); r3_tree_insert_path(n, "/corge/baz/bar", NULL); r3_tree_insert_path(n, "/corge/baz/qux", NULL); r3_tree_insert_path(n, "/corge/baz/quux", NULL); r3_tree_insert_path(n, "/corge/baz/grault", NULL); r3_tree_insert_path(n, "/corge/baz/garply", NULL); r3_tree_insert_path(n, "/corge/qux/foo", NULL); r3_tree_insert_path(n, "/corge/qux/bar", NULL); r3_tree_insert_path(n, "/corge/qux/baz", NULL); r3_tree_insert_path(n, "/corge/qux/quux", NULL); r3_tree_insert_path(n, "/corge/qux/grault", NULL); r3_tree_insert_path(n, "/corge/qux/garply", NULL); r3_tree_insert_path(n, "/corge/quux/foo", NULL); r3_tree_insert_path(n, "/corge/quux/bar", NULL); r3_tree_insert_path(n, "/corge/quux/baz", NULL); r3_tree_insert_path(n, "/corge/quux/qux", NULL); r3_tree_insert_path(n, "/corge/quux/grault", NULL); r3_tree_insert_path(n, "/corge/quux/garply", NULL); r3_tree_insert_path(n, "/corge/grault/foo", NULL); r3_tree_insert_path(n, "/corge/grault/bar", NULL); r3_tree_insert_path(n, "/corge/grault/baz", NULL); r3_tree_insert_path(n, "/corge/grault/qux", NULL); r3_tree_insert_path(n, "/corge/grault/quux", NULL); r3_tree_insert_path(n, "/corge/grault/garply", NULL); r3_tree_insert_path(n, "/corge/garply/foo", NULL); r3_tree_insert_path(n, "/corge/garply/bar", NULL); r3_tree_insert_path(n, "/corge/garply/baz", NULL); r3_tree_insert_path(n, "/corge/garply/qux", NULL); r3_tree_insert_path(n, "/corge/garply/quux", NULL); r3_tree_insert_path(n, "/corge/garply/grault", NULL); r3_tree_insert_path(n, "/grault/foo/bar", NULL); r3_tree_insert_path(n, "/grault/foo/baz", NULL); r3_tree_insert_path(n, "/grault/foo/qux", NULL); r3_tree_insert_path(n, "/grault/foo/quux", NULL); r3_tree_insert_path(n, "/grault/foo/corge", NULL); r3_tree_insert_path(n, "/grault/foo/garply", NULL); r3_tree_insert_path(n, "/grault/bar/foo", NULL); r3_tree_insert_path(n, "/grault/bar/baz", NULL); r3_tree_insert_path(n, "/grault/bar/qux", NULL); r3_tree_insert_path(n, "/grault/bar/quux", NULL); r3_tree_insert_path(n, "/grault/bar/corge", NULL); r3_tree_insert_path(n, "/grault/bar/garply", NULL); r3_tree_insert_path(n, "/grault/baz/foo", NULL); r3_tree_insert_path(n, "/grault/baz/bar", NULL); r3_tree_insert_path(n, "/grault/baz/qux", NULL); r3_tree_insert_path(n, "/grault/baz/quux", NULL); r3_tree_insert_path(n, "/grault/baz/corge", NULL); r3_tree_insert_path(n, "/grault/baz/garply", NULL); r3_tree_insert_path(n, "/grault/qux/foo", NULL); r3_tree_insert_path(n, "/grault/qux/bar", NULL); r3_tree_insert_path(n, "/grault/qux/baz", NULL); r3_tree_insert_path(n, "/grault/qux/quux", NULL); r3_tree_insert_path(n, "/grault/qux/corge", NULL); r3_tree_insert_path(n, "/grault/qux/garply", NULL); r3_tree_insert_path(n, "/grault/quux/foo", NULL); r3_tree_insert_path(n, "/grault/quux/bar", NULL); r3_tree_insert_path(n, "/grault/quux/baz", NULL); r3_tree_insert_path(n, "/grault/quux/qux", NULL); r3_tree_insert_path(n, "/grault/quux/corge", NULL); r3_tree_insert_path(n, "/grault/quux/garply", NULL); r3_tree_insert_path(n, "/grault/corge/foo", NULL); r3_tree_insert_path(n, "/grault/corge/bar", NULL); r3_tree_insert_path(n, "/grault/corge/baz", NULL); r3_tree_insert_path(n, "/grault/corge/qux", NULL); r3_tree_insert_path(n, "/grault/corge/quux", NULL); r3_tree_insert_path(n, "/grault/corge/garply", NULL); r3_tree_insert_path(n, "/grault/garply/foo", NULL); r3_tree_insert_path(n, "/grault/garply/bar", NULL); r3_tree_insert_path(n, "/grault/garply/baz", NULL); r3_tree_insert_path(n, "/grault/garply/qux", NULL); r3_tree_insert_path(n, "/grault/garply/quux", NULL); r3_tree_insert_path(n, "/grault/garply/corge", NULL); r3_tree_insert_path(n, "/garply/foo/bar", NULL); r3_tree_insert_path(n, "/garply/foo/baz", NULL); r3_tree_insert_path(n, "/garply/foo/qux", NULL); r3_tree_insert_path(n, "/garply/foo/quux", NULL); r3_tree_insert_path(n, "/garply/foo/corge", NULL); r3_tree_insert_path(n, "/garply/foo/grault", NULL); r3_tree_insert_path(n, "/garply/bar/foo", NULL); r3_tree_insert_path(n, "/garply/bar/baz", NULL); r3_tree_insert_path(n, "/garply/bar/qux", NULL); r3_tree_insert_path(n, "/garply/bar/quux", NULL); r3_tree_insert_path(n, "/garply/bar/corge", NULL); r3_tree_insert_path(n, "/garply/bar/grault", NULL); r3_tree_insert_path(n, "/garply/baz/foo", NULL); r3_tree_insert_path(n, "/garply/baz/bar", NULL); r3_tree_insert_path(n, "/garply/baz/qux", NULL); r3_tree_insert_path(n, "/garply/baz/quux", NULL); r3_tree_insert_path(n, "/garply/baz/corge", NULL); r3_tree_insert_path(n, "/garply/baz/grault", NULL); r3_tree_insert_path(n, "/garply/qux/foo", NULL); r3_tree_insert_path(n, "/garply/qux/bar", NULL); r3_tree_insert_path(n, "/garply/qux/baz", NULL); r3_tree_insert_path(n, "/garply/qux/quux", NULL); r3_tree_insert_path(n, "/garply/qux/corge", NULL); r3_tree_insert_path(n, "/garply/qux/grault", NULL); r3_tree_insert_path(n, "/garply/quux/foo", NULL); r3_tree_insert_path(n, "/garply/quux/bar", NULL); r3_tree_insert_path(n, "/garply/quux/baz", NULL); r3_tree_insert_path(n, "/garply/quux/qux", NULL); r3_tree_insert_path(n, "/garply/quux/corge", NULL); r3_tree_insert_path(n, "/garply/quux/grault", NULL); r3_tree_insert_path(n, "/garply/corge/foo", NULL); r3_tree_insert_path(n, "/garply/corge/bar", NULL); r3_tree_insert_path(n, "/garply/corge/baz", NULL); r3_tree_insert_path(n, "/garply/corge/qux", NULL); r3_tree_insert_path(n, "/garply/corge/quux", NULL); r3_tree_insert_path(n, "/garply/corge/grault", NULL); r3_tree_insert_path(n, "/garply/grault/foo", NULL); r3_tree_insert_path(n, "/garply/grault/bar", NULL); r3_tree_insert_path(n, "/garply/grault/baz", NULL); r3_tree_insert_path(n, "/garply/grault/qux", NULL); r3_tree_insert_path(n, "/garply/grault/quux", NULL); r3_tree_insert_path(n, "/garply/grault/corge", NULL); MEASURE(tree_compile) r3_tree_compile(n, NULL); END_MEASURE(tree_compile) node *m; m = r3_tree_match(n , "/qux/bar/corge", NULL); assert(m != NULL); assert( *((int*) m->data) == 999 ); BENCHMARK(str_dispatch) r3_tree_matchl(n , "/qux/bar/corge", strlen("/qux/bar/corge"), NULL); END_BENCHMARK(str_dispatch) BENCHMARK_SUMMARY(str_dispatch); BENCHMARK(str_match_entry) match_entry * e = match_entry_createl("/qux/bar/corge", strlen("/qux/bar/corge") ); r3_tree_match_entry(n , e); match_entry_free(e); END_BENCHMARK(str_match_entry) BENCHMARK_SUMMARY(str_match_entry); node * tree2 = r3_tree_create(1); r3_tree_insert_path(tree2, "/post/{year}/{month}", NULL); r3_tree_compile(tree2, NULL); BENCHMARK(pcre_dispatch) r3_tree_matchl(tree2, "/post/2014/12", strlen("/post/2014/12"), NULL); END_BENCHMARK(pcre_dispatch) BENCHMARK_SUMMARY(pcre_dispatch); BENCHMARK_RECORD_CSV("bench_str.csv", 4, BR(str_dispatch), BR(pcre_dispatch), BR(tree_compile), BR(str_match_entry) ); r3_tree_free(tree2); r3_tree_free(n); return 0; } r3-1.3.4/tests/bench.h000066400000000000000000000025031262260041500144330ustar00rootroot00000000000000/* * bench.h * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #ifndef BENCH_H #define BENCH_H #include #define MICRO_IN_SEC 1000000.00 #define SEC_IN_MIN 60 #define NUL '\0' typedef struct { long N; // N for each run long R; // runs double secs; double start; double end; } bench; unsigned long unixtime(); double microtime(); void bench_start(bench *b); void bench_stop(bench *b); double bench_iteration_speed(bench *b); void bench_print_summary(bench *b); double bench_duration(bench *b); void bench_append_csv(char *filename, int countOfB, ...); #define MEASURE(B) \ bench B; B.N = 1; B.R = 1; \ printf("Measuring " #B "...\n"); \ bench_start(&B); #define END_MEASURE(B) \ bench_stop(&B); #define BENCHMARK(B) \ bench B; B.N = 5000000; B.R = 3; \ printf("Benchmarking " #B "...\n"); \ bench_start(&B); \ for (int _r = 0; _r < B.R ; _r++ ) { \ for (int _i = 0; _i < B.N ; _i++ ) { #define END_BENCHMARK(B) \ } \ } \ bench_stop(&B); #define BENCHMARK_SUMMARY(B) bench_print_summary(&B); #define BENCHMARK_RECORD_CSV(filename, countOfB, ...) \ bench_append_csv(filename, countOfB, __VA_ARGS__) #define BR(b) &b #endif /* !BENCH_H */ r3-1.3.4/tests/check_gvc.c000066400000000000000000000041501262260041500152630ustar00rootroot00000000000000/* * check_gvc.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include "r3.h" #include "r3_gvc.h" #include "r3_str.h" #include "bench.h" START_TEST (test_gvc_render_dot) { node * n = r3_tree_create(1); r3_tree_insert_path(n, "/foo/bar/baz", NULL); r3_tree_insert_path(n, "/foo/bar/qux", NULL); r3_tree_insert_path(n, "/foo/bar/quux", NULL); r3_tree_insert_path(n, "/foo/bar/corge", NULL); r3_tree_insert_path(n, "/foo/bar/grault", NULL); r3_tree_insert_path(n, "/garply/grault/foo", NULL); r3_tree_insert_path(n, "/garply/grault/bar", NULL); r3_tree_compile(n, NULL); r3_tree_render_dot(n, "dot", stderr); r3_tree_free(n); } END_TEST START_TEST (test_gvc_render_file) { node * n = r3_tree_create(1); r3_tree_insert_path(n, "/foo/bar/baz", NULL); r3_tree_insert_path(n, "/foo/bar/qux", NULL); r3_tree_insert_path(n, "/foo/bar/quux", NULL); r3_tree_insert_path(n, "/foo/bar/corge", NULL); r3_tree_insert_path(n, "/foo/bar/grault", NULL); r3_tree_insert_path(n, "/garply/grault/foo", NULL); r3_tree_insert_path(n, "/garply/grault/bar", NULL); r3_tree_insert_path(n, "/user/{id}", NULL); r3_tree_insert_path(n, "/post/{title:\\w+}", NULL); char *errstr = NULL; int errcode; errcode = r3_tree_compile(n, &errstr); r3_tree_render_file(n, "png", "check_gvc.png"); r3_tree_free(n); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("gvc test"); TCase *tcase = tcase_create("test_gvc"); tcase_add_test(tcase, test_gvc_render_file); tcase_add_test(tcase, test_gvc_render_dot); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; } r3-1.3.4/tests/check_json.c000066400000000000000000000025061262260041500154600ustar00rootroot00000000000000/* * check_json.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include #include "r3.h" #include "r3_str.h" #include "r3_json.h" #include "zmalloc.h" START_TEST (test_json_encode) { node * n; n = r3_tree_create(10); ck_assert(n); r3_tree_insert_path(n, "/zoo", NULL); r3_tree_insert_path(n, "/foo", NULL); r3_tree_insert_path(n, "/bar", NULL); r3_tree_insert_route(n, METHOD_GET, "/post/get", NULL); r3_tree_insert_route(n, METHOD_POST, "/post/post", NULL); r3_tree_compile(n, NULL); json_object * obj = r3_node_to_json_object(n); ck_assert(obj); const char *json = r3_node_to_json_pretty_string(n); printf("JSON: %s\n",json); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("json test"); TCase *tcase = tcase_create("json test"); tcase_add_test(tcase, test_json_encode); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; } r3-1.3.4/tests/check_routes.c000066400000000000000000002437751262260041500160470ustar00rootroot00000000000000 /** DO NOT MODIFY THIS FILE, THIS TEST FILE IS AUTO-GENERATED. **/ #include "config.h" #include #include #include #include #include "r3.h" #include "r3_str.h" #include "zmalloc.h" START_TEST (test_routes) { node * n = r3_tree_create(10); node * m = NULL; char *data0 = "/foo/bar/baz"; r3_tree_insert_path(n, "/foo/bar/baz", (void*) data0); char *data1 = "/foo/bar/qux"; r3_tree_insert_path(n, "/foo/bar/qux", (void*) data1); char *data2 = "/foo/bar/quux"; r3_tree_insert_path(n, "/foo/bar/quux", (void*) data2); char *data3 = "/foo/bar/corge"; r3_tree_insert_path(n, "/foo/bar/corge", (void*) data3); char *data4 = "/foo/bar/grault"; r3_tree_insert_path(n, "/foo/bar/grault", (void*) data4); char *data5 = "/foo/bar/garply"; r3_tree_insert_path(n, "/foo/bar/garply", (void*) data5); char *data6 = "/foo/baz/bar"; r3_tree_insert_path(n, "/foo/baz/bar", (void*) data6); char *data7 = "/foo/baz/qux"; r3_tree_insert_path(n, "/foo/baz/qux", (void*) data7); char *data8 = "/foo/baz/quux"; r3_tree_insert_path(n, "/foo/baz/quux", (void*) data8); char *data9 = "/foo/baz/corge"; r3_tree_insert_path(n, "/foo/baz/corge", (void*) data9); char *data10 = "/foo/baz/grault"; r3_tree_insert_path(n, "/foo/baz/grault", (void*) data10); char *data11 = "/foo/baz/garply"; r3_tree_insert_path(n, "/foo/baz/garply", (void*) data11); char *data12 = "/foo/qux/bar"; r3_tree_insert_path(n, "/foo/qux/bar", (void*) data12); char *data13 = "/foo/qux/baz"; r3_tree_insert_path(n, "/foo/qux/baz", (void*) data13); char *data14 = "/foo/qux/quux"; r3_tree_insert_path(n, "/foo/qux/quux", (void*) data14); char *data15 = "/foo/qux/corge"; r3_tree_insert_path(n, "/foo/qux/corge", (void*) data15); char *data16 = "/foo/qux/grault"; r3_tree_insert_path(n, "/foo/qux/grault", (void*) data16); char *data17 = "/foo/qux/garply"; r3_tree_insert_path(n, "/foo/qux/garply", (void*) data17); char *data18 = "/foo/quux/bar"; r3_tree_insert_path(n, "/foo/quux/bar", (void*) data18); char *data19 = "/foo/quux/baz"; r3_tree_insert_path(n, "/foo/quux/baz", (void*) data19); char *data20 = "/foo/quux/qux"; r3_tree_insert_path(n, "/foo/quux/qux", (void*) data20); char *data21 = "/foo/quux/corge"; r3_tree_insert_path(n, "/foo/quux/corge", (void*) data21); char *data22 = "/foo/quux/grault"; r3_tree_insert_path(n, "/foo/quux/grault", (void*) data22); char *data23 = "/foo/quux/garply"; r3_tree_insert_path(n, "/foo/quux/garply", (void*) data23); char *data24 = "/foo/corge/bar"; r3_tree_insert_path(n, "/foo/corge/bar", (void*) data24); char *data25 = "/foo/corge/baz"; r3_tree_insert_path(n, "/foo/corge/baz", (void*) data25); char *data26 = "/foo/corge/qux"; r3_tree_insert_path(n, "/foo/corge/qux", (void*) data26); char *data27 = "/foo/corge/quux"; r3_tree_insert_path(n, "/foo/corge/quux", (void*) data27); char *data28 = "/foo/corge/grault"; r3_tree_insert_path(n, "/foo/corge/grault", (void*) data28); char *data29 = "/foo/corge/garply"; r3_tree_insert_path(n, "/foo/corge/garply", (void*) data29); char *data30 = "/foo/grault/bar"; r3_tree_insert_path(n, "/foo/grault/bar", (void*) data30); char *data31 = "/foo/grault/baz"; r3_tree_insert_path(n, "/foo/grault/baz", (void*) data31); char *data32 = "/foo/grault/qux"; r3_tree_insert_path(n, "/foo/grault/qux", (void*) data32); char *data33 = "/foo/grault/quux"; r3_tree_insert_path(n, "/foo/grault/quux", (void*) data33); char *data34 = "/foo/grault/corge"; r3_tree_insert_path(n, "/foo/grault/corge", (void*) data34); char *data35 = "/foo/grault/garply"; r3_tree_insert_path(n, "/foo/grault/garply", (void*) data35); char *data36 = "/foo/garply/bar"; r3_tree_insert_path(n, "/foo/garply/bar", (void*) data36); char *data37 = "/foo/garply/baz"; r3_tree_insert_path(n, "/foo/garply/baz", (void*) data37); char *data38 = "/foo/garply/qux"; r3_tree_insert_path(n, "/foo/garply/qux", (void*) data38); char *data39 = "/foo/garply/quux"; r3_tree_insert_path(n, "/foo/garply/quux", (void*) data39); char *data40 = "/foo/garply/corge"; r3_tree_insert_path(n, "/foo/garply/corge", (void*) data40); char *data41 = "/foo/garply/grault"; r3_tree_insert_path(n, "/foo/garply/grault", (void*) data41); char *data42 = "/bar/foo/baz"; r3_tree_insert_path(n, "/bar/foo/baz", (void*) data42); char *data43 = "/bar/foo/qux"; r3_tree_insert_path(n, "/bar/foo/qux", (void*) data43); char *data44 = "/bar/foo/quux"; r3_tree_insert_path(n, "/bar/foo/quux", (void*) data44); char *data45 = "/bar/foo/corge"; r3_tree_insert_path(n, "/bar/foo/corge", (void*) data45); char *data46 = "/bar/foo/grault"; r3_tree_insert_path(n, "/bar/foo/grault", (void*) data46); char *data47 = "/bar/foo/garply"; r3_tree_insert_path(n, "/bar/foo/garply", (void*) data47); char *data48 = "/bar/baz/foo"; r3_tree_insert_path(n, "/bar/baz/foo", (void*) data48); char *data49 = "/bar/baz/qux"; r3_tree_insert_path(n, "/bar/baz/qux", (void*) data49); char *data50 = "/bar/baz/quux"; r3_tree_insert_path(n, "/bar/baz/quux", (void*) data50); char *data51 = "/bar/baz/corge"; r3_tree_insert_path(n, "/bar/baz/corge", (void*) data51); char *data52 = "/bar/baz/grault"; r3_tree_insert_path(n, "/bar/baz/grault", (void*) data52); char *data53 = "/bar/baz/garply"; r3_tree_insert_path(n, "/bar/baz/garply", (void*) data53); char *data54 = "/bar/qux/foo"; r3_tree_insert_path(n, "/bar/qux/foo", (void*) data54); char *data55 = "/bar/qux/baz"; r3_tree_insert_path(n, "/bar/qux/baz", (void*) data55); char *data56 = "/bar/qux/quux"; r3_tree_insert_path(n, "/bar/qux/quux", (void*) data56); char *data57 = "/bar/qux/corge"; r3_tree_insert_path(n, "/bar/qux/corge", (void*) data57); char *data58 = "/bar/qux/grault"; r3_tree_insert_path(n, "/bar/qux/grault", (void*) data58); char *data59 = "/bar/qux/garply"; r3_tree_insert_path(n, "/bar/qux/garply", (void*) data59); char *data60 = "/bar/quux/foo"; r3_tree_insert_path(n, "/bar/quux/foo", (void*) data60); char *data61 = "/bar/quux/baz"; r3_tree_insert_path(n, "/bar/quux/baz", (void*) data61); char *data62 = "/bar/quux/qux"; r3_tree_insert_path(n, "/bar/quux/qux", (void*) data62); char *data63 = "/bar/quux/corge"; r3_tree_insert_path(n, "/bar/quux/corge", (void*) data63); char *data64 = "/bar/quux/grault"; r3_tree_insert_path(n, "/bar/quux/grault", (void*) data64); char *data65 = "/bar/quux/garply"; r3_tree_insert_path(n, "/bar/quux/garply", (void*) data65); char *data66 = "/bar/corge/foo"; r3_tree_insert_path(n, "/bar/corge/foo", (void*) data66); char *data67 = "/bar/corge/baz"; r3_tree_insert_path(n, "/bar/corge/baz", (void*) data67); char *data68 = "/bar/corge/qux"; r3_tree_insert_path(n, "/bar/corge/qux", (void*) data68); char *data69 = "/bar/corge/quux"; r3_tree_insert_path(n, "/bar/corge/quux", (void*) data69); char *data70 = "/bar/corge/grault"; r3_tree_insert_path(n, "/bar/corge/grault", (void*) data70); char *data71 = "/bar/corge/garply"; r3_tree_insert_path(n, "/bar/corge/garply", (void*) data71); char *data72 = "/bar/grault/foo"; r3_tree_insert_path(n, "/bar/grault/foo", (void*) data72); char *data73 = "/bar/grault/baz"; r3_tree_insert_path(n, "/bar/grault/baz", (void*) data73); char *data74 = "/bar/grault/qux"; r3_tree_insert_path(n, "/bar/grault/qux", (void*) data74); char *data75 = "/bar/grault/quux"; r3_tree_insert_path(n, "/bar/grault/quux", (void*) data75); char *data76 = "/bar/grault/corge"; r3_tree_insert_path(n, "/bar/grault/corge", (void*) data76); char *data77 = "/bar/grault/garply"; r3_tree_insert_path(n, "/bar/grault/garply", (void*) data77); char *data78 = "/bar/garply/foo"; r3_tree_insert_path(n, "/bar/garply/foo", (void*) data78); char *data79 = "/bar/garply/baz"; r3_tree_insert_path(n, "/bar/garply/baz", (void*) data79); char *data80 = "/bar/garply/qux"; r3_tree_insert_path(n, "/bar/garply/qux", (void*) data80); char *data81 = "/bar/garply/quux"; r3_tree_insert_path(n, "/bar/garply/quux", (void*) data81); char *data82 = "/bar/garply/corge"; r3_tree_insert_path(n, "/bar/garply/corge", (void*) data82); char *data83 = "/bar/garply/grault"; r3_tree_insert_path(n, "/bar/garply/grault", (void*) data83); char *data84 = "/baz/foo/bar"; r3_tree_insert_path(n, "/baz/foo/bar", (void*) data84); char *data85 = "/baz/foo/qux"; r3_tree_insert_path(n, "/baz/foo/qux", (void*) data85); char *data86 = "/baz/foo/quux"; r3_tree_insert_path(n, "/baz/foo/quux", (void*) data86); char *data87 = "/baz/foo/corge"; r3_tree_insert_path(n, "/baz/foo/corge", (void*) data87); char *data88 = "/baz/foo/grault"; r3_tree_insert_path(n, "/baz/foo/grault", (void*) data88); char *data89 = "/baz/foo/garply"; r3_tree_insert_path(n, "/baz/foo/garply", (void*) data89); char *data90 = "/baz/bar/foo"; r3_tree_insert_path(n, "/baz/bar/foo", (void*) data90); char *data91 = "/baz/bar/qux"; r3_tree_insert_path(n, "/baz/bar/qux", (void*) data91); char *data92 = "/baz/bar/quux"; r3_tree_insert_path(n, "/baz/bar/quux", (void*) data92); char *data93 = "/baz/bar/corge"; r3_tree_insert_path(n, "/baz/bar/corge", (void*) data93); char *data94 = "/baz/bar/grault"; r3_tree_insert_path(n, "/baz/bar/grault", (void*) data94); char *data95 = "/baz/bar/garply"; r3_tree_insert_path(n, "/baz/bar/garply", (void*) data95); char *data96 = "/baz/qux/foo"; r3_tree_insert_path(n, "/baz/qux/foo", (void*) data96); char *data97 = "/baz/qux/bar"; r3_tree_insert_path(n, "/baz/qux/bar", (void*) data97); char *data98 = "/baz/qux/quux"; r3_tree_insert_path(n, "/baz/qux/quux", (void*) data98); char *data99 = "/baz/qux/corge"; r3_tree_insert_path(n, "/baz/qux/corge", (void*) data99); char *data100 = "/baz/qux/grault"; r3_tree_insert_path(n, "/baz/qux/grault", (void*) data100); char *data101 = "/baz/qux/garply"; r3_tree_insert_path(n, "/baz/qux/garply", (void*) data101); char *data102 = "/baz/quux/foo"; r3_tree_insert_path(n, "/baz/quux/foo", (void*) data102); char *data103 = "/baz/quux/bar"; r3_tree_insert_path(n, "/baz/quux/bar", (void*) data103); char *data104 = "/baz/quux/qux"; r3_tree_insert_path(n, "/baz/quux/qux", (void*) data104); char *data105 = "/baz/quux/corge"; r3_tree_insert_path(n, "/baz/quux/corge", (void*) data105); char *data106 = "/baz/quux/grault"; r3_tree_insert_path(n, "/baz/quux/grault", (void*) data106); char *data107 = "/baz/quux/garply"; r3_tree_insert_path(n, "/baz/quux/garply", (void*) data107); char *data108 = "/baz/corge/foo"; r3_tree_insert_path(n, "/baz/corge/foo", (void*) data108); char *data109 = "/baz/corge/bar"; r3_tree_insert_path(n, "/baz/corge/bar", (void*) data109); char *data110 = "/baz/corge/qux"; r3_tree_insert_path(n, "/baz/corge/qux", (void*) data110); char *data111 = "/baz/corge/quux"; r3_tree_insert_path(n, "/baz/corge/quux", (void*) data111); char *data112 = "/baz/corge/grault"; r3_tree_insert_path(n, "/baz/corge/grault", (void*) data112); char *data113 = "/baz/corge/garply"; r3_tree_insert_path(n, "/baz/corge/garply", (void*) data113); char *data114 = "/baz/grault/foo"; r3_tree_insert_path(n, "/baz/grault/foo", (void*) data114); char *data115 = "/baz/grault/bar"; r3_tree_insert_path(n, "/baz/grault/bar", (void*) data115); char *data116 = "/baz/grault/qux"; r3_tree_insert_path(n, "/baz/grault/qux", (void*) data116); char *data117 = "/baz/grault/quux"; r3_tree_insert_path(n, "/baz/grault/quux", (void*) data117); char *data118 = "/baz/grault/corge"; r3_tree_insert_path(n, "/baz/grault/corge", (void*) data118); char *data119 = "/baz/grault/garply"; r3_tree_insert_path(n, "/baz/grault/garply", (void*) data119); char *data120 = "/baz/garply/foo"; r3_tree_insert_path(n, "/baz/garply/foo", (void*) data120); char *data121 = "/baz/garply/bar"; r3_tree_insert_path(n, "/baz/garply/bar", (void*) data121); char *data122 = "/baz/garply/qux"; r3_tree_insert_path(n, "/baz/garply/qux", (void*) data122); char *data123 = "/baz/garply/quux"; r3_tree_insert_path(n, "/baz/garply/quux", (void*) data123); char *data124 = "/baz/garply/corge"; r3_tree_insert_path(n, "/baz/garply/corge", (void*) data124); char *data125 = "/baz/garply/grault"; r3_tree_insert_path(n, "/baz/garply/grault", (void*) data125); char *data126 = "/qux/foo/bar"; r3_tree_insert_path(n, "/qux/foo/bar", (void*) data126); char *data127 = "/qux/foo/baz"; r3_tree_insert_path(n, "/qux/foo/baz", (void*) data127); char *data128 = "/qux/foo/quux"; r3_tree_insert_path(n, "/qux/foo/quux", (void*) data128); char *data129 = "/qux/foo/corge"; r3_tree_insert_path(n, "/qux/foo/corge", (void*) data129); char *data130 = "/qux/foo/grault"; r3_tree_insert_path(n, "/qux/foo/grault", (void*) data130); char *data131 = "/qux/foo/garply"; r3_tree_insert_path(n, "/qux/foo/garply", (void*) data131); char *data132 = "/qux/bar/foo"; r3_tree_insert_path(n, "/qux/bar/foo", (void*) data132); char *data133 = "/qux/bar/baz"; r3_tree_insert_path(n, "/qux/bar/baz", (void*) data133); char *data134 = "/qux/bar/quux"; r3_tree_insert_path(n, "/qux/bar/quux", (void*) data134); char *data135 = "/qux/bar/corge"; r3_tree_insert_path(n, "/qux/bar/corge", (void*) data135); char *data136 = "/qux/bar/grault"; r3_tree_insert_path(n, "/qux/bar/grault", (void*) data136); char *data137 = "/qux/bar/garply"; r3_tree_insert_path(n, "/qux/bar/garply", (void*) data137); char *data138 = "/qux/baz/foo"; r3_tree_insert_path(n, "/qux/baz/foo", (void*) data138); char *data139 = "/qux/baz/bar"; r3_tree_insert_path(n, "/qux/baz/bar", (void*) data139); char *data140 = "/qux/baz/quux"; r3_tree_insert_path(n, "/qux/baz/quux", (void*) data140); char *data141 = "/qux/baz/corge"; r3_tree_insert_path(n, "/qux/baz/corge", (void*) data141); char *data142 = "/qux/baz/grault"; r3_tree_insert_path(n, "/qux/baz/grault", (void*) data142); char *data143 = "/qux/baz/garply"; r3_tree_insert_path(n, "/qux/baz/garply", (void*) data143); char *data144 = "/qux/quux/foo"; r3_tree_insert_path(n, "/qux/quux/foo", (void*) data144); char *data145 = "/qux/quux/bar"; r3_tree_insert_path(n, "/qux/quux/bar", (void*) data145); char *data146 = "/qux/quux/baz"; r3_tree_insert_path(n, "/qux/quux/baz", (void*) data146); char *data147 = "/qux/quux/corge"; r3_tree_insert_path(n, "/qux/quux/corge", (void*) data147); char *data148 = "/qux/quux/grault"; r3_tree_insert_path(n, "/qux/quux/grault", (void*) data148); char *data149 = "/qux/quux/garply"; r3_tree_insert_path(n, "/qux/quux/garply", (void*) data149); char *data150 = "/qux/corge/foo"; r3_tree_insert_path(n, "/qux/corge/foo", (void*) data150); char *data151 = "/qux/corge/bar"; r3_tree_insert_path(n, "/qux/corge/bar", (void*) data151); char *data152 = "/qux/corge/baz"; r3_tree_insert_path(n, "/qux/corge/baz", (void*) data152); char *data153 = "/qux/corge/quux"; r3_tree_insert_path(n, "/qux/corge/quux", (void*) data153); char *data154 = "/qux/corge/grault"; r3_tree_insert_path(n, "/qux/corge/grault", (void*) data154); char *data155 = "/qux/corge/garply"; r3_tree_insert_path(n, "/qux/corge/garply", (void*) data155); char *data156 = "/qux/grault/foo"; r3_tree_insert_path(n, "/qux/grault/foo", (void*) data156); char *data157 = "/qux/grault/bar"; r3_tree_insert_path(n, "/qux/grault/bar", (void*) data157); char *data158 = "/qux/grault/baz"; r3_tree_insert_path(n, "/qux/grault/baz", (void*) data158); char *data159 = "/qux/grault/quux"; r3_tree_insert_path(n, "/qux/grault/quux", (void*) data159); char *data160 = "/qux/grault/corge"; r3_tree_insert_path(n, "/qux/grault/corge", (void*) data160); char *data161 = "/qux/grault/garply"; r3_tree_insert_path(n, "/qux/grault/garply", (void*) data161); char *data162 = "/qux/garply/foo"; r3_tree_insert_path(n, "/qux/garply/foo", (void*) data162); char *data163 = "/qux/garply/bar"; r3_tree_insert_path(n, "/qux/garply/bar", (void*) data163); char *data164 = "/qux/garply/baz"; r3_tree_insert_path(n, "/qux/garply/baz", (void*) data164); char *data165 = "/qux/garply/quux"; r3_tree_insert_path(n, "/qux/garply/quux", (void*) data165); char *data166 = "/qux/garply/corge"; r3_tree_insert_path(n, "/qux/garply/corge", (void*) data166); char *data167 = "/qux/garply/grault"; r3_tree_insert_path(n, "/qux/garply/grault", (void*) data167); char *data168 = "/quux/foo/bar"; r3_tree_insert_path(n, "/quux/foo/bar", (void*) data168); char *data169 = "/quux/foo/baz"; r3_tree_insert_path(n, "/quux/foo/baz", (void*) data169); char *data170 = "/quux/foo/qux"; r3_tree_insert_path(n, "/quux/foo/qux", (void*) data170); char *data171 = "/quux/foo/corge"; r3_tree_insert_path(n, "/quux/foo/corge", (void*) data171); char *data172 = "/quux/foo/grault"; r3_tree_insert_path(n, "/quux/foo/grault", (void*) data172); char *data173 = "/quux/foo/garply"; r3_tree_insert_path(n, "/quux/foo/garply", (void*) data173); char *data174 = "/quux/bar/foo"; r3_tree_insert_path(n, "/quux/bar/foo", (void*) data174); char *data175 = "/quux/bar/baz"; r3_tree_insert_path(n, "/quux/bar/baz", (void*) data175); char *data176 = "/quux/bar/qux"; r3_tree_insert_path(n, "/quux/bar/qux", (void*) data176); char *data177 = "/quux/bar/corge"; r3_tree_insert_path(n, "/quux/bar/corge", (void*) data177); char *data178 = "/quux/bar/grault"; r3_tree_insert_path(n, "/quux/bar/grault", (void*) data178); char *data179 = "/quux/bar/garply"; r3_tree_insert_path(n, "/quux/bar/garply", (void*) data179); char *data180 = "/quux/baz/foo"; r3_tree_insert_path(n, "/quux/baz/foo", (void*) data180); char *data181 = "/quux/baz/bar"; r3_tree_insert_path(n, "/quux/baz/bar", (void*) data181); char *data182 = "/quux/baz/qux"; r3_tree_insert_path(n, "/quux/baz/qux", (void*) data182); char *data183 = "/quux/baz/corge"; r3_tree_insert_path(n, "/quux/baz/corge", (void*) data183); char *data184 = "/quux/baz/grault"; r3_tree_insert_path(n, "/quux/baz/grault", (void*) data184); char *data185 = "/quux/baz/garply"; r3_tree_insert_path(n, "/quux/baz/garply", (void*) data185); char *data186 = "/quux/qux/foo"; r3_tree_insert_path(n, "/quux/qux/foo", (void*) data186); char *data187 = "/quux/qux/bar"; r3_tree_insert_path(n, "/quux/qux/bar", (void*) data187); char *data188 = "/quux/qux/baz"; r3_tree_insert_path(n, "/quux/qux/baz", (void*) data188); char *data189 = "/quux/qux/corge"; r3_tree_insert_path(n, "/quux/qux/corge", (void*) data189); char *data190 = "/quux/qux/grault"; r3_tree_insert_path(n, "/quux/qux/grault", (void*) data190); char *data191 = "/quux/qux/garply"; r3_tree_insert_path(n, "/quux/qux/garply", (void*) data191); char *data192 = "/quux/corge/foo"; r3_tree_insert_path(n, "/quux/corge/foo", (void*) data192); char *data193 = "/quux/corge/bar"; r3_tree_insert_path(n, "/quux/corge/bar", (void*) data193); char *data194 = "/quux/corge/baz"; r3_tree_insert_path(n, "/quux/corge/baz", (void*) data194); char *data195 = "/quux/corge/qux"; r3_tree_insert_path(n, "/quux/corge/qux", (void*) data195); char *data196 = "/quux/corge/grault"; r3_tree_insert_path(n, "/quux/corge/grault", (void*) data196); char *data197 = "/quux/corge/garply"; r3_tree_insert_path(n, "/quux/corge/garply", (void*) data197); char *data198 = "/quux/grault/foo"; r3_tree_insert_path(n, "/quux/grault/foo", (void*) data198); char *data199 = "/quux/grault/bar"; r3_tree_insert_path(n, "/quux/grault/bar", (void*) data199); char *data200 = "/quux/grault/baz"; r3_tree_insert_path(n, "/quux/grault/baz", (void*) data200); char *data201 = "/quux/grault/qux"; r3_tree_insert_path(n, "/quux/grault/qux", (void*) data201); char *data202 = "/quux/grault/corge"; r3_tree_insert_path(n, "/quux/grault/corge", (void*) data202); char *data203 = "/quux/grault/garply"; r3_tree_insert_path(n, "/quux/grault/garply", (void*) data203); char *data204 = "/quux/garply/foo"; r3_tree_insert_path(n, "/quux/garply/foo", (void*) data204); char *data205 = "/quux/garply/bar"; r3_tree_insert_path(n, "/quux/garply/bar", (void*) data205); char *data206 = "/quux/garply/baz"; r3_tree_insert_path(n, "/quux/garply/baz", (void*) data206); char *data207 = "/quux/garply/qux"; r3_tree_insert_path(n, "/quux/garply/qux", (void*) data207); char *data208 = "/quux/garply/corge"; r3_tree_insert_path(n, "/quux/garply/corge", (void*) data208); char *data209 = "/quux/garply/grault"; r3_tree_insert_path(n, "/quux/garply/grault", (void*) data209); char *data210 = "/corge/foo/bar"; r3_tree_insert_path(n, "/corge/foo/bar", (void*) data210); char *data211 = "/corge/foo/baz"; r3_tree_insert_path(n, "/corge/foo/baz", (void*) data211); char *data212 = "/corge/foo/qux"; r3_tree_insert_path(n, "/corge/foo/qux", (void*) data212); char *data213 = "/corge/foo/quux"; r3_tree_insert_path(n, "/corge/foo/quux", (void*) data213); char *data214 = "/corge/foo/grault"; r3_tree_insert_path(n, "/corge/foo/grault", (void*) data214); char *data215 = "/corge/foo/garply"; r3_tree_insert_path(n, "/corge/foo/garply", (void*) data215); char *data216 = "/corge/bar/foo"; r3_tree_insert_path(n, "/corge/bar/foo", (void*) data216); char *data217 = "/corge/bar/baz"; r3_tree_insert_path(n, "/corge/bar/baz", (void*) data217); char *data218 = "/corge/bar/qux"; r3_tree_insert_path(n, "/corge/bar/qux", (void*) data218); char *data219 = "/corge/bar/quux"; r3_tree_insert_path(n, "/corge/bar/quux", (void*) data219); char *data220 = "/corge/bar/grault"; r3_tree_insert_path(n, "/corge/bar/grault", (void*) data220); char *data221 = "/corge/bar/garply"; r3_tree_insert_path(n, "/corge/bar/garply", (void*) data221); char *data222 = "/corge/baz/foo"; r3_tree_insert_path(n, "/corge/baz/foo", (void*) data222); char *data223 = "/corge/baz/bar"; r3_tree_insert_path(n, "/corge/baz/bar", (void*) data223); char *data224 = "/corge/baz/qux"; r3_tree_insert_path(n, "/corge/baz/qux", (void*) data224); char *data225 = "/corge/baz/quux"; r3_tree_insert_path(n, "/corge/baz/quux", (void*) data225); char *data226 = "/corge/baz/grault"; r3_tree_insert_path(n, "/corge/baz/grault", (void*) data226); char *data227 = "/corge/baz/garply"; r3_tree_insert_path(n, "/corge/baz/garply", (void*) data227); char *data228 = "/corge/qux/foo"; r3_tree_insert_path(n, "/corge/qux/foo", (void*) data228); char *data229 = "/corge/qux/bar"; r3_tree_insert_path(n, "/corge/qux/bar", (void*) data229); char *data230 = "/corge/qux/baz"; r3_tree_insert_path(n, "/corge/qux/baz", (void*) data230); char *data231 = "/corge/qux/quux"; r3_tree_insert_path(n, "/corge/qux/quux", (void*) data231); char *data232 = "/corge/qux/grault"; r3_tree_insert_path(n, "/corge/qux/grault", (void*) data232); char *data233 = "/corge/qux/garply"; r3_tree_insert_path(n, "/corge/qux/garply", (void*) data233); char *data234 = "/corge/quux/foo"; r3_tree_insert_path(n, "/corge/quux/foo", (void*) data234); char *data235 = "/corge/quux/bar"; r3_tree_insert_path(n, "/corge/quux/bar", (void*) data235); char *data236 = "/corge/quux/baz"; r3_tree_insert_path(n, "/corge/quux/baz", (void*) data236); char *data237 = "/corge/quux/qux"; r3_tree_insert_path(n, "/corge/quux/qux", (void*) data237); char *data238 = "/corge/quux/grault"; r3_tree_insert_path(n, "/corge/quux/grault", (void*) data238); char *data239 = "/corge/quux/garply"; r3_tree_insert_path(n, "/corge/quux/garply", (void*) data239); char *data240 = "/corge/grault/foo"; r3_tree_insert_path(n, "/corge/grault/foo", (void*) data240); char *data241 = "/corge/grault/bar"; r3_tree_insert_path(n, "/corge/grault/bar", (void*) data241); char *data242 = "/corge/grault/baz"; r3_tree_insert_path(n, "/corge/grault/baz", (void*) data242); char *data243 = "/corge/grault/qux"; r3_tree_insert_path(n, "/corge/grault/qux", (void*) data243); char *data244 = "/corge/grault/quux"; r3_tree_insert_path(n, "/corge/grault/quux", (void*) data244); char *data245 = "/corge/grault/garply"; r3_tree_insert_path(n, "/corge/grault/garply", (void*) data245); char *data246 = "/corge/garply/foo"; r3_tree_insert_path(n, "/corge/garply/foo", (void*) data246); char *data247 = "/corge/garply/bar"; r3_tree_insert_path(n, "/corge/garply/bar", (void*) data247); char *data248 = "/corge/garply/baz"; r3_tree_insert_path(n, "/corge/garply/baz", (void*) data248); char *data249 = "/corge/garply/qux"; r3_tree_insert_path(n, "/corge/garply/qux", (void*) data249); char *data250 = "/corge/garply/quux"; r3_tree_insert_path(n, "/corge/garply/quux", (void*) data250); char *data251 = "/corge/garply/grault"; r3_tree_insert_path(n, "/corge/garply/grault", (void*) data251); char *data252 = "/grault/foo/bar"; r3_tree_insert_path(n, "/grault/foo/bar", (void*) data252); char *data253 = "/grault/foo/baz"; r3_tree_insert_path(n, "/grault/foo/baz", (void*) data253); char *data254 = "/grault/foo/qux"; r3_tree_insert_path(n, "/grault/foo/qux", (void*) data254); char *data255 = "/grault/foo/quux"; r3_tree_insert_path(n, "/grault/foo/quux", (void*) data255); char *data256 = "/grault/foo/corge"; r3_tree_insert_path(n, "/grault/foo/corge", (void*) data256); char *data257 = "/grault/foo/garply"; r3_tree_insert_path(n, "/grault/foo/garply", (void*) data257); char *data258 = "/grault/bar/foo"; r3_tree_insert_path(n, "/grault/bar/foo", (void*) data258); char *data259 = "/grault/bar/baz"; r3_tree_insert_path(n, "/grault/bar/baz", (void*) data259); char *data260 = "/grault/bar/qux"; r3_tree_insert_path(n, "/grault/bar/qux", (void*) data260); char *data261 = "/grault/bar/quux"; r3_tree_insert_path(n, "/grault/bar/quux", (void*) data261); char *data262 = "/grault/bar/corge"; r3_tree_insert_path(n, "/grault/bar/corge", (void*) data262); char *data263 = "/grault/bar/garply"; r3_tree_insert_path(n, "/grault/bar/garply", (void*) data263); char *data264 = "/grault/baz/foo"; r3_tree_insert_path(n, "/grault/baz/foo", (void*) data264); char *data265 = "/grault/baz/bar"; r3_tree_insert_path(n, "/grault/baz/bar", (void*) data265); char *data266 = "/grault/baz/qux"; r3_tree_insert_path(n, "/grault/baz/qux", (void*) data266); char *data267 = "/grault/baz/quux"; r3_tree_insert_path(n, "/grault/baz/quux", (void*) data267); char *data268 = "/grault/baz/corge"; r3_tree_insert_path(n, "/grault/baz/corge", (void*) data268); char *data269 = "/grault/baz/garply"; r3_tree_insert_path(n, "/grault/baz/garply", (void*) data269); char *data270 = "/grault/qux/foo"; r3_tree_insert_path(n, "/grault/qux/foo", (void*) data270); char *data271 = "/grault/qux/bar"; r3_tree_insert_path(n, "/grault/qux/bar", (void*) data271); char *data272 = "/grault/qux/baz"; r3_tree_insert_path(n, "/grault/qux/baz", (void*) data272); char *data273 = "/grault/qux/quux"; r3_tree_insert_path(n, "/grault/qux/quux", (void*) data273); char *data274 = "/grault/qux/corge"; r3_tree_insert_path(n, "/grault/qux/corge", (void*) data274); char *data275 = "/grault/qux/garply"; r3_tree_insert_path(n, "/grault/qux/garply", (void*) data275); char *data276 = "/grault/quux/foo"; r3_tree_insert_path(n, "/grault/quux/foo", (void*) data276); char *data277 = "/grault/quux/bar"; r3_tree_insert_path(n, "/grault/quux/bar", (void*) data277); char *data278 = "/grault/quux/baz"; r3_tree_insert_path(n, "/grault/quux/baz", (void*) data278); char *data279 = "/grault/quux/qux"; r3_tree_insert_path(n, "/grault/quux/qux", (void*) data279); char *data280 = "/grault/quux/corge"; r3_tree_insert_path(n, "/grault/quux/corge", (void*) data280); char *data281 = "/grault/quux/garply"; r3_tree_insert_path(n, "/grault/quux/garply", (void*) data281); char *data282 = "/grault/corge/foo"; r3_tree_insert_path(n, "/grault/corge/foo", (void*) data282); char *data283 = "/grault/corge/bar"; r3_tree_insert_path(n, "/grault/corge/bar", (void*) data283); char *data284 = "/grault/corge/baz"; r3_tree_insert_path(n, "/grault/corge/baz", (void*) data284); char *data285 = "/grault/corge/qux"; r3_tree_insert_path(n, "/grault/corge/qux", (void*) data285); char *data286 = "/grault/corge/quux"; r3_tree_insert_path(n, "/grault/corge/quux", (void*) data286); char *data287 = "/grault/corge/garply"; r3_tree_insert_path(n, "/grault/corge/garply", (void*) data287); char *data288 = "/grault/garply/foo"; r3_tree_insert_path(n, "/grault/garply/foo", (void*) data288); char *data289 = "/grault/garply/bar"; r3_tree_insert_path(n, "/grault/garply/bar", (void*) data289); char *data290 = "/grault/garply/baz"; r3_tree_insert_path(n, "/grault/garply/baz", (void*) data290); char *data291 = "/grault/garply/qux"; r3_tree_insert_path(n, "/grault/garply/qux", (void*) data291); char *data292 = "/grault/garply/quux"; r3_tree_insert_path(n, "/grault/garply/quux", (void*) data292); char *data293 = "/grault/garply/corge"; r3_tree_insert_path(n, "/grault/garply/corge", (void*) data293); char *data294 = "/garply/foo/bar"; r3_tree_insert_path(n, "/garply/foo/bar", (void*) data294); char *data295 = "/garply/foo/baz"; r3_tree_insert_path(n, "/garply/foo/baz", (void*) data295); char *data296 = "/garply/foo/qux"; r3_tree_insert_path(n, "/garply/foo/qux", (void*) data296); char *data297 = "/garply/foo/quux"; r3_tree_insert_path(n, "/garply/foo/quux", (void*) data297); char *data298 = "/garply/foo/corge"; r3_tree_insert_path(n, "/garply/foo/corge", (void*) data298); char *data299 = "/garply/foo/grault"; r3_tree_insert_path(n, "/garply/foo/grault", (void*) data299); char *data300 = "/garply/bar/foo"; r3_tree_insert_path(n, "/garply/bar/foo", (void*) data300); char *data301 = "/garply/bar/baz"; r3_tree_insert_path(n, "/garply/bar/baz", (void*) data301); char *data302 = "/garply/bar/qux"; r3_tree_insert_path(n, "/garply/bar/qux", (void*) data302); char *data303 = "/garply/bar/quux"; r3_tree_insert_path(n, "/garply/bar/quux", (void*) data303); char *data304 = "/garply/bar/corge"; r3_tree_insert_path(n, "/garply/bar/corge", (void*) data304); char *data305 = "/garply/bar/grault"; r3_tree_insert_path(n, "/garply/bar/grault", (void*) data305); char *data306 = "/garply/baz/foo"; r3_tree_insert_path(n, "/garply/baz/foo", (void*) data306); char *data307 = "/garply/baz/bar"; r3_tree_insert_path(n, "/garply/baz/bar", (void*) data307); char *data308 = "/garply/baz/qux"; r3_tree_insert_path(n, "/garply/baz/qux", (void*) data308); char *data309 = "/garply/baz/quux"; r3_tree_insert_path(n, "/garply/baz/quux", (void*) data309); char *data310 = "/garply/baz/corge"; r3_tree_insert_path(n, "/garply/baz/corge", (void*) data310); char *data311 = "/garply/baz/grault"; r3_tree_insert_path(n, "/garply/baz/grault", (void*) data311); char *data312 = "/garply/qux/foo"; r3_tree_insert_path(n, "/garply/qux/foo", (void*) data312); char *data313 = "/garply/qux/bar"; r3_tree_insert_path(n, "/garply/qux/bar", (void*) data313); char *data314 = "/garply/qux/baz"; r3_tree_insert_path(n, "/garply/qux/baz", (void*) data314); char *data315 = "/garply/qux/quux"; r3_tree_insert_path(n, "/garply/qux/quux", (void*) data315); char *data316 = "/garply/qux/corge"; r3_tree_insert_path(n, "/garply/qux/corge", (void*) data316); char *data317 = "/garply/qux/grault"; r3_tree_insert_path(n, "/garply/qux/grault", (void*) data317); char *data318 = "/garply/quux/foo"; r3_tree_insert_path(n, "/garply/quux/foo", (void*) data318); char *data319 = "/garply/quux/bar"; r3_tree_insert_path(n, "/garply/quux/bar", (void*) data319); char *data320 = "/garply/quux/baz"; r3_tree_insert_path(n, "/garply/quux/baz", (void*) data320); char *data321 = "/garply/quux/qux"; r3_tree_insert_path(n, "/garply/quux/qux", (void*) data321); char *data322 = "/garply/quux/corge"; r3_tree_insert_path(n, "/garply/quux/corge", (void*) data322); char *data323 = "/garply/quux/grault"; r3_tree_insert_path(n, "/garply/quux/grault", (void*) data323); char *data324 = "/garply/corge/foo"; r3_tree_insert_path(n, "/garply/corge/foo", (void*) data324); char *data325 = "/garply/corge/bar"; r3_tree_insert_path(n, "/garply/corge/bar", (void*) data325); char *data326 = "/garply/corge/baz"; r3_tree_insert_path(n, "/garply/corge/baz", (void*) data326); char *data327 = "/garply/corge/qux"; r3_tree_insert_path(n, "/garply/corge/qux", (void*) data327); char *data328 = "/garply/corge/quux"; r3_tree_insert_path(n, "/garply/corge/quux", (void*) data328); char *data329 = "/garply/corge/grault"; r3_tree_insert_path(n, "/garply/corge/grault", (void*) data329); char *data330 = "/garply/grault/foo"; r3_tree_insert_path(n, "/garply/grault/foo", (void*) data330); char *data331 = "/garply/grault/bar"; r3_tree_insert_path(n, "/garply/grault/bar", (void*) data331); char *data332 = "/garply/grault/baz"; r3_tree_insert_path(n, "/garply/grault/baz", (void*) data332); char *data333 = "/garply/grault/qux"; r3_tree_insert_path(n, "/garply/grault/qux", (void*) data333); char *data334 = "/garply/grault/quux"; r3_tree_insert_path(n, "/garply/grault/quux", (void*) data334); char *data335 = "/garply/grault/corge"; r3_tree_insert_path(n, "/garply/grault/corge", (void*) data335); char *err = NULL; r3_tree_compile(n, &err); ck_assert(err == NULL); m = r3_tree_match(n, "/foo/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data0); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data1); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data2); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data3); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data4); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data5); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data6); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data7); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data8); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data9); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data10); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data11); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data12); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data13); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data14); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data15); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data16); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data17); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data18); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data19); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data20); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data21); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data22); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data23); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data24); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data25); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data26); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data27); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data28); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data29); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data30); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data31); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data32); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data33); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data34); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data35); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data36); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data37); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data38); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data39); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data40); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/foo/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data41); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data42); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data43); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data44); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data45); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data46); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data47); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data48); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data49); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data50); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data51); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data52); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data53); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data54); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data55); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data56); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data57); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data58); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data59); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data60); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data61); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data62); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data63); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data64); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data65); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data66); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data67); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data68); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data69); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data70); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data71); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data72); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data73); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data74); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data75); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data76); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data77); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data78); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data79); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data80); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data81); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data82); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/bar/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data83); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data84); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data85); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data86); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data87); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data88); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data89); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data90); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data91); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data92); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data93); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data94); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data95); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data96); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data97); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data98); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data99); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data100); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data101); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data102); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data103); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data104); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data105); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data106); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data107); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data108); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data109); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data110); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data111); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data112); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data113); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data114); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data115); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data116); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data117); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data118); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data119); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data120); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data121); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data122); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data123); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data124); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/baz/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data125); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data126); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data127); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data128); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data129); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data130); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data131); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data132); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data133); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data134); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data135); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data136); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data137); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data138); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data139); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data140); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data141); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data142); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data143); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data144); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data145); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data146); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data147); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data148); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data149); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data150); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data151); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data152); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data153); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data154); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data155); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data156); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data157); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data158); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data159); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data160); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data161); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data162); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data163); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data164); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data165); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data166); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/qux/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data167); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data168); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data169); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data170); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data171); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data172); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data173); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data174); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data175); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data176); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data177); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data178); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data179); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data180); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data181); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data182); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data183); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data184); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data185); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data186); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data187); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data188); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data189); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data190); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data191); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data192); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data193); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data194); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data195); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data196); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data197); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data198); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data199); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data200); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data201); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data202); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data203); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data204); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data205); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data206); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data207); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data208); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/quux/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data209); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data210); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data211); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data212); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data213); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data214); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data215); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data216); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data217); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data218); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data219); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data220); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data221); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data222); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data223); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data224); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data225); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data226); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data227); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data228); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data229); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data230); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data231); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data232); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data233); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data234); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data235); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data236); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data237); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data238); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data239); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data240); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data241); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data242); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data243); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data244); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/grault/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data245); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data246); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data247); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data248); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data249); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data250); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/corge/garply/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data251); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data252); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data253); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data254); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data255); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data256); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/foo/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data257); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data258); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data259); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data260); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data261); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data262); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/bar/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data263); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data264); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data265); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data266); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data267); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data268); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/baz/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data269); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data270); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data271); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data272); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data273); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data274); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/qux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data275); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data276); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data277); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data278); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data279); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data280); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/quux/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data281); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data282); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data283); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data284); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data285); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data286); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/corge/garply", NULL); ck_assert(m != NULL); ck_assert(m->data == data287); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data288); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data289); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data290); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data291); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data292); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/grault/garply/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data293); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data294); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data295); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data296); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data297); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data298); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/foo/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data299); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data300); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data301); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data302); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data303); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data304); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/bar/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data305); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data306); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data307); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data308); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data309); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data310); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/baz/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data311); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data312); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data313); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data314); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data315); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data316); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/qux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data317); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data318); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data319); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data320); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data321); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data322); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/quux/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data323); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data324); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data325); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data326); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data327); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data328); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/corge/grault", NULL); ck_assert(m != NULL); ck_assert(m->data == data329); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/foo", NULL); ck_assert(m != NULL); ck_assert(m->data == data330); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/bar", NULL); ck_assert(m != NULL); ck_assert(m->data == data331); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/baz", NULL); ck_assert(m != NULL); ck_assert(m->data == data332); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/qux", NULL); ck_assert(m != NULL); ck_assert(m->data == data333); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/quux", NULL); ck_assert(m != NULL); ck_assert(m->data == data334); ck_assert(m->endpoint > 0); m = r3_tree_match(n, "/garply/grault/corge", NULL); ck_assert(m != NULL); ck_assert(m->data == data335); ck_assert(m->endpoint > 0); r3_tree_free(n); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("r3 routes tests"); TCase *tcase = tcase_create("testcase"); tcase_add_test(tcase, test_routes); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; } r3-1.3.4/tests/check_slug.c000066400000000000000000000141011262260041500154530ustar00rootroot00000000000000/* * check_slug.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include "r3.h" #include "r3_str.h" #include "zmalloc.h" #include "slug.h" START_TEST (test_pattern_to_opcode) { ck_assert( r3_pattern_to_opcode("\\w+", strlen("\\w+")) == OP_EXPECT_MORE_WORDS ); ck_assert( r3_pattern_to_opcode("\\d+", strlen("\\d+")) == OP_EXPECT_MORE_DIGITS ); ck_assert( r3_pattern_to_opcode("[^/]+",strlen("[^/]+")) == OP_EXPECT_NOSLASH ); ck_assert( r3_pattern_to_opcode("[^-]+",strlen("[^-]+")) == OP_EXPECT_NODASH ); } END_TEST START_TEST (test_r3_slug_compile) { char * path = "/user/{id}"; char * c = NULL; ck_assert_str_eq( c = r3_slug_compile(path, strlen(path) ) , "^/user/([^/]+)" ); zfree(c); char * path2 = "/what/{id}-foo"; ck_assert_str_eq( c = r3_slug_compile(path2, strlen(path2) ) , "^/what/([^/]+)-foo" ); zfree(c); char * path3 = "-{id}"; ck_assert_str_eq( c = r3_slug_compile(path3, strlen(path3)), "^-([^/]+)" ); zfree(c); char * path4 = "-{idx:\\d{3}}"; ck_assert_str_eq( c = r3_slug_compile(path4, strlen(path4)), "^-(\\d{3})" ); zfree(c); } END_TEST START_TEST (test_contains_slug) { ck_assert( r3_path_contains_slug_char("/user/{id}/{name}") ); } END_TEST START_TEST (test_r3_slug_find_pattern) { int len; char * namerex = r3_slug_find_pattern("{name:\\s+}", &len); ck_assert( strncmp(namerex, "\\s+", len) == 0 ); } END_TEST START_TEST (test_r3_slug_find_name) { int len; char * namerex = r3_slug_find_name("{name:\\s+}", &len); ck_assert( strncmp(namerex, "name", len) == 0 ); } END_TEST START_TEST (test_r3_slug_find_name_without_pattern) { int len; char * namerex = r3_slug_find_name("{name}", &len); ck_assert( strncmp(namerex, "name", len) == 0 ); } END_TEST START_TEST (test_r3_slug_find_name_with_multiple_slug) { int len; char * namerex = r3_slug_find_name("{name}/{name2}", &len); ck_assert( strncmp(namerex, "name", len) == 0 ); } END_TEST START_TEST (test_r3_slug_find_placeholder) { int slug_len = 0; char * slug; slug = r3_slug_find_placeholder("/user/{name:\\s+}/to/{id}", &slug_len); ck_assert( strncmp(slug, "{name:\\s+}", slug_len) == 0 ); slug = r3_slug_find_placeholder("/user/{idx:\\d{3}}/to/{idy:\\d{3}}", &slug_len); ck_assert( slug_len == strlen("{idx:\\d{3}}") ); ck_assert( strncmp(slug, "{idx:\\d{3}}", slug_len) == 0 ); } END_TEST START_TEST (test_r3_inside_slug) { char * pattern = "/user/{name:\\s+}/to/{id}"; char * offset = strchr(pattern, '{') + 2; ck_assert( (int)r3_inside_slug(pattern, strlen(pattern), offset, NULL) ); ck_assert( *(r3_inside_slug(pattern, strlen(pattern), offset, NULL)) == '{' ); ck_assert( ! r3_inside_slug(pattern, strlen(pattern), pattern, NULL) ); } END_TEST START_TEST (test_incomplete_slug) { int cnt = 0; char * errstr = NULL; char * pattern = "/user/{name:\\d{3}}/to/{id"; cnt = r3_slug_count(pattern, strlen(pattern), &errstr); ck_assert_int_eq(cnt, -1); ck_assert(errstr); printf("%s\n",errstr); free(errstr); } END_TEST /* START_TEST (test_slug_parse_with_pattern) { char * pattern = "/user/{name:\\d{3}}"; char * errstr = NULL; r3_slug_t s; int ret; ret = r3_slug_parse(&s, pattern, strlen(pattern), pattern, &errstr); ck_assert(ret); char * out = r3_slug_to_str(&s); ck_assert(out); printf("%s\n",out); free(out); } END_TEST START_TEST (test_slug_parse_without_pattern) { char * pattern = "/user/{name}"; char * errstr = NULL; r3_slug_t *s = r3_slug_new(pattern, strlen(pattern)); int ret; ret = r3_slug_parse(s, pattern, strlen(pattern), pattern, &errstr); ck_assert(s); char * out = r3_slug_to_str(s); ck_assert(out); printf("%s\n",out); free(out); r3_slug_free(s); } END_TEST */ START_TEST (test_r3_slug_count) { int cnt = 0; char * pattern = "/user/{name:\\s+}/to/{id}"; char * errstr = NULL; cnt = r3_slug_count(pattern, strlen(pattern), &errstr); ck_assert_int_eq(cnt, 2); if(errstr) free(errstr); char * pattern2 = "/user/{name:\\d{3}}/to/{id}"; cnt = r3_slug_count(pattern2, strlen(pattern2), &errstr); ck_assert_int_eq(cnt, 2); if(errstr) free(errstr); char * pattern3 = "/user/{name:\\d{3}}/to/{id}"; cnt = r3_slug_count(pattern3, strlen(pattern3), &errstr); ck_assert_int_eq(cnt, 2); if(errstr) free(errstr); } END_TEST START_TEST (test_r3_slug_find_placeholder_with_broken_slug) { int slug_len = 0; char * slug = r3_slug_find_placeholder("/user/{name:\\s+/to/{id", &slug_len); ck_assert(slug == 0); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("slug test"); TCase *tcase = tcase_create("test_slug"); tcase_set_timeout(tcase, 30); tcase_add_test(tcase, test_contains_slug); tcase_add_test(tcase, test_r3_inside_slug); tcase_add_test(tcase, test_r3_slug_find_pattern); tcase_add_test(tcase, test_r3_slug_find_placeholder); tcase_add_test(tcase, test_r3_slug_find_placeholder_with_broken_slug); tcase_add_test(tcase, test_r3_slug_count); tcase_add_test(tcase, test_r3_slug_compile); tcase_add_test(tcase, test_pattern_to_opcode); tcase_add_test(tcase, test_incomplete_slug); tcase_add_test(tcase, test_r3_slug_find_name); tcase_add_test(tcase, test_r3_slug_find_name_without_pattern); tcase_add_test(tcase, test_r3_slug_find_name_with_multiple_slug); // tcase_add_test(tcase, test_slug_parse_with_pattern); // tcase_add_test(tcase, test_slug_parse_without_pattern); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; } r3-1.3.4/tests/check_str_array.c000066400000000000000000000023741262260041500165200ustar00rootroot00000000000000/* * check_str_array.c * Copyright (C) 2014 c9s * * Distributed under terms of the MIT license. */ #include "config.h" #include #include #include #include "r3.h" #include "r3_str.h" #include "zmalloc.h" START_TEST (test_str_array) { str_array * l = str_array_create(3); ck_assert(l); ck_assert(str_array_append(l, zstrdup("abc"))); ck_assert( l->len == 1 ); ck_assert(str_array_append(l, zstrdup("foo") )); ck_assert( l->len == 2 ); ck_assert( str_array_append(l, zstrdup("bar") ) ); ck_assert( l->len == 3 ); ck_assert( str_array_append(l, zstrdup("zoo") ) ); ck_assert( l->len == 4 ); ck_assert( str_array_resize(l, l->cap * 2) ); str_array_free(l); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("str_array test"); TCase *tcase = tcase_create("testcase"); tcase_add_test(tcase, test_str_array); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; } r3-1.3.4/tests/check_tree.c000066400000000000000000000477011262260041500154540ustar00rootroot00000000000000#include "config.h" #include #include #include #include #include "r3.h" #include "r3_str.h" #include "zmalloc.h" #include "bench.h" #define SAFE_FREE(ptr) if(ptr) free(ptr); #define STR(str) str, sizeof(str)-1 START_TEST (test_find_common_prefix) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("/foo/{slug}"), sizeof("/foo/{slug}")-1, NULL); r3_node_append_edge(n,e); char *errstr = NULL; int prefix_len = 0; edge *ret_edge = NULL; errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo", sizeof("/foo")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 4); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo/", sizeof("/foo/")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 5); SAFE_FREE(errstr); errstr = NULL; prefix_len = 0; ret_edge = r3_node_find_common_prefix(n, "/foo/{slog}", sizeof("/foo/{slog}")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 5); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo/{bar}", sizeof("/foo/{bar}")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 5); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo/bar", sizeof("/foo/bar")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 5); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/bar/", sizeof("/bar/")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 1); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "{bar}", sizeof("{bar}")-1, &prefix_len, &errstr); ck_assert(ret_edge == NULL); ck_assert_int_eq(prefix_len, 0); SAFE_FREE(errstr); r3_tree_free(n); } END_TEST START_TEST (test_find_common_prefix_after) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("{slug}/foo"), sizeof("{slug}/foo")-1, NULL); r3_node_append_edge(n,e); int prefix_len = 0; edge *ret_edge = NULL; char *errstr = NULL; errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo", sizeof("/foo")-1, &prefix_len, &errstr); ck_assert(ret_edge == NULL); ck_assert_int_eq(prefix_len, 0); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "{slug}/bar", sizeof("{slug}/bar")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 7); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "{slug}/foo", sizeof("{slug}/foo")-1, &prefix_len, &errstr); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 10); SAFE_FREE(errstr); r3_tree_free(n); } END_TEST START_TEST (test_find_common_prefix_double_middle) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("{slug}/foo/{name}"), sizeof("{slug}/foo/{name}")-1, NULL); r3_node_append_edge(n,e); int prefix_len; edge *ret_edge = NULL; char *errstr; errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "{slug}/foo/{number}", sizeof("{slug}/foo/{number}")-1, &prefix_len, &errstr); ck_assert(ret_edge); ck_assert_int_eq(prefix_len, 11); SAFE_FREE(errstr); r3_tree_free(n); } END_TEST START_TEST (test_find_common_prefix_middle) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("/foo/{slug}/hate"), sizeof("/foo/{slug}/hate")-1, NULL); r3_node_append_edge(n,e); int prefix_len; edge *ret_edge = NULL; char *errstr = NULL; errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/foo/{slug}/bar", sizeof("/foo/{slug}/bar")-1, &prefix_len, &errstr); ck_assert(ret_edge); ck_assert_int_eq(prefix_len, 12); SAFE_FREE(errstr); errstr = NULL; ret_edge = r3_node_find_common_prefix(n, "/fo/{slug}/bar", sizeof("/fo/{slug}/bar")-1, &prefix_len, &errstr); ck_assert(ret_edge); ck_assert_int_eq(prefix_len, 3); SAFE_FREE(errstr); r3_tree_free(n); } END_TEST START_TEST (test_find_common_prefix_same_pattern) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("/foo/{slug:xxx}/hate"), sizeof("/foo/{slug:xxx}/hate")-1, NULL); r3_node_append_edge(n,e); int prefix_len; edge *ret_edge = NULL; prefix_len = 0; ret_edge = r3_node_find_common_prefix(n, "/foo/{slug:yyy}/hate", sizeof("/foo/{slug:yyy}/hate")-1, &prefix_len, NULL); ck_assert(ret_edge); ck_assert_int_eq(prefix_len, 5); prefix_len = 0; ret_edge = r3_node_find_common_prefix(n, "/foo/{slug}/hate", sizeof("/foo/{slug}/hate")-1, &prefix_len, NULL); ck_assert(ret_edge != NULL); ck_assert_int_eq(prefix_len, 5); r3_tree_free(n); } END_TEST START_TEST (test_find_common_prefix_same_pattern2) { node * n = r3_tree_create(10); edge * e = r3_edge_createl(zstrdup("{slug:xxx}/hate"), sizeof("{slug:xxx}/hate")-1, NULL); r3_node_append_edge(n,e); int prefix_len; edge *ret_edge = NULL; prefix_len = 0; ret_edge = r3_node_find_common_prefix(n, "{slug:yyy}/hate", sizeof("{slug:yyy}/hate")-1, &prefix_len, NULL); ck_assert(ret_edge); ck_assert_int_eq(prefix_len, 0); r3_tree_free(n); } END_TEST START_TEST (test_node_construct_and_free) { node * n = r3_tree_create(10); node * another_tree = r3_tree_create(3); r3_tree_free(n); r3_tree_free(another_tree); } END_TEST static node * create_simple_str_tree() { node * n; n = r3_tree_create(10); r3_tree_insert_path(n, "/zoo", NULL); r3_tree_insert_path(n, "/foo", NULL); r3_tree_insert_path(n, "/bar", NULL); r3_tree_compile(n, NULL); return n; } START_TEST (test_compile) { node *n; node *m; n = create_simple_str_tree(); #ifdef DEBUG r3_tree_dump(n, 0); #endif r3_tree_insert_path(n, "/foo/{id}", NULL); r3_tree_insert_path(n, "/{id}", NULL); r3_tree_compile(n, NULL); r3_tree_compile(n, NULL); // test double compile // r3_tree_dump(n, 0); match_entry * entry; entry = match_entry_createl( "foo" , strlen("/foo") ); m = r3_tree_matchl( n , "/foo", strlen("/foo"), entry); ck_assert( m ); entry = match_entry_createl( "/zoo" , strlen("/zoo") ); m = r3_tree_matchl( n , "/zoo", strlen("/zoo"), entry); ck_assert( m ); entry = match_entry_createl( "/bar" , strlen("/bar") ); m = r3_tree_matchl( n , "/bar", strlen("/bar"), entry); ck_assert( m ); entry = match_entry_createl( "/xxx" , strlen("/xxx") ); m = r3_tree_matchl( n , "/xxx", strlen("/xxx"), entry); ck_assert( m ); entry = match_entry_createl( "/foo/xxx" , strlen("/foo/xxx") ); m = r3_tree_matchl( n , "/foo/xxx", strlen("/foo/xxx"), entry); ck_assert( m ); entry = match_entry_createl( "/some_id" , strlen("/some_id") ); m = r3_tree_matchl( n , "/some_id", strlen("/some_id"), entry); ck_assert( m ); } END_TEST START_TEST (test_incomplete_slug_path) { node * n = r3_tree_create(10); node * ret_node; // r3_tree_insert_path(n, "/foo-{user}-{id}", NULL, NULL); ret_node = r3_tree_insert_path(n, "/post/{handle", NULL); assert(!ret_node); ret_node = r3_tree_insert_path(n, "/post/{handle:\\", NULL); assert(!ret_node); ret_node = r3_tree_insert_path(n, "/post/{handle:\\d", NULL); assert(!ret_node); ret_node = r3_tree_insert_path(n, "/post/{handle:\\d{", NULL); assert(!ret_node); ret_node = r3_tree_insert_path(n, "/post/{handle:\\d{3", NULL); assert(!ret_node); r3_tree_insert_path(n, "/post/{handle:\\d{3}", NULL); r3_tree_insert_path(n, "/post/{handle:\\d{3}}/{", NULL); r3_tree_insert_path(n, "/post/{handle:\\d{3}}/{a", NULL); r3_tree_insert_path(n, "/post/{handle:\\d{3}}/{a}", NULL); ret_node = r3_tree_insert_path(n, "/users/{idx:\\d{3}}/{idy}", NULL); ck_assert(ret_node); // OK to insert, but should return error when compiling patterns node * ret_node2 = r3_tree_insert_path(n, "/users/{idx:\\d{3}}/{idy:aaa}", NULL); ck_assert(ret_node2); ck_assert(ret_node2 != ret_node); // make sure it's another node char *errstr = NULL; r3_tree_compile(n, &errstr); ck_assert(errstr == NULL); // no error // r3_tree_dump(n, 0); r3_tree_free(n); } END_TEST START_TEST (test_pcre_patterns_insert) { node * n = r3_tree_create(10); // r3_tree_insert_path(n, "/foo-{user}-{id}", NULL, NULL); r3_tree_insert_path(n, "/post/{handle:\\d+}-{id:\\d+}", NULL); r3_tree_insert_path(n, "/post/foo", NULL); r3_tree_insert_path(n, "/post/bar", NULL); char *errstr = NULL; int errcode; errcode = r3_tree_compile(n, &errstr); ck_assert(errcode == 0); // no error // r3_tree_dump(n, 0); node *matched; matched = r3_tree_match(n, "/post/foo", NULL); ck_assert(matched); ck_assert(matched->endpoint > 0); matched = r3_tree_match(n, "/post/bar", NULL); ck_assert(matched); ck_assert(matched->endpoint > 0); matched = r3_tree_match(n, "/post/kkkfoo", NULL); ck_assert(!matched); matched = r3_tree_match(n, "/post/kkkbar", NULL); ck_assert(!matched); matched = r3_tree_matchl(n, "/post/111-222", strlen("/post/111-222"), NULL); ck_assert(matched); ck_assert(matched->endpoint > 0); // incomplete string shouldn't match matched = r3_tree_matchl(n, "/post/111-", strlen("/post/111-"), NULL); ck_assert(! matched); r3_tree_free(n); } END_TEST /** * Test for root '/' */ START_TEST (test_root_match) { node * n = r3_tree_create(10); int a = 10; int b = 20; int c = 30; r3_tree_insert_path(n, "/", &a); r3_tree_insert_path(n, "/foo", &b); r3_tree_insert_path(n, "/bar", &c); char *errstr = NULL; r3_tree_compile(n, &errstr); // r3_tree_dump(n, 0); node *matched; matched = r3_tree_match(n, "/", NULL); ck_assert(matched); ck_assert(matched->data == &a); ck_assert(matched->endpoint > 0); matched = r3_tree_match(n, "/foo", NULL); ck_assert(matched); ck_assert(matched->data == &b); ck_assert(matched->endpoint > 0); matched = r3_tree_match(n, "/bar", NULL); ck_assert(matched); ck_assert(matched->data == &c); ck_assert(matched->endpoint > 0); } END_TEST /** * Test for \d{2}/\d{2} */ START_TEST (test_pcre_patterns_insert_2) { node * n = r3_tree_create(10); r3_tree_insert_path(n, "/post/{idx:\\d{2}}/{idy:\\d{2}}", NULL); r3_tree_insert_path(n, "/zoo", NULL); r3_tree_insert_path(n, "/foo", NULL); r3_tree_insert_path(n, "/bar", NULL); char *errstr = NULL; r3_tree_compile(n, &errstr); // r3_tree_dump(n, 0); node *matched; matched = r3_tree_match(n, "/post/11/22", NULL); ck_assert((int)matched); ck_assert(matched->endpoint > 0); } END_TEST /** * Test for (\d{2})/([^/]+) */ START_TEST (test_pcre_patterns_insert_3) { node * n = r3_tree_create(10); printf("Inserting /post/{idx:\\d{2}}/{idy}\n"); r3_tree_insert_path(n, "/post/{idx:\\d{2}}/{idy}", NULL); // r3_tree_dump(n, 0); printf("Inserting /zoo\n"); r3_tree_insert_path(n, "/zoo", NULL); // r3_tree_dump(n, 0); r3_tree_insert_path(n, "/foo", NULL); r3_tree_insert_path(n, "/bar", NULL); char *errstr = NULL; r3_tree_compile(n, &errstr); // r3_tree_dump(n, 0); node *matched; matched = r3_tree_match(n, "/post/11/22", NULL); ck_assert((int)matched); matched = r3_tree_match(n, "/post/11", NULL); ck_assert(!matched); matched = r3_tree_match(n, "/post/11/", NULL); ck_assert(!matched); /* matched = r3_tree_match(n, "/post/113", NULL); ck_assert(!matched); */ } END_TEST START_TEST (test_insert_pathl_fail) { node * n = r3_tree_create(10); node * ret; char *errstr = NULL; ret = r3_tree_insert_pathl_ex(n, "/foo/{name:\\d{5}", strlen("/foo/{name:\\d{5}"), NULL, NULL, &errstr); ck_assert(ret == NULL); ck_assert(errstr != NULL); printf("%s\n", errstr); // Returns Incomplete slug pattern. PATTERN (16): '/foo/{name:\d{5}', OFFSET: 16, STATE: 1 SAFE_FREE(errstr); errstr = NULL; r3_tree_compile(n, &errstr); ck_assert(errstr == NULL); r3_tree_free(n); } END_TEST START_TEST (test_insert_pathl) { node * n = r3_tree_create(10); node * ret; ret = r3_tree_insert_path(n, "/foo/bar", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/zoo", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{id}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{number:\\d+}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{name:\\w+}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{name:\\d+}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{name:\\d{5}}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{idx}/{idy}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{idx}/{idh}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/f/id" , NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/post/{id}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/post/{handle}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/post/{handle}-{id}", NULL); ck_assert(ret); char * errstr = NULL; r3_tree_compile(n, &errstr); ck_assert(errstr == NULL); // r3_tree_dump(n, 0); r3_tree_free(n); } END_TEST START_TEST (test_compile_fail) { node * n = r3_tree_create(10); node * ret; ret = r3_tree_insert_path(n, "/foo/{idx}/{idy:)}", NULL); ck_assert(ret); ret = r3_tree_insert_path(n, "/foo/{idx}/{idh:(}", NULL); ck_assert(ret); char * errstr = NULL; r3_tree_compile(n, &errstr); ck_assert(errstr); fprintf(stderr, "Compile failed: %s\n", errstr); free(errstr); // r3_tree_dump(n, 0); r3_tree_free(n); } END_TEST START_TEST(test_route_cmp) { route *r1 = r3_route_create("/blog/post"); match_entry * m = match_entry_create("/blog/post"); fail_if( r3_route_cmp(r1, m) == -1, "should match"); r1->request_method = METHOD_GET; m->request_method = METHOD_GET; fail_if( r3_route_cmp(r1, m) == -1, "should match"); r1->request_method = METHOD_GET; m->request_method = METHOD_POST; fail_if( r3_route_cmp(r1, m) == 0, "should be different"); r1->request_method = METHOD_GET; m->request_method = METHOD_POST | METHOD_GET; fail_if( r3_route_cmp(r1, m) == -1, "should match"); r3_route_free(r1); match_entry_free(m); } END_TEST START_TEST(test_pcre_pattern_simple) { match_entry * entry; entry = match_entry_createl( "/user/123" , strlen("/user/123") ); node * n = r3_tree_create(10); r3_tree_insert_path(n, "/user/{id:\\d+}", NULL); r3_tree_insert_path(n, "/user", NULL); r3_tree_compile(n, NULL); // r3_tree_dump(n, 0); node *matched; matched = r3_tree_matchl(n, "/user/123", strlen("/user/123"), entry); ck_assert(matched); ck_assert(entry->vars->len > 0); ck_assert_str_eq(entry->vars->tokens[0],"123"); r3_tree_free(n); } END_TEST START_TEST(test_pcre_pattern_more) { match_entry * entry; entry = match_entry_createl( "/user/123" , strlen("/user/123") ); node * n = r3_tree_create(10); int var0 = 5; int var1 = 100; int var2 = 200; int var3 = 300; info("var0: %p\n", &var0); info("var1: %p\n", &var1); info("var2: %p\n", &var2); info("var3: %p\n", &var3); r3_tree_insert_path(n, "/user/{id:\\d+}", &var1); r3_tree_insert_path(n, "/user2/{id:\\d+}", &var2); r3_tree_insert_path(n, "/user3/{id:\\d{3}}", &var3); r3_tree_insert_path(n, "/user", &var0); r3_tree_compile(n, NULL); // r3_tree_dump(n, 0); node *matched; matched = r3_tree_matchl(n, "/user/123", strlen("/user/123"), entry); ck_assert(matched); ck_assert(entry->vars->len > 0); ck_assert_str_eq(entry->vars->tokens[0],"123"); info("matched %p\n", matched->data); info("matched %p\n", matched->data); ck_assert_int_eq( *((int*) matched->data), var1); matched = r3_tree_matchl(n, "/user2/123", strlen("/user2/123"), entry); ck_assert(matched); ck_assert(entry->vars->len > 0); ck_assert_str_eq(entry->vars->tokens[0],"123"); ck_assert_int_eq( *((int*)matched->data), var2); matched = r3_tree_matchl(n, "/user3/123", strlen("/user3/123"), entry); ck_assert(matched); ck_assert(entry->vars->len > 0); ck_assert_str_eq(entry->vars->tokens[0],"123"); ck_assert_int_eq( *((int*)matched->data), var3); r3_tree_free(n); } END_TEST START_TEST(test_insert_pathl_before_root) { char *errstr = NULL; int var1 = 22; int var2 = 33; int var3 = 44; node * n = r3_tree_create(3); r3_tree_insert_pathl_ex(n, STR("/blog/post"), NULL, &var1, NULL); r3_tree_insert_pathl_ex(n, STR("/blog"), NULL, &var2, NULL); r3_tree_insert_pathl_ex(n, STR("/"), NULL, &var3, NULL); errstr = NULL; r3_tree_compile(n, &errstr); r3_tree_dump(n, 0); r3_tree_free(n); } END_TEST START_TEST(test_insert_route) { int var1 = 22; int var2 = 33; node * n = r3_tree_create(2); r3_tree_insert_route(n, METHOD_GET, "/blog/post", &var1); r3_tree_insert_route(n, METHOD_POST, "/blog/post", &var2); match_entry * entry; route *r; entry = match_entry_create("/blog/post"); entry->request_method = METHOD_GET; r = r3_tree_match_route(n, entry); ck_assert(r != NULL); ck_assert(r->request_method & METHOD_GET ); ck_assert(*((int*)r->data) == 22); match_entry_free(entry); entry = match_entry_create("/blog/post"); entry->request_method = METHOD_POST; r = r3_tree_match_route(n, entry); ck_assert(r != NULL); ck_assert(r->request_method & METHOD_POST ); ck_assert(*((int*)r->data) == 33); match_entry_free(entry); r3_tree_free(n); } END_TEST Suite* r3_suite (void) { Suite *suite = suite_create("r3 core tests"); TCase *tcase = tcase_create("common_prefix_testcase"); tcase_add_test(tcase, test_find_common_prefix); tcase_add_test(tcase, test_find_common_prefix_after); tcase_add_test(tcase, test_find_common_prefix_double_middle); tcase_add_test(tcase, test_find_common_prefix_middle); tcase_add_test(tcase, test_find_common_prefix_same_pattern); tcase_add_test(tcase, test_find_common_prefix_same_pattern2); suite_add_tcase(suite, tcase); tcase = tcase_create("insert_testcase"); tcase_add_test(tcase, test_insert_pathl); tcase_add_test(tcase, test_insert_pathl_fail); tcase_add_test(tcase, test_node_construct_and_free); suite_add_tcase(suite, tcase); tcase = tcase_create("compile_testcase"); tcase_add_test(tcase, test_compile); tcase_add_test(tcase, test_compile_fail); tcase_add_test(tcase, test_route_cmp); tcase_add_test(tcase, test_insert_route); tcase_add_test(tcase, test_insert_pathl_before_root); suite_add_tcase(suite, tcase); tcase = tcase_create("pcre_pattern_testcase"); tcase_add_test(tcase, test_pcre_pattern_simple); tcase_add_test(tcase, test_pcre_pattern_more); tcase_add_test(tcase, test_pcre_patterns_insert); tcase_add_test(tcase, test_pcre_patterns_insert_2); tcase_add_test(tcase, test_root_match); tcase_add_test(tcase, test_pcre_patterns_insert_3); tcase_add_test(tcase, test_incomplete_slug_path); suite_add_tcase(suite, tcase); return suite; } int main (int argc, char *argv[]) { int number_failed; Suite *suite = r3_suite(); SRunner *runner = srunner_create(suite); srunner_run_all(runner, CK_NORMAL); number_failed = srunner_ntests_failed(runner); srunner_free(runner); return number_failed; }